text
stringlengths 54
60.6k
|
---|
<commit_before>#include "Platform.h"
namespace clw
{
namespace detail
{
vector<cl_platform_id> getPlatformIDs()
{
cl_uint num;
if(clGetPlatformIDs(0, nullptr, &num) != CL_SUCCESS)
return vector<cl_platform_id>();
vector<cl_platform_id> platformIds(num);
clGetPlatformIDs(num, platformIds.data(), nullptr);
return platformIds;
}
string platformInfo(cl_platform_id id, cl_platform_info name)
{
size_t size;
if(!id || clGetPlatformInfo(id, name, 0, nullptr, &size) != CL_SUCCESS)
return string();
vector<char> infoBuf(size);
clGetPlatformInfo(id, name, size, infoBuf.data(), &size);
return string(infoBuf.data());
}
}
string Platform::versionString() const
{
return detail::platformInfo(id, CL_PLATFORM_VERSION);
}
EPlatformVersion Platform::version() const
{
// Format returned by clGetPlatformInfo with CL_PLATFORM_VERSION is:
// OpenCL<space><major_version.minor_version><space><platform-specific information>
static const string prefix("OpenCL ");
string ver = detail::platformInfo(id, CL_PLATFORM_VERSION);
if(!prefix.compare(0, prefix.length(), ver))
return EPlatformVersion::Version_Undefined;
ver = ver.substr(prefix.length());
string::size_type pos = 0;
while(ver[pos] != '.' && pos < ver.length())
++pos;
if(pos == ver.length())
return EPlatformVersion::Version_Undefined;
int major = std::stoi(ver.substr(0, pos));
string::size_type mpos = pos + 1;
while(ver[mpos] != ' ' && mpos < ver.length())
++mpos;
if(mpos == ver.length())
return EPlatformVersion::Version_Undefined;
int minor = std::stoi(ver.substr(pos+1, mpos-(pos+1)));
switch(major)
{
case 1:
switch(minor)
{
case 0: return EPlatformVersion::Version_1_0;
case 1: return EPlatformVersion::Version_1_1;
case 2: return EPlatformVersion::Version_1_2;
}
default:
return EPlatformVersion::Version_Undefined;
}
}
string Platform::name() const
{
return detail::platformInfo(id, CL_PLATFORM_NAME);
}
string Platform::vendor() const
{
return detail::platformInfo(id, CL_PLATFORM_VENDOR);
}
string Platform::extensionSuffix() const
{
return detail::platformInfo(id, CL_PLATFORM_ICD_SUFFIX_KHR);
}
vector<Platform> availablePlatforms()
{
vector<cl_platform_id> platformIds = detail::getPlatformIDs();
if(platformIds.empty())
return vector<Platform>();
vector<Platform> platforms(platformIds.size());
for(size_t i = 0; i < platformIds.size(); ++i)
platforms[i] = Platform(platformIds[i]);
return platforms;
}
Platform defaultPlatform()
{
cl_platform_id platformId;
if(clGetPlatformIDs(1, &platformId, nullptr) != CL_SUCCESS)
return Platform();
return Platform(platformId);
}
}<commit_msg>refactored local vars<commit_after>#include "Platform.h"
namespace clw
{
namespace detail
{
vector<cl_platform_id> getPlatformIDs()
{
cl_uint num;
if(clGetPlatformIDs(0, nullptr, &num) != CL_SUCCESS)
return vector<cl_platform_id>();
vector<cl_platform_id> pids(num);
clGetPlatformIDs(num, pids.data(), nullptr);
return pids;
}
string platformInfo(cl_platform_id id, cl_platform_info name)
{
size_t size;
if(!id || clGetPlatformInfo(id, name, 0, nullptr, &size) != CL_SUCCESS)
return string();
vector<char> infoBuf(size);
clGetPlatformInfo(id, name, size, infoBuf.data(), &size);
return string(infoBuf.data());
}
}
string Platform::versionString() const
{
return detail::platformInfo(id, CL_PLATFORM_VERSION);
}
EPlatformVersion Platform::version() const
{
// Format returned by clGetPlatformInfo with CL_PLATFORM_VERSION is:
// OpenCL<space><major_version.minor_version><space><platform-specific information>
static const string prefix("OpenCL ");
string ver = detail::platformInfo(id, CL_PLATFORM_VERSION);
if(!prefix.compare(0, prefix.length(), ver))
return EPlatformVersion::Version_Undefined;
ver = ver.substr(prefix.length());
string::size_type pos = 0;
while(ver[pos] != '.' && pos < ver.length())
++pos;
if(pos == ver.length())
return EPlatformVersion::Version_Undefined;
int major = std::stoi(ver.substr(0, pos));
string::size_type mpos = pos + 1;
while(ver[mpos] != ' ' && mpos < ver.length())
++mpos;
if(mpos == ver.length())
return EPlatformVersion::Version_Undefined;
int minor = std::stoi(ver.substr(pos+1, mpos-(pos+1)));
switch(major)
{
case 1:
switch(minor)
{
case 0: return EPlatformVersion::Version_1_0;
case 1: return EPlatformVersion::Version_1_1;
case 2: return EPlatformVersion::Version_1_2;
}
default:
return EPlatformVersion::Version_Undefined;
}
}
string Platform::name() const
{
return detail::platformInfo(id, CL_PLATFORM_NAME);
}
string Platform::vendor() const
{
return detail::platformInfo(id, CL_PLATFORM_VENDOR);
}
string Platform::extensionSuffix() const
{
return detail::platformInfo(id, CL_PLATFORM_ICD_SUFFIX_KHR);
}
vector<Platform> availablePlatforms()
{
vector<cl_platform_id> pids = detail::getPlatformIDs();
if(pids.empty())
return vector<Platform>();
vector<Platform> platforms(pids.size());
for(size_t i = 0; i < pids.size(); ++i)
platforms[i] = Platform(pids[i]);
return platforms;
}
Platform defaultPlatform()
{
cl_platform_id pid;
if(clGetPlatformIDs(1, &pid, nullptr) != CL_SUCCESS)
return Platform();
return Platform(pid);
}
}<|endoftext|> |
<commit_before>#ifndef STAN_LANG_RETHROW_LOCATED_HPP
#define STAN_LANG_RETHROW_LOCATED_HPP
#include <stan/io/program_reader.hpp>
#include <exception>
#include <ios>
#include <new>
#include <sstream>
#include <stdexcept>
#include <string>
#include <typeinfo>
namespace stan {
namespace lang {
/**
* Returns true if the specified exception can be dynamically
* cast to the template parameter type.
*
* @tparam E Type to test.
* @param[in] e Exception to test.
* @return true if exception can be dynamically cast to type.
*/
template <typename E>
bool is_type(const std::exception& e) {
try {
(void) dynamic_cast<const E&>(e);
return true;
} catch (...) {
return false;
}
}
/**
* Structure for a located exception for standard library
* exception types that have no what-based constructors.
*
* @param E Type of original exception.
*/
template <typename E>
struct located_exception : public E {
std::string what_;
/**
* Construct a located exception with no what message.
*/
located_exception() throw() : what_("") { }
/**
* Construct a located exception with the specified what
* message and specified original type.
*
* @param[in] what Original what message.
* @param[in] orig_type Original type.
*/
located_exception(const std::string& what,
const std::string& orig_type) throw()
: what_(what + " [origin: " + orig_type + "]") {
}
/**
* Destroy a located exception.
*/
~located_exception() throw() { }
/**
* Return the character sequence describing the exception,
* including the original waht message and original type if
* constructed with such.
*
* @return Description of exception.
*/
const char* what() const throw() {
return what_.c_str();
}
};
/**
* Rethrow an exception of type specified by the dynamic type of
* the specified exception, adding the specified line number to
* the specified exception's message.
*
* @param[in] e original exception
* @param[in] line line number in Stan source program where
* exception originated
* @param[in] reader trace of how program was included from files
*/
inline void rethrow_located(const std::exception& e, int line,
const io::program_reader& reader =
stan::io::program_reader()) {
using std::bad_alloc; // -> exception
using std::bad_cast; // -> exception
using std::bad_exception; // -> exception
using std::bad_typeid; // -> exception
using std::ios_base; // ::failure -> exception
using std::domain_error; // -> logic_error
using std::invalid_argument; // -> logic_error
using std::length_error; // -> logic_error
using std::out_of_range; // -> logic_error
using std::logic_error; // -> exception
using std::overflow_error; // -> runtime_error
using std::range_error; // -> runtime_error
using std::underflow_error; // -> runtime_error
using std::runtime_error; // -> exception
using std::exception;
// create message with trace of includes and location of error
std::stringstream o;
o << "Exception: " << e.what();
if (line < 1) {
o << " Found before start of program.";
} else {
io::program_reader::trace_t tr = reader.trace(line);
o << " (in '" << tr[tr.size() - 1].first
<< "' at line " << tr[tr.size() - 1].second;
for (int i = tr.size() - 1; --i >= 0; )
o << "; included from '" << tr[i].first
<< "' at line " << tr[i].second;
o << ")" << std::endl;
}
std::string s = o.str();
if (is_type<bad_alloc>(e))
throw located_exception<bad_alloc>(s, "bad_alloc");
if (is_type<bad_cast>(e))
throw located_exception<bad_cast>(s, "bad_cast");
if (is_type<bad_exception>(e))
throw located_exception<bad_exception>(s, "bad_exception");
if (is_type<bad_typeid>(e))
throw located_exception<bad_typeid>(s, "bad_typeid");
if (is_type<domain_error>(e))
throw domain_error(s);
if (is_type<invalid_argument>(e))
throw invalid_argument(s);
if (is_type<length_error>(e))
throw length_error(s);
if (is_type<out_of_range>(e))
throw out_of_range(s);
if (is_type<logic_error>(e))
throw logic_error(s);
if (is_type<overflow_error>(e))
throw overflow_error(s);
if (is_type<range_error>(e))
throw range_error(s);
if (is_type<underflow_error>(e))
throw underflow_error(s);
if (is_type<runtime_error>(e))
throw runtime_error(s);
throw located_exception<exception>(s, "unknown original type");
}
}
}
#endif
<commit_msg>delete space<commit_after>#ifndef STAN_LANG_RETHROW_LOCATED_HPP
#define STAN_LANG_RETHROW_LOCATED_HPP
#include <stan/io/program_reader.hpp>
#include <exception>
#include <ios>
#include <new>
#include <sstream>
#include <stdexcept>
#include <string>
#include <typeinfo>
namespace stan {
namespace lang {
/**
* Returns true if the specified exception can be dynamically
* cast to the template parameter type.
*
* @tparam E Type to test.
* @param[in] e Exception to test.
* @return true if exception can be dynamically cast to type.
*/
template <typename E>
bool is_type(const std::exception& e) {
try {
(void) dynamic_cast<const E&>(e);
return true;
} catch (...) {
return false;
}
}
/**
* Structure for a located exception for standard library
* exception types that have no what-based constructors.
*
* @param E Type of original exception.
*/
template <typename E>
struct located_exception : public E {
std::string what_;
/**
* Construct a located exception with no what message.
*/
located_exception() throw() : what_("") { }
/**
* Construct a located exception with the specified what
* message and specified original type.
*
* @param[in] what Original what message.
* @param[in] orig_type Original type.
*/
located_exception(const std::string& what,
const std::string& orig_type) throw()
: what_(what + " [origin: " + orig_type + "]") {
}
/**
* Destroy a located exception.
*/
~located_exception() throw() { }
/**
* Return the character sequence describing the exception,
* including the original waht message and original type if
* constructed with such.
*
* @return Description of exception.
*/
const char* what() const throw() {
return what_.c_str();
}
};
/**
* Rethrow an exception of type specified by the dynamic type of
* the specified exception, adding the specified line number to
* the specified exception's message.
*
* @param[in] e original exception
* @param[in] line line number in Stan source program where
* exception originated
* @param[in] reader trace of how program was included from files
*/
inline void rethrow_located(const std::exception& e, int line,
const io::program_reader& reader =
stan::io::program_reader()) {
using std::bad_alloc; // -> exception
using std::bad_cast; // -> exception
using std::bad_exception; // -> exception
using std::bad_typeid; // -> exception
using std::ios_base; // ::failure -> exception
using std::domain_error; // -> logic_error
using std::invalid_argument; // -> logic_error
using std::length_error; // -> logic_error
using std::out_of_range; // -> logic_error
using std::logic_error; // -> exception
using std::overflow_error; // -> runtime_error
using std::range_error; // -> runtime_error
using std::underflow_error; // -> runtime_error
using std::runtime_error; // -> exception
using std::exception;
// create message with trace of includes and location of error
std::stringstream o;
o << "Exception: " << e.what();
if (line < 1) {
o << " Found before start of program.";
} else {
io::program_reader::trace_t tr = reader.trace(line);
o << " (in '" << tr[tr.size() - 1].first
<< "' at line " << tr[tr.size() - 1].second;
for (int i = tr.size() - 1; --i >= 0; )
o << "; included from '" << tr[i].first
<< "' at line " << tr[i].second;
o << ")" << std::endl;
}
std::string s = o.str();
if (is_type<bad_alloc>(e))
throw located_exception<bad_alloc>(s, "bad_alloc");
if (is_type<bad_cast>(e))
throw located_exception<bad_cast>(s, "bad_cast");
if (is_type<bad_exception>(e))
throw located_exception<bad_exception>(s, "bad_exception");
if (is_type<bad_typeid>(e))
throw located_exception<bad_typeid>(s, "bad_typeid");
if (is_type<domain_error>(e))
throw domain_error(s);
if (is_type<invalid_argument>(e))
throw invalid_argument(s);
if (is_type<length_error>(e))
throw length_error(s);
if (is_type<out_of_range>(e))
throw out_of_range(s);
if (is_type<logic_error>(e))
throw logic_error(s);
if (is_type<overflow_error>(e))
throw overflow_error(s);
if (is_type<range_error>(e))
throw range_error(s);
if (is_type<underflow_error>(e))
throw underflow_error(s);
if (is_type<runtime_error>(e))
throw runtime_error(s);
throw located_exception<exception>(s, "unknown original type");
}
}
}
#endif
<|endoftext|> |
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2007 Jos van den Oever <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "strigiconfig.h"
#include "strigi_thread.h"
#include "filelister.h"
#include "analyzerconfiguration.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include "stgdirent.h" //dirent replacement (includes native if available)
#ifdef HAVE_DIRECT_H
#include <direct.h>
#endif
#include <errno.h>
using namespace std;
string fixPath (string path)
{
if ( path.c_str() == NULL || path.length() == 0 )
return "";
string temp(path);
#ifdef HAVE_WINDOWS_H
size_t l= temp.length();
char* t = (char*)temp.c_str();
for (size_t i=0;i<l;i++){
if ( t[i] == '\\' )
t[i] = '/';
}
temp[0] = tolower(temp.at(0));
#endif
char separator = '/';
if (temp[temp.length() - 1 ] != separator)
temp += separator;
return temp;
}
class Strigi::FileLister::Private {
public:
char path[10000];
STRIGI_MUTEX_DEFINE(mutex);
DIR** dirs;
DIR** dirsEnd;
DIR** curDir;
int* len;
int* lenEnd;
int* curLen;
time_t mtime;
struct dirent* subdir;
struct stat dirstat;
const Strigi::AnalyzerConfiguration* const config;
Private(const Strigi::AnalyzerConfiguration* ic);
~Private();
int nextFile(string& p, time_t& time) {
int r;
STRIGI_MUTEX_LOCK(&mutex);
r = nextFile();
if (r > 0) {
p.assign(path, r);
time = mtime;
}
STRIGI_MUTEX_UNLOCK(&mutex);
return r;
}
void startListing(const std::string&);
int nextFile();
};
Strigi::FileLister::Private::Private(
const Strigi::AnalyzerConfiguration* ic) :
config(ic) {
STRIGI_MUTEX_INIT(&mutex);
int nOpenDirs = 100;
dirs = (DIR**)malloc(sizeof(DIR*)*nOpenDirs);
dirsEnd = dirs + nOpenDirs;
len = (int*)malloc(sizeof(int)*nOpenDirs);
lenEnd = len + nOpenDirs;
curDir = dirs - 1;
}
void
Strigi::FileLister::Private::startListing(const string& dir){
curDir = dirs;
curLen = len;
int len = dir.length();
*curLen = len;
strcpy(path, dir.c_str());
if (len) {
if (path[len-1] != '/') {
path[len++] = '/';
path[len] = 0;
*curLen = len;
}
DIR* d = opendir(path);
if (d) {
*curDir = d;
} else {
curDir--;
}
} else {
curDir--;
}
}
Strigi::FileLister::Private::~Private() {
while (curDir >= dirs) {
if (*curDir) {
closedir(*curDir);
}
curDir--;
}
free(dirs);
free(len);
STRIGI_MUTEX_DESTROY(&mutex);
}
int
Strigi::FileLister::Private::nextFile() {
while (curDir >= dirs) {
DIR* dir = *curDir;
int l = *curLen;
subdir = readdir(dir);
while (subdir) {
// skip the directories '.' and '..'
char c1 = subdir->d_name[0];
if (c1 == '.') {
char c2 = subdir->d_name[1];
if (c2 == '.' || c2 == '\0') {
subdir = readdir(dir);
continue;
}
}
strcpy(path + l, subdir->d_name);
int sl = l + strlen(subdir->d_name);
if (lstat(path, &dirstat) == 0) {
if (S_ISREG(dirstat.st_mode)) {
if (config == 0 || config->indexFile(path, path+sl)) {
mtime = dirstat.st_mtime;
return sl;
}
} else if (dirstat.st_mode & S_IFDIR && (config == 0
|| config->indexDir(path, path+sl))) {
mtime = dirstat.st_mtime;
strcpy(this->path+sl, "/");
DIR* d = opendir(path);
if (d) {
curDir++;
curLen++;
dir = *curDir = d;
l = *curLen = sl+1;
}
}
}
subdir = readdir(dir);
}
closedir(dir);
curDir--;
curLen--;
}
return -1;
}
Strigi::FileLister::FileLister(const Strigi::AnalyzerConfiguration* ic)
: p(new Private(ic)) {
}
Strigi::FileLister::~FileLister() {
delete p;
}
void
Strigi::FileLister::startListing(const string& dir) {
p->startListing(dir);
}
int
Strigi::FileLister::nextFile(std::string& path, time_t& time) {
return p->nextFile(path, time);
}
int
Strigi::FileLister::nextFile(const char*& path, time_t& time) {
int r = p->nextFile();
if (r >= 0) {
time = p->mtime;
path = p->path;
}
return r;
}
<commit_msg>no lstat on win32<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2007 Jos van den Oever <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "strigiconfig.h"
#include "strigi_thread.h"
#include "filelister.h"
#include "analyzerconfiguration.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include "stgdirent.h" //dirent replacement (includes native if available)
#ifdef HAVE_DIRECT_H
#include <direct.h>
#endif
#include <errno.h>
using namespace std;
string fixPath (string path)
{
if ( path.c_str() == NULL || path.length() == 0 )
return "";
string temp(path);
#ifdef HAVE_WINDOWS_H
size_t l= temp.length();
char* t = (char*)temp.c_str();
for (size_t i=0;i<l;i++){
if ( t[i] == '\\' )
t[i] = '/';
}
temp[0] = tolower(temp.at(0));
#endif
char separator = '/';
if (temp[temp.length() - 1 ] != separator)
temp += separator;
return temp;
}
class Strigi::FileLister::Private {
public:
char path[10000];
STRIGI_MUTEX_DEFINE(mutex);
DIR** dirs;
DIR** dirsEnd;
DIR** curDir;
int* len;
int* lenEnd;
int* curLen;
time_t mtime;
struct dirent* subdir;
struct stat dirstat;
const Strigi::AnalyzerConfiguration* const config;
Private(const Strigi::AnalyzerConfiguration* ic);
~Private();
int nextFile(string& p, time_t& time) {
int r;
STRIGI_MUTEX_LOCK(&mutex);
r = nextFile();
if (r > 0) {
p.assign(path, r);
time = mtime;
}
STRIGI_MUTEX_UNLOCK(&mutex);
return r;
}
void startListing(const std::string&);
int nextFile();
};
Strigi::FileLister::Private::Private(
const Strigi::AnalyzerConfiguration* ic) :
config(ic) {
STRIGI_MUTEX_INIT(&mutex);
int nOpenDirs = 100;
dirs = (DIR**)malloc(sizeof(DIR*)*nOpenDirs);
dirsEnd = dirs + nOpenDirs;
len = (int*)malloc(sizeof(int)*nOpenDirs);
lenEnd = len + nOpenDirs;
curDir = dirs - 1;
}
void
Strigi::FileLister::Private::startListing(const string& dir){
curDir = dirs;
curLen = len;
int len = dir.length();
*curLen = len;
strcpy(path, dir.c_str());
if (len) {
if (path[len-1] != '/') {
path[len++] = '/';
path[len] = 0;
*curLen = len;
}
DIR* d = opendir(path);
if (d) {
*curDir = d;
} else {
curDir--;
}
} else {
curDir--;
}
}
Strigi::FileLister::Private::~Private() {
while (curDir >= dirs) {
if (*curDir) {
closedir(*curDir);
}
curDir--;
}
free(dirs);
free(len);
STRIGI_MUTEX_DESTROY(&mutex);
}
int
Strigi::FileLister::Private::nextFile() {
while (curDir >= dirs) {
DIR* dir = *curDir;
int l = *curLen;
subdir = readdir(dir);
while (subdir) {
// skip the directories '.' and '..'
char c1 = subdir->d_name[0];
if (c1 == '.') {
char c2 = subdir->d_name[1];
if (c2 == '.' || c2 == '\0') {
subdir = readdir(dir);
continue;
}
}
strcpy(path + l, subdir->d_name);
int sl = l + strlen(subdir->d_name);
#ifdef _WIN32
if (stat(path, &dirstat) == 0) {
#else
if (lstat(path, &dirstat) == 0) {
#endif
if (S_ISREG(dirstat.st_mode)) {
if (config == 0 || config->indexFile(path, path+sl)) {
mtime = dirstat.st_mtime;
return sl;
}
} else if (dirstat.st_mode & S_IFDIR && (config == 0
|| config->indexDir(path, path+sl))) {
mtime = dirstat.st_mtime;
strcpy(this->path+sl, "/");
DIR* d = opendir(path);
if (d) {
curDir++;
curLen++;
dir = *curDir = d;
l = *curLen = sl+1;
}
}
}
subdir = readdir(dir);
}
closedir(dir);
curDir--;
curLen--;
}
return -1;
}
Strigi::FileLister::FileLister(const Strigi::AnalyzerConfiguration* ic)
: p(new Private(ic)) {
}
Strigi::FileLister::~FileLister() {
delete p;
}
void
Strigi::FileLister::startListing(const string& dir) {
p->startListing(dir);
}
int
Strigi::FileLister::nextFile(std::string& path, time_t& time) {
return p->nextFile(path, time);
}
int
Strigi::FileLister::nextFile(const char*& path, time_t& time) {
int r = p->nextFile();
if (r >= 0) {
time = p->mtime;
path = p->path;
}
return r;
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// Antioch - A Gas Dynamics Thermochemistry Library
//
// Copyright (C) 2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
//
// $Id$
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
// valarray has to be declared before Antioch or gcc can't find the
// right versions of exp() and pow() to use??
#include "antioch_config.h"
#include <valarray>
#ifdef ANTIOCH_HAVE_EIGEN
#include "Eigen/Dense"
#endif
#ifdef ANTIOCH_HAVE_METAPHYSICL
#include "metaphysicl/numberarray.h"
#endif
#include "antioch/arrhenius_rate.h"
#include "antioch/eigen_utils.h"
#include "antioch/metaphysicl_utils.h"
#include "antioch/valarray_utils.h"
#include <cmath>
#include <limits>
template <typename PairScalars>
int vectester(const PairScalars& example)
{
typedef typename Antioch::value_type<PairScalars>::type Scalar;
const Scalar Cf = 1.4;
const Scalar eta = 1.2;
const Scalar Ea = 5.0;
Antioch::ArrheniusRate<Scalar> arrhenius_rate(Cf,eta,Ea);
// Construct from example to avoid resizing issues
PairScalars T = example;
T[0] = 1500.1;
T[1] = 1600.1;
const Scalar rate_exact0 = Cf*std::pow(1500.1,eta)*std::exp(-Ea/1500.1);
const Scalar rate_exact1 = Cf*std::pow(1600.1,eta)*std::exp(-Ea/1600.1);
int return_flag = 0;
const PairScalars rate = arrhenius_rate(T);
const Scalar tol = std::numeric_limits<Scalar>::epsilon()*10;
if( std::fabs( (rate[0] - rate_exact0)/rate_exact0 ) > tol )
{
std::cout << "Error: Mismatch in rate values." << std::endl
<< "rate(T0) = " << rate[0] << std::endl
<< "rate_exact = " << rate_exact0 << std::endl
<< "difference = " << rate[0] - rate_exact0 << std::endl;
return_flag = 1;
}
if( std::fabs( (rate[1] - rate_exact1)/rate_exact1 ) > tol )
{
std::cout << "Error: Mismatch in rate values." << std::endl
<< "rate(T1) = " << rate[1] << std::endl
<< "rate_exact = " << rate_exact1 << std::endl
<< "difference = " << rate[1] - rate_exact1 << std::endl;
return_flag = 1;
}
std::cout << "Arrhenius rate: " << arrhenius_rate << std::endl;
return return_flag;
}
int main()
{
int returnval = 0;
returnval = returnval ||
vectester (std::valarray<float>(2));
returnval = returnval ||
vectester (std::valarray<double>(2));
returnval = returnval ||
vectester (std::valarray<long double>(2));
#ifdef ANTIOCH_HAVE_EIGEN
returnval = returnval ||
vectester (Eigen::Array2f());
returnval = returnval ||
vectester (Eigen::Array2d());
returnval = returnval ||
vectester (Eigen::Array<long double, 2, 1>());
#endif
#ifdef ANTIOCH_HAVE_METAPHYSICL
returnval = returnval ||
vectester (MetaPhysicL::NumberArray<2, float> (0));
returnval = returnval ||
vectester (MetaPhysicL::NumberArray<2, double> (0));
returnval = returnval ||
vectester (MetaPhysicL::NumberArray<2, long double> (0));
#endif
return returnval;
}
<commit_msg>[antioch]: #2839, fixing ambigious overload by explicitly casting as Scalar type. Fixes a std::pow error on intel 11.1 on lonestar.<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// Antioch - A Gas Dynamics Thermochemistry Library
//
// Copyright (C) 2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
//
// $Id$
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
// valarray has to be declared before Antioch or gcc can't find the
// right versions of exp() and pow() to use??
#include "antioch_config.h"
#include <valarray>
#ifdef ANTIOCH_HAVE_EIGEN
#include "Eigen/Dense"
#endif
#ifdef ANTIOCH_HAVE_METAPHYSICL
#include "metaphysicl/numberarray.h"
#endif
#include "antioch/arrhenius_rate.h"
#include "antioch/eigen_utils.h"
#include "antioch/metaphysicl_utils.h"
#include "antioch/valarray_utils.h"
#include <cmath>
#include <limits>
template <typename PairScalars>
int vectester(const PairScalars& example)
{
typedef typename Antioch::value_type<PairScalars>::type Scalar;
const Scalar Cf = 1.4;
const Scalar eta = 1.2;
const Scalar Ea = 5.0;
Antioch::ArrheniusRate<Scalar> arrhenius_rate(Cf,eta,Ea);
// Construct from example to avoid resizing issues
PairScalars T = example;
T[0] = 1500.1;
T[1] = 1600.1;
const Scalar rate_exact0 = Cf*std::pow(Scalar(1500.1),eta)*std::exp(-Ea/1500.1);
const Scalar rate_exact1 = Cf*std::pow(Scalar(1600.1),eta)*std::exp(-Ea/1600.1);
int return_flag = 0;
const PairScalars rate = arrhenius_rate(T);
const Scalar tol = std::numeric_limits<Scalar>::epsilon()*10;
if( std::fabs( (rate[0] - rate_exact0)/rate_exact0 ) > tol )
{
std::cout << "Error: Mismatch in rate values." << std::endl
<< "rate(T0) = " << rate[0] << std::endl
<< "rate_exact = " << rate_exact0 << std::endl
<< "difference = " << rate[0] - rate_exact0 << std::endl;
return_flag = 1;
}
if( std::fabs( (rate[1] - rate_exact1)/rate_exact1 ) > tol )
{
std::cout << "Error: Mismatch in rate values." << std::endl
<< "rate(T1) = " << rate[1] << std::endl
<< "rate_exact = " << rate_exact1 << std::endl
<< "difference = " << rate[1] - rate_exact1 << std::endl;
return_flag = 1;
}
std::cout << "Arrhenius rate: " << arrhenius_rate << std::endl;
return return_flag;
}
int main()
{
int returnval = 0;
returnval = returnval ||
vectester (std::valarray<float>(2));
returnval = returnval ||
vectester (std::valarray<double>(2));
returnval = returnval ||
vectester (std::valarray<long double>(2));
#ifdef ANTIOCH_HAVE_EIGEN
returnval = returnval ||
vectester (Eigen::Array2f());
returnval = returnval ||
vectester (Eigen::Array2d());
returnval = returnval ||
vectester (Eigen::Array<long double, 2, 1>());
#endif
#ifdef ANTIOCH_HAVE_METAPHYSICL
returnval = returnval ||
vectester (MetaPhysicL::NumberArray<2, float> (0));
returnval = returnval ||
vectester (MetaPhysicL::NumberArray<2, double> (0));
returnval = returnval ||
vectester (MetaPhysicL::NumberArray<2, long double> (0));
#endif
return returnval;
}
<|endoftext|> |
<commit_before>// (C) Copyright Gennadiy Rozental 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision: 62023 $
//
// Description : unit test for new assertion construction based on input expression
// ***************************************************************************
// Boost.Test
#define BOOST_TEST_MODULE Boost.Test assertion consruction test
#include <boost/test/unit_test.hpp>
#include <boost/test/tools/assertion.hpp>
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_basic_value_expression_construction )
{
using namespace boost::test_tools;
assertion::seed seed;
{
assertion::expression const& E = assertion::seed()->*1;
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
BOOST_CHECK( res.message().is_empty() );
}
{
assertion::expression const& E = seed->*0;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
}
{
assertion::expression const& E = seed->*true;
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
BOOST_CHECK( res.message().is_empty() );
}
{
assertion::expression const& E = seed->*1.5;
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
}
#ifndef BOOST_NO_DECLTYPE
{
assertion::expression const& E = seed->* "abc";
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
}
#endif
{
assertion::expression const& E = seed->* 1>2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "1<=2" );
}
}
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_comparison_expression )
{
using namespace boost::test_tools;
assertion::seed seed;
{
assertion::expression const& E = seed->* 1>2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "1<=2" );
}
{
assertion::expression const& E = seed->* 100 < 50;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "100>=50" );
}
{
assertion::expression const& E = seed->* 5<=4;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "5>4" );
}
{
assertion::expression const& E = seed->* 10>=20;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "10<20" );
}
{
int i = 10;
assertion::expression const& E = seed->* i != 10;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "10==10" );
}
{
int i = 5;
assertion::expression const& E = seed->* i == 3;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "5!=3" );
}
}
//____________________________________________________________________________//
#ifndef BOOST_NO_DECLTYPE
BOOST_AUTO_TEST_CASE( test_arithmetic_ops )
{
using namespace boost::test_tools;
assertion::seed seed;
{
int i = 3;
int j = 5;
assertion::expression const& E = seed->* i+j !=8;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "3+5==8" );
}
{
int i = 3;
int j = 5;
assertion::expression const& E = seed->* 2*i-j > 1;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "2*3-5<=1" );
}
{
int j = 5;
assertion::expression const& E = seed->* 2<<j < 30;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "2<<5>=30" );
}
{
int i = 2;
int j = 5;
assertion::expression const& E = seed->* i&j;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "2&5" );
}
{
int i = 3;
int j = 5;
assertion::expression const& E = seed->* i^j^6;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "3^5^6" );
}
// do not support
// assertion::expression const& E = seed->*99/2 == 48 || 101/2 > 50;
// assertion::expression const& E = seed->* a ? 100 < 50 : 25*2 == 50;
// assertion::expression const& E = seed->* true,false;
}
//____________________________________________________________________________//
#endif // BOOST_NO_DECLTYPE
struct Testee {
static int s_copy_counter;
Testee() : m_value( false ) {}
Testee( Testee const& ) : m_value(false) { s_copy_counter++; }
#ifndef BOOST_NO_RVALUE_REFERENCES
Testee( Testee&& ) : m_value(false) {}
Testee( Testee const&& ) : m_value(false) {}
#endif
bool foo() { return m_value; }
operator bool() const { return m_value; }
friend std::ostream& operator<<( std::ostream& ostr, Testee const& ) { return ostr << "Testee"; }
bool m_value;
};
int Testee::s_copy_counter = 0;
#ifndef BOOST_NO_RVALUE_REFERENCES
Testee get_obj() { return std::move( Testee() ); }
Testee const get_const_obj() { return std::move( Testee() ); }
#else
Testee get_obj() { return Testee(); }
Testee const get_const_obj() { return Testee(); }
#endif
BOOST_AUTO_TEST_CASE( test_objects )
{
using namespace boost::test_tools;
assertion::seed seed;
{
Testee obj;
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* obj;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 0 );
#else
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 1 );
#endif
}
{
Testee const obj;
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* obj;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 0 );
#else
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 1 );
#endif
}
{
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* get_obj();
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 0 );
}
{
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* get_const_obj();
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 0 );
}
}
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_pointers )
{
using namespace boost::test_tools;
assertion::seed seed;
{
Testee* ptr = 0;
assertion::expression const& E = seed->* ptr;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
}
{
Testee obj1;
Testee obj2;
assertion::expression const& E = seed->* &obj1 == &obj2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
}
{
Testee obj;
Testee* ptr =&obj;
assertion::expression const& E = seed->* *ptr;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
}
#ifndef BOOST_NO_DECLTYPE
{
Testee obj;
Testee* ptr =&obj;
bool Testee::* mem_ptr =&Testee::m_value;
assertion::expression const& E = seed->* ptr->*mem_ptr;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
}
#endif
// do not support
// Testee obj;
// bool Testee::* mem_ptr =&Testee::m_value;
// assertion::expression const& E = seed->* obj.*mem_ptr;
}
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_mutating_ops )
{
using namespace boost::test_tools;
assertion::seed seed;
{
int j = 5;
assertion::expression const& E = seed->* j = 0;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j -= 5;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j *= 0;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j /= 10;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 4;
assertion::expression const& E = seed->* j %= 2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 4 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j ^= j;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
}
//____________________________________________________________________________//
// EOF
<commit_msg>Fix test case for C++03.<commit_after>// (C) Copyright Gennadiy Rozental 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision: 62023 $
//
// Description : unit test for new assertion construction based on input expression
// ***************************************************************************
// Boost.Test
#define BOOST_TEST_MODULE Boost.Test assertion consruction test
#include <boost/test/unit_test.hpp>
#include <boost/test/tools/assertion.hpp>
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_basic_value_expression_construction )
{
using namespace boost::test_tools;
assertion::seed seed;
{
assertion::expression const& E = assertion::seed()->*1;
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
BOOST_CHECK( res.message().is_empty() );
}
{
assertion::expression const& E = seed->*0;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
}
{
assertion::expression const& E = seed->*true;
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
BOOST_CHECK( res.message().is_empty() );
}
{
assertion::expression const& E = seed->*1.5;
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
}
#ifndef BOOST_NO_DECLTYPE
{
assertion::expression const& E = seed->* "abc";
predicate_result const& res = E.evaluate();
BOOST_CHECK( res );
}
#endif
{
assertion::expression const& E = seed->* 1>2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "1<=2" );
}
}
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_comparison_expression )
{
using namespace boost::test_tools;
assertion::seed seed;
{
assertion::expression const& E = seed->* 1>2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "1<=2" );
}
{
assertion::expression const& E = seed->* 100 < 50;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "100>=50" );
}
{
assertion::expression const& E = seed->* 5<=4;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "5>4" );
}
{
assertion::expression const& E = seed->* 10>=20;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "10<20" );
}
{
int i = 10;
assertion::expression const& E = seed->* i != 10;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "10==10" );
}
{
int i = 5;
assertion::expression const& E = seed->* i == 3;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "5!=3" );
}
}
//____________________________________________________________________________//
#ifndef BOOST_NO_DECLTYPE
BOOST_AUTO_TEST_CASE( test_arithmetic_ops )
{
using namespace boost::test_tools;
assertion::seed seed;
{
int i = 3;
int j = 5;
assertion::expression const& E = seed->* i+j !=8;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "3+5==8" );
}
{
int i = 3;
int j = 5;
assertion::expression const& E = seed->* 2*i-j > 1;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "2*3-5<=1" );
}
{
int j = 5;
assertion::expression const& E = seed->* 2<<j < 30;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "2<<5>=30" );
}
{
int i = 2;
int j = 5;
assertion::expression const& E = seed->* i&j;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "2&5" );
}
{
int i = 3;
int j = 5;
assertion::expression const& E = seed->* i^j^6;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "3^5^6" );
}
// do not support
// assertion::expression const& E = seed->*99/2 == 48 || 101/2 > 50;
// assertion::expression const& E = seed->* a ? 100 < 50 : 25*2 == 50;
// assertion::expression const& E = seed->* true,false;
}
//____________________________________________________________________________//
#endif // BOOST_NO_DECLTYPE
struct Testee {
static int s_copy_counter;
Testee() : m_value( false ) {}
Testee( Testee const& ) : m_value(false) { s_copy_counter++; }
#ifndef BOOST_NO_RVALUE_REFERENCES
Testee( Testee&& ) : m_value(false) {}
Testee( Testee const&& ) : m_value(false) {}
#endif
bool foo() { return m_value; }
operator bool() const { return m_value; }
friend std::ostream& operator<<( std::ostream& ostr, Testee const& ) { return ostr << "Testee"; }
bool m_value;
};
int Testee::s_copy_counter = 0;
#ifndef BOOST_NO_RVALUE_REFERENCES
Testee get_obj() { return std::move( Testee() ); }
Testee const get_const_obj() { return std::move( Testee() ); }
#else
Testee get_obj() { return Testee(); }
Testee const get_const_obj() { return Testee(); }
#endif
BOOST_AUTO_TEST_CASE( test_objects )
{
using namespace boost::test_tools;
assertion::seed seed;
{
Testee obj;
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* obj;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 0 );
#else
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 1 );
#endif
}
{
Testee const obj;
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* obj;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 0 );
#else
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 1 );
#endif
}
{
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* get_obj();
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 0 );
#else
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 1 );
#endif
}
{
Testee::s_copy_counter = 0;
assertion::expression const& E = seed->* get_const_obj();
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 0 );
#else
BOOST_CHECK_EQUAL( Testee::s_copy_counter, 1 );
#endif
}
}
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_pointers )
{
using namespace boost::test_tools;
assertion::seed seed;
{
Testee* ptr = 0;
assertion::expression const& E = seed->* ptr;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
}
{
Testee obj1;
Testee obj2;
assertion::expression const& E = seed->* &obj1 == &obj2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
}
{
Testee obj;
Testee* ptr =&obj;
assertion::expression const& E = seed->* *ptr;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)Testee is false" );
}
#ifndef BOOST_NO_DECLTYPE
{
Testee obj;
Testee* ptr =&obj;
bool Testee::* mem_ptr =&Testee::m_value;
assertion::expression const& E = seed->* ptr->*mem_ptr;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
}
#endif
// do not support
// Testee obj;
// bool Testee::* mem_ptr =&Testee::m_value;
// assertion::expression const& E = seed->* obj.*mem_ptr;
}
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_mutating_ops )
{
using namespace boost::test_tools;
assertion::seed seed;
{
int j = 5;
assertion::expression const& E = seed->* j = 0;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j -= 5;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j *= 0;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j /= 10;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
{
int j = 4;
assertion::expression const& E = seed->* j %= 2;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 4 );
#endif
}
{
int j = 5;
assertion::expression const& E = seed->* j ^= j;
predicate_result const& res = E.evaluate();
BOOST_CHECK( !res );
BOOST_CHECK_EQUAL( res.message(), "(bool)0 is false" );
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_EQUAL( j, 0 );
#else
BOOST_CHECK_EQUAL( j, 5 );
#endif
}
}
//____________________________________________________________________________//
// EOF
<|endoftext|> |
<commit_before>/*
This file is part of SWGANH. For more information, visit http://swganh.com
Copyright (c) 2006 - 2011 The SWG:ANH Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "swganh/login/login_service.h"
#include <boost/log/trivial.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "anh/app/kernel_interface.h"
#include "anh/database/database_manager.h"
#include "anh/event_dispatcher.h"
#include "anh/network/soe/packet.h"
#include "anh/network/soe/session.h"
#include "anh/network/soe/server.h"
#include "anh/service/service_directory_interface.h"
#include "anh/service/service_manager.h"
#include "anh/plugin/plugin_manager.h"
#include "swganh/base/swg_message_handler.h"
#include "swganh/login/messages/enumerate_character_id.h"
#include "swganh/login/messages/error_message.h"
#include "swganh/login/messages/login_client_token.h"
#include "swganh/login/messages/login_cluster_status.h"
#include "swganh/login/messages/login_enum_cluster.h"
#include "swganh/login/authentication_manager.h"
#include "swganh/login/login_client.h"
#include "swganh/login/encoders/sha512_encoder.h"
#include "swganh/login/providers/mysql_account_provider.h"
using namespace anh;
using namespace app;
using namespace swganh::login;
using namespace messages;
using namespace network::soe;
using namespace swganh::login;
using namespace swganh::base;
using namespace swganh::character;
using namespace swganh::galaxy;
using namespace database;
using namespace event_dispatcher;
using namespace std;
using boost::asio::ip::udp;
LoginService::LoginService(string listen_address, uint16_t listen_port, KernelInterface* kernel)
: BaseService(kernel)
, swganh::network::BaseSwgServer(kernel->GetIoService())
, galaxy_status_timer_(kernel->GetIoService())
, listen_address_(listen_address)
, listen_port_(listen_port)
{
account_provider_ = kernel->GetPluginManager()->CreateObject<providers::AccountProviderInterface>("LoginService::AccountProvider");
if (!account_provider_)
{
account_provider_ = make_shared<providers::MysqlAccountProvider>(kernel->GetDatabaseManager());
}
shared_ptr<encoders::EncoderInterface> encoder = kernel->GetPluginManager()->CreateObject<encoders::EncoderInterface>("LoginService::Encoder");
if (!encoder) {
encoder = make_shared<encoders::Sha512Encoder>(kernel->GetDatabaseManager());
}
authentication_manager_ = make_shared<AuthenticationManager>(encoder);
}
LoginService::~LoginService() {}
service::ServiceDescription LoginService::GetServiceDescription() {
service::ServiceDescription service_description(
"ANH Login Service",
"login",
"0.1",
listen_address_,
0,
listen_port_,
0);
return service_description;
}
shared_ptr<Session> LoginService::CreateSession(const udp::endpoint& endpoint)
{
shared_ptr<LoginClient> session = nullptr;
{
boost::lock_guard<boost::mutex> lg(session_map_mutex_);
if (session_map_.find(endpoint) == session_map_.end())
{
session = make_shared<LoginClient>(endpoint, this);
session_map_.insert(make_pair(endpoint, session));
}
}
return session;
}
bool LoginService::RemoveSession(std::shared_ptr<Session> session) {
{
boost::lock_guard<boost::mutex> lg(session_map_mutex_);
session_map_.erase(session->remote_endpoint());
}
return true;
}
shared_ptr<Session> LoginService::GetSession(const udp::endpoint& endpoint) {
{
boost::lock_guard<boost::mutex> lg(session_map_mutex_);
auto find_iter = session_map_.find(endpoint);
if (find_iter != session_map_.end())
{
return find_iter->second;
}
}
return CreateSession(endpoint);
}
void LoginService::onStart() {
character_service_ = static_pointer_cast<CharacterService>(kernel()->GetServiceManager()->GetService("CharacterService"));
galaxy_service_ = static_pointer_cast<GalaxyService>(kernel()->GetServiceManager()->GetService("GalaxyService"));
Server::Start(listen_port_);
UpdateGalaxyStatus_();
active().AsyncRepeated(boost::posix_time::milliseconds(5), [this] () {
boost::lock_guard<boost::mutex> lg(session_map_mutex_);
for_each(
begin(session_map_),
end(session_map_),
[=] (SessionMap::value_type& type)
{
type.second->Update();
});
});
}
void LoginService::onStop()
{
Server::Shutdown();
}
void LoginService::subscribe()
{
RegisterMessageHandler(&LoginService::HandleLoginClientId_, this);
auto event_dispatcher = kernel()->GetEventDispatcher();
event_dispatcher->Subscribe(
"UpdateGalaxyStatus",
[this] (const shared_ptr<anh::EventInterface>& incoming_event)
{
UpdateGalaxyStatus_();
});
}
int LoginService::galaxy_status_check_duration_secs() const
{
return galaxy_status_check_duration_secs_;
}
void LoginService::galaxy_status_check_duration_secs(int new_duration)
{
galaxy_status_check_duration_secs_ = new_duration;
}
int LoginService::login_error_timeout_secs() const
{
return login_error_timeout_secs_;
}
void LoginService::login_auto_registration(bool auto_registration)
{
login_auto_registration_ = auto_registration;
}
bool LoginService::login_auto_registration() const
{
return login_auto_registration_;
}
void LoginService::login_error_timeout_secs(int new_timeout)
{
login_error_timeout_secs_ = new_timeout;
}
void LoginService::UpdateGalaxyStatus_() {
BOOST_LOG_TRIVIAL(info) << "Updating galaxy status";
galaxy_status_ = GetGalaxyStatus_();
const vector<GalaxyStatus>& status = galaxy_status_;
//boost::lock_guard<boost::mutex> lg(clients_mutex_);
//std::for_each(clients_.begin(), clients_.end(), [&status] (ClientMap::value_type& client_entry) {
// if (client_entry.second) {
// client_entry.second->SendMessage(
// BuildLoginClusterStatus(status));
// }
//});
}
std::vector<GalaxyStatus> LoginService::GetGalaxyStatus_() {
std::vector<GalaxyStatus> galaxy_status;
auto service_directory = kernel()->GetServiceDirectory();
auto galaxy_list = service_directory->getGalaxySnapshot();
std::for_each(galaxy_list.begin(), galaxy_list.end(), [this, &galaxy_status, &service_directory] (anh::service::Galaxy& galaxy) {
auto service_list = service_directory->getServiceSnapshot(galaxy);
auto it = std::find_if(service_list.begin(), service_list.end(), [] (anh::service::ServiceDescription& service) {
return service.type().compare("connection") == 0;
});
if (it != service_list.end()) {
GalaxyStatus status;
status.address = it->address();
status.connection_port = it->udp_port();
// TODO: Add a meaningful value here (ping to client from server?)
status.distance = 0xffff8f80;
status.galaxy_id = galaxy.id();
// TODO: Add a configurable value here
status.max_characters = 2;
// TODO: Add a configurable value here
status.max_population = 0x00000cb2;
status.name = galaxy.name();
status.ping_port = it->ping_port();
status.server_population = galaxy_service_->GetPopulation();
status.status = service_directory->galaxy().status();
galaxy_status.push_back(std::move(status));
}
});
return galaxy_status;
}
void LoginService::HandleLoginClientId_(std::shared_ptr<LoginClient> login_client, const LoginClientId& message)
{
login_client->SetUsername(message.username);
login_client->SetPassword(message.password);
login_client->SetVersion(message.client_version);
auto account = account_provider_->FindByUsername(message.username);
if (!account && login_auto_registration_ == true)
{
if(account_provider_->AutoRegisterAccount(message.username, message.password))
{
account = account_provider_->FindByUsername(message.username);
}
}
if (!account || !authentication_manager_->Authenticate(login_client, account)) {
BOOST_LOG_TRIVIAL(warning) << "Login request for invalid user: " << login_client->GetUsername();
ErrorMessage error;
error.type = "@cpt_login_fail";
error.message = "@msg_login_fail";
error.force_fatal = false;
login_client->SendMessage(error);
auto timer = std::make_shared<boost::asio::deadline_timer>(kernel()->GetIoService(), boost::posix_time::seconds(login_error_timeout_secs_));
timer->async_wait([login_client] (const boost::system::error_code& e)
{
if (login_client)
{
login_client->Close();
BOOST_LOG_TRIVIAL(warning) << "Closing connection";
}
});
return;
}
login_client->SetAccount(account);
// create account session
string account_session = boost::posix_time::to_simple_string(boost::posix_time::microsec_clock::local_time())
+ boost::lexical_cast<string>(login_client->remote_endpoint().address());
account_provider_->CreateAccountSession(account->account_id(), account_session);
login_client->SendMessage(
messages::BuildLoginClientToken(login_client, account_session));
login_client->SendMessage(
messages::BuildLoginEnumCluster(login_client, galaxy_status_));
login_client->SendMessage(
messages::BuildLoginClusterStatus(galaxy_status_));
auto characters = character_service_->GetCharactersForAccount(login_client->GetAccount()->account_id());
login_client->SendMessage(
messages::BuildEnumerateCharacterId(characters));
}
uint32_t LoginService::GetAccountBySessionKey(const string& session_key) {
return account_provider_->FindBySessionKey(session_key);
}
<commit_msg>Re-enabled sending status updates to clients.<commit_after>/*
This file is part of SWGANH. For more information, visit http://swganh.com
Copyright (c) 2006 - 2011 The SWG:ANH Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "swganh/login/login_service.h"
#include <boost/log/trivial.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "anh/app/kernel_interface.h"
#include "anh/database/database_manager.h"
#include "anh/event_dispatcher.h"
#include "anh/network/soe/packet.h"
#include "anh/network/soe/session.h"
#include "anh/network/soe/server.h"
#include "anh/service/service_directory_interface.h"
#include "anh/service/service_manager.h"
#include "anh/plugin/plugin_manager.h"
#include "swganh/base/swg_message_handler.h"
#include "swganh/login/messages/enumerate_character_id.h"
#include "swganh/login/messages/error_message.h"
#include "swganh/login/messages/login_client_token.h"
#include "swganh/login/messages/login_cluster_status.h"
#include "swganh/login/messages/login_enum_cluster.h"
#include "swganh/login/authentication_manager.h"
#include "swganh/login/login_client.h"
#include "swganh/login/encoders/sha512_encoder.h"
#include "swganh/login/providers/mysql_account_provider.h"
using namespace anh;
using namespace app;
using namespace swganh::login;
using namespace messages;
using namespace network::soe;
using namespace swganh::login;
using namespace swganh::base;
using namespace swganh::character;
using namespace swganh::galaxy;
using namespace database;
using namespace event_dispatcher;
using namespace std;
using boost::asio::ip::udp;
LoginService::LoginService(string listen_address, uint16_t listen_port, KernelInterface* kernel)
: BaseService(kernel)
, swganh::network::BaseSwgServer(kernel->GetIoService())
, galaxy_status_timer_(kernel->GetIoService())
, listen_address_(listen_address)
, listen_port_(listen_port)
{
account_provider_ = kernel->GetPluginManager()->CreateObject<providers::AccountProviderInterface>("LoginService::AccountProvider");
if (!account_provider_)
{
account_provider_ = make_shared<providers::MysqlAccountProvider>(kernel->GetDatabaseManager());
}
shared_ptr<encoders::EncoderInterface> encoder = kernel->GetPluginManager()->CreateObject<encoders::EncoderInterface>("LoginService::Encoder");
if (!encoder) {
encoder = make_shared<encoders::Sha512Encoder>(kernel->GetDatabaseManager());
}
authentication_manager_ = make_shared<AuthenticationManager>(encoder);
}
LoginService::~LoginService() {}
service::ServiceDescription LoginService::GetServiceDescription() {
service::ServiceDescription service_description(
"ANH Login Service",
"login",
"0.1",
listen_address_,
0,
listen_port_,
0);
return service_description;
}
shared_ptr<Session> LoginService::CreateSession(const udp::endpoint& endpoint)
{
shared_ptr<LoginClient> session = nullptr;
{
boost::lock_guard<boost::mutex> lg(session_map_mutex_);
if (session_map_.find(endpoint) == session_map_.end())
{
session = make_shared<LoginClient>(endpoint, this);
session_map_.insert(make_pair(endpoint, session));
}
}
return session;
}
bool LoginService::RemoveSession(std::shared_ptr<Session> session) {
{
boost::lock_guard<boost::mutex> lg(session_map_mutex_);
session_map_.erase(session->remote_endpoint());
}
return true;
}
shared_ptr<Session> LoginService::GetSession(const udp::endpoint& endpoint) {
{
boost::lock_guard<boost::mutex> lg(session_map_mutex_);
auto find_iter = session_map_.find(endpoint);
if (find_iter != session_map_.end())
{
return find_iter->second;
}
}
return CreateSession(endpoint);
}
void LoginService::onStart() {
character_service_ = static_pointer_cast<CharacterService>(kernel()->GetServiceManager()->GetService("CharacterService"));
galaxy_service_ = static_pointer_cast<GalaxyService>(kernel()->GetServiceManager()->GetService("GalaxyService"));
Server::Start(listen_port_);
UpdateGalaxyStatus_();
active().AsyncRepeated(boost::posix_time::milliseconds(5), [this] () {
boost::lock_guard<boost::mutex> lg(session_map_mutex_);
for_each(
begin(session_map_),
end(session_map_),
[=] (SessionMap::value_type& type)
{
type.second->Update();
});
});
}
void LoginService::onStop()
{
Server::Shutdown();
}
void LoginService::subscribe()
{
RegisterMessageHandler(&LoginService::HandleLoginClientId_, this);
auto event_dispatcher = kernel()->GetEventDispatcher();
event_dispatcher->Subscribe(
"UpdateGalaxyStatus",
[this] (const shared_ptr<anh::EventInterface>& incoming_event)
{
UpdateGalaxyStatus_();
});
}
int LoginService::galaxy_status_check_duration_secs() const
{
return galaxy_status_check_duration_secs_;
}
void LoginService::galaxy_status_check_duration_secs(int new_duration)
{
galaxy_status_check_duration_secs_ = new_duration;
}
int LoginService::login_error_timeout_secs() const
{
return login_error_timeout_secs_;
}
void LoginService::login_auto_registration(bool auto_registration)
{
login_auto_registration_ = auto_registration;
}
bool LoginService::login_auto_registration() const
{
return login_auto_registration_;
}
void LoginService::login_error_timeout_secs(int new_timeout)
{
login_error_timeout_secs_ = new_timeout;
}
void LoginService::UpdateGalaxyStatus_() {
BOOST_LOG_TRIVIAL(info) << "Updating galaxy status";
galaxy_status_ = GetGalaxyStatus_();
auto status_message = BuildLoginClusterStatus(galaxy_status_);
boost::lock_guard<boost::mutex> lg(session_map_mutex_);
std::for_each(
begin(session_map_),
end(session_map_),
[&status_message] (SessionMap::value_type& item)
{
if (item.second) {
item.second->SendMessage(status_message);
}
});
}
std::vector<GalaxyStatus> LoginService::GetGalaxyStatus_() {
std::vector<GalaxyStatus> galaxy_status;
auto service_directory = kernel()->GetServiceDirectory();
auto galaxy_list = service_directory->getGalaxySnapshot();
std::for_each(galaxy_list.begin(), galaxy_list.end(), [this, &galaxy_status, &service_directory] (anh::service::Galaxy& galaxy) {
auto service_list = service_directory->getServiceSnapshot(galaxy);
auto it = std::find_if(service_list.begin(), service_list.end(), [] (anh::service::ServiceDescription& service) {
return service.type().compare("connection") == 0;
});
if (it != service_list.end()) {
GalaxyStatus status;
status.address = it->address();
status.connection_port = it->udp_port();
// TODO: Add a meaningful value here (ping to client from server?)
status.distance = 0xffff8f80;
status.galaxy_id = galaxy.id();
// TODO: Add a configurable value here
status.max_characters = 2;
// TODO: Add a configurable value here
status.max_population = 0x00000cb2;
status.name = galaxy.name();
status.ping_port = it->ping_port();
status.server_population = galaxy_service_->GetPopulation();
status.status = service_directory->galaxy().status();
galaxy_status.push_back(std::move(status));
}
});
return galaxy_status;
}
void LoginService::HandleLoginClientId_(std::shared_ptr<LoginClient> login_client, const LoginClientId& message)
{
login_client->SetUsername(message.username);
login_client->SetPassword(message.password);
login_client->SetVersion(message.client_version);
auto account = account_provider_->FindByUsername(message.username);
if (!account && login_auto_registration_ == true)
{
if(account_provider_->AutoRegisterAccount(message.username, message.password))
{
account = account_provider_->FindByUsername(message.username);
}
}
if (!account || !authentication_manager_->Authenticate(login_client, account)) {
BOOST_LOG_TRIVIAL(warning) << "Login request for invalid user: " << login_client->GetUsername();
ErrorMessage error;
error.type = "@cpt_login_fail";
error.message = "@msg_login_fail";
error.force_fatal = false;
login_client->SendMessage(error);
auto timer = std::make_shared<boost::asio::deadline_timer>(kernel()->GetIoService(), boost::posix_time::seconds(login_error_timeout_secs_));
timer->async_wait([login_client] (const boost::system::error_code& e)
{
if (login_client)
{
login_client->Close();
BOOST_LOG_TRIVIAL(warning) << "Closing connection";
}
});
return;
}
login_client->SetAccount(account);
// create account session
string account_session = boost::posix_time::to_simple_string(boost::posix_time::microsec_clock::local_time())
+ boost::lexical_cast<string>(login_client->remote_endpoint().address());
account_provider_->CreateAccountSession(account->account_id(), account_session);
login_client->SendMessage(
messages::BuildLoginClientToken(login_client, account_session));
login_client->SendMessage(
messages::BuildLoginEnumCluster(login_client, galaxy_status_));
login_client->SendMessage(
messages::BuildLoginClusterStatus(galaxy_status_));
auto characters = character_service_->GetCharactersForAccount(login_client->GetAccount()->account_id());
login_client->SendMessage(
messages::BuildEnumerateCharacterId(characters));
}
uint32_t LoginService::GetAccountBySessionKey(const string& session_key) {
return account_provider_->FindBySessionKey(session_key);
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "watchtable.h"
#include <QtCore/qdebug.h>
#include <QtGui/qevent.h>
#include <QtGui/qaction.h>
#include <QtGui/qmenu.h>
#include <private/qmldebug_p.h>
#include <QtDeclarative/qmlmetatype.h>
QT_BEGIN_NAMESPACE
WatchTableModel::WatchTableModel(QmlEngineDebug *client, QObject *parent)
: QAbstractTableModel(parent),
m_client(client)
{
}
WatchTableModel::~WatchTableModel()
{
for (int i=0; i<m_columns.count(); ++i)
delete m_columns[i].watch;
}
void WatchTableModel::setEngineDebug(QmlEngineDebug *client)
{
m_client = client;
}
void WatchTableModel::addWatch(QmlDebugWatch *watch, const QString &title)
{
QString property;
if (qobject_cast<QmlDebugPropertyWatch *>(watch))
property = qobject_cast<QmlDebugPropertyWatch *>(watch)->name();
connect(watch, SIGNAL(valueChanged(QByteArray,QVariant)),
SLOT(watchedValueChanged(QByteArray,QVariant)));
connect(watch, SIGNAL(stateChanged(QmlDebugWatch::State)), SLOT(watchStateChanged()));
int col = columnCount(QModelIndex());
beginInsertColumns(QModelIndex(), col, col);
WatchedEntity e;
e.title = title;
e.hasFirstValue = false;
e.property = property;
e.watch = watch;
m_columns.append(e);
endInsertColumns();
}
void WatchTableModel::removeWatch(QmlDebugWatch *watch)
{
int column = columnForWatch(watch);
if (column == -1)
return;
WatchedEntity entity = m_columns.takeAt(column);
for (QList<Value>::Iterator iter = m_values.begin(); iter != m_values.end();) {
if (iter->column == column) {
iter = m_values.erase(iter);
} else {
if(iter->column > column)
--iter->column;
++iter;
}
}
reset();
}
void WatchTableModel::updateWatch(QmlDebugWatch *watch, const QVariant &value)
{
int column = columnForWatch(watch);
if (column == -1)
return;
addValue(column, value);
if (!m_columns[column].hasFirstValue) {
m_columns[column].hasFirstValue = true;
m_values[m_values.count() - 1].first = true;
}
}
QmlDebugWatch *WatchTableModel::findWatch(int column) const
{
if (column < m_columns.count())
return m_columns.at(column).watch;
return 0;
}
QmlDebugWatch *WatchTableModel::findWatch(int objectDebugId, const QString &property) const
{
for (int i=0; i<m_columns.count(); ++i) {
if (m_columns[i].watch->objectDebugId() == objectDebugId
&& m_columns[i].property == property) {
return m_columns[i].watch;
}
}
return 0;
}
int WatchTableModel::rowCount(const QModelIndex &) const
{
return m_values.count();
}
int WatchTableModel::columnCount(const QModelIndex &) const
{
return m_columns.count();
}
QVariant WatchTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (section < m_columns.count() && role == Qt::DisplayRole)
return m_columns.at(section).title;
} else {
if (role == Qt::DisplayRole)
return section + 1;
}
return QVariant();
}
QVariant WatchTableModel::data(const QModelIndex &idx, int role) const
{
if (m_values.at(idx.row()).column == idx.column()) {
if (role == Qt::DisplayRole) {
const QVariant &value = m_values.at(idx.row()).variant;
QString str = value.toString();
if (str.isEmpty() && QmlMetaType::isObject(value.userType())) {
QObject *o = QmlMetaType::toQObject(value);
if(o) {
QString objectName = o->objectName();
if(objectName.isEmpty())
objectName = QLatin1String("<unnamed>");
str = QLatin1String(o->metaObject()->className()) +
QLatin1String(": ") + objectName;
}
}
if(str.isEmpty()) {
QDebug d(&str);
d << value;
}
return QVariant(str);
} else if(role == Qt::BackgroundRole) {
if(m_values.at(idx.row()).first)
return QColor(Qt::green);
else
return QVariant();
} else {
return QVariant();
}
} else {
return QVariant();
}
}
void WatchTableModel::watchStateChanged()
{
QmlDebugWatch *watch = qobject_cast<QmlDebugWatch*>(sender());
if (watch && watch->state() == QmlDebugWatch::Inactive) {
removeWatch(watch);
watch->deleteLater();
}
}
int WatchTableModel::columnForWatch(QmlDebugWatch *watch) const
{
for (int i=0; i<m_columns.count(); ++i) {
if (m_columns.at(i).watch == watch)
return i;
}
return -1;
}
void WatchTableModel::addValue(int column, const QVariant &value)
{
int row = columnCount(QModelIndex());
beginInsertRows(QModelIndex(), row, row);
Value v;
v.column = column;
v.variant = value;
v.first = false;
m_values.append(v);
endInsertRows();
}
void WatchTableModel::togglePropertyWatch(const QmlDebugObjectReference &object, const QmlDebugPropertyReference &property)
{
if (!m_client || !property.hasNotifySignal())
return;
QmlDebugWatch *watch = findWatch(object.debugId(), property.name());
if (watch) {
// watch will be deleted in watchStateChanged()
m_client->removeWatch(watch);
return;
}
watch = m_client->addWatch(property, this);
if (watch->state() == QmlDebugWatch::Dead) {
delete watch;
watch = 0;
} else {
QString desc = property.name()
+ QLatin1String(" on\n")
+ object.className()
+ QLatin1String(":\n")
+ (object.name().isEmpty() ? QLatin1String("<unnamed object>") : object.name());
addWatch(watch, desc);
emit watchCreated(watch);
}
}
void WatchTableModel::watchedValueChanged(const QByteArray &propertyName, const QVariant &value)
{
Q_UNUSED(propertyName);
QmlDebugWatch *watch = qobject_cast<QmlDebugWatch*>(sender());
if (watch)
updateWatch(watch, value);
}
void WatchTableModel::expressionWatchRequested(const QmlDebugObjectReference &obj, const QString &expr)
{
if (!m_client)
return;
QmlDebugWatch *watch = m_client->addWatch(obj, expr, this);
if (watch->state() == QmlDebugWatch::Dead) {
delete watch;
watch = 0;
} else {
addWatch(watch, expr);
emit watchCreated(watch);
}
}
void WatchTableModel::removeWatchAt(int column)
{
if (!m_client)
return;
QmlDebugWatch *watch = findWatch(column);
if (watch) {
m_client->removeWatch(watch);
delete watch;
watch = 0;
}
}
void WatchTableModel::removeAllWatches()
{
for (int i=0; i<m_columns.count(); ++i) {
if (m_client)
m_client->removeWatch(m_columns[i].watch);
else
delete m_columns[i].watch;
}
m_columns.clear();
m_values.clear();
reset();
}
//----------------------------------------------
WatchTableHeaderView::WatchTableHeaderView(WatchTableModel *model, QWidget *parent)
: QHeaderView(Qt::Horizontal, parent),
m_model(model)
{
setClickable(true);
}
void WatchTableHeaderView::mousePressEvent(QMouseEvent *me)
{
QHeaderView::mousePressEvent(me);
if (me->button() == Qt::RightButton && me->type() == QEvent::MouseButtonPress) {
int col = logicalIndexAt(me->pos());
if (col >= 0) {
QAction action(tr("Stop watching"), 0);
QList<QAction *> actions;
actions << &action;
if (QMenu::exec(actions, me->globalPos()))
m_model->removeWatchAt(col);
}
}
}
//----------------------------------------------
WatchTableView::WatchTableView(WatchTableModel *model, QWidget *parent)
: QTableView(parent),
m_model(model)
{
setAlternatingRowColors(true);
connect(model, SIGNAL(watchCreated(QmlDebugWatch*)), SLOT(watchCreated(QmlDebugWatch*)));
connect(this, SIGNAL(activated(QModelIndex)), SLOT(indexActivated(QModelIndex)));
}
void WatchTableView::indexActivated(const QModelIndex &index)
{
QmlDebugWatch *watch = m_model->findWatch(index.column());
if (watch)
emit objectActivated(watch->objectDebugId());
}
void WatchTableView::watchCreated(QmlDebugWatch *watch)
{
int column = m_model->columnForWatch(watch);
resizeColumnToContents(column);
}
QT_END_NAMESPACE
<commit_msg>Compile.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "watchtable.h"
#include <QtCore/qdebug.h>
#include <QtGui/qevent.h>
#include <QtGui/qaction.h>
#include <QtGui/qmenu.h>
#include <private/qmldebug_p.h>
#include <QtDeclarative/qmlmetatype.h>
QT_BEGIN_NAMESPACE
WatchTableModel::WatchTableModel(QmlEngineDebug *client, QObject *parent)
: QAbstractTableModel(parent),
m_client(client)
{
}
WatchTableModel::~WatchTableModel()
{
for (int i=0; i<m_columns.count(); ++i)
delete m_columns[i].watch;
}
void WatchTableModel::setEngineDebug(QmlEngineDebug *client)
{
m_client = client;
}
void WatchTableModel::addWatch(QmlDebugWatch *watch, const QString &title)
{
QString property;
if (qobject_cast<QmlDebugPropertyWatch *>(watch))
property = qobject_cast<QmlDebugPropertyWatch *>(watch)->name();
connect(watch, SIGNAL(valueChanged(QByteArray,QVariant)),
SLOT(watchedValueChanged(QByteArray,QVariant)));
connect(watch, SIGNAL(stateChanged(QmlDebugWatch::State)), SLOT(watchStateChanged()));
int col = columnCount(QModelIndex());
beginInsertColumns(QModelIndex(), col, col);
WatchedEntity e;
e.title = title;
e.hasFirstValue = false;
e.property = property;
e.watch = watch;
m_columns.append(e);
endInsertColumns();
}
void WatchTableModel::removeWatch(QmlDebugWatch *watch)
{
int column = columnForWatch(watch);
if (column == -1)
return;
WatchedEntity entity = m_columns.takeAt(column);
for (QList<Value>::Iterator iter = m_values.begin(); iter != m_values.end();) {
if (iter->column == column) {
iter = m_values.erase(iter);
} else {
if(iter->column > column)
--iter->column;
++iter;
}
}
reset();
}
void WatchTableModel::updateWatch(QmlDebugWatch *watch, const QVariant &value)
{
int column = columnForWatch(watch);
if (column == -1)
return;
addValue(column, value);
if (!m_columns[column].hasFirstValue) {
m_columns[column].hasFirstValue = true;
m_values[m_values.count() - 1].first = true;
}
}
QmlDebugWatch *WatchTableModel::findWatch(int column) const
{
if (column < m_columns.count())
return m_columns.at(column).watch;
return 0;
}
QmlDebugWatch *WatchTableModel::findWatch(int objectDebugId, const QString &property) const
{
for (int i=0; i<m_columns.count(); ++i) {
if (m_columns[i].watch->objectDebugId() == objectDebugId
&& m_columns[i].property == property) {
return m_columns[i].watch;
}
}
return 0;
}
int WatchTableModel::rowCount(const QModelIndex &) const
{
return m_values.count();
}
int WatchTableModel::columnCount(const QModelIndex &) const
{
return m_columns.count();
}
QVariant WatchTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (section < m_columns.count() && role == Qt::DisplayRole)
return m_columns.at(section).title;
} else {
if (role == Qt::DisplayRole)
return section + 1;
}
return QVariant();
}
QVariant WatchTableModel::data(const QModelIndex &idx, int role) const
{
if (m_values.at(idx.row()).column == idx.column()) {
if (role == Qt::DisplayRole) {
const QVariant &value = m_values.at(idx.row()).variant;
QString str = value.toString();
if (str.isEmpty() && QmlMetaType::isQObject(value.userType())) {
QObject *o = QmlMetaType::toQObject(value);
if(o) {
QString objectName = o->objectName();
if(objectName.isEmpty())
objectName = QLatin1String("<unnamed>");
str = QLatin1String(o->metaObject()->className()) +
QLatin1String(": ") + objectName;
}
}
if(str.isEmpty()) {
QDebug d(&str);
d << value;
}
return QVariant(str);
} else if(role == Qt::BackgroundRole) {
if(m_values.at(idx.row()).first)
return QColor(Qt::green);
else
return QVariant();
} else {
return QVariant();
}
} else {
return QVariant();
}
}
void WatchTableModel::watchStateChanged()
{
QmlDebugWatch *watch = qobject_cast<QmlDebugWatch*>(sender());
if (watch && watch->state() == QmlDebugWatch::Inactive) {
removeWatch(watch);
watch->deleteLater();
}
}
int WatchTableModel::columnForWatch(QmlDebugWatch *watch) const
{
for (int i=0; i<m_columns.count(); ++i) {
if (m_columns.at(i).watch == watch)
return i;
}
return -1;
}
void WatchTableModel::addValue(int column, const QVariant &value)
{
int row = columnCount(QModelIndex());
beginInsertRows(QModelIndex(), row, row);
Value v;
v.column = column;
v.variant = value;
v.first = false;
m_values.append(v);
endInsertRows();
}
void WatchTableModel::togglePropertyWatch(const QmlDebugObjectReference &object, const QmlDebugPropertyReference &property)
{
if (!m_client || !property.hasNotifySignal())
return;
QmlDebugWatch *watch = findWatch(object.debugId(), property.name());
if (watch) {
// watch will be deleted in watchStateChanged()
m_client->removeWatch(watch);
return;
}
watch = m_client->addWatch(property, this);
if (watch->state() == QmlDebugWatch::Dead) {
delete watch;
watch = 0;
} else {
QString desc = property.name()
+ QLatin1String(" on\n")
+ object.className()
+ QLatin1String(":\n")
+ (object.name().isEmpty() ? QLatin1String("<unnamed object>") : object.name());
addWatch(watch, desc);
emit watchCreated(watch);
}
}
void WatchTableModel::watchedValueChanged(const QByteArray &propertyName, const QVariant &value)
{
Q_UNUSED(propertyName);
QmlDebugWatch *watch = qobject_cast<QmlDebugWatch*>(sender());
if (watch)
updateWatch(watch, value);
}
void WatchTableModel::expressionWatchRequested(const QmlDebugObjectReference &obj, const QString &expr)
{
if (!m_client)
return;
QmlDebugWatch *watch = m_client->addWatch(obj, expr, this);
if (watch->state() == QmlDebugWatch::Dead) {
delete watch;
watch = 0;
} else {
addWatch(watch, expr);
emit watchCreated(watch);
}
}
void WatchTableModel::removeWatchAt(int column)
{
if (!m_client)
return;
QmlDebugWatch *watch = findWatch(column);
if (watch) {
m_client->removeWatch(watch);
delete watch;
watch = 0;
}
}
void WatchTableModel::removeAllWatches()
{
for (int i=0; i<m_columns.count(); ++i) {
if (m_client)
m_client->removeWatch(m_columns[i].watch);
else
delete m_columns[i].watch;
}
m_columns.clear();
m_values.clear();
reset();
}
//----------------------------------------------
WatchTableHeaderView::WatchTableHeaderView(WatchTableModel *model, QWidget *parent)
: QHeaderView(Qt::Horizontal, parent),
m_model(model)
{
setClickable(true);
}
void WatchTableHeaderView::mousePressEvent(QMouseEvent *me)
{
QHeaderView::mousePressEvent(me);
if (me->button() == Qt::RightButton && me->type() == QEvent::MouseButtonPress) {
int col = logicalIndexAt(me->pos());
if (col >= 0) {
QAction action(tr("Stop watching"), 0);
QList<QAction *> actions;
actions << &action;
if (QMenu::exec(actions, me->globalPos()))
m_model->removeWatchAt(col);
}
}
}
//----------------------------------------------
WatchTableView::WatchTableView(WatchTableModel *model, QWidget *parent)
: QTableView(parent),
m_model(model)
{
setAlternatingRowColors(true);
connect(model, SIGNAL(watchCreated(QmlDebugWatch*)), SLOT(watchCreated(QmlDebugWatch*)));
connect(this, SIGNAL(activated(QModelIndex)), SLOT(indexActivated(QModelIndex)));
}
void WatchTableView::indexActivated(const QModelIndex &index)
{
QmlDebugWatch *watch = m_model->findWatch(index.column());
if (watch)
emit objectActivated(watch->objectDebugId());
}
void WatchTableView::watchCreated(QmlDebugWatch *watch)
{
int column = m_model->columnForWatch(watch);
resizeColumnToContents(column);
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwaylandeglwindow.h"
#include "qwaylandscreen.h"
#include "qwaylandglcontext.h"
#include <QtPlatformSupport/private/qeglconvenience_p.h>
#include <QDebug>
#include <QtGui/QWindow>
#include <qpa/qwindowsysteminterface.h>
#include <QOpenGLFramebufferObject>
#include <QOpenGLContext>
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
#include "windowmanager_integration/qwaylandwindowmanagerintegration.h"
#endif
QT_USE_NAMESPACE
QWaylandEglWindow::QWaylandEglWindow(QWindow *window)
: QWaylandWindow(window)
, m_eglIntegration(static_cast<QWaylandEglIntegration *>(mDisplay->eglIntegration()))
, m_waylandEglWindow(0)
, m_eglSurface(0)
, m_eglConfig(0)
, m_contentFBO(0)
, m_resize(false)
, m_format(window->format())
{
setGeometry(window->geometry());
}
QWaylandEglWindow::~QWaylandEglWindow()
{
if (m_eglSurface) {
eglDestroySurface(m_eglIntegration->eglDisplay(), m_eglSurface);
m_eglSurface = 0;
}
wl_egl_window_destroy(m_waylandEglWindow);
delete m_contentFBO;
}
QWaylandWindow::WindowType QWaylandEglWindow::windowType() const
{
return QWaylandWindow::Egl;
}
void QWaylandEglWindow::setGeometry(const QRect &rect)
{
createDecoration();
QMargins margins = frameMargins();
QSize sizeWithMargins = rect.size() + QSize(margins.left() + margins.right(), margins.top() + margins.bottom());
if (m_waylandEglWindow) {
int current_width, current_height;
wl_egl_window_get_attached_size(m_waylandEglWindow,¤t_width,¤t_height);
if (current_width != sizeWithMargins.width() || current_height != sizeWithMargins.height()) {
wl_egl_window_resize(m_waylandEglWindow, sizeWithMargins.width(), sizeWithMargins.height(), mOffset.x(), mOffset.y());
mOffset = QPoint();
m_resize = true;
}
} else {
m_waylandEglWindow = wl_egl_window_create(wl_surface(), sizeWithMargins.width(), sizeWithMargins.height());
}
QWaylandWindow::setGeometry(rect);
}
QRect QWaylandEglWindow::contentsRect() const
{
QRect r = geometry();
QMargins m = frameMargins();
return QRect(m.left(), m.bottom(), r.width(), r.height());
}
QSurfaceFormat QWaylandEglWindow::format() const
{
return m_format;
}
EGLSurface QWaylandEglWindow::eglSurface() const
{
if (!m_waylandEglWindow) {
QWaylandEglWindow *self = const_cast<QWaylandEglWindow *>(this);
self->createDecoration();
QMargins margins = frameMargins();
QSize sizeWithMargins = geometry().size() + QSize(margins.left() + margins.right(), margins.top() + margins.bottom());
m_waylandEglWindow = wl_egl_window_create(self->wl_surface(), sizeWithMargins.width(), sizeWithMargins.height());
}
if (!m_eglSurface) {
m_eglConfig = q_configFromGLFormat(m_eglIntegration->eglDisplay(), window()->format(), true);
const_cast<QWaylandEglWindow *>(this)->m_format = q_glFormatFromConfig(m_eglIntegration->eglDisplay(),m_eglConfig);
EGLNativeWindowType window = (EGLNativeWindowType) m_waylandEglWindow;
m_eglSurface = eglCreateWindowSurface(m_eglIntegration->eglDisplay(), m_eglConfig, window, 0);
}
return m_eglSurface;
}
GLuint QWaylandEglWindow::contentFBO() const
{
if (!decoration())
return 0;
if (m_resize || !m_contentFBO) {
QOpenGLFramebufferObject *old = m_contentFBO;
m_contentFBO = new QOpenGLFramebufferObject(geometry().width(), geometry().height(), QOpenGLFramebufferObject::CombinedDepthStencil);
delete old;
m_resize = false;
}
return m_contentFBO->handle();
}
GLuint QWaylandEglWindow::contentTexture() const
{
return m_contentFBO->texture();
}
void QWaylandEglWindow::bindContentFBO()
{
if (decoration()) {
contentFBO();
m_contentFBO->bind();
}
}
<commit_msg>Use requested window format<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwaylandeglwindow.h"
#include "qwaylandscreen.h"
#include "qwaylandglcontext.h"
#include <QtPlatformSupport/private/qeglconvenience_p.h>
#include <QDebug>
#include <QtGui/QWindow>
#include <qpa/qwindowsysteminterface.h>
#include <QOpenGLFramebufferObject>
#include <QOpenGLContext>
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
#include "windowmanager_integration/qwaylandwindowmanagerintegration.h"
#endif
QT_USE_NAMESPACE
QWaylandEglWindow::QWaylandEglWindow(QWindow *window)
: QWaylandWindow(window)
, m_eglIntegration(static_cast<QWaylandEglIntegration *>(mDisplay->eglIntegration()))
, m_waylandEglWindow(0)
, m_eglSurface(0)
, m_eglConfig(0)
, m_contentFBO(0)
, m_resize(false)
, m_format(window->requestedFormat())
{
setGeometry(window->geometry());
}
QWaylandEglWindow::~QWaylandEglWindow()
{
if (m_eglSurface) {
eglDestroySurface(m_eglIntegration->eglDisplay(), m_eglSurface);
m_eglSurface = 0;
}
wl_egl_window_destroy(m_waylandEglWindow);
delete m_contentFBO;
}
QWaylandWindow::WindowType QWaylandEglWindow::windowType() const
{
return QWaylandWindow::Egl;
}
void QWaylandEglWindow::setGeometry(const QRect &rect)
{
createDecoration();
QMargins margins = frameMargins();
QSize sizeWithMargins = rect.size() + QSize(margins.left() + margins.right(), margins.top() + margins.bottom());
if (m_waylandEglWindow) {
int current_width, current_height;
wl_egl_window_get_attached_size(m_waylandEglWindow,¤t_width,¤t_height);
if (current_width != sizeWithMargins.width() || current_height != sizeWithMargins.height()) {
wl_egl_window_resize(m_waylandEglWindow, sizeWithMargins.width(), sizeWithMargins.height(), mOffset.x(), mOffset.y());
mOffset = QPoint();
m_resize = true;
}
} else {
m_waylandEglWindow = wl_egl_window_create(wl_surface(), sizeWithMargins.width(), sizeWithMargins.height());
}
QWaylandWindow::setGeometry(rect);
}
QRect QWaylandEglWindow::contentsRect() const
{
QRect r = geometry();
QMargins m = frameMargins();
return QRect(m.left(), m.bottom(), r.width(), r.height());
}
QSurfaceFormat QWaylandEglWindow::format() const
{
return m_format;
}
EGLSurface QWaylandEglWindow::eglSurface() const
{
if (!m_waylandEglWindow) {
QWaylandEglWindow *self = const_cast<QWaylandEglWindow *>(this);
self->createDecoration();
QMargins margins = frameMargins();
QSize sizeWithMargins = geometry().size() + QSize(margins.left() + margins.right(), margins.top() + margins.bottom());
m_waylandEglWindow = wl_egl_window_create(self->wl_surface(), sizeWithMargins.width(), sizeWithMargins.height());
}
if (!m_eglSurface) {
m_eglConfig = q_configFromGLFormat(m_eglIntegration->eglDisplay(), window()->format(), true);
const_cast<QWaylandEglWindow *>(this)->m_format = q_glFormatFromConfig(m_eglIntegration->eglDisplay(),m_eglConfig);
EGLNativeWindowType window = (EGLNativeWindowType) m_waylandEglWindow;
m_eglSurface = eglCreateWindowSurface(m_eglIntegration->eglDisplay(), m_eglConfig, window, 0);
}
return m_eglSurface;
}
GLuint QWaylandEglWindow::contentFBO() const
{
if (!decoration())
return 0;
if (m_resize || !m_contentFBO) {
QOpenGLFramebufferObject *old = m_contentFBO;
m_contentFBO = new QOpenGLFramebufferObject(geometry().width(), geometry().height(), QOpenGLFramebufferObject::CombinedDepthStencil);
delete old;
m_resize = false;
}
return m_contentFBO->handle();
}
GLuint QWaylandEglWindow::contentTexture() const
{
return m_contentFBO->texture();
}
void QWaylandEglWindow::bindContentFBO()
{
if (decoration()) {
contentFBO();
m_contentFBO->bind();
}
}
<|endoftext|> |
<commit_before>#include "dummy_video.h"
#include <halley/core/graphics/painter.h>
#include <halley/core/graphics/texture.h>
#include <halley/core/graphics/shader.h>
#include <halley/core/graphics/render_target/render_target_texture.h>
#include "dummy_system.h"
#include <chrono>
using namespace Halley;
DummyVideoAPI::DummyVideoAPI(SystemAPI&)
{}
void DummyVideoAPI::startRender()
{
}
void DummyVideoAPI::finishRender()
{
using namespace std::chrono_literals;
std::this_thread::sleep_for(10ms);
}
void DummyVideoAPI::setWindow(WindowDefinition&& windowDescriptor)
{
//window = system.createWindow(windowDescriptor);
window = std::make_shared<DummyWindow>(windowDescriptor);
}
const Window& DummyVideoAPI::getWindow() const
{
Expects(window);
return *window;
}
bool DummyVideoAPI::hasWindow() const
{
return static_cast<bool>(window);
}
std::unique_ptr<Texture> DummyVideoAPI::createTexture(Vector2i size)
{
return std::make_unique<DummyTexture>(size);
}
std::unique_ptr<Shader> DummyVideoAPI::createShader(const ShaderDefinition&)
{
return std::make_unique<DummyShader>();
}
std::unique_ptr<TextureRenderTarget> DummyVideoAPI::createTextureRenderTarget()
{
return std::make_unique<TextureRenderTarget>();
}
std::unique_ptr<ScreenRenderTarget> DummyVideoAPI::createScreenRenderTarget()
{
return std::make_unique<ScreenRenderTarget>(Rect4i({}, getWindow().getWindowRect().getSize()));
}
std::unique_ptr<MaterialConstantBuffer> DummyVideoAPI::createConstantBuffer()
{
return std::make_unique<DummyMaterialConstantBuffer>();
}
void DummyVideoAPI::init()
{
}
void DummyVideoAPI::deInit()
{
}
std::unique_ptr<Painter> DummyVideoAPI::makePainter(Resources& resources)
{
return std::make_unique<DummyPainter>(resources);
}
String DummyVideoAPI::getShaderLanguage()
{
return "glsl";
}
DummyTexture::DummyTexture(Vector2i size)
: Texture(size)
{
}
void DummyTexture::load(TextureDescriptor&&)
{
doneLoading();
}
int DummyShader::getUniformLocation(const String&, ShaderType)
{
return 0;
}
int DummyShader::getBlockLocation(const String&, ShaderType)
{
return 0;
}
void DummyMaterialConstantBuffer::update(const MaterialDataBlock&) {}
DummyPainter::DummyPainter(Resources& resources)
: Painter(resources)
{}
void DummyPainter::clear(Colour colour) {}
void DummyPainter::setMaterialPass(const Material&, int) {}
void DummyPainter::doStartRender() {}
void DummyPainter::doEndRender() {}
void DummyPainter::setVertices(const MaterialDefinition&, size_t, void*, size_t, unsigned short*, bool) {}
void DummyPainter::drawTriangles(size_t) {}
void DummyPainter::setViewPort(Rect4i) {}
void DummyPainter::setClip(Rect4i, bool) {}
void DummyPainter::setMaterialData(const Material&) {}
void DummyPainter::onUpdateProjection(Material&) {}
<commit_msg>Revert "DummyVideoAPI::finishRender now sleeps for 10 milliseconds to avoid headless clients using 100% CPU"<commit_after>#include "dummy_video.h"
#include <halley/core/graphics/painter.h>
#include <halley/core/graphics/texture.h>
#include <halley/core/graphics/shader.h>
#include <halley/core/graphics/render_target/render_target_texture.h>
#include "dummy_system.h"
using namespace Halley;
DummyVideoAPI::DummyVideoAPI(SystemAPI&)
{}
void DummyVideoAPI::startRender()
{
}
void DummyVideoAPI::finishRender()
{
}
void DummyVideoAPI::setWindow(WindowDefinition&& windowDescriptor)
{
//window = system.createWindow(windowDescriptor);
window = std::make_shared<DummyWindow>(windowDescriptor);
}
const Window& DummyVideoAPI::getWindow() const
{
Expects(window);
return *window;
}
bool DummyVideoAPI::hasWindow() const
{
return static_cast<bool>(window);
}
std::unique_ptr<Texture> DummyVideoAPI::createTexture(Vector2i size)
{
return std::make_unique<DummyTexture>(size);
}
std::unique_ptr<Shader> DummyVideoAPI::createShader(const ShaderDefinition&)
{
return std::make_unique<DummyShader>();
}
std::unique_ptr<TextureRenderTarget> DummyVideoAPI::createTextureRenderTarget()
{
return std::make_unique<TextureRenderTarget>();
}
std::unique_ptr<ScreenRenderTarget> DummyVideoAPI::createScreenRenderTarget()
{
return std::make_unique<ScreenRenderTarget>(Rect4i({}, getWindow().getWindowRect().getSize()));
}
std::unique_ptr<MaterialConstantBuffer> DummyVideoAPI::createConstantBuffer()
{
return std::make_unique<DummyMaterialConstantBuffer>();
}
void DummyVideoAPI::init()
{
}
void DummyVideoAPI::deInit()
{
}
std::unique_ptr<Painter> DummyVideoAPI::makePainter(Resources& resources)
{
return std::make_unique<DummyPainter>(resources);
}
String DummyVideoAPI::getShaderLanguage()
{
return "glsl";
}
DummyTexture::DummyTexture(Vector2i size)
: Texture(size)
{
}
void DummyTexture::load(TextureDescriptor&&)
{
doneLoading();
}
int DummyShader::getUniformLocation(const String&, ShaderType)
{
return 0;
}
int DummyShader::getBlockLocation(const String&, ShaderType)
{
return 0;
}
void DummyMaterialConstantBuffer::update(const MaterialDataBlock&) {}
DummyPainter::DummyPainter(Resources& resources)
: Painter(resources)
{}
void DummyPainter::clear(Colour colour) {}
void DummyPainter::setMaterialPass(const Material&, int) {}
void DummyPainter::doStartRender() {}
void DummyPainter::doEndRender() {}
void DummyPainter::setVertices(const MaterialDefinition&, size_t, void*, size_t, unsigned short*, bool) {}
void DummyPainter::drawTriangles(size_t) {}
void DummyPainter::setViewPort(Rect4i) {}
void DummyPainter::setClip(Rect4i, bool) {}
void DummyPainter::setMaterialData(const Material&) {}
void DummyPainter::onUpdateProjection(Material&) {}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <warn/push>
#include <warn/ignore/all>
#include <gtest/gtest.h>
#include <warn/pop>
#include <inviwo/core/common/inviwo.h>
#include <modules/base/algorithm/mesh/meshclipping.h>
#include <inviwo/core/datastructures/buffer/buffer.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>
#include <inviwo/core/datastructures/geometry/mesh.h>
#include <modules/base/algorithm/meshutils.h>
namespace inviwo {
TEST(MeshCutting, BarycentricInsidePolygon) {
auto testCorners = [](const std::vector<vec2>& poly) {
for (int i = 0; i < poly.size(); ++i) {
const auto res = meshutil::detail::barycentricInsidePolygon(poly[i], poly);
for (int j = 0; j < res.size(); ++j) {
if (i == j) {
EXPECT_FLOAT_EQ(res[j], 1.0f);
} else {
EXPECT_FLOAT_EQ(res[j], 0.0f);
}
}
}
};
auto testCenter = [](const std::vector<vec2>& poly) {
const auto res = meshutil::detail::barycentricInsidePolygon(vec2{0.5, 0.5}, poly);
for (int j = 0; j < res.size(); ++j) {
EXPECT_FLOAT_EQ(res[j], 1.0f / res.size());
}
};
std::vector<vec2> poly2{{0.0f, 0.0f}, {1.0f, 1.0f}};
testCorners(poly2);
testCenter(poly2);
std::vector<vec2> poly3{{0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f}};
testCorners(poly3);
std::vector<vec2> poly4{{0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f}, {1.0f, 0.0f}};
testCorners(poly4);
testCenter(poly4);
}
TEST(MeshCutting, SutherlandHodgman) {
const glm::u32vec3 triangle{0, 1, 2};
const Plane plane{vec3{0, 0, 0}, vec3{0, 1, 0}};
std::vector<vec3> positions{vec3{-1, -1, 0}, vec3{1, -1, 0}, vec3{0, 1, 0}};
std::vector<std::uint32_t> indicesVec{};
const meshutil::detail::InterpolateFunctor addInterpolatedVertex =
[&](const std::vector<uint32_t>& indices, const std::vector<float>& weights,
std::optional<vec3>, std::optional<vec3>) -> uint32_t {
const auto val = std::inner_product(
indices.begin(), indices.end(), weights.begin(), vec3{0}, std::plus<>{},
[&](uint32_t index, float weight) { return positions[index] * weight; });
positions.push_back(val);
return static_cast<uint32_t>(positions.size() - 1);
};
auto newEdge = meshutil::detail::sutherlandHodgman(triangle, plane, positions, indicesVec,
addInterpolatedVertex);
ASSERT_TRUE(newEdge);
EXPECT_EQ((*newEdge)[0], 3);
EXPECT_EQ((*newEdge)[1], 4);
ASSERT_EQ(indicesVec.size(), 3);
EXPECT_EQ(indicesVec[0], 3);
EXPECT_EQ(indicesVec[1], 2);
EXPECT_EQ(indicesVec[2], 4);
ASSERT_EQ(positions.size(), 5);
EXPECT_FLOAT_EQ(positions[3][0], 0.5f);
EXPECT_FLOAT_EQ(positions[3][1], 0.0f);
EXPECT_FLOAT_EQ(positions[4][0], -0.5f);
EXPECT_FLOAT_EQ(positions[4][1], 0.0f);
}
TEST(MeshCutting, GatherLoops) {
const std::vector<vec3> positions{vec3{-1, -1, 0}, vec3{1, -1, 0}, vec3{0, 1, 0}};
std::vector<glm::u32vec2> edges{{0, 1}, {1, 2}, {2, 0}};
const auto loops = meshutil::detail::gatherLoops(edges, positions, 0.0000001f);
ASSERT_EQ(loops.size(), 1);
ASSERT_EQ(loops[0].size(), 3);
}
TEST(MeshCutting, ClipMeshAgainstPlane) {
const auto mesh = meshutil::cube(mat4{1}, vec4{1, 1, 0, 1});
const Plane plane{vec3{0.5, 0.5, 0.5}, vec3{0, 1, 0}};
const auto clipped = meshutil::clipMeshAgainstPlane(*mesh, plane, true);
EXPECT_EQ(clipped->getIndexBuffers().front().second->getSize(), 66);
EXPECT_EQ(clipped->getBuffers()[0].second->getSize(), 41);
EXPECT_EQ(clipped->getBuffers()[1].second->getSize(), 41);
EXPECT_EQ(clipped->getBuffers()[2].second->getSize(), 41);
}
} // namespace inviwo
<commit_msg>Base: waring fix<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <warn/push>
#include <warn/ignore/all>
#include <gtest/gtest.h>
#include <warn/pop>
#include <inviwo/core/common/inviwo.h>
#include <modules/base/algorithm/mesh/meshclipping.h>
#include <inviwo/core/datastructures/buffer/buffer.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>
#include <inviwo/core/datastructures/geometry/mesh.h>
#include <modules/base/algorithm/meshutils.h>
namespace inviwo {
TEST(MeshCutting, BarycentricInsidePolygon) {
auto testCorners = [](const std::vector<vec2>& poly) {
for (size_t i = 0; i < poly.size(); ++i) {
const auto res = meshutil::detail::barycentricInsidePolygon(poly[i], poly);
for (size_t j = 0; j < res.size(); ++j) {
if (i == j) {
EXPECT_FLOAT_EQ(res[j], 1.0f);
} else {
EXPECT_FLOAT_EQ(res[j], 0.0f);
}
}
}
};
auto testCenter = [](const std::vector<vec2>& poly) {
const auto res = meshutil::detail::barycentricInsidePolygon(vec2{0.5, 0.5}, poly);
for (size_t j = 0; j < res.size(); ++j) {
EXPECT_FLOAT_EQ(res[j], 1.0f / res.size());
}
};
std::vector<vec2> poly2{{0.0f, 0.0f}, {1.0f, 1.0f}};
testCorners(poly2);
testCenter(poly2);
std::vector<vec2> poly3{{0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f}};
testCorners(poly3);
std::vector<vec2> poly4{{0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f}, {1.0f, 0.0f}};
testCorners(poly4);
testCenter(poly4);
}
TEST(MeshCutting, SutherlandHodgman) {
const glm::u32vec3 triangle{0, 1, 2};
const Plane plane{vec3{0, 0, 0}, vec3{0, 1, 0}};
std::vector<vec3> positions{vec3{-1, -1, 0}, vec3{1, -1, 0}, vec3{0, 1, 0}};
std::vector<std::uint32_t> indicesVec{};
const meshutil::detail::InterpolateFunctor addInterpolatedVertex =
[&](const std::vector<uint32_t>& indices, const std::vector<float>& weights,
std::optional<vec3>, std::optional<vec3>) -> uint32_t {
const auto val = std::inner_product(
indices.begin(), indices.end(), weights.begin(), vec3{0}, std::plus<>{},
[&](uint32_t index, float weight) { return positions[index] * weight; });
positions.push_back(val);
return static_cast<uint32_t>(positions.size() - 1);
};
auto newEdge = meshutil::detail::sutherlandHodgman(triangle, plane, positions, indicesVec,
addInterpolatedVertex);
ASSERT_TRUE(newEdge);
EXPECT_EQ((*newEdge)[0], 3);
EXPECT_EQ((*newEdge)[1], 4);
ASSERT_EQ(indicesVec.size(), 3);
EXPECT_EQ(indicesVec[0], 3);
EXPECT_EQ(indicesVec[1], 2);
EXPECT_EQ(indicesVec[2], 4);
ASSERT_EQ(positions.size(), 5);
EXPECT_FLOAT_EQ(positions[3][0], 0.5f);
EXPECT_FLOAT_EQ(positions[3][1], 0.0f);
EXPECT_FLOAT_EQ(positions[4][0], -0.5f);
EXPECT_FLOAT_EQ(positions[4][1], 0.0f);
}
TEST(MeshCutting, GatherLoops) {
const std::vector<vec3> positions{vec3{-1, -1, 0}, vec3{1, -1, 0}, vec3{0, 1, 0}};
std::vector<glm::u32vec2> edges{{0, 1}, {1, 2}, {2, 0}};
const auto loops = meshutil::detail::gatherLoops(edges, positions, 0.0000001f);
ASSERT_EQ(loops.size(), 1);
ASSERT_EQ(loops[0].size(), 3);
}
TEST(MeshCutting, ClipMeshAgainstPlane) {
const auto mesh = meshutil::cube(mat4{1}, vec4{1, 1, 0, 1});
const Plane plane{vec3{0.5, 0.5, 0.5}, vec3{0, 1, 0}};
const auto clipped = meshutil::clipMeshAgainstPlane(*mesh, plane, true);
EXPECT_EQ(clipped->getIndexBuffers().front().second->getSize(), 66);
EXPECT_EQ(clipped->getBuffers()[0].second->getSize(), 41);
EXPECT_EQ(clipped->getBuffers()[1].second->getSize(), 41);
EXPECT_EQ(clipped->getBuffers()[2].second->getSize(), 41);
}
} // namespace inviwo
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkOnce.h"
#include "SkOpts.h"
#define SK_OPTS_NS sk_default
#include "SkBlitMask_opts.h"
#include "SkBlitRow_opts.h"
#include "SkBlurImageFilter_opts.h"
#include "SkColorCubeFilter_opts.h"
#include "SkFloatingPoint_opts.h"
#include "SkMatrix_opts.h"
#include "SkMorphologyImageFilter_opts.h"
#include "SkTextureCompressor_opts.h"
#include "SkUtils_opts.h"
#include "SkXfermode_opts.h"
#if defined(SK_CPU_X86)
#if defined(SK_BUILD_FOR_WIN32)
#include <intrin.h>
static void cpuid (uint32_t abcd[4]) { __cpuid ((int*)abcd, 1); }
static void cpuid7(uint32_t abcd[4]) { __cpuidex((int*)abcd, 7, 0); }
static uint64_t xgetbv(uint32_t xcr) { return _xgetbv(xcr); }
#else
#include <cpuid.h>
#if !defined(__cpuid_count) // Old Mac Clang doesn't have this defined.
#define __cpuid_count(eax, ecx, a, b, c, d) \
__asm__("cpuid" : "=a"(a), "=b"(b), "=c"(c), "=d"(d) : "0"(eax), "2"(ecx))
#endif
static void cpuid (uint32_t abcd[4]) { __get_cpuid(1, abcd+0, abcd+1, abcd+2, abcd+3); }
static void cpuid7(uint32_t abcd[4]) {
__cpuid_count(7, 0, abcd[0], abcd[1], abcd[2], abcd[3]);
}
static uint64_t xgetbv(uint32_t xcr) {
uint32_t eax, edx;
__asm__ __volatile__ ( "xgetbv" : "=a"(eax), "=d"(edx) : "c"(xcr));
return (uint64_t)(edx) << 32 | eax;
}
#endif
#elif !defined(SK_ARM_HAS_NEON) && \
defined(SK_CPU_ARM32) && \
defined(SK_BUILD_FOR_ANDROID) && \
!defined(SK_BUILD_FOR_ANDROID_FRAMEWORK)
#include <cpu-features.h>
#endif
namespace SkOpts {
// Define default function pointer values here...
// If our global compile options are set high enough, these defaults might even be
// CPU-specialized, e.g. a typical x86-64 machine might start with SSE2 defaults.
// They'll still get a chance to be replaced with even better ones, e.g. using SSE4.1.
decltype(rsqrt) rsqrt = sk_default::rsqrt;
decltype(memset16) memset16 = sk_default::memset16;
decltype(memset32) memset32 = sk_default::memset32;
decltype(create_xfermode) create_xfermode = sk_default::create_xfermode;
decltype(color_cube_filter_span) color_cube_filter_span = sk_default::color_cube_filter_span;
decltype(box_blur_xx) box_blur_xx = sk_default::box_blur_xx;
decltype(box_blur_xy) box_blur_xy = sk_default::box_blur_xy;
decltype(box_blur_yx) box_blur_yx = sk_default::box_blur_yx;
decltype(dilate_x) dilate_x = sk_default::dilate_x;
decltype(dilate_y) dilate_y = sk_default::dilate_y;
decltype( erode_x) erode_x = sk_default::erode_x;
decltype( erode_y) erode_y = sk_default::erode_y;
decltype(texture_compressor) texture_compressor = sk_default::texture_compressor;
decltype(fill_block_dimensions) fill_block_dimensions = sk_default::fill_block_dimensions;
decltype(blit_mask_d32_a8) blit_mask_d32_a8 = sk_default::blit_mask_d32_a8;
decltype(blit_row_color32) blit_row_color32 = sk_default::blit_row_color32;
decltype(matrix_translate) matrix_translate = sk_default::matrix_translate;
decltype(matrix_scale_translate) matrix_scale_translate = sk_default::matrix_scale_translate;
decltype(matrix_affine) matrix_affine = sk_default::matrix_affine;
// Each Init_foo() is defined in src/opts/SkOpts_foo.cpp.
void Init_ssse3();
void Init_sse41();
void Init_neon();
void Init_avx() { SkDEBUGCODE( SkDebugf("avx detected\n"); ) }
void Init_avx2() { SkDEBUGCODE( SkDebugf("avx2 detected\n"); ) }
//TODO: _dsp2, _armv7, _armv8, _x86, _x86_64, _sse42, ... ?
static void init() {
// TODO: Chrome's not linking _sse* opts on iOS simulator builds. Bug or feature?
#if defined(SK_CPU_X86) && !defined(SK_BUILD_FOR_IOS)
uint32_t abcd[] = {0,0,0,0};
cpuid(abcd);
if (abcd[2] & (1<< 9)) { Init_ssse3(); }
if (abcd[2] & (1<<19)) { Init_sse41(); }
// AVX detection's kind of a pain. This is cribbed from Chromium.
if ( ( abcd[2] & (7<<26)) == (7<<26) && // Check bits 26-28 of ecx are all set,
(xgetbv(0) & 6 ) == 6 ){ // and check the OS supports XSAVE.
Init_avx();
// AVX2 additionally needs bit 5 set on ebx after calling cpuid(7).
uint32_t abcd7[] = {0,0,0,0};
cpuid7(abcd7);
if (abcd7[1] & (1<<5)) { Init_avx2(); }
}
#elif !defined(SK_ARM_HAS_NEON) && \
defined(SK_CPU_ARM32) && \
defined(SK_BUILD_FOR_ANDROID) && \
!defined(SK_BUILD_FOR_ANDROID_FRAMEWORK)
if (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) { Init_neon(); }
#endif
}
SK_DECLARE_STATIC_ONCE(gInitOnce);
void Init() { SkOnce(&gInitOnce, init); }
#if SK_ALLOW_STATIC_GLOBAL_INITIALIZERS
static struct AutoInit {
AutoInit() { Init(); }
} gAutoInit;
#endif
}
<commit_msg>sse 4.2 detection<commit_after>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkOnce.h"
#include "SkOpts.h"
#define SK_OPTS_NS sk_default
#include "SkBlitMask_opts.h"
#include "SkBlitRow_opts.h"
#include "SkBlurImageFilter_opts.h"
#include "SkColorCubeFilter_opts.h"
#include "SkFloatingPoint_opts.h"
#include "SkMatrix_opts.h"
#include "SkMorphologyImageFilter_opts.h"
#include "SkTextureCompressor_opts.h"
#include "SkUtils_opts.h"
#include "SkXfermode_opts.h"
#if defined(SK_CPU_X86)
#if defined(SK_BUILD_FOR_WIN32)
#include <intrin.h>
static void cpuid (uint32_t abcd[4]) { __cpuid ((int*)abcd, 1); }
static void cpuid7(uint32_t abcd[4]) { __cpuidex((int*)abcd, 7, 0); }
static uint64_t xgetbv(uint32_t xcr) { return _xgetbv(xcr); }
#else
#include <cpuid.h>
#if !defined(__cpuid_count) // Old Mac Clang doesn't have this defined.
#define __cpuid_count(eax, ecx, a, b, c, d) \
__asm__("cpuid" : "=a"(a), "=b"(b), "=c"(c), "=d"(d) : "0"(eax), "2"(ecx))
#endif
static void cpuid (uint32_t abcd[4]) { __get_cpuid(1, abcd+0, abcd+1, abcd+2, abcd+3); }
static void cpuid7(uint32_t abcd[4]) {
__cpuid_count(7, 0, abcd[0], abcd[1], abcd[2], abcd[3]);
}
static uint64_t xgetbv(uint32_t xcr) {
uint32_t eax, edx;
__asm__ __volatile__ ( "xgetbv" : "=a"(eax), "=d"(edx) : "c"(xcr));
return (uint64_t)(edx) << 32 | eax;
}
#endif
#elif !defined(SK_ARM_HAS_NEON) && \
defined(SK_CPU_ARM32) && \
defined(SK_BUILD_FOR_ANDROID) && \
!defined(SK_BUILD_FOR_ANDROID_FRAMEWORK)
#include <cpu-features.h>
#endif
namespace SkOpts {
// Define default function pointer values here...
// If our global compile options are set high enough, these defaults might even be
// CPU-specialized, e.g. a typical x86-64 machine might start with SSE2 defaults.
// They'll still get a chance to be replaced with even better ones, e.g. using SSE4.1.
decltype(rsqrt) rsqrt = sk_default::rsqrt;
decltype(memset16) memset16 = sk_default::memset16;
decltype(memset32) memset32 = sk_default::memset32;
decltype(create_xfermode) create_xfermode = sk_default::create_xfermode;
decltype(color_cube_filter_span) color_cube_filter_span = sk_default::color_cube_filter_span;
decltype(box_blur_xx) box_blur_xx = sk_default::box_blur_xx;
decltype(box_blur_xy) box_blur_xy = sk_default::box_blur_xy;
decltype(box_blur_yx) box_blur_yx = sk_default::box_blur_yx;
decltype(dilate_x) dilate_x = sk_default::dilate_x;
decltype(dilate_y) dilate_y = sk_default::dilate_y;
decltype( erode_x) erode_x = sk_default::erode_x;
decltype( erode_y) erode_y = sk_default::erode_y;
decltype(texture_compressor) texture_compressor = sk_default::texture_compressor;
decltype(fill_block_dimensions) fill_block_dimensions = sk_default::fill_block_dimensions;
decltype(blit_mask_d32_a8) blit_mask_d32_a8 = sk_default::blit_mask_d32_a8;
decltype(blit_row_color32) blit_row_color32 = sk_default::blit_row_color32;
decltype(matrix_translate) matrix_translate = sk_default::matrix_translate;
decltype(matrix_scale_translate) matrix_scale_translate = sk_default::matrix_scale_translate;
decltype(matrix_affine) matrix_affine = sk_default::matrix_affine;
// Each Init_foo() is defined in src/opts/SkOpts_foo.cpp.
void Init_ssse3();
void Init_sse41();
void Init_sse42() { SkDEBUGCODE( SkDebugf("sse 4.2 detected\n"); ) }
void Init_avx() { SkDEBUGCODE( SkDebugf("avx detected\n"); ) }
void Init_avx2() { SkDEBUGCODE( SkDebugf("avx2 detected\n"); ) }
void Init_neon();
//TODO: _dsp2, _armv7, _armv8, _x86, _x86_64, _sse42, ... ?
static void init() {
// TODO: Chrome's not linking _sse* opts on iOS simulator builds. Bug or feature?
#if defined(SK_CPU_X86) && !defined(SK_BUILD_FOR_IOS)
uint32_t abcd[] = {0,0,0,0};
cpuid(abcd);
if (abcd[2] & (1<< 9)) { Init_ssse3(); }
if (abcd[2] & (1<<19)) { Init_sse41(); }
if (abcd[2] & (1<<20)) { Init_sse42(); }
// AVX detection's kind of a pain. This is cribbed from Chromium.
if ( ( abcd[2] & (7<<26)) == (7<<26) && // Check bits 26-28 of ecx are all set,
(xgetbv(0) & 6 ) == 6 ){ // and check the OS supports XSAVE.
Init_avx();
// AVX2 additionally needs bit 5 set on ebx after calling cpuid(7).
uint32_t abcd7[] = {0,0,0,0};
cpuid7(abcd7);
if (abcd7[1] & (1<<5)) { Init_avx2(); }
}
#elif !defined(SK_ARM_HAS_NEON) && \
defined(SK_CPU_ARM32) && \
defined(SK_BUILD_FOR_ANDROID) && \
!defined(SK_BUILD_FOR_ANDROID_FRAMEWORK)
if (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) { Init_neon(); }
#endif
}
SK_DECLARE_STATIC_ONCE(gInitOnce);
void Init() { SkOnce(&gInitOnce, init); }
#if SK_ALLOW_STATIC_GLOBAL_INITIALIZERS
static struct AutoInit {
AutoInit() { Init(); }
} gAutoInit;
#endif
}
<|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2010 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#ifndef _FORMATTER_HPP_
#define _FORMATTER_HPP_
#include <iostream>
namespace Formatter {
/*
* See also http://bytes.com/topic/c/answers/63822-design-question-little-c-header-colorizing-text-linux-comments-ideas
*/
class Attribute {
public:
virtual ~Attribute() {}
virtual std::ostream& apply(std::ostream& os) const { return os; }
};
enum Color {
RED,
GREEN,
BLUE,
};
class Formatter {
public:
virtual ~Formatter() {}
virtual Attribute *normal(void) const { return new Attribute; }
virtual Attribute *bold(void) const { return new Attribute; }
virtual Attribute *italic(void) const { return new Attribute; }
virtual Attribute *color(Color color) const { return new Attribute; }
};
class AnsiAttribute : public Attribute {
protected:
const char *escape;
public:
AnsiAttribute(const char *_escape) : escape(_escape) {}
std::ostream & apply(std::ostream& os) const {
return os << "\33[" << escape;
}
};
/**
* Formatter for plain-text files which outputs ANSI escape codes. See
* http://en.wikipedia.org/wiki/ANSI_escape_code for more information
* concerning ANSI escape codes.
*/
class AnsiFormatter : public Formatter {
protected:
public:
virtual Attribute *normal(void) const { return new AnsiAttribute("0m"); }
virtual Attribute *bold(void) const { return new AnsiAttribute("1m"); }
virtual Attribute *italic(void) const { return new AnsiAttribute("3m"); }
virtual Attribute *color(Color c) const {
static const char *color_escapes[] = {
"31m", /* red */
"32m", /* green */
"34m", /* blue */
};
return new AnsiAttribute(color_escapes[c]);
}
};
inline std::ostream& operator<<(std::ostream& os, const Attribute *attr) {
return attr->apply(os);
}
#ifdef WIN32
#include <windows.h>
class WindowsAttribute : public Attribute {
protected:
WORD wAttributes;
public:
WindowsAttribute(WORD _wAttributes) : wAttributes(_wAttributes) {}
std::ostream & apply(std::ostream& os) const {
DWORD nStdHandleOutput;
if (os == std::cout) {
nStdHandleOutput = STD_OUTPUT_HANDLE;
} else if (os == std::cerr) {
nStdHandleOutput = STD_ERROR_HANDLE;
} else {
return os;
}
HANDLE hConsoleOutput = GetStdHandle(nStdHandleOutput);
SetConsoleTextAttribute(hConsoleOutput, wAttributes);
}
};
/**
* Formatter for the Windows Console.
*/
class WindowsFormatter : public Formatter {
protected:
public:
virtual Attribute *normal(void) const { return new WindowsAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); }
virtual Attribute *bold(void) const { return new WindowsAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY); }
virtual Attribute *italic(void) const { return new WindowsAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); }
virtual Attribute *color(Color c) const {
static const WORD color_escapes[] = {
FOREGROUND_RED | FOREGROUND_INTENSITY,
FOREGROUND_GREEN | FOREGROUND_INTENSITY,
FOREGROUND_BLUE | FOREGROUND_INTENSITY,
};
return new WindowsAttribute(color_escapes[c]);
}
};
#endif
inline Formatter *defaultFormatter(void) {
#ifdef WIN32
return new WindowsFormatter;
#else
return new AnsiFormatter;
#endif
}
} /* namespace Formatter */
#endif /* _FORMATTER_HPP_ */
<commit_msg>Fix windows formatting.<commit_after>/**************************************************************************
*
* Copyright 2010 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#ifndef _FORMATTER_HPP_
#define _FORMATTER_HPP_
#include <iostream>
namespace Formatter {
/*
* See also http://bytes.com/topic/c/answers/63822-design-question-little-c-header-colorizing-text-linux-comments-ideas
*/
class Attribute {
public:
virtual ~Attribute() {}
virtual void apply(std::ostream& os) const {}
};
enum Color {
RED,
GREEN,
BLUE,
};
class Formatter {
public:
virtual ~Formatter() {}
virtual Attribute *normal(void) const { return new Attribute; }
virtual Attribute *bold(void) const { return new Attribute; }
virtual Attribute *italic(void) const { return new Attribute; }
virtual Attribute *color(Color color) const { return new Attribute; }
};
class AnsiAttribute : public Attribute {
protected:
const char *escape;
public:
AnsiAttribute(const char *_escape) : escape(_escape) {}
void apply(std::ostream& os) const {
os << "\33[" << escape;
}
};
/**
* Formatter for plain-text files which outputs ANSI escape codes. See
* http://en.wikipedia.org/wiki/ANSI_escape_code for more information
* concerning ANSI escape codes.
*/
class AnsiFormatter : public Formatter {
protected:
public:
virtual Attribute *normal(void) const { return new AnsiAttribute("0m"); }
virtual Attribute *bold(void) const { return new AnsiAttribute("1m"); }
virtual Attribute *italic(void) const { return new AnsiAttribute("3m"); }
virtual Attribute *color(Color c) const {
static const char *color_escapes[] = {
"31m", /* red */
"32m", /* green */
"34m", /* blue */
};
return new AnsiAttribute(color_escapes[c]);
}
};
inline std::ostream& operator<<(std::ostream& os, const Attribute *attr) {
attr->apply(os);
return os;
}
#ifdef WIN32
#include <windows.h>
class WindowsAttribute : public Attribute {
protected:
WORD wAttributes;
public:
WindowsAttribute(WORD _wAttributes) : wAttributes(_wAttributes) {}
void apply(std::ostream& os) const {
DWORD nStdHandleOutput;
if (os == std::cout) {
nStdHandleOutput = STD_OUTPUT_HANDLE;
} else if (os == std::cerr) {
nStdHandleOutput = STD_ERROR_HANDLE;
} else {
return;
}
HANDLE hConsoleOutput = GetStdHandle(nStdHandleOutput);
if (hConsoleOutput == INVALID_HANDLE_VALUE) {
return;
}
SetConsoleTextAttribute(hConsoleOutput, wAttributes);
}
};
/**
* Formatter for the Windows Console.
*/
class WindowsFormatter : public Formatter {
protected:
public:
virtual Attribute *normal(void) const { return new WindowsAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); }
virtual Attribute *bold(void) const { return new WindowsAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY); }
virtual Attribute *italic(void) const { return new WindowsAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); }
virtual Attribute *color(Color c) const {
static const WORD color_escapes[] = {
FOREGROUND_RED | FOREGROUND_INTENSITY,
FOREGROUND_GREEN | FOREGROUND_INTENSITY,
FOREGROUND_BLUE | FOREGROUND_INTENSITY,
};
return new WindowsAttribute(color_escapes[c]);
}
};
#endif
inline Formatter *defaultFormatter(void) {
#ifdef WIN32
return new WindowsFormatter;
#else
return new AnsiFormatter;
#endif
}
} /* namespace Formatter */
#endif /* _FORMATTER_HPP_ */
<|endoftext|> |
<commit_before>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "berryHelpSearchView.h"
#include "berryHelpPluginActivator.h"
#include "berryQHelpEngineWrapper.h"
#include "berryHelpEditorInput.h"
#include "berryHelpEditor.h"
#include <QLayout>
#include <QMenu>
#include <QEvent>
#include <QMouseEvent>
#include <QMimeData>
#include <QTextBrowser>
#include <QClipboard>
#include <QHelpSearchQueryWidget>
#include <QHelpSearchResultWidget>
#include <QApplication>
namespace berry {
HelpSearchView::HelpSearchView()
: m_ZoomCount(0)
, m_Parent(nullptr)
, m_SearchEngine(HelpPluginActivator::getInstance()->getQHelpEngine().searchEngine())
, m_ResultWidget(nullptr)
, m_QueryWidget(nullptr)
{
}
HelpSearchView::~HelpSearchView()
{
// prevent deletion of the widget
m_ResultWidget->setParent(nullptr);
}
void HelpSearchView::CreateQtPartControl(QWidget* parent)
{
if (m_ResultWidget == nullptr)
{
m_Parent = parent;
auto vLayout = new QVBoxLayout(parent);
// This will be lead to strange behavior when using multiple instances of this view
// because the QHelpSearchResultWidget instance is shared. The new view will
// reparent the widget.
m_ResultWidget = m_SearchEngine->resultWidget();
m_QueryWidget = new QHelpSearchQueryWidget();
vLayout->addWidget(m_QueryWidget);
vLayout->addWidget(m_ResultWidget);
connect(m_QueryWidget, SIGNAL(search()), this, SLOT(search()));
connect(m_ResultWidget, SIGNAL(requestShowLink(QUrl)), this,
SLOT(requestShowLink(QUrl)));
connect(m_SearchEngine, SIGNAL(searchingStarted()), this,
SLOT(searchingStarted()));
connect(m_SearchEngine, SIGNAL(searchingFinished(int)), this,
SLOT(searchingFinished(int)));
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser) // Will be null if QtHelp was configured not to use CLucene.
{
browser->viewport()->installEventFilter(this);
browser->setContextMenuPolicy(Qt::CustomContextMenu);
connect(browser, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(showContextMenu(QPoint)));
}
}
}
void HelpSearchView::SetFocus()
{
if (!(m_ResultWidget->hasFocus()))
{
m_QueryWidget->setFocus();
}
}
void HelpSearchView::zoomIn()
{
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser && m_ZoomCount != 10)
{
m_ZoomCount++;
browser->zoomIn();
}
}
void HelpSearchView::zoomOut()
{
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser && m_ZoomCount != -5)
{
m_ZoomCount--;
browser->zoomOut();
}
}
void HelpSearchView::resetZoom()
{
if (m_ZoomCount == 0)
return;
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser)
{
browser->zoomOut(m_ZoomCount);
m_ZoomCount = 0;
}
}
void HelpSearchView::search() const
{
QList<QHelpSearchQuery> query = m_QueryWidget->query();
m_SearchEngine->search(query);
}
void HelpSearchView::searchingStarted()
{
m_Parent->setCursor(QCursor(Qt::WaitCursor));
}
void HelpSearchView::searchingFinished(int hits)
{
Q_UNUSED(hits)
m_Parent->unsetCursor();
//qApp->restoreOverrideCursor();
}
void HelpSearchView::requestShowLink(const QUrl &link)
{
HelpPluginActivator::linkActivated(this->GetSite()->GetPage(), link);
}
bool HelpSearchView::eventFilter(QObject* o, QEvent *e)
{
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser && o == browser->viewport()
&& e->type() == QEvent::MouseButtonRelease)
{
QMouseEvent* me = static_cast<QMouseEvent*>(e);
QUrl link = m_ResultWidget->linkAt(me->pos());
if (!link.isEmpty() || link.isValid())
{
bool controlPressed = me->modifiers() & Qt::ControlModifier;
if((me->button() == Qt::LeftButton && controlPressed)
|| (me->button() == Qt::MidButton))
{
IEditorInput::Pointer input(new HelpEditorInput(link));
this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);
}
}
}
return QObject::eventFilter(o,e);
}
void HelpSearchView::showContextMenu(const QPoint& point)
{
QMenu menu;
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (!browser)
return;
// QPoint point = browser->mapFromGlobal(pos);
// if (!browser->rect().contains(point, true))
// return;
QUrl link = browser->anchorAt(point);
QKeySequence keySeq(QKeySequence::Copy);
QAction *copyAction = menu.addAction(tr("&Copy") + QLatin1String("\t") +
keySeq.toString(QKeySequence::NativeText));
copyAction->setEnabled(QTextCursor(browser->textCursor()).hasSelection());
QAction *copyAnchorAction = menu.addAction(tr("Copy &Link Location"));
copyAnchorAction->setEnabled(!link.isEmpty() && link.isValid());
keySeq = QKeySequence(Qt::CTRL);
QAction *newTabAction = menu.addAction(tr("Open Link in New Tab") +
QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText) +
QLatin1String("LMB"));
newTabAction->setEnabled(!link.isEmpty() && link.isValid());
menu.addSeparator();
keySeq = QKeySequence::SelectAll;
QAction *selectAllAction = menu.addAction(tr("Select All") +
QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText));
QAction *usedAction = menu.exec(browser->mapToGlobal(point));
if (usedAction == copyAction)
{
QTextCursor cursor = browser->textCursor();
if (!cursor.isNull() && cursor.hasSelection())
{
QString selectedText = cursor.selectedText();
auto data = new QMimeData();
data->setText(selectedText);
QApplication::clipboard()->setMimeData(data);
}
}
else if (usedAction == copyAnchorAction)
{
QApplication::clipboard()->setText(link.toString());
}
else if (usedAction == newTabAction)
{
IEditorInput::Pointer input(new HelpEditorInput(link));
this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);
}
else if (usedAction == selectAllAction)
{
browser->selectAll();
}
}
}
<commit_msg>Make background of help search results browser white<commit_after>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "berryHelpSearchView.h"
#include "berryHelpPluginActivator.h"
#include "berryQHelpEngineWrapper.h"
#include "berryHelpEditorInput.h"
#include "berryHelpEditor.h"
#include <QLayout>
#include <QMenu>
#include <QEvent>
#include <QMouseEvent>
#include <QMimeData>
#include <QTextBrowser>
#include <QClipboard>
#include <QHelpSearchQueryWidget>
#include <QHelpSearchResultWidget>
#include <QApplication>
namespace berry {
HelpSearchView::HelpSearchView()
: m_ZoomCount(0)
, m_Parent(nullptr)
, m_SearchEngine(HelpPluginActivator::getInstance()->getQHelpEngine().searchEngine())
, m_ResultWidget(nullptr)
, m_QueryWidget(nullptr)
{
}
HelpSearchView::~HelpSearchView()
{
// prevent deletion of the widget
m_ResultWidget->setParent(nullptr);
}
void HelpSearchView::CreateQtPartControl(QWidget* parent)
{
if (m_ResultWidget == nullptr)
{
m_Parent = parent;
auto vLayout = new QVBoxLayout(parent);
// This will be lead to strange behavior when using multiple instances of this view
// because the QHelpSearchResultWidget instance is shared. The new view will
// reparent the widget.
m_ResultWidget = m_SearchEngine->resultWidget();
m_QueryWidget = new QHelpSearchQueryWidget();
vLayout->addWidget(m_QueryWidget);
vLayout->addWidget(m_ResultWidget);
connect(m_QueryWidget, SIGNAL(search()), this, SLOT(search()));
connect(m_ResultWidget, SIGNAL(requestShowLink(QUrl)), this,
SLOT(requestShowLink(QUrl)));
connect(m_SearchEngine, SIGNAL(searchingStarted()), this,
SLOT(searchingStarted()));
connect(m_SearchEngine, SIGNAL(searchingFinished(int)), this,
SLOT(searchingFinished(int)));
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser) // Will be null if QtHelp was configured not to use CLucene.
{
browser->document()->setDefaultStyleSheet(QStringLiteral("body { background-color: white; }"));
browser->viewport()->installEventFilter(this);
browser->setContextMenuPolicy(Qt::CustomContextMenu);
connect(browser, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(showContextMenu(QPoint)));
}
}
}
void HelpSearchView::SetFocus()
{
if (!(m_ResultWidget->hasFocus()))
{
m_QueryWidget->setFocus();
}
}
void HelpSearchView::zoomIn()
{
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser && m_ZoomCount != 10)
{
m_ZoomCount++;
browser->zoomIn();
}
}
void HelpSearchView::zoomOut()
{
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser && m_ZoomCount != -5)
{
m_ZoomCount--;
browser->zoomOut();
}
}
void HelpSearchView::resetZoom()
{
if (m_ZoomCount == 0)
return;
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser)
{
browser->zoomOut(m_ZoomCount);
m_ZoomCount = 0;
}
}
void HelpSearchView::search() const
{
QList<QHelpSearchQuery> query = m_QueryWidget->query();
m_SearchEngine->search(query);
}
void HelpSearchView::searchingStarted()
{
m_Parent->setCursor(QCursor(Qt::WaitCursor));
}
void HelpSearchView::searchingFinished(int hits)
{
Q_UNUSED(hits)
m_Parent->unsetCursor();
//qApp->restoreOverrideCursor();
}
void HelpSearchView::requestShowLink(const QUrl &link)
{
HelpPluginActivator::linkActivated(this->GetSite()->GetPage(), link);
}
bool HelpSearchView::eventFilter(QObject* o, QEvent *e)
{
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser && o == browser->viewport()
&& e->type() == QEvent::MouseButtonRelease)
{
QMouseEvent* me = static_cast<QMouseEvent*>(e);
QUrl link = m_ResultWidget->linkAt(me->pos());
if (!link.isEmpty() || link.isValid())
{
bool controlPressed = me->modifiers() & Qt::ControlModifier;
if((me->button() == Qt::LeftButton && controlPressed)
|| (me->button() == Qt::MidButton))
{
IEditorInput::Pointer input(new HelpEditorInput(link));
this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);
}
}
}
return QObject::eventFilter(o,e);
}
void HelpSearchView::showContextMenu(const QPoint& point)
{
QMenu menu;
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (!browser)
return;
// QPoint point = browser->mapFromGlobal(pos);
// if (!browser->rect().contains(point, true))
// return;
QUrl link = browser->anchorAt(point);
QKeySequence keySeq(QKeySequence::Copy);
QAction *copyAction = menu.addAction(tr("&Copy") + QLatin1String("\t") +
keySeq.toString(QKeySequence::NativeText));
copyAction->setEnabled(QTextCursor(browser->textCursor()).hasSelection());
QAction *copyAnchorAction = menu.addAction(tr("Copy &Link Location"));
copyAnchorAction->setEnabled(!link.isEmpty() && link.isValid());
keySeq = QKeySequence(Qt::CTRL);
QAction *newTabAction = menu.addAction(tr("Open Link in New Tab") +
QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText) +
QLatin1String("LMB"));
newTabAction->setEnabled(!link.isEmpty() && link.isValid());
menu.addSeparator();
keySeq = QKeySequence::SelectAll;
QAction *selectAllAction = menu.addAction(tr("Select All") +
QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText));
QAction *usedAction = menu.exec(browser->mapToGlobal(point));
if (usedAction == copyAction)
{
QTextCursor cursor = browser->textCursor();
if (!cursor.isNull() && cursor.hasSelection())
{
QString selectedText = cursor.selectedText();
auto data = new QMimeData();
data->setText(selectedText);
QApplication::clipboard()->setMimeData(data);
}
}
else if (usedAction == copyAnchorAction)
{
QApplication::clipboard()->setText(link.toString());
}
else if (usedAction == newTabAction)
{
IEditorInput::Pointer input(new HelpEditorInput(link));
this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);
}
else if (usedAction == selectAllAction)
{
browser->selectAll();
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/program_options.hpp>
#include "common.h"
#include "scope_guard.h"
#include "connection.h"
#include "context.h"
#include "agenda.h"
#include "sync.h"
#include <sys/ioctl.h>
#include <boost/bind.hpp>
using namespace es3;
#include <curl/curl.h>
static int term_width = 80;
namespace po = boost::program_options;
typedef std::vector<std::string> stringvec;
int do_rsync(context_ptr context, const stringvec& params,
agenda_ptr ag, bool help)
{
bool delete_missing=false;
po::options_description opts("Sync options", term_width);
opts.add_options()
("delete-missing,D", po::value<bool>(
&delete_missing)->default_value(false),
"Delete missing files from the sync destination")
;
if (help)
{
std::cout << "Sync syntax: es3 sync [OPTIONS] <SOURCE> <DESTINATION>\n"
<< "where <SOURCE> and <DESTINATION> are either:\n"
<< "\t - Local directory\n"
<< "\t - Amazon S3 storage (in s3://<bucket>/path/ format)"
<< std::endl << std::endl;
std::cout << opts;
return 0;
}
po::positional_options_description pos;
pos.add("<SOURCE>", 1);
pos.add("<DESTINATION>", 1);
std::string src, tgt;
opts.add_options()
("<SOURCE>", po::value<std::string>(&src)->required())
("<DESTINATION>", po::value<std::string>(&tgt)->required())
;
try
{
po::variables_map vm;
po::store(po::command_line_parser(params)
.options(opts).positional(pos).run(), vm);
po::notify(vm);
} catch(const boost::program_options::error &err)
{
std::cerr << "Failed to parse configuration options. Error: "
<< err.what() << "\n"
<< "Use --help for help\n";
return 2;
}
s3_path path;
std::string local;
bool upload = false;
if (src.find("s3://")==0)
{
path = parse_path(src);
local = tgt;
upload = false;
} else if (tgt.find("s3://")==0)
{
path = parse_path(tgt);
local = src;
upload = true;
} else
{
std::cerr << "Error: one of <SOURCE> or <DESTINATION> must be an S3 URL.\n";
return 2;
}
if (local.find("s3://")==0)
{
std::cerr << "Error: one of <SOURCE> or <DESTINATION> must be a local path \n";
return 2;
}
//TODO: de-uglify
context->bucket_=path.bucket_;
context->zone_="s3";
s3_connection conn(context);
std::string region=conn.find_region();
if (!region.empty())
context->zone_="s3-"+region;
synchronizer sync(ag, context, path.path_, local, upload, delete_missing);
sync.create_schedule();
return ag->run();
}
std::vector<po::option> subcommands_parser(stringvec& args,
const stringvec& subcommands)
{
std::vector<po::option> result;
if (args.empty())
return result;
stringvec::const_iterator i(args.begin());
stringvec::const_iterator cmd_idx=std::find(subcommands.begin(),
subcommands.end(),*i);
if (cmd_idx!=subcommands.end())
{
po::option opt;
opt.string_key = "subcommand";
opt.value.push_back(*i);
opt.original_tokens.push_back(*i);
result.push_back(opt);
for (++i; i != args.end(); ++i)
{
po::option opt;
opt.string_key = "subcommand_params";
opt.value.push_back(*i);
opt.original_tokens.push_back(*i);
result.push_back(opt);
}
args.clear();
}
return result;
}
int main(int argc, char **argv)
{
int verbosity = 0;
bool quiet=false;
//Get terminal size (to pretty-print help text)
struct winsize w={0};
ioctl(0, TIOCGWINSZ, &w);
term_width=(w.ws_col==0)? 80 : w.ws_col;
context_ptr cd(new conn_context());
po::options_description generic("Generic options", term_width);
generic.add_options()
("help", "Display this message")
("config,c", po::value<std::string>(),
"Path to a file that contains configuration settings")
("verbosity,v", po::value<int>(&verbosity)->default_value(1),
"Verbosity level [0 - the lowest, 9 - the highest]")
("quiet,q", "Quiet mode (no progress indicator)")
("scratch-dir,r", po::value<bf::path>(&cd->scratch_dir_)
->default_value(bf::temp_directory_path())->required(),
"Path to the scratch directory")
;
po::options_description access("Access settings", term_width);
access.add_options()
("access-key,a", po::value<std::string>(
&cd->api_key_)->required(),
"Amazon S3 API key")
("secret-key,s", po::value<std::string>(
&cd->secret_key)->required(),
"Amazon S3 secret key")
("use-ssl,l", po::value<bool>(
&cd->use_ssl_)->default_value(false),
"Use SSL for communications with the Amazon S3 servers")
("compression,m", po::value<bool>(
&cd->do_compression_)->default_value(true)->required(),
"Use GZIP compression")
;
generic.add(access);
int thread_num=0, io_threads=0, cpu_threads=0, segment_size=0, segments=0;
po::options_description tuning("Tuning", term_width);
tuning.add_options()
("thread-num,n", po::value<int>(&thread_num)->default_value(0),
"Number of download/upload threads used [0 - autodetect]")
("reader-threads,t", po::value<int>(
&io_threads)->default_value(0),
"Number of filesystem reader/writer threads [0 - autodetect]")
("compressor-threads,o", po::value<int>(
&cpu_threads)->default_value(0),
"Number of compressor threads [0 - autodetect]")
("segment-size,g", po::value<int>(
&segment_size)->default_value(0),
"Segment size in bytes [0 - autodetect, 6291456 - minimum]")
("segments-in-flight,f", po::value<int>(
&segments)->default_value(0),
"Number of segments in-flight [0 - autodetect]")
;
generic.add(tuning);
po::options_description sub_data("Subcommands");
sub_data.add_options()
("subcommand", po::value<std::string>())
("subcommand_params", po::value<stringvec>()->multitoken());
std::map< std::string,
std::function<int(context_ptr, const stringvec&, agenda_ptr, bool)> >
subcommands_map;
subcommands_map["sync"] = boost::bind(&do_rsync, _1, _2, _3, _4);
// subcommands.push_back("ls");
// subcommands.push_back("cp");
// subcommands.push_back("rm");
// subcommands.push_back("mb");
// subcommands.push_back("rb");
stringvec subcommands;
for(auto iter=subcommands_map.begin();iter!=subcommands_map.end();++iter)
subcommands.push_back(iter->first);
std::string cur_subcommand;
stringvec cur_sub_params;
po::variables_map vm;
try
{
sub_data.add(generic);
po::parsed_options parsed = po::command_line_parser(argc, argv)
.options(sub_data)
.extra_style_parser(boost::bind(&subcommands_parser, _1,
subcommands))
.run();
po::store(parsed, vm);
cur_subcommand=vm.count("subcommand")==0?
"" : vm["subcommand"].as<std::string>();
cur_sub_params=vm.count("subcommand_params")==0?
stringvec() : vm["subcommand_params"].as<stringvec>();
if (argc < 2 || vm.count("help"))
{
if (cur_subcommand.empty())
{
std::cout << "Extreme S3 - fast S3 client\n" << generic
<< "\nThe following commands are supported:\n\t";
for(auto iter=subcommands.begin();iter!=subcommands.end();++iter)
std::cout<< *iter <<" ";
std::cout << "\nUse --help <command_name> to get more info\n";
} else
{
std::cout << "Extreme S3 - fast S3 client\n";
subcommands_map[cur_subcommand](cd, cur_sub_params,
agenda_ptr(), true);
}
return 1;
}
if (cur_subcommand.empty())
{
std::cout << "No command specified. Use --help for help\n";
return 2;
}
} catch(const boost::program_options::error &err)
{
std::cerr << "Failed to parse command line. Error: "
<< err.what() << std::endl;
return 2;
}
try
{
if (vm.count("config"))
{
// Parse the file and store the options
std::string config_file = vm["config"].as<std::string>();
po::store(po::parse_config_file<char>(config_file.c_str(),generic), vm);
}
} catch(const boost::program_options::error &err)
{
std::cerr << "Failed to parse the configuration file. Error: "
<< err.what() << std::endl;
return 2;
}
quiet = vm.count("quiet");
try
{
po::notify(vm);
} catch(const boost::program_options::required_option &option)
{
std::cerr << "Required option " << option.get_option_name()
<< " is not present." << std::endl;
return 1;
}
logger::set_verbosity(verbosity);
curl_global_init(CURL_GLOBAL_ALL);
ON_BLOCK_EXIT(&curl_global_cleanup);
if (segments>MAX_IN_FLIGHT || segments<=0)
segments=MAX_IN_FLIGHT;
if (segment_size<MIN_SEGMENT_SIZE)
segment_size=MIN_SEGMENT_SIZE;
if (cpu_threads<=0)
cpu_threads=sysconf(_SC_NPROCESSORS_ONLN)+2;
if (io_threads<=0)
io_threads=sysconf(_SC_NPROCESSORS_ONLN)*4;
if (thread_num<=0)
thread_num=sysconf(_SC_NPROCESSORS_ONLN)*9+8;
agenda_ptr ag(new agenda(thread_num, cpu_threads, io_threads, quiet,
segment_size, segments));
try
{
return subcommands_map[cur_subcommand](cd, cur_sub_params, ag, false);
} catch(const std::exception &ex)
{
VLOG(0) << "Unexpected error: " << ex.what() << std::endl;
return 8;
}
}
<commit_msg>Add default file location<commit_after>#include <iostream>
#include <boost/program_options.hpp>
#include "common.h"
#include "scope_guard.h"
#include "connection.h"
#include "context.h"
#include "agenda.h"
#include "sync.h"
#include <sys/ioctl.h>
#include <boost/bind.hpp>
using namespace es3;
#include <curl/curl.h>
static int term_width = 80;
namespace po = boost::program_options;
typedef std::vector<std::string> stringvec;
int do_rsync(context_ptr context, const stringvec& params,
agenda_ptr ag, bool help)
{
bool delete_missing=false;
po::options_description opts("Sync options", term_width);
opts.add_options()
("delete-missing,D", po::value<bool>(
&delete_missing)->default_value(false),
"Delete missing files from the sync destination")
;
if (help)
{
std::cout << "Sync syntax: es3 sync [OPTIONS] <SOURCE> <DESTINATION>\n"
<< "where <SOURCE> and <DESTINATION> are either:\n"
<< "\t - Local directory\n"
<< "\t - Amazon S3 storage (in s3://<bucket>/path/ format)"
<< std::endl << std::endl;
std::cout << opts;
return 0;
}
po::positional_options_description pos;
pos.add("<SOURCE>", 1);
pos.add("<DESTINATION>", 1);
std::string src, tgt;
opts.add_options()
("<SOURCE>", po::value<std::string>(&src)->required())
("<DESTINATION>", po::value<std::string>(&tgt)->required())
;
try
{
po::variables_map vm;
po::store(po::command_line_parser(params)
.options(opts).positional(pos).run(), vm);
po::notify(vm);
} catch(const boost::program_options::error &err)
{
std::cerr << "Failed to parse configuration options. Error: "
<< err.what() << "\n"
<< "Use --help for help\n";
return 2;
}
s3_path path;
std::string local;
bool upload = false;
if (src.find("s3://")==0)
{
path = parse_path(src);
local = tgt;
upload = false;
} else if (tgt.find("s3://")==0)
{
path = parse_path(tgt);
local = src;
upload = true;
} else
{
std::cerr << "Error: one of <SOURCE> or <DESTINATION> must be an S3 URL.\n";
return 2;
}
if (local.find("s3://")==0)
{
std::cerr << "Error: one of <SOURCE> or <DESTINATION> must be a local path \n";
return 2;
}
//TODO: de-uglify
context->bucket_=path.bucket_;
context->zone_="s3";
s3_connection conn(context);
std::string region=conn.find_region();
if (!region.empty())
context->zone_="s3-"+region;
synchronizer sync(ag, context, path.path_, local, upload, delete_missing);
sync.create_schedule();
return ag->run();
}
std::vector<po::option> subcommands_parser(stringvec& args,
const stringvec& subcommands)
{
std::vector<po::option> result;
if (args.empty())
return result;
stringvec::const_iterator i(args.begin());
stringvec::const_iterator cmd_idx=std::find(subcommands.begin(),
subcommands.end(),*i);
if (cmd_idx!=subcommands.end())
{
po::option opt;
opt.string_key = "subcommand";
opt.value.push_back(*i);
opt.original_tokens.push_back(*i);
result.push_back(opt);
for (++i; i != args.end(); ++i)
{
po::option opt;
opt.string_key = "subcommand_params";
opt.value.push_back(*i);
opt.original_tokens.push_back(*i);
result.push_back(opt);
}
args.clear();
}
return result;
}
int main(int argc, char **argv)
{
int verbosity = 0;
bool quiet=false;
//Get terminal size (to pretty-print help text)
struct winsize w={0};
ioctl(0, TIOCGWINSZ, &w);
term_width=(w.ws_col==0)? 80 : w.ws_col;
context_ptr cd(new conn_context());
po::options_description generic("Generic options", term_width);
generic.add_options()
("help", "Display this message")
("config,c", po::value<std::string>(),
"Path to a file that contains configuration settings")
("verbosity,v", po::value<int>(&verbosity)->default_value(1),
"Verbosity level [0 - the lowest, 9 - the highest]")
("quiet,q", "Quiet mode (no progress indicator)")
("scratch-dir,r", po::value<bf::path>(&cd->scratch_dir_)
->default_value(bf::temp_directory_path())->required(),
"Path to the scratch directory")
;
po::options_description access("Access settings", term_width);
access.add_options()
("access-key,a", po::value<std::string>(
&cd->api_key_)->required(),
"Amazon S3 API key")
("secret-key,s", po::value<std::string>(
&cd->secret_key)->required(),
"Amazon S3 secret key")
("use-ssl,l", po::value<bool>(
&cd->use_ssl_)->default_value(false),
"Use SSL for communications with the Amazon S3 servers")
("compression,m", po::value<bool>(
&cd->do_compression_)->default_value(true)->required(),
"Use GZIP compression")
;
generic.add(access);
int thread_num=0, io_threads=0, cpu_threads=0, segment_size=0, segments=0;
po::options_description tuning("Tuning", term_width);
tuning.add_options()
("thread-num,n", po::value<int>(&thread_num)->default_value(0),
"Number of download/upload threads used [0 - autodetect]")
("reader-threads,t", po::value<int>(
&io_threads)->default_value(0),
"Number of filesystem reader/writer threads [0 - autodetect]")
("compressor-threads,o", po::value<int>(
&cpu_threads)->default_value(0),
"Number of compressor threads [0 - autodetect]")
("segment-size,g", po::value<int>(
&segment_size)->default_value(0),
"Segment size in bytes [0 - autodetect, 6291456 - minimum]")
("segments-in-flight,f", po::value<int>(
&segments)->default_value(0),
"Number of segments in-flight [0 - autodetect]")
;
generic.add(tuning);
po::options_description sub_data("Subcommands");
sub_data.add_options()
("subcommand", po::value<std::string>())
("subcommand_params", po::value<stringvec>()->multitoken());
std::map< std::string,
std::function<int(context_ptr, const stringvec&, agenda_ptr, bool)> >
subcommands_map;
subcommands_map["sync"] = boost::bind(&do_rsync, _1, _2, _3, _4);
// subcommands.push_back("ls");
// subcommands.push_back("cp");
// subcommands.push_back("rm");
// subcommands.push_back("mb");
// subcommands.push_back("rb");
stringvec subcommands;
for(auto iter=subcommands_map.begin();iter!=subcommands_map.end();++iter)
subcommands.push_back(iter->first);
std::string cur_subcommand;
stringvec cur_sub_params;
po::variables_map vm;
try
{
sub_data.add(generic);
po::parsed_options parsed = po::command_line_parser(argc, argv)
.options(sub_data)
.extra_style_parser(boost::bind(&subcommands_parser, _1,
subcommands))
.run();
po::store(parsed, vm);
cur_subcommand=vm.count("subcommand")==0?
"" : vm["subcommand"].as<std::string>();
cur_sub_params=vm.count("subcommand_params")==0?
stringvec() : vm["subcommand_params"].as<stringvec>();
if (argc < 2 || vm.count("help"))
{
if (cur_subcommand.empty())
{
std::cout << "Extreme S3 - fast S3 client\n" << generic
<< "\nThe following commands are supported:\n\t";
for(auto iter=subcommands.begin();iter!=subcommands.end();++iter)
std::cout<< *iter <<" ";
std::cout << "\nUse --help <command_name> to get more info\n";
} else
{
std::cout << "Extreme S3 - fast S3 client\n";
subcommands_map[cur_subcommand](cd, cur_sub_params,
agenda_ptr(), true);
}
return 1;
}
if (cur_subcommand.empty())
{
std::cout << "No command specified. Use --help for help\n";
return 2;
}
} catch(const boost::program_options::error &err)
{
std::cerr << "Failed to parse command line. Error: "
<< err.what() << std::endl;
return 2;
}
try
{
if (vm.count("config"))
{
// Parse the file and store the options
std::string config_file = vm["config"].as<std::string>();
po::store(po::parse_config_file<char>(config_file.c_str(),generic), vm);
} else if (getenv("ES3_CONFIG"))
{
po::store(po::parse_config_file<char>(
getenv("ES3_CONFIG"),generic), vm);
} else
{
const char *home=getenv("HOME");
if (home)
{
bf::path cfg=bf::path(home) / ".es3cfg";
if (bf::exists(cfg))
po::store(po::parse_config_file<char>(
cfg.c_str(),generic), vm);
}
}
} catch(const boost::program_options::error &err)
{
std::cerr << "Failed to parse the configuration file. Error: "
<< err.what() << std::endl;
return 2;
}
quiet = vm.count("quiet");
try
{
po::notify(vm);
} catch(const boost::program_options::required_option &option)
{
std::cerr << "Required option " << option.get_option_name()
<< " is not present." << std::endl;
return 1;
}
logger::set_verbosity(verbosity);
curl_global_init(CURL_GLOBAL_ALL);
ON_BLOCK_EXIT(&curl_global_cleanup);
if (segments>MAX_IN_FLIGHT || segments<=0)
segments=MAX_IN_FLIGHT;
if (segment_size<MIN_SEGMENT_SIZE)
segment_size=MIN_SEGMENT_SIZE;
if (cpu_threads<=0)
cpu_threads=sysconf(_SC_NPROCESSORS_ONLN)+2;
if (io_threads<=0)
io_threads=sysconf(_SC_NPROCESSORS_ONLN)*4;
if (thread_num<=0)
thread_num=sysconf(_SC_NPROCESSORS_ONLN)*9+8;
agenda_ptr ag(new agenda(thread_num, cpu_threads, io_threads, quiet,
segment_size, segments));
try
{
return subcommands_map[cur_subcommand](cd, cur_sub_params, ag, false);
} catch(const std::exception &ex)
{
VLOG(0) << "Unexpected error: " << ex.what() << std::endl;
return 8;
}
}
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include <shadow.hpp>
#include <vector>
#include <iostream>
struct tca1
{
int i;
char c;
};
class tca2
{
public:
tca2() : c_('a')
{
}
tca2(char c) : c_(std::move(c))
{
}
char
get_c() const
{
return c_;
}
private:
char c_;
};
class tca3
{
public:
tca3(const int& i) : i_(i)
{
}
int
get_i() const
{
return i_;
}
private:
int i_;
};
namespace tca_space
{
REGISTER_TYPE_BEGIN()
REGISTER_TYPE(tca1)
REGISTER_TYPE(tca2)
REGISTER_TYPE(tca3)
REGISTER_TYPE_END()
REGISTER_CONSTRUCTOR(tca1, int, char)
REGISTER_CONSTRUCTOR(tca2)
REGISTER_CONSTRUCTOR(tca2, char)
REGISTER_CONSTRUCTOR(tca3, const int&)
SHADOW_INIT()
}
TEST_CASE("get all types", "[reflection_manager]")
{
auto types_pair = tca_space::manager.types();
SECTION("find double type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("double");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for double")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 2);
SECTION("find constructor taking 0 arguments")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 0;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("constructor double with 0 args")
{
// construct with no arg overload
auto obj = tca_space::manager.construct(*found_constr);
// construct with overload taking iterators to args
std::vector<shadow::variable> args;
auto obj2 = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("double"));
REQUIRE(obj2.type().name() == std::string("double"));
REQUIRE(tca_space::static_value_cast<double>(obj) ==
Approx(0.0));
REQUIRE(tca_space::static_value_cast<double>(obj2) ==
Approx(0.0));
}
}
SECTION("find constructor taking 1 argument")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 1;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("constructor double with 1 arg")
{
// construct with overload taking iterators to args
std::vector<shadow::variable> args{
tca_space::static_create<double>(20.0)};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("double"));
REQUIRE(tca_space::static_value_cast<double>(obj) ==
Approx(20.0));
}
}
}
}
SECTION("find tca1 type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("tca1");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for tca1")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 1);
SECTION("find constructor taking two args")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 2;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct a tca1 with two arguments")
{
std::vector<shadow::variable> args{
tca_space::static_create<int>(10),
tca_space::static_create<char>('c')};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("tca1"));
REQUIRE(tca_space::static_value_cast<tca1>(obj).i == 10);
REQUIRE(tca_space::static_value_cast<tca1>(obj).c == 'c');
}
}
}
}
SECTION("find tca2 type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("tca2");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for tca2")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 2);
SECTION("find default constructor for tca2")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 0;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct tca2 with default constructor")
{
auto obj = tca_space::manager.construct(*found_constr);
REQUIRE(obj.type().name() == std::string("tca2"));
REQUIRE(tca_space::static_value_cast<tca2>(obj).get_c() ==
'a');
}
}
SECTION("find constructor for tca2 taking one argument")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 1;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct tca2 with one arg constructor")
{
std::vector<shadow::variable> args{
tca_space::static_create<char>('w')};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("tca2"));
REQUIRE(tca_space::static_value_cast<tca2>(obj).get_c() ==
'w');
}
}
}
}
SECTION("find tca3 type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("tca3");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for tca3")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 1);
SECTION("find constructor taking one arg")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 1;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct tca3 with one argument")
{
std::vector<shadow::variable> args{
tca_space::static_create<int>(100)};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("tca3"));
}
}
}
}
}
<commit_msg>Add test causing segfault with pointer parameter. modified: tests/test_constructor_api.cpp<commit_after>#include "catch.hpp"
#include <shadow.hpp>
#include <vector>
#include <iostream>
struct tca1
{
int i;
char c;
};
class tca2
{
public:
tca2() : c_('a')
{
}
tca2(char c) : c_(std::move(c))
{
}
char
get_c() const
{
return c_;
}
private:
char c_;
};
class tca3
{
public:
tca3(const int& i) : i_(i)
{
}
int
get_i() const
{
return i_;
}
private:
int i_;
};
struct tca4
{
tca4(const int* i_ptr) : i(*i_ptr)
{
}
int i;
};
namespace tca_space
{
REGISTER_TYPE_BEGIN()
REGISTER_TYPE(tca1)
REGISTER_TYPE(tca2)
REGISTER_TYPE(tca3)
REGISTER_TYPE(tca4)
REGISTER_TYPE_END()
REGISTER_CONSTRUCTOR(tca1, int, char)
REGISTER_CONSTRUCTOR(tca2)
REGISTER_CONSTRUCTOR(tca2, char)
REGISTER_CONSTRUCTOR(tca3, const int&)
REGISTER_CONSTRUCTOR(tca4, const int*)
SHADOW_INIT()
}
TEST_CASE("get all types", "[reflection_manager]")
{
auto types_pair = tca_space::manager.types();
SECTION("find double type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("double");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for double")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 2);
SECTION("find constructor taking 0 arguments")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 0;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("constructor double with 0 args")
{
// construct with no arg overload
auto obj = tca_space::manager.construct(*found_constr);
// construct with overload taking iterators to args
std::vector<shadow::variable> args;
auto obj2 = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("double"));
REQUIRE(obj2.type().name() == std::string("double"));
REQUIRE(tca_space::static_value_cast<double>(obj) ==
Approx(0.0));
REQUIRE(tca_space::static_value_cast<double>(obj2) ==
Approx(0.0));
}
}
SECTION("find constructor taking 1 argument")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 1;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("constructor double with 1 arg")
{
// construct with overload taking iterators to args
std::vector<shadow::variable> args{
tca_space::static_create<double>(20.0)};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("double"));
REQUIRE(tca_space::static_value_cast<double>(obj) ==
Approx(20.0));
}
}
}
}
SECTION("find tca1 type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("tca1");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for tca1")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 1);
SECTION("find constructor taking two args")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 2;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct a tca1 with two arguments")
{
std::vector<shadow::variable> args{
tca_space::static_create<int>(10),
tca_space::static_create<char>('c')};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("tca1"));
REQUIRE(tca_space::static_value_cast<tca1>(obj).i == 10);
REQUIRE(tca_space::static_value_cast<tca1>(obj).c == 'c');
}
}
}
}
SECTION("find tca2 type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("tca2");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for tca2")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 2);
SECTION("find default constructor for tca2")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 0;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct tca2 with default constructor")
{
auto obj = tca_space::manager.construct(*found_constr);
REQUIRE(obj.type().name() == std::string("tca2"));
REQUIRE(tca_space::static_value_cast<tca2>(obj).get_c() ==
'a');
}
}
SECTION("find constructor for tca2 taking one argument")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 1;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct tca2 with one arg constructor")
{
std::vector<shadow::variable> args{
tca_space::static_create<char>('w')};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("tca2"));
REQUIRE(tca_space::static_value_cast<tca2>(obj).get_c() ==
'w');
}
}
}
}
SECTION("find tca3 type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("tca3");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for tca3")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 1);
SECTION("find constructor taking one arg")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 1;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct tca3 with one argument")
{
std::vector<shadow::variable> args{
tca_space::static_create<int>(100)};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("tca3"));
}
}
}
}
SECTION("find tca4 type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("tca4");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for tca4")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 1);
SECTION("find constructor taking one arg")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 1;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct a tca4 with one int argument")
{
std::vector<shadow::variable> args{
tca_space::static_create<int>(44)};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
}
}
}
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkXRenderWindowTclInteractor.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkActor.h"
#include "vtkActorCollection.h"
#include "vtkObjectFactory.h"
#include "vtkOldStyleCallbackCommand.h"
#include "vtkPoints.h"
#include "vtkXOpenGLRenderWindow.h"
#include "vtkXRenderWindowTclInteractor.h"
#include <X11/Shell.h>
#include <X11/X.h>
#include <X11/keysym.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vtkTk.h>
vtkCxxRevisionMacro(vtkXRenderWindowTclInteractor, "1.53");
vtkStandardNewMacro(vtkXRenderWindowTclInteractor);
// steal the first three elements of the TkMainInfo stuct
// we don't care about the rest of the elements.
struct TkMainInfo
{
int refCount;
struct TkWindow *winPtr;
Tcl_Interp *interp;
};
#if ((TK_MAJOR_VERSION <= 4)||((TK_MAJOR_VERSION == 8)&&(TK_MINOR_VERSION == 0)))
extern TkMainInfo *tkMainWindowList;
#else
extern "C" {TkMainInfo *TkGetMainInfoList();}
#endif
// returns 1 if done
static int vtkTclEventProc(XtPointer clientData,XEvent *event)
{
Boolean ctd;
vtkXOpenGLRenderWindow *rw;
rw = (vtkXOpenGLRenderWindow *)
(((vtkXRenderWindowTclInteractor *)clientData)->GetRenderWindow());
if (rw->GetWindowId() == (reinterpret_cast<XAnyEvent *>(event))->window)
{
vtkXRenderWindowTclInteractorCallback((Widget)NULL,clientData, event, &ctd);
ctd = 0;
}
else
{
ctd = 1;
}
return !ctd;
}
extern "C"
{
void vtkXTclTimerProc(ClientData clientData)
{
XtIntervalId id;
vtkXRenderWindowTclInteractorTimer((XtPointer)clientData,&id);
}
}
// Construct object so that light follows camera motion.
vtkXRenderWindowTclInteractor::vtkXRenderWindowTclInteractor()
{
this->App = 0;
this->top = 0;
this->TopLevelShell = NULL;
this->BreakLoopFlag = 0;
}
vtkXRenderWindowTclInteractor::~vtkXRenderWindowTclInteractor()
{
if (this->Initialized)
{
Tk_DeleteGenericHandler((Tk_GenericProc *)vtkTclEventProc,
(ClientData)this);
}
}
void vtkXRenderWindowTclInteractor::SetWidget(Widget foo)
{
this->top = foo;
}
// This method will store the top level shell widget for the interactor.
// This method and the method invocation sequence applies for:
// 1 vtkRenderWindow-Interactor pair in a nested widget heirarchy
// multiple vtkRenderWindow-Interactor pairs in the same top level shell
// It is not needed for
// 1 vtkRenderWindow-Interactor pair as the direct child of a top level shell
// multiple vtkRenderWindow-Interactor pairs, each in its own top level shell
//
// The method, along with EnterNotify event, changes the keyboard focus among
// the widgets/vtkRenderWindow(s) so the Interactor(s) can receive the proper
// keyboard events. The following calls need to be made:
// vtkRenderWindow's display ID need to be set to the top level shell's
// display ID.
// vtkXRenderWindowTclInteractor's Widget has to be set to the vtkRenderWindow's
// container widget
// vtkXRenderWindowTclInteractor's TopLevel has to be set to the top level
// shell widget
// note that the procedure for setting up render window in a widget needs to
// be followed. See vtkRenderWindowInteractor's SetWidget method.
//
// If multiple vtkRenderWindow-Interactor pairs in SEPARATE windows are desired,
// do not set the display ID (Interactor will create them as needed. Alternatively,
// create and set distinct DisplayID for each vtkRenderWindow. Using the same
// display ID without setting the parent widgets will cause the display to be
// reinitialized every time an interactor is initialized), do not set the
// widgets (so the render windows would be in their own windows), and do
// not set TopLevelShell (each has its own top level shell already)
void vtkXRenderWindowTclInteractor::SetTopLevelShell(Widget topLevel)
{
this->TopLevelShell = topLevel;
}
static void vtkBreakTclLoop(void *iren)
{
((vtkXRenderWindowTclInteractor*)iren)->SetBreakLoopFlag(1);
}
void vtkXRenderWindowTclInteractor::Start()
{
// Let the compositing handle the event loop if it wants to.
if (this->HasObserver(vtkCommand::StartEvent) && !this->HandleEventLoop)
{
this->InvokeEvent(vtkCommand::StartEvent,NULL);
return;
}
vtkOldStyleCallbackCommand *cbc = vtkOldStyleCallbackCommand::New();
cbc->Callback = vtkBreakTclLoop;
cbc->ClientData = this;
unsigned long ExitTag = this->AddObserver(vtkCommand::ExitEvent,cbc, 0.5);
cbc->Delete();
this->BreakLoopFlag = 0;
while(this->BreakLoopFlag == 0)
{
Tk_DoOneEvent(0);
}
this->RemoveObserver(ExitTag);
}
// Initializes the event handlers
void vtkXRenderWindowTclInteractor::Initialize(XtAppContext app)
{
this->App = app;
this->Initialize();
}
// Begin processing keyboard strokes.
void vtkXRenderWindowTclInteractor::Initialize()
{
vtkXOpenGLRenderWindow *ren;
int *size;
// make sure we have a RenderWindow and camera
if ( ! this->RenderWindow)
{
vtkErrorMacro(<<"No renderer defined!");
return;
}
this->Initialized = 1;
ren = (vtkXOpenGLRenderWindow *)(this->RenderWindow);
// use the same display as tcl/tk
#if ((TK_MAJOR_VERSION <= 4)||((TK_MAJOR_VERSION == 8)&&(TK_MINOR_VERSION == 0)))
ren->SetDisplayId(Tk_Display(tkMainWindowList->winPtr));
#else
ren->SetDisplayId(Tk_Display(TkGetMainInfoList()->winPtr));
#endif
this->DisplayId = ren->GetDisplayId();
// get the info we need from the RenderingWindow
size = ren->GetSize();
size = ren->GetSize();
ren->Start();
this->WindowId = ren->GetWindowId();
size = ren->GetSize();
this->Size[0] = size[0];
this->Size[1] = size[1];
this->Enable();
// Set the event handler
Tk_CreateGenericHandler((Tk_GenericProc *)vtkTclEventProc,(ClientData)this);
}
void vtkXRenderWindowTclInteractor::Enable()
{
// avoid cycles of calling Initialize() and Enable()
if (this->Enabled)
{
return;
}
// Select the events that we want to respond to
// (Multiple calls to XSelectInput overrides the previous settings)
XSelectInput(this->DisplayId, this->WindowId,
KeyPressMask | KeyReleaseMask |
ButtonPressMask | ButtonReleaseMask |
ExposureMask | StructureNotifyMask |
EnterWindowMask | LeaveWindowMask |
PointerMotionMask | PointerMotionMask);
// Setup for capturing the window deletion
this->KillAtom = XInternAtom(this->DisplayId,"WM_DELETE_WINDOW",False);
XSetWMProtocols(this->DisplayId,this->WindowId,&this->KillAtom,1);
this->Enabled = 1;
this->Modified();
}
void vtkXRenderWindowTclInteractor::Disable()
{
if (!this->Enabled)
{
return;
}
// Remove the all the events that we registered for EXCEPT for
// StructureNotifyMask event since we need to keep track of the window
// size (we will not render if we are disabled, we simply track the window
// size changes for a possible Enable()). Expose events are disabled.
// (Multiple calls to XSelectInput overrides the previous settings)
XSelectInput(this->DisplayId,this->WindowId,
StructureNotifyMask );
this->Enabled = 0;
this->Modified();
}
void vtkXRenderWindowTclInteractor::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
if (this->App)
{
os << indent << "App: " << this->App << "\n";
}
else
{
os << indent << "App: (none)\n";
}
os << indent << "Break Loop Flag: "
<< (this->BreakLoopFlag ? "On\n" : "Off\n");
}
void vtkXRenderWindowTclInteractor::UpdateSize(int x,int y)
{
// if the size changed send this on to the RenderWindow
if ((x != this->Size[0])||(y != this->Size[1]))
{
this->Size[0] = x;
this->Size[1] = y;
this->RenderWindow->SetSize(x,y);
}
}
void vtkXRenderWindowTclInteractorCallback(Widget vtkNotUsed(w),
XtPointer client_data,
XEvent *event,
Boolean *vtkNotUsed(ctd))
{
vtkXRenderWindowTclInteractor *me;
me = (vtkXRenderWindowTclInteractor *)client_data;
int xp, yp;
switch (event->type)
{
case Expose:
{
if (!me->Enabled)
{
return;
}
XEvent result;
while (XCheckTypedWindowEvent(me->DisplayId,
me->WindowId,
Expose,
&result))
{
// just getting the expose configure event
event = &result;
}
int width = (reinterpret_cast<XConfigureEvent *>(event))->width;
int height = (reinterpret_cast<XConfigureEvent *>(event))->height;
me->SetEventSize(width, height);
xp = (reinterpret_cast<XButtonEvent*>(event))->x;
yp = (reinterpret_cast<XButtonEvent*>(event))->y;
yp = me->Size[1] - xp - 1;
me->SetEventPosition(xp, yp);
// only render if we are currently accepting events
if (me->Enabled)
{
me->InvokeEvent(vtkCommand::ExposeEvent,NULL);
me->Render();
}
}
break;
case MapNotify:
{
// only render if we are currently accepting events
if (me->Enabled && me->GetRenderWindow()->GetNeverRendered())
{
me->Render();
}
}
break;
case ConfigureNotify:
{
XEvent result;
while (XCheckTypedWindowEvent(me->DisplayId,
me->WindowId,
ConfigureNotify,
&result))
{
// just getting the last configure event
event = &result;
}
int width = (reinterpret_cast<XConfigureEvent *>(event))->width;
int height = (reinterpret_cast<XConfigureEvent *>(event))->height;
if (width != me->Size[0] || height != me->Size[1])
{
me->UpdateSize(width, height);
xp = (reinterpret_cast<XButtonEvent*>(event))->x;
yp = (reinterpret_cast<XButtonEvent*>(event))->y;
me->SetEventPosition(xp, me->Size[1] - yp - 1);
// only render if we are currently accepting events
if (me->Enabled)
{
me->InvokeEvent(vtkCommand::ConfigureEvent,NULL);
me->Render();
}
}
}
break;
case ButtonPress:
{
if (!me->Enabled)
{
return;
}
int ctrl =
(reinterpret_cast<XButtonEvent *>(event))->state & ControlMask ? 1 : 0;
int shift =
(reinterpret_cast<XButtonEvent *>(event))->state & ShiftMask ? 1 : 0;
int alt =
(reinterpret_cast<XButtonEvent *>(event))->state & Mod1Mask ? 1 : 0;
xp = (reinterpret_cast<XButtonEvent*>(event))->x;
yp = (reinterpret_cast<XButtonEvent*>(event))->y;
me->SetEventInformationFlipY(xp,
yp,
ctrl,
shift);
me->SetAltKey(alt);
switch ((reinterpret_cast<XButtonEvent *>(event))->button)
{
case Button1:
me->InvokeEvent(vtkCommand::LeftButtonPressEvent, NULL);
break;
case Button2:
me->InvokeEvent(vtkCommand::MiddleButtonPressEvent, NULL);
break;
case Button3:
me->InvokeEvent(vtkCommand::RightButtonPressEvent, NULL);
break;
case Button4:
me->InvokeEvent(vtkCommand::MouseWheelForwardEvent, NULL);
break;
case Button5:
me->InvokeEvent(vtkCommand::MouseWheelBackwardEvent, NULL);
break;
}
}
break;
case ButtonRelease:
{
if (!me->Enabled)
{
return;
}
int ctrl =
(reinterpret_cast<XButtonEvent *>(event))->state & ControlMask ? 1 : 0;
int shift =
(reinterpret_cast<XButtonEvent *>(event))->state & ShiftMask ? 1 : 0;
int alt =
(reinterpret_cast<XButtonEvent *>(event))->state & Mod1Mask ? 1 : 0;
xp = (reinterpret_cast<XButtonEvent*>(event))->x;
yp = (reinterpret_cast<XButtonEvent*>(event))->y;
// check for double click
static int MousePressTime = 0;
int repeat = 0;
// 400 ms threshold by default is probably good to start
if((reinterpret_cast<XButtonEvent*>(event)->time - MousePressTime) < 400)
{
MousePressTime -= 2000; // no double click next time
repeat = 1;
}
else
{
MousePressTime = reinterpret_cast<XButtonEvent*>(event)->time;
}
me->SetEventInformationFlipY(xp,
yp,
ctrl,
shift,
0,
repeat);
me->SetAltKey(alt);
switch ((reinterpret_cast<XButtonEvent *>(event))->button)
{
case Button1:
me->InvokeEvent(vtkCommand::LeftButtonReleaseEvent, NULL);
break;
case Button2:
me->InvokeEvent(vtkCommand::MiddleButtonReleaseEvent, NULL);
break;
case Button3:
me->InvokeEvent(vtkCommand::RightButtonReleaseEvent, NULL);
break;
}
}
break;
case EnterNotify:
{
// Force the keyboard focus to be this render window
if (me->TopLevelShell != NULL)
{
XtSetKeyboardFocus(me->TopLevelShell, me->top);
}
if (me->Enabled)
{
XEnterWindowEvent *e = reinterpret_cast<XEnterWindowEvent *>(event);
me->SetEventInformationFlipY(e->x,
e->y,
(e->state & ControlMask) != 0,
(e->state & ShiftMask) != 0);
me->SetAltKey(
(reinterpret_cast<XButtonEvent *>(event))->state & Mod1Mask ? 1 : 0);
me->InvokeEvent(vtkCommand::EnterEvent, NULL);
}
}
break;
case LeaveNotify:
{
if (me->Enabled)
{
XLeaveWindowEvent *e = reinterpret_cast<XLeaveWindowEvent *>(event);
me->SetEventInformationFlipY(e->x,
e->y,
(e->state & ControlMask) != 0,
(e->state & ShiftMask) != 0);
me->SetAltKey(
(reinterpret_cast<XButtonEvent *>(event))->state & Mod1Mask ? 1 : 0);
me->InvokeEvent(vtkCommand::LeaveEvent, NULL);
}
}
break;
case KeyPress:
{
if (!me->Enabled)
{
return;
}
int ctrl =
(reinterpret_cast<XButtonEvent *>(event))->state & ControlMask ? 1 : 0;
int shift =
(reinterpret_cast<XButtonEvent *>(event))->state & ShiftMask ? 1 : 0;
int alt =
(reinterpret_cast<XButtonEvent *>(event))->state & Mod1Mask ? 1 : 0;
KeySym ks;
static char buffer[20];
buffer[0] = '\0';
XLookupString(reinterpret_cast<XKeyEvent *>(event),buffer, 20, &ks,NULL);
xp = (reinterpret_cast<XKeyEvent*>(event))->x;
yp = (reinterpret_cast<XKeyEvent*>(event))->y;
me->SetEventInformationFlipY(xp,
yp,
ctrl,
shift,
buffer[0],
1,
XKeysymToString(ks));
me->SetAltKey(alt);
me->InvokeEvent(vtkCommand::KeyPressEvent, NULL);
me->InvokeEvent(vtkCommand::CharEvent, NULL);
}
break;
case KeyRelease:
{
if (!me->Enabled)
{
return;
}
int ctrl =
(reinterpret_cast<XButtonEvent *>(event))->state & ControlMask ? 1 : 0;
int shift =
(reinterpret_cast<XButtonEvent *>(event))->state & ShiftMask ? 1 : 0;
int alt =
(reinterpret_cast<XButtonEvent *>(event))->state & Mod1Mask ? 1 : 0;
KeySym ks;
static char buffer[20];
buffer[0] = '\0';
XLookupString(reinterpret_cast<XKeyEvent *>(event),buffer, 20, &ks,NULL);
xp = (reinterpret_cast<XKeyEvent *>(event))->x;
yp = (reinterpret_cast<XKeyEvent *>(event))->y;
me->SetEventInformationFlipY(xp,
yp,
ctrl,
shift,
buffer[0],
1,
XKeysymToString(ks));
me->SetAltKey(alt);
me->InvokeEvent(vtkCommand::KeyReleaseEvent, NULL);
}
break;
case MotionNotify:
{
if (!me->Enabled)
{
return;
}
int ctrl =
(reinterpret_cast<XButtonEvent *>(event))->state & ControlMask ? 1 : 0;
int shift =
(reinterpret_cast<XButtonEvent *>(event))->state & ShiftMask ? 1 : 0;
int alt =
(reinterpret_cast<XButtonEvent *>(event))->state & Mod1Mask ? 1 : 0;
xp = (reinterpret_cast<XMotionEvent*>(event))->x;
yp = (reinterpret_cast<XMotionEvent*>(event))->y;
me->SetEventInformationFlipY(xp,
yp,
ctrl,
shift);
me->SetAltKey(alt);
me->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);
}
break;
case ClientMessage:
{
if( static_cast<Atom>(event->xclient.data.l[0]) == me->KillAtom )
{
me->InvokeEvent(vtkCommand::ExitEvent, NULL);
}
}
break;
}
}
void vtkXRenderWindowTclInteractorTimer(XtPointer client_data,
XtIntervalId *vtkNotUsed(id))
{
vtkXRenderWindowTclInteractor *me;
me = (vtkXRenderWindowTclInteractor *)client_data;
Window root,child;
int root_x,root_y;
int x,y;
unsigned int keys;
// get the pointer position
XQueryPointer(me->DisplayId,
me->WindowId,
&root,
&child,
&root_x,
&root_y,
&x,
&y,
&keys);
if (!me->Enabled)
{
return;
}
me->SetEventInformationFlipY(x,
y,
0,
0);
me->InvokeEvent(vtkCommand::TimerEvent, NULL);
}
int vtkXRenderWindowTclInteractor::CreateTimer(int vtkNotUsed(timertype))
{
Tk_CreateTimerHandler(this->TimerDuration,vtkXTclTimerProc,(ClientData)this);
return 1;
}
int vtkXRenderWindowTclInteractor::DestroyTimer(void)
{
// timers automatically expire in X windows
return 1;
}
void vtkXRenderWindowTclInteractor::TerminateApp(void)
{
#if ((TK_MAJOR_VERSION <= 4)||((TK_MAJOR_VERSION == 8)&&(TK_MINOR_VERSION == 0)))
Tcl_Interp* interp = tkMainWindowList->interp;
#else
Tcl_Interp* interp = TkGetMainInfoList()->interp;
#endif
#if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION <= 2
char es[12];
strcpy(es,"exit");
Tcl_GlobalEval(interp, es);
#else
Tcl_EvalEx(interp, "exit", -1, TCL_EVAL_GLOBAL);
#endif
}
<commit_msg>ENH: Merge changes from main tree into VTK-5-2 branch. (cvs -q up -j1.53 -j1.56 Rendering/vtkXRenderWindowTclInteractor.cxx)<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkXRenderWindowTclInteractor.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkXRenderWindowTclInteractor.h"
#include "vtkCallbackCommand.h"
#include "vtkCommand.h"
#include "vtkObjectFactory.h"
#include "vtkXOpenGLRenderWindow.h"
#include <vtksys/stl/map>
#include <vtkTk.h>
//-------------------------------------------------------------------------
vtkCxxRevisionMacro(vtkXRenderWindowTclInteractor, "1.53.14.1");
vtkStandardNewMacro(vtkXRenderWindowTclInteractor);
//-------------------------------------------------------------------------
// steal the first three elements of the TkMainInfo stuct
// we don't care about the rest of the elements.
struct TkMainInfo
{
int refCount;
struct TkWindow *winPtr;
Tcl_Interp *interp;
};
#if ((TK_MAJOR_VERSION <= 4)||((TK_MAJOR_VERSION == 8)&&(TK_MINOR_VERSION == 0)))
extern TkMainInfo *tkMainWindowList;
#else
extern "C" {TkMainInfo *TkGetMainInfoList();}
#endif
//-------------------------------------------------------------------------
class vtkXTclTimer
{
public:
vtkXTclTimer()
{
this->Interactor = 0;
this->ID = 0;
this->TimerToken = 0;
}
vtkRenderWindowInteractor *Interactor;
int ID;
Tcl_TimerToken TimerToken;
};
//-------------------------------------------------------------------------
void vtkXTclTimerProc(ClientData clientData)
{
vtkXTclTimer* timer = static_cast<vtkXTclTimer*>(clientData);
vtkXRenderWindowTclInteractor* me =
static_cast<vtkXRenderWindowTclInteractor*>(timer->Interactor);
int platformTimerId = timer->ID;
int timerId = me->GetVTKTimerId(platformTimerId);
if (me->GetEnabled())
{
me->InvokeEvent(vtkCommand::TimerEvent, &timerId);
}
if (!me->IsOneShotTimer(timerId))
{
me->ResetTimer(timerId);
}
}
//-------------------------------------------------------------------------
// Map between the Tcl native timer token to our own int id. Note this
// is separate from the TimerMap in the vtkRenderWindowInteractor
// superclass. This is used to avoid passing 64-bit values back
// through the "int" return type of InternalCreateTimer.
class vtkXRenderWindowTclInteractorInternals
{
public:
vtkXTclTimer* CreateTimer(vtkRenderWindowInteractor* iren,
int timerId, unsigned long duration)
{
vtkXTclTimer* timer = &this->Timers[timerId];
timer->Interactor = iren;
timer->ID = timerId;
timer->TimerToken = Tcl_CreateTimerHandler(duration, vtkXTclTimerProc,
(ClientData) timer);
return timer;
}
int DestroyTimer(int timerId)
{
int destroyed = 0;
vtkXTclTimer* timer = &this->Timers[timerId];
if (0 != timer->ID)
{
Tcl_DeleteTimerHandler(timer->TimerToken);
timer->Interactor = 0;
timer->ID = 0;
timer->TimerToken = 0;
destroyed = 1;
}
this->Timers.erase(timerId);
return destroyed;
}
private:
vtkstd::map<int, vtkXTclTimer> Timers;
};
//-------------------------------------------------------------------------
static int vtkTclEventProc(XtPointer clientData, XEvent *event)
{
Boolean ctd;
vtkXOpenGLRenderWindow *rw;
rw = (vtkXOpenGLRenderWindow *)
(((vtkXRenderWindowTclInteractor *)clientData)->GetRenderWindow());
if (rw->GetWindowId() == (reinterpret_cast<XAnyEvent *>(event))->window)
{
vtkXRenderWindowInteractorCallback((Widget)NULL, clientData, event, &ctd);
ctd = 0;
}
else
{
ctd = 1;
}
return !ctd;
}
//-------------------------------------------------------------------------
vtkXRenderWindowTclInteractor::vtkXRenderWindowTclInteractor()
{
this->Internal = new vtkXRenderWindowTclInteractorInternals;
}
//-------------------------------------------------------------------------
vtkXRenderWindowTclInteractor::~vtkXRenderWindowTclInteractor()
{
if (this->Initialized)
{
Tk_DeleteGenericHandler((Tk_GenericProc *)vtkTclEventProc,
(ClientData)this);
}
delete this->Internal;
this->Internal = 0;
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Initialize()
{
if (this->Initialized)
{
return;
}
// make sure we have a RenderWindow
if (!this->RenderWindow)
{
vtkErrorMacro(<<"No RenderWindow defined!");
return;
}
this->Initialized = 1;
vtkXOpenGLRenderWindow* ren =
static_cast<vtkXOpenGLRenderWindow *>(this->RenderWindow);
// Use the same display as tcl/tk:
//
#if ((TK_MAJOR_VERSION <= 4)||((TK_MAJOR_VERSION == 8)&&(TK_MINOR_VERSION == 0)))
ren->SetDisplayId(Tk_Display(tkMainWindowList->winPtr));
#else
ren->SetDisplayId(Tk_Display(TkGetMainInfoList()->winPtr));
#endif
this->DisplayId = ren->GetDisplayId();
// Create a Tcl/Tk event handler:
//
Tk_CreateGenericHandler((Tk_GenericProc *)vtkTclEventProc, (ClientData)this);
ren->Start();
this->WindowId = ren->GetWindowId();
int* size = ren->GetSize();
this->Size[0] = size[0];
this->Size[1] = size[1];
this->Enable();
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Initialize(XtAppContext app)
{
this->Superclass::Initialize(app);
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Enable()
{
// avoid cycles of calling Initialize() and Enable()
if (this->Enabled)
{
return;
}
// Select the events that we want to respond to
// (Multiple calls to XSelectInput overrides the previous settings)
XSelectInput(this->DisplayId, this->WindowId,
KeyPressMask | KeyReleaseMask |
ButtonPressMask | ButtonReleaseMask |
ExposureMask | StructureNotifyMask |
EnterWindowMask | LeaveWindowMask |
PointerMotionMask | PointerMotionMask);
// Setup for capturing the window deletion
this->KillAtom = XInternAtom(this->DisplayId,"WM_DELETE_WINDOW",False);
XSetWMProtocols(this->DisplayId,this->WindowId,&this->KillAtom,1);
this->Enabled = 1;
this->Modified();
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Disable()
{
if (!this->Enabled)
{
return;
}
// Remove the all the events that we registered for EXCEPT for
// StructureNotifyMask event since we need to keep track of the window
// size (we will not render if we are disabled, we simply track the window
// size changes for a possible Enable()). Expose events are disabled.
// (Multiple calls to XSelectInput overrides the previous settings)
XSelectInput(this->DisplayId,this->WindowId,
StructureNotifyMask );
this->Enabled = 0;
this->Modified();
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Start()
{
// Let the compositing handle the event loop if it wants to.
if (this->HasObserver(vtkCommand::StartEvent) && !this->HandleEventLoop)
{
this->InvokeEvent(vtkCommand::StartEvent, NULL);
return;
}
if (!this->Initialized)
{
this->Initialize();
}
if (!this->Initialized)
{
return;
}
unsigned long ExitTag = this->AddObserver(vtkCommand::ExitEvent, this->BreakXtLoopCallback);
this->BreakLoopFlag = 0;
do
{
Tk_DoOneEvent(0);
}
while (this->BreakLoopFlag == 0);
this->RemoveObserver(ExitTag);
}
//-------------------------------------------------------------------------
int vtkXRenderWindowTclInteractor::InternalCreateTimer(int timerId,
int vtkNotUsed(timerType),
unsigned long duration)
{
duration = (duration > 0 ? duration : this->TimerDuration);
vtkXTclTimer* timer = this->Internal->CreateTimer(this, timerId, duration);
return timer->ID;
}
//-------------------------------------------------------------------------
int vtkXRenderWindowTclInteractor::InternalDestroyTimer(int platformTimerId)
{
return this->Internal->DestroyTimer(platformTimerId);
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkXRenderWindowTclInteractor.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkXRenderWindowTclInteractor.h"
#include "vtkCallbackCommand.h"
#include "vtkCommand.h"
#include "vtkObjectFactory.h"
#include "vtkXOpenGLRenderWindow.h"
#include <vtksys/stl/map>
#include <vtkTk.h>
//-------------------------------------------------------------------------
vtkCxxRevisionMacro(vtkXRenderWindowTclInteractor, "1.56");
vtkStandardNewMacro(vtkXRenderWindowTclInteractor);
//-------------------------------------------------------------------------
// steal the first three elements of the TkMainInfo stuct
// we don't care about the rest of the elements.
struct TkMainInfo
{
int refCount;
struct TkWindow *winPtr;
Tcl_Interp *interp;
};
#if ((TK_MAJOR_VERSION <= 4)||((TK_MAJOR_VERSION == 8)&&(TK_MINOR_VERSION == 0)))
extern TkMainInfo *tkMainWindowList;
#else
extern "C" {TkMainInfo *TkGetMainInfoList();}
#endif
//-------------------------------------------------------------------------
class vtkXTclTimer
{
public:
vtkXTclTimer()
{
this->Interactor = 0;
this->ID = 0;
this->TimerToken = 0;
}
vtkRenderWindowInteractor *Interactor;
int ID;
Tcl_TimerToken TimerToken;
};
//-------------------------------------------------------------------------
void vtkXTclTimerProc(ClientData clientData)
{
vtkXTclTimer* timer = static_cast<vtkXTclTimer*>(clientData);
vtkXRenderWindowTclInteractor* me =
static_cast<vtkXRenderWindowTclInteractor*>(timer->Interactor);
int platformTimerId = timer->ID;
int timerId = me->GetVTKTimerId(platformTimerId);
if (me->GetEnabled())
{
me->InvokeEvent(vtkCommand::TimerEvent, &timerId);
}
if (!me->IsOneShotTimer(timerId))
{
me->ResetTimer(timerId);
}
}
//-------------------------------------------------------------------------
// Map between the Tcl native timer token to our own int id. Note this
// is separate from the TimerMap in the vtkRenderWindowInteractor
// superclass. This is used to avoid passing 64-bit values back
// through the "int" return type of InternalCreateTimer.
class vtkXRenderWindowTclInteractorInternals
{
public:
vtkXTclTimer* CreateTimer(vtkRenderWindowInteractor* iren,
int timerId, unsigned long duration)
{
vtkXTclTimer* timer = &this->Timers[timerId];
timer->Interactor = iren;
timer->ID = timerId;
timer->TimerToken = Tcl_CreateTimerHandler(duration, vtkXTclTimerProc,
(ClientData) timer);
return timer;
}
int DestroyTimer(int timerId)
{
int destroyed = 0;
vtkXTclTimer* timer = &this->Timers[timerId];
if (0 != timer->ID)
{
Tcl_DeleteTimerHandler(timer->TimerToken);
timer->Interactor = 0;
timer->ID = 0;
timer->TimerToken = 0;
destroyed = 1;
}
this->Timers.erase(timerId);
return destroyed;
}
private:
vtkstd::map<int, vtkXTclTimer> Timers;
};
//-------------------------------------------------------------------------
static int vtkTclEventProc(XtPointer clientData, XEvent *event)
{
Boolean ctd;
vtkXOpenGLRenderWindow *rw;
rw = (vtkXOpenGLRenderWindow *)
(((vtkXRenderWindowTclInteractor *)clientData)->GetRenderWindow());
if (rw->GetWindowId() == (reinterpret_cast<XAnyEvent *>(event))->window)
{
vtkXRenderWindowInteractorCallback((Widget)NULL, clientData, event, &ctd);
ctd = 0;
}
else
{
ctd = 1;
}
return !ctd;
}
//-------------------------------------------------------------------------
vtkXRenderWindowTclInteractor::vtkXRenderWindowTclInteractor()
{
this->Internal = new vtkXRenderWindowTclInteractorInternals;
}
//-------------------------------------------------------------------------
vtkXRenderWindowTclInteractor::~vtkXRenderWindowTclInteractor()
{
if (this->Initialized)
{
Tk_DeleteGenericHandler((Tk_GenericProc *)vtkTclEventProc,
(ClientData)this);
}
delete this->Internal;
this->Internal = 0;
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Initialize()
{
if (this->Initialized)
{
return;
}
// make sure we have a RenderWindow
if (!this->RenderWindow)
{
vtkErrorMacro(<<"No RenderWindow defined!");
return;
}
this->Initialized = 1;
vtkXOpenGLRenderWindow* ren =
static_cast<vtkXOpenGLRenderWindow *>(this->RenderWindow);
// Use the same display as tcl/tk:
//
#if ((TK_MAJOR_VERSION <= 4)||((TK_MAJOR_VERSION == 8)&&(TK_MINOR_VERSION == 0)))
ren->SetDisplayId(Tk_Display(tkMainWindowList->winPtr));
#else
ren->SetDisplayId(Tk_Display(TkGetMainInfoList()->winPtr));
#endif
this->DisplayId = ren->GetDisplayId();
// Create a Tcl/Tk event handler:
//
Tk_CreateGenericHandler((Tk_GenericProc *)vtkTclEventProc, (ClientData)this);
ren->Start();
this->WindowId = ren->GetWindowId();
int* size = ren->GetSize();
this->Size[0] = size[0];
this->Size[1] = size[1];
this->Enable();
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Initialize(XtAppContext app)
{
this->Superclass::Initialize(app);
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Enable()
{
// avoid cycles of calling Initialize() and Enable()
if (this->Enabled)
{
return;
}
// Select the events that we want to respond to
// (Multiple calls to XSelectInput overrides the previous settings)
XSelectInput(this->DisplayId, this->WindowId,
KeyPressMask | KeyReleaseMask |
ButtonPressMask | ButtonReleaseMask |
ExposureMask | StructureNotifyMask |
EnterWindowMask | LeaveWindowMask |
PointerMotionMask | PointerMotionMask);
// Setup for capturing the window deletion
this->KillAtom = XInternAtom(this->DisplayId,"WM_DELETE_WINDOW",False);
XSetWMProtocols(this->DisplayId,this->WindowId,&this->KillAtom,1);
this->Enabled = 1;
this->Modified();
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Disable()
{
if (!this->Enabled)
{
return;
}
// Remove the all the events that we registered for EXCEPT for
// StructureNotifyMask event since we need to keep track of the window
// size (we will not render if we are disabled, we simply track the window
// size changes for a possible Enable()). Expose events are disabled.
// (Multiple calls to XSelectInput overrides the previous settings)
XSelectInput(this->DisplayId,this->WindowId,
StructureNotifyMask );
this->Enabled = 0;
this->Modified();
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Start()
{
// Let the compositing handle the event loop if it wants to.
if (this->HasObserver(vtkCommand::StartEvent) && !this->HandleEventLoop)
{
this->InvokeEvent(vtkCommand::StartEvent, NULL);
return;
}
if (!this->Initialized)
{
this->Initialize();
}
if (!this->Initialized)
{
return;
}
unsigned long ExitTag = this->AddObserver(vtkCommand::ExitEvent, this->BreakXtLoopCallback);
this->BreakLoopFlag = 0;
do
{
Tk_DoOneEvent(0);
}
while (this->BreakLoopFlag == 0);
this->RemoveObserver(ExitTag);
}
//-------------------------------------------------------------------------
int vtkXRenderWindowTclInteractor::InternalCreateTimer(int timerId,
int vtkNotUsed(timerType),
unsigned long duration)
{
duration = (duration > 0 ? duration : this->TimerDuration);
vtkXTclTimer* timer = this->Internal->CreateTimer(this, timerId, duration);
return timer->ID;
}
//-------------------------------------------------------------------------
int vtkXRenderWindowTclInteractor::InternalDestroyTimer(int platformTimerId)
{
return this->Internal->DestroyTimer(platformTimerId);
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
<commit_msg>COMP:Fixed warning on SunOS Warning (Anachronism): Formal argument proc of type extern C void(*)(void*) in call to Tcl_CreateTimerHandler(int, extern C void(*)(void*), void*) is being passed void(*)(void*) . Fixed other conversion or old-style cast warnings.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkXRenderWindowTclInteractor.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkXRenderWindowTclInteractor.h"
#include "vtkCallbackCommand.h"
#include "vtkCommand.h"
#include "vtkObjectFactory.h"
#include "vtkXOpenGLRenderWindow.h"
#include <vtksys/stl/map>
#include <vtkTk.h>
//-------------------------------------------------------------------------
vtkCxxRevisionMacro(vtkXRenderWindowTclInteractor, "1.57");
vtkStandardNewMacro(vtkXRenderWindowTclInteractor);
//-------------------------------------------------------------------------
// steal the first three elements of the TkMainInfo stuct
// we don't care about the rest of the elements.
struct TkMainInfo
{
int refCount;
struct TkWindow *winPtr;
Tcl_Interp *interp;
};
#if ((TK_MAJOR_VERSION <= 4)||((TK_MAJOR_VERSION == 8)&&(TK_MINOR_VERSION == 0)))
extern TkMainInfo *tkMainWindowList;
#else
extern "C" {TkMainInfo *TkGetMainInfoList();}
#endif
//-------------------------------------------------------------------------
class vtkXTclTimer
{
public:
vtkXTclTimer()
{
this->Interactor = 0;
this->ID = 0;
this->TimerToken = 0;
}
vtkRenderWindowInteractor *Interactor;
int ID;
Tcl_TimerToken TimerToken;
};
//-------------------------------------------------------------------------
extern "C" void vtkXTclTimerProc(ClientData clientData)
{
vtkXTclTimer* timer = static_cast<vtkXTclTimer*>(clientData);
vtkXRenderWindowTclInteractor* me =
static_cast<vtkXRenderWindowTclInteractor*>(timer->Interactor);
int platformTimerId = timer->ID;
int timerId = me->GetVTKTimerId(platformTimerId);
if (me->GetEnabled())
{
me->InvokeEvent(vtkCommand::TimerEvent, &timerId);
}
if (!me->IsOneShotTimer(timerId))
{
me->ResetTimer(timerId);
}
}
//-------------------------------------------------------------------------
// Map between the Tcl native timer token to our own int id. Note this
// is separate from the TimerMap in the vtkRenderWindowInteractor
// superclass. This is used to avoid passing 64-bit values back
// through the "int" return type of InternalCreateTimer.
class vtkXRenderWindowTclInteractorInternals
{
public:
vtkXTclTimer* CreateTimer(vtkRenderWindowInteractor* iren,
int timerId, unsigned long duration)
{
vtkXTclTimer* timer = &this->Timers[timerId];
timer->Interactor = iren;
timer->ID = timerId;
timer->TimerToken = Tcl_CreateTimerHandler(static_cast<int>(duration),
vtkXTclTimerProc,
static_cast<ClientData>(timer));
return timer;
}
int DestroyTimer(int timerId)
{
int destroyed = 0;
vtkXTclTimer* timer = &this->Timers[timerId];
if (0 != timer->ID)
{
Tcl_DeleteTimerHandler(timer->TimerToken);
timer->Interactor = 0;
timer->ID = 0;
timer->TimerToken = 0;
destroyed = 1;
}
this->Timers.erase(timerId);
return destroyed;
}
private:
vtkstd::map<int, vtkXTclTimer> Timers;
};
//-------------------------------------------------------------------------
static int vtkTclEventProc(XtPointer clientData, XEvent *event)
{
Boolean ctd;
vtkXOpenGLRenderWindow *rw;
rw = static_cast<vtkXOpenGLRenderWindow *>
(static_cast<vtkXRenderWindowTclInteractor *>(
clientData)->GetRenderWindow());
if (rw->GetWindowId() == (reinterpret_cast<XAnyEvent *>(event))->window)
{
vtkXRenderWindowInteractorCallback(static_cast<Widget>(NULL), clientData,
event, &ctd);
ctd = 0;
}
else
{
ctd = 1;
}
return !ctd;
}
//-------------------------------------------------------------------------
vtkXRenderWindowTclInteractor::vtkXRenderWindowTclInteractor()
{
this->Internal = new vtkXRenderWindowTclInteractorInternals;
}
//-------------------------------------------------------------------------
vtkXRenderWindowTclInteractor::~vtkXRenderWindowTclInteractor()
{
if (this->Initialized)
{
Tk_DeleteGenericHandler(static_cast<Tk_GenericProc *>(vtkTclEventProc),
static_cast<ClientData>(this));
}
delete this->Internal;
this->Internal = 0;
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Initialize()
{
if (this->Initialized)
{
return;
}
// make sure we have a RenderWindow
if (!this->RenderWindow)
{
vtkErrorMacro(<<"No RenderWindow defined!");
return;
}
this->Initialized = 1;
vtkXOpenGLRenderWindow* ren =
static_cast<vtkXOpenGLRenderWindow *>(this->RenderWindow);
// Use the same display as tcl/tk:
//
#if ((TK_MAJOR_VERSION <= 4)||((TK_MAJOR_VERSION == 8)&&(TK_MINOR_VERSION == 0)))
ren->SetDisplayId(Tk_Display(tkMainWindowList->winPtr));
#else
ren->SetDisplayId(Tk_Display(TkGetMainInfoList()->winPtr));
#endif
this->DisplayId = ren->GetDisplayId();
// Create a Tcl/Tk event handler:
//
Tk_CreateGenericHandler(static_cast<Tk_GenericProc *>(vtkTclEventProc),
static_cast<ClientData>(this));
ren->Start();
this->WindowId = ren->GetWindowId();
int* size = ren->GetSize();
this->Size[0] = size[0];
this->Size[1] = size[1];
this->Enable();
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Initialize(XtAppContext app)
{
this->Superclass::Initialize(app);
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Enable()
{
// avoid cycles of calling Initialize() and Enable()
if (this->Enabled)
{
return;
}
// Select the events that we want to respond to
// (Multiple calls to XSelectInput overrides the previous settings)
XSelectInput(this->DisplayId, this->WindowId,
KeyPressMask | KeyReleaseMask |
ButtonPressMask | ButtonReleaseMask |
ExposureMask | StructureNotifyMask |
EnterWindowMask | LeaveWindowMask |
PointerMotionMask | PointerMotionMask);
// Setup for capturing the window deletion
this->KillAtom = XInternAtom(this->DisplayId,"WM_DELETE_WINDOW",False);
XSetWMProtocols(this->DisplayId,this->WindowId,&this->KillAtom,1);
this->Enabled = 1;
this->Modified();
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Disable()
{
if (!this->Enabled)
{
return;
}
// Remove the all the events that we registered for EXCEPT for
// StructureNotifyMask event since we need to keep track of the window
// size (we will not render if we are disabled, we simply track the window
// size changes for a possible Enable()). Expose events are disabled.
// (Multiple calls to XSelectInput overrides the previous settings)
XSelectInput(this->DisplayId,this->WindowId,
StructureNotifyMask );
this->Enabled = 0;
this->Modified();
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::Start()
{
// Let the compositing handle the event loop if it wants to.
if (this->HasObserver(vtkCommand::StartEvent) && !this->HandleEventLoop)
{
this->InvokeEvent(vtkCommand::StartEvent, NULL);
return;
}
if (!this->Initialized)
{
this->Initialize();
}
if (!this->Initialized)
{
return;
}
unsigned long ExitTag = this->AddObserver(vtkCommand::ExitEvent, this->BreakXtLoopCallback);
this->BreakLoopFlag = 0;
do
{
Tk_DoOneEvent(0);
}
while (this->BreakLoopFlag == 0);
this->RemoveObserver(ExitTag);
}
//-------------------------------------------------------------------------
int vtkXRenderWindowTclInteractor::InternalCreateTimer(int timerId,
int vtkNotUsed(timerType),
unsigned long duration)
{
duration = (duration > 0 ? duration : this->TimerDuration);
vtkXTclTimer* timer = this->Internal->CreateTimer(this, timerId, duration);
return timer->ID;
}
//-------------------------------------------------------------------------
int vtkXRenderWindowTclInteractor::InternalDestroyTimer(int platformTimerId)
{
return this->Internal->DestroyTimer(platformTimerId);
}
//-------------------------------------------------------------------------
void vtkXRenderWindowTclInteractor::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
<|endoftext|> |
<commit_before>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#include "webkit/glue/npruntime_util.h"
// Import the definition of PrivateIdentifier
#if USE(V8_BINDING)
#include "webkit/port/bindings/v8/np_v8object.h"
#elif USE(JAVASCRIPTCORE_BINDINGS)
#include "c_utility.h"
#endif
#include "base/pickle.h"
namespace webkit_glue {
bool SerializeNPIdentifier(NPIdentifier identifier, Pickle* pickle) {
PrivateIdentifier* priv = static_cast<PrivateIdentifier*>(identifier);
// If the identifier was null, then we just send a numeric 0. This is to
// support cases where the other end doesn't care about the NPIdentifier
// being serialized, so the bogus value of 0 is really inconsequential.
PrivateIdentifier null_id;
if (!priv) {
priv = &null_id;
priv->isString = false;
priv->value.number = 0;
}
if (!pickle->WriteBool(priv->isString))
return false;
if (priv->isString) {
// Write the null byte for efficiency on the other end.
return pickle->WriteData(
priv->value.string, strlen(priv->value.string) + 1);
}
return pickle->WriteInt(priv->value.number);
}
bool DeserializeNPIdentifier(const Pickle& pickle, void** pickle_iter,
NPIdentifier* identifier) {
bool is_string;
if (!pickle.ReadBool(pickle_iter, &is_string))
return false;
if (is_string) {
const char* data;
int data_len;
if (!pickle.ReadData(pickle_iter, &data, &data_len))
return false;
DCHECK_EQ(data_len, strlen(data) + 1);
*identifier = NPN_GetStringIdentifier(data);
} else {
int number;
if (!pickle.ReadInt(pickle_iter, &number))
return false;
*identifier = NPN_GetIntIdentifier(number);
}
return true;
}
} // namespace webkit_glue
<commit_msg>fix kjs build<commit_after>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#include "webkit/glue/npruntime_util.h"
// Import the definition of PrivateIdentifier
#if USE(V8_BINDING)
#include "webkit/port/bindings/v8/np_v8object.h"
#elif USE(JAVASCRIPTCORE_BINDINGS)
#include "c/c_utility.h"
#endif
#include "base/pickle.h"
namespace webkit_glue {
bool SerializeNPIdentifier(NPIdentifier identifier, Pickle* pickle) {
PrivateIdentifier* priv = static_cast<PrivateIdentifier*>(identifier);
// If the identifier was null, then we just send a numeric 0. This is to
// support cases where the other end doesn't care about the NPIdentifier
// being serialized, so the bogus value of 0 is really inconsequential.
PrivateIdentifier null_id;
if (!priv) {
priv = &null_id;
priv->isString = false;
priv->value.number = 0;
}
if (!pickle->WriteBool(priv->isString))
return false;
if (priv->isString) {
// Write the null byte for efficiency on the other end.
return pickle->WriteData(
priv->value.string, strlen(priv->value.string) + 1);
}
return pickle->WriteInt(priv->value.number);
}
bool DeserializeNPIdentifier(const Pickle& pickle, void** pickle_iter,
NPIdentifier* identifier) {
bool is_string;
if (!pickle.ReadBool(pickle_iter, &is_string))
return false;
if (is_string) {
const char* data;
int data_len;
if (!pickle.ReadData(pickle_iter, &data, &data_len))
return false;
DCHECK_EQ(data_len, strlen(data) + 1);
*identifier = NPN_GetStringIdentifier(data);
} else {
int number;
if (!pickle.ReadInt(pickle_iter, &number))
return false;
*identifier = NPN_GetIntIdentifier(number);
}
return true;
}
} // namespace webkit_glue
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2006 Justin Karneges
*
* 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
*
*/
// this code assumes the following ioctls work:
// SIOCGIFCONF - get list of devices
// SIOCGIFFLAGS - get flags about a device
// gateway detection currently only works on linux
#include "irisnetplugin.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/route.h>
#include <netinet/in.h>
#include <errno.h>
// for solaris
#ifndef SIOCGIFCONF
# include<sys/sockio.h>
#endif
class UnixIface
{
public:
QString name;
bool loopback;
QHostAddress address;
};
class UnixGateway
{
public:
QString ifaceName;
QHostAddress address;
};
static QList<UnixIface> get_sioc_ifaces()
{
QList<UnixIface> out;
int tmpsock = socket(AF_INET, SOCK_DGRAM, 0);
if(tmpsock < 0)
return out;
struct ifconf ifc;
int lastlen = 0;
QByteArray buf(100 * sizeof(struct ifreq), 0); // guess
while(1)
{
ifc.ifc_len = buf.size();
ifc.ifc_buf = buf.data();
if(ioctl(tmpsock, SIOCGIFCONF, &ifc) < 0)
{
if(errno != EINVAL || lastlen != 0)
return out;
}
else
{
// if it didn't grow since last time, then
// there's no overflow
if(ifc.ifc_len == lastlen)
break;
lastlen = ifc.ifc_len;
}
buf.resize(buf.size() + 10 * sizeof(struct ifreq));
}
buf.resize(lastlen);
int itemsize;
for(int at = 0; at < buf.size(); at += itemsize)
{
struct ifreq *ifr = (struct ifreq *)(buf.data() + at);
int sockaddr_len;
if(((struct sockaddr *)&ifr->ifr_addr)->sa_family == AF_INET)
sockaddr_len = sizeof(struct sockaddr_in);
else if(((struct sockaddr *)&ifr->ifr_addr)->sa_family == AF_INET6)
sockaddr_len = sizeof(struct sockaddr_in6);
else
sockaddr_len = sizeof(struct sockaddr);
// set this asap so the next iteration is possible
itemsize = sizeof(ifr->ifr_name) + sockaddr_len;
// skip if the family is 0 (sometimes you get empty entries)
if(ifr->ifr_addr.sa_family == 0)
continue;
// make a copy of this item to do additional ioctls on
struct ifreq ifrcopy = *ifr;
// grab the flags
if(ioctl(tmpsock, SIOCGIFFLAGS, &ifrcopy) < 0)
continue;
// device must be up and not loopback
if(!(ifrcopy.ifr_flags & IFF_UP))
continue;
UnixIface i;
i.name = QString::fromLatin1(ifr->ifr_name);
i.loopback = (ifrcopy.ifr_flags & IFF_LOOPBACK) ? true : false;
i.address.setAddress(&ifr->ifr_addr);
out += i;
}
// don't need this anymore
close(tmpsock);
return out;
}
#ifdef Q_OS_LINUX
static QStringList read_proc_as_lines(const char *procfile)
{
QStringList out;
FILE *f = fopen(procfile, "r");
if(!f)
return out;
QByteArray buf;
while(!feof(f))
{
// max read on a proc is 4K
QByteArray block(4096, 0);
int ret = fread(block.data(), 1, block.size(), f);
if(ret <= 0)
break;
block.resize(ret);
buf += block;
}
fclose(f);
QString str = QString::fromLocal8Bit(buf);
out = str.split('\n', QString::SkipEmptyParts);
return out;
}
static QHostAddress linux_ipv6_to_qaddr(const QString &in)
{
QHostAddress out;
if(in.length() != 32)
return out;
quint8 raw[16];
for(int n = 0; n < 16; ++n)
{
bool ok;
int x = in.mid(n * 2, 2).toInt(&ok, 16);
if(!ok)
return out;
raw[n] = (quint8)x;
}
out.setAddress(raw);
return out;
}
static QHostAddress linux_ipv4_to_qaddr(const QString &in)
{
QHostAddress out;
if(in.length() != 8)
return out;
quint32 raw;
unsigned char *rawp = (unsigned char *)&raw;
for(int n = 0; n < 4; ++n)
{
bool ok;
int x = in.mid(n * 2, 2).toInt(&ok, 16);
if(!ok)
return out;
rawp[n] = (unsigned char )x;
}
out.setAddress(raw);
return out;
}
static QList<UnixIface> get_linux_ipv6_ifaces()
{
QList<UnixIface> out;
QStringList lines = read_proc_as_lines("/proc/net/if_inet6");
for(int n = 0; n < lines.count(); ++n)
{
const QString &line = lines[n];
QStringList parts = line.simplified().split(' ', QString::SkipEmptyParts);
if(parts.count() < 6)
continue;
QString name = parts[5];
if(name.isEmpty())
continue;
QHostAddress addr = linux_ipv6_to_qaddr(parts[0]);
if(addr.isNull())
continue;
QString scopestr = parts[3];
bool ok;
unsigned int scope = parts[3].toInt(&ok, 16);
if(!ok)
continue;
// IPV6_ADDR_LOOPBACK 0x0010U
// IPV6_ADDR_SCOPE_MASK 0x00f0U
bool loopback = false;
if((scope & 0x00f0U) == 0x0010U)
loopback = true;
UnixIface i;
i.name = name;
i.loopback = loopback;
i.address = addr;
out += i;
}
return out;
}
static QList<UnixGateway> get_linux_gateways()
{
QList<UnixGateway> out;
QStringList lines = read_proc_as_lines("/proc/net/route");
// skip the first line, so we start at 1
for(int n = 1; n < lines.count(); ++n)
{
const QString &line = lines[n];
QStringList parts = line.simplified().split(' ', QString::SkipEmptyParts);
if(parts.count() < 10) // net-tools does 10, but why not 11?
continue;
QHostAddress addr = linux_ipv4_to_qaddr(parts[2]);
if(addr.isNull())
continue;
int iflags = parts[3].toInt(0, 16);
if(!(iflags & RTF_UP))
continue;
if(!(iflags & RTF_GATEWAY))
continue;
UnixGateway g;
g.ifaceName = parts[0];
g.address = addr;
out += g;
}
lines = read_proc_as_lines("/proc/net/ipv6_route");
for(int n = 0; n < lines.count(); ++n)
{
const QString &line = lines[n];
QStringList parts = line.simplified().split(' ', QString::SkipEmptyParts);
if(parts.count() < 10)
continue;
QHostAddress addr = linux_ipv6_to_qaddr(parts[4]);
if(addr.isNull())
continue;
int iflags = parts[8].toInt(0, 16);
if(!(iflags & RTF_UP))
continue;
if(!(iflags & RTF_GATEWAY))
continue;
UnixGateway g;
g.ifaceName = parts[9];
g.address = addr;
out += g;
}
return out;
}
#endif
static QList<UnixIface> get_unix_ifaces()
{
QList<UnixIface> out = get_sioc_ifaces();
#ifdef Q_OS_LINUX
out += get_linux_ipv6_ifaces();
#endif
return out;
}
static QList<UnixGateway> get_unix_gateways()
{
// support other platforms here
QList<UnixGateway> out;
#ifdef Q_OS_LINUX
out = get_linux_gateways();
#endif
return out;
}
namespace XMPP {
class UnixNet : public NetInterfaceProvider
{
Q_OBJECT
Q_INTERFACES(XMPP::NetInterfaceProvider);
public:
QList<Info> info;
QTimer t;
UnixNet() : t(this)
{
connect(&t, SIGNAL(timeout()), SLOT(check()));
}
void start()
{
t.start(5000);
poll();
}
QList<Info> interfaces() const
{
return info;
}
void poll()
{
QList<Info> ifaces;
QList<UnixIface> list = get_unix_ifaces();
for(int n = 0; n < list.count(); ++n)
{
// see if we have it already
int lookup = -1;
for(int k = 0; k < ifaces.count(); ++k)
{
if(ifaces[k].id == list[n].name)
{
lookup = k;
break;
}
}
// don't have it? make it
if(lookup == -1)
{
Info i;
i.id = list[n].name;
i.name = list[n].name;
i.isLoopback = list[n].loopback;
i.addresses += list[n].address;
ifaces += i;
}
// otherwise, tack on the address
else
ifaces[lookup].addresses += list[n].address;
}
QList<UnixGateway> glist = get_unix_gateways();
for(int n = 0; n < glist.count(); ++n)
{
// look up the interface
int lookup = -1;
for(int k = 0; k < ifaces.count(); ++k)
{
if(ifaces[k].id == glist[n].ifaceName)
{
lookup = k;
break;
}
}
if(lookup == -1)
break;
ifaces[lookup].gateway = glist[n].address;
}
info = ifaces;
}
public slots:
void check()
{
poll();
emit updated();
}
};
class UnixNetProvider : public IrisNetProvider
{
Q_OBJECT
Q_INTERFACES(XMPP::IrisNetProvider);
public:
virtual NetInterfaceProvider *createNetInterfaceProvider()
{
return new UnixNet;
}
};
IrisNetProvider *irisnet_createUnixNetProvider()
{
return new UnixNetProvider;
}
}
#include "netinterface_unix.moc"
<commit_msg>netinterface_unix.cpp: Fix code on linux for interfaces with ipv6 addresses. Linux seems to use a static record size for all AF_*:s.<commit_after>/*
* Copyright (C) 2006 Justin Karneges
*
* 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
*
*/
// this code assumes the following ioctls work:
// SIOCGIFCONF - get list of devices
// SIOCGIFFLAGS - get flags about a device
// gateway detection currently only works on linux
#include "irisnetplugin.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/route.h>
#include <netinet/in.h>
#include <errno.h>
// for solaris
#ifndef SIOCGIFCONF
# include<sys/sockio.h>
#endif
class UnixIface
{
public:
QString name;
bool loopback;
QHostAddress address;
};
class UnixGateway
{
public:
QString ifaceName;
QHostAddress address;
};
static QList<UnixIface> get_sioc_ifaces()
{
QList<UnixIface> out;
int tmpsock = socket(AF_INET, SOCK_DGRAM, 0);
if(tmpsock < 0)
return out;
struct ifconf ifc;
int lastlen = 0;
QByteArray buf(100 * sizeof(struct ifreq), 0); // guess
while(1)
{
ifc.ifc_len = buf.size();
ifc.ifc_buf = buf.data();
if(ioctl(tmpsock, SIOCGIFCONF, &ifc) < 0)
{
if(errno != EINVAL || lastlen != 0)
return out;
}
else
{
// if it didn't grow since last time, then
// there's no overflow
if(ifc.ifc_len == lastlen)
break;
lastlen = ifc.ifc_len;
}
buf.resize(buf.size() + 10 * sizeof(struct ifreq));
}
buf.resize(lastlen);
int itemsize;
for(int at = 0; at < buf.size(); at += itemsize)
{
struct ifreq *ifr = (struct ifreq *)(buf.data() + at);
int sockaddr_len;
#ifndef Q_OS_LINUX
if(((struct sockaddr *)&ifr->ifr_addr)->sa_family == AF_INET) {
sockaddr_len = sizeof(struct sockaddr_in);
} else if(((struct sockaddr *)&ifr->ifr_addr)->sa_family == AF_INET6) {
sockaddr_len = sizeof(struct sockaddr_in6);
} else {
sockaddr_len = sizeof(struct sockaddr);
}
// set this asap so the next iteration is possible
itemsize = sizeof(ifr->ifr_name) + sockaddr_len;
#else
itemsize = sizeof(ifreq);
#endif
// skip if the family is 0 (sometimes you get empty entries)
if(ifr->ifr_addr.sa_family == 0)
continue;
// make a copy of this item to do additional ioctls on
struct ifreq ifrcopy = *ifr;
// grab the flags
if(ioctl(tmpsock, SIOCGIFFLAGS, &ifrcopy) < 0)
continue;
// device must be up and not loopback
if(!(ifrcopy.ifr_flags & IFF_UP))
continue;
UnixIface i;
i.name = QString::fromLatin1(ifr->ifr_name);
i.loopback = (ifrcopy.ifr_flags & IFF_LOOPBACK) ? true : false;
i.address.setAddress(&ifr->ifr_addr);
out += i;
}
// don't need this anymore
close(tmpsock);
return out;
}
#ifdef Q_OS_LINUX
static QStringList read_proc_as_lines(const char *procfile)
{
QStringList out;
FILE *f = fopen(procfile, "r");
if(!f)
return out;
QByteArray buf;
while(!feof(f))
{
// max read on a proc is 4K
QByteArray block(4096, 0);
int ret = fread(block.data(), 1, block.size(), f);
if(ret <= 0)
break;
block.resize(ret);
buf += block;
}
fclose(f);
QString str = QString::fromLocal8Bit(buf);
out = str.split('\n', QString::SkipEmptyParts);
return out;
}
static QHostAddress linux_ipv6_to_qaddr(const QString &in)
{
QHostAddress out;
if(in.length() != 32)
return out;
quint8 raw[16];
for(int n = 0; n < 16; ++n)
{
bool ok;
int x = in.mid(n * 2, 2).toInt(&ok, 16);
if(!ok)
return out;
raw[n] = (quint8)x;
}
out.setAddress(raw);
return out;
}
static QHostAddress linux_ipv4_to_qaddr(const QString &in)
{
QHostAddress out;
if(in.length() != 8)
return out;
quint32 raw;
unsigned char *rawp = (unsigned char *)&raw;
for(int n = 0; n < 4; ++n)
{
bool ok;
int x = in.mid(n * 2, 2).toInt(&ok, 16);
if(!ok)
return out;
rawp[n] = (unsigned char )x;
}
out.setAddress(raw);
return out;
}
static QList<UnixIface> get_linux_ipv6_ifaces()
{
QList<UnixIface> out;
QStringList lines = read_proc_as_lines("/proc/net/if_inet6");
for(int n = 0; n < lines.count(); ++n)
{
const QString &line = lines[n];
QStringList parts = line.simplified().split(' ', QString::SkipEmptyParts);
if(parts.count() < 6)
continue;
QString name = parts[5];
if(name.isEmpty())
continue;
QHostAddress addr = linux_ipv6_to_qaddr(parts[0]);
if(addr.isNull())
continue;
QString scopestr = parts[3];
bool ok;
unsigned int scope = parts[3].toInt(&ok, 16);
if(!ok)
continue;
// IPV6_ADDR_LOOPBACK 0x0010U
// IPV6_ADDR_SCOPE_MASK 0x00f0U
bool loopback = false;
if((scope & 0x00f0U) == 0x0010U)
loopback = true;
UnixIface i;
i.name = name;
i.loopback = loopback;
i.address = addr;
out += i;
}
return out;
}
static QList<UnixGateway> get_linux_gateways()
{
QList<UnixGateway> out;
QStringList lines = read_proc_as_lines("/proc/net/route");
// skip the first line, so we start at 1
for(int n = 1; n < lines.count(); ++n)
{
const QString &line = lines[n];
QStringList parts = line.simplified().split(' ', QString::SkipEmptyParts);
if(parts.count() < 10) // net-tools does 10, but why not 11?
continue;
QHostAddress addr = linux_ipv4_to_qaddr(parts[2]);
if(addr.isNull())
continue;
int iflags = parts[3].toInt(0, 16);
if(!(iflags & RTF_UP))
continue;
if(!(iflags & RTF_GATEWAY))
continue;
UnixGateway g;
g.ifaceName = parts[0];
g.address = addr;
out += g;
}
lines = read_proc_as_lines("/proc/net/ipv6_route");
for(int n = 0; n < lines.count(); ++n)
{
const QString &line = lines[n];
QStringList parts = line.simplified().split(' ', QString::SkipEmptyParts);
if(parts.count() < 10)
continue;
QHostAddress addr = linux_ipv6_to_qaddr(parts[4]);
if(addr.isNull())
continue;
int iflags = parts[8].toInt(0, 16);
if(!(iflags & RTF_UP))
continue;
if(!(iflags & RTF_GATEWAY))
continue;
UnixGateway g;
g.ifaceName = parts[9];
g.address = addr;
out += g;
}
return out;
}
#endif
static QList<UnixIface> get_unix_ifaces()
{
QList<UnixIface> out = get_sioc_ifaces();
#ifdef Q_OS_LINUX
out += get_linux_ipv6_ifaces();
#endif
return out;
}
static QList<UnixGateway> get_unix_gateways()
{
// support other platforms here
QList<UnixGateway> out;
#ifdef Q_OS_LINUX
out = get_linux_gateways();
#endif
return out;
}
namespace XMPP {
class UnixNet : public NetInterfaceProvider
{
Q_OBJECT
Q_INTERFACES(XMPP::NetInterfaceProvider);
public:
QList<Info> info;
QTimer t;
UnixNet() : t(this)
{
connect(&t, SIGNAL(timeout()), SLOT(check()));
}
void start()
{
t.start(5000);
poll();
}
QList<Info> interfaces() const
{
return info;
}
void poll()
{
QList<Info> ifaces;
QList<UnixIface> list = get_unix_ifaces();
for(int n = 0; n < list.count(); ++n)
{
// see if we have it already
int lookup = -1;
for(int k = 0; k < ifaces.count(); ++k)
{
if(ifaces[k].id == list[n].name)
{
lookup = k;
break;
}
}
// don't have it? make it
if(lookup == -1)
{
Info i;
i.id = list[n].name;
i.name = list[n].name;
i.isLoopback = list[n].loopback;
i.addresses += list[n].address;
ifaces += i;
}
// otherwise, tack on the address
else
ifaces[lookup].addresses += list[n].address;
}
QList<UnixGateway> glist = get_unix_gateways();
for(int n = 0; n < glist.count(); ++n)
{
// look up the interface
int lookup = -1;
for(int k = 0; k < ifaces.count(); ++k)
{
if(ifaces[k].id == glist[n].ifaceName)
{
lookup = k;
break;
}
}
if(lookup == -1)
break;
ifaces[lookup].gateway = glist[n].address;
}
info = ifaces;
}
public slots:
void check()
{
poll();
emit updated();
}
};
class UnixNetProvider : public IrisNetProvider
{
Q_OBJECT
Q_INTERFACES(XMPP::IrisNetProvider);
public:
virtual NetInterfaceProvider *createNetInterfaceProvider()
{
return new UnixNet;
}
};
IrisNetProvider *irisnet_createUnixNetProvider()
{
return new UnixNetProvider;
}
}
#include "netinterface_unix.moc"
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS pchfix02 (1.9.42); FILE MERGED 2006/09/01 17:54:58 kaib 1.9.42.1: #i68856# Added header markers and pch files<commit_after><|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, 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. *
**************************************************************************/
/* $Id$ */
/** @file AliFMDRawReader.cxx
@author Christian Holm Christensen <[email protected]>
@date Mon Mar 27 12:45:23 2006
@brief Class to read raw data
@ingroup FMD_rec
*/
//____________________________________________________________________
//
// Class to read ADC values from a AliRawReader object.
//
// This class uses the AliFMDRawStreamer class to read the ALTRO
// formatted data.
//
// +-------+
// | TTask |
// +-------+
// ^
// |
// +-----------------+ <<references>> +--------------+
// | AliFMDRawReader |<>----------------| AliRawReader |
// +-----------------+ +--------------+
// | ^
// | <<uses>> |
// V |
// +-----------------+ <<uses>> |
// | AliFMDRawStream |------------------------+
// +-----------------+
// |
// V
// +----------------+
// | AliAltroStream |
// +----------------+
//
// #include <AliLog.h> // ALILOG_H
#include "AliFMDDebug.h" // Better debug macros
#include "AliFMDParameters.h" // ALIFMDPARAMETERS_H
#include "AliFMDDigit.h" // ALIFMDDIGIT_H
#include "AliFMDRawStream.h" // ALIFMDRAWSTREAM_H
// #include "AliRawReader.h" // ALIRAWREADER_H
#include "AliFMDRawReader.h" // ALIFMDRAWREADER_H
// #include "AliFMDAltroIO.h" // ALIFMDALTROIO_H
// #include <TArrayI.h> // ROOT_TArrayI
#include <TTree.h> // ROOT_TTree
#include <TClonesArray.h> // ROOT_TClonesArray
// #include <iostream>
// #include <iomanip>
//____________________________________________________________________
ClassImp(AliFMDRawReader)
#if 0
; // This is here to keep Emacs for indenting the next line
#endif
//____________________________________________________________________
AliFMDRawReader::AliFMDRawReader(AliRawReader* reader, TTree* tree)
: TTask("FMDRawReader", "Reader of Raw ADC values from the FMD"),
fTree(tree),
fReader(reader),
fSampleRate(1)
{
// Default CTOR
}
//____________________________________________________________________
void
AliFMDRawReader::Exec(Option_t*)
{
// Read the data
TClonesArray* array = new TClonesArray("AliFMDDigit");
if (!fTree) {
AliError("No tree");
return;
}
fTree->Branch("FMD", &array);
ReadAdcs(array);
Int_t nWrite = fTree->Fill();
AliFMDDebug(1, ("Got a grand total of %d digits, wrote %d bytes to tree",
array->GetEntries(), nWrite));
}
#if 1
//____________________________________________________________________
Bool_t
AliFMDRawReader::ReadAdcs(TClonesArray* array)
{
// Read raw data into the digits array, using AliFMDAltroReader.
if (!array) {
AliError("No TClonesArray passed");
return kFALSE;
}
// if (!fReader->ReadHeader()) {
// AliError("Couldn't read header");
// return kFALSE;
// }
// Get sample rate
AliFMDParameters* pars = AliFMDParameters::Instance();
AliFMDRawStream input(fReader);
UShort_t stripMin = 0;
UShort_t stripMax = 127;
UShort_t preSamp = 0;
UInt_t ddl = 0;
UInt_t rate = 0;
UInt_t last = 0;
UInt_t hwaddr = 0;
// Data array is approx twice the size needed.
UShort_t data[2048];
Bool_t isGood = kTRUE;
while (isGood) {
isGood = input.ReadChannel(ddl, hwaddr, last, data);
AliFMDDebug(5, ("Read channel 0x%x of size %d", hwaddr, last));
UShort_t det, sec, str;
Char_t ring;
if (!pars->Hardware2Detector(ddl, hwaddr, det, ring, sec, str)) {
AliError(Form("Failed to get detector id from DDL %d "
"and hardware address 0x%x", ddl, hwaddr));
continue;
}
rate = pars->GetSampleRate(det, ring, sec, str);
stripMin = pars->GetMinStrip(det, ring, sec, str);
stripMax = pars->GetMaxStrip(det, ring, sec, str);
AliFMDDebug(5, ("DDL 0x%04x, address 0x%03x maps to FMD%d%c[%2d,%3d]",
ddl, hwaddr, det, ring, sec, str));
// Loop over the `timebins', and make the digits
for (size_t i = 0; i < last; i++) {
if (i < preSamp) continue;
Int_t n = array->GetEntriesFast();
UShort_t curStr = str + stripMin + i / rate;
if ((curStr-str) > stripMax) {
AliError(Form("Current strip is %d but DB says max is %d",
curStr, stripMax));
}
AliFMDDebug(5, ("making digit for FMD%d%c[%2d,%3d] from sample %4d",
det, ring, sec, curStr, i));
new ((*array)[n]) AliFMDDigit(det, ring, sec, curStr, data[i],
(rate >= 2 ? data[i+1] : 0),
(rate >= 3 ? data[i+2] : 0),
(rate >= 4 ? data[i+3] : 0));
if (rate >= 2) i++;
if (rate >= 3) i++;
if (rate >= 4) i++;
}
}
return kTRUE;
}
#else
//____________________________________________________________________
Bool_t
AliFMDRawReader::ReadAdcs(TClonesArray* array)
{
// Read raw data into the digits array, using AliFMDAltroReader.
if (!array) {
AliError("No TClonesArray passed");
return kFALSE;
}
// if (!fReader->ReadHeader()) {
// AliError("Couldn't read header");
// return kFALSE;
// }
// Get sample rate
AliFMDParameters* pars = AliFMDParameters::Instance();
// Select FMD DDL's
fReader->Select("FMD");
UShort_t stripMin = 0;
UShort_t stripMax = 127;
UShort_t preSamp = 0;
do {
UChar_t* cdata;
if (!fReader->ReadNextData(cdata)) break;
size_t nchar = fReader->GetDataSize();
UShort_t ddl = fReader->GetDDLID();
UShort_t rate = 0;
AliFMDDebug(1, ("Reading %d bytes (%d 10bit words) from %d",
nchar, nchar * 8 / 10, ddl));
// Make a stream to read from
std::string str((char*)(cdata), nchar);
std::istringstream s(str);
// Prep the reader class.
AliFMDAltroReader r(s);
// Data array is approx twice the size needed.
UShort_t data[2048], hwaddr, last;
while (r.ReadChannel(hwaddr, last, data) > 0) {
AliFMDDebug(5, ("Read channel 0x%x of size %d", hwaddr, last));
UShort_t det, sec, str;
Char_t ring;
if (!pars->Hardware2Detector(ddl, hwaddr, det, ring, sec, str)) {
AliError(Form("Failed to detector id from DDL %d "
"and hardware address 0x%x", ddl, hwaddr));
continue;
}
rate = pars->GetSampleRate(det, ring, sec, str);
stripMin = pars->GetMinStrip(det, ring, sec, str);
stripMax = pars->GetMaxStrip(det, ring, sec, str);
AliFMDDebug(5, ("DDL 0x%04x, address 0x%03x maps to FMD%d%c[%2d,%3d]",
ddl, hwaddr, det, ring, sec, str));
// Loop over the `timebins', and make the digits
for (size_t i = 0; i < last; i++) {
if (i < preSamp) continue;
Int_t n = array->GetEntries();
UShort_t curStr = str + stripMin + i / rate;
if ((curStr-str) > stripMax) {
AliError(Form("Current strip is %d but DB says max is %d",
curStr, stripMax));
}
AliFMDDebug(5, ("making digit for FMD%d%c[%2d,%3d] from sample %4d",
det, ring, sec, curStr, i));
new ((*array)[n]) AliFMDDigit(det, ring, sec, curStr, data[i],
(rate >= 2 ? data[i+1] : 0),
(rate >= 3 ? data[i+2] : 0));
if (rate >= 2) i++;
if (rate >= 3) i++;
}
if (r.IsBof()) break;
}
} while (true);
return kTRUE;
}
// This is the old method, for comparison. It's really ugly, and far
// too convoluted.
//____________________________________________________________________
void
AliFMDRawReader::Exec(Option_t*)
{
// Read raw data into the digits array
// if (!fReader->ReadHeader()) {
// Error("ReadAdcs", "Couldn't read header");
// return;
// }
Int_t n = 0;
TClonesArray* array = new TClonesArray("AliFMDDigit");
fTree->Branch("FMD", &array);
// Get sample rate
AliFMDParameters* pars = AliFMDParameters::Instance();
fSampleRate = pars->GetSampleRate(0);
// Use AliAltroRawStream to read the ALTRO format. No need to
// reinvent the wheel :-)
AliFMDRawStream input(fReader, fSampleRate);
// Select FMD DDL's
fReader->Select("FMD");
Int_t oldDDL = -1;
Int_t count = 0;
UShort_t detector = 1; // Must be one here
UShort_t oldDetector = 0;
Bool_t next = kTRUE;
// local Cache
TArrayI counts(10);
counts.Reset(-1);
// Loop over data in file
while (next) {
next = input.Next();
count++;
Int_t ddl = fReader->GetDDLID();
AliFMDDebug(10, ("Current DDL is %d", ddl));
if (ddl != oldDDL || input.IsNewStrip() || !next) {
// Make a new digit, if we have some data (oldDetector == 0,
// means that we haven't really read anything yet - that is,
// it's the first time we get here).
if (oldDetector > 0) {
// Got a new strip.
AliFMDDebug(10, ("Add a new strip: FMD%d%c[%2d,%3d] "
"(current: FMD%d%c[%2d,%3d])",
oldDetector, input.PrevRing(),
input.PrevSector() , input.PrevStrip(),
detector , input.Ring(), input.Sector(),
input.Strip()));
new ((*array)[n]) AliFMDDigit(oldDetector,
input.PrevRing(),
input.PrevSector(),
input.PrevStrip(),
counts[0], counts[1], counts[2]);
n++;
#if 0
AliFMDDigit* digit =
static_cast<AliFMDDigit*>(fFMD->Digits()->
UncheckedAt(fFMD->GetNdigits()-1));
#endif
}
if (!next) {
AliFMDDebug(10, ("Read %d channels for FMD%d",
count + 1, detector));
break;
}
// If we got a new DDL, it means we have a new detector.
if (ddl != oldDDL) {
if (detector != 0)
AliFMDDebug(10, ("Read %d channels for FMD%d", count + 1, detector));
// Reset counts, and update the DDL cache
count = 0;
oldDDL = ddl;
// Check that we're processing a FMD detector
Int_t detId = fReader->GetDetectorID();
if (detId != (AliDAQ::DetectorID("FMD"))) {
AliError(Form("Detector ID %d != %d",
detId, (AliDAQ::DetectorID("FMD"))));
break;
}
// Figure out what detector we're deling with
oldDetector = detector;
switch (ddl) {
case 0: detector = 1; break;
case 1: detector = 2; break;
case 2: detector = 3; break;
default:
AliError(Form("Unknown DDL 0x%x for FMD", ddl));
return;
}
AliFMDDebug(10, ("Reading ADCs for 0x%x - That is FMD%d",
fReader->GetEquipmentId(), detector));
}
counts.Reset(-1);
}
counts[input.Sample()] = input.Count();
AliFMDDebug(10, ("ADC of FMD%d%c[%2d,%3d] += %d",
detector, input.Ring(), input.Sector(),
input.Strip(), input.Count()));
oldDetector = detector;
}
fTree->Fill();
return;
}
#endif
//____________________________________________________________________
//
// EOF
//
<commit_msg>Bug fix: do not enrter in the while loop if no FMD data<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, 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. *
**************************************************************************/
/* $Id$ */
/** @file AliFMDRawReader.cxx
@author Christian Holm Christensen <[email protected]>
@date Mon Mar 27 12:45:23 2006
@brief Class to read raw data
@ingroup FMD_rec
*/
//____________________________________________________________________
//
// Class to read ADC values from a AliRawReader object.
//
// This class uses the AliFMDRawStreamer class to read the ALTRO
// formatted data.
//
// +-------+
// | TTask |
// +-------+
// ^
// |
// +-----------------+ <<references>> +--------------+
// | AliFMDRawReader |<>----------------| AliRawReader |
// +-----------------+ +--------------+
// | ^
// | <<uses>> |
// V |
// +-----------------+ <<uses>> |
// | AliFMDRawStream |------------------------+
// +-----------------+
// |
// V
// +----------------+
// | AliAltroStream |
// +----------------+
//
// #include <AliLog.h> // ALILOG_H
#include "AliFMDDebug.h" // Better debug macros
#include "AliFMDParameters.h" // ALIFMDPARAMETERS_H
#include "AliFMDDigit.h" // ALIFMDDIGIT_H
#include "AliFMDRawStream.h" // ALIFMDRAWSTREAM_H
// #include "AliRawReader.h" // ALIRAWREADER_H
#include "AliFMDRawReader.h" // ALIFMDRAWREADER_H
// #include "AliFMDAltroIO.h" // ALIFMDALTROIO_H
// #include <TArrayI.h> // ROOT_TArrayI
#include <TTree.h> // ROOT_TTree
#include <TClonesArray.h> // ROOT_TClonesArray
// #include <iostream>
// #include <iomanip>
//____________________________________________________________________
ClassImp(AliFMDRawReader)
#if 0
; // This is here to keep Emacs for indenting the next line
#endif
//____________________________________________________________________
AliFMDRawReader::AliFMDRawReader(AliRawReader* reader, TTree* tree)
: TTask("FMDRawReader", "Reader of Raw ADC values from the FMD"),
fTree(tree),
fReader(reader),
fSampleRate(1)
{
// Default CTOR
}
//____________________________________________________________________
void
AliFMDRawReader::Exec(Option_t*)
{
// Read the data
TClonesArray* array = new TClonesArray("AliFMDDigit");
if (!fTree) {
AliError("No tree");
return;
}
fTree->Branch("FMD", &array);
ReadAdcs(array);
Int_t nWrite = fTree->Fill();
AliFMDDebug(1, ("Got a grand total of %d digits, wrote %d bytes to tree",
array->GetEntries(), nWrite));
}
#if 1
//____________________________________________________________________
Bool_t
AliFMDRawReader::ReadAdcs(TClonesArray* array)
{
// Read raw data into the digits array, using AliFMDAltroReader.
if (!array) {
AliError("No TClonesArray passed");
return kFALSE;
}
// if (!fReader->ReadHeader()) {
// AliError("Couldn't read header");
// return kFALSE;
// }
// Get sample rate
AliFMDParameters* pars = AliFMDParameters::Instance();
AliFMDRawStream input(fReader);
UShort_t stripMin = 0;
UShort_t stripMax = 127;
UShort_t preSamp = 0;
UInt_t ddl = 0;
UInt_t rate = 0;
UInt_t last = 0;
UInt_t hwaddr = 0;
// Data array is approx twice the size needed.
UShort_t data[2048];
while (input.ReadChannel(ddl, hwaddr, last, data)) {
AliFMDDebug(5, ("Read channel 0x%x of size %d", hwaddr, last));
UShort_t det, sec, str;
Char_t ring;
if (!pars->Hardware2Detector(ddl, hwaddr, det, ring, sec, str)) {
AliError(Form("Failed to get detector id from DDL %d "
"and hardware address 0x%x", ddl, hwaddr));
continue;
}
rate = pars->GetSampleRate(det, ring, sec, str);
stripMin = pars->GetMinStrip(det, ring, sec, str);
stripMax = pars->GetMaxStrip(det, ring, sec, str);
AliFMDDebug(5, ("DDL 0x%04x, address 0x%03x maps to FMD%d%c[%2d,%3d]",
ddl, hwaddr, det, ring, sec, str));
// Loop over the `timebins', and make the digits
for (size_t i = 0; i < last; i++) {
if (i < preSamp) continue;
Int_t n = array->GetEntriesFast();
UShort_t curStr = str + stripMin + i / rate;
if ((curStr-str) > stripMax) {
AliError(Form("Current strip is %d but DB says max is %d",
curStr, stripMax));
}
AliFMDDebug(5, ("making digit for FMD%d%c[%2d,%3d] from sample %4d",
det, ring, sec, curStr, i));
new ((*array)[n]) AliFMDDigit(det, ring, sec, curStr, data[i],
(rate >= 2 ? data[i+1] : 0),
(rate >= 3 ? data[i+2] : 0),
(rate >= 4 ? data[i+3] : 0));
if (rate >= 2) i++;
if (rate >= 3) i++;
if (rate >= 4) i++;
}
}
return kTRUE;
}
#else
//____________________________________________________________________
Bool_t
AliFMDRawReader::ReadAdcs(TClonesArray* array)
{
// Read raw data into the digits array, using AliFMDAltroReader.
if (!array) {
AliError("No TClonesArray passed");
return kFALSE;
}
// if (!fReader->ReadHeader()) {
// AliError("Couldn't read header");
// return kFALSE;
// }
// Get sample rate
AliFMDParameters* pars = AliFMDParameters::Instance();
// Select FMD DDL's
fReader->Select("FMD");
UShort_t stripMin = 0;
UShort_t stripMax = 127;
UShort_t preSamp = 0;
do {
UChar_t* cdata;
if (!fReader->ReadNextData(cdata)) break;
size_t nchar = fReader->GetDataSize();
UShort_t ddl = fReader->GetDDLID();
UShort_t rate = 0;
AliFMDDebug(1, ("Reading %d bytes (%d 10bit words) from %d",
nchar, nchar * 8 / 10, ddl));
// Make a stream to read from
std::string str((char*)(cdata), nchar);
std::istringstream s(str);
// Prep the reader class.
AliFMDAltroReader r(s);
// Data array is approx twice the size needed.
UShort_t data[2048], hwaddr, last;
while (r.ReadChannel(hwaddr, last, data) > 0) {
AliFMDDebug(5, ("Read channel 0x%x of size %d", hwaddr, last));
UShort_t det, sec, str;
Char_t ring;
if (!pars->Hardware2Detector(ddl, hwaddr, det, ring, sec, str)) {
AliError(Form("Failed to detector id from DDL %d "
"and hardware address 0x%x", ddl, hwaddr));
continue;
}
rate = pars->GetSampleRate(det, ring, sec, str);
stripMin = pars->GetMinStrip(det, ring, sec, str);
stripMax = pars->GetMaxStrip(det, ring, sec, str);
AliFMDDebug(5, ("DDL 0x%04x, address 0x%03x maps to FMD%d%c[%2d,%3d]",
ddl, hwaddr, det, ring, sec, str));
// Loop over the `timebins', and make the digits
for (size_t i = 0; i < last; i++) {
if (i < preSamp) continue;
Int_t n = array->GetEntries();
UShort_t curStr = str + stripMin + i / rate;
if ((curStr-str) > stripMax) {
AliError(Form("Current strip is %d but DB says max is %d",
curStr, stripMax));
}
AliFMDDebug(5, ("making digit for FMD%d%c[%2d,%3d] from sample %4d",
det, ring, sec, curStr, i));
new ((*array)[n]) AliFMDDigit(det, ring, sec, curStr, data[i],
(rate >= 2 ? data[i+1] : 0),
(rate >= 3 ? data[i+2] : 0));
if (rate >= 2) i++;
if (rate >= 3) i++;
}
if (r.IsBof()) break;
}
} while (true);
return kTRUE;
}
// This is the old method, for comparison. It's really ugly, and far
// too convoluted.
//____________________________________________________________________
void
AliFMDRawReader::Exec(Option_t*)
{
// Read raw data into the digits array
// if (!fReader->ReadHeader()) {
// Error("ReadAdcs", "Couldn't read header");
// return;
// }
Int_t n = 0;
TClonesArray* array = new TClonesArray("AliFMDDigit");
fTree->Branch("FMD", &array);
// Get sample rate
AliFMDParameters* pars = AliFMDParameters::Instance();
fSampleRate = pars->GetSampleRate(0);
// Use AliAltroRawStream to read the ALTRO format. No need to
// reinvent the wheel :-)
AliFMDRawStream input(fReader, fSampleRate);
// Select FMD DDL's
fReader->Select("FMD");
Int_t oldDDL = -1;
Int_t count = 0;
UShort_t detector = 1; // Must be one here
UShort_t oldDetector = 0;
Bool_t next = kTRUE;
// local Cache
TArrayI counts(10);
counts.Reset(-1);
// Loop over data in file
while (next) {
next = input.Next();
count++;
Int_t ddl = fReader->GetDDLID();
AliFMDDebug(10, ("Current DDL is %d", ddl));
if (ddl != oldDDL || input.IsNewStrip() || !next) {
// Make a new digit, if we have some data (oldDetector == 0,
// means that we haven't really read anything yet - that is,
// it's the first time we get here).
if (oldDetector > 0) {
// Got a new strip.
AliFMDDebug(10, ("Add a new strip: FMD%d%c[%2d,%3d] "
"(current: FMD%d%c[%2d,%3d])",
oldDetector, input.PrevRing(),
input.PrevSector() , input.PrevStrip(),
detector , input.Ring(), input.Sector(),
input.Strip()));
new ((*array)[n]) AliFMDDigit(oldDetector,
input.PrevRing(),
input.PrevSector(),
input.PrevStrip(),
counts[0], counts[1], counts[2]);
n++;
#if 0
AliFMDDigit* digit =
static_cast<AliFMDDigit*>(fFMD->Digits()->
UncheckedAt(fFMD->GetNdigits()-1));
#endif
}
if (!next) {
AliFMDDebug(10, ("Read %d channels for FMD%d",
count + 1, detector));
break;
}
// If we got a new DDL, it means we have a new detector.
if (ddl != oldDDL) {
if (detector != 0)
AliFMDDebug(10, ("Read %d channels for FMD%d", count + 1, detector));
// Reset counts, and update the DDL cache
count = 0;
oldDDL = ddl;
// Check that we're processing a FMD detector
Int_t detId = fReader->GetDetectorID();
if (detId != (AliDAQ::DetectorID("FMD"))) {
AliError(Form("Detector ID %d != %d",
detId, (AliDAQ::DetectorID("FMD"))));
break;
}
// Figure out what detector we're deling with
oldDetector = detector;
switch (ddl) {
case 0: detector = 1; break;
case 1: detector = 2; break;
case 2: detector = 3; break;
default:
AliError(Form("Unknown DDL 0x%x for FMD", ddl));
return;
}
AliFMDDebug(10, ("Reading ADCs for 0x%x - That is FMD%d",
fReader->GetEquipmentId(), detector));
}
counts.Reset(-1);
}
counts[input.Sample()] = input.Count();
AliFMDDebug(10, ("ADC of FMD%d%c[%2d,%3d] += %d",
detector, input.Ring(), input.Sector(),
input.Strip(), input.Count()));
oldDetector = detector;
}
fTree->Fill();
return;
}
#endif
//____________________________________________________________________
//
// EOF
//
<|endoftext|> |
<commit_before>// @(#)root/memstat:$Id$
// Author: Anar Manafov ([email protected]) 2008-03-02
/*************************************************************************
* Copyright (C) 1995-2010, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
// STD
#include <cstdlib>
// ROOT
#include "TSystem.h"
#include "TEnv.h"
#include "TError.h"
#include "Riostream.h"
#include "TObject.h"
#include "TFile.h"
#include "TTree.h"
#include "TArrayL64.h"
#include "TH1.h"
#include "TMD5.h"
// Memstat
#include "TMemStatBacktrace.h"
#include "TMemStatMng.h"
using namespace memstat;
ClassImp(TMemStatMng)
TMemStatMng* TMemStatMng::fgInstance = NULL;
//****************************************************************************//
//
//****************************************************************************//
TMemStatMng::TMemStatMng():
TObject(),
#if !defined(__APPLE__)
fPreviousMallocHook(TMemStatHook::GetMallocHook()),
fPreviousFreeHook(TMemStatHook::GetFreeHook()),
#endif
fDumpFile(NULL),
fDumpTree(NULL),
fUseGNUBuiltinBacktrace(kFALSE),
fBeginTime(0),
fPos(0),
fTimems(0),
fNBytes(0),
fN(0),
fBtID(0),
fMaxCalls(5000000),
fFAddrsList(0),
fHbtids(0),
fBTCount(0),
fBTIDCount(0),
fSysInfo(NULL)
{
// Default constructor
}
//______________________________________________________________________________
void TMemStatMng::Init()
{
//Initialize MemStat manager - used only by instance method
fBeginTime = fTimeStamp.AsDouble();
fDumpFile = new TFile(Form("memstat_%d.root", gSystem->GetPid()), "recreate");
Int_t opt = 200000;
if(!fDumpTree) {
fDumpTree = new TTree("T", "Memory Statistics");
fDumpTree->Branch("pos", &fPos, "pos/l", opt);
fDumpTree->Branch("time", &fTimems, "time/I", opt);
fDumpTree->Branch("nbytes", &fNBytes, "nbytes/I", opt);
fDumpTree->Branch("btid", &fBtID, "btid/I", opt);
}
fBTCount = 0;
fBTIDCount = 0;
fFAddrsList = new TObjArray();
fFAddrsList->SetOwner(kTRUE);
fFAddrsList->SetName("FAddrsList");
fHbtids = new TH1I("btids", "table of btids", 10000, 0, 1); //where fHbtids is a member of the manager class
fHbtids->SetDirectory(0);
// save the histogram and the TObjArray to the tree header
fDumpTree->GetUserInfo()->Add(fHbtids);
fDumpTree->GetUserInfo()->Add(fFAddrsList);
// save the system info to a tree header
string sSysInfo(gSystem->GetBuildNode());
sSysInfo += " | ";
sSysInfo += gSystem->GetBuildCompilerVersion();
sSysInfo += " | ";
sSysInfo += gSystem->GetFlagsDebug();
sSysInfo += " ";
sSysInfo += gSystem->GetFlagsOpt();
fSysInfo = new TNamed("SysInfo", sSysInfo.c_str());
fDumpTree->GetUserInfo()->Add(fSysInfo);
fDumpTree->SetAutoSave(10000000);
}
//______________________________________________________________________________
TMemStatMng* TMemStatMng::GetInstance()
{
// GetInstance - a static function
// Initialize a singleton of MemStat manager
if(!fgInstance) {
fgInstance = new TMemStatMng;
fgInstance->Init();
}
return fgInstance;
}
//______________________________________________________________________________
void TMemStatMng::Close()
{
// Close - a static function
// This method stops the manager,
// flashes all the buffered data and closes the output tree.
// TODO: This is a temporary solution until we find a properalgorithm for SaveData
//fgInstance->fDumpFile->WriteObject(fgInstance->fFAddrsList, "FAddrsList");
// to be documented
fgInstance->fDumpTree->AutoSave();
fgInstance->fDumpTree->GetUserInfo()->Delete();
printf("TMemStat Tree saved to file %s\n",fgInstance->fDumpFile->GetName());
//delete fgInstance->fFAddrsList;
//delete fgInstance->fSysInfo;
delete fgInstance;
fgInstance = NULL;
}
//______________________________________________________________________________
TMemStatMng::~TMemStatMng()
{
// if an instance is destructed - the hooks are reseted to old hooks
if(this != TMemStatMng::GetInstance())
return;
Info("~TMemStatMng", ">>> All free/malloc calls count: %d", fBTIDCount);
Info("~TMemStatMng", ">>> Unique BTIDs count: %zu", fBTChecksums.size());
Disable();
}
//______________________________________________________________________________
void TMemStatMng::SetMaxcalls(Long64_t maxcalls)
{
//set the maximum number of new/delete registered in the output Tree
fMaxCalls = maxcalls;
printf("setting MasCalls=%lld\n",maxcalls);
}
//______________________________________________________________________________
void TMemStatMng::Enable()
{
// Enable memory hooks
if(this != GetInstance())
return;
#if defined(__APPLE__)
TMemStatHook::trackZoneMalloc(MacAllocHook, MacFreeHook);
#else
// set hook to our functions
TMemStatHook::SetMallocHook(AllocHook);
TMemStatHook::SetFreeHook(FreeHook);
#endif
}
//______________________________________________________________________________
void TMemStatMng::Disable()
{
// Disble memory hooks
if(this != GetInstance())
return;
#if defined(__APPLE__)
TMemStatHook::untrackZoneMalloc();
#else
// set hook to our functions
TMemStatHook::SetMallocHook(fPreviousMallocHook);
TMemStatHook::SetFreeHook(fPreviousFreeHook);
#endif
}
//______________________________________________________________________________
void TMemStatMng::MacAllocHook(void *ptr, size_t size)
{
// AllocHook - a static function
// a special memory hook for Mac OS X memory zones.
// Triggered when memory is allocated.
TMemStatMng* instance = TMemStatMng::GetInstance();
// Restore all old hooks
instance->Disable();
// Call our routine
instance->AddPointer(ptr, Int_t(size));
// Restore our own hooks
instance->Enable();
}
//______________________________________________________________________________
void TMemStatMng::MacFreeHook(void *ptr)
{
// AllocHook - a static function
// a special memory hook for Mac OS X memory zones.
// Triggered when memory is deallocated.
TMemStatMng* instance = TMemStatMng::GetInstance();
// Restore all old hooks
instance->Disable();
// Call our routine
instance->AddPointer(ptr, -1);
// Restore our own hooks
instance->Enable();
}
//______________________________________________________________________________
void *TMemStatMng::AllocHook(size_t size, const void* /*caller*/)
{
// AllocHook - a static function
// A glibc memory allocation hook.
TMemStatMng* instance = TMemStatMng::GetInstance();
// Restore all old hooks
instance->Disable();
// Call recursively
void *result = malloc(size);
// Call our routine
instance->AddPointer(result, Int_t(size));
// TTimer::SingleShot(0, "TYamsMemMng", instance, "SaveData()");
// Restore our own hooks
instance->Enable();
return result;
}
//______________________________________________________________________________
void TMemStatMng::FreeHook(void* ptr, const void* /*caller*/)
{
// FreeHook - a static function
// A glibc memory deallocation hook.
TMemStatMng* instance = TMemStatMng::GetInstance();
// Restore all old hooks
instance->Disable();
// Call recursively
free(ptr);
// Call our routine
instance->AddPointer(ptr, -1);
// Restore our own hooks
instance->Enable();
}
//______________________________________________________________________________
Int_t TMemStatMng::generateBTID(UChar_t *CRCdigest, Int_t stackEntries,
void **stackPointers)
{
// An internal function, which returns a bitid for a corresponding CRC digest
// cache variables
static Int_t old_btid = -1;
static SCustomDigest old_digest;
Int_t ret_val = -1;
bool startCheck(false);
if(old_btid >= 0) {
for(int i = 0; i < g_digestSize; ++i) {
if(old_digest.fValue[i] != CRCdigest[i]) {
startCheck = true;
break;
}
}
ret_val = old_btid;
} else {
startCheck = true;
}
// return cached value
if(!startCheck)
return ret_val;
old_digest = SCustomDigest(CRCdigest);
CRCSet_t::const_iterator found = fBTChecksums.find(CRCdigest);
if(fBTChecksums.end() == found) {
// check the size of the BT array container
const int nbins = fHbtids->GetNbinsX();
//check that the current allocation in fHbtids is enough, otherwise expend it with
if(fBTCount + stackEntries + 1 >= nbins) {
fHbtids->SetBins(nbins * 2, 0, 1);
}
int *btids = fHbtids->GetArray();
// A first value is a number of entries in a given stack
btids[fBTCount++] = stackEntries;
ret_val = fBTCount;
if(stackEntries <= 0) {
Warning("AddPointer",
"A number of stack entries is equal or less than zero. For btid %d", ret_val);
}
// add new BT's CRC value
pair<CRCSet_t::iterator, bool> res = fBTChecksums.insert(CRCSet_t::value_type(CRCdigest, ret_val));
if(!res.second)
Error("AddPointer", "Can't added a new BTID to the container.");
// save all symbols of this BT
for(int i = 0; i < stackEntries; ++i) {
ULong_t func_addr = (ULong_t)(stackPointers[i]);
Int_t idx = fFAddrs.find(func_addr);
// check, whether it's a new symbol
if(idx < 0) {
TString strFuncAddr;
strFuncAddr += func_addr;
TString strSymbolInfo;
getSymbolFullInfo(stackPointers[i], &strSymbolInfo);
TNamed *nm = new TNamed(strFuncAddr, strSymbolInfo);
fFAddrsList->Add(nm);
idx = fFAddrsList->GetEntriesFast() - 1;
// TODO: more detailed error message...
if(!fFAddrs.add(func_addr, idx))
Error("AddPointer", "Can't add a function return address to the container");
}
// even if we have -1 as an index we add it to the container
btids[fBTCount++] = idx;
}
} else {
// reuse an existing BT
ret_val = found->second;
}
old_btid = ret_val;
return ret_val;
}
//______________________________________________________________________________
void TMemStatMng::AddPointer(void *ptr, Int_t size)
{
// Add pointer to table.
// This method is called every time when any of the hooks are triggered.
// The memory de-/allocation information will is recorded.
void *stptr[g_BTStackLevel + 1];
const int stackentries = getBacktrace(stptr, g_BTStackLevel, fUseGNUBuiltinBacktrace);
// save only unique BTs
TMD5 md5;
md5.Update(reinterpret_cast<UChar_t*>(stptr), sizeof(void*) * stackentries);
UChar_t digest[g_digestSize];
md5.Final(digest);
// for Debug. A counter of all (de)allacations.
++fBTIDCount;
Int_t btid(generateBTID(digest, stackentries, stptr));
if(btid <= 0)
Error("AddPointer", "bad BT id");
fTimeStamp.Set();
Double_t CurTime = fTimeStamp.AsDouble();
fTimems = Int_t(10000.*(CurTime - fBeginTime));
ULong_t ul = (ULong_t)(ptr);
fPos = (ULong64_t)(ul);
fNBytes = size;
fN = 0;
fBtID = btid;
fDumpTree->Fill();
if (fDumpTree->GetEntries() >= fMaxCalls) TMemStatMng::GetInstance()->Disable();
}
<commit_msg>Disable TmemstatMng before writing the tree header<commit_after>// @(#)root/memstat:$Id$
// Author: Anar Manafov ([email protected]) 2008-03-02
/*************************************************************************
* Copyright (C) 1995-2010, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
// STD
#include <cstdlib>
// ROOT
#include "TSystem.h"
#include "TEnv.h"
#include "TError.h"
#include "Riostream.h"
#include "TObject.h"
#include "TFile.h"
#include "TTree.h"
#include "TArrayL64.h"
#include "TH1.h"
#include "TMD5.h"
// Memstat
#include "TMemStatBacktrace.h"
#include "TMemStatMng.h"
using namespace memstat;
ClassImp(TMemStatMng)
TMemStatMng* TMemStatMng::fgInstance = NULL;
//****************************************************************************//
//
//****************************************************************************//
TMemStatMng::TMemStatMng():
TObject(),
#if !defined(__APPLE__)
fPreviousMallocHook(TMemStatHook::GetMallocHook()),
fPreviousFreeHook(TMemStatHook::GetFreeHook()),
#endif
fDumpFile(NULL),
fDumpTree(NULL),
fUseGNUBuiltinBacktrace(kFALSE),
fBeginTime(0),
fPos(0),
fTimems(0),
fNBytes(0),
fN(0),
fBtID(0),
fMaxCalls(5000000),
fFAddrsList(0),
fHbtids(0),
fBTCount(0),
fBTIDCount(0),
fSysInfo(NULL)
{
// Default constructor
}
//______________________________________________________________________________
void TMemStatMng::Init()
{
//Initialize MemStat manager - used only by instance method
fBeginTime = fTimeStamp.AsDouble();
fDumpFile = new TFile(Form("memstat_%d.root", gSystem->GetPid()), "recreate");
Int_t opt = 200000;
if(!fDumpTree) {
fDumpTree = new TTree("T", "Memory Statistics");
fDumpTree->Branch("pos", &fPos, "pos/l", opt);
fDumpTree->Branch("time", &fTimems, "time/I", opt);
fDumpTree->Branch("nbytes", &fNBytes, "nbytes/I", opt);
fDumpTree->Branch("btid", &fBtID, "btid/I", opt);
}
fBTCount = 0;
fBTIDCount = 0;
fFAddrsList = new TObjArray();
fFAddrsList->SetOwner(kTRUE);
fFAddrsList->SetName("FAddrsList");
fHbtids = new TH1I("btids", "table of btids", 10000, 0, 1); //where fHbtids is a member of the manager class
fHbtids->SetDirectory(0);
// save the histogram and the TObjArray to the tree header
fDumpTree->GetUserInfo()->Add(fHbtids);
fDumpTree->GetUserInfo()->Add(fFAddrsList);
// save the system info to a tree header
string sSysInfo(gSystem->GetBuildNode());
sSysInfo += " | ";
sSysInfo += gSystem->GetBuildCompilerVersion();
sSysInfo += " | ";
sSysInfo += gSystem->GetFlagsDebug();
sSysInfo += " ";
sSysInfo += gSystem->GetFlagsOpt();
fSysInfo = new TNamed("SysInfo", sSysInfo.c_str());
fDumpTree->GetUserInfo()->Add(fSysInfo);
fDumpTree->SetAutoSave(10000000);
}
//______________________________________________________________________________
TMemStatMng* TMemStatMng::GetInstance()
{
// GetInstance - a static function
// Initialize a singleton of MemStat manager
if(!fgInstance) {
fgInstance = new TMemStatMng;
fgInstance->Init();
}
return fgInstance;
}
//______________________________________________________________________________
void TMemStatMng::Close()
{
// Close - a static function
// This method stops the manager,
// flashes all the buffered data and closes the output tree.
// TODO: This is a temporary solution until we find a properalgorithm for SaveData
//fgInstance->fDumpFile->WriteObject(fgInstance->fFAddrsList, "FAddrsList");
// to be documented
fgInstance->Disable();
fgInstance->fDumpTree->AutoSave();
fgInstance->fDumpTree->GetUserInfo()->Delete();
printf("TMemStat Tree saved to file %s\n",fgInstance->fDumpFile->GetName());
delete fgInstance->fDumpFile;
//fgInstance->fDumpFile->Close();
//delete fgInstance->fFAddrsList;
//delete fgInstance->fSysInfo;
delete fgInstance;
fgInstance = NULL;
}
//______________________________________________________________________________
TMemStatMng::~TMemStatMng()
{
// if an instance is destructed - the hooks are reseted to old hooks
if(this != TMemStatMng::GetInstance())
return;
Info("~TMemStatMng", ">>> All free/malloc calls count: %d", fBTIDCount);
Info("~TMemStatMng", ">>> Unique BTIDs count: %zu", fBTChecksums.size());
Disable();
}
//______________________________________________________________________________
void TMemStatMng::SetMaxcalls(Long64_t maxcalls)
{
//set the maximum number of new/delete registered in the output Tree
fMaxCalls = maxcalls;
printf("setting MasCalls=%lld\n",maxcalls);
}
//______________________________________________________________________________
void TMemStatMng::Enable()
{
// Enable memory hooks
if(this != GetInstance())
return;
#if defined(__APPLE__)
TMemStatHook::trackZoneMalloc(MacAllocHook, MacFreeHook);
#else
// set hook to our functions
TMemStatHook::SetMallocHook(AllocHook);
TMemStatHook::SetFreeHook(FreeHook);
#endif
}
//______________________________________________________________________________
void TMemStatMng::Disable()
{
// Disble memory hooks
if(this != GetInstance())
return;
#if defined(__APPLE__)
TMemStatHook::untrackZoneMalloc();
#else
// set hook to our functions
TMemStatHook::SetMallocHook(fPreviousMallocHook);
TMemStatHook::SetFreeHook(fPreviousFreeHook);
#endif
}
//______________________________________________________________________________
void TMemStatMng::MacAllocHook(void *ptr, size_t size)
{
// AllocHook - a static function
// a special memory hook for Mac OS X memory zones.
// Triggered when memory is allocated.
TMemStatMng* instance = TMemStatMng::GetInstance();
// Restore all old hooks
instance->Disable();
// Call our routine
instance->AddPointer(ptr, Int_t(size));
// Restore our own hooks
instance->Enable();
}
//______________________________________________________________________________
void TMemStatMng::MacFreeHook(void *ptr)
{
// AllocHook - a static function
// a special memory hook for Mac OS X memory zones.
// Triggered when memory is deallocated.
TMemStatMng* instance = TMemStatMng::GetInstance();
// Restore all old hooks
instance->Disable();
// Call our routine
instance->AddPointer(ptr, -1);
// Restore our own hooks
instance->Enable();
}
//______________________________________________________________________________
void *TMemStatMng::AllocHook(size_t size, const void* /*caller*/)
{
// AllocHook - a static function
// A glibc memory allocation hook.
TMemStatMng* instance = TMemStatMng::GetInstance();
// Restore all old hooks
instance->Disable();
// Call recursively
void *result = malloc(size);
// Call our routine
instance->AddPointer(result, Int_t(size));
// TTimer::SingleShot(0, "TYamsMemMng", instance, "SaveData()");
// Restore our own hooks
instance->Enable();
return result;
}
//______________________________________________________________________________
void TMemStatMng::FreeHook(void* ptr, const void* /*caller*/)
{
// FreeHook - a static function
// A glibc memory deallocation hook.
TMemStatMng* instance = TMemStatMng::GetInstance();
// Restore all old hooks
instance->Disable();
// Call recursively
free(ptr);
// Call our routine
instance->AddPointer(ptr, -1);
// Restore our own hooks
instance->Enable();
}
//______________________________________________________________________________
Int_t TMemStatMng::generateBTID(UChar_t *CRCdigest, Int_t stackEntries,
void **stackPointers)
{
// An internal function, which returns a bitid for a corresponding CRC digest
// cache variables
static Int_t old_btid = -1;
static SCustomDigest old_digest;
Int_t ret_val = -1;
bool startCheck(false);
if(old_btid >= 0) {
for(int i = 0; i < g_digestSize; ++i) {
if(old_digest.fValue[i] != CRCdigest[i]) {
startCheck = true;
break;
}
}
ret_val = old_btid;
} else {
startCheck = true;
}
// return cached value
if(!startCheck)
return ret_val;
old_digest = SCustomDigest(CRCdigest);
CRCSet_t::const_iterator found = fBTChecksums.find(CRCdigest);
if(fBTChecksums.end() == found) {
// check the size of the BT array container
const int nbins = fHbtids->GetNbinsX();
//check that the current allocation in fHbtids is enough, otherwise expend it with
if(fBTCount + stackEntries + 1 >= nbins) {
fHbtids->SetBins(nbins * 2, 0, 1);
}
int *btids = fHbtids->GetArray();
// A first value is a number of entries in a given stack
btids[fBTCount++] = stackEntries;
ret_val = fBTCount;
if(stackEntries <= 0) {
Warning("AddPointer",
"A number of stack entries is equal or less than zero. For btid %d", ret_val);
}
// add new BT's CRC value
pair<CRCSet_t::iterator, bool> res = fBTChecksums.insert(CRCSet_t::value_type(CRCdigest, ret_val));
if(!res.second)
Error("AddPointer", "Can't added a new BTID to the container.");
// save all symbols of this BT
for(int i = 0; i < stackEntries; ++i) {
ULong_t func_addr = (ULong_t)(stackPointers[i]);
Int_t idx = fFAddrs.find(func_addr);
// check, whether it's a new symbol
if(idx < 0) {
TString strFuncAddr;
strFuncAddr += func_addr;
TString strSymbolInfo;
getSymbolFullInfo(stackPointers[i], &strSymbolInfo);
TNamed *nm = new TNamed(strFuncAddr, strSymbolInfo);
fFAddrsList->Add(nm);
idx = fFAddrsList->GetEntriesFast() - 1;
// TODO: more detailed error message...
if(!fFAddrs.add(func_addr, idx))
Error("AddPointer", "Can't add a function return address to the container");
}
// even if we have -1 as an index we add it to the container
btids[fBTCount++] = idx;
}
} else {
// reuse an existing BT
ret_val = found->second;
}
old_btid = ret_val;
return ret_val;
}
//______________________________________________________________________________
void TMemStatMng::AddPointer(void *ptr, Int_t size)
{
// Add pointer to table.
// This method is called every time when any of the hooks are triggered.
// The memory de-/allocation information will is recorded.
void *stptr[g_BTStackLevel + 1];
const int stackentries = getBacktrace(stptr, g_BTStackLevel, fUseGNUBuiltinBacktrace);
// save only unique BTs
TMD5 md5;
md5.Update(reinterpret_cast<UChar_t*>(stptr), sizeof(void*) * stackentries);
UChar_t digest[g_digestSize];
md5.Final(digest);
// for Debug. A counter of all (de)allacations.
++fBTIDCount;
Int_t btid(generateBTID(digest, stackentries, stptr));
if(btid <= 0)
Error("AddPointer", "bad BT id");
fTimeStamp.Set();
Double_t CurTime = fTimeStamp.AsDouble();
fTimems = Int_t(10000.*(CurTime - fBeginTime));
ULong_t ul = (ULong_t)(ptr);
fPos = (ULong64_t)(ul);
fNBytes = size;
fN = 0;
fBtID = btid;
fDumpTree->Fill();
if (fDumpTree->GetEntries() >= fMaxCalls) TMemStatMng::GetInstance()->Disable();
}
<|endoftext|> |
<commit_before>/*
* RUtil.cpp
*
* Copyright (C) 2009-18 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <r/RUtil.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/regex.hpp>
#include <core/Algorithm.hpp>
#include <core/FilePath.hpp>
#include <core/StringUtils.hpp>
#include <core/Error.hpp>
#include <core/RegexUtils.hpp>
#include <r/RExec.hpp>
#include <R_ext/Riconv.h>
#ifndef CP_ACP
# define CP_ACP 0
#endif
using namespace rstudio::core;
namespace rstudio {
namespace r {
namespace util {
std::string expandFileName(const std::string& name)
{
return std::string(R_ExpandFileName(name.c_str()));
}
std::string fixPath(const std::string& path)
{
// R sometimes gives us a path a double slashes in it ("//"). Eliminate them.
std::string fixedPath(path);
boost::algorithm::replace_all(fixedPath, "//", "/");
return fixedPath;
}
bool hasRequiredVersion(const std::string& version)
{
std::string versionTest("getRversion() >= \"" + version + "\"");
bool hasRequired = false;
Error error = r::exec::evaluateString(versionTest, &hasRequired);
if (error)
{
LOG_ERROR(error);
return false;
}
else
{
return hasRequired;
}
}
bool hasCapability(const std::string& capability)
{
bool hasCap = false;
Error error = r::exec::RFunction("capabilities", capability).call(&hasCap);
if (error)
LOG_ERROR(error);
return hasCap;
}
std::string rconsole2utf8(const std::string& encoded)
{
int codepage = CP_ACP;
#ifdef _WIN32
Error error = r::exec::evaluateString("base::l10n_info()$codepage", &codepage);
if (error)
LOG_ERROR(error);
#endif
boost::regex utf8("\x02\xFF\xFE(.*?)(\x03\xFF\xFE|\\')");
std::string output;
std::string::const_iterator pos = encoded.begin();
boost::smatch m;
while (pos != encoded.end() && regex_utils::search(pos, encoded.end(), m, utf8))
{
if (pos < m[0].first)
output.append(string_utils::systemToUtf8(std::string(pos, m[0].first), codepage));
output.append(m[1].first, m[1].second);
pos = m[0].second;
}
if (pos != encoded.end())
output.append(string_utils::systemToUtf8(std::string(pos, encoded.end()), codepage));
return output;
}
core::Error iconvstr(const std::string& value,
const std::string& from,
const std::string& to,
bool allowSubstitution,
std::string* pResult)
{
std::string effectiveFrom = from;
if (effectiveFrom.empty())
effectiveFrom = "UTF-8";
std::string effectiveTo = to;
if (effectiveTo.empty())
effectiveTo = "UTF-8";
if (effectiveFrom == effectiveTo)
{
*pResult = value;
return Success();
}
std::vector<char> output;
output.reserve(value.length());
void* handle = ::Riconv_open(to.c_str(), from.c_str());
if (handle == (void*)(-1))
return systemError(R_ERRNO, ERROR_LOCATION);
const char* pIn = value.data();
size_t inBytes = value.size();
char buffer[256];
while (inBytes > 0)
{
const char* pInOrig = pIn;
char* pOut = buffer;
size_t outBytes = sizeof(buffer);
size_t result = ::Riconv(handle, &pIn, &inBytes, &pOut, &outBytes);
if (buffer != pOut)
output.insert(output.end(), buffer, pOut);
if (result == (size_t)(-1))
{
if ((R_ERRNO == EILSEQ || R_ERRNO == EINVAL) && allowSubstitution)
{
output.push_back('?');
pIn++;
inBytes--;
}
else if (R_ERRNO == E2BIG && pInOrig != pIn)
{
continue;
}
else
{
::Riconv_close(handle);
Error error = systemError(R_ERRNO, ERROR_LOCATION);
error.addProperty("str", value);
error.addProperty("len", value.length());
error.addProperty("from", from);
error.addProperty("to", to);
return error;
}
}
}
::Riconv_close(handle);
*pResult = std::string(output.begin(), output.end());
return Success();
}
std::set<std::string> makeRKeywords()
{
std::set<std::string> keywords;
keywords.insert("TRUE");
keywords.insert("FALSE");
keywords.insert("NA");
keywords.insert("NaN");
keywords.insert("NULL");
keywords.insert("NA_real_");
keywords.insert("NA_complex_");
keywords.insert("NA_integer_");
keywords.insert("NA_character_");
keywords.insert("Inf");
keywords.insert("if");
keywords.insert("else");
keywords.insert("while");
keywords.insert("for");
keywords.insert("in");
keywords.insert("function");
keywords.insert("next");
keywords.insert("break");
keywords.insert("repeat");
keywords.insert("...");
return keywords;
}
bool isRKeyword(const std::string& name)
{
static const std::set<std::string> s_rKeywords = makeRKeywords();
static const boost::regex s_reDotDotNumbers("\\.\\.[0-9]+");
return s_rKeywords.count(name) != 0 ||
regex_utils::textMatches(name, s_reDotDotNumbers, false, false);
}
std::set<std::string> makeWindowsOnlyFunctions()
{
std::set<std::string> fns;
fns.insert("shell");
fns.insert("shell.exec");
fns.insert("Sys.junction");
return fns;
}
bool isWindowsOnlyFunction(const std::string& name)
{
static const std::set<std::string> s_rWindowsOnly = makeWindowsOnlyFunctions();
return core::algorithm::contains(s_rWindowsOnly, name);
}
bool isPackageAttached(const std::string& packageName)
{
SEXP namespaces = R_NilValue;
r::sexp::Protect protect;
Error error = r::exec::RFunction("search").call(&namespaces, &protect);
if (error)
{
// not fatal; we'll just presume package is not on the path
LOG_ERROR(error);
return false;
}
std::string fullPackageName = "package:";
fullPackageName += packageName;
int len = r::sexp::length(namespaces);
for (int i = 0; i < len; i++)
{
std::string ns = r::sexp::safeAsString(STRING_ELT(namespaces, i), "");
if (ns == fullPackageName)
{
return true;
}
}
return false;
}
} // namespace util
} // namespace r
} // namespace rstudio
<commit_msg>make use of R's localeCP directly<commit_after>/*
* RUtil.cpp
*
* Copyright (C) 2009-18 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <r/RUtil.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/regex.hpp>
#include <core/Algorithm.hpp>
#include <core/FilePath.hpp>
#include <core/StringUtils.hpp>
#include <core/Error.hpp>
#include <core/RegexUtils.hpp>
#include <r/RExec.hpp>
#include <R_ext/Riconv.h>
#ifndef CP_ACP
# define CP_ACP 0
#endif
#ifdef _WIN32
#include <Windows.h>
extern "C" {
__declspec(dllimport) unsigned int localeCP;
}
#endif
using namespace rstudio::core;
namespace rstudio {
namespace r {
namespace util {
std::string expandFileName(const std::string& name)
{
return std::string(R_ExpandFileName(name.c_str()));
}
std::string fixPath(const std::string& path)
{
// R sometimes gives us a path a double slashes in it ("//"). Eliminate them.
std::string fixedPath(path);
boost::algorithm::replace_all(fixedPath, "//", "/");
return fixedPath;
}
bool hasRequiredVersion(const std::string& version)
{
std::string versionTest("getRversion() >= \"" + version + "\"");
bool hasRequired = false;
Error error = r::exec::evaluateString(versionTest, &hasRequired);
if (error)
{
LOG_ERROR(error);
return false;
}
else
{
return hasRequired;
}
}
bool hasCapability(const std::string& capability)
{
bool hasCap = false;
Error error = r::exec::RFunction("capabilities", capability).call(&hasCap);
if (error)
LOG_ERROR(error);
return hasCap;
}
std::string rconsole2utf8(const std::string& encoded)
{
#ifndef _WIN32
return encoded;
#else
unsigned int codepage = localeCP;
std::string output;
std::string::const_iterator pos = encoded.begin();
boost::smatch m;
while (pos != encoded.end() && regex_utils::search(pos, encoded.end(), m, utf8))
{
if (pos < m[0].first)
output.append(string_utils::systemToUtf8(std::string(pos, m[0].first), codepage));
output.append(m[1].first, m[1].second);
pos = m[0].second;
}
if (pos != encoded.end())
output.append(string_utils::systemToUtf8(std::string(pos, encoded.end()), codepage));
return output;
#endif
}
core::Error iconvstr(const std::string& value,
const std::string& from,
const std::string& to,
bool allowSubstitution,
std::string* pResult)
{
std::string effectiveFrom = from;
if (effectiveFrom.empty())
effectiveFrom = "UTF-8";
std::string effectiveTo = to;
if (effectiveTo.empty())
effectiveTo = "UTF-8";
if (effectiveFrom == effectiveTo)
{
*pResult = value;
return Success();
}
std::vector<char> output;
output.reserve(value.length());
void* handle = ::Riconv_open(to.c_str(), from.c_str());
if (handle == (void*)(-1))
return systemError(R_ERRNO, ERROR_LOCATION);
const char* pIn = value.data();
size_t inBytes = value.size();
char buffer[256];
while (inBytes > 0)
{
const char* pInOrig = pIn;
char* pOut = buffer;
size_t outBytes = sizeof(buffer);
size_t result = ::Riconv(handle, &pIn, &inBytes, &pOut, &outBytes);
if (buffer != pOut)
output.insert(output.end(), buffer, pOut);
if (result == (size_t)(-1))
{
if ((R_ERRNO == EILSEQ || R_ERRNO == EINVAL) && allowSubstitution)
{
output.push_back('?');
pIn++;
inBytes--;
}
else if (R_ERRNO == E2BIG && pInOrig != pIn)
{
continue;
}
else
{
::Riconv_close(handle);
Error error = systemError(R_ERRNO, ERROR_LOCATION);
error.addProperty("str", value);
error.addProperty("len", value.length());
error.addProperty("from", from);
error.addProperty("to", to);
return error;
}
}
}
::Riconv_close(handle);
*pResult = std::string(output.begin(), output.end());
return Success();
}
std::set<std::string> makeRKeywords()
{
std::set<std::string> keywords;
keywords.insert("TRUE");
keywords.insert("FALSE");
keywords.insert("NA");
keywords.insert("NaN");
keywords.insert("NULL");
keywords.insert("NA_real_");
keywords.insert("NA_complex_");
keywords.insert("NA_integer_");
keywords.insert("NA_character_");
keywords.insert("Inf");
keywords.insert("if");
keywords.insert("else");
keywords.insert("while");
keywords.insert("for");
keywords.insert("in");
keywords.insert("function");
keywords.insert("next");
keywords.insert("break");
keywords.insert("repeat");
keywords.insert("...");
return keywords;
}
bool isRKeyword(const std::string& name)
{
static const std::set<std::string> s_rKeywords = makeRKeywords();
static const boost::regex s_reDotDotNumbers("\\.\\.[0-9]+");
return s_rKeywords.count(name) != 0 ||
regex_utils::textMatches(name, s_reDotDotNumbers, false, false);
}
std::set<std::string> makeWindowsOnlyFunctions()
{
std::set<std::string> fns;
fns.insert("shell");
fns.insert("shell.exec");
fns.insert("Sys.junction");
return fns;
}
bool isWindowsOnlyFunction(const std::string& name)
{
static const std::set<std::string> s_rWindowsOnly = makeWindowsOnlyFunctions();
return core::algorithm::contains(s_rWindowsOnly, name);
}
bool isPackageAttached(const std::string& packageName)
{
SEXP namespaces = R_NilValue;
r::sexp::Protect protect;
Error error = r::exec::RFunction("search").call(&namespaces, &protect);
if (error)
{
// not fatal; we'll just presume package is not on the path
LOG_ERROR(error);
return false;
}
std::string fullPackageName = "package:";
fullPackageName += packageName;
int len = r::sexp::length(namespaces);
for (int i = 0; i < len; i++)
{
std::string ns = r::sexp::safeAsString(STRING_ELT(namespaces, i), "");
if (ns == fullPackageName)
{
return true;
}
}
return false;
}
} // namespace util
} // namespace r
} // namespace rstudio
<|endoftext|> |
<commit_before>/*!
\file
\brief
<a href="http://om-language.org">Om</a> source file.
\version
0.1.2
\date
2012-2013
\copyright
Copyright (c) <a href="http://sparist.com">Sparist</a>. All rights reserved. This program and the accompanying materials are made available under the terms of the <a href="http://www.eclipse.org/legal/epl-v10.html">Eclipse Public License, Version 1.0</a>, which accompanies this distribution.
\authors
Jason Erb - Initial API, implementation, and documentation.
*/
#if !defined( Om_ )
#include "om.hpp"
#if defined( Om_Macros_Test_ )
#define BOOST_TEST_MODULE \
OmTest
#include "boost/test/included/unit_test.hpp"
class OmFixture {
public:
OmFixture() {
Om::System::Get().Initialize( "en_US.UTF-8" );
}
};
BOOST_GLOBAL_FIXTURE( OmFixture );
bool init_unit_test() {
return( true );
}
#else
/*!
\param theArgumentCount
The argument count; must be greater than 0.
\param theArgumentArray
The argument array contains (in order):
- The program invocation.
- <em>(Optional)</em> A valid UTF-8 <a href="http://userguide.icu-project.org/locale">locale string</a>; defaults to "en_US.UTF-8".
*/
int main(
int const theArgumentCount,
char const * const theArgumentArray[]
) {
assert( 0 < theArgumentCount );
assert( theArgumentArray );
Om::System::Get().Initialize(
( 1 < theArgumentCount )?
theArgumentArray[ 1 ]:
"en_US.UTF-8"
);
typedef Om::Sources::StreamSource<> CodeUnitSource;
CodeUnitSource theCodeUnitSource( std::cin );
Om::Sources::CodePointSource< CodeUnitSource > theCodePointSource(
theCodeUnitSource,
CodeUnitSource()
);
typedef Om::Sinks::StreamSink<> CodeUnitSink;
CodeUnitSink theCodeUnitSink( std::cout );
Om::Sinks::CodePointSink< CodeUnitSink > theCodePointSink( theCodeUnitSink );
Om::System::Get().Evaluate(
theCodePointSource,
theCodePointSink
);
return( EXIT_SUCCESS );
}
#endif
#endif
<commit_msg>Turned off boost memory leak detection.<commit_after>/*!
\file
\brief
<a href="http://om-language.org">Om</a> source file.
\version
0.1.2
\date
2012-2013
\copyright
Copyright (c) <a href="http://sparist.com">Sparist</a>. All rights reserved. This program and the accompanying materials are made available under the terms of the <a href="http://www.eclipse.org/legal/epl-v10.html">Eclipse Public License, Version 1.0</a>, which accompanies this distribution.
\authors
Jason Erb - Initial API, implementation, and documentation.
*/
#if !defined( Om_ )
#include "om.hpp"
#if defined( Om_Macros_Test_ )
#define BOOST_TEST_MODULE \
OmTest
#include "boost/test/included/unit_test.hpp"
class OmFixture {
public:
OmFixture() {
Om::System::Get().Initialize( "en_US.UTF-8" );
}
};
BOOST_GLOBAL_FIXTURE( OmFixture );
bool init_unit_test() {
boost::debug::detect_memory_leaks(false);
return( true );
}
#else
/*!
\param theArgumentCount
The argument count; must be greater than 0.
\param theArgumentArray
The argument array contains (in order):
- The program invocation.
- <em>(Optional)</em> A valid UTF-8 <a href="http://userguide.icu-project.org/locale">locale string</a>; defaults to "en_US.UTF-8".
*/
int main(
int const theArgumentCount,
char const * const theArgumentArray[]
) {
assert( 0 < theArgumentCount );
assert( theArgumentArray );
Om::System::Get().Initialize(
( 1 < theArgumentCount )?
theArgumentArray[ 1 ]:
"en_US.UTF-8"
);
typedef Om::Sources::StreamSource<> CodeUnitSource;
CodeUnitSource theCodeUnitSource( std::cin );
Om::Sources::CodePointSource< CodeUnitSource > theCodePointSource(
theCodeUnitSource,
CodeUnitSource()
);
typedef Om::Sinks::StreamSink<> CodeUnitSink;
CodeUnitSink theCodeUnitSink( std::cout );
Om::Sinks::CodePointSink< CodeUnitSink > theCodePointSink( theCodeUnitSink );
Om::System::Get().Evaluate(
theCodePointSource,
theCodePointSink
);
return( EXIT_SUCCESS );
}
#endif
#endif
<|endoftext|> |
<commit_before>// Copyright 2017 The NXT 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 "tests/NXTTest.h"
#include <cstring>
class BufferMapReadTests : public NXTTest {
protected:
static void MapReadCallback(nxtBufferMapReadStatus status, const void* data, nxtCallbackUserdata userdata) {
ASSERT_EQ(NXT_BUFFER_MAP_READ_STATUS_SUCCESS, status);
ASSERT_NE(nullptr, data);
auto test = reinterpret_cast<BufferMapReadTests*>(static_cast<uintptr_t>(userdata));
test->mappedData = data;
}
const void* MapReadAsyncAndWait(const nxt::Buffer& buffer, uint32_t start, uint32_t offset) {
buffer.MapReadAsync(start, offset, MapReadCallback, static_cast<nxt::CallbackUserdata>(reinterpret_cast<uintptr_t>(this)));
while (mappedData == nullptr) {
WaitABit();
}
return mappedData;
}
private:
const void* mappedData = nullptr;
};
// Test that the simplest map read (one u32 at offset 0) works.
TEST_P(BufferMapReadTests, SmallReadAtZero) {
nxt::Buffer buffer = device.CreateBufferBuilder()
.SetSize(4)
.SetAllowedUsage(nxt::BufferUsageBit::MapRead | nxt::BufferUsageBit::TransferDst)
.SetInitialUsage(nxt::BufferUsageBit::TransferDst)
.GetResult();
uint32_t myData = 2934875;
buffer.SetSubData(0, 1, &myData);
buffer.TransitionUsage(nxt::BufferUsageBit::MapRead);
const void* mappedData = MapReadAsyncAndWait(buffer, 0, 4);
ASSERT_EQ(myData, *reinterpret_cast<const uint32_t*>(mappedData));
buffer.Unmap();
}
// Test mapping a buffer at an offset.
TEST_P(BufferMapReadTests, SmallReadAtOffset) {
nxt::Buffer buffer = device.CreateBufferBuilder()
.SetSize(4000)
.SetAllowedUsage(nxt::BufferUsageBit::MapRead | nxt::BufferUsageBit::TransferDst)
.SetInitialUsage(nxt::BufferUsageBit::TransferDst)
.GetResult();
uint32_t myData = 2934875;
buffer.SetSubData(2048 / sizeof(uint32_t), 1, &myData);
buffer.TransitionUsage(nxt::BufferUsageBit::MapRead);
const void* mappedData = MapReadAsyncAndWait(buffer, 2048, 4);
ASSERT_EQ(myData, *reinterpret_cast<const uint32_t*>(mappedData));
buffer.Unmap();
}
// Test mapping large ranges of a buffer.
TEST_P(BufferMapReadTests, LargeRead) {
constexpr uint32_t kDataSize = 1000 * 1000;
std::vector<uint32_t> myData;
for (uint32_t i = 0; i < kDataSize; ++i) {
myData.push_back(i);
}
nxt::Buffer buffer = device.CreateBufferBuilder()
.SetSize(static_cast<uint32_t>(kDataSize * sizeof(uint32_t)))
.SetAllowedUsage(nxt::BufferUsageBit::MapRead | nxt::BufferUsageBit::TransferDst)
.SetInitialUsage(nxt::BufferUsageBit::TransferDst)
.GetResult();
buffer.SetSubData(0, static_cast<uint32_t>(kDataSize), myData.data());
buffer.TransitionUsage(nxt::BufferUsageBit::MapRead);
const void* mappedData = MapReadAsyncAndWait(buffer, 0, static_cast<uint32_t>(kDataSize * sizeof(uint32_t)));
ASSERT_EQ(0, memcmp(mappedData, myData.data(), kDataSize * sizeof(uint32_t)));
buffer.Unmap();
}
NXT_INSTANTIATE_TEST(BufferMapReadTests, D3D12Backend, MetalBackend, OpenGLBackend)
class BufferSetSubDataTests : public NXTTest {
};
// Test the simplest set sub data: setting one u32 at offset 0.
TEST_P(BufferSetSubDataTests, SmallDataAtZero) {
nxt::Buffer buffer = device.CreateBufferBuilder()
.SetSize(4)
.SetAllowedUsage(nxt::BufferUsageBit::TransferSrc | nxt::BufferUsageBit::TransferDst)
.SetInitialUsage(nxt::BufferUsageBit::TransferDst)
.GetResult();
uint32_t value = 298371;
buffer.SetSubData(0, 1, &value);
EXPECT_BUFFER_U32_EQ(value, buffer, 0);
}
// Test that SetSubData offset works.
TEST_P(BufferSetSubDataTests, SmallDataAtOffset) {
nxt::Buffer buffer = device.CreateBufferBuilder()
.SetSize(4000)
.SetAllowedUsage(nxt::BufferUsageBit::TransferSrc | nxt::BufferUsageBit::TransferDst)
.SetInitialUsage(nxt::BufferUsageBit::TransferDst)
.GetResult();
constexpr uint32_t kOffset = 2000;
uint32_t value = 298371;
buffer.SetSubData(kOffset / 4, 1, &value);
EXPECT_BUFFER_U32_EQ(value, buffer, kOffset);
}
// Stress test for many calls to SetSubData
TEST_P(BufferSetSubDataTests, ManySetSubData) {
if (IsD3D12() || IsMetal()) {
// TODO([email protected]): Use ringbuffers for SetSubData on explicit APIs.
// otherwise this creates too many resources and can take freeze the driver(?)
std::cout << "Test skipped on D3D12 and Metal" << std::endl;
return;
}
constexpr uint32_t kSize = 4000 * 1000;
constexpr uint32_t kElements = 1000 * 1000;
nxt::Buffer buffer = device.CreateBufferBuilder()
.SetSize(kSize)
.SetAllowedUsage(nxt::BufferUsageBit::TransferSrc | nxt::BufferUsageBit::TransferDst)
.SetInitialUsage(nxt::BufferUsageBit::TransferDst)
.GetResult();
std::vector<uint32_t> expectedData;
for (uint32_t i = 0; i < kElements; ++i) {
buffer.SetSubData(i, 1, &i);
expectedData.push_back(i);
}
EXPECT_BUFFER_U32_RANGE_EQ(expectedData.data(), buffer, 0, kElements);
}
// Test using SetSubData for lots of data
TEST_P(BufferSetSubDataTests, LargeSetSubData) {
constexpr uint32_t kSize = 4000 * 1000;
constexpr uint32_t kElements = 1000 * 1000;
nxt::Buffer buffer = device.CreateBufferBuilder()
.SetSize(kSize)
.SetAllowedUsage(nxt::BufferUsageBit::TransferSrc | nxt::BufferUsageBit::TransferDst)
.SetInitialUsage(nxt::BufferUsageBit::TransferDst)
.GetResult();
std::vector<uint32_t> expectedData;
for (uint32_t i = 0; i < kElements; ++i) {
expectedData.push_back(i);
}
buffer.SetSubData(0, kElements, expectedData.data());
EXPECT_BUFFER_U32_RANGE_EQ(expectedData.data(), buffer, 0, kElements);
}
NXT_INSTANTIATE_TEST(BufferSetSubDataTests, D3D12Backend, MetalBackend, OpenGLBackend)
<commit_msg>Enable first tests on Vulkan!<commit_after>// Copyright 2017 The NXT 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 "tests/NXTTest.h"
#include <cstring>
class BufferMapReadTests : public NXTTest {
protected:
static void MapReadCallback(nxtBufferMapReadStatus status, const void* data, nxtCallbackUserdata userdata) {
ASSERT_EQ(NXT_BUFFER_MAP_READ_STATUS_SUCCESS, status);
ASSERT_NE(nullptr, data);
auto test = reinterpret_cast<BufferMapReadTests*>(static_cast<uintptr_t>(userdata));
test->mappedData = data;
}
const void* MapReadAsyncAndWait(const nxt::Buffer& buffer, uint32_t start, uint32_t offset) {
buffer.MapReadAsync(start, offset, MapReadCallback, static_cast<nxt::CallbackUserdata>(reinterpret_cast<uintptr_t>(this)));
while (mappedData == nullptr) {
WaitABit();
}
return mappedData;
}
private:
const void* mappedData = nullptr;
};
// Test that the simplest map read (one u32 at offset 0) works.
TEST_P(BufferMapReadTests, SmallReadAtZero) {
nxt::Buffer buffer = device.CreateBufferBuilder()
.SetSize(4)
.SetAllowedUsage(nxt::BufferUsageBit::MapRead | nxt::BufferUsageBit::TransferDst)
.SetInitialUsage(nxt::BufferUsageBit::TransferDst)
.GetResult();
uint32_t myData = 2934875;
buffer.SetSubData(0, 1, &myData);
buffer.TransitionUsage(nxt::BufferUsageBit::MapRead);
const void* mappedData = MapReadAsyncAndWait(buffer, 0, 4);
ASSERT_EQ(myData, *reinterpret_cast<const uint32_t*>(mappedData));
buffer.Unmap();
}
// Test mapping a buffer at an offset.
TEST_P(BufferMapReadTests, SmallReadAtOffset) {
nxt::Buffer buffer = device.CreateBufferBuilder()
.SetSize(4000)
.SetAllowedUsage(nxt::BufferUsageBit::MapRead | nxt::BufferUsageBit::TransferDst)
.SetInitialUsage(nxt::BufferUsageBit::TransferDst)
.GetResult();
uint32_t myData = 2934875;
buffer.SetSubData(2048 / sizeof(uint32_t), 1, &myData);
buffer.TransitionUsage(nxt::BufferUsageBit::MapRead);
const void* mappedData = MapReadAsyncAndWait(buffer, 2048, 4);
ASSERT_EQ(myData, *reinterpret_cast<const uint32_t*>(mappedData));
buffer.Unmap();
}
// Test mapping large ranges of a buffer.
TEST_P(BufferMapReadTests, LargeRead) {
constexpr uint32_t kDataSize = 1000 * 1000;
std::vector<uint32_t> myData;
for (uint32_t i = 0; i < kDataSize; ++i) {
myData.push_back(i);
}
nxt::Buffer buffer = device.CreateBufferBuilder()
.SetSize(static_cast<uint32_t>(kDataSize * sizeof(uint32_t)))
.SetAllowedUsage(nxt::BufferUsageBit::MapRead | nxt::BufferUsageBit::TransferDst)
.SetInitialUsage(nxt::BufferUsageBit::TransferDst)
.GetResult();
buffer.SetSubData(0, static_cast<uint32_t>(kDataSize), myData.data());
buffer.TransitionUsage(nxt::BufferUsageBit::MapRead);
const void* mappedData = MapReadAsyncAndWait(buffer, 0, static_cast<uint32_t>(kDataSize * sizeof(uint32_t)));
ASSERT_EQ(0, memcmp(mappedData, myData.data(), kDataSize * sizeof(uint32_t)));
buffer.Unmap();
}
NXT_INSTANTIATE_TEST(BufferMapReadTests, D3D12Backend, MetalBackend, OpenGLBackend, VulkanBackend)
class BufferSetSubDataTests : public NXTTest {
};
// Test the simplest set sub data: setting one u32 at offset 0.
TEST_P(BufferSetSubDataTests, SmallDataAtZero) {
nxt::Buffer buffer = device.CreateBufferBuilder()
.SetSize(4)
.SetAllowedUsage(nxt::BufferUsageBit::TransferSrc | nxt::BufferUsageBit::TransferDst)
.SetInitialUsage(nxt::BufferUsageBit::TransferDst)
.GetResult();
uint32_t value = 298371;
buffer.SetSubData(0, 1, &value);
EXPECT_BUFFER_U32_EQ(value, buffer, 0);
}
// Test that SetSubData offset works.
TEST_P(BufferSetSubDataTests, SmallDataAtOffset) {
nxt::Buffer buffer = device.CreateBufferBuilder()
.SetSize(4000)
.SetAllowedUsage(nxt::BufferUsageBit::TransferSrc | nxt::BufferUsageBit::TransferDst)
.SetInitialUsage(nxt::BufferUsageBit::TransferDst)
.GetResult();
constexpr uint32_t kOffset = 2000;
uint32_t value = 298371;
buffer.SetSubData(kOffset / 4, 1, &value);
EXPECT_BUFFER_U32_EQ(value, buffer, kOffset);
}
// Stress test for many calls to SetSubData
TEST_P(BufferSetSubDataTests, ManySetSubData) {
if (IsD3D12() || IsMetal()) {
// TODO([email protected]): Use ringbuffers for SetSubData on explicit APIs.
// otherwise this creates too many resources and can take freeze the driver(?)
std::cout << "Test skipped on D3D12 and Metal" << std::endl;
return;
}
constexpr uint32_t kSize = 4000 * 1000;
constexpr uint32_t kElements = 1000 * 1000;
nxt::Buffer buffer = device.CreateBufferBuilder()
.SetSize(kSize)
.SetAllowedUsage(nxt::BufferUsageBit::TransferSrc | nxt::BufferUsageBit::TransferDst)
.SetInitialUsage(nxt::BufferUsageBit::TransferDst)
.GetResult();
std::vector<uint32_t> expectedData;
for (uint32_t i = 0; i < kElements; ++i) {
buffer.SetSubData(i, 1, &i);
expectedData.push_back(i);
}
EXPECT_BUFFER_U32_RANGE_EQ(expectedData.data(), buffer, 0, kElements);
}
// Test using SetSubData for lots of data
TEST_P(BufferSetSubDataTests, LargeSetSubData) {
constexpr uint32_t kSize = 4000 * 1000;
constexpr uint32_t kElements = 1000 * 1000;
nxt::Buffer buffer = device.CreateBufferBuilder()
.SetSize(kSize)
.SetAllowedUsage(nxt::BufferUsageBit::TransferSrc | nxt::BufferUsageBit::TransferDst)
.SetInitialUsage(nxt::BufferUsageBit::TransferDst)
.GetResult();
std::vector<uint32_t> expectedData;
for (uint32_t i = 0; i < kElements; ++i) {
expectedData.push_back(i);
}
buffer.SetSubData(0, kElements, expectedData.data());
EXPECT_BUFFER_U32_RANGE_EQ(expectedData.data(), buffer, 0, kElements);
}
NXT_INSTANTIATE_TEST(BufferSetSubDataTests, D3D12Backend, MetalBackend, OpenGLBackend)
<|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: Ali Saidi
*/
#ifndef __CPU_CPUEVENT_HH__
#define __CPU_CPUEVENT_HH__
#include <vector>
#include "sim/eventq.hh"
class ThreadContext;
/** This class creates a global list of events that need a pointer to a
* thread context. When a switchover takes place the events can be migrated
* to the new thread context, otherwise you could have a wake timer interrupt
* go off on a switched out cpu or other unfortunate events. This object MUST be
* dynamically allocated to avoid it being deleted after a cpu switch happens.
* */
class CpuEvent : public Event
{
protected:
/** type of global list of cpu events. */
typedef std::vector<CpuEvent *> CpuEventList;
/** Static list of cpu events that is searched every time a cpu switch
* happens. */
static CpuEventList cpuEventList;
/** The thread context that is switched to the new cpus. */
ThreadContext *tc;
public:
CpuEvent(EventQueue *q, ThreadContext *_tc, Priority p = Default_Pri)
: Event(q, p), tc(_tc)
{ cpuEventList.push_back(this); }
/** delete the cpu event from the global list. */
~CpuEvent();
/** Update all events switching old tc to new tc.
* @param oldTc the old thread context we are switching from
* @param newTc the new thread context we are switching to.
*/
static void replaceThreadContext(ThreadContext *oldTc,
ThreadContext *newTc);
};
template <class T, void (T::* F)(ThreadContext *tc)>
class CpuEventWrapper : public CpuEvent
{
private:
T *object;
public:
CpuEventWrapper(T *obj, ThreadContext *_tc, EventQueue *q = &mainEventQueue,
Priority p = Default_Pri)
: CpuEvent(q, _tc, p), object(obj)
{ }
void process() { (object->*F)(tc); }
};
#endif // __CPU_CPUEVENT_HH__
<commit_msg>Formatting<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: Ali Saidi
*/
#ifndef __CPU_CPUEVENT_HH__
#define __CPU_CPUEVENT_HH__
#include <vector>
#include "sim/eventq.hh"
class ThreadContext;
/**
* This class creates a global list of events that need a pointer to a
* thread context. When a switchover takes place the events can be
* migrated to the new thread context, otherwise you could have a wake
* timer interrupt go off on a switched out cpu or other unfortunate
* events. This object MUST be dynamically allocated to avoid it being
* deleted after a cpu switch happens.
*/
class CpuEvent : public Event
{
protected:
/** type of global list of cpu events. */
typedef std::vector<CpuEvent *> CpuEventList;
/** Static list of cpu events that is searched every time a cpu switch
* happens. */
static CpuEventList cpuEventList;
/** The thread context that is switched to the new cpus. */
ThreadContext *tc;
public:
CpuEvent(EventQueue *q, ThreadContext *_tc, Priority p = Default_Pri)
: Event(q, p), tc(_tc)
{ cpuEventList.push_back(this); }
/** delete the cpu event from the global list. */
~CpuEvent();
/** Update all events switching old tc to new tc.
* @param oldTc the old thread context we are switching from
* @param newTc the new thread context we are switching to.
*/
static void replaceThreadContext(ThreadContext *oldTc,
ThreadContext *newTc);
};
template <class T, void (T::* F)(ThreadContext *tc)>
class CpuEventWrapper : public CpuEvent
{
private:
T *object;
public:
CpuEventWrapper(T *obj, ThreadContext *_tc,
EventQueue *q = &mainEventQueue, Priority p = Default_Pri)
: CpuEvent(q, _tc, p), object(obj)
{ }
void process() { (object->*F)(tc); }
};
#endif // __CPU_CPUEVENT_HH__
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
* Copyright (C) 2016 Andrew Zonenberg and contributors *
* *
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General *
* Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for *
* more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this program; if not, you may *
* find one here: *
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt *
* or you may search the http://www.gnu.org website for the version 2.1 license, or you may write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
**********************************************************************************************************************/
#include "Greenpak4.h"
#include <stdio.h>
#include <stdlib.h>
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
Greenpak4ShiftRegister::Greenpak4ShiftRegister(
Greenpak4Device* device,
unsigned int matrix,
unsigned int ibase,
unsigned int oword,
unsigned int cbase)
: Greenpak4BitstreamEntity(device, matrix, ibase, oword, cbase)
, m_clock(device->GetGround())
, m_input(device->GetGround())
, m_reset(device->GetGround()) //default must be reset
, m_delayA(1) //default must be 0xf so that unused ones show as unused
, m_delayB(1)
, m_invertA(false)
{
}
Greenpak4ShiftRegister::~Greenpak4ShiftRegister()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Accessors
string Greenpak4ShiftRegister::GetDescription()
{
char buf[128];
snprintf(buf, sizeof(buf), "SHREG_%d_%d", m_matrix, m_inputBaseWord);
return string(buf);
}
vector<string> Greenpak4ShiftRegister::GetInputPorts() const
{
vector<string> r;
r.push_back("IN");
r.push_back("nRST");
r.push_back("CLK");
return r;
}
void Greenpak4ShiftRegister::SetInput(string port, Greenpak4EntityOutput src)
{
if(port == "IN")
m_input = src;
else if(port == "nRST")
m_reset = src;
else if(port == "CLK")
m_clock = src;
//ignore anything else silently (should not be possible since synthesis would error out)
}
vector<string> Greenpak4ShiftRegister::GetOutputPorts() const
{
vector<string> r;
r.push_back("OUTA");
r.push_back("OUTB");
return r;
}
unsigned int Greenpak4ShiftRegister::GetOutputNetNumber(string port)
{
if(port == "OUTA")
return m_outputBaseWord + 1;
else if(port == "OUTB")
return m_outputBaseWord;
else
return -1;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Serialization
void Greenpak4ShiftRegister::CommitChanges()
{
//Get our cell, or bail if we're unassigned
auto ncell = dynamic_cast<Greenpak4NetlistCell*>(GetNetlistEntity());
if(ncell == NULL)
return;
if(ncell->HasParameter("OUTA_TAP"))
{
m_delayA = atoi(ncell->m_parameters["OUTA_TAP"].c_str());
if( (m_delayA < 1) || (m_delayA > 16) )
{
fprintf(stderr, "ERROR: Shift register OUTA_TAP must be in [1, 16]\n");
exit(-1);
}
}
if(ncell->HasParameter("OUTB_TAP"))
{
m_delayB = atoi(ncell->m_parameters["OUTB_TAP"].c_str());
if( (m_delayB < 1) || (m_delayB > 16) )
{
fprintf(stderr, "ERROR: Shift register OUTB_TAP must be in [1, 16]\n");
exit(-1);
}
}
if(ncell->HasParameter("OUTA_INVERT"))
m_invertA = atoi(ncell->m_parameters["OUTA_INVERT"].c_str());
}
bool Greenpak4ShiftRegister::Load(bool* /*bitstream*/)
{
//TODO: Do our inputs
fprintf(stderr, "unimplemented\n");
return false;
}
bool Greenpak4ShiftRegister::Save(bool* bitstream)
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// INPUT BUS
if(!WriteMatrixSelector(bitstream, m_inputBaseWord + 0, m_clock))
return false;
if(!WriteMatrixSelector(bitstream, m_inputBaseWord + 1, m_input))
return false;
if(!WriteMatrixSelector(bitstream, m_inputBaseWord + 2, m_reset))
return false;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Configuration
//Tap B comes first (considered output 0 in Silego docs but we flip so that A has the inverter)
//Note that we use 0-based tap positions, while the parameter to the shreg is 1-based delay in clocks
int delayB = m_delayB - 1;
bitstream[m_configBase + 0] = (delayB & 1) ? true : false;
bitstream[m_configBase + 1] = (delayB & 2) ? true : false;
bitstream[m_configBase + 2] = (delayB & 4) ? true : false;
bitstream[m_configBase + 3] = (delayB & 8) ? true : false;
//then tap A
int delayA = m_delayA - 1;
bitstream[m_configBase + 4] = (delayA & 1) ? true : false;
bitstream[m_configBase + 5] = (delayA & 2) ? true : false;
bitstream[m_configBase + 6] = (delayA & 4) ? true : false;
bitstream[m_configBase + 7] = (delayA & 8) ? true : false;
//then invert flag
bitstream[m_configBase + 8] = m_invertA;
return true;
}
<commit_msg>Renamed GP_SHREG cell names to be more friendly for LOC'ing<commit_after>/***********************************************************************************************************************
* Copyright (C) 2016 Andrew Zonenberg and contributors *
* *
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General *
* Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for *
* more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this program; if not, you may *
* find one here: *
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt *
* or you may search the http://www.gnu.org website for the version 2.1 license, or you may write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
**********************************************************************************************************************/
#include "Greenpak4.h"
#include <stdio.h>
#include <stdlib.h>
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
Greenpak4ShiftRegister::Greenpak4ShiftRegister(
Greenpak4Device* device,
unsigned int matrix,
unsigned int ibase,
unsigned int oword,
unsigned int cbase)
: Greenpak4BitstreamEntity(device, matrix, ibase, oword, cbase)
, m_clock(device->GetGround())
, m_input(device->GetGround())
, m_reset(device->GetGround()) //default must be reset
, m_delayA(1) //default must be 0xf so that unused ones show as unused
, m_delayB(1)
, m_invertA(false)
{
}
Greenpak4ShiftRegister::~Greenpak4ShiftRegister()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Accessors
string Greenpak4ShiftRegister::GetDescription()
{
char buf[128];
snprintf(buf, sizeof(buf), "SHREG_%d", m_matrix);
return string(buf);
}
vector<string> Greenpak4ShiftRegister::GetInputPorts() const
{
vector<string> r;
r.push_back("IN");
r.push_back("nRST");
r.push_back("CLK");
return r;
}
void Greenpak4ShiftRegister::SetInput(string port, Greenpak4EntityOutput src)
{
if(port == "IN")
m_input = src;
else if(port == "nRST")
m_reset = src;
else if(port == "CLK")
m_clock = src;
//ignore anything else silently (should not be possible since synthesis would error out)
}
vector<string> Greenpak4ShiftRegister::GetOutputPorts() const
{
vector<string> r;
r.push_back("OUTA");
r.push_back("OUTB");
return r;
}
unsigned int Greenpak4ShiftRegister::GetOutputNetNumber(string port)
{
if(port == "OUTA")
return m_outputBaseWord + 1;
else if(port == "OUTB")
return m_outputBaseWord;
else
return -1;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Serialization
void Greenpak4ShiftRegister::CommitChanges()
{
//Get our cell, or bail if we're unassigned
auto ncell = dynamic_cast<Greenpak4NetlistCell*>(GetNetlistEntity());
if(ncell == NULL)
return;
if(ncell->HasParameter("OUTA_TAP"))
{
m_delayA = atoi(ncell->m_parameters["OUTA_TAP"].c_str());
if( (m_delayA < 1) || (m_delayA > 16) )
{
fprintf(stderr, "ERROR: Shift register OUTA_TAP must be in [1, 16]\n");
exit(-1);
}
}
if(ncell->HasParameter("OUTB_TAP"))
{
m_delayB = atoi(ncell->m_parameters["OUTB_TAP"].c_str());
if( (m_delayB < 1) || (m_delayB > 16) )
{
fprintf(stderr, "ERROR: Shift register OUTB_TAP must be in [1, 16]\n");
exit(-1);
}
}
if(ncell->HasParameter("OUTA_INVERT"))
m_invertA = atoi(ncell->m_parameters["OUTA_INVERT"].c_str());
}
bool Greenpak4ShiftRegister::Load(bool* /*bitstream*/)
{
//TODO: Do our inputs
fprintf(stderr, "unimplemented\n");
return false;
}
bool Greenpak4ShiftRegister::Save(bool* bitstream)
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// INPUT BUS
if(!WriteMatrixSelector(bitstream, m_inputBaseWord + 0, m_clock))
return false;
if(!WriteMatrixSelector(bitstream, m_inputBaseWord + 1, m_input))
return false;
if(!WriteMatrixSelector(bitstream, m_inputBaseWord + 2, m_reset))
return false;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Configuration
//Tap B comes first (considered output 0 in Silego docs but we flip so that A has the inverter)
//Note that we use 0-based tap positions, while the parameter to the shreg is 1-based delay in clocks
int delayB = m_delayB - 1;
bitstream[m_configBase + 0] = (delayB & 1) ? true : false;
bitstream[m_configBase + 1] = (delayB & 2) ? true : false;
bitstream[m_configBase + 2] = (delayB & 4) ? true : false;
bitstream[m_configBase + 3] = (delayB & 8) ? true : false;
//then tap A
int delayA = m_delayA - 1;
bitstream[m_configBase + 4] = (delayA & 1) ? true : false;
bitstream[m_configBase + 5] = (delayA & 2) ? true : false;
bitstream[m_configBase + 6] = (delayA & 4) ? true : false;
bitstream[m_configBase + 7] = (delayA & 8) ? true : false;
//then invert flag
bitstream[m_configBase + 8] = m_invertA;
return true;
}
<|endoftext|> |
<commit_before>#include "include/gomoku.hpp"
#include <iostream>
#define BOARD_SIZE 19
int main(void)
{
typedef unsigned int PosType; /**< Position type */
typedef size_t SizeType;
enum PlayerType
{
NONE = 0,
BLACK = 1,
WHITE = 2
};
enum StatusType /**< Status type */
{
E_SUCCESS, /**< Success */
E_GAME_NOT_RUNNING, /**< The game is not running */
E_POSITION_ERROR /**< The provided position is not able to put */
};
game::Gomoku<BOARD_SIZE> game;
PosType screen[BOARD_SIZE][BOARD_SIZE];
while(game.IsRunning())
{
{
game.CopyBoard(screen);
printf(" ");
for(SizeType i = 0; i < BOARD_SIZE; ++i)
printf("%2d ", i);
printf("\n");
for(SizeType i = 0; i < BOARD_SIZE; ++i)
{
printf("%2d ", i);
for(SizeType j = 0; j < BOARD_SIZE; ++j)
{
if(screen[i][j] == BLACK)
printf(" %c", 'o');
else if(screen[i][j] == WHITE)
printf(" %c", 'x');
else
printf(" %c", '.');
}
printf("\n");
}
}
PosType x, y;
std::cout << "Player "
<< ((game.CurrentTurn() == BLACK) ? "O" : "X")
<< "'s turn."
<< std::endl
<< "Enter position (x y): ";
std::cin >> x;
std::cin >> y;
StatusType status = (StatusType)game.PutStone(x, y);
if(status == E_POSITION_ERROR)
std::cout << "Error: E_POSITION_ERROR" << std::endl;
if(status == E_GAME_NOT_RUNNING)
std::cout << "Warning: E_GAME_NOT_RUNNING" << std::endl;
}
std::cout << "Player "
<< ((game.Winner() == BLACK) ? "O" : "X")
<< " is the winner"
<< std::endl;
return 0;
}
<commit_msg>Replace type definitions to use class' definition<commit_after>#include "include/gomoku.hpp"
#include <iostream>
#define BOARD_SIZE 19
int main(void)
{
typedef game::Gomoku<BOARD_SIZE> Gomoku;
typedef Gomoku::PosType PosType; /**< Position type */
typedef Gomoku::SizeType SizeType;
Gomoku game;
PosType screen[BOARD_SIZE][BOARD_SIZE];
while(game.IsRunning())
{
{
game.CopyBoard(screen);
printf(" ");
for(SizeType i = 0; i < BOARD_SIZE; ++i)
printf("%2d ", i);
printf("\n");
for(SizeType i = 0; i < BOARD_SIZE; ++i)
{
printf("%2d ", i);
for(SizeType j = 0; j < BOARD_SIZE; ++j)
{
if(screen[i][j] == Gomoku::BLACK)
printf(" %c", 'o');
else if(screen[i][j] == Gomoku::WHITE)
printf(" %c", 'x');
else
printf(" %c", '.');
}
printf("\n");
}
}
PosType x, y;
std::cout << "Player "
<< ((game.CurrentTurn() == Gomoku::BLACK) ? "O" : "X")
<< "'s turn."
<< std::endl
<< "Enter position (x y): ";
std::cin >> x;
std::cin >> y;
Gomoku::StatusType status = (Gomoku::StatusType)game.PutStone(x, y);
if(status == Gomoku::E_POSITION_ERROR)
std::cout << "Error: E_POSITION_ERROR" << std::endl;
if(status == Gomoku::E_GAME_NOT_RUNNING)
std::cout << "Warning: E_GAME_NOT_RUNNING" << std::endl;
}
std::cout << "Player "
<< ((game.Winner() == Gomoku::BLACK) ? "O" : "X")
<< " is the winner"
<< std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "Copyright (c) 2012-2013 Tokutek Inc. All rights reserved."
#ident "$Id$"
#include "backup_manager.h"
#include "real_syscalls.h"
#include "backup_debug.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#if DEBUG_HOTBACKUP
#define WARN(string, arg) HotBackup::CaptureWarn(string, arg)
#define TRACE(string, arg) HotBackup::CaptureTrace(string, arg)
#define ERROR(string, arg) HotBackup::CaptureError(string, arg)
#else
#define WARN(string, arg)
#define TRACE(string, arg)
#define ERROR(string, arg)
#endif
///////////////////////////////////////////////////////////////////////////////
//
// backup_manager() -
//
// Description:
//
// Constructor.
//
backup_manager::backup_manager()
: m_doing_backup(false),
m_doing_copy(true), // <CER> Set to false to turn off copy, for debugging purposes.
m_session(NULL),
m_throttle(ULONG_MAX)
{
int r = pthread_mutex_init(&m_mutex, NULL);
assert(r == 0);
r = pthread_mutex_init(&m_session_mutex, NULL);
assert(r == 0);
}
///////////////////////////////////////////////////////////////////////////////
//
// do_backup() -
//
// Description:
//
//
//
int backup_manager::do_backup(const char *source, const char *dest, backup_callbacks calls) {
int r = calls.poll(0, "Preparing backup");
if (r != 0) {
calls.report_error(r, "User aborted backup");
goto error_out;
}
r = pthread_mutex_trylock(&m_mutex);
if (r != 0) {
if (r==EBUSY) {
calls.report_error(r, "Another backup is in progress.");
goto error_out;
}
goto error_out;
}
pthread_mutex_lock(&m_session_mutex);
m_session = new backup_session(source, dest, calls);
pthread_mutex_unlock(&m_session_mutex);
if (!m_session->directories_set()) {
// TODO: Disambiguate between whether the source or destination string does not exist.
calls.report_error(ENOENT, "Either of the given backup directories do not exist");
r = ENOENT;
goto unlock_out;
}
r = this->prepare_directories_for_backup(*m_session);
if (r != 0) {
goto unlock_out;
}
r = m_session->do_copy();
if (r != 0) {
// This means we couldn't start the copy thread (ex: pthread error).
goto unlock_out;
}
// TODO: Print the current time after CAPTURE has been disabled.
unlock_out:
pthread_mutex_lock(&m_session_mutex);
delete m_session;
m_session = NULL;
pthread_mutex_unlock(&m_session_mutex);
{
int pthread_error = pthread_mutex_unlock(&m_mutex);
if (pthread_error != 0) {
// TODO: Should there be a way to disable backup permanently in this case?
calls.report_error(pthread_error, "pthread_mutex_unlock failed. Backup system is probably broken");
if (r != 0) {
r = pthread_error;
}
}
}
error_out:
return r;
}
int open_path(const char *file_path);
///////////////////////////////////////////////////////////////////////////////
//
int backup_manager::prepare_directories_for_backup(backup_session &session)
{
int r = 0;
// Loop through all the current file descriptions and prepare them
// for backup.
for (int i = 0; i < m_map.size(); ++i) {
file_description *file = m_map.get(i);
if (file == NULL) {
continue;
}
const char * source_path = file->get_full_source_name();
if (!session.is_prefix(source_path)) {
continue;
}
char * file_name = session.translate_prefix(source_path);
file->prepare_for_backup(file_name);
free(file_name);
int r = open_path(file_name);
if (r != 0) {
// TODO: Could not open path, abort backup.
session.abort();
goto out;
}
r = file->create();
if (r != 0) {
// TODO: Could not create the file, abort backup.
session.abort();
goto out;
}
}
out:
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// create() -
//
// Description:
//
// TBD: How is create different from open? Is the only
// difference that we KNOW the file doesn't yet exist (from
// copy) for the create case?
//
void backup_manager::create(int fd, const char *file)
{
TRACE("entering create() with fd = ", fd);
m_map.put(fd);
file_description *description = m_map.get(fd);
description->set_full_source_name(file);
pthread_mutex_lock(&m_session_mutex);
if (m_session != NULL) {
char *backup_file_name = m_session->capture_create(file);
if (backup_file_name != NULL) {
description->prepare_for_backup(backup_file_name);
int r = description->create();
if(r != 0) {
// TODO: abort backup, creation of backup file failed.
m_session->abort();
}
free((void*)backup_file_name);
}
}
pthread_mutex_unlock(&m_session_mutex);
}
///////////////////////////////////////////////////////////////////////////////
//
// open() -
//
// Description:
//
// If the given file is in our source directory, this method
// creates a new file_description object and opens the file in
// the backup directory. We need the bakcup copy open because
// it may be updated if and when the user updates the original/source
// copy of the file.
//
void backup_manager::open(int fd, const char *file, int oflag)
{
TRACE("entering open() with fd = ", fd);
m_map.put(fd);
file_description *description = m_map.get(fd);
description->set_full_source_name(file);
pthread_mutex_lock(&m_session_mutex);
if(m_session != NULL) {
char *backup_file_name = m_session->capture_open(file);
if(backup_file_name != NULL) {
description->prepare_for_backup(backup_file_name);
int r = description->open();
if(r != 0) {
// TODO: abort backup, open failed.
m_session->abort();
}
free((void*)backup_file_name);
}
}
pthread_mutex_unlock(&m_session_mutex);
// TODO: Remove this dead code.
oflag++;
}
///////////////////////////////////////////////////////////////////////////////
//
// close() -
//
// Description:
//
// Find and deallocate file description based on incoming fd.
//
void backup_manager::close(int fd)
{
TRACE("entering close() with fd = ", fd);
m_map.erase(fd); // If the fd exists in the map, close it and remove it from the mmap.
}
///////////////////////////////////////////////////////////////////////////////
//
// write() -
//
// Description:
//
// Using the given file descriptor, this method updates the
// backup copy of a prevously opened file.
// Also does the write itself (the write is in here so that a lock can be obtained to protect the file offset)
//
ssize_t backup_manager::write(int fd, const void *buf, size_t nbyte)
{
TRACE("entering write() with fd = ", fd);
ssize_t r = 0;
file_description *description = m_map.get(fd);
if (description == NULL) {
r = call_real_write(fd, buf, nbyte);
} else {
description->lock();
r = call_real_write(fd, buf, nbyte);
// TODO: Don't call our write if the first one fails.
description->write(r, buf);
description->unlock();
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// read() -
//
// Description:
//
// Do the read.
//
ssize_t backup_manager::read(int fd, void *buf, size_t nbyte) {
ssize_t r = 0;
TRACE("entering write() with fd = ", fd);
file_description *description = m_map.get(fd);
if (description == NULL) {
r = call_real_read(fd, buf, nbyte);
} else {
description->lock();
r = call_real_read(fd, buf, nbyte);
// TODO: Don't perform our read if the first one fails.
description->read(r);
description->unlock();
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// pwrite() -
//
// Description:
//
// Same as regular write, but uses additional offset argument
// to write to a particular position in the backup file.
//
void backup_manager::pwrite(int fd, const void *buf, size_t nbyte, off_t offset)
{
TRACE("entering pwrite() with fd = ", fd);
file_description *description = NULL;
description = m_map.get(fd);
if (description == NULL) {
return;
}
int r = description->pwrite(buf, nbyte, offset);
if(r != 0) {
// TODO: abort backup, pwrite on the backup file failed.
}
}
///////////////////////////////////////////////////////////////////////////////
//
// seek() -
//
// Description:
//
// Move the backup file descriptor to the new position. This allows
// upcoming intercepted writes to be backed up properly.
//
off_t backup_manager::lseek(int fd, size_t nbyte, int whence) {
TRACE("entering seek() with fd = ", fd);
file_description *description = NULL;
description = m_map.get(fd);
if (description == NULL) {
return call_real_lseek(fd, nbyte, whence);
} else {
description->lock();
off_t new_offset = call_real_lseek(fd, nbyte, whence);
description->lseek(new_offset);
description->unlock();
return new_offset;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// rename() -
//
// Description:
//
// TBD...
//
void backup_manager::rename(const char *oldpath, const char *newpath)
{
TRACE("entering rename()...", "");
TRACE("-> old path = ", oldpath);
TRACE("-> new path = ", newpath);
// TODO:
oldpath++;
newpath++;
}
///////////////////////////////////////////////////////////////////////////////
//
// ftruncate() -
//
// Description:
//
// TBD...
//
void backup_manager::ftruncate(int fd, off_t length)
{
int r = 0;
TRACE("entering ftruncate with fd = ", fd);
file_description *description = m_map.get(fd);
if (description != NULL) {
r = description->truncate(length);
}
if(r != 0) {
// TODO: Abort the backup, truncate failed on the file.
}
}
///////////////////////////////////////////////////////////////////////////////
//
// truncate() -
//
// Description:
//
// TBD...
//
void backup_manager::truncate(const char *path, off_t length)
{
TRACE("entering truncate() with path = ", path);
// TODO:
// 1. Convert the path to the backup dir.
// 2. Call real_ftruncate directly.
if(path) {
length++;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// mkdir() -
//
// Description:
//
// TBD...
//
void backup_manager::mkdir(const char *pathname)
{
pthread_mutex_lock(&m_session_mutex);
if(m_session != NULL) {
m_session->capture_mkdir(pathname);
}
pthread_mutex_unlock(&m_session_mutex);
}
///////////////////////////////////////////////////////////////////////////////
//
void backup_manager::set_throttle(unsigned long bytes_per_second) {
__atomic_store(&m_throttle, &bytes_per_second, __ATOMIC_SEQ_CST); // sequential consistency is probably too much, but this isn't called often
}
///////////////////////////////////////////////////////////////////////////////
//
unsigned long backup_manager::get_throttle(void) {
unsigned long ret;
__atomic_load(&m_throttle, &ret, __ATOMIC_SEQ_CST);
return ret;
}
<commit_msg>Refs #6363. freed it one line too early.<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "Copyright (c) 2012-2013 Tokutek Inc. All rights reserved."
#ident "$Id$"
#include "backup_manager.h"
#include "real_syscalls.h"
#include "backup_debug.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#if DEBUG_HOTBACKUP
#define WARN(string, arg) HotBackup::CaptureWarn(string, arg)
#define TRACE(string, arg) HotBackup::CaptureTrace(string, arg)
#define ERROR(string, arg) HotBackup::CaptureError(string, arg)
#else
#define WARN(string, arg)
#define TRACE(string, arg)
#define ERROR(string, arg)
#endif
///////////////////////////////////////////////////////////////////////////////
//
// backup_manager() -
//
// Description:
//
// Constructor.
//
backup_manager::backup_manager()
: m_doing_backup(false),
m_doing_copy(true), // <CER> Set to false to turn off copy, for debugging purposes.
m_session(NULL),
m_throttle(ULONG_MAX)
{
int r = pthread_mutex_init(&m_mutex, NULL);
assert(r == 0);
r = pthread_mutex_init(&m_session_mutex, NULL);
assert(r == 0);
}
///////////////////////////////////////////////////////////////////////////////
//
// do_backup() -
//
// Description:
//
//
//
int backup_manager::do_backup(const char *source, const char *dest, backup_callbacks calls) {
int r = calls.poll(0, "Preparing backup");
if (r != 0) {
calls.report_error(r, "User aborted backup");
goto error_out;
}
r = pthread_mutex_trylock(&m_mutex);
if (r != 0) {
if (r==EBUSY) {
calls.report_error(r, "Another backup is in progress.");
goto error_out;
}
goto error_out;
}
pthread_mutex_lock(&m_session_mutex);
m_session = new backup_session(source, dest, calls);
pthread_mutex_unlock(&m_session_mutex);
if (!m_session->directories_set()) {
// TODO: Disambiguate between whether the source or destination string does not exist.
calls.report_error(ENOENT, "Either of the given backup directories do not exist");
r = ENOENT;
goto unlock_out;
}
r = this->prepare_directories_for_backup(*m_session);
if (r != 0) {
goto unlock_out;
}
r = m_session->do_copy();
if (r != 0) {
// This means we couldn't start the copy thread (ex: pthread error).
goto unlock_out;
}
// TODO: Print the current time after CAPTURE has been disabled.
unlock_out:
pthread_mutex_lock(&m_session_mutex);
delete m_session;
m_session = NULL;
pthread_mutex_unlock(&m_session_mutex);
{
int pthread_error = pthread_mutex_unlock(&m_mutex);
if (pthread_error != 0) {
// TODO: Should there be a way to disable backup permanently in this case?
calls.report_error(pthread_error, "pthread_mutex_unlock failed. Backup system is probably broken");
if (r != 0) {
r = pthread_error;
}
}
}
error_out:
return r;
}
int open_path(const char *file_path);
///////////////////////////////////////////////////////////////////////////////
//
int backup_manager::prepare_directories_for_backup(backup_session &session)
{
int r = 0;
// Loop through all the current file descriptions and prepare them
// for backup.
for (int i = 0; i < m_map.size(); ++i) {
file_description *file = m_map.get(i);
if (file == NULL) {
continue;
}
const char * source_path = file->get_full_source_name();
if (!session.is_prefix(source_path)) {
continue;
}
char * file_name = session.translate_prefix(source_path);
file->prepare_for_backup(file_name);
int r = open_path(file_name);
free(file_name);
if (r != 0) {
// TODO: Could not open path, abort backup.
session.abort();
goto out;
}
r = file->create();
if (r != 0) {
// TODO: Could not create the file, abort backup.
session.abort();
goto out;
}
}
out:
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// create() -
//
// Description:
//
// TBD: How is create different from open? Is the only
// difference that we KNOW the file doesn't yet exist (from
// copy) for the create case?
//
void backup_manager::create(int fd, const char *file)
{
TRACE("entering create() with fd = ", fd);
m_map.put(fd);
file_description *description = m_map.get(fd);
description->set_full_source_name(file);
pthread_mutex_lock(&m_session_mutex);
if (m_session != NULL) {
char *backup_file_name = m_session->capture_create(file);
if (backup_file_name != NULL) {
description->prepare_for_backup(backup_file_name);
int r = description->create();
if(r != 0) {
// TODO: abort backup, creation of backup file failed.
m_session->abort();
}
free((void*)backup_file_name);
}
}
pthread_mutex_unlock(&m_session_mutex);
}
///////////////////////////////////////////////////////////////////////////////
//
// open() -
//
// Description:
//
// If the given file is in our source directory, this method
// creates a new file_description object and opens the file in
// the backup directory. We need the bakcup copy open because
// it may be updated if and when the user updates the original/source
// copy of the file.
//
void backup_manager::open(int fd, const char *file, int oflag)
{
TRACE("entering open() with fd = ", fd);
m_map.put(fd);
file_description *description = m_map.get(fd);
description->set_full_source_name(file);
pthread_mutex_lock(&m_session_mutex);
if(m_session != NULL) {
char *backup_file_name = m_session->capture_open(file);
if(backup_file_name != NULL) {
description->prepare_for_backup(backup_file_name);
int r = description->open();
if(r != 0) {
// TODO: abort backup, open failed.
m_session->abort();
}
free((void*)backup_file_name);
}
}
pthread_mutex_unlock(&m_session_mutex);
// TODO: Remove this dead code.
oflag++;
}
///////////////////////////////////////////////////////////////////////////////
//
// close() -
//
// Description:
//
// Find and deallocate file description based on incoming fd.
//
void backup_manager::close(int fd)
{
TRACE("entering close() with fd = ", fd);
m_map.erase(fd); // If the fd exists in the map, close it and remove it from the mmap.
}
///////////////////////////////////////////////////////////////////////////////
//
// write() -
//
// Description:
//
// Using the given file descriptor, this method updates the
// backup copy of a prevously opened file.
// Also does the write itself (the write is in here so that a lock can be obtained to protect the file offset)
//
ssize_t backup_manager::write(int fd, const void *buf, size_t nbyte)
{
TRACE("entering write() with fd = ", fd);
ssize_t r = 0;
file_description *description = m_map.get(fd);
if (description == NULL) {
r = call_real_write(fd, buf, nbyte);
} else {
description->lock();
r = call_real_write(fd, buf, nbyte);
// TODO: Don't call our write if the first one fails.
description->write(r, buf);
description->unlock();
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// read() -
//
// Description:
//
// Do the read.
//
ssize_t backup_manager::read(int fd, void *buf, size_t nbyte) {
ssize_t r = 0;
TRACE("entering write() with fd = ", fd);
file_description *description = m_map.get(fd);
if (description == NULL) {
r = call_real_read(fd, buf, nbyte);
} else {
description->lock();
r = call_real_read(fd, buf, nbyte);
// TODO: Don't perform our read if the first one fails.
description->read(r);
description->unlock();
}
return r;
}
///////////////////////////////////////////////////////////////////////////////
//
// pwrite() -
//
// Description:
//
// Same as regular write, but uses additional offset argument
// to write to a particular position in the backup file.
//
void backup_manager::pwrite(int fd, const void *buf, size_t nbyte, off_t offset)
{
TRACE("entering pwrite() with fd = ", fd);
file_description *description = NULL;
description = m_map.get(fd);
if (description == NULL) {
return;
}
int r = description->pwrite(buf, nbyte, offset);
if(r != 0) {
// TODO: abort backup, pwrite on the backup file failed.
}
}
///////////////////////////////////////////////////////////////////////////////
//
// seek() -
//
// Description:
//
// Move the backup file descriptor to the new position. This allows
// upcoming intercepted writes to be backed up properly.
//
off_t backup_manager::lseek(int fd, size_t nbyte, int whence) {
TRACE("entering seek() with fd = ", fd);
file_description *description = NULL;
description = m_map.get(fd);
if (description == NULL) {
return call_real_lseek(fd, nbyte, whence);
} else {
description->lock();
off_t new_offset = call_real_lseek(fd, nbyte, whence);
description->lseek(new_offset);
description->unlock();
return new_offset;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// rename() -
//
// Description:
//
// TBD...
//
void backup_manager::rename(const char *oldpath, const char *newpath)
{
TRACE("entering rename()...", "");
TRACE("-> old path = ", oldpath);
TRACE("-> new path = ", newpath);
// TODO:
oldpath++;
newpath++;
}
///////////////////////////////////////////////////////////////////////////////
//
// ftruncate() -
//
// Description:
//
// TBD...
//
void backup_manager::ftruncate(int fd, off_t length)
{
int r = 0;
TRACE("entering ftruncate with fd = ", fd);
file_description *description = m_map.get(fd);
if (description != NULL) {
r = description->truncate(length);
}
if(r != 0) {
// TODO: Abort the backup, truncate failed on the file.
}
}
///////////////////////////////////////////////////////////////////////////////
//
// truncate() -
//
// Description:
//
// TBD...
//
void backup_manager::truncate(const char *path, off_t length)
{
TRACE("entering truncate() with path = ", path);
// TODO:
// 1. Convert the path to the backup dir.
// 2. Call real_ftruncate directly.
if(path) {
length++;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// mkdir() -
//
// Description:
//
// TBD...
//
void backup_manager::mkdir(const char *pathname)
{
pthread_mutex_lock(&m_session_mutex);
if(m_session != NULL) {
m_session->capture_mkdir(pathname);
}
pthread_mutex_unlock(&m_session_mutex);
}
///////////////////////////////////////////////////////////////////////////////
//
void backup_manager::set_throttle(unsigned long bytes_per_second) {
__atomic_store(&m_throttle, &bytes_per_second, __ATOMIC_SEQ_CST); // sequential consistency is probably too much, but this isn't called often
}
///////////////////////////////////////////////////////////////////////////////
//
unsigned long backup_manager::get_throttle(void) {
unsigned long ret;
__atomic_load(&m_throttle, &ret, __ATOMIC_SEQ_CST);
return ret;
}
<|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 "remoting/base/resources.h"
#include "remoting/base/string_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace remoting {
// TODO(alexeypa): Reenable the test once http://crbug.com/269143 is fixed.
#if defined(OS_WIN) || defined(OS_MACOSX)
#define MAYBE_ProductName ProductName
#else
#define MAYBE_ProductName DISABLED_ProductName
#endif
class ResourcesTest : public testing::Test {
protected:
ResourcesTest(): resources_available_(false) {
}
virtual void SetUp() OVERRIDE {
resources_available_ = LoadResources("en-US");
}
virtual void TearDown() OVERRIDE {
UnloadResources();
}
bool resources_available_;
};
TEST_F(ResourcesTest, ProductName) {
#if defined(GOOGLE_CHROME_BUILD)
std::string expected_product_name = "Chrome Remote Desktop";
#else // defined(GOOGLE_CHROME_BUILD)
std::string expected_product_name = "Chromoting";
#endif // !defined(GOOGLE_CHROME_BUILD)
// Chrome-style i18n is not used on Windows.
#if defined(OS_WIN)
EXPECT_FALSE(resources_available_);
#else
EXPECT_TRUE(resources_available_);
#endif
if (resources_available_) {
EXPECT_EQ(expected_product_name,
l10n_util::GetStringUTF8(IDR_PRODUCT_NAME));
}
}
} // namespace remoting
<commit_msg>disable ResourcesTest.ProductName<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 "remoting/base/resources.h"
#include "remoting/base/string_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace remoting {
class ResourcesTest : public testing::Test {
protected:
ResourcesTest(): resources_available_(false) {
}
virtual void SetUp() OVERRIDE {
resources_available_ = LoadResources("en-US");
}
virtual void TearDown() OVERRIDE {
UnloadResources();
}
bool resources_available_;
};
// TODO(alexeypa): Reenable the test once http://crbug.com/269143 is fixed.
#if !defined(OS_CHROMEOS)
#define MAYBE_ProductName ProductName
#else
#define MAYBE_ProductName DISABLED_ProductName
#endif
TEST_F(ResourcesTest, MAYBE_ProductName) {
#if defined(GOOGLE_CHROME_BUILD)
std::string expected_product_name = "Chrome Remote Desktop";
#else // defined(GOOGLE_CHROME_BUILD)
std::string expected_product_name = "Chromoting";
#endif // !defined(GOOGLE_CHROME_BUILD)
// Chrome-style i18n is not used on Windows.
#if defined(OS_WIN)
EXPECT_FALSE(resources_available_);
#else
EXPECT_TRUE(resources_available_);
#endif
if (resources_available_) {
EXPECT_EQ(expected_product_name,
l10n_util::GetStringUTF8(IDR_PRODUCT_NAME));
}
}
} // namespace remoting
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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 "remoting/host/event_executor_win.h"
#include <windows.h>
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "remoting/host/capturer.h"
#include "remoting/proto/event.pb.h"
#include "ui/base/keycodes/keyboard_codes.h"
namespace remoting {
using protocol::MouseEvent;
using protocol::KeyEvent;
EventExecutorWin::EventExecutorWin(
MessageLoop* message_loop, Capturer* capturer)
: message_loop_(message_loop),
capturer_(capturer) {
}
EventExecutorWin::~EventExecutorWin() {
}
void EventExecutorWin::InjectKeyEvent(const KeyEvent* event, Task* done) {
if (MessageLoop::current() != message_loop_) {
message_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &EventExecutorWin::InjectKeyEvent,
event, done));
return;
}
HandleKey(event);
done->Run();
delete done;
}
void EventExecutorWin::InjectMouseEvent(const MouseEvent* event, Task* done) {
if (MessageLoop::current() != message_loop_) {
message_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &EventExecutorWin::InjectMouseEvent,
event, done));
return;
}
HandleMouse(event);
done->Run();
delete done;
}
void EventExecutorWin::HandleKey(const KeyEvent* event) {
int key = event->keycode();
bool down = event->pressed();
// Calculate scan code from virtual key.
HKL hkl = GetKeyboardLayout(0);
int scan_code = MapVirtualKeyEx(key, MAPVK_VK_TO_VSC_EX, hkl);
INPUT input;
input.type = INPUT_KEYBOARD;
input.ki.time = 0;
input.ki.wVk = key;
input.ki.wScan = scan_code;
// Flag to mark extended 'e0' key scancodes. Without this, the left and
// right windows keys will not be handled properly (on US keyboard).
if ((scan_code & 0xFF00) == 0xE000) {
input.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
}
// Flag to mark keyup events. Default is keydown.
if (!down) {
input.ki.dwFlags |= KEYEVENTF_KEYUP;
}
SendInput(1, &input, sizeof(INPUT));
}
protocol::InputStub* CreateEventExecutor(MessageLoop* message_loop,
Capturer* capturer) {
return new EventExecutorWin(message_loop, capturer);
}
void EventExecutorWin::HandleMouse(const MouseEvent* event) {
// TODO(garykac) Collapse mouse (x,y) and button events into a single
// input event when possible.
if (event->has_x() && event->has_y()) {
int x = event->x();
int y = event->y();
INPUT input;
input.type = INPUT_MOUSE;
input.mi.time = 0;
input.mi.dx = static_cast<int>((x * 65535) / capturer_->width());
input.mi.dy = static_cast<int>((y * 65535) / capturer_->height());
input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
SendInput(1, &input, sizeof(INPUT));
}
if (event->has_wheel_offset_x() && event->has_wheel_offset_y()) {
INPUT wheel;
wheel.type = INPUT_MOUSE;
wheel.mi.time = 0;
int dx = event->wheel_offset_x();
int dy = event->wheel_offset_y();
if (dx != 0) {
wheel.mi.mouseData = dx;
wheel.mi.dwFlags = MOUSEEVENTF_HWHEEL;
SendInput(1, &wheel, sizeof(INPUT));
}
if (dy != 0) {
wheel.mi.mouseData = dy;
wheel.mi.dwFlags = MOUSEEVENTF_WHEEL;
SendInput(1, &wheel, sizeof(INPUT));
}
}
if (event->has_button() && event->has_button_down()) {
INPUT button_event;
button_event.type = INPUT_MOUSE;
button_event.mi.time = 0;
button_event.mi.dx = 0;
button_event.mi.dy = 0;
MouseEvent::MouseButton button = event->button();
bool down = event->button_down();
if (button == MouseEvent::BUTTON_LEFT) {
button_event.mi.dwFlags =
down ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP;
} else if (button == MouseEvent::BUTTON_MIDDLE) {
button_event.mi.dwFlags =
down ? MOUSEEVENTF_MIDDLEDOWN : MOUSEEVENTF_MIDDLEUP;
} else if (button == MouseEvent::BUTTON_RIGHT) {
button_event.mi.dwFlags =
down ? MOUSEEVENTF_RIGHTDOWN : MOUSEEVENTF_RIGHTUP;
} else {
button_event.mi.dwFlags =
down ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP;
}
SendInput(1, &button_event, sizeof(INPUT));
}
}
} // namespace remoting
<commit_msg>Fix key missing problem on windows<commit_after>// Copyright (c) 2010 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 "remoting/host/event_executor_win.h"
#include <windows.h>
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "remoting/host/capturer.h"
#include "remoting/proto/event.pb.h"
#include "ui/base/keycodes/keyboard_codes.h"
namespace remoting {
using protocol::MouseEvent;
using protocol::KeyEvent;
EventExecutorWin::EventExecutorWin(
MessageLoop* message_loop, Capturer* capturer)
: message_loop_(message_loop),
capturer_(capturer) {
}
EventExecutorWin::~EventExecutorWin() {
}
void EventExecutorWin::InjectKeyEvent(const KeyEvent* event, Task* done) {
if (MessageLoop::current() != message_loop_) {
message_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &EventExecutorWin::InjectKeyEvent,
event, done));
return;
}
HandleKey(event);
done->Run();
delete done;
}
void EventExecutorWin::InjectMouseEvent(const MouseEvent* event, Task* done) {
if (MessageLoop::current() != message_loop_) {
message_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &EventExecutorWin::InjectMouseEvent,
event, done));
return;
}
HandleMouse(event);
done->Run();
delete done;
}
void EventExecutorWin::HandleKey(const KeyEvent* event) {
int key = event->keycode();
bool down = event->pressed();
// Calculate scan code from virtual key.
HKL hkl = GetKeyboardLayout(0);
int scan_code = MapVirtualKeyEx(key, MAPVK_VK_TO_VSC_EX, hkl);
INPUT input;
memset(&input, 0, sizeof(input));
input.type = INPUT_KEYBOARD;
input.ki.time = 0;
input.ki.wVk = key;
input.ki.wScan = scan_code;
// Flag to mark extended 'e0' key scancodes. Without this, the left and
// right windows keys will not be handled properly (on US keyboard).
if ((scan_code & 0xFF00) == 0xE000) {
input.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
}
// Flag to mark keyup events. Default is keydown.
if (!down) {
input.ki.dwFlags |= KEYEVENTF_KEYUP;
}
SendInput(1, &input, sizeof(INPUT));
}
protocol::InputStub* CreateEventExecutor(MessageLoop* message_loop,
Capturer* capturer) {
return new EventExecutorWin(message_loop, capturer);
}
void EventExecutorWin::HandleMouse(const MouseEvent* event) {
// TODO(garykac) Collapse mouse (x,y) and button events into a single
// input event when possible.
if (event->has_x() && event->has_y()) {
int x = event->x();
int y = event->y();
INPUT input;
input.type = INPUT_MOUSE;
input.mi.time = 0;
input.mi.dx = static_cast<int>((x * 65535) / capturer_->width());
input.mi.dy = static_cast<int>((y * 65535) / capturer_->height());
input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
SendInput(1, &input, sizeof(INPUT));
}
if (event->has_wheel_offset_x() && event->has_wheel_offset_y()) {
INPUT wheel;
wheel.type = INPUT_MOUSE;
wheel.mi.time = 0;
int dx = event->wheel_offset_x();
int dy = event->wheel_offset_y();
if (dx != 0) {
wheel.mi.mouseData = dx;
wheel.mi.dwFlags = MOUSEEVENTF_HWHEEL;
SendInput(1, &wheel, sizeof(INPUT));
}
if (dy != 0) {
wheel.mi.mouseData = dy;
wheel.mi.dwFlags = MOUSEEVENTF_WHEEL;
SendInput(1, &wheel, sizeof(INPUT));
}
}
if (event->has_button() && event->has_button_down()) {
INPUT button_event;
button_event.type = INPUT_MOUSE;
button_event.mi.time = 0;
button_event.mi.dx = 0;
button_event.mi.dy = 0;
MouseEvent::MouseButton button = event->button();
bool down = event->button_down();
if (button == MouseEvent::BUTTON_LEFT) {
button_event.mi.dwFlags =
down ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP;
} else if (button == MouseEvent::BUTTON_MIDDLE) {
button_event.mi.dwFlags =
down ? MOUSEEVENTF_MIDDLEDOWN : MOUSEEVENTF_MIDDLEUP;
} else if (button == MouseEvent::BUTTON_RIGHT) {
button_event.mi.dwFlags =
down ? MOUSEEVENTF_RIGHTDOWN : MOUSEEVENTF_RIGHTUP;
} else {
button_event.mi.dwFlags =
down ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP;
}
SendInput(1, &button_event, sizeof(INPUT));
}
}
} // namespace remoting
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file reference_line.cc
**/
#include "modules/planning/reference_line/reference_line.h"
#include <algorithm>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "boost/math/tools/minima.hpp"
#include "modules/common/log.h"
#include "modules/common/math/angle.h"
#include "modules/common/math/linear_interpolation.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/math/double.h"
namespace apollo {
namespace planning {
using ReferenceMapLine = hdmap::Path;
ReferenceLine::ReferenceLine(
const std::vector<ReferencePoint>& reference_points)
: reference_points_(reference_points),
reference_map_line_(ReferenceMapLine(std::vector<hdmap::MapPathPoint>(
reference_points.begin(), reference_points.end()))) {}
ReferenceLine::ReferenceLine(
const std::vector<ReferencePoint>& reference_points,
const std::vector<hdmap::LaneSegment>& lane_segments,
const double max_approximation_error)
: reference_points_(reference_points),
reference_map_line_(ReferenceMapLine(
std::vector<hdmap::MapPathPoint>(reference_points.begin(),
reference_points.end()),
lane_segments, max_approximation_error)) {}
ReferencePoint ReferenceLine::get_reference_point(const double s) const {
const auto& accumulated_s = reference_map_line_.accumulated_s();
if (s < accumulated_s.front()) {
AWARN << "The requested s is nearer than the start point of the reference "
"line; reference line starts at "
<< accumulated_s.back() << ", requested " << s << ".";
ReferencePoint ref_point(reference_map_line_.get_smooth_point(s),
0.0, 0.0, 0.0, 0.0);
return ref_point;
}
if (s > accumulated_s.back()) {
AWARN << "The requested s exceeds the reference line; reference line "
"ends at "
<< accumulated_s.back() << "requested " << s << " .";
ReferencePoint ref_point(reference_map_line_.get_smooth_point(s),
0.0, 0.0, 0.0, 0.0);
return ref_point;
}
auto it_lower =
std::lower_bound(accumulated_s.begin(), accumulated_s.end(), s);
if (it_lower == accumulated_s.begin()) {
return reference_points_.front();
} else {
std::uint32_t index =
static_cast<std::uint32_t>(it_lower - accumulated_s.begin());
auto p0 = reference_points_[index - 1];
auto p1 = reference_points_[index];
auto s0 = accumulated_s[index - 1];
auto s1 = accumulated_s[index];
return ReferenceLine::interpolate(p0, s0, p1, s1, s);
}
}
double ReferenceLine::find_min_distance_point(const ReferencePoint& p0,
const double s0,
const ReferencePoint& p1,
const double s1, const double x,
const double y) {
auto func_dist_square = [&p0, &p1, &s0, &s1, &x, &y](const double s) {
auto p = ReferenceLine::interpolate(p0, s0, p1, s1, s);
double dx = p.x() - x;
double dy = p.y() - y;
return dx * dx + dy * dy;
};
return ::boost::math::tools::brent_find_minima(func_dist_square, s0, s1, 8)
.first;
}
ReferencePoint ReferenceLine::get_reference_point(const double x,
const double y) const {
CHECK_GE(reference_points_.size(), 0);
auto func_distance_square = [](const ReferencePoint& point, const double x,
const double y) {
double dx = point.x() - x;
double dy = point.y() - y;
return dx * dx + dy * dy;
};
double d_min = func_distance_square(reference_points_.front(), x, y);
double index_min = 0;
for (uint32_t i = 1; i < reference_points_.size(); ++i) {
double d_temp = func_distance_square(reference_points_[i], x, y);
if (d_temp < d_min) {
d_min = d_temp;
index_min = i;
}
}
uint32_t index_start = (index_min == 0 ? index_min : index_min - 1);
uint32_t index_end =
(index_min + 1 == reference_points_.size() ? index_min : index_min + 1);
if (index_start == index_end) {
return reference_points_[index_start];
}
double s0 = reference_map_line_.accumulated_s()[index_start];
double s1 = reference_map_line_.accumulated_s()[index_end];
double s = ReferenceLine::find_min_distance_point(
reference_points_[index_start], s0, reference_points_[index_end], s1, x,
y);
return ReferenceLine::interpolate(reference_points_[index_start], s0,
reference_points_[index_end], s1, s);
}
bool ReferenceLine::get_point_in_Cartesian_frame(
const common::SLPoint& sl_point,
common::math::Vec2d* const xy_point) const {
CHECK_NOTNULL(xy_point);
if (reference_map_line_.num_points() < 2) {
AERROR << "The reference line has too few points.";
return false;
}
const auto matched_point = get_reference_point(sl_point.s());
const auto angle = common::math::Angle16::from_rad(matched_point.heading());
xy_point->set_x(matched_point.x() - common::math::sin(angle) * sl_point.l());
xy_point->set_y(matched_point.y() + common::math::cos(angle) * sl_point.l());
return true;
}
bool ReferenceLine::get_point_in_frenet_frame(
const common::math::Vec2d& xy_point,
common::SLPoint* const sl_point) const {
DCHECK_NOTNULL(sl_point);
double s = 0;
double l = 0;
if (!reference_map_line_.get_projection(xy_point, &s, &l)) {
AERROR << "Can't get nearest point from path.";
return false;
}
if (s > reference_map_line_.accumulated_s().back()) {
AERROR << "The s of point is bigger than the length of current path. s: "
<< s << ", curr path length: "
<< reference_map_line_.accumulated_s().back() << ".";
return false;
}
sl_point->set_s(s);
sl_point->set_l(l);
return true;
}
ReferencePoint ReferenceLine::interpolate(const ReferencePoint& p0,
const double s0,
const ReferencePoint& p1,
const double s1, const double s) {
ReferencePoint p = p1;
p.set_x(common::math::lerp(p0.x(), s0, p1.x(), s1, s));
p.set_y(common::math::lerp(p0.y(), s0, p1.y(), s1, s));
p.set_heading(common::math::slerp(p0.heading(), s0, p1.heading(), s1, s));
p.set_kappa(common::math::lerp(p0.kappa(), s0, p1.kappa(), s1, s));
p.set_dkappa(common::math::lerp(p0.dkappa(), s0, p1.dkappa(), s1, s));
// lane boundary info, lane info will be the same as the p1.
return p;
}
const std::vector<ReferencePoint>& ReferenceLine::reference_points() const {
return reference_points_;
}
const ReferenceMapLine& ReferenceLine::reference_map_line() const {
return reference_map_line_;
}
double ReferenceLine::get_lane_width(const double s) const {
// TODO(startcode) : need implement;
return 4.0;
}
bool ReferenceLine::get_lane_width(const double s, double* const left_width,
double* const right_width) const {
return reference_map_line_.get_width(s, left_width, right_width);
}
bool ReferenceLine::is_on_road(const common::SLPoint& sl_point) const {
if (sl_point.s() <= 0 || sl_point.s() > reference_map_line_.length()) {
return false;
}
double left_width = 0.0;
double right_width = 0.0;
if (!get_lane_width(sl_point.s(), &left_width, &right_width)) {
return false;
}
if (sl_point.l() <= -right_width || sl_point.l() >= left_width) {
return false;
}
return true;
}
std::string ReferenceLine::DebugString() const {
std::ostringstream ss;
ss << "point num:" << reference_points_.size();
for (int32_t i = 0; i < static_cast<int32_t>(reference_points_.size()) &&
i < FLAGS_trajectory_point_num_for_debug;
++i) {
ss << reference_points_[i].DebugString();
}
return ss.str();
}
} // namespace planning
} // namespace apollo
<commit_msg>added lane_waypoints when empty in planning.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file reference_line.cc
**/
#include "modules/planning/reference_line/reference_line.h"
#include <algorithm>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "boost/math/tools/minima.hpp"
#include "modules/common/log.h"
#include "modules/common/math/angle.h"
#include "modules/common/math/linear_interpolation.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/math/double.h"
namespace apollo {
namespace planning {
using ReferenceMapLine = hdmap::Path;
ReferenceLine::ReferenceLine(
const std::vector<ReferencePoint>& reference_points)
: reference_points_(reference_points),
reference_map_line_(ReferenceMapLine(std::vector<hdmap::MapPathPoint>(
reference_points.begin(), reference_points.end()))) {}
ReferenceLine::ReferenceLine(
const std::vector<ReferencePoint>& reference_points,
const std::vector<hdmap::LaneSegment>& lane_segments,
const double max_approximation_error)
: reference_points_(reference_points),
reference_map_line_(ReferenceMapLine(
std::vector<hdmap::MapPathPoint>(reference_points.begin(),
reference_points.end()),
lane_segments, max_approximation_error)) {}
ReferencePoint ReferenceLine::get_reference_point(const double s) const {
const auto& accumulated_s = reference_map_line_.accumulated_s();
if (s < accumulated_s.front()) {
AWARN << "The requested s is nearer than the start point of the reference "
"line; reference line starts at "
<< accumulated_s.back() << ", requested " << s << ".";
ReferencePoint ref_point(reference_map_line_.get_smooth_point(s), 0.0, 0.0,
0.0, 0.0);
if (ref_point.lane_waypoints().empty()) {
ref_point.add_lane_waypoints(reference_points_.front().lane_waypoints());
}
return ref_point;
}
if (s > accumulated_s.back()) {
AWARN << "The requested s exceeds the reference line; reference line "
"ends at "
<< accumulated_s.back() << "requested " << s << " .";
ReferencePoint ref_point(reference_map_line_.get_smooth_point(s), 0.0, 0.0,
0.0, 0.0);
if (ref_point.lane_waypoints().empty()) {
ref_point.add_lane_waypoints(reference_points_.back().lane_waypoints());
}
return ref_point;
}
auto it_lower =
std::lower_bound(accumulated_s.begin(), accumulated_s.end(), s);
if (it_lower == accumulated_s.begin()) {
return reference_points_.front();
} else {
std::uint32_t index =
static_cast<std::uint32_t>(it_lower - accumulated_s.begin());
auto p0 = reference_points_[index - 1];
auto p1 = reference_points_[index];
auto s0 = accumulated_s[index - 1];
auto s1 = accumulated_s[index];
return ReferenceLine::interpolate(p0, s0, p1, s1, s);
}
}
double ReferenceLine::find_min_distance_point(const ReferencePoint& p0,
const double s0,
const ReferencePoint& p1,
const double s1, const double x,
const double y) {
auto func_dist_square = [&p0, &p1, &s0, &s1, &x, &y](const double s) {
auto p = ReferenceLine::interpolate(p0, s0, p1, s1, s);
double dx = p.x() - x;
double dy = p.y() - y;
return dx * dx + dy * dy;
};
return ::boost::math::tools::brent_find_minima(func_dist_square, s0, s1, 8)
.first;
}
ReferencePoint ReferenceLine::get_reference_point(const double x,
const double y) const {
CHECK_GE(reference_points_.size(), 0);
auto func_distance_square = [](const ReferencePoint& point, const double x,
const double y) {
double dx = point.x() - x;
double dy = point.y() - y;
return dx * dx + dy * dy;
};
double d_min = func_distance_square(reference_points_.front(), x, y);
double index_min = 0;
for (uint32_t i = 1; i < reference_points_.size(); ++i) {
double d_temp = func_distance_square(reference_points_[i], x, y);
if (d_temp < d_min) {
d_min = d_temp;
index_min = i;
}
}
uint32_t index_start = (index_min == 0 ? index_min : index_min - 1);
uint32_t index_end =
(index_min + 1 == reference_points_.size() ? index_min : index_min + 1);
if (index_start == index_end) {
return reference_points_[index_start];
}
double s0 = reference_map_line_.accumulated_s()[index_start];
double s1 = reference_map_line_.accumulated_s()[index_end];
double s = ReferenceLine::find_min_distance_point(
reference_points_[index_start], s0, reference_points_[index_end], s1, x,
y);
return ReferenceLine::interpolate(reference_points_[index_start], s0,
reference_points_[index_end], s1, s);
}
bool ReferenceLine::get_point_in_Cartesian_frame(
const common::SLPoint& sl_point,
common::math::Vec2d* const xy_point) const {
CHECK_NOTNULL(xy_point);
if (reference_map_line_.num_points() < 2) {
AERROR << "The reference line has too few points.";
return false;
}
const auto matched_point = get_reference_point(sl_point.s());
const auto angle = common::math::Angle16::from_rad(matched_point.heading());
xy_point->set_x(matched_point.x() - common::math::sin(angle) * sl_point.l());
xy_point->set_y(matched_point.y() + common::math::cos(angle) * sl_point.l());
return true;
}
bool ReferenceLine::get_point_in_frenet_frame(
const common::math::Vec2d& xy_point,
common::SLPoint* const sl_point) const {
DCHECK_NOTNULL(sl_point);
double s = 0;
double l = 0;
if (!reference_map_line_.get_projection(xy_point, &s, &l)) {
AERROR << "Can't get nearest point from path.";
return false;
}
if (s > reference_map_line_.accumulated_s().back()) {
AERROR << "The s of point is bigger than the length of current path. s: "
<< s << ", curr path length: "
<< reference_map_line_.accumulated_s().back() << ".";
return false;
}
sl_point->set_s(s);
sl_point->set_l(l);
return true;
}
ReferencePoint ReferenceLine::interpolate(const ReferencePoint& p0,
const double s0,
const ReferencePoint& p1,
const double s1, const double s) {
ReferencePoint p = p1;
p.set_x(common::math::lerp(p0.x(), s0, p1.x(), s1, s));
p.set_y(common::math::lerp(p0.y(), s0, p1.y(), s1, s));
p.set_heading(common::math::slerp(p0.heading(), s0, p1.heading(), s1, s));
p.set_kappa(common::math::lerp(p0.kappa(), s0, p1.kappa(), s1, s));
p.set_dkappa(common::math::lerp(p0.dkappa(), s0, p1.dkappa(), s1, s));
// lane boundary info, lane info will be the same as the p1.
return p;
}
const std::vector<ReferencePoint>& ReferenceLine::reference_points() const {
return reference_points_;
}
const ReferenceMapLine& ReferenceLine::reference_map_line() const {
return reference_map_line_;
}
double ReferenceLine::get_lane_width(const double s) const {
// TODO(startcode) : need implement;
return 4.0;
}
bool ReferenceLine::get_lane_width(const double s, double* const left_width,
double* const right_width) const {
return reference_map_line_.get_width(s, left_width, right_width);
}
bool ReferenceLine::is_on_road(const common::SLPoint& sl_point) const {
if (sl_point.s() <= 0 || sl_point.s() > reference_map_line_.length()) {
return false;
}
double left_width = 0.0;
double right_width = 0.0;
if (!get_lane_width(sl_point.s(), &left_width, &right_width)) {
return false;
}
if (sl_point.l() <= -right_width || sl_point.l() >= left_width) {
return false;
}
return true;
}
std::string ReferenceLine::DebugString() const {
std::ostringstream ss;
ss << "point num:" << reference_points_.size();
for (int32_t i = 0; i < static_cast<int32_t>(reference_points_.size()) &&
i < FLAGS_trajectory_point_num_for_debug;
++i) {
ss << reference_points_[i].DebugString();
}
return ss.str();
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file reference_line.cc
**/
#include "modules/planning/reference_line/reference_line.h"
#include <algorithm>
#include <limits>
#include <string>
#include <utility>
#include <vector>
#include "boost/math/tools/minima.hpp"
#include "modules/common/log.h"
#include "modules/common/math/angle.h"
#include "modules/common/math/linear_interpolation.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/util/string_util.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using MapPath = hdmap::Path;
using apollo::common::SLPoint;
ReferenceLine::ReferenceLine(
const std::vector<ReferencePoint>& reference_points)
: reference_points_(reference_points),
map_path_(MapPath(std::vector<hdmap::MapPathPoint>(
reference_points.begin(), reference_points.end()))) {}
ReferenceLine::ReferenceLine(const MapPath& hdmap_path)
: map_path_(hdmap_path) {
for (const auto& point : hdmap_path.path_points()) {
DCHECK(!point.lane_waypoints().empty());
const auto& lane_waypoint = point.lane_waypoints()[0];
reference_points_.emplace_back(
hdmap::MapPathPoint(point, point.heading(), lane_waypoint), 0.0, 0.0,
0.0, 0.0);
}
}
ReferenceLine::ReferenceLine(
const std::vector<ReferencePoint>& reference_points,
const std::vector<hdmap::LaneSegment>& lane_segments,
const double max_approximation_error)
: reference_points_(reference_points),
map_path_(MapPath(std::vector<hdmap::MapPathPoint>(
reference_points.begin(), reference_points.end()),
lane_segments, max_approximation_error)) {}
ReferencePoint ReferenceLine::GetReferencePoint(const double s) const {
const auto& accumulated_s = map_path_.accumulated_s();
if (s < accumulated_s.front()) {
AWARN << "The requested s " << s << " < 0";
ReferencePoint ref_point(map_path_.GetSmoothPoint(s), 0.0, 0.0, 0.0, 0.0);
if (ref_point.lane_waypoints().empty()) {
ref_point.add_lane_waypoints(reference_points_.front().lane_waypoints());
}
return ref_point;
}
if (s > accumulated_s.back()) {
AWARN << "The requested s " << s << " > reference line length "
<< accumulated_s.back();
ReferencePoint ref_point(map_path_.GetSmoothPoint(s), 0.0, 0.0, 0.0, 0.0);
if (ref_point.lane_waypoints().empty()) {
ref_point.add_lane_waypoints(reference_points_.back().lane_waypoints());
}
return ref_point;
}
auto it_lower =
std::lower_bound(accumulated_s.begin(), accumulated_s.end(), s);
if (it_lower == accumulated_s.begin()) {
return reference_points_.front();
} else {
auto index = std::distance(accumulated_s.begin(), it_lower);
const auto& p0 = reference_points_[index - 1];
const auto& p1 = reference_points_[index];
const double s0 = accumulated_s[index - 1];
const double s1 = accumulated_s[index];
return Interpolate(p0, s0, p1, s1, s);
}
}
double ReferenceLine::FindMinDistancePoint(const ReferencePoint& p0,
const double s0,
const ReferencePoint& p1,
const double s1, const double x,
const double y) {
auto func_dist_square = [&p0, &p1, &s0, &s1, &x, &y](const double s) {
auto p = Interpolate(p0, s0, p1, s1, s);
double dx = p.x() - x;
double dy = p.y() - y;
return dx * dx + dy * dy;
};
return ::boost::math::tools::brent_find_minima(func_dist_square, s0, s1, 8)
.first;
}
ReferencePoint ReferenceLine::GetReferencePoint(const double x,
const double y) const {
CHECK_GE(reference_points_.size(), 0);
auto func_distance_square = [](const ReferencePoint& point, const double x,
const double y) {
double dx = point.x() - x;
double dy = point.y() - y;
return dx * dx + dy * dy;
};
double d_min = func_distance_square(reference_points_.front(), x, y);
double index_min = 0;
for (uint32_t i = 1; i < reference_points_.size(); ++i) {
double d_temp = func_distance_square(reference_points_[i], x, y);
if (d_temp < d_min) {
d_min = d_temp;
index_min = i;
}
}
uint32_t index_start = (index_min == 0 ? index_min : index_min - 1);
uint32_t index_end =
(index_min + 1 == reference_points_.size() ? index_min : index_min + 1);
if (index_start == index_end) {
return reference_points_[index_start];
}
double s0 = map_path_.accumulated_s()[index_start];
double s1 = map_path_.accumulated_s()[index_end];
double s = ReferenceLine::FindMinDistancePoint(
reference_points_[index_start], s0, reference_points_[index_end], s1, x,
y);
return Interpolate(reference_points_[index_start], s0,
reference_points_[index_end], s1, s);
}
bool ReferenceLine::SLToXY(const SLPoint& sl_point,
common::math::Vec2d* const xy_point) const {
CHECK_NOTNULL(xy_point);
if (map_path_.num_points() < 2) {
AERROR << "The reference line has too few points.";
return false;
}
const auto matched_point = GetReferencePoint(sl_point.s());
const auto angle = common::math::Angle16::from_rad(matched_point.heading());
xy_point->set_x(matched_point.x() - common::math::sin(angle) * sl_point.l());
xy_point->set_y(matched_point.y() + common::math::cos(angle) * sl_point.l());
return true;
}
bool ReferenceLine::XYToSL(const common::math::Vec2d& xy_point,
SLPoint* const sl_point) const {
DCHECK_NOTNULL(sl_point);
double s = 0;
double l = 0;
if (!map_path_.GetProjection(xy_point, &s, &l)) {
AERROR << "Can't get nearest point from path.";
return false;
}
sl_point->set_s(s);
sl_point->set_l(l);
return true;
}
ReferencePoint ReferenceLine::Interpolate(const ReferencePoint& p0,
const double s0,
const ReferencePoint& p1,
const double s1, const double s) {
if (std::fabs(s0 - s1) < common::math::kMathEpsilon) {
return p0;
}
DCHECK_LE(s0 - 1.0e-6, s) << " s: " << s << " is less than s0 :" << s0;
DCHECK_LE(s, s1 + 1.0e-6) << "s: " << s << "is larger than s1: " << s1;
CHECK(!p0.lane_waypoints().empty());
CHECK(!p1.lane_waypoints().empty());
const double x = common::math::lerp(p0.x(), s0, p1.x(), s1, s);
const double y = common::math::lerp(p0.y(), s0, p1.y(), s1, s);
const double heading =
common::math::slerp(p0.heading(), s0, p1.heading(), s1, s);
const double kappa = common::math::lerp(p0.kappa(), s0, p1.kappa(), s1, s);
const double dkappa = common::math::lerp(p0.dkappa(), s0, p1.dkappa(), s1, s);
const auto& p0_waypoint = p0.lane_waypoints()[0];
std::vector<hdmap::LaneWaypoint> waypoints;
double upper_bound = 0.0;
double lower_bound = 0.0;
if ((s - s0) + p0_waypoint.s <= p0_waypoint.lane->total_length()) {
const double lane_s = p0_waypoint.s + s - s0;
waypoints.emplace_back(p0_waypoint.lane, lane_s);
p0_waypoint.lane->GetWidth(lane_s, &upper_bound, &lower_bound);
}
const auto& p1_waypoint = p1.lane_waypoints()[0];
if (p1_waypoint.lane->id().id() != p0_waypoint.lane->id().id() &&
p1_waypoint.s - (s1 - s) >= 0) {
const double lane_s = p1_waypoint.s - (s1 - s);
waypoints.emplace_back(p1_waypoint.lane, lane_s);
p1_waypoint.lane->GetWidth(lane_s, &upper_bound, &lower_bound);
}
if (waypoints.empty()) {
const double lane_s = p0_waypoint.s;
waypoints.emplace_back(p0_waypoint.lane, lane_s);
p0_waypoint.lane->GetWidth(lane_s, &upper_bound, &lower_bound);
}
return ReferencePoint(hdmap::MapPathPoint({x, y}, heading, waypoints), kappa,
dkappa, lower_bound, upper_bound);
}
const std::vector<ReferencePoint>& ReferenceLine::reference_points() const {
return reference_points_;
}
const MapPath& ReferenceLine::map_path() const { return map_path_; }
bool ReferenceLine::GetLaneWidth(const double s, double* const left_width,
double* const right_width) const {
return map_path_.GetWidth(s, left_width, right_width);
}
bool ReferenceLine::IsOnRoad(const SLPoint& sl_point) const {
if (sl_point.s() <= 0 || sl_point.s() > map_path_.length()) {
return false;
}
double left_width = 0.0;
double right_width = 0.0;
if (!GetLaneWidth(sl_point.s(), &left_width, &right_width)) {
return false;
}
if (sl_point.l() <= -right_width || sl_point.l() >= left_width) {
return false;
}
return true;
}
bool ReferenceLine::GetSLBoundary(const common::math::Box2d& box,
SLBoundary* const sl_boundary) const {
double start_s(std::numeric_limits<double>::max());
double end_s(std::numeric_limits<double>::lowest());
double start_l(std::numeric_limits<double>::max());
double end_l(std::numeric_limits<double>::lowest());
std::vector<common::math::Vec2d> corners;
box.GetAllCorners(&corners);
for (const auto& point : corners) {
SLPoint sl_point;
if (!XYToSL(point, &sl_point)) {
AERROR << "failed to get projection for point: " << point.DebugString()
<< " on reference line.";
return false;
}
start_s = std::fmin(start_s, sl_point.s());
end_s = std::fmax(end_s, sl_point.s());
start_l = std::fmin(start_l, sl_point.l());
end_l = std::fmax(end_l, sl_point.l());
}
sl_boundary->set_start_s(start_s);
sl_boundary->set_end_s(end_s);
sl_boundary->set_start_l(start_l);
sl_boundary->set_end_l(end_l);
return true;
}
bool ReferenceLine::HasOverlap(const common::math::Box2d& box) const {
SLBoundary sl_boundary;
if (!GetSLBoundary(box, &sl_boundary)) {
AERROR << "Failed to get sl boundary for box " << box.DebugString();
return false;
}
if (sl_boundary.end_s() < 0 || sl_boundary.start_s() > Length()) {
return false;
}
if (sl_boundary.start_l() * sl_boundary.end_l() < 0) {
return false;
}
double left_width = 0.0;
double right_width = 0.0;
const double mid_s = (sl_boundary.start_s() + sl_boundary.end_s()) / 2.0;
if (mid_s < 0 || mid_s > Length()) {
ADEBUG << "ref_s out of range:" << mid_s;
return false;
}
if (!map_path_.GetWidth(mid_s, &left_width, &right_width)) {
AERROR << "failed to get width at s = " << mid_s;
return false;
}
if (sl_boundary.start_l() > 0) {
return sl_boundary.start_l() < left_width;
} else {
return sl_boundary.end_l() > -right_width;
}
}
std::string ReferenceLine::DebugString() const {
const auto limit =
std::min(reference_points_.size(),
static_cast<size_t>(FLAGS_trajectory_point_num_for_debug));
return apollo::common::util::StrCat(
"point num:", reference_points_.size(),
apollo::common::util::PrintDebugStringIter(
reference_points_.begin(), reference_points_.begin() + limit, ""));
}
double ReferenceLine::GetSpeedLimitFromS(const double s) const {
const auto& map_path_point = GetReferencePoint(s);
double speed_limit = FLAGS_planning_upper_speed_limit;
for (const auto& lane_waypoint : map_path_point.lane_waypoints()) {
if (lane_waypoint.lane == nullptr) {
AWARN << "lane_waypoint.lane is nullptr";
continue;
}
ADEBUG << "map speed limit: " << lane_waypoint.lane->lane().speed_limit();
speed_limit =
std::fmin(lane_waypoint.lane->lane().speed_limit(), speed_limit);
}
return speed_limit;
}
} // namespace planning
} // namespace apollo
<commit_msg>[planning] GetReferencePoint: use start point and end point when s is out of range<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file reference_line.cc
**/
#include "modules/planning/reference_line/reference_line.h"
#include <algorithm>
#include <limits>
#include <string>
#include <utility>
#include <vector>
#include "boost/math/tools/minima.hpp"
#include "modules/common/log.h"
#include "modules/common/math/angle.h"
#include "modules/common/math/linear_interpolation.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/util/string_util.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using MapPath = hdmap::Path;
using apollo::common::SLPoint;
ReferenceLine::ReferenceLine(
const std::vector<ReferencePoint>& reference_points)
: reference_points_(reference_points),
map_path_(MapPath(std::vector<hdmap::MapPathPoint>(
reference_points.begin(), reference_points.end()))) {}
ReferenceLine::ReferenceLine(const MapPath& hdmap_path)
: map_path_(hdmap_path) {
for (const auto& point : hdmap_path.path_points()) {
DCHECK(!point.lane_waypoints().empty());
const auto& lane_waypoint = point.lane_waypoints()[0];
reference_points_.emplace_back(
hdmap::MapPathPoint(point, point.heading(), lane_waypoint), 0.0, 0.0,
0.0, 0.0);
}
}
ReferenceLine::ReferenceLine(
const std::vector<ReferencePoint>& reference_points,
const std::vector<hdmap::LaneSegment>& lane_segments,
const double max_approximation_error)
: reference_points_(reference_points),
map_path_(MapPath(std::vector<hdmap::MapPathPoint>(
reference_points.begin(), reference_points.end()),
lane_segments, max_approximation_error)) {}
ReferencePoint ReferenceLine::GetReferencePoint(const double s) const {
const auto& accumulated_s = map_path_.accumulated_s();
if (s < accumulated_s.front()) {
AWARN << "The requested s " << s << " < 0";
return reference_points_.front();
}
if (s > accumulated_s.back()) {
AWARN << "The requested s " << s << " > reference line length "
<< accumulated_s.back();
return reference_points_.back();
}
auto it_lower =
std::lower_bound(accumulated_s.begin(), accumulated_s.end(), s);
if (it_lower == accumulated_s.begin()) {
return reference_points_.front();
} else {
auto index = std::distance(accumulated_s.begin(), it_lower);
const auto& p0 = reference_points_[index - 1];
const auto& p1 = reference_points_[index];
const double s0 = accumulated_s[index - 1];
const double s1 = accumulated_s[index];
return Interpolate(p0, s0, p1, s1, s);
}
}
double ReferenceLine::FindMinDistancePoint(const ReferencePoint& p0,
const double s0,
const ReferencePoint& p1,
const double s1, const double x,
const double y) {
auto func_dist_square = [&p0, &p1, &s0, &s1, &x, &y](const double s) {
auto p = Interpolate(p0, s0, p1, s1, s);
double dx = p.x() - x;
double dy = p.y() - y;
return dx * dx + dy * dy;
};
return ::boost::math::tools::brent_find_minima(func_dist_square, s0, s1, 8)
.first;
}
ReferencePoint ReferenceLine::GetReferencePoint(const double x,
const double y) const {
CHECK_GE(reference_points_.size(), 0);
auto func_distance_square = [](const ReferencePoint& point, const double x,
const double y) {
double dx = point.x() - x;
double dy = point.y() - y;
return dx * dx + dy * dy;
};
double d_min = func_distance_square(reference_points_.front(), x, y);
double index_min = 0;
for (uint32_t i = 1; i < reference_points_.size(); ++i) {
double d_temp = func_distance_square(reference_points_[i], x, y);
if (d_temp < d_min) {
d_min = d_temp;
index_min = i;
}
}
uint32_t index_start = (index_min == 0 ? index_min : index_min - 1);
uint32_t index_end =
(index_min + 1 == reference_points_.size() ? index_min : index_min + 1);
if (index_start == index_end) {
return reference_points_[index_start];
}
double s0 = map_path_.accumulated_s()[index_start];
double s1 = map_path_.accumulated_s()[index_end];
double s = ReferenceLine::FindMinDistancePoint(
reference_points_[index_start], s0, reference_points_[index_end], s1, x,
y);
return Interpolate(reference_points_[index_start], s0,
reference_points_[index_end], s1, s);
}
bool ReferenceLine::SLToXY(const SLPoint& sl_point,
common::math::Vec2d* const xy_point) const {
CHECK_NOTNULL(xy_point);
if (map_path_.num_points() < 2) {
AERROR << "The reference line has too few points.";
return false;
}
const auto matched_point = GetReferencePoint(sl_point.s());
const auto angle = common::math::Angle16::from_rad(matched_point.heading());
xy_point->set_x(matched_point.x() - common::math::sin(angle) * sl_point.l());
xy_point->set_y(matched_point.y() + common::math::cos(angle) * sl_point.l());
return true;
}
bool ReferenceLine::XYToSL(const common::math::Vec2d& xy_point,
SLPoint* const sl_point) const {
DCHECK_NOTNULL(sl_point);
double s = 0;
double l = 0;
if (!map_path_.GetProjection(xy_point, &s, &l)) {
AERROR << "Can't get nearest point from path.";
return false;
}
sl_point->set_s(s);
sl_point->set_l(l);
return true;
}
ReferencePoint ReferenceLine::Interpolate(const ReferencePoint& p0,
const double s0,
const ReferencePoint& p1,
const double s1, const double s) {
if (std::fabs(s0 - s1) < common::math::kMathEpsilon) {
return p0;
}
DCHECK_LE(s0 - 1.0e-6, s) << " s: " << s << " is less than s0 :" << s0;
DCHECK_LE(s, s1 + 1.0e-6) << "s: " << s << "is larger than s1: " << s1;
CHECK(!p0.lane_waypoints().empty());
CHECK(!p1.lane_waypoints().empty());
const double x = common::math::lerp(p0.x(), s0, p1.x(), s1, s);
const double y = common::math::lerp(p0.y(), s0, p1.y(), s1, s);
const double heading =
common::math::slerp(p0.heading(), s0, p1.heading(), s1, s);
const double kappa = common::math::lerp(p0.kappa(), s0, p1.kappa(), s1, s);
const double dkappa = common::math::lerp(p0.dkappa(), s0, p1.dkappa(), s1, s);
const auto& p0_waypoint = p0.lane_waypoints()[0];
std::vector<hdmap::LaneWaypoint> waypoints;
double upper_bound = 0.0;
double lower_bound = 0.0;
if ((s - s0) + p0_waypoint.s <= p0_waypoint.lane->total_length()) {
const double lane_s = p0_waypoint.s + s - s0;
waypoints.emplace_back(p0_waypoint.lane, lane_s);
p0_waypoint.lane->GetWidth(lane_s, &upper_bound, &lower_bound);
}
const auto& p1_waypoint = p1.lane_waypoints()[0];
if (p1_waypoint.lane->id().id() != p0_waypoint.lane->id().id() &&
p1_waypoint.s - (s1 - s) >= 0) {
const double lane_s = p1_waypoint.s - (s1 - s);
waypoints.emplace_back(p1_waypoint.lane, lane_s);
p1_waypoint.lane->GetWidth(lane_s, &upper_bound, &lower_bound);
}
if (waypoints.empty()) {
const double lane_s = p0_waypoint.s;
waypoints.emplace_back(p0_waypoint.lane, lane_s);
p0_waypoint.lane->GetWidth(lane_s, &upper_bound, &lower_bound);
}
return ReferencePoint(hdmap::MapPathPoint({x, y}, heading, waypoints), kappa,
dkappa, lower_bound, upper_bound);
}
const std::vector<ReferencePoint>& ReferenceLine::reference_points() const {
return reference_points_;
}
const MapPath& ReferenceLine::map_path() const { return map_path_; }
bool ReferenceLine::GetLaneWidth(const double s, double* const left_width,
double* const right_width) const {
return map_path_.GetWidth(s, left_width, right_width);
}
bool ReferenceLine::IsOnRoad(const SLPoint& sl_point) const {
if (sl_point.s() <= 0 || sl_point.s() > map_path_.length()) {
return false;
}
double left_width = 0.0;
double right_width = 0.0;
if (!GetLaneWidth(sl_point.s(), &left_width, &right_width)) {
return false;
}
if (sl_point.l() <= -right_width || sl_point.l() >= left_width) {
return false;
}
return true;
}
bool ReferenceLine::GetSLBoundary(const common::math::Box2d& box,
SLBoundary* const sl_boundary) const {
double start_s(std::numeric_limits<double>::max());
double end_s(std::numeric_limits<double>::lowest());
double start_l(std::numeric_limits<double>::max());
double end_l(std::numeric_limits<double>::lowest());
std::vector<common::math::Vec2d> corners;
box.GetAllCorners(&corners);
for (const auto& point : corners) {
SLPoint sl_point;
if (!XYToSL(point, &sl_point)) {
AERROR << "failed to get projection for point: " << point.DebugString()
<< " on reference line.";
return false;
}
start_s = std::fmin(start_s, sl_point.s());
end_s = std::fmax(end_s, sl_point.s());
start_l = std::fmin(start_l, sl_point.l());
end_l = std::fmax(end_l, sl_point.l());
}
sl_boundary->set_start_s(start_s);
sl_boundary->set_end_s(end_s);
sl_boundary->set_start_l(start_l);
sl_boundary->set_end_l(end_l);
return true;
}
bool ReferenceLine::HasOverlap(const common::math::Box2d& box) const {
SLBoundary sl_boundary;
if (!GetSLBoundary(box, &sl_boundary)) {
AERROR << "Failed to get sl boundary for box " << box.DebugString();
return false;
}
if (sl_boundary.end_s() < 0 || sl_boundary.start_s() > Length()) {
return false;
}
if (sl_boundary.start_l() * sl_boundary.end_l() < 0) {
return false;
}
double left_width = 0.0;
double right_width = 0.0;
const double mid_s = (sl_boundary.start_s() + sl_boundary.end_s()) / 2.0;
if (mid_s < 0 || mid_s > Length()) {
ADEBUG << "ref_s out of range:" << mid_s;
return false;
}
if (!map_path_.GetWidth(mid_s, &left_width, &right_width)) {
AERROR << "failed to get width at s = " << mid_s;
return false;
}
if (sl_boundary.start_l() > 0) {
return sl_boundary.start_l() < left_width;
} else {
return sl_boundary.end_l() > -right_width;
}
}
std::string ReferenceLine::DebugString() const {
const auto limit =
std::min(reference_points_.size(),
static_cast<size_t>(FLAGS_trajectory_point_num_for_debug));
return apollo::common::util::StrCat(
"point num:", reference_points_.size(),
apollo::common::util::PrintDebugStringIter(
reference_points_.begin(), reference_points_.begin() + limit, ""));
}
double ReferenceLine::GetSpeedLimitFromS(const double s) const {
const auto& map_path_point = GetReferencePoint(s);
double speed_limit = FLAGS_planning_upper_speed_limit;
for (const auto& lane_waypoint : map_path_point.lane_waypoints()) {
if (lane_waypoint.lane == nullptr) {
AWARN << "lane_waypoint.lane is nullptr";
continue;
}
ADEBUG << "map speed limit: " << lane_waypoint.lane->lane().speed_limit();
speed_limit =
std::fmin(lane_waypoint.lane->lane().speed_limit(), speed_limit);
}
return speed_limit;
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>#include "OneDHeatForcingFunction.h"
template <>
InputParameters
validParams<OneDHeatForcingFunction>()
{
InputParameters params = validParams<Kernel>();
params.addRequiredParam<Real>("power_fraction", "The fraction of power used");
params.addRequiredCoupledVar("total_power", "Total reactor power");
params.addRequiredParam<Real>("volume", "The total heat structure volume");
params.addParam<FunctionName>("power_shape_function",
"The name of the function that defines the power shape");
return params;
}
OneDHeatForcingFunction::OneDHeatForcingFunction(const InputParameters & parameters)
: Kernel(parameters),
_power_fraction(getParam<Real>("power_fraction")),
_total_power(coupledScalarValue("total_power")),
_volume(getParam<Real>("volume")),
_power_shape_function(getFunction("power_shape_function"))
{
}
Real
OneDHeatForcingFunction::computeQpResidual()
{
Real power_density = _power_fraction * _total_power[0] / _volume;
Real local_power = power_density * _power_shape_function.value(_t, _q_point[_qp]);
return -local_power * _test[_i][_qp];
}
<commit_msg>More correct code<commit_after>#include "OneDHeatForcingFunction.h"
template <>
InputParameters
validParams<OneDHeatForcingFunction>()
{
InputParameters params = validParams<Kernel>();
params.addRequiredParam<Real>("power_fraction", "The fraction of power used");
params.addRequiredCoupledVar("total_power", "Total reactor power");
params.addRequiredParam<Real>("volume", "The total heat structure volume");
params.addRequiredParam<FunctionName>("power_shape_function",
"The name of the function that defines the power shape");
return params;
}
OneDHeatForcingFunction::OneDHeatForcingFunction(const InputParameters & parameters)
: Kernel(parameters),
_power_fraction(getParam<Real>("power_fraction")),
_total_power(coupledScalarValue("total_power")),
_volume(getParam<Real>("volume")),
_power_shape_function(getFunction("power_shape_function"))
{
}
Real
OneDHeatForcingFunction::computeQpResidual()
{
Real power_density = _power_fraction * _total_power[0] / _volume;
Real local_power = power_density * _power_shape_function.value(_t, _q_point[_qp]);
return -local_power * _test[_i][_qp];
}
<|endoftext|> |
<commit_before>//=================================================================================================
/*!
// \file src/mathtest/typetraits/OperationTest.cpp
// \brief Source file for the mathematical type traits operation test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <blaze/math/CompressedVector.h>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/StaticVector.h>
#include <blaze/math/typetraits/BaseElementType.h>
#include <blaze/math/typetraits/NumericElementType.h>
#include <blaze/util/Complex.h>
#include <blaze/util/constraints/SameType.h>
#include <blazetest/mathtest/typetraits/OperationTest.h>
namespace blazetest {
namespace mathtest {
namespace typetraits {
//=================================================================================================
//
// CONSTRUCTORS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Constructor for the OperationTest class test.
//
// \exception std::runtime_error Operation error detected.
*/
OperationTest::OperationTest()
{
testElementType();
}
//*************************************************************************************************
//=================================================================================================
//
// TEST TYPE TRAITS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Test of the mathematical 'BaseElementType' type trait.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the mathematical 'BaseElementType' type trait. In case an
// error is detected, a \a std::runtime_error exception is thrown.
*/
void OperationTest::testBaseElementType()
{
using blaze::complex;
using blaze::StaticVector;
using blaze::DynamicVector;
using blaze::CompressedVector;
using blaze::BaseElementType;
typedef double Type1; // Built-in data type
typedef complex<float> Type2; // Complex data type
typedef StaticVector<int,3UL> Type3; // Vector with built-in element type
typedef CompressedVector< DynamicVector<float> > Type4; // Vector with vector element type
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( BaseElementType<Type1>::Type, double );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( BaseElementType<Type2>::Type, float );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( BaseElementType<Type3>::Type, int );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( BaseElementType<Type4>::Type, float );
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the mathematical 'NumericElementType' type trait.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the mathematical 'NumericElementType' type trait. In case an
// error is detected, a \a std::runtime_error exception is thrown.
*/
void OperationTest::testNumericElementType()
{
using blaze::complex;
using blaze::StaticVector;
using blaze::DynamicVector;
using blaze::CompressedVector;
using blaze::NumericElementType;
typedef double Type1; // Built-in data type
typedef complex<float> Type2; // Complex data type
typedef StaticVector<int,3UL> Type3; // Vector with built-in element type
typedef CompressedVector< DynamicVector<float> > Type4; // Vector with vector element type
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( NumericElementType<Type1>::Type, double );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( NumericElementType<Type2>::Type, complex<float> );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( NumericElementType<Type3>::Type, int );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( NumericElementType<Type4>::Type, float );
}
//*************************************************************************************************
} // namespace typetraits
} // namespace mathtest
} // namespace blazetest
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running mathematical type traits operation test..." << std::endl;
try
{
RUN_TYPETRAITS_OPERATION_TEST;
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during mathematical type traits operation test:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
<commit_msg>Fix the documentation of the mathematical typetraits operation tests<commit_after>//=================================================================================================
/*!
// \file src/mathtest/typetraits/OperationTest.cpp
// \brief Source file for the mathematical type traits operation test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <blaze/math/CompressedVector.h>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/StaticVector.h>
#include <blaze/math/typetraits/BaseElementType.h>
#include <blaze/math/typetraits/NumericElementType.h>
#include <blaze/util/Complex.h>
#include <blaze/util/constraints/SameType.h>
#include <blazetest/mathtest/typetraits/OperationTest.h>
namespace blazetest {
namespace mathtest {
namespace typetraits {
//=================================================================================================
//
// CONSTRUCTORS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Constructor for the OperationTest class test.
//
// \exception std::runtime_error Operation error detected.
*/
OperationTest::OperationTest()
{
testElementType();
}
//*************************************************************************************************
//=================================================================================================
//
// TEST TYPE TRAITS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Test of the mathematical 'BaseElementType' type trait.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a compile time test of the mathematical 'BaseElementType' type trait.
// In case an error is detected, a compilation error is created.
*/
void OperationTest::testBaseElementType()
{
using blaze::complex;
using blaze::StaticVector;
using blaze::DynamicVector;
using blaze::CompressedVector;
using blaze::BaseElementType;
typedef double Type1; // Built-in data type
typedef complex<float> Type2; // Complex data type
typedef StaticVector<int,3UL> Type3; // Vector with built-in element type
typedef CompressedVector< DynamicVector<float> > Type4; // Vector with vector element type
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( BaseElementType<Type1>::Type, double );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( BaseElementType<Type2>::Type, float );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( BaseElementType<Type3>::Type, int );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( BaseElementType<Type4>::Type, float );
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the mathematical 'NumericElementType' type trait.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a compile time test of the mathematical 'NumericElementType' type trait.
// In case an error is detected, a compilation error is created.
*/
void OperationTest::testNumericElementType()
{
using blaze::complex;
using blaze::StaticVector;
using blaze::DynamicVector;
using blaze::CompressedVector;
using blaze::NumericElementType;
typedef double Type1; // Built-in data type
typedef complex<float> Type2; // Complex data type
typedef StaticVector<int,3UL> Type3; // Vector with built-in element type
typedef CompressedVector< DynamicVector<float> > Type4; // Vector with vector element type
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( NumericElementType<Type1>::Type, double );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( NumericElementType<Type2>::Type, complex<float> );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( NumericElementType<Type3>::Type, int );
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( NumericElementType<Type4>::Type, float );
}
//*************************************************************************************************
} // namespace typetraits
} // namespace mathtest
} // namespace blazetest
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running mathematical type traits operation test..." << std::endl;
try
{
RUN_TYPETRAITS_OPERATION_TEST;
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during mathematical type traits operation test:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
<|endoftext|> |
<commit_before>// Copyright (c) 2015 Andrew Sutton
// All rights reserved
#ifndef BEAKER_SYMBOL_HPP
#define BEAKER_SYMBOL_HPP
#include "string.hpp"
#include "cast.hpp"
#include <unordered_map>
#include <typeinfo>
// -------------------------------------------------------------------------- //
// Symbols
// The base class of all symbols of a language. By
// itself, this class is capable of representing
// symbols that have no other attributes such as
// punctuators and operators.
class Symbol
{
friend struct Symbol_table;
public:
Symbol(int);
virtual ~Symbol() { }
String const& spelling() const;
int token() const;
private:
String const* str_; // The textual representation
int tok_; // The associated token kind
};
inline
Symbol::Symbol(int k)
: str_(nullptr), tok_(k)
{ }
// Returns the spelling of the symbol.
inline String const&
Symbol::spelling() const
{
return *str_;
}
// Returns the kind of token classfication of
// the symbol.
inline int
Symbol::token() const
{
return tok_;
}
// Represents the integer symbols true and false.
struct Boolean_sym : Symbol
{
Boolean_sym(int k, bool b)
: Symbol(k), value_(b)
{ }
bool value() const { return value_; }
bool value_;
};
// Represents all integer symbols.
//
// TODO: Develop and use a good arbitrary precision
// integer for this representation.
//
// TOOD: Track the integer base? Technically, that
// can be inferred by the spelling, but it might be
// useful to keep cached.
struct Integer_sym : Symbol
{
Integer_sym(int k, int n)
: Symbol(k), value_(n)
{ }
int value() const { return value_; }
int value_;
};
// Represents all identifiers.
//
// TODO: Track the innermost binding of the identifier?
struct Identifier_sym : Symbol
{
Identifier_sym(int k)
: Symbol(k)
{ }
};
// Streaming
std::ostream& operator<<(std::ostream&, Symbol const&);
// -------------------------------------------------------------------------- //
// Symbol table
// The symbol table maintains a mapping of
// unique string values to their corresponding
// symbols.
struct Symbol_table : std::unordered_map<std::string, Symbol*>
{
~Symbol_table();
template<typename T, typename... Args>
Symbol* put(String const&, Args&&...);
template<typename T, typename... Args>
Symbol* put(char const*, char const*, Args&&...);
Symbol const* get(String const&) const;
Symbol const* get(char const*) const;
};
// Delete allocated resources.
inline
Symbol_table::~Symbol_table()
{
for (auto const& x : *this)
delete x.second;
}
// Insert a new symbol into the table. The spelling
// of the symbol is given by the string s and the
// attributes are given in args.
//
// Note that the type of the symbol must be given
// explicitly, and it must derive from the Symbol
// class.
//
// If the symbol already exists, no insertion is
// performed. If new symbol is of a different kind
// (e.g., redefining an integer as an identifier),
// a runtime error is thrown.
//
// TODO: It might also be helpful to verify the
// attributes of re-inserted symbols. That's a bit
// harder.
template<typename T, typename... Args>
Symbol*
Symbol_table::put(String const& s, Args&&... args)
{
auto x = emplace(s, nullptr);
auto iter = x.first;
if (x.second) {
// Insertion succeeded, so create a new symbol
// and bind its string representation.
iter->second = new T(std::forward<Args>(args)...);
iter->second->str_ = &iter->first;
} else {
// Insertion did not succeed. Check that we have
// not redefined the symbol kind.
if(typeid(T) != typeid(*iter->second))
throw std::runtime_error("lexical symbol redefinition");
}
return iter->second;
}
// Insert a symbol with the spelling [first, last) and
// the properties in args...
template<typename T, typename... Args>
inline Symbol*
Symbol_table::put(char const* first, char const* last, Args&&... args)
{
return this->template put<T>(String(first, last), std::forward<Args>(args)...);
}
// Returns the symbol with the given spelling or
// nullptr if no such symbol exists.
inline Symbol const*
Symbol_table::get(String const& s) const
{
auto iter = find(s);
if (iter != end())
return iter->second;
else
return nullptr;
}
// Returns the symbol with the given spelling or
// nullptr if no such symbol exists.
inline Symbol const*
Symbol_table::get(char const* s) const
{
auto iter = find(s);
if (iter != end())
return iter->second;
else
return nullptr;
}
#endif
<commit_msg>Don't warn on typeid comparison.<commit_after>// Copyright (c) 2015 Andrew Sutton
// All rights reserved
#ifndef BEAKER_SYMBOL_HPP
#define BEAKER_SYMBOL_HPP
#include "string.hpp"
#include "cast.hpp"
#include <unordered_map>
#include <typeinfo>
// -------------------------------------------------------------------------- //
// Symbols
// The base class of all symbols of a language. By
// itself, this class is capable of representing
// symbols that have no other attributes such as
// punctuators and operators.
class Symbol
{
friend struct Symbol_table;
public:
Symbol(int);
virtual ~Symbol() { }
String const& spelling() const;
int token() const;
private:
String const* str_; // The textual representation
int tok_; // The associated token kind
};
inline
Symbol::Symbol(int k)
: str_(nullptr), tok_(k)
{ }
// Returns the spelling of the symbol.
inline String const&
Symbol::spelling() const
{
return *str_;
}
// Returns the kind of token classfication of
// the symbol.
inline int
Symbol::token() const
{
return tok_;
}
// Represents the integer symbols true and false.
struct Boolean_sym : Symbol
{
Boolean_sym(int k, bool b)
: Symbol(k), value_(b)
{ }
bool value() const { return value_; }
bool value_;
};
// Represents all integer symbols.
//
// TODO: Develop and use a good arbitrary precision
// integer for this representation.
//
// TOOD: Track the integer base? Technically, that
// can be inferred by the spelling, but it might be
// useful to keep cached.
struct Integer_sym : Symbol
{
Integer_sym(int k, int n)
: Symbol(k), value_(n)
{ }
int value() const { return value_; }
int value_;
};
// Represents all identifiers.
//
// TODO: Track the innermost binding of the identifier?
struct Identifier_sym : Symbol
{
Identifier_sym(int k)
: Symbol(k)
{ }
};
// Streaming
std::ostream& operator<<(std::ostream&, Symbol const&);
// -------------------------------------------------------------------------- //
// Symbol table
// The symbol table maintains a mapping of
// unique string values to their corresponding
// symbols.
struct Symbol_table : std::unordered_map<std::string, Symbol*>
{
~Symbol_table();
template<typename T, typename... Args>
Symbol* put(String const&, Args&&...);
template<typename T, typename... Args>
Symbol* put(char const*, char const*, Args&&...);
Symbol const* get(String const&) const;
Symbol const* get(char const*) const;
};
// Delete allocated resources.
inline
Symbol_table::~Symbol_table()
{
for (auto const& x : *this)
delete x.second;
}
// Insert a new symbol into the table. The spelling
// of the symbol is given by the string s and the
// attributes are given in args.
//
// Note that the type of the symbol must be given
// explicitly, and it must derive from the Symbol
// class.
//
// If the symbol already exists, no insertion is
// performed. If new symbol is of a different kind
// (e.g., redefining an integer as an identifier),
// a runtime error is thrown.
//
// TODO: It might also be helpful to verify the
// attributes of re-inserted symbols. That's a bit
// harder.
template<typename T, typename... Args>
Symbol*
Symbol_table::put(String const& s, Args&&... args)
{
auto x = emplace(s, nullptr);
auto iter = x.first;
Symbol*& sym = iter->second;
if (x.second) {
// Insertion succeeded, so create a new symbol
// and bind its string representation.
sym = new T(std::forward<Args>(args)...);
sym->str_ = &iter->first;
} else {
// Insertion did not succeed. Check that we have
// not redefined the symbol kind.
if (typeid(T) != typeid(*sym))
throw std::runtime_error("redefinition of symbol");
}
return iter->second;
}
// Insert a symbol with the spelling [first, last) and
// the properties in args...
template<typename T, typename... Args>
inline Symbol*
Symbol_table::put(char const* first, char const* last, Args&&... args)
{
return this->template put<T>(String(first, last), std::forward<Args>(args)...);
}
// Returns the symbol with the given spelling or
// nullptr if no such symbol exists.
inline Symbol const*
Symbol_table::get(String const& s) const
{
auto iter = find(s);
if (iter != end())
return iter->second;
else
return nullptr;
}
// Returns the symbol with the given spelling or
// nullptr if no such symbol exists.
inline Symbol const*
Symbol_table::get(char const* s) const
{
auto iter = find(s);
if (iter != end())
return iter->second;
else
return nullptr;
}
#endif
<|endoftext|> |
<commit_before>//
// WidgetProxy.cpp
// Chilli Source
// Created by Scott Downie on 18/08/2014.
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Tag Games 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.
//
#include <ChilliSource/UI/Base/WidgetProxy.h>
#include <ChilliSource/Core/Math/Vector2.h>
#include <ChilliSource/Core/Math/Vector3.h>
#include <ChilliSource/Core/Math/Vector4.h>
#include <ChilliSource/Rendering/Base/AlignmentAnchors.h>
namespace ChilliSource
{
namespace UI
{
namespace WidgetProxy
{
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void RegisterWithLuaScript(Lua::LuaScript* in_script)
{
in_script->RegisterStaticClass("Widget",
"setName", &WidgetProxy::SetName,
"setRelativePosition", &WidgetProxy::SetRelativePosition,
"setAbsolutePosition", &WidgetProxy::SetAbsolutePosition,
"setRelativeSize", &WidgetProxy::SetRelativeSize,
"setAbsoluteSize", &WidgetProxy::SetAbsoluteSize,
"relativeMoveBy", &WidgetProxy::RelativeMoveBy,
"absoluteMoveBy", &WidgetProxy::AbsoluteMoveBy,
"getLocalAbsolutePosition", &WidgetProxy::GetLocalAbsolutePosition,
"getLocalRelativePosition", &WidgetProxy::GetLocalRelativePosition,
"getFinalPosition", &WidgetProxy::GetFinalPosition,
"scaleBy", &WidgetProxy::ScaleBy,
"scaleTo", &WidgetProxy::ScaleTo,
"getLocalScale", &WidgetProxy::GetLocalScale,
"getFinalScale", &WidgetProxy::GetFinalScale,
"rotateTo", &WidgetProxy::RotateTo,
"rotateBy", &WidgetProxy::RotateBy,
"getLocalRotation", &WidgetProxy::GetLocalRotation,
"getFinalRotation", &WidgetProxy::GetFinalRotation,
"setColour", &WidgetProxy::SetColour,
"getLocalColour", &WidgetProxy::GetLocalColour,
"getFinalColour", &WidgetProxy::GetFinalColour,
"setVisible", &WidgetProxy::SetVisible,
"isVisible", &WidgetProxy::IsVisible,
"bringToFront", &WidgetProxy::BringToFront,
"bringForward", &WidgetProxy::BringForward,
"sendToBack", &WidgetProxy::SendToBack,
"sendBackward", &WidgetProxy::SendBackward,
"setSizePolicy", &WidgetProxy::SetSizePolicy,
"getSizePolicy", &WidgetProxy::GetSizePolicy,
"setOriginAnchor", &WidgetProxy::SetOriginAnchor,
"getOriginAnchor", &WidgetProxy::GetOriginAnchor,
"setParentalAnchor", &WidgetProxy::SetParentalAnchor,
"getParentalAnchor", &WidgetProxy::GetParentalAnchor,
"getInternalWidget", &WidgetProxy::GetInternalWidget,
"getWidget", &WidgetProxy::GetWidget,
"getDrawable", &WidgetProxy::GetDrawable,
"getBoolProperty", &WidgetProxy::GetProperty<bool>,
"getIntProperty", &WidgetProxy::GetProperty<s32>,
"getFloatProperty", &WidgetProxy::GetProperty<f32>,
"getStringProperty", &WidgetProxy::GetProperty<std::string>,
"getVec2Property", &WidgetProxy::GetProperty<Core::Vector2>,
"getVec3Property", &WidgetProxy::GetProperty<Core::Vector3>,
"getVec4Property", &WidgetProxy::GetProperty<Core::Vector4>,
"getColourProperty", &WidgetProxy::GetProperty<Core::Colour>,
"getAlignmentAnchorProperty", &WidgetProxy::GetProperty<Rendering::AlignmentAnchor>,
"getSizePolicyProperty", &WidgetProxy::GetProperty<SizePolicy>,
"getStorageLocationProperty", &WidgetProxy::GetProperty<Core::StorageLocation>,
"setBoolProperty", &WidgetProxy::SetProperty<bool>,
"setIntProperty", &WidgetProxy::SetProperty<s32>,
"setFloatProperty", &WidgetProxy::SetProperty<f32>,
"setStringProperty", &WidgetProxy::SetProperty<std::string>,
"setVec2Property", &WidgetProxy::SetProperty<Core::Vector2>,
"setVec3Property", &WidgetProxy::SetProperty<Core::Vector3>,
"setVec4Property", &WidgetProxy::SetProperty<Core::Vector4>,
"setColourProperty", &WidgetProxy::SetProperty<Core::Colour>,
"setAlignmentAnchorProperty", &WidgetProxy::SetProperty<Rendering::AlignmentAnchor>,
"setSizePolicyProperty", &WidgetProxy::SetProperty<SizePolicy>,
"setStorageLocationProperty", &WidgetProxy::SetProperty<Core::StorageLocation>
);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetName(Widget* in_widget, const std::string& in_name)
{
in_widget->SetName(in_name);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
const std::string& GetName(Widget* in_widget)
{
return in_widget->GetName();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
IDrawable* GetDrawable(Widget* in_widget)
{
return in_widget->GetDrawable();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetRelativeSize(Widget* in_widget, const Core::Vector2& in_size)
{
in_widget->SetRelativeSize(in_size);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetLocalRelativeSize(Widget* in_widget)
{
return in_widget->GetLocalRelativeSize();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetAbsoluteSize(Widget* in_widget, const Core::Vector2& in_size)
{
in_widget->SetAbsoluteSize(in_size);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetLocalAbsoluteSize(Widget* in_widget)
{
return in_widget->GetLocalAbsoluteSize();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetSizePolicy(Widget* in_widget, SizePolicy in_policy)
{
in_widget->SetSizePolicy(in_policy);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
SizePolicy GetSizePolicy(Widget* in_widget)
{
return in_widget->GetSizePolicy();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetRelativePosition(Widget* in_widget, const Core::Vector2& in_pos)
{
in_widget->SetRelativePosition(in_pos);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetLocalRelativePosition(Widget* in_widget)
{
return in_widget->GetLocalRelativePosition();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetAbsolutePosition(Widget* in_widget, const Core::Vector2& in_pos)
{
in_widget->SetAbsolutePosition(in_pos);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetLocalAbsolutePosition(Widget* in_widget)
{
return in_widget->GetLocalAbsolutePosition();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void RelativeMoveBy(Widget* in_widget, const Core::Vector2& in_translate)
{
in_widget->RelativeMoveBy(in_translate);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void AbsoluteMoveBy(Widget* in_widget, const Core::Vector2& in_translate)
{
in_widget->AbsoluteMoveBy(in_translate);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void RotateBy(Widget* in_widget, f32 in_angleRads)
{
in_widget->RotateBy(in_angleRads);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void RotateTo(Widget* in_widget, f32 in_angleRads)
{
in_widget->RotateTo(in_angleRads);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
f32 GetLocalRotation(Widget* in_widget)
{
return in_widget->GetLocalRotation();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void ScaleBy(Widget* in_widget, const Core::Vector2& in_scale)
{
in_widget->ScaleBy(in_scale);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void ScaleTo(Widget* in_widget, const Core::Vector2& in_scale)
{
in_widget->ScaleTo(in_scale);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetLocalScale(Widget* in_widget)
{
return in_widget->GetLocalScale();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetParentalAnchor(Widget* in_widget, Rendering::AlignmentAnchor in_anchor)
{
in_widget->SetParentalAnchor(in_anchor);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Rendering::AlignmentAnchor GetParentalAnchor(Widget* in_widget)
{
return in_widget->GetParentalAnchor();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetOriginAnchor(Widget* in_widget, Rendering::AlignmentAnchor in_anchor)
{
in_widget->SetOriginAnchor(in_anchor);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Rendering::AlignmentAnchor GetOriginAnchor(Widget* in_widget)
{
return in_widget->GetOriginAnchor();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetColour(Widget* in_widget, const Core::Colour& in_colour)
{
in_widget->SetColour(in_colour);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Colour GetLocalColour(Widget* in_widget)
{
return in_widget->GetLocalColour();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetVisible(Widget* in_widget, bool in_visible)
{
in_widget->SetVisible(in_visible);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
bool IsVisible(Widget* in_widget)
{
return in_widget->IsVisible();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetClippingEnabled(Widget* in_widget, bool in_enabled)
{
in_widget->SetClippingEnabled(in_enabled);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
bool IsClippingEnabled(Widget* in_widget)
{
return in_widget->IsClippingEnabled();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Widget* GetWidget(Widget* in_widget, const std::string& in_name)
{
return in_widget->GetWidget(in_name);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Widget* GetInternalWidget(Widget* in_widget, const std::string& in_name)
{
return in_widget->GetInternalWidget(in_name);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void BringToFront(Widget* in_widget)
{
in_widget->BringToFront();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void BringForward(Widget* in_widget)
{
in_widget->BringForward();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SendBackward(Widget* in_widget)
{
in_widget->SendBackward();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SendToBack(Widget* in_widget)
{
in_widget->SendToBack();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetFinalPosition(Widget* in_widget)
{
return in_widget->GetFinalPosition();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetFinalSize(Widget* in_widget)
{
return in_widget->GetFinalSize();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetPreferredSize(Widget* in_widget)
{
return in_widget->GetPreferredSize();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
f32 GetFinalRotation(Widget* in_widget)
{
return in_widget->GetFinalRotation();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetFinalScale(Widget* in_widget)
{
return in_widget->GetFinalScale();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Colour GetFinalColour(Widget* in_widget)
{
return in_widget->GetFinalColour();
}
}
}
}
<commit_msg>Fixing windows compiler error<commit_after>//
// WidgetProxy.cpp
// Chilli Source
// Created by Scott Downie on 18/08/2014.
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Tag Games 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.
//
#include <ChilliSource/UI/Base/WidgetProxy.h>
#include <ChilliSource/Core/File/StorageLocation.h>
#include <ChilliSource/Core/Math/Vector2.h>
#include <ChilliSource/Core/Math/Vector3.h>
#include <ChilliSource/Core/Math/Vector4.h>
#include <ChilliSource/Rendering/Base/AlignmentAnchors.h>
namespace ChilliSource
{
namespace UI
{
namespace WidgetProxy
{
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void RegisterWithLuaScript(Lua::LuaScript* in_script)
{
in_script->RegisterStaticClass("Widget",
"setName", &WidgetProxy::SetName,
"setRelativePosition", &WidgetProxy::SetRelativePosition,
"setAbsolutePosition", &WidgetProxy::SetAbsolutePosition,
"setRelativeSize", &WidgetProxy::SetRelativeSize,
"setAbsoluteSize", &WidgetProxy::SetAbsoluteSize,
"relativeMoveBy", &WidgetProxy::RelativeMoveBy,
"absoluteMoveBy", &WidgetProxy::AbsoluteMoveBy,
"getLocalAbsolutePosition", &WidgetProxy::GetLocalAbsolutePosition,
"getLocalRelativePosition", &WidgetProxy::GetLocalRelativePosition,
"getFinalPosition", &WidgetProxy::GetFinalPosition,
"scaleBy", &WidgetProxy::ScaleBy,
"scaleTo", &WidgetProxy::ScaleTo,
"getLocalScale", &WidgetProxy::GetLocalScale,
"getFinalScale", &WidgetProxy::GetFinalScale,
"rotateTo", &WidgetProxy::RotateTo,
"rotateBy", &WidgetProxy::RotateBy,
"getLocalRotation", &WidgetProxy::GetLocalRotation,
"getFinalRotation", &WidgetProxy::GetFinalRotation,
"setColour", &WidgetProxy::SetColour,
"getLocalColour", &WidgetProxy::GetLocalColour,
"getFinalColour", &WidgetProxy::GetFinalColour,
"setVisible", &WidgetProxy::SetVisible,
"isVisible", &WidgetProxy::IsVisible,
"bringToFront", &WidgetProxy::BringToFront,
"bringForward", &WidgetProxy::BringForward,
"sendToBack", &WidgetProxy::SendToBack,
"sendBackward", &WidgetProxy::SendBackward,
"setSizePolicy", &WidgetProxy::SetSizePolicy,
"getSizePolicy", &WidgetProxy::GetSizePolicy,
"setOriginAnchor", &WidgetProxy::SetOriginAnchor,
"getOriginAnchor", &WidgetProxy::GetOriginAnchor,
"setParentalAnchor", &WidgetProxy::SetParentalAnchor,
"getParentalAnchor", &WidgetProxy::GetParentalAnchor,
"getInternalWidget", &WidgetProxy::GetInternalWidget,
"getWidget", &WidgetProxy::GetWidget,
"getDrawable", &WidgetProxy::GetDrawable,
"getBoolProperty", &WidgetProxy::GetProperty<bool>,
"getIntProperty", &WidgetProxy::GetProperty<s32>,
"getFloatProperty", &WidgetProxy::GetProperty<f32>,
"getStringProperty", &WidgetProxy::GetProperty<std::string>,
"getVec2Property", &WidgetProxy::GetProperty<Core::Vector2>,
"getVec3Property", &WidgetProxy::GetProperty<Core::Vector3>,
"getVec4Property", &WidgetProxy::GetProperty<Core::Vector4>,
"getColourProperty", &WidgetProxy::GetProperty<Core::Colour>,
"getAlignmentAnchorProperty", &WidgetProxy::GetProperty<Rendering::AlignmentAnchor>,
"getSizePolicyProperty", &WidgetProxy::GetProperty<SizePolicy>,
"getStorageLocationProperty", &WidgetProxy::GetProperty<Core::StorageLocation>,
"setBoolProperty", &WidgetProxy::SetProperty<bool>,
"setIntProperty", &WidgetProxy::SetProperty<s32>,
"setFloatProperty", &WidgetProxy::SetProperty<f32>,
"setStringProperty", &WidgetProxy::SetProperty<std::string>,
"setVec2Property", &WidgetProxy::SetProperty<Core::Vector2>,
"setVec3Property", &WidgetProxy::SetProperty<Core::Vector3>,
"setVec4Property", &WidgetProxy::SetProperty<Core::Vector4>,
"setColourProperty", &WidgetProxy::SetProperty<Core::Colour>,
"setAlignmentAnchorProperty", &WidgetProxy::SetProperty<Rendering::AlignmentAnchor>,
"setSizePolicyProperty", &WidgetProxy::SetProperty<SizePolicy>,
"setStorageLocationProperty", &WidgetProxy::SetProperty<Core::StorageLocation>
);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetName(Widget* in_widget, const std::string& in_name)
{
in_widget->SetName(in_name);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
const std::string& GetName(Widget* in_widget)
{
return in_widget->GetName();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
IDrawable* GetDrawable(Widget* in_widget)
{
return in_widget->GetDrawable();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetRelativeSize(Widget* in_widget, const Core::Vector2& in_size)
{
in_widget->SetRelativeSize(in_size);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetLocalRelativeSize(Widget* in_widget)
{
return in_widget->GetLocalRelativeSize();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetAbsoluteSize(Widget* in_widget, const Core::Vector2& in_size)
{
in_widget->SetAbsoluteSize(in_size);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetLocalAbsoluteSize(Widget* in_widget)
{
return in_widget->GetLocalAbsoluteSize();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetSizePolicy(Widget* in_widget, SizePolicy in_policy)
{
in_widget->SetSizePolicy(in_policy);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
SizePolicy GetSizePolicy(Widget* in_widget)
{
return in_widget->GetSizePolicy();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetRelativePosition(Widget* in_widget, const Core::Vector2& in_pos)
{
in_widget->SetRelativePosition(in_pos);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetLocalRelativePosition(Widget* in_widget)
{
return in_widget->GetLocalRelativePosition();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetAbsolutePosition(Widget* in_widget, const Core::Vector2& in_pos)
{
in_widget->SetAbsolutePosition(in_pos);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetLocalAbsolutePosition(Widget* in_widget)
{
return in_widget->GetLocalAbsolutePosition();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void RelativeMoveBy(Widget* in_widget, const Core::Vector2& in_translate)
{
in_widget->RelativeMoveBy(in_translate);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void AbsoluteMoveBy(Widget* in_widget, const Core::Vector2& in_translate)
{
in_widget->AbsoluteMoveBy(in_translate);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void RotateBy(Widget* in_widget, f32 in_angleRads)
{
in_widget->RotateBy(in_angleRads);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void RotateTo(Widget* in_widget, f32 in_angleRads)
{
in_widget->RotateTo(in_angleRads);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
f32 GetLocalRotation(Widget* in_widget)
{
return in_widget->GetLocalRotation();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void ScaleBy(Widget* in_widget, const Core::Vector2& in_scale)
{
in_widget->ScaleBy(in_scale);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void ScaleTo(Widget* in_widget, const Core::Vector2& in_scale)
{
in_widget->ScaleTo(in_scale);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetLocalScale(Widget* in_widget)
{
return in_widget->GetLocalScale();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetParentalAnchor(Widget* in_widget, Rendering::AlignmentAnchor in_anchor)
{
in_widget->SetParentalAnchor(in_anchor);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Rendering::AlignmentAnchor GetParentalAnchor(Widget* in_widget)
{
return in_widget->GetParentalAnchor();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetOriginAnchor(Widget* in_widget, Rendering::AlignmentAnchor in_anchor)
{
in_widget->SetOriginAnchor(in_anchor);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Rendering::AlignmentAnchor GetOriginAnchor(Widget* in_widget)
{
return in_widget->GetOriginAnchor();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetColour(Widget* in_widget, const Core::Colour& in_colour)
{
in_widget->SetColour(in_colour);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Colour GetLocalColour(Widget* in_widget)
{
return in_widget->GetLocalColour();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetVisible(Widget* in_widget, bool in_visible)
{
in_widget->SetVisible(in_visible);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
bool IsVisible(Widget* in_widget)
{
return in_widget->IsVisible();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SetClippingEnabled(Widget* in_widget, bool in_enabled)
{
in_widget->SetClippingEnabled(in_enabled);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
bool IsClippingEnabled(Widget* in_widget)
{
return in_widget->IsClippingEnabled();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Widget* GetWidget(Widget* in_widget, const std::string& in_name)
{
return in_widget->GetWidget(in_name);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Widget* GetInternalWidget(Widget* in_widget, const std::string& in_name)
{
return in_widget->GetInternalWidget(in_name);
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void BringToFront(Widget* in_widget)
{
in_widget->BringToFront();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void BringForward(Widget* in_widget)
{
in_widget->BringForward();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SendBackward(Widget* in_widget)
{
in_widget->SendBackward();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
void SendToBack(Widget* in_widget)
{
in_widget->SendToBack();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetFinalPosition(Widget* in_widget)
{
return in_widget->GetFinalPosition();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetFinalSize(Widget* in_widget)
{
return in_widget->GetFinalSize();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetPreferredSize(Widget* in_widget)
{
return in_widget->GetPreferredSize();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
f32 GetFinalRotation(Widget* in_widget)
{
return in_widget->GetFinalRotation();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Vector2 GetFinalScale(Widget* in_widget)
{
return in_widget->GetFinalScale();
}
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
Core::Colour GetFinalColour(Widget* in_widget)
{
return in_widget->GetFinalColour();
}
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: canvascustomspritehelper.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2005-11-02 12:42:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_CANVAS_CANVASCUSTOMSPRITEHELPER_HXX
#define INCLUDED_CANVAS_CANVASCUSTOMSPRITEHELPER_HXX
#ifndef _COM_SUN_STAR_RENDERING_XCUSTOMSPRITE_HPP_
#include <com/sun/star/rendering/XCustomSprite.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XPOLYPOLYGON2D_HPP_
#include <com/sun/star/rendering/XPolyPolygon2D.hpp>
#endif
#ifndef _BGFX_POINT_B2DPOINT_HXX
#include <basegfx/point/b2dpoint.hxx>
#endif
#ifndef _BGFX_VECTOR_B2DVECTOR_HXX
#include <basegfx/vector/b2dvector.hxx>
#endif
#ifndef _BGFX_RANGE_B2DRANGE_HXX
#include <basegfx/range/b2drange.hxx>
#endif
#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#ifndef INCLUDED_CANVAS_SPRITESURFACE_HXX
#include <canvas/base/spritesurface.hxx>
#endif
namespace canvas
{
/* Definition of CanvasCustomSpriteHelper class */
/** Base class for an XSprite helper implementation - to be used
in concert with CanvasCustomSpriteBase
*/
class CanvasCustomSpriteHelper
{
public:
CanvasCustomSpriteHelper();
virtual ~CanvasCustomSpriteHelper() {}
/** Init helper
@param rSpriteSize
Requested size of the sprite, as passed to the
XSpriteCanvas::createCustomSprite() method
@param rOwningSpriteCanvas
The XSpriteCanvas this sprite is displayed on
*/
void init( const ::com::sun::star::geometry::RealSize2D& rSpriteSize,
const SpriteSurface::Reference& rOwningSpriteCanvas );
/** Object is being disposed, release all internal references
@derive when overriding this method in derived classes,
<em>always</em> call the base class' method!
*/
void disposing();
// XCanvas
/// need to call this method for XCanvas::drawBitmap(), for opacity tracking
void checkDrawBitmap( const Sprite::Reference& rSprite,
const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmap >& xBitmap,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
// XSprite
void setAlpha( const Sprite::Reference& rSprite,
double alpha );
void move( const Sprite::Reference& rSprite,
const ::com::sun::star::geometry::RealPoint2D& aNewPos,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
void transform( const Sprite::Reference& rSprite,
const ::com::sun::star::geometry::AffineMatrix2D& aTransformation );
void clip( const Sprite::Reference& rSprite,
const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& aClip );
void setPriority( const Sprite::Reference& rSprite,
double nPriority );
void show( const Sprite::Reference& rSprite );
void hide( const Sprite::Reference& rSprite );
// XCustomSprite
/// Need to call this method for XCustomSprite::getContentCanvas(), for surface preparations
void prepareContentCanvas( const Sprite::Reference& rSprite );
// Sprite
bool isAreaUpdateOpaque( const ::basegfx::B2DRange& rUpdateArea ) const;
::basegfx::B2DPoint getPosPixel() const;
::basegfx::B2DVector getSizePixel() const;
::basegfx::B2DRange getUpdateArea() const;
double getPriority() const;
// redraw must be implemented by derived - non sensible default implementation
// void redraw( const Sprite::Reference& rSprite,
// const ::basegfx::B2DPoint& rPos ) const;
// Helper methods for derived classes
// ----------------------------------
/// Calc sprite update area from given raw sprite bounds
::basegfx::B2DRange getUpdateArea( const ::basegfx::B2DRange& rUntransformedSpriteBounds ) const;
/// Calc update area for unclipped sprite content
::basegfx::B2DRange getFullSpriteRect() const;
/** Returns true, if sprite content bitmap is fully opaque.
This does not take clipping or transformation into
account, but only denotes that the sprite bitmap's alpha
channel is all 1.0
*/
bool isContentFullyOpaque() const { return mbIsContentFullyOpaque; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasAlphaChanged() const { return mbAlphaDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasPositionChanged() const { return mbPositionDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasTransformChanged() const { return mbTransformDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasClipChanged() const { return mbClipDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasPrioChanged() const { return mbPrioDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasVisibilityChanged() const { return mbVisibilityDirty; }
/// Retrieve current alpha value
double getAlpha() const { return mfAlpha; }
/// Retrieve current clip
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& getClip() const { return mxClipPoly; }
const ::basegfx::B2DHomMatrix& getTransformation() const { return maTransform; }
/// Retrieve current activation state
bool isActive() const { return mbActive; }
protected:
/** Notifies that caller is again in sync with current alph
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void alphaUpdated() const { mbAlphaDirty=false; }
/** Notifies that caller is again in sync with current position
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void positionUpdated() const { mbPositionDirty=false; }
/** Notifies that caller is again in sync with current transformation
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void transformUpdated() const { mbTransformDirty=false; }
/** Notifies that caller is again in sync with current clip
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void clipUpdated() const { mbClipDirty=false; }
/** Notifies that caller is again in sync with current priority
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void prioUpdated() const { mbPrioDirty=false; }
/** Notifies that caller is again in sync with current visibility
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void visibilityUpdated() const { mbVisibilityDirty=false; }
private:
CanvasCustomSpriteHelper( const CanvasCustomSpriteHelper& );
CanvasCustomSpriteHelper& operator=( const CanvasCustomSpriteHelper& );
/** Called to clear the sprite surface to fully transparent
@derive must be overridden by derived classes, and
implemented as to fully clear the sprite content.
*/
virtual void clearSurface() = 0;
/** Called to convert an API polygon to a basegfx polygon
@derive Needs to be provided by backend-specific code
*/
virtual ::basegfx::B2DPolyPolygon polyPolygonFromXPolyPolygon2D(
::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& xPoly ) const = 0;
/** Update clip information from current state
This method recomputes the maCurrClipBounds and
mbIsCurrClipRectangle members from the current clip and
transformation. IFF the clip changed from rectangular to
rectangular again, this method issues a sequence of
optimized SpriteSurface::updateSprite() calls.
@return true, if SpriteSurface::updateSprite() was already
called within this method.
*/
bool updateClipState( const Sprite::Reference& rSprite );
// --------------------------------------------------------------------
/// Owning sprite canvas
SpriteSurface::Reference mpSpriteCanvas;
/** Currently active clip area.
This member is either empty, denoting that the current
clip shows the full sprite content, or contains a
rectangular subarea of the sprite, outside of which
the sprite content is fully clipped.
@see mbIsCurrClipRectangle
*/
::basegfx::B2DRange maCurrClipBounds;
// sprite state
::basegfx::B2DPoint maPosition;
::basegfx::B2DVector maSize;
::basegfx::B2DHomMatrix maTransform;
::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D > mxClipPoly;
double mfPriority;
double mfAlpha;
bool mbActive; // true, if not hidden
/** If true, denotes that the current sprite clip is a true
rectangle, i.e. maCurrClipBounds <em>exactly</em>
describes the visible area of the sprite.
@see maCurrClipBounds
*/
bool mbIsCurrClipRectangle;
/** Redraw speedup.
When true, this flag denotes that the current sprite
content is fully opaque, thus, that blits to the screen do
neither have to take alpha into account, nor prepare any
background for the sprite area.
*/
mutable bool mbIsContentFullyOpaque;
/// True, iff mfAlpha has changed
mutable bool mbAlphaDirty;
/// True, iff maPosition has changed
mutable bool mbPositionDirty;
/// True, iff maTransform has changed
mutable bool mbTransformDirty;
/// True, iff mxClipPoly has changed
mutable bool mbClipDirty;
/// True, iff mnPriority has changed
mutable bool mbPrioDirty;
/// True, iff mbActive has changed
mutable bool mbVisibilityDirty;
};
}
#endif /* INCLUDED_CANVAS_CANVASCUSTOMSPRITEHELPER_HXX */
<commit_msg>INTEGRATION: CWS presfixes12 (1.2.76); FILE MERGED 2007/02/20 22:23:07 thb 1.2.76.1: #i37778# Added XCanvas::clear() method throughout all implementations<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: canvascustomspritehelper.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2007-07-17 14:18:28 $
*
* 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 INCLUDED_CANVAS_CANVASCUSTOMSPRITEHELPER_HXX
#define INCLUDED_CANVAS_CANVASCUSTOMSPRITEHELPER_HXX
#ifndef _COM_SUN_STAR_RENDERING_XCUSTOMSPRITE_HPP_
#include <com/sun/star/rendering/XCustomSprite.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XPOLYPOLYGON2D_HPP_
#include <com/sun/star/rendering/XPolyPolygon2D.hpp>
#endif
#ifndef _BGFX_POINT_B2DPOINT_HXX
#include <basegfx/point/b2dpoint.hxx>
#endif
#ifndef _BGFX_VECTOR_B2DVECTOR_HXX
#include <basegfx/vector/b2dvector.hxx>
#endif
#ifndef _BGFX_RANGE_B2DRANGE_HXX
#include <basegfx/range/b2drange.hxx>
#endif
#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#ifndef INCLUDED_CANVAS_SPRITESURFACE_HXX
#include <canvas/base/spritesurface.hxx>
#endif
namespace canvas
{
/* Definition of CanvasCustomSpriteHelper class */
/** Base class for an XSprite helper implementation - to be used
in concert with CanvasCustomSpriteBase
*/
class CanvasCustomSpriteHelper
{
public:
CanvasCustomSpriteHelper();
virtual ~CanvasCustomSpriteHelper() {}
/** Init helper
@param rSpriteSize
Requested size of the sprite, as passed to the
XSpriteCanvas::createCustomSprite() method
@param rOwningSpriteCanvas
The XSpriteCanvas this sprite is displayed on
*/
void init( const ::com::sun::star::geometry::RealSize2D& rSpriteSize,
const SpriteSurface::Reference& rOwningSpriteCanvas );
/** Object is being disposed, release all internal references
@derive when overriding this method in derived classes,
<em>always</em> call the base class' method!
*/
void disposing();
// XCanvas
/// need to call this method for XCanvas::clear(), for opacity tracking
void clearingContent( const Sprite::Reference& rSprite );
/// need to call this method for XCanvas::drawBitmap(), for opacity tracking
void checkDrawBitmap( const Sprite::Reference& rSprite,
const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmap >& xBitmap,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
// XSprite
void setAlpha( const Sprite::Reference& rSprite,
double alpha );
void move( const Sprite::Reference& rSprite,
const ::com::sun::star::geometry::RealPoint2D& aNewPos,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
void transform( const Sprite::Reference& rSprite,
const ::com::sun::star::geometry::AffineMatrix2D& aTransformation );
void clip( const Sprite::Reference& rSprite,
const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& aClip );
void setPriority( const Sprite::Reference& rSprite,
double nPriority );
void show( const Sprite::Reference& rSprite );
void hide( const Sprite::Reference& rSprite );
// Sprite
bool isAreaUpdateOpaque( const ::basegfx::B2DRange& rUpdateArea ) const;
::basegfx::B2DPoint getPosPixel() const;
::basegfx::B2DVector getSizePixel() const;
::basegfx::B2DRange getUpdateArea() const;
double getPriority() const;
// redraw must be implemented by derived - non sensible default implementation
// void redraw( const Sprite::Reference& rSprite,
// const ::basegfx::B2DPoint& rPos ) const;
// Helper methods for derived classes
// ----------------------------------
/// Calc sprite update area from given raw sprite bounds
::basegfx::B2DRange getUpdateArea( const ::basegfx::B2DRange& rUntransformedSpriteBounds ) const;
/// Calc update area for unclipped sprite content
::basegfx::B2DRange getFullSpriteRect() const;
/** Returns true, if sprite content bitmap is fully opaque.
This does not take clipping or transformation into
account, but only denotes that the sprite bitmap's alpha
channel is all 1.0
*/
bool isContentFullyOpaque() const { return mbIsContentFullyOpaque; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasAlphaChanged() const { return mbAlphaDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasPositionChanged() const { return mbPositionDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasTransformChanged() const { return mbTransformDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasClipChanged() const { return mbClipDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasPrioChanged() const { return mbPrioDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasVisibilityChanged() const { return mbVisibilityDirty; }
/// Retrieve current alpha value
double getAlpha() const { return mfAlpha; }
/// Retrieve current clip
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& getClip() const { return mxClipPoly; }
const ::basegfx::B2DHomMatrix& getTransformation() const { return maTransform; }
/// Retrieve current activation state
bool isActive() const { return mbActive; }
protected:
/** Notifies that caller is again in sync with current alph
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void alphaUpdated() const { mbAlphaDirty=false; }
/** Notifies that caller is again in sync with current position
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void positionUpdated() const { mbPositionDirty=false; }
/** Notifies that caller is again in sync with current transformation
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void transformUpdated() const { mbTransformDirty=false; }
/** Notifies that caller is again in sync with current clip
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void clipUpdated() const { mbClipDirty=false; }
/** Notifies that caller is again in sync with current priority
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void prioUpdated() const { mbPrioDirty=false; }
/** Notifies that caller is again in sync with current visibility
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void visibilityUpdated() const { mbVisibilityDirty=false; }
private:
CanvasCustomSpriteHelper( const CanvasCustomSpriteHelper& );
CanvasCustomSpriteHelper& operator=( const CanvasCustomSpriteHelper& );
/** Called to convert an API polygon to a basegfx polygon
@derive Needs to be provided by backend-specific code
*/
virtual ::basegfx::B2DPolyPolygon polyPolygonFromXPolyPolygon2D(
::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& xPoly ) const = 0;
/** Update clip information from current state
This method recomputes the maCurrClipBounds and
mbIsCurrClipRectangle members from the current clip and
transformation. IFF the clip changed from rectangular to
rectangular again, this method issues a sequence of
optimized SpriteSurface::updateSprite() calls.
@return true, if SpriteSurface::updateSprite() was already
called within this method.
*/
bool updateClipState( const Sprite::Reference& rSprite );
// --------------------------------------------------------------------
/// Owning sprite canvas
SpriteSurface::Reference mpSpriteCanvas;
/** Currently active clip area.
This member is either empty, denoting that the current
clip shows the full sprite content, or contains a
rectangular subarea of the sprite, outside of which
the sprite content is fully clipped.
@see mbIsCurrClipRectangle
*/
::basegfx::B2DRange maCurrClipBounds;
// sprite state
::basegfx::B2DPoint maPosition;
::basegfx::B2DVector maSize;
::basegfx::B2DHomMatrix maTransform;
::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D > mxClipPoly;
double mfPriority;
double mfAlpha;
bool mbActive; // true, if not hidden
/** If true, denotes that the current sprite clip is a true
rectangle, i.e. maCurrClipBounds <em>exactly</em>
describes the visible area of the sprite.
@see maCurrClipBounds
*/
bool mbIsCurrClipRectangle;
/** Redraw speedup.
When true, this flag denotes that the current sprite
content is fully opaque, thus, that blits to the screen do
neither have to take alpha into account, nor prepare any
background for the sprite area.
*/
mutable bool mbIsContentFullyOpaque;
/// True, iff mfAlpha has changed
mutable bool mbAlphaDirty;
/// True, iff maPosition has changed
mutable bool mbPositionDirty;
/// True, iff maTransform has changed
mutable bool mbTransformDirty;
/// True, iff mxClipPoly has changed
mutable bool mbClipDirty;
/// True, iff mnPriority has changed
mutable bool mbPrioDirty;
/// True, iff mbActive has changed
mutable bool mbVisibilityDirty;
};
}
#endif /* INCLUDED_CANVAS_CANVASCUSTOMSPRITEHELPER_HXX */
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, 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. *
**************************************************************************/
/*
$Log: AliT0Align.cxx,v $
Revision 2008/01/30
Removing code violations
Version 1.1 2006/10
Preliminary test version (T.Malkiewicz)
*/
#include "AliT0Align.h"
#include "TROOT.h"
#include "Riostream.h"
#include "TFile.h"
#include "TMath.h"
#include "TSystem.h"
#include "TString.h"
#include "AliSurveyObj.h"
#include "AliAlignObjParams.h"
#include "AliCDBStorage.h"
#include <TClonesArray.h>
#include <TFile.h>
#include "AliLog.h"
#include "AliCDBManager.h"
#include "AliSurveyPoint.h"
// Class creating the T0 aligmnent objects
// from the surveys done by surveyers at Point2.
// Survey results are fetched from
// Survey Depot, based on survey results
// position of T0 alignment objects is computed.
ClassImp(AliT0Align)
AliT0Align::AliT0Align() :
TObject(),
fFileGlob(0x0),
fT0AAlignObj(0x0),
fT0CAlignObj(0x0),
fDebug(0),
fXPosC(0.),
fYPosC(0.),
fXPosA(0.),
fYPosA(0.),
fRepLoc(0),
fRepGlob(0),
fSide(0x0),
fUser(0x0)
{
//
// default constructor
//
}
//________________________________________________________________________
AliT0Align::AliT0Align(Int_t reportloc, Int_t side, Int_t reportglob) :
TObject(),
fFileGlob(0x0),
fT0AAlignObj(0x0),
fT0CAlignObj(0x0),
fDebug(0),
fXPosC(0.),
fYPosC(0.),
fXPosA(0.),
fYPosA(0.),
fRepLoc(0),
fRepGlob(0),
fSide(0x0),
fUser(0x0)
{
//
// constructor - defines data files
//
fRepLoc = reportloc;
fRepGlob = reportglob;
fSide = side;
// Char_t path[50];
TString path = Form("%s",gSystem->Getenv("ALICE_ROOT")) ;
// fFileGlob = new Char_t[80];
// fUser = new Char_t[10];
fFileGlob = Form("%s/T0/Survey_%d_V0.txt",path.Data(),reportglob);
fUser = Form("%s/T0/Survey_%d_V0.txt",path.Data(),reportglob);
// sprintf(path,gSystem->Getenv("ALICE_ROOT"));
//
// sprintf(fFileLoc,"%s/T0/Survey_%d_T0.txt",path,reportloc);
// sprintf(fFileGlob,"%s/T0/Survey_%d_V0.txt",path,reportglob);
//
// sprintf(fUser,gSystem->Getenv("alien_API_USER"));
}
//_________________________________________________________________________
AliT0Align::AliT0Align(const AliT0Align &align) :
TObject(),
fFileGlob(0x0),
fT0AAlignObj(0x0),
fT0CAlignObj(0x0),
fDebug(0),
fXPosC(0.),
fYPosC(0.),
fXPosA(0.),
fYPosA(0.),
fRepLoc(0),
fRepGlob(0),
fSide(0x0),
fUser(0x0)
{
//
// copy constructor - dummy
//
((AliT0Align &) align).Copy(*this);
}
//__________________________________________________________________________
AliT0Align & AliT0Align::operator =(const AliT0Align & align)
{
//
// assignment operator - dummy
//
if (this != &align) ((AliT0Align &) align).Copy(*this);
return (*this);
}
//__________________________________________________________________________
AliT0Align::~AliT0Align()
{
//
// destructor
//
if(fT0AAlignObj) delete fT0AAlignObj;
if(fT0CAlignObj) delete fT0CAlignObj;
if(fFileGlob) delete[] fFileGlob;
if(fUser) delete[] fUser;
}
//__________________________________________________________________________
Bool_t AliT0Align::LoadSurveyData()
{
//
// Create a new survey object and fill it.
AliSurveyObj * s1 = new AliSurveyObj();
const int numberPoints = 2;
TString pointNames[numberPoints]={"Flange_0","C67_6_Beamcircle"};
if(fRepLoc == 0)
{
//
// Filling from DCDB (via GRID)
//
s1->SetGridUser(fUser);
if(fSide == 0)
{
s1->Fill("T0", fRepGlob, fUser);
}
else if(fSide == 1)
{
s1->Fill("VZERO", fRepGlob, fUser);
}
else
{
cout<<"Enter the side properly: '0'- A side, '1'- C side'" <<endl;
return 0;
}
}
else
//
// Filling from local file
//
{
s1->FillFromLocalFile(fFileGlob);
}
//
Float_t surveyedPoints [numberPoints][2];
AliSurveyPoint *currPoint;
//
for(Int_t i=0;i<numberPoints;i++)
{
currPoint=0;
currPoint = (AliSurveyPoint *) s1->GetData()->FindObject(pointNames[i]);
//
if(currPoint)
{
surveyedPoints[i][0]=currPoint->GetX();
surveyedPoints[i][1]=currPoint->GetY();
// surveyedPoints[i]=currPoint->GetZ();
if(fDebug)
Printf(Form("INFO: Point %s coordinates read.\n", pointNames[i].Data()) ) ;
}
else
{
if(fDebug)
{
Printf(Form("ERROR: Essential point missing: %s\n", pointNames[i].Data())) ;
return 1;
}
}
}
if(fSide == 0)
{
fXPosA = surveyedPoints[0][0];
fYPosA = surveyedPoints[0][1];
}
else if(fSide == 1)
{
fXPosC = surveyedPoints[1][0];
fYPosC = surveyedPoints[1][1];
}
//
delete s1;
//
return 0;
}
//_________________________________________________________________
Double_t AliT0Align::ComputePosition()
{
// Float_t fZPos, shift;
// fZPos = surveyedPoints[3] - shift;
return 0;
}
//_______________________________________________________________________
void AliT0Align::CreateAlignObj()
{
//
// TClonesArray *array = new TClonesArray("AliAlignObjParams",2);
// TClonesArray &alobj = *array;
Double_t dx=0., dy=0., dz=0., dpsi=0., dtheta=0., dphi=0.;
dx=fXPosA;
dy=fYPosA;
fT0AAlignObj = new AliAlignObjParams("ALIC_1/0STL_1",0,dx,dy,dz,dpsi,dtheta,dphi,kTRUE);
dx=fXPosC;
dy=fYPosC;
// dz=surveyedPoints[2];
dz=0.;
fT0CAlignObj = new AliAlignObjParams("ALIC_1/0STR_1",0,dx,dy,dz,dpsi,dtheta,dphi,kTRUE);
}
//______________________________________________________________________
void AliT0Align::Run()
{
//
// runs the full chain
//
// SetDebug(0);
Bool_t flag = LoadSurveyData();
if(flag)
{
cout<<"Missing points"<<endl;
return;
}
// ComputePosition();
CreateAlignObj();
StoreAlignObj();
}
//_________________________________________________________________________
void AliT0Align::StoreAlignObj()
{
//
// Storing T0 alignment objects
//
AliCDBManager* cdb = AliCDBManager::Instance();
if(!cdb->IsDefaultStorageSet()) cdb->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
//
TClonesArray *array = new TClonesArray("AliAlignObjParams",2);
//
Double_t shifts[3];
Double_t rots[3];
//
fT0AAlignObj->GetPars(shifts,rots);
new((*array)[0]) AliAlignObjParams(fT0AAlignObj->GetSymName(),0,shifts[0],
shifts[1],shifts[2],rots[0],rots[1],rots[2],kTRUE);
fT0CAlignObj->GetPars(shifts,rots);
new((*array)[1]) AliAlignObjParams(fT0CAlignObj->GetSymName(),0,shifts[0],
shifts[1],shifts[2],rots[0],rots[1],rots[2],kTRUE);
//
// storing either in the OCDB or local file
//
if( TString(gSystem->Getenv("TOCDB")) != TString("kTRUE") ){
// save on file
const char* filename = "T0SurveyMisalignment.root";
// Char_t fullname[80];
// sprintf(fullname,"%s/T0/Align/Data/%s",gSystem->Getenv("ALICE_ROOT"),filename);
TString fullname = Form("%s/T0/Align/Data/%s",gSystem->Getenv("ALICE_ROOT"), filename);
TFile *f = new TFile(fullname.Data(),"RECREATE");
if(!f){
AliError("cannot open file for output\n");
return;
}
AliInfo(Form("Saving alignment objects to the file %s", filename));
f->cd();
f->WriteObject(array,"T0AlignObjs","kSingleKey");
f->Close();
}else{
// save in CDB storage
AliCDBStorage* storage;
//
TString Storage = gSystem->Getenv("STORAGE");
if(!Storage.BeginsWith("local://") && !Storage.BeginsWith("alien://")) {
AliError(Form(
"STORAGE variable set to %s is not valid. Exiting\n",Storage.Data()));
return;
}
storage = cdb->GetStorage(Storage.Data());
if(!storage){
AliError(Form("Unable to open storage %s\n",Storage.Data()));
return;
}
//
AliCDBMetaData* md = new AliCDBMetaData();
md->SetResponsible("Tomasz Malkiewicz");
md->SetComment("Position of T0-A and T0-C from survey");
AliCDBId id("T0/Align/Data",0,AliCDBRunRange::Infinity());
storage->Put(array,id,md);
}
}
<commit_msg>warning fixed<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, 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. *
**************************************************************************/
/*
$Log: AliT0Align.cxx,v $
Revision 2008/01/30
Removing code violations
Version 1.1 2006/10
Preliminary test version (T.Malkiewicz)
*/
#include "AliT0Align.h"
#include "TROOT.h"
#include "Riostream.h"
#include "TFile.h"
#include "TMath.h"
#include "TSystem.h"
#include "TString.h"
#include "AliSurveyObj.h"
#include "AliAlignObjParams.h"
#include "AliCDBStorage.h"
#include <TClonesArray.h>
#include <TFile.h>
#include "AliLog.h"
#include "AliCDBManager.h"
#include "AliSurveyPoint.h"
// Class creating the T0 aligmnent objects
// from the surveys done by surveyers at Point2.
// Survey results are fetched from
// Survey Depot, based on survey results
// position of T0 alignment objects is computed.
ClassImp(AliT0Align)
AliT0Align::AliT0Align() :
TObject(),
fFileGlob(0x0),
fT0AAlignObj(0x0),
fT0CAlignObj(0x0),
fDebug(0),
fXPosC(0.),
fYPosC(0.),
fXPosA(0.),
fYPosA(0.),
fRepLoc(0),
fRepGlob(0),
fSide(0x0),
fUser(0x0)
{
//
// default constructor
//
}
//________________________________________________________________________
AliT0Align::AliT0Align(Int_t reportloc, Int_t side, Int_t reportglob) :
TObject(),
fFileGlob(0x0),
fT0AAlignObj(0x0),
fT0CAlignObj(0x0),
fDebug(0),
fXPosC(0.),
fYPosC(0.),
fXPosA(0.),
fYPosA(0.),
fRepLoc(0),
fRepGlob(0),
fSide(0x0),
fUser(0x0)
{
//
// constructor - defines data files
//
fRepLoc = reportloc;
fRepGlob = reportglob;
fSide = side;
// Char_t path[50];
TString path = Form("%s",gSystem->Getenv("ALICE_ROOT")) ;
// fFileGlob = new Char_t[80];
// fUser = new Char_t[10];
fFileGlob = Form("%s/T0/Survey_%d_V0.txt",path.Data(),reportglob);
fUser = Form("%s/T0/Survey_%d_V0.txt",path.Data(),reportglob);
// sprintf(path,gSystem->Getenv("ALICE_ROOT"));
//
// sprintf(fFileLoc,"%s/T0/Survey_%d_T0.txt",path,reportloc);
// sprintf(fFileGlob,"%s/T0/Survey_%d_V0.txt",path,reportglob);
//
// sprintf(fUser,gSystem->Getenv("alien_API_USER"));
}
//_________________________________________________________________________
AliT0Align::AliT0Align(const AliT0Align &align) :
TObject(),
fFileGlob(0x0),
fT0AAlignObj(0x0),
fT0CAlignObj(0x0),
fDebug(0),
fXPosC(0.),
fYPosC(0.),
fXPosA(0.),
fYPosA(0.),
fRepLoc(0),
fRepGlob(0),
fSide(0x0),
fUser(0x0)
{
//
// copy constructor - dummy
//
((AliT0Align &) align).Copy(*this);
}
//__________________________________________________________________________
AliT0Align & AliT0Align::operator =(const AliT0Align & align)
{
//
// assignment operator - dummy
//
if (this != &align) ((AliT0Align &) align).Copy(*this);
return (*this);
}
//__________________________________________________________________________
AliT0Align::~AliT0Align()
{
//
// destructor
//
if(fT0AAlignObj) delete fT0AAlignObj;
if(fT0CAlignObj) delete fT0CAlignObj;
if(fFileGlob) delete[] fFileGlob;
if(fUser) delete[] fUser;
}
//__________________________________________________________________________
Bool_t AliT0Align::LoadSurveyData()
{
//
// Create a new survey object and fill it.
AliSurveyObj * s1 = new AliSurveyObj();
const int numberPoints = 2;
TString pointNames[numberPoints]={"Flange_0","C67_6_Beamcircle"};
if(fRepLoc == 0)
{
//
// Filling from DCDB (via GRID)
//
s1->SetGridUser(fUser);
if(fSide == 0)
{
s1->Fill("T0", fRepGlob, fUser);
}
else if(fSide == 1)
{
s1->Fill("VZERO", fRepGlob, fUser);
}
else
{
cout<<"Enter the side properly: '0'- A side, '1'- C side'" <<endl;
return 0;
}
}
else
//
// Filling from local file
//
{
s1->FillFromLocalFile(fFileGlob);
}
//
Float_t surveyedPoints [numberPoints][2];
AliSurveyPoint *currPoint;
//
for(Int_t i=0;i<numberPoints;i++)
{
currPoint=0;
currPoint = (AliSurveyPoint *) s1->GetData()->FindObject(pointNames[i]);
//
if(currPoint)
{
surveyedPoints[i][0]=currPoint->GetX();
surveyedPoints[i][1]=currPoint->GetY();
// surveyedPoints[i]=currPoint->GetZ();
if(fDebug)
Printf("INFO: Point %s coordinates read.\n", pointNames[i].Data() ) ;
}
else
{
if(fDebug)
{
Printf("ERROR: Essential point missing: %s\n", pointNames[i].Data() ) ;
return 1;
}
}
}
if(fSide == 0)
{
fXPosA = surveyedPoints[0][0];
fYPosA = surveyedPoints[0][1];
}
else if(fSide == 1)
{
fXPosC = surveyedPoints[1][0];
fYPosC = surveyedPoints[1][1];
}
//
delete s1;
//
return 0;
}
//_________________________________________________________________
Double_t AliT0Align::ComputePosition()
{
// Float_t fZPos, shift;
// fZPos = surveyedPoints[3] - shift;
return 0;
}
//_______________________________________________________________________
void AliT0Align::CreateAlignObj()
{
//
// TClonesArray *array = new TClonesArray("AliAlignObjParams",2);
// TClonesArray &alobj = *array;
Double_t dx=0., dy=0., dz=0., dpsi=0., dtheta=0., dphi=0.;
dx=fXPosA;
dy=fYPosA;
fT0AAlignObj = new AliAlignObjParams("ALIC_1/0STL_1",0,dx,dy,dz,dpsi,dtheta,dphi,kTRUE);
dx=fXPosC;
dy=fYPosC;
// dz=surveyedPoints[2];
dz=0.;
fT0CAlignObj = new AliAlignObjParams("ALIC_1/0STR_1",0,dx,dy,dz,dpsi,dtheta,dphi,kTRUE);
}
//______________________________________________________________________
void AliT0Align::Run()
{
//
// runs the full chain
//
// SetDebug(0);
Bool_t flag = LoadSurveyData();
if(flag)
{
cout<<"Missing points"<<endl;
return;
}
// ComputePosition();
CreateAlignObj();
StoreAlignObj();
}
//_________________________________________________________________________
void AliT0Align::StoreAlignObj()
{
//
// Storing T0 alignment objects
//
AliCDBManager* cdb = AliCDBManager::Instance();
if(!cdb->IsDefaultStorageSet()) cdb->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
//
TClonesArray *array = new TClonesArray("AliAlignObjParams",2);
//
Double_t shifts[3];
Double_t rots[3];
//
fT0AAlignObj->GetPars(shifts,rots);
new((*array)[0]) AliAlignObjParams(fT0AAlignObj->GetSymName(),0,shifts[0],
shifts[1],shifts[2],rots[0],rots[1],rots[2],kTRUE);
fT0CAlignObj->GetPars(shifts,rots);
new((*array)[1]) AliAlignObjParams(fT0CAlignObj->GetSymName(),0,shifts[0],
shifts[1],shifts[2],rots[0],rots[1],rots[2],kTRUE);
//
// storing either in the OCDB or local file
//
if( TString(gSystem->Getenv("TOCDB")) != TString("kTRUE") ){
// save on file
const char* filename = "T0SurveyMisalignment.root";
// Char_t fullname[80];
// sprintf(fullname,"%s/T0/Align/Data/%s",gSystem->Getenv("ALICE_ROOT"),filename);
TString fullname = Form("%s/T0/Align/Data/%s",gSystem->Getenv("ALICE_ROOT"), filename);
TFile *f = new TFile(fullname.Data(),"RECREATE");
if(!f){
AliError("cannot open file for output\n");
return;
}
AliInfo(Form("Saving alignment objects to the file %s", filename));
f->cd();
f->WriteObject(array,"T0AlignObjs","kSingleKey");
f->Close();
}else{
// save in CDB storage
AliCDBStorage* storage;
//
TString Storage = gSystem->Getenv("STORAGE");
if(!Storage.BeginsWith("local://") && !Storage.BeginsWith("alien://")) {
AliError(Form(
"STORAGE variable set to %s is not valid. Exiting\n",Storage.Data()));
return;
}
storage = cdb->GetStorage(Storage.Data());
if(!storage){
AliError(Form("Unable to open storage %s\n",Storage.Data()));
return;
}
//
AliCDBMetaData* md = new AliCDBMetaData();
md->SetResponsible("Tomasz Malkiewicz");
md->SetComment("Position of T0-A and T0-C from survey");
AliCDBId id("T0/Align/Data",0,AliCDBRunRange::Infinity());
storage->Put(array,id,md);
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "launcherpackets.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qendian.h>
namespace qbs {
namespace Internal {
LauncherPacket::~LauncherPacket() { }
QByteArray LauncherPacket::serialize() const
{
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
stream << static_cast<int>(0) << static_cast<quint8>(type) << token;
doSerialize(stream);
stream.device()->reset();
stream << static_cast<int>(data.size() - sizeof(int));
return data;
}
void LauncherPacket::deserialize(const QByteArray &data)
{
QDataStream stream(data);
doDeserialize(stream);
}
StartProcessPacket::StartProcessPacket(quintptr token)
: LauncherPacket(LauncherPacketType::StartProcess, token)
{
}
void StartProcessPacket::doSerialize(QDataStream &stream) const
{
stream << command << arguments << workingDir << env;
}
void StartProcessPacket::doDeserialize(QDataStream &stream)
{
stream >> command >> arguments >> workingDir >> env;
}
StopProcessPacket::StopProcessPacket(quintptr token)
: LauncherPacket(LauncherPacketType::StopProcess, token)
{
}
void StopProcessPacket::doSerialize(QDataStream &stream) const
{
Q_UNUSED(stream);
}
void StopProcessPacket::doDeserialize(QDataStream &stream)
{
Q_UNUSED(stream);
}
ProcessErrorPacket::ProcessErrorPacket(quintptr token)
: LauncherPacket(LauncherPacketType::ProcessError, token)
{
}
void ProcessErrorPacket::doSerialize(QDataStream &stream) const
{
stream << static_cast<quint8>(error) << errorString;
}
void ProcessErrorPacket::doDeserialize(QDataStream &stream)
{
quint8 e;
stream >> e;
error = static_cast<QProcess::ProcessError>(e);
stream >> errorString;
}
ProcessFinishedPacket::ProcessFinishedPacket(quintptr token)
: LauncherPacket(LauncherPacketType::ProcessFinished, token)
{
}
void ProcessFinishedPacket::doSerialize(QDataStream &stream) const
{
stream << errorString << stdOut << stdErr
<< static_cast<quint8>(exitStatus) << static_cast<quint8>(error)
<< exitCode;
}
void ProcessFinishedPacket::doDeserialize(QDataStream &stream)
{
stream >> errorString >> stdOut >> stdErr;
quint8 val;
stream >> val;
exitStatus = static_cast<QProcess::ExitStatus>(val);
stream >> val;
error = static_cast<QProcess::ProcessError>(val);
stream >> exitCode;
}
ShutdownPacket::ShutdownPacket() : LauncherPacket(LauncherPacketType::Shutdown, 0) { }
void ShutdownPacket::doSerialize(QDataStream &stream) const { Q_UNUSED(stream); }
void ShutdownPacket::doDeserialize(QDataStream &stream) { Q_UNUSED(stream); }
void PacketParser::setDevice(QIODevice *device)
{
m_stream.setDevice(device);
m_sizeOfNextPacket = -1;
}
bool PacketParser::parse()
{
static const int commonPayloadSize = static_cast<int>(1 + sizeof(quintptr));
if (m_sizeOfNextPacket == -1) {
if (m_stream.device()->bytesAvailable() < static_cast<int>(sizeof m_sizeOfNextPacket))
return false;
m_stream >> m_sizeOfNextPacket;
if (m_sizeOfNextPacket < commonPayloadSize)
throw InvalidPacketSizeException(m_sizeOfNextPacket);
}
if (m_stream.device()->bytesAvailable() < m_sizeOfNextPacket)
return false;
quint8 type;
m_stream >> type;
m_type = static_cast<LauncherPacketType>(type);
m_stream >> m_token;
m_packetData = m_stream.device()->read(m_sizeOfNextPacket - commonPayloadSize);
m_sizeOfNextPacket = -1;
return true;
}
} // namespace Internal
} // namespace qbs
<commit_msg>Remove seemingly unused header<commit_after>/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "launcherpackets.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qcoreapplication.h>
namespace qbs {
namespace Internal {
LauncherPacket::~LauncherPacket() { }
QByteArray LauncherPacket::serialize() const
{
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
stream << static_cast<int>(0) << static_cast<quint8>(type) << token;
doSerialize(stream);
stream.device()->reset();
stream << static_cast<int>(data.size() - sizeof(int));
return data;
}
void LauncherPacket::deserialize(const QByteArray &data)
{
QDataStream stream(data);
doDeserialize(stream);
}
StartProcessPacket::StartProcessPacket(quintptr token)
: LauncherPacket(LauncherPacketType::StartProcess, token)
{
}
void StartProcessPacket::doSerialize(QDataStream &stream) const
{
stream << command << arguments << workingDir << env;
}
void StartProcessPacket::doDeserialize(QDataStream &stream)
{
stream >> command >> arguments >> workingDir >> env;
}
StopProcessPacket::StopProcessPacket(quintptr token)
: LauncherPacket(LauncherPacketType::StopProcess, token)
{
}
void StopProcessPacket::doSerialize(QDataStream &stream) const
{
Q_UNUSED(stream);
}
void StopProcessPacket::doDeserialize(QDataStream &stream)
{
Q_UNUSED(stream);
}
ProcessErrorPacket::ProcessErrorPacket(quintptr token)
: LauncherPacket(LauncherPacketType::ProcessError, token)
{
}
void ProcessErrorPacket::doSerialize(QDataStream &stream) const
{
stream << static_cast<quint8>(error) << errorString;
}
void ProcessErrorPacket::doDeserialize(QDataStream &stream)
{
quint8 e;
stream >> e;
error = static_cast<QProcess::ProcessError>(e);
stream >> errorString;
}
ProcessFinishedPacket::ProcessFinishedPacket(quintptr token)
: LauncherPacket(LauncherPacketType::ProcessFinished, token)
{
}
void ProcessFinishedPacket::doSerialize(QDataStream &stream) const
{
stream << errorString << stdOut << stdErr
<< static_cast<quint8>(exitStatus) << static_cast<quint8>(error)
<< exitCode;
}
void ProcessFinishedPacket::doDeserialize(QDataStream &stream)
{
stream >> errorString >> stdOut >> stdErr;
quint8 val;
stream >> val;
exitStatus = static_cast<QProcess::ExitStatus>(val);
stream >> val;
error = static_cast<QProcess::ProcessError>(val);
stream >> exitCode;
}
ShutdownPacket::ShutdownPacket() : LauncherPacket(LauncherPacketType::Shutdown, 0) { }
void ShutdownPacket::doSerialize(QDataStream &stream) const { Q_UNUSED(stream); }
void ShutdownPacket::doDeserialize(QDataStream &stream) { Q_UNUSED(stream); }
void PacketParser::setDevice(QIODevice *device)
{
m_stream.setDevice(device);
m_sizeOfNextPacket = -1;
}
bool PacketParser::parse()
{
static const int commonPayloadSize = static_cast<int>(1 + sizeof(quintptr));
if (m_sizeOfNextPacket == -1) {
if (m_stream.device()->bytesAvailable() < static_cast<int>(sizeof m_sizeOfNextPacket))
return false;
m_stream >> m_sizeOfNextPacket;
if (m_sizeOfNextPacket < commonPayloadSize)
throw InvalidPacketSizeException(m_sizeOfNextPacket);
}
if (m_stream.device()->bytesAvailable() < m_sizeOfNextPacket)
return false;
quint8 type;
m_stream >> type;
m_type = static_cast<LauncherPacketType>(type);
m_stream >> m_token;
m_packetData = m_stream.device()->read(m_sizeOfNextPacket - commonPayloadSize);
m_sizeOfNextPacket = -1;
return true;
}
} // namespace Internal
} // namespace qbs
<|endoftext|> |
<commit_before>/*
* This file is part of the kreenshot-editor project.
*
* Copyright (C) 2014 by Gregor Mi <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 or 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 General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "document.h"
#include <QImage>
#include <QPainter>
#include <QApplication>
#include <QClipboard>
#include "impl/kreengraphicsscene.h"
#include "impl/toolmanager.h"
namespace kreen {
namespace core {
class DocumentImpl
{
public:
DocumentImpl()
{
scene = std::make_shared<KreenGraphicsScene>();
}
/**
* this image serves as a placeholder image if no base image is loaded
*/
static QImage createDefaultImage()
{
QPixmap pixmap(400, 300);
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing);
painter.setBackground(QBrush(Qt::white));
painter.setBrush(QBrush(Qt::white));
painter.drawRect(0, 0, 400, 300);
//painter.setBrush(QBrush(Qt::lightGray));
painter.setPen(QPen(Qt::gray));
painter.setFont(QFont("Sans", 16));
painter.drawText(QPointF(30.0, 50.0), "No image loaded.");
return pixmap.toImage();
}
public:
QImage baseImage;
KreenGraphicsScenePtr scene;
int transientContentId = 0;
};
DocumentPtr Document::create(QImage baseImage)
{
if (baseImage.isNull()) {
baseImage = DocumentImpl::createDefaultImage();
}
auto doc = std::make_shared<Document>();
doc->setBaseImage(baseImage);
return doc;
}
Document::Document()
{
KREEN_PIMPL_INIT(Document)
}
Document::~Document()
{
}
QImage Document::baseImage()
{
return d->baseImage;
}
void Document::setBaseImage(QImage image)
{
d->baseImage = image;
}
bool Document::isClean()
{
// TMP, TODO: use QUndoStack
return d->transientContentId == 0;
}
void Document::setClean()
{
// TMP, TODO: use QUndoStack
d->transientContentId = 0;
}
// int Document::contentHashTransient()
// {
// return d->transientContentId;
// }
void Document::addItem(KreenItemPtr item)
{
d->transientContentId++;
_items.push_back(item);
}
void Document::removeItems(const QList<KreenItemPtr> items)
{
foreach (auto item, items) {
d->transientContentId++;
_items.removeAll(item);
}
}
void Document::addDemoItems()
{
//TODO
{
auto item = KreenItem::create("line");
item->setLine(QLine(QPoint(10, 20), QPoint(30, 40)));
_items.push_back(item);
}
{
auto item = KreenItem::create("rect");
item->setRect(QRect(30, 30, 40, 30));
item->lineColor()->color = Qt::darkGreen;
item->lineStyle()->width = 3; // TODO: if this number is uneven, then the item AND the black selection handles become blurred!
item->lineStyle()->penStyle = Qt::DotLine;
_items.push_back(item);
}
{
auto item = KreenItem::create("ellipse");
item->setRect(QRect(10, 40, 40, 40));
_items.push_back(item);
}
{
auto item = KreenItem::create("ellipse");
item->setRect(QRect(10, 80, 70, 40));
item->lineColor()->color = Qt::blue;
item->lineStyle()->width = 2;
item->lineStyle()->penStyle = Qt::DashLine;
_items.push_back(item);
}
{
auto item = KreenItem::create("rect");
item->setRect(QRect(0, 0, 10, 10));
item->lineStyle()->width = 1;
item->lineStyle()->penStyle = Qt::SolidLine;
item->dropShadow()->enabled = false;
_items.push_back(item);
}
{
auto item = KreenItem::create("text");
item->setRect(QRect(10, 120, 200, 40));
item->lineColor()->color = Qt::gray;
item->text = TextProperty::create();
item->text->text = "Hello from the document";
_items.push_back(item);
}
{
auto item = KreenItem::create("text");
item->setRect(QRect(10, 420, 150, 40));
item->lineColor()->color = Qt::magenta;
item->text = TextProperty::create();
item->text->text = "TODO: apply attributes; fill shape; multiline; edit text";
_items.push_back(item);
}
{
auto item = KreenItem::create("rect");
item->setRect(QRect(200, 200, 50, 50));
_items.push_back(item);
}
{
auto item = KreenItem::create("rect");
item->setRect(QRect(962-10, 556-10, 10, 10));
_items.push_back(item);
}
}
void Document::operationCrop(QRect rect)
{
setBaseImage(baseImage().copy(rect));
foreach (auto item, items()) {
item->translate(-rect.x(), -rect.y());
}
}
const QList<KreenItemPtr> Document::items()
{
return _items;
}
KreenGraphicsScenePtr Document::graphicsScene()
{
return d->scene;
}
QImage Document::renderToImage()
{
QImage image = baseImage().copy();
Q_ASSERT_X(!image.isNull(), "renderToImage", "image must not be empty otherwise creation of the painter will fail");
QPainter painterImage(&image);
painterImage.setRenderHint(QPainter::Antialiasing);
d->scene->renderFinalImageOnly(true);
d->scene->render(&painterImage);
d->scene->renderFinalImageOnly(false);
return image;
}
void Document::copyImageToClipboard()
{
QImage image = renderToImage();
QClipboard* clipboard = QApplication::clipboard();
clipboard->setImage(image);
}
}
}
<commit_msg>small fix in default image<commit_after>/*
* This file is part of the kreenshot-editor project.
*
* Copyright (C) 2014 by Gregor Mi <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 or 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 General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "document.h"
#include <QImage>
#include <QPainter>
#include <QApplication>
#include <QClipboard>
#include "impl/kreengraphicsscene.h"
#include "impl/toolmanager.h"
namespace kreen {
namespace core {
class DocumentImpl
{
public:
DocumentImpl()
{
scene = std::make_shared<KreenGraphicsScene>();
}
/**
* this image serves as a placeholder image if no base image is loaded
*/
static QImage createDefaultImage()
{
QPixmap pixmap(400, 300);
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing);
painter.setBackground(QBrush(Qt::white));
painter.setBrush(QBrush(Qt::white));
painter.setPen(QPen(Qt::white));
painter.drawRect(0, 0, 400, 300);
//painter.setBrush(QBrush(Qt::lightGray));
painter.setPen(QPen(Qt::gray));
painter.setFont(QFont("Sans", 16));
painter.drawText(QPointF(30.0, 50.0), "No image loaded.");
return pixmap.toImage();
}
public:
QImage baseImage;
KreenGraphicsScenePtr scene;
int transientContentId = 0;
};
DocumentPtr Document::create(QImage baseImage)
{
if (baseImage.isNull()) {
baseImage = DocumentImpl::createDefaultImage();
}
auto doc = std::make_shared<Document>();
doc->setBaseImage(baseImage);
return doc;
}
Document::Document()
{
KREEN_PIMPL_INIT(Document)
}
Document::~Document()
{
}
QImage Document::baseImage()
{
return d->baseImage;
}
void Document::setBaseImage(QImage image)
{
d->baseImage = image;
}
bool Document::isClean()
{
// TMP, TODO: use QUndoStack
return d->transientContentId == 0;
}
void Document::setClean()
{
// TMP, TODO: use QUndoStack
d->transientContentId = 0;
}
// int Document::contentHashTransient()
// {
// return d->transientContentId;
// }
void Document::addItem(KreenItemPtr item)
{
d->transientContentId++;
_items.push_back(item);
}
void Document::removeItems(const QList<KreenItemPtr> items)
{
foreach (auto item, items) {
d->transientContentId++;
_items.removeAll(item);
}
}
void Document::addDemoItems()
{
//TODO
{
auto item = KreenItem::create("line");
item->setLine(QLine(QPoint(10, 20), QPoint(30, 40)));
_items.push_back(item);
}
{
auto item = KreenItem::create("rect");
item->setRect(QRect(30, 30, 40, 30));
item->lineColor()->color = Qt::darkGreen;
item->lineStyle()->width = 3; // TODO: if this number is uneven, then the item AND the black selection handles become blurred!
item->lineStyle()->penStyle = Qt::DotLine;
_items.push_back(item);
}
{
auto item = KreenItem::create("ellipse");
item->setRect(QRect(10, 40, 40, 40));
_items.push_back(item);
}
{
auto item = KreenItem::create("ellipse");
item->setRect(QRect(10, 80, 70, 40));
item->lineColor()->color = Qt::blue;
item->lineStyle()->width = 2;
item->lineStyle()->penStyle = Qt::DashLine;
_items.push_back(item);
}
{
auto item = KreenItem::create("rect");
item->setRect(QRect(0, 0, 10, 10));
item->lineStyle()->width = 1;
item->lineStyle()->penStyle = Qt::SolidLine;
item->dropShadow()->enabled = false;
_items.push_back(item);
}
{
auto item = KreenItem::create("text");
item->setRect(QRect(10, 120, 200, 40));
item->lineColor()->color = Qt::gray;
item->text = TextProperty::create();
item->text->text = "Hello from the document";
_items.push_back(item);
}
{
auto item = KreenItem::create("text");
item->setRect(QRect(10, 420, 150, 40));
item->lineColor()->color = Qt::magenta;
item->text = TextProperty::create();
item->text->text = "TODO: apply attributes; fill shape; multiline; edit text";
_items.push_back(item);
}
{
auto item = KreenItem::create("rect");
item->setRect(QRect(200, 200, 50, 50));
_items.push_back(item);
}
{
auto item = KreenItem::create("rect");
item->setRect(QRect(962-10, 556-10, 10, 10));
_items.push_back(item);
}
}
void Document::operationCrop(QRect rect)
{
setBaseImage(baseImage().copy(rect));
foreach (auto item, items()) {
item->translate(-rect.x(), -rect.y());
}
}
const QList<KreenItemPtr> Document::items()
{
return _items;
}
KreenGraphicsScenePtr Document::graphicsScene()
{
return d->scene;
}
QImage Document::renderToImage()
{
QImage image = baseImage().copy();
Q_ASSERT_X(!image.isNull(), "renderToImage", "image must not be empty otherwise creation of the painter will fail");
QPainter painterImage(&image);
painterImage.setRenderHint(QPainter::Antialiasing);
d->scene->renderFinalImageOnly(true);
d->scene->render(&painterImage);
d->scene->renderFinalImageOnly(false);
return image;
}
void Document::copyImageToClipboard()
{
QImage image = renderToImage();
QClipboard* clipboard = QApplication::clipboard();
clipboard->setImage(image);
}
}
}
<|endoftext|> |
<commit_before>/*
*
* Copyright (c) 2021 Project CHIP 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 "Resolver.h"
#include <limits>
#include "MinimalMdnsServer.h"
#include "ServiceNaming.h"
#include <mdns/TxtFields.h>
#include <mdns/minimal/Parser.h>
#include <mdns/minimal/QueryBuilder.h>
#include <mdns/minimal/RecordData.h>
#include <mdns/minimal/core/FlatAllocatedQName.h>
#include <support/logging/CHIPLogging.h>
// MDNS servers will receive all broadcast packets over the network.
// Disable 'invalid packet' messages because the are expected and common
// These logs are useful for debug only
#undef MINMDNS_RESOLVER_OVERLY_VERBOSE
namespace chip {
namespace Mdns {
namespace {
enum class DiscoveryType
{
kUnknown,
kOperational,
kCommissionableNode,
};
class TxtRecordDelegateImpl : public mdns::Minimal::TxtRecordDelegate
{
public:
TxtRecordDelegateImpl(CommissionableNodeData * nodeData) : mNodeData(nodeData) {}
void OnRecord(const mdns::Minimal::BytesRange & name, const mdns::Minimal::BytesRange & value);
private:
CommissionableNodeData * mNodeData;
};
const ByteSpan GetSpan(const mdns::Minimal::BytesRange & range)
{
return ByteSpan(range.Start(), range.Size());
}
void TxtRecordDelegateImpl::OnRecord(const mdns::Minimal::BytesRange & name, const mdns::Minimal::BytesRange & value)
{
if (mNodeData == nullptr)
{
return;
}
ByteSpan key = GetSpan(name);
ByteSpan val = GetSpan(value);
FillNodeDataFromTxt(key, val, mNodeData);
}
constexpr size_t kMdnsMaxPacketSize = 1024;
constexpr uint16_t kMdnsPort = 5353;
using namespace mdns::Minimal;
class PacketDataReporter : public ParserDelegate
{
public:
PacketDataReporter(ResolverDelegate * delegate, chip::Inet::InterfaceId interfaceId, DiscoveryType discoveryType,
const BytesRange & packet) :
mDelegate(delegate),
mDiscoveryType(discoveryType), mPacketRange(packet)
{
mNodeData.mInterfaceId = interfaceId;
}
// ParserDelegate implementation
void OnHeader(ConstHeaderRef & header) override;
void OnQuery(const QueryData & data) override;
void OnResource(ResourceType type, const ResourceData & data) override;
// Called after ParsePacket is complete to send final notifications to the delegate.
// Used to ensure all the available IP addresses are attached before completion.
void OnComplete();
private:
ResolverDelegate * mDelegate = nullptr;
DiscoveryType mDiscoveryType;
ResolvedNodeData mNodeData;
CommissionableNodeData mCommissionableNodeData;
BytesRange mPacketRange;
bool mValid = false;
bool mHasNodePort = false;
bool mHasIP = false;
void OnCommissionableNodeSrvRecord(SerializedQNameIterator name, const SrvRecord & srv);
void OnOperationalSrvRecord(SerializedQNameIterator name, const SrvRecord & srv);
void OnCommissionableNodeIPAddress(const chip::Inet::IPAddress & addr);
void OnOperationalIPAddress(const chip::Inet::IPAddress & addr);
};
void PacketDataReporter::OnQuery(const QueryData & data)
{
ChipLogError(Discovery, "Unexpected query packet being parsed as a response");
mValid = false;
}
void PacketDataReporter::OnHeader(ConstHeaderRef & header)
{
mValid = header.GetFlags().IsResponse();
if (header.GetFlags().IsTruncated())
{
#ifdef MINMDNS_RESOLVER_OVERLY_VERBOSE
// MinMdns does not cache data, so receiving piecewise data does not work
ChipLogError(Discovery, "Truncated responses not supported for address resolution");
#endif
}
}
void PacketDataReporter::OnOperationalSrvRecord(SerializedQNameIterator name, const SrvRecord & srv)
{
if (!name.Next())
{
#ifdef MINMDNS_RESOLVER_OVERLY_VERBOSE
ChipLogError(Discovery, "mDNS packet is missing a valid server name");
#endif
mHasNodePort = false;
return;
}
// Before attempting to parse hex values for node/fabrid, validate
// that he response is indeed from a chip tcp service.
{
SerializedQNameIterator suffix = name;
constexpr const char * kExpectedSuffix[] = { "_chip", "_tcp", "local" };
if (suffix != FullQName(kExpectedSuffix))
{
#ifdef MINMDNS_RESOLVER_OVERLY_VERBOSE
ChipLogError(Discovery, "mDNS packet is not for a CHIP device");
#endif
mHasNodePort = false;
return;
}
}
if (ExtractIdFromInstanceName(name.Value(), &mNodeData.mPeerId) != CHIP_NO_ERROR)
{
ChipLogError(Discovery, "Failed to parse peer id from %s", name.Value());
mHasNodePort = false;
return;
}
mNodeData.mPort = srv.GetPort();
mHasNodePort = true;
if (mHasIP)
{
mDelegate->OnNodeIdResolved(mNodeData);
}
}
void PacketDataReporter::OnCommissionableNodeSrvRecord(SerializedQNameIterator name, const SrvRecord & srv)
{
// Host name is the first part of the qname
mdns::Minimal::SerializedQNameIterator it = srv.GetName();
if (!it.Next())
{
return;
}
strncpy(mCommissionableNodeData.hostName, it.Value(), sizeof(CommissionableNodeData::hostName));
}
void PacketDataReporter::OnOperationalIPAddress(const chip::Inet::IPAddress & addr)
{
// TODO: should validate that the IP address we receive belongs to the
// server associated with the SRV record.
//
// This code assumes that all entries in the mDNS packet relate to the
// same entity. This may not be correct if multiple servers are reported
// (if multi-admin decides to use unique ports for every ecosystem).
mNodeData.mAddress = addr;
mHasIP = true;
if (mHasNodePort)
{
mDelegate->OnNodeIdResolved(mNodeData);
}
}
void PacketDataReporter::OnCommissionableNodeIPAddress(const chip::Inet::IPAddress & addr)
{
if (mCommissionableNodeData.numIPs >= CommissionableNodeData::kMaxIPAddresses)
{
return;
}
mCommissionableNodeData.ipAddress[mCommissionableNodeData.numIPs++] = addr;
}
void PacketDataReporter::OnResource(ResourceType type, const ResourceData & data)
{
if (!mValid)
{
return;
}
/// Data content is expected to contain:
/// - A SRV entry that includes the node ID in expected format (fabric + nodeid)
/// - Can extract: fabricid, nodeid, port
/// - References ServerName
/// - Additional records tied to ServerName contain A/AAAA records for IP address data
switch (data.GetType())
{
case QType::SRV: {
SrvRecord srv;
if (!srv.Parse(data.GetData(), mPacketRange))
{
ChipLogError(Discovery, "Packet data reporter failed to parse SRV record");
mHasNodePort = false;
}
else if (mDiscoveryType == DiscoveryType::kOperational)
{
OnOperationalSrvRecord(data.GetName(), srv);
}
else if (mDiscoveryType == DiscoveryType::kCommissionableNode)
{
OnCommissionableNodeSrvRecord(data.GetName(), srv);
}
break;
}
case QType::TXT:
if (mDiscoveryType == DiscoveryType::kCommissionableNode)
{
TxtRecordDelegateImpl textRecordDelegate(&mCommissionableNodeData);
ParseTxtRecord(data.GetData(), &textRecordDelegate);
}
break;
case QType::A: {
Inet::IPAddress addr;
if (!ParseARecord(data.GetData(), &addr))
{
ChipLogError(Discovery, "Packet data reporter failed to parse A record");
mHasIP = false;
}
else
{
if (mDiscoveryType == DiscoveryType::kOperational)
{
OnOperationalIPAddress(addr);
}
else if (mDiscoveryType == DiscoveryType::kCommissionableNode)
{
OnCommissionableNodeIPAddress(addr);
}
}
break;
}
case QType::AAAA: {
Inet::IPAddress addr;
if (!ParseAAAARecord(data.GetData(), &addr))
{
ChipLogError(Discovery, "Packet data reporter failed to parse AAAA record");
mHasIP = false;
}
else
{
if (mDiscoveryType == DiscoveryType::kOperational)
{
OnOperationalIPAddress(addr);
}
else if (mDiscoveryType == DiscoveryType::kCommissionableNode)
{
OnCommissionableNodeIPAddress(addr);
}
}
break;
}
default:
break;
}
}
void PacketDataReporter::OnComplete()
{
if (mDiscoveryType == DiscoveryType::kCommissionableNode && mCommissionableNodeData.IsValid())
{
mDelegate->OnCommissionableNodeFound(mCommissionableNodeData);
}
}
class MinMdnsResolver : public Resolver, public MdnsPacketDelegate
{
public:
MinMdnsResolver() { GlobalMinimalMdnsServer::Instance().SetResponseDelegate(this); }
//// MdnsPacketDelegate implementation
void OnMdnsPacketData(const BytesRange & data, const chip::Inet::IPPacketInfo * info) override;
///// Resolver implementation
CHIP_ERROR StartResolver(chip::Inet::InetLayer * inetLayer, uint16_t port) override;
CHIP_ERROR SetResolverDelegate(ResolverDelegate * delegate) override;
CHIP_ERROR ResolveNodeId(const PeerId & peerId, Inet::IPAddressType type) override;
CHIP_ERROR FindCommissionableNodes(DiscoveryFilter filter = DiscoveryFilter()) override;
private:
ResolverDelegate * mDelegate = nullptr;
DiscoveryType mDiscoveryType = DiscoveryType::kUnknown;
CHIP_ERROR SendQuery(mdns::Minimal::FullQName qname, mdns::Minimal::QType type);
CHIP_ERROR BrowseNodes(DiscoveryType type, DiscoveryFilter subtype);
template <typename... Args>
mdns::Minimal::FullQName CheckAndAllocateQName(Args &&... parts)
{
size_t requiredSize = mdns::Minimal::FlatAllocatedQName::RequiredStorageSize(parts...);
if (requiredSize > kMaxQnameSize)
{
return mdns::Minimal::FullQName();
}
return mdns::Minimal::FlatAllocatedQName::Build(qnameStorage, parts...);
}
static constexpr int kMaxQnameSize = 100;
char qnameStorage[kMaxQnameSize];
};
void MinMdnsResolver::OnMdnsPacketData(const BytesRange & data, const chip::Inet::IPPacketInfo * info)
{
if (mDelegate == nullptr)
{
return;
}
PacketDataReporter reporter(mDelegate, info->Interface, mDiscoveryType, data);
if (!ParsePacket(data, &reporter))
{
ChipLogError(Discovery, "Failed to parse received mDNS packet");
}
else
{
reporter.OnComplete();
}
}
CHIP_ERROR MinMdnsResolver::StartResolver(chip::Inet::InetLayer * inetLayer, uint16_t port)
{
/// Note: we do not double-check the port as we assume the APP will always use
/// the same inetLayer and port for mDNS.
if (GlobalMinimalMdnsServer::Server().IsListening())
{
return CHIP_NO_ERROR;
}
return GlobalMinimalMdnsServer::Instance().StartServer(inetLayer, port);
}
CHIP_ERROR MinMdnsResolver::SetResolverDelegate(ResolverDelegate * delegate)
{
mDelegate = delegate;
return CHIP_NO_ERROR;
}
CHIP_ERROR MinMdnsResolver::SendQuery(mdns::Minimal::FullQName qname, mdns::Minimal::QType type)
{
System::PacketBufferHandle buffer = System::PacketBufferHandle::New(kMdnsMaxPacketSize);
ReturnErrorCodeIf(buffer.IsNull(), CHIP_ERROR_NO_MEMORY);
QueryBuilder builder(std::move(buffer));
builder.Header().SetMessageId(0);
mdns::Minimal::Query query(qname);
query.SetType(type).SetClass(mdns::Minimal::QClass::IN);
// TODO(cecille): Not sure why unicast response isn't working - fix.
query.SetAnswerViaUnicast(false);
builder.AddQuery(query);
ReturnErrorCodeIf(!builder.Ok(), CHIP_ERROR_INTERNAL);
return GlobalMinimalMdnsServer::Server().BroadcastSend(builder.ReleasePacket(), kMdnsPort);
}
CHIP_ERROR MinMdnsResolver::FindCommissionableNodes(DiscoveryFilter filter)
{
return BrowseNodes(DiscoveryType::kCommissionableNode, filter);
}
// TODO(cecille): Extend filter and use this for Resolve
CHIP_ERROR MinMdnsResolver::BrowseNodes(DiscoveryType type, DiscoveryFilter filter)
{
mDiscoveryType = type;
mdns::Minimal::FullQName qname;
switch (type)
{
case DiscoveryType::kOperational:
qname = CheckAndAllocateQName(kOperationalServiceName, kOperationalProtocol, kLocalDomain);
break;
case DiscoveryType::kCommissionableNode:
if (filter.type == DiscoveryFilterType::kNone)
{
qname = CheckAndAllocateQName(kCommissionableServiceName, kCommissionProtocol, kLocalDomain);
}
else
{
char subtypeStr[kMaxSubtypeDescSize];
ReturnErrorOnFailure(MakeServiceSubtype(subtypeStr, sizeof(subtypeStr), filter));
qname = CheckAndAllocateQName(subtypeStr, kSubtypeServiceNamePart, kCommissionableServiceName, kCommissionProtocol,
kLocalDomain);
}
break;
case DiscoveryType::kUnknown:
break;
}
if (!qname.nameCount)
{
return CHIP_ERROR_NO_MEMORY;
}
return SendQuery(qname, mdns::Minimal::QType::ANY);
}
CHIP_ERROR MinMdnsResolver::ResolveNodeId(const PeerId & peerId, Inet::IPAddressType type)
{
mDiscoveryType = DiscoveryType::kOperational;
System::PacketBufferHandle buffer = System::PacketBufferHandle::New(kMdnsMaxPacketSize);
ReturnErrorCodeIf(buffer.IsNull(), CHIP_ERROR_NO_MEMORY);
QueryBuilder builder(std::move(buffer));
builder.Header().SetMessageId(0);
{
char nameBuffer[64] = "";
// Node and fabricid are encoded in server names.
ReturnErrorOnFailure(MakeInstanceName(nameBuffer, sizeof(nameBuffer), peerId));
const char * instanceQName[] = { nameBuffer, kOperationalServiceName, kOperationalProtocol, kLocalDomain };
Query query(instanceQName);
query
.SetClass(QClass::IN) //
.SetType(QType::ANY) //
.SetAnswerViaUnicast(false) //
;
// NOTE: type above is NOT A or AAAA because the name searched for is
// a SRV record. The layout is:
// SRV -> hostname
// Hostname -> A
// Hostname -> AAAA
//
// Query is sent for ANY and expectation is to receive A/AAAA records
// in the additional section of the reply.
//
// Sending a A/AAAA query will return no results
// Sending a SRV query will return the srv only and an additional query
// would be needed to resolve the host name to an IP address
builder.AddQuery(query);
}
ReturnErrorCodeIf(!builder.Ok(), CHIP_ERROR_INTERNAL);
return GlobalMinimalMdnsServer::Server().BroadcastSend(builder.ReleasePacket(), kMdnsPort);
}
MinMdnsResolver gResolver;
} // namespace
Resolver & chip::Mdns::Resolver::Instance()
{
return gResolver;
}
} // namespace Mdns
} // namespace chip
<commit_msg>Filter received mdns records to chip only. (#7527)<commit_after>/*
*
* Copyright (c) 2021 Project CHIP 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 "Resolver.h"
#include <limits>
#include "MinimalMdnsServer.h"
#include "ServiceNaming.h"
#include <mdns/TxtFields.h>
#include <mdns/minimal/Parser.h>
#include <mdns/minimal/QueryBuilder.h>
#include <mdns/minimal/RecordData.h>
#include <mdns/minimal/core/FlatAllocatedQName.h>
#include <support/logging/CHIPLogging.h>
// MDNS servers will receive all broadcast packets over the network.
// Disable 'invalid packet' messages because the are expected and common
// These logs are useful for debug only
#undef MINMDNS_RESOLVER_OVERLY_VERBOSE
namespace chip {
namespace Mdns {
namespace {
enum class DiscoveryType
{
kUnknown,
kOperational,
kCommissionableNode,
};
class TxtRecordDelegateImpl : public mdns::Minimal::TxtRecordDelegate
{
public:
TxtRecordDelegateImpl(CommissionableNodeData * nodeData) : mNodeData(nodeData) {}
void OnRecord(const mdns::Minimal::BytesRange & name, const mdns::Minimal::BytesRange & value);
private:
CommissionableNodeData * mNodeData;
};
const ByteSpan GetSpan(const mdns::Minimal::BytesRange & range)
{
return ByteSpan(range.Start(), range.Size());
}
void TxtRecordDelegateImpl::OnRecord(const mdns::Minimal::BytesRange & name, const mdns::Minimal::BytesRange & value)
{
if (mNodeData == nullptr)
{
return;
}
ByteSpan key = GetSpan(name);
ByteSpan val = GetSpan(value);
FillNodeDataFromTxt(key, val, mNodeData);
}
constexpr size_t kMdnsMaxPacketSize = 1024;
constexpr uint16_t kMdnsPort = 5353;
using namespace mdns::Minimal;
class PacketDataReporter : public ParserDelegate
{
public:
PacketDataReporter(ResolverDelegate * delegate, chip::Inet::InterfaceId interfaceId, DiscoveryType discoveryType,
const BytesRange & packet) :
mDelegate(delegate),
mDiscoveryType(discoveryType), mPacketRange(packet)
{
mNodeData.mInterfaceId = interfaceId;
}
// ParserDelegate implementation
void OnHeader(ConstHeaderRef & header) override;
void OnQuery(const QueryData & data) override;
void OnResource(ResourceType type, const ResourceData & data) override;
// Called after ParsePacket is complete to send final notifications to the delegate.
// Used to ensure all the available IP addresses are attached before completion.
void OnComplete();
private:
ResolverDelegate * mDelegate = nullptr;
DiscoveryType mDiscoveryType;
ResolvedNodeData mNodeData;
CommissionableNodeData mCommissionableNodeData;
BytesRange mPacketRange;
bool mValid = false;
bool mHasNodePort = false;
bool mHasIP = false;
void OnCommissionableNodeSrvRecord(SerializedQNameIterator name, const SrvRecord & srv);
void OnOperationalSrvRecord(SerializedQNameIterator name, const SrvRecord & srv);
void OnCommissionableNodeIPAddress(const chip::Inet::IPAddress & addr);
void OnOperationalIPAddress(const chip::Inet::IPAddress & addr);
};
void PacketDataReporter::OnQuery(const QueryData & data)
{
ChipLogError(Discovery, "Unexpected query packet being parsed as a response");
mValid = false;
}
void PacketDataReporter::OnHeader(ConstHeaderRef & header)
{
mValid = header.GetFlags().IsResponse();
if (header.GetFlags().IsTruncated())
{
#ifdef MINMDNS_RESOLVER_OVERLY_VERBOSE
// MinMdns does not cache data, so receiving piecewise data does not work
ChipLogError(Discovery, "Truncated responses not supported for address resolution");
#endif
}
}
void PacketDataReporter::OnOperationalSrvRecord(SerializedQNameIterator name, const SrvRecord & srv)
{
if (!name.Next())
{
#ifdef MINMDNS_RESOLVER_OVERLY_VERBOSE
ChipLogError(Discovery, "mDNS packet is missing a valid server name");
#endif
mHasNodePort = false;
return;
}
if (ExtractIdFromInstanceName(name.Value(), &mNodeData.mPeerId) != CHIP_NO_ERROR)
{
ChipLogError(Discovery, "Failed to parse peer id from %s", name.Value());
mHasNodePort = false;
return;
}
mNodeData.mPort = srv.GetPort();
mHasNodePort = true;
}
void PacketDataReporter::OnCommissionableNodeSrvRecord(SerializedQNameIterator name, const SrvRecord & srv)
{
// Host name is the first part of the qname
mdns::Minimal::SerializedQNameIterator it = srv.GetName();
if (!it.Next())
{
return;
}
strncpy(mCommissionableNodeData.hostName, it.Value(), sizeof(CommissionableNodeData::hostName));
}
void PacketDataReporter::OnOperationalIPAddress(const chip::Inet::IPAddress & addr)
{
// TODO: should validate that the IP address we receive belongs to the
// server associated with the SRV record.
//
// This code assumes that all entries in the mDNS packet relate to the
// same entity. This may not be correct if multiple servers are reported
// (if multi-admin decides to use unique ports for every ecosystem).
mNodeData.mAddress = addr;
mHasIP = true;
}
void PacketDataReporter::OnCommissionableNodeIPAddress(const chip::Inet::IPAddress & addr)
{
if (mCommissionableNodeData.numIPs >= CommissionableNodeData::kMaxIPAddresses)
{
return;
}
mCommissionableNodeData.ipAddress[mCommissionableNodeData.numIPs++] = addr;
}
bool HasQNamePart(SerializedQNameIterator qname, QNamePart part)
{
while (qname.Next())
{
if (strcmp(qname.Value(), part) == 0)
{
return true;
}
}
return false;
}
void PacketDataReporter::OnResource(ResourceType type, const ResourceData & data)
{
if (!mValid)
{
return;
}
/// Data content is expected to contain:
/// - A SRV entry that includes the node ID in expected format (fabric + nodeid)
/// - Can extract: fabricid, nodeid, port
/// - References ServerName
/// - Additional records tied to ServerName contain A/AAAA records for IP address data
switch (data.GetType())
{
case QType::SRV: {
SrvRecord srv;
if (!srv.Parse(data.GetData(), mPacketRange))
{
ChipLogError(Discovery, "Packet data reporter failed to parse SRV record");
mHasNodePort = false;
}
else if (mDiscoveryType == DiscoveryType::kOperational)
{
// Ensure this is our record.
if (HasQNamePart(data.GetName(), kOperationalServiceName))
{
OnOperationalSrvRecord(data.GetName(), srv);
}
else
{
mValid = false;
}
}
else if (mDiscoveryType == DiscoveryType::kCommissionableNode)
{
if (HasQNamePart(data.GetName(), kCommissionableServiceName))
{
OnCommissionableNodeSrvRecord(data.GetName(), srv);
}
else
{
mValid = false;
}
}
break;
}
case QType::TXT:
if (mDiscoveryType == DiscoveryType::kCommissionableNode)
{
TxtRecordDelegateImpl textRecordDelegate(&mCommissionableNodeData);
ParseTxtRecord(data.GetData(), &textRecordDelegate);
}
break;
case QType::A: {
Inet::IPAddress addr;
if (!ParseARecord(data.GetData(), &addr))
{
ChipLogError(Discovery, "Packet data reporter failed to parse A record");
mHasIP = false;
}
else
{
if (mDiscoveryType == DiscoveryType::kOperational)
{
OnOperationalIPAddress(addr);
}
else if (mDiscoveryType == DiscoveryType::kCommissionableNode)
{
OnCommissionableNodeIPAddress(addr);
}
}
break;
}
case QType::AAAA: {
Inet::IPAddress addr;
if (!ParseAAAARecord(data.GetData(), &addr))
{
ChipLogError(Discovery, "Packet data reporter failed to parse AAAA record");
mHasIP = false;
}
else
{
if (mDiscoveryType == DiscoveryType::kOperational)
{
OnOperationalIPAddress(addr);
}
else if (mDiscoveryType == DiscoveryType::kCommissionableNode)
{
OnCommissionableNodeIPAddress(addr);
}
}
break;
}
default:
break;
}
}
void PacketDataReporter::OnComplete()
{
if (mDiscoveryType == DiscoveryType::kCommissionableNode && mCommissionableNodeData.IsValid())
{
mDelegate->OnCommissionableNodeFound(mCommissionableNodeData);
}
else if (mDiscoveryType == DiscoveryType::kOperational && mHasIP && mHasNodePort)
{
mDelegate->OnNodeIdResolved(mNodeData);
}
}
class MinMdnsResolver : public Resolver, public MdnsPacketDelegate
{
public:
MinMdnsResolver() { GlobalMinimalMdnsServer::Instance().SetResponseDelegate(this); }
//// MdnsPacketDelegate implementation
void OnMdnsPacketData(const BytesRange & data, const chip::Inet::IPPacketInfo * info) override;
///// Resolver implementation
CHIP_ERROR StartResolver(chip::Inet::InetLayer * inetLayer, uint16_t port) override;
CHIP_ERROR SetResolverDelegate(ResolverDelegate * delegate) override;
CHIP_ERROR ResolveNodeId(const PeerId & peerId, Inet::IPAddressType type) override;
CHIP_ERROR FindCommissionableNodes(DiscoveryFilter filter = DiscoveryFilter()) override;
private:
ResolverDelegate * mDelegate = nullptr;
DiscoveryType mDiscoveryType = DiscoveryType::kUnknown;
CHIP_ERROR SendQuery(mdns::Minimal::FullQName qname, mdns::Minimal::QType type);
CHIP_ERROR BrowseNodes(DiscoveryType type, DiscoveryFilter subtype);
template <typename... Args>
mdns::Minimal::FullQName CheckAndAllocateQName(Args &&... parts)
{
size_t requiredSize = mdns::Minimal::FlatAllocatedQName::RequiredStorageSize(parts...);
if (requiredSize > kMaxQnameSize)
{
return mdns::Minimal::FullQName();
}
return mdns::Minimal::FlatAllocatedQName::Build(qnameStorage, parts...);
}
static constexpr int kMaxQnameSize = 100;
char qnameStorage[kMaxQnameSize];
};
void MinMdnsResolver::OnMdnsPacketData(const BytesRange & data, const chip::Inet::IPPacketInfo * info)
{
if (mDelegate == nullptr)
{
return;
}
PacketDataReporter reporter(mDelegate, info->Interface, mDiscoveryType, data);
if (!ParsePacket(data, &reporter))
{
ChipLogError(Discovery, "Failed to parse received mDNS packet");
}
else
{
reporter.OnComplete();
}
}
CHIP_ERROR MinMdnsResolver::StartResolver(chip::Inet::InetLayer * inetLayer, uint16_t port)
{
/// Note: we do not double-check the port as we assume the APP will always use
/// the same inetLayer and port for mDNS.
if (GlobalMinimalMdnsServer::Server().IsListening())
{
return CHIP_NO_ERROR;
}
return GlobalMinimalMdnsServer::Instance().StartServer(inetLayer, port);
}
CHIP_ERROR MinMdnsResolver::SetResolverDelegate(ResolverDelegate * delegate)
{
mDelegate = delegate;
return CHIP_NO_ERROR;
}
CHIP_ERROR MinMdnsResolver::SendQuery(mdns::Minimal::FullQName qname, mdns::Minimal::QType type)
{
System::PacketBufferHandle buffer = System::PacketBufferHandle::New(kMdnsMaxPacketSize);
ReturnErrorCodeIf(buffer.IsNull(), CHIP_ERROR_NO_MEMORY);
QueryBuilder builder(std::move(buffer));
builder.Header().SetMessageId(0);
mdns::Minimal::Query query(qname);
query.SetType(type).SetClass(mdns::Minimal::QClass::IN);
// TODO(cecille): Not sure why unicast response isn't working - fix.
query.SetAnswerViaUnicast(false);
builder.AddQuery(query);
ReturnErrorCodeIf(!builder.Ok(), CHIP_ERROR_INTERNAL);
return GlobalMinimalMdnsServer::Server().BroadcastSend(builder.ReleasePacket(), kMdnsPort);
}
CHIP_ERROR MinMdnsResolver::FindCommissionableNodes(DiscoveryFilter filter)
{
return BrowseNodes(DiscoveryType::kCommissionableNode, filter);
}
// TODO(cecille): Extend filter and use this for Resolve
CHIP_ERROR MinMdnsResolver::BrowseNodes(DiscoveryType type, DiscoveryFilter filter)
{
mDiscoveryType = type;
mdns::Minimal::FullQName qname;
switch (type)
{
case DiscoveryType::kOperational:
qname = CheckAndAllocateQName(kOperationalServiceName, kOperationalProtocol, kLocalDomain);
break;
case DiscoveryType::kCommissionableNode:
if (filter.type == DiscoveryFilterType::kNone)
{
qname = CheckAndAllocateQName(kCommissionableServiceName, kCommissionProtocol, kLocalDomain);
}
else
{
char subtypeStr[kMaxSubtypeDescSize];
ReturnErrorOnFailure(MakeServiceSubtype(subtypeStr, sizeof(subtypeStr), filter));
qname = CheckAndAllocateQName(subtypeStr, kSubtypeServiceNamePart, kCommissionableServiceName, kCommissionProtocol,
kLocalDomain);
}
break;
case DiscoveryType::kUnknown:
break;
}
if (!qname.nameCount)
{
return CHIP_ERROR_NO_MEMORY;
}
return SendQuery(qname, mdns::Minimal::QType::ANY);
}
CHIP_ERROR MinMdnsResolver::ResolveNodeId(const PeerId & peerId, Inet::IPAddressType type)
{
mDiscoveryType = DiscoveryType::kOperational;
System::PacketBufferHandle buffer = System::PacketBufferHandle::New(kMdnsMaxPacketSize);
ReturnErrorCodeIf(buffer.IsNull(), CHIP_ERROR_NO_MEMORY);
QueryBuilder builder(std::move(buffer));
builder.Header().SetMessageId(0);
{
char nameBuffer[64] = "";
// Node and fabricid are encoded in server names.
ReturnErrorOnFailure(MakeInstanceName(nameBuffer, sizeof(nameBuffer), peerId));
const char * instanceQName[] = { nameBuffer, kOperationalServiceName, kOperationalProtocol, kLocalDomain };
Query query(instanceQName);
query
.SetClass(QClass::IN) //
.SetType(QType::ANY) //
.SetAnswerViaUnicast(false) //
;
// NOTE: type above is NOT A or AAAA because the name searched for is
// a SRV record. The layout is:
// SRV -> hostname
// Hostname -> A
// Hostname -> AAAA
//
// Query is sent for ANY and expectation is to receive A/AAAA records
// in the additional section of the reply.
//
// Sending a A/AAAA query will return no results
// Sending a SRV query will return the srv only and an additional query
// would be needed to resolve the host name to an IP address
builder.AddQuery(query);
}
ReturnErrorCodeIf(!builder.Ok(), CHIP_ERROR_INTERNAL);
return GlobalMinimalMdnsServer::Server().BroadcastSend(builder.ReleasePacket(), kMdnsPort);
}
MinMdnsResolver gResolver;
} // namespace
Resolver & chip::Mdns::Resolver::Instance()
{
return gResolver;
}
} // namespace Mdns
} // namespace chip
<|endoftext|> |
<commit_before>// IBM_PROLOG_BEGIN_TAG
// This is an automatically generated prolog.
//
// $Source: src/usr/diag/prdf/test/prdfTest.H $
//
// IBM CONFIDENTIAL
//
// COPYRIGHT International Business Machines Corp. 2012
//
// p1
//
// Object Code Only (OCO) source materials
// Licensed Internal Code Source Materials
// IBM HostBoot Licensed Internal Code
//
// The source code for this program is not published or other-
// wise divested of its trade secrets, irrespective of what has
// been deposited with the U.S. Copyright Office.
//
// Origin: 30
//
// IBM_PROLOG_END
#ifndef __TEST_PRDFTEST_H
#define __TEST_PRDFTEST_H
/**
* @file prdfTest.H
*
* @brief prdf unit test
*/
#include <cxxtest/TestSuite.H>
#include <prdfTrace.H>
#include <prdf_proto.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
class prdfTest: public CxxTest::TestSuite
{
public:
void testTrace(void)
{
TS_TRACE(ENTER_MRK __FUNCTION__);
PRDF_ENTER( "%s", __FUNCTION__ );
const char * l_testStr = "running testTrace";
uint64_t l_testHex = 0xDEADBEEF;
uint64_t l_testDec = 99;
PRDF_INF( "testTrace() %s - testHex=0x%08X, testDec=%d", l_testStr, l_testHex, l_testDec );
uint64_t l_chip = 0xFFFFFFFF;
uint64_t l_sig = 0x12345678;
PRDF_SIG( "%08X %08X", l_chip, l_sig);
PRDF_ERR( "testTrace() Please ignore this error trace 0x%08X", l_testHex );
PRDF_EXIT( "%s", __FUNCTION__ );
PRDF_DENTER( "testTrace()" );
PRDF_DINF( "testTrace() running testTrace" );
PRDF_DEXIT( "testTrace()" );
TS_TRACE(EXIT_MRK __FUNCTION__);
}
void testPrdInitialize(void)
{
using namespace PRDF;
TS_TRACE(ENTER_MRK __FUNCTION__);
PRDF_ENTER( "testPrdInitialize()" );
errlHndl_t l_pErr = NULL;
l_pErr = PrdInitialize();
if (l_pErr)
{
PRDF_ERR( "testPrdInitialize(): PrdInitialize returned error" );
TS_FAIL("testPrdInitialize(): PrdInitialize returned error");
errlCommit(l_pErr,PRDF_COMP_ID);
}
else
{
PRDF_INF( "testPrdInitialize(): PrdInitialize completed with no error" );
TS_TRACE(INFO_MRK "testPrdInitialize(): PrdInitialize completed with no error");
}
PRDF_EXIT( "testPrdInitialize()" );
TS_TRACE(EXIT_MRK __FUNCTION__);
}
void testPrdMain(void)
{
using namespace PRDF;
TS_TRACE(ENTER_MRK __FUNCTION__);
PRDF_ENTER( "testPrdMain()" );
errlHndl_t l_pErr = NULL;
//l_pErr = PrdMain();
if (l_pErr)
{
PRDF_ERR( "testPrdMain(): PrdMain returned error" );
TS_FAIL("testPrdMain(): PrdMain returned error");
errlCommit(l_pErr,PRDF_COMP_ID);
}
else
{
PRDF_INF( "testPrdMain(): PrdMain completed with no error" );
TS_TRACE(INFO_MRK "testPrdMain(): PrdMain completed with no error");
}
PRDF_EXIT( "testPrdMain()" );
TS_TRACE(EXIT_MRK __FUNCTION__);
}
void testPrdIplCleanup(void)
{
using namespace PRDF;
TS_TRACE(ENTER_MRK __FUNCTION__);
PRDF_ENTER( "testPrdIplCleanup()" );
PrdIplCleanup();
PRDF_EXIT( "testPrdIplCleanup()" );
TS_TRACE(EXIT_MRK __FUNCTION__);
}
};
#endif
<commit_msg>Fix __FUNCTION__ error in TS_TRACE<commit_after>// IBM_PROLOG_BEGIN_TAG
// This is an automatically generated prolog.
//
// $Source: src/usr/diag/prdf/test/prdfTest.H $
//
// IBM CONFIDENTIAL
//
// COPYRIGHT International Business Machines Corp. 2012
//
// p1
//
// Object Code Only (OCO) source materials
// Licensed Internal Code Source Materials
// IBM HostBoot Licensed Internal Code
//
// The source code for this program is not published or other-
// wise divested of its trade secrets, irrespective of what has
// been deposited with the U.S. Copyright Office.
//
// Origin: 30
//
// IBM_PROLOG_END
#ifndef __TEST_PRDFTEST_H
#define __TEST_PRDFTEST_H
/**
* @file prdfTest.H
*
* @brief prdf unit test
*/
#include <cxxtest/TestSuite.H>
#include <prdfTrace.H>
#include <prdf_proto.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
class prdfTest: public CxxTest::TestSuite
{
public:
void testTrace(void)
{
TS_TRACE(ENTER_MRK "testTrace()");
PRDF_ENTER( "testTrace()" );
const char * l_testStr = "running testTrace";
uint64_t l_testHex = 0xDEADBEEF;
uint64_t l_testDec = 99;
PRDF_INF( "testTrace() %s - testHex=0x%08X, testDec=%d", l_testStr, l_testHex, l_testDec );
uint64_t l_chip = 0xFFFFFFFF;
uint64_t l_sig = 0x12345678;
PRDF_SIG( "%08X %08X", l_chip, l_sig);
PRDF_ERR( "testTrace() Please ignore this error trace 0x%08X", l_testHex );
PRDF_DENTER( "testTrace()" );
PRDF_DINF( "testTrace() running testTrace" );
PRDF_DEXIT( "testTrace()" );
PRDF_EXIT( "testTrace()" );
TS_TRACE(EXIT_MRK "testTrace()");
}
void testPrdInitialize(void)
{
using namespace PRDF;
TS_TRACE(ENTER_MRK "testPrdInitialize()");
PRDF_ENTER( "testPrdInitialize()" );
errlHndl_t l_pErr = NULL;
l_pErr = PrdInitialize();
if (l_pErr)
{
PRDF_ERR( "testPrdInitialize(): PrdInitialize returned error" );
TS_FAIL("testPrdInitialize(): PrdInitialize returned error");
errlCommit(l_pErr,PRDF_COMP_ID);
}
else
{
PRDF_INF( "testPrdInitialize(): PrdInitialize completed with no error" );
TS_TRACE(INFO_MRK "testPrdInitialize(): PrdInitialize completed with no error");
}
PRDF_EXIT( "testPrdInitialize()" );
TS_TRACE(EXIT_MRK "testPrdInitialize()");
}
void testPrdMain(void)
{
using namespace PRDF;
TS_TRACE(ENTER_MRK "testPrdMain()");
PRDF_ENTER( "testPrdMain()" );
errlHndl_t l_pErr = NULL;
//l_pErr = PrdMain();
if (l_pErr)
{
PRDF_ERR( "testPrdMain(): PrdMain returned error" );
TS_FAIL("testPrdMain(): PrdMain returned error");
errlCommit(l_pErr,PRDF_COMP_ID);
}
else
{
PRDF_INF( "testPrdMain(): PrdMain completed with no error" );
TS_TRACE(INFO_MRK "testPrdMain(): PrdMain completed with no error");
}
PRDF_EXIT( "testPrdMain()" );
TS_TRACE(EXIT_MRK "testPrdMain()");
}
void testPrdIplCleanup(void)
{
using namespace PRDF;
TS_TRACE(ENTER_MRK "testPrdIplCleanup()");
PRDF_ENTER( "testPrdIplCleanup()" );
PrdIplCleanup();
PRDF_EXIT( "testPrdIplCleanup()" );
TS_TRACE(EXIT_MRK "testPrdIplCleanup()");
}
};
#endif
<|endoftext|> |
<commit_before><commit_msg>calculate 2x2 determinants - testing<commit_after><|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/gtk/infobar_gtk.h"
#include <gtk/gtk.h>
#include "base/gfx/gtk_util.h"
#include "base/string_util.h"
#include "chrome/browser/gtk/custom_button.h"
#include "chrome/browser/gtk/infobar_container_gtk.h"
namespace {
// TODO(estade): The background should be a gradient. For now we just use this
// solid color.
const GdkColor kBackgroundColor = GDK_COLOR_RGB(250, 230, 145);
// Border color (the top pixel of the infobar).
const GdkColor kBorderColor = GDK_COLOR_RGB(0xbe, 0xc8, 0xd4);
// The total height of the info bar.
const int kInfoBarHeight = 37;
// Pixels between infobar elements.
const int kElementPadding = 5;
// Extra padding on either end of info bar.
const int kLeftPadding = 5;
const int kRightPadding = 5;
}
InfoBar::InfoBar(InfoBarDelegate* delegate)
: container_(NULL),
delegate_(delegate) {
// Create |hbox_| and pad the sides.
hbox_ = gtk_hbox_new(FALSE, kElementPadding);
GtkWidget* padding = gtk_alignment_new(0, 0, 1, 1);
gtk_alignment_set_padding(GTK_ALIGNMENT(padding),
0, 0, kLeftPadding, kRightPadding);
GtkWidget* bg_box = gtk_event_box_new();
gtk_container_add(GTK_CONTAINER(padding), hbox_);
gtk_container_add(GTK_CONTAINER(bg_box), padding);
// Set the top border and background color.
gtk_widget_modify_bg(bg_box, GTK_STATE_NORMAL, &kBackgroundColor);
widget_.Own(gfx::CreateGtkBorderBin(bg_box, &kBorderColor,
1, 0, 0, 0));
gtk_widget_set_size_request(widget_.get(), -1, kInfoBarHeight);
close_button_.reset(CustomDrawButton::AddBarCloseButton(hbox_));
g_signal_connect(G_OBJECT(close_button_->widget()), "clicked",
G_CALLBACK(OnCloseButton), this);
g_object_set_data(G_OBJECT(widget_.get()), "info-bar", this);
}
InfoBar::~InfoBar() {
widget_.Destroy();
}
void InfoBar::AnimateOpen() {
// TODO(port): add animations. In the meantime just Open().
NOTIMPLEMENTED();
Open();
}
void InfoBar::Open() {
gtk_widget_show_all(widget_.get());
}
void InfoBar::AnimateClose() {
// TODO(port): add animations. In the meantime just Close().
NOTIMPLEMENTED();
Close();
}
void InfoBar::Close() {
gtk_widget_hide(widget_.get());
}
void InfoBar::RemoveInfoBar() const {
container_->RemoveDelegate(delegate_);
}
// static
void InfoBar::OnCloseButton(GtkWidget* button, InfoBar* info_bar) {
info_bar->AnimateClose();
}
// AlertInfoBar ----------------------------------------------------------------
class AlertInfoBar : public InfoBar {
public:
AlertInfoBar(AlertInfoBarDelegate* delegate)
: InfoBar(delegate) {
std::wstring text = delegate->GetMessageText();
GtkWidget* label = gtk_label_new(WideToUTF8(text).c_str());
SkBitmap* icon = delegate->GetIcon();
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(icon);
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
gdk_pixbuf_unref(pixbuf);
gtk_box_pack_start(GTK_BOX(hbox_), image, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 0);
}
};
// LinkInfoBar -----------------------------------------------------------------
class LinkInfoBar : public InfoBar {
public:
LinkInfoBar(LinkInfoBarDelegate* delegate)
: InfoBar(delegate) {
// TODO(estade): remove these lines.
NOTIMPLEMENTED();
GtkWidget* label = gtk_label_new("LinkInfoBar not yet implemented. "
"Check back later.");
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 10);
}
};
// ConfirmInfoBar --------------------------------------------------------------
class ConfirmInfoBar : public AlertInfoBar {
public:
ConfirmInfoBar(ConfirmInfoBarDelegate* delegate)
: AlertInfoBar(delegate) {
NOTIMPLEMENTED();
}
};
// AlertInfoBarDelegate, InfoBarDelegate overrides: ----------------------------
InfoBar* AlertInfoBarDelegate::CreateInfoBar() {
return new AlertInfoBar(this);
}
// LinkInfoBarDelegate, InfoBarDelegate overrides: -----------------------------
InfoBar* LinkInfoBarDelegate::CreateInfoBar() {
return new LinkInfoBar(this);
}
// ConfirmInfoBarDelegate, InfoBarDelegate overrides: --------------------------
InfoBar* ConfirmInfoBarDelegate::CreateInfoBar() {
return new ConfirmInfoBar(this);
}
<commit_msg>Linux: Hook up confirm info bar buttons. Session restore works.<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/gtk/infobar_gtk.h"
#include <gtk/gtk.h>
#include "base/gfx/gtk_util.h"
#include "base/string_util.h"
#include "chrome/browser/gtk/custom_button.h"
#include "chrome/browser/gtk/infobar_container_gtk.h"
namespace {
// TODO(estade): The background should be a gradient. For now we just use this
// solid color.
const GdkColor kBackgroundColor = GDK_COLOR_RGB(250, 230, 145);
// Border color (the top pixel of the infobar).
const GdkColor kBorderColor = GDK_COLOR_RGB(0xbe, 0xc8, 0xd4);
// The total height of the info bar.
const int kInfoBarHeight = 37;
// Pixels between infobar elements.
const int kElementPadding = 5;
// Extra padding on either end of info bar.
const int kLeftPadding = 5;
const int kRightPadding = 5;
}
InfoBar::InfoBar(InfoBarDelegate* delegate)
: container_(NULL),
delegate_(delegate) {
// Create |hbox_| and pad the sides.
hbox_ = gtk_hbox_new(FALSE, kElementPadding);
GtkWidget* padding = gtk_alignment_new(0, 0, 1, 1);
gtk_alignment_set_padding(GTK_ALIGNMENT(padding),
0, 0, kLeftPadding, kRightPadding);
GtkWidget* bg_box = gtk_event_box_new();
gtk_container_add(GTK_CONTAINER(padding), hbox_);
gtk_container_add(GTK_CONTAINER(bg_box), padding);
// Set the top border and background color.
gtk_widget_modify_bg(bg_box, GTK_STATE_NORMAL, &kBackgroundColor);
widget_.Own(gfx::CreateGtkBorderBin(bg_box, &kBorderColor,
1, 0, 0, 0));
gtk_widget_set_size_request(widget_.get(), -1, kInfoBarHeight);
close_button_.reset(CustomDrawButton::AddBarCloseButton(hbox_));
g_signal_connect(close_button_->widget(), "clicked",
G_CALLBACK(OnCloseButton), this);
g_object_set_data(G_OBJECT(widget_.get()), "info-bar", this);
}
InfoBar::~InfoBar() {
widget_.Destroy();
}
void InfoBar::AnimateOpen() {
// TODO(port): add animations. In the meantime just Open().
NOTIMPLEMENTED();
Open();
}
void InfoBar::Open() {
gtk_widget_show_all(widget_.get());
}
void InfoBar::AnimateClose() {
// TODO(port): add animations. In the meantime just Close().
NOTIMPLEMENTED();
Close();
}
void InfoBar::Close() {
gtk_widget_hide(widget_.get());
}
void InfoBar::RemoveInfoBar() const {
container_->RemoveDelegate(delegate_);
}
// static
void InfoBar::OnCloseButton(GtkWidget* button, InfoBar* info_bar) {
info_bar->AnimateClose();
}
// AlertInfoBar ----------------------------------------------------------------
class AlertInfoBar : public InfoBar {
public:
AlertInfoBar(AlertInfoBarDelegate* delegate)
: InfoBar(delegate) {
std::wstring text = delegate->GetMessageText();
GtkWidget* label = gtk_label_new(WideToUTF8(text).c_str());
SkBitmap* icon = delegate->GetIcon();
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(icon);
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
gdk_pixbuf_unref(pixbuf);
gtk_box_pack_start(GTK_BOX(hbox_), image, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 0);
}
};
// LinkInfoBar -----------------------------------------------------------------
class LinkInfoBar : public InfoBar {
public:
LinkInfoBar(LinkInfoBarDelegate* delegate)
: InfoBar(delegate) {
// TODO(estade): remove these lines.
NOTIMPLEMENTED();
GtkWidget* label = gtk_label_new("LinkInfoBar not yet implemented. "
"Check back later.");
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 10);
}
};
// ConfirmInfoBar --------------------------------------------------------------
class ConfirmInfoBar : public AlertInfoBar {
public:
ConfirmInfoBar(ConfirmInfoBarDelegate* delegate)
: AlertInfoBar(delegate) {
AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_CANCEL);
AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_OK);
}
private:
// Adds a button to the info bar by type. It will do nothing if the delegate
// doesn't specify a button of the given type.
void AddConfirmButton(ConfirmInfoBarDelegate::InfoBarButton type) {
if (delegate_->AsConfirmInfoBarDelegate()->GetButtons() & type) {
GtkWidget* button = gtk_button_new_with_label(WideToUTF8(
delegate_->AsConfirmInfoBarDelegate()->GetButtonLabel(type)).c_str());
GtkWidget* centering_vbox = gtk_vbox_new(FALSE, 0);
gtk_box_pack_end(GTK_BOX(centering_vbox), button, TRUE, FALSE, 0);
gtk_box_pack_end(GTK_BOX(hbox_), centering_vbox, FALSE, FALSE, 0);
g_signal_connect(button, "clicked",
G_CALLBACK(type == ConfirmInfoBarDelegate::BUTTON_OK ?
OnOkButton : OnCancelButton),
this);
}
}
static void OnCancelButton(GtkWidget* button, ConfirmInfoBar* info_bar) {
if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Cancel())
info_bar->RemoveInfoBar();
}
static void OnOkButton(GtkWidget* button, ConfirmInfoBar* info_bar) {
if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Accept())
info_bar->RemoveInfoBar();
}
};
// AlertInfoBarDelegate, InfoBarDelegate overrides: ----------------------------
InfoBar* AlertInfoBarDelegate::CreateInfoBar() {
return new AlertInfoBar(this);
}
// LinkInfoBarDelegate, InfoBarDelegate overrides: -----------------------------
InfoBar* LinkInfoBarDelegate::CreateInfoBar() {
return new LinkInfoBar(this);
}
// ConfirmInfoBarDelegate, InfoBarDelegate overrides: --------------------------
InfoBar* ConfirmInfoBarDelegate::CreateInfoBar() {
return new ConfirmInfoBar(this);
}
<|endoftext|> |
<commit_before>// Copyright 2014 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 "mojo/services/html_viewer/webmimeregistry_impl.h"
#include "base/files/file_path.h"
#include "base/strings/string_util.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "media/base/key_systems.h"
#include "media/filters/stream_parser_factory.h"
#include "net/base/mime_util.h"
#include "third_party/WebKit/public/platform/WebString.h"
namespace html_viewer {
namespace {
std::string ToASCIIOrEmpty(const blink::WebString& string) {
return base::IsStringASCII(string) ? base::UTF16ToASCII(string)
: std::string();
}
} // namespace
blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsMIMEType(
const blink::WebString& mime_type) {
return net::IsSupportedMimeType(ToASCIIOrEmpty(mime_type)) ?
blink::WebMimeRegistry::IsSupported :
blink::WebMimeRegistry::IsNotSupported;
}
blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsImageMIMEType(
const blink::WebString& mime_type) {
return net::IsSupportedImageMimeType(ToASCIIOrEmpty(mime_type)) ?
blink::WebMimeRegistry::IsSupported :
blink::WebMimeRegistry::IsNotSupported;
}
blink::WebMimeRegistry::SupportsType
WebMimeRegistryImpl::supportsImagePrefixedMIMEType(
const blink::WebString& mime_type) {
std::string ascii_mime_type = ToASCIIOrEmpty(mime_type);
return (net::IsSupportedImageMimeType(ascii_mime_type) ||
(StartsWithASCII(ascii_mime_type, "image/", true) &&
net::IsSupportedNonImageMimeType(ascii_mime_type)))
? WebMimeRegistry::IsSupported
: WebMimeRegistry::IsNotSupported;
}
blink::WebMimeRegistry::SupportsType
WebMimeRegistryImpl::supportsJavaScriptMIMEType(
const blink::WebString& mime_type) {
return net::IsSupportedJavascriptMimeType(ToASCIIOrEmpty(mime_type)) ?
blink::WebMimeRegistry::IsSupported :
blink::WebMimeRegistry::IsNotSupported;
}
blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsMediaMIMEType(
const blink::WebString& mime_type,
const blink::WebString& codecs,
const blink::WebString& key_system) {
const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
// Not supporting the container is a flat-out no.
if (!net::IsSupportedMediaMimeType(mime_type_ascii))
return IsNotSupported;
// Mojo does not currently support any key systems.
if (!key_system.isEmpty())
return IsNotSupported;
// Check list of strict codecs to see if it is supported.
if (net::IsStrictMediaMimeType(mime_type_ascii)) {
// Check if the codecs are a perfect match.
std::vector<std::string> strict_codecs;
net::ParseCodecString(ToASCIIOrEmpty(codecs), &strict_codecs, false);
return static_cast<WebMimeRegistry::SupportsType>(
net::IsSupportedStrictMediaMimeType(mime_type_ascii, strict_codecs));
}
// If we don't recognize the codec, it's possible we support it.
std::vector<std::string> parsed_codecs;
net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codecs, true);
if (!net::AreSupportedMediaCodecs(parsed_codecs))
return MayBeSupported;
// Otherwise we have a perfect match.
return IsSupported;
}
bool WebMimeRegistryImpl::supportsMediaSourceMIMEType(
const blink::WebString& mime_type,
const blink::WebString& codecs) {
const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
if (mime_type_ascii.empty())
return false;
std::vector<std::string> parsed_codec_ids;
net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codec_ids, false);
return media::StreamParserFactory::IsTypeSupported(mime_type_ascii,
parsed_codec_ids);
}
blink::WebMimeRegistry::SupportsType
WebMimeRegistryImpl::supportsNonImageMIMEType(
const blink::WebString& mime_type) {
return net::IsSupportedNonImageMimeType(ToASCIIOrEmpty(mime_type)) ?
blink::WebMimeRegistry::IsSupported :
blink::WebMimeRegistry::IsNotSupported;
}
blink::WebString WebMimeRegistryImpl::mimeTypeForExtension(
const blink::WebString& file_extension) {
NOTIMPLEMENTED();
return blink::WebString();
}
blink::WebString WebMimeRegistryImpl::wellKnownMimeTypeForExtension(
const blink::WebString& file_extension) {
NOTIMPLEMENTED();
return blink::WebString();
}
blink::WebString WebMimeRegistryImpl::mimeTypeFromFile(
const blink::WebString& file_path) {
NOTIMPLEMENTED();
return blink::WebString();
}
} // namespace html_viewer
<commit_msg>html_viewer: Implement various mime utilities.<commit_after>// Copyright 2014 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 "mojo/services/html_viewer/webmimeregistry_impl.h"
#include "base/files/file_path.h"
#include "base/strings/string_util.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "media/base/key_systems.h"
#include "media/filters/stream_parser_factory.h"
#include "net/base/mime_util.h"
#include "third_party/WebKit/public/platform/WebString.h"
namespace html_viewer {
namespace {
std::string ToASCIIOrEmpty(const blink::WebString& string) {
return base::IsStringASCII(string) ? base::UTF16ToASCII(string)
: std::string();
}
} // namespace
blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsMIMEType(
const blink::WebString& mime_type) {
return net::IsSupportedMimeType(ToASCIIOrEmpty(mime_type)) ?
blink::WebMimeRegistry::IsSupported :
blink::WebMimeRegistry::IsNotSupported;
}
blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsImageMIMEType(
const blink::WebString& mime_type) {
return net::IsSupportedImageMimeType(ToASCIIOrEmpty(mime_type)) ?
blink::WebMimeRegistry::IsSupported :
blink::WebMimeRegistry::IsNotSupported;
}
blink::WebMimeRegistry::SupportsType
WebMimeRegistryImpl::supportsImagePrefixedMIMEType(
const blink::WebString& mime_type) {
std::string ascii_mime_type = ToASCIIOrEmpty(mime_type);
return (net::IsSupportedImageMimeType(ascii_mime_type) ||
(StartsWithASCII(ascii_mime_type, "image/", true) &&
net::IsSupportedNonImageMimeType(ascii_mime_type)))
? WebMimeRegistry::IsSupported
: WebMimeRegistry::IsNotSupported;
}
blink::WebMimeRegistry::SupportsType
WebMimeRegistryImpl::supportsJavaScriptMIMEType(
const blink::WebString& mime_type) {
return net::IsSupportedJavascriptMimeType(ToASCIIOrEmpty(mime_type)) ?
blink::WebMimeRegistry::IsSupported :
blink::WebMimeRegistry::IsNotSupported;
}
blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsMediaMIMEType(
const blink::WebString& mime_type,
const blink::WebString& codecs,
const blink::WebString& key_system) {
const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
// Not supporting the container is a flat-out no.
if (!net::IsSupportedMediaMimeType(mime_type_ascii))
return IsNotSupported;
// Mojo does not currently support any key systems.
if (!key_system.isEmpty())
return IsNotSupported;
// Check list of strict codecs to see if it is supported.
if (net::IsStrictMediaMimeType(mime_type_ascii)) {
// Check if the codecs are a perfect match.
std::vector<std::string> strict_codecs;
net::ParseCodecString(ToASCIIOrEmpty(codecs), &strict_codecs, false);
return static_cast<WebMimeRegistry::SupportsType>(
net::IsSupportedStrictMediaMimeType(mime_type_ascii, strict_codecs));
}
// If we don't recognize the codec, it's possible we support it.
std::vector<std::string> parsed_codecs;
net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codecs, true);
if (!net::AreSupportedMediaCodecs(parsed_codecs))
return MayBeSupported;
// Otherwise we have a perfect match.
return IsSupported;
}
bool WebMimeRegistryImpl::supportsMediaSourceMIMEType(
const blink::WebString& mime_type,
const blink::WebString& codecs) {
const std::string mime_type_ascii = ToASCIIOrEmpty(mime_type);
if (mime_type_ascii.empty())
return false;
std::vector<std::string> parsed_codec_ids;
net::ParseCodecString(ToASCIIOrEmpty(codecs), &parsed_codec_ids, false);
return media::StreamParserFactory::IsTypeSupported(mime_type_ascii,
parsed_codec_ids);
}
blink::WebMimeRegistry::SupportsType
WebMimeRegistryImpl::supportsNonImageMIMEType(
const blink::WebString& mime_type) {
return net::IsSupportedNonImageMimeType(ToASCIIOrEmpty(mime_type)) ?
blink::WebMimeRegistry::IsSupported :
blink::WebMimeRegistry::IsNotSupported;
}
blink::WebString WebMimeRegistryImpl::mimeTypeForExtension(
const blink::WebString& file_extension) {
std::string mime_type;
net::GetMimeTypeFromExtension(
base::FilePath::FromUTF16Unsafe(file_extension).value(), &mime_type);
return blink::WebString::fromUTF8(mime_type);
}
blink::WebString WebMimeRegistryImpl::wellKnownMimeTypeForExtension(
const blink::WebString& file_extension) {
std::string mime_type;
net::GetWellKnownMimeTypeFromExtension(
base::FilePath::FromUTF16Unsafe(file_extension).value(), &mime_type);
return blink::WebString::fromUTF8(mime_type);
}
blink::WebString WebMimeRegistryImpl::mimeTypeFromFile(
const blink::WebString& file_path) {
std::string mime_type;
net::GetMimeTypeFromFile(base::FilePath::FromUTF16Unsafe(file_path),
&mime_type);
return blink::WebString::fromUTF8(mime_type);
}
} // namespace html_viewer
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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/browser_accessibility_manager_win.h"
#include "chrome/browser/browser_accessibility_win.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/common/render_messages.h"
using webkit_glue::WebAccessibility;
// Factory method to create an instance of BrowserAccessibility
BrowserAccessibility* BrowserAccessibilityFactory::Create() {
CComObject<BrowserAccessibility>* instance;
HRESULT hr = CComObject<BrowserAccessibility>::CreateInstance(&instance);
DCHECK(SUCCEEDED(hr));
return instance->NewReference();
}
// static
// Start child IDs at -1 and decrement each time, because clients use
// child IDs of 1, 2, 3, ... to access the children of an object by
// index, so we use negative IDs to clearly distinguish between indices
// and unique IDs.
LONG BrowserAccessibilityManager::next_child_id_ = -1;
BrowserAccessibilityManager::BrowserAccessibilityManager(
HWND parent_hwnd,
const webkit_glue::WebAccessibility& src,
BrowserAccessibilityDelegate* delegate,
BrowserAccessibilityFactory* factory)
: parent_hwnd_(parent_hwnd),
delegate_(delegate),
factory_(factory),
focus_(NULL) {
HRESULT hr = ::CreateStdAccessibleObject(
parent_hwnd_, OBJID_WINDOW, IID_IAccessible,
reinterpret_cast<void **>(&window_iaccessible_));
DCHECK(SUCCEEDED(hr));
root_ = CreateAccessibilityTree(NULL, GetNextChildID(), src, 0);
if (!focus_)
focus_ = root_;
}
BrowserAccessibilityManager::~BrowserAccessibilityManager() {
// Clients could still hold references to some nodes of the tree, so
// calling Inactivate will make sure that as many nodes as possible are
// released now, and remaining nodes are marked as inactive so that
// calls to any methods on them will return E_FAIL;
root_->InactivateTree();
root_->Release();
}
BrowserAccessibility* BrowserAccessibilityManager::GetRoot() {
return root_;
}
void BrowserAccessibilityManager::Remove(LONG child_id) {
child_id_map_.erase(child_id);
}
BrowserAccessibility* BrowserAccessibilityManager::GetFromChildID(
LONG child_id) {
base::hash_map<LONG, BrowserAccessibility*>::iterator iter =
child_id_map_.find(child_id);
if (iter != child_id_map_.end()) {
return iter->second;
} else {
return NULL;
}
}
IAccessible* BrowserAccessibilityManager::GetParentWindowIAccessible() {
return window_iaccessible_;
}
HWND BrowserAccessibilityManager::GetParentHWND() {
return parent_hwnd_;
}
BrowserAccessibility* BrowserAccessibilityManager::GetFocus(
BrowserAccessibility* root) {
if (focus_ && (!root || focus_->IsDescendantOf(root)))
return focus_;
return NULL;
}
void BrowserAccessibilityManager::SetFocus(const BrowserAccessibility& node) {
if (delegate_)
delegate_->SetAccessibilityFocus(node.renderer_id());
}
void BrowserAccessibilityManager::DoDefaultAction(
const BrowserAccessibility& node) {
if (delegate_)
delegate_->AccessibilityDoDefaultAction(node.renderer_id());
}
void BrowserAccessibilityManager::OnAccessibilityFocusChange(int renderer_id) {
base::hash_map<int, LONG>::iterator iter =
renderer_id_to_child_id_map_.find(renderer_id);
if (iter == renderer_id_to_child_id_map_.end())
return;
LONG child_id = iter->second;
base::hash_map<LONG, BrowserAccessibility*>::iterator uniq_iter =
child_id_map_.find(child_id);
if (uniq_iter != child_id_map_.end())
focus_ = uniq_iter->second;
::NotifyWinEvent(EVENT_OBJECT_FOCUS, parent_hwnd_, OBJID_CLIENT, child_id);
}
void BrowserAccessibilityManager::OnAccessibilityObjectStateChange(
const webkit_glue::WebAccessibility& acc_obj) {
BrowserAccessibility* new_browser_acc = UpdateTree(acc_obj);
if (!new_browser_acc)
return;
NotifyWinEvent(
EVENT_OBJECT_STATECHANGE,
parent_hwnd_,
OBJID_CLIENT,
new_browser_acc->child_id());
}
void BrowserAccessibilityManager::OnAccessibilityObjectChildrenChange(
const std::vector<webkit_glue::WebAccessibility>& acc_changes) {
if (delegate_)
delegate_->AccessibilityObjectChildrenChangeAck();
// For each accessibility object child change.
for (unsigned int index = 0; index < acc_changes.size(); index++) {
const webkit_glue::WebAccessibility& acc_obj = acc_changes[index];
BrowserAccessibility* new_browser_acc = UpdateTree(acc_obj);
if (!new_browser_acc)
continue;
LONG child_id;
if (root_ != new_browser_acc) {
child_id = new_browser_acc->GetParent()->child_id();
} else {
child_id = CHILDID_SELF;
}
NotifyWinEvent(EVENT_OBJECT_REORDER, parent_hwnd_, OBJID_CLIENT, child_id);
}
}
BrowserAccessibility* BrowserAccessibilityManager::UpdateTree(
const webkit_glue::WebAccessibility& acc_obj) {
base::hash_map<int, LONG>::iterator iter =
renderer_id_to_child_id_map_.find(acc_obj.id);
if (iter == renderer_id_to_child_id_map_.end())
return NULL;
LONG child_id = iter->second;
BrowserAccessibility* old_browser_acc = GetFromChildID(child_id);
if (old_browser_acc->GetChildCount() == 0 && acc_obj.children.size() == 0) {
// Reinitialize the BrowserAccessibility if there are no children to update.
old_browser_acc->Initialize(
this,
old_browser_acc->GetParent(),
child_id,
old_browser_acc->index_in_parent(),
acc_obj);
return old_browser_acc;
} else {
BrowserAccessibility* new_browser_acc = CreateAccessibilityTree(
old_browser_acc->GetParent(),
child_id,
acc_obj,
old_browser_acc->index_in_parent());
if (old_browser_acc->GetParent()) {
old_browser_acc->GetParent()->ReplaceChild(
old_browser_acc,
new_browser_acc);
} else {
DCHECK_EQ(old_browser_acc, root_);
root_ = new_browser_acc;
}
old_browser_acc->InactivateTree();
old_browser_acc->Release();
child_id_map_[child_id] = new_browser_acc;
return new_browser_acc;
}
}
LONG BrowserAccessibilityManager::GetNextChildID() {
// Get the next child ID, and wrap around when we get near the end
// of a 32-bit integer range. It's okay to wrap around; we just want
// to avoid it as long as possible because clients may cache the ID of
// an object for a while to determine if they've seen it before.
next_child_id_--;
if (next_child_id_ == -2000000000)
next_child_id_ = -1;
return next_child_id_;
}
BrowserAccessibility* BrowserAccessibilityManager::CreateAccessibilityTree(
BrowserAccessibility* parent,
int child_id,
const webkit_glue::WebAccessibility& src,
int index_in_parent) {
BrowserAccessibility* instance = factory_->Create();
instance->Initialize(this, parent, child_id, index_in_parent, src);
child_id_map_[child_id] = instance;
renderer_id_to_child_id_map_[src.id] = child_id;
if ((src.state >> WebAccessibility::STATE_FOCUSED) & 1)
focus_ = instance;
for (int i = 0; i < static_cast<int>(src.children.size()); ++i) {
BrowserAccessibility* child = CreateAccessibilityTree(
instance, GetNextChildID(), src.children[i], i);
instance->AddChild(child);
}
return instance;
}
<commit_msg>Fix a chrome browser crash which occurs when launched as part of chrome frame while processing the ViewHostMsg_AccessibilityObjectChildrenChange message. The crash occurs because we fail to find the BrowserAccessibility interface for the child id passed in. <commit_after>// Copyright (c) 2010 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/browser_accessibility_manager_win.h"
#include "chrome/browser/browser_accessibility_win.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/common/render_messages.h"
using webkit_glue::WebAccessibility;
// Factory method to create an instance of BrowserAccessibility
BrowserAccessibility* BrowserAccessibilityFactory::Create() {
CComObject<BrowserAccessibility>* instance;
HRESULT hr = CComObject<BrowserAccessibility>::CreateInstance(&instance);
DCHECK(SUCCEEDED(hr));
return instance->NewReference();
}
// static
// Start child IDs at -1 and decrement each time, because clients use
// child IDs of 1, 2, 3, ... to access the children of an object by
// index, so we use negative IDs to clearly distinguish between indices
// and unique IDs.
LONG BrowserAccessibilityManager::next_child_id_ = -1;
BrowserAccessibilityManager::BrowserAccessibilityManager(
HWND parent_hwnd,
const webkit_glue::WebAccessibility& src,
BrowserAccessibilityDelegate* delegate,
BrowserAccessibilityFactory* factory)
: parent_hwnd_(parent_hwnd),
delegate_(delegate),
factory_(factory),
focus_(NULL) {
HRESULT hr = ::CreateStdAccessibleObject(
parent_hwnd_, OBJID_WINDOW, IID_IAccessible,
reinterpret_cast<void **>(&window_iaccessible_));
DCHECK(SUCCEEDED(hr));
root_ = CreateAccessibilityTree(NULL, GetNextChildID(), src, 0);
if (!focus_)
focus_ = root_;
}
BrowserAccessibilityManager::~BrowserAccessibilityManager() {
// Clients could still hold references to some nodes of the tree, so
// calling Inactivate will make sure that as many nodes as possible are
// released now, and remaining nodes are marked as inactive so that
// calls to any methods on them will return E_FAIL;
root_->InactivateTree();
root_->Release();
}
BrowserAccessibility* BrowserAccessibilityManager::GetRoot() {
return root_;
}
void BrowserAccessibilityManager::Remove(LONG child_id) {
child_id_map_.erase(child_id);
}
BrowserAccessibility* BrowserAccessibilityManager::GetFromChildID(
LONG child_id) {
base::hash_map<LONG, BrowserAccessibility*>::iterator iter =
child_id_map_.find(child_id);
if (iter != child_id_map_.end()) {
return iter->second;
} else {
return NULL;
}
}
IAccessible* BrowserAccessibilityManager::GetParentWindowIAccessible() {
return window_iaccessible_;
}
HWND BrowserAccessibilityManager::GetParentHWND() {
return parent_hwnd_;
}
BrowserAccessibility* BrowserAccessibilityManager::GetFocus(
BrowserAccessibility* root) {
if (focus_ && (!root || focus_->IsDescendantOf(root)))
return focus_;
return NULL;
}
void BrowserAccessibilityManager::SetFocus(const BrowserAccessibility& node) {
if (delegate_)
delegate_->SetAccessibilityFocus(node.renderer_id());
}
void BrowserAccessibilityManager::DoDefaultAction(
const BrowserAccessibility& node) {
if (delegate_)
delegate_->AccessibilityDoDefaultAction(node.renderer_id());
}
void BrowserAccessibilityManager::OnAccessibilityFocusChange(int renderer_id) {
base::hash_map<int, LONG>::iterator iter =
renderer_id_to_child_id_map_.find(renderer_id);
if (iter == renderer_id_to_child_id_map_.end())
return;
LONG child_id = iter->second;
base::hash_map<LONG, BrowserAccessibility*>::iterator uniq_iter =
child_id_map_.find(child_id);
if (uniq_iter != child_id_map_.end())
focus_ = uniq_iter->second;
::NotifyWinEvent(EVENT_OBJECT_FOCUS, parent_hwnd_, OBJID_CLIENT, child_id);
}
void BrowserAccessibilityManager::OnAccessibilityObjectStateChange(
const webkit_glue::WebAccessibility& acc_obj) {
BrowserAccessibility* new_browser_acc = UpdateTree(acc_obj);
if (!new_browser_acc)
return;
NotifyWinEvent(
EVENT_OBJECT_STATECHANGE,
parent_hwnd_,
OBJID_CLIENT,
new_browser_acc->child_id());
}
void BrowserAccessibilityManager::OnAccessibilityObjectChildrenChange(
const std::vector<webkit_glue::WebAccessibility>& acc_changes) {
if (delegate_)
delegate_->AccessibilityObjectChildrenChangeAck();
// For each accessibility object child change.
for (unsigned int index = 0; index < acc_changes.size(); index++) {
const webkit_glue::WebAccessibility& acc_obj = acc_changes[index];
BrowserAccessibility* new_browser_acc = UpdateTree(acc_obj);
if (!new_browser_acc)
continue;
LONG child_id;
if (root_ != new_browser_acc) {
child_id = new_browser_acc->GetParent()->child_id();
} else {
child_id = CHILDID_SELF;
}
NotifyWinEvent(EVENT_OBJECT_REORDER, parent_hwnd_, OBJID_CLIENT, child_id);
}
}
BrowserAccessibility* BrowserAccessibilityManager::UpdateTree(
const webkit_glue::WebAccessibility& acc_obj) {
base::hash_map<int, LONG>::iterator iter =
renderer_id_to_child_id_map_.find(acc_obj.id);
if (iter == renderer_id_to_child_id_map_.end())
return NULL;
LONG child_id = iter->second;
BrowserAccessibility* old_browser_acc = GetFromChildID(child_id);
if (!old_browser_acc)
return NULL;
if (old_browser_acc->GetChildCount() == 0 && acc_obj.children.size() == 0) {
// Reinitialize the BrowserAccessibility if there are no children to update.
old_browser_acc->Initialize(
this,
old_browser_acc->GetParent(),
child_id,
old_browser_acc->index_in_parent(),
acc_obj);
return old_browser_acc;
} else {
BrowserAccessibility* new_browser_acc = CreateAccessibilityTree(
old_browser_acc->GetParent(),
child_id,
acc_obj,
old_browser_acc->index_in_parent());
if (old_browser_acc->GetParent()) {
old_browser_acc->GetParent()->ReplaceChild(
old_browser_acc,
new_browser_acc);
} else {
DCHECK_EQ(old_browser_acc, root_);
root_ = new_browser_acc;
}
old_browser_acc->InactivateTree();
old_browser_acc->Release();
child_id_map_[child_id] = new_browser_acc;
return new_browser_acc;
}
}
LONG BrowserAccessibilityManager::GetNextChildID() {
// Get the next child ID, and wrap around when we get near the end
// of a 32-bit integer range. It's okay to wrap around; we just want
// to avoid it as long as possible because clients may cache the ID of
// an object for a while to determine if they've seen it before.
next_child_id_--;
if (next_child_id_ == -2000000000)
next_child_id_ = -1;
return next_child_id_;
}
BrowserAccessibility* BrowserAccessibilityManager::CreateAccessibilityTree(
BrowserAccessibility* parent,
int child_id,
const webkit_glue::WebAccessibility& src,
int index_in_parent) {
BrowserAccessibility* instance = factory_->Create();
instance->Initialize(this, parent, child_id, index_in_parent, src);
child_id_map_[child_id] = instance;
renderer_id_to_child_id_map_[src.id] = child_id;
if ((src.state >> WebAccessibility::STATE_FOCUSED) & 1)
focus_ = instance;
for (int i = 0; i < static_cast<int>(src.children.size()); ++i) {
BrowserAccessibility* child = CreateAccessibilityTree(
instance, GetNextChildID(), src.children[i], i);
instance->AddChild(child);
}
return instance;
}
<|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 "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
TabContents* tab = browser()->GetTabContentsAt(0);
inspected_rvh_ = tab->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests set breakpoint.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalCallFrame) {
RunTest("testEvalCallFrame", kEvalTestPage);
}
} // namespace
<commit_msg>DevTools: temporary disable TestConsoleLog and TestEvalGlobal that would fail with next WebKit roll. Review URL: http://codereview.chromium.org/208009<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 "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
TabContents* tab = browser()->GetTabContentsAt(0);
inspected_rvh_ = tab->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests set breakpoint.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalCallFrame) {
RunTest("testEvalCallFrame", kEvalTestPage);
}
} // namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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/extension_apitest.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#if defined(OS_MACOSX)
// Tabs appears to timeout, or maybe crash on mac.
// http://crbug.com/53779
#define MAYBE_Tabs FAILS_Tabs
#else
// It's flaky on win and linux.
// http://crbug.com/58269
#define MAYBE_Tabs FLAKY_Tabs
#endif
// TabOnRemoved is flaky on chromeos and linux views debug build.
// http://crbug.com/49258
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG)
#define MAYBE_TabOnRemoved FLAKY_TabOnRemoved
#else
#define MAYBE_TabOnRemoved TabOnRemoved
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
ASSERT_TRUE(test_server()->Start());
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_jpeg.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_png.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}
<commit_msg>Remove FLAKY prefix from TabOnRemoved test.<commit_after>// Copyright (c) 2010 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/extension_apitest.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#if defined(OS_MACOSX)
// Tabs appears to timeout, or maybe crash on mac.
// http://crbug.com/53779
#define MAYBE_Tabs FAILS_Tabs
#else
// It's flaky on win and linux.
// http://crbug.com/58269
#define MAYBE_Tabs FLAKY_Tabs
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
ASSERT_TRUE(test_server()->Start());
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabOnRemoved) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_jpeg.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_png.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}
<|endoftext|> |
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file linear_observation_model.hpp
* \date October 2014
* \author Jan Issac ([email protected])
*/
#ifndef FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP
#define FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP
#include <fl/util/traits.hpp>
#include <fl/util/descriptor.hpp>
#include <fl/distribution/gaussian.hpp>
#include <fl/distribution/decorrelated_gaussian.hpp>
#include <fl/model/adaptive_model.hpp>
#include <fl/model/observation/interface/observation_density.hpp>
#include <fl/model/observation/interface/observation_model_interface.hpp>
#include <fl/model/observation/interface/additive_observation_function.hpp>
#include <fl/model/observation/interface/additive_uncorrelated_observation_function.hpp>
namespace fl
{
/**
* \ingroup observation_models
*/
template <typename Obsrv_, typename State_, typename Density>
class LinearObservationModel
: public ObservationDensity<Obsrv_, State_>, // p(y|x)
public AdditiveObservationFunction<Obsrv_, State_, Obsrv_> // H*x + N*v
{
public:
typedef State_ State;
typedef Obsrv_ Obsrv;
typedef ObservationDensity<Obsrv, State> DensityInterface;
typedef AdditiveObservationFunction<Obsrv, State, Obsrv> AdditiveInterface;
typedef typename AdditiveInterface::FunctionInterface FunctionInterface;
/**
* Linear model density. The density for linear model is the Gaussian over
* observation space.
*/
//typedef Gaussian<Obsrv> Density;
/**
* Observation model sensor matrix \f$H_t\f$ use in
*
* \f$ y_t = H_t x_t + N_t v_t \f$
*/
typedef Eigen::Matrix<
typename State::Scalar,
SizeOf<Obsrv>::Value,
SizeOf<State>::Value
> SensorMatrix;
/**
* Observation model noise matrix \f$N_t\f$ use in
*
* \f$ y_t = H_t x_t + N_t v_t\f$
*
* In this linear model, the noise model matrix is equivalent to the
* square root of the covariance of the model density. Hence, the
* NoiseMatrix type is the same type as the second moment of the density.
*
* This is equivalent to
* > typedef typename Gaussian<Obsrv>::SecondMoment NoiseMatrix;
*/
typedef typename AdditiveInterface::NoiseMatrix NoiseMatrix;
public:
/**
* Constructs a linear gaussian observation model
* \param obsrv_dim observation dimension if dynamic size
* \param state_dim state dimension if dynamic size
*/
explicit
LinearObservationModel(int obsrv_dim = DimensionOf<Obsrv>(),
int state_dim = DimensionOf<State>())
: sensor_matrix_(SensorMatrix::Identity(obsrv_dim, state_dim)),
density_(obsrv_dim)
{
assert(obsrv_dim > 0);
assert(state_dim > 0);
}
/**
* \brief Overridable default destructor
*/
virtual ~LinearObservationModel() { }
/**
* \brief expected_observation
* \param state
* \return
*/
Obsrv expected_observation(const State& state) const override
{
return sensor_matrix_ * state;
}
Real log_probability(const Obsrv& obsrv, const State& state) const
{
density_.mean(expected_observation(state));
return density_.log_probability(obsrv);
}
const SensorMatrix& sensor_matrix() const override
{
return sensor_matrix_;
}
const NoiseMatrix& noise_matrix() const override
{
return density_.square_root();
}
const NoiseMatrix& noise_covariance() const override
{
return density_.covariance();
}
int obsrv_dimension() const override
{
return sensor_matrix_.rows();
}
int noise_dimension() const override
{
return density_.square_root().cols();
}
int state_dimension() const override
{
return sensor_matrix_.cols();
}
virtual void sensor_matrix(const SensorMatrix& sensor_mat)
{
sensor_matrix_ = sensor_mat;
}
virtual void noise_matrix(const NoiseMatrix& noise_mat)
{
density_.square_root(noise_mat);
}
virtual void noise_covariance(const NoiseMatrix& noise_mat_squared)
{
density_.covariance(noise_mat_squared);
}
virtual SensorMatrix create_sensor_matrix() const
{
auto H = sensor_matrix();
H.setIdentity();
return H;
}
virtual NoiseMatrix create_noise_matrix() const
{
auto N = noise_matrix();
N.setIdentity();
return N;
}
protected:
SensorMatrix sensor_matrix_;
mutable Density density_;
};
}
#endif
<commit_msg>Density > NoiseDensity<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file linear_observation_model.hpp
* \date October 2014
* \author Jan Issac ([email protected])
*/
#ifndef FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP
#define FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP
#include <fl/util/traits.hpp>
#include <fl/util/types.hpp>
#include <fl/util/descriptor.hpp>
#include <fl/distribution/gaussian.hpp>
#include <fl/distribution/decorrelated_gaussian.hpp>
#include <fl/model/adaptive_model.hpp>
#include <fl/model/observation/interface/observation_density.hpp>
#include <fl/model/observation/interface/observation_function.hpp>
#include <fl/model/observation/interface/additive_observation_function.hpp>
#include <fl/model/observation/interface/additive_uncorrelated_observation_function.hpp>
namespace fl
{
/**
* \ingroup observation_models
*/
template <typename Obsrv, typename State, typename NoiseDensity>
class LinearObservationModel
: public ObservationDensity<Obsrv, State>,
public AdditiveObservationFunction<Obsrv, State, NoiseDensity>,
private internal::LinearModelType
{
public:
typedef ObservationDensity<Obsrv, State> DensityInterface;
typedef AdditiveObservationFunction<Obsrv, State, NoiseDensity> AdditiveInterface;
typedef typename AdditiveInterface::FunctionInterface FunctionInterface;
/**
* Linear model density. The density for linear model is the Gaussian over
* observation space.
*/
//typedef Gaussian<Obsrv> Density;
/**
* Observation model sensor matrix \f$H_t\f$ use in
*
* \f$ y_t = H_t x_t + N_t v_t \f$
*/
typedef Eigen::Matrix<
typename State::Scalar,
SizeOf<Obsrv>::Value,
SizeOf<State>::Value
> SensorMatrix;
/**
* Observation model noise matrix \f$N_t\f$ use in
*
* \f$ y_t = H_t x_t + N_t v_t\f$
*
* In this linear model, the noise model matrix is equivalent to the
* square root of the covariance of the model density. Hence, the
* NoiseMatrix type is the same type as the second moment of the density.
*
* This is equivalent to
* > typedef typename Gaussian<Obsrv>::SecondMoment NoiseMatrix;
*/
typedef typename AdditiveInterface::NoiseMatrix NoiseMatrix;
public:
/**
* Constructs a linear gaussian observation model
* \param obsrv_dim observation dimension if dynamic size
* \param state_dim state dimension if dynamic size
*/
explicit
LinearObservationModel(int obsrv_dim = DimensionOf<Obsrv>(),
int state_dim = DimensionOf<State>())
: sensor_matrix_(SensorMatrix::Identity(obsrv_dim, state_dim)),
density_(obsrv_dim)
{
assert(obsrv_dim > 0);
assert(state_dim > 0);
}
/**
* \brief Overridable default destructor
*/
virtual ~LinearObservationModel() { }
/**
* \brief expected_observation
* \param state
* \return
*/
Obsrv expected_observation(const State& state) const override
{
return sensor_matrix_ * state;
}
Real log_probability(const Obsrv& obsrv, const State& state) const
{
density_.mean(expected_observation(state));
return density_.log_probability(obsrv);
}
const SensorMatrix& sensor_matrix() const override
{
return sensor_matrix_;
}
NoiseMatrix noise_matrix() const override
{
return density_.square_root();
}
NoiseMatrix noise_covariance() const override
{
return density_.covariance();
}
int obsrv_dimension() const override
{
return sensor_matrix_.rows();
}
int noise_dimension() const override
{
return density_.square_root().cols();
}
int state_dimension() const override
{
return sensor_matrix_.cols();
}
virtual void sensor_matrix(const SensorMatrix& sensor_mat)
{
sensor_matrix_ = sensor_mat;
}
virtual void noise_matrix(const NoiseMatrix& noise_mat)
{
density_.square_root(noise_mat);
}
virtual void noise_covariance(const NoiseMatrix& noise_mat_squared)
{
density_.covariance(noise_mat_squared);
}
virtual SensorMatrix create_sensor_matrix() const
{
auto H = sensor_matrix();
H.setIdentity();
return H;
}
virtual NoiseMatrix create_noise_matrix() const
{
auto N = noise_matrix();
N.setIdentity();
return N;
}
protected:
SensorMatrix sensor_matrix_;
mutable NoiseDensity density_;
};
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: helpinterceptor.hxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: kz $ $Date: 2004-06-10 13:28:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef INCLUDED_SFX_HELPINTERCEPTOR_HXX
#define INCLUDED_SFX_HELPINTERCEPTOR_HXX
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTOR_HPP_
#include <com/sun/star/frame/XDispatchProviderInterceptor.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XINTERCEPTORINFO_HPP_
#include <com/sun/star/frame/XInterceptorInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTION_HPP_
#include <com/sun/star/frame/XDispatchProviderInterception.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
struct HelpHistoryEntry_Impl
{
String aURL;
com::sun::star::uno::Any aViewData;
HelpHistoryEntry_Impl( const String& rURL, const com::sun::star::uno::Any& rViewData ) :
aURL( rURL ), aViewData(rViewData) {}
};
DECLARE_LIST(HelpHistoryList_Impl,HelpHistoryEntry_Impl*);
class SfxHelpWindow_Impl;
class HelpInterceptor_Impl : public ::cppu::WeakImplHelper3<
::com::sun::star::frame::XDispatchProviderInterceptor,
::com::sun::star::frame::XInterceptorInfo,
::com::sun::star::frame::XDispatch >
{
private:
friend class HelpDispatch_Impl;
friend class SfxHelpWindow_Impl;
// the component which's dispatches we're intercepting
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterception > m_xIntercepted;
// chaining
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xSlaveDispatcher;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xMasterDispatcher;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener > m_xListener;
HelpHistoryList_Impl* m_pHistory;
SfxHelpWindow_Impl* m_pWindow;
ULONG m_nCurPos;
String m_aCurrentURL;
com::sun::star::uno::Any m_aViewData;
void addURL( const String& rURL );
public:
HelpInterceptor_Impl();
~HelpInterceptor_Impl();
void setInterception( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame );
void SetStartURL( const String& rURL );
String GetCurrentURL() const { return m_aCurrentURL; }
const com::sun::star::uno::Any& GetViewData()const {return m_aViewData;}
sal_Bool HasHistoryPred() const; // is there a predecessor for the current in the history
sal_Bool HasHistorySucc() const; // is there a successor for the current in the history
// XDispatchProvider
virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL
queryDispatch( const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL
queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& aDescripts ) throw(::com::sun::star::uno::RuntimeException);
// XDispatchProviderInterceptor
virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL
getSlaveDispatchProvider( ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewSlave ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL
getMasterDispatchProvider( ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewMaster ) throw(::com::sun::star::uno::RuntimeException);
// XInterceptorInfo
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getInterceptedURLs( ) throw(::com::sun::star::uno::RuntimeException);
// XDispatch
virtual void SAL_CALL dispatch( const ::com::sun::star::util::URL& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xControl, const ::com::sun::star::util::URL& aURL ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xControl, const ::com::sun::star::util::URL& aURL ) throw(::com::sun::star::uno::RuntimeException);
// extras
void InitWaiter( SfxHelpWindow_Impl* pWindow )
{ m_pWindow = pWindow; }
SfxHelpWindow_Impl* GetHelpWindow() const { return m_pWindow; }
};
// HelpListener_Impl -----------------------------------------------------
class HelpListener_Impl : public ::cppu::WeakImplHelper1< ::com::sun::star::frame::XStatusListener >
{
private:
HelpInterceptor_Impl* pInterceptor;
Link aChangeLink;
String aFactory;
public:
HelpListener_Impl( HelpInterceptor_Impl* pInter );
virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event )
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& obj )
throw( ::com::sun::star::uno::RuntimeException );
void SetChangeHdl( const Link& rLink ) { aChangeLink = rLink; }
String GetFactory() const { return aFactory; }
};
// HelpStatusListener_Impl -----------------------------------------------------
class HelpStatusListener_Impl : public
::cppu::WeakImplHelper1< ::com::sun::star::frame::XStatusListener >
{
private:
::com::sun::star::uno::Reference < ::com::sun::star::frame::XDispatch > xDispatch;
::com::sun::star::frame::FeatureStateEvent aStateEvent;
public:
HelpStatusListener_Impl(
::com::sun::star::uno::Reference < ::com::sun::star::frame::XDispatch > xDispatch,
com::sun::star::util::URL& rURL);
~HelpStatusListener_Impl();
virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event )
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& obj )
throw( ::com::sun::star::uno::RuntimeException );
const ::com::sun::star::frame::FeatureStateEvent&
GetStateEvent() const {return aStateEvent;}
};
#endif // #ifndef INCLUDED_SFX_HELPINTERCEPTOR_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.15.520); FILE MERGED 2005/09/05 15:22:07 rt 1.15.520.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: helpinterceptor.hxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: rt $ $Date: 2005-09-07 17:39:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_SFX_HELPINTERCEPTOR_HXX
#define INCLUDED_SFX_HELPINTERCEPTOR_HXX
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTOR_HPP_
#include <com/sun/star/frame/XDispatchProviderInterceptor.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XINTERCEPTORINFO_HPP_
#include <com/sun/star/frame/XInterceptorInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTION_HPP_
#include <com/sun/star/frame/XDispatchProviderInterception.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
struct HelpHistoryEntry_Impl
{
String aURL;
com::sun::star::uno::Any aViewData;
HelpHistoryEntry_Impl( const String& rURL, const com::sun::star::uno::Any& rViewData ) :
aURL( rURL ), aViewData(rViewData) {}
};
DECLARE_LIST(HelpHistoryList_Impl,HelpHistoryEntry_Impl*);
class SfxHelpWindow_Impl;
class HelpInterceptor_Impl : public ::cppu::WeakImplHelper3<
::com::sun::star::frame::XDispatchProviderInterceptor,
::com::sun::star::frame::XInterceptorInfo,
::com::sun::star::frame::XDispatch >
{
private:
friend class HelpDispatch_Impl;
friend class SfxHelpWindow_Impl;
// the component which's dispatches we're intercepting
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterception > m_xIntercepted;
// chaining
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xSlaveDispatcher;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xMasterDispatcher;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener > m_xListener;
HelpHistoryList_Impl* m_pHistory;
SfxHelpWindow_Impl* m_pWindow;
ULONG m_nCurPos;
String m_aCurrentURL;
com::sun::star::uno::Any m_aViewData;
void addURL( const String& rURL );
public:
HelpInterceptor_Impl();
~HelpInterceptor_Impl();
void setInterception( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame );
void SetStartURL( const String& rURL );
String GetCurrentURL() const { return m_aCurrentURL; }
const com::sun::star::uno::Any& GetViewData()const {return m_aViewData;}
sal_Bool HasHistoryPred() const; // is there a predecessor for the current in the history
sal_Bool HasHistorySucc() const; // is there a successor for the current in the history
// XDispatchProvider
virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL
queryDispatch( const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL
queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& aDescripts ) throw(::com::sun::star::uno::RuntimeException);
// XDispatchProviderInterceptor
virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL
getSlaveDispatchProvider( ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewSlave ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL
getMasterDispatchProvider( ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewMaster ) throw(::com::sun::star::uno::RuntimeException);
// XInterceptorInfo
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getInterceptedURLs( ) throw(::com::sun::star::uno::RuntimeException);
// XDispatch
virtual void SAL_CALL dispatch( const ::com::sun::star::util::URL& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xControl, const ::com::sun::star::util::URL& aURL ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xControl, const ::com::sun::star::util::URL& aURL ) throw(::com::sun::star::uno::RuntimeException);
// extras
void InitWaiter( SfxHelpWindow_Impl* pWindow )
{ m_pWindow = pWindow; }
SfxHelpWindow_Impl* GetHelpWindow() const { return m_pWindow; }
};
// HelpListener_Impl -----------------------------------------------------
class HelpListener_Impl : public ::cppu::WeakImplHelper1< ::com::sun::star::frame::XStatusListener >
{
private:
HelpInterceptor_Impl* pInterceptor;
Link aChangeLink;
String aFactory;
public:
HelpListener_Impl( HelpInterceptor_Impl* pInter );
virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event )
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& obj )
throw( ::com::sun::star::uno::RuntimeException );
void SetChangeHdl( const Link& rLink ) { aChangeLink = rLink; }
String GetFactory() const { return aFactory; }
};
// HelpStatusListener_Impl -----------------------------------------------------
class HelpStatusListener_Impl : public
::cppu::WeakImplHelper1< ::com::sun::star::frame::XStatusListener >
{
private:
::com::sun::star::uno::Reference < ::com::sun::star::frame::XDispatch > xDispatch;
::com::sun::star::frame::FeatureStateEvent aStateEvent;
public:
HelpStatusListener_Impl(
::com::sun::star::uno::Reference < ::com::sun::star::frame::XDispatch > xDispatch,
com::sun::star::util::URL& rURL);
~HelpStatusListener_Impl();
virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event )
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& obj )
throw( ::com::sun::star::uno::RuntimeException );
const ::com::sun::star::frame::FeatureStateEvent&
GetStateEvent() const {return aStateEvent;}
};
#endif // #ifndef INCLUDED_SFX_HELPINTERCEPTOR_HXX
<|endoftext|> |
<commit_before>
#include <iostream>
//GlEW, before GLFW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
// Should make it cross platform
// Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;
void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
// Shaders
const GLchar* vertexShaderSource =
"#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"void main()\n"
"{\n"
"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
"}\0";
const GLchar* fragmentShaderSource =
"#version 330 core\n"
"out vec4 color;\n"
"void main()\n"
"{\n"
" color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n";
void InitShaders(GLuint &vertexShader, GLuint &fragmentShader)
{
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); // 1 string, attach source code
glCompileShader(vertexShader);
// Check for compile errors
GLint vertexShaderSuccess;
GLchar infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &vertexShaderSuccess); // Check if shader compilation successful
if (!vertexShaderSuccess)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Compile fragment shader
//GLuint fragmentShader;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
// Check for compile errors
GLint fragmentShaderSuccess;
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &fragmentShaderSuccess); // Check if shader compilation successful
if (!fragmentShaderSuccess)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
}
}
void InitShaderProgram(GLuint &shaderProgram, GLuint vertexShader, GLuint fragmentShader)
{
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// Check for link errors
GLint shaderProgramSuccess;
GLchar infoLog[512];
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &shaderProgramSuccess);
if (!shaderProgramSuccess)
{
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADEPROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
}
int main()
{
std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl;
// Init GLFW and set all its required options
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Use OpenGl 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Don't use old functionality
//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Necessary for Mac OSX
// Init GLFWwindow object
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, KeyCallback);
// Init GLEW to setup function pointers for OpenGl
glewExperimental = GL_TRUE; // Use core profile modern OpenGL techniques
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to init GLEW" << std::endl;
return -1;
}
// Define width and height for OpenGL (viewport dimensions)
// OpenGL uses this data to map from processed coordinates in range (-1,1) to (0,800) and (0,600)
int width, height;
glfwGetFramebufferSize(window, &width, &height); // Framebuffer size in pixels instead of screen coordinates
glViewport(0, 0, width, height); // (0, 0) = Southwest corner of window
// Triangle vertices as normalized device coordinates
GLfloat vertices[] =
{
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f, 0.5f, 0.0f
};
// Init triangle VBO to store vertices in GPU memory
GLuint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Copies vertex data to GPU
// GL_STATIC_DRAW since the data most likely
// will not change
// Compile shaders
GLuint vertexShader, fragmentShader;
InitShaders(vertexShader, fragmentShader);
GLuint shaderProgram;
InitShaderProgram(shaderProgram, vertexShader, fragmentShader);
glUseProgram(shaderProgram);
// Game loop
while (!glfwWindowShouldClose(window))
{
glfwPollEvents(); // Check if events have been activated
// Rendering commands
glClearColor(0.2f, 0.5f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
}
glfwTerminate(); // Clear allocated resources
return 0;
}<commit_msg>Triangle rendered with shader program.<commit_after>
#include <iostream>
//GlEW, before GLFW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
// Should make it cross platform
// Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;
void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
// Shaders
const GLchar* vertexShaderSource =
"#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"void main()\n"
"{\n"
"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
"}\0";
const GLchar* fragmentShaderSource =
"#version 330 core\n"
"out vec4 color;\n"
"void main()\n"
"{\n"
" color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n";
void InitShaders(GLuint &vertexShader, GLuint &fragmentShader)
{
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); // 1 string, attach source code
glCompileShader(vertexShader);
// Check for compile errors
GLint vertexShaderSuccess;
GLchar infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &vertexShaderSuccess); // Check if shader compilation successful
if (!vertexShaderSuccess)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Compile fragment shader
//GLuint fragmentShader;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
// Check for compile errors
GLint fragmentShaderSuccess;
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &fragmentShaderSuccess); // Check if shader compilation successful
if (!fragmentShaderSuccess)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
}
}
void InitShaderProgram(GLuint &shaderProgram, GLuint vertexShader, GLuint fragmentShader)
{
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// Check for link errors
GLint shaderProgramSuccess;
GLchar infoLog[512];
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &shaderProgramSuccess);
if (!shaderProgramSuccess)
{
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADEPROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
}
void DrawTriangle(const GLuint &shaderProgram, const GLuint &VAO)
{
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3); // Arg1 0 start index of vertex array
// Arg2 3 vertices are to be drawn
glBindVertexArray(0);
}
int main()
{
std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl;
// Init GLFW and set all its required options
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Use OpenGl 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Don't use old functionality
//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Necessary for Mac OSX
// Init GLFWwindow object
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, KeyCallback);
// Init GLEW to setup function pointers for OpenGl
glewExperimental = GL_TRUE; // Use core profile modern OpenGL techniques
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to init GLEW" << std::endl;
return -1;
}
// Define width and height for OpenGL (viewport dimensions)
// OpenGL uses this data to map from processed coordinates in range (-1,1) to (0,800) and (0,600)
int width, height;
glfwGetFramebufferSize(window, &width, &height); // Framebuffer size in pixels instead of screen coordinates
glViewport(0, 0, width, height); // (0, 0) = Southwest corner of window
// Triangle vertices as normalized device coordinates
GLfloat vertices[] =
{
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f, 0.5f, 0.0f
};
// Init triangle VBO to store vertices in GPU memory
GLuint VBO;
glGenBuffers(1, &VBO);
// Init vertex array object
GLuint VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Copies vertex data to GPU
// GL_STATIC_DRAW since the data most likely
// will not change
// Specify how vertex data is to be interpreted
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); // Arg1 0 since position is layout 0
// Arg2 3 since position data vec3
// Arg4 false since already normalized values
// Arg5 Space between attribute sets
// Arg6 No data offset in buffer
glEnableVertexAttribArray(0); // Vertex attribute location is 0
glBindVertexArray(0); // Unbind vertex array to not risk misconfiguring
// Compile shaders
GLuint vertexShader, fragmentShader;
InitShaders(vertexShader, fragmentShader);
// Attach shaders and link shader program
GLuint shaderProgram;
InitShaderProgram(shaderProgram, vertexShader, fragmentShader);
glUseProgram(shaderProgram);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
// Game loop
while (!glfwWindowShouldClose(window))
{
glfwPollEvents(); // Check if events have been activated
// Rendering commands
glClearColor(0.2f, 0.5f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
DrawTriangle(shaderProgram, VAO);
glfwSwapBuffers(window);
}
// Deallocate resources
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glfwTerminate(); // Clear allocated resources
return 0;
}<|endoftext|> |
<commit_before>
/*
* share-ui -- Handset UX Share user interface
* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
* Contact: Jukka Tiihonen <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "ShareUI/pluginloader.h"
#include "pluginloader_p.h"
#include "ShareUI/PluginInterface"
#include "ShareUI/PluginBase"
#include <QDebug>
#include <QFileInfo>
#include <QRegExp>
#include <QtConcurrentRun>
#include <QTimer>
#ifndef SHARE_UI_PLUGIN_FOLDER
// Folder where plugins are loaded
#define SHARE_UI_PLUGIN_FOLDER "/usr/lib/share-ui/plugins"
#endif
#ifndef SHARE_UI_CONF_PATH
// Path to configuration file (method/plugin ordering)
#define SHARE_UI_CONF_PATH "/etc/share-ui.conf"
#endif
#ifndef SHARE_UI_PLUGIN_FILTER
// Filter for plugins
#define SHARE_UI_PLUGIN_FILTER "lib*.so"
#endif
#ifndef SHARE_UI_PLUGIN_CLEAN_PREFIX
// Prefix in plugin files that removed to get name of plugin
#define SHARE_UI_PLUGIN_CLEAN_PREFIX "lib"
#endif
#ifndef SHARE_UI_PLUGIN_CLEAN_SUFFIX
// Suffix in plugin files that removed to get name of plugin
#define SHARE_UI_PLUGIN_CLEAN_SUFFIX ".so"
#endif
static const int PLUGIN_LOADER_THREAD_STOP_TIMEOUT = 5000; // ms
using namespace ShareUI;
PluginLoader::PluginLoader(QObject * parent) : QObject (parent),
d_ptr (new PluginLoaderPrivate (SHARE_UI_PLUGIN_FOLDER,
SHARE_UI_CONF_PATH, this)) {
connect (d_ptr, SIGNAL (newMethod(ShareUI::MethodBase*)), this,
SIGNAL(newMethod(ShareUI::MethodBase*)));
connect (d_ptr, SIGNAL (methodVisible(ShareUI::MethodBase*,bool)), this,
SIGNAL(methodVisible(ShareUI::MethodBase*,bool)));
connect (d_ptr, SIGNAL (allPluginsLoaded()),
this, SIGNAL (allPluginsLoaded()));
}
PluginLoader::~PluginLoader() {
if (d_ptr->m_loaderThread != 0) {
d_ptr->m_loaderThread->abort();
if (!d_ptr->m_loaderThread->wait(PLUGIN_LOADER_THREAD_STOP_TIMEOUT)) {
qWarning() << "Plugin loader thread not yet finished, exiting anyway";
}
}
if (d_ptr->m_loaders.isEmpty() == false) {
unload();
}
d_ptr->disconnect (this);
delete d_ptr;
}
void PluginLoader::setPluginPath (const QString & path) {
d_ptr->m_pluginDir = path;
}
QString PluginLoader::pluginPath () const {
return d_ptr->m_pluginDir.absolutePath();
}
int PluginLoader::pluginCount () const {
return d_ptr->m_loaders.count();
}
int PluginLoader::methodCount () const {
return d_ptr->m_loadedMethods.count();
}
QString PluginLoader::pluginName (int at) {
if (at < 0 || at >= d_ptr->m_loaders.count()) {
qWarning() << "No plugin available with index" << at;
return "";
}
QString path = d_ptr->m_loaders.at (at)->fileName();
return PluginLoaderPrivate::loaderToName (d_ptr->m_loaders.at(at));
}
ShareUI::MethodBase * PluginLoader::method (int at) {
ShareUI::MethodBase * met = 0;
if (d_ptr->m_loadedMethods.count() > at) {
met = d_ptr->m_loadedMethods.at (at);
}
return met;
}
void PluginLoader::setPluginLoadingDelay(int delay) {
d_ptr->m_pluginLoadingDelay = delay;
}
bool PluginLoader::loadPlugins () {
if (d_ptr->m_loaders.count() > 0) {
qWarning() << "First release old plugins";
return false;
}
QDir dir = d_ptr->m_pluginDir;
// Get list of plugin files
QStringList filters;
filters << SHARE_UI_PLUGIN_FILTER;
dir.setNameFilters (filters);
QStringList plugins = dir.entryList (filters, QDir::Files, QDir::Name);
QStringList pluginsWithPath;
foreach (const QString &pluginName, plugins) {
pluginsWithPath.append(dir.filePath(pluginName));
}
if (pluginsWithPath.isEmpty()) {
qWarning() << "No plugins found";
}
else {
qDebug() << "Starting to load plugins, number of plugins found:" <<
pluginsWithPath.size();
d_ptr->m_loaderThread =
new PluginLoaderThread(pluginsWithPath, thread(), this);
QTimer::singleShot(d_ptr->m_pluginLoadingDelay, d_ptr, SLOT(doLoadPlugins()));
}
return true;
}
void PluginLoader::unload() {
qDebug() << "Unloading all plugins";
for (int i = 0; i < d_ptr->m_loadedMethods.count(); ++i) {
delete d_ptr->m_loadedMethods.at (i);
}
d_ptr->m_loadedMethods.clear();
for (int i = 0; i < d_ptr->m_loaders.count(); ++i) {
QPluginLoader * loader = d_ptr->m_loaders.at(i);
loader->unload();
delete loader;
}
d_ptr->m_loaders.clear();
}
QList <ShareUI::MethodBase *> PluginLoader::methods () const {
return d_ptr->m_loadedMethods;
}
QString PluginLoader::pluginNameForMethod (ShareUI::MethodBase * method) const {
return d_ptr->pluginNameForMethod (method);
}
bool PluginLoader::methodOrderingValues (ShareUI::MethodBase * method,
int & order, int & suborder) {
if (method == 0) {
return false;
}
ShareUI::MethodBase::Type type = method->type();
// Handle promoted methods (with check)
bool isPromoted = (type == ShareUI::MethodBase::TYPE_PROMOTED);
if (isPromoted == true) {
int topOrder = d_ptr->promotedOrderValue (method);
if (topOrder == -1) {
isPromoted = false;
} else {
order = topOrder;
suborder = method->order();
}
}
// Handle normal methods
if (isPromoted == false) {
if (type == ShareUI::MethodBase::TYPE_WEB_SERVICE) {
order = -1;
suborder = d_ptr->subOrderValue (method, type);
// Default type is other
} else {
if (type != ShareUI::MethodBase::TYPE_OTHER) {
qWarning() << "Type of method" << method->id()
<< "changed to other from" << type;
}
order = -2;
suborder = d_ptr->subOrderValue (method, type);
}
}
return true;
}
// - private ------------------------------------------------------------------
PluginLoaderPrivate::PluginLoaderPrivate (const QString & pluginDir,
const QString & confFile, PluginLoader * parent) : QObject (parent),
m_pluginDir (pluginDir), m_pluginConfig (confFile, QSettings::IniFormat),
m_loaderThread(0), m_pluginLoadingDelay(0)
{
m_promotedPlugins = m_pluginConfig.value (
"promoted/plugins").toStringList();
buildRegExpList (m_pluginConfig.value ("services/order").toStringList(),
m_serviceOrder);
buildRegExpList (m_pluginConfig.value ("others/order").toStringList(),
m_otherOrder);
}
PluginLoaderPrivate::~PluginLoaderPrivate () {
}
void PluginLoaderPrivate::buildRegExpList (const QStringList & input,
QList<QRegExp> & output) {
QStringListIterator iter (input);
while (iter.hasNext()) {
QString value = iter.next();
if (value.isEmpty() == true) {
continue;
}
//Only use wildcard mode (KISS)
QRegExp regexp (value, Qt::CaseSensitive, QRegExp::Wildcard);
if (regexp.isValid() == true) {
output.append (regexp);
} else {
qWarning() << "Invalid ordering value ignored:" << value;
}
}
}
int PluginLoaderPrivate::promotedOrderValue (ShareUI::MethodBase * method) {
QString name = pluginNameForMethod (method);
if (name.isEmpty() == true) {
return -1;
}
int index = m_promotedPlugins.indexOf (name);
if (index >= 0) {
index = m_promotedPlugins.count() - index;
}
return index;
}
int PluginLoaderPrivate::subOrderValue (ShareUI::MethodBase * method,
ShareUI::MethodBase::Type type) {
// No id return always 0
QString id = method->id();
if (id.isEmpty() == true) {
return 0;
}
const QList<QRegExp> * list = &m_otherOrder;
if (type == ShareUI::MethodBase::TYPE_WEB_SERVICE) {
list = &m_serviceOrder;
}
// If no list -> always 0 (less than found)
if (list->isEmpty() == true) {
return 0;
}
// Construct longId used in lists (plugin name + / + method id)
QString longId = pluginNameForMethod (method);
longId.append ("/");
longId.append (id);
// Use regexp finder (wildcard support)
int found = findRegExp (*list, longId);
if (found >= 0) {
return list->count() - found;
}
return 0;
}
int PluginLoaderPrivate::findRegExp (const QList<QRegExp> & list,
const QString & name) {
int i = 0;
QListIterator<QRegExp> iter (list);
while (iter.hasNext()) {
QRegExp regexp = iter.next();
if (regexp.exactMatch (name) == true) {
return i;
}
++i;
}
return -1;
}
QString PluginLoaderPrivate::loaderToName (QPluginLoader * loader) {
static QString cleanPrefix = QLatin1String (SHARE_UI_PLUGIN_CLEAN_PREFIX);
static QString cleanSuffix = QLatin1String (SHARE_UI_PLUGIN_CLEAN_SUFFIX);
QString path = loader->fileName();
QFileInfo fInfo (path);
QString name = fInfo.fileName();
// Cut out parts of filename
if (name.startsWith (cleanPrefix) == true) {
name.remove (0, cleanPrefix.length());
}
if (name.endsWith (cleanSuffix) == true) {
name.chop (cleanSuffix.length());
}
return name;
}
void PluginLoaderPrivate::newMethodFromPlugin (ShareUI::MethodBase * method) {
ShareUI::PluginBase * plugin = qobject_cast <ShareUI::PluginBase*>(
sender());
if (plugin != 0) {
m_methodPluginMap.insert (method, plugin);
}
method->setParent (this);
m_loadedMethods.append (method);
connect (method, SIGNAL (visible(bool)), this, SLOT (methodVisible(bool)));
Q_EMIT (newMethod(method));
}
QString PluginLoaderPrivate::pluginNameForMethod (
ShareUI::MethodBase * method) const {
QPluginLoader * loader = 0;
ShareUI::PluginBase * plugin = 0;
plugin = m_methodPluginMap.value (method);
if (plugin != 0) {
loader = m_pluginLoaderMap.value (plugin);
} else {
qCritical() << "Plugin for method" << method << "not found";
}
QString name;
if (loader != 0) {
name = loaderToName (loader);
} else {
qCritical() << "Loader for method" << method << "not found";
}
return name;
}
void PluginLoaderPrivate::methodVisible (bool visible) {
ShareUI::MethodBase * method = qobject_cast<ShareUI::MethodBase*> (
sender());
if (method == 0) {
qCritical() << "Invalid caller for" << __FUNCTION__;
return;
}
Q_EMIT (methodVisible(method, visible));
}
void PluginLoaderPrivate::pluginLoaded(QPluginLoader *loader, bool last) {
if (loader != 0) {
QObject * obj = loader->instance();
ShareUI::PluginBase * plugin =
qobject_cast<ShareUI::PluginBase *>(obj);
if (plugin != 0 && plugin->init()) {
m_pluginLoaderMap.insert (plugin, loader);
QList <ShareUI::MethodBase *> pluginMethods =
plugin->methods (this);
int loaded = 0;
for (int i = 0; i < pluginMethods.size(); ++i) {
ShareUI::MethodBase * met = pluginMethods.at (i);
if (met != 0) {
m_methodPluginMap.insert (met, plugin);
m_loadedMethods.append (met);
++loaded;
connect (met, SIGNAL (visible(bool)), this,
SLOT (methodVisible(bool)));
}
}
m_loaders.append (loader);
QObject::connect (plugin,
SIGNAL (newMethod(ShareUI::MethodBase*)), this,
SLOT (newMethodFromPlugin(ShareUI::MethodBase*)));
} else {
if (plugin != 0) {
qCritical() << "Initalization failed with plugin";
delete plugin;
}
qCritical() << "Plugin not accepted";
delete loader;
}
}
if (last) {
qDebug() << "Method load summary:" << m_loaders.count()
<< "plugin(s) and" << m_loadedMethods.count() << "method(s)";
Q_EMIT(allPluginsLoaded());
}
}
void PluginLoaderPrivate::doLoadPlugins() {
connect(m_loaderThread, SIGNAL(pluginLoaded(QPluginLoader*, bool)),
this, SLOT(pluginLoaded(QPluginLoader*, bool)), Qt::QueuedConnection);
m_loaderThread->start();
}
<commit_msg>Small change to plugin in filename filter.<commit_after>
/*
* share-ui -- Handset UX Share user interface
* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
* Contact: Jukka Tiihonen <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "ShareUI/pluginloader.h"
#include "pluginloader_p.h"
#include "ShareUI/PluginInterface"
#include "ShareUI/PluginBase"
#include <QDebug>
#include <QFileInfo>
#include <QRegExp>
#include <QtConcurrentRun>
#include <QTimer>
#ifndef SHARE_UI_PLUGIN_FOLDER
// Folder where plugins are loaded
#define SHARE_UI_PLUGIN_FOLDER "/usr/lib/share-ui/plugins"
#endif
#ifndef SHARE_UI_CONF_PATH
// Path to configuration file (method/plugin ordering)
#define SHARE_UI_CONF_PATH "/etc/share-ui.conf"
#endif
#ifndef SHARE_UI_PLUGIN_CLEAN_PREFIX
// Prefix in plugin files that removed to get name of plugin
#define SHARE_UI_PLUGIN_CLEAN_PREFIX "lib"
#endif
#ifndef SHARE_UI_PLUGIN_CLEAN_SUFFIX
// Suffix in plugin files that removed to get name of plugin
#define SHARE_UI_PLUGIN_CLEAN_SUFFIX ".so"
#endif
#ifndef SHARE_UI_PLUGIN_FILTER
// Filter for plugins (e.g. "lib*.so")
#define SHARE_UI_PLUGIN_FILTER SHARE_UI_PLUGIN_CLEAN_PREFIX "*" SHARE_UI_PLUGIN_CLEAN_SUFFIX
#endif
static const int PLUGIN_LOADER_THREAD_STOP_TIMEOUT = 5000; // ms
using namespace ShareUI;
PluginLoader::PluginLoader(QObject * parent) : QObject (parent),
d_ptr (new PluginLoaderPrivate (SHARE_UI_PLUGIN_FOLDER,
SHARE_UI_CONF_PATH, this)) {
connect (d_ptr, SIGNAL (newMethod(ShareUI::MethodBase*)), this,
SIGNAL(newMethod(ShareUI::MethodBase*)));
connect (d_ptr, SIGNAL (methodVisible(ShareUI::MethodBase*,bool)), this,
SIGNAL(methodVisible(ShareUI::MethodBase*,bool)));
connect (d_ptr, SIGNAL (allPluginsLoaded()),
this, SIGNAL (allPluginsLoaded()));
}
PluginLoader::~PluginLoader() {
if (d_ptr->m_loaderThread != 0) {
d_ptr->m_loaderThread->abort();
if (!d_ptr->m_loaderThread->wait(PLUGIN_LOADER_THREAD_STOP_TIMEOUT)) {
qWarning() << "Plugin loader thread not yet finished, exiting anyway";
}
}
if (d_ptr->m_loaders.isEmpty() == false) {
unload();
}
d_ptr->disconnect (this);
delete d_ptr;
}
void PluginLoader::setPluginPath (const QString & path) {
d_ptr->m_pluginDir = path;
}
QString PluginLoader::pluginPath () const {
return d_ptr->m_pluginDir.absolutePath();
}
int PluginLoader::pluginCount () const {
return d_ptr->m_loaders.count();
}
int PluginLoader::methodCount () const {
return d_ptr->m_loadedMethods.count();
}
QString PluginLoader::pluginName (int at) {
if (at < 0 || at >= d_ptr->m_loaders.count()) {
qWarning() << "No plugin available with index" << at;
return "";
}
QString path = d_ptr->m_loaders.at (at)->fileName();
return PluginLoaderPrivate::loaderToName (d_ptr->m_loaders.at(at));
}
ShareUI::MethodBase * PluginLoader::method (int at) {
ShareUI::MethodBase * met = 0;
if (d_ptr->m_loadedMethods.count() > at) {
met = d_ptr->m_loadedMethods.at (at);
}
return met;
}
void PluginLoader::setPluginLoadingDelay(int delay) {
d_ptr->m_pluginLoadingDelay = delay;
}
bool PluginLoader::loadPlugins () {
if (d_ptr->m_loaders.count() > 0) {
qWarning() << "First release old plugins";
return false;
}
QDir dir = d_ptr->m_pluginDir;
// Get list of plugin files
QStringList filters;
filters << SHARE_UI_PLUGIN_FILTER;
dir.setNameFilters (filters);
QStringList plugins = dir.entryList (filters, QDir::Files, QDir::Name);
QStringList pluginsWithPath;
foreach (const QString &pluginName, plugins) {
pluginsWithPath.append(dir.filePath(pluginName));
}
if (pluginsWithPath.isEmpty()) {
qWarning() << "No plugins found";
}
else {
qDebug() << "Starting to load plugins, number of plugins found:" <<
pluginsWithPath.size();
d_ptr->m_loaderThread =
new PluginLoaderThread(pluginsWithPath, thread(), this);
QTimer::singleShot(d_ptr->m_pluginLoadingDelay, d_ptr, SLOT(doLoadPlugins()));
}
return true;
}
void PluginLoader::unload() {
qDebug() << "Unloading all plugins";
for (int i = 0; i < d_ptr->m_loadedMethods.count(); ++i) {
delete d_ptr->m_loadedMethods.at (i);
}
d_ptr->m_loadedMethods.clear();
for (int i = 0; i < d_ptr->m_loaders.count(); ++i) {
QPluginLoader * loader = d_ptr->m_loaders.at(i);
loader->unload();
delete loader;
}
d_ptr->m_loaders.clear();
}
QList <ShareUI::MethodBase *> PluginLoader::methods () const {
return d_ptr->m_loadedMethods;
}
QString PluginLoader::pluginNameForMethod (ShareUI::MethodBase * method) const {
return d_ptr->pluginNameForMethod (method);
}
bool PluginLoader::methodOrderingValues (ShareUI::MethodBase * method,
int & order, int & suborder) {
if (method == 0) {
return false;
}
ShareUI::MethodBase::Type type = method->type();
// Handle promoted methods (with check)
bool isPromoted = (type == ShareUI::MethodBase::TYPE_PROMOTED);
if (isPromoted == true) {
int topOrder = d_ptr->promotedOrderValue (method);
if (topOrder == -1) {
isPromoted = false;
} else {
order = topOrder;
suborder = method->order();
}
}
// Handle normal methods
if (isPromoted == false) {
if (type == ShareUI::MethodBase::TYPE_WEB_SERVICE) {
order = -1;
suborder = d_ptr->subOrderValue (method, type);
// Default type is other
} else {
if (type != ShareUI::MethodBase::TYPE_OTHER) {
qWarning() << "Type of method" << method->id()
<< "changed to other from" << type;
}
order = -2;
suborder = d_ptr->subOrderValue (method, type);
}
}
return true;
}
// - private ------------------------------------------------------------------
PluginLoaderPrivate::PluginLoaderPrivate (const QString & pluginDir,
const QString & confFile, PluginLoader * parent) : QObject (parent),
m_pluginDir (pluginDir), m_pluginConfig (confFile, QSettings::IniFormat),
m_loaderThread(0), m_pluginLoadingDelay(0)
{
m_promotedPlugins = m_pluginConfig.value (
"promoted/plugins").toStringList();
buildRegExpList (m_pluginConfig.value ("services/order").toStringList(),
m_serviceOrder);
buildRegExpList (m_pluginConfig.value ("others/order").toStringList(),
m_otherOrder);
}
PluginLoaderPrivate::~PluginLoaderPrivate () {
}
void PluginLoaderPrivate::buildRegExpList (const QStringList & input,
QList<QRegExp> & output) {
QStringListIterator iter (input);
while (iter.hasNext()) {
QString value = iter.next();
if (value.isEmpty() == true) {
continue;
}
//Only use wildcard mode (KISS)
QRegExp regexp (value, Qt::CaseSensitive, QRegExp::Wildcard);
if (regexp.isValid() == true) {
output.append (regexp);
} else {
qWarning() << "Invalid ordering value ignored:" << value;
}
}
}
int PluginLoaderPrivate::promotedOrderValue (ShareUI::MethodBase * method) {
QString name = pluginNameForMethod (method);
if (name.isEmpty() == true) {
return -1;
}
int index = m_promotedPlugins.indexOf (name);
if (index >= 0) {
index = m_promotedPlugins.count() - index;
}
return index;
}
int PluginLoaderPrivate::subOrderValue (ShareUI::MethodBase * method,
ShareUI::MethodBase::Type type) {
// No id return always 0
QString id = method->id();
if (id.isEmpty() == true) {
return 0;
}
const QList<QRegExp> * list = &m_otherOrder;
if (type == ShareUI::MethodBase::TYPE_WEB_SERVICE) {
list = &m_serviceOrder;
}
// If no list -> always 0 (less than found)
if (list->isEmpty() == true) {
return 0;
}
// Construct longId used in lists (plugin name + / + method id)
QString longId = pluginNameForMethod (method);
longId.append ("/");
longId.append (id);
// Use regexp finder (wildcard support)
int found = findRegExp (*list, longId);
if (found >= 0) {
return list->count() - found;
}
return 0;
}
int PluginLoaderPrivate::findRegExp (const QList<QRegExp> & list,
const QString & name) {
int i = 0;
QListIterator<QRegExp> iter (list);
while (iter.hasNext()) {
QRegExp regexp = iter.next();
if (regexp.exactMatch (name) == true) {
return i;
}
++i;
}
return -1;
}
QString PluginLoaderPrivate::loaderToName (QPluginLoader * loader) {
static QString cleanPrefix = QLatin1String (SHARE_UI_PLUGIN_CLEAN_PREFIX);
static QString cleanSuffix = QLatin1String (SHARE_UI_PLUGIN_CLEAN_SUFFIX);
QString path = loader->fileName();
QFileInfo fInfo (path);
QString name = fInfo.fileName();
// Cut out parts of filename
if (name.startsWith (cleanPrefix) == true) {
name.remove (0, cleanPrefix.length());
}
if (name.endsWith (cleanSuffix) == true) {
name.chop (cleanSuffix.length());
}
return name;
}
void PluginLoaderPrivate::newMethodFromPlugin (ShareUI::MethodBase * method) {
ShareUI::PluginBase * plugin = qobject_cast <ShareUI::PluginBase*>(
sender());
if (plugin != 0) {
m_methodPluginMap.insert (method, plugin);
}
method->setParent (this);
m_loadedMethods.append (method);
connect (method, SIGNAL (visible(bool)), this, SLOT (methodVisible(bool)));
Q_EMIT (newMethod(method));
}
QString PluginLoaderPrivate::pluginNameForMethod (
ShareUI::MethodBase * method) const {
QPluginLoader * loader = 0;
ShareUI::PluginBase * plugin = 0;
plugin = m_methodPluginMap.value (method);
if (plugin != 0) {
loader = m_pluginLoaderMap.value (plugin);
} else {
qCritical() << "Plugin for method" << method << "not found";
}
QString name;
if (loader != 0) {
name = loaderToName (loader);
} else {
qCritical() << "Loader for method" << method << "not found";
}
return name;
}
void PluginLoaderPrivate::methodVisible (bool visible) {
ShareUI::MethodBase * method = qobject_cast<ShareUI::MethodBase*> (
sender());
if (method == 0) {
qCritical() << "Invalid caller for" << __FUNCTION__;
return;
}
Q_EMIT (methodVisible(method, visible));
}
void PluginLoaderPrivate::pluginLoaded(QPluginLoader *loader, bool last) {
if (loader != 0) {
QObject * obj = loader->instance();
ShareUI::PluginBase * plugin =
qobject_cast<ShareUI::PluginBase *>(obj);
if (plugin != 0 && plugin->init()) {
m_pluginLoaderMap.insert (plugin, loader);
QList <ShareUI::MethodBase *> pluginMethods =
plugin->methods (this);
int loaded = 0;
for (int i = 0; i < pluginMethods.size(); ++i) {
ShareUI::MethodBase * met = pluginMethods.at (i);
if (met != 0) {
m_methodPluginMap.insert (met, plugin);
m_loadedMethods.append (met);
++loaded;
connect (met, SIGNAL (visible(bool)), this,
SLOT (methodVisible(bool)));
}
}
m_loaders.append (loader);
QObject::connect (plugin,
SIGNAL (newMethod(ShareUI::MethodBase*)), this,
SLOT (newMethodFromPlugin(ShareUI::MethodBase*)));
} else {
if (plugin != 0) {
qCritical() << "Initalization failed with plugin";
delete plugin;
}
qCritical() << "Plugin not accepted";
delete loader;
}
}
if (last) {
qDebug() << "Method load summary:" << m_loaders.count()
<< "plugin(s) and" << m_loadedMethods.count() << "method(s)";
Q_EMIT(allPluginsLoaded());
}
}
void PluginLoaderPrivate::doLoadPlugins() {
connect(m_loaderThread, SIGNAL(pluginLoaded(QPluginLoader*, bool)),
this, SLOT(pluginLoaded(QPluginLoader*, bool)), Qt::QueuedConnection);
m_loaderThread->start();
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <nav_msgs/OccupancyGrid.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/core/core.hpp>
//using namespace cv;
void occupancyGridCb(const nav_msgs::OccupancyGrid::Ptr msg);
cv::Vec3b getColorFromMapValue(int8_t val);
image_transport::Publisher image_pub;
image_transport::Publisher color_image_pub;
int main(int argc, char** argv)
{
ros::init(argc, argv, "occupancy_image_publisher");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe<nav_msgs::OccupancyGrid::Ptr>("/costmap/costmap/costmap", 1, &occupancyGridCb);
image_transport::ImageTransport it(n);
image_pub = it.advertise("occupancy_image", 1);
color_image_pub = it.advertise("occupancy_image_color", 1);
ros::spin();
return 0;
}
void occupancyGridCb(const nav_msgs::OccupancyGrid::Ptr msg)
{
// Greyscale image
cv::Mat im(msg->info.height, msg->info.width, CV_8SC1);
unsigned im_length = msg->info.height*msg->info.width;
for (int i = 0; i < msg->info.height; ++i) {
for (int j = 0; j < msg->info.width; ++j) {
im.data[i* msg->info.width + j] = msg->data[(msg->info.height-i)*msg->info.width + j];
}
}
sensor_msgs::ImagePtr im_msg = cv_bridge::CvImage(std_msgs::Header(), "mono8", im).toImageMsg();
image_pub.publish(im_msg);
// Color image
cv::Mat imgColor(msg->info.height,msg->info.width, CV_8UC3);
for(int y=0; y < msg->info.height;y++){
cv::Vec3b* imgRow = imgColor.ptr<cv::Vec3b>(y);
for(int x = 0; x < msg->info.width;x++){
imgRow[x] = getColorFromMapValue(msg->data[(msg->info.height-y)*msg->info.width + x]);
}
}
sensor_msgs::ImagePtr imColor_msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", imgColor).toImageMsg();
color_image_pub.publish(imColor_msg);
}
cv::Vec3b getColorFromMapValue(int8_t val)
{
cv::Vec3b res;
if(val < 0)
{
res[0] = 128;
res[1] = 128;
res[2] = 128;
}
else if( val >= 0 && val <=100)
{
if(val <= 50){
res[2] = 250 - (50 -val) * 3;
res[1] = 250;
res[0] = 0;
}
else
{
res[2] = 250;
res[1] = 250 - val * 2.5;
res[0] = 0;
// ROS_INFO("val: %i - green: %i",val,res[1]);
}
}
else
{
res[0] = 0;
res[1] = 0;
res[2] = 0;
}
return res;
}
<commit_msg>image publish fixed<commit_after>#include <ros/ros.h>
#include <nav_msgs/OccupancyGrid.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/core/core.hpp>
//using namespace cv;
void occupancyGridCb(const nav_msgs::OccupancyGrid::Ptr msg);
cv::Vec3b getColorFromMapValue(int8_t val);
image_transport::Publisher image_pub;
image_transport::Publisher color_image_pub;
int main(int argc, char** argv)
{
ros::init(argc, argv, "occupancy_image_publisher");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe<nav_msgs::OccupancyGrid::Ptr>("/costmap/costmap/costmap", 1, &occupancyGridCb);
image_transport::ImageTransport it(n);
image_pub = it.advertise("occupancy_image", 1);
color_image_pub = it.advertise("occupancy_image_color", 1);
ros::spin();
return 0;
}
void occupancyGridCb(const nav_msgs::OccupancyGrid::Ptr msg)
{
// Greyscale image
cv::Mat im(msg->info.height, msg->info.width, CV_8SC1);
unsigned im_length = msg->info.height*msg->info.width;
for (int i = 0; i < msg->info.height; ++i) {
for (int j = 0; j < msg->info.width; ++j) {
im.data[i* msg->info.width + j] = msg->data[(msg->info.height-(i+1))*msg->info.width + j];
}
}
sensor_msgs::ImagePtr im_msg = cv_bridge::CvImage(std_msgs::Header(), "mono8", im).toImageMsg();
image_pub.publish(im_msg);
// Color image
cv::Mat imgColor(msg->info.height,msg->info.width, CV_8UC3);
for(int y=0; y < msg->info.height;y++){
cv::Vec3b* imgRow = imgColor.ptr<cv::Vec3b>(y);
for(int x = 0; x < msg->info.width;x++){
imgRow[x] = getColorFromMapValue(msg->data[(msg->info.height-(y+1))*msg->info.width + x]);
}
}
sensor_msgs::ImagePtr imColor_msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", imgColor).toImageMsg();
color_image_pub.publish(imColor_msg);
}
cv::Vec3b getColorFromMapValue(int8_t val)
{
cv::Vec3b res;
if(val < 0)
{
res[0] = 128;
res[1] = 128;
res[2] = 128;
}
else if( val >= 0 && val <=100)
{
if(val <= 50){
res[2] = 250 - (50 -val) * 3;
res[1] = 250;
res[0] = 0;
}
else
{
res[2] = 250;
res[1] = 250 - val * 2.5;
res[0] = 0;
// ROS_INFO("val: %i - green: %i",val,res[1]);
}
}
else
{
res[0] = 0;
res[1] = 0;
res[2] = 0;
}
return res;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016 Luke San Antonio
* All rights reserved.
*
* This file provides the implementation for the engine's C interface,
* specifically tailored for LuaJIT's FFI facilities.
*
* Scene stuff
*/
#include "redcrane.hpp"
#define CHECK_ID(id) \
REDC_ASSERT_MSG(id != 0, "No more room for any more objects"); \
if(id == 0) return id;
using namespace redc;
extern "C"
{
// See scene.lua
void *redc_make_scene(void *engine)
{
auto sc = new redc::Scene;
sc->engine = (redc::Engine *) engine;
return sc;
}
void redc_unmake_scene(void *scene)
{
auto sc = (redc::Scene *) scene;
delete sc;
}
uint16_t redc_scene_add_camera(void *sc, const char *tp)
{
// For the moment, this is the only kind of camera we support
std::function <gfx::Camera(gfx::IDriver const&)> cam_func;
if(strcmp(tp, "fps") == 0)
{
// Ayy we got a camera
cam_func = redc::gfx::make_fps_camera;
}
else
{
log_w("Invalid camera type '%' so making an fps camera", tp);
}
// The first camera will be set as active automatically by Active_Map from
// id_map.hpp.
auto scene = (redc::Scene *) sc;
auto id = scene->index_gen.get();
CHECK_ID(id);
auto &obj = scene->objs[id - 1];
obj.obj = Cam_Object{cam_func(*scene->engine->driver)};
// We can be sure at this point the id is non-zero (because of CHECK_ID).
// If this is our first camera
if(!scene->active_camera) scene->active_camera = id;
// Return the id
return id;
}
uint16_t redc_scene_get_active_camera(void *sc)
{
auto scene = (redc::Scene *) sc;
// This will be zero when there isn't an active camera.
return scene->active_camera;
}
void redc_scene_activate_camera(void *sc, uint16_t cam)
{
if(!cam)
{
log_w("Cannot make an invalid object the active camera, "
"ignoring request");
return;
}
// We have a camera
auto scene = (redc::Scene *) sc;
if(scene->objs[cam].obj.which() == Object::Cam)
{
scene->active_camera = cam+1;
}
else
{
log_w("Cannot make non-camera the active camera, ignoring request");
}
}
uint16_t redc_scene_attach(void *sc, void *ms, uint16_t parent)
{
auto scene = (redc::Scene *) sc;
auto mesh = (redc::gfx::Mesh_Chunk *) ms;
auto id = scene->index_gen.get();
CHECK_ID(id);
scene->objs[id - 1].obj = Mesh_Object{gfx::copy_mesh_chunk_share_mesh(*mesh),
glm::mat4(1.0f)};
if(parent)
{
scene->objs[id - 1].parent = &scene->objs[parent];
}
}
bool redc_running(void *eng)
{
return ((redc::Engine *) eng)->running;
}
void redc_scene_step(void *sc)
{
auto scene = (redc::Scene *) sc;
Cam_Object* active_camera;
if(scene->active_camera)
{
active_camera =
&boost::get<Cam_Object>(scene->objs[scene->active_camera-1].obj);
}
SDL_Event event;
while(SDL_PollEvent(&event))
{
// If we already used the event, bail.
//if(collect_input(input, event, input_cfg)) continue;
// Otherwise
switch(event.type)
{
case SDL_QUIT:
scene->engine->running = false;
break;
case SDL_MOUSEMOTION:
if(active_camera)
{
active_camera->control.apply_delta_yaw(active_camera->cam,
event.motion.xrel / 1000.0f);
active_camera->control.apply_delta_pitch(active_camera->cam,
event.motion.yrel / 1000.0f);
}
break;
case SDL_KEYDOWN:
//if(event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) running = false;
break;
default:
break;
}
}
}
void redc_scene_render(void *sc)
{
auto scene = (redc::Scene *) sc;
// Make sure we have an active camera
if(!scene->active_camera)
{
log_e("No active camera; cannot render scene");
return;
}
// Load the active camera
auto active_camera =
boost::get<Cam_Object>(scene->objs[scene->active_camera - 1].obj);
gfx::use_camera(*scene->engine->driver, active_camera.cam);
// Clear the screen
scene->engine->driver->clear();
// Find active shader.
auto active_shader = scene->engine->driver->active_shader();
// i is the loop counter, id is our current id.
// Loop however many times as we have ids.
int cur_id = 0;
for(int i = 0; i < scene->index_gen.reserved(); ++i);
{
// Check to make sure the current id hasn't been removed.
// Remember to add one
// Increment the current id until we find one that is valid. Technically
// we could just check if it hasn't been removed because we shouldn't
// get far enough to exceed count but whatever this makes more semantic
// sense. Then again if we exceed count_ we could enter a loop where we
// exit only at overflow.
while(!scene->index_gen.is_valid((cur_id + 1))) { ++cur_id; }
// If the above scenario becomes an issue, replace !is_valid with
// is_removed and check if it's valid here. If it hasn't been removed
// but isn't valid we went to far, so exit early. I'm not doing that here
// because I don't think it will be an issue.
auto &obj = scene->objs[cur_id];
if(obj.obj.which() == Object::Cam)
{
// Debugging enabled? Render cameras in some way?
}
else if(obj.obj.which() == Object::Mesh)
{
auto mesh_obj = boost::get<Mesh_Object>(obj.obj);
// Find out the model
auto model = object_model(obj);
gfx::render_chunk(mesh_obj.chunk);
}
}
}
}
<commit_msg>Properly cast mesh parameter in redc_scene_attach<commit_after>/*
* Copyright (c) 2016 Luke San Antonio
* All rights reserved.
*
* This file provides the implementation for the engine's C interface,
* specifically tailored for LuaJIT's FFI facilities.
*
* Scene stuff
*/
#include "redcrane.hpp"
#define CHECK_ID(id) \
REDC_ASSERT_MSG(id != 0, "No more room for any more objects"); \
if(id == 0) return id;
using namespace redc;
extern "C"
{
// See scene.lua
void *redc_make_scene(void *engine)
{
auto sc = new redc::Scene;
sc->engine = (redc::Engine *) engine;
return sc;
}
void redc_unmake_scene(void *scene)
{
auto sc = (redc::Scene *) scene;
delete sc;
}
uint16_t redc_scene_add_camera(void *sc, const char *tp)
{
// For the moment, this is the only kind of camera we support
std::function <gfx::Camera(gfx::IDriver const&)> cam_func;
if(strcmp(tp, "fps") == 0)
{
// Ayy we got a camera
cam_func = redc::gfx::make_fps_camera;
}
else
{
log_w("Invalid camera type '%' so making an fps camera", tp);
}
// The first camera will be set as active automatically by Active_Map from
// id_map.hpp.
auto scene = (redc::Scene *) sc;
auto id = scene->index_gen.get();
CHECK_ID(id);
auto &obj = scene->objs[id - 1];
obj.obj = Cam_Object{cam_func(*scene->engine->driver)};
// We can be sure at this point the id is non-zero (because of CHECK_ID).
// If this is our first camera
if(!scene->active_camera) scene->active_camera = id;
// Return the id
return id;
}
uint16_t redc_scene_get_active_camera(void *sc)
{
auto scene = (redc::Scene *) sc;
// This will be zero when there isn't an active camera.
return scene->active_camera;
}
void redc_scene_activate_camera(void *sc, uint16_t cam)
{
if(!cam)
{
log_w("Cannot make an invalid object the active camera, "
"ignoring request");
return;
}
// We have a camera
auto scene = (redc::Scene *) sc;
if(scene->objs[cam].obj.which() == Object::Cam)
{
scene->active_camera = cam+1;
}
else
{
log_w("Cannot make non-camera the active camera, ignoring request");
}
}
uint16_t redc_scene_attach(void *sc, void *ms, uint16_t parent)
{
auto scene = (redc::Scene *) sc;
auto mesh = (redc::Peer_Ptr<redc::gfx::Mesh_Chunk> *) ms;
auto id = scene->index_gen.get();
CHECK_ID(id);
scene->objs[id - 1].obj =
Mesh_Object{gfx::copy_mesh_chunk_share_mesh(*mesh->get()),
glm::mat4(1.0f)};
if(parent)
{
scene->objs[id - 1].parent = &scene->objs[parent];
}
}
bool redc_running(void *eng)
{
return ((redc::Engine *) eng)->running;
}
void redc_scene_step(void *sc)
{
auto scene = (redc::Scene *) sc;
Cam_Object* active_camera;
if(scene->active_camera)
{
active_camera =
&boost::get<Cam_Object>(scene->objs[scene->active_camera-1].obj);
}
SDL_Event event;
while(SDL_PollEvent(&event))
{
// If we already used the event, bail.
//if(collect_input(input, event, input_cfg)) continue;
// Otherwise
switch(event.type)
{
case SDL_QUIT:
scene->engine->running = false;
break;
case SDL_MOUSEMOTION:
if(active_camera)
{
active_camera->control.apply_delta_yaw(active_camera->cam,
event.motion.xrel / 1000.0f);
active_camera->control.apply_delta_pitch(active_camera->cam,
event.motion.yrel / 1000.0f);
}
break;
case SDL_KEYDOWN:
//if(event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) running = false;
break;
default:
break;
}
}
}
void redc_scene_render(void *sc)
{
auto scene = (redc::Scene *) sc;
// Make sure we have an active camera
if(!scene->active_camera)
{
log_e("No active camera; cannot render scene");
return;
}
// Load the active camera
auto active_camera =
boost::get<Cam_Object>(scene->objs[scene->active_camera - 1].obj);
gfx::use_camera(*scene->engine->driver, active_camera.cam);
// Clear the screen
scene->engine->driver->clear();
// Find active shader.
auto active_shader = scene->engine->driver->active_shader();
// i is the loop counter, id is our current id.
// Loop however many times as we have ids.
int cur_id = 0;
for(int i = 0; i < scene->index_gen.reserved(); ++i);
{
// Check to make sure the current id hasn't been removed.
// Remember to add one
// Increment the current id until we find one that is valid. Technically
// we could just check if it hasn't been removed because we shouldn't
// get far enough to exceed count but whatever this makes more semantic
// sense. Then again if we exceed count_ we could enter a loop where we
// exit only at overflow.
while(!scene->index_gen.is_valid((cur_id + 1))) { ++cur_id; }
// If the above scenario becomes an issue, replace !is_valid with
// is_removed and check if it's valid here. If it hasn't been removed
// but isn't valid we went to far, so exit early. I'm not doing that here
// because I don't think it will be an issue.
auto &obj = scene->objs[cur_id];
if(obj.obj.which() == Object::Cam)
{
// Debugging enabled? Render cameras in some way?
}
else if(obj.obj.which() == Object::Mesh)
{
auto mesh_obj = boost::get<Mesh_Object>(obj.obj);
// Find out the model
auto model = object_model(obj);
gfx::render_chunk(mesh_obj.chunk);
}
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Records For Living, Inc. 2004-2012. All rights reserved
*/
// TEST Foundation::DataExchangeFormat::ObjectVariantMapper
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/Configuration/Locale.h"
#include "Stroika/Foundation/DataExchangeFormat/BadFormatException.h"
#include "Stroika/Foundation/DataExchangeFormat/ObjectVariantMapper.h"
#include "Stroika/Foundation/DataExchangeFormat/JSON/Reader.h"
#include "Stroika/Foundation/DataExchangeFormat/JSON/Writer.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/IO/FileSystem/BinaryFileInputStream.h"
#include "Stroika/Foundation/IO/FileSystem/BinaryFileOutputStream.h"
#include "Stroika/Foundation/Memory/VariantValue.h"
#include "Stroika/Foundation/Streams/BasicBinaryInputOutputStream.h"
#include "Stroika/Foundation/Math/Common.h"
#include "Stroika/Foundation/Time/DateTime.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::DataExchangeFormat;
using Memory::Byte;
using Memory::VariantValue;
using Time::DateTime;
namespace {
void DoRegressionTests_SimpleRegisterEtc_1_ ()
{
}
}
namespace {
void DoRegressionTests_SimpleMapToFromJSON_2_ ()
{
const bool kWrite2FileAsWell_ = false; // just for debugging
struct SharedContactsConfig_ {
bool fEnabled;
DateTime fLastSynchronizedAt;
Mapping<String, String> fThisPHRsIDToSharedContactID;
SharedContactsConfig_ ()
: fEnabled (false)
, fLastSynchronizedAt ()
, fThisPHRsIDToSharedContactID () {
}
bool operator== (const SharedContactsConfig_& rhs) const {
return fEnabled == rhs.fEnabled and
fLastSynchronizedAt == rhs.fLastSynchronizedAt and
fThisPHRsIDToSharedContactID == rhs.fThisPHRsIDToSharedContactID
;
}
};
ObjectVariantMapper mapper;
// register each of your mappable (even private) types
#if qCompilerAndStdLib_Supports_initializer_lists
mapper.RegisterClass<SharedContactsConfig_> (Sequence<StructureFieldInfo> ( {
ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fEnabled, L"Enabled"),
ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fLastSynchronizedAt, L"Last-Synchronized-At"),
ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fThisPHRsIDToSharedContactID, L"This-HR-ContactID-To-SharedContactID-Map"),
}));
#else
DataExchangeFormat::ObjectVariantMapper::StructureFieldInfo kInfo[] = {
ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fEnabled, L"Enabled"),
ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fLastSynchronizedAt, L"Last-Synchronized-At"),
ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fThisPHRsIDToSharedContactID, L"This-HR-ContactID-To-SharedContactID-Map"),
};
mapper.RegisterClass<SharedContactsConfig_> (Sequence<DataExchangeFormat::ObjectVariantMapper::StructureFieldInfo> (std::begin (kInfo), std::end (kInfo)));
#endif
bool newEnabled = true;
SharedContactsConfig_ tmp;
tmp.fEnabled = newEnabled;
tmp.fThisPHRsIDToSharedContactID.Add (L"A", L"B");
tmp.fLastSynchronizedAt = DateTime (Time::Date (Time::Year (1998), Time::MonthOfYear::eApril, Time::DayOfMonth::e11), Time::TimeOfDay::Parse (L"3pm", locale::classic ()));
VariantValue v = mapper.FromObject (tmp);
// at this point - we should have VariantValue object with "Enabled" field.
// This can then be serialized using
Streams::BasicBinaryInputOutputStream tmpStream;
DataExchangeFormat::JSON::PrettyPrint (v, tmpStream);
if (kWrite2FileAsWell_) {
IO::FileSystem::BinaryFileOutputStream tmp (L"t.txt");
DataExchangeFormat::JSON::PrettyPrint (v, tmp);
}
if (kWrite2FileAsWell_) {
IO::FileSystem::BinaryFileInputStream tmp (L"t.txt");
SharedContactsConfig_ tmp2 = mapper.ToObject<SharedContactsConfig_> (DataExchangeFormat::JSON::Reader (IO::FileSystem::BinaryFileInputStream (L"t.txt")));
}
// THEN deserialized, and mapped back to C++ object form
SharedContactsConfig_ tmp2 = mapper.ToObject<SharedContactsConfig_> (DataExchangeFormat::JSON::Reader (tmpStream));
VerifyTestResult (tmp2 == tmp);
}
}
namespace {
void DoRegressionTests_ ()
{
DoRegressionTests_SimpleRegisterEtc_1_ ();
DoRegressionTests_SimpleMapToFromJSON_2_ ();
}
}
int main (int argc, const char* argv[])
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<commit_msg>minor cleanups of ObjectVariantMapper regtest<commit_after>/*
* Copyright(c) Records For Living, Inc. 2004-2012. All rights reserved
*/
// TEST Foundation::DataExchangeFormat::ObjectVariantMapper
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/Configuration/Locale.h"
#include "Stroika/Foundation/DataExchangeFormat/BadFormatException.h"
#include "Stroika/Foundation/DataExchangeFormat/ObjectVariantMapper.h"
#include "Stroika/Foundation/DataExchangeFormat/JSON/Reader.h"
#include "Stroika/Foundation/DataExchangeFormat/JSON/Writer.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/IO/FileSystem/BinaryFileInputStream.h"
#include "Stroika/Foundation/IO/FileSystem/BinaryFileOutputStream.h"
#include "Stroika/Foundation/Memory/VariantValue.h"
#include "Stroika/Foundation/Streams/BasicBinaryInputOutputStream.h"
#include "Stroika/Foundation/Math/Common.h"
#include "Stroika/Foundation/Time/DateTime.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::DataExchangeFormat;
using Memory::Byte;
using Memory::VariantValue;
using Time::DateTime;
namespace {
void DoRegressionTests_SimpleRegisterEtc_1_ ()
{
}
}
namespace {
void DoRegressionTests_SimpleMapToFromJSON_2_ ()
{
const bool kWrite2FileAsWell_ = false; // just for debugging
struct SharedContactsConfig_ {
bool fEnabled;
DateTime fLastSynchronizedAt;
Mapping<String, String> fThisPHRsIDToSharedContactID;
SharedContactsConfig_ ()
: fEnabled (false)
, fLastSynchronizedAt ()
, fThisPHRsIDToSharedContactID () {
}
bool operator== (const SharedContactsConfig_& rhs) const {
return fEnabled == rhs.fEnabled and
fLastSynchronizedAt == rhs.fLastSynchronizedAt and
fThisPHRsIDToSharedContactID == rhs.fThisPHRsIDToSharedContactID
;
}
};
ObjectVariantMapper mapper;
// register each of your mappable (even private) types
#if qCompilerAndStdLib_Supports_initializer_lists
mapper.RegisterClass<SharedContactsConfig_> (Sequence<ObjectVariantMapper::StructureFieldInfo> ( {
ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fEnabled, L"Enabled"),
ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fLastSynchronizedAt, L"Last-Synchronized-At"),
ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fThisPHRsIDToSharedContactID, L"This-HR-ContactID-To-SharedContactID-Map"),
}));
#else
ObjectVariantMapper::StructureFieldInfo kInfo[] = {
ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fEnabled, L"Enabled"),
ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fLastSynchronizedAt, L"Last-Synchronized-At"),
ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fThisPHRsIDToSharedContactID, L"This-HR-ContactID-To-SharedContactID-Map"),
};
mapper.RegisterClass<SharedContactsConfig_> (Sequence<ObjectVariantMapper::StructureFieldInfo> (std::begin (kInfo), std::end (kInfo)));
#endif
bool newEnabled = true;
SharedContactsConfig_ tmp;
tmp.fEnabled = newEnabled;
tmp.fThisPHRsIDToSharedContactID.Add (L"A", L"B");
tmp.fLastSynchronizedAt = DateTime (Time::Date (Time::Year (1998), Time::MonthOfYear::eApril, Time::DayOfMonth::e11), Time::TimeOfDay::Parse (L"3pm", locale::classic ()));
VariantValue v = mapper.FromObject (tmp);
// at this point - we should have VariantValue object with "Enabled" field.
// This can then be serialized using
Streams::BasicBinaryInputOutputStream tmpStream;
JSON::PrettyPrint (v, tmpStream);
if (kWrite2FileAsWell_) {
IO::FileSystem::BinaryFileOutputStream tmp (L"t.txt");
JSON::PrettyPrint (v, tmp);
}
if (kWrite2FileAsWell_) {
IO::FileSystem::BinaryFileInputStream tmp (L"t.txt");
SharedContactsConfig_ tmp2 = mapper.ToObject<SharedContactsConfig_> (JSON::Reader (IO::FileSystem::BinaryFileInputStream (L"t.txt")));
}
// THEN deserialized, and mapped back to C++ object form
SharedContactsConfig_ tmp2 = mapper.ToObject<SharedContactsConfig_> (JSON::Reader (tmpStream));
VerifyTestResult (tmp2 == tmp);
}
}
namespace {
void DoRegressionTests_ ()
{
DoRegressionTests_SimpleRegisterEtc_1_ ();
DoRegressionTests_SimpleMapToFromJSON_2_ ();
}
}
int main (int argc, const char* argv[])
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <random>
#include "data/corpus.h"
namespace marian {
namespace data {
typedef std::vector<size_t> WordBatch;
typedef std::vector<float> MaskBatch;
typedef std::pair<WordBatch, MaskBatch> WordMask;
typedef std::vector<WordMask> SentBatch;
CorpusIterator::CorpusIterator() : pos_(-1), tup_(0) {}
CorpusIterator::CorpusIterator(Corpus& corpus)
: corpus_(&corpus), pos_(0), tup_(corpus_->next()) {}
void CorpusIterator::increment() {
tup_ = corpus_->next();
pos_++;
}
bool CorpusIterator::equal(CorpusIterator const& other) const {
return this->pos_ == other.pos_ || (this->tup_.empty() && other.tup_.empty());
}
const SentenceTuple& CorpusIterator::dereference() const {
return tup_;
}
Corpus::Corpus(Ptr<Config> options, bool translate)
: options_(options),
maxLength_(options_->get<size_t>("max-length")),
g_(Config::seed) {
if(!translate)
paths_ = options_->get<std::vector<std::string>>("train-sets");
else
paths_ = options_->get<std::vector<std::string>>("input");
std::vector<std::string> vocabPaths;
if(options_->has("vocabs"))
vocabPaths = options_->get<std::vector<std::string>>("vocabs");
if(!translate) {
UTIL_THROW_IF2(!vocabPaths.empty() && paths_.size() != vocabPaths.size(),
"Number of corpus files and vocab files does not agree");
}
std::vector<int> maxVocabs = options_->get<std::vector<int>>("dim-vocabs");
if(!translate) {
std::vector<Vocab> vocabs;
if(vocabPaths.empty()) {
for(size_t i = 0; i < paths_.size(); ++i) {
Ptr<Vocab> vocab = New<Vocab>();
vocab->loadOrCreate("", paths_[i], maxVocabs[i]);
options_->get()["vocabs"].push_back(paths_[i] + ".yml");
vocabs_.emplace_back(vocab);
}
} else {
for(size_t i = 0; i < vocabPaths.size(); ++i) {
Ptr<Vocab> vocab = New<Vocab>();
vocab->loadOrCreate(vocabPaths[i], paths_[i], maxVocabs[i]);
vocabs_.emplace_back(vocab);
}
}
} else {
for(size_t i = 0; i+1 < vocabPaths.size(); ++i) {
Ptr<Vocab> vocab = New<Vocab>();
vocab->loadOrCreate(vocabPaths[i], paths_[i], maxVocabs[i]);
vocabs_.emplace_back(vocab);
}
}
for(auto path : paths_) {
if(path == "stdin")
files_.emplace_back(new InputFileStream(std::cin));
else {
files_.emplace_back(new InputFileStream(path));
UTIL_THROW_IF2(files_.back()->empty(), "File " << path << " is empty");
}
}
}
Corpus::Corpus(std::vector<std::string> paths,
std::vector<Ptr<Vocab>> vocabs,
Ptr<Config> options,
size_t maxLength)
: DatasetBase(paths),
options_(options),
vocabs_(vocabs),
maxLength_(maxLength ? maxLength : options_->get<size_t>("max-length")) {
UTIL_THROW_IF2(paths_.size() != vocabs_.size(),
"Number of corpus files and vocab files does not agree");
for(auto path : paths_) {
files_.emplace_back(new InputFileStream(path));
}
}
SentenceTuple Corpus::next() {
bool cont = true;
while(cont) {
// get index of the current sentence
size_t curId = pos_;
// if corpus has been shuffled, ids_ contains sentence indexes
if(pos_ < ids_.size())
curId = ids_[pos_];
pos_++;
// fill up the sentence tuple with sentences from all input files
SentenceTuple tup(curId);
for(size_t i = 0; i < files_.size(); ++i) {
std::string line;
if(std::getline((std::istream&)*files_[i], line)) {
Words words = (*vocabs_[i])(line);
if(words.empty())
words.push_back(0);
tup.push_back(words);
}
}
// continue only if each input file has provided an example
cont = tup.size() == files_.size();
// continue if all sentences are no longer than maximum allowed length
if(cont && std::all_of(tup.begin(), tup.end(), [=](const Words& words) {
return words.size() > 0 && words.size() <= maxLength_;
}))
return tup;
}
return SentenceTuple(0);
}
void Corpus::shuffle() {
shuffleFiles(paths_);
}
void Corpus::reset() {
files_.clear();
ids_.clear();
pos_ = 0;
for(auto& path : paths_) {
if(path == "stdin")
files_.emplace_back(new InputFileStream(std::cin));
else
files_.emplace_back(new InputFileStream(path));
}
}
void Corpus::shuffleFiles(const std::vector<std::string>& paths) {
LOG(data)->info("Shuffling files");
std::vector<std::vector<std::string>> corpus;
files_.clear();
for(auto path : paths) {
files_.emplace_back(new InputFileStream(path));
}
bool cont = true;
while(cont) {
std::vector<std::string> lines(files_.size());
for(size_t i = 0; i < files_.size(); ++i) {
cont = cont && std::getline((std::istream&)*files_[i], lines[i]);
}
if(cont)
corpus.push_back(lines);
}
pos_ = 0;
ids_.resize(corpus.size());
std::iota(ids_.begin(), ids_.end(), 0);
std::shuffle(ids_.begin(), ids_.end(), g_);
tempFiles_.clear();
std::vector<UPtr<OutputFileStream>> outs;
for(size_t i = 0; i < files_.size(); ++i) {
tempFiles_.emplace_back(
new TemporaryFile(options_->get<std::string>("tempdir")));
outs.emplace_back(new OutputFileStream(*tempFiles_[i]));
}
for(auto id : ids_) {
auto& lines = corpus[id];
size_t i = 0;
for(auto& line : lines) {
(std::ostream&)*outs[i++] << line << std::endl;
}
}
files_.clear();
for(size_t i = 0; i < outs.size(); ++i) {
files_.emplace_back(new InputFileStream(*tempFiles_[i]));
}
LOG(data)->info("Done");
}
}
}
<commit_msg>Sanity checks with respect to vocabularies and their dimensions.<commit_after>#include <random>
#include "data/corpus.h"
namespace marian {
namespace data {
typedef std::vector<size_t> WordBatch;
typedef std::vector<float> MaskBatch;
typedef std::pair<WordBatch, MaskBatch> WordMask;
typedef std::vector<WordMask> SentBatch;
CorpusIterator::CorpusIterator() : pos_(-1), tup_(0) {}
CorpusIterator::CorpusIterator(Corpus& corpus)
: corpus_(&corpus), pos_(0), tup_(corpus_->next()) {}
void CorpusIterator::increment() {
tup_ = corpus_->next();
pos_++;
}
bool CorpusIterator::equal(CorpusIterator const& other) const {
return this->pos_ == other.pos_ || (this->tup_.empty() && other.tup_.empty());
}
const SentenceTuple& CorpusIterator::dereference() const {
return tup_;
}
Corpus::Corpus(Ptr<Config> options, bool translate)
: options_(options),
maxLength_(options_->get<size_t>("max-length")),
g_(Config::seed) {
if(!translate)
paths_ = options_->get<std::vector<std::string>>("train-sets");
else
paths_ = options_->get<std::vector<std::string>>("input");
std::vector<std::string> vocabPaths;
if(options_->has("vocabs"))
vocabPaths = options_->get<std::vector<std::string>>("vocabs");
if(!translate) {
UTIL_THROW_IF2(!vocabPaths.empty() && paths_.size() != vocabPaths.size(),
"Number of corpus files and vocab files does not agree");
}
std::vector<int> maxVocabs = options_->get<std::vector<int>>("dim-vocabs");
UTIL_THROW_IF2(maxVocabs.size() != vocabPaths.size(),
"number of vocabularies and specification of vocabulary sizes "
"does not match!");
// If vocabularies exist, can't we get the dimensions from them and require
// dim-vocabs only when they don't? [UG]
if(!translate) {
std::vector<Vocab> vocabs;
if(vocabPaths.empty()) {
for(size_t i = 0; i < paths_.size(); ++i) {
Ptr<Vocab> vocab = New<Vocab>();
vocab->loadOrCreate("", paths_[i], maxVocabs[i]);
options_->get()["vocabs"].push_back(paths_[i] + ".yml");
vocabs_.emplace_back(vocab);
}
} else {
for(size_t i = 0; i < vocabPaths.size(); ++i) {
Ptr<Vocab> vocab = New<Vocab>();
vocab->loadOrCreate(vocabPaths[i], paths_[i], maxVocabs[i]);
vocabs_.emplace_back(vocab);
}
}
} else { // i.e., if translating
UTIL_THROW_IF2(vocabPaths.empty(), "translating but vocabularies are missing!");
for(size_t i = 0; i+1 < vocabPaths.size(); ++i) {
Ptr<Vocab> vocab = New<Vocab>();
vocab->loadOrCreate(vocabPaths[i], paths_[i], maxVocabs[i]);
vocabs_.emplace_back(vocab);
}
}
for(auto path : paths_) {
if(path == "stdin")
files_.emplace_back(new InputFileStream(std::cin));
else {
files_.emplace_back(new InputFileStream(path));
UTIL_THROW_IF2(files_.back()->empty(), "File " << path << " is empty");
}
}
}
Corpus::Corpus(std::vector<std::string> paths,
std::vector<Ptr<Vocab>> vocabs,
Ptr<Config> options,
size_t maxLength)
: DatasetBase(paths),
options_(options),
vocabs_(vocabs),
maxLength_(maxLength ? maxLength : options_->get<size_t>("max-length")) {
UTIL_THROW_IF2(paths_.size() != vocabs_.size(),
"Number of corpus files and vocab files does not agree");
for(auto path : paths_) {
files_.emplace_back(new InputFileStream(path));
}
}
SentenceTuple Corpus::next() {
bool cont = true;
while(cont) {
// get index of the current sentence
size_t curId = pos_;
// if corpus has been shuffled, ids_ contains sentence indexes
if(pos_ < ids_.size())
curId = ids_[pos_];
pos_++;
// fill up the sentence tuple with sentences from all input files
SentenceTuple tup(curId);
for(size_t i = 0; i < files_.size(); ++i) {
std::string line;
if(std::getline((std::istream&)*files_[i], line)) {
Words words = (*vocabs_[i])(line);
if(words.empty())
words.push_back(0);
tup.push_back(words);
}
}
// continue only if each input file has provided an example
cont = tup.size() == files_.size();
// continue if all sentences are no longer than maximum allowed length
if(cont && std::all_of(tup.begin(), tup.end(), [=](const Words& words) {
return words.size() > 0 && words.size() <= maxLength_;
}))
return tup;
}
return SentenceTuple(0);
}
void Corpus::shuffle() {
shuffleFiles(paths_);
}
void Corpus::reset() {
files_.clear();
ids_.clear();
pos_ = 0;
for(auto& path : paths_) {
if(path == "stdin")
files_.emplace_back(new InputFileStream(std::cin));
else
files_.emplace_back(new InputFileStream(path));
}
}
void Corpus::shuffleFiles(const std::vector<std::string>& paths) {
LOG(data)->info("Shuffling files");
std::vector<std::vector<std::string>> corpus;
files_.clear();
for(auto path : paths) {
files_.emplace_back(new InputFileStream(path));
}
bool cont = true;
while(cont) {
std::vector<std::string> lines(files_.size());
for(size_t i = 0; i < files_.size(); ++i) {
cont = cont && std::getline((std::istream&)*files_[i], lines[i]);
}
if(cont)
corpus.push_back(lines);
}
pos_ = 0;
ids_.resize(corpus.size());
std::iota(ids_.begin(), ids_.end(), 0);
std::shuffle(ids_.begin(), ids_.end(), g_);
tempFiles_.clear();
std::vector<UPtr<OutputFileStream>> outs;
for(size_t i = 0; i < files_.size(); ++i) {
tempFiles_.emplace_back(
new TemporaryFile(options_->get<std::string>("tempdir")));
outs.emplace_back(new OutputFileStream(*tempFiles_[i]));
}
for(auto id : ids_) {
auto& lines = corpus[id];
size_t i = 0;
for(auto& line : lines) {
(std::ostream&)*outs[i++] << line << std::endl;
}
}
files_.clear();
for(size_t i = 0; i < outs.size(); ++i) {
files_.emplace_back(new InputFileStream(*tempFiles_[i]));
}
LOG(data)->info("Done");
}
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015, Aaditya Kalsi
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file object.cpp
* \date 2015
*/
// LANG includes
// PKG includes
#include <uscheme/type/type.hpp>
#include <uscheme/type/object.hpp>
#if defined(_WIN32)
# define STRDUP _strdup
#else
# define STRDUP strdup
#endif//defined(_WIN32)
namespace uscheme {
static const object_ptr TRUE = object::create_boolean(true);
static const object_ptr FALSE = object::create_boolean(false);
object_ptr true_value(void)
{
return TRUE;
}
object_ptr false_value(void)
{
return FALSE;
}
void object::init_string(const char* value)
{
data_.string.value = STRDUP(value);
}
void object::destroy()
{
switch (type_) {
case STRING: {
free((void*)data_.string.value);
break;
}
default: {
break;
}
}
}
}//namespace uscheme
<commit_msg>Fix call to strdup on Windows<commit_after>/*
Copyright (c) 2015, Aaditya Kalsi
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file object.cpp
* \date 2015
*/
// LANG includes
#include <cstring>
// PKG includes
#include <uscheme/type/type.hpp>
#include <uscheme/type/object.hpp>
#if defined(_WIN32)
# define STRDUP _strdup
#else
# define STRDUP strdup
#endif//defined(_WIN32)
namespace uscheme {
static const object_ptr TRUE = object::create_boolean(true);
static const object_ptr FALSE = object::create_boolean(false);
object_ptr true_value(void)
{
return TRUE;
}
object_ptr false_value(void)
{
return FALSE;
}
void object::init_string(const char* value)
{
data_.string.value = STRDUP(value);
}
void object::destroy()
{
switch (type_) {
case STRING: {
free((void*)data_.string.value);
break;
}
default: {
break;
}
}
}
}//namespace uscheme
<|endoftext|> |
<commit_before>/* $Id$ */
//-------------------------------------------------------------------
// Class AliHBTPairCut:
// implements cut on the pair of particles
// more info: http://alisoft.cern.ch/people/skowron/analyzer/index.html
// Author: [email protected]
//-------------------------------------------------------------------
#include "AliHBTPairCut.h"
#include "AliHBTPair.h"
#include "AliHBTParticleCut.h"
ClassImp(AliHBTPairCut)
const Int_t AliHBTPairCut::fgkMaxCuts = 50;
/**********************************************************/
AliHBTPairCut::AliHBTPairCut():
fNCuts(0)
{
//constructor
fFirstPartCut = new AliHBTEmptyParticleCut(); //empty cuts
fSecondPartCut= new AliHBTEmptyParticleCut(); //empty cuts
fCuts = new AliHbtBasePairCut*[fgkMaxCuts];
}
/**********************************************************/
AliHBTPairCut::AliHBTPairCut(const AliHBTPairCut& in):
TNamed(in)
{
//copy constructor
fCuts = new AliHbtBasePairCut*[fgkMaxCuts];
fNCuts = in.fNCuts;
fFirstPartCut = (AliHBTParticleCut*)in.fFirstPartCut->Clone();
fSecondPartCut = (AliHBTParticleCut*)in.fSecondPartCut->Clone();
for (Int_t i = 0;i<fNCuts;i++)
{
fCuts[i] = (AliHbtBasePairCut*)in.fCuts[i]->Clone();//create new object (clone) and rember pointer to it
}
}
/**********************************************************/
AliHBTPairCut& AliHBTPairCut::operator=(const AliHBTPairCut& in)
{
//assignment operator
fCuts = new AliHbtBasePairCut*[fgkMaxCuts];
fNCuts = in.fNCuts;
fFirstPartCut = (AliHBTParticleCut*)in.fFirstPartCut->Clone();
fSecondPartCut = (AliHBTParticleCut*)in.fSecondPartCut->Clone();
for (Int_t i = 0;i<fNCuts;i++)
{
fCuts[i] = (AliHbtBasePairCut*)in.fCuts[i]->Clone();//create new object (clone) and rember pointer to it
}
return * this;
}
/**********************************************************/
AliHBTPairCut::~AliHBTPairCut()
{
//destructor
if (fFirstPartCut != fSecondPartCut)
{
delete fSecondPartCut;
}
delete fFirstPartCut;
for (Int_t i = 0;i<fNCuts;i++)
{
delete fCuts[i];
}
delete []fCuts;
}
/**********************************************************/
/**********************************************************/
void AliHBTPairCut::AddBasePairCut(AliHbtBasePairCut* basecut)
{
//adds the base pair cut (cut on one value)
if (!basecut) return;
if( fNCuts == (fgkMaxCuts-1) )
{
Warning("AddBasePairCut","Not enough place for another cut");
return;
}
fCuts[fNCuts++]=basecut;
}
/**********************************************************/
Bool_t AliHBTPairCut::Pass(AliHBTPair* pair) const
{
//methods which checks if given pair meets all criteria of the cut
//if it meets returns FALSE
//if NOT returns TRUE
if(!pair)
{
Warning("Pass","No Pasaran! We never accept NULL pointers");
return kTRUE;
}
//check particle's cuts
if( ( fFirstPartCut->Pass( pair->Particle1()) ) ||
( fSecondPartCut->Pass(pair->Particle2()) ) )
{
return kTRUE;
}
return PassPairProp(pair);
}
/**********************************************************/
Bool_t AliHBTPairCut::PassPairProp(AliHBTPair* pair) const
{
//methods which checks if given pair meets all criteria of the cut
//if it meets returns FALSE
//if NOT returns TRUE
//examine all base pair cuts
for (Int_t i = 0;i<fNCuts;i++)
{
if ( (fCuts[i]->Pass(pair)) ) return kTRUE; //if one of the cuts reject, then reject
}
return kFALSE;
}
/**********************************************************/
void AliHBTPairCut::SetFirstPartCut(AliHBTParticleCut* cut)
{
// set cut for the first particle
if(!cut)
{
Error("SetFirstPartCut","argument is NULL");
return;
}
delete fFirstPartCut;
fFirstPartCut = (AliHBTParticleCut*)cut->Clone();
}
/**********************************************************/
void AliHBTPairCut::SetSecondPartCut(AliHBTParticleCut* cut)
{
// set cut for the second particle
if(!cut)
{
Error("SetSecondPartCut","argument is NULL");
return;
}
delete fSecondPartCut;
fSecondPartCut = (AliHBTParticleCut*)cut->Clone();
}
/**********************************************************/
void AliHBTPairCut::SetPartCut(AliHBTParticleCut* cut)
{
//sets the the same cut on both particles
if(!cut)
{
Error("SetFirstPartCut","argument is NULL");
return;
}
delete fFirstPartCut;
fFirstPartCut = (AliHBTParticleCut*)cut->Clone();
delete fSecondPartCut; //even if null should not be harmful
fSecondPartCut = fFirstPartCut;
}
/**********************************************************/
void AliHBTPairCut::SetQInvRange(Double_t min, Double_t max)
{
// set range of accepted invariant masses
AliHBTQInvCut* cut= (AliHBTQInvCut*)FindCut(kHbtPairCutPropQInv);
if(cut) cut->SetRange(min,max);
else fCuts[fNCuts++] = new AliHBTQInvCut(min,max);
}
/**********************************************************/
void AliHBTPairCut::SetQOutCMSLRange(Double_t min, Double_t max)
{
// set range of accepted QOut in CMS
AliHBTQOutCMSLCCut* cut= (AliHBTQOutCMSLCCut*)FindCut(kHbtPairCutPropQOutCMSLC);
if(cut) cut->SetRange(min,max);
else fCuts[fNCuts++] = new AliHBTQOutCMSLCCut(min,max);
}
/**********************************************************/
void AliHBTPairCut::SetQSideCMSLRange(Double_t min, Double_t max)
{
// set range of accepted QSide in CMS
AliHBTQSideCMSLCCut* cut= (AliHBTQSideCMSLCCut*)FindCut(kHbtPairCutPropQSideCMSLC);
if(cut) cut->SetRange(min,max);
else fCuts[fNCuts++] = new AliHBTQSideCMSLCCut(min,max);
}
/**********************************************************/
void AliHBTPairCut::SetQLongCMSLRange(Double_t min, Double_t max)
{
// set range of accepted QLong in CMS
AliHBTQLongCMSLCCut* cut= (AliHBTQLongCMSLCCut*)FindCut(kHbtPairCutPropQLongCMSLC);
if(cut) cut->SetRange(min,max);
else fCuts[fNCuts++] = new AliHBTQLongCMSLCCut(min,max);
}
/**********************************************************/
void AliHBTPairCut::SetKtRange(Double_t min, Double_t max)
{
// set range of accepted Kt (?)
AliHBTKtCut* cut= (AliHBTKtCut*)FindCut(kHbtPairCutPropKt);
if(cut) cut->SetRange(min,max);
else fCuts[fNCuts++] = new AliHBTKtCut(min,max);
}
/**********************************************************/
void AliHBTPairCut::SetKStarRange(Double_t min, Double_t max)
{
// set range of accepted KStar (?)
AliHBTKStarCut* cut= (AliHBTKStarCut*)FindCut(kHbtPairCutPropKStar);
if(cut) cut->SetRange(min,max);
else fCuts[fNCuts++] = new AliHBTKStarCut(min,max);
}
/**********************************************************/
AliHbtBasePairCut* AliHBTPairCut::FindCut(AliHBTPairCutProperty property)
{
// Find the cut corresponding to "property"
for (Int_t i = 0;i<fNCuts;i++)
{
if (fCuts[i]->GetProperty() == property)
return fCuts[i]; //we found the cut we were searching for
}
return 0x0; //we did not found this cut
}
/**********************************************************/
void AliHBTPairCut::Streamer(TBuffer &b)
{
// Stream all objects in the array to or from the I/O buffer.
UInt_t R__s, R__c;
if (b.IsReading())
{
Version_t v = b.ReadVersion(&R__s, &R__c);
if (v > -1)
{
delete fFirstPartCut;
delete fSecondPartCut;
fFirstPartCut = 0x0;
fSecondPartCut = 0x0;
TObject::Streamer(b);
b >> fFirstPartCut;
b >> fSecondPartCut;
b >> fNCuts;
for (Int_t i = 0;i<fNCuts;i++)
{
b >> fCuts[i];
}
}
b.CheckByteCount(R__s, R__c,AliHBTPairCut::IsA());
}
else
{
R__c = b.WriteVersion(AliHBTPairCut::IsA(), kTRUE);
TObject::Streamer(b);
b << fFirstPartCut;
b << fSecondPartCut;
b << fNCuts;
for (Int_t i = 0;i<fNCuts;i++)
{
b << fCuts[i];
}
b.SetByteCount(R__c, kTRUE);
}
}
ClassImp(AliHBTEmptyPairCut)
void AliHBTEmptyPairCut::Streamer(TBuffer &b)
{
//streamer for empty pair cut
AliHBTPairCut::Streamer(b);
}
ClassImp(AliHbtBasePairCut)
ClassImp(AliHBTQInvCut)
ClassImp(AliHBTKtCut)
ClassImp(AliHBTQSideCMSLCCut)
ClassImp(AliHBTQOutCMSLCCut)
ClassImp(AliHBTQLongCMSLCCut)
<commit_msg>Bug correction<commit_after>/* $Id$ */
//-------------------------------------------------------------------
// Class AliHBTPairCut:
// implements cut on the pair of particles
// more info: http://alisoft.cern.ch/people/skowron/analyzer/index.html
// Author: [email protected]
//-------------------------------------------------------------------
#include "AliHBTPairCut.h"
#include "AliHBTPair.h"
#include "AliHBTParticleCut.h"
ClassImp(AliHBTPairCut)
const Int_t AliHBTPairCut::fgkMaxCuts = 50;
/**********************************************************/
AliHBTPairCut::AliHBTPairCut():
fNCuts(0)
{
//constructor
fFirstPartCut = new AliHBTEmptyParticleCut(); //empty cuts
fSecondPartCut= new AliHBTEmptyParticleCut(); //empty cuts
fCuts = new AliHbtBasePairCut*[fgkMaxCuts];
}
/**********************************************************/
AliHBTPairCut::AliHBTPairCut(const AliHBTPairCut& in):
TNamed(in)
{
//copy constructor
fCuts = new AliHbtBasePairCut*[fgkMaxCuts];
fNCuts = in.fNCuts;
fFirstPartCut = (AliHBTParticleCut*)in.fFirstPartCut->Clone();
fSecondPartCut = (AliHBTParticleCut*)in.fSecondPartCut->Clone();
for (Int_t i = 0;i<fNCuts;i++)
{
fCuts[i] = (AliHbtBasePairCut*)in.fCuts[i]->Clone();//create new object (clone) and rember pointer to it
}
}
/**********************************************************/
AliHBTPairCut& AliHBTPairCut::operator=(const AliHBTPairCut& in)
{
//assignment operator
fCuts = new AliHbtBasePairCut*[fgkMaxCuts];
fNCuts = in.fNCuts;
fFirstPartCut = (AliHBTParticleCut*)in.fFirstPartCut->Clone();
fSecondPartCut = (AliHBTParticleCut*)in.fSecondPartCut->Clone();
for (Int_t i = 0;i<fNCuts;i++)
{
fCuts[i] = (AliHbtBasePairCut*)in.fCuts[i]->Clone();//create new object (clone) and rember pointer to it
}
return * this;
}
/**********************************************************/
AliHBTPairCut::~AliHBTPairCut()
{
//destructor
if (fFirstPartCut != fSecondPartCut)
{
delete fSecondPartCut;
}
delete fFirstPartCut;
for (Int_t i = 0;i<fNCuts;i++)
{
delete fCuts[i];
}
delete []fCuts;
}
/**********************************************************/
/**********************************************************/
void AliHBTPairCut::AddBasePairCut(AliHbtBasePairCut* basecut)
{
//adds the base pair cut (cut on one value)
if (!basecut) return;
if( fNCuts == (fgkMaxCuts-1) )
{
Warning("AddBasePairCut","Not enough place for another cut");
return;
}
fCuts[fNCuts++]=basecut;
}
/**********************************************************/
Bool_t AliHBTPairCut::Pass(AliHBTPair* pair) const
{
//methods which checks if given pair meets all criteria of the cut
//if it meets returns FALSE
//if NOT returns TRUE
if(!pair)
{
Warning("Pass","No Pasaran! We never accept NULL pointers");
return kTRUE;
}
//check particle's cuts
if( ( fFirstPartCut->Pass( pair->Particle1()) ) ||
( fSecondPartCut->Pass(pair->Particle2()) ) )
{
return kTRUE;
}
return PassPairProp(pair);
}
/**********************************************************/
Bool_t AliHBTPairCut::PassPairProp(AliHBTPair* pair) const
{
//methods which checks if given pair meets all criteria of the cut
//if it meets returns FALSE
//if NOT returns TRUE
//examine all base pair cuts
for (Int_t i = 0;i<fNCuts;i++)
{
if ( (fCuts[i]->Pass(pair)) ) return kTRUE; //if one of the cuts reject, then reject
}
return kFALSE;
}
/**********************************************************/
void AliHBTPairCut::SetFirstPartCut(AliHBTParticleCut* cut)
{
// set cut for the first particle
if(!cut)
{
Error("SetFirstPartCut","argument is NULL");
return;
}
delete fFirstPartCut;
fFirstPartCut = (AliHBTParticleCut*)cut->Clone();
}
/**********************************************************/
void AliHBTPairCut::SetSecondPartCut(AliHBTParticleCut* cut)
{
// set cut for the second particle
if(!cut)
{
Error("SetSecondPartCut","argument is NULL");
return;
}
delete fSecondPartCut;
fSecondPartCut = (AliHBTParticleCut*)cut->Clone();
}
/**********************************************************/
void AliHBTPairCut::SetPartCut(AliHBTParticleCut* cut)
{
//sets the the same cut on both particles
if(!cut)
{
Error("SetFirstPartCut","argument is NULL");
return;
}
if (fFirstPartCut == fSecondPartCut) fSecondPartCut = 0x0;
delete fFirstPartCut;
fFirstPartCut = (AliHBTParticleCut*)cut->Clone();
delete fSecondPartCut; //even if null should not be harmful
fSecondPartCut = fFirstPartCut;
}
/**********************************************************/
void AliHBTPairCut::SetQInvRange(Double_t min, Double_t max)
{
// set range of accepted invariant masses
AliHBTQInvCut* cut= (AliHBTQInvCut*)FindCut(kHbtPairCutPropQInv);
if(cut) cut->SetRange(min,max);
else fCuts[fNCuts++] = new AliHBTQInvCut(min,max);
}
/**********************************************************/
void AliHBTPairCut::SetQOutCMSLRange(Double_t min, Double_t max)
{
// set range of accepted QOut in CMS
AliHBTQOutCMSLCCut* cut= (AliHBTQOutCMSLCCut*)FindCut(kHbtPairCutPropQOutCMSLC);
if(cut) cut->SetRange(min,max);
else fCuts[fNCuts++] = new AliHBTQOutCMSLCCut(min,max);
}
/**********************************************************/
void AliHBTPairCut::SetQSideCMSLRange(Double_t min, Double_t max)
{
// set range of accepted QSide in CMS
AliHBTQSideCMSLCCut* cut= (AliHBTQSideCMSLCCut*)FindCut(kHbtPairCutPropQSideCMSLC);
if(cut) cut->SetRange(min,max);
else fCuts[fNCuts++] = new AliHBTQSideCMSLCCut(min,max);
}
/**********************************************************/
void AliHBTPairCut::SetQLongCMSLRange(Double_t min, Double_t max)
{
// set range of accepted QLong in CMS
AliHBTQLongCMSLCCut* cut= (AliHBTQLongCMSLCCut*)FindCut(kHbtPairCutPropQLongCMSLC);
if(cut) cut->SetRange(min,max);
else fCuts[fNCuts++] = new AliHBTQLongCMSLCCut(min,max);
}
/**********************************************************/
void AliHBTPairCut::SetKtRange(Double_t min, Double_t max)
{
// set range of accepted Kt (?)
AliHBTKtCut* cut= (AliHBTKtCut*)FindCut(kHbtPairCutPropKt);
if(cut) cut->SetRange(min,max);
else fCuts[fNCuts++] = new AliHBTKtCut(min,max);
}
/**********************************************************/
void AliHBTPairCut::SetKStarRange(Double_t min, Double_t max)
{
// set range of accepted KStar (?)
AliHBTKStarCut* cut= (AliHBTKStarCut*)FindCut(kHbtPairCutPropKStar);
if(cut) cut->SetRange(min,max);
else fCuts[fNCuts++] = new AliHBTKStarCut(min,max);
}
/**********************************************************/
AliHbtBasePairCut* AliHBTPairCut::FindCut(AliHBTPairCutProperty property)
{
// Find the cut corresponding to "property"
for (Int_t i = 0;i<fNCuts;i++)
{
if (fCuts[i]->GetProperty() == property)
return fCuts[i]; //we found the cut we were searching for
}
return 0x0; //we did not found this cut
}
/**********************************************************/
void AliHBTPairCut::Streamer(TBuffer &b)
{
// Stream all objects in the array to or from the I/O buffer.
UInt_t R__s, R__c;
if (b.IsReading())
{
Version_t v = b.ReadVersion(&R__s, &R__c);
if (v > -1)
{
delete fFirstPartCut;
delete fSecondPartCut;
fFirstPartCut = 0x0;
fSecondPartCut = 0x0;
TObject::Streamer(b);
b >> fFirstPartCut;
b >> fSecondPartCut;
b >> fNCuts;
for (Int_t i = 0;i<fNCuts;i++)
{
b >> fCuts[i];
}
}
b.CheckByteCount(R__s, R__c,AliHBTPairCut::IsA());
}
else
{
R__c = b.WriteVersion(AliHBTPairCut::IsA(), kTRUE);
TObject::Streamer(b);
// printf("Streamer Cut 1 %#x Cut 2 %#x\n",fFirstPartCut,fSecondPartCut);
// this->Dump();
// fFirstPartCut->Dump();
b << fFirstPartCut;
b << fSecondPartCut;
b << fNCuts;
for (Int_t i = 0;i<fNCuts;i++)
{
b << fCuts[i];
}
b.SetByteCount(R__c, kTRUE);
}
}
ClassImp(AliHBTEmptyPairCut)
void AliHBTEmptyPairCut::Streamer(TBuffer &b)
{
//streamer for empty pair cut
AliHBTPairCut::Streamer(b);
}
ClassImp(AliHbtBasePairCut)
ClassImp(AliHBTQInvCut)
ClassImp(AliHBTKtCut)
ClassImp(AliHBTQSideCMSLCCut)
ClassImp(AliHBTQOutCMSLCCut)
ClassImp(AliHBTQLongCMSLCCut)
<|endoftext|> |
<commit_before>
#include "BinaryHeap.h"
#include <fstream>
// initialize the variables
BinaryHeap :: BinaryHeap()
{
root = NULL;
lastElement = NULL;
}
// clear the memory
BinaryHeap :: ~BinaryHeap()
{
clear(root);
}
// make a new heap
void BinaryHeap :: makeHeap()
{
if(root!=NULL)
clear(root);
root = NULL;
lastElement = NULL;
}
// insert the given key into the heap
Location BinaryHeap :: insertKey(Priority key)
{
BinaryNode *z,*x=new BinaryNode();
x->key=key;
setLocation(x,x->key);
// make the fields null of new node
x->leftChild=x->rightChild=NULL;
x->leftSibling=x->rightSibling=NULL;
//check root is null or not??
if(root==NULL){
root=x;
lastElement=x;
x->parent=NULL;
}
else{
if(lastElement==root) // 2nd element inserted in the heap
{
root->leftChild=x;
x->parent=root;
} //add a node in the right child of a node
else if(lastElement->parent->leftChild==lastElement)
{
lastElement->parent->rightChild=x;
x->parent=lastElement->parent;
x->leftSibling=lastElement;
lastElement->rightSibling=x;
}
//add a node in the left child of a node
else if(lastElement->parent->rightChild==lastElement){
if(lastElement->parent->rightSibling==NULL)
{
z=lastElement;
while(z->leftSibling!=NULL)
z=z->leftSibling;
z->leftChild=x;
x->parent=z;
}
else
{
lastElement->parent->rightSibling->leftChild=x;
x->parent=lastElement->parent->rightSibling;
x->leftSibling=lastElement;
lastElement->rightSibling=x;
}
}
}
lastElement=x;
Priority data;
//heapify the heap
while(x!=NULL){
if(x!=root && x->parent->key > x->key )
{
data=x->key;
x->key=x->parent->key;
setLocation(x,x->key);
x->parent->key=data;
setLocation(x->parent,x->parent->key);
x=x->parent;
}
else
x=NULL;
}
return x;
}
// delete the given node from the heap
int BinaryHeap :: deleteKey(Location nodeAddress)
{
BinaryNode *x,*z,*y=(BinaryNode*)nodeAddress;
Priority datakey =lastElement->key;
x=lastElement;
//updation of pointers
if(root==NULL || y==NULL )
return -1;
else if(y==root)
root=lastElement=NULL;
else if(x->parent->rightChild==x){
x->parent->rightChild=NULL;
lastElement=x->parent->leftChild;
x->leftSibling->rightSibling=NULL;
}
else if(x->parent->leftChild==x)
{
x->parent->leftChild=NULL;
if(x->parent==root)
lastElement=root;
else
{
if(x->parent->leftSibling==NULL)
{
z=x->parent;
while(z->rightSibling!=NULL)
{
z=z->rightSibling;
}
lastElement=z;
}
else{
lastElement=x->parent->leftSibling->rightChild;
x->parent->leftSibling->rightChild->rightSibling=NULL;
}
}
}
keyToAddress.erase(x->key);
delete x; //delete the node
// heapify the given heap
if(y->key < datakey)
increaseKey(y,datakey);
else if(y->key > datakey)
decreaseKey(y,datakey);
return 0;
}
// delete the node which contain the minimum value and return the minimum value
Priority BinaryHeap :: extractMin()
{
Priority datakey =root->key;
if(root==NULL)
{
cout<<"INVALID OPERATION\n";
return -1;
}
else{
deleteKey(root);
}
return datakey;
}
// return the minimum value of the heap
Priority BinaryHeap :: findMin()
{
Priority x=0;
if(root!=NULL) //check root is null or not ??
x=root->key;
return x;
}
// increase the key of given node by the given value
bool BinaryHeap :: increaseKey(Location nodeAddress, Priority newKey)
{
Priority data=newKey;
BinaryNode *x,*y=(BinaryNode*)nodeAddress;
x=y;
if(y==NULL || (newKey <= y->key)) //check for a invalid input
return -1;
else{
//update the given node by that key
y->key=newKey;
setLocation(y,y->key);
//check which key has to be change right or left ??
if(y->leftChild!=NULL && y->leftChild->key < newKey){
data=y->leftChild->key;
x=y->leftChild;
}
if(y->rightChild!=NULL && (y->rightChild->key < newKey)){
if(data >y->rightChild->key)
{
data=y->rightChild->key;
x=y->rightChild;
}
}
//modify the heap according to respective changes
if(y->leftChild==x){
y->key=y->leftChild->key ;
setLocation(y,y->key);
increaseKey(y->leftChild,newKey);
}
else if(y->rightChild==x){
y->key=y->rightChild->key ;
setLocation(y,y->key);
increaseKey(y->rightChild,newKey);
}
}
return 0;
}
// decrease the given key by a given value
bool BinaryHeap :: decreaseKey(Location nodeAddress, Priority newKey)
{
BinaryNode *y=(BinaryNode*)nodeAddress;
if(y==NULL || (newKey >= y->key)) //check for a invalid input
return false;
else{
y->key=newKey; //change the key in the heap
setLocation(y,y->key);
// update the parent if required
if(y->parent!=NULL && y->parent->key > newKey){
y->key=y->parent->key;
setLocation(y,y->key);
// recursive call on the parent to trill up the key upto the root
decreaseKey(y->parent,newKey);
}
}
return true;
}
//function to write the nodes to the output file..
bool BinaryHeap :: displayHeap(char* fileName)
{
/*BinaryNode *x,*z;
x=root;
while(x!=NULL)
{
cout<<x->key << " ";
if(x->rightSibling==NULL){
cout<<endl;
z=x;
while(z->leftSibling!=NULL)
z=z->leftSibling;
x=z->leftChild;
}
else
x=x->rightSibling;
}*/
fstream outFile;
char errorMsg[100];
outFile.open(fileName,fstream::out);
if (!outFile.is_open())
{
sprintf(errorMsg,"Error while opening %s:",fileName);
perror(errorMsg);
return false;
}
BinaryNode * root1 = root;
outFile<<"/* Generated by Heap Program */"<<endl;
outFile<<"digraph binaryHeap {"<<endl;
printDOT(root1,outFile);
outFile<<"}"<<endl;
outFile.close();
return true;
}
void BinaryHeap::printDOT(BinaryNode *root1,fstream& out)
{
BinaryNode * ptr;
if(root1 == NULL)
return;
ptr = root1->leftChild;
if(ptr != NULL)
{
//printing children
out<<" "<<root1->key<<" -> {";
out<<ptr->key<<" ; ";
out<<"}"<<endl;
printDOT(ptr,out);
}
ptr = root1->rightChild;
if(ptr != NULL)
{
//printing children
out<<" "<<root1->key<<" -> {";
out<<ptr->key<<" ; ";
out<<"}"<<endl;
printDOT(ptr,out);
}
}
// clear all the present nodes in the tree
void BinaryHeap::clear(BinaryNode* listRoot)
{
if(listRoot == NULL) return;
BinaryNode* ptr = listRoot;
clear(ptr->leftChild); //call on the left child
clear(ptr->rightChild); //call on the right child
delete ptr;
}
<commit_msg>Binary works - Chirag<commit_after>
#include "BinaryHeap.h"
#include <fstream>
// initialize the variables
BinaryHeap :: BinaryHeap()
{
root = NULL;
lastElement = NULL;
}
// clear the memory
BinaryHeap :: ~BinaryHeap()
{
clear(root);
}
// make a new heap
void BinaryHeap :: makeHeap()
{
if(root!=NULL)
clear(root);
root = NULL;
lastElement = NULL;
}
// insert the given key into the heap
Location BinaryHeap :: insertKey(Priority key)
{
BinaryNode *z,*x=new BinaryNode();
x->key=key;
setLocation(x,x->key);
// make the fields null of new node
x->leftChild=x->rightChild=NULL;
x->leftSibling=x->rightSibling=NULL;
//check root is null or not??
if(root==NULL){
root=x;
lastElement=x;
x->parent=NULL;
}
else{
if(lastElement==root) // 2nd element inserted in the heap
{
root->leftChild=x;
x->parent=root;
} //add a node in the right child of a node
else if(lastElement->parent->leftChild==lastElement)
{
lastElement->parent->rightChild=x;
x->parent=lastElement->parent;
x->leftSibling=lastElement;
lastElement->rightSibling=x;
}
//add a node in the left child of a node
else if(lastElement->parent->rightChild==lastElement){
if(lastElement->parent->rightSibling==NULL)
{
z=lastElement;
while(z->leftSibling!=NULL)
z=z->leftSibling;
z->leftChild=x;
x->parent=z;
}
else
{
lastElement->parent->rightSibling->leftChild=x;
x->parent=lastElement->parent->rightSibling;
x->leftSibling=lastElement;
lastElement->rightSibling=x;
}
}
}
lastElement=x;
Priority data;
//heapify the heap
while(x!=NULL){
if(x!=root && x->parent->key > x->key )
{
data=x->key;
x->key=x->parent->key;
setLocation(x,x->key);
x->parent->key=data;
setLocation(x->parent,x->parent->key);
x=x->parent;
}
else
x=NULL;
}
return x;
}
// delete the given node from the heap
int BinaryHeap :: deleteKey(Location nodeAddress)
{
BinaryNode *x,*z,*y=(BinaryNode*)nodeAddress;
Priority datakey =lastElement->key;
x=lastElement;
//updation of pointers
if(root==NULL || y==NULL )
return -1;
else if(y==root && y->leftChild==NULL && y->rightChild==NULL)
root=lastElement=NULL;
else if(x->parent->rightChild==x){
x->parent->rightChild=NULL;
lastElement=x->parent->leftChild;
x->leftSibling->rightSibling=NULL;
}
else if(x->parent->leftChild==x)
{
x->parent->leftChild=NULL;
if(x->parent==root)
lastElement=root;
else
{
if(x->parent->leftSibling==NULL)
{
z=x->parent;
while(z->rightSibling!=NULL)
{
z=z->rightSibling;
}
lastElement=z;
}
else{
lastElement=x->parent->leftSibling->rightChild;
x->parent->leftSibling->rightChild->rightSibling=NULL;
}
}
}
keyToAddress.erase(x->key);
delete x; //delete the node
// heapify the given heap
if(y->key < datakey)
increaseKey(y,datakey);
else if(y->key > datakey)
decreaseKey(y,datakey);
return 0;
}
// delete the node which contain the minimum value and return the minimum value
Priority BinaryHeap :: extractMin()
{
Priority datakey =root->key;
if(root==NULL)
{
cout<<"INVALID OPERATION\n";
return -1;
}
else{
deleteKey(root);
}
return datakey;
}
// return the minimum value of the heap
Priority BinaryHeap :: findMin()
{
Priority x=0;
if(root!=NULL) //check root is null or not ??
x=root->key;
return x;
}
// increase the key of given node by the given value
bool BinaryHeap :: increaseKey(Location nodeAddress, Priority newKey)
{
Priority data=newKey;
BinaryNode *x,*y=(BinaryNode*)nodeAddress;
x=y;
if(y==NULL || (newKey <= y->key)) //check for a invalid input
return -1;
else{
//update the given node by that key
y->key=newKey;
setLocation(y,y->key);
//check which key has to be change right or left ??
if(y->leftChild!=NULL && y->leftChild->key < newKey){
data=y->leftChild->key;
x=y->leftChild;
}
if(y->rightChild!=NULL && (y->rightChild->key < newKey)){
if(data >y->rightChild->key)
{
data=y->rightChild->key;
x=y->rightChild;
}
}
//modify the heap according to respective changes
if(y->leftChild==x){
y->key=y->leftChild->key ;
setLocation(y,y->key);
increaseKey(y->leftChild,newKey);
}
else if(y->rightChild==x){
y->key=y->rightChild->key ;
setLocation(y,y->key);
increaseKey(y->rightChild,newKey);
}
}
return 0;
}
// decrease the given key by a given value
bool BinaryHeap :: decreaseKey(Location nodeAddress, Priority newKey)
{
BinaryNode *y=(BinaryNode*)nodeAddress;
if(y==NULL || (newKey >= y->key)) //check for a invalid input
return false;
else{
y->key=newKey; //change the key in the heap
setLocation(y,y->key);
// update the parent if required
if(y->parent!=NULL && y->parent->key > newKey){
y->key=y->parent->key;
setLocation(y,y->key);
// recursive call on the parent to trill up the key upto the root
decreaseKey(y->parent,newKey);
}
}
return true;
}
//function to write the nodes to the output file..
bool BinaryHeap :: displayHeap(char* fileName)
{
/*BinaryNode *x,*z;
x=root;
while(x!=NULL)
{
cout<<x->key << " ";
if(x->rightSibling==NULL){
cout<<endl;
z=x;
while(z->leftSibling!=NULL)
z=z->leftSibling;
x=z->leftChild;
}
else
x=x->rightSibling;
}*/
fstream outFile;
char errorMsg[100];
outFile.open(fileName,fstream::out);
if (!outFile.is_open())
{
sprintf(errorMsg,"Error while opening %s:",fileName);
perror(errorMsg);
return false;
}
BinaryNode * root1 = root;
outFile<<"/* Generated by Heap Program */"<<endl;
outFile<<"digraph binaryHeap {"<<endl;
printDOT(root1,outFile);
outFile<<"}"<<endl;
outFile.close();
return true;
}
void BinaryHeap::printDOT(BinaryNode *root1,fstream& out)
{
BinaryNode * ptr;
if(root1 == NULL)
return;
ptr = root1->leftChild;
if(ptr != NULL)
{
//printing children
out<<" "<<root1->key<<" -> {";
out<<ptr->key<<" ; ";
out<<"}"<<endl;
printDOT(ptr,out);
}
ptr = root1->rightChild;
if(ptr != NULL)
{
//printing children
out<<" "<<root1->key<<" -> {";
out<<ptr->key<<" ; ";
out<<"}"<<endl;
printDOT(ptr,out);
}
}
// clear all the present nodes in the tree
void BinaryHeap::clear(BinaryNode* listRoot)
{
if(listRoot == NULL) return;
BinaryNode* ptr = listRoot;
clear(ptr->leftChild); //call on the left child
clear(ptr->rightChild); //call on the right child
delete ptr;
}
<|endoftext|> |
<commit_before>#include "hippomocks.h"
#include "yaffut.h"
class IA {
public:
virtual ~IA() {}
virtual void f() {}
virtual void g() = 0;
};
FUNC (checkBaseCase)
{
MockRepository mocks;
IA *iamock = mocks.InterfaceMock<IA>();
mocks.ExpectCall(iamock, &IA::f);
mocks.ExpectCall(iamock, &IA::g);
mocks.ReplayAll();
iamock->f();
iamock->g();
mocks.VerifyAll();
}
FUNC (checkMultiCall)
{
MockRepository mocks;
IA *iamock = mocks.InterfaceMock<IA>();
mocks.ExpectCall(iamock, &IA::f);
mocks.ExpectCall(iamock, &IA::g);
mocks.ExpectCall(iamock, &IA::f);
mocks.ReplayAll();
iamock->f();
iamock->g();
iamock->f();
mocks.VerifyAll();
}
FUNC (checkMultiCallNotCalled)
{
MockRepository mocks;
IA *iamock = mocks.InterfaceMock<IA>();
mocks.ExpectCall(iamock, &IA::f);
mocks.ExpectCall(iamock, &IA::g);
mocks.ExpectCall(iamock, &IA::f);
mocks.ReplayAll();
iamock->f();
iamock->g();
bool exceptionCaught = true;
try {
mocks.VerifyAll();
}
catch (ExpectationException &)
{
exceptionCaught = true;
}
CHECK(exceptionCaught);
}
FUNC (checkMultiCallWrongOrder)
{
MockRepository mocks;
IA *iamock = mocks.InterfaceMock<IA>();
mocks.ExpectCall(iamock, &IA::f);
mocks.ExpectCall(iamock, &IA::g);
mocks.ExpectCall(iamock, &IA::f);
mocks.ReplayAll();
iamock->f();
bool exceptionCaught = true;
try {
iamock->f();
}
catch (ExpectationException &)
{
exceptionCaught = true;
}
CHECK(exceptionCaught);
}
FUNC (checkExpectationsNotCompleted)
{
bool exceptionCaught = false;
MockRepository mocks;
IA *iamock = mocks.InterfaceMock<IA>();
mocks.ExpectCall(iamock, &IA::f);
mocks.ExpectCall(iamock, &IA::g);
mocks.ReplayAll();
iamock->f();
try {
mocks.VerifyAll();
}
catch (ExpectationException &)
{
exceptionCaught = true;
}
CHECK(exceptionCaught);
}
FUNC (checkOvercompleteExpectations)
{
MockRepository mocks;
IA *iamock = mocks.InterfaceMock<IA>();
mocks.ExpectCall(iamock, &IA::f);
mocks.ExpectCall(iamock, &IA::g);
mocks.ReplayAll();
iamock->f();
iamock->g();
bool exceptionCaught = true;
try {
iamock->f();
}
catch (ExpectationException &)
{
exceptionCaught = true;
}
CHECK(exceptionCaught);
}
FUNC (checkExpectationsAreInOrder)
{
MockRepository mocks;
IA *iamock = mocks.InterfaceMock<IA>();
mocks.ExpectCall(iamock, &IA::f);
mocks.ExpectCall(iamock, &IA::g);
mocks.ReplayAll();
bool exceptionCaught = true;
try {
iamock->g();
}
catch (ExpectationException &)
{
exceptionCaught = true;
}
CHECK(exceptionCaught);
}
<commit_msg>Fix unit test "bool exceptionCaught = true;"<commit_after>#include "hippomocks.h"
#include "yaffut.h"
class IA {
public:
virtual ~IA() {}
virtual void f() {}
virtual void g() = 0;
};
FUNC (checkBaseCase)
{
MockRepository mocks;
IA *iamock = mocks.InterfaceMock<IA>();
mocks.ExpectCall(iamock, &IA::f);
mocks.ExpectCall(iamock, &IA::g);
mocks.ReplayAll();
iamock->f();
iamock->g();
mocks.VerifyAll();
}
FUNC (checkMultiCall)
{
MockRepository mocks;
IA *iamock = mocks.InterfaceMock<IA>();
mocks.ExpectCall(iamock, &IA::f);
mocks.ExpectCall(iamock, &IA::g);
mocks.ExpectCall(iamock, &IA::f);
mocks.ReplayAll();
iamock->f();
iamock->g();
iamock->f();
mocks.VerifyAll();
}
FUNC (checkMultiCallNotCalled)
{
MockRepository mocks;
IA *iamock = mocks.InterfaceMock<IA>();
mocks.ExpectCall(iamock, &IA::f);
mocks.ExpectCall(iamock, &IA::g);
mocks.ExpectCall(iamock, &IA::f);
mocks.ReplayAll();
iamock->f();
iamock->g();
bool exceptionCaught = false;
try {
mocks.VerifyAll();
}
catch (ExpectationException &)
{
exceptionCaught = true;
}
CHECK(exceptionCaught);
}
FUNC (checkMultiCallWrongOrder)
{
MockRepository mocks;
IA *iamock = mocks.InterfaceMock<IA>();
mocks.ExpectCall(iamock, &IA::f);
mocks.ExpectCall(iamock, &IA::g);
mocks.ExpectCall(iamock, &IA::f);
mocks.ReplayAll();
iamock->f();
bool exceptionCaught = false;
try {
iamock->f();
}
catch (ExpectationException &)
{
exceptionCaught = true;
}
CHECK(exceptionCaught);
}
FUNC (checkExpectationsNotCompleted)
{
bool exceptionCaught = false;
MockRepository mocks;
IA *iamock = mocks.InterfaceMock<IA>();
mocks.ExpectCall(iamock, &IA::f);
mocks.ExpectCall(iamock, &IA::g);
mocks.ReplayAll();
iamock->f();
try {
mocks.VerifyAll();
}
catch (ExpectationException &)
{
exceptionCaught = true;
}
CHECK(exceptionCaught);
}
FUNC (checkOvercompleteExpectations)
{
MockRepository mocks;
IA *iamock = mocks.InterfaceMock<IA>();
mocks.ExpectCall(iamock, &IA::f);
mocks.ExpectCall(iamock, &IA::g);
mocks.ReplayAll();
iamock->f();
iamock->g();
bool exceptionCaught = false;
try {
iamock->f();
}
catch (ExpectationException &)
{
exceptionCaught = true;
}
CHECK(exceptionCaught);
}
FUNC (checkExpectationsAreInOrder)
{
MockRepository mocks;
IA *iamock = mocks.InterfaceMock<IA>();
mocks.ExpectCall(iamock, &IA::f);
mocks.ExpectCall(iamock, &IA::g);
mocks.ReplayAll();
bool exceptionCaught = false;
try {
iamock->g();
}
catch (ExpectationException &)
{
exceptionCaught = true;
}
CHECK(exceptionCaught);
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include "Ndbcntr.hpp"
#define arrayLength(x) sizeof(x)/sizeof(x[0])
// SYSTAB_0
static const Ndbcntr::SysColumn
column_SYSTAB_0[] = {
{ 0, "SYSKEY_0",
DictTabInfo::ExtUnsigned, 1,
true, false
},
{ 1, "NEXTID",
DictTabInfo::ExtBigunsigned, 1,
false, false
}
};
const Ndbcntr::SysTable
Ndbcntr::g_sysTable_SYSTAB_0 = {
"sys/def/SYSTAB_0",
arrayLength(column_SYSTAB_0), column_SYSTAB_0,
DictTabInfo::SystemTable,
DictTabInfo::AllNodesSmallTable,
true, ~0
};
// NDB$EVENTS_0
static const Ndbcntr::SysColumn
column_NDBEVENTS_0[] = {
{ 0, "NAME",
DictTabInfo::ExtChar, MAX_TAB_NAME_SIZE,
true, false
},
{ 1, "EVENT_TYPE",
DictTabInfo::ExtUnsigned, 1,
false, false
},
{ 2, "TABLE_NAME",
DictTabInfo::ExtChar, MAX_TAB_NAME_SIZE,
false, false
},
{ 3, "ATTRIBUTE_MASK",
DictTabInfo::ExtUnsigned, MAXNROFATTRIBUTESINWORDS,
false, false
},
{ 4, "SUBID",
DictTabInfo::ExtUnsigned, 1,
false, false
},
{ 5, "SUBKEY",
DictTabInfo::ExtUnsigned, 1,
false, false
}
};
const Ndbcntr::SysTable
Ndbcntr::g_sysTable_NDBEVENTS_0 = {
"sys/def/NDB$EVENTS_0",
arrayLength(column_NDBEVENTS_0), column_NDBEVENTS_0,
DictTabInfo::SystemTable,
DictTabInfo::AllNodesSmallTable,
true, ~0
};
// all
const Ndbcntr::SysTable*
Ndbcntr::g_sysTableList[] = {
&g_sysTable_SYSTAB_0,
&g_sysTable_NDBEVENTS_0
};
//TODO Backup needs this info to allocate appropriate number of records
//BackupInit.cpp
const unsigned
Ndbcntr::g_sysTableCount = arrayLength(Ndbcntr::g_sysTableList);
<commit_msg>Fix event systable collation (binary)<commit_after>/* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include "Ndbcntr.hpp"
#define arrayLength(x) sizeof(x)/sizeof(x[0])
// SYSTAB_0
static const Ndbcntr::SysColumn
column_SYSTAB_0[] = {
{ 0, "SYSKEY_0",
DictTabInfo::ExtUnsigned, 1,
true, false
},
{ 1, "NEXTID",
DictTabInfo::ExtBigunsigned, 1,
false, false
}
};
const Ndbcntr::SysTable
Ndbcntr::g_sysTable_SYSTAB_0 = {
"sys/def/SYSTAB_0",
arrayLength(column_SYSTAB_0), column_SYSTAB_0,
DictTabInfo::SystemTable,
DictTabInfo::AllNodesSmallTable,
true, ~0
};
// NDB$EVENTS_0
static const Ndbcntr::SysColumn
column_NDBEVENTS_0[] = {
{ 0, "NAME",
DictTabInfo::ExtBinary, MAX_TAB_NAME_SIZE,
true, false
},
{ 1, "EVENT_TYPE",
DictTabInfo::ExtUnsigned, 1,
false, false
},
{ 2, "TABLE_NAME",
DictTabInfo::ExtBinary, MAX_TAB_NAME_SIZE,
false, false
},
{ 3, "ATTRIBUTE_MASK",
DictTabInfo::ExtUnsigned, MAXNROFATTRIBUTESINWORDS,
false, false
},
{ 4, "SUBID",
DictTabInfo::ExtUnsigned, 1,
false, false
},
{ 5, "SUBKEY",
DictTabInfo::ExtUnsigned, 1,
false, false
}
};
const Ndbcntr::SysTable
Ndbcntr::g_sysTable_NDBEVENTS_0 = {
"sys/def/NDB$EVENTS_0",
arrayLength(column_NDBEVENTS_0), column_NDBEVENTS_0,
DictTabInfo::SystemTable,
DictTabInfo::AllNodesSmallTable,
true, ~0
};
// all
const Ndbcntr::SysTable*
Ndbcntr::g_sysTableList[] = {
&g_sysTable_SYSTAB_0,
&g_sysTable_NDBEVENTS_0
};
//TODO Backup needs this info to allocate appropriate number of records
//BackupInit.cpp
const unsigned
Ndbcntr::g_sysTableCount = arrayLength(Ndbcntr::g_sysTableList);
<|endoftext|> |
<commit_before>// Homework3.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
time_t startTime = time(0);
class StopLight {
public:
StopLight(string direction) {
this->lightColor = "";
this->direction = direction;
}
StopLight(string color , string direction) {
this->lightColor = color;
this->direction = direction;
}
string getLightColor() {
return this->lightColor;
}
void setLightColor(string c) {
this->lightColor = c;
}
string getDirection() {
return this->direction;
}
void setNextLight(StopLight *nextLight) {
this->nextLight = nextLight;
}
void cycleLights() {
if(this->nextLight != NULL) {
this->nextLight->lightColor = "green";
this->nextLight->cycleLights();
}
}
private:
string lightColor;
StopLight *nextLight;
string direction;
};
int _tmain(int argc, _TCHAR* argv[])
{
StopLight north("red");
StopLight south("red");
StopLight east("red");
StopLight west("red");
north.setNextLight(&south);
south.setNextLight(&west);
west.setNextLight(&east);
east.setNextLight(NULL);
north.cycleLights();
cout << north.getLightColor() << endl;
cout << south.getLightColor() << endl;
cout << east.getLightColor() << endl;
cout << west.getLightColor() << endl;
return 0;
}
<commit_msg>StopLight class is almost done with the exception on yellow chaninging lights<commit_after>// Homework3.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
const int NUM_OF_LIGHTS = 4;
time_t startTime = time(0);
enum direction {
north = 0 , south = 1 , east = 2 , west = 3
};
class StopLight {
public:
StopLight(direction direction) {
this->lightColor = "";
this->direction = direction;
}
StopLight(string color , direction direction) {
this->lightColor = color;
this->direction = direction;
}
StopLight(string color , direction direction , StopLight *nextLight) {
this->lightColor = color;
this->direction = direction;
this->nextLight = nextLight;
}
string getLightColor() {
return this->lightColor;
}
void setLightColor(string c) {
this->lightColor = c;
}
direction getDirection() {
return this->direction;
}
void setNextLight(StopLight *nextLight) {
this->nextLight = nextLight;
}
void cycleLights() {
this->lightColor = this->lightColor == "red" ? "green" : "red";
/*switch(this->direction) {
case north:
case south:
this->lightColor = this->lightColor == "red" ? "green" : "red";
break;
case east:
case west:
this->lightColor = this->lightColor == "red" ? "green" : "red";
break;
}*/
if(this->nextLight != NULL) {
this->nextLight->cycleLights();
}
}
static void emergencyChange(direction dir , StopLight (&lights)[NUM_OF_LIGHTS]) {
for(int i = 0; i < NUM_OF_LIGHTS; i++) {
if(lights[i].direction == dir)
lights[i].setLightColor("green");
else
lights[i].setLightColor("red");
}
}
static void resetLights(StopLight (&lights)[NUM_OF_LIGHTS]) {
for(int i = 0 ; i < NUM_OF_LIGHTS ; i++) {
switch(lights[i].direction) {
case north:
case south:
lights[i].setLightColor("green");
break;
case east:
case west:
lights[i].setLightColor("red");
break;
default:
break;
}
}
}
void printLightColor() {
cout << this->lightColor;
}
private:
string lightColor;
StopLight *nextLight;
direction direction;
};
int _tmain(int argc , _TCHAR* argv []) {
StopLight lights [] = {
StopLight("green" , direction::north , &lights[1]) ,
StopLight("green" , direction::south , &lights[2]) ,
StopLight("red" , direction::west , &lights[3]) ,
StopLight("red" , direction::east , NULL)
};
lights[0].cycleLights();
StopLight::emergencyChange(direction::north , lights);
//StopLight::resetLights(lights);
for each (auto var in lights) {
cout << var.getDirection() << ": ";
var.printLightColor();
cout << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "GraphicsManager.h"
#include "../Logger.h"
#include "ScaleSystem.h"
#include "SpriteBatch.h"
#ifdef _WIN32
#include <Windows.h>
#endif
#ifdef DESKTOP
#include <wglext.h>
#endif
namespace star
{
GraphicsManager * GraphicsManager::mGraphicsManager = nullptr;
GraphicsManager::~GraphicsManager()
{
star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : Destructor"));
}
GraphicsManager::GraphicsManager() :
mScreenHeight(0),
mScreenWidth(0),
m_bHasWindowChanged(false),
mIsInitialized(false)
{
star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : Constructor"));
}
GraphicsManager * GraphicsManager::GetInstance()
{
if(mGraphicsManager == nullptr)
{
mGraphicsManager = new GraphicsManager();
}
return mGraphicsManager;
}
#ifdef DESKTOP
void GraphicsManager::Initialize(int32 screenWidth, int32 screenHeight)
{
if(!mIsInitialized)
{
mScreenWidth = screenWidth;
mScreenHeight = screenHeight;
glewInit();
star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : Initializing OpenGL Functors"));
if(!InitializeOpenGLFunctors())
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : Graphics card doesn't support VSync option!!"));
}
//Initializes base GL state.
// In a simple 2D game, we have control over the third
// dimension. So we do not really need a Z-buffer.
glDisable(GL_DEPTH_TEST);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
mIsInitialized = true;
}
}
#else
void GraphicsManager::Initialize(const android_app* pApplication)
{
if(!mIsInitialized)
{
star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : Initialize"));
EGLint lFormat, lNumConfigs, lErrorResult;
EGLConfig lConfig;
// Defines display requirements. 16bits mode here.
const EGLint lAttributes[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_BLUE_SIZE, 5, EGL_GREEN_SIZE, 6, EGL_RED_SIZE, 5,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_NONE
};
mDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (mDisplay == EGL_NO_DISPLAY)
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : No display found"));
return;
}
if (!eglInitialize(mDisplay, NULL, NULL))
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : Could not initialize display"));
return;
}
if(!eglChooseConfig(mDisplay, lAttributes, &lConfig, 1,&lNumConfigs) || (lNumConfigs <= 0))
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : No display config"));
return;
}
if (!eglGetConfigAttrib(mDisplay, lConfig,EGL_NATIVE_VISUAL_ID, &lFormat))
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : No config attributes"));
return;
}
ANativeWindow_setBuffersGeometry(pApplication->window, 0, 0,lFormat);
mSurface = eglCreateWindowSurface(mDisplay, lConfig, pApplication->window, NULL );
if (mSurface == EGL_NO_SURFACE)
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : Could not create surface"));
return;
}
EGLint contextAttrs[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
mContext = eglCreateContext(mDisplay, lConfig, EGL_NO_CONTEXT, contextAttrs);
if (mContext == EGL_NO_CONTEXT)
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : Could not create context"));
return;
}
if (!eglMakeCurrent(mDisplay, mSurface, mSurface, mContext)
|| !eglQuerySurface(mDisplay, mSurface, EGL_WIDTH, &mScreenWidth)
|| !eglQuerySurface(mDisplay, mSurface, EGL_HEIGHT, &mScreenHeight)
|| (mScreenWidth <= 0) || (mScreenHeight <= 0))
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : Could not activate display"));
return;
}
glViewport(0,0,mScreenWidth,mScreenHeight);
star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : Initialized"));
mIsInitialized = true;
}
}
void GraphicsManager::Destroy()
{
star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : Destroy"));
// Destroys OpenGL context.
if (mDisplay != EGL_NO_DISPLAY)
{
eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE,EGL_NO_CONTEXT);
if (mContext != EGL_NO_CONTEXT)
{
eglDestroyContext(mDisplay, mContext);
mContext = EGL_NO_CONTEXT;
}
if (mSurface != EGL_NO_SURFACE)
{
eglDestroySurface(mDisplay, mSurface);
mSurface = EGL_NO_SURFACE;
}
eglTerminate(mDisplay);
mDisplay = EGL_NO_DISPLAY;
star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : Destroyed"));
SpriteBatch::GetInstance()->CleanUp();
mIsInitialized = false;
}
}
#endif
void GraphicsManager::StartDraw()
{
//star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : StartDraw"));
glClearColor(1.0f, 0.0f, 0.0f, 1.0f); // Clear the background of our window to red
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); //Clear the colour buffer (more buffers later on)
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
/*
GLint temp[4];
glGetIntegerv(GL_VIEWPORT, temp);
tstringstream buffer;
buffer << _T("Viewport Width: ") << temp[2] << _T(" Viewport Height: ") << temp[3];
Logger::GetInstance()->Log(LogLevel::Info, buffer.str());*/
}
void GraphicsManager::StopDraw()
{
//star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : StopDraw"));
glDisable(GL_BLEND);
#ifdef ANDROID
if (eglSwapBuffers(mDisplay, mSurface) != EGL_TRUE)
{
return;
}
#endif
}
int32 GraphicsManager::GetWindowWidth() const
{
return mScreenWidth;
}
int32 GraphicsManager::GetWindowHeight() const
{
return mScreenHeight;
}
float GraphicsManager::GetWindowAspectRatio() const
{
return float(mScreenWidth) / float(mScreenHeight);
}
vec2 GraphicsManager::GetWindowResolution() const
{
return vec2(mScreenWidth, mScreenHeight);
}
void GraphicsManager::SetWindowDimensions(int32 width, int32 height)
{
//star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : SetWindowDimensions"));
mScreenWidth = width;
mScreenHeight = height;
glViewport(0,0,width, height);
ScaleSystem::GetInstance()->UpdateWorkingResolution();
}
void GraphicsManager::SetHasWindowChanged(bool isTrue)
{
//star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : SetWindowChanged"));
m_bHasWindowChanged = isTrue;
}
bool GraphicsManager::GetHasWindowChanged() const
{
return m_bHasWindowChanged;
}
#ifdef DESKTOP
bool GraphicsManager::WGLExtensionSupported(const char* extension_name)
{
// this is the pointer to the function which returns the pointer to string with the list of all wgl extensions
PFNWGLGETEXTENSIONSSTRINGEXTPROC _wglGetExtensionsStringEXT = NULL;
// determine pointer to wglGetExtensionsStringEXT function
_wglGetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC) wglGetProcAddress("wglGetExtensionsStringEXT");
if (strstr(_wglGetExtensionsStringEXT(), extension_name) == NULL)
{
// string was not found
return false;
}
// extension is supported
return true;
}
bool GraphicsManager::InitializeOpenGLFunctors()
{
PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL;
PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = NULL;
if (WGLExtensionSupported("WGL_EXT_swap_control"))
{
// Extension is supported, init pointers.
wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
// this is another function from WGL_EXT_swap_control extension
wglGetSwapIntervalEXT = (PFNWGLGETSWAPINTERVALEXTPROC) wglGetProcAddress("wglGetSwapIntervalEXT");
wglSwapIntervalEXT(1);
return true;
}
return false;
}
#endif
}
<commit_msg>hotfix border<commit_after>#include "GraphicsManager.h"
#include "../Logger.h"
#include "ScaleSystem.h"
#include "SpriteBatch.h"
#ifdef _WIN32
#include <Windows.h>
#endif
#ifdef DESKTOP
#include <wglext.h>
#endif
namespace star
{
GraphicsManager * GraphicsManager::mGraphicsManager = nullptr;
GraphicsManager::~GraphicsManager()
{
star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : Destructor"));
}
GraphicsManager::GraphicsManager() :
mScreenHeight(0),
mScreenWidth(0),
m_bHasWindowChanged(false),
mIsInitialized(false)
{
star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : Constructor"));
}
GraphicsManager * GraphicsManager::GetInstance()
{
if(mGraphicsManager == nullptr)
{
mGraphicsManager = new GraphicsManager();
}
return mGraphicsManager;
}
#ifdef DESKTOP
void GraphicsManager::Initialize(int32 screenWidth, int32 screenHeight)
{
if(!mIsInitialized)
{
mScreenWidth = screenWidth;
mScreenHeight = screenHeight;
glewInit();
star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : Initializing OpenGL Functors"));
if(!InitializeOpenGLFunctors())
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : Graphics card doesn't support VSync option!!"));
}
//Initializes base GL state.
// In a simple 2D game, we have control over the third
// dimension. So we do not really need a Z-buffer.
glDisable(GL_DEPTH_TEST);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
mIsInitialized = true;
}
}
#else
void GraphicsManager::Initialize(const android_app* pApplication)
{
if(!mIsInitialized)
{
star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : Initialize"));
EGLint lFormat, lNumConfigs, lErrorResult;
EGLConfig lConfig;
// Defines display requirements. 16bits mode here.
const EGLint lAttributes[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_BLUE_SIZE, 5, EGL_GREEN_SIZE, 6, EGL_RED_SIZE, 5,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_NONE
};
mDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (mDisplay == EGL_NO_DISPLAY)
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : No display found"));
return;
}
if (!eglInitialize(mDisplay, NULL, NULL))
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : Could not initialize display"));
return;
}
if(!eglChooseConfig(mDisplay, lAttributes, &lConfig, 1,&lNumConfigs) || (lNumConfigs <= 0))
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : No display config"));
return;
}
if (!eglGetConfigAttrib(mDisplay, lConfig,EGL_NATIVE_VISUAL_ID, &lFormat))
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : No config attributes"));
return;
}
ANativeWindow_setBuffersGeometry(pApplication->window, 0, 0,lFormat);
mSurface = eglCreateWindowSurface(mDisplay, lConfig, pApplication->window, NULL );
if (mSurface == EGL_NO_SURFACE)
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : Could not create surface"));
return;
}
EGLint contextAttrs[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
mContext = eglCreateContext(mDisplay, lConfig, EGL_NO_CONTEXT, contextAttrs);
if (mContext == EGL_NO_CONTEXT)
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : Could not create context"));
return;
}
if (!eglMakeCurrent(mDisplay, mSurface, mSurface, mContext)
|| !eglQuerySurface(mDisplay, mSurface, EGL_WIDTH, &mScreenWidth)
|| !eglQuerySurface(mDisplay, mSurface, EGL_HEIGHT, &mScreenHeight)
|| (mScreenWidth <= 0) || (mScreenHeight <= 0))
{
star::Logger::GetInstance()->Log(star::LogLevel::Error, _T("Graphics Manager : Could not activate display"));
return;
}
glViewport(0,0,mScreenWidth,mScreenHeight);
star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : Initialized"));
mIsInitialized = true;
}
}
void GraphicsManager::Destroy()
{
star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : Destroy"));
// Destroys OpenGL context.
if (mDisplay != EGL_NO_DISPLAY)
{
eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE,EGL_NO_CONTEXT);
if (mContext != EGL_NO_CONTEXT)
{
eglDestroyContext(mDisplay, mContext);
mContext = EGL_NO_CONTEXT;
}
if (mSurface != EGL_NO_SURFACE)
{
eglDestroySurface(mDisplay, mSurface);
mSurface = EGL_NO_SURFACE;
}
eglTerminate(mDisplay);
mDisplay = EGL_NO_DISPLAY;
star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : Destroyed"));
SpriteBatch::GetInstance()->CleanUp();
mIsInitialized = false;
}
}
#endif
void GraphicsManager::StartDraw()
{
#ifdef _WIN32
glViewport(0, 0, mScreenWidth, mScreenHeight);
#endif
//star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : StartDraw"));
glClearColor(1.0f, 0.0f, 0.0f, 1.0f); // Clear the background of our window to red
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); //Clear the colour buffer (more buffers later on)
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
/*
GLint temp[4];
glGetIntegerv(GL_VIEWPORT, temp);
tstringstream buffer;
buffer << _T("Viewport Width: ") << temp[2] << _T(" Viewport Height: ") << temp[3];
Logger::GetInstance()->Log(LogLevel::Info, buffer.str());*/
}
void GraphicsManager::StopDraw()
{
//star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : StopDraw"));
glDisable(GL_BLEND);
#ifdef ANDROID
if (eglSwapBuffers(mDisplay, mSurface) != EGL_TRUE)
{
return;
}
#endif
}
int32 GraphicsManager::GetWindowWidth() const
{
return mScreenWidth;
}
int32 GraphicsManager::GetWindowHeight() const
{
return mScreenHeight;
}
float GraphicsManager::GetWindowAspectRatio() const
{
return float(mScreenWidth) / float(mScreenHeight);
}
vec2 GraphicsManager::GetWindowResolution() const
{
return vec2(mScreenWidth, mScreenHeight);
}
void GraphicsManager::SetWindowDimensions(int32 width, int32 height)
{
//star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : SetWindowDimensions"));
mScreenWidth = width;
mScreenHeight = height;
glViewport(0,0,width, height);
ScaleSystem::GetInstance()->UpdateWorkingResolution();
}
void GraphicsManager::SetHasWindowChanged(bool isTrue)
{
//star::Logger::GetInstance()->Log(star::LogLevel::Info, _T("Graphics Manager : SetWindowChanged"));
m_bHasWindowChanged = isTrue;
}
bool GraphicsManager::GetHasWindowChanged() const
{
return m_bHasWindowChanged;
}
#ifdef DESKTOP
bool GraphicsManager::WGLExtensionSupported(const char* extension_name)
{
// this is the pointer to the function which returns the pointer to string with the list of all wgl extensions
PFNWGLGETEXTENSIONSSTRINGEXTPROC _wglGetExtensionsStringEXT = NULL;
// determine pointer to wglGetExtensionsStringEXT function
_wglGetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC) wglGetProcAddress("wglGetExtensionsStringEXT");
if (strstr(_wglGetExtensionsStringEXT(), extension_name) == NULL)
{
// string was not found
return false;
}
// extension is supported
return true;
}
bool GraphicsManager::InitializeOpenGLFunctors()
{
PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL;
PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = NULL;
if (WGLExtensionSupported("WGL_EXT_swap_control"))
{
// Extension is supported, init pointers.
wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
// this is another function from WGL_EXT_swap_control extension
wglGetSwapIntervalEXT = (PFNWGLGETSWAPINTERVALEXTPROC) wglGetProcAddress("wglGetSwapIntervalEXT");
wglSwapIntervalEXT(1);
return true;
}
return false;
}
#endif
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/canbus/vehicle/lincoln/protocol/steering_65.h"
#include "gtest/gtest.h"
namespace apollo {
namespace canbus {
namespace lincoln {
TEST(Steering65Test, General) {
uint8_t data = 0x01;
int32_t length = 8;
ChassisDetail cd;
Steering65 steering;
steering.Parse(&data, length, &cd);
EXPECT_FALSE(cd.eps().steering_enabled());
}
} // namespace lincoln
} // namespace apollo
} // namespace canbus
<commit_msg>fixed data issue in steering_65_test<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/canbus/vehicle/lincoln/protocol/steering_65.h"
#include "gtest/gtest.h"
namespace apollo {
namespace canbus {
namespace lincoln {
TEST(Steering65Test, General) {
uint8_t data[8] = {0x67, 0x62, 0x63, 0x64, 0x51, 0x52, 0x53, 0x54};
int32_t length = 8;
ChassisDetail cd;
Steering65 steering;
steering.Parse(data, length, &cd);
EXPECT_FALSE(cd.eps().steering_enabled());
EXPECT_TRUE(cd.vehicle_spd().is_vehicle_spd_valid());
EXPECT_DOUBLE_EQ(cd.vehicle_spd().vehicle_spd(), 58.536111111111111);
EXPECT_TRUE(cd.eps().is_steering_angle_valid());
EXPECT_DOUBLE_EQ(cd.eps().steering_angle(), 2519.1);
EXPECT_DOUBLE_EQ(cd.eps().steering_angle_cmd(), 2569.9);
EXPECT_DOUBLE_EQ(cd.eps().vehicle_speed(), 58.536111111111111);
EXPECT_DOUBLE_EQ(cd.eps().epas_torque(), 5.1875);
EXPECT_FALSE(cd.eps().steering_enabled());
EXPECT_FALSE(cd.eps().driver_override());
EXPECT_TRUE(cd.eps().driver_activity());
EXPECT_FALSE(cd.eps().watchdog_fault());
EXPECT_TRUE(cd.eps().channel_1_fault());
EXPECT_FALSE(cd.eps().channel_2_fault());
EXPECT_TRUE(cd.eps().calibration_fault());
EXPECT_FALSE(cd.eps().connector_fault());
EXPECT_TRUE(cd.check_response().is_eps_online());
}
} // namespace lincoln
} // namespace apollo
} // namespace canbus
<|endoftext|> |
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2018, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* 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 Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* Author: David Keeney, April, 2018
* ---------------------------------------------------------------------
*/
/*---------------------------------------------------------------------
* This is a test of the backtrackingTMCpp C++ implimentation (no Python).
*
* For those not familiar with GTest:
* ASSERT_TRUE(value) -- Fatal assertion that the value is true. Test
* terminates if false.
* ASSERT_FALSE(value) -- Fatal assertion that the value
* is false. Test terminates if true.
* ASSERT_STREQ(str1, str2) -- Fatal assertion that the strings are equal.
* Test terminates if false.
* EXPECT_TRUE(value) -- Nonfatal assertion that the value is true. Test
* continues if false.
* EXPECT_FALSE(value) -- Nonfatal assertion that the value is false.
* Test continues if true.
* EXPECT_STREQ(str1, str2) -- Nonfatal assertion that the strings are equal.
* Test continues if false.
* EXPECT_THROW(statement, exception_type) -- nonfatal exception, cought,
* reported and continues.
*---------------------------------------------------------------------
*/
#include <random>
#include <vector>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <nupic/algorithms/BacktrackingTMCpp.hpp>
#include <nupic/os/Directory.hpp>
#include <nupic/os/Path.hpp>
#include <nupic/types/Exception.hpp>
#include <gtest/gtest.h>
#define VERBOSITY 0
#define VERBOSE if (verbose) std::cerr << "[ ] "
static bool verbose = true; // turn this on to print extra stuff for debugging the test.
#define SEED 12
using namespace nupic;
using namespace nupic::algorithms::backtracking_tm;
namespace testing {
////////////////////////////////////////////////////////////////////////////////
// helper routines
////////////////////////////////////////////////////////////////////////////////
typedef shared_ptr<Real32> Pattern_t;
// Generate a single test pattern of random bits with given parameters.
//
// Parameters :
// @numCols -Number of columns in each pattern.
// @minOnes -The minimum number of 1's in each pattern.
// @maxOnes -The maximum number of 1's in each pattern.
static Pattern_t generatePattern(Size numCols = 100, Size minOnes = 21,
Size maxOnes = 25) {
NTA_ASSERT(minOnes <= maxOnes);
NTA_ASSERT(maxOnes < numCols);
Pattern_t p(new Real32[numCols], std::default_delete<Real32[]>());
memset(p.get(), 0, numCols);
int numOnes = (int)minOnes + std::rand() % (maxOnes - minOnes + 1);
std::uniform_int_distribution<> distr(0, (int)numCols - 1); // define the range (requires C++11)
for (int n = 0; n < numOnes; n++) {
int idx = std::rand() % numCols;
p.get()[idx] = 1.0f;
}
return p;
}
// Generates a sequence of n random patterns.
static std::vector<Pattern_t> generateSequence(Size n = 10, Size numCols = 100,
Size minOnes = 21,
Size maxOnes = 25) {
std::vector<Pattern_t> seq;
Pattern_t p; // an empty pattern which means reset
seq.push_back(p);
for (Size i = 0; i < n; i++) {
Pattern_t p = generatePattern(numCols, minOnes, maxOnes);
seq.push_back(p);
}
return seq;
}
struct param_t {
UInt32 numberOfCols;
UInt32 cellsPerColumn;
Real32 initialPerm;
Real32 connectedPerm;
UInt32 minThreshold;
UInt32 newSynapseCount;
Real32 permanenceInc;
Real32 permanenceDec;
Real32 permanenceMax;
Real32 globalDecay;
UInt32 activationThreshold;
bool doPooling;
UInt32 segUpdateValidDuration;
UInt32 burnIn;
bool collectStats;
Int32 seed;
Int32 verbosity;
bool checkSynapseConsistency;
UInt32 pamLength;
UInt32 maxInfBacktrack;
UInt32 maxLrnBacktrack;
UInt32 maxAge;
UInt32 maxSeqLength;
Int32 maxSegmentsPerCell;
Int32 maxSynapsesPerSegment;
char outputType[25];
};
void initializeParameters(struct param_t ¶m) {
// same as default settings
param.numberOfCols = 10;
param.cellsPerColumn = 3;
param.initialPerm = 0.11f;
param.connectedPerm = 0.5f;
param.minThreshold = 8;
param.newSynapseCount = 15;
param.permanenceInc = 0.1f;
param.permanenceDec = 0.1f;
param.permanenceMax = 1.0f;
param.globalDecay = 0.1f;
param.activationThreshold = 12;
param.doPooling = false;
param.segUpdateValidDuration = 5;
param.burnIn = 2;
param.collectStats = false;
param.seed = 42;
param.verbosity = VERBOSITY;
param.checkSynapseConsistency = false;
param.pamLength = 1;
param.maxInfBacktrack = 10;
param.maxLrnBacktrack = 5;
param.maxAge = 100000;
param.maxSeqLength = 32;
param.maxSegmentsPerCell = -1;
param.maxSynapsesPerSegment = -1;
strcpy(param.outputType, "normal");
}
//////////////////////////////////////////////////////////////////
////////// Tests
//////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// Run a test of the basic TM class ported from backtracking_tm_test.py
TEST(BacktrackingTMTest, testCheckpointLearned) {
struct param_t param;
initializeParameters(param);
param.numberOfCols = 100;
param.cellsPerColumn = 12;
param.verbosity = VERBOSITY;
// Create TM object
BacktrackingTMCpp tm1(
param.numberOfCols, param.cellsPerColumn, param.initialPerm,
param.connectedPerm, param.minThreshold, param.newSynapseCount,
param.permanenceInc, param.permanenceDec, param.permanenceMax,
param.globalDecay, param.activationThreshold, param.doPooling,
param.segUpdateValidDuration, param.burnIn, param.collectStats,
param.seed, param.verbosity, param.checkSynapseConsistency,
param.pamLength, param.maxInfBacktrack, param.maxLrnBacktrack,
param.maxAge, param.maxSeqLength, param.maxSegmentsPerCell,
param.maxSynapsesPerSegment, param.outputType);
// generate 5 sets of sequences
// The first pattern in each sequence is empty (a reset)
std::vector<std::vector<Pattern_t>> sequences;
for (Size s = 0; s < 5; s++) {
sequences.push_back(generateSequence());
}
// train with the first 3 sets of sequences.
std::vector<Pattern_t> train;
for (Size s = 0; s < 3; s++) {
for (Size i = 0; i < sequences[s].size();i++) {
train.push_back(sequences[s][i]);
}
}
// process the patterns that are in the training set.
for (Size t = 0; t < train.size(); t++) {
if (!train[t]) {
tm1.reset();
} else {
Real *bottomUpInput = train[t].get();
tm1.compute(bottomUpInput, true, true);
}
}
// Serialize and deserialized the TM.
Directory::create("TestOutputDir", false, true);
std::string checkpointPath = "TestOutputDir/tm.save";
tm1.saveToFile(checkpointPath);
BacktrackingTMCpp tm2;
tm2.loadFromFile(checkpointPath);
// Check that the TMs are the same.
ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm2, std::cout, 2));
// Feed remaining data into the models.
train.clear();
for (Size s = 3; s < sequences.size(); s++) {
for (Size i = 0; i < sequences[s].size(); i++) {
train.push_back(sequences[s][i]);
}
}
for (Size t = 0; t < train.size(); t++) {
if (!train[t]) {
tm1.reset();
tm2.reset();
} else {
Real *bottomUpInput = train[t].get();
Real *result1 = tm1.compute(bottomUpInput, true, true);
Real *result2 = tm2.compute(bottomUpInput, true, true);
ASSERT_TRUE(tm1 == tm2);
ASSERT_TRUE(tm1.getOutputBufferSize() == tm2.getOutputBufferSize());
ASSERT_EQ(tm1, tm2);
for (Size i = 0; i < tm1.getOutputBufferSize(); i++) {
ASSERT_TRUE(result1[i] == result2[i]);
}
}
}
// cleanup .
Directory::removeTree("TestOutputDir");
}
TEST(BacktrackingTMTest, testCheckpointMiddleOfSequence)
{
// Create a model and give it some inputs to learn.
BacktrackingTMCpp tm1(100, 12);
tm1.setVerbosity((Int32)VERBOSITY);
// generate 5 sets of sequences
std::vector<std::vector<Pattern_t>> sequences;
for (Size s = 0; s < 5; s++) {
sequences.push_back(generateSequence());
}
// separate train sets of sequences into halves
std::vector<Pattern_t> firstHalf, secondHalf;
const int HALF = 5*10 /2;
int idx = 0;
for (auto seq: sequences) {
for (auto pattern : seq) {
if(idx++ < HALF) firstHalf.push_back(pattern);
else secondHalf.push_back(pattern);
}
}
// compute each of the patterns in train, learn
for (auto p: firstHalf) {
const auto pat = p.get();
if (!pat) {
tm1.reset();
} else {
tm1.compute(pat, true, true);
}
}
// Serialize and TM.
Directory::create("TestOutputDir", false, true);
std::string checkpointPath = "TestOutputDir/tm.save";
tm1.saveToFile(checkpointPath);
// Restore the saved TM into tm2.
// Note that this resets the random generator to the same
// point that the first TM used when it processed that second set
// of patterns.
BacktrackingTMCpp tm2;
tm2.loadFromFile(checkpointPath);
ASSERT_EQ(tm1, tm2) << "Deserialized TM is equal";
ASSERT_TRUE(tm1 == tm2);
// process the remaining patterns in train with the first TM.
for (auto p: secondHalf) {
const auto pat = p.get();
if (!pat) {
tm1.reset();
} else {
Real *result1 = tm1.compute(pat, true, true);
}
}
ASSERT_TRUE(tm1 != tm2) << "TM1 moved, TM2 didn't";
// process the same remaining patterns in the train with the second TM.
for (auto p: secondHalf) {
const auto pat = p.get();
if (!pat) {
tm2.reset();
} else {
Real *result22= tm2.compute(pat, true, true);
}
}
ASSERT_EQ(tm1, tm2) << "Both TM trained";
ASSERT_TRUE(tm1 == tm2);
// cleanup if successful.
Directory::removeTree("TestOutputDir");
}
////////////////////////////////////////////////////////////////////////////////
// Run a test of the TM class ported from backtracking_tm_cpp2_test.py
TEST(BacktrackingTMTest, basicTest) {
// Create a model and give it some inputs to learn.
BacktrackingTMCpp tm1(10, 3, 0.2f, 0.8f, 2, 5, 0.10f, 0.05f, 1.0f, 0.05f, 4,
false, 5, 2, false, SEED, (Int32)VERBOSITY /* rest are defaults */);
tm1.setRetrieveLearningStates(true);
Size nCols = tm1.getnumCol();
// Serialize and deserialized the TM.
Directory::create("TestOutputDir", false, true);
std::string checkpointPath = "TestOutputDir/tm.save";
tm1.saveToFile(checkpointPath);
BacktrackingTMCpp tm2;
tm2.loadFromFile(checkpointPath);
// Check that the TMs are the same.
ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm2, std::cout, 2));
// generate some test data and NT patterns from it.
std::vector<Pattern_t> data = generateSequence(10, nCols, 2, 2);
std::vector<std::vector<UInt>> nzData;
for (Size i = 0; i < data.size(); i++) {
if (data[i]) { // skip reset patterns
const auto indices =
nupic::algorithms::backtracking_tm::nonzero<Real>(data[i].get(), nCols);
nzData.push_back(indices);
}
}
// Learn
for (Size i = 0; i < 5; i++) {
if (data[i])
tm1.learn(data[i].get());
}
tm1.reset();
// save and reload again after learning.
tm1.saveToFile(checkpointPath);
BacktrackingTMCpp tm3;
tm3.loadFromFile(checkpointPath);
// Check that the TMs are the same.
ASSERT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm3, std::cout, 2));
// Infer
for (Size i = 0; i < 10; i++) {
if (data[i]) {
tm1.infer(data[i].get());
if (i > 0)
tm1._checkPrediction(nzData);
}
}
// cleanup if successful.
Directory::removeTree("TestOutputDir");
}
} // namespace testing
<commit_msg>BackTM: fix test, use vectors, blame infer()<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2018, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* 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 Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* Author: David Keeney, April, 2018
* ---------------------------------------------------------------------
*/
#include <random>
#include <vector>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <nupic/algorithms/BacktrackingTMCpp.hpp>
#include <nupic/os/Directory.hpp>
#include <nupic/os/Path.hpp>
#include <nupic/types/Exception.hpp>
#include <gtest/gtest.h>
#define VERBOSITY 0
#define VERBOSE if (verbose) std::cerr << "[ ] "
static bool verbose = true; // turn this on to print extra stuff for debugging the test.
#define SEED 12
using namespace nupic;
using namespace nupic::algorithms::backtracking_tm;
namespace testing {
////////////////////////////////////////////////////////////////////////////////
// helper routines
////////////////////////////////////////////////////////////////////////////////
typedef std::vector<Real> Pattern_t;
// Generate a single test pattern of random bits with given parameters.
//
// Parameters :
// @numCols -Number of columns in each pattern.
// @minOnes -The minimum number of 1's in each pattern.
// @maxOnes -The maximum number of 1's in each pattern.
static Pattern_t generatePattern(Size numCols = 100, Size minOnes = 21,
Size maxOnes = 25) {
NTA_ASSERT(minOnes <= maxOnes);
NTA_ASSERT(maxOnes < numCols);
Pattern_t p(numCols);
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> getOnes(minOnes,maxOnes); // guaranteed unbiased
const int numOnes = getOnes(rng); //in range
std::uniform_int_distribution<> getCols(0, (int)numCols - 1); // define the range (requires C++11)
for (int n = 0; n < numOnes; n++) {
const auto idx = getCols(rng); //0..nCols
p[idx] = 1.0f;
}
return p;
}
// Generates a sequence of n random patterns.
static std::vector<Pattern_t> generateSequence(Size n = 10, Size numCols = 100,
Size minOnes = 21,
Size maxOnes = 25) {
std::vector<Pattern_t> seq;
Pattern_t p; // an empty pattern which means reset
seq.push_back(p);
for (Size i = 0; i < n; i++) {
const Pattern_t p = generatePattern(numCols, minOnes, maxOnes);
seq.push_back(p);
}
return seq;
}
//TODO remove
struct param_t {
UInt32 numberOfCols;
UInt32 cellsPerColumn;
Real32 initialPerm;
Real32 connectedPerm;
UInt32 minThreshold;
UInt32 newSynapseCount;
Real32 permanenceInc;
Real32 permanenceDec;
Real32 permanenceMax;
Real32 globalDecay;
UInt32 activationThreshold;
bool doPooling;
UInt32 segUpdateValidDuration;
UInt32 burnIn;
bool collectStats;
Int32 seed;
Int32 verbosity;
bool checkSynapseConsistency;
UInt32 pamLength;
UInt32 maxInfBacktrack;
UInt32 maxLrnBacktrack;
UInt32 maxAge;
UInt32 maxSeqLength;
Int32 maxSegmentsPerCell;
Int32 maxSynapsesPerSegment;
char outputType[25];
};
void initializeParameters(struct param_t ¶m) {
// same as default settings
param.numberOfCols = 10;
param.cellsPerColumn = 3;
param.initialPerm = 0.11f;
param.connectedPerm = 0.5f;
param.minThreshold = 8;
param.newSynapseCount = 15;
param.permanenceInc = 0.1f;
param.permanenceDec = 0.1f;
param.permanenceMax = 1.0f;
param.globalDecay = 0.1f;
param.activationThreshold = 12;
param.doPooling = false;
param.segUpdateValidDuration = 5;
param.burnIn = 2;
param.collectStats = false;
param.seed = 42;
param.verbosity = VERBOSITY;
param.checkSynapseConsistency = false;
param.pamLength = 1;
param.maxInfBacktrack = 10;
param.maxLrnBacktrack = 5;
param.maxAge = 100000;
param.maxSeqLength = 32;
param.maxSegmentsPerCell = -1;
param.maxSynapsesPerSegment = -1;
strcpy(param.outputType, "normal");
}
//////////////////////////////////////////////////////////////////
////////// Tests
//////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// Run a test of the basic TM class ported from backtracking_tm_test.py
TEST(BacktrackingTMTest, testCheckpointLearned) {
struct param_t param;
initializeParameters(param);
param.numberOfCols = 100;
param.cellsPerColumn = 12;
param.verbosity = VERBOSITY;
// Create TM object
BacktrackingTMCpp tm1(
param.numberOfCols, param.cellsPerColumn, param.initialPerm,
param.connectedPerm, param.minThreshold, param.newSynapseCount,
param.permanenceInc, param.permanenceDec, param.permanenceMax,
param.globalDecay, param.activationThreshold, param.doPooling,
param.segUpdateValidDuration, param.burnIn, param.collectStats,
param.seed, param.verbosity, param.checkSynapseConsistency,
param.pamLength, param.maxInfBacktrack, param.maxLrnBacktrack,
param.maxAge, param.maxSeqLength, param.maxSegmentsPerCell,
param.maxSynapsesPerSegment, param.outputType);
// generate 5 sets of sequences
// The first pattern in each sequence is empty (a reset)
std::vector<std::vector<Pattern_t>> sequences;
for (Size s = 0; s < 5; s++) {
sequences.push_back(generateSequence());
}
// train with the first 3 sets of sequences.
std::vector<Pattern_t> train;
for (Size s = 0; s < 3; s++) {
for (Size i = 0; i < sequences[s].size();i++) {
train.push_back(sequences[s][i]);
}
}
// process the patterns that are in the training set.
for (auto p : train) {
if (p.empty()) {
tm1.reset();
} else {
tm1.compute(p.data(), true, true);
}
}
// Serialize and deserialized the TM.
Directory::create("TestOutputDir", false, true);
std::string checkpointPath = "TestOutputDir/tm.save";
tm1.saveToFile(checkpointPath);
BacktrackingTMCpp tm2;
tm2.loadFromFile(checkpointPath);
// Check that the TMs are the same.
EXPECT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm2, std::cout, 2));
// Feed remaining data into the models.
train.clear();
for (auto seq: sequences) {
for (auto p : seq) {
train.push_back(p);
}
}
for (auto p : train) {
if (p.empty()) {
tm1.reset();
tm2.reset();
} else {
auto result1 = tm1.compute(p.data(), true, true);
auto result2 = tm2.compute(p.data(), true, true);
EXPECT_TRUE(tm1 == tm2);
EXPECT_TRUE(tm1.getOutputBufferSize() == tm2.getOutputBufferSize());
EXPECT_EQ(tm1, tm2) << "TMs not same!";
for (Size i = 0; i < tm1.getOutputBufferSize(); i++) {
EXPECT_TRUE(result1[i] == result2[i]);
}
}
}
// cleanup .
Directory::removeTree("TestOutputDir");
}
TEST(BacktrackingTMTest, testCheckpointMiddleOfSequence)
{
// Create a model and give it some inputs to learn.
BacktrackingTMCpp tm1(100, 12);
tm1.setVerbosity((Int32)VERBOSITY);
// generate 5 sets of sequences
std::vector<std::vector<Pattern_t>> sequences;
for (Size s = 0; s < 5; s++) {
sequences.push_back(generateSequence());
}
// separate train sets of sequences into halves
std::vector<Pattern_t> firstHalf, secondHalf;
{
const int HALF = 5*10 /2;
int idx = 0;
for (auto seq: sequences) {
for (auto pattern : seq) {
if(idx++ < HALF) firstHalf.push_back(pattern);
else secondHalf.push_back(pattern);
}
}
}
// compute each of the patterns in train, learn
for (auto p: firstHalf) {
if (p.empty()) {
tm1.reset();
} else {
tm1.compute(p.data(), true, true);
}
}
// Serialize and TM.
Directory::create("TestOutputDir", false, true);
std::string checkpointPath = "TestOutputDir/tm.save";
tm1.saveToFile(checkpointPath);
// Restore the saved TM into tm2.
// Note that this resets the random generator to the same
// point that the first TM used when it processed that second set
// of patterns.
BacktrackingTMCpp tm2;
tm2.loadFromFile(checkpointPath);
ASSERT_EQ(tm1, tm2) << "Deserialized TM is equal";
ASSERT_TRUE(tm1 == tm2);
// process the remaining patterns in train with the first TM.
for (auto p: secondHalf) {
if (p.empty()) {
tm1.reset();
} else {
tm1.compute(p.data(), true, true);
}
}
EXPECT_TRUE(tm1 != tm2) << "TM1 moved, TM2 didn't";
// process the same remaining patterns in the train with the second TM.
for (auto p: secondHalf) {
if (p.empty()) {
tm2.reset();
} else {
tm2.compute(p.data(), true, true);
}
}
EXPECT_EQ(tm1, tm2) << "Both TM trained";
EXPECT_TRUE(tm1 == tm2);
// cleanup if successful.
Directory::removeTree("TestOutputDir");
}
////////////////////////////////////////////////////////////////////////////////
// Run a test of the TM class ported from backtracking_tm_cpp2_test.py
TEST(BacktrackingTMTest, basicTest) {
// Create a model and give it some inputs to learn.
BacktrackingTMCpp tm1(10, 3, 0.2f, 0.8f, 2, 5, 0.10f, 0.05f, 1.0f, 0.05f, 4,
false, 5, 2, false, SEED, (Int32)VERBOSITY /* rest are defaults */);
tm1.setRetrieveLearningStates(true);
const Size nCols = tm1.getnumCol();
// Serialize and deserialized the TM.
Directory::create("TestOutputDir", false, true);
std::string checkpointPath = "TestOutputDir/tm.save";
tm1.saveToFile(checkpointPath);
{
BacktrackingTMCpp tm2;
tm2.loadFromFile(checkpointPath);
// Check that the TMs are the same.
EXPECT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm2, std::cout, 2));
}
// generate some test data and NT patterns from it.
std::vector<Pattern_t> data = generateSequence(10, nCols, 2, 2);
// Learn
for (Size i = 0; i < 5; i++) {
if (!data[i].empty())
tm1.learn(data[i].data());
}
tm1.reset();
// save and reload again after learning.
tm1.saveToFile(checkpointPath);
{
BacktrackingTMCpp tm3;
tm3.loadFromFile(checkpointPath);
// Check that the TMs are the same.
EXPECT_TRUE(BacktrackingTMCpp::tmDiff2(tm1, tm3, std::cout, 2));
}
/*
// Infer
std::vector<std::vector<UInt>> nzData;
for (auto p : data) {
if (p.empty()) continue; // skip reset patterns
const auto indices =
nupic::algorithms::backtracking_tm::nonzero<Real>(p.data(), nCols);
nzData.push_back(indices);
}
for (Size i = 0; i < 10; i++) {
if (!data[i].empty()) {
tm1.infer(data[i].data());
if (i > 0) tm1._checkPrediction(nzData);
}
}
*/
// cleanup if successful.
Directory::removeTree("TestOutputDir");
}
} // namespace testing
<|endoftext|> |
<commit_before>// Copyright (c) 2011 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/ui/views/global_error_bubble_view.h"
#include "base/logging.h"
#include "chrome/browser/ui/global_error.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/toolbar_view.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/image/image.h"
#include "views/controls/button/text_button.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/layout/grid_layout.h"
#include "views/layout/layout_constants.h"
namespace {
enum {
TAG_ACCEPT_BUTTON = 1,
TAG_CANCEL_BUTTON,
};
const int kBubbleViewWidth = 262;
// The horizontal padding between the title and the icon.
const int kTitleHorizontalPadding = 3;
// The vertical offset of the wrench bubble from the wrench menu button.
const int kWrenchBubblePointOffsetY = 6;
} // namespace
GlobalErrorBubbleView::GlobalErrorBubbleView(Browser* browser,
GlobalError* error)
: browser_(browser),
error_(error) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
int resource_id = error_->GetBubbleViewIconResourceID();
scoped_ptr<views::ImageView> image_view(new views::ImageView());
image_view->SetImage(rb.GetImageNamed(resource_id).ToSkBitmap());
string16 title_string(error_->GetBubbleViewTitle());
scoped_ptr<views::Label> title_label(
new views::Label(UTF16ToWideHack(title_string)));
title_label->SetMultiLine(true);
title_label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
title_label->SetFont(title_label->font().DeriveFont(1));
string16 message_string(error_->GetBubbleViewMessage());
scoped_ptr<views::Label> message_label(
new views::Label(UTF16ToWideHack(message_string)));
message_label->SetMultiLine(true);
message_label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
string16 accept_string(error_->GetBubbleViewAcceptButtonLabel());
scoped_ptr<views::TextButton> accept_button(
new views::NativeTextButton(this, UTF16ToWideHack(accept_string)));
accept_button->SetIsDefault(true);
string16 cancel_string(error_->GetBubbleViewCancelButtonLabel());
scoped_ptr<views::TextButton> cancel_button;
if (!cancel_string.empty()) {
cancel_button.reset(
new views::NativeTextButton(this, UTF16ToWideHack(cancel_string)));
}
views::GridLayout* layout = new views::GridLayout(this);
SetLayoutManager(layout);
// Top row, icon and title.
views::ColumnSet* cs = layout->AddColumnSet(0);
cs->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING,
0, views::GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(0, kTitleHorizontalPadding);
cs->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL,
1, views::GridLayout::USE_PREF, 0, 0);
// Middle row, message label.
cs = layout->AddColumnSet(1);
cs->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL,
1, views::GridLayout::USE_PREF, 0, 0);
// Bottom row, accept and cancel button.
cs = layout->AddColumnSet(2);
cs->AddPaddingColumn(1, views::kRelatedControlHorizontalSpacing);
cs->AddColumn(views::GridLayout::TRAILING, views::GridLayout::LEADING,
0, views::GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(0, views::kRelatedButtonHSpacing);
cs->AddColumn(views::GridLayout::TRAILING, views::GridLayout::LEADING,
0, views::GridLayout::USE_PREF, 0, 0);
layout->StartRow(1, 0);
layout->AddView(image_view.release());
layout->AddView(title_label.release());
layout->AddPaddingRow(0, views::kRelatedControlSmallVerticalSpacing);
layout->StartRow(1, 1);
layout->AddView(message_label.release());
layout->AddPaddingRow(0, views::kRelatedControlSmallVerticalSpacing);
layout->StartRow(0, 2);
if (cancel_button.get())
layout->AddView(cancel_button.release());
else
layout->SkipColumns(1);
layout->AddView(accept_button.release());
}
GlobalErrorBubbleView::~GlobalErrorBubbleView() {
}
gfx::Size GlobalErrorBubbleView::GetPreferredSize() {
views::GridLayout* layout =
static_cast<views::GridLayout*>(GetLayoutManager());
int height = layout->GetPreferredHeightForWidth(this, kBubbleViewWidth);
return gfx::Size(kBubbleViewWidth, height);
}
void GlobalErrorBubbleView::ButtonPressed(views::Button* sender,
const views::Event& event) {
if (sender->tag() == TAG_ACCEPT_BUTTON)
error_->BubbleViewAcceptButtonPressed();
else if (sender->tag() == TAG_CANCEL_BUTTON)
error_->BubbleViewCancelButtonPressed();
else
NOTREACHED();
}
void GlobalErrorBubbleView::BubbleClosing(Bubble* bubble,
bool closed_by_escape) {
error_->BubbleViewDidClose();
}
bool GlobalErrorBubbleView::CloseOnEscape() {
return true;
}
bool GlobalErrorBubbleView::FadeInOnShow() {
return true;
}
void GlobalError::ShowBubbleView(Browser* browser, GlobalError* error) {
BrowserView* browser_view = BrowserView::GetBrowserViewForNativeWindow(
browser->window()->GetNativeHandle());
views::View* wrench_button = browser_view->toolbar()->app_menu();
gfx::Point origin;
views::View::ConvertPointToScreen(wrench_button, &origin);
gfx::Rect bounds(origin.x(), origin.y(), wrench_button->width(),
wrench_button->height());
bounds.Inset(0, kWrenchBubblePointOffsetY);
GlobalErrorBubbleView* bubble_view =
new GlobalErrorBubbleView(browser, error);
// Bubble::Show() takes ownership of the view.
Bubble::Show(browser_view->GetWidget(), bounds,
views::BubbleBorder::TOP_RIGHT, bubble_view, bubble_view);
}
<commit_msg>Disable fading in global error bubble view<commit_after>// Copyright (c) 2011 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/ui/views/global_error_bubble_view.h"
#include "base/logging.h"
#include "chrome/browser/ui/global_error.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/toolbar_view.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/image/image.h"
#include "views/controls/button/text_button.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/layout/grid_layout.h"
#include "views/layout/layout_constants.h"
namespace {
enum {
TAG_ACCEPT_BUTTON = 1,
TAG_CANCEL_BUTTON,
};
const int kBubbleViewWidth = 262;
// The horizontal padding between the title and the icon.
const int kTitleHorizontalPadding = 3;
// The vertical offset of the wrench bubble from the wrench menu button.
const int kWrenchBubblePointOffsetY = 6;
} // namespace
GlobalErrorBubbleView::GlobalErrorBubbleView(Browser* browser,
GlobalError* error)
: browser_(browser),
error_(error) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
int resource_id = error_->GetBubbleViewIconResourceID();
scoped_ptr<views::ImageView> image_view(new views::ImageView());
image_view->SetImage(rb.GetImageNamed(resource_id).ToSkBitmap());
string16 title_string(error_->GetBubbleViewTitle());
scoped_ptr<views::Label> title_label(
new views::Label(UTF16ToWideHack(title_string)));
title_label->SetMultiLine(true);
title_label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
title_label->SetFont(title_label->font().DeriveFont(1));
string16 message_string(error_->GetBubbleViewMessage());
scoped_ptr<views::Label> message_label(
new views::Label(UTF16ToWideHack(message_string)));
message_label->SetMultiLine(true);
message_label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
string16 accept_string(error_->GetBubbleViewAcceptButtonLabel());
scoped_ptr<views::TextButton> accept_button(
new views::NativeTextButton(this, UTF16ToWideHack(accept_string)));
accept_button->SetIsDefault(true);
string16 cancel_string(error_->GetBubbleViewCancelButtonLabel());
scoped_ptr<views::TextButton> cancel_button;
if (!cancel_string.empty()) {
cancel_button.reset(
new views::NativeTextButton(this, UTF16ToWideHack(cancel_string)));
}
views::GridLayout* layout = new views::GridLayout(this);
SetLayoutManager(layout);
// Top row, icon and title.
views::ColumnSet* cs = layout->AddColumnSet(0);
cs->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING,
0, views::GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(0, kTitleHorizontalPadding);
cs->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL,
1, views::GridLayout::USE_PREF, 0, 0);
// Middle row, message label.
cs = layout->AddColumnSet(1);
cs->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL,
1, views::GridLayout::USE_PREF, 0, 0);
// Bottom row, accept and cancel button.
cs = layout->AddColumnSet(2);
cs->AddPaddingColumn(1, views::kRelatedControlHorizontalSpacing);
cs->AddColumn(views::GridLayout::TRAILING, views::GridLayout::LEADING,
0, views::GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(0, views::kRelatedButtonHSpacing);
cs->AddColumn(views::GridLayout::TRAILING, views::GridLayout::LEADING,
0, views::GridLayout::USE_PREF, 0, 0);
layout->StartRow(1, 0);
layout->AddView(image_view.release());
layout->AddView(title_label.release());
layout->AddPaddingRow(0, views::kRelatedControlSmallVerticalSpacing);
layout->StartRow(1, 1);
layout->AddView(message_label.release());
layout->AddPaddingRow(0, views::kRelatedControlSmallVerticalSpacing);
layout->StartRow(0, 2);
if (cancel_button.get())
layout->AddView(cancel_button.release());
else
layout->SkipColumns(1);
layout->AddView(accept_button.release());
}
GlobalErrorBubbleView::~GlobalErrorBubbleView() {
}
gfx::Size GlobalErrorBubbleView::GetPreferredSize() {
views::GridLayout* layout =
static_cast<views::GridLayout*>(GetLayoutManager());
int height = layout->GetPreferredHeightForWidth(this, kBubbleViewWidth);
return gfx::Size(kBubbleViewWidth, height);
}
void GlobalErrorBubbleView::ButtonPressed(views::Button* sender,
const views::Event& event) {
if (sender->tag() == TAG_ACCEPT_BUTTON)
error_->BubbleViewAcceptButtonPressed();
else if (sender->tag() == TAG_CANCEL_BUTTON)
error_->BubbleViewCancelButtonPressed();
else
NOTREACHED();
}
void GlobalErrorBubbleView::BubbleClosing(Bubble* bubble,
bool closed_by_escape) {
error_->BubbleViewDidClose();
}
bool GlobalErrorBubbleView::CloseOnEscape() {
return true;
}
bool GlobalErrorBubbleView::FadeInOnShow() {
// TODO(sail): Enabling fade causes the window to be disabled for some
// reason. Until this is fixed we need to disable fade.
return false;
}
void GlobalError::ShowBubbleView(Browser* browser, GlobalError* error) {
BrowserView* browser_view = BrowserView::GetBrowserViewForNativeWindow(
browser->window()->GetNativeHandle());
views::View* wrench_button = browser_view->toolbar()->app_menu();
gfx::Point origin;
views::View::ConvertPointToScreen(wrench_button, &origin);
gfx::Rect bounds(origin.x(), origin.y(), wrench_button->width(),
wrench_button->height());
bounds.Inset(0, kWrenchBubblePointOffsetY);
GlobalErrorBubbleView* bubble_view =
new GlobalErrorBubbleView(browser, error);
// Bubble::Show() takes ownership of the view.
Bubble::Show(browser_view->GetWidget(), bounds,
views::BubbleBorder::TOP_RIGHT, bubble_view, bubble_view);
}
<|endoftext|> |
<commit_before>#include "cmat.hpp"
#include "msgpack.hpp"
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
void print(value &v){
stringstream ss;
v.serialize(ss);
string str;
getline(ss, str);
for(int i = 0 ; i < (int)str.size() ; i++)
cout << setw(2) << setfill('0') << hex << (((int)str[i])&255) << ' ';
cout << endl;
}
struct DEFAULT{
value m_default;
vector<pair<int, int> > source;
DEFAULT(){
map<string, value> empty_value_map;
m_default = value(empty_value_map);
m_default.get_map()["file_in"] = value(string("in.png"));
m_default.get_map()["file_out"] = value(string("out.png"));
m_default.get_map()["mask_file_out"] = value(string("mask.out.png"));
m_default.get_map()["lonely"] = value(empty_value_map);
m_default.get_map()["lonely"].get_map()["start"] = value(int64_t(6));
m_default.get_map()["lonely"].get_map()["end"] = value(int64_t(20));
m_default.get_map()["lonely"].get_map()["times"] = value(int64_t(1));
m_default.get_map()["cvt"] = value(empty_value_map);
m_default.get_map()["cvt"].get_map()["R"] = value(int64_t(0));
m_default.get_map()["cvt"].get_map()["G"] = value(int64_t(0));
m_default.get_map()["cvt"].get_map()["B"] = value(int64_t(0));
m_default.get_map()["black_white"] = value(int64_t(20));
m_default.get_map()["margin"] = value(int64_t(2));
m_default.get_map()["total_sources"] = value(int64_t(1));
source.push_back(pair<int,int>(0,0));
}
string& INPUT(){
return m_default.get_map()["file_in"].get_string();
}
string& OUTPUT(){
return m_default.get_map()["file_out"].get_string();
}
string& MASK_OUTPUT(){
return m_default.get_map()["mask_file_out"].get_string();
}
int64_t& LONELY_START(){
return m_default.get_map()["lonely"].get_map()["start"].get_integer();
}
int64_t& LONELY_END(){
return m_default.get_map()["lonely"].get_map()["end"].get_integer();
}
int64_t& LONELY_TIMES(){
return m_default.get_map()["lonely"].get_map()["times"].get_integer();
}
int64_t& BLACK_WHITE(){
return m_default.get_map()["black_white"].get_integer();
}
int64_t& MARGIN(){
return m_default.get_map()["margin"].get_integer();
}
int64_t& TOTAL_SOURCES(){
return m_default.get_map()["total_sources"].get_integer();
}
};
int string2int(string str){
stringstream ss(str);
int re;
ss >> re;
return re;
}
int main(int argc, char **argv){
DEFAULT Default;
for(int i = 1 ; i < argc ; i++){
if(string(argv[i]) == string("-i")) {
Default.INPUT() = string(argv[i+1]);
++i;
} else if (string(argv[i]) == string("-o")) {
Default.OUTPUT() = string(argv[i+1]);
++i;
} else if (string(argv[i]) == string("-mo")) {
Default.MASK_OUTPUT() = string(argv[i+1]);
++i;
} else if (string(argv[i]) == string("-l")) {
Default.LONELY_START() = string2int(string(argv[i+1]));
Default.LONELY_END() = string2int(string(argv[i+2]));
Default.LONELY_TIMES() = string2int(string(argv[i+3]));
i+=3;
} else if (string(argv[i]) == string("-bw")) {
Default.BLACK_WHITE() = string2int(string(argv[i+1]));
++i;
} else if (string(argv[i]) == string("-m")) {
Default.MARGIN() = string2int(string(argv[i+1]));
++i;
} else if (string(argv[i]) == string("-s")) {
Default.TOTAL_SOURCES() = string2int(string(argv[i+1]));
++i;
Default.source.pop_back();
for(int a=0;a<Default.TOTAL_SOURCES();a++){
++i;
string input_point = string(argv[i]);
int sep=input_point.find(",");
int x=string2int(input_point.substr(0,sep));
int y=string2int(input_point.substr(sep+1,input_point.length()-1));
Default.source.push_back(pair<int,int>(x,y));
}
} else if (string(argv[i]) == string("help") || string(argv[i]) == string("-h")) {
cout << "[Help]" << endl;
cout << "[-i input] [-o output] [-mo mask_output]" << endl;
cout << "[-l lonely_start lonely_end lonely_times]" << endl;
cout << "[-s $total_sources \"a1,b1\" \"a2,b2\" source]" << endl;
cout << "[-bw black_white] [-m margin] [-h | help]" << endl;
return 0;
} else {
return 0;
}
}
Default.m_default.print_tree();
CMat pic;
CMat mask = pic.set_in_file_path( Default.INPUT() ).set_out_file_path( Default.OUTPUT() ).open();
mask.guass().cvt_color().soble().guass().black_white( Default.BLACK_WHITE() );
for(int i = 0 ; i < Default.LONELY_TIMES() ; i++){
mask.lonely( Default.LONELY_START() + i, Default.LONELY_END() - i);
}
mask.set_out_file_path( Default.MASK_OUTPUT() ).save();
pic.kill_pos_color(mask.flood(Default.source), Default.MARGIN()).save();
return 0;
}
<commit_msg>fix indent<commit_after>#include "cmat.hpp"
#include "msgpack.hpp"
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
void print(value &v){
stringstream ss;
v.serialize(ss);
string str;
getline(ss, str);
for(int i = 0 ; i < (int)str.size() ; i++)
cout << setw(2) << setfill('0') << hex << (((int)str[i])&255) << ' ';
cout << endl;
}
struct DEFAULT{
value m_default;
vector<pair<int, int> > source;
DEFAULT(){
map<string, value> empty_value_map;
m_default = value(empty_value_map);
m_default.get_map()["file_in"] = value(string("in.png"));
m_default.get_map()["file_out"] = value(string("out.png"));
m_default.get_map()["mask_file_out"] = value(string("mask.out.png"));
m_default.get_map()["lonely"] = value(empty_value_map);
m_default.get_map()["lonely"].get_map()["start"] = value(int64_t(6));
m_default.get_map()["lonely"].get_map()["end"] = value(int64_t(20));
m_default.get_map()["lonely"].get_map()["times"] = value(int64_t(1));
m_default.get_map()["cvt"] = value(empty_value_map);
m_default.get_map()["cvt"].get_map()["R"] = value(int64_t(0));
m_default.get_map()["cvt"].get_map()["G"] = value(int64_t(0));
m_default.get_map()["cvt"].get_map()["B"] = value(int64_t(0));
m_default.get_map()["black_white"] = value(int64_t(20));
m_default.get_map()["margin"] = value(int64_t(2));
m_default.get_map()["total_sources"] = value(int64_t(1));
source.push_back(pair<int,int>(0,0));
}
string& INPUT(){
return m_default.get_map()["file_in"].get_string();
}
string& OUTPUT(){
return m_default.get_map()["file_out"].get_string();
}
string& MASK_OUTPUT(){
return m_default.get_map()["mask_file_out"].get_string();
}
int64_t& LONELY_START(){
return m_default.get_map()["lonely"].get_map()["start"].get_integer();
}
int64_t& LONELY_END(){
return m_default.get_map()["lonely"].get_map()["end"].get_integer();
}
int64_t& LONELY_TIMES(){
return m_default.get_map()["lonely"].get_map()["times"].get_integer();
}
int64_t& BLACK_WHITE(){
return m_default.get_map()["black_white"].get_integer();
}
int64_t& MARGIN(){
return m_default.get_map()["margin"].get_integer();
}
int64_t& TOTAL_SOURCES(){
return m_default.get_map()["total_sources"].get_integer();
}
};
int string2int(string str){
stringstream ss(str);
int re;
ss >> re;
return re;
}
int main(int argc, char **argv){
DEFAULT Default;
for(int i = 1 ; i < argc ; i++){
if(string(argv[i]) == string("-i")) {
Default.INPUT() = string(argv[i+1]);
++i;
} else if (string(argv[i]) == string("-o")) {
Default.OUTPUT() = string(argv[i+1]);
++i;
} else if (string(argv[i]) == string("-mo")) {
Default.MASK_OUTPUT() = string(argv[i+1]);
++i;
} else if (string(argv[i]) == string("-l")) {
Default.LONELY_START() = string2int(string(argv[i+1]));
Default.LONELY_END() = string2int(string(argv[i+2]));
Default.LONELY_TIMES() = string2int(string(argv[i+3]));
i+=3;
} else if (string(argv[i]) == string("-bw")) {
Default.BLACK_WHITE() = string2int(string(argv[i+1]));
++i;
} else if (string(argv[i]) == string("-m")) {
Default.MARGIN() = string2int(string(argv[i+1]));
++i;
} else if (string(argv[i]) == string("-s")) {
Default.TOTAL_SOURCES() = string2int(string(argv[i+1]));
++i;
Default.source.pop_back();
for(int a=0;a<Default.TOTAL_SOURCES();a++){
++i;
string input_point = string(argv[i]);
int sep=input_point.find(",");
int x=string2int(input_point.substr(0,sep));
int y=string2int(input_point.substr(sep+1,input_point.length()-1));
Default.source.push_back(pair<int,int>(x,y));
}
} else if (string(argv[i]) == string("help") || string(argv[i]) == string("-h")) {
cout << "[Help]" << endl;
cout << "[-i input] [-o output] [-mo mask_output]" << endl;
cout << "[-l lonely_start lonely_end lonely_times]" << endl;
cout << "[-s $total_sources \"a1,b1\" \"a2,b2\" source]" << endl;
cout << "[-bw black_white] [-m margin] [-h | help]" << endl;
return 0;
} else {
return 0;
}
}
Default.m_default.print_tree();
CMat pic;
CMat mask = pic.set_in_file_path( Default.INPUT() ).set_out_file_path( Default.OUTPUT() ).open();
mask.guass().cvt_color().soble().guass().black_white( Default.BLACK_WHITE() );
for(int i = 0 ; i < Default.LONELY_TIMES() ; i++){
mask.lonely( Default.LONELY_START() + i, Default.LONELY_END() - i);
}
mask.set_out_file_path( Default.MASK_OUTPUT() ).save();
pic.kill_pos_color(mask.flood(Default.source), Default.MARGIN()).save();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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/service/service_process.h"
#include <algorithm>
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/singleton.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/service_process_util.h"
#include "chrome/service/cloud_print/cloud_print_proxy.h"
#include "chrome/service/service_ipc_server.h"
#include "chrome/service/service_process_prefs.h"
#include "net/base/network_change_notifier.h"
#if defined(ENABLE_REMOTING)
#include "remoting/base/constants.h"
#include "remoting/host/chromoting_host.h"
#include "remoting/host/chromoting_host_context.h"
#include "remoting/host/json_host_config.h"
#endif // defined(ENABLED_REMOTING)
ServiceProcess* g_service_process = NULL;
namespace {
// Delay in millseconds after the last service is disabled before we attempt
// a shutdown.
const int64 kShutdownDelay = 60000;
class ServiceIOThread : public base::Thread {
public:
explicit ServiceIOThread(const char* name);
virtual ~ServiceIOThread();
protected:
virtual void CleanUp();
private:
DISALLOW_COPY_AND_ASSIGN(ServiceIOThread);
};
ServiceIOThread::ServiceIOThread(const char* name) : base::Thread(name) {}
ServiceIOThread::~ServiceIOThread() {
// We cannot rely on our base class to stop the thread since we want our
// CleanUp function to run.
Stop();
}
void ServiceIOThread::CleanUp() {
URLFetcher::CancelAll();
}
} // namespace
ServiceProcess::ServiceProcess()
: shutdown_event_(true, false),
main_message_loop_(NULL),
enabled_services_(0),
update_available_(false) {
DCHECK(!g_service_process);
g_service_process = this;
}
bool ServiceProcess::Initialize(MessageLoop* message_loop,
const CommandLine& command_line) {
main_message_loop_ = message_loop;
network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
base::Thread::Options options;
options.message_loop_type = MessageLoop::TYPE_IO;
io_thread_.reset(new ServiceIOThread("ServiceProcess_IO"));
file_thread_.reset(new base::Thread("ServiceProcess_File"));
if (!io_thread_->StartWithOptions(options) ||
!file_thread_->StartWithOptions(options)) {
NOTREACHED();
Teardown();
return false;
}
// See if we have been suppiled an LSID in the command line. This LSID will
// override the credentials we use for Cloud Print.
std::string lsid = command_line.GetSwitchValueASCII(
switches::kServiceAccountLsid);
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
FilePath pref_path = user_data_dir.Append(chrome::kServiceStateFileName);
service_prefs_.reset(
new ServiceProcessPrefs(pref_path, file_thread_->message_loop_proxy()));
service_prefs_->ReadPrefs();
bool remoting_host_enabled = false;
// For development, we allow forcing the enabling of the host daemon via a
// commandline flag, regardless of the preference setting.
//
// TODO(ajwong): When we've gotten the preference setting workflow more
// stable, we should remove the command-line flag force-enable.
service_prefs_->GetBoolean(prefs::kRemotingHostEnabled,
&remoting_host_enabled);
remoting_host_enabled |= command_line.HasSwitch(switches::kEnableRemoting);
#if defined(ENABLE_REMOTING)
// Check if remoting host is already enabled.
if (remoting_host_enabled) {
StartChromotingHost();
}
#endif
// Enable Cloud Print if needed. First check the command-line.
bool cloud_print_proxy_enabled =
command_line.HasSwitch(switches::kEnableCloudPrintProxy);
if (!cloud_print_proxy_enabled) {
// Then check if the cloud print proxy was previously enabled.
service_prefs_->GetBoolean(prefs::kCloudPrintProxyEnabled,
&cloud_print_proxy_enabled);
}
if (cloud_print_proxy_enabled) {
GetCloudPrintProxy()->EnableForUser(lsid);
}
VLOG(1) << "Starting Service Process IPC Server";
ipc_server_.reset(new ServiceIPCServer(GetServiceProcessChannelName()));
ipc_server_->Init();
// After the IPC server has started we signal that the service process is
// ready.
ServiceProcessState::GetInstance()->SignalReady(
NewRunnableMethod(this, &ServiceProcess::Shutdown));
// See if we need to stay running.
ScheduleShutdownCheck();
return true;
}
bool ServiceProcess::Teardown() {
service_prefs_.reset();
cloud_print_proxy_.reset();
#if defined(ENABLE_REMOTING)
ShutdownChromotingHost();
#endif
ipc_server_.reset();
// Signal this event before shutting down the service process. That way all
// background threads can cleanup.
shutdown_event_.Signal();
io_thread_.reset();
file_thread_.reset();
// The NetworkChangeNotifier must be destroyed after all other threads that
// might use it have been shut down.
network_change_notifier_.reset();
ServiceProcessState::GetInstance()->SignalStopped();
return true;
}
void ServiceProcess::Shutdown() {
// Quit the main message loop.
main_message_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
bool ServiceProcess::HandleClientDisconnect() {
// If there are no enabled services or if there is an update available
// we want to shutdown right away. Else we want to keep listening for
// new connections.
if (!enabled_services_ || update_available()) {
Shutdown();
return false;
}
return true;
}
CloudPrintProxy* ServiceProcess::GetCloudPrintProxy() {
if (!cloud_print_proxy_.get()) {
cloud_print_proxy_.reset(new CloudPrintProxy());
cloud_print_proxy_->Initialize(service_prefs_.get(), this);
}
return cloud_print_proxy_.get();
}
void ServiceProcess::OnCloudPrintProxyEnabled() {
// Save the preference that we have enabled the cloud print proxy.
service_prefs_->SetBoolean(prefs::kCloudPrintProxyEnabled, true);
service_prefs_->WritePrefs();
OnServiceEnabled();
}
void ServiceProcess::OnCloudPrintProxyDisabled() {
// Save the preference that we have disabled the cloud print proxy.
service_prefs_->SetBoolean(prefs::kCloudPrintProxyEnabled, false);
service_prefs_->WritePrefs();
OnServiceDisabled();
}
void ServiceProcess::OnServiceEnabled() {
enabled_services_++;
if (1 == enabled_services_) {
ServiceProcessState::GetInstance()->AddToAutoRun();
}
}
void ServiceProcess::OnServiceDisabled() {
DCHECK_NE(enabled_services_, 0);
enabled_services_--;
if (0 == enabled_services_) {
ServiceProcessState::GetInstance()->RemoveFromAutoRun();
// We will wait for some time to respond to IPCs before shutting down.
ScheduleShutdownCheck();
}
}
void ServiceProcess::ScheduleShutdownCheck() {
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
NewRunnableMethod(this, &ServiceProcess::ShutdownIfNeeded),
kShutdownDelay);
}
void ServiceProcess::ShutdownIfNeeded() {
if (0 == enabled_services_) {
if (ipc_server_->is_client_connected()) {
// If there is a client connected, we need to try again later.
// Note that there is still a timing window here because a client may
// decide to connect at this point.
// TODO(sanjeevr): Fix this timing window.
ScheduleShutdownCheck();
} else {
Shutdown();
}
}
}
#if defined(ENABLE_REMOTING)
bool ServiceProcess::EnableChromotingHostWithTokens(
const std::string& login,
const std::string& remoting_token,
const std::string& talk_token) {
// Save the login info and tokens.
remoting_login_ = login;
remoting_token_ = remoting_token;
talk_token_ = talk_token;
// Use the remoting directory to register the host.
if (remoting_directory_.get())
remoting_directory_->CancelRequest();
remoting_directory_.reset(new RemotingDirectoryService(this));
remoting_directory_->AddHost(remoting_token);
return true;
}
bool ServiceProcess::StartChromotingHost() {
// We have already started.
if (chromoting_context_.get())
return true;
// Load chromoting config from the disk.
LoadChromotingConfig();
// Start the chromoting context first.
chromoting_context_.reset(new remoting::ChromotingHostContext());
chromoting_context_->Start();
// Create a chromoting host object.
chromoting_host_ = remoting::ChromotingHost::Create(chromoting_context_.get(),
chromoting_config_);
// Then start the chromoting host.
// When ChromotingHost is shutdown because of failure or a request that
// we made OnChromotingShutdown() is calls.
chromoting_host_->Start(
NewRunnableMethod(this, &ServiceProcess::OnChromotingHostShutdown));
OnServiceEnabled();
return true;
}
bool ServiceProcess::ShutdownChromotingHost() {
// Chromoting host doesn't exist so return true.
if (!chromoting_host_)
return true;
// Shutdown the chromoting host asynchronously. This will signal the host to
// shutdown, we'll actually wait for all threads to stop when we destroy
// the chromoting context.
chromoting_host_->Shutdown();
chromoting_host_ = NULL;
return true;
}
void ServiceProcess::OnRemotingHostAdded() {
// Save configuration for chromoting.
SaveChromotingConfig(remoting_login_,
talk_token_,
remoting_directory_->host_id(),
remoting_directory_->host_name(),
remoting_directory_->host_key_pair());
remoting_directory_.reset();
remoting_login_ = "";
remoting_token_ = "";
talk_token_ = "";
// Save the preference that we have enabled the remoting host.
service_prefs_->SetBoolean(prefs::kRemotingHostEnabled, true);
// Force writing prefs to the disk.
service_prefs_->WritePrefs();
// TODO(hclam): If we have a problem we need to send an IPC message back
// to the client that started this.
bool ret = StartChromotingHost();
DCHECK(ret);
}
void ServiceProcess::OnRemotingDirectoryError() {
remoting_directory_.reset();
remoting_login_ = "";
remoting_token_ = "";
talk_token_ = "";
// TODO(hclam): If we have a problem we need to send an IPC message back
// to the client that started this.
}
void ServiceProcess::SaveChromotingConfig(
const std::string& login,
const std::string& token,
const std::string& host_id,
const std::string& host_name,
remoting::HostKeyPair* host_key_pair) {
// First we need to load the config first.
LoadChromotingConfig();
// And then do the update.
chromoting_config_->SetString(remoting::kXmppLoginConfigPath, login);
chromoting_config_->SetString(remoting::kXmppAuthTokenConfigPath, token);
chromoting_config_->SetString(remoting::kHostIdConfigPath, host_id);
chromoting_config_->SetString(remoting::kHostNameConfigPath, host_name);
chromoting_config_->Save();
// And then save the key pair.
host_key_pair->Save(chromoting_config_);
}
void ServiceProcess::LoadChromotingConfig() {
// TODO(hclam): We really should be doing this on IO thread so we are not
// blocked on file IOs.
if (chromoting_config_)
return;
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
FilePath chromoting_config_path =
user_data_dir.Append(FILE_PATH_LITERAL(".ChromotingConfig.json"));
chromoting_config_ = new remoting::JsonHostConfig(
chromoting_config_path, file_thread_->message_loop_proxy());
if (!chromoting_config_->Read())
VLOG(1) << "Failed to read chromoting config file.";
}
void ServiceProcess::OnChromotingHostShutdown() {
// TODO(hclam): Implement.
}
#endif
ServiceProcess::~ServiceProcess() {
Teardown();
g_service_process = NULL;
}
// Disable refcounting for runnable method because it is really not needed
// when we post tasks on the main message loop.
DISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcess);
<commit_msg>Stop the chromoting_context<commit_after>// Copyright (c) 2010 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/service/service_process.h"
#include <algorithm>
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/singleton.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/service_process_util.h"
#include "chrome/service/cloud_print/cloud_print_proxy.h"
#include "chrome/service/service_ipc_server.h"
#include "chrome/service/service_process_prefs.h"
#include "net/base/network_change_notifier.h"
#if defined(ENABLE_REMOTING)
#include "remoting/base/constants.h"
#include "remoting/host/chromoting_host.h"
#include "remoting/host/chromoting_host_context.h"
#include "remoting/host/json_host_config.h"
#endif // defined(ENABLED_REMOTING)
ServiceProcess* g_service_process = NULL;
namespace {
// Delay in millseconds after the last service is disabled before we attempt
// a shutdown.
const int64 kShutdownDelay = 60000;
class ServiceIOThread : public base::Thread {
public:
explicit ServiceIOThread(const char* name);
virtual ~ServiceIOThread();
protected:
virtual void CleanUp();
private:
DISALLOW_COPY_AND_ASSIGN(ServiceIOThread);
};
ServiceIOThread::ServiceIOThread(const char* name) : base::Thread(name) {}
ServiceIOThread::~ServiceIOThread() {
// We cannot rely on our base class to stop the thread since we want our
// CleanUp function to run.
Stop();
}
void ServiceIOThread::CleanUp() {
URLFetcher::CancelAll();
}
} // namespace
ServiceProcess::ServiceProcess()
: shutdown_event_(true, false),
main_message_loop_(NULL),
enabled_services_(0),
update_available_(false) {
DCHECK(!g_service_process);
g_service_process = this;
}
bool ServiceProcess::Initialize(MessageLoop* message_loop,
const CommandLine& command_line) {
main_message_loop_ = message_loop;
network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
base::Thread::Options options;
options.message_loop_type = MessageLoop::TYPE_IO;
io_thread_.reset(new ServiceIOThread("ServiceProcess_IO"));
file_thread_.reset(new base::Thread("ServiceProcess_File"));
if (!io_thread_->StartWithOptions(options) ||
!file_thread_->StartWithOptions(options)) {
NOTREACHED();
Teardown();
return false;
}
// See if we have been suppiled an LSID in the command line. This LSID will
// override the credentials we use for Cloud Print.
std::string lsid = command_line.GetSwitchValueASCII(
switches::kServiceAccountLsid);
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
FilePath pref_path = user_data_dir.Append(chrome::kServiceStateFileName);
service_prefs_.reset(
new ServiceProcessPrefs(pref_path, file_thread_->message_loop_proxy()));
service_prefs_->ReadPrefs();
bool remoting_host_enabled = false;
// For development, we allow forcing the enabling of the host daemon via a
// commandline flag, regardless of the preference setting.
//
// TODO(ajwong): When we've gotten the preference setting workflow more
// stable, we should remove the command-line flag force-enable.
service_prefs_->GetBoolean(prefs::kRemotingHostEnabled,
&remoting_host_enabled);
remoting_host_enabled |= command_line.HasSwitch(switches::kEnableRemoting);
#if defined(ENABLE_REMOTING)
// Check if remoting host is already enabled.
if (remoting_host_enabled) {
StartChromotingHost();
}
#endif
// Enable Cloud Print if needed. First check the command-line.
bool cloud_print_proxy_enabled =
command_line.HasSwitch(switches::kEnableCloudPrintProxy);
if (!cloud_print_proxy_enabled) {
// Then check if the cloud print proxy was previously enabled.
service_prefs_->GetBoolean(prefs::kCloudPrintProxyEnabled,
&cloud_print_proxy_enabled);
}
if (cloud_print_proxy_enabled) {
GetCloudPrintProxy()->EnableForUser(lsid);
}
VLOG(1) << "Starting Service Process IPC Server";
ipc_server_.reset(new ServiceIPCServer(GetServiceProcessChannelName()));
ipc_server_->Init();
// After the IPC server has started we signal that the service process is
// ready.
ServiceProcessState::GetInstance()->SignalReady(
NewRunnableMethod(this, &ServiceProcess::Shutdown));
// See if we need to stay running.
ScheduleShutdownCheck();
return true;
}
bool ServiceProcess::Teardown() {
service_prefs_.reset();
cloud_print_proxy_.reset();
#if defined(ENABLE_REMOTING)
ShutdownChromotingHost();
#endif
ipc_server_.reset();
// Signal this event before shutting down the service process. That way all
// background threads can cleanup.
shutdown_event_.Signal();
io_thread_.reset();
file_thread_.reset();
// The NetworkChangeNotifier must be destroyed after all other threads that
// might use it have been shut down.
network_change_notifier_.reset();
ServiceProcessState::GetInstance()->SignalStopped();
return true;
}
void ServiceProcess::Shutdown() {
// Quit the main message loop.
main_message_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
bool ServiceProcess::HandleClientDisconnect() {
// If there are no enabled services or if there is an update available
// we want to shutdown right away. Else we want to keep listening for
// new connections.
if (!enabled_services_ || update_available()) {
Shutdown();
return false;
}
return true;
}
CloudPrintProxy* ServiceProcess::GetCloudPrintProxy() {
if (!cloud_print_proxy_.get()) {
cloud_print_proxy_.reset(new CloudPrintProxy());
cloud_print_proxy_->Initialize(service_prefs_.get(), this);
}
return cloud_print_proxy_.get();
}
void ServiceProcess::OnCloudPrintProxyEnabled() {
// Save the preference that we have enabled the cloud print proxy.
service_prefs_->SetBoolean(prefs::kCloudPrintProxyEnabled, true);
service_prefs_->WritePrefs();
OnServiceEnabled();
}
void ServiceProcess::OnCloudPrintProxyDisabled() {
// Save the preference that we have disabled the cloud print proxy.
service_prefs_->SetBoolean(prefs::kCloudPrintProxyEnabled, false);
service_prefs_->WritePrefs();
OnServiceDisabled();
}
void ServiceProcess::OnServiceEnabled() {
enabled_services_++;
if (1 == enabled_services_) {
ServiceProcessState::GetInstance()->AddToAutoRun();
}
}
void ServiceProcess::OnServiceDisabled() {
DCHECK_NE(enabled_services_, 0);
enabled_services_--;
if (0 == enabled_services_) {
ServiceProcessState::GetInstance()->RemoveFromAutoRun();
// We will wait for some time to respond to IPCs before shutting down.
ScheduleShutdownCheck();
}
}
void ServiceProcess::ScheduleShutdownCheck() {
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
NewRunnableMethod(this, &ServiceProcess::ShutdownIfNeeded),
kShutdownDelay);
}
void ServiceProcess::ShutdownIfNeeded() {
if (0 == enabled_services_) {
if (ipc_server_->is_client_connected()) {
// If there is a client connected, we need to try again later.
// Note that there is still a timing window here because a client may
// decide to connect at this point.
// TODO(sanjeevr): Fix this timing window.
ScheduleShutdownCheck();
} else {
Shutdown();
}
}
}
#if defined(ENABLE_REMOTING)
bool ServiceProcess::EnableChromotingHostWithTokens(
const std::string& login,
const std::string& remoting_token,
const std::string& talk_token) {
// Save the login info and tokens.
remoting_login_ = login;
remoting_token_ = remoting_token;
talk_token_ = talk_token;
// Use the remoting directory to register the host.
if (remoting_directory_.get())
remoting_directory_->CancelRequest();
remoting_directory_.reset(new RemotingDirectoryService(this));
remoting_directory_->AddHost(remoting_token);
return true;
}
bool ServiceProcess::StartChromotingHost() {
// We have already started.
if (chromoting_context_.get())
return true;
// Load chromoting config from the disk.
LoadChromotingConfig();
// Start the chromoting context first.
chromoting_context_.reset(new remoting::ChromotingHostContext());
chromoting_context_->Start();
// Create a chromoting host object.
chromoting_host_ = remoting::ChromotingHost::Create(chromoting_context_.get(),
chromoting_config_);
// Then start the chromoting host.
// When ChromotingHost is shutdown because of failure or a request that
// we made OnChromotingShutdown() is calls.
chromoting_host_->Start(
NewRunnableMethod(this, &ServiceProcess::OnChromotingHostShutdown));
OnServiceEnabled();
return true;
}
bool ServiceProcess::ShutdownChromotingHost() {
// Chromoting host doesn't exist so return true.
if (!chromoting_host_)
return true;
// Shutdown the chromoting host asynchronously. This will signal the host to
// shutdown, we'll actually wait for all threads to stop when we destroy
// the chromoting context.
chromoting_host_->Shutdown();
chromoting_host_ = NULL;
chromoting_context_->Stop();
chromoting_context_ .reset();
return true;
}
void ServiceProcess::OnRemotingHostAdded() {
// Save configuration for chromoting.
SaveChromotingConfig(remoting_login_,
talk_token_,
remoting_directory_->host_id(),
remoting_directory_->host_name(),
remoting_directory_->host_key_pair());
remoting_directory_.reset();
remoting_login_ = "";
remoting_token_ = "";
talk_token_ = "";
// Save the preference that we have enabled the remoting host.
service_prefs_->SetBoolean(prefs::kRemotingHostEnabled, true);
// Force writing prefs to the disk.
service_prefs_->WritePrefs();
// TODO(hclam): If we have a problem we need to send an IPC message back
// to the client that started this.
bool ret = StartChromotingHost();
DCHECK(ret);
}
void ServiceProcess::OnRemotingDirectoryError() {
remoting_directory_.reset();
remoting_login_ = "";
remoting_token_ = "";
talk_token_ = "";
// TODO(hclam): If we have a problem we need to send an IPC message back
// to the client that started this.
}
void ServiceProcess::SaveChromotingConfig(
const std::string& login,
const std::string& token,
const std::string& host_id,
const std::string& host_name,
remoting::HostKeyPair* host_key_pair) {
// First we need to load the config first.
LoadChromotingConfig();
// And then do the update.
chromoting_config_->SetString(remoting::kXmppLoginConfigPath, login);
chromoting_config_->SetString(remoting::kXmppAuthTokenConfigPath, token);
chromoting_config_->SetString(remoting::kHostIdConfigPath, host_id);
chromoting_config_->SetString(remoting::kHostNameConfigPath, host_name);
chromoting_config_->Save();
// And then save the key pair.
host_key_pair->Save(chromoting_config_);
}
void ServiceProcess::LoadChromotingConfig() {
// TODO(hclam): We really should be doing this on IO thread so we are not
// blocked on file IOs.
if (chromoting_config_)
return;
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
FilePath chromoting_config_path =
user_data_dir.Append(FILE_PATH_LITERAL(".ChromotingConfig.json"));
chromoting_config_ = new remoting::JsonHostConfig(
chromoting_config_path, file_thread_->message_loop_proxy());
if (!chromoting_config_->Read())
VLOG(1) << "Failed to read chromoting config file.";
}
void ServiceProcess::OnChromotingHostShutdown() {
// TODO(hclam): Implement.
}
#endif
ServiceProcess::~ServiceProcess() {
Teardown();
g_service_process = NULL;
}
// Disable refcounting for runnable method because it is really not needed
// when we post tasks on the main message loop.
DISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcess);
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
*/
/** @file
* Isa Fake Device implementation
*/
#include "base/trace.hh"
#include "debug/IsaFake.hh"
#include "dev/isa_fake.hh"
#include "mem/packet.hh"
#include "mem/packet_access.hh"
#include "sim/system.hh"
using namespace std;
IsaFake::IsaFake(Params *p)
: BasicPioDevice(p, p->ret_bad_addr ? 0 : p->pio_size)
{
retData8 = p->ret_data8;
retData16 = p->ret_data16;
retData32 = p->ret_data32;
retData64 = p->ret_data64;
}
Tick
IsaFake::read(PacketPtr pkt)
{
pkt->allocate();
pkt->makeAtomicResponse();
if (params()->warn_access != "")
warn("Device %s accessed by read to address %#x size=%d\n",
name(), pkt->getAddr(), pkt->getSize());
if (params()->ret_bad_addr) {
DPRINTF(IsaFake, "read to bad address va=%#x size=%d\n",
pkt->getAddr(), pkt->getSize());
pkt->setBadAddress();
} else {
assert(pkt->getAddr() >= pioAddr && pkt->getAddr() < pioAddr + pioSize);
DPRINTF(IsaFake, "read va=%#x size=%d\n",
pkt->getAddr(), pkt->getSize());
switch (pkt->getSize()) {
case sizeof(uint64_t):
pkt->set(retData64);
break;
case sizeof(uint32_t):
pkt->set(retData32);
break;
case sizeof(uint16_t):
pkt->set(retData16);
break;
case sizeof(uint8_t):
pkt->set(retData8);
break;
default:
if (params()->fake_mem)
std::memset(pkt->getPtr<uint8_t>(), 0, pkt->getSize());
else
panic("invalid access size! Device being accessed by cache?\n");
}
}
return pioDelay;
}
Tick
IsaFake::write(PacketPtr pkt)
{
pkt->makeAtomicResponse();
if (params()->warn_access != "") {
uint64_t data;
switch (pkt->getSize()) {
case sizeof(uint64_t):
data = pkt->get<uint64_t>();
break;
case sizeof(uint32_t):
data = pkt->get<uint32_t>();
break;
case sizeof(uint16_t):
data = pkt->get<uint16_t>();
break;
case sizeof(uint8_t):
data = pkt->get<uint8_t>();
break;
default:
panic("invalid access size!\n");
}
warn("Device %s accessed by write to address %#x size=%d data=%#x\n",
name(), pkt->getAddr(), pkt->getSize(), data);
}
if (params()->ret_bad_addr) {
DPRINTF(IsaFake, "write to bad address va=%#x size=%d \n",
pkt->getAddr(), pkt->getSize());
pkt->setBadAddress();
} else {
DPRINTF(IsaFake, "write - va=%#x size=%d \n",
pkt->getAddr(), pkt->getSize());
if (params()->update_data) {
switch (pkt->getSize()) {
case sizeof(uint64_t):
retData64 = pkt->get<uint64_t>();
break;
case sizeof(uint32_t):
retData32 = pkt->get<uint32_t>();
break;
case sizeof(uint16_t):
retData16 = pkt->get<uint16_t>();
break;
case sizeof(uint8_t):
retData8 = pkt->get<uint8_t>();
break;
default:
panic("invalid access size!\n");
}
}
}
return pioDelay;
}
IsaFake *
IsaFakeParams::create()
{
return new IsaFake(this);
}
<commit_msg>dev: Output invalid access size in IsaFake panic (transplanted from 85274f24c37a1fcc5389ed06410442a5119a6668)<commit_after>/*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
*/
/** @file
* Isa Fake Device implementation
*/
#include "base/trace.hh"
#include "debug/IsaFake.hh"
#include "dev/isa_fake.hh"
#include "mem/packet.hh"
#include "mem/packet_access.hh"
#include "sim/system.hh"
using namespace std;
IsaFake::IsaFake(Params *p)
: BasicPioDevice(p, p->ret_bad_addr ? 0 : p->pio_size)
{
retData8 = p->ret_data8;
retData16 = p->ret_data16;
retData32 = p->ret_data32;
retData64 = p->ret_data64;
}
Tick
IsaFake::read(PacketPtr pkt)
{
pkt->allocate();
pkt->makeAtomicResponse();
if (params()->warn_access != "")
warn("Device %s accessed by read to address %#x size=%d\n",
name(), pkt->getAddr(), pkt->getSize());
if (params()->ret_bad_addr) {
DPRINTF(IsaFake, "read to bad address va=%#x size=%d\n",
pkt->getAddr(), pkt->getSize());
pkt->setBadAddress();
} else {
assert(pkt->getAddr() >= pioAddr && pkt->getAddr() < pioAddr + pioSize);
DPRINTF(IsaFake, "read va=%#x size=%d\n",
pkt->getAddr(), pkt->getSize());
switch (pkt->getSize()) {
case sizeof(uint64_t):
pkt->set(retData64);
break;
case sizeof(uint32_t):
pkt->set(retData32);
break;
case sizeof(uint16_t):
pkt->set(retData16);
break;
case sizeof(uint8_t):
pkt->set(retData8);
break;
default:
if (params()->fake_mem)
std::memset(pkt->getPtr<uint8_t>(), 0, pkt->getSize());
else
panic("invalid access size! Device being accessed by cache?\n");
}
}
return pioDelay;
}
Tick
IsaFake::write(PacketPtr pkt)
{
pkt->makeAtomicResponse();
if (params()->warn_access != "") {
uint64_t data;
switch (pkt->getSize()) {
case sizeof(uint64_t):
data = pkt->get<uint64_t>();
break;
case sizeof(uint32_t):
data = pkt->get<uint32_t>();
break;
case sizeof(uint16_t):
data = pkt->get<uint16_t>();
break;
case sizeof(uint8_t):
data = pkt->get<uint8_t>();
break;
default:
panic("invalid access size: %u\n", pkt->getSize());
}
warn("Device %s accessed by write to address %#x size=%d data=%#x\n",
name(), pkt->getAddr(), pkt->getSize(), data);
}
if (params()->ret_bad_addr) {
DPRINTF(IsaFake, "write to bad address va=%#x size=%d \n",
pkt->getAddr(), pkt->getSize());
pkt->setBadAddress();
} else {
DPRINTF(IsaFake, "write - va=%#x size=%d \n",
pkt->getAddr(), pkt->getSize());
if (params()->update_data) {
switch (pkt->getSize()) {
case sizeof(uint64_t):
retData64 = pkt->get<uint64_t>();
break;
case sizeof(uint32_t):
retData32 = pkt->get<uint32_t>();
break;
case sizeof(uint16_t):
retData16 = pkt->get<uint16_t>();
break;
case sizeof(uint8_t):
retData8 = pkt->get<uint8_t>();
break;
default:
panic("invalid access size!\n");
}
}
}
return pioDelay;
}
IsaFake *
IsaFakeParams::create()
{
return new IsaFake(this);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/views/single_split_view.h"
#include "base/gfx/skia_utils.h"
#include "chrome/common/gfx/chrome_canvas.h"
namespace views {
// Size of the divider in pixels.
static const int kDividerSize = 6;
SingleSplitView::SingleSplitView(View* leading,
View* trailing) : divider_x_(-1) {
AddChildView(leading);
AddChildView(trailing);
}
void SingleSplitView::PaintBackground(ChromeCanvas* canvas) {
canvas->drawColor(gfx::COLORREFToSkColor(GetSysColor(COLOR_3DFACE)),
SkPorterDuff::kSrc_Mode);
}
void SingleSplitView::Layout() {
if (GetChildViewCount() != 2)
return;
View* leading = GetChildViewAt(0);
View* trailing = GetChildViewAt(1);
if (divider_x_ < 0)
divider_x_ = (width() - kDividerSize) / 2;
else
divider_x_ = std::min(divider_x_, width() - kDividerSize);
leading->SetBounds(0, 0, divider_x_, height());
trailing->SetBounds(divider_x_ + kDividerSize, 0,
width() - divider_x_ - kDividerSize, height());
SchedulePaint();
// Invoke super's implementation so that the children are layed out.
View::Layout();
}
gfx::Size SingleSplitView::GetPreferredSize() {
int width = 0;
int height = 0;
for (int i = 0; i < 2 && i < GetChildViewCount(); ++i) {
View* view = GetChildViewAt(i);
gfx::Size pref = view->GetPreferredSize();
width += pref.width();
height = std::max(height, pref.height());
}
width += kDividerSize;
return gfx::Size(width, height);
}
HCURSOR SingleSplitView::GetCursorForPoint(Event::EventType event_type,
int x,
int y) {
if (IsPointInDivider(x)) {
static HCURSOR resize_cursor = LoadCursor(NULL, IDC_SIZEWE);
return resize_cursor;
}
return NULL;
}
bool SingleSplitView::OnMousePressed(const MouseEvent& event) {
if (!IsPointInDivider(event.x()))
return false;
drag_info_.initial_mouse_x = event.x();
drag_info_.initial_divider_x = divider_x_;
return true;
}
bool SingleSplitView::OnMouseDragged(const MouseEvent& event) {
if (GetChildViewCount() < 2)
return false;
int delta_x = event.x() - drag_info_.initial_mouse_x;
if (UILayoutIsRightToLeft())
delta_x *= -1;
// Honor the minimum size when resizing.
int new_width = std::max(GetChildViewAt(0)->GetMinimumSize().width(),
drag_info_.initial_divider_x + delta_x);
// And don't let the view get bigger than our width.
new_width = std::min(width() - kDividerSize, new_width);
if (new_width != divider_x_) {
set_divider_x(new_width);
Layout();
}
return true;
}
void SingleSplitView::OnMouseReleased(const MouseEvent& event, bool canceled) {
if (GetChildViewCount() < 2)
return;
if (canceled && drag_info_.initial_divider_x != divider_x_) {
set_divider_x(drag_info_.initial_divider_x);
Layout();
}
}
bool SingleSplitView::IsPointInDivider(int x) {
if (GetChildViewCount() < 2)
return false;
View* leading = GetChildViewAt(0);
int divider_relative_x =
x - MirroredXCoordinateInsideView(leading->width());
return (divider_relative_x >= 0 && divider_relative_x < kDividerSize);
}
} // namespace views
<commit_msg>Fixes resizing of single split view for RTL case.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/views/single_split_view.h"
#include "base/gfx/skia_utils.h"
#include "chrome/common/gfx/chrome_canvas.h"
namespace views {
// Size of the divider in pixels.
static const int kDividerSize = 6;
SingleSplitView::SingleSplitView(View* leading,
View* trailing) : divider_x_(-1) {
AddChildView(leading);
AddChildView(trailing);
}
void SingleSplitView::PaintBackground(ChromeCanvas* canvas) {
canvas->drawColor(gfx::COLORREFToSkColor(GetSysColor(COLOR_3DFACE)),
SkPorterDuff::kSrc_Mode);
}
void SingleSplitView::Layout() {
if (GetChildViewCount() != 2)
return;
View* leading = GetChildViewAt(0);
View* trailing = GetChildViewAt(1);
if (divider_x_ < 0)
divider_x_ = (width() - kDividerSize) / 2;
else
divider_x_ = std::min(divider_x_, width() - kDividerSize);
leading->SetBounds(0, 0, divider_x_, height());
trailing->SetBounds(divider_x_ + kDividerSize, 0,
width() - divider_x_ - kDividerSize, height());
SchedulePaint();
// Invoke super's implementation so that the children are layed out.
View::Layout();
}
gfx::Size SingleSplitView::GetPreferredSize() {
int width = 0;
int height = 0;
for (int i = 0; i < 2 && i < GetChildViewCount(); ++i) {
View* view = GetChildViewAt(i);
gfx::Size pref = view->GetPreferredSize();
width += pref.width();
height = std::max(height, pref.height());
}
width += kDividerSize;
return gfx::Size(width, height);
}
HCURSOR SingleSplitView::GetCursorForPoint(Event::EventType event_type,
int x,
int y) {
if (IsPointInDivider(x)) {
static HCURSOR resize_cursor = LoadCursor(NULL, IDC_SIZEWE);
return resize_cursor;
}
return NULL;
}
bool SingleSplitView::OnMousePressed(const MouseEvent& event) {
if (!IsPointInDivider(event.x()))
return false;
drag_info_.initial_mouse_x = event.x();
drag_info_.initial_divider_x = divider_x_;
return true;
}
bool SingleSplitView::OnMouseDragged(const MouseEvent& event) {
if (GetChildViewCount() < 2)
return false;
int delta_x = event.x() - drag_info_.initial_mouse_x;
if (UILayoutIsRightToLeft())
delta_x *= -1;
// Honor the minimum size when resizing.
int new_width = std::max(GetChildViewAt(0)->GetMinimumSize().width(),
drag_info_.initial_divider_x + delta_x);
// And don't let the view get bigger than our width.
new_width = std::min(width() - kDividerSize, new_width);
if (new_width != divider_x_) {
set_divider_x(new_width);
Layout();
}
return true;
}
void SingleSplitView::OnMouseReleased(const MouseEvent& event, bool canceled) {
if (GetChildViewCount() < 2)
return;
if (canceled && drag_info_.initial_divider_x != divider_x_) {
set_divider_x(drag_info_.initial_divider_x);
Layout();
}
}
bool SingleSplitView::IsPointInDivider(int x) {
if (GetChildViewCount() < 2)
return false;
int divider_relative_x =
x - GetChildViewAt(UILayoutIsRightToLeft() ? 1 : 0)->width();
return (divider_relative_x >= 0 && divider_relative_x < kDividerSize);
}
} // namespace views
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
*/
/** @file
* Implements a 8250 UART
*/
#include <string>
#include <vector>
#include "base/inifile.hh"
#include "base/str.hh" // for to_number
#include "base/trace.hh"
#include "dev/simconsole.hh"
#include "dev/uart8250.hh"
#include "dev/platform.hh"
#include "mem/packet.hh"
#include "mem/packet_access.hh"
#include "sim/builder.hh"
using namespace std;
using namespace TheISA;
Uart8250::IntrEvent::IntrEvent(Uart8250 *u, int bit)
: Event(&mainEventQueue), uart(u)
{
DPRINTF(Uart, "UART Interrupt Event Initilizing\n");
intrBit = bit;
}
const char *
Uart8250::IntrEvent::description()
{
return "uart interrupt delay event";
}
void
Uart8250::IntrEvent::process()
{
if (intrBit & uart->IER) {
DPRINTF(Uart, "UART InterEvent, interrupting\n");
uart->platform->postConsoleInt();
uart->status |= intrBit;
uart->lastTxInt = curTick;
}
else
DPRINTF(Uart, "UART InterEvent, not interrupting\n");
}
/* The linux serial driver (8250.c about line 1182) loops reading from
* the device until the device reports it has no more data to
* read. After a maximum of 255 iterations the code prints "serial8250
* too much work for irq X," and breaks out of the loop. Since the
* simulated system is so much slower than the actual system, if a
* user is typing on the keyboard it is very easy for them to provide
* input at a fast enough rate to not allow the loop to exit and thus
* the error to be printed. This magic number provides a delay between
* the time the UART receives a character to send to the simulated
* system and the time it actually notifies the system it has a
* character to send to alleviate this problem. --Ali
*/
void
Uart8250::IntrEvent::scheduleIntr()
{
static const Tick interval = (Tick)((Clock::Float::s / 2e9) * 450);
DPRINTF(Uart, "Scheduling IER interrupt for %#x, at cycle %lld\n", intrBit,
curTick + interval);
if (!scheduled())
schedule(curTick + interval);
else
reschedule(curTick + interval);
}
Uart8250::Uart8250(Params *p)
: Uart(p), txIntrEvent(this, TX_INT), rxIntrEvent(this, RX_INT)
{
pioSize = 8;
IER = 0;
DLAB = 0;
LCR = 0;
MCR = 0;
}
Tick
Uart8250::read(PacketPtr pkt)
{
assert(pkt->result == Packet::Unknown);
assert(pkt->getAddr() >= pioAddr && pkt->getAddr() < pioAddr + pioSize);
assert(pkt->getSize() == 1);
Addr daddr = pkt->getAddr() - pioAddr;
pkt->allocate();
DPRINTF(Uart, " read register %#x\n", daddr);
switch (daddr) {
case 0x0:
if (!(LCR & 0x80)) { // read byte
if (cons->dataAvailable())
pkt->set(cons->in());
else {
pkt->set((uint8_t)0);
// A limited amount of these are ok.
DPRINTF(Uart, "empty read of RX register\n");
}
status &= ~RX_INT;
platform->clearConsoleInt();
if (cons->dataAvailable() && (IER & UART_IER_RDI))
rxIntrEvent.scheduleIntr();
} else { // dll divisor latch
;
}
break;
case 0x1:
if (!(LCR & 0x80)) { // Intr Enable Register(IER)
pkt->set(IER);
} else { // DLM divisor latch MSB
;
}
break;
case 0x2: // Intr Identification Register (IIR)
DPRINTF(Uart, "IIR Read, status = %#x\n", (uint32_t)status);
if (status & RX_INT) /* Rx data interrupt has a higher priority */
pkt->set(IIR_RXID);
else if (status & TX_INT) {
pkt->set(IIR_TXID);
//Tx interrupts are cleared on IIR reads
status &= ~TX_INT;
} else
pkt->set(IIR_NOPEND);
break;
case 0x3: // Line Control Register (LCR)
pkt->set(LCR);
break;
case 0x4: // Modem Control Register (MCR)
break;
case 0x5: // Line Status Register (LSR)
uint8_t lsr;
lsr = 0;
// check if there are any bytes to be read
if (cons->dataAvailable())
lsr = UART_LSR_DR;
lsr |= UART_LSR_TEMT | UART_LSR_THRE;
pkt->set(lsr);
break;
case 0x6: // Modem Status Register (MSR)
pkt->set((uint8_t)0);
break;
case 0x7: // Scratch Register (SCR)
pkt->set((uint8_t)0); // doesn't exist with at 8250.
break;
default:
panic("Tried to access a UART port that doesn't exist\n");
break;
}
/* uint32_t d32 = *data;
DPRINTF(Uart, "Register read to register %#x returned %#x\n", daddr, d32);
*/
pkt->result = Packet::Success;
return pioDelay;
}
Tick
Uart8250::write(PacketPtr pkt)
{
assert(pkt->result == Packet::Unknown);
assert(pkt->getAddr() >= pioAddr && pkt->getAddr() < pioAddr + pioSize);
assert(pkt->getSize() == 1);
Addr daddr = pkt->getAddr() - pioAddr;
DPRINTF(Uart, " write register %#x value %#x\n", daddr, pkt->get<uint8_t>());
switch (daddr) {
case 0x0:
if (!(LCR & 0x80)) { // write byte
cons->out(pkt->get<uint8_t>());
platform->clearConsoleInt();
status &= ~TX_INT;
if (UART_IER_THRI & IER)
txIntrEvent.scheduleIntr();
} else { // dll divisor latch
;
}
break;
case 0x1:
if (!(LCR & 0x80)) { // Intr Enable Register(IER)
IER = pkt->get<uint8_t>();
if (UART_IER_THRI & IER)
{
DPRINTF(Uart, "IER: IER_THRI set, scheduling TX intrrupt\n");
if (curTick - lastTxInt >
(Tick)((Clock::Float::s / 2e9) * 450)) {
DPRINTF(Uart, "-- Interrupting Immediately... %d,%d\n",
curTick, lastTxInt);
txIntrEvent.process();
} else {
DPRINTF(Uart, "-- Delaying interrupt... %d,%d\n",
curTick, lastTxInt);
txIntrEvent.scheduleIntr();
}
}
else
{
DPRINTF(Uart, "IER: IER_THRI cleared, descheduling TX intrrupt\n");
if (txIntrEvent.scheduled())
txIntrEvent.deschedule();
if (status & TX_INT)
platform->clearConsoleInt();
status &= ~TX_INT;
}
if ((UART_IER_RDI & IER) && cons->dataAvailable()) {
DPRINTF(Uart, "IER: IER_RDI set, scheduling RX intrrupt\n");
rxIntrEvent.scheduleIntr();
} else {
DPRINTF(Uart, "IER: IER_RDI cleared, descheduling RX intrrupt\n");
if (rxIntrEvent.scheduled())
rxIntrEvent.deschedule();
if (status & RX_INT)
platform->clearConsoleInt();
status &= ~RX_INT;
}
} else { // DLM divisor latch MSB
;
}
break;
case 0x2: // FIFO Control Register (FCR)
break;
case 0x3: // Line Control Register (LCR)
LCR = pkt->get<uint8_t>();
break;
case 0x4: // Modem Control Register (MCR)
if (pkt->get<uint8_t>() == (UART_MCR_LOOP | 0x0A))
MCR = 0x9A;
break;
case 0x7: // Scratch Register (SCR)
// We are emulating a 8250 so we don't have a scratch reg
break;
default:
panic("Tried to access a UART port that doesn't exist\n");
break;
}
pkt->result = Packet::Success;
return pioDelay;
}
void
Uart8250::dataAvailable()
{
// if the kernel wants an interrupt when we have data
if (IER & UART_IER_RDI)
{
platform->postConsoleInt();
status |= RX_INT;
}
}
void
Uart8250::addressRanges(AddrRangeList &range_list)
{
assert(pioSize != 0);
range_list.clear();
range_list.push_back(RangeSize(pioAddr, pioSize));
}
void
Uart8250::serialize(ostream &os)
{
SERIALIZE_SCALAR(status);
SERIALIZE_SCALAR(IER);
SERIALIZE_SCALAR(DLAB);
SERIALIZE_SCALAR(LCR);
SERIALIZE_SCALAR(MCR);
Tick rxintrwhen;
if (rxIntrEvent.scheduled())
rxintrwhen = rxIntrEvent.when();
else
rxintrwhen = 0;
Tick txintrwhen;
if (txIntrEvent.scheduled())
txintrwhen = txIntrEvent.when();
else
txintrwhen = 0;
SERIALIZE_SCALAR(rxintrwhen);
SERIALIZE_SCALAR(txintrwhen);
}
void
Uart8250::unserialize(Checkpoint *cp, const std::string §ion)
{
UNSERIALIZE_SCALAR(status);
UNSERIALIZE_SCALAR(IER);
UNSERIALIZE_SCALAR(DLAB);
UNSERIALIZE_SCALAR(LCR);
UNSERIALIZE_SCALAR(MCR);
Tick rxintrwhen;
Tick txintrwhen;
UNSERIALIZE_SCALAR(rxintrwhen);
UNSERIALIZE_SCALAR(txintrwhen);
if (rxintrwhen != 0)
rxIntrEvent.schedule(rxintrwhen);
if (txintrwhen != 0)
txIntrEvent.schedule(txintrwhen);
}
BEGIN_DECLARE_SIM_OBJECT_PARAMS(Uart8250)
Param<Addr> pio_addr;
Param<Tick> pio_latency;
SimObjectParam<Platform *> platform;
SimObjectParam<SimConsole *> sim_console;
SimObjectParam<System *> system;
END_DECLARE_SIM_OBJECT_PARAMS(Uart8250)
BEGIN_INIT_SIM_OBJECT_PARAMS(Uart8250)
INIT_PARAM(pio_addr, "Device Address"),
INIT_PARAM_DFLT(pio_latency, "Programmed IO latency", 1000),
INIT_PARAM(platform, "platform"),
INIT_PARAM(sim_console, "The Simulator Console"),
INIT_PARAM(system, "system object")
END_INIT_SIM_OBJECT_PARAMS(Uart8250)
CREATE_SIM_OBJECT(Uart8250)
{
Uart8250::Params *p = new Uart8250::Params;
p->name = getInstanceName();
p->pio_addr = pio_addr;
p->pio_delay = pio_latency;
p->platform = platform;
p->cons = sim_console;
p->system = system;
return new Uart8250(p);
}
REGISTER_SIM_OBJECT("Uart8250", Uart8250)
<commit_msg>initialize lastTxInt to 0<commit_after>/*
* Copyright (c) 2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
*/
/** @file
* Implements a 8250 UART
*/
#include <string>
#include <vector>
#include "base/inifile.hh"
#include "base/str.hh" // for to_number
#include "base/trace.hh"
#include "dev/simconsole.hh"
#include "dev/uart8250.hh"
#include "dev/platform.hh"
#include "mem/packet.hh"
#include "mem/packet_access.hh"
#include "sim/builder.hh"
using namespace std;
using namespace TheISA;
Uart8250::IntrEvent::IntrEvent(Uart8250 *u, int bit)
: Event(&mainEventQueue), uart(u)
{
DPRINTF(Uart, "UART Interrupt Event Initilizing\n");
intrBit = bit;
}
const char *
Uart8250::IntrEvent::description()
{
return "uart interrupt delay event";
}
void
Uart8250::IntrEvent::process()
{
if (intrBit & uart->IER) {
DPRINTF(Uart, "UART InterEvent, interrupting\n");
uart->platform->postConsoleInt();
uart->status |= intrBit;
uart->lastTxInt = curTick;
}
else
DPRINTF(Uart, "UART InterEvent, not interrupting\n");
}
/* The linux serial driver (8250.c about line 1182) loops reading from
* the device until the device reports it has no more data to
* read. After a maximum of 255 iterations the code prints "serial8250
* too much work for irq X," and breaks out of the loop. Since the
* simulated system is so much slower than the actual system, if a
* user is typing on the keyboard it is very easy for them to provide
* input at a fast enough rate to not allow the loop to exit and thus
* the error to be printed. This magic number provides a delay between
* the time the UART receives a character to send to the simulated
* system and the time it actually notifies the system it has a
* character to send to alleviate this problem. --Ali
*/
void
Uart8250::IntrEvent::scheduleIntr()
{
static const Tick interval = (Tick)((Clock::Float::s / 2e9) * 450);
DPRINTF(Uart, "Scheduling IER interrupt for %#x, at cycle %lld\n", intrBit,
curTick + interval);
if (!scheduled())
schedule(curTick + interval);
else
reschedule(curTick + interval);
}
Uart8250::Uart8250(Params *p)
: Uart(p), IER(0), DLAB(0), LCR(0), MCR(0), lastTxInt(0),
txIntrEvent(this, TX_INT), rxIntrEvent(this, RX_INT)
{
pioSize = 8;
}
Tick
Uart8250::read(PacketPtr pkt)
{
assert(pkt->result == Packet::Unknown);
assert(pkt->getAddr() >= pioAddr && pkt->getAddr() < pioAddr + pioSize);
assert(pkt->getSize() == 1);
Addr daddr = pkt->getAddr() - pioAddr;
pkt->allocate();
DPRINTF(Uart, " read register %#x\n", daddr);
switch (daddr) {
case 0x0:
if (!(LCR & 0x80)) { // read byte
if (cons->dataAvailable())
pkt->set(cons->in());
else {
pkt->set((uint8_t)0);
// A limited amount of these are ok.
DPRINTF(Uart, "empty read of RX register\n");
}
status &= ~RX_INT;
platform->clearConsoleInt();
if (cons->dataAvailable() && (IER & UART_IER_RDI))
rxIntrEvent.scheduleIntr();
} else { // dll divisor latch
;
}
break;
case 0x1:
if (!(LCR & 0x80)) { // Intr Enable Register(IER)
pkt->set(IER);
} else { // DLM divisor latch MSB
;
}
break;
case 0x2: // Intr Identification Register (IIR)
DPRINTF(Uart, "IIR Read, status = %#x\n", (uint32_t)status);
if (status & RX_INT) /* Rx data interrupt has a higher priority */
pkt->set(IIR_RXID);
else if (status & TX_INT) {
pkt->set(IIR_TXID);
//Tx interrupts are cleared on IIR reads
status &= ~TX_INT;
} else
pkt->set(IIR_NOPEND);
break;
case 0x3: // Line Control Register (LCR)
pkt->set(LCR);
break;
case 0x4: // Modem Control Register (MCR)
break;
case 0x5: // Line Status Register (LSR)
uint8_t lsr;
lsr = 0;
// check if there are any bytes to be read
if (cons->dataAvailable())
lsr = UART_LSR_DR;
lsr |= UART_LSR_TEMT | UART_LSR_THRE;
pkt->set(lsr);
break;
case 0x6: // Modem Status Register (MSR)
pkt->set((uint8_t)0);
break;
case 0x7: // Scratch Register (SCR)
pkt->set((uint8_t)0); // doesn't exist with at 8250.
break;
default:
panic("Tried to access a UART port that doesn't exist\n");
break;
}
/* uint32_t d32 = *data;
DPRINTF(Uart, "Register read to register %#x returned %#x\n", daddr, d32);
*/
pkt->result = Packet::Success;
return pioDelay;
}
Tick
Uart8250::write(PacketPtr pkt)
{
assert(pkt->result == Packet::Unknown);
assert(pkt->getAddr() >= pioAddr && pkt->getAddr() < pioAddr + pioSize);
assert(pkt->getSize() == 1);
Addr daddr = pkt->getAddr() - pioAddr;
DPRINTF(Uart, " write register %#x value %#x\n", daddr, pkt->get<uint8_t>());
switch (daddr) {
case 0x0:
if (!(LCR & 0x80)) { // write byte
cons->out(pkt->get<uint8_t>());
platform->clearConsoleInt();
status &= ~TX_INT;
if (UART_IER_THRI & IER)
txIntrEvent.scheduleIntr();
} else { // dll divisor latch
;
}
break;
case 0x1:
if (!(LCR & 0x80)) { // Intr Enable Register(IER)
IER = pkt->get<uint8_t>();
if (UART_IER_THRI & IER)
{
DPRINTF(Uart, "IER: IER_THRI set, scheduling TX intrrupt\n");
if (curTick - lastTxInt >
(Tick)((Clock::Float::s / 2e9) * 450)) {
DPRINTF(Uart, "-- Interrupting Immediately... %d,%d\n",
curTick, lastTxInt);
txIntrEvent.process();
} else {
DPRINTF(Uart, "-- Delaying interrupt... %d,%d\n",
curTick, lastTxInt);
txIntrEvent.scheduleIntr();
}
}
else
{
DPRINTF(Uart, "IER: IER_THRI cleared, descheduling TX intrrupt\n");
if (txIntrEvent.scheduled())
txIntrEvent.deschedule();
if (status & TX_INT)
platform->clearConsoleInt();
status &= ~TX_INT;
}
if ((UART_IER_RDI & IER) && cons->dataAvailable()) {
DPRINTF(Uart, "IER: IER_RDI set, scheduling RX intrrupt\n");
rxIntrEvent.scheduleIntr();
} else {
DPRINTF(Uart, "IER: IER_RDI cleared, descheduling RX intrrupt\n");
if (rxIntrEvent.scheduled())
rxIntrEvent.deschedule();
if (status & RX_INT)
platform->clearConsoleInt();
status &= ~RX_INT;
}
} else { // DLM divisor latch MSB
;
}
break;
case 0x2: // FIFO Control Register (FCR)
break;
case 0x3: // Line Control Register (LCR)
LCR = pkt->get<uint8_t>();
break;
case 0x4: // Modem Control Register (MCR)
if (pkt->get<uint8_t>() == (UART_MCR_LOOP | 0x0A))
MCR = 0x9A;
break;
case 0x7: // Scratch Register (SCR)
// We are emulating a 8250 so we don't have a scratch reg
break;
default:
panic("Tried to access a UART port that doesn't exist\n");
break;
}
pkt->result = Packet::Success;
return pioDelay;
}
void
Uart8250::dataAvailable()
{
// if the kernel wants an interrupt when we have data
if (IER & UART_IER_RDI)
{
platform->postConsoleInt();
status |= RX_INT;
}
}
void
Uart8250::addressRanges(AddrRangeList &range_list)
{
assert(pioSize != 0);
range_list.clear();
range_list.push_back(RangeSize(pioAddr, pioSize));
}
void
Uart8250::serialize(ostream &os)
{
SERIALIZE_SCALAR(status);
SERIALIZE_SCALAR(IER);
SERIALIZE_SCALAR(DLAB);
SERIALIZE_SCALAR(LCR);
SERIALIZE_SCALAR(MCR);
Tick rxintrwhen;
if (rxIntrEvent.scheduled())
rxintrwhen = rxIntrEvent.when();
else
rxintrwhen = 0;
Tick txintrwhen;
if (txIntrEvent.scheduled())
txintrwhen = txIntrEvent.when();
else
txintrwhen = 0;
SERIALIZE_SCALAR(rxintrwhen);
SERIALIZE_SCALAR(txintrwhen);
}
void
Uart8250::unserialize(Checkpoint *cp, const std::string §ion)
{
UNSERIALIZE_SCALAR(status);
UNSERIALIZE_SCALAR(IER);
UNSERIALIZE_SCALAR(DLAB);
UNSERIALIZE_SCALAR(LCR);
UNSERIALIZE_SCALAR(MCR);
Tick rxintrwhen;
Tick txintrwhen;
UNSERIALIZE_SCALAR(rxintrwhen);
UNSERIALIZE_SCALAR(txintrwhen);
if (rxintrwhen != 0)
rxIntrEvent.schedule(rxintrwhen);
if (txintrwhen != 0)
txIntrEvent.schedule(txintrwhen);
}
BEGIN_DECLARE_SIM_OBJECT_PARAMS(Uart8250)
Param<Addr> pio_addr;
Param<Tick> pio_latency;
SimObjectParam<Platform *> platform;
SimObjectParam<SimConsole *> sim_console;
SimObjectParam<System *> system;
END_DECLARE_SIM_OBJECT_PARAMS(Uart8250)
BEGIN_INIT_SIM_OBJECT_PARAMS(Uart8250)
INIT_PARAM(pio_addr, "Device Address"),
INIT_PARAM_DFLT(pio_latency, "Programmed IO latency", 1000),
INIT_PARAM(platform, "platform"),
INIT_PARAM(sim_console, "The Simulator Console"),
INIT_PARAM(system, "system object")
END_INIT_SIM_OBJECT_PARAMS(Uart8250)
CREATE_SIM_OBJECT(Uart8250)
{
Uart8250::Params *p = new Uart8250::Params;
p->name = getInstanceName();
p->pio_addr = pio_addr;
p->pio_delay = pio_latency;
p->platform = platform;
p->cons = sim_console;
p->system = system;
return new Uart8250(p);
}
REGISTER_SIM_OBJECT("Uart8250", Uart8250)
<|endoftext|> |
<commit_before>#include "Quadrant.h"
#include <iostream>
#include "Globals.h"
Quadrant::Quadrant(QuadrantCoordinates* coordinates)
{
this->coordinates = coordinates;
glm::vec3 v = glm::vec3(0.0,0.0,0.0);
this->influenceVector = new InfluenceVector(0, glm::vec3(0.0,0.0,0.0));
}
std::vector<Particle> Quadrant::getParticles()
{
return std::vector<Particle>();
}
void Quadrant::setParticles(Particle particles[])
{
}
void Quadrant::calculateInfluenceVector()
{
float x = -1 * this->coordinates->getX();
float y = -1 * this->coordinates->getY();
float z = -1 * this->coordinates->getZ();
this->influenceVector->setVector(glm::vec3(x,y,z));
this->influenceVector->setIntensity(this->calculateIntensity());
}
double Quadrant::calculateIntensity()
{
double particle_influence = (double)this->particles.size() * PARTICLE_INFLUENCE;
}
Quadrant::~Quadrant(void)
{
}
<commit_msg>alkohol oder was<commit_after>#include "Quadrant.h"
#include <iostream>
#include "Globals.h"
Quadrant::Quadrant(QuadrantCoordinates* coordinates)
{
this->coordinates = coordinates;
glm::vec3 v = glm::vec3(0.0,0.0,0.0);
this->influenceVector = new InfluenceVector(0, glm::vec3(0.0,0.0,0.0));
}
std::vector<Particle> Quadrant::getParticles()
{
return std::vector<Particle>();
}
void Quadrant::setParticles(Particle particles[])
{
}
void Quadrant::calculateInfluenceVector()
{
float x = -1 * this->coordinates->getX();
float y = -1 * this->coordinates->getY();
float z = -1 * this->coordinates->getZ();
this->influenceVector->setVector(glm::vec3(x,y,z));
this->influenceVector->setIntensity(this->calculateIntensity());
}
double Quadrant::calculateIntensity()
{
double particle_influence = (double)this->particles.size() * PARTICLE_INFLUENCE;
}
Quadrant::~Quadrant(void)
{
}
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
}
<commit_msg>thread safe deque<commit_after>#include <iostream>
#include <mutex>
#include <deque>
using namespace std;
typedef unsigned char BYTE
// thread safe queuing
mutex mu;
deque<BYTE*> callQueue;
void add(BYTE* bytes) {
lock_guard<mutex> locker(mu);
callQueue.push_back(bytes);
}
deque<BYTE*> getAll() {
lock_guard<mutex> locker(mu);
deque<BYTE*> ret = callQueue;
callQueue.clear();
return ret;
}
int main() {
cout << "Hello World!" << endl;
}
<|endoftext|> |
<commit_before>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2006 Laurent Ribon ([email protected])
Version 0.9.6, packaged on June, 2006.
http://glc-lib.sourceforge.net
GLC-lib 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.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_material.cpp implementation of the GLC_Material class.
#include <QtDebug>
#include <assert.h>
#include "glc_material.h"
#include "glc_collection.h"
//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Material::GLC_Material()
:GLC_Object("Material")
, m_fShininess(50.0) // By default shininess 50
, m_pTexture(NULL) // no texture
{
// Ambient Color
initAmbientColor();
// Others
initOtherColor();
}
GLC_Material::GLC_Material(const QColor &ambientColor)
:GLC_Object("Material")
, m_fShininess(50.0) // default : shininess 50
, m_pTexture(NULL) // no texture
{
m_AmbientColor= ambientColor;
// Others
initOtherColor();
}
GLC_Material::GLC_Material(const char *pName ,const GLfloat *pAmbientColor)
:GLC_Object(pName)
, m_fShininess(50.0) // default : shininess 50
, m_pTexture(NULL) // no texture
{
// Init Ambiant Color
if (pAmbientColor != 0)
{
m_AmbientColor.setRgbF(static_cast<qreal>(pAmbientColor[0]),
static_cast<qreal>(pAmbientColor[1]),
static_cast<qreal>(pAmbientColor[2]),
static_cast<qreal>(pAmbientColor[3]));
}
else
{
initAmbientColor();
}
// Others
initOtherColor();
}
GLC_Material::GLC_Material(GLC_Texture* pTexture, const char *pName)
:GLC_Object(pName)
, m_fShininess(50.0) // By default shininess 50
, m_pTexture(pTexture) // Init texture
{
// Ambiente Color
initAmbientColor();
// Others
initOtherColor();
}
// Copy constructor
GLC_Material::GLC_Material(const GLC_Material &InitMaterial)
:GLC_Object(InitMaterial.getName())
, m_fShininess(InitMaterial.m_fShininess)
, m_pTexture(NULL)
{
if (NULL != InitMaterial.m_pTexture)
{
m_pTexture= new GLC_Texture(*(InitMaterial.m_pTexture));
assert(m_pTexture != NULL);
}
// Ambient Color
m_AmbientColor= InitMaterial.m_AmbientColor;
// Diffuse Color
m_DiffuseColor= InitMaterial.m_DiffuseColor;
// Specular Color
m_SpecularColor= InitMaterial.m_SpecularColor;
// Lighting emit
m_LightEmission= InitMaterial.m_LightEmission;
}
// Destructor
GLC_Material::~GLC_Material(void)
{
// clear whereUSED Hash table
m_WhereUsed.clear();
if (NULL != m_pTexture)
{
delete m_pTexture;
m_pTexture= NULL;
}
}
//////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////
// Get Ambiant color
QColor GLC_Material::getAmbientColor() const
{
return m_AmbientColor;
}
// Get diffuse color
QColor GLC_Material::getDiffuseColor() const
{
return m_DiffuseColor;
}
// Get specular color
QColor GLC_Material::getSpecularColor() const
{
return m_SpecularColor;
}
// Get the emissive color
QColor GLC_Material::getLightEmission() const
{
return m_LightEmission;
}
// Get the texture File Name
QString GLC_Material::getTextureFileName() const
{
if (m_pTexture != NULL)
{
return m_pTexture->getTextureFileName();
}
else
{
return "";
}
}
// Get Texture Id
GLuint GLC_Material::getTextureID() const
{
if (m_pTexture != NULL)
{
return m_pTexture->getTextureID();
}
else
{
return 0;
}
}
// return true if the texture is loaded
bool GLC_Material::textureIsLoaded() const
{
if (m_pTexture != NULL)
{
return m_pTexture->isLoaded();
}
else
{
return false;
}
}
//////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Set Material properties
void GLC_Material::setMaterial(const GLC_Material* pMat)
{
if (NULL != pMat->m_pTexture)
{
GLC_Texture* pTexture= new GLC_Texture(*(pMat->m_pTexture));
setTexture(pTexture);
}
// Ambient Color
m_AmbientColor= pMat->m_AmbientColor;
// Diffuse Color
m_DiffuseColor= pMat->m_DiffuseColor;
// Specular Color
m_SpecularColor= pMat->m_SpecularColor;
// Lighting emit
m_LightEmission= pMat->m_LightEmission;
m_fShininess= pMat->m_fShininess;
updateUsed();
}
// Set Ambiant Color
void GLC_Material::setAmbientColor(const QColor& ambientColor)
{
m_AmbientColor= ambientColor;
updateUsed();
}
// Set Diffuse color
void GLC_Material::setDiffuseColor(const QColor& diffuseColor)
{
m_DiffuseColor= diffuseColor;
updateUsed();
}
// Set Specular color
void GLC_Material::setSpecularColor(const QColor& specularColor)
{
m_SpecularColor= specularColor;
updateUsed();
}
// Set Emissive
void GLC_Material::setLightEmission(const QColor& lightEmission)
{
m_LightEmission= lightEmission;
updateUsed();
}
// Set Texture
void GLC_Material::setTexture(GLC_Texture* pTexture)
{
qDebug() << "GLC_Material::SetTexture";
if (m_pTexture != NULL)
{
delete m_pTexture;
m_pTexture= pTexture;
glLoadTexture();
}
else
{
// It is not sure that there is OpenGL context
m_pTexture= pTexture;
}
updateUsed();
}
// remove Material Texture
void GLC_Material::removeTexture()
{
if (m_pTexture != NULL)
{
delete m_pTexture;
m_pTexture= NULL;
updateUsed();
}
}
// Add Geometry to where used hash table
bool GLC_Material::addGLC_Geom(GLC_Geometry* pGeom)
{
CWhereUsed::iterator iGeom= m_WhereUsed.find(pGeom->getID());
if (iGeom == m_WhereUsed.end())
{ // Ok, ID doesn't exist
// Add Geometry to where used hash table
m_WhereUsed.insert(pGeom->getID(), pGeom);
return true;
}
else
{ // KO, ID exist
qDebug("GLC_Material::AddGLC_Geom : Geometry not added");
return false;
}
}
// Supprime une gomtrie de la collection
bool GLC_Material::delGLC_Geom(GLC_uint Key)
{
CWhereUsed::iterator iGeom= m_WhereUsed.find(Key);
if (iGeom != m_WhereUsed.end())
{ // Ok, ID exist
m_WhereUsed.remove(Key); // Remove container
return true;
}
else
{ // KO doesn't exist
qDebug("GLC_Material::DelGLC_Geom : Geometry not remove");
return false;
}
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
// Load the texture
void GLC_Material::glLoadTexture(void)
{
if (m_pTexture != NULL)
{
m_pTexture->glLoadTexture();
}
}
// Execute OpenGL Material
void GLC_Material::glExecute(GLenum Mode)
{
GLfloat pAmbientColor[4]= {getAmbientColor().redF(),
getAmbientColor().greenF(),
getAmbientColor().blueF(),
getAmbientColor().alphaF()};
GLfloat pDiffuseColor[4]= {getDiffuseColor().redF(),
getDiffuseColor().greenF(),
getDiffuseColor().blueF(),
getDiffuseColor().alphaF()};
GLfloat pSpecularColor[4]= {getSpecularColor().redF(),
getSpecularColor().greenF(),
getSpecularColor().blueF(),
getSpecularColor().alphaF()};
GLfloat pLightEmission[4]= {getLightEmission().redF(),
getLightEmission().greenF(),
getLightEmission().blueF(),
getLightEmission().alphaF()};
if (m_pTexture != NULL)
{
// for blend managing
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
m_pTexture->glcBindTexture();
}
glColor4fv(pAmbientColor);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, pAmbientColor);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, pDiffuseColor);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, pSpecularColor);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, pLightEmission);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, &m_fShininess);
// OpenGL Error handler
GLenum errCode;
if ((errCode= glGetError()) != GL_NO_ERROR)
{
const GLubyte* errString;
errString = gluErrorString(errCode);
qDebug("GLC_Material::GlExecute OpenGL Error %s", errString);
}
}
//////////////////////////////////////////////////////////////////////
// Private servicies Functions
//////////////////////////////////////////////////////////////////////
// Update geometries which used material
void GLC_Material::updateUsed(void)
{
CWhereUsed::iterator iEntry= m_WhereUsed.begin();
while (iEntry != m_WhereUsed.constEnd())
{
// Indique aux gomtrie utilisant la matire que celle ci change
iEntry.value()->setMaterial(this);
++iEntry;
}
}
// Init Ambiant Color
void GLC_Material::initAmbientColor(void)
{
m_AmbientColor.setRgbF(0.8, 0.8, 0.8, 1.0);
}
// Init default color
void GLC_Material::initOtherColor(void)
{
// Diffuse Color
m_DiffuseColor.setRgbF(0.7, 0.7, 0.7, 1.0);
// Specular Color
m_SpecularColor.setRgbF(0.5, 0.5, 0.5, 1.0);
// Lighting emit
m_LightEmission.setRgbF(0.0, 0.0, 0.0, 1.0);
}
<commit_msg>change default material color<commit_after>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2006 Laurent Ribon ([email protected])
Version 0.9.6, packaged on June, 2006.
http://glc-lib.sourceforge.net
GLC-lib 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.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_material.cpp implementation of the GLC_Material class.
#include <QtDebug>
#include <assert.h>
#include "glc_material.h"
#include "glc_collection.h"
//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Material::GLC_Material()
:GLC_Object("Material")
, m_fShininess(50.0) // By default shininess 50
, m_pTexture(NULL) // no texture
{
// Ambient Color
initAmbientColor();
// Others
initOtherColor();
}
GLC_Material::GLC_Material(const QColor &ambientColor)
:GLC_Object("Material")
, m_fShininess(50.0) // default : shininess 50
, m_pTexture(NULL) // no texture
{
m_AmbientColor= ambientColor;
// Others
initOtherColor();
}
GLC_Material::GLC_Material(const char *pName ,const GLfloat *pAmbientColor)
:GLC_Object(pName)
, m_fShininess(50.0) // default : shininess 50
, m_pTexture(NULL) // no texture
{
// Init Ambiant Color
if (pAmbientColor != 0)
{
m_AmbientColor.setRgbF(static_cast<qreal>(pAmbientColor[0]),
static_cast<qreal>(pAmbientColor[1]),
static_cast<qreal>(pAmbientColor[2]),
static_cast<qreal>(pAmbientColor[3]));
}
else
{
initAmbientColor();
}
// Others
initOtherColor();
}
GLC_Material::GLC_Material(GLC_Texture* pTexture, const char *pName)
:GLC_Object(pName)
, m_fShininess(50.0) // By default shininess 50
, m_pTexture(pTexture) // Init texture
{
// Ambiente Color
initAmbientColor();
// Others
initOtherColor();
}
// Copy constructor
GLC_Material::GLC_Material(const GLC_Material &InitMaterial)
:GLC_Object(InitMaterial.getName())
, m_fShininess(InitMaterial.m_fShininess)
, m_pTexture(NULL)
{
if (NULL != InitMaterial.m_pTexture)
{
m_pTexture= new GLC_Texture(*(InitMaterial.m_pTexture));
assert(m_pTexture != NULL);
}
// Ambient Color
m_AmbientColor= InitMaterial.m_AmbientColor;
// Diffuse Color
m_DiffuseColor= InitMaterial.m_DiffuseColor;
// Specular Color
m_SpecularColor= InitMaterial.m_SpecularColor;
// Lighting emit
m_LightEmission= InitMaterial.m_LightEmission;
}
// Destructor
GLC_Material::~GLC_Material(void)
{
// clear whereUSED Hash table
m_WhereUsed.clear();
if (NULL != m_pTexture)
{
delete m_pTexture;
m_pTexture= NULL;
}
}
//////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////
// Get Ambiant color
QColor GLC_Material::getAmbientColor() const
{
return m_AmbientColor;
}
// Get diffuse color
QColor GLC_Material::getDiffuseColor() const
{
return m_DiffuseColor;
}
// Get specular color
QColor GLC_Material::getSpecularColor() const
{
return m_SpecularColor;
}
// Get the emissive color
QColor GLC_Material::getLightEmission() const
{
return m_LightEmission;
}
// Get the texture File Name
QString GLC_Material::getTextureFileName() const
{
if (m_pTexture != NULL)
{
return m_pTexture->getTextureFileName();
}
else
{
return "";
}
}
// Get Texture Id
GLuint GLC_Material::getTextureID() const
{
if (m_pTexture != NULL)
{
return m_pTexture->getTextureID();
}
else
{
return 0;
}
}
// return true if the texture is loaded
bool GLC_Material::textureIsLoaded() const
{
if (m_pTexture != NULL)
{
return m_pTexture->isLoaded();
}
else
{
return false;
}
}
//////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Set Material properties
void GLC_Material::setMaterial(const GLC_Material* pMat)
{
if (NULL != pMat->m_pTexture)
{
GLC_Texture* pTexture= new GLC_Texture(*(pMat->m_pTexture));
setTexture(pTexture);
}
// Ambient Color
m_AmbientColor= pMat->m_AmbientColor;
// Diffuse Color
m_DiffuseColor= pMat->m_DiffuseColor;
// Specular Color
m_SpecularColor= pMat->m_SpecularColor;
// Lighting emit
m_LightEmission= pMat->m_LightEmission;
m_fShininess= pMat->m_fShininess;
updateUsed();
}
// Set Ambiant Color
void GLC_Material::setAmbientColor(const QColor& ambientColor)
{
m_AmbientColor= ambientColor;
updateUsed();
}
// Set Diffuse color
void GLC_Material::setDiffuseColor(const QColor& diffuseColor)
{
m_DiffuseColor= diffuseColor;
updateUsed();
}
// Set Specular color
void GLC_Material::setSpecularColor(const QColor& specularColor)
{
m_SpecularColor= specularColor;
updateUsed();
}
// Set Emissive
void GLC_Material::setLightEmission(const QColor& lightEmission)
{
m_LightEmission= lightEmission;
updateUsed();
}
// Set Texture
void GLC_Material::setTexture(GLC_Texture* pTexture)
{
qDebug() << "GLC_Material::SetTexture";
if (m_pTexture != NULL)
{
delete m_pTexture;
m_pTexture= pTexture;
glLoadTexture();
}
else
{
// It is not sure that there is OpenGL context
m_pTexture= pTexture;
}
updateUsed();
}
// remove Material Texture
void GLC_Material::removeTexture()
{
if (m_pTexture != NULL)
{
delete m_pTexture;
m_pTexture= NULL;
updateUsed();
}
}
// Add Geometry to where used hash table
bool GLC_Material::addGLC_Geom(GLC_Geometry* pGeom)
{
CWhereUsed::iterator iGeom= m_WhereUsed.find(pGeom->getID());
if (iGeom == m_WhereUsed.end())
{ // Ok, ID doesn't exist
// Add Geometry to where used hash table
m_WhereUsed.insert(pGeom->getID(), pGeom);
return true;
}
else
{ // KO, ID exist
qDebug("GLC_Material::AddGLC_Geom : Geometry not added");
return false;
}
}
// Supprime une gomtrie de la collection
bool GLC_Material::delGLC_Geom(GLC_uint Key)
{
CWhereUsed::iterator iGeom= m_WhereUsed.find(Key);
if (iGeom != m_WhereUsed.end())
{ // Ok, ID exist
m_WhereUsed.remove(Key); // Remove container
return true;
}
else
{ // KO doesn't exist
qDebug("GLC_Material::DelGLC_Geom : Geometry not remove");
return false;
}
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
// Load the texture
void GLC_Material::glLoadTexture(void)
{
if (m_pTexture != NULL)
{
m_pTexture->glLoadTexture();
}
}
// Execute OpenGL Material
void GLC_Material::glExecute(GLenum Mode)
{
GLfloat pAmbientColor[4]= {getAmbientColor().redF(),
getAmbientColor().greenF(),
getAmbientColor().blueF(),
getAmbientColor().alphaF()};
GLfloat pDiffuseColor[4]= {getDiffuseColor().redF(),
getDiffuseColor().greenF(),
getDiffuseColor().blueF(),
getDiffuseColor().alphaF()};
GLfloat pSpecularColor[4]= {getSpecularColor().redF(),
getSpecularColor().greenF(),
getSpecularColor().blueF(),
getSpecularColor().alphaF()};
GLfloat pLightEmission[4]= {getLightEmission().redF(),
getLightEmission().greenF(),
getLightEmission().blueF(),
getLightEmission().alphaF()};
if (m_pTexture != NULL)
{
// for blend managing
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
m_pTexture->glcBindTexture();
}
glColor4fv(pAmbientColor);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, pAmbientColor);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, pDiffuseColor);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, pSpecularColor);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, pLightEmission);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, &m_fShininess);
// OpenGL Error handler
GLenum errCode;
if ((errCode= glGetError()) != GL_NO_ERROR)
{
const GLubyte* errString;
errString = gluErrorString(errCode);
qDebug("GLC_Material::GlExecute OpenGL Error %s", errString);
}
}
//////////////////////////////////////////////////////////////////////
// Private servicies Functions
//////////////////////////////////////////////////////////////////////
// Update geometries which used material
void GLC_Material::updateUsed(void)
{
CWhereUsed::iterator iEntry= m_WhereUsed.begin();
while (iEntry != m_WhereUsed.constEnd())
{
// Indique aux gomtrie utilisant la matire que celle ci change
iEntry.value()->setMaterial(this);
++iEntry;
}
}
// Init Ambiant Color
void GLC_Material::initAmbientColor(void)
{
m_AmbientColor.setRgbF(0.8, 0.8, 0.8, 1.0);
}
// Init default color
void GLC_Material::initOtherColor(void)
{
// Diffuse Color
m_DiffuseColor.setRgbF(1.0, 1.0, 1.0, 1.0);
// Specular Color
m_SpecularColor.setRgbF(0.5, 0.5, 0.5, 1.0);
// Lighting emit
m_LightEmission.setRgbF(0.0, 0.0, 0.0, 1.0);
}
<|endoftext|> |
<commit_before>#include <gl/freeglut.h>
void init();
void display(void);
void centerOnScreen();
void drawObject();
// define the window position on screen
int window_x;
int window_y;
// variables representing the window size
int window_width = 480;
int window_height = 480;
// variable representing the window title
char *window_title = "Sample OpenGL FreeGlut App";
//-------------------------------------------------------------------------
// Program Main method.
//-------------------------------------------------------------------------
void main(int argc, char **argv)
{
// Connect to the windowing system + create a window
// with the specified dimensions and position
// + set the display mode + specify the window title.
glutInit(&argc, argv);
centerOnScreen();
glutInitWindowSize(window_width, window_height);
glutInitWindowPosition(window_x, window_y);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutCreateWindow(window_title);
// Set OpenGL program initial state.
init();
// Set the callback functions
glutDisplayFunc(display);
// Start GLUT event processing loop
glutMainLoop();
}
//-------------------------------------------------------------------------
// Set OpenGL program initial state.
//-------------------------------------------------------------------------
void init()
{
// Set the frame buffer clear color to black.
glClearColor(0.0, 0.0, 0.0, 0.0);
}
//-------------------------------------------------------------------------
// This function is passed to glutDisplayFunc in order to display
// OpenGL contents on the window.
//-------------------------------------------------------------------------
void display(void)
{
// Clear the window or more specifically the frame buffer...
// This happens by replacing all the contents of the frame
// buffer by the clear color (black in our case)
glClear(GL_COLOR_BUFFER_BIT);
// Draw object
drawObject();
// Swap contents of backward and forward frame buffers
glutSwapBuffers();
}
//-------------------------------------------------------------------------
// Draws our object.
//-------------------------------------------------------------------------
void drawObject()
{
// Draw Icosahedron
glutWireIcosahedron();
}
//-------------------------------------------------------------------------
// This function sets the window x and y coordinates
// such that the window becomes centered
//-------------------------------------------------------------------------
void centerOnScreen()
{
window_x = (glutGet(GLUT_SCREEN_WIDTH) - window_width) / 2;
window_y = (glutGet(GLUT_SCREEN_HEIGHT) - window_height) / 2;
}<commit_msg>basic<commit_after>#include <gl/freeglut.h>
void init();
void display(void);
void centerOnScreen();
void drawObject();
// define the window position on screen
int window_x;
int window_y;
// variables representing the window size
int window_width = 480;
int window_height = 480;
// variable representing the window title
char *window_title = "Sample OpenGL FreeGlut App";
//-------------------------------------------------------------------------
// Program Main method.
//-------------------------------------------------------------------------
/*
void main(int argc, char **argv)
{
// Connect to the windowing system + create a window
// with the specified dimensions and position
// + set the display mode + specify the window title.
glutInit(&argc, argv);
centerOnScreen();
glutInitWindowSize(window_width, window_height);
glutInitWindowPosition(window_x, window_y);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutCreateWindow(window_title);
// Set OpenGL program initial state.
init();
// Set the callback functions
glutDisplayFunc(display);
// Start GLUT event processing loop
glutMainLoop();
}
*/
//-------------------------------------------------------------------------
// Set OpenGL program initial state.
//-------------------------------------------------------------------------
void init()
{
// Set the frame buffer clear color to black.
glClearColor(0.0, 0.0, 0.0, 0.0);
}
//-------------------------------------------------------------------------
// This function is passed to glutDisplayFunc in order to display
// OpenGL contents on the window.
//-------------------------------------------------------------------------
void display(void)
{
// Clear the window or more specifically the frame buffer...
// This happens by replacing all the contents of the frame
// buffer by the clear color (black in our case)
glClear(GL_COLOR_BUFFER_BIT);
// Draw object
drawObject();
// Swap contents of backward and forward frame buffers
glutSwapBuffers();
}
//-------------------------------------------------------------------------
// Draws our object.
//-------------------------------------------------------------------------
void drawObject()
{
// Draw Icosahedron
glutWireIcosahedron();
}
//-------------------------------------------------------------------------
// This function sets the window x and y coordinates
// such that the window becomes centered
//-------------------------------------------------------------------------
void centerOnScreen()
{
window_x = (glutGet(GLUT_SCREEN_WIDTH) - window_width) / 2;
window_y = (glutGet(GLUT_SCREEN_HEIGHT) - window_height) / 2;
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2020 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 "call/version.h"
namespace webrtc {
// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2020-12-14T14:30:00";
void LoadWebRTCVersionInRegister() {
// Using volatile to instruct the compiler to not optimize `p` away even
// if it looks unused.
const char* volatile p = kSourceTimestamp;
static_cast<void>(p);
}
} // namespace webrtc
<commit_msg>Update WebRTC code version (2020-12-17T07:06:37).<commit_after>/*
* Copyright (c) 2020 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 "call/version.h"
namespace webrtc {
// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2020-12-17T07:06:37";
void LoadWebRTCVersionInRegister() {
// Using volatile to instruct the compiler to not optimize `p` away even
// if it looks unused.
const char* volatile p = kSourceTimestamp;
static_cast<void>(p);
}
} // namespace webrtc
<|endoftext|> |
<commit_before>/*
* ArcEmu MMORPG Server
* Copyright (C) 2008-2010 <http://www.ArcEmu.org/>
*
* 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
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "Config/ConfigEnv.h"
#include "Log.h"
#include <cstdarg>
string FormatOutputString(const char * Prefix, const char * Description, bool useTimeStamp)
{
char p[MAX_PATH];
p[0] = 0;
time_t t = time(NULL);
tm * a = gmtime(&t);
strcat(p, Prefix);
strcat(p, "/");
strcat(p, Description);
if(useTimeStamp)
{
char ftime[100];
snprintf(ftime, 100, "-%-4d-%02d-%02d %02d-%02d-%02d", a->tm_year+1900, a->tm_mon+1, a->tm_mday, a->tm_hour, a->tm_min, a->tm_sec);
strcat(p, ftime);
}
strcat(p, ".log");
return string(p);
}
createFileSingleton( oLog );
initialiseSingleton( WorldLog );
SERVER_DECL time_t UNIXTIME;
SERVER_DECL tm g_localTime;
void oLog::outFile(FILE *file, char *msg, const char *source)
{
char time_buffer[TIME_FORMAT_LENGTH];
char szltr_buffer[SZLTR_LENGTH];
Time(time_buffer);
pdcds(SZLTR, szltr_buffer);
if(source != NULL){
fprintf(file, "%s%s%s: %s\n", time_buffer, szltr_buffer, source, msg);
printf( "%s%s%s: %s\n", time_buffer, szltr_buffer, source, msg);
}else{
fprintf(file, "%s%s%s\n", time_buffer, szltr_buffer, msg);
printf( "%s%s%s\n", time_buffer, szltr_buffer, msg);
}
}
void oLog::Time(char *buffer)
{
time_t now;
struct tm * timeinfo = NULL;
time( &now );
timeinfo = localtime( &now );
if( timeinfo != NULL )
{
strftime(buffer,TIME_FORMAT_LENGTH,TIME_FORMAT,timeinfo);
}
else
{
buffer[0] = '\0';
}
}
void oLog::outString( const char * str, ... )
{
if(m_normalFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, str);
vsnprintf(buf, 32768, str, ap);
va_end(ap);
outFile(m_normalFile, buf);
}
void oLog::outError( const char * err, ... )
{
if(m_errorFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, err);
vsnprintf(buf, 32768, err, ap);
va_end(ap);
outFile(m_errorFile, buf);
}
void oLog::outBasic( const char * str, ... )
{
if(m_normalFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, str);
vsnprintf(buf, 32768, str, ap);
va_end(ap);
outFile(m_normalFile, buf);
}
void oLog::outDetail( const char * str, ... )
{
if(m_fileLogLevel < 1 || m_normalFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, str);
vsnprintf(buf, 32768, str, ap);
va_end(ap);
outFile(m_normalFile, buf);
}
void oLog::outDebug( const char * str, ... )
{
if(m_fileLogLevel < 2 || m_errorFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, str);
vsnprintf(buf, 32768, str, ap);
va_end(ap);
outFile(m_errorFile, buf);
}
//old NGLog.h methods
void oLog::Notice(const char * source, const char * format, ...)
{
if(m_fileLogLevel < 1 || m_normalFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, format);
vsnprintf(buf, 32768, format, ap);
va_end(ap);
outFile(m_normalFile, buf, source);
}
void oLog::Warning(const char * source, const char * format, ...)
{
if(m_fileLogLevel < 1 || m_normalFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, format);
vsnprintf(buf, 32768, format, ap);
va_end(ap);
outFile(m_normalFile, buf, source);
}
void oLog::Success(const char * source, const char * format, ...)
{
if(m_normalFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, format);
vsnprintf(buf, 32768, format, ap);
va_end(ap);
outFile(m_normalFile, buf, source);
}
void oLog::Error(const char * source, const char * format, ...)
{
if(m_errorFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, format);
vsnprintf(buf, 32768, format, ap);
va_end(ap);
outFile(m_errorFile, buf, source);
}
void oLog::Debug(const char * source, const char * format, ...)
{
if(m_fileLogLevel < 2 || m_errorFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, format);
vsnprintf(buf, 32768, format, ap);
va_end(ap);
outFile(m_errorFile, buf, source);
}
void oLog::LargeErrorMessage(const char * source, ...)
{
std::vector<char*> lines;
char * pointer;
va_list ap;
va_start(ap, source);
pointer = const_cast<char*>(source);
lines.push_back(pointer);
size_t i,j,k;
pointer = va_arg(ap, char*);
while( pointer != NULL )
{
lines.push_back( pointer );
pointer = va_arg(ap, char*);
}
outError("*********************************************************************");
outError("* MAJOR ERROR/WARNING *");
outError("* =================== *");
for(std::vector<char*>::iterator itr = lines.begin(); itr != lines.end(); ++itr)
{
stringstream sstext;
i = strlen(*itr);
j = (i<=65) ? 65 - i : 0;
sstext << "* " << *itr;
for( k = 0; k < j; ++k )
{
sstext << " ";
}
sstext << " *";
outError(sstext.str().c_str());
}
outError("*********************************************************************");
}
void oLog::Init(int32 fileLogLevel, LogType logType)
{
SetFileLoggingLevel(fileLogLevel);
const char *logNormalFilename = NULL, *logErrorFilename = NULL;
switch(logType)
{
case LOGON_LOG:
{
logNormalFilename = "logon-normal.log";
logErrorFilename = "logon-error.log";
break;
}
case WORLD_LOG:
{
logNormalFilename = "world-normal.log";
logErrorFilename = "world-error.log";
break;
}
}
m_normalFile = fopen(logNormalFilename, "a");
if (m_normalFile == NULL)
fprintf(stderr, "%s: Error opening '%s': %s\n", __FUNCTION__, logNormalFilename, strerror(errno));
else
{
tm* aTm = localtime(&UNIXTIME);
outBasic("[%-4d-%02d-%02d %02d:%02d:%02d] ",aTm->tm_year+1900,aTm->tm_mon+1,aTm->tm_mday,aTm->tm_hour,aTm->tm_min,aTm->tm_sec);
}
m_errorFile = fopen(logErrorFilename, "a");
if (m_errorFile == NULL)
fprintf(stderr, "%s: Error opening '%s': %s\n", __FUNCTION__, logErrorFilename, strerror(errno));
else
{
tm* aTm = localtime(&UNIXTIME);
outError("[%-4d-%02d-%02d %02d:%02d:%02d] ",aTm->tm_year+1900,aTm->tm_mon+1,aTm->tm_mday,aTm->tm_hour,aTm->tm_min,aTm->tm_sec);
}
}
void oLog::Close()
{
if(m_normalFile != NULL)
{
fflush(m_normalFile);
fclose(m_normalFile);
m_normalFile = NULL;
}
if(m_errorFile != NULL)
{
fflush(m_errorFile);
fclose(m_errorFile);
m_errorFile = NULL;
}
}
void oLog::SetFileLoggingLevel(int32 level)
{
//log level -1 is no more allowed
if(level >= 0)
m_fileLogLevel = level;
}
void SessionLogWriter::write(const char* format, ...)
{
if(!m_file)
return;
char out[32768];
va_list ap;
va_start(ap, format);
time_t t = time(NULL);
tm* aTm = localtime(&t);
sprintf(out, "[%-4d-%02d-%02d %02d:%02d:%02d] ",aTm->tm_year+1900,aTm->tm_mon+1,aTm->tm_mday,aTm->tm_hour,aTm->tm_min,aTm->tm_sec);
size_t l = strlen(out);
vsnprintf(&out[l], 32768 - l, format, ap);
fprintf(m_file, "%s\n", out);
va_end(ap);
}
WorldLog::WorldLog()
{
bEnabled = false;
m_file= NULL;
if (Config.MainConfig.GetBoolDefault("LogLevel", "World", false))
{
Log.Notice("WorldLog", "Enabling packetlog output to \"world.log\"");
Enable();
} else {
Disable();
}
}
void WorldLog::Enable()
{
if(bEnabled)
return;
bEnabled = true;
if(m_file != NULL)
{
Disable();
bEnabled=true;
}
m_file = fopen("world.log", "a");
}
void WorldLog::Disable()
{
if(!bEnabled)
return;
bEnabled = false;
if(!m_file)
return;
fflush(m_file);
fclose(m_file);
m_file= NULL;
}
WorldLog::~WorldLog()
{
if (m_file)
{
fclose(m_file);
m_file = NULL;
}
}
void SessionLogWriter::Open()
{
m_file = fopen(m_filename, "a");
}
void SessionLogWriter::Close()
{
if(!m_file) return;
fflush(m_file);
fclose(m_file);
m_file= NULL;
}
SessionLogWriter::SessionLogWriter(const char * filename, bool open)
{
m_filename = strdup(filename);
m_file= NULL;
if(open)
Open();
}
SessionLogWriter::~SessionLogWriter()
{
if(m_file)
Close();
free(m_filename);
}<commit_msg>Sorry GM did not mean to commit this :\<commit_after>/*
* ArcEmu MMORPG Server
* Copyright (C) 2008-2010 <http://www.ArcEmu.org/>
*
* 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
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "Config/ConfigEnv.h"
#include "Log.h"
#include <cstdarg>
string FormatOutputString(const char * Prefix, const char * Description, bool useTimeStamp)
{
char p[MAX_PATH];
p[0] = 0;
time_t t = time(NULL);
tm * a = gmtime(&t);
strcat(p, Prefix);
strcat(p, "/");
strcat(p, Description);
if(useTimeStamp)
{
char ftime[100];
snprintf(ftime, 100, "-%-4d-%02d-%02d %02d-%02d-%02d", a->tm_year+1900, a->tm_mon+1, a->tm_mday, a->tm_hour, a->tm_min, a->tm_sec);
strcat(p, ftime);
}
strcat(p, ".log");
return string(p);
}
createFileSingleton( oLog );
initialiseSingleton( WorldLog );
SERVER_DECL time_t UNIXTIME;
SERVER_DECL tm g_localTime;
void oLog::outFile(FILE *file, char *msg, const char *source)
{
char time_buffer[TIME_FORMAT_LENGTH];
char szltr_buffer[SZLTR_LENGTH];
Time(time_buffer);
pdcds(SZLTR, szltr_buffer);
if(source != NULL)
fprintf(file, "%s%s%s: %s\n", time_buffer, szltr_buffer, source, msg);
else
fprintf(file, "%s%s%s\n", time_buffer, szltr_buffer, msg);
}
void oLog::Time(char *buffer)
{
time_t now;
struct tm * timeinfo = NULL;
time( &now );
timeinfo = localtime( &now );
if( timeinfo != NULL )
{
strftime(buffer,TIME_FORMAT_LENGTH,TIME_FORMAT,timeinfo);
}
else
{
buffer[0] = '\0';
}
}
void oLog::outString( const char * str, ... )
{
if(m_normalFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, str);
vsnprintf(buf, 32768, str, ap);
va_end(ap);
outFile(m_normalFile, buf);
}
void oLog::outError( const char * err, ... )
{
if(m_errorFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, err);
vsnprintf(buf, 32768, err, ap);
va_end(ap);
outFile(m_errorFile, buf);
}
void oLog::outBasic( const char * str, ... )
{
if(m_normalFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, str);
vsnprintf(buf, 32768, str, ap);
va_end(ap);
outFile(m_normalFile, buf);
}
void oLog::outDetail( const char * str, ... )
{
if(m_fileLogLevel < 1 || m_normalFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, str);
vsnprintf(buf, 32768, str, ap);
va_end(ap);
outFile(m_normalFile, buf);
}
void oLog::outDebug( const char * str, ... )
{
if(m_fileLogLevel < 2 || m_errorFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, str);
vsnprintf(buf, 32768, str, ap);
va_end(ap);
outFile(m_errorFile, buf);
}
//old NGLog.h methods
void oLog::Notice(const char * source, const char * format, ...)
{
if(m_fileLogLevel < 1 || m_normalFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, format);
vsnprintf(buf, 32768, format, ap);
va_end(ap);
outFile(m_normalFile, buf, source);
}
void oLog::Warning(const char * source, const char * format, ...)
{
if(m_fileLogLevel < 1 || m_normalFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, format);
vsnprintf(buf, 32768, format, ap);
va_end(ap);
outFile(m_normalFile, buf, source);
}
void oLog::Success(const char * source, const char * format, ...)
{
if(m_normalFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, format);
vsnprintf(buf, 32768, format, ap);
va_end(ap);
outFile(m_normalFile, buf, source);
}
void oLog::Error(const char * source, const char * format, ...)
{
if(m_errorFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, format);
vsnprintf(buf, 32768, format, ap);
va_end(ap);
outFile(m_errorFile, buf, source);
}
void oLog::Debug(const char * source, const char * format, ...)
{
if(m_fileLogLevel < 2 || m_errorFile == NULL)
return;
char buf[32768];
va_list ap;
va_start(ap, format);
vsnprintf(buf, 32768, format, ap);
va_end(ap);
outFile(m_errorFile, buf, source);
}
void oLog::LargeErrorMessage(const char * source, ...)
{
std::vector<char*> lines;
char * pointer;
va_list ap;
va_start(ap, source);
pointer = const_cast<char*>(source);
lines.push_back(pointer);
size_t i,j,k;
pointer = va_arg(ap, char*);
while( pointer != NULL )
{
lines.push_back( pointer );
pointer = va_arg(ap, char*);
}
outError("*********************************************************************");
outError("* MAJOR ERROR/WARNING *");
outError("* =================== *");
for(std::vector<char*>::iterator itr = lines.begin(); itr != lines.end(); ++itr)
{
stringstream sstext;
i = strlen(*itr);
j = (i<=65) ? 65 - i : 0;
sstext << "* " << *itr;
for( k = 0; k < j; ++k )
{
sstext << " ";
}
sstext << " *";
outError(sstext.str().c_str());
}
outError("*********************************************************************");
}
void oLog::Init(int32 fileLogLevel, LogType logType)
{
SetFileLoggingLevel(fileLogLevel);
const char *logNormalFilename = NULL, *logErrorFilename = NULL;
switch(logType)
{
case LOGON_LOG:
{
logNormalFilename = "logon-normal.log";
logErrorFilename = "logon-error.log";
break;
}
case WORLD_LOG:
{
logNormalFilename = "world-normal.log";
logErrorFilename = "world-error.log";
break;
}
}
m_normalFile = fopen(logNormalFilename, "a");
if (m_normalFile == NULL)
fprintf(stderr, "%s: Error opening '%s': %s\n", __FUNCTION__, logNormalFilename, strerror(errno));
else
{
tm* aTm = localtime(&UNIXTIME);
outBasic("[%-4d-%02d-%02d %02d:%02d:%02d] ",aTm->tm_year+1900,aTm->tm_mon+1,aTm->tm_mday,aTm->tm_hour,aTm->tm_min,aTm->tm_sec);
}
m_errorFile = fopen(logErrorFilename, "a");
if (m_errorFile == NULL)
fprintf(stderr, "%s: Error opening '%s': %s\n", __FUNCTION__, logErrorFilename, strerror(errno));
else
{
tm* aTm = localtime(&UNIXTIME);
outError("[%-4d-%02d-%02d %02d:%02d:%02d] ",aTm->tm_year+1900,aTm->tm_mon+1,aTm->tm_mday,aTm->tm_hour,aTm->tm_min,aTm->tm_sec);
}
}
void oLog::Close()
{
if(m_normalFile != NULL)
{
fflush(m_normalFile);
fclose(m_normalFile);
m_normalFile = NULL;
}
if(m_errorFile != NULL)
{
fflush(m_errorFile);
fclose(m_errorFile);
m_errorFile = NULL;
}
}
void oLog::SetFileLoggingLevel(int32 level)
{
//log level -1 is no more allowed
if(level >= 0)
m_fileLogLevel = level;
}
void SessionLogWriter::write(const char* format, ...)
{
if(!m_file)
return;
char out[32768];
va_list ap;
va_start(ap, format);
time_t t = time(NULL);
tm* aTm = localtime(&t);
sprintf(out, "[%-4d-%02d-%02d %02d:%02d:%02d] ",aTm->tm_year+1900,aTm->tm_mon+1,aTm->tm_mday,aTm->tm_hour,aTm->tm_min,aTm->tm_sec);
size_t l = strlen(out);
vsnprintf(&out[l], 32768 - l, format, ap);
fprintf(m_file, "%s\n", out);
va_end(ap);
}
WorldLog::WorldLog()
{
bEnabled = false;
m_file= NULL;
if (Config.MainConfig.GetBoolDefault("LogLevel", "World", false))
{
Log.Notice("WorldLog", "Enabling packetlog output to \"world.log\"");
Enable();
} else {
Disable();
}
}
void WorldLog::Enable()
{
if(bEnabled)
return;
bEnabled = true;
if(m_file != NULL)
{
Disable();
bEnabled=true;
}
m_file = fopen("world.log", "a");
}
void WorldLog::Disable()
{
if(!bEnabled)
return;
bEnabled = false;
if(!m_file)
return;
fflush(m_file);
fclose(m_file);
m_file= NULL;
}
WorldLog::~WorldLog()
{
if (m_file)
{
fclose(m_file);
m_file = NULL;
}
}
void SessionLogWriter::Open()
{
m_file = fopen(m_filename, "a");
}
void SessionLogWriter::Close()
{
if(!m_file) return;
fflush(m_file);
fclose(m_file);
m_file= NULL;
}
SessionLogWriter::SessionLogWriter(const char * filename, bool open)
{
m_filename = strdup(filename);
m_file= NULL;
if(open)
Open();
}
SessionLogWriter::~SessionLogWriter()
{
if(m_file)
Close();
free(m_filename);
}<|endoftext|> |
<commit_before>// Copyright 2014 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 "chromecast/renderer/cast_content_renderer_client.h"
#include <sys/sysinfo.h>
#include "base/command_line.h"
#include "base/memory/memory_pressure_listener.h"
#include "chromecast/common/chromecast_switches.h"
#include "chromecast/renderer/cast_media_load_deferrer.h"
#include "chromecast/renderer/cast_render_process_observer.h"
#include "chromecast/renderer/key_systems_cast.h"
#include "chromecast/renderer/media/cma_media_renderer_factory.h"
#include "components/dns_prefetch/renderer/prescient_networking_dispatcher.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "crypto/nss_util.h"
#include "third_party/WebKit/public/platform/WebColor.h"
#include "third_party/WebKit/public/web/WebSettings.h"
#include "third_party/WebKit/public/web/WebView.h"
namespace chromecast {
namespace shell {
namespace {
// Default background color to set for WebViews. WebColor is in ARGB format
// though the comment of WebColor says it is in RGBA.
const blink::WebColor kColorBlack = 0xFF000000;
} // namespace
CastContentRendererClient::CastContentRendererClient() {
}
CastContentRendererClient::~CastContentRendererClient() {
}
void CastContentRendererClient::RenderThreadStarted() {
#if defined(USE_NSS)
// Note: Copied from chrome_render_process_observer.cc to fix b/8676652.
//
// On platforms where the system NSS shared libraries are used,
// initialize NSS now because it won't be able to load the .so's
// after entering the sandbox.
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(switches::kSingleProcess))
crypto::InitNSSSafely();
#endif
cast_observer_.reset(new CastRenderProcessObserver());
prescient_networking_dispatcher_.reset(
new dns_prefetch::PrescientNetworkingDispatcher());
}
void CastContentRendererClient::RenderViewCreated(
content::RenderView* render_view) {
blink::WebView* webview = render_view->GetWebView();
if (webview) {
webview->setBaseBackgroundColor(kColorBlack);
// The following settings express consistent behaviors across Cast
// embedders, though Android has enabled by default for mobile browsers.
webview->settings()->setShrinksViewportContentToFit(false);
webview->settings()->setMediaControlsOverlayPlayButtonEnabled(false);
}
}
void CastContentRendererClient::AddKeySystems(
std::vector< ::media::KeySystemInfo>* key_systems) {
AddChromecastKeySystems(key_systems);
AddChromecastPlatformKeySystems(key_systems);
}
#if !defined(OS_ANDROID)
scoped_ptr<::media::RendererFactory>
CastContentRendererClient::CreateMediaRendererFactory(
::content::RenderFrame* render_frame) {
const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
if (!cmd_line->HasSwitch(switches::kEnableCmaMediaPipeline))
return nullptr;
return scoped_ptr<::media::RendererFactory>(
new chromecast::media::CmaMediaRendererFactory(
render_frame->GetRoutingID()));
}
#endif
blink::WebPrescientNetworking*
CastContentRendererClient::GetPrescientNetworking() {
return prescient_networking_dispatcher_.get();
}
void CastContentRendererClient::DeferMediaLoad(
content::RenderFrame* render_frame,
const base::Closure& closure) {
if (!render_frame->IsHidden()) {
closure.Run();
return;
}
// Lifetime is tied to |render_frame| via content::RenderFrameObserver.
new CastMediaLoadDeferrer(render_frame, closure);
}
} // namespace shell
} // namespace chromecast
<commit_msg>Chromecast: forcibly trigger GC in low-memory situations.<commit_after>// Copyright 2014 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 "chromecast/renderer/cast_content_renderer_client.h"
#include <sys/sysinfo.h>
#include "base/command_line.h"
#include "base/memory/memory_pressure_listener.h"
#include "chromecast/common/chromecast_switches.h"
#include "chromecast/renderer/cast_media_load_deferrer.h"
#include "chromecast/renderer/cast_render_process_observer.h"
#include "chromecast/renderer/key_systems_cast.h"
#include "chromecast/renderer/media/cma_media_renderer_factory.h"
#include "components/dns_prefetch/renderer/prescient_networking_dispatcher.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "crypto/nss_util.h"
#include "third_party/WebKit/public/platform/WebColor.h"
#include "third_party/WebKit/public/web/WebSettings.h"
#include "third_party/WebKit/public/web/WebView.h"
namespace chromecast {
namespace shell {
namespace {
#if defined(ARCH_CPU_ARM_FAMILY) && !defined(OS_ANDROID)
// These memory thresholds are set for Chromecast. See the UMA histogram
// Platform.MeminfoMemFree when tuning.
// TODO(gunsch): These should be platform/product-dependent. Look into a way
// to move these to platform-specific repositories.
const int kCriticalMinFreeMemMB = 24;
const int kModerateMinFreeMemMB = 48;
const int kPollingIntervalMS = 5000;
void PlatformPollFreemem(void) {
struct sysinfo sys;
if (sysinfo(&sys) == -1) {
LOG(ERROR) << "platform_poll_freemem(): sysinfo failed";
} else {
int free_mem_mb = static_cast<int64_t>(sys.freeram) *
sys.mem_unit / (1024 * 1024);
if (free_mem_mb <= kModerateMinFreeMemMB) {
if (free_mem_mb <= kCriticalMinFreeMemMB) {
// Memory is getting really low, we need to do whatever we can to
// prevent deadlocks and interfering with other processes.
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_CRITICAL);
} else {
// There is enough memory, but it is starting to get low.
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_MODERATE);
}
}
}
// Setup next poll.
base::MessageLoopProxy::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&PlatformPollFreemem),
base::TimeDelta::FromMilliseconds(kPollingIntervalMS));
}
#endif
// Default background color to set for WebViews. WebColor is in ARGB format
// though the comment of WebColor says it is in RGBA.
const blink::WebColor kColorBlack = 0xFF000000;
} // namespace
CastContentRendererClient::CastContentRendererClient() {
}
CastContentRendererClient::~CastContentRendererClient() {
}
void CastContentRendererClient::RenderThreadStarted() {
#if defined(USE_NSS)
// Note: Copied from chrome_render_process_observer.cc to fix b/8676652.
//
// On platforms where the system NSS shared libraries are used,
// initialize NSS now because it won't be able to load the .so's
// after entering the sandbox.
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(switches::kSingleProcess))
crypto::InitNSSSafely();
#endif
#if defined(ARCH_CPU_ARM_FAMILY) && !defined(OS_ANDROID)
PlatformPollFreemem();
#endif
cast_observer_.reset(new CastRenderProcessObserver());
prescient_networking_dispatcher_.reset(
new dns_prefetch::PrescientNetworkingDispatcher());
}
void CastContentRendererClient::RenderViewCreated(
content::RenderView* render_view) {
blink::WebView* webview = render_view->GetWebView();
if (webview) {
webview->setBaseBackgroundColor(kColorBlack);
// The following settings express consistent behaviors across Cast
// embedders, though Android has enabled by default for mobile browsers.
webview->settings()->setShrinksViewportContentToFit(false);
webview->settings()->setMediaControlsOverlayPlayButtonEnabled(false);
}
}
void CastContentRendererClient::AddKeySystems(
std::vector< ::media::KeySystemInfo>* key_systems) {
AddChromecastKeySystems(key_systems);
AddChromecastPlatformKeySystems(key_systems);
}
#if !defined(OS_ANDROID)
scoped_ptr<::media::RendererFactory>
CastContentRendererClient::CreateMediaRendererFactory(
::content::RenderFrame* render_frame) {
const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
if (!cmd_line->HasSwitch(switches::kEnableCmaMediaPipeline))
return nullptr;
return scoped_ptr<::media::RendererFactory>(
new chromecast::media::CmaMediaRendererFactory(
render_frame->GetRoutingID()));
}
#endif
blink::WebPrescientNetworking*
CastContentRendererClient::GetPrescientNetworking() {
return prescient_networking_dispatcher_.get();
}
void CastContentRendererClient::DeferMediaLoad(
content::RenderFrame* render_frame,
const base::Closure& closure) {
if (!render_frame->IsHidden()) {
closure.Run();
return;
}
// Lifetime is tied to |render_frame| via content::RenderFrameObserver.
new CastMediaLoadDeferrer(render_frame, closure);
}
} // namespace shell
} // namespace chromecast
<|endoftext|> |
<commit_before>#include "omp.h"
inline
kth_cv_omp::kth_cv_omp(const std::string in_path,
const std::string in_actionNames,
const field<std::string> in_all_people,
const int in_scale_factor,
const int in_shift,
const int in_scene, //only for kth
const int in_segment_length,
const int in_dim
):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), dim(in_dim)
{
actions.load( actionNames );
}
// Log-Euclidean Distance
inline
void
kth_cv_omp::logEucl()
{
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
//No hacer acc aqui. Hacerlo al final final. Cuando tengas todos los real_labels and est_labels
float acc;
acc = 0;
//int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3
int n_test = n_peo*n_actions*total_scenes; // - person13_handclapping_d3
vec real_labels;
vec est_labels;
field<std::string> test_video_list(n_test);
real_labels.zeros(n_test);
est_labels.zeros(n_test);
int k=0;
int sc = 1; // = total scenes
mat peo_act(n_test,2);
for (int pe = 0; pe< n_peo; ++pe)
{
for (int act=0; act<n_actions; ++act)
{
peo_act (k,0) = pe;
peo_act (k,1) = act;
k++;
}
}
omp_set_num_threads(8); //Use only 8 processors
#pragma omp parallel for
for (int n = 0; n< n_test; ++n)
{
int pe = peo_act (n,0);
int act = peo_act (n,1);
//load number of segments
vec total_seg;
int num_s;
std::stringstream load_sub_path;
std::stringstream load_num_seg;
load_sub_path << path << "/kth-cov-mat_dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat";
int tid=omp_get_thread_num();
#pragma omp critical
cout<< "Processor " << tid <<" doing "<< all_people (pe) << "_" << actions(act) << endl;
total_seg.load( load_num_seg.str());
num_s = total_seg(0);
uvec est_lab_segm;
est_lab_segm.zeros(num_s);
vec count = zeros<vec>( n_actions );
//wall_clock timer;
//timer.tic();
for (int s=0; s<num_s; ++s)
{
std::stringstream load_cov_seg;
load_cov_seg << load_sub_path.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5";
//cout << "LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5" << endl;
//debe devolver el est_labe de ese segmento
est_lab_segm(s) = logEucl_one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str());
#pragma omp critical
count( est_lab_segm(s) )++;
}
uword index_video;
double max_val = count.max(index_video);
//est_lab_segm.t().print("est_lab_segm");
cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl;
real_labels(n) = act;
est_labels(n) = index_video;
test_video_list(n) = load_sub_path.str();
#pragma omp critical
if (index_video == act)
{acc++; }
}
real_labels.save("Log_Eucl_real_labels.dat", raw_ascii);
est_labels.save("Log_Eucl_est_labels.dat", raw_ascii);
test_video_list.save("Log_Eucl_test_video_list.dat", raw_ascii);
cout << "Performance: " << acc*100/n_test << " %" << endl;
}
inline
uword
kth_cv_omp::logEucl_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name)
{
//wall_clock timer;
//timer.tic();
mat logMtest_cov;
logMtest_cov.load(segm_name);
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
double dist, tmp_dist;
tmp_dist = datum::inf;
double est_lab;
//cout << "Comparing with person ";
for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr)
{
if (pe_tr!= pe_test)
{
//cout << " " << all_people (pe_tr);
for (int sc = 1; sc<=total_scenes; ++sc) //scene
{
for (int act=0; act<n_actions; ++act)
{
vec total_seg;
int num_s;
std::stringstream load_num_seg;
load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat";
total_seg.load( load_num_seg.str());
num_s = total_seg(0);
for (int s_tr=0; s_tr<num_s; ++s_tr)
{
std::stringstream load_cov_seg_tr;
load_cov_seg_tr << load_sub_path << "/LogMcov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5";
//cout << "Comparing with cov_seg" << s_tr << "_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5" << endl;
mat logMtrain_cov;
logMtrain_cov.load( load_cov_seg_tr.str() );
//logMtest_cov.print("logMtest_cov");
//train_cov.print("train_cov");
dist = norm( logMtest_cov - logMtrain_cov, "fro");
//cout << "dist " << dist << endl;
///crear un vec aca y guardar todas las distancias
if (dist < tmp_dist)
{
//cout << "Es menor" << endl;
tmp_dist = dist;
est_lab = act;
}
//cout << "Press a key" << endl;
//getchar();
}
}
}
}
}
//double n = timer.toc();
//cout << "number of seconds: " << n << endl;
//cout << " est_lab "<< est_lab << endl << endl;
//getchar();
return est_lab;
}
//DO IT
// Stein Divergence
inline
void
kth_cv_omp::SteinDiv()
{
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
float acc;
acc = 0;
int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3
vec real_labels;
vec est_labels;
field<std::string> test_video_list(n_test);
real_labels.zeros(n_test);
est_labels.zeros(n_test);
int k=0;
for (int sc = 1; sc<=total_scenes; ++sc) //scene
{
for (int pe = 0; pe< n_peo; ++pe)
{
for (int act=0; act<n_actions; ++act)
{
if( !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3
{
//load number of segments
vec total_seg;
int num_s;
std::stringstream load_sub_path;
std::stringstream load_num_seg;
load_sub_path << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat";
total_seg.load( load_num_seg.str());
num_s = total_seg(0);
uvec est_lab_segm;
est_lab_segm.zeros(num_s);
vec count = zeros<vec>( n_actions );
for (int s=0; s<num_s; ++s)
{
std::stringstream load_cov_seg;
load_cov_seg << load_sub_path.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5";
est_lab_segm(s) = SteinDiv_one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str());
count( est_lab_segm(s) )++;
//getchar();
}
uword index_video;
double max_val = count.max(index_video);
//est_lab_segm.t().print("est_lab_segm");
cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl;
real_labels(k) = act;
est_labels(k) = index_video;
test_video_list(k) = load_sub_path.str();
real_labels.save("Stein_div_real_labels.dat", raw_ascii);
est_labels.save("Stein_div__est_labels.dat", raw_ascii);
test_video_list.save("Stein_div_test_video_list.dat", raw_ascii);
k++;
if (index_video == act) {
acc++;
}
//getchar();
}
}
}
}
cout << "Performance: " << acc*100/n_test << " %" << endl;
}
//DO IT!!!!!!!!!
inline
uword
kth_cv_omp::SteinDiv_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name)
{
//wall_clock timer;
//timer.tic();
mat test_cov;
test_cov.load(segm_name);
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
double dist_stein, tmp_dist;
tmp_dist = datum::inf;
double est_lab;
//cout << "Comparing with person ";
for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr)
{
if (pe_tr!= pe_test)
{
//cout << " " << all_people (pe_tr);
for (int sc = 1; sc<=total_scenes; ++sc) //scene
{
for (int act=0; act<n_actions; ++act)
{
vec total_seg;
int num_s;
std::stringstream load_num_seg;
load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat";
total_seg.load( load_num_seg.str());
num_s = total_seg(0);
for (int s_tr=0; s_tr<num_s; ++s_tr)
{
std::stringstream load_cov_seg_tr;
load_cov_seg_tr << load_sub_path << "/cov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5";
mat train_cov;
train_cov.load( load_cov_seg_tr.str() );
//Esto vienen de PartI4. No recuerdo mas :(
double det_op1 = det( diagmat( (test_cov + train_cov)/2 ) );
double det_op2 = det( diagmat( ( test_cov%train_cov ) ) );
dist_stein = log( det_op1 ) - 0.5*log( det_op2 ) ;
//dist_stein = norm( logMtest_cov - logMtrain_cov, "fro");
//cout << "dist " << dist << endl;
if (dist_stein < tmp_dist)
{
//cout << "Es menor" << endl;
tmp_dist = dist_stein;
est_lab = act;
}
//cout << "Press a key" << endl;
//getchar();
}
}
}
}
}
//double n = timer.toc();
//cout << "number of seconds: " << n << endl;
//cout << " est_lab "<< est_lab << endl << endl;
//getchar();
return est_lab;
}
<commit_msg>Non ||<commit_after>#include "omp.h"
inline
kth_cv_omp::kth_cv_omp(const std::string in_path,
const std::string in_actionNames,
const field<std::string> in_all_people,
const int in_scale_factor,
const int in_shift,
const int in_scene, //only for kth
const int in_segment_length,
const int in_dim
):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), dim(in_dim)
{
actions.load( actionNames );
}
// Log-Euclidean Distance
inline
void
kth_cv_omp::logEucl()
{
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
//No hacer acc aqui. Hacerlo al final final. Cuando tengas todos los real_labels and est_labels
float acc;
acc = 0;
//int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3
int n_test = n_peo*n_actions*total_scenes; // - person13_handclapping_d3
vec real_labels;
vec est_labels;
field<std::string> test_video_list(n_test);
real_labels.zeros(n_test);
est_labels.zeros(n_test);
int k=0;
int sc = 1; // = total scenes
mat peo_act(n_test,2);
for (int pe = 0; pe< n_peo; ++pe)
{
for (int act=0; act<n_actions; ++act)
{
peo_act (k,0) = pe;
peo_act (k,1) = act;
k++;
}
}
//omp_set_num_threads(8); //Use only 8 processors
//#pragma omp parallel for
for (int n = 0; n< n_test; ++n)
{
int pe = peo_act (n,0);
int act = peo_act (n,1);
//load number of segments
vec total_seg;
int num_s;
std::stringstream load_sub_path;
std::stringstream load_num_seg;
load_sub_path << path << "/kth-cov-mat_dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat";
int tid=omp_get_thread_num();
//#pragma omp critical
cout<< "Processor " << tid <<" doing "<< all_people (pe) << "_" << actions(act) << endl;
total_seg.load( load_num_seg.str());
num_s = total_seg(0);
uvec est_lab_segm;
est_lab_segm.zeros(num_s);
vec count = zeros<vec>( n_actions );
//wall_clock timer;
//timer.tic();
for (int s=0; s<num_s; ++s)
{
std::stringstream load_cov_seg;
load_cov_seg << load_sub_path.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5";
//cout << "LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5" << endl;
//debe devolver el est_labe de ese segmento
est_lab_segm(s) = logEucl_one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str());
//#pragma omp critical
count( est_lab_segm(s) )++;
}
uword index_video;
double max_val = count.max(index_video);
//est_lab_segm.t().print("est_lab_segm");
cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl;
real_labels(n) = act;
est_labels(n) = index_video;
test_video_list(n) = load_sub_path.str();
//#pragma omp critical
if (index_video == act)
{acc++; }
}
real_labels.save("Log_Eucl_real_labels.dat", raw_ascii);
est_labels.save("Log_Eucl_est_labels.dat", raw_ascii);
test_video_list.save("Log_Eucl_test_video_list.dat", raw_ascii);
cout << "Performance: " << acc*100/n_test << " %" << endl;
}
inline
uword
kth_cv_omp::logEucl_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name)
{
//wall_clock timer;
//timer.tic();
mat logMtest_cov;
logMtest_cov.load(segm_name);
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
double dist, tmp_dist;
tmp_dist = datum::inf;
double est_lab;
//cout << "Comparing with person ";
for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr)
{
if (pe_tr!= pe_test)
{
//cout << " " << all_people (pe_tr);
for (int sc = 1; sc<=total_scenes; ++sc) //scene
{
for (int act=0; act<n_actions; ++act)
{
vec total_seg;
int num_s;
std::stringstream load_num_seg;
load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat";
total_seg.load( load_num_seg.str());
num_s = total_seg(0);
for (int s_tr=0; s_tr<num_s; ++s_tr)
{
std::stringstream load_cov_seg_tr;
load_cov_seg_tr << load_sub_path << "/LogMcov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5";
//cout << "Comparing with cov_seg" << s_tr << "_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5" << endl;
mat logMtrain_cov;
logMtrain_cov.load( load_cov_seg_tr.str() );
//logMtest_cov.print("logMtest_cov");
//train_cov.print("train_cov");
dist = norm( logMtest_cov - logMtrain_cov, "fro");
//cout << "dist " << dist << endl;
///crear un vec aca y guardar todas las distancias
if (dist < tmp_dist)
{
//cout << "Es menor" << endl;
tmp_dist = dist;
est_lab = act;
}
//cout << "Press a key" << endl;
//getchar();
}
}
}
}
}
//double n = timer.toc();
//cout << "number of seconds: " << n << endl;
//cout << " est_lab "<< est_lab << endl << endl;
//getchar();
return est_lab;
}
//DO IT
// Stein Divergence
inline
void
kth_cv_omp::SteinDiv()
{
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
float acc;
acc = 0;
int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3
vec real_labels;
vec est_labels;
field<std::string> test_video_list(n_test);
real_labels.zeros(n_test);
est_labels.zeros(n_test);
int k=0;
for (int sc = 1; sc<=total_scenes; ++sc) //scene
{
for (int pe = 0; pe< n_peo; ++pe)
{
for (int act=0; act<n_actions; ++act)
{
if( !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3
{
//load number of segments
vec total_seg;
int num_s;
std::stringstream load_sub_path;
std::stringstream load_num_seg;
load_sub_path << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat";
total_seg.load( load_num_seg.str());
num_s = total_seg(0);
uvec est_lab_segm;
est_lab_segm.zeros(num_s);
vec count = zeros<vec>( n_actions );
for (int s=0; s<num_s; ++s)
{
std::stringstream load_cov_seg;
load_cov_seg << load_sub_path.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5";
est_lab_segm(s) = SteinDiv_one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str());
count( est_lab_segm(s) )++;
//getchar();
}
uword index_video;
double max_val = count.max(index_video);
//est_lab_segm.t().print("est_lab_segm");
cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl;
real_labels(k) = act;
est_labels(k) = index_video;
test_video_list(k) = load_sub_path.str();
real_labels.save("Stein_div_real_labels.dat", raw_ascii);
est_labels.save("Stein_div__est_labels.dat", raw_ascii);
test_video_list.save("Stein_div_test_video_list.dat", raw_ascii);
k++;
if (index_video == act) {
acc++;
}
//getchar();
}
}
}
}
cout << "Performance: " << acc*100/n_test << " %" << endl;
}
//DO IT!!!!!!!!!
inline
uword
kth_cv_omp::SteinDiv_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name)
{
//wall_clock timer;
//timer.tic();
mat test_cov;
test_cov.load(segm_name);
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
double dist_stein, tmp_dist;
tmp_dist = datum::inf;
double est_lab;
//cout << "Comparing with person ";
for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr)
{
if (pe_tr!= pe_test)
{
//cout << " " << all_people (pe_tr);
for (int sc = 1; sc<=total_scenes; ++sc) //scene
{
for (int act=0; act<n_actions; ++act)
{
vec total_seg;
int num_s;
std::stringstream load_num_seg;
load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat";
total_seg.load( load_num_seg.str());
num_s = total_seg(0);
for (int s_tr=0; s_tr<num_s; ++s_tr)
{
std::stringstream load_cov_seg_tr;
load_cov_seg_tr << load_sub_path << "/cov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5";
mat train_cov;
train_cov.load( load_cov_seg_tr.str() );
//Esto vienen de PartI4. No recuerdo mas :(
double det_op1 = det( diagmat( (test_cov + train_cov)/2 ) );
double det_op2 = det( diagmat( ( test_cov%train_cov ) ) );
dist_stein = log( det_op1 ) - 0.5*log( det_op2 ) ;
//dist_stein = norm( logMtest_cov - logMtrain_cov, "fro");
//cout << "dist " << dist << endl;
if (dist_stein < tmp_dist)
{
//cout << "Es menor" << endl;
tmp_dist = dist_stein;
est_lab = act;
}
//cout << "Press a key" << endl;
//getchar();
}
}
}
}
}
//double n = timer.toc();
//cout << "number of seconds: " << n << endl;
//cout << " est_lab "<< est_lab << endl << endl;
//getchar();
return est_lab;
}
<|endoftext|> |
<commit_before>#include <memory>
#include <fstream>
#include <sstream>
#include <chrono>
#include <ctime>
#include "solver.h"
#include "solve.h"
Solver::Solver(double (*function)(double)){
fn = function;
}
Solver::~Solver(){};
void Solver::setup(unsigned int n){
double h = 1/static_cast<double>(n+2);
domain = h*arma::linspace(0, n+2, n+2); // Armadillo lacks arange :(
btilde = domain;
btilde.transform(fn);
btilde *= h*h; // b~ = f(x)h^2
// Set the boundary conditions
btilde[0] = lowerBound; btilde[n+1] = upperBound;
}
void Solver::solve(Method method, unsigned int low, unsigned int high, unsigned int step) {
char identifier;
void (Solver::*targetSolver)(unsigned int);
switch (method) {
case Method::GENERAL:
std::cout << "=== Using the general method ===" << std::endl;
targetSolver = &Solver::solveGeneral;
identifier = 'G';
break;
case Method::SPECIAL:
std::cout << "=== Using the specialized method ===" << std::endl;
targetSolver = &Solver::solveSpecial;
identifier = 'S';
break;
case Method::LU:
std::cout << "=== Using LU decomposition === " << std::endl;
targetSolver = &Solver::solveLU;
identifier = 'L';
break;
}
for(unsigned int n = low; n <= high; n *= step){
std::cout << "Solving for " << n << "×" << n << " matrix using "
<< repetitions << " repetitions\n";
(this->*targetSolver)(n);
if(saveFlag){
std::stringstream name;
name << identifier << n << ".txt";
save(name.str());
}
}
}
void Solver::solveGeneral(unsigned int n) {
setup(n);
arma::vec a = arma::vec(n+2); a.fill(-1);
arma::vec b = arma::vec(n+2); b.fill(2);
arma::vec c = arma::vec(n+2); c.fill(-1);
b[0] = 1; c[0] = 0; b[n+1] = 1; a[n+1] = 0;
startTiming();
for(unsigned int r = 0; r < repetitions; r++)
solution = thomas(a, b, c, btilde);
endTiming();
}
void Solver::solveSpecial(unsigned int n){
setup(n);
startTiming();
for(unsigned int r = 0; r < repetitions; r++)
solution = thomasSpecial(btilde);
endTiming();
}
void Solver::solveLU(unsigned int n) {
setup(n);
arma::mat A = tridiagonalMat(n+2, -1, 2, -1);
arma::mat L, U;
arma::vec y;
// Ax = b -> LUx = b -> Ly = b -> Ux = y
startTiming();
for(unsigned int r = 0; r < repetitions; r++){
arma::lu(L,U,A);
y = arma::solve(L, btilde);
solution = arma::solve(U, y);
}
endTiming();
}
void Solver::save(const std::string& identifier){
solution.save(savepath+identifier, arma::raw_ascii);
}
void Solver::startTiming(){
startWallTime = std::chrono::high_resolution_clock::now();
startCPUTime = std::clock();
}
void Solver::endTiming(){
auto CPUTime = (std::clock() - startCPUTime)/static_cast<double>(CLOCKS_PER_SEC);
std::chrono::duration<double> wallTime = (std::chrono::high_resolution_clock::now() - startWallTime);
std::cout << "Average wall time: " << wallTime.count()/repetitions << "s\n"
<< "Average CPU time: " << CPUTime/repetitions << "s" << std::endl;
}
void Solver::calculateError(unsigned int n_start, unsigned int n_stop, unsigned int step){
saveFlag = false; // Dont dump everything
char identifier = 'E'; // Error analysis identifier
unsigned int n_iterations = (n_stop - n_start)/step;
double errors[2][n_iterations] = {0};
unsigned int i = 0;
<<<<<<< HEAD
std::ofstream outputFile("data/E.txt");
=======
>>>>>>> e5d6edd72bb65f2481eecc50708d05c03bfafbfc
for(unsigned int n = n_start; n <= n_stop; n+=step){
setup(n); // Reset setup
arma::vec x_num = arma::zeros(n);
arma::vec x_ana = arma::zeros(n);
arma::vec rel_error = arma::zeros(n);
// TODO: Replace with specialized algorithm, currently an issue with running it
arma::vec a = arma::vec(n+2); a.fill(-1);
arma::vec b = arma::vec(n+2); b.fill(2);
arma::vec c = arma::vec(n+2); c.fill(-1);
b[0] = 1; c[0] = 0; b[n+1] = 1; a[n+1] = 0;
x_ana = analyticSolution(domain);
x_num = thomas(a,b,c,btilde);
for(unsigned int i = 1; i <= n-1; i++){
rel_error[i] = fabs((x_num[i] - x_ana[i])/x_ana[i]);
}
<<<<<<< HEAD
errors[0][i] = n;
errors[1][i] = rel_error.max();
outputFile << n << " " << std::fixed << errors[1][i] << std::endl;
std::cout << "n = " << errors[0][i] << " Relative error = "<< errors[1][i] << std::endl;
i += 1;
}
outputFile.close();
=======
errors[0][i] = n;
errors[1][i] = rel_error.max();
std::cout << "n = " << errors[0][i] << " Relative error = "<< errors[1][i] << std::endl;
i += 1;
}
>>>>>>> e5d6edd72bb65f2481eecc50708d05c03bfafbfc
}
<commit_msg>Its late and github is messing with me<commit_after>#include <memory>
#include <fstream>
#include <sstream>
#include <chrono>
#include <ctime>
#include "solver.h"
#include "solve.h"
Solver::Solver(double (*function)(double)){
fn = function;
}
Solver::~Solver(){};
void Solver::setup(unsigned int n){
double h = 1/static_cast<double>(n+2);
domain = h*arma::linspace(0, n+2, n+2); // Armadillo lacks arange :(
btilde = domain;
btilde.transform(fn);
btilde *= h*h; // b~ = f(x)h^2
// Set the boundary conditions
btilde[0] = lowerBound; btilde[n+1] = upperBound;
}
void Solver::solve(Method method, unsigned int low, unsigned int high, unsigned int step) {
char identifier;
void (Solver::*targetSolver)(unsigned int);
switch (method) {
case Method::GENERAL:
std::cout << "=== Using the general method ===" << std::endl;
targetSolver = &Solver::solveGeneral;
identifier = 'G';
break;
case Method::SPECIAL:
std::cout << "=== Using the specialized method ===" << std::endl;
targetSolver = &Solver::solveSpecial;
identifier = 'S';
break;
case Method::LU:
std::cout << "=== Using LU decomposition === " << std::endl;
targetSolver = &Solver::solveLU;
identifier = 'L';
break;
}
for(unsigned int n = low; n <= high; n *= step){
std::cout << "Solving for " << n << "×" << n << " matrix using "
<< repetitions << " repetitions\n";
(this->*targetSolver)(n);
if(saveFlag){
std::stringstream name;
name << identifier << n << ".txt";
save(name.str());
}
}
}
void Solver::solveGeneral(unsigned int n) {
setup(n);
arma::vec a = arma::vec(n+2); a.fill(-1);
arma::vec b = arma::vec(n+2); b.fill(2);
arma::vec c = arma::vec(n+2); c.fill(-1);
b[0] = 1; c[0] = 0; b[n+1] = 1; a[n+1] = 0;
startTiming();
for(unsigned int r = 0; r < repetitions; r++)
solution = thomas(a, b, c, btilde);
endTiming();
}
void Solver::solveSpecial(unsigned int n){
setup(n);
startTiming();
for(unsigned int r = 0; r < repetitions; r++)
solution = thomasSpecial(btilde);
endTiming();
}
void Solver::solveLU(unsigned int n) {
setup(n);
arma::mat A = tridiagonalMat(n+2, -1, 2, -1);
arma::mat L, U;
arma::vec y;
// Ax = b -> LUx = b -> Ly = b -> Ux = y
startTiming();
for(unsigned int r = 0; r < repetitions; r++){
arma::lu(L,U,A);
y = arma::solve(L, btilde);
solution = arma::solve(U, y);
}
endTiming();
}
void Solver::save(const std::string& identifier){
solution.save(savepath+identifier, arma::raw_ascii);
}
void Solver::startTiming(){
startWallTime = std::chrono::high_resolution_clock::now();
startCPUTime = std::clock();
}
void Solver::endTiming(){
auto CPUTime = (std::clock() - startCPUTime)/static_cast<double>(CLOCKS_PER_SEC);
std::chrono::duration<double> wallTime = (std::chrono::high_resolution_clock::now() - startWallTime);
std::cout << "Average wall time: " << wallTime.count()/repetitions << "s\n"
<< "Average CPU time: " << CPUTime/repetitions << "s" << std::endl;
}
void Solver::calculateError(unsigned int n_start, unsigned int n_stop, unsigned int step){
saveFlag = false; // Dont dump everything
char identifier = 'E'; // Error analysis identifier
unsigned int n_iterations = (n_stop - n_start)/step;
double errors[2][n_iterations] = {0};
unsigned int i = 0;
std::ofstream outputFile("data/E.txt");
for(unsigned int n = n_start; n <= n_stop; n+=step){
setup(n); // Reset setup
arma::vec x_num = arma::zeros(n);
arma::vec x_ana = arma::zeros(n);
arma::vec rel_error = arma::zeros(n);
// TODO: Replace with specialized algorithm, currently an issue with running it
arma::vec a = arma::vec(n+2); a.fill(-1);
arma::vec b = arma::vec(n+2); b.fill(2);
arma::vec c = arma::vec(n+2); c.fill(-1);
b[0] = 1; c[0] = 0; b[n+1] = 1; a[n+1] = 0;
x_ana = analyticSolution(domain);
x_num = thomas(a,b,c,btilde);
for(unsigned int i = 1; i <= n-1; i++){
rel_error[i] = fabs((x_num[i] - x_ana[i])/x_ana[i]);
}
errors[0][i] = n;
errors[1][i] = rel_error.max();
outputFile << n << " " << std::fixed << errors[1][i] << std::endl;
std::cout << "n = " << errors[0][i] << " Relative error = "<< errors[1][i] << std::endl;
i += 1;
}
outputFile.close();
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2006 by Tobias Koenig <[email protected]> *
* *
* 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 "tracer.h"
#include <QtCore/QString>
#include "traceradaptor.h"
#include "dbustracer.h"
#include "filetracer.h"
#include "nulltracer.h"
using namespace Akonadi;
Tracer* Tracer::mSelf = 0;
Tracer::Tracer()
{
// TODO: make it configurable?
mTracerBackend = new DBusTracer();
new TracerAdaptor( this );
QDBusConnection::sessionBus().registerObject( QLatin1String("/tracing"), this, QDBusConnection::ExportAdaptors );
}
Tracer::~Tracer()
{
delete mTracerBackend;
mTracerBackend = 0;
}
Tracer* Tracer::self()
{
if ( !mSelf )
mSelf = new Tracer();
return mSelf;
}
void Tracer::beginConnection( const QString &identifier, const QString &msg )
{
mMutex.lock();
mTracerBackend->beginConnection( identifier, msg );
mMutex.unlock();
}
void Tracer::endConnection( const QString &identifier, const QString &msg )
{
mMutex.lock();
mTracerBackend->endConnection( identifier, msg );
mMutex.unlock();
}
void Tracer::connectionInput( const QString &identifier, const QString &msg )
{
mMutex.lock();
mTracerBackend->connectionInput( identifier, msg );
mMutex.unlock();
}
void Tracer::connectionOutput( const QString &identifier, const QString &msg )
{
mMutex.lock();
mTracerBackend->connectionOutput( identifier, msg );
mMutex.unlock();
}
void Tracer::signal( const QString &signalName, const QString &msg )
{
mMutex.lock();
mTracerBackend->signal( signalName, msg );
mMutex.unlock();
}
void Akonadi::Tracer::signal(const char * signalName, const QString & msg)
{
signal( QLatin1String( signalName ), msg );
}
void Tracer::warning( const QString &componentName, const QString &msg )
{
mMutex.lock();
mTracerBackend->warning( componentName, msg );
mMutex.unlock();
}
void Tracer::error( const QString &componentName, const QString &msg )
{
mMutex.lock();
mTracerBackend->error( componentName, msg );
mMutex.unlock();
}
void Akonadi::Tracer::error(const char * componentName, const QString & msg)
{
error( QLatin1String( componentName ), msg );
}
#include "tracer.moc"
<commit_msg>Allow to disable client/server communication debugging, speeds things up quite a bit.<commit_after>/***************************************************************************
* Copyright (C) 2006 by Tobias Koenig <[email protected]> *
* *
* 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 "tracer.h"
#include <QtCore/QSettings>
#include <QtCore/QString>
#include "traceradaptor.h"
#include "dbustracer.h"
#include "filetracer.h"
#include "nulltracer.h"
#include "xdgbasedirs.h"
using namespace Akonadi;
Tracer* Tracer::mSelf = 0;
Tracer::Tracer() : mTracerBackend( 0 )
{
// TODO de-duplicate the following lines
XdgBaseDirs baseDirs;
QString serverConfigFile = baseDirs.findResourceFile( "config", QLatin1String( "akonadi/akonadiserverrc" ) );
if ( serverConfigFile.isEmpty() ) {
serverConfigFile = baseDirs.saveDir( "config", QLatin1String( "akonadi" )) + QLatin1String( "/akonadiserverrc" );
}
QSettings settings( serverConfigFile, QSettings::IniFormat );
const QString type = settings.value( QLatin1String( "Debug/Tracer" ), QLatin1String( "dbus" ) ).toString();
if ( type == QLatin1String("file") ) {
qFatal( "Implement me!" );
// mTracerBackend = new FileTracer();
} else if ( type == QLatin1String("null") ) {
mTracerBackend = new NullTracer();
} else {
mTracerBackend = new DBusTracer();
}
Q_ASSERT( mTracerBackend );
new TracerAdaptor( this );
QDBusConnection::sessionBus().registerObject( QLatin1String("/tracing"), this, QDBusConnection::ExportAdaptors );
}
Tracer::~Tracer()
{
delete mTracerBackend;
mTracerBackend = 0;
}
Tracer* Tracer::self()
{
if ( !mSelf )
mSelf = new Tracer();
return mSelf;
}
void Tracer::beginConnection( const QString &identifier, const QString &msg )
{
mMutex.lock();
mTracerBackend->beginConnection( identifier, msg );
mMutex.unlock();
}
void Tracer::endConnection( const QString &identifier, const QString &msg )
{
mMutex.lock();
mTracerBackend->endConnection( identifier, msg );
mMutex.unlock();
}
void Tracer::connectionInput( const QString &identifier, const QString &msg )
{
mMutex.lock();
mTracerBackend->connectionInput( identifier, msg );
mMutex.unlock();
}
void Tracer::connectionOutput( const QString &identifier, const QString &msg )
{
mMutex.lock();
mTracerBackend->connectionOutput( identifier, msg );
mMutex.unlock();
}
void Tracer::signal( const QString &signalName, const QString &msg )
{
mMutex.lock();
mTracerBackend->signal( signalName, msg );
mMutex.unlock();
}
void Akonadi::Tracer::signal(const char * signalName, const QString & msg)
{
signal( QLatin1String( signalName ), msg );
}
void Tracer::warning( const QString &componentName, const QString &msg )
{
mMutex.lock();
mTracerBackend->warning( componentName, msg );
mMutex.unlock();
}
void Tracer::error( const QString &componentName, const QString &msg )
{
mMutex.lock();
mTracerBackend->error( componentName, msg );
mMutex.unlock();
}
void Akonadi::Tracer::error(const char * componentName, const QString & msg)
{
error( QLatin1String( componentName ), msg );
}
#include "tracer.moc"
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2008 by Jason Ansel *
* [email protected] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "dynamictask.h"
#include "jasm.h"
#include <pthread.h>
#define PBCC_SEQUENTIAL
#define INLINE_NULL_TASKS
namespace hecura {
DynamicScheduler *DynamicTask::scheduler = NULL;
DynamicTask::DynamicTask()
{
// when this task is created, no other thread would touch it
// so no lock for numOfPredecessor update
state = S_NEW;
numOfPredecessor = 0;
#ifndef PBCC_SEQUENTIAL
// allocate scheduler when the first task is created
if(scheduler == NULL) {
scheduler = new DynamicScheduler();
scheduler->startWorkerThreads();
}
#endif
}
#ifdef PBCC_SEQUENTIAL
void DynamicTask::enqueue() { run();}
#else
void DynamicTask::enqueue()
{
int preds;
{
JLOCKSCOPE(lock);
preds=numOfPredecessor;
if(preds==0)
state=S_READY;
else
state=S_PENDING;
}
if(preds==0){
#ifdef INLINE_NULL_TASKS
if(isNullTask()){
runWrapper(); //dont bother enqueuing null tasks
}else
#endif
{
scheduler->enqueue(this);
}
}
}
#endif // PBCC_SEQUENTIAL
#ifdef PBCC_SEQUENTIAL
void DynamicTask::dependsOn(const DynamicTaskPtr &that){}
#else
void DynamicTask::dependsOn(const DynamicTaskPtr &that)
{
if(!that) return;
JASSERT(that!=this).Text("task cant depend on itself");
JASSERT(state==S_NEW)(state).Text(".dependsOn must be called before enqueue()");
that->lock.lock();
if(that->state == S_CONTINUED){
that->lock.unlock();
dependsOn(that->continuation);
}else if(that->state != S_COMPLETE){
that->dependents.push_back(this);
jalib::atomicAdd<1> (&numOfPredecessor);
that->lock.unlock();
}else{
that->lock.unlock();
}
#ifdef VERBOSE
printf("thread %d: task %p depends on task %p counter: %d\n", pthread_self(), this, that.asPtr(), numOfPredecessor);
#endif
}
#endif // PBCC_SEQUENTIAL
void hecura::DynamicTask::decrementPredecessors(){
bool shouldEnqueue = false;
{
JLOCKSCOPE(lock);
if((jalib::atomicAdd<-1> (&numOfPredecessor))==0 && state==S_PENDING){
state = S_READY;
shouldEnqueue = true;
}
}
if(shouldEnqueue){
#ifdef INLINE_NULL_TASKS
if(isNullTask()){
runWrapper(); //dont bother enqueuing null tasks
}else
#endif
{
scheduler->enqueue(this);
}
}
}
void hecura::DynamicTask::runWrapper(){
JASSERT(state==S_READY && numOfPredecessor==0)(state)(numOfPredecessor);
continuation = run();
std::vector<DynamicTaskPtr> tmp;
{
JLOCKSCOPE(lock);
dependents.swap(tmp);
if(continuation) state = S_CONTINUED;
else state = S_COMPLETE;
}
if(continuation){
#ifdef VERBOSE
JTRACE("task complete, continued")(tmp.size());
#endif
{
JLOCKSCOPE(continuation->lock);
if(continuation->dependents.empty()){
//swap is faster than insert
continuation->dependents.swap(tmp);
}else{
continuation->dependents.insert(continuation->dependents.end(), tmp.begin(), tmp.end());
}
}
continuation->enqueue();
}else{
#ifdef VERBOSE
if(!isNullTask()) JTRACE("task complete")(tmp.size());
#endif
std::vector<DynamicTaskPtr>::iterator it;
for(it = tmp.begin(); it != tmp.end(); ++it) {
(*it)->decrementPredecessors();
}
}
}
#ifdef PBCC_SEQUENTIAL
void DynamicTask::waitUntilComplete() {}
#else
void DynamicTask::waitUntilComplete()
{
lock.lock();
while(state != S_COMPLETE && state!= S_CONTINUED) {
lock.unlock();
// get a task for execution
DynamicTaskPtr task = scheduler->tryDequeue();
if (!task) {
pthread_yield();
} else {
task->runWrapper();
}
lock.lock();
}
lock.unlock();
if(state == S_CONTINUED)
continuation->waitUntilComplete();
}
#endif // PBCC_SEQUENTIAL
}
<commit_msg>replace atomic opterions with lock operations in dynamictask on numOfPredecedents<commit_after>/***************************************************************************
* Copyright (C) 2008 by Jason Ansel *
* [email protected] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "dynamictask.h"
#include "jasm.h"
#include <pthread.h>
#define PBCC_SEQUENTIAL
#define INLINE_NULL_TASKS
namespace hecura {
DynamicScheduler *DynamicTask::scheduler = NULL;
DynamicTask::DynamicTask()
{
// when this task is created, no other thread would touch it
// so no lock for numOfPredecessor update
state = S_NEW;
numOfPredecessor = 0;
#ifndef PBCC_SEQUENTIAL
// allocate scheduler when the first task is created
if(scheduler == NULL) {
scheduler = new DynamicScheduler();
scheduler->startWorkerThreads();
}
#endif
}
#ifdef PBCC_SEQUENTIAL
void DynamicTask::enqueue() { run();}
#else
void DynamicTask::enqueue()
{
int preds;
{
JLOCKSCOPE(lock);
preds=numOfPredecessor;
if(preds==0)
state=S_READY;
else
state=S_PENDING;
}
if(preds==0){
#ifdef INLINE_NULL_TASKS
if(isNullTask()){
runWrapper(); //dont bother enqueuing null tasks
}else
#endif
{
scheduler->enqueue(this);
}
}
}
#endif // PBCC_SEQUENTIAL
#ifdef PBCC_SEQUENTIAL
void DynamicTask::dependsOn(const DynamicTaskPtr &that){}
#else
void DynamicTask::dependsOn(const DynamicTaskPtr &that)
{
if(!that) return;
JASSERT(that!=this).Text("task cant depend on itself");
JASSERT(state==S_NEW)(state).Text(".dependsOn must be called before enqueue()");
that->lock.lock();
if(that->state == S_CONTINUED){
that->lock.unlock();
dependsOn(that->continuation);
}else if(that->state != S_COMPLETE){
that->dependents.push_back(this);
lock();
numOfPredecessor++;
unlock();
that->lock.unlock();
}else{
that->lock.unlock();
}
#ifdef VERBOSE
printf("thread %d: task %p depends on task %p counter: %d\n", pthread_self(), this, that.asPtr(), numOfPredecessor);
#endif
}
#endif // PBCC_SEQUENTIAL
void hecura::DynamicTask::decrementPredecessors(){
bool shouldEnqueue = false;
{
JLOCKSCOPE(lock);
if(--numOfPredecessor==0 && state==S_PENDING){
state = S_READY;
shouldEnqueue = true;
}
}
if(shouldEnqueue){
#ifdef INLINE_NULL_TASKS
if(isNullTask()){
runWrapper(); //dont bother enqueuing null tasks
}else
#endif
{
scheduler->enqueue(this);
}
}
}
void hecura::DynamicTask::runWrapper(){
JASSERT(state==S_READY && numOfPredecessor==0)(state)(numOfPredecessor);
continuation = run();
std::vector<DynamicTaskPtr> tmp;
{
JLOCKSCOPE(lock);
dependents.swap(tmp);
if(continuation) state = S_CONTINUED;
else state = S_COMPLETE;
}
if(continuation){
#ifdef VERBOSE
JTRACE("task complete, continued")(tmp.size());
#endif
{
JLOCKSCOPE(continuation->lock);
if(continuation->dependents.empty()){
//swap is faster than insert
continuation->dependents.swap(tmp);
}else{
continuation->dependents.insert(continuation->dependents.end(), tmp.begin(), tmp.end());
}
}
continuation->enqueue();
}else{
#ifdef VERBOSE
if(!isNullTask()) JTRACE("task complete")(tmp.size());
#endif
std::vector<DynamicTaskPtr>::iterator it;
for(it = tmp.begin(); it != tmp.end(); ++it) {
(*it)->decrementPredecessors();
}
}
}
#ifdef PBCC_SEQUENTIAL
void DynamicTask::waitUntilComplete() {}
#else
void DynamicTask::waitUntilComplete()
{
lock.lock();
while(state != S_COMPLETE && state!= S_CONTINUED) {
lock.unlock();
// get a task for execution
DynamicTaskPtr task = scheduler->tryDequeue();
if (!task) {
pthread_yield();
} else {
task->runWrapper();
}
lock.lock();
}
lock.unlock();
if(state == S_CONTINUED)
continuation->waitUntilComplete();
}
#endif // PBCC_SEQUENTIAL
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkColorPriv.h"
#include "SkGeometry.h"
#include "SkShader.h"
#define WIRE_FRAME_WIDTH 1.1f
static void tesselate(const SkPath& src, SkPath* dst) {
SkPath::Iter iter(src, true);
SkPoint pts[4];
SkPath::Verb verb;
while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
switch (verb) {
case SkPath::kMove_Verb:
dst->moveTo(pts[0]);
break;
case SkPath::kLine_Verb:
dst->lineTo(pts[1]);
break;
case SkPath::kQuad_Verb: {
SkPoint p;
for (int i = 1; i <= 8; ++i) {
SkEvalQuadAt(pts, i / 8.0f, &p, NULL);
dst->lineTo(p);
}
} break;
case SkPath::kCubic_Verb: {
SkPoint p;
for (int i = 1; i <= 8; ++i) {
SkEvalCubicAt(pts, i / 8.0f, &p, NULL, NULL);
dst->lineTo(p);
}
} break;
}
}
}
static void setFade(SkPaint* paint, bool showGL) {
paint->setAlpha(showGL ? 0x66 : 0xFF);
}
static void setGLFrame(SkPaint* paint) {
paint->setColor(0xFFFF0000);
paint->setStyle(SkPaint::kStroke_Style);
paint->setAntiAlias(true);
paint->setStrokeWidth(WIRE_FRAME_WIDTH);
}
static void show_mesh(SkCanvas* canvas, const SkRect& r) {
SkPaint paint;
setGLFrame(&paint);
canvas->drawRect(r, paint);
canvas->drawLine(r.fLeft, r.fTop, r.fRight, r.fBottom, paint);
}
static void drawLine(SkCanvas* canvas, const SkPoint& p0, const SkPoint& p1,
const SkPaint& paint) {
canvas->drawLine(p0.fX, p0.fY, p1.fX, p1.fY, paint);
}
static void show_mesh(SkCanvas* canvas, const SkPoint pts[],
const uint16_t indices[], int count) {
SkPaint paint;
setGLFrame(&paint);
for (int i = 0; i < count - 2; ++i) {
drawLine(canvas, pts[indices[i]], pts[indices[i+1]], paint);
drawLine(canvas, pts[indices[i+1]], pts[indices[i+2]], paint);
drawLine(canvas, pts[indices[i+2]], pts[indices[i]], paint);
}
}
static void show_glframe(SkCanvas* canvas, const SkPath& path) {
SkPaint paint;
setGLFrame(&paint);
canvas->drawPath(path, paint);
}
static void show_mesh_between(SkCanvas* canvas, const SkPath& p0, const SkPath& p1) {
SkPath d0, d1;
tesselate(p0, &d0);
tesselate(p1, &d1);
SkPoint pts0[256*2], pts1[256];
int count = d0.getPoints(pts0, SK_ARRAY_COUNT(pts0));
int count1 = d1.getPoints(pts1, SK_ARRAY_COUNT(pts1));
SkASSERT(count == count1);
memcpy(&pts0[count], pts1, count * sizeof(SkPoint));
uint16_t indices[256*6];
uint16_t* ndx = indices;
for (int i = 0; i < count; ++i) {
*ndx++ = i;
*ndx++ = i + count;
}
*ndx++ = 0;
show_mesh(canvas, pts0, indices, ndx - indices);
}
static void show_fan(SkCanvas* canvas, const SkPath& path, SkScalar cx, SkScalar cy) {
SkPaint paint;
setGLFrame(&paint);
canvas->drawPath(path, paint);
SkPoint pts[256];
int count = path.getPoints(pts, SK_ARRAY_COUNT(pts));
for (int i = 0; i < count; ++i) {
canvas->drawLine(pts[i].fX, pts[i].fY, cx, cy, paint);
}
}
///////////////////////////////////////////////////////////////////////////////
typedef void (*DrawProc)(SkCanvas* canvas, bool showGL, int flags);
static void draw_line(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
if (showGL) {
setGLFrame(&paint);
}
canvas->drawLine(50, 50, 400, 100, paint);
paint.setColor(SK_ColorBLACK);
canvas->rotate(40);
setFade(&paint, showGL);
paint.setStrokeWidth(40);
canvas->drawLine(100, 50, 450, 50, paint);
if (showGL) {
show_mesh(canvas, SkRect::MakeLTRB(100, 50-20, 450, 50+20));
}
}
static void draw_rect(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
SkRect r = SkRect::MakeLTRB(50, 70, 250, 370);
setFade(&paint, showGL);
canvas->drawRect(r, paint);
if (showGL) {
show_mesh(canvas, r);
}
canvas->translate(320, 0);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(25);
canvas->drawRect(r, paint);
if (showGL) {
SkScalar rad = paint.getStrokeWidth() / 2;
SkPoint pts[8];
r.outset(rad, rad);
r.toQuad(&pts[0]);
r.inset(rad*2, rad*2);
r.toQuad(&pts[4]);
const uint16_t indices[] = {
0, 4, 1, 5, 2, 6, 3, 7, 0, 4
};
show_mesh(canvas, pts, indices, SK_ARRAY_COUNT(indices));
}
}
static void draw_oval(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
SkRect r = SkRect::MakeLTRB(50, 70, 250, 370);
setFade(&paint, showGL);
canvas->drawOval(r, paint);
if (showGL) {
switch (flags) {
case 0: {
SkPath path;
path.addOval(r);
show_glframe(canvas, path);
} break;
case 1:
case 3: {
SkPath src, dst;
src.addOval(r);
tesselate(src, &dst);
show_fan(canvas, dst, r.centerX(), r.centerY());
} break;
case 2: {
SkPaint p(paint);
show_mesh(canvas, r);
setGLFrame(&p);
paint.setStyle(SkPaint::kFill_Style);
canvas->drawCircle(r.centerX(), r.centerY(), 3, p);
} break;
}
}
canvas->translate(320, 0);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(25);
canvas->drawOval(r, paint);
if (showGL) {
switch (flags) {
case 0: {
SkPath path;
SkScalar rad = paint.getStrokeWidth() / 2;
r.outset(rad, rad);
path.addOval(r);
r.inset(rad*2, rad*2);
path.addOval(r);
show_glframe(canvas, path);
} break;
case 1: {
SkPath path0, path1;
SkScalar rad = paint.getStrokeWidth() / 2;
r.outset(rad, rad);
path0.addOval(r);
r.inset(rad*2, rad*2);
path1.addOval(r);
show_mesh_between(canvas, path0, path1);
} break;
case 2: {
SkPath path;
path.addOval(r);
show_glframe(canvas, path);
SkScalar rad = paint.getStrokeWidth() / 2;
r.outset(rad, rad);
show_mesh(canvas, r);
} break;
case 3: {
SkScalar rad = paint.getStrokeWidth() / 2;
r.outset(rad, rad);
SkPaint paint;
paint.setAlpha(0x33);
canvas->drawRect(r, paint);
show_mesh(canvas, r);
} break;
}
}
}
#include "SkImageDecoder.h"
static void draw_image(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
setFade(&paint, showGL);
SkBitmap bm;
SkImageDecoder::DecodeFile("/skimages/startrek.png", &bm);
SkRect r = SkRect::MakeWH(bm.width(), bm.height());
canvas->save();
canvas->translate(30, 30);
canvas->scale(0.8f, 0.8f);
canvas->drawBitmap(bm, 0, 0, &paint);
if (showGL) {
show_mesh(canvas, r);
}
canvas->restore();
canvas->translate(210, 290);
canvas->rotate(-35);
canvas->drawBitmap(bm, 0, 0, &paint);
if (showGL) {
show_mesh(canvas, r);
}
}
static void draw_text(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
paint.setLCDRenderText(true);
const char text[] = "Graphics at Google";
size_t len = strlen(text);
setFade(&paint, showGL);
canvas->translate(40, 50);
for (int i = 0; i < 10; ++i) {
paint.setTextSize(12 + i * 3);
canvas->drawText(text, len, 0, 0, paint);
if (showGL) {
SkRect bounds[256];
SkScalar widths[256];
int count = paint.getTextWidths(text, len, widths, bounds);
SkScalar adv = 0;
for (int j = 0; j < count; ++j) {
bounds[j].offset(adv, 0);
show_mesh(canvas, bounds[j]);
adv += widths[j];
}
}
canvas->translate(0, paint.getTextSize() * 3 / 2);
}
}
static const struct {
DrawProc fProc;
const char* fName;
} gRec[] = {
{ draw_line, "Lines" },
{ draw_rect, "Rects" },
{ draw_oval, "Ovals" },
{ draw_image, "Images" },
{ draw_text, "Text" },
};
class TalkGM : public skiagm::GM {
DrawProc fProc;
SkString fName;
bool fShowGL;
int fFlags;
public:
TalkGM(int index, bool showGL, int flags = 0) {
fProc = gRec[index].fProc;
fName.set(gRec[index].fName);
if (showGL) {
fName.append("-gl");
}
fShowGL = showGL;
fFlags = flags;
}
protected:
virtual SkString onShortName() {
return fName;
}
virtual SkISize onISize() {
return SkISize::Make(640, 480);
}
virtual void onDraw(SkCanvas* canvas) {
SkRect dst = SkRect::MakeWH(canvas->getDevice()->width(), canvas->getDevice()->height());
SkRect src = SkRect::MakeWH(640, 480);
SkMatrix matrix;
matrix.setRectToRect(src, dst, SkMatrix::kCenter_ScaleToFit);
canvas->concat(matrix);
fProc(canvas, fShowGL, fFlags);
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
#define GM_CONCAT(X,Y) GM_CONCAT_IMPL(X,Y)
#define GM_CONCAT_IMPL(X,Y) X##Y
#define FACTORY_NAME GM_CONCAT(Factory, __LINE__)
#define REGISTRY_NAME GM_CONCAT(gReg, __LINE__)
#define ADD_GM(Class, args) \
static skiagm::GM* FACTORY_NAME(void*) { return new Class args; } \
static skiagm::GMRegistry REGISTRY_NAME(FACTORY_NAME);
ADD_GM(TalkGM, (0, false))
ADD_GM(TalkGM, (0, true))
ADD_GM(TalkGM, (1, false))
ADD_GM(TalkGM, (1, true))
ADD_GM(TalkGM, (2, false))
ADD_GM(TalkGM, (2, true))
ADD_GM(TalkGM, (2, true, 1))
ADD_GM(TalkGM, (2, true, 2))
ADD_GM(TalkGM, (2, true, 3))
ADD_GM(TalkGM, (3, false))
ADD_GM(TalkGM, (3, true))
ADD_GM(TalkGM, (4, false))
ADD_GM(TalkGM, (4, true))
//static GM* MyFactory(void*) { return new TalkGM(0, false); }
//static GMRegistry reg(MyFactory);
<commit_msg>cache decoded bitmap in global for now<commit_after>
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkColorPriv.h"
#include "SkGeometry.h"
#include "SkShader.h"
#define WIRE_FRAME_WIDTH 1.1f
static void tesselate(const SkPath& src, SkPath* dst) {
SkPath::Iter iter(src, true);
SkPoint pts[4];
SkPath::Verb verb;
while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
switch (verb) {
case SkPath::kMove_Verb:
dst->moveTo(pts[0]);
break;
case SkPath::kLine_Verb:
dst->lineTo(pts[1]);
break;
case SkPath::kQuad_Verb: {
SkPoint p;
for (int i = 1; i <= 8; ++i) {
SkEvalQuadAt(pts, i / 8.0f, &p, NULL);
dst->lineTo(p);
}
} break;
case SkPath::kCubic_Verb: {
SkPoint p;
for (int i = 1; i <= 8; ++i) {
SkEvalCubicAt(pts, i / 8.0f, &p, NULL, NULL);
dst->lineTo(p);
}
} break;
}
}
}
static void setFade(SkPaint* paint, bool showGL) {
paint->setAlpha(showGL ? 0x66 : 0xFF);
}
static void setGLFrame(SkPaint* paint) {
paint->setColor(0xFFFF0000);
paint->setStyle(SkPaint::kStroke_Style);
paint->setAntiAlias(true);
paint->setStrokeWidth(WIRE_FRAME_WIDTH);
}
static void show_mesh(SkCanvas* canvas, const SkRect& r) {
SkPaint paint;
setGLFrame(&paint);
canvas->drawRect(r, paint);
canvas->drawLine(r.fLeft, r.fTop, r.fRight, r.fBottom, paint);
}
static void drawLine(SkCanvas* canvas, const SkPoint& p0, const SkPoint& p1,
const SkPaint& paint) {
canvas->drawLine(p0.fX, p0.fY, p1.fX, p1.fY, paint);
}
static void show_mesh(SkCanvas* canvas, const SkPoint pts[],
const uint16_t indices[], int count) {
SkPaint paint;
setGLFrame(&paint);
for (int i = 0; i < count - 2; ++i) {
drawLine(canvas, pts[indices[i]], pts[indices[i+1]], paint);
drawLine(canvas, pts[indices[i+1]], pts[indices[i+2]], paint);
drawLine(canvas, pts[indices[i+2]], pts[indices[i]], paint);
}
}
static void show_glframe(SkCanvas* canvas, const SkPath& path) {
SkPaint paint;
setGLFrame(&paint);
canvas->drawPath(path, paint);
}
static void show_mesh_between(SkCanvas* canvas, const SkPath& p0, const SkPath& p1) {
SkPath d0, d1;
tesselate(p0, &d0);
tesselate(p1, &d1);
SkPoint pts0[256*2], pts1[256];
int count = d0.getPoints(pts0, SK_ARRAY_COUNT(pts0));
int count1 = d1.getPoints(pts1, SK_ARRAY_COUNT(pts1));
SkASSERT(count == count1);
memcpy(&pts0[count], pts1, count * sizeof(SkPoint));
uint16_t indices[256*6];
uint16_t* ndx = indices;
for (int i = 0; i < count; ++i) {
*ndx++ = i;
*ndx++ = i + count;
}
*ndx++ = 0;
show_mesh(canvas, pts0, indices, ndx - indices);
}
static void show_fan(SkCanvas* canvas, const SkPath& path, SkScalar cx, SkScalar cy) {
SkPaint paint;
setGLFrame(&paint);
canvas->drawPath(path, paint);
SkPoint pts[256];
int count = path.getPoints(pts, SK_ARRAY_COUNT(pts));
for (int i = 0; i < count; ++i) {
canvas->drawLine(pts[i].fX, pts[i].fY, cx, cy, paint);
}
}
///////////////////////////////////////////////////////////////////////////////
typedef void (*DrawProc)(SkCanvas* canvas, bool showGL, int flags);
static void draw_line(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
if (showGL) {
setGLFrame(&paint);
}
canvas->drawLine(50, 50, 400, 100, paint);
paint.setColor(SK_ColorBLACK);
canvas->rotate(40);
setFade(&paint, showGL);
paint.setStrokeWidth(40);
canvas->drawLine(100, 50, 450, 50, paint);
if (showGL) {
show_mesh(canvas, SkRect::MakeLTRB(100, 50-20, 450, 50+20));
}
}
static void draw_rect(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
SkRect r = SkRect::MakeLTRB(50, 70, 250, 370);
setFade(&paint, showGL);
canvas->drawRect(r, paint);
if (showGL) {
show_mesh(canvas, r);
}
canvas->translate(320, 0);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(25);
canvas->drawRect(r, paint);
if (showGL) {
SkScalar rad = paint.getStrokeWidth() / 2;
SkPoint pts[8];
r.outset(rad, rad);
r.toQuad(&pts[0]);
r.inset(rad*2, rad*2);
r.toQuad(&pts[4]);
const uint16_t indices[] = {
0, 4, 1, 5, 2, 6, 3, 7, 0, 4
};
show_mesh(canvas, pts, indices, SK_ARRAY_COUNT(indices));
}
}
static void draw_oval(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
SkRect r = SkRect::MakeLTRB(50, 70, 250, 370);
setFade(&paint, showGL);
canvas->drawOval(r, paint);
if (showGL) {
switch (flags) {
case 0: {
SkPath path;
path.addOval(r);
show_glframe(canvas, path);
} break;
case 1:
case 3: {
SkPath src, dst;
src.addOval(r);
tesselate(src, &dst);
show_fan(canvas, dst, r.centerX(), r.centerY());
} break;
case 2: {
SkPaint p(paint);
show_mesh(canvas, r);
setGLFrame(&p);
paint.setStyle(SkPaint::kFill_Style);
canvas->drawCircle(r.centerX(), r.centerY(), 3, p);
} break;
}
}
canvas->translate(320, 0);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(25);
canvas->drawOval(r, paint);
if (showGL) {
switch (flags) {
case 0: {
SkPath path;
SkScalar rad = paint.getStrokeWidth() / 2;
r.outset(rad, rad);
path.addOval(r);
r.inset(rad*2, rad*2);
path.addOval(r);
show_glframe(canvas, path);
} break;
case 1: {
SkPath path0, path1;
SkScalar rad = paint.getStrokeWidth() / 2;
r.outset(rad, rad);
path0.addOval(r);
r.inset(rad*2, rad*2);
path1.addOval(r);
show_mesh_between(canvas, path0, path1);
} break;
case 2: {
SkPath path;
path.addOval(r);
show_glframe(canvas, path);
SkScalar rad = paint.getStrokeWidth() / 2;
r.outset(rad, rad);
show_mesh(canvas, r);
} break;
case 3: {
SkScalar rad = paint.getStrokeWidth() / 2;
r.outset(rad, rad);
SkPaint paint;
paint.setAlpha(0x33);
canvas->drawRect(r, paint);
show_mesh(canvas, r);
} break;
}
}
}
#include "SkImageDecoder.h"
static void draw_image(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
setFade(&paint, showGL);
static SkBitmap* gBM;
if (NULL == gBM) {
gBM = new SkBitmap;
SkImageDecoder::DecodeFile("/skimages/startrek.png", gBM);
}
SkRect r = SkRect::MakeWH(gBM->width(), gBM->height());
canvas->save();
canvas->translate(30, 30);
canvas->scale(0.8f, 0.8f);
canvas->drawBitmap(*gBM, 0, 0, &paint);
if (showGL) {
show_mesh(canvas, r);
}
canvas->restore();
canvas->translate(210, 290);
canvas->rotate(-35);
canvas->drawBitmap(*gBM, 0, 0, &paint);
if (showGL) {
show_mesh(canvas, r);
}
}
static void draw_text(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
paint.setLCDRenderText(true);
const char text[] = "Graphics at Google";
size_t len = strlen(text);
setFade(&paint, showGL);
canvas->translate(40, 50);
for (int i = 0; i < 10; ++i) {
paint.setTextSize(12 + i * 3);
canvas->drawText(text, len, 0, 0, paint);
if (showGL) {
SkRect bounds[256];
SkScalar widths[256];
int count = paint.getTextWidths(text, len, widths, bounds);
SkScalar adv = 0;
for (int j = 0; j < count; ++j) {
bounds[j].offset(adv, 0);
show_mesh(canvas, bounds[j]);
adv += widths[j];
}
}
canvas->translate(0, paint.getTextSize() * 3 / 2);
}
}
static const struct {
DrawProc fProc;
const char* fName;
} gRec[] = {
{ draw_line, "Lines" },
{ draw_rect, "Rects" },
{ draw_oval, "Ovals" },
{ draw_image, "Images" },
{ draw_text, "Text" },
};
class TalkGM : public skiagm::GM {
DrawProc fProc;
SkString fName;
bool fShowGL;
int fFlags;
public:
TalkGM(int index, bool showGL, int flags = 0) {
fProc = gRec[index].fProc;
fName.set(gRec[index].fName);
if (showGL) {
fName.append("-gl");
}
fShowGL = showGL;
fFlags = flags;
}
protected:
virtual SkString onShortName() {
return fName;
}
virtual SkISize onISize() {
return SkISize::Make(640, 480);
}
virtual void onDraw(SkCanvas* canvas) {
SkRect dst = SkRect::MakeWH(canvas->getDevice()->width(), canvas->getDevice()->height());
SkRect src = SkRect::MakeWH(640, 480);
SkMatrix matrix;
matrix.setRectToRect(src, dst, SkMatrix::kCenter_ScaleToFit);
canvas->concat(matrix);
fProc(canvas, fShowGL, fFlags);
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
#define GM_CONCAT(X,Y) GM_CONCAT_IMPL(X,Y)
#define GM_CONCAT_IMPL(X,Y) X##Y
#define FACTORY_NAME GM_CONCAT(Factory, __LINE__)
#define REGISTRY_NAME GM_CONCAT(gReg, __LINE__)
#define ADD_GM(Class, args) \
static skiagm::GM* FACTORY_NAME(void*) { return new Class args; } \
static skiagm::GMRegistry REGISTRY_NAME(FACTORY_NAME);
ADD_GM(TalkGM, (0, false))
ADD_GM(TalkGM, (0, true))
ADD_GM(TalkGM, (1, false))
ADD_GM(TalkGM, (1, true))
ADD_GM(TalkGM, (2, false))
ADD_GM(TalkGM, (2, true))
ADD_GM(TalkGM, (2, true, 1))
ADD_GM(TalkGM, (2, true, 2))
ADD_GM(TalkGM, (2, true, 3))
ADD_GM(TalkGM, (3, false))
ADD_GM(TalkGM, (3, true))
ADD_GM(TalkGM, (4, false))
ADD_GM(TalkGM, (4, true))
//static GM* MyFactory(void*) { return new TalkGM(0, false); }
//static GMRegistry reg(MyFactory);
<|endoftext|> |
<commit_before>#define MS_CLASS "RTC::SeqManager"
// #define MS_LOG_DEV_LEVEL 3
#include "RTC/SeqManager.hpp"
#include "Logger.hpp"
#include <iterator>
namespace RTC
{
template<typename T>
bool SeqManager<T>::SeqLowerThan::operator()(const T lhs, const T rhs) const
{
return ((rhs > lhs) && (rhs - lhs <= MaxValue / 2)) ||
((lhs > rhs) && (lhs - rhs > MaxValue / 2));
}
template<typename T>
bool SeqManager<T>::SeqHigherThan::operator()(const T lhs, const T rhs) const
{
return ((lhs > rhs) && (lhs - rhs <= MaxValue / 2)) ||
((rhs > lhs) && (rhs - lhs > MaxValue / 2));
}
template<typename T>
const typename SeqManager<T>::SeqLowerThan SeqManager<T>::isSeqLowerThan{};
template<typename T>
const typename SeqManager<T>::SeqHigherThan SeqManager<T>::isSeqHigherThan{};
template<typename T>
bool SeqManager<T>::IsSeqLowerThan(const T lhs, const T rhs)
{
return isSeqLowerThan(lhs, rhs);
}
template<typename T>
bool SeqManager<T>::IsSeqHigherThan(const T lhs, const T rhs)
{
return isSeqHigherThan(lhs, rhs);
}
template<typename T>
void SeqManager<T>::Sync(T input)
{
// Update base.
this->base = this->maxOutput - input;
// Update maxInput.
this->maxInput = input;
// Clear dropped set.
this->dropped.clear();
}
template<typename T>
void SeqManager<T>::Drop(T input)
{
// Mark as dropped if 'input' is higher than anyone already processed.
if (SeqManager<T>::IsSeqHigherThan(input, this->maxInput))
{
this->dropped.insert(input);
}
}
template<typename T>
void SeqManager<T>::Offset(T offset)
{
this->base += offset;
}
template<typename T>
bool SeqManager<T>::Input(const T input, T& output)
{
auto base = this->base;
// There are dropped inputs. Synchronize.
if (!this->dropped.empty())
{
// Delete dropped inputs older than input - MaxValue/2.
size_t droppedSize = this->dropped.size();
auto it = this->dropped.lower_bound(input - MaxValue / 2);
this->dropped.erase(this->dropped.begin(), it);
this->base -= (droppedSize - this->dropped.size());
base = this->base;
// Check whether this input was dropped.
it = this->dropped.find(input);
if (it != this->dropped.end())
{
MS_DEBUG_DEV("trying to send a dropped input");
return false;
}
// Count dropped entries before 'input' in order to adapt the base.
size_t dropped =
this->dropped.size() - std::distance(this->dropped.upper_bound(input), this->dropped.end());
base -= dropped;
}
output = input + base;
T idelta = input - this->maxInput;
T odelta = output - this->maxOutput;
// New input is higher than the maximum seen. But less than acceptable units higher.
// Keep it as the maximum seen. See Drop().
if (idelta < MaxValue / 2)
this->maxInput = input;
// New output is higher than the maximum seen. But less than acceptable units higher.
// Keep it as the maximum seen. See Sync().
if (odelta < MaxValue / 2)
this->maxOutput = output;
return true;
}
template<typename T>
T SeqManager<T>::GetMaxInput() const
{
return this->maxInput;
}
template<typename T>
T SeqManager<T>::GetMaxOutput() const
{
return this->maxOutput;
}
// Explicit instantiation to have all SeqManager definitions in this file.
template class SeqManager<uint8_t>;
template class SeqManager<uint16_t>;
template class SeqManager<uint32_t>;
} // namespace RTC
<commit_msg>SeqManager: increase performance (#398)<commit_after>#define MS_CLASS "RTC::SeqManager"
// #define MS_LOG_DEV_LEVEL 3
#include "RTC/SeqManager.hpp"
#include "Logger.hpp"
#include <iterator>
namespace RTC
{
template<typename T>
bool SeqManager<T>::SeqLowerThan::operator()(const T lhs, const T rhs) const
{
return ((rhs > lhs) && (rhs - lhs <= MaxValue / 2)) ||
((lhs > rhs) && (lhs - rhs > MaxValue / 2));
}
template<typename T>
bool SeqManager<T>::SeqHigherThan::operator()(const T lhs, const T rhs) const
{
return ((lhs > rhs) && (lhs - rhs <= MaxValue / 2)) ||
((rhs > lhs) && (rhs - lhs > MaxValue / 2));
}
template<typename T>
const typename SeqManager<T>::SeqLowerThan SeqManager<T>::isSeqLowerThan{};
template<typename T>
const typename SeqManager<T>::SeqHigherThan SeqManager<T>::isSeqHigherThan{};
template<typename T>
bool SeqManager<T>::IsSeqLowerThan(const T lhs, const T rhs)
{
return isSeqLowerThan(lhs, rhs);
}
template<typename T>
bool SeqManager<T>::IsSeqHigherThan(const T lhs, const T rhs)
{
return isSeqHigherThan(lhs, rhs);
}
template<typename T>
void SeqManager<T>::Sync(T input)
{
// Update base.
this->base = this->maxOutput - input;
// Update maxInput.
this->maxInput = input;
// Clear dropped set.
this->dropped.clear();
}
template<typename T>
void SeqManager<T>::Drop(T input)
{
// Mark as dropped if 'input' is higher than anyone already processed.
if (SeqManager<T>::IsSeqHigherThan(input, this->maxInput))
{
this->dropped.insert(input);
}
}
template<typename T>
void SeqManager<T>::Offset(T offset)
{
this->base += offset;
}
template<typename T>
bool SeqManager<T>::Input(const T input, T& output)
{
auto base = this->base;
// There are dropped inputs. Synchronize.
if (!this->dropped.empty())
{
// Delete dropped inputs older than input - MaxValue/2.
size_t droppedCount = this->dropped.size();
auto it = this->dropped.lower_bound(input - MaxValue / 2);
this->dropped.erase(this->dropped.begin(), it);
this->base -= (droppedCount - this->dropped.size());
// Count dropped entries before 'input' in order to adapt the base.
droppedCount = this->dropped.size();
it = this->dropped.lower_bound(input);
if (it != this->dropped.end())
{
// Check whether this input was dropped.
if (*it == input)
{
MS_DEBUG_DEV("trying to send a dropped input");
return false;
}
droppedCount -= std::distance(it, this->dropped.end());
}
base = this->base - droppedCount;
}
output = input + base;
T idelta = input - this->maxInput;
T odelta = output - this->maxOutput;
// New input is higher than the maximum seen. But less than acceptable units higher.
// Keep it as the maximum seen. See Drop().
if (idelta < MaxValue / 2)
this->maxInput = input;
// New output is higher than the maximum seen. But less than acceptable units higher.
// Keep it as the maximum seen. See Sync().
if (odelta < MaxValue / 2)
this->maxOutput = output;
return true;
}
template<typename T>
T SeqManager<T>::GetMaxInput() const
{
return this->maxInput;
}
template<typename T>
T SeqManager<T>::GetMaxOutput() const
{
return this->maxOutput;
}
// Explicit instantiation to have all SeqManager definitions in this file.
template class SeqManager<uint8_t>;
template class SeqManager<uint16_t>;
template class SeqManager<uint32_t>;
} // namespace RTC
<|endoftext|> |
<commit_before>#include "gm.h"
#include "SkBitmap.h"
#include "SkShader.h"
#include "SkXfermode.h"
namespace skiagm {
static void make_bitmaps(int w, int h, SkBitmap* src, SkBitmap* dst) {
src->setConfig(SkBitmap::kARGB_8888_Config, w, h);
src->allocPixels();
src->eraseColor(0);
SkCanvas c(*src);
SkPaint p;
SkRect r;
SkScalar ww = SkIntToScalar(w);
SkScalar hh = SkIntToScalar(h);
p.setAntiAlias(true);
p.setColor(0xFFFFCC44);
r.set(0, 0, ww*3/4, hh*3/4);
c.drawOval(r, p);
dst->setConfig(SkBitmap::kARGB_8888_Config, w, h);
dst->allocPixels();
dst->eraseColor(0);
c.setBitmapDevice(*dst);
p.setColor(0xFF66AAFF);
r.set(ww/3, hh/3, ww*19/20, hh*19/20);
c.drawRect(r, p);
}
static uint16_t gBG[] = { 0xFFFF, 0xCCCF, 0xCCCF, 0xFFFF };
class XfermodesGM : public GM {
SkBitmap fBitmap;
SkBitmap fBG;
SkBitmap fSrcB, fDstB;
void draw_mode(SkCanvas* canvas, SkXfermode* mode, int alpha) {
SkPaint p;
canvas->drawBitmap(fSrcB, 0, 0, &p);
p.setAlpha(alpha);
p.setXfermode(mode);
canvas->drawBitmap(fDstB, 0, 0, &p);
}
public:
XfermodesGM() {
const int W = 64;
const int H = 64;
fBitmap.setConfig(SkBitmap::kARGB_8888_Config, W, H);
fBitmap.allocPixels();
fBG.setConfig(SkBitmap::kARGB_4444_Config, 2, 2, 4);
fBG.setPixels(gBG);
fBG.setIsOpaque(true);
make_bitmaps(W, H, &fSrcB, &fDstB);
}
protected:
SkString onShortName() {
return SkString("xfermodes");
}
SkISize onISize() { return make_isize(640, 380); }
void drawBG(SkCanvas* canvas) {
canvas->drawColor(SK_ColorWHITE);
return;
SkShader* s = SkShader::CreateBitmapShader(fBG,
SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode);
SkPaint p;
SkMatrix m;
p.setShader(s)->unref();
m.setScale(SkIntToScalar(8), SkIntToScalar(8));
s->setLocalMatrix(m);
canvas->drawPaint(p);
}
virtual void onDraw(SkCanvas* canvas) {
this->drawBG(canvas);
const struct {
SkPorterDuff::Mode fMode;
const char* fLabel;
} gModes[] = {
{ SkPorterDuff::kClear_Mode, "Clear" },
{ SkPorterDuff::kSrc_Mode, "Src" },
{ SkPorterDuff::kDst_Mode, "Dst" },
{ SkPorterDuff::kSrcOver_Mode, "SrcOver" },
{ SkPorterDuff::kDstOver_Mode, "DstOver" },
{ SkPorterDuff::kSrcIn_Mode, "SrcIn" },
{ SkPorterDuff::kDstIn_Mode, "DstIn" },
{ SkPorterDuff::kSrcOut_Mode, "SrcOut" },
{ SkPorterDuff::kDstOut_Mode, "DstOut" },
{ SkPorterDuff::kSrcATop_Mode, "SrcATop" },
{ SkPorterDuff::kDstATop_Mode, "DstATop" },
{ SkPorterDuff::kXor_Mode, "Xor" },
{ SkPorterDuff::kDarken_Mode, "Darken" },
{ SkPorterDuff::kLighten_Mode, "Lighten" },
{ SkPorterDuff::kMultiply_Mode, "Multiply" },
{ SkPorterDuff::kScreen_Mode, "Screen" }
};
canvas->translate(SkIntToScalar(10), SkIntToScalar(20));
SkCanvas c(fBitmap);
const SkScalar w = SkIntToScalar(fBitmap.width());
const SkScalar h = SkIntToScalar(fBitmap.height());
SkShader* s = SkShader::CreateBitmapShader(fBG,
SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode);
SkMatrix m;
m.setScale(SkIntToScalar(6), SkIntToScalar(6));
s->setLocalMatrix(m);
SkPaint labelP;
labelP.setAntiAlias(true);
labelP.setTextAlign(SkPaint::kCenter_Align);
SkScalar x0 = 0;
for (int twice = 0; twice < 2; twice++) {
SkScalar x = x0, y = 0;
for (size_t i = 0; i < SK_ARRAY_COUNT(gModes); i++) {
SkXfermode* mode = SkPorterDuff::CreateXfermode(gModes[i].fMode);
fBitmap.eraseColor(0);
draw_mode(&c, mode, twice ? 0x88 : 0xFF);
mode->safeUnref();
SkPaint p;
SkRect r;
r.set(x, y, x+w, y+h);
r.inset(-SK_ScalarHalf, -SK_ScalarHalf);
p.setStyle(SkPaint::kStroke_Style);
canvas->drawRect(r, p);
p.setStyle(SkPaint::kFill_Style);
p.setShader(s);
r.inset(SK_ScalarHalf, SK_ScalarHalf);
canvas->drawRect(r, p);
canvas->drawBitmap(fBitmap, x, y, NULL);
#if 1
canvas->drawText(gModes[i].fLabel, strlen(gModes[i].fLabel),
x + w/2, y - labelP.getTextSize()/2, labelP);
#endif
x += w + SkIntToScalar(10);
if ((i & 3) == 3) {
x = x0;
y += h + SkIntToScalar(30);
}
}
x0 += SkIntToScalar(330);
}
s->unref();
}
private:
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new XfermodesGM; }
static GMRegistry reg(MyFactory);
}
<commit_msg>update to use new xfermodes<commit_after>#include "gm.h"
#include "SkBitmap.h"
#include "SkShader.h"
#include "SkXfermode.h"
namespace skiagm {
static void make_bitmaps(int w, int h, SkBitmap* src, SkBitmap* dst) {
src->setConfig(SkBitmap::kARGB_8888_Config, w, h);
src->allocPixels();
src->eraseColor(0);
SkCanvas c(*src);
SkPaint p;
SkRect r;
SkScalar ww = SkIntToScalar(w);
SkScalar hh = SkIntToScalar(h);
p.setAntiAlias(true);
p.setColor(0xFFFFCC44);
r.set(0, 0, ww*3/4, hh*3/4);
c.drawOval(r, p);
dst->setConfig(SkBitmap::kARGB_8888_Config, w, h);
dst->allocPixels();
dst->eraseColor(0);
c.setBitmapDevice(*dst);
p.setColor(0xFF66AAFF);
r.set(ww/3, hh/3, ww*19/20, hh*19/20);
c.drawRect(r, p);
}
static uint16_t gBG[] = { 0xFFFF, 0xCCCF, 0xCCCF, 0xFFFF };
class XfermodesGM : public GM {
SkBitmap fBitmap;
SkBitmap fBG;
SkBitmap fSrcB, fDstB;
void draw_mode(SkCanvas* canvas, SkXfermode* mode, int alpha) {
SkPaint p;
canvas->drawBitmap(fSrcB, 0, 0, &p);
p.setAlpha(alpha);
p.setXfermode(mode);
canvas->drawBitmap(fDstB, 0, 0, &p);
}
public:
XfermodesGM() {
const int W = 64;
const int H = 64;
fBitmap.setConfig(SkBitmap::kARGB_8888_Config, W, H);
fBitmap.allocPixels();
fBG.setConfig(SkBitmap::kARGB_4444_Config, 2, 2, 4);
fBG.setPixels(gBG);
fBG.setIsOpaque(true);
make_bitmaps(W, H, &fSrcB, &fDstB);
}
protected:
SkString onShortName() {
return SkString("xfermodes");
}
SkISize onISize() { return make_isize(790, 480); }
void drawBG(SkCanvas* canvas) {
canvas->drawColor(SK_ColorWHITE);
return;
SkShader* s = SkShader::CreateBitmapShader(fBG,
SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode);
SkPaint p;
SkMatrix m;
p.setShader(s)->unref();
m.setScale(SkIntToScalar(8), SkIntToScalar(8));
s->setLocalMatrix(m);
canvas->drawPaint(p);
}
virtual void onDraw(SkCanvas* canvas) {
this->drawBG(canvas);
const struct {
SkXfermode::Mode fMode;
const char* fLabel;
} gModes[] = {
{ SkXfermode::kClear_Mode, "Clear" },
{ SkXfermode::kSrc_Mode, "Src" },
{ SkXfermode::kDst_Mode, "Dst" },
{ SkXfermode::kSrcOver_Mode, "SrcOver" },
{ SkXfermode::kDstOver_Mode, "DstOver" },
{ SkXfermode::kSrcIn_Mode, "SrcIn" },
{ SkXfermode::kDstIn_Mode, "DstIn" },
{ SkXfermode::kSrcOut_Mode, "SrcOut" },
{ SkXfermode::kDstOut_Mode, "DstOut" },
{ SkXfermode::kSrcATop_Mode, "SrcATop" },
{ SkXfermode::kDstATop_Mode, "DstATop" },
{ SkXfermode::kXor_Mode, "Xor" },
{ SkXfermode::kPlus_Mode, "Plus" },
{ SkXfermode::kMultiply_Mode, "Multiply" },
{ SkXfermode::kScreen_Mode, "Screen" },
{ SkXfermode::kOverlay_Mode, "Overlay" },
{ SkXfermode::kDarken_Mode, "Darken" },
{ SkXfermode::kLighten_Mode, "Lighten" },
{ SkXfermode::kColorDodge_Mode, "ColorDodge" },
{ SkXfermode::kColorBurn_Mode, "ColorBurn" },
{ SkXfermode::kHardLight_Mode, "HardLight" },
{ SkXfermode::kSoftLight_Mode, "SoftLight" },
{ SkXfermode::kDifference_Mode, "Difference" },
{ SkXfermode::kExclusion_Mode, "Exclusion" },
};
canvas->translate(SkIntToScalar(10), SkIntToScalar(20));
SkCanvas c(fBitmap);
const SkScalar w = SkIntToScalar(fBitmap.width());
const SkScalar h = SkIntToScalar(fBitmap.height());
SkShader* s = SkShader::CreateBitmapShader(fBG,
SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode);
SkMatrix m;
m.setScale(SkIntToScalar(6), SkIntToScalar(6));
s->setLocalMatrix(m);
SkPaint labelP;
labelP.setAntiAlias(true);
labelP.setTextAlign(SkPaint::kCenter_Align);
const int W = 5;
SkScalar x0 = 0;
for (int twice = 0; twice < 2; twice++) {
SkScalar x = x0, y = 0;
for (size_t i = 0; i < SK_ARRAY_COUNT(gModes); i++) {
SkXfermode* mode = SkXfermode::Create(gModes[i].fMode);
fBitmap.eraseColor(0);
draw_mode(&c, mode, twice ? 0x88 : 0xFF);
SkSafeUnref(mode);
SkPaint p;
SkRect r;
r.set(x, y, x+w, y+h);
r.inset(-SK_ScalarHalf, -SK_ScalarHalf);
p.setStyle(SkPaint::kStroke_Style);
canvas->drawRect(r, p);
p.setStyle(SkPaint::kFill_Style);
p.setShader(s);
r.inset(SK_ScalarHalf, SK_ScalarHalf);
canvas->drawRect(r, p);
canvas->drawBitmap(fBitmap, x, y, NULL);
canvas->drawText(gModes[i].fLabel, strlen(gModes[i].fLabel),
x + w/2, y - labelP.getTextSize()/2, labelP);
x += w + SkIntToScalar(10);
if ((i % W) == W - 1) {
x = x0;
y += h + SkIntToScalar(30);
}
}
x0 += SkIntToScalar(400);
}
s->unref();
}
private:
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new XfermodesGM; }
static GMRegistry reg(MyFactory);
}
<|endoftext|> |
<commit_before>/*
* caosVM_flow.cpp
* openc2e
*
* Created by Alyssa Milburn on Sun May 30 2004.
* Copyright (c) 2004 Alyssa Milburn. 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 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.
*
*/
#include "caosVM.h"
#include <iostream>
#include "openc2e.h"
#include "World.h" // enum
#include <cmath> // sqrt
#include <sstream>
/**
DOIF (command) condition (condition)
%pragma parser new DoifParser()
%status maybe
Part of a DOIF/ELIF/ELSE/ENDI block. Jumps to the next part of the block if condition is false,
otherwise continues executing the script.
*/
/**
ELIF (command) condition (condition)
%pragma parser new DoifParser()
%status maybe
Part of a DOIF/ELIF/ELSE/ENDI block. If none of the previous DOIF/ELIF conditions have been true, and condition evaluates to true, then the code in the ELIF block is executed.
If found outside a DOIF block, it is equivalent to a DOIF. If you take advantage of this behavior, fuzzie is of the opinion that you should be shot.
*/
/**
ELSE (command)
%pragma noparse
%status maybe
Part of a DOIF/ELIF/ELSE/ENDI block. If ELSE is present, it is jumped to when none of the previous DOIF/ELIF conditions are true.
*/
/**
ENDI (command)
%pragma noparse
%status maybe
The end of a DOIF/ELIF/ELSE/ENDI block.
*/
/**
REPS (command) reps (integer)
%pragma parser new parseREPS()
%status maybe
The start of a REPS...REPE loop. The body of the loop will be executed (reps) times.
*/
/**
REPE (command)
%pragma noparse
%status maybe
The end of a REPS...REPE loop.
*/
/**
LOOP (command)
%pragma parser new parseLOOP()
%status maybe
The start of a LOOP...EVER or LOOP...UNTL loop.
*/
/**
EVER (command)
%pragma noparse
%status maybe
Jumps back to the matching LOOP, no matter what.
*/
/**
UNTL (command) condition (condition)
%pragma noparse
%status maybe
Jumps back to the matching LOOP unless the condition evaluates to true.
*/
/**
GSUB (command) label (label)
%pragma parser new parseGSUB()
%pragma retc -1
%status maybe
Jumps to a subroutine defined by SUBR with label (label).
*/
/**
SUBR (command) label (label)
%pragma parser new parseSUBR()
%status maybe
Defines the start of a subroute to be called with GSUB, with label (label).
If the command is encountered during execution, it acts like a STOP.
*/
/**
RETN (command)
%pragma retc -1
%status maybe
Returns from a subroutine called with GSUB.
*/
void caosVM::c_RETN() {
if (callStack.empty())
throw creaturesException("RETN with an empty callstack");
nip = callStack.back().nip;
callStack.back().valueStack->swap(valueStack);
callStack.pop_back();
}
/**
NEXT (command)
%pragma noparse
%status maybe
The end of an ENUM...NEXT loop.
*/
/**
ENUM (command) family (integer) genus (integer) species (integer)
%status maybe
%pragma parserclass ENUMhelper
%pragma retc -1
Loops through all agents with the given classifier. 0 on any field is a
wildcard. The loop body is terminated by a NEXT.
*/
void caosVM::c_ENUM() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
for (std::list<boost::shared_ptr<Agent> >::iterator i
= world.agents.begin(); i != world.agents.end(); i++) {
boost::shared_ptr<Agent> a = (*i);
if (!a) continue;
if (species && species != a->species) continue;
if (genus && genus != a->genus) continue;
if (family && family != a->family) continue;
caosVar v; v.setAgent(a);
valueStack.push_back(v);
}
}
/**
ESEE (command) family (integer) genus (integer) species (integer)
%status maybe
%pragma parserclass ENUMhelper
%pragma retc -1
Simular to ENUM, but iterates through agents visible to OWNR. An agent can be seen if it is within the
range set by RNGE, and is visible (this includes the PERM value of walls that lie between them,
and, if the agent is a Creature, it not having the 'invisible' attribute).
*/
void caosVM::c_ESEE() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
valid_agent(owner);
float ownerx = (owner->x + owner->getWidth() / 2);
float ownery = (owner->y + owner->getHeight() / 2);
MetaRoom *ownermeta = world.map.metaRoomAt(ownerx, ownery);
Room *ownerroom = world.map.roomAt(ownerx, ownery);
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
if (!ownermeta) return;
if (!ownerroom) return;
for (std::list<boost::shared_ptr<Agent> >::iterator i
= world.agents.begin(); i != world.agents.end(); i++) {
boost::shared_ptr<Agent> a = (*i);
if (!a) continue;
// TODO: if owner is a creature, skip stuff with invisible attribute
// verify species/genus/family
if (species && species != a->species) continue;
if (genus && genus != a->genus) continue;
if (family && family != a->family) continue;
// verify we're in the same metaroom as owner, and in a room
float thisx = a->x + (a->getWidth() / 2);
float thisy = a->y + (a->getHeight() / 2);
MetaRoom *m = world.map.metaRoomAt(thisx, thisy);
if (m != ownermeta) continue;
Room *r = world.map.roomAt(thisx, thisy);
// compare squared distance with range
double deltax = thisx - ownerx; deltax *= deltax;
double deltay = thisy - ownery; deltay *= deltay;
if ((deltax + deltay) > (owner->range * owner->range)) continue;
// do the actual visibiltiy check using a line between centers
Point src(ownerx, ownery), dest(thisx, thisy);
Line dummywall; unsigned int dummydir;
world.map.collideLineWithRoomSystem(src, dest, ownerroom, src, dummywall, dummydir, owner->perm);
if (src != dest) continue;
// okay, we can see this agent!
caosVar v; v.setAgent(a);
valueStack.push_back(v);
}
}
/**
ETCH (command) family (integer) genus (integer) species (integer)
%pragma parserclass ENUMhelper
%pragma retc -1
%status maybe
Similar to ENUM, but iterates through the agents OWNR is touching.
*/
void caosVM::c_ETCH() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
valid_agent(owner);
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
for (std::list<boost::shared_ptr<Agent> >::iterator i
= world.agents.begin(); i != world.agents.end(); i++) {
boost::shared_ptr<Agent> a = (*i);
if (!a) continue;
if (species && species != a->species) continue;
if (genus && genus != a->genus) continue;
if (family && family != a->family) continue;
if (a->x < owner->x) {
if ((a->x + a->getWidth()) < owner->x) continue;
} else {
if ((owner->x + owner->getWidth()) < a->x) continue;
}
if (a->y < owner->y) {
if ((a->y + a->getHeight()) < owner->y) continue;
} else {
if ((owner->y + owner->getHeight()) < a->y) continue;
}
caosVar v; v.setAgent(a);
valueStack.push_back(v);
}
}
/**
EPAS (command) family (integer) genus (integer) species (integer)
%pragma parserclass ENUMhelper
%pragma retc -1
%status stub
Similar to ENUM, but iterates through the OWNR vehicle's passengers.
*/
void caosVM::c_EPAS() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
// TODO: should probably implement this (ESEE)
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
}
/**
ECON (command) agent (agent)
%pragma parserclass ENUMhelper
%pragma retc -1
%status stub
Loops through all the agents in the connective system containing the given agent.
*/
void caosVM::c_ECON() {
VM_VERIFY_SIZE(3)
VM_PARAM_VALIDAGENT(agent)
// TODO: should probably implement this (ESEE)
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
}
/**
CALL (command) script_no (integer) p1 (any) p2 (any)
%status maybe
Calls script_no on OWNR, then waits for it to return. The invoked script
will inherit the caller's INST setting, but any changes it makes to it will
be reversed once it returns - so eg if you call a script when in INST mode,
it calls OVER and returns, you'll still be in INST.
Script variables (VAxx) will not be preserved - you'll have to use OVxx
for any parameters.
*/
void caosVM::c_CALL() {
VM_PARAM_VALUE(p2)
VM_PARAM_VALUE(p1)
VM_PARAM_INTEGER(script_no)
valid_agent(owner);
caos_assert(script_no >= 0 && script_no < 65536);
shared_ptr<script> s = owner->findScript(script_no);
if (!s) return;
caosVM *newvm = world.getVM(owner);
newvm->trace = trace;
ensure(newvm->fireScript(s, false));
newvm->inst = inst;
newvm->_p_[0] = p1;
newvm->_p_[1] = p2;
owner->pushVM(newvm);
stop_loop = true;
}
/**
CAOS (string) inline (integer) state_trans (integer) p1 (anything) p2 (anything) commands (string) throws (integer) catches (integer) report (variable)
%status maybe
Runs commands as caos code immediately. If inline, copy _IT_ VAxx TARG OWNR, etc. If state_trans, copy FROM and
OWNR. If an error occurs, it catches it and stuffs it in the report. (XXX: non-conforming)
*/
// XXX: exception catching is very broken right now
void caosVM::v_CAOS() {
// XXX: capture output
VM_PARAM_VARIABLE(report)
VM_PARAM_INTEGER(catches)
VM_PARAM_INTEGER(throws)
VM_PARAM_STRING(commands)
VM_PARAM_VALUE(p2)
VM_PARAM_VALUE(p1)
VM_PARAM_INTEGER(state_trans)
VM_PARAM_INTEGER(inl)
caosVM *sub = world.getVM(NULL);
if (inl) {
for (int i = 0; i < 100; i++)
sub->var[i] = var[i];
sub->targ = targ;
sub->_it_ = _it_;
sub->part = part;
sub->owner = owner;
// sub->from = from;
}
if (state_trans) {
sub->owner = owner;
// sub->from = from;
}
sub->_p_[0] = p1;
sub->_p_[1] = p2;
try {
std::istringstream iss(commands);
std::ostringstream oss;
caosScript s("c3", "CAOS command"); // XXX: variant
s.parse(iss);
s.installScripts();
sub->outputstream = &oss;
sub->runEntirely(s.installer);
sub->outputstream = &std::cout;
result.setString(oss.str());
} catch (std::exception &e) {
sub->outputstream = &std::cout;
if (!throws || catches) {
report->setString(e.what());
result.setString("###");
} else {
world.freeVM(sub);
throw;
}
}
world.freeVM(sub);
}
/* vim: set noet: */
<commit_msg>make ESEE/ETCH use targ instead of owner in install scripts<commit_after>/*
* caosVM_flow.cpp
* openc2e
*
* Created by Alyssa Milburn on Sun May 30 2004.
* Copyright (c) 2004 Alyssa Milburn. 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 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.
*
*/
#include "caosVM.h"
#include <iostream>
#include "openc2e.h"
#include "World.h" // enum
#include <cmath> // sqrt
#include <sstream>
/**
DOIF (command) condition (condition)
%pragma parser new DoifParser()
%status maybe
Part of a DOIF/ELIF/ELSE/ENDI block. Jumps to the next part of the block if condition is false,
otherwise continues executing the script.
*/
/**
ELIF (command) condition (condition)
%pragma parser new DoifParser()
%status maybe
Part of a DOIF/ELIF/ELSE/ENDI block. If none of the previous DOIF/ELIF conditions have been true, and condition evaluates to true, then the code in the ELIF block is executed.
If found outside a DOIF block, it is equivalent to a DOIF. If you take advantage of this behavior, fuzzie is of the opinion that you should be shot.
*/
/**
ELSE (command)
%pragma noparse
%status maybe
Part of a DOIF/ELIF/ELSE/ENDI block. If ELSE is present, it is jumped to when none of the previous DOIF/ELIF conditions are true.
*/
/**
ENDI (command)
%pragma noparse
%status maybe
The end of a DOIF/ELIF/ELSE/ENDI block.
*/
/**
REPS (command) reps (integer)
%pragma parser new parseREPS()
%status maybe
The start of a REPS...REPE loop. The body of the loop will be executed (reps) times.
*/
/**
REPE (command)
%pragma noparse
%status maybe
The end of a REPS...REPE loop.
*/
/**
LOOP (command)
%pragma parser new parseLOOP()
%status maybe
The start of a LOOP...EVER or LOOP...UNTL loop.
*/
/**
EVER (command)
%pragma noparse
%status maybe
Jumps back to the matching LOOP, no matter what.
*/
/**
UNTL (command) condition (condition)
%pragma noparse
%status maybe
Jumps back to the matching LOOP unless the condition evaluates to true.
*/
/**
GSUB (command) label (label)
%pragma parser new parseGSUB()
%pragma retc -1
%status maybe
Jumps to a subroutine defined by SUBR with label (label).
*/
/**
SUBR (command) label (label)
%pragma parser new parseSUBR()
%status maybe
Defines the start of a subroute to be called with GSUB, with label (label).
If the command is encountered during execution, it acts like a STOP.
*/
/**
RETN (command)
%pragma retc -1
%status maybe
Returns from a subroutine called with GSUB.
*/
void caosVM::c_RETN() {
if (callStack.empty())
throw creaturesException("RETN with an empty callstack");
nip = callStack.back().nip;
callStack.back().valueStack->swap(valueStack);
callStack.pop_back();
}
/**
NEXT (command)
%pragma noparse
%status maybe
The end of an ENUM...NEXT loop.
*/
/**
ENUM (command) family (integer) genus (integer) species (integer)
%status maybe
%pragma parserclass ENUMhelper
%pragma retc -1
Loops through all agents with the given classifier. 0 on any field is a
wildcard. The loop body is terminated by a NEXT.
*/
void caosVM::c_ENUM() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
for (std::list<boost::shared_ptr<Agent> >::iterator i
= world.agents.begin(); i != world.agents.end(); i++) {
boost::shared_ptr<Agent> a = (*i);
if (!a) continue;
if (species && species != a->species) continue;
if (genus && genus != a->genus) continue;
if (family && family != a->family) continue;
caosVar v; v.setAgent(a);
valueStack.push_back(v);
}
}
/**
ESEE (command) family (integer) genus (integer) species (integer)
%status maybe
%pragma parserclass ENUMhelper
%pragma retc -1
Simular to ENUM, but iterates through agents visible to OWNR, or visible to TARG in an install script.
An agent can be seen if it is within the range set by RNGE, and is visible (this includes the PERM value
of walls that lie between them, and, if the agent is a Creature, it not having the 'invisible' attribute).
*/
void caosVM::c_ESEE() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
Agent *seeing;
if (owner) seeing = owner; else seeing = targ;
valid_agent(seeing);
float ownerx = (seeing->x + seeing->getWidth() / 2);
float ownery = (seeing->y + seeing->getHeight() / 2);
MetaRoom *ownermeta = world.map.metaRoomAt(ownerx, ownery);
Room *ownerroom = world.map.roomAt(ownerx, ownery);
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
if (!ownermeta) return;
if (!ownerroom) return;
for (std::list<boost::shared_ptr<Agent> >::iterator i
= world.agents.begin(); i != world.agents.end(); i++) {
boost::shared_ptr<Agent> a = (*i);
if (!a) continue;
// TODO: if owner is a creature, skip stuff with invisible attribute
// verify species/genus/family
if (species && species != a->species) continue;
if (genus && genus != a->genus) continue;
if (family && family != a->family) continue;
// verify we're in the same metaroom as owner, and in a room
float thisx = a->x + (a->getWidth() / 2);
float thisy = a->y + (a->getHeight() / 2);
MetaRoom *m = world.map.metaRoomAt(thisx, thisy);
if (m != ownermeta) continue;
Room *r = world.map.roomAt(thisx, thisy);
// compare squared distance with range
double deltax = thisx - ownerx; deltax *= deltax;
double deltay = thisy - ownery; deltay *= deltay;
if ((deltax + deltay) > (seeing->range * seeing->range)) continue;
// do the actual visibiltiy check using a line between centers
Point src(ownerx, ownery), dest(thisx, thisy);
Line dummywall; unsigned int dummydir;
world.map.collideLineWithRoomSystem(src, dest, ownerroom, src, dummywall, dummydir, seeing->perm);
if (src != dest) continue;
// okay, we can see this agent!
caosVar v; v.setAgent(a);
valueStack.push_back(v);
}
}
/**
ETCH (command) family (integer) genus (integer) species (integer)
%pragma parserclass ENUMhelper
%pragma retc -1
%status maybe
Similar to ENUM, but iterates through the agents OWNR is touching, or TARG is touching in an install script.
*/
void caosVM::c_ETCH() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
Agent *touching;
if (owner) touching = owner; else touching = targ;
valid_agent(touching);
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
for (std::list<boost::shared_ptr<Agent> >::iterator i
= world.agents.begin(); i != world.agents.end(); i++) {
boost::shared_ptr<Agent> a = (*i);
if (!a) continue;
if (species && species != a->species) continue;
if (genus && genus != a->genus) continue;
if (family && family != a->family) continue;
if (a->x < touching->x) {
if ((a->x + a->getWidth()) < touching->x) continue;
} else {
if ((touching->x + touching->getWidth()) < a->x) continue;
}
if (a->y < touching->y) {
if ((a->y + a->getHeight()) < touching->y) continue;
} else {
if ((touching->y + touching->getHeight()) < a->y) continue;
}
caosVar v; v.setAgent(a);
valueStack.push_back(v);
}
}
/**
EPAS (command) family (integer) genus (integer) species (integer)
%pragma parserclass ENUMhelper
%pragma retc -1
%status stub
Similar to ENUM, but iterates through the OWNR vehicle's passengers.
*/
void caosVM::c_EPAS() {
VM_VERIFY_SIZE(3)
VM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);
VM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);
VM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);
// TODO: should probably implement this (ESEE)
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
}
/**
ECON (command) agent (agent)
%pragma parserclass ENUMhelper
%pragma retc -1
%status stub
Loops through all the agents in the connective system containing the given agent.
*/
void caosVM::c_ECON() {
VM_VERIFY_SIZE(3)
VM_PARAM_VALIDAGENT(agent)
// TODO: should probably implement this (ESEE)
caosVar nullv; nullv.reset();
valueStack.push_back(nullv);
}
/**
CALL (command) script_no (integer) p1 (any) p2 (any)
%status maybe
Calls script_no on OWNR, then waits for it to return. The invoked script
will inherit the caller's INST setting, but any changes it makes to it will
be reversed once it returns - so eg if you call a script when in INST mode,
it calls OVER and returns, you'll still be in INST.
Script variables (VAxx) will not be preserved - you'll have to use OVxx
for any parameters.
*/
void caosVM::c_CALL() {
VM_PARAM_VALUE(p2)
VM_PARAM_VALUE(p1)
VM_PARAM_INTEGER(script_no)
valid_agent(owner);
caos_assert(script_no >= 0 && script_no < 65536);
shared_ptr<script> s = owner->findScript(script_no);
if (!s) return;
caosVM *newvm = world.getVM(owner);
newvm->trace = trace;
ensure(newvm->fireScript(s, false));
newvm->inst = inst;
newvm->_p_[0] = p1;
newvm->_p_[1] = p2;
owner->pushVM(newvm);
stop_loop = true;
}
/**
CAOS (string) inline (integer) state_trans (integer) p1 (anything) p2 (anything) commands (string) throws (integer) catches (integer) report (variable)
%status maybe
Runs commands as caos code immediately. If inline, copy _IT_ VAxx TARG OWNR, etc. If state_trans, copy FROM and
OWNR. If an error occurs, it catches it and stuffs it in the report. (XXX: non-conforming)
*/
// XXX: exception catching is very broken right now
void caosVM::v_CAOS() {
// XXX: capture output
VM_PARAM_VARIABLE(report)
VM_PARAM_INTEGER(catches)
VM_PARAM_INTEGER(throws)
VM_PARAM_STRING(commands)
VM_PARAM_VALUE(p2)
VM_PARAM_VALUE(p1)
VM_PARAM_INTEGER(state_trans)
VM_PARAM_INTEGER(inl)
caosVM *sub = world.getVM(NULL);
if (inl) {
for (int i = 0; i < 100; i++)
sub->var[i] = var[i];
sub->targ = targ;
sub->_it_ = _it_;
sub->part = part;
sub->owner = owner;
// sub->from = from;
}
if (state_trans) {
sub->owner = owner;
// sub->from = from;
}
sub->_p_[0] = p1;
sub->_p_[1] = p2;
try {
std::istringstream iss(commands);
std::ostringstream oss;
caosScript s("c3", "CAOS command"); // XXX: variant
s.parse(iss);
s.installScripts();
sub->outputstream = &oss;
sub->runEntirely(s.installer);
sub->outputstream = &std::cout;
result.setString(oss.str());
} catch (std::exception &e) {
sub->outputstream = &std::cout;
if (!throws || catches) {
report->setString(e.what());
result.setString("###");
} else {
world.freeVM(sub);
throw;
}
}
world.freeVM(sub);
}
/* vim: set noet: */
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file GLTexture3D.cpp
\author Jens Krueger
SCI Institute
University of Utah
\date August 2008
*/
#include "GLTexture3D.h"
#include "GLError.h"
#include "Controller/Controller.h"
using namespace tuvok;
GLTexture3D::GLTexture3D(uint32_t iSizeX, uint32_t iSizeY, uint32_t iSizeZ,
GLint internalformat, GLenum format, GLenum type,
const GLvoid *pixels,
GLint iMagFilter, GLint iMinFilter, GLint wrapX,
GLint wrapY, GLint wrapZ) :
GLTexture(internalformat, format, type, iMagFilter, iMinFilter),
m_iSizeX(GLuint(iSizeX)),
m_iSizeY(GLuint(iSizeY)),
m_iSizeZ(GLuint(iSizeZ))
{
GLint prevTex;
GL(glGetIntegerv(GL_TEXTURE_BINDING_3D, &prevTex));
GL(glGenTextures(1, &m_iGLID));
GL(glBindTexture(GL_TEXTURE_3D, m_iGLID));
GL(glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, wrapX));
GL(glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, wrapY));
GL(glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, wrapZ));
GL(glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, iMagFilter));
GL(glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, iMinFilter));
GL(glPixelStorei(GL_PACK_ALIGNMENT, 1));
GL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
glTexImage3D(GL_TEXTURE_3D, 0, m_internalformat,
m_iSizeX, m_iSizeY, m_iSizeZ,
0, m_format, m_type, (GLvoid*)pixels);
GLenum err = glGetError();
if(err == GL_OUT_OF_MEMORY) {
this->Delete();
throw OUT_OF_MEMORY("allocating 3d texture");
} else if(err != GL_NO_ERROR) {
WARNING("Unknown error (%x) occurred while setting 3D texture.",
static_cast<unsigned int>(err));
}
GL(glBindTexture(GL_TEXTURE_3D, prevTex));
}
void GLTexture3D::SetData(const UINTVECTOR3& offset, const UINTVECTOR3& size,
const void *pixels, bool bRestoreBinding) {
GL(glPixelStorei(GL_PACK_ALIGNMENT, 1));
GL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
GLint prevTex=0;
if (bRestoreBinding) GL(glGetIntegerv(GL_TEXTURE_BINDING_3D, &prevTex));
GL(glBindTexture(GL_TEXTURE_3D, m_iGLID));
GL(glTexSubImage3D(GL_TEXTURE_3D, 0,
offset.x, offset.y, offset.z,
size.x, size.y, size.z,
m_format, m_type, (GLvoid*)pixels));
if (bRestoreBinding && GLuint(prevTex) != m_iGLID) GL(glBindTexture(GL_TEXTURE_3D, prevTex));
}
void GLTexture3D::SetData(const void *pixels, bool bRestoreBinding) {
GL(glPixelStorei(GL_PACK_ALIGNMENT, 1));
GL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
GLint prevTex=0;
if (bRestoreBinding) GL(glGetIntegerv(GL_TEXTURE_BINDING_3D, &prevTex));
GL(glBindTexture(GL_TEXTURE_3D, m_iGLID));
GL(glTexImage3D(GL_TEXTURE_3D, 0, m_internalformat,
m_iSizeX, m_iSizeY, m_iSizeZ,
0, m_format, m_type, (GLvoid*)pixels));
GLenum err = glGetError();
if(err == GL_OUT_OF_MEMORY) {
this->Delete();
throw OUT_OF_MEMORY("allocating 3d texture");
} else if(err != GL_NO_ERROR) {
WARNING("Unknown error (%x) occurred while setting 3D texture.",
static_cast<unsigned int>(err));
}
if (bRestoreBinding && GLuint(prevTex) != m_iGLID) GL(glBindTexture(GL_TEXTURE_3D, prevTex));
}
void GLTexture3D::GetData(std::shared_ptr<void> data)
{
GL(glPixelStorei(GL_PACK_ALIGNMENT ,1));
GL(glPixelStorei(GL_UNPACK_ALIGNMENT ,1));
GL(glBindTexture(GL_TEXTURE_3D, m_iGLID));
GL(glGetTexImage(GL_TEXTURE_3D, 0, m_format, m_type, data.get()));
}
<commit_msg>Properly check for GL out of memory errors.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file GLTexture3D.cpp
\author Jens Krueger
SCI Institute
University of Utah
\date August 2008
*/
#include "GLTexture3D.h"
#include "GLError.h"
#include "Controller/Controller.h"
using namespace tuvok;
GLTexture3D::GLTexture3D(uint32_t iSizeX, uint32_t iSizeY, uint32_t iSizeZ,
GLint internalformat, GLenum format, GLenum type,
const GLvoid *pixels,
GLint iMagFilter, GLint iMinFilter, GLint wrapX,
GLint wrapY, GLint wrapZ) :
GLTexture(internalformat, format, type, iMagFilter, iMinFilter),
m_iSizeX(GLuint(iSizeX)),
m_iSizeY(GLuint(iSizeY)),
m_iSizeZ(GLuint(iSizeZ))
{
GLint prevTex;
GL(glGetIntegerv(GL_TEXTURE_BINDING_3D, &prevTex));
GL(glGenTextures(1, &m_iGLID));
GL(glBindTexture(GL_TEXTURE_3D, m_iGLID));
GL(glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, wrapX));
GL(glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, wrapY));
GL(glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, wrapZ));
GL(glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, iMagFilter));
GL(glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, iMinFilter));
GL(glPixelStorei(GL_PACK_ALIGNMENT, 1));
GL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
glTexImage3D(GL_TEXTURE_3D, 0, m_internalformat,
m_iSizeX, m_iSizeY, m_iSizeZ,
0, m_format, m_type, (GLvoid*)pixels);
GLenum err = glGetError();
if(err == GL_OUT_OF_MEMORY) {
this->Delete();
throw OUT_OF_MEMORY("allocating 3d texture");
} else if(err != GL_NO_ERROR) {
WARNING("Unknown error (%x) occurred while setting 3D texture.",
static_cast<unsigned int>(err));
}
GL(glBindTexture(GL_TEXTURE_3D, prevTex));
}
void GLTexture3D::SetData(const UINTVECTOR3& offset, const UINTVECTOR3& size,
const void *pixels, bool bRestoreBinding) {
GL(glPixelStorei(GL_PACK_ALIGNMENT, 1));
GL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
GLint prevTex=0;
if (bRestoreBinding) GL(glGetIntegerv(GL_TEXTURE_BINDING_3D, &prevTex));
GL(glBindTexture(GL_TEXTURE_3D, m_iGLID));
GL(glTexSubImage3D(GL_TEXTURE_3D, 0,
offset.x, offset.y, offset.z,
size.x, size.y, size.z,
m_format, m_type, (GLvoid*)pixels));
if (bRestoreBinding && GLuint(prevTex) != m_iGLID) GL(glBindTexture(GL_TEXTURE_3D, prevTex));
}
void GLTexture3D::SetData(const void *pixels, bool bRestoreBinding) {
GL(glPixelStorei(GL_PACK_ALIGNMENT, 1));
GL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
GLint prevTex=0;
if (bRestoreBinding) GL(glGetIntegerv(GL_TEXTURE_BINDING_3D, &prevTex));
GL(glBindTexture(GL_TEXTURE_3D, m_iGLID));
glTexImage3D(GL_TEXTURE_3D, 0, m_internalformat,
m_iSizeX, m_iSizeY, m_iSizeZ,
0, m_format, m_type, (GLvoid*)pixels);
GLenum err = glGetError();
if(err == GL_OUT_OF_MEMORY) {
this->Delete();
throw OUT_OF_MEMORY("allocating 3d texture");
} else if(err != GL_NO_ERROR) {
WARNING("Unknown error (%x) occurred while setting 3D texture.",
static_cast<unsigned int>(err));
}
if (bRestoreBinding && GLuint(prevTex) != m_iGLID) GL(glBindTexture(GL_TEXTURE_3D, prevTex));
}
void GLTexture3D::GetData(std::shared_ptr<void> data)
{
GL(glPixelStorei(GL_PACK_ALIGNMENT ,1));
GL(glPixelStorei(GL_UNPACK_ALIGNMENT ,1));
GL(glBindTexture(GL_TEXTURE_3D, m_iGLID));
GL(glGetTexImage(GL_TEXTURE_3D, 0, m_format, m_type, data.get()));
}
<|endoftext|> |
<commit_before>#pragma once
#include <string>
#include <variant>
#include <functional>
#include <iostream>
#include <fstream>
#include "acmacs-base/filesystem.hh"
// ----------------------------------------------------------------------
namespace acmacs::file
{
enum class force_compression { no, yes };
enum class backup_file { no, yes };
enum class backup_move { no, yes };
// ----------------------------------------------------------------------
inline bool exists(std::string aFilename) { return fs::exists(aFilename); }
std::string decompress_if_necessary(std::string_view aSource);
// ----------------------------------------------------------------------
class file_error : public std::runtime_error { public: using std::runtime_error::runtime_error; };
class not_opened : public file_error { public: not_opened(std::string aMsg) : file_error("cannot open " + aMsg) {} };
class cannot_read : public file_error { public: cannot_read(std::string aMsg) : file_error("cannot read " + aMsg) {} };
class not_found : public file_error { public: not_found(std::string aFilename) : file_error("not found: " + aFilename) {} };
class read_access
{
public:
read_access() = default;
read_access(std::string_view aFilename);
~read_access();
read_access(const read_access&) = delete;
read_access(read_access&&);
read_access& operator=(const read_access&) = delete;
read_access& operator=(read_access&&);
operator std::string() const { return decompress_if_necessary({mapped, len}); }
size_t size() const { return len; }
const char* data() const { return mapped; }
bool valid() const { return mapped != nullptr; }
private:
int fd = -1;
size_t len = 0;
char* mapped = nullptr;
}; // class read_access
template <typename S> inline read_access read(S&& aFilename) { return {aFilename}; }
std::string read_from_file_descriptor(int fd, size_t chunk_size = 1024);
inline std::string read_stdin() { return read_from_file_descriptor(0); }
void write(std::string aFilename, std::string_view aData, force_compression aForceCompression = force_compression::no, backup_file aBackupFile = backup_file::yes);
inline void write(std::string_view aFilename, std::string_view aData, force_compression aForceCompression = force_compression::no, backup_file aBackupFile = backup_file::yes) { write(std::string(aFilename), aData, aForceCompression, aBackupFile); }
void backup(const fs::path& to_backup, const fs::path& backup_dir, backup_move bm = backup_move::no);
inline void backup(const fs::path& to_backup, backup_move bm = backup_move::no) { backup(to_backup, to_backup.parent_path() / ".backup", bm); }
// ----------------------------------------------------------------------
class temp
{
public:
temp(std::string prefix, std::string suffix);
temp(std::string suffix);
~temp();
inline temp& operator = (temp&& aFrom) noexcept { name = std::move(aFrom.name); fd = aFrom.fd; aFrom.name.clear(); return *this; }
inline operator std::string() const { return name; }
inline operator int() const { return fd; }
private:
std::string name;
int fd;
std::string make_template(std::string prefix);
}; // class temp
class ifstream
{
public:
ifstream(std::string filename) : backend_(std::cin)
{
if (filename != "-")
backend_ = std::ifstream(filename);
}
ifstream(std::string_view filename) : ifstream(std::string(filename)) {}
std::istream& stream() { return std::visit([](auto&& stream) -> std::istream& { return stream; }, backend_); }
const std::istream& stream() const { return std::visit([](auto&& stream) -> const std::istream& { return stream; }, backend_); }
std::istream& operator*() { return stream(); }
std::istream* operator->() { return &stream(); }
operator std::istream&() { return stream(); }
std::string read() { return {std::istreambuf_iterator<char>(stream()), {}}; }
explicit operator bool() const { return bool(stream()); }
private:
std::variant<std::reference_wrapper<std::istream>,std::ifstream> backend_;
};
class ofstream
{
public:
ofstream(std::string filename) : backend_(std::cout)
{
if (filename == "=")
backend_ = std::cerr;
else if (filename != "-")
backend_ = std::ofstream(filename);
}
ofstream(std::string_view filename) : ofstream(std::string(filename)) {}
std::ostream& stream() { return std::visit([](auto&& stream) -> std::ostream& { return stream; }, backend_); }
const std::ostream& stream() const { return std::visit([](auto&& stream) -> const std::ostream& { return stream; }, backend_); }
std::ostream& operator*() { return stream(); }
std::ostream* operator->() { return &stream(); }
operator std::ostream&() { return stream(); }
explicit operator bool() const { return bool(stream()); }
private:
std::variant<std::reference_wrapper<std::ostream>,std::ofstream> backend_;
};
} // namespace acmacs::file
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>minor fix<commit_after>#pragma once
#include <string>
#include <variant>
#include <functional>
#include <iostream>
#include <fstream>
#include "acmacs-base/filesystem.hh"
// ----------------------------------------------------------------------
namespace acmacs::file
{
enum class force_compression { no, yes };
enum class backup_file { no, yes };
enum class backup_move { no, yes };
// ----------------------------------------------------------------------
inline bool exists(std::string aFilename) { return fs::exists(aFilename); }
std::string decompress_if_necessary(std::string_view aSource);
// ----------------------------------------------------------------------
class file_error : public std::runtime_error { public: using std::runtime_error::runtime_error; };
class not_opened : public file_error { public: not_opened(std::string aMsg) : file_error("cannot open " + aMsg) {} };
class cannot_read : public file_error { public: cannot_read(std::string aMsg) : file_error("cannot read " + aMsg) {} };
class not_found : public file_error { public: not_found(std::string aFilename) : file_error("not found: " + aFilename) {} };
class read_access
{
public:
read_access() = default;
read_access(std::string_view aFilename);
~read_access();
read_access(const read_access&) = delete;
read_access(read_access&&);
read_access& operator=(const read_access&) = delete;
read_access& operator=(read_access&&);
operator std::string() const { return decompress_if_necessary({mapped, len}); }
size_t size() const { return len; }
const char* data() const { return mapped; }
bool valid() const { return mapped != nullptr; }
private:
int fd = -1;
size_t len = 0;
char* mapped = nullptr;
}; // class read_access
template <typename S> inline read_access read(S&& aFilename) { return {std::forward<S>(aFilename)}; }
std::string read_from_file_descriptor(int fd, size_t chunk_size = 1024);
inline std::string read_stdin() { return read_from_file_descriptor(0); }
void write(std::string aFilename, std::string_view aData, force_compression aForceCompression = force_compression::no, backup_file aBackupFile = backup_file::yes);
inline void write(std::string_view aFilename, std::string_view aData, force_compression aForceCompression = force_compression::no, backup_file aBackupFile = backup_file::yes) { write(std::string(aFilename), aData, aForceCompression, aBackupFile); }
void backup(const fs::path& to_backup, const fs::path& backup_dir, backup_move bm = backup_move::no);
inline void backup(const fs::path& to_backup, backup_move bm = backup_move::no) { backup(to_backup, to_backup.parent_path() / ".backup", bm); }
// ----------------------------------------------------------------------
class temp
{
public:
temp(std::string prefix, std::string suffix);
temp(std::string suffix);
~temp();
inline temp& operator = (temp&& aFrom) noexcept { name = std::move(aFrom.name); fd = aFrom.fd; aFrom.name.clear(); return *this; }
inline operator std::string() const { return name; }
inline operator int() const { return fd; }
private:
std::string name;
int fd;
std::string make_template(std::string prefix);
}; // class temp
class ifstream
{
public:
ifstream(std::string filename) : backend_(std::cin)
{
if (filename != "-")
backend_ = std::ifstream(filename);
}
ifstream(std::string_view filename) : ifstream(std::string(filename)) {}
std::istream& stream() { return std::visit([](auto&& stream) -> std::istream& { return stream; }, backend_); }
const std::istream& stream() const { return std::visit([](auto&& stream) -> const std::istream& { return stream; }, backend_); }
std::istream& operator*() { return stream(); }
std::istream* operator->() { return &stream(); }
operator std::istream&() { return stream(); }
std::string read() { return {std::istreambuf_iterator<char>(stream()), {}}; }
explicit operator bool() const { return bool(stream()); }
private:
std::variant<std::reference_wrapper<std::istream>,std::ifstream> backend_;
};
class ofstream
{
public:
ofstream(std::string filename) : backend_(std::cout)
{
if (filename == "=")
backend_ = std::cerr;
else if (filename != "-")
backend_ = std::ofstream(filename);
}
ofstream(std::string_view filename) : ofstream(std::string(filename)) {}
std::ostream& stream() { return std::visit([](auto&& stream) -> std::ostream& { return stream; }, backend_); }
const std::ostream& stream() const { return std::visit([](auto&& stream) -> const std::ostream& { return stream; }, backend_); }
std::ostream& operator*() { return stream(); }
std::ostream* operator->() { return &stream(); }
operator std::ostream&() { return stream(); }
explicit operator bool() const { return bool(stream()); }
private:
std::variant<std::reference_wrapper<std::ostream>,std::ofstream> backend_;
};
} // namespace acmacs::file
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include <X86/LocalApic.hh>
#include <Debug.hh>
#include <Memory.hh>
#include <X86/Processor.hh>
#include <X86/CpuRegisters.hh>
#include <X86/IoPort.hh>
#include <cstdio>
LocalApic::LocalApic(uintptr_t physicalAddress)
: physicalAddressM(physicalAddress)
{
init();
idM = (read32(0x20) >> 24) & 0xf;
printf("Local APIC at %p, Id: %u\n", (void*)physicalAddressM, idM);
}
LocalApic::LocalApic(uintptr_t physicalAddress, uint32_t id)
: physicalAddressM(physicalAddress),
idM(id)
{
printf("Local APIC at %p, Id: %u\n", (void*)physicalAddressM, idM);
}
uint32_t
LocalApic::read32(uint32_t offset)
{
return *(volatile uint32_t *)(apicAddressM + offset);
}
uint64_t
LocalApic::read64(uint32_t offset)
{
uint32_t a, b;
a = *(volatile uint32_t *)(apicAddressM + offset);
b = *(volatile uint32_t *)(apicAddressM + offset + 4);
return (uint64_t )a | ((uint64_t )b << 32);
}
void
LocalApic::write32(uint32_t offset, uint32_t value)
{
*(volatile uint32_t *)(apicAddressM + offset) = value;
}
void
LocalApic::write64(uint32_t offset, uint64_t value)
{
*(volatile uint32_t *)(apicAddressM + offset) = value;
*(volatile uint32_t *)(apicAddressM + offset + 4) = value >> 32;
}
int
LocalApic::probe()
{
cpuid_t id;
// probe
cpuid(1, &id);
if ((id.ecx & (1 << 21)) == 0)
{
return 0;
}
return 1;
}
void
LocalApic::init()
{
cpuid_t id;
cpuid(0x1, &id);
if (id.eax & CPUID::APIC)
{
printf("APIC: found controller\n");
}
else
{
printf("APIC: not found\n");
enabledM = false;
return;
}
uint64_t msr = x86_rdmsr(IA32_APIC_BASE);
apicAddressM = msr & IA32_APIC_BASE_ADDRESS_MASK;
if (msr & IA32_APIC_BASE_BSP)
{
flagsM |= ApicIsBsp;
}
if (msr & IA32_APIC_BASE_EN)
{
flagsM |= ApicIsEnabled;
}
printf("APIC: base address: 0x%lx\n", apicAddressM);
apicAddressM = Memory::mapRegion(apicAddressM, 4096u, Memory::MapUncacheable);
KASSERT(apicAddressM != 0);
printf("APIC: CPU type: %s\n",
(flagsM & ApicIsBsp) ? "BSP" : "APU");
printf("APIC: state: %s\n",
(flagsM & ApicIsEnabled) ? "enabled" : "disabled");
printf("APIC: LAPIC Id: %u\n", getLocalApicId());
uint64_t version = read32(LocalApicVersion);
printf("APIC: Version: 0x%hhx, LVTs: %u\n",
(uint8_t)(version & 0xff),
(uint32_t)((version >> 16) & 0x7f) + 1);
// virtual wire mode?
// outb(0x22, 0x70);
// outb(0x23, 0x1);
auto tpr = read32(0x80);
printf("TPR: 0x%x\n", tpr);
auto lint0 = read32(LvtLint0);
printf("LINT0: 0x%x\n", lint0);
printLocalVectorTable(lint0);
auto lint1 = read32(LvtLint1);
printf("LINT1: 0x%x\n", lint1);
printLocalVectorTable(lint1);
auto perfmon = read32(LvtPerfMon);
printf("PMON: 0x%x\n", perfmon);
printLocalVectorTable(perfmon);
// enable perfmon interrupt as nmi
perfmon = createLocalVectorTable(Lvt::NotMasked, Lvt::DeliveryModeNmi, 0);
write32(LvtPerfMon, perfmon);
perfmon = read32(LvtPerfMon);
printf("PMON: 0x%x\n", perfmon);
printLocalVectorTable(perfmon);
uint32_t siv = read32(SpuriousInterruptVector);
printf("APIC: Spurious Vector: %u\n", siv & SpuriousVectorMask);
printf("APIC: Spurious Vector Register: 0x%x\n", siv);
siv = 255 | ApicSoftwareEnable | ApicFocusDisabled;
write32(SpuriousInterruptVector, siv);
siv = read32(SpuriousInterruptVector);
printf("APIC: Spurious Vector Register: 0x%x\n", siv);
enabledM = true;
// EOI
write32(Eoi, 0x00);
}
#if 0
void
LocalApic::setLocalInt(int pin)
{
// write32(LvtLint0, createLocalVectorTable(DeliveryModeExtInt, 0));
// XXX this should come from acpi
write32(LvtLint1, createLocalVectorTable(Lvt::DeliveryModeNmi, 0));
}
#endif
void
LocalApic::endOfInterrupt()
{
// non specific now
if (enabledM)
{
write32(Eoi, 0x00);
}
}
int
LocalApic::initOtherProcessors(uintptr_t vector)
{
assert(vector < 0x100000);
return 0;
}
void
LocalApic::printInformation()
{
}
uint32_t
LocalApic::getLocalApicId()
{
uint32_t apicId = read32(0x20);
// XXX
return (apicId >> 24) & 0xf;
}
uint32_t
LocalApic::createLocalVectorTable(Lvt::Mask mask,
Lvt::TriggerMode triggerMode,
Lvt::PinPolarity polarity,
Lvt::DeliveryMode deliveryMode,
uint8_t vector)
{
uint32_t lvt = 0;
lvt |= (mask & 0x1u) << 16;
lvt |= (triggerMode & 0x1u) << 14;
lvt |= (polarity & 0x1u) << 13;
lvt |= (deliveryMode & 0x7u) << 8;
lvt |= vector;
return lvt;
}
uint32_t
LocalApic::createLocalVectorTable(Lvt::Mask mask,
Lvt::DeliveryMode deliveryMode,
uint8_t vector)
{
uint32_t lvt = 0;
lvt |= (mask & 0x1u) << 16;
lvt |= (deliveryMode & 0x7u) << 8;
lvt |= vector;
return lvt;
}
// ISA-like
uint32_t
LocalApic::createLocalVectorTable(Lvt::DeliveryMode deliveryMode,
uint8_t vector)
{
return createLocalVectorTable(Lvt::NotMasked, Lvt::Edge, Lvt::ActiveHigh,
deliveryMode, vector);
}
void
LocalApic::printLocalVectorTable(uint32_t lvt)
{
uint8_t mask = (lvt >> 16) & 0x1u;
uint8_t triggerMode = (lvt >> 15) & 0x1u;
uint8_t polarity = (lvt >> 13) & 0x1u;
uint8_t deliveryMode = (lvt >> 8) & 0x7u;
uint8_t vector = lvt & 0xff;
printf("LVT: Vector: %u, Deliv: %u, Pol: %u, TMode: %u, Masked: %u\n",
vector, deliveryMode, polarity, triggerMode, mask);
}
<commit_msg>Debug and try to force init<commit_after>#include <X86/LocalApic.hh>
#include <Debug.hh>
#include <Memory.hh>
#include <X86/Processor.hh>
#include <X86/CpuRegisters.hh>
#include <X86/IoPort.hh>
#include <cstdio>
LocalApic::LocalApic(uintptr_t physicalAddress)
: physicalAddressM(physicalAddress)
{
init();
idM = (read32(0x20) >> 24) & 0xf;
printf("Local APIC at %p, Id: %u\n", (void*)physicalAddressM, idM);
}
LocalApic::LocalApic(uintptr_t physicalAddress, uint32_t id)
: physicalAddressM(physicalAddress),
idM(id)
{
printf("Local APIC at %p, Id: %u\n", (void*)physicalAddressM, idM);
}
uint32_t
LocalApic::read32(uint32_t offset)
{
return *(volatile uint32_t *)(apicAddressM + offset);
}
uint64_t
LocalApic::read64(uint32_t offset)
{
uint32_t a, b;
a = *(volatile uint32_t *)(apicAddressM + offset);
b = *(volatile uint32_t *)(apicAddressM + offset + 4);
return (uint64_t )a | ((uint64_t )b << 32);
}
void
LocalApic::write32(uint32_t offset, uint32_t value)
{
*(volatile uint32_t *)(apicAddressM + offset) = value;
}
void
LocalApic::write64(uint32_t offset, uint64_t value)
{
*(volatile uint32_t *)(apicAddressM + offset) = value;
*(volatile uint32_t *)(apicAddressM + offset + 4) = value >> 32;
}
int
LocalApic::probe()
{
cpuid_t id;
// probe
cpuid(1, &id);
if ((id.ecx & (1 << 21)) == 0)
{
return 0;
}
return 1;
}
void
LocalApic::init()
{
cpuid_t id;
cpuid(0x1, &id);
if (id.eax & CPUID::APIC)
{
printf("APIC: found controller\n");
}
else
{
printf("APIC: not found\n");
enabledM = false;
return;
}
uint64_t msr = x86_rdmsr(IA32_APIC_BASE);
apicAddressM = msr & IA32_APIC_BASE_ADDRESS_MASK;
if (msr & IA32_APIC_BASE_BSP)
{
flagsM |= ApicIsBsp;
}
if (msr & IA32_APIC_BASE_EN)
{
flagsM |= ApicIsEnabled;
}
else
{
Debug::panic("APIC is disabled\n");
}
printf("APIC: base address: 0x%lx\n", apicAddressM);
apicAddressM = Memory::mapRegion(apicAddressM, 4096u, Memory::MapUncacheable);
KASSERT(apicAddressM != 0);
printf("APIC: CPU type: %s\n",
(flagsM & ApicIsBsp) ? "BSP" : "APU");
printf("APIC: state: %s\n",
(flagsM & ApicIsEnabled) ? "enabled" : "disabled");
printf("APIC: LAPIC Id: %u\n", getLocalApicId());
uint64_t version = read32(LocalApicVersion);
printf("APIC: Version: 0x%hhx, LVTs: %u\n",
(uint8_t)(version & 0xff),
(uint32_t)((version >> 16) & 0x7f) + 1);
// virtual wire mode?
// outb(0x22, 0x70);
// outb(0x23, 0x1);
auto tpr = read32(0x80);
printf("TPR: 0x%x\n", tpr);
write32(0x80, 0);
auto lint0 = read32(LvtLint0);
printf("LINT0: 0x%x\n", lint0);
printLocalVectorTable(lint0);
auto lint1 = read32(LvtLint1);
printf("LINT1: 0x%x\n", lint1);
printLocalVectorTable(lint1);
auto perfmon = read32(LvtPerfMon);
printf("PMON: 0x%x\n", perfmon);
printLocalVectorTable(perfmon);
// enable perfmon interrupt as nmi
perfmon = createLocalVectorTable(Lvt::NotMasked, Lvt::DeliveryModeNmi, 0);
write32(LvtPerfMon, perfmon);
perfmon = read32(LvtPerfMon);
printf("PMON: 0x%x\n", perfmon);
printLocalVectorTable(perfmon);
uint32_t siv = read32(SpuriousInterruptVector);
printf("APIC: Spurious Vector: %u\n", siv & SpuriousVectorMask);
printf("APIC: Spurious Vector Register: 0x%x\n", siv);
siv = 255 | ApicSoftwareEnable | ApicFocusDisabled;
write32(SpuriousInterruptVector, siv);
siv = read32(SpuriousInterruptVector);
printf("APIC: Spurious Vector Register: 0x%x\n", siv);
enabledM = true;
// EOI
write32(Eoi, 0x00);
}
#if 0
void
LocalApic::setLocalInt(int pin)
{
// write32(LvtLint0, createLocalVectorTable(DeliveryModeExtInt, 0));
// XXX this should come from acpi
write32(LvtLint1, createLocalVectorTable(Lvt::DeliveryModeNmi, 0));
}
#endif
void
LocalApic::endOfInterrupt()
{
// non specific now
if (enabledM)
{
write32(Eoi, 0x00);
}
}
int
LocalApic::initOtherProcessors(uintptr_t vector)
{
assert(vector < 0x100000);
return 0;
}
void
LocalApic::printInformation()
{
}
uint32_t
LocalApic::getLocalApicId()
{
uint32_t apicId = read32(0x20);
// XXX
return (apicId >> 24) & 0xf;
}
uint32_t
LocalApic::createLocalVectorTable(Lvt::Mask mask,
Lvt::TriggerMode triggerMode,
Lvt::PinPolarity polarity,
Lvt::DeliveryMode deliveryMode,
uint8_t vector)
{
uint32_t lvt = 0;
lvt |= (mask & 0x1u) << 16;
lvt |= (triggerMode & 0x1u) << 14;
lvt |= (polarity & 0x1u) << 13;
lvt |= (deliveryMode & 0x7u) << 8;
lvt |= vector;
return lvt;
}
uint32_t
LocalApic::createLocalVectorTable(Lvt::Mask mask,
Lvt::DeliveryMode deliveryMode,
uint8_t vector)
{
uint32_t lvt = 0;
lvt |= (mask & 0x1u) << 16;
lvt |= (deliveryMode & 0x7u) << 8;
lvt |= vector;
return lvt;
}
// ISA-like
uint32_t
LocalApic::createLocalVectorTable(Lvt::DeliveryMode deliveryMode,
uint8_t vector)
{
return createLocalVectorTable(Lvt::NotMasked, Lvt::Edge, Lvt::ActiveHigh,
deliveryMode, vector);
}
void
LocalApic::printLocalVectorTable(uint32_t lvt)
{
uint8_t mask = (lvt >> 16) & 0x1u;
uint8_t triggerMode = (lvt >> 15) & 0x1u;
uint8_t polarity = (lvt >> 13) & 0x1u;
uint8_t deliveryMode = (lvt >> 8) & 0x7u;
uint8_t vector = lvt & 0xff;
printf("LVT: Vector: %u, Deliv: %u, Pol: %u, TMode: %u, Masked: %u\n",
vector, deliveryMode, polarity, triggerMode, mask);
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "common/Material.h"
#include "common/Data.h"
#include "texture/Texture2D.h"
#include "math/spectrum.h"
#include "Principled_ispc.h"
namespace ospray {
namespace pathtracer {
struct Principled : public ospray::Material
{
//! \brief common function to help printf-debugging
/*! Every derived class should overrride this! */
virtual std::string toString() const override
{ return "ospray::pathtracer::Principled"; }
Principled()
{
ispcEquivalent = ispc::PathTracer_Principled_create();
}
//! \brief commit the material's parameters
virtual void commit() override
{
Texture2D* baseColorMap = (Texture2D*)getParamObject("baseColorMap");
affine2f baseColorXform = getTextureTransform("baseColorMap");
vec3f baseColor = getParam3f("baseColor", baseColorMap ? vec3f(1.f) : vec3f(0.8f));
Texture2D* metallicMap = (Texture2D*)getParamObject("metallicMap");
affine2f metallicXform = getTextureTransform("metallicMap");
float metallic = getParamf("metallic", metallicMap ? 1.f : 0.f);
Texture2D* specularMap = (Texture2D*)getParamObject("specularMap");
affine2f specularXform = getTextureTransform("specularMap");
float specular = getParamf("specular", specularMap ? 1.f : 0.f);
Texture2D* edgeColorMap = (Texture2D*)getParamObject("edgeColorMap");
affine2f edgeColorXform = getTextureTransform("edgeColorMap");
vec3f edgeColor = getParam3f("edgeColor", vec3f(1.f));
Texture2D* transmissionMap = (Texture2D*)getParamObject("transmissionMap");
affine2f transmissionXform = getTextureTransform("transmissionMap");
float transmission = getParamf("transmission", transmissionMap ? 1.f : 0.f);
Texture2D* roughnessMap = (Texture2D*)getParamObject("roughnessMap");
affine2f roughnessXform = getTextureTransform("roughnessMap");
float roughness = getParamf("roughness", roughnessMap ? 1.f : 0.f);
Texture2D* normalMap = (Texture2D*)getParamObject("normalMap");
affine2f normalXform = getTextureTransform("normalMap");
linear2f normalRot = normalXform.l.orthogonal().transposed();
float normalScale = getParamf("normalScale", 1.f);
Texture2D* coatMap = (Texture2D*)getParamObject("coatMap");
affine2f coatXform = getTextureTransform("coatMap");
float coat = getParamf("coat", coatMap ? 1.f : 0.f);
Texture2D* coatColorMap = (Texture2D*)getParamObject("coatColorMap");
#if 0 //NOTE(jda) - this is unused, triggering a warning...remove if not needed
affine2f coatColorXform = getTextureTransform("coatColorMap");
#endif
vec3f coatColor = getParam3f("coatColor", vec3f(1.f));
Texture2D* coatThicknessMap = (Texture2D*)getParamObject("coatThicknessMap");
affine2f coatThicknessXform = getTextureTransform("coatThicknessMap");
float coatThickness = getParamf("coatThickness", 1.f);
Texture2D* coatRoughnessMap = (Texture2D*)getParamObject("coatRoughnessMap");
affine2f coatRoughnessXform = getTextureTransform("coatRoughnessMap");
float coatRoughness = getParamf("coatRoughness", coatRoughnessMap ? 1.f : 0.f);
Texture2D* coatNormalMap = (Texture2D*)getParamObject("coatNormalMap");
affine2f coatNormalXform = getTextureTransform("coatNormalMap");
linear2f coatNormalRot = coatNormalXform.l.orthogonal().transposed();
float coatNormalScale = getParamf("coatNormalScale", 1.f);
float ior = getParamf("ior", 1.5f);
vec3f transmissionColor = getParam3f("transmissionColor", vec3f(1.f));
float transmissionDepth = getParamf("transmissionDepth", 1.f);
float iorOutside = getParamf("iorOutside", 1.f);
vec3f transmissionColorOutside = getParam3f("transmissionColorOutside", vec3f(1.f));
float transmissionDepthOutside = getParamf("transmissionDepthOutside", 1.f);
ispc::PathTracer_Principled_set(getIE(),
(const ispc::vec3f&)baseColor, baseColorMap ? baseColorMap->getIE() : nullptr, (const ispc::AffineSpace2f&)baseColorXform,
metallic, metallicMap ? metallicMap->getIE() : nullptr, (const ispc::AffineSpace2f&)metallicXform,
specular, specularMap ? specularMap->getIE() : nullptr, (const ispc::AffineSpace2f&)specularXform,
(const ispc::vec3f&)edgeColor, edgeColorMap ? edgeColorMap->getIE() : nullptr, (const ispc::AffineSpace2f&)edgeColorXform,
transmission, transmissionMap ? transmissionMap->getIE() : nullptr, (const ispc::AffineSpace2f&)transmissionXform,
roughness, roughnessMap ? roughnessMap->getIE() : nullptr, (const ispc::AffineSpace2f&)roughnessXform,
normalMap ? normalMap->getIE() : nullptr, (const ispc::AffineSpace2f&)normalXform, (const ispc::LinearSpace2f&)normalRot, normalScale,
coat, coatMap ? coatMap->getIE() : nullptr, (const ispc::AffineSpace2f&)coatXform,
(const ispc::vec3f&)coatColor, coatColorMap ? coatColorMap->getIE() : nullptr, (const ispc::AffineSpace2f&)coatXform,
coatThickness, coatThicknessMap ? coatThicknessMap->getIE() : nullptr, (const ispc::AffineSpace2f&)coatThicknessXform,
coatRoughness, coatRoughnessMap ? coatRoughnessMap->getIE() : nullptr, (const ispc::AffineSpace2f&)coatRoughnessXform,
coatNormalMap ? coatNormalMap->getIE() : nullptr, (const ispc::AffineSpace2f&)coatNormalXform, (const ispc::LinearSpace2f&)coatNormalRot, coatNormalScale,
ior,
(const ispc::vec3f&)transmissionColor,
transmissionDepth,
iorOutside,
(const ispc::vec3f&)transmissionColorOutside,
transmissionDepthOutside);
}
};
OSP_REGISTER_MATERIAL(Principled,PathTracer_Principled);
}
}
<commit_msg>fixed minor bug in Principled<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "common/Material.h"
#include "common/Data.h"
#include "texture/Texture2D.h"
#include "math/spectrum.h"
#include "Principled_ispc.h"
namespace ospray {
namespace pathtracer {
struct Principled : public ospray::Material
{
//! \brief common function to help printf-debugging
/*! Every derived class should overrride this! */
virtual std::string toString() const override
{ return "ospray::pathtracer::Principled"; }
Principled()
{
ispcEquivalent = ispc::PathTracer_Principled_create();
}
//! \brief commit the material's parameters
virtual void commit() override
{
Texture2D* baseColorMap = (Texture2D*)getParamObject("baseColorMap");
affine2f baseColorXform = getTextureTransform("baseColorMap");
vec3f baseColor = getParam3f("baseColor", baseColorMap ? vec3f(1.f) : vec3f(0.8f));
Texture2D* metallicMap = (Texture2D*)getParamObject("metallicMap");
affine2f metallicXform = getTextureTransform("metallicMap");
float metallic = getParamf("metallic", metallicMap ? 1.f : 0.f);
Texture2D* specularMap = (Texture2D*)getParamObject("specularMap");
affine2f specularXform = getTextureTransform("specularMap");
float specular = getParamf("specular", specularMap ? 1.f : 0.f);
Texture2D* edgeColorMap = (Texture2D*)getParamObject("edgeColorMap");
affine2f edgeColorXform = getTextureTransform("edgeColorMap");
vec3f edgeColor = getParam3f("edgeColor", vec3f(1.f));
Texture2D* transmissionMap = (Texture2D*)getParamObject("transmissionMap");
affine2f transmissionXform = getTextureTransform("transmissionMap");
float transmission = getParamf("transmission", transmissionMap ? 1.f : 0.f);
Texture2D* roughnessMap = (Texture2D*)getParamObject("roughnessMap");
affine2f roughnessXform = getTextureTransform("roughnessMap");
float roughness = getParamf("roughness", roughnessMap ? 1.f : 0.f);
Texture2D* normalMap = (Texture2D*)getParamObject("normalMap");
affine2f normalXform = getTextureTransform("normalMap");
linear2f normalRot = normalXform.l.orthogonal().transposed();
float normalScale = getParamf("normalScale", 1.f);
Texture2D* coatMap = (Texture2D*)getParamObject("coatMap");
affine2f coatXform = getTextureTransform("coatMap");
float coat = getParamf("coat", coatMap ? 1.f : 0.f);
Texture2D* coatColorMap = (Texture2D*)getParamObject("coatColorMap");
affine2f coatColorXform = getTextureTransform("coatColorMap");
vec3f coatColor = getParam3f("coatColor", vec3f(1.f));
Texture2D* coatThicknessMap = (Texture2D*)getParamObject("coatThicknessMap");
affine2f coatThicknessXform = getTextureTransform("coatThicknessMap");
float coatThickness = getParamf("coatThickness", 1.f);
Texture2D* coatRoughnessMap = (Texture2D*)getParamObject("coatRoughnessMap");
affine2f coatRoughnessXform = getTextureTransform("coatRoughnessMap");
float coatRoughness = getParamf("coatRoughness", coatRoughnessMap ? 1.f : 0.f);
Texture2D* coatNormalMap = (Texture2D*)getParamObject("coatNormalMap");
affine2f coatNormalXform = getTextureTransform("coatNormalMap");
linear2f coatNormalRot = coatNormalXform.l.orthogonal().transposed();
float coatNormalScale = getParamf("coatNormalScale", 1.f);
float ior = getParamf("ior", 1.5f);
vec3f transmissionColor = getParam3f("transmissionColor", vec3f(1.f));
float transmissionDepth = getParamf("transmissionDepth", 1.f);
float iorOutside = getParamf("iorOutside", 1.f);
vec3f transmissionColorOutside = getParam3f("transmissionColorOutside", vec3f(1.f));
float transmissionDepthOutside = getParamf("transmissionDepthOutside", 1.f);
ispc::PathTracer_Principled_set(getIE(),
(const ispc::vec3f&)baseColor, baseColorMap ? baseColorMap->getIE() : nullptr, (const ispc::AffineSpace2f&)baseColorXform,
metallic, metallicMap ? metallicMap->getIE() : nullptr, (const ispc::AffineSpace2f&)metallicXform,
specular, specularMap ? specularMap->getIE() : nullptr, (const ispc::AffineSpace2f&)specularXform,
(const ispc::vec3f&)edgeColor, edgeColorMap ? edgeColorMap->getIE() : nullptr, (const ispc::AffineSpace2f&)edgeColorXform,
transmission, transmissionMap ? transmissionMap->getIE() : nullptr, (const ispc::AffineSpace2f&)transmissionXform,
roughness, roughnessMap ? roughnessMap->getIE() : nullptr, (const ispc::AffineSpace2f&)roughnessXform,
normalMap ? normalMap->getIE() : nullptr, (const ispc::AffineSpace2f&)normalXform, (const ispc::LinearSpace2f&)normalRot, normalScale,
coat, coatMap ? coatMap->getIE() : nullptr, (const ispc::AffineSpace2f&)coatXform,
(const ispc::vec3f&)coatColor, coatColorMap ? coatColorMap->getIE() : nullptr, (const ispc::AffineSpace2f&)coatColorXform,
coatThickness, coatThicknessMap ? coatThicknessMap->getIE() : nullptr, (const ispc::AffineSpace2f&)coatThicknessXform,
coatRoughness, coatRoughnessMap ? coatRoughnessMap->getIE() : nullptr, (const ispc::AffineSpace2f&)coatRoughnessXform,
coatNormalMap ? coatNormalMap->getIE() : nullptr, (const ispc::AffineSpace2f&)coatNormalXform, (const ispc::LinearSpace2f&)coatNormalRot, coatNormalScale,
ior,
(const ispc::vec3f&)transmissionColor,
transmissionDepth,
iorOutside,
(const ispc::vec3f&)transmissionColorOutside,
transmissionDepthOutside);
}
};
OSP_REGISTER_MATERIAL(Principled,PathTracer_Principled);
}
}
<|endoftext|> |
<commit_before>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011, 2012 *
* Dominik Charousset <[email protected]> *
* *
* This file is part of libcppa. *
* libcppa is free software: you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation, either version 3 of the License *
* or (at your option) any later version. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#include <string>
#include <cstring>
#include <cstdint>
#include <type_traits>
#include "cppa/primitive_variant.hpp"
#include "cppa/binary_serializer.hpp"
using std::enable_if;
namespace cppa {
namespace {
constexpr size_t chunk_size = 512;
constexpr size_t ui32_size = sizeof(std::uint32_t);
class binary_writer {
public:
binary_writer(util::buffer* sink) : m_sink(sink) { }
template<typename T>
static inline void write_int(util::buffer* sink, const T& value) {
sink->write(sizeof(T), &value, util::grow_if_needed);
}
static inline void write_string(util::buffer* sink,
const std::string& str) {
write_int(sink, static_cast<std::uint32_t>(str.size()));
sink->write(str.size(), str.c_str(), util::grow_if_needed);
}
template<typename T>
void operator()(const T& value,
typename enable_if<std::is_integral<T>::value>::type* = 0) {
write_int(m_sink, value);
}
template<typename T>
void operator()(const T& value,
typename enable_if<std::is_floating_point<T>::value>::type* = 0) {
// write floating points as strings
std::string str = std::to_string(value);
(*this)(str);
}
void operator()(const std::string& str) {
write_string(m_sink, str);
}
void operator()(const std::u16string& str) {
write_int(m_sink, static_cast<std::uint32_t>(str.size()));
for (char16_t c : str) {
// force writer to use exactly 16 bit
write_int(m_sink, static_cast<std::uint16_t>(c));
}
}
void operator()(const std::u32string& str) {
write_int(m_sink, static_cast<std::uint32_t>(str.size()));
for (char32_t c : str) {
// force writer to use exactly 32 bit
write_int(m_sink, static_cast<std::uint32_t>(c));
}
}
private:
util::buffer* m_sink;
};
} // namespace <anonymous>
binary_serializer::binary_serializer(util::buffer* buf)
: m_obj_count(0), m_begin_pos(0), m_sink(buf) {
}
void binary_serializer::begin_object(const std::string& tname) {
if (++m_obj_count == 1) {
// store a dummy size in the buffer that is
// eventually updated on matching end_object()
m_begin_pos = m_sink->size();
std::uint32_t dummy_size = 0;
m_sink->write(sizeof(std::uint32_t), &dummy_size, util::grow_if_needed);
}
binary_writer::write_string(m_sink, tname);
}
void binary_serializer::end_object() {
if (--m_obj_count == 0) {
// update the size in the buffer
auto data = m_sink->data();
auto s = static_cast<std::uint32_t>(m_sink->size()
- (m_begin_pos + ui32_size));
auto wr_pos = data + m_begin_pos;
memcpy(wr_pos, &s, sizeof(std::uint32_t));
}
}
void binary_serializer::begin_sequence(size_t list_size) {
binary_writer::write_int(m_sink, static_cast<std::uint32_t>(list_size));
}
void binary_serializer::end_sequence() { }
void binary_serializer::write_value(const primitive_variant& value) {
value.apply(binary_writer(m_sink));
}
void binary_serializer::write_raw(size_t num_bytes, const void* data) {
m_sink->write(num_bytes, data, util::grow_if_needed);
}
void binary_serializer::write_tuple(size_t size,
const primitive_variant* values) {
const primitive_variant* end = values + size;
for ( ; values != end; ++values) {
write_value(*values);
}
}
void binary_serializer::reset() {
m_obj_count = 0;
}
} // namespace cppa
<commit_msg>no more black magic during serialize<commit_after>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011, 2012 *
* Dominik Charousset <[email protected]> *
* *
* This file is part of libcppa. *
* libcppa is free software: you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation, either version 3 of the License *
* or (at your option) any later version. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#include <string>
#include <cstring>
#include <cstdint>
#include <type_traits>
#include "cppa/primitive_variant.hpp"
#include "cppa/binary_serializer.hpp"
using std::enable_if;
namespace cppa {
namespace {
constexpr size_t chunk_size = 512;
constexpr size_t ui32_size = sizeof(std::uint32_t);
class binary_writer {
public:
binary_writer(util::buffer* sink) : m_sink(sink) { }
template<typename T>
static inline void write_int(util::buffer* sink, const T& value) {
sink->write(sizeof(T), &value, util::grow_if_needed);
}
static inline void write_string(util::buffer* sink,
const std::string& str) {
write_int(sink, static_cast<std::uint32_t>(str.size()));
sink->write(str.size(), str.c_str(), util::grow_if_needed);
}
template<typename T>
void operator()(const T& value,
typename enable_if<std::is_integral<T>::value>::type* = 0) {
write_int(m_sink, value);
}
template<typename T>
void operator()(const T& value,
typename enable_if<std::is_floating_point<T>::value>::type* = 0) {
// write floating points as strings
std::string str = std::to_string(value);
(*this)(str);
}
void operator()(const std::string& str) {
write_string(m_sink, str);
}
void operator()(const std::u16string& str) {
write_int(m_sink, static_cast<std::uint32_t>(str.size()));
for (char16_t c : str) {
// force writer to use exactly 16 bit
write_int(m_sink, static_cast<std::uint16_t>(c));
}
}
void operator()(const std::u32string& str) {
write_int(m_sink, static_cast<std::uint32_t>(str.size()));
for (char32_t c : str) {
// force writer to use exactly 32 bit
write_int(m_sink, static_cast<std::uint32_t>(c));
}
}
private:
util::buffer* m_sink;
};
} // namespace <anonymous>
binary_serializer::binary_serializer(util::buffer* buf)
: m_obj_count(0), m_begin_pos(0), m_sink(buf) {
}
void binary_serializer::begin_object(const std::string& tname) {
/*
if (++m_obj_count == 1) {
// store a dummy size in the buffer that is
// eventually updated on matching end_object()
m_begin_pos = m_sink->size();
std::uint32_t dummy_size = 0;
m_sink->write(sizeof(std::uint32_t), &dummy_size, util::grow_if_needed);
}
*/
binary_writer::write_string(m_sink, tname);
}
void binary_serializer::end_object() {
/*
if (--m_obj_count == 0) {
// update the size in the buffer
auto data = m_sink->data();
auto s = static_cast<std::uint32_t>(m_sink->size()
- (m_begin_pos + ui32_size));
auto wr_pos = data + m_begin_pos;
memcpy(wr_pos, &s, sizeof(std::uint32_t));
}
*/
}
void binary_serializer::begin_sequence(size_t list_size) {
binary_writer::write_int(m_sink, static_cast<std::uint32_t>(list_size));
}
void binary_serializer::end_sequence() { }
void binary_serializer::write_value(const primitive_variant& value) {
value.apply(binary_writer(m_sink));
}
void binary_serializer::write_raw(size_t num_bytes, const void* data) {
m_sink->write(num_bytes, data, util::grow_if_needed);
}
void binary_serializer::write_tuple(size_t size,
const primitive_variant* values) {
const primitive_variant* end = values + size;
for ( ; values != end; ++values) {
write_value(*values);
}
}
void binary_serializer::reset() {
m_obj_count = 0;
}
} // namespace cppa
<|endoftext|> |
<commit_before>#include <QDebug>
#include <QtCore/QReadWriteLock>
#include <QtQml/QJSValueIterator>
#include "jsonlistmodel.h"
static const int BASE_ROLE = Qt::UserRole + 1;
JsonListModel::JsonListModel(QObject *parent) :
QAbstractItemModel(parent),
m_lock(new QReadWriteLock(QReadWriteLock::Recursive)),
m_idAttribute("id")
{
}
void JsonListModel::extractRoles(const QJSValue &item,
const QString &prefix = QString())
{
QJSValueIterator it(item);
while (it.next()) {
QString n = prefix + it.name();
addRole(n);
QJSValue v = it.value();
if (!v.isArray() && v.isObject())
extractRoles(it.value(), n + ".");
}
}
int JsonListModel::addItem(const QJSValue &item)
{
int row = -1;
QString id;
if (item.isString() || item.isNumber() || item.isDate()) {
id = item.toString();
addRole("modelData");
} else if (item.isObject()) {
if (!item.hasProperty(m_idAttribute)) {
qWarning() << QString("Object does not have a %1 property").arg(m_idAttribute);
return row;
}
id = item.property(m_idAttribute).toString();
}
QJSValue existingItem = m_items[id];
if (existingItem.strictlyEquals(item)) {
return row;
}
m_items[id] = item;
if (existingItem.isUndefined()) {
m_keys.append(id);
row = m_keys.count() - 1;
return row;
}
return m_keys.indexOf(id);
}
void JsonListModel::add(const QJSValue &item)
{
m_lock->lockForWrite();
int originalSize = m_keys.count();
if (item.isArray()) {
QJSValueIterator array(item);
int updateFrom = INT_MAX;
int updateTo = INT_MIN;
// Only extract roles from the first item (assumes uniform data)
if (array.next()) {
if (array.hasNext()) { // ignore if last element
extractRoles(array.value());
int row = addItem(array.value());
if (row >= 0 && row < originalSize) {
updateFrom = qMin(updateFrom, row);
updateTo = qMax(updateTo, row);
}
}
}
while (array.next()) {
if (!array.hasNext())
break; // last value in array is an int with the length
int row = addItem(array.value());
if (row >= 0 && row < originalSize) {
updateFrom = qMin(updateFrom, row);
updateTo = qMax(updateTo, row);
}
}
int newSize = m_keys.count();
m_lock->unlock();
// emit signals after the mutex is unlocked
if (newSize > originalSize) {
beginInsertRows(QModelIndex(), originalSize, newSize - 1);
endInsertRows();
} else {
if (updateFrom != INT_MAX && updateTo != INT_MIN) {
emit dataChanged(createIndex(updateFrom, 0), createIndex(updateTo, 0));
}
}
} else {
extractRoles(item);
int row = addItem(item);
if (row >= 0 && row < originalSize) {
QModelIndex index = createIndex(row, 0);
m_lock->unlock();
emit dataChanged(index, index);
return;
}
int newSize = m_keys.count();
m_lock->unlock();
if (newSize > originalSize) {
beginInsertRows(QModelIndex(), originalSize, newSize - 1);
endInsertRows();
}
}
}
void JsonListModel::remove(const QJSValue &item)
{
int index;
{
QWriteLocker writeLocker(m_lock);
QString key;
if (item.isString() || item.isNumber() || item.isDate()) {
key = item.toString();
index = m_keys.indexOf(key);
} else if (item.hasProperty(m_idAttribute)){
key = item.property(m_idAttribute).toString();
index = m_keys.indexOf(key);
} else {
qWarning() << "Unable to remove item";
return;
}
m_keys.removeAt(index);
m_items.remove(key);
}
beginRemoveRows(QModelIndex(), index, index);
endRemoveRows();
}
void JsonListModel::clear()
{
m_lock->lockForWrite();
int originalSize = m_keys.length();
m_keys.clear();
m_items.clear();
m_lock->unlock();
beginRemoveRows(QModelIndex(), 0, originalSize);
endRemoveRows();
}
QJSValue JsonListModel::at(int row) const
{
QReadLocker locker(m_lock);
if (row >= 0 && row < m_keys.count()) {
return m_items[m_keys[row]];
}
return QJSValue();
}
QModelIndex JsonListModel::index(int row, int column, const QModelIndex &) const
{
QReadLocker readLock(m_lock);
if (row >= 0 && row < m_keys.count()) {
return createIndex(row, column);
} else {
qWarning() << "Out of bounds";
}
return QModelIndex();
}
QModelIndex JsonListModel::parent(const QModelIndex &) const
{
return QModelIndex();
}
int JsonListModel::rowCount(const QModelIndex &) const
{
QReadLocker locker(m_lock);
return m_keys.count();
}
int JsonListModel::columnCount(const QModelIndex &) const
{
return 1;
}
QVariant JsonListModel::data(const QModelIndex &index, int role) const
{
QReadLocker readLock(m_lock);
int row = index.row();
if (row < 0 || row > m_keys.count()) {
qWarning() << "Out of bounds";
return QVariant();
}
QJSValue item = m_items[m_keys[row]];
QString roleName = getRole(role);
if (item.isString() || item.isNumber() || item.isDate()) {
return item.toVariant();
} else {
QStringList parts = roleName.split(".");
roleName = parts.takeLast();
for (QStringList::const_iterator p = parts.constBegin(); p != parts.end(); p++) {
item = item.property(*p);
}
if (item.hasProperty(roleName))
return item.property(roleName).toVariant();
return QJSValue().toVariant();
}
}
QHash<int, QByteArray> JsonListModel::roleNames() const
{
QHash<int, QByteArray> roles;
for (int i = 0; i < m_roles.count(); ++i) {
roles.insert(BASE_ROLE + i, m_roles.at(i).toUtf8());
}
return roles;
}
QString JsonListModel::idAttribute() const
{
return m_idAttribute;
}
void JsonListModel::addRole(const QString &r)
{
foreach (const QString s, m_roles) {
if (s == r)
return;
}
m_roles.append(r);
emit roleAdded(r);
// TODO: emit dataChanged(); ?
}
QString JsonListModel::getRole(int role) const
{
role -= BASE_ROLE;
if (role < 0 || role > m_roles.count())
return "";
return m_roles[role];
}
int JsonListModel::getRole(const QString &role) const
{
int roleIndex = m_roles.indexOf(role);
if (roleIndex < 0)
return Qt::DisplayRole;
return BASE_ROLE + roleIndex;
}
void JsonListModel::setIdAttribute(QString idAttribute)
{
if (m_idAttribute == idAttribute)
return;
m_idAttribute = idAttribute;
emit idAttributeChanged(idAttribute);
}
bool JsonListModel::setData(const QModelIndex &, const QVariant &, int)
{
return false;
}
<commit_msg>Fix bug when removing non-existant items.<commit_after>#include <QDebug>
#include <QtCore/QReadWriteLock>
#include <QtQml/QJSValueIterator>
#include "jsonlistmodel.h"
static const int BASE_ROLE = Qt::UserRole + 1;
JsonListModel::JsonListModel(QObject *parent) :
QAbstractItemModel(parent),
m_lock(new QReadWriteLock(QReadWriteLock::Recursive)),
m_idAttribute("id")
{
}
void JsonListModel::extractRoles(const QJSValue &item,
const QString &prefix = QString())
{
QJSValueIterator it(item);
while (it.next()) {
QString n = prefix + it.name();
addRole(n);
QJSValue v = it.value();
if (!v.isArray() && v.isObject())
extractRoles(it.value(), n + ".");
}
}
int JsonListModel::addItem(const QJSValue &item)
{
int row = -1;
QString id;
if (item.isString() || item.isNumber() || item.isDate()) {
id = item.toString();
addRole("modelData");
} else if (item.isObject()) {
if (!item.hasProperty(m_idAttribute)) {
qWarning() << QString("Object does not have a %1 property").arg(m_idAttribute);
return row;
}
id = item.property(m_idAttribute).toString();
}
QJSValue existingItem = m_items[id];
if (existingItem.strictlyEquals(item)) {
return row;
}
m_items[id] = item;
if (existingItem.isUndefined()) {
m_keys.append(id);
row = m_keys.count() - 1;
return row;
}
return m_keys.indexOf(id);
}
void JsonListModel::add(const QJSValue &item)
{
m_lock->lockForWrite();
int originalSize = m_keys.count();
if (item.isArray()) {
QJSValueIterator array(item);
int updateFrom = INT_MAX;
int updateTo = INT_MIN;
// Only extract roles from the first item (assumes uniform data)
if (array.next()) {
if (array.hasNext()) { // ignore if last element
extractRoles(array.value());
int row = addItem(array.value());
if (row >= 0 && row < originalSize) {
updateFrom = qMin(updateFrom, row);
updateTo = qMax(updateTo, row);
}
}
}
while (array.next()) {
if (!array.hasNext())
break; // last value in array is an int with the length
int row = addItem(array.value());
if (row >= 0 && row < originalSize) {
updateFrom = qMin(updateFrom, row);
updateTo = qMax(updateTo, row);
}
}
int newSize = m_keys.count();
m_lock->unlock();
// emit signals after the mutex is unlocked
if (newSize > originalSize) {
beginInsertRows(QModelIndex(), originalSize, newSize - 1);
endInsertRows();
} else {
if (updateFrom != INT_MAX && updateTo != INT_MIN) {
emit dataChanged(createIndex(updateFrom, 0), createIndex(updateTo, 0));
}
}
} else {
extractRoles(item);
int row = addItem(item);
if (row >= 0 && row < originalSize) {
QModelIndex index = createIndex(row, 0);
m_lock->unlock();
emit dataChanged(index, index);
return;
}
int newSize = m_keys.count();
m_lock->unlock();
if (newSize > originalSize) {
beginInsertRows(QModelIndex(), originalSize, newSize - 1);
endInsertRows();
}
}
}
void JsonListModel::remove(const QJSValue &item)
{
int index;
{
QWriteLocker writeLocker(m_lock);
QString key;
if (item.isString() || item.isNumber() || item.isDate()) {
key = item.toString();
index = m_keys.indexOf(key);
} else if (item.hasProperty(m_idAttribute)){
key = item.property(m_idAttribute).toString();
index = m_keys.indexOf(key);
} else {
qWarning() << "Unable to remove item";
return;
}
if (index == -1)
return;
m_keys.removeAt(index);
m_items.remove(key);
}
beginRemoveRows(QModelIndex(), index, index);
endRemoveRows();
}
void JsonListModel::clear()
{
m_lock->lockForWrite();
int originalSize = m_keys.length();
m_keys.clear();
m_items.clear();
m_lock->unlock();
beginRemoveRows(QModelIndex(), 0, originalSize);
endRemoveRows();
}
QJSValue JsonListModel::at(int row) const
{
QReadLocker locker(m_lock);
if (row >= 0 && row < m_keys.count()) {
return m_items[m_keys[row]];
}
return QJSValue();
}
QModelIndex JsonListModel::index(int row, int column, const QModelIndex &) const
{
QReadLocker readLock(m_lock);
if (row >= 0 && row < m_keys.count()) {
return createIndex(row, column);
} else {
qWarning() << "Out of bounds";
}
return QModelIndex();
}
QModelIndex JsonListModel::parent(const QModelIndex &) const
{
return QModelIndex();
}
int JsonListModel::rowCount(const QModelIndex &) const
{
QReadLocker locker(m_lock);
return m_keys.count();
}
int JsonListModel::columnCount(const QModelIndex &) const
{
return 1;
}
QVariant JsonListModel::data(const QModelIndex &index, int role) const
{
QReadLocker readLock(m_lock);
int row = index.row();
if (row < 0 || row > m_keys.count()) {
qWarning() << "Out of bounds";
return QVariant();
}
QJSValue item = m_items[m_keys[row]];
QString roleName = getRole(role);
if (item.isString() || item.isNumber() || item.isDate()) {
return item.toVariant();
} else {
QStringList parts = roleName.split(".");
roleName = parts.takeLast();
for (QStringList::const_iterator p = parts.constBegin(); p != parts.end(); p++) {
item = item.property(*p);
}
if (item.hasProperty(roleName))
return item.property(roleName).toVariant();
return QJSValue().toVariant();
}
}
QHash<int, QByteArray> JsonListModel::roleNames() const
{
QHash<int, QByteArray> roles;
for (int i = 0; i < m_roles.count(); ++i) {
roles.insert(BASE_ROLE + i, m_roles.at(i).toUtf8());
}
return roles;
}
QString JsonListModel::idAttribute() const
{
return m_idAttribute;
}
void JsonListModel::addRole(const QString &r)
{
foreach (const QString s, m_roles) {
if (s == r)
return;
}
m_roles.append(r);
emit roleAdded(r);
// TODO: emit dataChanged(); ?
}
QString JsonListModel::getRole(int role) const
{
role -= BASE_ROLE;
if (role < 0 || role > m_roles.count())
return "";
return m_roles[role];
}
int JsonListModel::getRole(const QString &role) const
{
int roleIndex = m_roles.indexOf(role);
if (roleIndex < 0)
return Qt::DisplayRole;
return BASE_ROLE + roleIndex;
}
void JsonListModel::setIdAttribute(QString idAttribute)
{
if (m_idAttribute == idAttribute)
return;
m_idAttribute = idAttribute;
emit idAttributeChanged(idAttribute);
}
bool JsonListModel::setData(const QModelIndex &, const QVariant &, int)
{
return false;
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2014 Rapptz
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef JSONPP_PARSER_HPP
#define JSONPP_PARSER_HPP
#include "error.hpp"
#include "value.hpp"
#include <cstring>
#include <iosfwd>
namespace json {
inline namespace v1 {
namespace detail {
struct parser_state {
unsigned line;
unsigned column;
const char* str;
};
inline void skip_white_space(parser_state& ps) {
while(*ps.str && isspace(*ps.str)) {
if(*ps.str == '\n') {
++ps.line;
ps.column = 0;
}
++ps.str;
++ps.column;
}
}
inline void parse_value(parser_state& ps, value& v);
inline void parse_null(parser_state& ps, value& v) {
static const char null_str[] = "null";
if(*ps.str == '\0') {
throw parser_error("expected null, received EOF instead", ps.line, ps.column);
}
if(std::strncmp(ps.str, null_str, sizeof(null_str) - 1) != 0) {
throw parser_error("expected null not found", ps.line, ps.column);
}
v = nullptr;
ps.str = ps.str + sizeof(null_str) - 1;
ps.column += sizeof(null_str);
}
inline void parse_number(parser_state& ps, value& v) {
static const std::string lookup = "0123456789eE+-.";
const char* begin = ps.str;
if(*begin == '\0') {
throw parser_error("expected number, received EOF instead", ps.line, ps.column);
}
while(lookup.find(*ps.str) != std::string::npos) {
++ps.str;
}
double val = 0.0;
try {
std::string temp(begin, ps.str);
val = std::stod(temp);
ps.column += temp.size() + 1;
}
catch(const std::exception& e) {
throw parser_error("number could not be parsed properly", ps.line, ps.column);
}
v = val;
}
template<typename Value>
inline void parse_string(parser_state& ps, Value& v) {
const char* end = ps.str + 1;
if(*end == '\0') {
throw parser_error("expected string, received EOF instead", ps.line, ps.column);
}
while(*end) {
if(*end == '\\' && *(end + 1) != '\0' && *(end + 1) == '"') {
end = end + 2;
}
else if(*end == '"') {
break;
}
else {
++end;
}
}
if(*end == '\0') {
throw parser_error("unescaped string sequence found", ps.line, ps.column);
}
auto&& temp = std::string(ps.str + 1, end);
ps.column += temp.size() + 1;
v = temp;
++end;
ps.str = end;
}
inline void parse_bool(parser_state& ps, value& v) {
if(*ps.str == '\0') {
throw parser_error("expected boolean, received EOF instead", ps.line, ps.column);
}
bool expected_true = *ps.str == 't';
const char* boolean = expected_true ? "true" : "false";
const size_t len = expected_true ? 4 : 5;
if(std::strncmp(ps.str, boolean, len) != 0) {
throw parser_error("expected boolean not found", ps.line, ps.column);
}
v = expected_true;
ps.str = ps.str + len;
ps.column += len;
}
inline void parse_array(parser_state& ps, value& v) {
++ps.str;
array arr;
value elem;
skip_white_space(ps);
if(*ps.str == '\0') {
throw parser_error("expected value, received EOF instead", ps.line, ps.column);
}
while (*ps.str && *ps.str != ']') {
parse_value(ps, elem);
if(*ps.str != ',') {
if(*ps.str != ']') {
throw parser_error("missing comma", ps.line, ps.column);
}
}
else if(*ps.str == ',') {
++ps.str;
// skip whitespace
skip_white_space(ps);
// handle missing input
if(*ps.str && *ps.str == ']') {
throw parser_error("extraneous comma spotted", ps.line, ps.column);
}
}
arr.push_back(elem);
}
v = arr;
if(*ps.str == ']') {
++ps.str;
}
}
inline void parse_object(parser_state& ps, value& v) {
++ps.str;
object obj;
std::string key;
value elem;
skip_white_space(ps);
if(*ps.str == '\0') {
throw parser_error("expected string key, received EOF instead", ps.line, ps.column);
}
while(*ps.str) {
skip_white_space(ps);
// empty object
if(*ps.str == '}') {
break;
}
if(*ps.str != '"') {
throw parser_error("expected string as key not found", ps.line, ps.column);
}
parse_string(ps, key);
skip_white_space(ps);
if(*ps.str != ':') {
throw parser_error("missing semicolon", ps.line, ps.column);
}
++ps.str;
parse_value(ps, elem);
if(*ps.str != ',') {
if(*ps.str != '}') {
throw parser_error("missing comma", ps.line, ps.column);
}
}
else if(*ps.str == ',') {
++ps.str;
}
obj.emplace(key, elem);
}
v = obj;
if(*ps.str == '}') {
++ps.str;
}
}
inline void parse_value(parser_state& ps, value& v) {
skip_white_space(ps);
if(*ps.str == '\0') {
throw parser_error("unexpected EOF found", ps.line, ps.column);
}
if(isdigit(*ps.str) || *ps.str == '+' || *ps.str == '-') {
parse_number(ps, v);
}
else {
switch(*ps.str) {
case 'n':
parse_null(ps, v);
break;
case '"':
parse_string(ps, v);
break;
case 't':
case 'f':
parse_bool(ps, v);
break;
case '[':
parse_array(ps, v);
break;
case '{':
parse_object(ps, v);
break;
default:
throw parser_error("unexpected token found", ps.line, ps.column);
break;
}
}
skip_white_space(ps);
}
} // detail
inline void parse(const std::string& str, value& v) {
detail::parser_state ps = { 1, 1, str.c_str() };
detail::parse_value(ps, v);
if(*ps.str != '\0') {
throw parser_error("unexpected token found", ps.line, ps.column);
}
}
template<typename IStream, DisableIf<is_string<IStream>> = 0>
inline void parse(IStream& in, value& v) {
static_assert(std::is_base_of<std::istream, IStream>::value, "Input stream passed must inherit from std::istream");
if(in) {
in.seekg(0, in.end);
auto size = in.tellg();
in.seekg(0, in.beg);
std::string str;
str.resize(size);
in.read(&str[0], size);
parse(str, v);
}
}
} // v1
} // json
#endif // JSONPP_PARSER_HPP
<commit_msg>Allow std::cin and other streams to be used. Fixes #1.<commit_after>// The MIT License (MIT)
// Copyright (c) 2014 Rapptz
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef JSONPP_PARSER_HPP
#define JSONPP_PARSER_HPP
#include "error.hpp"
#include "value.hpp"
#include <cstring>
#include <iosfwd>
namespace json {
inline namespace v1 {
namespace detail {
struct parser_state {
unsigned line;
unsigned column;
const char* str;
};
inline void skip_white_space(parser_state& ps) {
while(*ps.str && isspace(*ps.str)) {
if(*ps.str == '\n') {
++ps.line;
ps.column = 0;
}
++ps.str;
++ps.column;
}
}
inline void parse_value(parser_state& ps, value& v);
inline void parse_null(parser_state& ps, value& v) {
static const char null_str[] = "null";
if(*ps.str == '\0') {
throw parser_error("expected null, received EOF instead", ps.line, ps.column);
}
if(std::strncmp(ps.str, null_str, sizeof(null_str) - 1) != 0) {
throw parser_error("expected null not found", ps.line, ps.column);
}
v = nullptr;
ps.str = ps.str + sizeof(null_str) - 1;
ps.column += sizeof(null_str);
}
inline void parse_number(parser_state& ps, value& v) {
static const std::string lookup = "0123456789eE+-.";
const char* begin = ps.str;
if(*begin == '\0') {
throw parser_error("expected number, received EOF instead", ps.line, ps.column);
}
while(lookup.find(*ps.str) != std::string::npos) {
++ps.str;
}
double val = 0.0;
try {
std::string temp(begin, ps.str);
val = std::stod(temp);
ps.column += temp.size() + 1;
}
catch(const std::exception& e) {
throw parser_error("number could not be parsed properly", ps.line, ps.column);
}
v = val;
}
template<typename Value>
inline void parse_string(parser_state& ps, Value& v) {
const char* end = ps.str + 1;
if(*end == '\0') {
throw parser_error("expected string, received EOF instead", ps.line, ps.column);
}
while(*end) {
if(*end == '\\' && *(end + 1) != '\0' && *(end + 1) == '"') {
end = end + 2;
}
else if(*end == '"') {
break;
}
else {
++end;
}
}
if(*end == '\0') {
throw parser_error("unescaped string sequence found", ps.line, ps.column);
}
auto&& temp = std::string(ps.str + 1, end);
ps.column += temp.size() + 1;
v = temp;
++end;
ps.str = end;
}
inline void parse_bool(parser_state& ps, value& v) {
if(*ps.str == '\0') {
throw parser_error("expected boolean, received EOF instead", ps.line, ps.column);
}
bool expected_true = *ps.str == 't';
const char* boolean = expected_true ? "true" : "false";
const size_t len = expected_true ? 4 : 5;
if(std::strncmp(ps.str, boolean, len) != 0) {
throw parser_error("expected boolean not found", ps.line, ps.column);
}
v = expected_true;
ps.str = ps.str + len;
ps.column += len;
}
inline void parse_array(parser_state& ps, value& v) {
++ps.str;
array arr;
value elem;
skip_white_space(ps);
if(*ps.str == '\0') {
throw parser_error("expected value, received EOF instead", ps.line, ps.column);
}
while (*ps.str && *ps.str != ']') {
parse_value(ps, elem);
if(*ps.str != ',') {
if(*ps.str != ']') {
throw parser_error("missing comma", ps.line, ps.column);
}
}
else if(*ps.str == ',') {
++ps.str;
// skip whitespace
skip_white_space(ps);
// handle missing input
if(*ps.str && *ps.str == ']') {
throw parser_error("extraneous comma spotted", ps.line, ps.column);
}
}
arr.push_back(elem);
}
v = arr;
if(*ps.str == ']') {
++ps.str;
}
}
inline void parse_object(parser_state& ps, value& v) {
++ps.str;
object obj;
std::string key;
value elem;
skip_white_space(ps);
if(*ps.str == '\0') {
throw parser_error("expected string key, received EOF instead", ps.line, ps.column);
}
while(*ps.str) {
skip_white_space(ps);
// empty object
if(*ps.str == '}') {
break;
}
if(*ps.str != '"') {
throw parser_error("expected string as key not found", ps.line, ps.column);
}
parse_string(ps, key);
skip_white_space(ps);
if(*ps.str != ':') {
throw parser_error("missing semicolon", ps.line, ps.column);
}
++ps.str;
parse_value(ps, elem);
if(*ps.str != ',') {
if(*ps.str != '}') {
throw parser_error("missing comma", ps.line, ps.column);
}
}
else if(*ps.str == ',') {
++ps.str;
}
obj.emplace(key, elem);
}
v = obj;
if(*ps.str == '}') {
++ps.str;
}
}
inline void parse_value(parser_state& ps, value& v) {
skip_white_space(ps);
if(*ps.str == '\0') {
throw parser_error("unexpected EOF found", ps.line, ps.column);
}
if(isdigit(*ps.str) || *ps.str == '+' || *ps.str == '-') {
parse_number(ps, v);
}
else {
switch(*ps.str) {
case 'n':
parse_null(ps, v);
break;
case '"':
parse_string(ps, v);
break;
case 't':
case 'f':
parse_bool(ps, v);
break;
case '[':
parse_array(ps, v);
break;
case '{':
parse_object(ps, v);
break;
default:
throw parser_error("unexpected token found", ps.line, ps.column);
break;
}
}
skip_white_space(ps);
}
} // detail
inline void parse(const std::string& str, value& v) {
detail::parser_state ps = { 1, 1, str.c_str() };
detail::parse_value(ps, v);
if(*ps.str != '\0') {
throw parser_error("unexpected token found", ps.line, ps.column);
}
}
template<typename IStream, DisableIf<is_string<IStream>> = 0>
inline void parse(IStream& in, value& v) {
static_assert(std::is_base_of<std::istream, IStream>::value, "Input stream passed must inherit from std::istream");
if(in) {
std::ostringstream ss;
ss << in.rdbuf();
parse(ss.str(), v);
}
}
} // v1
} // json
#endif // JSONPP_PARSER_HPP
<|endoftext|> |
<commit_before>// -------------------------------------------------------------------
//
// sst_rewrite.cc
//
// Copyright (c) 2015 Basho Technologies, Inc. All Rights Reserved.
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// -------------------------------------------------------------------
#include <memory>
#include <stdio.h>
#include <stdlib.h>
//#include <libgen.h>
#include "leveldb/env.h"
#include "leveldb/filter_policy.h"
#include "leveldb/options.h"
#include "leveldb/table.h"
#include "leveldb/table_builder.h"
void command_help();
// wrapper class for opening / closing existing leveldb tables
class LDbTable
{
public:
LDbTable(leveldb::Options &, std::string &);
virtual ~LDbTable();
bool Ok() const {return(m_IsOpen);};
leveldb::Iterator * NewIterator();
const leveldb::Status & GetStatus() const {return(m_LastStatus);};
const char * GetFileName() const {return(m_FileName.c_str());};
uint64_t GetSstCounter(unsigned Idx) const
{return(m_IsOpen ? m_TablePtr->GetSstCounters().Value(Idx) : 0);};
protected:
leveldb::Options & m_Options;
const std::string m_FileName;
leveldb::RandomAccessFile * m_FilePtr;
leveldb::Table * m_TablePtr;
uint64_t m_FileSize;
leveldb::Status m_LastStatus;
bool m_IsOpen;
void Reset();
private:
// disable these
LDbTable();
LDbTable(const LDbTable &);
const LDbTable operator=(const LDbTable&);
}; // LDbTable
LDbTable::LDbTable(
leveldb::Options & Options,
std::string & FileName)
: m_Options(Options), m_FileName(FileName),
m_FilePtr(NULL), m_TablePtr(NULL), m_FileSize(0), m_IsOpen(false)
{
m_LastStatus=m_Options.env->GetFileSize(m_FileName, &m_FileSize);
if (m_LastStatus.ok())
{m_LastStatus=m_Options.env->NewRandomAccessFile(m_FileName, &m_FilePtr);}
if (m_LastStatus.ok())
{
m_LastStatus=leveldb::Table::Open(m_Options, m_FilePtr, m_FileSize, &m_TablePtr);
// use fadvise to start file pre-read
m_FilePtr->SetForCompaction(m_FileSize);
} // if
m_IsOpen=m_LastStatus.ok();
if (!m_IsOpen)
{
// some people would throw() at this point, but not me
Reset();
} // if
return;
} // LDbTable::LDbTable
LDbTable::~LDbTable()
{
Reset();
return;
} // LDbTable::~LDbTable
void
LDbTable::Reset()
{
m_IsOpen=false;
delete m_TablePtr;
m_TablePtr=NULL;
delete m_FilePtr;
m_FilePtr=NULL;
m_FileSize=0;
return;
} // LDbTable::Reset
leveldb::Iterator *
LDbTable::NewIterator()
{
leveldb::Iterator * ret_ptr(NULL);
if (m_IsOpen)
{
leveldb::ReadOptions read_options;
read_options.fill_cache=false;
ret_ptr=m_TablePtr->NewIterator(read_options);
} // if
return(ret_ptr);
} // LDbTable::NewIterator
int
main(
int argc,
char ** argv)
{
bool error_seen, running, compare_files;
char ** cursor;
compare_files=false;
error_seen=false;
running=true;
// Options: needs filter & total_leveldb_mem initialized
leveldb::Options options;
// using 16 bit width per key in bloom filter
options.filter_policy=leveldb::NewBloomFilterPolicy2(16);
// tell leveldb it can use 512Mbyte of memory
options.total_leveldb_mem=(512 << 20);
for (cursor=argv+1;
NULL!=*cursor && running && !error_seen;
++cursor)
{
// option flag?
if ('-'==**cursor)
{
char flag;
flag=*((*cursor)+1);
switch(flag)
{
case 'b':
{
error_seen=(NULL==(cursor+1));
if (!error_seen)
{options.block_size=atol(*(cursor+1));};
break;
} // case b
case 's': options.compression=leveldb::kSnappyCompression; break;
case 'z': options.compression=leveldb::kLZ4Compression; break;
case 'n': options.compression=leveldb::kNoCompression; break;
case 'c':
{
// test for first pair ... but after that user beware
error_seen=(NULL==(cursor+1)) || (NULL==(cursor+2));
if (!error_seen)
{compare_files=true;}
break;
} // case c
case 'w': compare_files=false; break;
default:
fprintf(stderr, " option \'%c\' is not valid\n", flag);
command_help();
running=false;
error_seen=true;
break;
} // switch
} // if
// sst file
else
{
std::string fname;
fname=*cursor;
// do a rewrite
if (!compare_files)
{
leveldb::WritableFile * outfile;
leveldb::Status s;
std::auto_ptr<leveldb::Iterator> it;
std::auto_ptr<leveldb::TableBuilder> builder;
LDbTable in_file(options, fname);
if (in_file.GetStatus().ok())
{
it.reset(in_file.NewIterator());
fname.append(".new");
s = options.env->NewWritableFile(fname, &outfile,
options.env->RecoveryMmapSize(&options));
if (s.ok())
builder.reset(new leveldb::TableBuilder(options, outfile));
else
{
// Table::Open failed on file "fname"
fprintf(stderr, "%s: NewWritableFile failed (%s)\n",
fname.c_str(), s.ToString().c_str());
error_seen=true;
} // else
for (it->SeekToFirst(); it->Valid() && s.ok(); it->Next())
{
leveldb::Slice key = it->key();
builder->Add(key, it->value());
} // for
// hmmm, nothing new setting status right now.
if (s.ok()) {
s = builder->Finish();
} else {
builder->Abandon();
}
if (NULL!=outfile)
outfile->Close();
delete outfile;
} // if
else
{
fprintf(stderr, "%s: Input table open failed (%s)\n",
fname.c_str(), in_file.GetStatus().ToString().c_str());
error_seen=true;
} // else
} // if
// compare two files
else
{
LDbTable file1(options, fname);
++cursor;
if (NULL!=*cursor)
{
fname=*cursor;
LDbTable file2(options, fname);
if (file1.GetStatus().ok() && file2.GetStatus().ok())
{
// quick check: same number of keys and bytes of user data?
// do this before reading entire files
if (file1.GetSstCounter(leveldb::eSstCountKeys)==file2.GetSstCounter(leveldb::eSstCountKeys)
&& file1.GetSstCounter(leveldb::eSstCountKeySize)==file2.GetSstCounter(leveldb::eSstCountKeySize)
&& file1.GetSstCounter(leveldb::eSstCountValueSize)==file2.GetSstCounter(leveldb::eSstCountValueSize))
{
leveldb::Iterator * it1, *it2;
uint64_t key_count;
bool match;
it1=file1.NewIterator();
it2=file2.NewIterator();
match=true;
for (it1->SeekToFirst(), it2->SeekToFirst(), key_count=1;
it1->Valid() && it2->Valid() && match;
it1->Next(), it2->Next(), ++key_count)
{
match=(0==it1->key().compare(it2->key())) && (0==it1->value().compare(it2->value()));
if (!match)
{
fprintf(stderr, "%s, %s: Content mismatch at key position %d (%d, %d).\n",
file1.GetFileName(), file2.GetFileName(),
(int)key_count,
it1->key().compare(it2->key()), it1->value().compare(it2->value()));
error_seen=true;
} // if
} // for
if (it1->Valid() != it2->Valid())
{
fprintf(stderr, "%s, %s: Walk of keys terminated early (%d, %d).\n",
file1.GetFileName(), file2.GetFileName(),
(int)it1->Valid(), (int)it2->Valid());
error_seen=true;
}
} // if
else
{
if (file1.GetSstCounter(leveldb::eSstCountKeys)==file2.GetSstCounter(leveldb::eSstCountKeys))
fprintf(stderr, "%s, %s: Number of keys different.\n",
file1.GetFileName(), file2.GetFileName());
if (file1.GetSstCounter(leveldb::eSstCountKeySize)==file2.GetSstCounter(leveldb::eSstCountKeySize))
fprintf(stderr, "%s, %s: Byte size of all keys different.\n",
file1.GetFileName(), file2.GetFileName());
if (file1.GetSstCounter(leveldb::eSstCountValueSize)==file2.GetSstCounter(leveldb::eSstCountValueSize))
fprintf(stderr, "%s, %s: Byte size of all values different.\n",
file1.GetFileName(), file2.GetFileName());
error_seen=true;
} // else
} // if
else
{
if (!file1.GetStatus().ok())
fprintf(stderr, "%s: Input table open failed (%s)\n",
file1.GetFileName(), file1.GetStatus().ToString().c_str());
if (!file2.GetStatus().ok())
fprintf(stderr, "%s: Input table open failed (%s)\n",
file2.GetFileName(), file2.GetStatus().ToString().c_str());
error_seen=true;
} // else
} // if
else
{
fprintf(stderr, "%s: compare needs two file names, only have one\n",
fname.c_str());
} // else
} // else
} // else
} // for
// cleanup
options.env->Shutdown();
delete options.filter_policy;
if (1==argc)
command_help();
return( error_seen ? 1 : 0 );
} // main
void
command_help()
{
fprintf(stderr, "sst_rewrite [option | file]*\n");
fprintf(stderr, " options\n");
// fprintf(stderr, " -b print details about block\n");
fprintf(stderr, " -c compare next two files (inverse of -w)\n");
fprintf(stderr, " -w rewrite next file (default, inverse of -c)\n");
} // command_help
namespace leveldb {
} // namespace leveldb
<commit_msg>add description of new options to command_help()<commit_after>// -------------------------------------------------------------------
//
// sst_rewrite.cc
//
// Copyright (c) 2015 Basho Technologies, Inc. All Rights Reserved.
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// -------------------------------------------------------------------
#include <memory>
#include <stdio.h>
#include <stdlib.h>
//#include <libgen.h>
#include "leveldb/env.h"
#include "leveldb/filter_policy.h"
#include "leveldb/options.h"
#include "leveldb/table.h"
#include "leveldb/table_builder.h"
void command_help();
// wrapper class for opening / closing existing leveldb tables
class LDbTable
{
public:
LDbTable(leveldb::Options &, std::string &);
virtual ~LDbTable();
bool Ok() const {return(m_IsOpen);};
leveldb::Iterator * NewIterator();
const leveldb::Status & GetStatus() const {return(m_LastStatus);};
const char * GetFileName() const {return(m_FileName.c_str());};
uint64_t GetSstCounter(unsigned Idx) const
{return(m_IsOpen ? m_TablePtr->GetSstCounters().Value(Idx) : 0);};
protected:
leveldb::Options & m_Options;
const std::string m_FileName;
leveldb::RandomAccessFile * m_FilePtr;
leveldb::Table * m_TablePtr;
uint64_t m_FileSize;
leveldb::Status m_LastStatus;
bool m_IsOpen;
void Reset();
private:
// disable these
LDbTable();
LDbTable(const LDbTable &);
const LDbTable operator=(const LDbTable&);
}; // LDbTable
LDbTable::LDbTable(
leveldb::Options & Options,
std::string & FileName)
: m_Options(Options), m_FileName(FileName),
m_FilePtr(NULL), m_TablePtr(NULL), m_FileSize(0), m_IsOpen(false)
{
m_LastStatus=m_Options.env->GetFileSize(m_FileName, &m_FileSize);
if (m_LastStatus.ok())
{m_LastStatus=m_Options.env->NewRandomAccessFile(m_FileName, &m_FilePtr);}
if (m_LastStatus.ok())
{
m_LastStatus=leveldb::Table::Open(m_Options, m_FilePtr, m_FileSize, &m_TablePtr);
// use fadvise to start file pre-read
m_FilePtr->SetForCompaction(m_FileSize);
} // if
m_IsOpen=m_LastStatus.ok();
if (!m_IsOpen)
{
// some people would throw() at this point, but not me
Reset();
} // if
return;
} // LDbTable::LDbTable
LDbTable::~LDbTable()
{
Reset();
return;
} // LDbTable::~LDbTable
void
LDbTable::Reset()
{
m_IsOpen=false;
delete m_TablePtr;
m_TablePtr=NULL;
delete m_FilePtr;
m_FilePtr=NULL;
m_FileSize=0;
return;
} // LDbTable::Reset
leveldb::Iterator *
LDbTable::NewIterator()
{
leveldb::Iterator * ret_ptr(NULL);
if (m_IsOpen)
{
leveldb::ReadOptions read_options;
read_options.fill_cache=false;
ret_ptr=m_TablePtr->NewIterator(read_options);
} // if
return(ret_ptr);
} // LDbTable::NewIterator
int
main(
int argc,
char ** argv)
{
bool error_seen, running, compare_files;
char ** cursor;
compare_files=false;
error_seen=false;
running=true;
// Options: needs filter & total_leveldb_mem initialized
leveldb::Options options;
// using 16 bit width per key in bloom filter
options.filter_policy=leveldb::NewBloomFilterPolicy2(16);
// tell leveldb it can use 512Mbyte of memory
options.total_leveldb_mem=(512 << 20);
for (cursor=argv+1;
NULL!=*cursor && running && !error_seen;
++cursor)
{
// option flag?
if ('-'==**cursor)
{
char flag;
flag=*((*cursor)+1);
switch(flag)
{
case 'b':
{
error_seen=(NULL==(cursor+1));
if (!error_seen)
{options.block_size=atol(*(cursor+1));};
break;
} // case b
case 's': options.compression=leveldb::kSnappyCompression; break;
case 'z': options.compression=leveldb::kLZ4Compression; break;
case 'n': options.compression=leveldb::kNoCompression; break;
case 'c':
{
// test for first pair ... but after that user beware
error_seen=(NULL==(cursor+1)) || (NULL==(cursor+2));
if (!error_seen)
{compare_files=true;}
break;
} // case c
case 'w': compare_files=false; break;
default:
fprintf(stderr, " option \'%c\' is not valid\n", flag);
command_help();
running=false;
error_seen=true;
break;
} // switch
} // if
// sst file
else
{
std::string fname;
fname=*cursor;
// do a rewrite
if (!compare_files)
{
leveldb::WritableFile * outfile;
leveldb::Status s;
std::auto_ptr<leveldb::Iterator> it;
std::auto_ptr<leveldb::TableBuilder> builder;
LDbTable in_file(options, fname);
if (in_file.GetStatus().ok())
{
it.reset(in_file.NewIterator());
fname.append(".new");
s = options.env->NewWritableFile(fname, &outfile,
options.env->RecoveryMmapSize(&options));
if (s.ok())
builder.reset(new leveldb::TableBuilder(options, outfile));
else
{
// Table::Open failed on file "fname"
fprintf(stderr, "%s: NewWritableFile failed (%s)\n",
fname.c_str(), s.ToString().c_str());
error_seen=true;
} // else
for (it->SeekToFirst(); it->Valid() && s.ok(); it->Next())
{
leveldb::Slice key = it->key();
builder->Add(key, it->value());
} // for
// hmmm, nothing new setting status right now.
if (s.ok()) {
s = builder->Finish();
} else {
builder->Abandon();
}
if (NULL!=outfile)
outfile->Close();
delete outfile;
} // if
else
{
fprintf(stderr, "%s: Input table open failed (%s)\n",
fname.c_str(), in_file.GetStatus().ToString().c_str());
error_seen=true;
} // else
} // if
// compare two files
else
{
LDbTable file1(options, fname);
++cursor;
if (NULL!=*cursor)
{
fname=*cursor;
LDbTable file2(options, fname);
if (file1.GetStatus().ok() && file2.GetStatus().ok())
{
// quick check: same number of keys and bytes of user data?
// do this before reading entire files
if (file1.GetSstCounter(leveldb::eSstCountKeys)==file2.GetSstCounter(leveldb::eSstCountKeys)
&& file1.GetSstCounter(leveldb::eSstCountKeySize)==file2.GetSstCounter(leveldb::eSstCountKeySize)
&& file1.GetSstCounter(leveldb::eSstCountValueSize)==file2.GetSstCounter(leveldb::eSstCountValueSize))
{
leveldb::Iterator * it1, *it2;
uint64_t key_count;
bool match;
it1=file1.NewIterator();
it2=file2.NewIterator();
match=true;
for (it1->SeekToFirst(), it2->SeekToFirst(), key_count=1;
it1->Valid() && it2->Valid() && match;
it1->Next(), it2->Next(), ++key_count)
{
match=(0==it1->key().compare(it2->key())) && (0==it1->value().compare(it2->value()));
if (!match)
{
fprintf(stderr, "%s, %s: Content mismatch at key position %d (%d, %d).\n",
file1.GetFileName(), file2.GetFileName(),
(int)key_count,
it1->key().compare(it2->key()), it1->value().compare(it2->value()));
error_seen=true;
} // if
} // for
if (it1->Valid() != it2->Valid())
{
fprintf(stderr, "%s, %s: Walk of keys terminated early (%d, %d).\n",
file1.GetFileName(), file2.GetFileName(),
(int)it1->Valid(), (int)it2->Valid());
error_seen=true;
}
} // if
else
{
if (file1.GetSstCounter(leveldb::eSstCountKeys)==file2.GetSstCounter(leveldb::eSstCountKeys))
fprintf(stderr, "%s, %s: Number of keys different, %ld vs %ld.\n",
file1.GetFileName(), file2.GetFileName(),
file1.GetSstCounter(leveldb::eSstCountKeys),
file2.GetSstCounter(leveldb::eSstCountKeys));
if (file1.GetSstCounter(leveldb::eSstCountKeySize)==file2.GetSstCounter(leveldb::eSstCountKeySize))
fprintf(stderr, "%s, %s: Byte size of all keys different, %ld vs %ld\n",
file1.GetFileName(), file2.GetFileName(),
file1.GetSstCounter(leveldb::eSstCountKeySize),
file2.GetSstCounter(leveldb::eSstCountKeySize));
if (file1.GetSstCounter(leveldb::eSstCountValueSize)==file2.GetSstCounter(leveldb::eSstCountValueSize))
fprintf(stderr, "%s, %s: Byte size of all values different, %ld vs %ld\n",
file1.GetFileName(), file2.GetFileName(),
file1.GetSstCounter(leveldb::eSstCountValueSize),
file2.GetSstCounter(leveldb::eSstCountValueSize));
error_seen=true;
} // else
} // if
else
{
if (!file1.GetStatus().ok())
fprintf(stderr, "%s: Input table open failed (%s)\n",
file1.GetFileName(), file1.GetStatus().ToString().c_str());
if (!file2.GetStatus().ok())
fprintf(stderr, "%s: Input table open failed (%s)\n",
file2.GetFileName(), file2.GetStatus().ToString().c_str());
error_seen=true;
} // else
} // if
else
{
fprintf(stderr, "%s: compare needs two file names, only have one\n",
fname.c_str());
} // else
} // else
} // else
} // for
// cleanup
options.env->Shutdown();
delete options.filter_policy;
if (1==argc)
command_help();
return( error_seen ? 1 : 0 );
} // main
void
command_help()
{
fprintf(stderr, "sst_rewrite [option | file]*\n");
fprintf(stderr, " options\n");
fprintf(stderr, " -b value set Options.block_size to value\n");
fprintf(stderr, " -n set Options.compression to No compression\n");
fprintf(stderr, " -s set Options.compression to Snappy compression\n");
fprintf(stderr, " -z set Options.compression to LZ4 compression\n");
fprintf(stderr, " -c compare next two files (inverse of -w)\n");
fprintf(stderr, " -w rewrite next file (default, inverse of -c)\n");
} // command_help
namespace leveldb {
} // namespace leveldb
<|endoftext|> |
<commit_before>#ifndef BUFFER_CACHE_BLOB_HPP_
#define BUFFER_CACHE_BLOB_HPP_
#include <string>
#include <vector>
#include <stdint.h>
#include <stddef.h>
#include "errors.hpp"
#include <boost/shared_ptr.hpp>
#include "buffer_cache/types.hpp"
#include "concurrency/access.hpp"
#include "containers/buffer_group.hpp"
/* An explanation of blobs.
If we want to store values larger than 250 bytes, we must split
them into large numbers of blocks. Some kind of tree structure is
used. The blob_t type handles both kinds of values. Here's how it's used.
const int mrl = 251;
std::string x = ...;
// value_in_leafnode does not point to a buffer that has 251 bytes you can use.
char *ref = get_blob_ref_from_something();
// Create a buffer of the maxreflen
char tmp[mrl];
memcpy(tmp, ref, blob::ref_size(bs, ref, mrl));
{
blob_t b(tmp, mrl);
int64_t old_size = b.valuesize();
tmp.append_region(txn, x.size());
{
// group holds pointers to buffers. acq maintains the buf_lock_t
// ownership itself. You cannot use group outside the
// lifetime of acq.
blob_acq_t acq;
buffer_group_t group;
tmp.expose_region(txn, rwi_write, old_size, x.size(), &group, &acq);
copy_string_to_buffer_group(&group, x);
}
}
// The ref size changed because we modified the blob.
write_blob_ref_to_something(tmp, blob::ref_size(bs, ref, mrl));
*/
typedef uint32_t block_id_t;
class buffer_group_t;
class block_getter_t;
// Represents an acquisition of buffers owned by the blob.
class blob_acq_t {
public:
blob_acq_t() { }
~blob_acq_t();
void add_buf(buf_lock_t *buf) {
bufs_.push_back(buf);
}
private:
std::vector<buf_lock_t *> bufs_;
// disable copying
blob_acq_t(const blob_acq_t&);
void operator=(const blob_acq_t&);
};
union temporary_acq_tree_node_t;
namespace blob {
struct traverse_helper_t;
// Returns the number of bytes actually used by the blob reference.
// Returns a value in the range [1, maxreflen].
int ref_size(block_size_t block_size, const char *ref, int maxreflen);
// Returns true if the size of the blob reference is less than or
// equal to data_length, only reading memory in the range [ref, ref +
// data_length).
bool ref_fits(block_size_t block_size, int data_length, const char *ref, int maxreflen);
// Returns what the maxreflen would be, given the desired number of
// block ids in the blob ref.
int maxreflen_from_blockid_count(int count);
// The step size of a blob.
int64_t stepsize(block_size_t block_size, int levels);
// The internal node block ids of an internal node.
const block_id_t *internal_node_block_ids(const void *buf);
// Returns offset and size, clamped to and relative to the index'th subtree.
void shrink(block_size_t block_size, int levels, int64_t offset, int64_t size, int index, int64_t *suboffset_out, int64_t *subsize_out);
// The maxreflen value appropriate for use with memcached btrees. It's 251. This should be renamed.
extern int btree_maxreflen;
// The size of a blob, equivalent to blob_t(ref, maxreflen).valuesize().
int64_t value_size(const char *ref, int maxreflen);
struct ref_info_t {
// The ref_size of a ref.
int refsize;
// the number of levels in the underlying tree of buffers.
int levels;
};
ref_info_t ref_info(block_size_t block_size, const char *ref, int maxreflen);
// Returns the internal block ids of a non-inlined blob ref.
const block_id_t *block_ids(const char *ref, int maxreflen);
// Returns the char bytes of a leaf node.
const char *leaf_node_data(const void *buf);
// Returns the internal offset of the ref value, which is especially useful when it's not inlined.
int64_t ref_value_offset(const char *ref, int maxreflen);
extern block_magic_t internal_node_magic;
extern block_magic_t leaf_node_magic;
bool deep_fsck(block_getter_t *getter, block_size_t bs, const char *ref, int maxreflen, std::string *msg_out);
} // namespace blob
class blob_t {
public:
//Used to iterate over an exposed region of a blob
class iterator {
public:
iterator(boost::shared_ptr<buffer_group_t>, boost::shared_ptr<blob_acq_t>);
iterator(const iterator &);
char& operator*();
void operator++();
bool at_end();
private:
void increment_buffer();
boost::shared_ptr<buffer_group_t> bg;
boost::shared_ptr<blob_acq_t> acq;
buffer_group_t::buffer_t current_buffer;
unsigned cur_buffer_index;
unsigned next_buffer;
};
// maxreflen must be less than the block size minus 4 bytes.
blob_t(char *ref, int maxreflen);
// Returns ref_size(block_size, ref, maxreflen), the number of
// bytes actually used in the blob ref. A value in the internal
// [1, maxreflen_].
int refsize(block_size_t block_size) const;
// Returns the actual size of the value, some number >= 0 and less
// than one gazillion.
int64_t valuesize() const;
// Acquires internal buffers and copies pointers to internal
// buffers to the buffer_group_t, initializing acq_group_out so
// that it holds the acquisition of such buffers. acq_group_out
// must not be destroyed until the buffers are finished being
// used.
void expose_region(transaction_t *txn, access_t mode, int64_t offset, int64_t size, buffer_group_t *buffer_group_out, blob_acq_t *acq_group_out);
void expose_all(transaction_t *txn, access_t mode, buffer_group_t *buffer_group_out, blob_acq_t *acq_group_out);
// Alternate interface that returns an iterator to the exposed region.
iterator expose_region(transaction_t *txn, access_t mode, int64_t offset, int64_t size);
// Appends size bytes of garbage data to the blob.
void append_region(transaction_t *txn, int64_t size);
// Prepends size bytes of garbage data to the blob.
void prepend_region(transaction_t *txn, int64_t size);
// Removes size bytes of data from the end of the blob. size must
// be <= valuesize().
void unappend_region(transaction_t *txn, int64_t size);
// Removes size bytes of data from the beginning of the blob.
// size must be <= valuesize().
void unprepend_region(transaction_t *txn, int64_t size);
// Empties the blob, making its valuesize() be zero. Equivalent
// to unappend_region(txn, valuesize()) or unprepend_region(txn,
// valuesize()). In particular, you can be sure that the blob
// holds no internal blocks, once it has been cleared.
void clear(transaction_t *txn);
// Writes over the portion of the blob, starting at offset, with
// the contents of the string val. Caller is responsible for making
// sure this portion of the blob exists
void write_from_string(const std::string &val, transaction_t *txn, int64_t offset);
// Reads from the region of the blob from offset to offset + length into the string s_out
void read_to_string(std::string &s_out, transaction_t *txn, int64_t offset, int64_t length);
private:
bool traverse_to_dimensions(transaction_t *txn, int levels, int64_t old_offset, int64_t old_size, int64_t new_offset, int64_t new_size, blob::traverse_helper_t *helper);
bool allocate_to_dimensions(transaction_t *txn, int levels, int64_t new_offset, int64_t new_size);
bool shift_at_least(transaction_t *txn, int levels, int64_t min_shift);
void consider_big_shift(transaction_t *txn, int levels, int64_t *min_shift);
void consider_small_shift(transaction_t *txn, int levels, int64_t *min_shift);
void deallocate_to_dimensions(transaction_t *txn, int levels, int64_t new_offset, int64_t new_size);
int add_level(transaction_t *txn, int levels);
bool remove_level(transaction_t *txn, int *levels_ref);
char *ref_;
int maxreflen_;
// disable copying
blob_t(const blob_t&);
void operator=(const blob_t&);
};
#endif // BUFFER_CACHE_BLOB_HPP_
<commit_msg>Removed unimplemented unused blob_t::iterator nonsense.<commit_after>#ifndef BUFFER_CACHE_BLOB_HPP_
#define BUFFER_CACHE_BLOB_HPP_
#include <string>
#include <vector>
#include <stdint.h>
#include <stddef.h>
#include "errors.hpp"
#include <boost/shared_ptr.hpp>
#include "buffer_cache/types.hpp"
#include "concurrency/access.hpp"
#include "containers/buffer_group.hpp"
/* An explanation of blobs.
If we want to store values larger than 250 bytes, we must split
them into large numbers of blocks. Some kind of tree structure is
used. The blob_t type handles both kinds of values. Here's how it's used.
const int mrl = 251;
std::string x = ...;
// value_in_leafnode does not point to a buffer that has 251 bytes you can use.
char *ref = get_blob_ref_from_something();
// Create a buffer of the maxreflen
char tmp[mrl];
memcpy(tmp, ref, blob::ref_size(bs, ref, mrl));
{
blob_t b(tmp, mrl);
int64_t old_size = b.valuesize();
tmp.append_region(txn, x.size());
{
// group holds pointers to buffers. acq maintains the buf_lock_t
// ownership itself. You cannot use group outside the
// lifetime of acq.
blob_acq_t acq;
buffer_group_t group;
tmp.expose_region(txn, rwi_write, old_size, x.size(), &group, &acq);
copy_string_to_buffer_group(&group, x);
}
}
// The ref size changed because we modified the blob.
write_blob_ref_to_something(tmp, blob::ref_size(bs, ref, mrl));
*/
typedef uint32_t block_id_t;
class buffer_group_t;
class block_getter_t;
// Represents an acquisition of buffers owned by the blob.
class blob_acq_t {
public:
blob_acq_t() { }
~blob_acq_t();
void add_buf(buf_lock_t *buf) {
bufs_.push_back(buf);
}
private:
std::vector<buf_lock_t *> bufs_;
// disable copying
blob_acq_t(const blob_acq_t&);
void operator=(const blob_acq_t&);
};
union temporary_acq_tree_node_t;
namespace blob {
struct traverse_helper_t;
// Returns the number of bytes actually used by the blob reference.
// Returns a value in the range [1, maxreflen].
int ref_size(block_size_t block_size, const char *ref, int maxreflen);
// Returns true if the size of the blob reference is less than or
// equal to data_length, only reading memory in the range [ref, ref +
// data_length).
bool ref_fits(block_size_t block_size, int data_length, const char *ref, int maxreflen);
// Returns what the maxreflen would be, given the desired number of
// block ids in the blob ref.
int maxreflen_from_blockid_count(int count);
// The step size of a blob.
int64_t stepsize(block_size_t block_size, int levels);
// The internal node block ids of an internal node.
const block_id_t *internal_node_block_ids(const void *buf);
// Returns offset and size, clamped to and relative to the index'th subtree.
void shrink(block_size_t block_size, int levels, int64_t offset, int64_t size, int index, int64_t *suboffset_out, int64_t *subsize_out);
// The maxreflen value appropriate for use with memcached btrees. It's 251. This should be renamed.
extern int btree_maxreflen;
// The size of a blob, equivalent to blob_t(ref, maxreflen).valuesize().
int64_t value_size(const char *ref, int maxreflen);
struct ref_info_t {
// The ref_size of a ref.
int refsize;
// the number of levels in the underlying tree of buffers.
int levels;
};
ref_info_t ref_info(block_size_t block_size, const char *ref, int maxreflen);
// Returns the internal block ids of a non-inlined blob ref.
const block_id_t *block_ids(const char *ref, int maxreflen);
// Returns the char bytes of a leaf node.
const char *leaf_node_data(const void *buf);
// Returns the internal offset of the ref value, which is especially useful when it's not inlined.
int64_t ref_value_offset(const char *ref, int maxreflen);
extern block_magic_t internal_node_magic;
extern block_magic_t leaf_node_magic;
bool deep_fsck(block_getter_t *getter, block_size_t bs, const char *ref, int maxreflen, std::string *msg_out);
} // namespace blob
class blob_t {
public:
// maxreflen must be less than the block size minus 4 bytes.
blob_t(char *ref, int maxreflen);
// Returns ref_size(block_size, ref, maxreflen), the number of
// bytes actually used in the blob ref. A value in the internal
// [1, maxreflen_].
int refsize(block_size_t block_size) const;
// Returns the actual size of the value, some number >= 0 and less
// than one gazillion.
int64_t valuesize() const;
// Acquires internal buffers and copies pointers to internal
// buffers to the buffer_group_t, initializing acq_group_out so
// that it holds the acquisition of such buffers. acq_group_out
// must not be destroyed until the buffers are finished being
// used.
void expose_region(transaction_t *txn, access_t mode, int64_t offset, int64_t size, buffer_group_t *buffer_group_out, blob_acq_t *acq_group_out);
void expose_all(transaction_t *txn, access_t mode, buffer_group_t *buffer_group_out, blob_acq_t *acq_group_out);
// Appends size bytes of garbage data to the blob.
void append_region(transaction_t *txn, int64_t size);
// Prepends size bytes of garbage data to the blob.
void prepend_region(transaction_t *txn, int64_t size);
// Removes size bytes of data from the end of the blob. size must
// be <= valuesize().
void unappend_region(transaction_t *txn, int64_t size);
// Removes size bytes of data from the beginning of the blob.
// size must be <= valuesize().
void unprepend_region(transaction_t *txn, int64_t size);
// Empties the blob, making its valuesize() be zero. Equivalent
// to unappend_region(txn, valuesize()) or unprepend_region(txn,
// valuesize()). In particular, you can be sure that the blob
// holds no internal blocks, once it has been cleared.
void clear(transaction_t *txn);
// Writes over the portion of the blob, starting at offset, with
// the contents of the string val. Caller is responsible for making
// sure this portion of the blob exists
void write_from_string(const std::string &val, transaction_t *txn, int64_t offset);
// Reads from the region of the blob from offset to offset + length into the string s_out
void read_to_string(std::string &s_out, transaction_t *txn, int64_t offset, int64_t length);
private:
bool traverse_to_dimensions(transaction_t *txn, int levels, int64_t old_offset, int64_t old_size, int64_t new_offset, int64_t new_size, blob::traverse_helper_t *helper);
bool allocate_to_dimensions(transaction_t *txn, int levels, int64_t new_offset, int64_t new_size);
bool shift_at_least(transaction_t *txn, int levels, int64_t min_shift);
void consider_big_shift(transaction_t *txn, int levels, int64_t *min_shift);
void consider_small_shift(transaction_t *txn, int levels, int64_t *min_shift);
void deallocate_to_dimensions(transaction_t *txn, int levels, int64_t new_offset, int64_t new_size);
int add_level(transaction_t *txn, int levels);
bool remove_level(transaction_t *txn, int *levels_ref);
char *ref_;
int maxreflen_;
// disable copying
blob_t(const blob_t&);
void operator=(const blob_t&);
};
#endif // BUFFER_CACHE_BLOB_HPP_
<|endoftext|> |
<commit_before>#ifndef QRW_TEST_WALLACCESSSTRUCTUREMOCK_HPP
#define QRW_TEST_WALLACCESSSTRUCTUREMOCK_HPP
#include "game/skirmish/wallaccessstructurebase.hpp"
class WallAccessStructureMock : public qrw::WallAccessStructureBase
{
public:
const sf::Texture* getTexture() const override
{
throw "Not implemented";
}
public:
const qrw::SID& getTypeName() const override
{
throw "Not implemented";
}
};
#endif //QRW_TEST_WALLACCESSSTRUCTUREMOCK_HPP
<commit_msg>Fix tests by implementing pure virtual method in mock<commit_after>#ifndef QRW_TEST_WALLACCESSSTRUCTUREMOCK_HPP
#define QRW_TEST_WALLACCESSSTRUCTUREMOCK_HPP
#include "game/skirmish/wallaccessstructurebase.hpp"
class WallAccessStructureMock : public qrw::WallAccessStructureBase
{
public:
const sf::Texture* getTexture() const override
{
throw "Not implemented";
}
void setFlatMode(bool isFlatMode) override {
throw "Not implemented";
}
public:
const qrw::SID& getTypeName() const override
{
throw "Not implemented";
}
};
#endif //QRW_TEST_WALLACCESSSTRUCTUREMOCK_HPP
<|endoftext|> |
<commit_before>//
// Graph.cpp
// zombies
//
// Created by Sunil on 4/17/17.
// Copyright © 2017 Sunil. All rights reserved.
//
#include "Graph.h"
#include <set>
#include <map>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
template <class T>
Graph<T>::Graph() {
}
template <class T>
Graph<T>::~Graph() {
//dtor
}
template <class T>
void Graph<T>::addEdge(T v1, T v2, int weight) {
if (weight == -1) {
// no edge. ignore
return;
}
for (int i = 0; i < vertices.size(); i++) {
if(vertices[i].name != v1)
continue;
for (int j = 0; j < vertices.size(); j++) {
if(vertices[j].name != v2 || i == j) continue;
adjVertex<T> av;
av.v = &vertices[j];
av.weight = weight;
vertices[i].adj.push_back(av);
//add edge in the other direction
//vertices[i].adj.push_back(av);
//another vertex for edge in other direction
//adjVertex<T> av2;
//av2.v = &vertices[i];
//av2.weight = weight;
//vertices[j].adj.push_back(av2);
}
}
}
template <class T>
void Graph<T>::addVertex(T n) {
bool found = false;
for (int i = 0; i < vertices.size(); i++) {
if (vertices[i].name == n) {
found = true;
cout << vertices[i].name << " found." << endl;
}
}
if (found == false){
vertex<T> v;
v.name = n;
vertices.push_back(v);
}
}
template <class T>
void Graph<T>::displayEdges(){
//loop through all vertices and adjacent vertices
for (auto& city : vertices) {
cout << city.name << "-->";
for (auto& adjCity : city.adj) {
cout << adjCity.v->name << "***";
}
cout << endl;
}
}
template <class T>
void Graph<T>::displayVertices() {
for (auto& city : vertices) {
cout << city.districtId << ":" << city.name << "->";
auto hasMultipleEntries = false;
// print the adjacent cities.
for (auto& adjCity : city.adj) {
if (adjCity.weight == -1) continue;
if (hasMultipleEntries) cout << "**";
cout << adjCity.v->name;
hasMultipleEntries = true;
}
cout << endl;
}
}
template <class T>
void Graph<T>::assignDistrictIds() {
int districtId = 1;
for (auto& city : vertices) {
// check if this city has district id assigned.
if (city.districtId == -1) {
// if district id not assigned, then do bfs to assign id to
// it's connected cities.
bfsAssignId(city, districtId);
// increment the id
districtId++;
}
}
}
template <class T>
void Graph<T>::bfsAssignId(vertex<T>& city, int id) {
// do a bfs iterative traversal.
// very important to have a queue of pointers.
// otherwise district id would be assigned only to local copies.
deque<vertex<T>*> queue;
queue.push_back(&city);
while(!queue.empty()) {
auto city = queue.front();
queue.pop_front();
city->districtId = id;
for (auto& adjCity : city->adj) {
// ignore the current city.
// Verify: Is this taken care while adding a edge ?
if (adjCity.v->name == city->name) {
continue;
}
// Add the adjacent city if it doesn't have a district id assigned.
// I could have used a variable like visited in vertex to track if it's
// already visited or not. But i can get away with checking district id.
if (adjCity.v->districtId == -1) {
queue.push_back(adjCity.v);
}
}
}
}
template <class T>
vertex<T>* Graph<T>::findCity(string cityName) {
// use stl algorithm find_if with lambda expression to specify search criteria
auto iter = std::find_if(begin(vertices), end(vertices), [&cityName](vertex<T>& item) {
return item.name == cityName;
});
auto found = iter != end(vertices) ? &(*iter) : nullptr;
return found;
}
template <class T>
void Graph<T>::findShortestPath(std::string src, std::string dest) {
auto srcCity = findCity(src);
auto destCity = findCity(dest);
if (!srcCity || !destCity) {
// One or both cities not found:
cout << "One or more cities doesn't exist" << endl;
return;
}
if (srcCity->districtId == -1 || destCity->districtId == -1) {
// Districts not set yet
cout << "Please identify the districts before checking distances" << endl;
return;
}
if (srcCity->districtId != destCity->districtId) {
// Cities in different districts:
cout << "No safe path between cities" << endl;
return;
}
// if source and dest are same. Nothing to do.
if (srcCity->name == destCity->name) {
cout << "0, " << src << ", " << dest << endl;
return;
}
// run a dijkstra's algorithm here to find the shortest path.
dijkstra(src, dest);
}
template <class T>
int Graph<T>::length(vertex<T>* u, string v) {
for (auto adjCity : u->adj) {
if (adjCity.v->name == v) {
auto weight = adjCity.weight;
return weight == -1 ? INFINITY : weight;
}
}
return INFINITY;
}
template <class T>
void Graph<T>::dijkstra(string dest, string src) {
// I swap the parameters to get the output in right format.
// By swapping src, dest. It doesn't change anything.
// cout << "Run dijkstra's algorithm here" << endl;
// reference: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
map<string, int> dist;
map<string, string> prev;
set<vertex<T>*> q;
// Initialization
for (auto& v : vertices) {
dist[v.name] = INFINITY; // Unknown distance from source to v
prev[v.name] = UNDEFINED; // Previous node in optimal path from source
q.insert(&v); // All nodes initially in Q (unvisited nodes)
}
// Distance from source to source
dist[src] = 0;
auto minDist = [](set<vertex<T>*> q, map<string, int> dist) {
vertex<T>* min = nullptr;
auto d = INFINITY;
for (auto e : q) {
if (!min) {
min = e;
d = INFINITY;
}
if (dist[e->name] < d) {
d = dist[e->name];
min = e;
}
}
return min;
};
while (!q.empty()) {
// Node with the least distance will be selected first
auto u = minDist(q, dist);
if (u->name == dest) {
break;
}
q.erase(u);
// where v is still in Q.
for (auto& adj : u->adj) {
auto v = adj.v->name;
auto alt = dist[u->name] + length(u, v);
if (alt < dist[v]) {
dist[v] = alt;
prev[v] = u->name;
}
}
}
auto u = dest;
// print distance.
cout << dist[u] << ", ";
// Now we can read the shortest path from
// source to target by reverse iteration.
while (prev[u] != UNDEFINED) {
cout << u << ", ";
u = prev[u];
}
cout << u << endl;
}
<commit_msg>clean up<commit_after>//
// Graph.cpp
// zombies
//
// Created by Sunil on 4/17/17.
// Copyright © 2017 Sunil. All rights reserved.
//
#include "Graph.h"
#include <set>
#include <map>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
template <class T>
Graph<T>::Graph() {
}
template <class T>
Graph<T>::~Graph() {
//dtor
}
template <class T>
void Graph<T>::addEdge(T v1, T v2, int weight) {
if (weight == -1) {
// no edge. ignore
return;
}
for (int i = 0; i < vertices.size(); i++) {
if(vertices[i].name != v1)
continue;
for (int j = 0; j < vertices.size(); j++) {
if(vertices[j].name != v2 || i == j) continue;
adjVertex<T> av;
av.v = &vertices[j];
av.weight = weight;
vertices[i].adj.push_back(av);
//add edge in the other direction
//vertices[i].adj.push_back(av);
//another vertex for edge in other direction
//adjVertex<T> av2;
//av2.v = &vertices[i];
//av2.weight = weight;
//vertices[j].adj.push_back(av2);
}
}
}
template <class T>
void Graph<T>::addVertex(T n) {
bool found = false;
for (int i = 0; i < vertices.size(); i++) {
if (vertices[i].name == n) {
found = true;
cout << vertices[i].name << " found." << endl;
}
}
if (found == false){
vertex<T> v;
v.name = n;
vertices.push_back(v);
}
}
template <class T>
void Graph<T>::displayEdges(){
//loop through all vertices and adjacent vertices
for (auto& city : vertices) {
cout << city.name << "-->";
for (auto& adjCity : city.adj) {
cout << adjCity.v->name << "***";
}
cout << endl;
}
}
template <class T>
void Graph<T>::displayVertices() {
for (auto& city : vertices) {
cout << city.districtId << ":" << city.name << "->";
auto hasMultipleEntries = false;
// print the adjacent cities.
for (auto& adjCity : city.adj) {
if (adjCity.weight == -1) continue;
if (hasMultipleEntries) cout << "**";
cout << adjCity.v->name;
hasMultipleEntries = true;
}
cout << endl;
}
}
template <class T>
void Graph<T>::assignDistrictIds() {
int districtId = 1;
for (auto& city : vertices) {
// check if this city has district id assigned.
if (city.districtId == -1) {
// if district id not assigned, then do bfs to assign id to
// it's connected cities.
bfsAssignId(city, districtId);
// increment the id
districtId++;
}
}
}
template <class T>
void Graph<T>::bfsAssignId(vertex<T>& city, int id) {
// do a bfs iterative traversal.
// very important to have a queue of pointers.
// otherwise district id would be assigned only to local copies.
deque<vertex<T>*> queue;
queue.push_back(&city);
while(!queue.empty()) {
auto city = queue.front();
queue.pop_front();
city->districtId = id;
for (auto& adjCity : city->adj) {
// ignore the current city.
// Verify: Is this taken care while adding a edge ?
if (adjCity.v->name == city->name) {
continue;
}
// Add the adjacent city if it doesn't have a district id assigned.
// I could have used a variable like visited in vertex to track if it's
// already visited or not. But i can get away with checking district id.
if (adjCity.v->districtId == -1) {
queue.push_back(adjCity.v);
}
}
}
}
template <class T>
vertex<T>* Graph<T>::findCity(string cityName) {
// use stl algorithm find_if with lambda expression to specify search criteria
auto iter = std::find_if(begin(vertices), end(vertices), [&cityName](vertex<T>& item) {
return item.name == cityName;
});
auto found = iter != end(vertices) ? &(*iter) : nullptr;
return found;
}
template <class T>
void Graph<T>::findShortestPath(std::string src, std::string dest) {
auto srcCity = findCity(src);
auto destCity = findCity(dest);
if (!srcCity || !destCity) {
// One or both cities not found:
cout << "One or more cities doesn't exist" << endl;
return;
}
if (srcCity->districtId == -1 || destCity->districtId == -1) {
// Districts not set yet
cout << "Please identify the districts before checking distances" << endl;
return;
}
if (srcCity->districtId != destCity->districtId) {
// Cities in different districts:
cout << "No safe path between cities" << endl;
return;
}
// if source and dest are same. Nothing to do.
if (srcCity->name == destCity->name) {
cout << "0, " << src << ", " << dest << endl;
return;
}
// run a dijkstra's algorithm here to find the shortest path.
dijkstra(src, dest);
}
template <class T>
int Graph<T>::length(vertex<T>* u, string v) {
for (auto adjCity : u->adj) {
if (adjCity.v->name == v) {
auto weight = adjCity.weight;
return weight == -1 ? INFINITY : weight;
}
}
return INFINITY;
}
template <class T>
void Graph<T>::dijkstra(string dest, string src) {
// I swap the parameters to get the output in right format.
// By swapping src, dest. It doesn't change anything.
// cout << "Run dijkstra's algorithm here" << endl;
// reference: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
map<string, int> dist;
map<string, string> prev;
set<vertex<T>*> q;
// Initialization
for (auto& v : vertices) {
dist[v.name] = INFINITY; // Unknown distance from source to v
prev[v.name] = UNDEFINED; // Previous node in optimal path from source
q.insert(&v); // All nodes initially in Q (unvisited nodes)
}
// Distance from source to source
dist[src] = 0;
auto minDist = [](set<vertex<T>*> q, map<string, int> dist) {
vertex<T>* min = nullptr;
auto d = INFINITY;
for (auto e : q) {
if (!min) {
min = e;
d = INFINITY;
}
if (dist[e->name] < d) {
d = dist[e->name];
min = e;
}
}
return min;
};
while (!q.empty()) {
// Node with the least distance will be selected first
auto u = minDist(q, dist);
if (u->name == dest) {
break;
}
q.erase(u);
// where v is still in Q.
for (auto& adj : u->adj) {
auto v = adj.v->name;
auto alt = dist[u->name] + length(u, v);
if (alt < dist[v]) {
dist[v] = alt;
prev[v] = u->name;
}
}
}
auto u = dest;
// print distance.
cout << dist[u] << ", ";
// Now we can read the shortest path from
// source to target by reverse iteration.
while (prev[u] != UNDEFINED) {
cout << u << ", ";
u = prev[u];
}
cout << u << endl;
}
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <kinematic_constraints/kinematic_constraint.h>
#include <gtest/gtest.h>
class LoadPlanningModelsPr2 : public testing::Test
{
protected:
virtual void SetUp()
{
urdf_model.reset(new urdf::Model());
srdf_model.reset(new srdf::Model());
urdf_model->initFile("../planning_models/test/urdf/robot.xml");
kmodel.reset(new planning_models::KinematicModel(urdf_model, srdf_model));
};
virtual void TearDown()
{
}
protected:
boost::shared_ptr<urdf::Model> urdf_model;
boost::shared_ptr<srdf::Model> srdf_model;
planning_models::KinematicModelPtr kmodel;
};
TEST_F(LoadPlanningModelsPr2, JointConstraintsSimple)
{
planning_models::KinematicState ks(kmodel);
ks.setToDefaultValues();
planning_models::TransformsPtr tf(new planning_models::Transforms(kmodel->getModelFrame()));
kinematic_constraints::JointConstraint jc(kmodel, tf);
moveit_msgs::JointConstraint jcm;
jcm.joint_name = "head_pan_joint";
jcm.position = 0.4;
jcm.tolerance_above = 0.1;
jcm.tolerance_below = 0.05;
jcm.weight = 1.0;
EXPECT_TRUE(jc.configure(jcm));
kinematic_constraints::ConstraintEvaluationResult p1 = jc.decide(ks);
EXPECT_FALSE(p1.satisfied);
EXPECT_NEAR(p1.distance, jcm.position, 1e-6);
std::map<std::string, double> jvals;
jvals[jcm.joint_name] = 0.41;
ks.setStateValues(jvals);
kinematic_constraints::ConstraintEvaluationResult p2 = jc.decide(ks);
EXPECT_TRUE(p2.satisfied);
EXPECT_NEAR(p2.distance, 0.01, 1e-6);
jvals[jcm.joint_name] = 0.46;
ks.setStateValues(jvals);
EXPECT_TRUE(jc.decide(ks).satisfied);
jvals[jcm.joint_name] = 0.501;
ks.setStateValues(jvals);
EXPECT_FALSE(jc.decide(ks).satisfied);
jvals[jcm.joint_name] = 0.39;
ks.setStateValues(jvals);
EXPECT_TRUE(jc.decide(ks).satisfied);
jvals[jcm.joint_name] = 0.34;
ks.setStateValues(jvals);
EXPECT_FALSE(jc.decide(ks).satisfied);
EXPECT_TRUE(jc.equal(jc, 1e-12));
}
TEST_F(LoadPlanningModelsPr2, JointConstraintsCont)
{
planning_models::KinematicState ks(kmodel);
ks.setToDefaultValues();
planning_models::TransformsPtr tf(new planning_models::Transforms(kmodel->getModelFrame()));
kinematic_constraints::JointConstraint jc(kmodel, tf);
moveit_msgs::JointConstraint jcm;
jcm.joint_name = "l_wrist_roll_joint";
jcm.position = 3.14;
jcm.tolerance_above = 0.04;
jcm.tolerance_below = 0.02;
jcm.weight = 1.0;
EXPECT_TRUE(jc.configure(jcm));
std::map<std::string, double> jvals;
jvals[jcm.joint_name] = 3.17;
ks.setStateValues(jvals);
kinematic_constraints::ConstraintEvaluationResult p1 = jc.decide(ks);
EXPECT_TRUE(p1.satisfied);
EXPECT_NEAR(p1.distance, 0.03, 1e-6);
jvals[jcm.joint_name] = -3.14;
ks.setStateValues(jvals);
kinematic_constraints::ConstraintEvaluationResult p2 = jc.decide(ks);
EXPECT_TRUE(p2.satisfied);
EXPECT_NEAR(p2.distance, 0.003185, 1e-4);
}
TEST_F(LoadPlanningModelsPr2, PositionConstraintsFixed)
{
planning_models::KinematicState ks(kmodel);
ks.setToDefaultValues();
planning_models::TransformsPtr tf(new planning_models::Transforms(kmodel->getModelFrame()));
kinematic_constraints::PositionConstraint pc(kmodel, tf);
moveit_msgs::PositionConstraint pcm;
pcm.link_name = "l_wrist_roll_link";
pcm.target_point_offset.x = 0;
pcm.target_point_offset.y = 0;
pcm.target_point_offset.z = 0;
pcm.constraint_region.primitives.resize(1);
pcm.constraint_region.primitives[0].type = shape_msgs::SolidPrimitive::SPHERE;
pcm.constraint_region.primitives[0].dimensions.x = 0.2;
pcm.header.frame_id = kmodel->getModelFrame();
pcm.constraint_region.primitive_poses.resize(1);
pcm.constraint_region.primitive_poses[0].position.x = 0.55;
pcm.constraint_region.primitive_poses[0].position.y = 0.2;
pcm.constraint_region.primitive_poses[0].position.z = 1.25;
pcm.constraint_region.primitive_poses[0].orientation.x = 0.0;
pcm.constraint_region.primitive_poses[0].orientation.y = 0.0;
pcm.constraint_region.primitive_poses[0].orientation.z = 0.0;
pcm.constraint_region.primitive_poses[0].orientation.w = 1.0;
pcm.weight = 1.0;
EXPECT_TRUE(pc.configure(pcm));
EXPECT_TRUE(pc.decide(ks).satisfied);
std::map<std::string, double> jvals;
jvals["torso_lift_joint"] = 0.4;
ks.setStateValues(jvals);
EXPECT_FALSE(pc.decide(ks).satisfied);
EXPECT_TRUE(pc.equal(pc, 1e-12));
}
TEST_F(LoadPlanningModelsPr2, PositionConstraintsMobile)
{
planning_models::KinematicState ks(kmodel);
ks.setToDefaultValues();
planning_models::TransformsPtr tf(new planning_models::Transforms(kmodel->getModelFrame()));
kinematic_constraints::PositionConstraint pc(kmodel, tf);
moveit_msgs::PositionConstraint pcm;
pcm.link_name = "l_wrist_roll_link";
pcm.target_point_offset.x = 0;
pcm.target_point_offset.y = 0;
pcm.target_point_offset.z = 0;
pcm.constraint_region.primitives.resize(1);
pcm.constraint_region.primitives[0].type = shape_msgs::SolidPrimitive::SPHERE;
pcm.constraint_region.primitives[0].dimensions.x = 0.38 * 2.0;
pcm.header.frame_id = "r_wrist_roll_link";
pcm.constraint_region.primitive_poses.resize(1);
pcm.constraint_region.primitive_poses[0].position.x = 0.0;
pcm.constraint_region.primitive_poses[0].position.y = 0.0;
pcm.constraint_region.primitive_poses[0].position.z = 0.0;
pcm.constraint_region.primitive_poses[0].orientation.x = 0.0;
pcm.constraint_region.primitive_poses[0].orientation.y = 0.0;
pcm.constraint_region.primitive_poses[0].orientation.z = 0.0;
pcm.constraint_region.primitive_poses[0].orientation.w = 1.0;
pcm.weight = 1.0;
EXPECT_FALSE(tf->isFixedFrame(pcm.link_name));
EXPECT_TRUE(pc.configure(pcm));
EXPECT_TRUE(pc.decide(ks).satisfied);
pcm.constraint_region.primitives[0].type = shape_msgs::SolidPrimitive::BOX;
pcm.constraint_region.primitives[0].dimensions.x = 0.2;
pcm.constraint_region.primitives[0].dimensions.y = 1.25;
pcm.constraint_region.primitives[0].dimensions.z = 0.1;
EXPECT_TRUE(pc.configure(pcm));
std::map<std::string, double> jvals;
jvals["l_shoulder_pan_joint"] = 0.4;
ks.setStateValues(jvals);
EXPECT_TRUE(pc.decide(ks).satisfied);
EXPECT_TRUE(pc.equal(pc, 1e-12));
}
TEST_F(LoadPlanningModelsPr2, OrientationConstraintsSimple)
{
planning_models::KinematicState ks(kmodel);
ks.setToDefaultValues();
planning_models::TransformsPtr tf(new planning_models::Transforms(kmodel->getModelFrame()));
kinematic_constraints::OrientationConstraint oc(kmodel, tf);
moveit_msgs::OrientationConstraint ocm;
ocm.link_name = "r_wrist_roll_link";
ocm.header.frame_id = kmodel->getModelFrame();
ocm.orientation.x = 0.0;
ocm.orientation.y = 0.0;
ocm.orientation.z = 0.0;
ocm.orientation.w = 1.0;
ocm.absolute_x_axis_tolerance = 0.1;
ocm.absolute_y_axis_tolerance = 0.1;
ocm.absolute_z_axis_tolerance = 0.1;
ocm.weight = 1.0;
EXPECT_TRUE(oc.configure(ocm));
EXPECT_FALSE(oc.decide(ks).satisfied);
ocm.header.frame_id = ocm.link_name;
EXPECT_TRUE(oc.configure(ocm));
EXPECT_TRUE(oc.decide(ks).satisfied);
EXPECT_TRUE(oc.equal(oc, 1e-12));
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Fixing constraints test<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <kinematic_constraints/kinematic_constraint.h>
#include <gtest/gtest.h>
#include <urdf_parser/urdf_parser.h>
#include <fstream>
class LoadPlanningModelsPr2 : public testing::Test
{
protected:
virtual void SetUp()
{
srdf_model.reset(new srdf::Model());
std::string xml_string;
std::fstream xml_file("../planning_models/test/urdf/robot.xml", std::fstream::in);
if (xml_file.is_open())
{
while ( xml_file.good() )
{
std::string line;
std::getline( xml_file, line);
xml_string += (line + "\n");
}
xml_file.close();
urdf_model = urdf::parseURDF(xml_string);
}
kmodel.reset(new planning_models::KinematicModel(urdf_model, srdf_model));
};
virtual void TearDown()
{
}
protected:
boost::shared_ptr<urdf::ModelInterface> urdf_model;
boost::shared_ptr<srdf::Model> srdf_model;
planning_models::KinematicModelPtr kmodel;
};
TEST_F(LoadPlanningModelsPr2, JointConstraintsSimple)
{
planning_models::KinematicState ks(kmodel);
ks.setToDefaultValues();
planning_models::TransformsPtr tf(new planning_models::Transforms(kmodel->getModelFrame()));
kinematic_constraints::JointConstraint jc(kmodel, tf);
moveit_msgs::JointConstraint jcm;
jcm.joint_name = "head_pan_joint";
jcm.position = 0.4;
jcm.tolerance_above = 0.1;
jcm.tolerance_below = 0.05;
jcm.weight = 1.0;
EXPECT_TRUE(jc.configure(jcm));
kinematic_constraints::ConstraintEvaluationResult p1 = jc.decide(ks);
EXPECT_FALSE(p1.satisfied);
EXPECT_NEAR(p1.distance, jcm.position, 1e-6);
std::map<std::string, double> jvals;
jvals[jcm.joint_name] = 0.41;
ks.setStateValues(jvals);
kinematic_constraints::ConstraintEvaluationResult p2 = jc.decide(ks);
EXPECT_TRUE(p2.satisfied);
EXPECT_NEAR(p2.distance, 0.01, 1e-6);
jvals[jcm.joint_name] = 0.46;
ks.setStateValues(jvals);
EXPECT_TRUE(jc.decide(ks).satisfied);
jvals[jcm.joint_name] = 0.501;
ks.setStateValues(jvals);
EXPECT_FALSE(jc.decide(ks).satisfied);
jvals[jcm.joint_name] = 0.39;
ks.setStateValues(jvals);
EXPECT_TRUE(jc.decide(ks).satisfied);
jvals[jcm.joint_name] = 0.34;
ks.setStateValues(jvals);
EXPECT_FALSE(jc.decide(ks).satisfied);
EXPECT_TRUE(jc.equal(jc, 1e-12));
}
TEST_F(LoadPlanningModelsPr2, JointConstraintsCont)
{
planning_models::KinematicState ks(kmodel);
ks.setToDefaultValues();
planning_models::TransformsPtr tf(new planning_models::Transforms(kmodel->getModelFrame()));
kinematic_constraints::JointConstraint jc(kmodel, tf);
moveit_msgs::JointConstraint jcm;
jcm.joint_name = "l_wrist_roll_joint";
jcm.position = 3.14;
jcm.tolerance_above = 0.04;
jcm.tolerance_below = 0.02;
jcm.weight = 1.0;
EXPECT_TRUE(jc.configure(jcm));
std::map<std::string, double> jvals;
jvals[jcm.joint_name] = 3.17;
ks.setStateValues(jvals);
kinematic_constraints::ConstraintEvaluationResult p1 = jc.decide(ks);
EXPECT_TRUE(p1.satisfied);
EXPECT_NEAR(p1.distance, 0.03, 1e-6);
jvals[jcm.joint_name] = -3.14;
ks.setStateValues(jvals);
kinematic_constraints::ConstraintEvaluationResult p2 = jc.decide(ks);
EXPECT_TRUE(p2.satisfied);
EXPECT_NEAR(p2.distance, 0.003185, 1e-4);
}
TEST_F(LoadPlanningModelsPr2, PositionConstraintsFixed)
{
planning_models::KinematicState ks(kmodel);
ks.setToDefaultValues();
planning_models::TransformsPtr tf(new planning_models::Transforms(kmodel->getModelFrame()));
kinematic_constraints::PositionConstraint pc(kmodel, tf);
moveit_msgs::PositionConstraint pcm;
pcm.link_name = "l_wrist_roll_link";
pcm.target_point_offset.x = 0;
pcm.target_point_offset.y = 0;
pcm.target_point_offset.z = 0;
pcm.constraint_region.primitives.resize(1);
pcm.constraint_region.primitives[0].type = shape_msgs::SolidPrimitive::SPHERE;
pcm.constraint_region.primitives[0].dimensions.resize(1);
pcm.constraint_region.primitives[0].dimensions[shape_msgs::SolidPrimitive::BOX_X] = 0.2;
pcm.header.frame_id = kmodel->getModelFrame();
pcm.constraint_region.primitive_poses.resize(1);
pcm.constraint_region.primitive_poses[0].position.x = 0.55;
pcm.constraint_region.primitive_poses[0].position.y = 0.2;
pcm.constraint_region.primitive_poses[0].position.z = 1.25;
pcm.constraint_region.primitive_poses[0].orientation.x = 0.0;
pcm.constraint_region.primitive_poses[0].orientation.y = 0.0;
pcm.constraint_region.primitive_poses[0].orientation.z = 0.0;
pcm.constraint_region.primitive_poses[0].orientation.w = 1.0;
pcm.weight = 1.0;
EXPECT_TRUE(pc.configure(pcm));
EXPECT_TRUE(pc.decide(ks).satisfied);
std::map<std::string, double> jvals;
jvals["torso_lift_joint"] = 0.4;
ks.setStateValues(jvals);
EXPECT_FALSE(pc.decide(ks).satisfied);
EXPECT_TRUE(pc.equal(pc, 1e-12));
}
TEST_F(LoadPlanningModelsPr2, PositionConstraintsMobile)
{
planning_models::KinematicState ks(kmodel);
ks.setToDefaultValues();
planning_models::TransformsPtr tf(new planning_models::Transforms(kmodel->getModelFrame()));
kinematic_constraints::PositionConstraint pc(kmodel, tf);
moveit_msgs::PositionConstraint pcm;
pcm.link_name = "l_wrist_roll_link";
pcm.target_point_offset.x = 0;
pcm.target_point_offset.y = 0;
pcm.target_point_offset.z = 0;
pcm.constraint_region.primitives.resize(1);
pcm.constraint_region.primitives[0].type = shape_msgs::SolidPrimitive::SPHERE;
pcm.constraint_region.primitives[0].dimensions.resize(1);
pcm.constraint_region.primitives[0].dimensions[shape_msgs::SolidPrimitive::BOX_X] = 0.38 * 2.0;
pcm.header.frame_id = "r_wrist_roll_link";
pcm.constraint_region.primitive_poses.resize(1);
pcm.constraint_region.primitive_poses[0].position.x = 0.0;
pcm.constraint_region.primitive_poses[0].position.y = 0.0;
pcm.constraint_region.primitive_poses[0].position.z = 0.0;
pcm.constraint_region.primitive_poses[0].orientation.x = 0.0;
pcm.constraint_region.primitive_poses[0].orientation.y = 0.0;
pcm.constraint_region.primitive_poses[0].orientation.z = 0.0;
pcm.constraint_region.primitive_poses[0].orientation.w = 1.0;
pcm.weight = 1.0;
EXPECT_FALSE(tf->isFixedFrame(pcm.link_name));
EXPECT_TRUE(pc.configure(pcm));
EXPECT_TRUE(pc.decide(ks).satisfied);
pcm.constraint_region.primitives[0].type = shape_msgs::SolidPrimitive::BOX;
pcm.constraint_region.primitives[0].dimensions.resize(3);
pcm.constraint_region.primitives[0].dimensions[shape_msgs::SolidPrimitive::BOX_X] = 0.2;
pcm.constraint_region.primitives[0].dimensions[shape_msgs::SolidPrimitive::BOX_Y] = 1.25;
pcm.constraint_region.primitives[0].dimensions[shape_msgs::SolidPrimitive::BOX_Z] = 0.1;
EXPECT_TRUE(pc.configure(pcm));
std::map<std::string, double> jvals;
jvals["l_shoulder_pan_joint"] = 0.4;
ks.setStateValues(jvals);
EXPECT_TRUE(pc.decide(ks).satisfied);
EXPECT_TRUE(pc.equal(pc, 1e-12));
}
TEST_F(LoadPlanningModelsPr2, OrientationConstraintsSimple)
{
planning_models::KinematicState ks(kmodel);
ks.setToDefaultValues();
planning_models::TransformsPtr tf(new planning_models::Transforms(kmodel->getModelFrame()));
kinematic_constraints::OrientationConstraint oc(kmodel, tf);
moveit_msgs::OrientationConstraint ocm;
ocm.link_name = "r_wrist_roll_link";
ocm.header.frame_id = kmodel->getModelFrame();
ocm.orientation.x = 0.0;
ocm.orientation.y = 0.0;
ocm.orientation.z = 0.0;
ocm.orientation.w = 1.0;
ocm.absolute_x_axis_tolerance = 0.1;
ocm.absolute_y_axis_tolerance = 0.1;
ocm.absolute_z_axis_tolerance = 0.1;
ocm.weight = 1.0;
EXPECT_TRUE(oc.configure(ocm));
EXPECT_FALSE(oc.decide(ks).satisfied);
ocm.header.frame_id = ocm.link_name;
EXPECT_TRUE(oc.configure(ocm));
EXPECT_TRUE(oc.decide(ks).satisfied);
EXPECT_TRUE(oc.equal(oc, 1e-12));
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2019, PickNik 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 PickNik LLC nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Henning Kayser */
#include <stdexcept>
#include <moveit/moveit_cpp/moveit_cpp.h>
#include <moveit/planning_scene_monitor/current_state_monitor.h>
#include <moveit/common_planning_interface_objects/common_objects.h>
#include <std_msgs/String.h>
#include <tf2/utils.h>
#include <tf2_ros/transform_listener.h>
#include <ros/console.h>
#include <ros/ros.h>
namespace moveit
{
namespace planning_interface
{
constexpr char LOGNAME[] = "moveit_cpp";
constexpr char PLANNING_PLUGIN_PARAM[] = "planning_plugin";
MoveItCpp::MoveItCpp(const ros::NodeHandle& nh, const std::shared_ptr<tf2_ros::Buffer>& tf_buffer)
: MoveItCpp(Options(nh), nh, tf_buffer)
{
}
MoveItCpp::MoveItCpp(const Options& options, const ros::NodeHandle& /*unused*/,
const std::shared_ptr<tf2_ros::Buffer>& tf_buffer)
{
if (!tf_buffer_)
tf_buffer_.reset(new tf2_ros::Buffer());
tf_listener_.reset(new tf2_ros::TransformListener(*tf_buffer_));
// Configure planning scene monitor
if (!loadPlanningSceneMonitor(options.planning_scene_monitor_options))
{
const std::string error = "Unable to configure planning scene monitor";
ROS_FATAL_STREAM_NAMED(LOGNAME, error);
throw std::runtime_error(error);
}
robot_model_ = planning_scene_monitor_->getRobotModel();
if (!robot_model_)
{
const std::string error = "Unable to construct robot model. Please make sure all needed information is on the "
"parameter server.";
ROS_FATAL_STREAM_NAMED(LOGNAME, error);
throw std::runtime_error(error);
}
bool load_planning_pipelines = true;
if (load_planning_pipelines && !loadPlanningPipelines(options.planning_pipeline_options))
{
const std::string error = "Failed to load planning pipelines from parameter server";
ROS_FATAL_STREAM_NAMED(LOGNAME, error);
throw std::runtime_error(error);
}
// TODO(henningkayser): configure trajectory execution manager
trajectory_execution_manager_.reset(new trajectory_execution_manager::TrajectoryExecutionManager(
robot_model_, planning_scene_monitor_->getStateMonitor()));
ROS_INFO_NAMED(LOGNAME, "MoveItCpp running");
}
MoveItCpp::MoveItCpp(MoveItCpp&& other)
{
other.clearContents();
}
MoveItCpp::~MoveItCpp()
{
ROS_INFO_NAMED(LOGNAME, "Deleting MoveItCpp");
clearContents();
}
MoveItCpp& MoveItCpp::operator=(MoveItCpp&& other)
{
if (this != &other)
{
this->node_handle_ = other.node_handle_;
this->tf_buffer_ = other.tf_buffer_;
this->robot_model_ = other.robot_model_;
this->planning_scene_monitor_ = other.planning_scene_monitor_;
other.clearContents();
}
return *this;
}
bool MoveItCpp::loadPlanningSceneMonitor(const PlanningSceneMonitorOptions& options)
{
planning_scene_monitor_.reset(
new planning_scene_monitor::PlanningSceneMonitor(options.robot_description, tf_buffer_, options.name));
// Allows us to sycronize to Rviz and also publish collision objects to ourselves
ROS_DEBUG_STREAM_NAMED(LOGNAME, "Configuring Planning Scene Monitor");
if (planning_scene_monitor_->getPlanningScene())
{
// Start state and scene monitors
ROS_INFO_NAMED(LOGNAME, "Listening to '%s' for joint states", options.joint_state_topic.c_str());
planning_scene_monitor_->startStateMonitor(options.joint_state_topic, options.attached_collision_object_topic);
planning_scene_monitor_->startPublishingPlanningScene(planning_scene_monitor::PlanningSceneMonitor::UPDATE_SCENE,
options.publish_planning_scene_topic);
planning_scene_monitor_->startSceneMonitor(options.monitored_planning_scene_topic);
}
else
{
ROS_ERROR_STREAM_NAMED(LOGNAME, "Planning scene not configured");
return false;
}
// Wait for complete state to be recieved
if (options.wait_for_initial_state_timeout > 0.0)
{
return planning_scene_monitor_->getStateMonitor()->waitForCurrentState(ros::Time::now(),
options.wait_for_initial_state_timeout);
}
return true;
}
bool MoveItCpp::loadPlanningPipelines(const PlanningPipelineOptions& options)
{
ros::NodeHandle node_handle(options.parent_namespace.empty() ? "~" : options.parent_namespace);
for (const auto& planning_pipeline_name : options.pipeline_names)
{
if (planning_pipelines_.count(planning_pipeline_name) > 0)
{
ROS_WARN_NAMED(LOGNAME, "Skipping duplicate entry for planning pipeline '%s'.", planning_pipeline_name.c_str());
continue;
}
ROS_INFO_NAMED(LOGNAME, "Loading planning pipeline '%s'", planning_pipeline_name.c_str());
ros::NodeHandle child_nh(node_handle, planning_pipeline_name);
planning_pipeline::PlanningPipelinePtr pipeline;
pipeline.reset(new planning_pipeline::PlanningPipeline(robot_model_, child_nh, PLANNING_PLUGIN_PARAM));
if (!pipeline->getPlannerManager())
{
ROS_ERROR_NAMED(LOGNAME, "Failed to initialize planning pipeline '%s'.", planning_pipeline_name.c_str());
continue;
}
planning_pipelines_[planning_pipeline_name] = pipeline;
}
if (planning_pipelines_.empty())
{
return false;
ROS_ERROR_NAMED(LOGNAME, "Failed to load any planning pipelines.");
}
// Retrieve group/pipeline mapping for faster lookup
std::vector<std::string> group_names = robot_model_->getJointModelGroupNames();
for (const auto& pipeline_entry : planning_pipelines_)
{
for (const auto& group_name : group_names)
{
groups_pipelines_map_[group_name] = {};
const auto& pipeline = pipeline_entry.second;
for (const auto& planner_configuration : pipeline->getPlannerManager()->getPlannerConfigurations())
{
if (planner_configuration.second.group == group_name)
{
groups_pipelines_map_[group_name].insert(pipeline_entry.first);
}
}
}
}
return true;
}
robot_model::RobotModelConstPtr MoveItCpp::getRobotModel() const
{
return robot_model_;
}
const ros::NodeHandle& MoveItCpp::getNodeHandle() const
{
return node_handle_;
}
bool MoveItCpp::getCurrentState(robot_state::RobotStatePtr& current_state, double wait_seconds)
{
if (wait_seconds > 0.0 &&
!planning_scene_monitor_->getStateMonitor()->waitForCurrentState(ros::Time::now(), wait_seconds))
{
ROS_ERROR_NAMED(LOGNAME, "Did not receive robot state");
return false;
}
{ // Lock planning scene
planning_scene_monitor::LockedPlanningSceneRO scene(planning_scene_monitor_);
current_state.reset(new moveit::core::RobotState(scene->getCurrentState()));
} // Unlock planning scene
return true;
}
robot_state::RobotStatePtr MoveItCpp::getCurrentState(double wait)
{
robot_state::RobotStatePtr current_state;
getCurrentState(current_state, wait);
return current_state;
}
const std::map<std::string, planning_pipeline::PlanningPipelinePtr>& MoveItCpp::getPlanningPipelines() const
{
return planning_pipelines_;
}
std::set<std::string> MoveItCpp::getPlanningPipelineNames(const std::string& group_name) const
{
std::set<std::string> result_names;
if (!group_name.empty() && groups_pipelines_map_.count(group_name) == 0)
{
ROS_ERROR_NAMED(LOGNAME, "There are no planning pipelines loaded for group '%s'.", group_name.c_str());
return result_names; // empty
}
for (const auto& pipeline_entry : planning_pipelines_)
{
const std::string& pipeline_name = pipeline_entry.first;
// If group_name is defined and valid, skip pipelines that don't belong to the planning group
if (!group_name.empty())
{
const auto& group_pipelines = groups_pipelines_map_.at(group_name);
if (group_pipelines.find(pipeline_name) == group_pipelines.end())
continue;
}
result_names.insert(pipeline_name);
}
return result_names;
}
const planning_scene_monitor::PlanningSceneMonitorPtr& MoveItCpp::getPlanningSceneMonitor() const
{
return planning_scene_monitor_;
}
planning_scene_monitor::PlanningSceneMonitorPtr MoveItCpp::getPlanningSceneMonitorNonConst()
{
return planning_scene_monitor_;
}
const trajectory_execution_manager::TrajectoryExecutionManagerPtr& MoveItCpp::getTrajectoryExecutionManager() const
{
return trajectory_execution_manager_;
}
trajectory_execution_manager::TrajectoryExecutionManagerPtr MoveItCpp::getTrajectoryExecutionManagerNonConst()
{
return trajectory_execution_manager_;
}
bool MoveItCpp::execute(const std::string& group_name, const robot_trajectory::RobotTrajectoryPtr& robot_trajectory,
bool blocking)
{
if (!robot_trajectory)
{
ROS_ERROR_NAMED(LOGNAME, "Robot trajectory is undefined");
return false;
}
// Check if there are controllers that can handle the execution
if (!trajectory_execution_manager_->ensureActiveControllersForGroup(group_name))
{
ROS_ERROR_NAMED(LOGNAME, "Execution failed! No active controllers configured for group '%s'", group_name.c_str());
return false;
}
// Execute trajectory
moveit_msgs::RobotTrajectory robot_trajectory_msg;
robot_trajectory->getRobotTrajectoryMsg(robot_trajectory_msg);
if (blocking)
{
trajectory_execution_manager_->push(robot_trajectory_msg);
trajectory_execution_manager_->execute();
return trajectory_execution_manager_->waitForExecution();
}
trajectory_execution_manager_->pushAndExecute(robot_trajectory_msg);
return true;
}
const std::shared_ptr<tf2_ros::Buffer>& MoveItCpp::getTFBuffer() const
{
return tf_buffer_;
}
void MoveItCpp::clearContents()
{
tf_buffer_.reset();
planning_scene_monitor_.reset();
robot_model_.reset();
planning_pipelines_.clear();
}
} // namespace planning_interface
} // namespace moveit
<commit_msg>MoveItCpp: correctly initialize tf_buffer_<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2019, PickNik 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 PickNik LLC nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Henning Kayser */
#include <stdexcept>
#include <moveit/moveit_cpp/moveit_cpp.h>
#include <moveit/planning_scene_monitor/current_state_monitor.h>
#include <moveit/common_planning_interface_objects/common_objects.h>
#include <std_msgs/String.h>
#include <tf2/utils.h>
#include <tf2_ros/transform_listener.h>
#include <ros/console.h>
#include <ros/ros.h>
namespace moveit
{
namespace planning_interface
{
constexpr char LOGNAME[] = "moveit_cpp";
constexpr char PLANNING_PLUGIN_PARAM[] = "planning_plugin";
MoveItCpp::MoveItCpp(const ros::NodeHandle& nh, const std::shared_ptr<tf2_ros::Buffer>& tf_buffer)
: MoveItCpp(Options(nh), nh, tf_buffer)
{
}
MoveItCpp::MoveItCpp(const Options& options, const ros::NodeHandle& /*unused*/,
const std::shared_ptr<tf2_ros::Buffer>& tf_buffer)
: tf_buffer_(tf_buffer)
{
if (!tf_buffer_)
tf_buffer_.reset(new tf2_ros::Buffer());
tf_listener_.reset(new tf2_ros::TransformListener(*tf_buffer_));
// Configure planning scene monitor
if (!loadPlanningSceneMonitor(options.planning_scene_monitor_options))
{
const std::string error = "Unable to configure planning scene monitor";
ROS_FATAL_STREAM_NAMED(LOGNAME, error);
throw std::runtime_error(error);
}
robot_model_ = planning_scene_monitor_->getRobotModel();
if (!robot_model_)
{
const std::string error = "Unable to construct robot model. Please make sure all needed information is on the "
"parameter server.";
ROS_FATAL_STREAM_NAMED(LOGNAME, error);
throw std::runtime_error(error);
}
bool load_planning_pipelines = true;
if (load_planning_pipelines && !loadPlanningPipelines(options.planning_pipeline_options))
{
const std::string error = "Failed to load planning pipelines from parameter server";
ROS_FATAL_STREAM_NAMED(LOGNAME, error);
throw std::runtime_error(error);
}
// TODO(henningkayser): configure trajectory execution manager
trajectory_execution_manager_.reset(new trajectory_execution_manager::TrajectoryExecutionManager(
robot_model_, planning_scene_monitor_->getStateMonitor()));
ROS_INFO_NAMED(LOGNAME, "MoveItCpp running");
}
MoveItCpp::MoveItCpp(MoveItCpp&& other)
{
other.clearContents();
}
MoveItCpp::~MoveItCpp()
{
ROS_INFO_NAMED(LOGNAME, "Deleting MoveItCpp");
clearContents();
}
MoveItCpp& MoveItCpp::operator=(MoveItCpp&& other)
{
if (this != &other)
{
this->node_handle_ = other.node_handle_;
this->tf_buffer_ = other.tf_buffer_;
this->robot_model_ = other.robot_model_;
this->planning_scene_monitor_ = other.planning_scene_monitor_;
other.clearContents();
}
return *this;
}
bool MoveItCpp::loadPlanningSceneMonitor(const PlanningSceneMonitorOptions& options)
{
planning_scene_monitor_.reset(
new planning_scene_monitor::PlanningSceneMonitor(options.robot_description, tf_buffer_, options.name));
// Allows us to sycronize to Rviz and also publish collision objects to ourselves
ROS_DEBUG_STREAM_NAMED(LOGNAME, "Configuring Planning Scene Monitor");
if (planning_scene_monitor_->getPlanningScene())
{
// Start state and scene monitors
ROS_INFO_NAMED(LOGNAME, "Listening to '%s' for joint states", options.joint_state_topic.c_str());
planning_scene_monitor_->startStateMonitor(options.joint_state_topic, options.attached_collision_object_topic);
planning_scene_monitor_->startPublishingPlanningScene(planning_scene_monitor::PlanningSceneMonitor::UPDATE_SCENE,
options.publish_planning_scene_topic);
planning_scene_monitor_->startSceneMonitor(options.monitored_planning_scene_topic);
}
else
{
ROS_ERROR_STREAM_NAMED(LOGNAME, "Planning scene not configured");
return false;
}
// Wait for complete state to be recieved
if (options.wait_for_initial_state_timeout > 0.0)
{
return planning_scene_monitor_->getStateMonitor()->waitForCurrentState(ros::Time::now(),
options.wait_for_initial_state_timeout);
}
return true;
}
bool MoveItCpp::loadPlanningPipelines(const PlanningPipelineOptions& options)
{
ros::NodeHandle node_handle(options.parent_namespace.empty() ? "~" : options.parent_namespace);
for (const auto& planning_pipeline_name : options.pipeline_names)
{
if (planning_pipelines_.count(planning_pipeline_name) > 0)
{
ROS_WARN_NAMED(LOGNAME, "Skipping duplicate entry for planning pipeline '%s'.", planning_pipeline_name.c_str());
continue;
}
ROS_INFO_NAMED(LOGNAME, "Loading planning pipeline '%s'", planning_pipeline_name.c_str());
ros::NodeHandle child_nh(node_handle, planning_pipeline_name);
planning_pipeline::PlanningPipelinePtr pipeline;
pipeline.reset(new planning_pipeline::PlanningPipeline(robot_model_, child_nh, PLANNING_PLUGIN_PARAM));
if (!pipeline->getPlannerManager())
{
ROS_ERROR_NAMED(LOGNAME, "Failed to initialize planning pipeline '%s'.", planning_pipeline_name.c_str());
continue;
}
planning_pipelines_[planning_pipeline_name] = pipeline;
}
if (planning_pipelines_.empty())
{
return false;
ROS_ERROR_NAMED(LOGNAME, "Failed to load any planning pipelines.");
}
// Retrieve group/pipeline mapping for faster lookup
std::vector<std::string> group_names = robot_model_->getJointModelGroupNames();
for (const auto& pipeline_entry : planning_pipelines_)
{
for (const auto& group_name : group_names)
{
groups_pipelines_map_[group_name] = {};
const auto& pipeline = pipeline_entry.second;
for (const auto& planner_configuration : pipeline->getPlannerManager()->getPlannerConfigurations())
{
if (planner_configuration.second.group == group_name)
{
groups_pipelines_map_[group_name].insert(pipeline_entry.first);
}
}
}
}
return true;
}
robot_model::RobotModelConstPtr MoveItCpp::getRobotModel() const
{
return robot_model_;
}
const ros::NodeHandle& MoveItCpp::getNodeHandle() const
{
return node_handle_;
}
bool MoveItCpp::getCurrentState(robot_state::RobotStatePtr& current_state, double wait_seconds)
{
if (wait_seconds > 0.0 &&
!planning_scene_monitor_->getStateMonitor()->waitForCurrentState(ros::Time::now(), wait_seconds))
{
ROS_ERROR_NAMED(LOGNAME, "Did not receive robot state");
return false;
}
{ // Lock planning scene
planning_scene_monitor::LockedPlanningSceneRO scene(planning_scene_monitor_);
current_state.reset(new moveit::core::RobotState(scene->getCurrentState()));
} // Unlock planning scene
return true;
}
robot_state::RobotStatePtr MoveItCpp::getCurrentState(double wait)
{
robot_state::RobotStatePtr current_state;
getCurrentState(current_state, wait);
return current_state;
}
const std::map<std::string, planning_pipeline::PlanningPipelinePtr>& MoveItCpp::getPlanningPipelines() const
{
return planning_pipelines_;
}
std::set<std::string> MoveItCpp::getPlanningPipelineNames(const std::string& group_name) const
{
std::set<std::string> result_names;
if (!group_name.empty() && groups_pipelines_map_.count(group_name) == 0)
{
ROS_ERROR_NAMED(LOGNAME, "There are no planning pipelines loaded for group '%s'.", group_name.c_str());
return result_names; // empty
}
for (const auto& pipeline_entry : planning_pipelines_)
{
const std::string& pipeline_name = pipeline_entry.first;
// If group_name is defined and valid, skip pipelines that don't belong to the planning group
if (!group_name.empty())
{
const auto& group_pipelines = groups_pipelines_map_.at(group_name);
if (group_pipelines.find(pipeline_name) == group_pipelines.end())
continue;
}
result_names.insert(pipeline_name);
}
return result_names;
}
const planning_scene_monitor::PlanningSceneMonitorPtr& MoveItCpp::getPlanningSceneMonitor() const
{
return planning_scene_monitor_;
}
planning_scene_monitor::PlanningSceneMonitorPtr MoveItCpp::getPlanningSceneMonitorNonConst()
{
return planning_scene_monitor_;
}
const trajectory_execution_manager::TrajectoryExecutionManagerPtr& MoveItCpp::getTrajectoryExecutionManager() const
{
return trajectory_execution_manager_;
}
trajectory_execution_manager::TrajectoryExecutionManagerPtr MoveItCpp::getTrajectoryExecutionManagerNonConst()
{
return trajectory_execution_manager_;
}
bool MoveItCpp::execute(const std::string& group_name, const robot_trajectory::RobotTrajectoryPtr& robot_trajectory,
bool blocking)
{
if (!robot_trajectory)
{
ROS_ERROR_NAMED(LOGNAME, "Robot trajectory is undefined");
return false;
}
// Check if there are controllers that can handle the execution
if (!trajectory_execution_manager_->ensureActiveControllersForGroup(group_name))
{
ROS_ERROR_NAMED(LOGNAME, "Execution failed! No active controllers configured for group '%s'", group_name.c_str());
return false;
}
// Execute trajectory
moveit_msgs::RobotTrajectory robot_trajectory_msg;
robot_trajectory->getRobotTrajectoryMsg(robot_trajectory_msg);
if (blocking)
{
trajectory_execution_manager_->push(robot_trajectory_msg);
trajectory_execution_manager_->execute();
return trajectory_execution_manager_->waitForExecution();
}
trajectory_execution_manager_->pushAndExecute(robot_trajectory_msg);
return true;
}
const std::shared_ptr<tf2_ros::Buffer>& MoveItCpp::getTFBuffer() const
{
return tf_buffer_;
}
void MoveItCpp::clearContents()
{
tf_buffer_.reset();
planning_scene_monitor_.reset();
robot_model_.reset();
planning_pipelines_.clear();
}
} // namespace planning_interface
} // namespace moveit
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.