text
stringlengths 54
60.6k
|
---|
<commit_before>#pragma once
#include "simlib/concat_tostr.hh"
#include "simlib/file_path.hh"
#include "simlib/string_compare.hh"
#include "simlib/string_transform.hh"
#include <map>
#include <utility>
#include <vector>
class ConfigFile {
public:
class ParseError : public std::runtime_error {
std::string diagnostics_;
public:
explicit ParseError(const std::string& msg)
: runtime_error(msg) {}
template <class... Args,
std::enable_if_t<(is_string_argument<Args> and ...), int> = 0>
ParseError(size_t line, size_t pos, Args&&... msg)
: runtime_error(concat_tostr("line ", line, ':', pos, ": ",
std::forward<Args>(msg)...)) {}
ParseError(const ParseError& pe) = default;
ParseError(ParseError&&) noexcept = default;
ParseError& operator=(const ParseError& pe) = default;
ParseError& operator=(ParseError&&) noexcept = default;
using runtime_error::what;
[[nodiscard]] const std::string& diagnostics() const noexcept {
return diagnostics_;
}
~ParseError() noexcept override = default;
friend class ConfigFile;
};
class Variable {
public:
static constexpr uint8_t SET = 1; // set if variable appears in the
// config
static constexpr uint8_t ARRAY = 2; // set if variable is an array
struct ValueSpan {
size_t beg = 0;
size_t end = 0;
};
private:
uint8_t flag_ = 0;
std::string str_;
std::vector<std::string> arr_;
ValueSpan value_span_; // value occupies [beg, end) range of the file
void unset() noexcept {
flag_ = 0;
str_.clear();
arr_.clear();
}
public:
Variable() {} // NOLINT(modernize-use-equals-default): compiler bug
[[nodiscard]] bool is_set() const noexcept { return flag_ & SET; }
[[nodiscard]] bool is_array() const noexcept { return flag_ & ARRAY; }
// Returns value as bool or false on error
[[nodiscard]] bool as_bool() const noexcept {
return (str_ == "1" || lower_equal(str_, "on") ||
lower_equal(str_, "true"));
}
template <class T, std::enable_if_t<std::is_arithmetic_v<T>, int> = 0>
[[nodiscard]] std::optional<T> as() const noexcept {
return str2num<T>(str_);
}
// Returns value as string (empty if not a string or variable isn't
// set)
[[nodiscard]] const std::string& as_string() const noexcept {
return str_;
}
// Returns value as array (empty if not an array or variable isn't set)
[[nodiscard]] const std::vector<std::string>&
as_array() const noexcept {
return arr_;
}
[[nodiscard]] ValueSpan value_span() const noexcept {
return value_span_;
}
friend class ConfigFile;
};
private:
std::map<std::string, Variable, std::less<>> vars; // (name => value)
// TODO: ^ maybe StringView would be better?
static inline const Variable null_var{};
public:
ConfigFile() = default;
ConfigFile(const ConfigFile&) = default;
ConfigFile(ConfigFile&&) noexcept = default;
ConfigFile& operator=(const ConfigFile&) = default;
ConfigFile& operator=(ConfigFile&&) noexcept = default;
~ConfigFile() = default;
// Adds variables @p names to variable set, ignores duplications
template <class... Args>
void add_vars(Args&&... names) {
int t[] = {(vars.emplace(std::forward<Args>(names), Variable{}), 0)...};
(void)t;
}
// Clears variable set
void clear() { vars.clear(); }
// Returns a reference to a variable @p name from variable set or to a
// null_var
[[nodiscard]] const Variable&
get_var(const StringView& name) const noexcept {
return (*this)[name];
}
const Variable& operator[](const StringView& name) const noexcept {
auto it = vars.find(name);
return (it != vars.end() ? it->second : null_var);
}
[[nodiscard]] const decltype(vars)& get_vars() const { return vars; }
/**
* @brief Loads config (variables) form file @p pathname
* @details Uses load_config_from_string()
*
* @param pathname config file
* @param load_all whether load all variables from @p pathname or load only
* these from variable set
*
* @errors Throws an exception std::runtime_error if an open(2) error
* occurs and all exceptions from load_config_from_string()
*/
void load_config_from_file(FilePath pathname, bool load_all = false);
/**
* @brief Loads config (variables) form string @p config
*
* @param config input string
* @param load_all whether load all variables from @p config or load only
* these from variable set
*
* @errors Throws an exception (ParseError) if an error occurs
*/
void load_config_from_string(std::string config, bool load_all = false);
// Check if string @p str is a valid string literal
static bool is_string_literal(StringView str) noexcept;
/**
* @brief Escapes unsafe sequences in str
* @details '\'' replaces with "''"
*
* @param str input string
*
* @return escaped, single-quoted string
*/
static std::string escape_to_single_quoted_string(StringView str);
/**
* @brief Escapes unsafe sequences in str
* @details Escapes '\"' with "\\\"" and characters for which
* is_cntrl(3) != 0 with "\\xnn" sequence where n is a hexadecimal digit.
*
* @param str input string
*
* @return escaped, double-quoted string
*/
static std::string escape_to_double_quoted_string(StringView str);
/**
* @brief Escapes unsafe sequences in str
* @details Escapes '\"' with "\\\"" and characters for which
* is_print(3) == 0 with "\\xnn" sequence where n is a hexadecimal digit.
*
* The difference between escape_to_double_quoted_string() and this
* function is that characters (bytes) not from interval [0, 127] are also
* escaped hexadecimally, that is why this option is not recommended when
* using utf-8 encoding - it will escape every non-ascii character (byte)
*
* @param str input string
*
* @return escaped, double-quoted string
*/
static std::string full_escape_to_double_quoted_string(StringView str);
/**
* @brief Converts string @p str so that it can be safely placed in config
* file
* @details Possible cases:
* 1) @p str contains '\'' or character for which iscrtnl(3) != 0:
* Escaped @p str via escape_to_double_quoted_string() will be returned.
* 2) Otherwise if @p str is string literal (is_string_literal(@p str)):
* Unchanged @p str will be returned.
* 3) Otherwise:
* Escaped @p str via escape_to_single_quoted_string() will be returned.
*
* Examples:
* "" -> '' (single quoted string, special case)
* "foo-bar" -> foo-bar (string literal)
* "line: 1\nab d E\n" -> "line: 1\nab d E\n" (double quoted string)
* " My awesome text" -> ' My awesome text' (single quoted string)
* " \\\\\\\\ " -> ' \\\\ ' (single quoted string)
* " '\t\n' ś " -> " '\t\n' ś " (double quoted string)
*
* @param str input string
*
* @return escaped (and possibly quoted) string
*/
static std::string escape_string(StringView str);
/**
* @brief Converts string @p str so that it can be safely placed in config
* file
* @details Possible cases:
* 1) @p str contains '\'' or character for which is_print(3) == 0:
* Escaped @p str via full_escape_to_double_quoted_string() will be
* returned.
* 2) Otherwise if @p str is string literal (is_string_literal(@p str)):
* Unchanged @p str will be returned.
* 3) Otherwise:
* Escaped @p str via escape_to_single_quoted_string() will be returned.
*
* The difference between escape_string() and this function is that
* characters not from interval [0, 127] are also escaped hexadecimally
* with full_escape_to_double_quoted_string()
*
* Examples:
* "" -> '' (single quoted string, special case)
* "foo-bar" -> foo-bar (string literal)
* "line: 1\nab d E\n" -> "line: 1\nab d E\n" (double quoted string)
* " My awesome text" -> ' My awesome text' (single quoted string)
* " \\\\\\\\ " -> ' \\\\ ' (single quoted string)
* " '\t\n' ś " -> " '\t\n' ś " (double quoted string)
*
* @param str input string
*
* @return escaped (and possibly quoted) string
*/
static std::string full_escape_string(StringView str);
};
<commit_msg>config_file.hh: fixed doc comment of full_escape_string()<commit_after>#pragma once
#include "simlib/concat_tostr.hh"
#include "simlib/file_path.hh"
#include "simlib/string_compare.hh"
#include "simlib/string_transform.hh"
#include <map>
#include <utility>
#include <vector>
class ConfigFile {
public:
class ParseError : public std::runtime_error {
std::string diagnostics_;
public:
explicit ParseError(const std::string& msg)
: runtime_error(msg) {}
template <class... Args,
std::enable_if_t<(is_string_argument<Args> and ...), int> = 0>
ParseError(size_t line, size_t pos, Args&&... msg)
: runtime_error(concat_tostr("line ", line, ':', pos, ": ",
std::forward<Args>(msg)...)) {}
ParseError(const ParseError& pe) = default;
ParseError(ParseError&&) noexcept = default;
ParseError& operator=(const ParseError& pe) = default;
ParseError& operator=(ParseError&&) noexcept = default;
using runtime_error::what;
[[nodiscard]] const std::string& diagnostics() const noexcept {
return diagnostics_;
}
~ParseError() noexcept override = default;
friend class ConfigFile;
};
class Variable {
public:
static constexpr uint8_t SET = 1; // set if variable appears in the
// config
static constexpr uint8_t ARRAY = 2; // set if variable is an array
struct ValueSpan {
size_t beg = 0;
size_t end = 0;
};
private:
uint8_t flag_ = 0;
std::string str_;
std::vector<std::string> arr_;
ValueSpan value_span_; // value occupies [beg, end) range of the file
void unset() noexcept {
flag_ = 0;
str_.clear();
arr_.clear();
}
public:
Variable() {} // NOLINT(modernize-use-equals-default): compiler bug
[[nodiscard]] bool is_set() const noexcept { return flag_ & SET; }
[[nodiscard]] bool is_array() const noexcept { return flag_ & ARRAY; }
// Returns value as bool or false on error
[[nodiscard]] bool as_bool() const noexcept {
return (str_ == "1" || lower_equal(str_, "on") ||
lower_equal(str_, "true"));
}
template <class T, std::enable_if_t<std::is_arithmetic_v<T>, int> = 0>
[[nodiscard]] std::optional<T> as() const noexcept {
return str2num<T>(str_);
}
// Returns value as string (empty if not a string or variable isn't
// set)
[[nodiscard]] const std::string& as_string() const noexcept {
return str_;
}
// Returns value as array (empty if not an array or variable isn't set)
[[nodiscard]] const std::vector<std::string>&
as_array() const noexcept {
return arr_;
}
[[nodiscard]] ValueSpan value_span() const noexcept {
return value_span_;
}
friend class ConfigFile;
};
private:
std::map<std::string, Variable, std::less<>> vars; // (name => value)
// TODO: ^ maybe StringView would be better?
static inline const Variable null_var{};
public:
ConfigFile() = default;
ConfigFile(const ConfigFile&) = default;
ConfigFile(ConfigFile&&) noexcept = default;
ConfigFile& operator=(const ConfigFile&) = default;
ConfigFile& operator=(ConfigFile&&) noexcept = default;
~ConfigFile() = default;
// Adds variables @p names to variable set, ignores duplications
template <class... Args>
void add_vars(Args&&... names) {
int t[] = {(vars.emplace(std::forward<Args>(names), Variable{}), 0)...};
(void)t;
}
// Clears variable set
void clear() { vars.clear(); }
// Returns a reference to a variable @p name from variable set or to a
// null_var
[[nodiscard]] const Variable&
get_var(const StringView& name) const noexcept {
return (*this)[name];
}
const Variable& operator[](const StringView& name) const noexcept {
auto it = vars.find(name);
return (it != vars.end() ? it->second : null_var);
}
[[nodiscard]] const decltype(vars)& get_vars() const { return vars; }
/**
* @brief Loads config (variables) form file @p pathname
* @details Uses load_config_from_string()
*
* @param pathname config file
* @param load_all whether load all variables from @p pathname or load only
* these from variable set
*
* @errors Throws an exception std::runtime_error if an open(2) error
* occurs and all exceptions from load_config_from_string()
*/
void load_config_from_file(FilePath pathname, bool load_all = false);
/**
* @brief Loads config (variables) form string @p config
*
* @param config input string
* @param load_all whether load all variables from @p config or load only
* these from variable set
*
* @errors Throws an exception (ParseError) if an error occurs
*/
void load_config_from_string(std::string config, bool load_all = false);
// Check if string @p str is a valid string literal
static bool is_string_literal(StringView str) noexcept;
/**
* @brief Escapes unsafe sequences in str
* @details '\'' replaces with "''"
*
* @param str input string
*
* @return escaped, single-quoted string
*/
static std::string escape_to_single_quoted_string(StringView str);
/**
* @brief Escapes unsafe sequences in str
* @details Escapes '\"' with "\\\"" and characters for which
* is_cntrl(3) != 0 with "\\xnn" sequence where n is a hexadecimal digit.
*
* @param str input string
*
* @return escaped, double-quoted string
*/
static std::string escape_to_double_quoted_string(StringView str);
/**
* @brief Escapes unsafe sequences in str
* @details Escapes '\"' with "\\\"" and characters for which
* is_print(3) == 0 with "\\xnn" sequence where n is a hexadecimal digit.
*
* The difference between escape_to_double_quoted_string() and this
* function is that characters (bytes) not from interval [0, 127] are also
* escaped hexadecimally, that is why this option is not recommended when
* using utf-8 encoding - it will escape every non-ascii character (byte)
*
* @param str input string
*
* @return escaped, double-quoted string
*/
static std::string full_escape_to_double_quoted_string(StringView str);
/**
* @brief Converts string @p str so that it can be safely placed in config
* file
* @details Possible cases:
* 1) @p str contains '\'' or character for which iscrtnl(3) != 0:
* Escaped @p str via escape_to_double_quoted_string() will be returned.
* 2) Otherwise if @p str is string literal (is_string_literal(@p str)):
* Unchanged @p str will be returned.
* 3) Otherwise:
* Escaped @p str via escape_to_single_quoted_string() will be returned.
*
* Examples:
* "" -> '' (single quoted string, special case)
* "foo-bar" -> foo-bar (string literal)
* "line: 1\nab d E\n" -> "line: 1\nab d E\n" (double quoted string)
* " My awesome text" -> ' My awesome text' (single quoted string)
* " \\\\\\\\ " -> ' \\\\ ' (single quoted string)
* " '\t\n' ś " -> " '\t\n' ś " (double quoted string)
*
* @param str input string
*
* @return escaped (and possibly quoted) string
*/
static std::string escape_string(StringView str);
/**
* @brief Converts string @p str so that it can be safely placed in config
* file
* @details Possible cases:
* 1) @p str contains '\'' or character for which is_print(3) == 0:
* Escaped @p str via full_escape_to_double_quoted_string() will be
* returned.
* 2) Otherwise if @p str is string literal (is_string_literal(@p str)):
* Unchanged @p str will be returned.
* 3) Otherwise:
* Escaped @p str via escape_to_single_quoted_string() will be returned.
*
* The difference between escape_string() and this function is that
* characters not from interval [0, 127] are also escaped hexadecimally
* with full_escape_to_double_quoted_string()
*
* Examples:
* "" -> '' (single quoted string, special case)
* "foo-bar" -> foo-bar (string literal)
* "line: 1\nab d E\n" -> "line: 1\nab d E\n" (double quoted string)
* " My awesome text" -> ' My awesome text' (single quoted string)
* " \\\\\\\\ " -> ' \\\\ ' (single quoted string)
* " '\t\n' ś " -> " '\t\n' \xc5\x9b " (double quoted string)
*
* @param str input string
*
* @return escaped (and possibly quoted) string
*/
static std::string full_escape_string(StringView str);
};
<|endoftext|> |
<commit_before>/*
* Copyright 2015-2017 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SPIRV_CROSS_IMAGE_HPP
#define SPIRV_CROSS_IMAGE_HPP
#ifndef GLM_SWIZZLE
#define GLM_SWIZZLE
#endif
#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#endif
#include <glm/glm.hpp>
namespace spirv_cross
{
template <typename T>
struct image2DBase
{
virtual ~image2DBase() = default;
inline virtual T load(glm::ivec2 coord)
{
return T(0, 0, 0, 1);
}
inline virtual void store(glm::ivec2 coord, const T &v)
{
}
};
typedef image2DBase<glm::vec4> image2D;
typedef image2DBase<glm::ivec4> iimage2D;
typedef image2DBase<glm::uvec4> uimage2D;
template <typename T>
inline T imageLoad(const image2DBase<T> &image, glm::ivec2 coord)
{
return image.load(coord);
}
template <typename T>
void imageStore(image2DBase<T> &image, glm::ivec2 coord, const T &value)
{
image.store(coord, value);
}
}
#endif
<commit_msg>Make image2dBase::load const<commit_after>/*
* Copyright 2015-2017 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SPIRV_CROSS_IMAGE_HPP
#define SPIRV_CROSS_IMAGE_HPP
#ifndef GLM_SWIZZLE
#define GLM_SWIZZLE
#endif
#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#endif
#include <glm/glm.hpp>
namespace spirv_cross
{
template <typename T>
struct image2DBase
{
virtual ~image2DBase() = default;
inline virtual T load(glm::ivec2 coord) const
{
return T(0, 0, 0, 1);
}
inline virtual void store(glm::ivec2 coord, const T &v)
{
}
};
typedef image2DBase<glm::vec4> image2D;
typedef image2DBase<glm::ivec4> iimage2D;
typedef image2DBase<glm::uvec4> uimage2D;
template <typename T>
inline T imageLoad(const image2DBase<T> &image, glm::ivec2 coord)
{
return image.load(coord);
}
template <typename T>
void imageStore(image2DBase<T> &image, glm::ivec2 coord, const T &value)
{
image.store(coord, value);
}
}
#endif
<|endoftext|> |
<commit_before>#include "categories_holder.hpp"
#include "search_delimiters.hpp"
#include "search_string_utils.hpp"
#include "classificator.hpp"
#include "../coding/reader.hpp"
#include "../coding/reader_streambuf.hpp"
#include "../base/logging.hpp"
#include "../base/stl_add.hpp"
namespace
{
enum State
{
EParseTypes,
EParseLanguages
};
} // unnamed namespace
int8_t const CategoriesHolder::UNSUPPORTED_LOCALE_CODE;
CategoriesHolder::CategoriesHolder(Reader * reader)
{
ReaderStreamBuf buffer(reader);
istream s(&buffer);
LoadFromStream(s);
}
void CategoriesHolder::AddCategory(Category & cat, vector<uint32_t> & types)
{
if (!cat.m_synonyms.empty() && !types.empty())
{
shared_ptr<Category> p(new Category());
p->Swap(cat);
for (size_t i = 0; i < types.size(); ++i)
m_type2cat.insert(make_pair(types[i], p));
for (size_t i = 0; i < p->m_synonyms.size(); ++i)
{
ASSERT(p->m_synonyms[i].m_locale != UNSUPPORTED_LOCALE_CODE, ());
StringT const uniName = search::NormalizeAndSimplifyString(p->m_synonyms[i].m_name);
vector<StringT> tokens;
SplitUniString(uniName, MakeBackInsertFunctor(tokens), search::Delimiters());
for (size_t j = 0; j < tokens.size(); ++j)
for (size_t k = 0; k < types.size(); ++k)
if (ValidKeyToken(tokens[j]))
m_name2type.insert(make_pair(make_pair(p->m_synonyms[i].m_locale, tokens[j]), types[k]));
}
}
cat.m_synonyms.clear();
types.clear();
}
bool CategoriesHolder::ValidKeyToken(StringT const & s)
{
if (s.size() > 2)
return true;
/// @todo We need to have global stop words array for the most used languages.
char const * arr[] = { "a", "z", "s", "d", "di", "de", "le" };
for (size_t i = 0; i < ARRAY_SIZE(arr); ++i)
if (s.IsEqualAscii(arr[i]))
return false;
return true;
}
void CategoriesHolder::LoadFromStream(istream & s)
{
m_type2cat.clear();
m_name2type.clear();
State state = EParseTypes;
string line;
Category cat;
vector<uint32_t> types;
Classificator const & c = classif();
int lineNumber = 0;
while (s.good())
{
++lineNumber;
getline(s, line);
strings::SimpleTokenizer iter(line, state == EParseTypes ? "|" : ":|");
switch (state)
{
case EParseTypes:
{
AddCategory(cat, types);
while (iter)
{
// split category to sub categories for classificator
vector<string> v;
strings::Tokenize(*iter, "-", MakeBackInsertFunctor(v));
// get classificator type
uint32_t const type = c.GetTypeByPathSafe(v);
if (type != 0)
types.push_back(type);
else
LOG(LWARNING, ("Invalid type:", v, "at line:", lineNumber));
++iter;
}
if (!types.empty())
state = EParseLanguages;
}
break;
case EParseLanguages:
{
if (!iter)
{
state = EParseTypes;
continue;
}
int8_t const langCode = MapLocaleToInteger(*iter);
CHECK(langCode != UNSUPPORTED_LOCALE_CODE, ("Invalid language code:", *iter, "at line:", lineNumber));
while (++iter)
{
Category::Name name;
name.m_locale = langCode;
name.m_name = *iter;
if (name.m_name.empty())
{
LOG(LWARNING, ("Empty category name at line:", lineNumber));
continue;
}
if (name.m_name[0] >= '0' && name.m_name[0] <= '9')
{
name.m_prefixLengthToSuggest = name.m_name[0] - '0';
name.m_name = name.m_name.substr(1);
}
else
name.m_prefixLengthToSuggest = Category::EMPTY_PREFIX_LENGTH;
cat.m_synonyms.push_back(name);
}
}
break;
}
}
// add last category
AddCategory(cat, types);
}
bool CategoriesHolder::GetNameByType(uint32_t type, int8_t locale, string & name) const
{
pair<IteratorT, IteratorT> const range = m_type2cat.equal_range(type);
for (IteratorT i = range.first; i != range.second; ++i)
{
Category const & cat = *i->second;
for (size_t j = 0; j < cat.m_synonyms.size(); ++j)
if (cat.m_synonyms[j].m_locale == locale)
{
name = cat.m_synonyms[j].m_name;
return true;
}
}
if (range.first != range.second)
{
name = range.first->second->m_synonyms[0].m_name;
return true;
}
return false;
}
bool CategoriesHolder::IsTypeExist(uint32_t type) const
{
pair<IteratorT, IteratorT> const range = m_type2cat.equal_range(type);
return range.first != range.second;
}
namespace
{
struct Mapping
{
char const * m_name;
int8_t m_code;
};
} // namespace
int8_t CategoriesHolder::MapLocaleToInteger(string const & locale)
{
static const Mapping mapping[] = {
{"en", 1 },
{"ru", 2 },
{"uk", 3 },
{"de", 4 },
{"fr", 5 },
{"it", 6 },
{"es", 7 },
{"ko", 8 },
{"ja", 9 },
{"cs", 10 },
{"nl", 11 },
{"zh-Hant", 12 },
{"pl", 13 },
{"pt", 14 },
{"hu", 15 },
{"th", 16 },
{"zh-Hans", 17 },
{"ar", 18 },
{"da", 19 },
{"tr", 20 },
{"sk", 21 },
};
for (size_t i = 0; i < ARRAY_SIZE(mapping); ++i)
if (locale.find(mapping[i].m_name) == 0)
return mapping[i].m_code;
// Special cases for different Chinese variations
if (locale.find("zh") == 0)
{
string lower = locale;
strings::AsciiToLower(lower);
if (lower.find("hant") != string::npos
|| lower.find("tw") != string::npos
|| lower.find("hk") != string::npos
|| lower.find("mo") != string::npos)
return 12; // Traditional Chinese
return 17; // Simplified Chinese by default for all other cases
}
return UNSUPPORTED_LOCALE_CODE;
}
<commit_msg>[search] Do not match Wi-Fi with “wi” or “fi” token.<commit_after>#include "categories_holder.hpp"
#include "search_delimiters.hpp"
#include "search_string_utils.hpp"
#include "classificator.hpp"
#include "../coding/reader.hpp"
#include "../coding/reader_streambuf.hpp"
#include "../base/logging.hpp"
#include "../base/stl_add.hpp"
namespace
{
enum State
{
EParseTypes,
EParseLanguages
};
} // unnamed namespace
int8_t const CategoriesHolder::UNSUPPORTED_LOCALE_CODE;
CategoriesHolder::CategoriesHolder(Reader * reader)
{
ReaderStreamBuf buffer(reader);
istream s(&buffer);
LoadFromStream(s);
}
void CategoriesHolder::AddCategory(Category & cat, vector<uint32_t> & types)
{
if (!cat.m_synonyms.empty() && !types.empty())
{
shared_ptr<Category> p(new Category());
p->Swap(cat);
for (size_t i = 0; i < types.size(); ++i)
m_type2cat.insert(make_pair(types[i], p));
for (size_t i = 0; i < p->m_synonyms.size(); ++i)
{
ASSERT(p->m_synonyms[i].m_locale != UNSUPPORTED_LOCALE_CODE, ());
StringT const uniName = search::NormalizeAndSimplifyString(p->m_synonyms[i].m_name);
vector<StringT> tokens;
SplitUniString(uniName, MakeBackInsertFunctor(tokens), search::Delimiters());
for (size_t j = 0; j < tokens.size(); ++j)
for (size_t k = 0; k < types.size(); ++k)
if (ValidKeyToken(tokens[j]))
m_name2type.insert(make_pair(make_pair(p->m_synonyms[i].m_locale, tokens[j]), types[k]));
}
}
cat.m_synonyms.clear();
types.clear();
}
bool CategoriesHolder::ValidKeyToken(StringT const & s)
{
if (s.size() > 2)
return true;
/// @todo We need to have global stop words array for the most used languages.
char const * arr[] = { "a", "z", "s", "d", "di", "de", "le", "wi", "fi" };
for (size_t i = 0; i < ARRAY_SIZE(arr); ++i)
if (s.IsEqualAscii(arr[i]))
return false;
return true;
}
void CategoriesHolder::LoadFromStream(istream & s)
{
m_type2cat.clear();
m_name2type.clear();
State state = EParseTypes;
string line;
Category cat;
vector<uint32_t> types;
Classificator const & c = classif();
int lineNumber = 0;
while (s.good())
{
++lineNumber;
getline(s, line);
strings::SimpleTokenizer iter(line, state == EParseTypes ? "|" : ":|");
switch (state)
{
case EParseTypes:
{
AddCategory(cat, types);
while (iter)
{
// split category to sub categories for classificator
vector<string> v;
strings::Tokenize(*iter, "-", MakeBackInsertFunctor(v));
// get classificator type
uint32_t const type = c.GetTypeByPathSafe(v);
if (type != 0)
types.push_back(type);
else
LOG(LWARNING, ("Invalid type:", v, "at line:", lineNumber));
++iter;
}
if (!types.empty())
state = EParseLanguages;
}
break;
case EParseLanguages:
{
if (!iter)
{
state = EParseTypes;
continue;
}
int8_t const langCode = MapLocaleToInteger(*iter);
CHECK(langCode != UNSUPPORTED_LOCALE_CODE, ("Invalid language code:", *iter, "at line:", lineNumber));
while (++iter)
{
Category::Name name;
name.m_locale = langCode;
name.m_name = *iter;
if (name.m_name.empty())
{
LOG(LWARNING, ("Empty category name at line:", lineNumber));
continue;
}
if (name.m_name[0] >= '0' && name.m_name[0] <= '9')
{
name.m_prefixLengthToSuggest = name.m_name[0] - '0';
name.m_name = name.m_name.substr(1);
}
else
name.m_prefixLengthToSuggest = Category::EMPTY_PREFIX_LENGTH;
cat.m_synonyms.push_back(name);
}
}
break;
}
}
// add last category
AddCategory(cat, types);
}
bool CategoriesHolder::GetNameByType(uint32_t type, int8_t locale, string & name) const
{
pair<IteratorT, IteratorT> const range = m_type2cat.equal_range(type);
for (IteratorT i = range.first; i != range.second; ++i)
{
Category const & cat = *i->second;
for (size_t j = 0; j < cat.m_synonyms.size(); ++j)
if (cat.m_synonyms[j].m_locale == locale)
{
name = cat.m_synonyms[j].m_name;
return true;
}
}
if (range.first != range.second)
{
name = range.first->second->m_synonyms[0].m_name;
return true;
}
return false;
}
bool CategoriesHolder::IsTypeExist(uint32_t type) const
{
pair<IteratorT, IteratorT> const range = m_type2cat.equal_range(type);
return range.first != range.second;
}
namespace
{
struct Mapping
{
char const * m_name;
int8_t m_code;
};
} // namespace
int8_t CategoriesHolder::MapLocaleToInteger(string const & locale)
{
static const Mapping mapping[] = {
{"en", 1 },
{"ru", 2 },
{"uk", 3 },
{"de", 4 },
{"fr", 5 },
{"it", 6 },
{"es", 7 },
{"ko", 8 },
{"ja", 9 },
{"cs", 10 },
{"nl", 11 },
{"zh-Hant", 12 },
{"pl", 13 },
{"pt", 14 },
{"hu", 15 },
{"th", 16 },
{"zh-Hans", 17 },
{"ar", 18 },
{"da", 19 },
{"tr", 20 },
{"sk", 21 },
};
for (size_t i = 0; i < ARRAY_SIZE(mapping); ++i)
if (locale.find(mapping[i].m_name) == 0)
return mapping[i].m_code;
// Special cases for different Chinese variations
if (locale.find("zh") == 0)
{
string lower = locale;
strings::AsciiToLower(lower);
if (lower.find("hant") != string::npos
|| lower.find("tw") != string::npos
|| lower.find("hk") != string::npos
|| lower.find("mo") != string::npos)
return 12; // Traditional Chinese
return 17; // Simplified Chinese by default for all other cases
}
return UNSUPPORTED_LOCALE_CODE;
}
<|endoftext|> |
<commit_before>#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <mixerr.h>
#include <Instrument.h>
#include "PANECHO.h"
#include <rt.h>
#include <rtdefs.h>
extern "C" {
#include <ugens.h>
extern int resetval;
}
PANECHO::PANECHO() : Instrument()
{
// future setup here?
}
PANECHO::~PANECHO()
{
delete [] delarray1;
delete [] delarray2;
}
int PANECHO::init(float p[], short n_args)
{
// p0 = output skip; p1 = input skip; p2 = output duration
// p3 = amplitude multiplier
// p4 = chennel 0 delay time
// p5 = chennel 1 delay time
// p6 = regeneration multiplier (< 1!)
// p7 = ring-down duration
// p8 = input channel [optional]
// assumes function table 1 is the amplitude envelope
int amplen;
long delsamps;
rtsetinput(p[1], this);
nsamps = rtsetoutput(p[0], p[2]+p[7], this);
insamps = p[2] * SR;
if (NCHANS != 2) {
fprintf(stderr,"output must be stereo!\n");
exit(-1);
}
delsamps = p[4] * SR;
delarray1 = new float[delsamps];
if (!delarray1) {
fprintf(stderr,"Sorry, Charlie -- no space\n");
exit(-1);
}
wait1 = p[4];
delset(delarray1, deltabs1, wait1);
delsamps = p[5] * SR + 0.5;
delarray2 = new float[delsamps];
if (!delarray2) {
fprintf(stderr,"Sorry, Charlie -- no space\n");
exit(-1);
}
wait2 = p[5];
delset(delarray2, deltabs2, wait2);
regen = p[5];
amptable = floc(1);
amplen = fsize(1);
tableset(p[2], amplen, amptabs);
amp = p[3];
skip = SR/(float)resetval;
inchan = p[8];
if ((inchan+1) > inputchans) {
fprintf(stderr,"uh oh, you have asked for channel %d of a %d-channel file...\n",inchan,inputchans);
exit(-1);
}
return(nsamps);
}
int PANECHO::run()
{
int i,rsamps;
float in[2*MAXBUF],out[2];
float aamp;
int branch;
rsamps = chunksamps*inputchans;
rtgetin(in, this, rsamps);
branch = 0;
for (i = 0; i < rsamps; i += inputchans) {
if (cursamp > insamps) {
out[0] = delget(delarray2, wait2, deltabs2) * regen;
out[1] = delget(delarray1, wait1, deltabs1);
}
else {
if (--branch < 0) {
aamp = tablei(cursamp, amptable, amptabs) * amp;
branch = skip;
}
out[0] = (in[i+inchan]*aamp) + (delget(delarray2, wait2, deltabs2)*regen);
out[1] = delget(delarray1, wait1, deltabs1);
}
delput(out[0], delarray1, deltabs1);
delput(out[1], delarray2, deltabs2);
rtaddout(out);
cursamp++;
}
return(i);
}
Instrument*
makePANECHO()
{
PANECHO *inst;
inst = new PANECHO();
return inst;
}
void
rtprofile()
{
RT_INTRO("PANECHO",makePANECHO);
}
<commit_msg>Left chan delay line didn't have the + .5 fix.<commit_after>#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <mixerr.h>
#include <Instrument.h>
#include "PANECHO.h"
#include <rt.h>
#include <rtdefs.h>
extern "C" {
#include <ugens.h>
extern int resetval;
}
PANECHO::PANECHO() : Instrument()
{
// future setup here?
}
PANECHO::~PANECHO()
{
delete [] delarray1;
delete [] delarray2;
}
int PANECHO::init(float p[], short n_args)
{
// p0 = output skip; p1 = input skip; p2 = output duration
// p3 = amplitude multiplier
// p4 = chennel 0 delay time
// p5 = chennel 1 delay time
// p6 = regeneration multiplier (< 1!)
// p7 = ring-down duration
// p8 = input channel [optional]
// assumes function table 1 is the amplitude envelope
int amplen;
long delsamps;
rtsetinput(p[1], this);
nsamps = rtsetoutput(p[0], p[2]+p[7], this);
insamps = p[2] * SR;
if (NCHANS != 2) {
fprintf(stderr,"output must be stereo!\n");
exit(-1);
}
delsamps = p[4] * SR + 0.5;
delarray1 = new float[delsamps];
if (!delarray1) {
fprintf(stderr,"Sorry, Charlie -- no space\n");
exit(-1);
}
wait1 = p[4];
delset(delarray1, deltabs1, wait1);
delsamps = p[5] * SR + 0.5;
delarray2 = new float[delsamps];
if (!delarray2) {
fprintf(stderr,"Sorry, Charlie -- no space\n");
exit(-1);
}
wait2 = p[5];
delset(delarray2, deltabs2, wait2);
regen = p[5];
amptable = floc(1);
amplen = fsize(1);
tableset(p[2], amplen, amptabs);
amp = p[3];
skip = SR/(float)resetval;
inchan = p[8];
if ((inchan+1) > inputchans) {
fprintf(stderr,"uh oh, you have asked for channel %d of a %d-channel file...\n",inchan,inputchans);
exit(-1);
}
return(nsamps);
}
int PANECHO::run()
{
int i,rsamps;
float in[2*MAXBUF],out[2];
float aamp;
int branch;
rsamps = chunksamps*inputchans;
rtgetin(in, this, rsamps);
branch = 0;
for (i = 0; i < rsamps; i += inputchans) {
if (cursamp > insamps) {
out[0] = delget(delarray2, wait2, deltabs2) * regen;
out[1] = delget(delarray1, wait1, deltabs1);
}
else {
if (--branch < 0) {
aamp = tablei(cursamp, amptable, amptabs) * amp;
branch = skip;
}
out[0] = (in[i+inchan]*aamp) + (delget(delarray2, wait2, deltabs2)*regen);
out[1] = delget(delarray1, wait1, deltabs1);
}
delput(out[0], delarray1, deltabs1);
delput(out[1], delarray2, deltabs2);
rtaddout(out);
cursamp++;
}
return(i);
}
Instrument*
makePANECHO()
{
PANECHO *inst;
inst = new PANECHO();
return inst;
}
void
rtprofile()
{
RT_INTRO("PANECHO",makePANECHO);
}
<|endoftext|> |
<commit_before>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon ([email protected])
Version 1.1.0, packaged on March, 2009.
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_mesh2.cpp implementation of the GLC_Mesh2 class.
#include "glc_mesh2.h"
#include "glc_openglexception.h"
#include "glc_selectionmaterial.h"
#include "glc_state.h"
#include <QtDebug>
//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Mesh2::GLC_Mesh2()
:GLC_VboGeom("Mesh", false)
, m_Vertex()
, m_MaterialGroup()
, m_NumberOfFaces(0)
, m_IsSelected(false)
, m_ColorPearVertex(false)
{
//qDebug() << "GLC_Mesh2::GLC_Mesh2" << id();
// Index group with default material
IndexList* pIndexList= new IndexList;
m_MaterialGroup.insert(0, pIndexList);
}
GLC_Mesh2::GLC_Mesh2(const GLC_Mesh2 &meshToCopy)
: GLC_VboGeom(meshToCopy)
, m_Vertex(meshToCopy.m_Vertex)
, m_MaterialGroup()
, m_NumberOfFaces(meshToCopy.m_NumberOfFaces)
, m_IsSelected(false)
, m_ColorPearVertex(meshToCopy.m_ColorPearVertex)
{
// Copy Vertex and index data if necessary
if (m_VertexVector.isEmpty())
{
m_VertexVector= meshToCopy.getVertexVector();
m_IndexVector= meshToCopy.getIndexVector();
}
//qDebug() << "GLC_Mesh2::GLC_Mesh2" << id();
// Copy Material group IBO
MaterialGroupHash::const_iterator j= meshToCopy.m_MaterialGroup.begin();
while (j != meshToCopy.m_MaterialGroup.constEnd())
{
IndexList* pIndexList= new IndexList(*j.value());
m_MaterialGroup.insert(j.key(), pIndexList);
++j;
}
}
GLC_Mesh2::~GLC_Mesh2(void)
{
// delete mesh inner index material group
{
MaterialGroupHash::const_iterator i= m_MaterialGroup.begin();
while (i != m_MaterialGroup.constEnd())
{
// Delete index vector
delete i.value();
++i;
}
}
m_Vertex.clear();
m_MaterialGroup.clear();
}
/////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////
// return the mesh bounding box
GLC_BoundingBox& GLC_Mesh2::boundingBox(void)
{
if (NULL == m_pBoundingBox)
{
//qDebug() << "GLC_Mesh2::boundingBox create boundingBox";
m_pBoundingBox= new GLC_BoundingBox();
if (m_VertexVector.isEmpty())
{
qDebug() << "GLC_Mesh2::getBoundingBox empty m_VertexVector";
}
else
{
const int max= m_VertexVector.size();
for (int i= 0; i < max; ++i)
{
GLC_Vector3d vector(m_VertexVector[i].x, m_VertexVector[i].y, m_VertexVector[i].z);
m_pBoundingBox->combine(vector);
}
}
}
return *m_pBoundingBox;
}
// Return a copy of the current geometry
GLC_VboGeom* GLC_Mesh2::clone() const
{
return new GLC_Mesh2(*this);
}
// Return the Vertex Vector
VertexVector GLC_Mesh2::getVertexVector() const
{
if (0 != m_VboId)
{
// VBO created get data from VBO
const int sizeOfVbo= numberOfVertex();
const GLsizeiptr dataSize= sizeOfVbo * sizeof(GLC_Vertex);
VertexVector vertexVector(sizeOfVbo);
glBindBuffer(GL_ARRAY_BUFFER, m_VboId);
GLvoid* pVbo = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY);
memcpy(vertexVector.data(), pVbo, dataSize);
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return vertexVector;
}
else
{
return m_VertexVector;
}
}
// Return the Index Vector
QVector<GLuint> GLC_Mesh2::getIndexVector() const
{
if (0 != m_IboId)
{
// IBO created get data from IBO
const int sizeOfVbo= numberOfVertex();
const GLsizeiptr indexSize = sizeOfVbo * sizeof(GLuint);
QVector<GLuint> indexVector(sizeOfVbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IboId);
GLvoid* pIbo = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_ONLY);
memcpy(indexVector.data(), pIbo, indexSize);
glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
return indexVector;
}
else
{
return m_IndexVector;
}
}
/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Add triangles with the same material to the mesh
void GLC_Mesh2::addTriangles(const VertexList &triangles, GLC_Material* pMaterial)
{
// test if the material is already in the mesh
GLC_uint materialID;
if (NULL != pMaterial)
{
materialID= pMaterial->id();
}
else
{
materialID= 0;
}
IndexList* pCurIndexList= NULL;
if ((materialID == 0) or m_MaterialHash.contains(materialID))
{
pCurIndexList= m_MaterialGroup.value(materialID);
}
else
{
// Test if the mesh have already an equivalent material
GLC_uint index= materialIndex(*pMaterial);
if (0 == index)
{
addMaterial(pMaterial);
pCurIndexList= new IndexList;
m_MaterialGroup.insert(materialID, pCurIndexList);
}
else
{
pCurIndexList= m_MaterialGroup.value(index);
}
}
const int startVertexIndex= m_Vertex.size();
const int delta= triangles.size();
// Add triangles vertex to the mesh
m_Vertex+= triangles;
for (int i= 0; i < delta; ++i)
{
pCurIndexList->append(startVertexIndex + static_cast<GLuint>(i));
}
// Invalid the geometry
m_GeometryIsValid = false;
m_NumberOfFaces+= delta / 3;
}
// Reverse mesh normal
void GLC_Mesh2::reverseNormal()
{
// Copy Vertex and index data if necessary
if (m_VertexVector.isEmpty())
{
m_VertexVector= getVertexVector();
m_IndexVector= getIndexVector();
}
const int max= m_VertexVector.size();
for (int i= 0; i < max; ++i)
{
m_VertexVector[i].nx= m_VertexVector[i].nx * -1.0f;
m_VertexVector[i].ny= m_VertexVector[i].ny * -1.0f;
m_VertexVector[i].nz= m_VertexVector[i].nz * -1.0f;
}
// Invalid the geometry
m_GeometryIsValid = false;
}
// Specific glExecute method
void GLC_Mesh2::glExecute(bool isSelected, bool transparent)
{
m_IsSelected= isSelected;
GLC_VboGeom::glExecute(isSelected, transparent);
m_IsSelected= false;
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
// Virtual interface for OpenGL Geometry set up.
void GLC_Mesh2::glDraw(bool transparent)
{
Q_ASSERT(m_GeometryIsValid or not m_VertexVector.isEmpty());
const bool vboIsUsed= GLC_State::vboUsed();
IndexList iboList;
MaterialGroupHash::iterator iMaterialGroup;
// Create VBO and IBO
if (!m_GeometryIsValid)
{
// Fill index
iMaterialGroup= m_MaterialGroup.begin();
while (iMaterialGroup != m_MaterialGroup.constEnd())
{
if (!iMaterialGroup.value()->isEmpty())
{
iboList+= *(iMaterialGroup.value());
}
++iMaterialGroup;
}
// Set index vector
m_IndexVector= iboList.toVector();
if (vboIsUsed)
{
// Create VBO
const GLsizei dataNbr= static_cast<GLsizei>(m_VertexVector.size());
const GLsizeiptr dataSize= dataNbr * sizeof(GLC_Vertex);
glBufferData(GL_ARRAY_BUFFER, dataSize, m_VertexVector.data(), GL_STATIC_DRAW);
m_VertexVector.clear();
// Create IBO
const GLsizei indexNbr= static_cast<GLsizei>(iboList.size());
const GLsizeiptr indexSize = indexNbr * sizeof(GLuint);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexSize, m_IndexVector.data(), GL_STATIC_DRAW);
m_IndexVector.clear();
}
}
if (vboIsUsed)
{
// Use VBO
glVertexPointer(3, GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(0));
glNormalPointer(GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(12));
glTexCoordPointer(2, GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(24));
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
// test if color pear vertex is activated
if (m_ColorPearVertex and not m_IsSelected and not GLC_State::isInSelectionMode())
{
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4, GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(32));
}
}
else
{
// Use Vertex Array
float* pVertexData= (float *) m_VertexVector.data();
glVertexPointer(3, GL_FLOAT, sizeof(GLC_Vertex), pVertexData);
glNormalPointer(GL_FLOAT, sizeof(GLC_Vertex), &pVertexData[3]);
glTexCoordPointer(2, GL_FLOAT, sizeof(GLC_Vertex), &pVertexData[6]);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
// test if color pear vertex is activated
if (m_ColorPearVertex and not m_IsSelected and not GLC_State::isInSelectionMode())
{
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4, GL_FLOAT, sizeof(GLC_Vertex), &pVertexData[8]);
}
}
GLC_Material* pCurrentMaterial= NULL;
GLuint max;
GLuint cur= 0;
iMaterialGroup= m_MaterialGroup.begin();
while (iMaterialGroup != m_MaterialGroup.constEnd())
{
if (not iMaterialGroup.value()->isEmpty())
{
if ((not GLC_State::selectionShaderUsed() or not m_IsSelected) and not GLC_State::isInSelectionMode())
{
// Set current material
if (iMaterialGroup.key() == 0)
{
// Use default material
pCurrentMaterial= firstMaterial();
}
else
{
pCurrentMaterial= m_MaterialHash.value(iMaterialGroup.key());
Q_ASSERT(pCurrentMaterial != NULL);
}
if (pCurrentMaterial->isTransparent() == transparent)
{
// Execute current material
if (pCurrentMaterial->getAddRgbaTexture())
{
glEnable(GL_TEXTURE_2D);
}
else
{
glDisable(GL_TEXTURE_2D);
}
// Activate material
pCurrentMaterial->glExecute();
const GLfloat red= pCurrentMaterial->getDiffuseColor().redF();
const GLfloat green= pCurrentMaterial->getDiffuseColor().greenF();
const GLfloat blue= pCurrentMaterial->getDiffuseColor().blueF();
const GLfloat alpha= pCurrentMaterial->getDiffuseColor().alphaF();
glColor4f(red, green, blue, alpha);
if (m_IsSelected) GLC_SelectionMaterial::glExecute();
}
}
else if(not GLC_State::isInSelectionMode())
{
// Use Shader
glDisable(GL_TEXTURE_2D);
}
max= static_cast<GLuint>(iMaterialGroup.value()->size());
if (m_IsSelected or GLC_State::isInSelectionMode() or (pCurrentMaterial->isTransparent() == transparent))
{
// Draw Mesh
if (vboIsUsed)
{
// Use VBO
//glDrawRangeElements(GL_TRIANGLES, 0, max, max, GL_UNSIGNED_INT, BUFFER_OFFSET((cur) * sizeof(unsigned int)));
glDrawElements(GL_TRIANGLES, max, GL_UNSIGNED_INT, BUFFER_OFFSET((cur) * sizeof(unsigned int)));
}
else
{
// Use Vertex Array
glDrawElements(GL_TRIANGLES, max, GL_UNSIGNED_INT, &m_IndexVector.data()[cur]);
}
}
cur+= max;
}
++iMaterialGroup;
}
if (m_ColorPearVertex and not m_IsSelected and not GLC_State::isInSelectionMode())
{
glDisableClientState(GL_COLOR_ARRAY);
glDisable(GL_COLOR_MATERIAL);
}
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Mesh2::GlDraw ", error);
throw(OpenGlException);
}
}
<commit_msg>Bug Fix in copy constructor. Copy the inner material.<commit_after>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon ([email protected])
Version 1.1.0, packaged on March, 2009.
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_mesh2.cpp implementation of the GLC_Mesh2 class.
#include "glc_mesh2.h"
#include "glc_openglexception.h"
#include "glc_selectionmaterial.h"
#include "glc_state.h"
#include <QtDebug>
//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Mesh2::GLC_Mesh2()
:GLC_VboGeom("Mesh", false)
, m_Vertex()
, m_MaterialGroup()
, m_NumberOfFaces(0)
, m_IsSelected(false)
, m_ColorPearVertex(false)
{
//qDebug() << "GLC_Mesh2::GLC_Mesh2" << id();
// Index group with default material
IndexList* pIndexList= new IndexList;
m_MaterialGroup.insert(0, pIndexList);
}
GLC_Mesh2::GLC_Mesh2(const GLC_Mesh2 &meshToCopy)
: GLC_VboGeom(meshToCopy)
, m_Vertex(meshToCopy.m_Vertex)
, m_MaterialGroup()
, m_NumberOfFaces(meshToCopy.m_NumberOfFaces)
, m_IsSelected(false)
, m_ColorPearVertex(meshToCopy.m_ColorPearVertex)
{
// Copy Vertex and index data if necessary
if (m_VertexVector.isEmpty())
{
m_VertexVector= meshToCopy.getVertexVector();
m_IndexVector= meshToCopy.getIndexVector();
}
//qDebug() << "GLC_Mesh2::GLC_Mesh2" << id();
// Copy inner material hash
MaterialHash::const_iterator i= m_MaterialHash.begin();
MaterialHash newMaterialHash;
QHash<GLC_uint, GLC_uint> materialMap;
while (i != m_MaterialHash.constEnd())
{
// update inner material use table
i.value()->delGLC_Geom(id());
GLC_Material* pNewMaterial= new GLC_Material(*(i.value()));
newMaterialHash.insert(pNewMaterial->id(), pNewMaterial);
pNewMaterial->addGLC_Geom(this);
materialMap.insert(i.key(), pNewMaterial->id());
++i;
}
m_MaterialHash= newMaterialHash;
// Copy Material group IBO
MaterialGroupHash::const_iterator j= meshToCopy.m_MaterialGroup.begin();
while (j != meshToCopy.m_MaterialGroup.constEnd())
{
IndexList* pIndexList= new IndexList(*j.value());
m_MaterialGroup.insert(materialMap.value(j.key()), pIndexList);
++j;
}
}
GLC_Mesh2::~GLC_Mesh2(void)
{
// delete mesh inner index material group
{
MaterialGroupHash::const_iterator i= m_MaterialGroup.begin();
while (i != m_MaterialGroup.constEnd())
{
// Delete index vector
delete i.value();
++i;
}
}
m_Vertex.clear();
m_MaterialGroup.clear();
}
/////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////
// return the mesh bounding box
GLC_BoundingBox& GLC_Mesh2::boundingBox(void)
{
if (NULL == m_pBoundingBox)
{
//qDebug() << "GLC_Mesh2::boundingBox create boundingBox";
m_pBoundingBox= new GLC_BoundingBox();
if (m_VertexVector.isEmpty())
{
qDebug() << "GLC_Mesh2::getBoundingBox empty m_VertexVector";
}
else
{
const int max= m_VertexVector.size();
for (int i= 0; i < max; ++i)
{
GLC_Vector3d vector(m_VertexVector[i].x, m_VertexVector[i].y, m_VertexVector[i].z);
m_pBoundingBox->combine(vector);
}
}
}
return *m_pBoundingBox;
}
// Return a copy of the current geometry
GLC_VboGeom* GLC_Mesh2::clone() const
{
return new GLC_Mesh2(*this);
}
// Return the Vertex Vector
VertexVector GLC_Mesh2::getVertexVector() const
{
if (0 != m_VboId)
{
// VBO created get data from VBO
const int sizeOfVbo= numberOfVertex();
const GLsizeiptr dataSize= sizeOfVbo * sizeof(GLC_Vertex);
VertexVector vertexVector(sizeOfVbo);
glBindBuffer(GL_ARRAY_BUFFER, m_VboId);
GLvoid* pVbo = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY);
memcpy(vertexVector.data(), pVbo, dataSize);
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return vertexVector;
}
else
{
return m_VertexVector;
}
}
// Return the Index Vector
QVector<GLuint> GLC_Mesh2::getIndexVector() const
{
if (0 != m_IboId)
{
// IBO created get data from IBO
const int sizeOfVbo= numberOfVertex();
const GLsizeiptr indexSize = sizeOfVbo * sizeof(GLuint);
QVector<GLuint> indexVector(sizeOfVbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IboId);
GLvoid* pIbo = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_ONLY);
memcpy(indexVector.data(), pIbo, indexSize);
glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
return indexVector;
}
else
{
return m_IndexVector;
}
}
/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Add triangles with the same material to the mesh
void GLC_Mesh2::addTriangles(const VertexList &triangles, GLC_Material* pMaterial)
{
// test if the material is already in the mesh
GLC_uint materialID;
if (NULL != pMaterial)
{
materialID= pMaterial->id();
}
else
{
materialID= 0;
}
IndexList* pCurIndexList= NULL;
if ((materialID == 0) or m_MaterialHash.contains(materialID))
{
pCurIndexList= m_MaterialGroup.value(materialID);
}
else
{
// Test if the mesh have already an equivalent material
GLC_uint index= materialIndex(*pMaterial);
if (0 == index)
{
addMaterial(pMaterial);
pCurIndexList= new IndexList;
m_MaterialGroup.insert(materialID, pCurIndexList);
}
else
{
pCurIndexList= m_MaterialGroup.value(index);
}
}
const int startVertexIndex= m_Vertex.size();
const int delta= triangles.size();
// Add triangles vertex to the mesh
m_Vertex+= triangles;
for (int i= 0; i < delta; ++i)
{
pCurIndexList->append(startVertexIndex + static_cast<GLuint>(i));
}
// Invalid the geometry
m_GeometryIsValid = false;
m_NumberOfFaces+= delta / 3;
}
// Reverse mesh normal
void GLC_Mesh2::reverseNormal()
{
// Copy Vertex and index data if necessary
if (m_VertexVector.isEmpty())
{
m_VertexVector= getVertexVector();
m_IndexVector= getIndexVector();
}
const int max= m_VertexVector.size();
for (int i= 0; i < max; ++i)
{
m_VertexVector[i].nx= m_VertexVector[i].nx * -1.0f;
m_VertexVector[i].ny= m_VertexVector[i].ny * -1.0f;
m_VertexVector[i].nz= m_VertexVector[i].nz * -1.0f;
}
// Invalid the geometry
m_GeometryIsValid = false;
}
// Specific glExecute method
void GLC_Mesh2::glExecute(bool isSelected, bool transparent)
{
m_IsSelected= isSelected;
GLC_VboGeom::glExecute(isSelected, transparent);
m_IsSelected= false;
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
// Virtual interface for OpenGL Geometry set up.
void GLC_Mesh2::glDraw(bool transparent)
{
Q_ASSERT(m_GeometryIsValid or not m_VertexVector.isEmpty());
const bool vboIsUsed= GLC_State::vboUsed();
IndexList iboList;
MaterialGroupHash::iterator iMaterialGroup;
// Create VBO and IBO
if (!m_GeometryIsValid)
{
// Fill index
iMaterialGroup= m_MaterialGroup.begin();
while (iMaterialGroup != m_MaterialGroup.constEnd())
{
if (!iMaterialGroup.value()->isEmpty())
{
iboList+= *(iMaterialGroup.value());
}
++iMaterialGroup;
}
// Set index vector
m_IndexVector= iboList.toVector();
if (vboIsUsed)
{
// Create VBO
const GLsizei dataNbr= static_cast<GLsizei>(m_VertexVector.size());
const GLsizeiptr dataSize= dataNbr * sizeof(GLC_Vertex);
glBufferData(GL_ARRAY_BUFFER, dataSize, m_VertexVector.data(), GL_STATIC_DRAW);
m_VertexVector.clear();
// Create IBO
const GLsizei indexNbr= static_cast<GLsizei>(iboList.size());
const GLsizeiptr indexSize = indexNbr * sizeof(GLuint);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexSize, m_IndexVector.data(), GL_STATIC_DRAW);
m_IndexVector.clear();
}
}
if (vboIsUsed)
{
// Use VBO
glVertexPointer(3, GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(0));
glNormalPointer(GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(12));
glTexCoordPointer(2, GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(24));
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
// test if color pear vertex is activated
if (m_ColorPearVertex and not m_IsSelected and not GLC_State::isInSelectionMode())
{
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4, GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(32));
}
}
else
{
// Use Vertex Array
float* pVertexData= (float *) m_VertexVector.data();
glVertexPointer(3, GL_FLOAT, sizeof(GLC_Vertex), pVertexData);
glNormalPointer(GL_FLOAT, sizeof(GLC_Vertex), &pVertexData[3]);
glTexCoordPointer(2, GL_FLOAT, sizeof(GLC_Vertex), &pVertexData[6]);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
// test if color pear vertex is activated
if (m_ColorPearVertex and not m_IsSelected and not GLC_State::isInSelectionMode())
{
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4, GL_FLOAT, sizeof(GLC_Vertex), &pVertexData[8]);
}
}
GLC_Material* pCurrentMaterial= NULL;
GLuint max;
GLuint cur= 0;
iMaterialGroup= m_MaterialGroup.begin();
while (iMaterialGroup != m_MaterialGroup.constEnd())
{
if (not iMaterialGroup.value()->isEmpty())
{
if ((not GLC_State::selectionShaderUsed() or not m_IsSelected) and not GLC_State::isInSelectionMode())
{
// Set current material
if (iMaterialGroup.key() == 0)
{
// Use default material
pCurrentMaterial= firstMaterial();
}
else
{
pCurrentMaterial= m_MaterialHash.value(iMaterialGroup.key());
Q_ASSERT(pCurrentMaterial != NULL);
}
if (pCurrentMaterial->isTransparent() == transparent)
{
// Execute current material
if (pCurrentMaterial->getAddRgbaTexture())
{
glEnable(GL_TEXTURE_2D);
}
else
{
glDisable(GL_TEXTURE_2D);
}
// Activate material
pCurrentMaterial->glExecute();
const GLfloat red= pCurrentMaterial->getDiffuseColor().redF();
const GLfloat green= pCurrentMaterial->getDiffuseColor().greenF();
const GLfloat blue= pCurrentMaterial->getDiffuseColor().blueF();
const GLfloat alpha= pCurrentMaterial->getDiffuseColor().alphaF();
glColor4f(red, green, blue, alpha);
if (m_IsSelected) GLC_SelectionMaterial::glExecute();
}
}
else if(not GLC_State::isInSelectionMode())
{
// Use Shader
glDisable(GL_TEXTURE_2D);
}
max= static_cast<GLuint>(iMaterialGroup.value()->size());
if (m_IsSelected or GLC_State::isInSelectionMode() or (pCurrentMaterial->isTransparent() == transparent))
{
// Draw Mesh
if (vboIsUsed)
{
// Use VBO
//glDrawRangeElements(GL_TRIANGLES, 0, max, max, GL_UNSIGNED_INT, BUFFER_OFFSET((cur) * sizeof(unsigned int)));
glDrawElements(GL_TRIANGLES, max, GL_UNSIGNED_INT, BUFFER_OFFSET((cur) * sizeof(unsigned int)));
}
else
{
// Use Vertex Array
glDrawElements(GL_TRIANGLES, max, GL_UNSIGNED_INT, &m_IndexVector.data()[cur]);
}
}
cur+= max;
}
++iMaterialGroup;
}
if (m_ColorPearVertex and not m_IsSelected and not GLC_State::isInSelectionMode())
{
glDisableClientState(GL_COLOR_ARRAY);
glDisable(GL_COLOR_MATERIAL);
}
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Mesh2::GlDraw ", error);
throw(OpenGlException);
}
}
<|endoftext|> |
<commit_before>/*
Q Light Controller Plus
artnetplugin.cpp
Copyright (c) Massimo Callegari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "artnetplugin.h"
#include "configureartnet.h"
#include <QSettings>
#include <QDebug>
ArtNetPlugin::~ArtNetPlugin()
{
}
void ArtNetPlugin::init()
{
m_IOmapping.clear();
foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces())
{
foreach (QNetworkAddressEntry entry, interface.addressEntries())
{
QHostAddress addr = entry.ip();
if (addr.protocol() != QAbstractSocket::IPv6Protocol)
{
ArtNetIO tmpIO;
tmpIO.IPAddress = entry.ip().toString();
if (addr == QHostAddress::LocalHost)
tmpIO.MACAddress = "11:22:33:44:55:66";
else
tmpIO.MACAddress = interface.hardwareAddress();
tmpIO.controller = NULL;
m_IOmapping.append(tmpIO);
m_netInterfaces.append(entry);
}
}
}
}
QString ArtNetPlugin::name()
{
return QString("ArtNet");
}
int ArtNetPlugin::capabilities() const
{
return QLCIOPlugin::Output | QLCIOPlugin::Input | QLCIOPlugin::Infinite;
}
QString ArtNetPlugin::pluginInfo()
{
QString str;
str += QString("<HTML>");
str += QString("<HEAD>");
str += QString("<TITLE>%1</TITLE>").arg(name());
str += QString("</HEAD>");
str += QString("<BODY>");
str += QString("<P>");
str += QString("<H3>%1</H3>").arg(name());
str += tr("This plugin provides DMX output for devices supporting the ArtNet communication protocol.");
str += QString("</P>");
return str;
}
/*********************************************************************
* Outputs
*********************************************************************/
QStringList ArtNetPlugin::outputs()
{
QStringList list;
int j = 0;
if (m_IOmapping.count() == 1)
init();
foreach (ArtNetIO line, m_IOmapping)
{
list << QString(tr("%1: %2")).arg(j + 1).arg(line.IPAddress);
j++;
}
return list;
}
QString ArtNetPlugin::outputInfo(quint32 output)
{
if (m_IOmapping.count() == 1)
init();
if (output >= (quint32)m_IOmapping.length())
return QString();
QString str;
str += QString("<H3>%1 %2</H3>").arg(tr("Output")).arg(outputs()[output]);
str += QString("<P>");
ArtNetController *ctrl = m_IOmapping.at(output).controller;
if (ctrl == NULL || ctrl->type() == ArtNetController::Input)
str += tr("Status: Not open");
else
{
str += tr("Status: Open");
str += QString("<BR>");
str += tr("Nodes discovered: ");
str += QString("%1").arg(ctrl->getNodesList().size());
str += QString("<BR>");
str += tr("Packets sent: ");
str += QString("%1").arg(ctrl->getPacketSentNumber());
}
str += QString("</P>");
str += QString("</BODY>");
str += QString("</HTML>");
return str;
}
bool ArtNetPlugin::openOutput(quint32 output)
{
if (m_IOmapping.count() == 1)
init();
if (output >= (quint32)m_IOmapping.length())
return false;
qDebug() << "Open output with address :" << m_IOmapping.at(output).IPAddress;
// already open ? Just add the type flag
if (m_IOmapping[output].controller != NULL)
{
m_IOmapping[output].controller->setType(
(ArtNetController::Type)(m_IOmapping[output].controller->type() | ArtNetController::Output));
m_IOmapping[output].controller->changeReferenceCount(ArtNetController::Output, +1);
return true;
}
// not open ? Create a new ArtNetController
ArtNetController *controller = new ArtNetController(m_IOmapping.at(output).IPAddress,
m_netInterfaces, m_IOmapping.at(output).MACAddress,
ArtNetController::Output, output, this);
m_IOmapping[output].controller = controller;
return true;
}
void ArtNetPlugin::closeOutput(quint32 output)
{
if (output >= (quint32)m_IOmapping.length())
return;
ArtNetController *controller = m_IOmapping.at(output).controller;
if (controller != NULL)
{
controller->changeReferenceCount(ArtNetController::Output, -1);
// if a ArtNetController is also open as input
// then just remove the output capability
if (controller->type() & ArtNetController::Input)
{
controller->setType(ArtNetController::Input);
}
if (controller->referenceCount(ArtNetController::Input) == 0 &&
controller->referenceCount(ArtNetController::Output) == 0)
{
delete m_IOmapping[output].controller;
m_IOmapping[output].controller = NULL;
}
}
}
void ArtNetPlugin::writeUniverse(quint32 universe, quint32 output, const QByteArray &data)
{
if (output >= (quint32)m_IOmapping.count())
return;
ArtNetController *controller = m_IOmapping[output].controller;
if (controller != NULL)
controller->sendDmx(universe, data);
}
/*************************************************************************
* Inputs
*************************************************************************/
QStringList ArtNetPlugin::inputs()
{
QStringList list;
int j = 0;
if (m_IOmapping.count() == 1)
init();
foreach (ArtNetIO line, m_IOmapping)
{
list << QString(tr("%1: %2")).arg(j + 1).arg(line.IPAddress);
j++;
}
return list;
}
bool ArtNetPlugin::openInput(quint32 input)
{
if (m_IOmapping.count() == 1)
init();
if (input >= (quint32)m_IOmapping.length())
return false;
qDebug() << "Open input with address :" << m_IOmapping.at(input).IPAddress;
// already open ? Just add the type flag
if (m_IOmapping[input].controller != NULL)
{
m_IOmapping[input].controller->setType(
(ArtNetController::Type)(m_IOmapping[input].controller->type() | ArtNetController::Input));
m_IOmapping[input].controller->changeReferenceCount(ArtNetController::Input, +1);
return true;
}
// not open ? Create a new ArtNetController
ArtNetController *controller = new ArtNetController(m_IOmapping.at(input).IPAddress,
m_netInterfaces, m_IOmapping.at(input).MACAddress,
ArtNetController::Input, input, this);
connect(controller, SIGNAL(valueChanged(quint32,quint32,quint32,uchar)),
this, SIGNAL(valueChanged(quint32,quint32,quint32,uchar)));
m_IOmapping[input].controller = controller;
return true;
}
void ArtNetPlugin::closeInput(quint32 input)
{
if (input >= (quint32)m_IOmapping.length())
return;
ArtNetController *controller = m_IOmapping.at(input).controller;
if (controller != NULL)
{
controller->changeReferenceCount(ArtNetController::Input, -1);
// if a ArtNetController is also open as output
// then just remove the input capability
if (controller->type() & ArtNetController::Output)
{
controller->setType(ArtNetController::Output);
}
if (controller->referenceCount(ArtNetController::Input) == 0 &&
controller->referenceCount(ArtNetController::Output) == 0)
{
delete m_IOmapping[input].controller;
m_IOmapping[input].controller = NULL;
}
}
}
QString ArtNetPlugin::inputInfo(quint32 input)
{
if (m_IOmapping.count() == 1)
init();
if (input >= (quint32)m_IOmapping.length())
return QString();
QString str;
str += QString("<H3>%1 %2</H3>").arg(tr("Input")).arg(inputs()[input]);
str += QString("<P>");
ArtNetController *ctrl = m_IOmapping.at(input).controller;
if (ctrl == NULL || ctrl->type() == ArtNetController::Output)
str += tr("Status: Not open");
else
{
str += tr("Status: Open");
str += QString("<BR>");
str += tr("Packets received: ");
str += QString("%1").arg(ctrl->getPacketReceivedNumber());
}
str += QString("</P>");
str += QString("</BODY>");
str += QString("</HTML>");
return str;
}
/*********************************************************************
* Configuration
*********************************************************************/
void ArtNetPlugin::configure()
{
ConfigureArtNet conf(this);
conf.exec();
}
bool ArtNetPlugin::canConfigure()
{
return true;
}
QList<QNetworkAddressEntry> ArtNetPlugin::interfaces()
{
return m_netInterfaces;
}
QList<ArtNetIO> ArtNetPlugin::getIOMapping()
{
return m_IOmapping;
}
/*****************************************************************************
* Plugin export
****************************************************************************/
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
Q_EXPORT_PLUGIN2(artnetplugin, ArtNetPlugin)
#endif
<commit_msg>Plugins/ArtNet: for unknown reasons the interfaces list could be empty too<commit_after>/*
Q Light Controller Plus
artnetplugin.cpp
Copyright (c) Massimo Callegari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "artnetplugin.h"
#include "configureartnet.h"
#include <QSettings>
#include <QDebug>
ArtNetPlugin::~ArtNetPlugin()
{
}
void ArtNetPlugin::init()
{
m_IOmapping.clear();
foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces())
{
foreach (QNetworkAddressEntry entry, interface.addressEntries())
{
QHostAddress addr = entry.ip();
if (addr.protocol() != QAbstractSocket::IPv6Protocol)
{
ArtNetIO tmpIO;
tmpIO.IPAddress = entry.ip().toString();
if (addr == QHostAddress::LocalHost)
tmpIO.MACAddress = "11:22:33:44:55:66";
else
tmpIO.MACAddress = interface.hardwareAddress();
tmpIO.controller = NULL;
m_IOmapping.append(tmpIO);
m_netInterfaces.append(entry);
}
}
}
}
QString ArtNetPlugin::name()
{
return QString("ArtNet");
}
int ArtNetPlugin::capabilities() const
{
return QLCIOPlugin::Output | QLCIOPlugin::Input | QLCIOPlugin::Infinite;
}
QString ArtNetPlugin::pluginInfo()
{
QString str;
str += QString("<HTML>");
str += QString("<HEAD>");
str += QString("<TITLE>%1</TITLE>").arg(name());
str += QString("</HEAD>");
str += QString("<BODY>");
str += QString("<P>");
str += QString("<H3>%1</H3>").arg(name());
str += tr("This plugin provides DMX output for devices supporting the ArtNet communication protocol.");
str += QString("</P>");
return str;
}
/*********************************************************************
* Outputs
*********************************************************************/
QStringList ArtNetPlugin::outputs()
{
QStringList list;
int j = 0;
if (m_IOmapping.count() < 2)
init();
foreach (ArtNetIO line, m_IOmapping)
{
list << QString(tr("%1: %2")).arg(j + 1).arg(line.IPAddress);
j++;
}
return list;
}
QString ArtNetPlugin::outputInfo(quint32 output)
{
if (m_IOmapping.count() < 2)
init();
if (output >= (quint32)m_IOmapping.length())
return QString();
QString str;
str += QString("<H3>%1 %2</H3>").arg(tr("Output")).arg(outputs()[output]);
str += QString("<P>");
ArtNetController *ctrl = m_IOmapping.at(output).controller;
if (ctrl == NULL || ctrl->type() == ArtNetController::Input)
str += tr("Status: Not open");
else
{
str += tr("Status: Open");
str += QString("<BR>");
str += tr("Nodes discovered: ");
str += QString("%1").arg(ctrl->getNodesList().size());
str += QString("<BR>");
str += tr("Packets sent: ");
str += QString("%1").arg(ctrl->getPacketSentNumber());
}
str += QString("</P>");
str += QString("</BODY>");
str += QString("</HTML>");
return str;
}
bool ArtNetPlugin::openOutput(quint32 output)
{
if (m_IOmapping.count() < 2)
init();
if (output >= (quint32)m_IOmapping.length())
return false;
qDebug() << "Open output with address :" << m_IOmapping.at(output).IPAddress;
// already open ? Just add the type flag
if (m_IOmapping[output].controller != NULL)
{
m_IOmapping[output].controller->setType(
(ArtNetController::Type)(m_IOmapping[output].controller->type() | ArtNetController::Output));
m_IOmapping[output].controller->changeReferenceCount(ArtNetController::Output, +1);
return true;
}
// not open ? Create a new ArtNetController
ArtNetController *controller = new ArtNetController(m_IOmapping.at(output).IPAddress,
m_netInterfaces, m_IOmapping.at(output).MACAddress,
ArtNetController::Output, output, this);
m_IOmapping[output].controller = controller;
return true;
}
void ArtNetPlugin::closeOutput(quint32 output)
{
if (output >= (quint32)m_IOmapping.length())
return;
ArtNetController *controller = m_IOmapping.at(output).controller;
if (controller != NULL)
{
controller->changeReferenceCount(ArtNetController::Output, -1);
// if a ArtNetController is also open as input
// then just remove the output capability
if (controller->type() & ArtNetController::Input)
{
controller->setType(ArtNetController::Input);
}
if (controller->referenceCount(ArtNetController::Input) == 0 &&
controller->referenceCount(ArtNetController::Output) == 0)
{
delete m_IOmapping[output].controller;
m_IOmapping[output].controller = NULL;
}
}
}
void ArtNetPlugin::writeUniverse(quint32 universe, quint32 output, const QByteArray &data)
{
if (output >= (quint32)m_IOmapping.count())
return;
ArtNetController *controller = m_IOmapping[output].controller;
if (controller != NULL)
controller->sendDmx(universe, data);
}
/*************************************************************************
* Inputs
*************************************************************************/
QStringList ArtNetPlugin::inputs()
{
QStringList list;
int j = 0;
if (m_IOmapping.count() < 2)
init();
foreach (ArtNetIO line, m_IOmapping)
{
list << QString(tr("%1: %2")).arg(j + 1).arg(line.IPAddress);
j++;
}
return list;
}
bool ArtNetPlugin::openInput(quint32 input)
{
if (m_IOmapping.count() < 2)
init();
if (input >= (quint32)m_IOmapping.length())
return false;
qDebug() << "Open input with address :" << m_IOmapping.at(input).IPAddress;
// already open ? Just add the type flag
if (m_IOmapping[input].controller != NULL)
{
m_IOmapping[input].controller->setType(
(ArtNetController::Type)(m_IOmapping[input].controller->type() | ArtNetController::Input));
m_IOmapping[input].controller->changeReferenceCount(ArtNetController::Input, +1);
return true;
}
// not open ? Create a new ArtNetController
ArtNetController *controller = new ArtNetController(m_IOmapping.at(input).IPAddress,
m_netInterfaces, m_IOmapping.at(input).MACAddress,
ArtNetController::Input, input, this);
connect(controller, SIGNAL(valueChanged(quint32,quint32,quint32,uchar)),
this, SIGNAL(valueChanged(quint32,quint32,quint32,uchar)));
m_IOmapping[input].controller = controller;
return true;
}
void ArtNetPlugin::closeInput(quint32 input)
{
if (input >= (quint32)m_IOmapping.length())
return;
ArtNetController *controller = m_IOmapping.at(input).controller;
if (controller != NULL)
{
controller->changeReferenceCount(ArtNetController::Input, -1);
// if a ArtNetController is also open as output
// then just remove the input capability
if (controller->type() & ArtNetController::Output)
{
controller->setType(ArtNetController::Output);
}
if (controller->referenceCount(ArtNetController::Input) == 0 &&
controller->referenceCount(ArtNetController::Output) == 0)
{
delete m_IOmapping[input].controller;
m_IOmapping[input].controller = NULL;
}
}
}
QString ArtNetPlugin::inputInfo(quint32 input)
{
if (m_IOmapping.count() < 2)
init();
if (input >= (quint32)m_IOmapping.length())
return QString();
QString str;
str += QString("<H3>%1 %2</H3>").arg(tr("Input")).arg(inputs()[input]);
str += QString("<P>");
ArtNetController *ctrl = m_IOmapping.at(input).controller;
if (ctrl == NULL || ctrl->type() == ArtNetController::Output)
str += tr("Status: Not open");
else
{
str += tr("Status: Open");
str += QString("<BR>");
str += tr("Packets received: ");
str += QString("%1").arg(ctrl->getPacketReceivedNumber());
}
str += QString("</P>");
str += QString("</BODY>");
str += QString("</HTML>");
return str;
}
/*********************************************************************
* Configuration
*********************************************************************/
void ArtNetPlugin::configure()
{
ConfigureArtNet conf(this);
conf.exec();
}
bool ArtNetPlugin::canConfigure()
{
return true;
}
QList<QNetworkAddressEntry> ArtNetPlugin::interfaces()
{
return m_netInterfaces;
}
QList<ArtNetIO> ArtNetPlugin::getIOMapping()
{
return m_IOmapping;
}
/*****************************************************************************
* Plugin export
****************************************************************************/
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
Q_EXPORT_PLUGIN2(artnetplugin, ArtNetPlugin)
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2013, Michael Boyle
// See LICENSE file for details
#include "SWSHs.hpp"
#include "Quaternions.hpp"
#define InfinitelyManySolutions 1
#define NotEnoughPointsForDerivative 2
#define VectorSizeNotUnderstood 3
#define VectorSizeMismatch 4
// #define 7
using namespace SphericalFunctions;
using Quaternions::Quaternion;
using std::vector;
using std::complex;
using std::cerr;
using std::endl;
/// Class to create an object returning the factorial of an argument.
vector<double> FactorialTableCalculator() {
/// Note that because a double is returned, only values up to 28!
/// will be exact; higher values will be accurate to machine
/// precision. Values up to 170! only are allowed because higher
/// values overflow.
vector<double> FactorialTable(171);
FactorialTable[0] = 1.0;
for (int i=1;i<171;i++) {
FactorialTable[i] = i*FactorialTable[i-1];
}
return FactorialTable;
}
const std::vector<double> FactorialFunctor::FactorialTable = FactorialTableCalculator();
vector<double> BinomialCoefficientCalculator() {
/// We need (n+1) coefficients for each value of n from 0 (for
/// completeness) up to 2*ellMax (hard coded in the header file).
/// That's a total of
/// >>> from sympy import summation, symbols
/// >>> ellMax, n, k = symbols('ellMax n k', integer=True)
/// >>> summation(n+1, (n, 0, 2*ellMax))
/// 2*ellMax**2 + 3*ellMax + 1
/// With a similar calculation, we can see that the associated access
/// operator needs element (n*(n+1)/2 + k) of the array.
vector<double> BinomialCoefficientTable(2*ellMax*ellMax + 3*ellMax + 1);
unsigned int i=0;
FactorialFunctor Factorial;
for(unsigned int n=0; n<=2*ellMax; ++n) {
for(unsigned int k=0; k<=n; ++k) {
BinomialCoefficientTable[i++] = std::floor(0.5+Factorial(n)/(Factorial(k)*Factorial(n-k)));
}
}
return BinomialCoefficientTable;
}
const std::vector<double> BinomialCoefficientFunctor::BinomialCoefficientTable = BinomialCoefficientCalculator();
vector<double> LadderOperatorFactorCalculator() {
/// We need (2*ell+1) coefficients for each value of ell from 0 (for
/// completeness) up to ellMax (hard coded in the header file).
/// That's a total of
/// >>> from sympy import summation, symbols
/// >>> ell, ellMax, m, mp = symbols('ell ellMax m mp', integer=True)
/// >>> summation(2*ell+1, (ell, 0, ellMax))
/// ellMax**2 + 2*ellMax + 1
/// With a similar calculation, we can see that the associated access
/// operator needs element
/// >>> summation(2*ell+1, (ell, 0, ell-1)) + ell + m
/// ell**2 + ell + m
std::vector<double> FactorTable(ellMax*ellMax + 2*ellMax + 1);
unsigned int i=0;
for(int ell=0; ell<=ellMax; ++ell) {
for(int m=-ell; m<=ell; ++m) {
FactorTable[i++] = std::sqrt(ell*(ell+1)-m*(m+1));
}
}
return FactorTable;
}
const std::vector<double> LadderOperatorFactorFunctor::FactorTable = LadderOperatorFactorCalculator();
std::vector<double> WignerCoefficientCalculator() {
/// We need (2*ell+1)*(2*ell+1) coefficients for each value of ell
/// from 0 (for completenes) up to ellMax (hard coded in the header
/// file). That's a total of
/// >>> from sympy import summation, symbols, simplify
/// >>> from sympy.polys.polyfuncs import horner
/// >>> ell, ellMax, m, mp = symbols('ell ellMax m mp', integer=True)
/// >>> horner(simplify(summation((2*ell+1)**2, (ell, 0, ellMax))))
/// ellMax*(ellMax*(4*ellMax/3 + 4) + 11/3) + 1
/// With a similar calculation, we can see that the associated access
/// operator needs element
/// >>> horner(summation((2*ell+1)**2, (ell, 0, ell-1)) + (2*ell+1)*(ell+mp) + ell + m)
/// ell*(ell*(4*ell/3 + 2) + 5/3) + mp*(2*ell + 1) + m
/// of the array.
std::vector<double> CoefficientTable(int(ellMax*(ellMax*(1.3333333333333333*ellMax + 4) + 3.6666666666666667) + 1 + 0.5));
FactorialFunctor Factorial;
unsigned int i=0;
for(int ell=0; ell<=ellMax; ++ell) {
for(int mp=-ell; mp<=ell; ++mp) {
for(int m=-ell; m<=ell; ++m) {
CoefficientTable[i++] =
std::sqrt( Factorial(ell+m)*Factorial(ell-m)
/ double(Factorial(ell+mp)*Factorial(ell-mp)) );
}
}
}
return CoefficientTable;
}
const std::vector<double> WignerCoefficientFunctor::CoefficientTable = WignerCoefficientCalculator();
/// Construct the D matrix object given the (optional) rotor.
WignerDMatrix::WignerDMatrix(const Quaternion& R)
: BinomialCoefficient(), WignerCoefficient(),
Ra(R[0], R[3]), Rb(R[2], R[1]),
absRa(abs(Ra)), absRb(abs(Rb)), absRRatioSquared(absRb*absRb/(absRa*absRa))
{ }
/// Reset the rotor for this object to the given value.
WignerDMatrix& WignerDMatrix::SetRotation(const Quaternion& R) {
Ra = std::complex<double>(R[0], R[3]);
Rb = std::complex<double>(R[2], R[1]);
absRa = abs(Ra);
absRb = abs(Rb);
absRRatioSquared = absRb*absRb/(absRa*absRa);
return *this;
}
/// Evaluate the D matrix element for the given (ell, mp, m) indices.
std::complex<double> WignerDMatrix::operator()(const int ell, const int mp, const int m) const {
if(absRa < epsilon) {
return (mp!=-m ? 0.0 : ((ell+mp)%2==0 ? 1.0 : -1.0) * std::pow(Rb, 2*m) );
}
if(absRb < epsilon) {
return (mp!=m ? 0.0 : std::pow(Ra, 2*m) );
}
if(absRa < 1.e-3) { // Deal with NANs in certain cases
const std::complex<double> Prefactor =
WignerCoefficient(ell, mp, m) * std::pow(Ra, m+mp) * std::pow(Rb, m-mp);
const int rhoMin = std::max(0,mp-m);
const int rhoMax = std::min(ell+mp,ell-m);
const double absRaSquared = absRa*absRa;
const double absRbSquared = absRb*absRb;
double Sum = 0.0;
for(int rho=rhoMax; rho>=rhoMin; --rho) {
const double aTerm = std::pow(absRaSquared, ell-m-rho);
if(aTerm != aTerm || aTerm<1.e-100) { // This assumes --fast-math is off
Sum *= absRbSquared;
continue;
}
Sum = ( (rho%2==0 ? 1 : -1) * BinomialCoefficient(ell+mp,rho) * BinomialCoefficient(ell-mp, ell-rho-m) * aTerm )
+ ( Sum * absRbSquared );
}
return Prefactor * Sum * std::pow(absRbSquared, rhoMin);
}
const std::complex<double> Prefactor =
(WignerCoefficient(ell, mp, m) * std::pow(absRa, 2*ell-2*m))
* std::pow(Ra, m+mp) * std::pow(Rb, m-mp);
const int rhoMin = std::max(0,mp-m);
const int rhoMax = std::min(ell+mp,ell-m);
double Sum = 0.0;
for(int rho=rhoMax; rho>=rhoMin; --rho) {
Sum = ( (rho%2==0 ? 1 : -1) * BinomialCoefficient(ell+mp,rho) * BinomialCoefficient(ell-mp, ell-rho-m) )
+ ( Sum * absRRatioSquared );
}
return Prefactor * Sum * std::pow(absRRatioSquared, rhoMin);
}
<commit_msg>Use integer arithmetic for indexing<commit_after>// Copyright (c) 2013, Michael Boyle
// See LICENSE file for details
#include "SWSHs.hpp"
#include "Quaternions.hpp"
#define InfinitelyManySolutions 1
#define NotEnoughPointsForDerivative 2
#define VectorSizeNotUnderstood 3
#define VectorSizeMismatch 4
// #define 7
using namespace SphericalFunctions;
using Quaternions::Quaternion;
using std::vector;
using std::complex;
using std::cerr;
using std::endl;
/// Class to create an object returning the factorial of an argument.
vector<double> FactorialTableCalculator() {
/// Note that because a double is returned, only values up to 28!
/// will be exact; higher values will be accurate to machine
/// precision. Values up to 170! only are allowed because higher
/// values overflow.
vector<double> FactorialTable(171);
FactorialTable[0] = 1.0;
for (int i=1;i<171;i++) {
FactorialTable[i] = i*FactorialTable[i-1];
}
return FactorialTable;
}
const std::vector<double> FactorialFunctor::FactorialTable = FactorialTableCalculator();
vector<double> BinomialCoefficientCalculator() {
/// We need (n+1) coefficients for each value of n from 0 (for
/// completeness) up to 2*ellMax (hard coded in the header file).
/// That's a total of
/// >>> from sympy import summation, symbols
/// >>> ellMax, n, k = symbols('ellMax n k', integer=True)
/// >>> summation(n+1, (n, 0, 2*ellMax))
/// 2*ellMax**2 + 3*ellMax + 1
/// With a similar calculation, we can see that the associated access
/// operator needs element (n*(n+1)/2 + k) of the array.
vector<double> BinomialCoefficientTable(2*ellMax*ellMax + 3*ellMax + 1);
unsigned int i=0;
FactorialFunctor Factorial;
for(unsigned int n=0; n<=2*ellMax; ++n) {
for(unsigned int k=0; k<=n; ++k) {
BinomialCoefficientTable[i++] = std::floor(0.5+Factorial(n)/(Factorial(k)*Factorial(n-k)));
}
}
return BinomialCoefficientTable;
}
const std::vector<double> BinomialCoefficientFunctor::BinomialCoefficientTable = BinomialCoefficientCalculator();
vector<double> LadderOperatorFactorCalculator() {
/// We need (2*ell+1) coefficients for each value of ell from 0 (for
/// completeness) up to ellMax (hard coded in the header file).
/// That's a total of
/// >>> from sympy import summation, symbols
/// >>> ell, ellMax, m, mp = symbols('ell ellMax m mp', integer=True)
/// >>> summation(2*ell+1, (ell, 0, ellMax))
/// ellMax**2 + 2*ellMax + 1
/// With a similar calculation, we can see that the associated access
/// operator needs element
/// >>> summation(2*ell+1, (ell, 0, ell-1)) + ell + m
/// ell**2 + ell + m
std::vector<double> FactorTable(ellMax*ellMax + 2*ellMax + 1);
unsigned int i=0;
for(int ell=0; ell<=ellMax; ++ell) {
for(int m=-ell; m<=ell; ++m) {
FactorTable[i++] = std::sqrt(ell*(ell+1)-m*(m+1));
}
}
return FactorTable;
}
const std::vector<double> LadderOperatorFactorFunctor::FactorTable = LadderOperatorFactorCalculator();
std::vector<double> WignerCoefficientCalculator() {
/// We need (2*ell+1)*(2*ell+1) coefficients for each value of ell
/// from 0 (for completenes) up to ellMax (hard coded in the header
/// file). That's a total of
/// >>> from sympy import summation, symbols, simplify
/// >>> from sympy.polys.polyfuncs import horner
/// >>> ell, ellMax, m, mp = symbols('ell ellMax m mp', integer=True)
/// >>> horner(simplify(summation((2*ell+1)**2, (ell, 0, ellMax))))
/// ellMax*(ellMax*(4*ellMax/3 + 4) + 11/3) + 1
/// With a similar calculation, we can see that the associated access
/// operator needs element
/// >>> horner(summation((2*ell+1)**2, (ell, 0, ell-1)) + (2*ell+1)*(ell+mp) + ell + m)
/// ell*(ell*(4*ell/3 + 2) + 5/3) + mp*(2*ell + 1) + m
/// of the array.
std::vector<double> CoefficientTable(ellMax*(ellMax*(4*ellMax + 12) + 11)/3 + 1);
FactorialFunctor Factorial;
unsigned int i=0;
for(int ell=0; ell<=ellMax; ++ell) {
for(int mp=-ell; mp<=ell; ++mp) {
for(int m=-ell; m<=ell; ++m) {
CoefficientTable[i++] =
std::sqrt( Factorial(ell+m)*Factorial(ell-m)
/ double(Factorial(ell+mp)*Factorial(ell-mp)) );
}
}
}
return CoefficientTable;
}
const std::vector<double> WignerCoefficientFunctor::CoefficientTable = WignerCoefficientCalculator();
/// Construct the D matrix object given the (optional) rotor.
WignerDMatrix::WignerDMatrix(const Quaternion& R)
: BinomialCoefficient(), WignerCoefficient(),
Ra(R[0], R[3]), Rb(R[2], R[1]),
absRa(abs(Ra)), absRb(abs(Rb)), absRRatioSquared(absRb*absRb/(absRa*absRa))
{ }
/// Reset the rotor for this object to the given value.
WignerDMatrix& WignerDMatrix::SetRotation(const Quaternion& R) {
Ra = std::complex<double>(R[0], R[3]);
Rb = std::complex<double>(R[2], R[1]);
absRa = abs(Ra);
absRb = abs(Rb);
absRRatioSquared = absRb*absRb/(absRa*absRa);
return *this;
}
/// Evaluate the D matrix element for the given (ell, mp, m) indices.
std::complex<double> WignerDMatrix::operator()(const int ell, const int mp, const int m) const {
if(absRa < epsilon) {
return (mp!=-m ? 0.0 : ((ell+mp)%2==0 ? 1.0 : -1.0) * std::pow(Rb, 2*m) );
}
if(absRb < epsilon) {
return (mp!=m ? 0.0 : std::pow(Ra, 2*m) );
}
if(absRa < 1.e-3) { // Deal with NANs in certain cases
const std::complex<double> Prefactor =
WignerCoefficient(ell, mp, m) * std::pow(Ra, m+mp) * std::pow(Rb, m-mp);
const int rhoMin = std::max(0,mp-m);
const int rhoMax = std::min(ell+mp,ell-m);
const double absRaSquared = absRa*absRa;
const double absRbSquared = absRb*absRb;
double Sum = 0.0;
for(int rho=rhoMax; rho>=rhoMin; --rho) {
const double aTerm = std::pow(absRaSquared, ell-m-rho);
if(aTerm != aTerm || aTerm<1.e-100) { // This assumes --fast-math is off
Sum *= absRbSquared;
continue;
}
Sum = ( (rho%2==0 ? 1 : -1) * BinomialCoefficient(ell+mp,rho) * BinomialCoefficient(ell-mp, ell-rho-m) * aTerm )
+ ( Sum * absRbSquared );
}
return Prefactor * Sum * std::pow(absRbSquared, rhoMin);
}
const std::complex<double> Prefactor =
(WignerCoefficient(ell, mp, m) * std::pow(absRa, 2*ell-2*m))
* std::pow(Ra, m+mp) * std::pow(Rb, m-mp);
const int rhoMin = std::max(0,mp-m);
const int rhoMax = std::min(ell+mp,ell-m);
double Sum = 0.0;
for(int rho=rhoMax; rho>=rhoMin; --rho) {
Sum = ( (rho%2==0 ? 1 : -1) * BinomialCoefficient(ell+mp,rho) * BinomialCoefficient(ell-mp, ell-rho-m) )
+ ( Sum * absRRatioSquared );
}
return Prefactor * Sum * std::pow(absRRatioSquared, rhoMin);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: accpage.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2004-08-12 12:11:15 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _ACCPAGE_HXX
#define _ACCPAGE_HXX
#ifndef _ACCCONTEXT_HXX
#include "acccontext.hxx"
#endif
/**
* accessibility implementation for the page (SwPageFrm)
* The page is _only_ visible in the page preview. For the regular
* document view, it doesn't make sense to add this additional element
* into the hierarchy. For the page preview, however, the page is the
* important.
*/
class SwAccessiblePage : public SwAccessibleContext
{
sal_Bool bIsSelected; // protected by base class mutex
sal_Bool IsSelected();
protected:
// return the bounding box for the page in page preview mode
SwRect GetBounds( /* const SwFrm *pFrm =0 */ );
// Set states for getAccessibleStateSet.
// This drived class additionaly sets
// FOCUSABLE(1) and FOCUSED(+)
virtual void GetStates( ::utl::AccessibleStateSetHelper& rStateSet );
virtual void _InvalidateCursorPos();
virtual void _InvalidateFocus();
virtual ~SwAccessiblePage();
public:
// convenience constructor to avoid typecast;
// may only be called with SwPageFrm argument
SwAccessiblePage( SwAccessibleMap* pMap, const SwFrm *pFrame );
//
// XAccessibleContext methods that need to be overridden
//
virtual ::rtl::OUString SAL_CALL getAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException);
//
// XServiceInfo
//
virtual ::rtl::OUString SAL_CALL getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService (
const ::rtl::OUString& sServiceName)
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
getSupportedServiceNames (void)
throw (::com::sun::star::uno::RuntimeException);
//===== XTypeProvider ====================================================
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool HasCursor(); // required by map to remember that object
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.600); FILE MERGED 2005/09/05 13:38:24 rt 1.5.600.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accpage.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:53:17 $
*
* 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 _ACCPAGE_HXX
#define _ACCPAGE_HXX
#ifndef _ACCCONTEXT_HXX
#include "acccontext.hxx"
#endif
/**
* accessibility implementation for the page (SwPageFrm)
* The page is _only_ visible in the page preview. For the regular
* document view, it doesn't make sense to add this additional element
* into the hierarchy. For the page preview, however, the page is the
* important.
*/
class SwAccessiblePage : public SwAccessibleContext
{
sal_Bool bIsSelected; // protected by base class mutex
sal_Bool IsSelected();
protected:
// return the bounding box for the page in page preview mode
SwRect GetBounds( /* const SwFrm *pFrm =0 */ );
// Set states for getAccessibleStateSet.
// This drived class additionaly sets
// FOCUSABLE(1) and FOCUSED(+)
virtual void GetStates( ::utl::AccessibleStateSetHelper& rStateSet );
virtual void _InvalidateCursorPos();
virtual void _InvalidateFocus();
virtual ~SwAccessiblePage();
public:
// convenience constructor to avoid typecast;
// may only be called with SwPageFrm argument
SwAccessiblePage( SwAccessibleMap* pMap, const SwFrm *pFrame );
//
// XAccessibleContext methods that need to be overridden
//
virtual ::rtl::OUString SAL_CALL getAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException);
//
// XServiceInfo
//
virtual ::rtl::OUString SAL_CALL getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService (
const ::rtl::OUString& sServiceName)
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
getSupportedServiceNames (void)
throw (::com::sun::star::uno::RuntimeException);
//===== XTypeProvider ====================================================
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool HasCursor(); // required by map to remember that object
};
#endif
<|endoftext|> |
<commit_before>/* runner_common.cc
Wolfgang Sourdeau, 10 December 2014
Copyright (c) 2014 Datacratic. All rights reserved.
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "jml/arch/exception.h"
#include "runner_common.h"
using namespace std;
using namespace Datacratic;
namespace Datacratic {
std::string
strLaunchError(LaunchError error)
{
switch (error) {
case LaunchError::NONE: return "no error";
case LaunchError::READ_STATUS_PIPE: return "read() on status pipe";
case LaunchError::STATUS_PIPE_WRONG_LENGTH:
return "wrong message size reading launch pipe";
case LaunchError::SUBTASK_LAUNCH: return "exec() launching subtask";
case LaunchError::SUBTASK_WAITPID: return "waitpid waiting for subtask";
case LaunchError::WRONG_CHILD: return "waitpid() returned the wrong child";
}
throw ML::Exception("unknown error launch error code %d",
error);
}
std::string
statusStateAsString(ProcessState statusState)
{
switch (statusState) {
case ProcessState::UNKNOWN: return "UNKNOWN";
case ProcessState::LAUNCHING: return "LAUNCHING";
case ProcessState::RUNNING: return "RUNNING";
case ProcessState::STOPPED: return "STOPPED";
case ProcessState::DONE: return "DONE";
}
throw ML::Exception("unknown status %d", statusState);
}
}
/****************************************************************************/
/* PROCESS STATUS */
/****************************************************************************/
ProcessStatus::
ProcessStatus()
{
// Doing it this way keeps ValGrind happy
::memset(this, 0, sizeof(*this));
state = ProcessState::UNKNOWN;
pid = -1;
childStatus = -1;
launchErrno = 0;
launchErrorCode = LaunchError::NONE;
}
void
ProcessStatus::
setErrorCodes(int newLaunchErrno, LaunchError newErrorCode)
{
launchErrno = newLaunchErrno;
launchErrorCode = newErrorCode;
}
/****************************************************************************/
/* PROCESS FDS */
/****************************************************************************/
ProcessFds::
ProcessFds()
: stdIn(::fileno(stdin)),
stdOut(::fileno(stdout)),
stdErr(::fileno(stderr)),
statusFd(-1)
{
}
/* child api */
void
ProcessFds::
closeRemainingFds()
{
struct rlimit limits;
::getrlimit(RLIMIT_NOFILE, &limits);
for (int fd = 0; fd < limits.rlim_cur; fd++) {
if ((fd != STDIN_FILENO || stdIn == -1)
&& fd != STDOUT_FILENO && fd != STDERR_FILENO
&& fd != statusFd) {
::close(fd);
}
}
}
void
ProcessFds::
dupToStdStreams()
{
auto dupToStdStream = [&] (int oldFd, int newFd) {
if (oldFd != newFd) {
int rc = ::dup2(oldFd, newFd);
if (rc == -1) {
throw ML::Exception(errno,
"ProcessFds::dupToStdStream dup2");
}
}
};
if (stdIn != -1) {
dupToStdStream(stdIn, STDIN_FILENO);
}
dupToStdStream(stdOut, STDOUT_FILENO);
dupToStdStream(stdErr, STDERR_FILENO);
}
/* parent & child api */
void
ProcessFds::
close()
{
auto closeIfNotEqual = [&] (int & fd, int notValue) {
if (fd != notValue) {
::close(fd);
}
};
closeIfNotEqual(stdIn, STDIN_FILENO);
closeIfNotEqual(stdOut, STDOUT_FILENO);
closeIfNotEqual(stdErr, STDERR_FILENO);
closeIfNotEqual(statusFd, -1);
}
void
ProcessFds::
encodeToBuffer(char * buffer, size_t bufferSize)
const
{
int written = ::sprintf(buffer, "%.8x/%.8x/%.8x/%.8x",
stdIn, stdOut, stdErr, statusFd);
if (written < 0) {
throw ML::Exception("encoding failed");
}
/* bufferSize must be equal to the number of bytes used above, plus 1 for
'\0' */
if (written >= bufferSize) {
throw ML::Exception("buffer overflow");
}
}
void
ProcessFds::
decodeFromBuffer(const char * buffer)
{
int decoded = ::sscanf(buffer, "%x/%x/%x/%x",
&stdIn, &stdOut, &stdErr, &statusFd);
if (decoded < 0) {
throw ML::Exception(errno, "decoding failed");
}
}
void
ProcessFds::
writeStatus(const ProcessStatus & status)
const
{
int res = ::write(statusFd, &status, sizeof(status));
if (res == -1)
throw ML::Exception(errno, "write");
else if (res != sizeof(status))
throw ML::Exception("writing of status is incomplete");
}
<commit_msg>Don't spam with system calls to close all FDs<commit_after>/* runner_common.cc
Wolfgang Sourdeau, 10 December 2014
Copyright (c) 2014 Datacratic. All rights reserved.
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "jml/arch/exception.h"
#include "runner_common.h"
using namespace std;
using namespace Datacratic;
namespace Datacratic {
std::string
strLaunchError(LaunchError error)
{
switch (error) {
case LaunchError::NONE: return "no error";
case LaunchError::READ_STATUS_PIPE: return "read() on status pipe";
case LaunchError::STATUS_PIPE_WRONG_LENGTH:
return "wrong message size reading launch pipe";
case LaunchError::SUBTASK_LAUNCH: return "exec() launching subtask";
case LaunchError::SUBTASK_WAITPID: return "waitpid waiting for subtask";
case LaunchError::WRONG_CHILD: return "waitpid() returned the wrong child";
}
throw ML::Exception("unknown error launch error code %d",
error);
}
std::string
statusStateAsString(ProcessState statusState)
{
switch (statusState) {
case ProcessState::UNKNOWN: return "UNKNOWN";
case ProcessState::LAUNCHING: return "LAUNCHING";
case ProcessState::RUNNING: return "RUNNING";
case ProcessState::STOPPED: return "STOPPED";
case ProcessState::DONE: return "DONE";
}
throw ML::Exception("unknown status %d", statusState);
}
}
/****************************************************************************/
/* PROCESS STATUS */
/****************************************************************************/
ProcessStatus::
ProcessStatus()
{
// Doing it this way keeps ValGrind happy
::memset(this, 0, sizeof(*this));
state = ProcessState::UNKNOWN;
pid = -1;
childStatus = -1;
launchErrno = 0;
launchErrorCode = LaunchError::NONE;
}
void
ProcessStatus::
setErrorCodes(int newLaunchErrno, LaunchError newErrorCode)
{
launchErrno = newLaunchErrno;
launchErrorCode = newErrorCode;
}
/****************************************************************************/
/* PROCESS FDS */
/****************************************************************************/
ProcessFds::
ProcessFds()
: stdIn(::fileno(stdin)),
stdOut(::fileno(stdout)),
stdErr(::fileno(stderr)),
statusFd(-1)
{
}
/* child api */
void
ProcessFds::
closeRemainingFds()
{
#if 0
struct rlimit limits;
::getrlimit(RLIMIT_NOFILE, &limits);
for (int fd = 0; fd < limits.rlim_cur; fd++) {
if ((fd != STDIN_FILENO || stdIn == -1)
&& fd != STDOUT_FILENO && fd != STDERR_FILENO
&& fd != statusFd) {
::close(fd);
}
}
#endif
}
void
ProcessFds::
dupToStdStreams()
{
auto dupToStdStream = [&] (int oldFd, int newFd) {
if (oldFd != newFd) {
int rc = ::dup2(oldFd, newFd);
if (rc == -1) {
throw ML::Exception(errno,
"ProcessFds::dupToStdStream dup2");
}
}
};
if (stdIn != -1) {
dupToStdStream(stdIn, STDIN_FILENO);
}
dupToStdStream(stdOut, STDOUT_FILENO);
dupToStdStream(stdErr, STDERR_FILENO);
}
/* parent & child api */
void
ProcessFds::
close()
{
auto closeIfNotEqual = [&] (int & fd, int notValue) {
if (fd != notValue) {
::close(fd);
}
};
closeIfNotEqual(stdIn, STDIN_FILENO);
closeIfNotEqual(stdOut, STDOUT_FILENO);
closeIfNotEqual(stdErr, STDERR_FILENO);
closeIfNotEqual(statusFd, -1);
}
void
ProcessFds::
encodeToBuffer(char * buffer, size_t bufferSize)
const
{
int written = ::sprintf(buffer, "%.8x/%.8x/%.8x/%.8x",
stdIn, stdOut, stdErr, statusFd);
if (written < 0) {
throw ML::Exception("encoding failed");
}
/* bufferSize must be equal to the number of bytes used above, plus 1 for
'\0' */
if (written >= bufferSize) {
throw ML::Exception("buffer overflow");
}
}
void
ProcessFds::
decodeFromBuffer(const char * buffer)
{
int decoded = ::sscanf(buffer, "%x/%x/%x/%x",
&stdIn, &stdOut, &stdErr, &statusFd);
if (decoded < 0) {
throw ML::Exception(errno, "decoding failed");
}
}
void
ProcessFds::
writeStatus(const ProcessStatus & status)
const
{
int res = ::write(statusFd, &status, sizeof(status));
if (res == -1)
throw ML::Exception(errno, "write");
else if (res != sizeof(status))
throw ML::Exception("writing of status is incomplete");
}
<|endoftext|> |
<commit_before><commit_msg>coverity#736154 Dereference null return value<commit_after><|endoftext|> |
<commit_before>/* Copyright (c) 2017-2021 hors<[email protected]>
*
* 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 "subdevice.h"
SubDevice::SubDevice(QIODevice *pDevice, qint64 nOffset, qint64 nSize, QObject *pParent) : QIODevice(pParent)
{
if(nOffset>pDevice->size())
{
nOffset=pDevice->size();
}
if(nOffset<0)
{
nOffset=0;
}
if((nSize+nOffset>pDevice->size())||(nSize==-1)) // TODO Check
{
nSize=pDevice->size()-nOffset;
}
if(nSize+nOffset<0)
{
nSize=0;
}
this->g_pDevice=pDevice;
this->g_nOffset=nOffset;
this->g_nSize=nSize;
// reset();
pDevice->seek(nOffset);
}
SubDevice::~SubDevice()
{
if(isOpen())
{
_close();
}
}
qint64 SubDevice::getInitOffset()
{
return g_nOffset;
}
qint64 SubDevice::size() const
{
return g_nSize;
}
//qint64 SubDevice::bytesAvailable() const
//{
// return nSize;
//}
bool SubDevice::isSequential() const
{
return false;
}
bool SubDevice::seek(qint64 nPos)
{
bool bResult=false;
if((nPos<g_nSize)&&(nPos>=0))
{
if(g_pDevice->seek(g_nOffset+nPos))
{
bResult=QIODevice::seek(nPos);
}
}
return bResult;
}
bool SubDevice::reset()
{
return seek(0);
}
bool SubDevice::open(QIODevice::OpenMode mode)
{
setOpenMode(mode);
return true;
}
bool SubDevice::atEnd() const
{
return (bytesAvailable()==0);
}
void SubDevice::close()
{
_close();
}
qint64 SubDevice::pos() const
{
// return pDevice->pos()-nOffset;
return QIODevice::pos();
}
void SubDevice::_close()
{
setOpenMode(NotOpen);
}
qint64 SubDevice::readData(char *pData, qint64 nMaxSize)
{
nMaxSize=qMin(nMaxSize,g_nSize-pos());
qint64 nLen=g_pDevice->read(pData,nMaxSize);
return nLen;
}
qint64 SubDevice::writeData(const char *pData, qint64 nMaxSize)
{
nMaxSize=qMin(nMaxSize,g_nSize-pos());
qint64 nLen=g_pDevice->write(pData,nMaxSize);
return nLen;
}
void SubDevice::setErrorString(const QString &sString)
{
QIODevice::setErrorString(sString);
}
<commit_msg>Fix: 2022-01-09<commit_after>/* Copyright (c) 2017-2022 hors<[email protected]>
*
* 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 "subdevice.h"
SubDevice::SubDevice(QIODevice *pDevice, qint64 nOffset, qint64 nSize, QObject *pParent) : QIODevice(pParent)
{
if(nOffset>pDevice->size())
{
nOffset=pDevice->size();
}
if(nOffset<0)
{
nOffset=0;
}
if((nSize+nOffset>pDevice->size())||(nSize==-1)) // TODO Check
{
nSize=pDevice->size()-nOffset;
}
if(nSize+nOffset<0)
{
nSize=0;
}
this->g_pDevice=pDevice;
this->g_nOffset=nOffset;
this->g_nSize=nSize;
// reset();
pDevice->seek(nOffset);
}
SubDevice::~SubDevice()
{
if(isOpen())
{
_close();
}
}
qint64 SubDevice::getInitOffset()
{
return g_nOffset;
}
qint64 SubDevice::size() const
{
return g_nSize;
}
//qint64 SubDevice::bytesAvailable() const
//{
// return nSize;
//}
bool SubDevice::isSequential() const
{
return false;
}
bool SubDevice::seek(qint64 nPos)
{
bool bResult=false;
if((nPos<g_nSize)&&(nPos>=0))
{
if(g_pDevice->seek(g_nOffset+nPos))
{
bResult=QIODevice::seek(nPos);
}
}
return bResult;
}
bool SubDevice::reset()
{
return seek(0);
}
bool SubDevice::open(QIODevice::OpenMode mode)
{
setOpenMode(mode);
return true;
}
bool SubDevice::atEnd() const
{
return (bytesAvailable()==0);
}
void SubDevice::close()
{
_close();
}
qint64 SubDevice::pos() const
{
// return pDevice->pos()-nOffset;
return QIODevice::pos();
}
void SubDevice::_close()
{
setOpenMode(NotOpen);
}
qint64 SubDevice::readData(char *pData, qint64 nMaxSize)
{
nMaxSize=qMin(nMaxSize,g_nSize-pos());
qint64 nLen=g_pDevice->read(pData,nMaxSize);
return nLen;
}
qint64 SubDevice::writeData(const char *pData, qint64 nMaxSize)
{
nMaxSize=qMin(nMaxSize,g_nSize-pos());
qint64 nLen=g_pDevice->write(pData,nMaxSize);
return nLen;
}
void SubDevice::setErrorString(const QString &sString)
{
QIODevice::setErrorString(sString);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: parcss1.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:47:01 $
*
* 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 _PARCSS1_HXX
#define _PARCSS1_HXX
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
class Color;
/* */
// Die Tokens des CSS1-Parsers
enum CSS1Token
{
CSS1_NULL,
CSS1_UNKOWN,
CSS1_IDENT,
CSS1_STRING,
CSS1_NUMBER,
CSS1_PERCENTAGE,
CSS1_LENGTH, // eine absolute Groesse in 1/100 MM
CSS1_PIXLENGTH, // eine Pixel-Groesse
CSS1_EMS,
CSS1_EMX,
CSS1_HEXCOLOR,
CSS1_DOT_W_WS,
CSS1_DOT_WO_WS,
CSS1_COLON,
CSS1_SLASH,
CSS1_PLUS,
CSS1_MINUS,
CSS1_OBRACE,
CSS1_CBRACE,
CSS1_SEMICOLON,
CSS1_COMMA,
CSS1_HASH,
CSS1_IMPORT_SYM,
// Feature: PrintExt
CSS1_PAGE_SYM,
// /Feature: PrintExt
CSS1_IMPORTANT_SYM,
CSS1_URL,
CSS1_RGB
};
// die Zustaende des Parsers
enum CSS1ParserState
{
CSS1_PAR_ACCEPTED = 0,
CSS1_PAR_WORKING,
CSS1_PAR_ERROR
};
/* */
enum CSS1SelectorType
{
CSS1_SELTYPE_ELEMENT,
CSS1_SELTYPE_ELEM_CLASS,
CSS1_SELTYPE_CLASS,
CSS1_SELTYPE_ID,
CSS1_SELTYPE_PSEUDO,
// Feature: PrintExt
CSS1_SELTYPE_PAGE
// /Feature: PrintExt
};
// Die folegende Klasse beschreibt einen Simple-Selector, also
// - einen HTML-Element-Namen
// - einen HTML-Element-Namen mit Klasse (durch '.' getrennt)
// - eine Klasse (ohne Punkt)
// - eine mit ID=xxx gesetzte ID aus einem HTML-Dokument
// oder
// - ein Pseudo-Element
//
// Die Simple-Sektoren werden in einer Liste zu vollstaendigen
// Selektoren verkettet
class CSS1Selector
{
CSS1SelectorType eType; // Art des Selektors
String aSelector; // der Selektor selbst
CSS1Selector *pNext; // die naechste Komponente
public:
CSS1Selector( CSS1SelectorType eTyp, const String &rSel )
: eType(eTyp), aSelector( rSel ), pNext( 0 )
{}
~CSS1Selector();
CSS1SelectorType GetType() const { return eType; }
const String& GetString() const { return aSelector; }
void SetNext( CSS1Selector *pNxt ) { pNext = pNxt; }
const CSS1Selector *GetNext() const { return pNext; }
};
/* */
// Die folegende Klasse beschreibt einen Teil-Ausdruck einer
// CSS1-Deklaration sie besteht aus
//
// - dem Typ des Ausdrucks (entspricht dem Token)
// - dem eigentlichen Wert als String und ggf. double
// der double-Wert enthaelt das Vorzeichen fuer NUMBER und LENGTH
// - und dem Operator, mit dem er mit dem *Vorganger*-Ausdruck
// verknuepft ist.
//
struct CSS1Expression
{
sal_Unicode cOp; // Art der Verkuepfung mit dem Vorgaenger
CSS1Token eType; // der Typ des Wertes
String aValue; // und sein Wert als String
double nValue; // und als Zahl (TWIPs fuer LENGTH)
CSS1Expression *pNext; // die naechste Komponente
public:
CSS1Expression( CSS1Token eTyp, const String &rVal,
double nVal, sal_Unicode cO = 0 )
: cOp(cO), eType(eTyp), aValue(rVal), nValue(nVal), pNext(0)
{}
~CSS1Expression();
inline void Set( CSS1Token eTyp, const String &rVal, double nVal,
sal_Unicode cO = 0 );
CSS1Token GetType() const { return eType; }
const String& GetString() const { return aValue; }
double GetNumber() const { return nValue; }
inline sal_uInt32 GetULength() const;
inline sal_Int32 GetSLength() const;
sal_Unicode GetOp() const { return cOp; }
sal_Bool GetURL( String& rURL ) const;
sal_Bool GetColor( Color &rRGB ) const;
void SetNext( CSS1Expression *pNxt ) { pNext = pNxt; }
const CSS1Expression *GetNext() const { return pNext; }
};
inline void CSS1Expression::Set( CSS1Token eTyp, const String &rVal,
double nVal, sal_Unicode cO )
{
cOp = cO; eType = eTyp; aValue = rVal; nValue = nVal; pNext = 0;
}
inline sal_uInt32 CSS1Expression::GetULength() const
{
return nValue < 0. ? 0UL : (sal_uInt32)(nValue + .5);
}
inline sal_Int32 CSS1Expression::GetSLength() const
{
return (sal_Int32)(nValue + (nValue < 0. ? -.5 : .5 ));
}
/* */
// Diese Klasse parst den Inhalt eines Style-Elements oder eine Style-Option
// und bereitet ihn ein wenig auf.
//
// Das Ergebnis des Parsers wird durch die Mehtoden SelectorParsed()
// und DeclarationParsed() an abgeleitete Parser uebergeben. Bsp:
//
// H1, H2 { font-weight: bold; text-align: right }
// | | | |
// | | | DeclP( 'text-align', 'right' )
// | | DeclP( 'font-weight', 'bold' )
// | SelP( 'H2', sal_False )
// SelP( 'H1', sal_True )
//
class CSS1Parser
{
sal_Bool bWhiteSpace : 1; // White-Space gelesen?
sal_Bool bEOF : 1; // Ende des "Files" ?
sal_Unicode cNextCh; // naechstes Zeichen
xub_StrLen nInPos; // aktuelle Position im Input-String
sal_uInt32 nlLineNr; // akt. Zeilen Nummer
sal_uInt32 nlLinePos; // akt. Spalten Nummer
double nValue; // der Wert des Tokens als Zahl
CSS1ParserState eState; // der akteulle Zustand der Parsers
CSS1Token nToken; // das aktuelle Token
String aIn; // der zu parsende String
String aToken; // das Token als String
// Parsen vorbereiten
void InitRead( const String& rIn );
// das naechste Zeichen holen
sal_Unicode GetNextChar();
// das naechste Token holen
CSS1Token GetNextToken();
// arbeitet der Parser noch?
sal_Bool IsParserWorking() const { return CSS1_PAR_WORKING == eState; }
sal_Bool IsEOF() const { return bEOF; }
sal_uInt32 IncLineNr() { return ++nlLineNr; }
sal_uInt32 IncLinePos() { return ++nlLinePos; }
inline sal_uInt32 SetLineNr( sal_uInt32 nlNum ); // inline unten
inline sal_uInt32 SetLinePos( sal_uInt32 nlPos ); // inline unten
// Parsen von Teilen der Grammatik
void ParseStyleSheet();
void ParseRule();
CSS1Selector *ParseSelector();
CSS1Expression *ParseDeclaration( String& rProperty );
protected:
// Den Inhalt eines HTML-Style-Elements parsen.
// Fuer jeden Selektor und jede Deklaration wird
// SelectorParsed() bzw. DeclarationParsed() aufgerufen.
sal_Bool ParseStyleSheet( const String& rIn );
// Den Inhalt einer HTML-Style-Option parsen.
// Fr jede Deklaration wird DeclarationParsed() aufgerufen.
sal_Bool ParseStyleOption( const String& rIn );
// Diese Methode wird aufgerufen, wenn ein Selektor geparsed wurde
// Wenn 'bFirst' gesetzt ist, beginnt mit dem Selektor eine neue
// Deklaration. Wird sal_True zurueckgegeben, wird der Selektor
// geloscht, sonst nicht.
// Die Implementierung dieser Methode gibt nur sal_True zuruck.
virtual sal_Bool SelectorParsed( const CSS1Selector *pSelector,
sal_Bool bFirst );
// Diese Methode wird fuer jede geparsete Property aufgerufen. Wird
// sal_True zurueckgegeben wird der Selektor geloscht, sonst nicht.
// Die Implementierung dieser Methode gibt nur sal_True zuruck.
virtual sal_Bool DeclarationParsed( const String& rProperty,
const CSS1Expression *pExpr );
public:
CSS1Parser();
virtual ~CSS1Parser();
inline sal_uInt32 GetLineNr() const { return nlLineNr; }
inline sal_uInt32 GetLinePos() const { return nlLinePos; }
};
inline sal_uInt32 CSS1Parser::SetLineNr( sal_uInt32 nlNum )
{
sal_uInt32 nlOld = nlLineNr;
nlLineNr = nlNum;
return nlOld;
}
inline sal_uInt32 CSS1Parser::SetLinePos( sal_uInt32 nlPos )
{
sal_uInt32 nlOld = nlLinePos;
nlLinePos = nlPos;
return nlOld;
}
#endif
<commit_msg>INTEGRATION: CWS swwarnings (1.2.710); FILE MERGED 2007/03/16 14:11:23 tl 1.2.710.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: parcss1.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2007-09-27 09:50:52 $
*
* 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 _PARCSS1_HXX
#define _PARCSS1_HXX
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
class Color;
/* */
// Die Tokens des CSS1-Parsers
enum CSS1Token
{
CSS1_NULL,
CSS1_UNKOWN,
CSS1_IDENT,
CSS1_STRING,
CSS1_NUMBER,
CSS1_PERCENTAGE,
CSS1_LENGTH, // eine absolute Groesse in 1/100 MM
CSS1_PIXLENGTH, // eine Pixel-Groesse
CSS1_EMS,
CSS1_EMX,
CSS1_HEXCOLOR,
CSS1_DOT_W_WS,
CSS1_DOT_WO_WS,
CSS1_COLON,
CSS1_SLASH,
CSS1_PLUS,
CSS1_MINUS,
CSS1_OBRACE,
CSS1_CBRACE,
CSS1_SEMICOLON,
CSS1_COMMA,
CSS1_HASH,
CSS1_IMPORT_SYM,
// Feature: PrintExt
CSS1_PAGE_SYM,
// /Feature: PrintExt
CSS1_IMPORTANT_SYM,
CSS1_URL,
CSS1_RGB
};
// die Zustaende des Parsers
enum CSS1ParserState
{
CSS1_PAR_ACCEPTED = 0,
CSS1_PAR_WORKING,
CSS1_PAR_ERROR
};
/* */
enum CSS1SelectorType
{
CSS1_SELTYPE_ELEMENT,
CSS1_SELTYPE_ELEM_CLASS,
CSS1_SELTYPE_CLASS,
CSS1_SELTYPE_ID,
CSS1_SELTYPE_PSEUDO,
// Feature: PrintExt
CSS1_SELTYPE_PAGE
// /Feature: PrintExt
};
// Die folegende Klasse beschreibt einen Simple-Selector, also
// - einen HTML-Element-Namen
// - einen HTML-Element-Namen mit Klasse (durch '.' getrennt)
// - eine Klasse (ohne Punkt)
// - eine mit ID=xxx gesetzte ID aus einem HTML-Dokument
// oder
// - ein Pseudo-Element
//
// Die Simple-Sektoren werden in einer Liste zu vollstaendigen
// Selektoren verkettet
class CSS1Selector
{
CSS1SelectorType eType; // Art des Selektors
String aSelector; // der Selektor selbst
CSS1Selector *pNext; // die naechste Komponente
public:
CSS1Selector( CSS1SelectorType eTyp, const String &rSel )
: eType(eTyp), aSelector( rSel ), pNext( 0 )
{}
~CSS1Selector();
CSS1SelectorType GetType() const { return eType; }
const String& GetString() const { return aSelector; }
void SetNext( CSS1Selector *pNxt ) { pNext = pNxt; }
const CSS1Selector *GetNext() const { return pNext; }
};
/* */
// Die folegende Klasse beschreibt einen Teil-Ausdruck einer
// CSS1-Deklaration sie besteht aus
//
// - dem Typ des Ausdrucks (entspricht dem Token)
// - dem eigentlichen Wert als String und ggf. double
// der double-Wert enthaelt das Vorzeichen fuer NUMBER und LENGTH
// - und dem Operator, mit dem er mit dem *Vorganger*-Ausdruck
// verknuepft ist.
//
struct CSS1Expression
{
sal_Unicode cOp; // Art der Verkuepfung mit dem Vorgaenger
CSS1Token eType; // der Typ des Wertes
String aValue; // und sein Wert als String
double nValue; // und als Zahl (TWIPs fuer LENGTH)
CSS1Expression *pNext; // die naechste Komponente
public:
CSS1Expression( CSS1Token eTyp, const String &rVal,
double nVal, sal_Unicode cO = 0 )
: cOp(cO), eType(eTyp), aValue(rVal), nValue(nVal), pNext(0)
{}
~CSS1Expression();
inline void Set( CSS1Token eTyp, const String &rVal, double nVal,
sal_Unicode cO = 0 );
CSS1Token GetType() const { return eType; }
const String& GetString() const { return aValue; }
double GetNumber() const { return nValue; }
inline sal_uInt32 GetULength() const;
inline sal_Int32 GetSLength() const;
sal_Unicode GetOp() const { return cOp; }
sal_Bool GetURL( String& rURL ) const;
sal_Bool GetColor( Color &rRGB ) const;
void SetNext( CSS1Expression *pNxt ) { pNext = pNxt; }
const CSS1Expression *GetNext() const { return pNext; }
};
inline void CSS1Expression::Set( CSS1Token eTyp, const String &rVal,
double nVal, sal_Unicode cO )
{
cOp = cO; eType = eTyp; aValue = rVal; nValue = nVal; pNext = 0;
}
inline sal_uInt32 CSS1Expression::GetULength() const
{
return nValue < 0. ? 0UL : (sal_uInt32)(nValue + .5);
}
inline sal_Int32 CSS1Expression::GetSLength() const
{
return (sal_Int32)(nValue + (nValue < 0. ? -.5 : .5 ));
}
/* */
// Diese Klasse parst den Inhalt eines Style-Elements oder eine Style-Option
// und bereitet ihn ein wenig auf.
//
// Das Ergebnis des Parsers wird durch die Mehtoden SelectorParsed()
// und DeclarationParsed() an abgeleitete Parser uebergeben. Bsp:
//
// H1, H2 { font-weight: bold; text-align: right }
// | | | |
// | | | DeclP( 'text-align', 'right' )
// | | DeclP( 'font-weight', 'bold' )
// | SelP( 'H2', sal_False )
// SelP( 'H1', sal_True )
//
class CSS1Parser
{
sal_Bool bWhiteSpace : 1; // White-Space gelesen?
sal_Bool bEOF : 1; // Ende des "Files" ?
sal_Unicode cNextCh; // naechstes Zeichen
xub_StrLen nInPos; // aktuelle Position im Input-String
sal_uInt32 nlLineNr; // akt. Zeilen Nummer
sal_uInt32 nlLinePos; // akt. Spalten Nummer
double nValue; // der Wert des Tokens als Zahl
CSS1ParserState eState; // der akteulle Zustand der Parsers
CSS1Token nToken; // das aktuelle Token
String aIn; // der zu parsende String
String aToken; // das Token als String
// Parsen vorbereiten
void InitRead( const String& rIn );
// das naechste Zeichen holen
sal_Unicode GetNextChar();
// das naechste Token holen
CSS1Token GetNextToken();
// arbeitet der Parser noch?
sal_Bool IsParserWorking() const { return CSS1_PAR_WORKING == eState; }
sal_Bool IsEOF() const { return bEOF; }
sal_uInt32 IncLineNr() { return ++nlLineNr; }
sal_uInt32 IncLinePos() { return ++nlLinePos; }
inline sal_uInt32 SetLineNr( sal_uInt32 nlNum ); // inline unten
inline sal_uInt32 SetLinePos( sal_uInt32 nlPos ); // inline unten
// Parsen von Teilen der Grammatik
void ParseRule();
CSS1Selector *ParseSelector();
CSS1Expression *ParseDeclaration( String& rProperty );
protected:
void ParseStyleSheet();
// Den Inhalt eines HTML-Style-Elements parsen.
// Fuer jeden Selektor und jede Deklaration wird
// SelectorParsed() bzw. DeclarationParsed() aufgerufen.
sal_Bool ParseStyleSheet( const String& rIn );
// Den Inhalt einer HTML-Style-Option parsen.
// F�r jede Deklaration wird DeclarationParsed() aufgerufen.
sal_Bool ParseStyleOption( const String& rIn );
// Diese Methode wird aufgerufen, wenn ein Selektor geparsed wurde
// Wenn 'bFirst' gesetzt ist, beginnt mit dem Selektor eine neue
// Deklaration. Wird sal_True zurueckgegeben, wird der Selektor
// geloscht, sonst nicht.
// Die Implementierung dieser Methode gibt nur sal_True zuruck.
virtual sal_Bool SelectorParsed( const CSS1Selector *pSelector,
sal_Bool bFirst );
// Diese Methode wird fuer jede geparsete Property aufgerufen. Wird
// sal_True zurueckgegeben wird der Selektor geloscht, sonst nicht.
// Die Implementierung dieser Methode gibt nur sal_True zuruck.
virtual sal_Bool DeclarationParsed( const String& rProperty,
const CSS1Expression *pExpr );
public:
CSS1Parser();
virtual ~CSS1Parser();
inline sal_uInt32 GetLineNr() const { return nlLineNr; }
inline sal_uInt32 GetLinePos() const { return nlLinePos; }
};
inline sal_uInt32 CSS1Parser::SetLineNr( sal_uInt32 nlNum )
{
sal_uInt32 nlOld = nlLineNr;
nlLineNr = nlNum;
return nlOld;
}
inline sal_uInt32 CSS1Parser::SetLinePos( sal_uInt32 nlPos )
{
sal_uInt32 nlOld = nlLinePos;
nlLinePos = nlPos;
return nlOld;
}
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include "stream.hpp"
using namespace std;
int main()
{
Stream<int>::range(5)
.filter([] (int num)
{
return num % 2 == 0;
})
.take(5)
.map<float>([] (int num)
{
return (float)num + 0.5f;
})
.walk([] (float num)
{
cout << num << endl;
});
}
<commit_msg>comments for the example<commit_after>#include <iostream>
#include "stream.hpp"
using namespace std;
int main()
{
Stream<int>::range(5) // build a stream from 5 to infinity
.filter([] (int num) // only accept even numbers
{
return num % 2 == 0;
})
.take(5) // only take 5 even numbers
.map<float>([] (int num) // add 0.5 to each number and convert the stream to a float stream
{
return (float)num + 0.5f;
})
.walk([] (float num) // list the results
{
cout << num << endl;
});
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016 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 "modules/audio_processing/aec3/block_processor.h"
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include "modules/audio_processing/aec3/aec3_common.h"
#include "modules/audio_processing/aec3/mock/mock_echo_remover.h"
#include "modules/audio_processing/aec3/mock/mock_render_delay_buffer.h"
#include "modules/audio_processing/aec3/mock/mock_render_delay_controller.h"
#include "modules/audio_processing/test/echo_canceller_test_tools.h"
#include "rtc_base/checks.h"
#include "rtc_base/random.h"
#include "test/gmock.h"
#include "test/gtest.h"
namespace webrtc {
namespace {
using testing::AtLeast;
using testing::Return;
using testing::StrictMock;
using testing::_;
// Verifies that the basic BlockProcessor functionality works and that the API
// methods are callable.
void RunBasicSetupAndApiCallTest(int sample_rate_hz) {
std::unique_ptr<BlockProcessor> block_processor(
BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
std::vector<std::vector<float>> block(NumBandsForRate(sample_rate_hz),
std::vector<float>(kBlockSize, 0.f));
block_processor->BufferRender(block);
block_processor->ProcessCapture(false, false, &block);
block_processor->UpdateEchoLeakageStatus(false);
}
#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
void RunRenderBlockSizeVerificationTest(int sample_rate_hz) {
std::unique_ptr<BlockProcessor> block_processor(
BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
std::vector<std::vector<float>> block(
NumBandsForRate(sample_rate_hz), std::vector<float>(kBlockSize - 1, 0.f));
EXPECT_DEATH(block_processor->BufferRender(block), "");
}
void RunCaptureBlockSizeVerificationTest(int sample_rate_hz) {
std::unique_ptr<BlockProcessor> block_processor(
BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
std::vector<std::vector<float>> block(
NumBandsForRate(sample_rate_hz), std::vector<float>(kBlockSize - 1, 0.f));
EXPECT_DEATH(block_processor->ProcessCapture(false, false, &block), "");
}
void RunRenderNumBandsVerificationTest(int sample_rate_hz) {
const size_t wrong_num_bands = NumBandsForRate(sample_rate_hz) < 3
? NumBandsForRate(sample_rate_hz) + 1
: 1;
std::unique_ptr<BlockProcessor> block_processor(
BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
std::vector<std::vector<float>> block(wrong_num_bands,
std::vector<float>(kBlockSize, 0.f));
EXPECT_DEATH(block_processor->BufferRender(block), "");
}
void RunCaptureNumBandsVerificationTest(int sample_rate_hz) {
const size_t wrong_num_bands = NumBandsForRate(sample_rate_hz) < 3
? NumBandsForRate(sample_rate_hz) + 1
: 1;
std::unique_ptr<BlockProcessor> block_processor(
BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
std::vector<std::vector<float>> block(wrong_num_bands,
std::vector<float>(kBlockSize, 0.f));
EXPECT_DEATH(block_processor->ProcessCapture(false, false, &block), "");
}
#endif
std::string ProduceDebugText(int sample_rate_hz) {
std::ostringstream ss;
ss << "Sample rate: " << sample_rate_hz;
return ss.str();
}
} // namespace
// Verifies that the delay controller functionality is properly integrated with
// the render delay buffer inside block processor.
// TODO(peah): Activate the unittest once the required code has been landed.
TEST(BlockProcessor, DISABLED_DelayControllerIntegration) {
constexpr size_t kNumBlocks = 310;
constexpr size_t kDelayInSamples = 640;
constexpr size_t kDelayHeadroom = 1;
constexpr size_t kDelayInBlocks =
kDelayInSamples / kBlockSize - kDelayHeadroom;
Random random_generator(42U);
for (auto rate : {8000, 16000, 32000, 48000}) {
SCOPED_TRACE(ProduceDebugText(rate));
std::unique_ptr<testing::StrictMock<webrtc::test::MockRenderDelayBuffer>>
render_delay_buffer_mock(
new StrictMock<webrtc::test::MockRenderDelayBuffer>(rate));
EXPECT_CALL(*render_delay_buffer_mock, Insert(_))
.Times(kNumBlocks)
.WillRepeatedly(Return(true));
EXPECT_CALL(*render_delay_buffer_mock, IsBlockAvailable())
.Times(kNumBlocks)
.WillRepeatedly(Return(true));
EXPECT_CALL(*render_delay_buffer_mock, SetDelay(kDelayInBlocks))
.Times(AtLeast(1));
EXPECT_CALL(*render_delay_buffer_mock, MaxDelay()).WillOnce(Return(30));
EXPECT_CALL(*render_delay_buffer_mock, Delay())
.Times(kNumBlocks + 1)
.WillRepeatedly(Return(0));
std::unique_ptr<BlockProcessor> block_processor(BlockProcessor::Create(
EchoCanceller3Config(), rate, std::move(render_delay_buffer_mock)));
std::vector<std::vector<float>> render_block(
NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
std::vector<std::vector<float>> capture_block(
NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
DelayBuffer<float> signal_delay_buffer(kDelayInSamples);
for (size_t k = 0; k < kNumBlocks; ++k) {
RandomizeSampleVector(&random_generator, render_block[0]);
signal_delay_buffer.Delay(render_block[0], capture_block[0]);
block_processor->BufferRender(render_block);
block_processor->ProcessCapture(false, false, &capture_block);
}
}
}
// Verifies that BlockProcessor submodules are called in a proper manner.
TEST(BlockProcessor, DISABLED_SubmoduleIntegration) {
constexpr size_t kNumBlocks = 310;
Random random_generator(42U);
for (auto rate : {8000, 16000, 32000, 48000}) {
SCOPED_TRACE(ProduceDebugText(rate));
std::unique_ptr<testing::StrictMock<webrtc::test::MockRenderDelayBuffer>>
render_delay_buffer_mock(
new StrictMock<webrtc::test::MockRenderDelayBuffer>(rate));
std::unique_ptr<
testing::StrictMock<webrtc::test::MockRenderDelayController>>
render_delay_controller_mock(
new StrictMock<webrtc::test::MockRenderDelayController>());
std::unique_ptr<testing::StrictMock<webrtc::test::MockEchoRemover>>
echo_remover_mock(new StrictMock<webrtc::test::MockEchoRemover>());
EXPECT_CALL(*render_delay_buffer_mock, Insert(_))
.Times(kNumBlocks - 1)
.WillRepeatedly(Return(true));
EXPECT_CALL(*render_delay_buffer_mock, IsBlockAvailable())
.Times(kNumBlocks)
.WillRepeatedly(Return(true));
EXPECT_CALL(*render_delay_buffer_mock, UpdateBuffers()).Times(kNumBlocks);
EXPECT_CALL(*render_delay_buffer_mock, SetDelay(9)).Times(AtLeast(1));
EXPECT_CALL(*render_delay_buffer_mock, Delay())
.Times(kNumBlocks)
.WillRepeatedly(Return(0));
EXPECT_CALL(*render_delay_controller_mock, GetDelay(_, _))
.Times(kNumBlocks)
.WillRepeatedly(Return(9));
EXPECT_CALL(*render_delay_controller_mock, AlignmentHeadroomSamples())
.Times(kNumBlocks);
EXPECT_CALL(*echo_remover_mock, ProcessCapture(_, _, _, _, _))
.Times(kNumBlocks);
EXPECT_CALL(*echo_remover_mock, UpdateEchoLeakageStatus(_))
.Times(kNumBlocks);
std::unique_ptr<BlockProcessor> block_processor(BlockProcessor::Create(
EchoCanceller3Config(), rate, std::move(render_delay_buffer_mock),
std::move(render_delay_controller_mock), std::move(echo_remover_mock)));
std::vector<std::vector<float>> render_block(
NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
std::vector<std::vector<float>> capture_block(
NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
DelayBuffer<float> signal_delay_buffer(640);
for (size_t k = 0; k < kNumBlocks; ++k) {
RandomizeSampleVector(&random_generator, render_block[0]);
signal_delay_buffer.Delay(render_block[0], capture_block[0]);
block_processor->BufferRender(render_block);
block_processor->ProcessCapture(false, false, &capture_block);
block_processor->UpdateEchoLeakageStatus(false);
}
}
}
TEST(BlockProcessor, BasicSetupAndApiCalls) {
for (auto rate : {8000, 16000, 32000, 48000}) {
SCOPED_TRACE(ProduceDebugText(rate));
RunBasicSetupAndApiCallTest(rate);
}
}
#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
TEST(BlockProcessor, VerifyRenderBlockSizeCheck) {
for (auto rate : {8000, 16000, 32000, 48000}) {
SCOPED_TRACE(ProduceDebugText(rate));
RunRenderBlockSizeVerificationTest(rate);
}
}
TEST(BlockProcessor, VerifyCaptureBlockSizeCheck) {
for (auto rate : {8000, 16000, 32000, 48000}) {
SCOPED_TRACE(ProduceDebugText(rate));
RunCaptureBlockSizeVerificationTest(rate);
}
}
TEST(BlockProcessor, VerifyRenderNumBandsCheck) {
for (auto rate : {8000, 16000, 32000, 48000}) {
SCOPED_TRACE(ProduceDebugText(rate));
RunRenderNumBandsVerificationTest(rate);
}
}
// TODO(peah): Verify the check for correct number of bands in the capture
// signal.
TEST(BlockProcessor, VerifyCaptureNumBandsCheck) {
for (auto rate : {8000, 16000, 32000, 48000}) {
SCOPED_TRACE(ProduceDebugText(rate));
RunCaptureNumBandsVerificationTest(rate);
}
}
// Verifiers that the verification for null ProcessCapture input works.
TEST(BlockProcessor, NullProcessCaptureParameter) {
EXPECT_DEATH(std::unique_ptr<BlockProcessor>(
BlockProcessor::Create(EchoCanceller3Config(), 8000))
->ProcessCapture(false, false, nullptr),
"");
}
// Verifies the check for correct sample rate.
// TODO(peah): Re-enable the test once the issue with memory leaks during DEATH
// tests on test bots has been fixed.
TEST(BlockProcessor, DISABLED_WrongSampleRate) {
EXPECT_DEATH(std::unique_ptr<BlockProcessor>(
BlockProcessor::Create(EchoCanceller3Config(), 8001)),
"");
}
#endif
} // namespace webrtc
<commit_msg>Temporarily disabled failing death test.<commit_after>/*
* Copyright (c) 2016 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 "modules/audio_processing/aec3/block_processor.h"
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include "modules/audio_processing/aec3/aec3_common.h"
#include "modules/audio_processing/aec3/mock/mock_echo_remover.h"
#include "modules/audio_processing/aec3/mock/mock_render_delay_buffer.h"
#include "modules/audio_processing/aec3/mock/mock_render_delay_controller.h"
#include "modules/audio_processing/test/echo_canceller_test_tools.h"
#include "rtc_base/checks.h"
#include "rtc_base/random.h"
#include "test/gmock.h"
#include "test/gtest.h"
namespace webrtc {
namespace {
using testing::AtLeast;
using testing::Return;
using testing::StrictMock;
using testing::_;
// Verifies that the basic BlockProcessor functionality works and that the API
// methods are callable.
void RunBasicSetupAndApiCallTest(int sample_rate_hz) {
std::unique_ptr<BlockProcessor> block_processor(
BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
std::vector<std::vector<float>> block(NumBandsForRate(sample_rate_hz),
std::vector<float>(kBlockSize, 0.f));
block_processor->BufferRender(block);
block_processor->ProcessCapture(false, false, &block);
block_processor->UpdateEchoLeakageStatus(false);
}
#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
void RunRenderBlockSizeVerificationTest(int sample_rate_hz) {
std::unique_ptr<BlockProcessor> block_processor(
BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
std::vector<std::vector<float>> block(
NumBandsForRate(sample_rate_hz), std::vector<float>(kBlockSize - 1, 0.f));
EXPECT_DEATH(block_processor->BufferRender(block), "");
}
void RunCaptureBlockSizeVerificationTest(int sample_rate_hz) {
std::unique_ptr<BlockProcessor> block_processor(
BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
std::vector<std::vector<float>> block(
NumBandsForRate(sample_rate_hz), std::vector<float>(kBlockSize - 1, 0.f));
EXPECT_DEATH(block_processor->ProcessCapture(false, false, &block), "");
}
void RunRenderNumBandsVerificationTest(int sample_rate_hz) {
const size_t wrong_num_bands = NumBandsForRate(sample_rate_hz) < 3
? NumBandsForRate(sample_rate_hz) + 1
: 1;
std::unique_ptr<BlockProcessor> block_processor(
BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
std::vector<std::vector<float>> block(wrong_num_bands,
std::vector<float>(kBlockSize, 0.f));
EXPECT_DEATH(block_processor->BufferRender(block), "");
}
void RunCaptureNumBandsVerificationTest(int sample_rate_hz) {
const size_t wrong_num_bands = NumBandsForRate(sample_rate_hz) < 3
? NumBandsForRate(sample_rate_hz) + 1
: 1;
std::unique_ptr<BlockProcessor> block_processor(
BlockProcessor::Create(EchoCanceller3Config(), sample_rate_hz));
std::vector<std::vector<float>> block(wrong_num_bands,
std::vector<float>(kBlockSize, 0.f));
EXPECT_DEATH(block_processor->ProcessCapture(false, false, &block), "");
}
#endif
std::string ProduceDebugText(int sample_rate_hz) {
std::ostringstream ss;
ss << "Sample rate: " << sample_rate_hz;
return ss.str();
}
} // namespace
// Verifies that the delay controller functionality is properly integrated with
// the render delay buffer inside block processor.
// TODO(peah): Activate the unittest once the required code has been landed.
TEST(BlockProcessor, DISABLED_DelayControllerIntegration) {
constexpr size_t kNumBlocks = 310;
constexpr size_t kDelayInSamples = 640;
constexpr size_t kDelayHeadroom = 1;
constexpr size_t kDelayInBlocks =
kDelayInSamples / kBlockSize - kDelayHeadroom;
Random random_generator(42U);
for (auto rate : {8000, 16000, 32000, 48000}) {
SCOPED_TRACE(ProduceDebugText(rate));
std::unique_ptr<testing::StrictMock<webrtc::test::MockRenderDelayBuffer>>
render_delay_buffer_mock(
new StrictMock<webrtc::test::MockRenderDelayBuffer>(rate));
EXPECT_CALL(*render_delay_buffer_mock, Insert(_))
.Times(kNumBlocks)
.WillRepeatedly(Return(true));
EXPECT_CALL(*render_delay_buffer_mock, IsBlockAvailable())
.Times(kNumBlocks)
.WillRepeatedly(Return(true));
EXPECT_CALL(*render_delay_buffer_mock, SetDelay(kDelayInBlocks))
.Times(AtLeast(1));
EXPECT_CALL(*render_delay_buffer_mock, MaxDelay()).WillOnce(Return(30));
EXPECT_CALL(*render_delay_buffer_mock, Delay())
.Times(kNumBlocks + 1)
.WillRepeatedly(Return(0));
std::unique_ptr<BlockProcessor> block_processor(BlockProcessor::Create(
EchoCanceller3Config(), rate, std::move(render_delay_buffer_mock)));
std::vector<std::vector<float>> render_block(
NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
std::vector<std::vector<float>> capture_block(
NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
DelayBuffer<float> signal_delay_buffer(kDelayInSamples);
for (size_t k = 0; k < kNumBlocks; ++k) {
RandomizeSampleVector(&random_generator, render_block[0]);
signal_delay_buffer.Delay(render_block[0], capture_block[0]);
block_processor->BufferRender(render_block);
block_processor->ProcessCapture(false, false, &capture_block);
}
}
}
// Verifies that BlockProcessor submodules are called in a proper manner.
TEST(BlockProcessor, DISABLED_SubmoduleIntegration) {
constexpr size_t kNumBlocks = 310;
Random random_generator(42U);
for (auto rate : {8000, 16000, 32000, 48000}) {
SCOPED_TRACE(ProduceDebugText(rate));
std::unique_ptr<testing::StrictMock<webrtc::test::MockRenderDelayBuffer>>
render_delay_buffer_mock(
new StrictMock<webrtc::test::MockRenderDelayBuffer>(rate));
std::unique_ptr<
testing::StrictMock<webrtc::test::MockRenderDelayController>>
render_delay_controller_mock(
new StrictMock<webrtc::test::MockRenderDelayController>());
std::unique_ptr<testing::StrictMock<webrtc::test::MockEchoRemover>>
echo_remover_mock(new StrictMock<webrtc::test::MockEchoRemover>());
EXPECT_CALL(*render_delay_buffer_mock, Insert(_))
.Times(kNumBlocks - 1)
.WillRepeatedly(Return(true));
EXPECT_CALL(*render_delay_buffer_mock, IsBlockAvailable())
.Times(kNumBlocks)
.WillRepeatedly(Return(true));
EXPECT_CALL(*render_delay_buffer_mock, UpdateBuffers()).Times(kNumBlocks);
EXPECT_CALL(*render_delay_buffer_mock, SetDelay(9)).Times(AtLeast(1));
EXPECT_CALL(*render_delay_buffer_mock, Delay())
.Times(kNumBlocks)
.WillRepeatedly(Return(0));
EXPECT_CALL(*render_delay_controller_mock, GetDelay(_, _))
.Times(kNumBlocks)
.WillRepeatedly(Return(9));
EXPECT_CALL(*render_delay_controller_mock, AlignmentHeadroomSamples())
.Times(kNumBlocks);
EXPECT_CALL(*echo_remover_mock, ProcessCapture(_, _, _, _, _))
.Times(kNumBlocks);
EXPECT_CALL(*echo_remover_mock, UpdateEchoLeakageStatus(_))
.Times(kNumBlocks);
std::unique_ptr<BlockProcessor> block_processor(BlockProcessor::Create(
EchoCanceller3Config(), rate, std::move(render_delay_buffer_mock),
std::move(render_delay_controller_mock), std::move(echo_remover_mock)));
std::vector<std::vector<float>> render_block(
NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
std::vector<std::vector<float>> capture_block(
NumBandsForRate(rate), std::vector<float>(kBlockSize, 0.f));
DelayBuffer<float> signal_delay_buffer(640);
for (size_t k = 0; k < kNumBlocks; ++k) {
RandomizeSampleVector(&random_generator, render_block[0]);
signal_delay_buffer.Delay(render_block[0], capture_block[0]);
block_processor->BufferRender(render_block);
block_processor->ProcessCapture(false, false, &capture_block);
block_processor->UpdateEchoLeakageStatus(false);
}
}
}
TEST(BlockProcessor, BasicSetupAndApiCalls) {
for (auto rate : {8000, 16000, 32000, 48000}) {
SCOPED_TRACE(ProduceDebugText(rate));
RunBasicSetupAndApiCallTest(rate);
}
}
#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
// TODO(gustaf): Re-enable the test once the issue with memory leaks during
// DEATH tests on test bots has been fixed.
TEST(BlockProcessor, DISABLED_VerifyRenderBlockSizeCheck) {
for (auto rate : {8000, 16000, 32000, 48000}) {
SCOPED_TRACE(ProduceDebugText(rate));
RunRenderBlockSizeVerificationTest(rate);
}
}
TEST(BlockProcessor, VerifyCaptureBlockSizeCheck) {
for (auto rate : {8000, 16000, 32000, 48000}) {
SCOPED_TRACE(ProduceDebugText(rate));
RunCaptureBlockSizeVerificationTest(rate);
}
}
TEST(BlockProcessor, VerifyRenderNumBandsCheck) {
for (auto rate : {8000, 16000, 32000, 48000}) {
SCOPED_TRACE(ProduceDebugText(rate));
RunRenderNumBandsVerificationTest(rate);
}
}
// TODO(peah): Verify the check for correct number of bands in the capture
// signal.
TEST(BlockProcessor, VerifyCaptureNumBandsCheck) {
for (auto rate : {8000, 16000, 32000, 48000}) {
SCOPED_TRACE(ProduceDebugText(rate));
RunCaptureNumBandsVerificationTest(rate);
}
}
// Verifiers that the verification for null ProcessCapture input works.
TEST(BlockProcessor, NullProcessCaptureParameter) {
EXPECT_DEATH(std::unique_ptr<BlockProcessor>(
BlockProcessor::Create(EchoCanceller3Config(), 8000))
->ProcessCapture(false, false, nullptr),
"");
}
// Verifies the check for correct sample rate.
// TODO(peah): Re-enable the test once the issue with memory leaks during DEATH
// tests on test bots has been fixed.
TEST(BlockProcessor, DISABLED_WrongSampleRate) {
EXPECT_DEATH(std::unique_ptr<BlockProcessor>(
BlockProcessor::Create(EchoCanceller3Config(), 8001)),
"");
}
#endif
} // namespace webrtc
<|endoftext|> |
<commit_before>//*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#ifndef __OPENCV_HYBRIDTRACKER_H_
#define __OPENCV_HYBRIDTRACKER_H_
#include "opencv2/core/core.hpp"
#include "opencv2/core/operations.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/video/tracking.hpp"
#include "opencv2/ml/ml.hpp"
#ifdef __cplusplus
namespace cv
{
// Motion model for tracking algorithm. Currently supports objects that do not move much.
// To add Kalman filter
struct CV_EXPORTS CvMotionModel
{
enum {LOW_PASS_FILTER = 0, KALMAN_FILTER = 1, EM = 2};
CvMotionModel()
{
}
float low_pass_gain; // low pass gain
CvEMParams em_params; // EM parameters
};
// Mean Shift Tracker parameters for specifying use of HSV channel and CamShift parameters.
struct CV_EXPORTS CvMeanShiftTrackerParams
{
enum { H = 0, HS = 1, HSV = 2 };
CvMeanShiftTrackerParams(int tracking_type = CvMeanShiftTrackerParams::HS,
CvTermCriteria term_crit = CvTermCriteria())
{
}
int tracking_type;
float h_range[];
float s_range[];
float v_range[];
CvTermCriteria term_crit;
};
// Feature tracking parameters
struct CV_EXPORTS CvFeatureTrackerParams
{
enum { SIFT = 0, SURF = 1, OPTICAL_FLOW = 2 };
CvFeatureTrackerParams(int feature_type = 0, int window_size = 0)
{
feature_type = 0;
window_size = 0;
}
int feature_type; // Feature type to use
int window_size; // Window size in pixels around which to search for new window
};
// Hybrid Tracking parameters for specifying weights of individual trackers and motion model.
struct CV_EXPORTS CvHybridTrackerParams
{
CvHybridTrackerParams(float ft_tracker_weight = 0.5, float ms_tracker_weight = 0.5,
CvFeatureTrackerParams ft_params = CvFeatureTrackerParams(),
CvMeanShiftTrackerParams ms_params = CvMeanShiftTrackerParams(),
CvMotionModel model = CvMotionModel())
{
}
float ft_tracker_weight;
float ms_tracker_weight;
CvFeatureTrackerParams ft_params;
CvMeanShiftTrackerParams ms_params;
CvEMParams em_params;
int motion_model;
float low_pass_gain;
};
// Performs Camshift using parameters from MeanShiftTrackerParams
class CV_EXPORTS CvMeanShiftTracker
{
private:
Mat hsv, hue;
Mat backproj;
Mat mask, maskroi;
MatND hist;
Rect prev_trackwindow;
RotatedRect prev_trackbox;
Point2f prev_center;
public:
CvMeanShiftTrackerParams params;
CvMeanShiftTracker();
CvMeanShiftTracker(CvMeanShiftTrackerParams _params = CvMeanShiftTrackerParams());
~CvMeanShiftTracker();
void newTrackingWindow(Mat image, Rect selection);
RotatedRect updateTrackingWindow(Mat image);
Mat getHistogramProjection(int type);
void setTrackingWindow(Rect _window);
Rect getTrackingWindow();
RotatedRect getTrackingEllipse();
Point2f getTrackingCenter();
};
// Performs SIFT/SURF feature tracking using parameters from FeatureTrackerParams
class CV_EXPORTS CvFeatureTracker
{
private:
FeatureDetector* detector;
DescriptorExtractor* descriptor;
DescriptorMatcher* matcher;
vector<DMatch> matches;
Mat prev_image;
Mat prev_image_bw;
Rect prev_trackwindow;
Point2d prev_center;
int ittr;
vector<Point2f> features[2];
public:
Mat disp_matches;
CvFeatureTrackerParams params;
CvFeatureTracker();
CvFeatureTracker(CvFeatureTrackerParams params = CvFeatureTrackerParams(0,0));
~CvFeatureTracker();
void newTrackingWindow(Mat image, Rect selection);
Rect updateTrackingWindow(Mat image);
Rect updateTrackingWindowWithSIFT(Mat image);
Rect updateTrackingWindowWithFlow(Mat image);
void setTrackingWindow(Rect _window);
Rect getTrackingWindow();
Point2f getTrackingCenter();
};
// Performs Hybrid Tracking and combines individual trackers using EM or filters
class CV_EXPORTS CvHybridTracker
{
private:
CvMeanShiftTracker* mstracker;
CvFeatureTracker* fttracker;
CvMat* samples;
CvMat* labels;
CvEM em_model;
Rect prev_window;
Point2f prev_center;
Mat prev_proj;
RotatedRect trackbox;
int ittr;
Point2f curr_center;
inline float getL2Norm(Point2f p1, Point2f p2);
Mat getDistanceProjection(Mat image, Point2f center);
Mat getGaussianProjection(Mat image, int ksize, double sigma, Point2f center);
void updateTrackerWithEM(Mat image);
void updateTrackerWithLowPassFilter(Mat image);
public:
CvHybridTrackerParams params;
CvHybridTracker();
CvHybridTracker(CvHybridTrackerParams params = CvHybridTrackerParams());
~CvHybridTracker();
void newTracker(Mat image, Rect selection);
void updateTracker(Mat image);
Rect getTrackingWindow();
};
typedef CvMotionModel MotionModel;
typedef CvMeanShiftTrackerParams MeanShiftTrackerParams;
typedef CvFeatureTrackerParams FeatureTrackerParams;
typedef CvHybridTrackerParams HybridTrackerParams;
typedef CvMeanShiftTracker MeanShiftTracker;
typedef CvFeatureTracker FeatureTracker;
typedef CvHybridTracker HybridTracker;
}
#endif
#endif
<commit_msg>fixed hybrid tracker build problems on Windows<commit_after>//*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#ifndef __OPENCV_HYBRIDTRACKER_H_
#define __OPENCV_HYBRIDTRACKER_H_
#include "opencv2/core/core.hpp"
#include "opencv2/core/operations.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/video/tracking.hpp"
#include "opencv2/ml/ml.hpp"
#ifdef __cplusplus
namespace cv
{
// Motion model for tracking algorithm. Currently supports objects that do not move much.
// To add Kalman filter
struct CV_EXPORTS CvMotionModel
{
enum {LOW_PASS_FILTER = 0, KALMAN_FILTER = 1, EM = 2};
CvMotionModel()
{
}
float low_pass_gain; // low pass gain
CvEMParams em_params; // EM parameters
};
// Mean Shift Tracker parameters for specifying use of HSV channel and CamShift parameters.
struct CV_EXPORTS CvMeanShiftTrackerParams
{
enum { H = 0, HS = 1, HSV = 2 };
CvMeanShiftTrackerParams(int tracking_type = CvMeanShiftTrackerParams::HS,
CvTermCriteria term_crit = CvTermCriteria())
{
}
int tracking_type;
vector<float> h_range;
vector<float> s_range;
vector<float> v_range;
CvTermCriteria term_crit;
};
// Feature tracking parameters
struct CV_EXPORTS CvFeatureTrackerParams
{
enum { SIFT = 0, SURF = 1, OPTICAL_FLOW = 2 };
CvFeatureTrackerParams(int feature_type = 0, int window_size = 0)
{
feature_type = 0;
window_size = 0;
}
int feature_type; // Feature type to use
int window_size; // Window size in pixels around which to search for new window
};
// Hybrid Tracking parameters for specifying weights of individual trackers and motion model.
struct CV_EXPORTS CvHybridTrackerParams
{
CvHybridTrackerParams(float ft_tracker_weight = 0.5, float ms_tracker_weight = 0.5,
CvFeatureTrackerParams ft_params = CvFeatureTrackerParams(),
CvMeanShiftTrackerParams ms_params = CvMeanShiftTrackerParams(),
CvMotionModel model = CvMotionModel())
{
}
float ft_tracker_weight;
float ms_tracker_weight;
CvFeatureTrackerParams ft_params;
CvMeanShiftTrackerParams ms_params;
CvEMParams em_params;
int motion_model;
float low_pass_gain;
};
// Performs Camshift using parameters from MeanShiftTrackerParams
class CV_EXPORTS CvMeanShiftTracker
{
private:
Mat hsv, hue;
Mat backproj;
Mat mask, maskroi;
MatND hist;
Rect prev_trackwindow;
RotatedRect prev_trackbox;
Point2f prev_center;
public:
CvMeanShiftTrackerParams params;
CvMeanShiftTracker();
CvMeanShiftTracker(CvMeanShiftTrackerParams _params = CvMeanShiftTrackerParams());
~CvMeanShiftTracker();
void newTrackingWindow(Mat image, Rect selection);
RotatedRect updateTrackingWindow(Mat image);
Mat getHistogramProjection(int type);
void setTrackingWindow(Rect _window);
Rect getTrackingWindow();
RotatedRect getTrackingEllipse();
Point2f getTrackingCenter();
};
// Performs SIFT/SURF feature tracking using parameters from FeatureTrackerParams
class CV_EXPORTS CvFeatureTracker
{
private:
FeatureDetector* detector;
DescriptorExtractor* descriptor;
DescriptorMatcher* matcher;
vector<DMatch> matches;
Mat prev_image;
Mat prev_image_bw;
Rect prev_trackwindow;
Point2d prev_center;
int ittr;
vector<Point2f> features[2];
public:
Mat disp_matches;
CvFeatureTrackerParams params;
CvFeatureTracker();
CvFeatureTracker(CvFeatureTrackerParams params = CvFeatureTrackerParams(0,0));
~CvFeatureTracker();
void newTrackingWindow(Mat image, Rect selection);
Rect updateTrackingWindow(Mat image);
Rect updateTrackingWindowWithSIFT(Mat image);
Rect updateTrackingWindowWithFlow(Mat image);
void setTrackingWindow(Rect _window);
Rect getTrackingWindow();
Point2f getTrackingCenter();
};
// Performs Hybrid Tracking and combines individual trackers using EM or filters
class CV_EXPORTS CvHybridTracker
{
private:
CvMeanShiftTracker* mstracker;
CvFeatureTracker* fttracker;
CvMat* samples;
CvMat* labels;
CvEM em_model;
Rect prev_window;
Point2f prev_center;
Mat prev_proj;
RotatedRect trackbox;
int ittr;
Point2f curr_center;
inline float getL2Norm(Point2f p1, Point2f p2);
Mat getDistanceProjection(Mat image, Point2f center);
Mat getGaussianProjection(Mat image, int ksize, double sigma, Point2f center);
void updateTrackerWithEM(Mat image);
void updateTrackerWithLowPassFilter(Mat image);
public:
CvHybridTrackerParams params;
CvHybridTracker();
CvHybridTracker(CvHybridTrackerParams params = CvHybridTrackerParams());
~CvHybridTracker();
void newTracker(Mat image, Rect selection);
void updateTracker(Mat image);
Rect getTrackingWindow();
};
typedef CvMotionModel MotionModel;
typedef CvMeanShiftTrackerParams MeanShiftTrackerParams;
typedef CvFeatureTrackerParams FeatureTrackerParams;
typedef CvHybridTrackerParams HybridTrackerParams;
typedef CvMeanShiftTracker MeanShiftTracker;
typedef CvFeatureTracker FeatureTracker;
typedef CvHybridTracker HybridTracker;
}
#endif
#endif
<|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 "QmitkImageStatisticsWidget.h"
#include "QmitkStatisticsModelToStringConverter.h"
#include "QmitkImageStatisticsTreeModel.h"
#include <QSortFilterProxyModel>
#include <QClipboard>
QmitkImageStatisticsWidget::QmitkImageStatisticsWidget(QWidget* parent) : QWidget(parent)
{
m_Controls.setupUi(this);
m_imageStatisticsModel = new QmitkImageStatisticsTreeModel(parent);
CreateConnections();
m_ProxyModel = new QSortFilterProxyModel(this);
m_Controls.treeViewStatistics->setEnabled(false);
m_Controls.treeViewStatistics->setModel(m_ProxyModel);
m_ProxyModel->setSourceModel(m_imageStatisticsModel);
connect(m_imageStatisticsModel, &QmitkImageStatisticsTreeModel::dataAvailable, this, &QmitkImageStatisticsWidget::OnDataAvailable);
connect(m_imageStatisticsModel,
&QmitkImageStatisticsTreeModel::modelChanged,
m_Controls.treeViewStatistics,
&QTreeView::expandAll);
}
void QmitkImageStatisticsWidget::SetDataStorage(mitk::DataStorage* newDataStorage)
{
m_imageStatisticsModel->SetDataStorage(newDataStorage);
}
void QmitkImageStatisticsWidget::SetImageNodes(const std::vector<mitk::DataNode::ConstPointer>& nodes)
{
m_imageStatisticsModel->SetImageNodes(nodes);
}
void QmitkImageStatisticsWidget::SetMaskNodes(const std::vector<mitk::DataNode::ConstPointer>& nodes)
{
m_imageStatisticsModel->SetMaskNodes(nodes);
}
void QmitkImageStatisticsWidget::Reset()
{
m_imageStatisticsModel->Clear();
m_Controls.treeViewStatistics->setEnabled(false);
m_Controls.buttonCopyImageStatisticsToClipboard->setEnabled(false);
}
void QmitkImageStatisticsWidget::CreateConnections()
{
connect(m_Controls.buttonCopyImageStatisticsToClipboard, &QPushButton::clicked, this, &QmitkImageStatisticsWidget::OnClipboardButtonClicked);
}
void QmitkImageStatisticsWidget::OnDataAvailable()
{
m_Controls.buttonCopyImageStatisticsToClipboard->setEnabled(true);
m_Controls.treeViewStatistics->setEnabled(true);
}
void QmitkImageStatisticsWidget::OnClipboardButtonClicked()
{
QmitkStatisticsModelToStringConverter converter;
converter.SetTableModel(m_imageStatisticsModel);
converter.SetRootIndex(m_Controls.treeViewStatistics->rootIndex());
converter.SetIncludeHeaderData(true);
QString clipboardAsString = converter.GetString();
QApplication::clipboard()->setText(clipboardAsString, QClipboard::Clipboard);
}
<commit_msg>Change column delimiter to tab<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 "QmitkImageStatisticsWidget.h"
#include "QmitkStatisticsModelToStringConverter.h"
#include "QmitkImageStatisticsTreeModel.h"
#include <QSortFilterProxyModel>
#include <QClipboard>
QmitkImageStatisticsWidget::QmitkImageStatisticsWidget(QWidget* parent) : QWidget(parent)
{
m_Controls.setupUi(this);
m_imageStatisticsModel = new QmitkImageStatisticsTreeModel(parent);
CreateConnections();
m_ProxyModel = new QSortFilterProxyModel(this);
m_Controls.treeViewStatistics->setEnabled(false);
m_Controls.treeViewStatistics->setModel(m_ProxyModel);
m_ProxyModel->setSourceModel(m_imageStatisticsModel);
connect(m_imageStatisticsModel, &QmitkImageStatisticsTreeModel::dataAvailable, this, &QmitkImageStatisticsWidget::OnDataAvailable);
connect(m_imageStatisticsModel,
&QmitkImageStatisticsTreeModel::modelChanged,
m_Controls.treeViewStatistics,
&QTreeView::expandAll);
}
void QmitkImageStatisticsWidget::SetDataStorage(mitk::DataStorage* newDataStorage)
{
m_imageStatisticsModel->SetDataStorage(newDataStorage);
}
void QmitkImageStatisticsWidget::SetImageNodes(const std::vector<mitk::DataNode::ConstPointer>& nodes)
{
m_imageStatisticsModel->SetImageNodes(nodes);
}
void QmitkImageStatisticsWidget::SetMaskNodes(const std::vector<mitk::DataNode::ConstPointer>& nodes)
{
m_imageStatisticsModel->SetMaskNodes(nodes);
}
void QmitkImageStatisticsWidget::Reset()
{
m_imageStatisticsModel->Clear();
m_Controls.treeViewStatistics->setEnabled(false);
m_Controls.buttonCopyImageStatisticsToClipboard->setEnabled(false);
}
void QmitkImageStatisticsWidget::CreateConnections()
{
connect(m_Controls.buttonCopyImageStatisticsToClipboard, &QPushButton::clicked, this, &QmitkImageStatisticsWidget::OnClipboardButtonClicked);
}
void QmitkImageStatisticsWidget::OnDataAvailable()
{
m_Controls.buttonCopyImageStatisticsToClipboard->setEnabled(true);
m_Controls.treeViewStatistics->setEnabled(true);
}
void QmitkImageStatisticsWidget::OnClipboardButtonClicked()
{
QmitkStatisticsModelToStringConverter converter;
converter.SetColumnDelimiter('\t');
converter.SetTableModel(m_imageStatisticsModel);
converter.SetRootIndex(m_Controls.treeViewStatistics->rootIndex());
converter.SetIncludeHeaderData(true);
QString clipboardAsString = converter.GetString();
QApplication::clipboard()->setText(clipboardAsString, QClipboard::Clipboard);
}
<|endoftext|> |
<commit_before>/**
* @copyright
* ====================================================================
* Copyright (c) 2003 CollabNet. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://subversion.tigris.org/license-1.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision
* history and logs, available at http://subversion.tigris.org/.
* ====================================================================
* @endcopyright
*
* @file JNIUtil.cpp
* @brief Implementation of the class JNIUtil
*/
#include "JNIUtil.h"
#include <locale.h>
#include <apr_strings.h>
#include <apr_tables.h>
#include <apr_general.h>
#include <apr_lib.h>
#include <svn_pools.h>
#include <svn_config.h>
//#include <ios>
#include "SVNClient.h"
#include "JNIMutex.h"
#include "JNICriticalSection.h"
#include "JNIThreadData.h"
#include "JNIStringHolder.h"
apr_pool_t *JNIUtil::g_pool = NULL;
std::list<SVNClient*> JNIUtil::g_finalizedObjects;
JNIMutex *JNIUtil::g_finalizedObjectsMutex = NULL;
JNIMutex *JNIUtil::g_logMutex = NULL;
bool JNIUtil::g_initException;
bool JNIUtil::g_inInit;
JNIEnv *JNIUtil::g_initEnv;
char JNIUtil::g_initFormatBuffer[formatBufferSize];
int JNIUtil::g_logLevel = JNIUtil::noLog;
std::ofstream JNIUtil::g_logStream;
Pool *JNIUtil::g_requestPool;
bool JNIUtil::JNIInit(JNIEnv *env)
{
static bool run = false;
if(run)
{
env->ExceptionClear();
setEnv(env);
JNICriticalSection cs(*g_finalizedObjectsMutex) ;
if(isExceptionThrown())
{
return false;
}
for(std::list<SVNClient*>::iterator it = g_finalizedObjects.begin(); it != g_finalizedObjects.end(); it++)
{
delete *it;
}
g_finalizedObjects.clear();
return true;
}
run = true;
if(g_inInit)
{
return false;
}
g_inInit = true;
g_initEnv = env;
/* C programs default to the "C" locale by default. But because svn
is supposed to be i18n-aware, it should inherit the default
locale of its environment. */
setlocale (LC_ALL, "");
/* Initialize the APR subsystem, and register an atexit() function
to Uninitialize that subsystem at program exit. */
apr_status_t apr_err = apr_initialize ();
if (apr_err)
{
fprintf (stderr, "error: apr_initialize\n");
return false;
}
int err2 = atexit (apr_terminate);
if (err2)
{
fprintf (stderr, "error: atexit returned %d\n", err2);
return false;
}
/* Create our top-level pool. */
g_pool = svn_pool_create (NULL);
svn_error *err = svn_config_ensure (NULL, g_pool); // we use the default directory for config files
if (err)
{
svn_pool_destroy (g_pool);
handleSVNError(err);
return false;
}
g_finalizedObjectsMutex = new JNIMutex(g_pool);
if(isExceptionThrown())
{
return false;
}
g_logMutex = new JNIMutex(g_pool);
if(isExceptionThrown())
{
return false;
}
if(!JNIThreadData::initThreadData())
{
return false;
}
setEnv(env);
if(isExceptionThrown())
{
return false;
}
g_initEnv = NULL;
g_inInit = false;
return true;
}
apr_pool_t * JNIUtil::getPool()
{
return g_pool;
}
void JNIUtil::throwError(const char *message)
{
if(getLogLevel() >= errorLog)
{
JNICriticalSection cs(*g_logMutex);
g_logStream << "Error thrown <" << message << ">" << std::endl;
}
JNIEnv *env = getEnv();
jclass clazz = env->FindClass(JAVA_PACKAGE"/JNIError");
if(isJavaExceptionThrown())
{
return;
}
env->ThrowNew(clazz, message);
setExceptionThrown();
env->DeleteLocalRef(clazz);
}
void JNIUtil::handleSVNError(svn_error *err)
{
JNIEnv *env = getEnv();
jclass clazz = env->FindClass(JAVA_PACKAGE"/ClientException");
if(getLogLevel() >= exceptionLog)
{
JNICriticalSection cs(*g_logMutex);
g_logStream << "Error SVN exception thrown message:<";
g_logStream << err->message << "> file:<" << err->file << "> apr-err:<" << err->apr_err;
g_logStream << ">" << std::endl;
}
if(isJavaExceptionThrown())
{
return;
}
std::string buffer;
assembleErrorMessage(err, 0, APR_SUCCESS, buffer);
jstring jmessage = makeJString(buffer.c_str());
if(isJavaExceptionThrown())
{
return;
}
if(isJavaExceptionThrown())
{
return;
}
jstring jfile = makeJString(err->file);
if(isJavaExceptionThrown())
{
return;
}
jmethodID mid = env->GetMethodID(clazz, "<init>", "(Ljava/lang/String;Ljava/lang/String;I)V");
if(isJavaExceptionThrown())
{
return;
}
jobject error = env->NewObject(clazz, mid, jmessage, jfile, static_cast<jint>(err->apr_err));
if(isJavaExceptionThrown())
{
return;
}
env->DeleteLocalRef(clazz);
if(isJavaExceptionThrown())
{
return;
}
env->DeleteLocalRef(jmessage);
if(isJavaExceptionThrown())
{
return;
}
env->DeleteLocalRef(jfile);
if(isJavaExceptionThrown())
{
return;
}
env->Throw(static_cast<jthrowable>(error));
}
void JNIUtil::putFinalizedClient(SVNClient *cl)
{
if(getLogLevel() >= errorLog)
{
JNICriticalSection cs(*g_logMutex);
g_logStream << "a client object was not disposed" << std::endl;
}
JNICriticalSection cs(*g_finalizedObjectsMutex);
if(isExceptionThrown())
{
return;
}
g_finalizedObjects.push_back(cl);
}
void JNIUtil::handleAPRError(int error, const char *op)
{
char *buffer = getFormatBuffer();
if(buffer == NULL)
{
return;
}
apr_snprintf(buffer, formatBufferSize, "an error occured in funcation %s with return value %d",
op, error);
throwError(buffer);
}
bool JNIUtil::isExceptionThrown()
{
if(g_inInit)
{
return g_initException;
}
JNIThreadData *data = JNIThreadData::getThreadData();
return data == NULL || data->m_exceptionThrown;
}
void JNIUtil::setEnv(JNIEnv *env)
{
JNIThreadData *data = JNIThreadData::getThreadData();
data->m_env = env;
data->m_exceptionThrown = false;
}
JNIEnv * JNIUtil::getEnv()
{
if(g_inInit)
{
return g_initEnv;
}
JNIThreadData *data = JNIThreadData::getThreadData();
return data->m_env;
}
bool JNIUtil::isJavaExceptionThrown()
{
JNIEnv *env = getEnv();
if(env->ExceptionCheck())
{
jthrowable exp = env->ExceptionOccurred();
env->ExceptionDescribe();
env->Throw(exp);
env->DeleteLocalRef(exp);
return true;
}
return false;
}
jstring JNIUtil::makeJString(const char *txt)
{
if(txt == NULL)
{
return NULL;
}
JNIEnv *env = getEnv();
jstring js = env->NewStringUTF(txt);
return js;
}
void JNIUtil::setExceptionThrown()
{
if(g_inInit)
{
g_initException = true;
}
JNIThreadData *data = JNIThreadData::getThreadData();
data->m_exceptionThrown = true;
}
void JNIUtil::initLogFile(int level, jstring path)
{
JNICriticalSection cs(*g_logMutex);
if(g_logLevel > noLog)
{
g_logStream.close();
}
g_logLevel = level;
JNIStringHolder myPath(path);
if(g_logLevel > noLog)
{
g_logStream.open(myPath, std::ios::app);
//g_logStream.open(myPath, std::ios_base::app);
}
}
char * JNIUtil::getFormatBuffer()
{
if(g_inInit)
{
return g_initFormatBuffer;
}
JNIThreadData *data = JNIThreadData::getThreadData();
if(data == NULL)
{
return g_initFormatBuffer;
}
return data->m_formatBuffer;
}
int JNIUtil::getLogLevel()
{
return g_logLevel;
}
void JNIUtil::logMessage(const char *message)
{
JNICriticalSection cs(*g_logMutex);
g_logStream << message << std::endl;
}
jobject JNIUtil::createDate(apr_time_t time)
{
jlong javatime = time /1000;
JNIEnv *env = getEnv();
jclass clazz = env->FindClass("java/util/Date");
if(isJavaExceptionThrown())
{
return NULL;
}
static jmethodID mid = 0;
if(mid == 0)
{
mid = env->GetMethodID(clazz, "<init>", "(J)V");
if(isJavaExceptionThrown())
{
return NULL;
}
}
jobject ret = env->NewObject(clazz, mid, javatime);
if(isJavaExceptionThrown())
{
return NULL;
}
env->DeleteLocalRef(clazz);
if(isJavaExceptionThrown())
{
return NULL;
}
return ret;
}
Pool * JNIUtil::getRequestPool()
{
return g_requestPool;
}
void JNIUtil::setRequestPool(Pool *pool)
{
g_requestPool = pool;
}
jbyteArray JNIUtil::makeJByteArray(const signed char *data, int length)
{
if(data == NULL || length == 0)
{
return NULL;
}
JNIEnv *env = getEnv();
jbyteArray ret = env->NewByteArray(length);
if(isJavaExceptionThrown())
{
return NULL;
}
jbyte *retdata = env->GetByteArrayElements(ret, NULL);
if(isJavaExceptionThrown())
{
return NULL;
}
memcpy(retdata, data, length);
env->ReleaseByteArrayElements(ret, retdata, 0);
if(isJavaExceptionThrown())
{
return NULL;
}
return ret;
}
void JNIUtil::assembleErrorMessage(svn_error *err, int depth, apr_status_t parent_apr_err, std::string &buffer)
{
char errbuf[256];
// char utfbuf[2048];
// const char *err_string;
/* Pretty-print the error */
/* Note: we can also log errors here someday. */
/* When we're recursing, don't repeat the top-level message if its
the same as before. */
if (depth == 0 || err->apr_err != parent_apr_err)
{
/* Is this a Subversion-specific error code? */
if ((err->apr_err > APR_OS_START_USEERR)
&& (err->apr_err <= APR_OS_START_CANONERR))
buffer.append(svn_strerror (err->apr_err, errbuf, sizeof (errbuf)));
/* Otherwise, this must be an APR error code. */
else
buffer.append(apr_strerror (err->apr_err, errbuf, sizeof (errbuf)));
buffer.append("\n");
}
if (err->message)
buffer.append("svn: ").append(err->message).append("\n");
if (err->child)
assembleErrorMessage(err->child, depth + 1, err->apr_err, buffer);
}
<commit_msg>* JNIUtil.cpp (JNIUtil::handleSVNError(svn_error *err) handleSVNError will delete the parameter err to avoid leeks<commit_after>/**
* @copyright
* ====================================================================
* Copyright (c) 2003 CollabNet. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://subversion.tigris.org/license-1.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision
* history and logs, available at http://subversion.tigris.org/.
* ====================================================================
* @endcopyright
*
* @file JNIUtil.cpp
* @brief Implementation of the class JNIUtil
*/
#include "JNIUtil.h"
#include <locale.h>
#include <apr_strings.h>
#include <apr_tables.h>
#include <apr_general.h>
#include <apr_lib.h>
#include <svn_pools.h>
#include <svn_config.h>
//#include <ios>
#include "SVNClient.h"
#include "JNIMutex.h"
#include "JNICriticalSection.h"
#include "JNIThreadData.h"
#include "JNIStringHolder.h"
apr_pool_t *JNIUtil::g_pool = NULL;
std::list<SVNClient*> JNIUtil::g_finalizedObjects;
JNIMutex *JNIUtil::g_finalizedObjectsMutex = NULL;
JNIMutex *JNIUtil::g_logMutex = NULL;
bool JNIUtil::g_initException;
bool JNIUtil::g_inInit;
JNIEnv *JNIUtil::g_initEnv;
char JNIUtil::g_initFormatBuffer[formatBufferSize];
int JNIUtil::g_logLevel = JNIUtil::noLog;
std::ofstream JNIUtil::g_logStream;
Pool *JNIUtil::g_requestPool;
bool JNIUtil::JNIInit(JNIEnv *env)
{
static bool run = false;
if(run)
{
env->ExceptionClear();
setEnv(env);
JNICriticalSection cs(*g_finalizedObjectsMutex) ;
if(isExceptionThrown())
{
return false;
}
for(std::list<SVNClient*>::iterator it = g_finalizedObjects.begin(); it != g_finalizedObjects.end(); it++)
{
delete *it;
}
g_finalizedObjects.clear();
return true;
}
run = true;
if(g_inInit)
{
return false;
}
g_inInit = true;
g_initEnv = env;
/* C programs default to the "C" locale by default. But because svn
is supposed to be i18n-aware, it should inherit the default
locale of its environment. */
setlocale (LC_ALL, "");
/* Initialize the APR subsystem, and register an atexit() function
to Uninitialize that subsystem at program exit. */
apr_status_t apr_err = apr_initialize ();
if (apr_err)
{
fprintf (stderr, "error: apr_initialize\n");
return false;
}
int err2 = atexit (apr_terminate);
if (err2)
{
fprintf (stderr, "error: atexit returned %d\n", err2);
return false;
}
/* Create our top-level pool. */
g_pool = svn_pool_create (NULL);
svn_error *err = svn_config_ensure (NULL, g_pool); // we use the default directory for config files
if (err)
{
svn_pool_destroy (g_pool);
handleSVNError(err);
return false;
}
g_finalizedObjectsMutex = new JNIMutex(g_pool);
if(isExceptionThrown())
{
return false;
}
g_logMutex = new JNIMutex(g_pool);
if(isExceptionThrown())
{
return false;
}
if(!JNIThreadData::initThreadData())
{
return false;
}
setEnv(env);
if(isExceptionThrown())
{
return false;
}
g_initEnv = NULL;
g_inInit = false;
return true;
}
apr_pool_t * JNIUtil::getPool()
{
return g_pool;
}
void JNIUtil::throwError(const char *message)
{
if(getLogLevel() >= errorLog)
{
JNICriticalSection cs(*g_logMutex);
g_logStream << "Error thrown <" << message << ">" << std::endl;
}
JNIEnv *env = getEnv();
jclass clazz = env->FindClass(JAVA_PACKAGE"/JNIError");
if(isJavaExceptionThrown())
{
return;
}
env->ThrowNew(clazz, message);
setExceptionThrown();
env->DeleteLocalRef(clazz);
}
void JNIUtil::handleSVNError(svn_error *err)
{
JNIEnv *env = getEnv();
jclass clazz = env->FindClass(JAVA_PACKAGE"/ClientException");
if(getLogLevel() >= exceptionLog)
{
JNICriticalSection cs(*g_logMutex);
g_logStream << "Error SVN exception thrown message:<";
g_logStream << err->message << "> file:<" << err->file << "> apr-err:<" << err->apr_err;
g_logStream << ">" << std::endl;
}
if(isJavaExceptionThrown())
{
svn_error_clear(err);
return;
}
std::string buffer;
assembleErrorMessage(err, 0, APR_SUCCESS, buffer);
jstring jmessage = makeJString(buffer.c_str());
if(isJavaExceptionThrown())
{
svn_error_clear(err);
return;
}
if(isJavaExceptionThrown())
{
svn_error_clear(err);
return;
}
jstring jfile = makeJString(err->file);
if(isJavaExceptionThrown())
{
svn_error_clear(err);
return;
}
jmethodID mid = env->GetMethodID(clazz, "<init>", "(Ljava/lang/String;Ljava/lang/String;I)V");
if(isJavaExceptionThrown())
{
svn_error_clear(err);
return;
}
jobject error = env->NewObject(clazz, mid, jmessage, jfile, static_cast<jint>(err->apr_err));
svn_error_clear(err);
if(isJavaExceptionThrown())
{
return;
}
env->DeleteLocalRef(clazz);
if(isJavaExceptionThrown())
{
return;
}
env->DeleteLocalRef(jmessage);
if(isJavaExceptionThrown())
{
return;
}
env->DeleteLocalRef(jfile);
if(isJavaExceptionThrown())
{
return;
}
env->Throw(static_cast<jthrowable>(error));
}
void JNIUtil::putFinalizedClient(SVNClient *cl)
{
if(getLogLevel() >= errorLog)
{
JNICriticalSection cs(*g_logMutex);
g_logStream << "a client object was not disposed" << std::endl;
}
JNICriticalSection cs(*g_finalizedObjectsMutex);
if(isExceptionThrown())
{
return;
}
g_finalizedObjects.push_back(cl);
}
void JNIUtil::handleAPRError(int error, const char *op)
{
char *buffer = getFormatBuffer();
if(buffer == NULL)
{
return;
}
apr_snprintf(buffer, formatBufferSize, "an error occured in funcation %s with return value %d",
op, error);
throwError(buffer);
}
bool JNIUtil::isExceptionThrown()
{
if(g_inInit)
{
return g_initException;
}
JNIThreadData *data = JNIThreadData::getThreadData();
return data == NULL || data->m_exceptionThrown;
}
void JNIUtil::setEnv(JNIEnv *env)
{
JNIThreadData *data = JNIThreadData::getThreadData();
data->m_env = env;
data->m_exceptionThrown = false;
}
JNIEnv * JNIUtil::getEnv()
{
if(g_inInit)
{
return g_initEnv;
}
JNIThreadData *data = JNIThreadData::getThreadData();
return data->m_env;
}
bool JNIUtil::isJavaExceptionThrown()
{
JNIEnv *env = getEnv();
if(env->ExceptionCheck())
{
jthrowable exp = env->ExceptionOccurred();
env->ExceptionDescribe();
env->Throw(exp);
env->DeleteLocalRef(exp);
return true;
}
return false;
}
jstring JNIUtil::makeJString(const char *txt)
{
if(txt == NULL)
{
return NULL;
}
JNIEnv *env = getEnv();
jstring js = env->NewStringUTF(txt);
return js;
}
void JNIUtil::setExceptionThrown()
{
if(g_inInit)
{
g_initException = true;
}
JNIThreadData *data = JNIThreadData::getThreadData();
data->m_exceptionThrown = true;
}
void JNIUtil::initLogFile(int level, jstring path)
{
JNICriticalSection cs(*g_logMutex);
if(g_logLevel > noLog)
{
g_logStream.close();
}
g_logLevel = level;
JNIStringHolder myPath(path);
if(g_logLevel > noLog)
{
g_logStream.open(myPath, std::ios::app);
//g_logStream.open(myPath, std::ios_base::app);
}
}
char * JNIUtil::getFormatBuffer()
{
if(g_inInit)
{
return g_initFormatBuffer;
}
JNIThreadData *data = JNIThreadData::getThreadData();
if(data == NULL)
{
return g_initFormatBuffer;
}
return data->m_formatBuffer;
}
int JNIUtil::getLogLevel()
{
return g_logLevel;
}
void JNIUtil::logMessage(const char *message)
{
JNICriticalSection cs(*g_logMutex);
g_logStream << message << std::endl;
}
jobject JNIUtil::createDate(apr_time_t time)
{
jlong javatime = time /1000;
JNIEnv *env = getEnv();
jclass clazz = env->FindClass("java/util/Date");
if(isJavaExceptionThrown())
{
return NULL;
}
static jmethodID mid = 0;
if(mid == 0)
{
mid = env->GetMethodID(clazz, "<init>", "(J)V");
if(isJavaExceptionThrown())
{
return NULL;
}
}
jobject ret = env->NewObject(clazz, mid, javatime);
if(isJavaExceptionThrown())
{
return NULL;
}
env->DeleteLocalRef(clazz);
if(isJavaExceptionThrown())
{
return NULL;
}
return ret;
}
Pool * JNIUtil::getRequestPool()
{
return g_requestPool;
}
void JNIUtil::setRequestPool(Pool *pool)
{
g_requestPool = pool;
}
jbyteArray JNIUtil::makeJByteArray(const signed char *data, int length)
{
if(data == NULL || length == 0)
{
return NULL;
}
JNIEnv *env = getEnv();
jbyteArray ret = env->NewByteArray(length);
if(isJavaExceptionThrown())
{
return NULL;
}
jbyte *retdata = env->GetByteArrayElements(ret, NULL);
if(isJavaExceptionThrown())
{
return NULL;
}
memcpy(retdata, data, length);
env->ReleaseByteArrayElements(ret, retdata, 0);
if(isJavaExceptionThrown())
{
return NULL;
}
return ret;
}
void JNIUtil::assembleErrorMessage(svn_error *err, int depth, apr_status_t parent_apr_err, std::string &buffer)
{
char errbuf[256];
// char utfbuf[2048];
// const char *err_string;
/* Pretty-print the error */
/* Note: we can also log errors here someday. */
/* When we're recursing, don't repeat the top-level message if its
the same as before. */
if (depth == 0 || err->apr_err != parent_apr_err)
{
/* Is this a Subversion-specific error code? */
if ((err->apr_err > APR_OS_START_USEERR)
&& (err->apr_err <= APR_OS_START_CANONERR))
buffer.append(svn_strerror (err->apr_err, errbuf, sizeof (errbuf)));
/* Otherwise, this must be an APR error code. */
else
buffer.append(apr_strerror (err->apr_err, errbuf, sizeof (errbuf)));
buffer.append("\n");
}
if (err->message)
buffer.append("svn: ").append(err->message).append("\n");
if (err->child)
assembleErrorMessage(err->child, depth + 1, err->apr_err, buffer);
}
<|endoftext|> |
<commit_before><commit_msg>Constify some OUStrings<commit_after><|endoftext|> |
<commit_before>TString names=("TTree_cuts");
TObjArray* arrNames = names.Tokenize(";");
const Int_t nDie = arrNames->GetEntriesFast();
Int_t selectedCentrality = -1; // not yet implemented
Int_t selectedPID;
Bool_t isPrefilterCutset;
Double_t rejCutMee;
Double_t rejCutTheta;
Double_t rejCutPhiV;
//________________________________________________________________
// binning of 3D output histograms
// eta bins
const Double_t EtaMin = -1.;
const Double_t EtaMax = 1.;
const Int_t nBinsEta = 40; //flexible to rebin
// phi bins
const Double_t PhiMin = 0.;
const Double_t PhiMax = 6.2832;
const Int_t nBinsPhi = 60; //flexible to rebin
const Double_t PtBins[] = {0.0, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70,
0.75, 0.80, 0.85, 0.90, 1.00, 1.10, 1.15, 1.25, 1.35, 1.55, 1.80,
2.05, 2.30, 2.60, 2.90, 3.30, 3.60, 4.00, 5.00, 6.50, 8.00, 10.0};
// Bool_t bUseRelPResolution = kTRUE; //not used
Bool_t bUseEtaResolution = kTRUE; // use eta or theta resolution?
Bool_t CalcEfficiencyRec = kTRUE;
Bool_t CalcEfficiencyPoslabel = kFALSE;
Bool_t CalcResolution = kTRUE;
Bool_t MakeResolutionSparse = kFALSE;
Bool_t doPairing = kTRUE;
// resolution binnings
Int_t NbinsMom = 2000;
Double_t MomMin = 0.;
Double_t MomMax = 10.;
Int_t NbinsDeltaMom = 1001;
Double_t DeltaMomMin = -9.005;
Double_t DeltaMomMax = 1.005;
Int_t NbinsRelMom = 1201;
Double_t RelMomMin = -0.0005;
Double_t RelMomMax = 1.2005;
Int_t NbinsDeltaEta = 1001;
Double_t DeltaEtaMin = -0.5005;
Double_t DeltaEtaMax = 0.5005;
Int_t NbinsDeltaTheta = 1001;
Double_t DeltaThetaMin = -0.5005;
Double_t DeltaThetaMax = 0.5005;
Int_t NbinsDeltaPhi = 601;
Double_t DeltaPhiMin = -0.3005;
Double_t DeltaPhiMax = 0.3005;
Int_t NbinsDeltaAngle = 401;
Double_t DeltaAngleMin = -0.2005;
Double_t DeltaAngleMax = 0.6005;
//Create mass bins
const Double_t MeeBins[] ={0.00, 0.025, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.12,
0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.95, 1.05, 1.25,
1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 2.9, 3.0, 3.05, 3.1,
3.3, 3.8, 5.00};
const Int_t nBinsMee = sizeof(MeeBins)/sizeof(MeeBins[0])-1;
const Double_t PteeBins[] = {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9,
1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9,
2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9,
3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5,
8.0, 8.5, 9.0, 9.5, 10.0};
const Int_t nBinsPtee = sizeof(PteeBins)/sizeof(PteeBins[0])-1;
// in increasing order
const TString sRuns("265309, 265334, 265335, 265338, 265339,
265342, 265343, 265344, 265377, 265378,
265381, 265383, 265384, 265385, 265387,
265388, 265419, 265420, 265421, 265422,
265424, 265427, 265435, 265499, 265500,
265501, 265521, 265525");
//
// ^^^^^^^^^^ [/end binning histograms] ^^^^^^^^^^
//________________________________________________________________
// specify if track tree shall be filled and written to file (only recommended for small checks!)
const Bool_t writeTree = kFALSE;
// specify for which "cutInstance" the support histos should be filled!
const Int_t supportedCutInstance = 0;
//
//________________________________________________________________
// settings which are identical for all configs that run together
// event cuts
const Bool_t reqVertex = kTRUE;
const Double_t vertexZcut = 10.;
//Set centrality in AddTask arguments
// MC cuts
const Double_t EtaMinGEN = -1.; // make sure to be within 3D histogram binning (EtaMin, EtaMax, PtBins[]).
const Double_t EtaMaxGEN = 1.;
const Double_t PtMinGEN = 0.100; // 100 MeV as absolute lower limit for any setting.
const Double_t PtMaxGEN = 50.;
const Bool_t CutInjectedSignals = kFALSE;
const UInt_t NminEleInEventForRej = 2;
// ^^^^^^^^^^ [/end common settings] ^^^^^^^^^^
//________________________________________________________________
AliAnalysisCuts* SetupEventCuts()
{
// event cuts are identical for all analysis 'cutInstance's that run together!
AliDielectronEventCuts *eventCuts = new AliDielectronEventCuts("eventCuts","Vertex Track && |vtxZ|<10 && ncontrib>0");
eventCuts->SetVertexType(AliDielectronEventCuts::kVtxSPD); // AOD
eventCuts->SetRequireVertex();
eventCuts->SetMinVtxContributors(1);
eventCuts->SetVertexZ(-10.,10.);
return eventCuts;
}
//________________________________________________________________
AliAnalysisFilter* SetupTrackCutsAndSettings(Int_t cutInstance, Bool_t hasITS = kTRUE)
{
std::cout << "SetupTrackCutsAndSettings()" <<std::endl;
AliAnalysisFilter *anaFilter = new AliAnalysisFilter("anaFilter","anaFilter"); // named constructor seems mandatory!
selectedPID=-1;
isPrefilterCutset=kFALSE;
rejCutMee=-1;
rejCutTheta=-1;
rejCutPhiV=3.2; // relevant are values below pi, so initialization to 3.2 means disabling.
// produce analysis filter by using functions in this config:
anaFilter->AddCuts( SetupTrackCuts(cutInstance, hasITS) );
anaFilter->AddCuts( SetupPIDcuts(cutInstance) );
std::cout << "...cuts added!" <<std::endl;
return anaFilter;
}
// prefilter cuts are not used at the moment
//________________________________________________________________
Int_t SetupPrefilterPairCuts(Int_t cutInstance)
{
std::cout << "SetupPrefilterPairCuts()" <<std::endl;
return 1;
}
//________________________________________________________________
AliAnalysisCuts* SetupTrackCuts(Int_t cutInstance, Bool_t hasITS = kTRUE)
{
std::cout << "SetupTrackCuts()" <<std::endl;
//AliAnalysisCuts* trackCuts=0x0;
AliESDtrackCuts *fesdTrackCuts = new AliESDtrackCuts();
//Cuts implemented in TreeMaker
if(cutInstance == 0){
//FilterBit 4 used to filter AODs
//Set via GetStandardITSTPCTrackCuts 2011(kFALSE, 1)
fesdTrackCuts->SetPtRange(0.2, 1e30);
fesdTrackCuts->SetEtaRange(-0.8, 0.8);
fesdTrackCuts->SetMinNCrossedRowsTPC(70);
//fesdTrackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8);
fesdTrackCuts->SetMaxChi2PerClusterTPC(4);
fesdTrackCuts->SetAcceptKinkDaughters(kFALSE);
fesdTrackCuts->SetRequireSigmaToVertex(kFALSE);
fesdTrackCuts->SetRequireTPCRefit(kTRUE);
fesdTrackCuts->SetRequireITSRefit(kTRUE);
fesdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kAny);
fesdTrackCuts->SetRequireSigmaToVertex(kFALSE);
fesdTrackCuts->SetMaxChi2PerClusterITS(36);
//Manually set by fitler bit 4
////Override setting in TrackCuts2011
fesdTrackCuts->SetMaxDCAToVertexXY(2.4);
fesdTrackCuts->SetMaxDCAToVertexZ(3.2);
fesdTrackCuts->SetDCAToVertex2D(kTRUE);
//Manually implemented track cuts in TreeMaker
//General
fesdTrackCuts->SetPtRange(0.2, 10);
fesdTrackCuts->SetEtaRange(-0.8, 0.8);
fesdTrackCuts->SetMaxDCAToVertexZ(3.0);
fesdTrackCuts->SetMaxDCAToVertexXY(1.0);
//TPC
fesdTrackCuts->SetMinNClustersTPC(70);
//fesdTrackCuts->SetMinNCrossedRowsTPC(60); FilterBit4 stronger cut
fesdTrackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(0.3);
//fesdTrackCuts->SetMaxChi2PerClusterTPC(4.5);
fesdTrackCuts->SetMaxFractionSharedTPCClusters(0.4);
//ITS
if(hasITS){
fesdTrackCuts->SetMinNClustersITS(4);
}else{
fesdTrackCuts->SetMinNClustersITS(2);
}
}
return fesdTrackCuts;
}
//________________________________________________________________
AliAnalysisCuts* SetupPIDcuts(Int_t cutInstance)
{
std::cout << "SetupPIDcuts()" <<std::endl;
AliAnalysisCuts* pidCuts=0x0;
AliDielectronPID *pid = new AliDielectronPID();
//The only PID cut applied when creating Trees
if(cutInstance == 0){
pid->AddCut(AliDielectronPID::kTPC, AliPID::kElectron, -4, 4, 0, 1e30, kFALSE, AliDielectronPID::kRequire, AliDielectronVarManager::kPt);
}
pidCuts = pid;
return pidCuts;
}
<commit_msg>removed bug<commit_after>TString names=("TTree_cuts");
TObjArray* arrNames = names.Tokenize(";");
const Int_t nDie = arrNames->GetEntriesFast();
Int_t selectedCentrality = -1; // not yet implemented
Int_t selectedPID;
Bool_t isPrefilterCutset;
Double_t rejCutMee;
Double_t rejCutTheta;
Double_t rejCutPhiV;
//________________________________________________________________
// binning of 3D output histograms
// eta bins
const Double_t EtaMin = -1.;
const Double_t EtaMax = 1.;
const Int_t nBinsEta = 40; //flexible to rebin
// phi bins
const Double_t PhiMin = 0.;
const Double_t PhiMax = 6.2832;
const Int_t nBinsPhi = 60; //flexible to rebin
const Double_t PtBins[] = {0.0, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70,
0.75, 0.80, 0.85, 0.90, 1.00, 1.10, 1.15, 1.25, 1.35, 1.55, 1.80,
2.05, 2.30, 2.60, 2.90, 3.30, 3.60, 4.00, 5.00, 6.50, 8.00, 10.0};
// Bool_t bUseRelPResolution = kTRUE; //not used
Bool_t bUseEtaResolution = kTRUE; // use eta or theta resolution?
Bool_t CalcEfficiencyRec = kTRUE;
Bool_t CalcEfficiencyPoslabel = kFALSE;
Bool_t CalcResolution = kTRUE;
Bool_t MakeResolutionSparse = kFALSE;
Bool_t doPairing = kTRUE;
// resolution binnings
Int_t NbinsMom = 2000;
Double_t MomMin = 0.;
Double_t MomMax = 10.;
Int_t NbinsDeltaMom = 1001;
Double_t DeltaMomMin = -9.005;
Double_t DeltaMomMax = 1.005;
Int_t NbinsRelMom = 1201;
Double_t RelMomMin = -0.0005;
Double_t RelMomMax = 1.2005;
Int_t NbinsDeltaEta = 1001;
Double_t DeltaEtaMin = -0.5005;
Double_t DeltaEtaMax = 0.5005;
Int_t NbinsDeltaTheta = 1001;
Double_t DeltaThetaMin = -0.5005;
Double_t DeltaThetaMax = 0.5005;
Int_t NbinsDeltaPhi = 601;
Double_t DeltaPhiMin = -0.3005;
Double_t DeltaPhiMax = 0.3005;
Int_t NbinsDeltaAngle = 401;
Double_t DeltaAngleMin = -0.2005;
Double_t DeltaAngleMax = 0.6005;
//Create mass bins
const Double_t MeeBins[] ={0.00, 0.025, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.12,
0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.95, 1.05, 1.25,
1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 2.9, 3.0, 3.05, 3.1,
3.3, 3.8, 5.00};
const Int_t nBinsMee = sizeof(MeeBins)/sizeof(MeeBins[0])-1;
const Double_t PteeBins[] = {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9,
1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9,
2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9,
3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5,
8.0, 8.5, 9.0, 9.5, 10.0};
const Int_t nBinsPtee = sizeof(PteeBins)/sizeof(PteeBins[0])-1;
// in increasing order
const TString sRuns("265309, 265334, 265335, 265338, 265339,
265342, 265343, 265344, 265377, 265378,
265381, 265383, 265384, 265385, 265387,
265388, 265419, 265420, 265421, 265422,
265424, 265427, 265435, 265499, 265500,
265501, 265521, 265525");
//
// ^^^^^^^^^^ [/end binning histograms] ^^^^^^^^^^
//________________________________________________________________
// specify if track tree shall be filled and written to file (only recommended for small checks!)
const Bool_t writeTree = kFALSE;
// specify for which "cutInstance" the support histos should be filled!
const Int_t supportedCutInstance = 0;
//
//________________________________________________________________
// settings which are identical for all configs that run together
// event cuts
const Bool_t reqVertex = kTRUE;
const Double_t vertexZcut = 10.;
//Set centrality in AddTask arguments
// MC cuts
const Double_t EtaMinGEN = -1.; // make sure to be within 3D histogram binning (EtaMin, EtaMax, PtBins[]).
const Double_t EtaMaxGEN = 1.;
const Double_t PtMinGEN = 0.100; // 100 MeV as absolute lower limit for any setting.
const Double_t PtMaxGEN = 50.;
const Bool_t CutInjectedSignals = kFALSE;
const UInt_t NminEleInEventForRej = 2;
// ^^^^^^^^^^ [/end common settings] ^^^^^^^^^^
//________________________________________________________________
AliAnalysisCuts* SetupEventCuts()
{
// event cuts are identical for all analysis 'cutInstance's that run together!
AliDielectronEventCuts *eventCuts = new AliDielectronEventCuts("eventCuts","Vertex Track && |vtxZ|<10 && ncontrib>0");
eventCuts->SetVertexType(AliDielectronEventCuts::kVtxSPD); // AOD
eventCuts->SetRequireVertex();
eventCuts->SetMinVtxContributors(1);
eventCuts->SetVertexZ(-10.,10.);
return eventCuts;
}
//________________________________________________________________
AliAnalysisFilter* SetupTrackCutsAndSettings(Int_t cutInstance, Bool_t hasITS = kTRUE)
{
std::cout << "SetupTrackCutsAndSettings()" <<std::endl;
AliAnalysisFilter *anaFilter = new AliAnalysisFilter("anaFilter","anaFilter"); // named constructor seems mandatory!
selectedPID=-1;
isPrefilterCutset=kFALSE;
rejCutMee=-1;
rejCutTheta=-1;
rejCutPhiV=3.2; // relevant are values below pi, so initialization to 3.2 means disabling.
// produce analysis filter by using functions in this config:
anaFilter->AddCuts( SetupTrackCuts(cutInstance, hasITS) );
anaFilter->AddCuts( SetupPIDcuts(cutInstance) );
std::cout << "...cuts added!" <<std::endl;
return anaFilter;
}
// prefilter cuts are not used at the moment
//________________________________________________________________
Int_t SetupPrefilterPairCuts(Int_t cutInstance)
{
std::cout << "SetupPrefilterPairCuts()" <<std::endl;
return 1;
}
//________________________________________________________________
AliAnalysisCuts* SetupTrackCuts(Int_t cutInstance, Bool_t hasITS = kTRUE)
{
std::cout << "SetupTrackCuts()" <<std::endl;
//AliAnalysisCuts* trackCuts=0x0;
AliESDtrackCuts *fesdTrackCuts = new AliESDtrackCuts();
//Cuts implemented in TreeMaker
if(cutInstance == 0){
//FilterBit 4 used to filter AODs
//Set via GetStandardITSTPCTrackCuts 2011(kFALSE, 1)
fesdTrackCuts->SetMinNCrossedRowsTPC(70);
//fesdTrackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8);
fesdTrackCuts->SetMaxChi2PerClusterTPC(4);
fesdTrackCuts->SetAcceptKinkDaughters(kFALSE);
fesdTrackCuts->SetRequireSigmaToVertex(kFALSE);
fesdTrackCuts->SetRequireTPCRefit(kTRUE);
fesdTrackCuts->SetRequireITSRefit(kTRUE);
fesdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kAny);
fesdTrackCuts->SetRequireSigmaToVertex(kFALSE);
fesdTrackCuts->SetMaxChi2PerClusterITS(36);
//Manually set by fitler bit 4
////Override setting in TrackCuts2011
fesdTrackCuts->SetMaxDCAToVertexXY(2.4);
fesdTrackCuts->SetMaxDCAToVertexZ(3.2);
fesdTrackCuts->SetDCAToVertex2D(kTRUE);
//Manually implemented track cuts in TreeMaker
//General
fesdTrackCuts->SetPtRange(0.2, 10);
fesdTrackCuts->SetEtaRange(-0.8, 0.8);
fesdTrackCuts->SetMaxDCAToVertexZ(3.0);
fesdTrackCuts->SetMaxDCAToVertexXY(1.0);
//TPC
fesdTrackCuts->SetMinNClustersTPC(70);
//fesdTrackCuts->SetMinNCrossedRowsTPC(60); FilterBit4 stronger cut
fesdTrackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(0.3);
//fesdTrackCuts->SetMaxChi2PerClusterTPC(4.5);
fesdTrackCuts->SetMaxFractionSharedTPCClusters(0.4);
//ITS
if(hasITS){
fesdTrackCuts->SetMinNClustersITS(4);
}else{
fesdTrackCuts->SetMinNClustersITS(2);
}
}
return fesdTrackCuts;
}
//________________________________________________________________
AliAnalysisCuts* SetupPIDcuts(Int_t cutInstance)
{
std::cout << "SetupPIDcuts()" <<std::endl;
AliAnalysisCuts* pidCuts=0x0;
AliDielectronPID *pid = new AliDielectronPID();
//The only PID cut applied when creating Trees
if(cutInstance == 0){
pid->AddCut(AliDielectronPID::kTPC, AliPID::kElectron, -4, 4, 0, 1e30, kFALSE, AliDielectronPID::kRequire, AliDielectronVarManager::kPt);
}
pidCuts = pid;
return pidCuts;
}
<|endoftext|> |
<commit_before>/** @file
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <cstring>
#include <deque>
#include "P_SSLConfig.h"
#include "SSLSessionCache.h"
#define SSLSESSIONCACHE_STRINGIFY0(x) #x
#define SSLSESSIONCACHE_STRINGIFY(x) SSLSESSIONCACHE_STRINGIFY0(x)
#define SSLSESSIONCACHE_LINENO SSLSESSIONCACHE_STRINGIFY(__LINE__)
#ifdef DEBUG
#define PRINT_BUCKET(x) this->print(x " at " __FILE__ ":" SSLSESSIONCACHE_LINENO);
#else
#define PRINT_BUCKET(x)
#endif
using ts::detail::RBNode;
/* Session Cache */
SSLSessionCache::SSLSessionCache()
: session_bucket(NULL) {
Debug("ssl.session_cache", "Created new ssl session cache %p with %ld buckets each with size max size %ld", this, SSLConfigParams::session_cache_number_buckets, SSLConfigParams::session_cache_max_bucket_size);
session_bucket = new SSLSessionBucket[SSLConfigParams::session_cache_number_buckets];
}
SSLSessionCache::~SSLSessionCache() {
delete []session_bucket;
}
bool SSLSessionCache::getSession(const SSLSessionID &sid, SSL_SESSION **sess) const {
uint64_t hash = sid.hash();
uint64_t target_bucket = hash % SSLConfigParams::session_cache_number_buckets;
SSLSessionBucket *bucket = &session_bucket[target_bucket];
bool ret = false;
if (is_debug_tag_set("ssl.session_cache")) {
char buf[sid.len * 2 + 1];
sid.toString(buf, sizeof(buf));
Debug("ssl.session_cache.get", "SessionCache looking in bucket %" PRId64 " (%p) for session '%s' (hash: %" PRIX64 ").", target_bucket, bucket, buf, hash);
}
ret = bucket->getSession(sid, sess);
if (ret)
SSL_INCREMENT_DYN_STAT(ssl_session_cache_hit);
else
SSL_INCREMENT_DYN_STAT(ssl_session_cache_miss);
return ret;
}
void SSLSessionCache::removeSession(const SSLSessionID &sid) {
uint64_t hash = sid.hash();
uint64_t target_bucket = hash % SSLConfigParams::session_cache_number_buckets;
SSLSessionBucket *bucket = &session_bucket[target_bucket];
if (is_debug_tag_set("ssl.session_cache")) {
char buf[sid.len * 2 + 1];
sid.toString(buf, sizeof(buf));
Debug("ssl.session_cache.remove", "SessionCache using bucket %" PRId64 " (%p): Removing session '%s' (hash: %" PRIX64 ").", target_bucket, bucket, buf, hash);
}
SSL_INCREMENT_DYN_STAT(ssl_session_cache_eviction);
bucket->removeSession(sid);
}
void SSLSessionCache::insertSession(const SSLSessionID &sid, SSL_SESSION *sess) {
uint64_t hash = sid.hash();
uint64_t target_bucket = hash % SSLConfigParams::session_cache_number_buckets;
SSLSessionBucket *bucket = &session_bucket[target_bucket];
if (is_debug_tag_set("ssl.session_cache")) {
char buf[sid.len * 2 + 1];
sid.toString(buf, sizeof(buf));
Debug("ssl.session_cache.insert", "SessionCache using bucket %" PRId64 " (%p): Inserting session '%s' (hash: %" PRIX64 ").", target_bucket, bucket, buf, hash);
}
bucket->insertSession(sid, sess);
}
void SSLSessionBucket::insertSession(const SSLSessionID &id, SSL_SESSION *sess) {
size_t len = i2d_SSL_SESSION(sess, NULL); // make sure we're not going to need more than SSL_MAX_SESSION_SIZE bytes
/* do not cache a session that's too big. */
if (len > (size_t) SSL_MAX_SESSION_SIZE) {
Debug("ssl.session_cache", "Unable to save SSL session because size of %zd exceeds the max of %d", len, SSL_MAX_SESSION_SIZE);
return;
}
if (is_debug_tag_set("ssl.session_cache")) {
char buf[id.len * 2 + 1];
id.toString(buf, sizeof(buf));
Debug("ssl.session_cache", "Inserting session '%s' to bucket %p.", buf, this);
}
Ptr<IOBufferData> buf;
buf = new_IOBufferData(buffer_size_to_index(len, MAX_BUFFER_SIZE_INDEX), MEMALIGNED);
ink_release_assert(static_cast<size_t>(buf->block_size()) >= len);
unsigned char *loc = reinterpret_cast<unsigned char *>(buf->data());
i2d_SSL_SESSION(sess, &loc);
SSLSession *ssl_session = new SSLSession(id, buf, len);
MUTEX_TRY_LOCK(lock, mutex, this_ethread());
if (!lock.is_locked()) {
SSL_INCREMENT_DYN_STAT(ssl_session_cache_lock_contention);
if (SSLConfigParams::session_cache_skip_on_lock_contention)
return;
lock.acquire(this_ethread());
}
PRINT_BUCKET("insertSession before")
if (queue.size >= static_cast<int>(SSLConfigParams::session_cache_max_bucket_size)) {
removeOldestSession();
}
/* do the actual insert */
queue.enqueue(ssl_session);
PRINT_BUCKET("insertSession after")
}
bool SSLSessionBucket::getSession(const SSLSessionID &id,
SSL_SESSION **sess) {
char buf[id.len * 2 + 1];
buf[0] = '\0'; // just to be safe.
if (is_debug_tag_set("ssl.session_cache")) {
id.toString(buf, sizeof(buf));
}
Debug("ssl.session_cache", "Looking for session with id '%s' in bucket %p", buf, this);
MUTEX_TRY_LOCK(lock, mutex, this_ethread());
if (!lock.is_locked()) {
SSL_INCREMENT_DYN_STAT(ssl_session_cache_lock_contention);
if (SSLConfigParams::session_cache_skip_on_lock_contention)
return false;
lock.acquire(this_ethread());
}
PRINT_BUCKET("getSession")
// We work backwards because that's the most likely place we'll find our session...
SSLSession *node = queue.tail;
while (node) {
if (node->session_id == id)
{
const unsigned char *loc = reinterpret_cast<const unsigned char *>(node->asn1_data->data());
*sess = d2i_SSL_SESSION(NULL, &loc, node->len_asn1_data);
return true;
}
node = node->link.prev;
}
Debug("ssl.session_cache", "Session with id '%s' not found in bucket %p.", buf, this);
return false;
}
void inline SSLSessionBucket::print(const char *ref_str) const {
/* NOTE: This method assumes you're already holding the bucket lock */
if (!is_debug_tag_set("ssl.session_cache.bucket")) {
return;
}
fprintf(stderr, "-------------- BUCKET %p (%s) ----------------\n", this, ref_str);
fprintf(stderr, "Current Size: %d, Max Size: %zd\n", queue.size, SSLConfigParams::session_cache_max_bucket_size);
fprintf(stderr, "Queue: \n");
SSLSession *node = queue.head;
while(node) {
char s_buf[2 * node->session_id.len + 1];
node->session_id.toString(s_buf, sizeof(s_buf));
fprintf(stderr, " %s\n", s_buf);
node = node->link.next;
}
}
void inline SSLSessionBucket::removeOldestSession() {
PRINT_BUCKET("removeOldestSession before")
while (queue.head && queue.size >= static_cast<int>(SSLConfigParams::session_cache_max_bucket_size)) {
SSLSession *old_head = queue.pop();
if (is_debug_tag_set("ssl.session_cache")) {
char buf[old_head->session_id.len * 2 + 1];
old_head->session_id.toString(buf, sizeof(buf));
Debug("ssl.session_cache", "Removing session '%s' from bucket %p because the bucket has size %d and max %zd", buf, this, (queue.size + 1), SSLConfigParams::session_cache_max_bucket_size);
}
delete old_head;
}
PRINT_BUCKET("removeOldestSession after")
}
void SSLSessionBucket::removeSession(const SSLSessionID &id) {
MUTEX_LOCK(lock, mutex, this_ethread()); // We can't bail on contention here because this session MUST be removed.
SSLSession *node = queue.head;
while (node) {
if (node->session_id == id)
{
queue.remove(node);
delete node;
return;
}
}
}
/* Session Bucket */
SSLSessionBucket::SSLSessionBucket()
: mutex(new ProxyMutex())
{
mutex->init("session_bucket");
}
SSLSessionBucket::~SSLSessionBucket() {
}
<commit_msg>TS-3156: use a proxy allocated mutex<commit_after>/** @file
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <cstring>
#include <deque>
#include "P_SSLConfig.h"
#include "SSLSessionCache.h"
#define SSLSESSIONCACHE_STRINGIFY0(x) #x
#define SSLSESSIONCACHE_STRINGIFY(x) SSLSESSIONCACHE_STRINGIFY0(x)
#define SSLSESSIONCACHE_LINENO SSLSESSIONCACHE_STRINGIFY(__LINE__)
#ifdef DEBUG
#define PRINT_BUCKET(x) this->print(x " at " __FILE__ ":" SSLSESSIONCACHE_LINENO);
#else
#define PRINT_BUCKET(x)
#endif
using ts::detail::RBNode;
/* Session Cache */
SSLSessionCache::SSLSessionCache()
: session_bucket(NULL) {
Debug("ssl.session_cache", "Created new ssl session cache %p with %ld buckets each with size max size %ld", this, SSLConfigParams::session_cache_number_buckets, SSLConfigParams::session_cache_max_bucket_size);
session_bucket = new SSLSessionBucket[SSLConfigParams::session_cache_number_buckets];
}
SSLSessionCache::~SSLSessionCache() {
delete []session_bucket;
}
bool SSLSessionCache::getSession(const SSLSessionID &sid, SSL_SESSION **sess) const {
uint64_t hash = sid.hash();
uint64_t target_bucket = hash % SSLConfigParams::session_cache_number_buckets;
SSLSessionBucket *bucket = &session_bucket[target_bucket];
bool ret = false;
if (is_debug_tag_set("ssl.session_cache")) {
char buf[sid.len * 2 + 1];
sid.toString(buf, sizeof(buf));
Debug("ssl.session_cache.get", "SessionCache looking in bucket %" PRId64 " (%p) for session '%s' (hash: %" PRIX64 ").", target_bucket, bucket, buf, hash);
}
ret = bucket->getSession(sid, sess);
if (ret)
SSL_INCREMENT_DYN_STAT(ssl_session_cache_hit);
else
SSL_INCREMENT_DYN_STAT(ssl_session_cache_miss);
return ret;
}
void SSLSessionCache::removeSession(const SSLSessionID &sid) {
uint64_t hash = sid.hash();
uint64_t target_bucket = hash % SSLConfigParams::session_cache_number_buckets;
SSLSessionBucket *bucket = &session_bucket[target_bucket];
if (is_debug_tag_set("ssl.session_cache")) {
char buf[sid.len * 2 + 1];
sid.toString(buf, sizeof(buf));
Debug("ssl.session_cache.remove", "SessionCache using bucket %" PRId64 " (%p): Removing session '%s' (hash: %" PRIX64 ").", target_bucket, bucket, buf, hash);
}
SSL_INCREMENT_DYN_STAT(ssl_session_cache_eviction);
bucket->removeSession(sid);
}
void SSLSessionCache::insertSession(const SSLSessionID &sid, SSL_SESSION *sess) {
uint64_t hash = sid.hash();
uint64_t target_bucket = hash % SSLConfigParams::session_cache_number_buckets;
SSLSessionBucket *bucket = &session_bucket[target_bucket];
if (is_debug_tag_set("ssl.session_cache")) {
char buf[sid.len * 2 + 1];
sid.toString(buf, sizeof(buf));
Debug("ssl.session_cache.insert", "SessionCache using bucket %" PRId64 " (%p): Inserting session '%s' (hash: %" PRIX64 ").", target_bucket, bucket, buf, hash);
}
bucket->insertSession(sid, sess);
}
void SSLSessionBucket::insertSession(const SSLSessionID &id, SSL_SESSION *sess) {
size_t len = i2d_SSL_SESSION(sess, NULL); // make sure we're not going to need more than SSL_MAX_SESSION_SIZE bytes
/* do not cache a session that's too big. */
if (len > (size_t) SSL_MAX_SESSION_SIZE) {
Debug("ssl.session_cache", "Unable to save SSL session because size of %zd exceeds the max of %d", len, SSL_MAX_SESSION_SIZE);
return;
}
if (is_debug_tag_set("ssl.session_cache")) {
char buf[id.len * 2 + 1];
id.toString(buf, sizeof(buf));
Debug("ssl.session_cache", "Inserting session '%s' to bucket %p.", buf, this);
}
Ptr<IOBufferData> buf;
buf = new_IOBufferData(buffer_size_to_index(len, MAX_BUFFER_SIZE_INDEX), MEMALIGNED);
ink_release_assert(static_cast<size_t>(buf->block_size()) >= len);
unsigned char *loc = reinterpret_cast<unsigned char *>(buf->data());
i2d_SSL_SESSION(sess, &loc);
SSLSession *ssl_session = new SSLSession(id, buf, len);
MUTEX_TRY_LOCK(lock, mutex, this_ethread());
if (!lock.is_locked()) {
SSL_INCREMENT_DYN_STAT(ssl_session_cache_lock_contention);
if (SSLConfigParams::session_cache_skip_on_lock_contention)
return;
lock.acquire(this_ethread());
}
PRINT_BUCKET("insertSession before")
if (queue.size >= static_cast<int>(SSLConfigParams::session_cache_max_bucket_size)) {
removeOldestSession();
}
/* do the actual insert */
queue.enqueue(ssl_session);
PRINT_BUCKET("insertSession after")
}
bool SSLSessionBucket::getSession(const SSLSessionID &id,
SSL_SESSION **sess) {
char buf[id.len * 2 + 1];
buf[0] = '\0'; // just to be safe.
if (is_debug_tag_set("ssl.session_cache")) {
id.toString(buf, sizeof(buf));
}
Debug("ssl.session_cache", "Looking for session with id '%s' in bucket %p", buf, this);
MUTEX_TRY_LOCK(lock, mutex, this_ethread());
if (!lock.is_locked()) {
SSL_INCREMENT_DYN_STAT(ssl_session_cache_lock_contention);
if (SSLConfigParams::session_cache_skip_on_lock_contention)
return false;
lock.acquire(this_ethread());
}
PRINT_BUCKET("getSession")
// We work backwards because that's the most likely place we'll find our session...
SSLSession *node = queue.tail;
while (node) {
if (node->session_id == id)
{
const unsigned char *loc = reinterpret_cast<const unsigned char *>(node->asn1_data->data());
*sess = d2i_SSL_SESSION(NULL, &loc, node->len_asn1_data);
return true;
}
node = node->link.prev;
}
Debug("ssl.session_cache", "Session with id '%s' not found in bucket %p.", buf, this);
return false;
}
void inline SSLSessionBucket::print(const char *ref_str) const {
/* NOTE: This method assumes you're already holding the bucket lock */
if (!is_debug_tag_set("ssl.session_cache.bucket")) {
return;
}
fprintf(stderr, "-------------- BUCKET %p (%s) ----------------\n", this, ref_str);
fprintf(stderr, "Current Size: %d, Max Size: %zd\n", queue.size, SSLConfigParams::session_cache_max_bucket_size);
fprintf(stderr, "Queue: \n");
SSLSession *node = queue.head;
while(node) {
char s_buf[2 * node->session_id.len + 1];
node->session_id.toString(s_buf, sizeof(s_buf));
fprintf(stderr, " %s\n", s_buf);
node = node->link.next;
}
}
void inline SSLSessionBucket::removeOldestSession() {
PRINT_BUCKET("removeOldestSession before")
while (queue.head && queue.size >= static_cast<int>(SSLConfigParams::session_cache_max_bucket_size)) {
SSLSession *old_head = queue.pop();
if (is_debug_tag_set("ssl.session_cache")) {
char buf[old_head->session_id.len * 2 + 1];
old_head->session_id.toString(buf, sizeof(buf));
Debug("ssl.session_cache", "Removing session '%s' from bucket %p because the bucket has size %d and max %zd", buf, this, (queue.size + 1), SSLConfigParams::session_cache_max_bucket_size);
}
delete old_head;
}
PRINT_BUCKET("removeOldestSession after")
}
void SSLSessionBucket::removeSession(const SSLSessionID &id) {
MUTEX_LOCK(lock, mutex, this_ethread()); // We can't bail on contention here because this session MUST be removed.
SSLSession *node = queue.head;
while (node) {
if (node->session_id == id)
{
queue.remove(node);
delete node;
return;
}
}
}
/* Session Bucket */
SSLSessionBucket::SSLSessionBucket() : mutex(new_ProxyMutex())
{
}
SSLSessionBucket::~SSLSessionBucket()
{
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-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.
// This test is POSIX only.
#include <unistd.h>
#include <stdio.h>
#include "base/basictypes.h"
#include "chrome/common/file_descriptor_set_posix.h"
#include "testing/gtest/include/gtest/gtest.h"
// The FileDescriptorSet will try and close some of the descriptor numbers
// which we given it. This is the base descriptor value. It's great enough such
// that no real descriptor will accidently be closed.
static const int kFDBase = 50000;
TEST(FileDescriptorSet, BasicAdd) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
ASSERT_EQ(set->size(), 0u);
ASSERT_TRUE(set->empty());
ASSERT_TRUE(set->Add(kFDBase));
ASSERT_EQ(set->size(), 1u);
ASSERT_TRUE(!set->empty());
// Empties the set and stops a warning about deleting a set with unconsumed
// descriptors
set->CommitAll();
}
TEST(FileDescriptorSet, BasicAddAndClose) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
ASSERT_EQ(set->size(), 0u);
ASSERT_TRUE(set->empty());
ASSERT_TRUE(set->AddAndAutoClose(kFDBase));
ASSERT_EQ(set->size(), 1u);
ASSERT_TRUE(!set->empty());
set->CommitAll();
}
TEST(FileDescriptorSet, MaxSize) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
for (unsigned i = 0;
i < FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE; ++i) {
ASSERT_TRUE(set->Add(kFDBase + 1 + i));
}
ASSERT_TRUE(!set->Add(kFDBase));
set->CommitAll();
}
TEST(FileDescriptorSet, SetDescriptors) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
ASSERT_TRUE(set->empty());
set->SetDescriptors(NULL, 0);
ASSERT_TRUE(set->empty());
static const int fds[] = {kFDBase};
set->SetDescriptors(fds, 1);
ASSERT_TRUE(!set->empty());
ASSERT_EQ(set->size(), 1u);
set->CommitAll();
}
TEST(FileDescriptorSet, GetDescriptors) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
set->GetDescriptors(NULL);
ASSERT_TRUE(set->Add(kFDBase));
int fds[1];
fds[0] = 0;
set->GetDescriptors(fds);
ASSERT_EQ(fds[0], kFDBase);
set->CommitAll();
ASSERT_TRUE(set->empty());
}
TEST(FileDescriptorSet, WalkInOrder) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
ASSERT_TRUE(set->Add(kFDBase));
ASSERT_TRUE(set->Add(kFDBase + 1));
ASSERT_TRUE(set->Add(kFDBase + 2));
ASSERT_EQ(set->GetDescriptorAt(0), kFDBase);
ASSERT_EQ(set->GetDescriptorAt(1), kFDBase + 1);
ASSERT_EQ(set->GetDescriptorAt(2), kFDBase + 2);
set->CommitAll();
}
TEST(FileDescriptorSet, WalkWrongOrder) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
ASSERT_TRUE(set->Add(kFDBase));
ASSERT_TRUE(set->Add(kFDBase + 1));
ASSERT_TRUE(set->Add(kFDBase + 2));
ASSERT_EQ(set->GetDescriptorAt(0), kFDBase);
ASSERT_EQ(set->GetDescriptorAt(2), -1);
set->CommitAll();
}
TEST(FileDescriptorSet, WalkCycle) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
ASSERT_TRUE(set->Add(kFDBase));
ASSERT_TRUE(set->Add(kFDBase + 1));
ASSERT_TRUE(set->Add(kFDBase + 2));
ASSERT_EQ(set->GetDescriptorAt(0), kFDBase);
ASSERT_EQ(set->GetDescriptorAt(1), kFDBase + 1);
ASSERT_EQ(set->GetDescriptorAt(2), kFDBase + 2);
ASSERT_EQ(set->GetDescriptorAt(0), kFDBase);
ASSERT_EQ(set->GetDescriptorAt(1), kFDBase + 1);
ASSERT_EQ(set->GetDescriptorAt(2), kFDBase + 2);
ASSERT_EQ(set->GetDescriptorAt(0), kFDBase);
ASSERT_EQ(set->GetDescriptorAt(1), kFDBase + 1);
ASSERT_EQ(set->GetDescriptorAt(2), kFDBase + 2);
set->CommitAll();
}
TEST(FileDescriptorSet, DontClose) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
const int fd = open("/dev/null", O_RDONLY);
ASSERT_TRUE(set->Add(fd));
set->CommitAll();
const int duped = dup(fd);
ASSERT_GE(duped, 0);
close(duped);
close(fd);
}
TEST(FileDescriptorSet, DoClose) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
const int fd = open("/dev/null", O_RDONLY);
ASSERT_TRUE(set->AddAndAutoClose(fd));
set->CommitAll();
const int duped = dup(fd);
ASSERT_EQ(duped, -1);
close(fd);
}
<commit_msg>Mac: build fix<commit_after>// Copyright (c) 2006-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.
// This test is POSIX only.
#include <unistd.h>
#include <fcntl.h>
#include "base/basictypes.h"
#include "chrome/common/file_descriptor_set_posix.h"
#include "testing/gtest/include/gtest/gtest.h"
// The FileDescriptorSet will try and close some of the descriptor numbers
// which we given it. This is the base descriptor value. It's great enough such
// that no real descriptor will accidently be closed.
static const int kFDBase = 50000;
TEST(FileDescriptorSet, BasicAdd) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
ASSERT_EQ(set->size(), 0u);
ASSERT_TRUE(set->empty());
ASSERT_TRUE(set->Add(kFDBase));
ASSERT_EQ(set->size(), 1u);
ASSERT_TRUE(!set->empty());
// Empties the set and stops a warning about deleting a set with unconsumed
// descriptors
set->CommitAll();
}
TEST(FileDescriptorSet, BasicAddAndClose) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
ASSERT_EQ(set->size(), 0u);
ASSERT_TRUE(set->empty());
ASSERT_TRUE(set->AddAndAutoClose(kFDBase));
ASSERT_EQ(set->size(), 1u);
ASSERT_TRUE(!set->empty());
set->CommitAll();
}
TEST(FileDescriptorSet, MaxSize) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
for (unsigned i = 0;
i < FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE; ++i) {
ASSERT_TRUE(set->Add(kFDBase + 1 + i));
}
ASSERT_TRUE(!set->Add(kFDBase));
set->CommitAll();
}
TEST(FileDescriptorSet, SetDescriptors) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
ASSERT_TRUE(set->empty());
set->SetDescriptors(NULL, 0);
ASSERT_TRUE(set->empty());
static const int fds[] = {kFDBase};
set->SetDescriptors(fds, 1);
ASSERT_TRUE(!set->empty());
ASSERT_EQ(set->size(), 1u);
set->CommitAll();
}
TEST(FileDescriptorSet, GetDescriptors) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
set->GetDescriptors(NULL);
ASSERT_TRUE(set->Add(kFDBase));
int fds[1];
fds[0] = 0;
set->GetDescriptors(fds);
ASSERT_EQ(fds[0], kFDBase);
set->CommitAll();
ASSERT_TRUE(set->empty());
}
TEST(FileDescriptorSet, WalkInOrder) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
ASSERT_TRUE(set->Add(kFDBase));
ASSERT_TRUE(set->Add(kFDBase + 1));
ASSERT_TRUE(set->Add(kFDBase + 2));
ASSERT_EQ(set->GetDescriptorAt(0), kFDBase);
ASSERT_EQ(set->GetDescriptorAt(1), kFDBase + 1);
ASSERT_EQ(set->GetDescriptorAt(2), kFDBase + 2);
set->CommitAll();
}
TEST(FileDescriptorSet, WalkWrongOrder) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
ASSERT_TRUE(set->Add(kFDBase));
ASSERT_TRUE(set->Add(kFDBase + 1));
ASSERT_TRUE(set->Add(kFDBase + 2));
ASSERT_EQ(set->GetDescriptorAt(0), kFDBase);
ASSERT_EQ(set->GetDescriptorAt(2), -1);
set->CommitAll();
}
TEST(FileDescriptorSet, WalkCycle) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
ASSERT_TRUE(set->Add(kFDBase));
ASSERT_TRUE(set->Add(kFDBase + 1));
ASSERT_TRUE(set->Add(kFDBase + 2));
ASSERT_EQ(set->GetDescriptorAt(0), kFDBase);
ASSERT_EQ(set->GetDescriptorAt(1), kFDBase + 1);
ASSERT_EQ(set->GetDescriptorAt(2), kFDBase + 2);
ASSERT_EQ(set->GetDescriptorAt(0), kFDBase);
ASSERT_EQ(set->GetDescriptorAt(1), kFDBase + 1);
ASSERT_EQ(set->GetDescriptorAt(2), kFDBase + 2);
ASSERT_EQ(set->GetDescriptorAt(0), kFDBase);
ASSERT_EQ(set->GetDescriptorAt(1), kFDBase + 1);
ASSERT_EQ(set->GetDescriptorAt(2), kFDBase + 2);
set->CommitAll();
}
TEST(FileDescriptorSet, DontClose) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
const int fd = open("/dev/null", O_RDONLY);
ASSERT_TRUE(set->Add(fd));
set->CommitAll();
const int duped = dup(fd);
ASSERT_GE(duped, 0);
close(duped);
close(fd);
}
TEST(FileDescriptorSet, DoClose) {
scoped_refptr<FileDescriptorSet> set = new FileDescriptorSet;
const int fd = open("/dev/null", O_RDONLY);
ASSERT_TRUE(set->AddAndAutoClose(fd));
set->CommitAll();
const int duped = dup(fd);
ASSERT_EQ(duped, -1);
close(fd);
}
<|endoftext|> |
<commit_before>#pragma once
#define NUM_THREAD_BLOCKS 2500
#define NUM_THREADS 640000
#include <Interface/Manager/ComputeShaderManager.hpp>
#include <Internal/Light/LightInfoImpl.hpp>
#include <DirectXMath.h>
#include <d3d11.h>
#include <vector>
namespace DoremiEngine
{
namespace Graphic
{
struct LightInfo;
struct GraphicModuleContext;
struct Plane
{
DirectX::XMFLOAT3 normal; // plane normal
float distance; // distance to origin
};
struct FrustumInfo
{
Plane plane[4];
};
struct LightIndexListBuffer
{
// std::vector<unsigned int> lightIndexList;
unsigned int LightIndexList[NUM_THREAD_BLOCKS * 200];
};
struct LightGridInfo
{
unsigned int offset;
unsigned int value;
};
struct LightGridBuffer
{
LightGridInfo lightGridInfo[NUM_THREAD_BLOCKS];
};
struct LightCounterBuffer
{
float counter;
};
struct FrustumArray
{
FrustumInfo frustum[NUM_THREAD_BLOCKS];
};
enum BufferType
{
FRUSTUM,
O_LIGHTCOUNTER,
T_LIGHTCOUNTER,
O_LIGHTINDEXLIST,
T_LIGHTINDEXLIST,
O_LIGHTGRID,
T_LIGHTGRID,
NUM_BUFFERS
};
class ComputeShaderManagerImpl : public ComputeShaderManager
{
public:
ComputeShaderManagerImpl(const GraphicModuleContext& p_graphicContext);
~ComputeShaderManagerImpl();
void CreateComputeShaders() override;
// Set UAV for compute shaders. Index specifies which struct to send
void SetUAV(BufferType index) override;
void SetSRV();
ID3D11UnorderedAccessView* GetUAV(int i) override;
void DispatchFrustum() override;
void DispatchCulling() override;
void CopyCullingData() override;
void CopyData(BufferType index);
private:
const GraphicModuleContext& m_graphicContext;
ID3D11DeviceContext* m_deviceContext;
FrustumArray* m_frustumArray;
LightCounterBuffer* m_oLightCounter;
LightCounterBuffer* m_tLightCounter;
LightIndexListBuffer* m_oLightIndexList;
LightIndexListBuffer* m_tLightIndexList;
LightGridBuffer* m_oLightGrid;
LightGridBuffer* m_tLightGrid;
ID3D11UnorderedAccessView* m_uav[NUM_BUFFERS];
ID3D11ShaderResourceView* m_srv[NUM_BUFFERS];
ID3D11Buffer* m_buffer[NUM_BUFFERS];
ID3D11Buffer* m_bufferResult[NUM_BUFFERS];
ComputeShader* m_frustumShader;
ComputeShader* m_cullingShader;
};
}
}
<commit_msg>Fixed forward declaration for incorrect type<commit_after>#pragma once
#define NUM_THREAD_BLOCKS 2500
#define NUM_THREADS 640000
#include <Interface/Manager/ComputeShaderManager.hpp>
#include <Internal/Light/LightInfoImpl.hpp>
#include <DirectXMath.h>
#include <d3d11.h>
#include <vector>
namespace DoremiEngine
{
namespace Graphic
{
class LightInfo;
struct GraphicModuleContext;
struct Plane
{
DirectX::XMFLOAT3 normal; // plane normal
float distance; // distance to origin
};
struct FrustumInfo
{
Plane plane[4];
};
struct LightIndexListBuffer
{
// std::vector<unsigned int> lightIndexList;
unsigned int LightIndexList[NUM_THREAD_BLOCKS * 200];
};
struct LightGridInfo
{
unsigned int offset;
unsigned int value;
};
struct LightGridBuffer
{
LightGridInfo lightGridInfo[NUM_THREAD_BLOCKS];
};
struct LightCounterBuffer
{
float counter;
};
struct FrustumArray
{
FrustumInfo frustum[NUM_THREAD_BLOCKS];
};
enum BufferType
{
FRUSTUM,
O_LIGHTCOUNTER,
T_LIGHTCOUNTER,
O_LIGHTINDEXLIST,
T_LIGHTINDEXLIST,
O_LIGHTGRID,
T_LIGHTGRID,
NUM_BUFFERS
};
class ComputeShaderManagerImpl : public ComputeShaderManager
{
public:
ComputeShaderManagerImpl(const GraphicModuleContext& p_graphicContext);
~ComputeShaderManagerImpl();
void CreateComputeShaders() override;
// Set UAV for compute shaders. Index specifies which struct to send
void SetUAV(BufferType index) override;
void SetSRV();
ID3D11UnorderedAccessView* GetUAV(int i) override;
void DispatchFrustum() override;
void DispatchCulling() override;
void CopyCullingData() override;
void CopyData(BufferType index);
private:
const GraphicModuleContext& m_graphicContext;
ID3D11DeviceContext* m_deviceContext;
FrustumArray* m_frustumArray;
LightCounterBuffer* m_oLightCounter;
LightCounterBuffer* m_tLightCounter;
LightIndexListBuffer* m_oLightIndexList;
LightIndexListBuffer* m_tLightIndexList;
LightGridBuffer* m_oLightGrid;
LightGridBuffer* m_tLightGrid;
ID3D11UnorderedAccessView* m_uav[NUM_BUFFERS];
ID3D11ShaderResourceView* m_srv[NUM_BUFFERS];
ID3D11Buffer* m_buffer[NUM_BUFFERS];
ID3D11Buffer* m_bufferResult[NUM_BUFFERS];
ComputeShader* m_frustumShader;
ComputeShader* m_cullingShader;
};
}
}
<|endoftext|> |
<commit_before>/**
* @file regularized_svd_test.cpp
* @author Siddharth Agrawal
*
* Test the RegularizedSVDFunction class.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/regularized_svd/regularized_svd.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
using namespace mlpack::svd;
BOOST_AUTO_TEST_SUITE(RegularizedSVDTest);
BOOST_AUTO_TEST_CASE(RegularizedSVDFunctionRandomEvaluate)
{
// Define useful constants.
const size_t numUsers = 100;
const size_t numItems = 100;
const size_t numRatings = 1000;
const size_t maxRating = 5;
const size_t rank = 10;
const size_t numTrials = 50;
// Make a random rating dataset.
arma::mat data = arma::randu(3, numRatings);
data.row(0) = floor(data.row(0) * numUsers);
data.row(1) = floor(data.row(1) * numItems);
data.row(2) = floor(data.row(2) * maxRating + 0.5);
// Make a RegularizedSVDFunction with zero regularization.
RegularizedSVDFunction rSVDFunc(data, rank, 0);
for(size_t i = 0; i < numTrials; i++)
{
arma::mat parameters = arma::randu(rank, numUsers + numItems);
// Calculate cost by summing up cost of each example.
double cost = 0;
for(size_t j = 0; j < numRatings; j++)
{
const size_t user = data(0, j);
const size_t item = data(1, j) + numUsers;
const double rating = data(2, j);
double ratingError = rating - arma::dot(parameters.col(user),
parameters.col(item));
double ratingErrorSquared = ratingError * ratingError;
cost += ratingErrorSquared;
}
// Compare calculated cost and value obtained using Evaluate().
BOOST_REQUIRE_CLOSE(cost, rSVDFunc.Evaluate(parameters), 1e-5);
}
}
BOOST_AUTO_TEST_CASE(RegularizedSVDFunctionRegularizationEvaluate)
{
// Define useful constants.
const size_t numUsers = 100;
const size_t numItems = 100;
const size_t numRatings = 1000;
const size_t maxRating = 5;
const size_t rank = 10;
const size_t numTrials = 50;
// Make a random rating dataset.
arma::mat data = arma::randu(3, numRatings);
data.row(0) = floor(data.row(0) * numUsers);
data.row(1) = floor(data.row(1) * numItems);
data.row(2) = floor(data.row(2) * maxRating + 0.5);
// Make three RegularizedSVDFunction objects with different amounts of
// regularization.
RegularizedSVDFunction rSVDFuncNoReg(data, rank, 0);
RegularizedSVDFunction rSVDFuncSmallReg(data, rank, 0.5);
RegularizedSVDFunction rSVDFuncBigReg(data, rank, 20);
for(size_t i = 0; i < numTrials; i++)
{
arma::mat parameters = arma::randu(rank, numUsers + numItems);
// Calculate the regularization contributions of parameters corresponding to
// each rating and sum them up.
double smallRegTerm = 0;
double bigRegTerm = 0;
for(size_t j = 0; j < numRatings; j++)
{
const size_t user = data(0, j);
const size_t item = data(1, j) + numUsers;
double userVecNorm = arma::norm(parameters.col(user), 2);
double itemVecNorm = arma::norm(parameters.col(item), 2);
smallRegTerm += 0.5 * (userVecNorm * userVecNorm +
itemVecNorm * itemVecNorm);
bigRegTerm += 20 * (userVecNorm * userVecNorm +
itemVecNorm * itemVecNorm);
}
// Cost with regularization should be close to the sum of cost without
// regularization and the regularization terms.
BOOST_REQUIRE_CLOSE(rSVDFuncNoReg.Evaluate(parameters) + smallRegTerm,
rSVDFuncSmallReg.Evaluate(parameters), 1e-5);
BOOST_REQUIRE_CLOSE(rSVDFuncNoReg.Evaluate(parameters) + bigRegTerm,
rSVDFuncBigReg.Evaluate(parameters), 1e-5);
}
}
BOOST_AUTO_TEST_CASE(RegularizedSVDFunctionGradient)
{
// Define useful constants.
const size_t numUsers = 50;
const size_t numItems = 50;
const size_t numRatings = 100;
const size_t maxRating = 5;
const size_t rank = 10;
// Make a random rating dataset.
arma::mat data = arma::randu(3, numRatings);
data.row(0) = floor(data.row(0) * numUsers);
data.row(1) = floor(data.row(1) * numItems);
data.row(2) = floor(data.row(2) * maxRating + 0.5);
arma::mat parameters = arma::randu(rank, numUsers + numItems);
// Make two RegularizedSVDFunction objects, one with regularization and one
// without.
RegularizedSVDFunction rSVDFunc1(data, rank, 0);
RegularizedSVDFunction rSVDFunc2(data, rank, 0.5);
// Calculate gradients for both the objects.
arma::mat gradient1, gradient2;
rSVDFunc1.Gradient(parameters, gradient1);
rSVDFunc2.Gradient(parameters, gradient2);
// Perturbation constant.
const double epsilon = 0.0001;
double costPlus1, costMinus1, numGradient1;
double costPlus2, costMinus2, numGradient2;
for(size_t i = 0; i < rank; i++)
{
for(size_t j = 0; j < numUsers + numItems; j++)
{
// Perturb parameter with a positive constant and get costs.
parameters(i, j) += epsilon;
costPlus1 = rSVDFunc1.Evaluate(parameters);
costPlus2 = rSVDFunc2.Evaluate(parameters);
// Perturb parameter with a negative constant and get costs.
parameters(i, j) -= 2 * epsilon;
costMinus1 = rSVDFunc1.Evaluate(parameters);
costMinus2 = rSVDFunc2.Evaluate(parameters);
// Compute numerical gradients using the costs calculated above.
numGradient1 = (costPlus1 - costMinus1) / (2 * epsilon);
numGradient2 = (costPlus2 - costMinus2) / (2 * epsilon);
// Restore the parameter value.
parameters(i, j) += epsilon;
// Compare numerical and backpropagation gradient values.
BOOST_REQUIRE_CLOSE(numGradient1, gradient1(i, j), 1e-2);
BOOST_REQUIRE_CLOSE(numGradient2, gradient2(i, j), 1e-2);
}
}
}
BOOST_AUTO_TEST_CASE(RegularizedSVDFunctionOptimize)
{
// Define useful constants.
const size_t numUsers = 50;
const size_t numItems = 50;
const size_t numRatings = 100;
const size_t iterations = 10;
const size_t rank = 10;
const double alpha = 0.01;
const double lambda = 0.01;
// Initiate random parameters.
arma::mat parameters = arma::randu(rank, numUsers + numItems);
// Make a random rating dataset.
arma::mat data = arma::randu(3, numRatings);
data.row(0) = floor(data.row(0) * numUsers);
data.row(1) = floor(data.row(1) * numItems);
// Make rating entries based on the parameters.
for(size_t i = 0; i < numRatings; i++)
{
data(2, i) = arma::dot(parameters.col(data(0, i)),
parameters.col(numUsers + data(1, i)));
}
// Make the Reg SVD function and the optimizer.
RegularizedSVDFunction rSVDFunc(data, rank, lambda);
mlpack::optimization::SGD<RegularizedSVDFunction> optimizer(rSVDFunc,
alpha, iterations * numRatings);
// Obtain optimized parameters after training.
arma::mat optParameters = arma::randu(rank, numUsers + numItems);
optimizer.Optimize(optParameters);
// Get predicted ratings from optimized parameters.
arma::mat predictedData(1, numRatings);
for(size_t i = 0; i < numRatings; i++)
{
predictedData(0, i) = arma::dot(optParameters.col(data(0, i)),
optParameters.col(numUsers + data(1, i)));
}
// Calculate relative error.
double relativeError = arma::norm(data.row(2) - predictedData, "frob") /
arma::norm(data, "frob");
// Relative error should be small.
BOOST_REQUIRE_SMALL(relativeError, 1e-2);
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>For each random dataset, ensure that the size of the implied user/item matrix is numUsers by numItems by manually setting the last element. Some formatting and const-correctness fixes. Also, increase the number of iterations for the optimization test since it didn't seem to be converging (hopefully the specific number of 10 passes over the data was not chosen for a particular reason).<commit_after>/**
* @file regularized_svd_test.cpp
* @author Siddharth Agrawal
*
* Test the RegularizedSVDFunction class.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/regularized_svd/regularized_svd.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
using namespace mlpack;
using namespace mlpack::svd;
BOOST_AUTO_TEST_SUITE(RegularizedSVDTest);
BOOST_AUTO_TEST_CASE(RegularizedSVDFunctionRandomEvaluate)
{
// Define useful constants.
const size_t numUsers = 100;
const size_t numItems = 100;
const size_t numRatings = 1000;
const size_t maxRating = 5;
const size_t rank = 10;
const size_t numTrials = 50;
// Make a random rating dataset.
arma::mat data = arma::randu(3, numRatings);
data.row(0) = floor(data.row(0) * numUsers);
data.row(1) = floor(data.row(1) * numItems);
data.row(2) = floor(data.row(2) * maxRating + 0.5);
// Manually set last row to maximum user and maximum item.
data(0, numRatings - 1) = numUsers - 1;
data(1, numRatings - 1) = numItems - 1;
// Make a RegularizedSVDFunction with zero regularization.
RegularizedSVDFunction rSVDFunc(data, rank, 0);
for (size_t i = 0; i < numTrials; i++)
{
arma::mat parameters = arma::randu(rank, numUsers + numItems);
// Calculate cost by summing up cost of each example.
double cost = 0;
for (size_t j = 0; j < numRatings; j++)
{
const size_t user = data(0, j);
const size_t item = data(1, j) + numUsers;
const double rating = data(2, j);
const double ratingError = rating - arma::dot(parameters.col(user),
parameters.col(item));
const double ratingErrorSquared = ratingError * ratingError;
cost += ratingErrorSquared;
}
// Compare calculated cost and value obtained using Evaluate().
BOOST_REQUIRE_CLOSE(cost, rSVDFunc.Evaluate(parameters), 1e-5);
}
}
BOOST_AUTO_TEST_CASE(RegularizedSVDFunctionRegularizationEvaluate)
{
// Define useful constants.
const size_t numUsers = 100;
const size_t numItems = 100;
const size_t numRatings = 1000;
const size_t maxRating = 5;
const size_t rank = 10;
const size_t numTrials = 50;
// Make a random rating dataset.
arma::mat data = arma::randu(3, numRatings);
data.row(0) = floor(data.row(0) * numUsers);
data.row(1) = floor(data.row(1) * numItems);
data.row(2) = floor(data.row(2) * maxRating + 0.5);
// Manually set last row to maximum user and maximum item.
data(0, numRatings - 1) = numUsers - 1;
data(1, numRatings - 1) = numItems - 1;
// Make three RegularizedSVDFunction objects with different amounts of
// regularization.
RegularizedSVDFunction rSVDFuncNoReg(data, rank, 0);
RegularizedSVDFunction rSVDFuncSmallReg(data, rank, 0.5);
RegularizedSVDFunction rSVDFuncBigReg(data, rank, 20);
for (size_t i = 0; i < numTrials; i++)
{
arma::mat parameters = arma::randu(rank, numUsers + numItems);
// Calculate the regularization contributions of parameters corresponding to
// each rating and sum them up.
double smallRegTerm = 0;
double bigRegTerm = 0;
for (size_t j = 0; j < numRatings; j++)
{
const size_t user = data(0, j);
const size_t item = data(1, j) + numUsers;
const double userVecNorm = arma::norm(parameters.col(user), 2);
const double itemVecNorm = arma::norm(parameters.col(item), 2);
smallRegTerm += 0.5 * (userVecNorm * userVecNorm +
itemVecNorm * itemVecNorm);
bigRegTerm += 20 * (userVecNorm * userVecNorm +
itemVecNorm * itemVecNorm);
}
// Cost with regularization should be close to the sum of cost without
// regularization and the regularization terms.
BOOST_REQUIRE_CLOSE(rSVDFuncNoReg.Evaluate(parameters) + smallRegTerm,
rSVDFuncSmallReg.Evaluate(parameters), 1e-5);
BOOST_REQUIRE_CLOSE(rSVDFuncNoReg.Evaluate(parameters) + bigRegTerm,
rSVDFuncBigReg.Evaluate(parameters), 1e-5);
}
}
BOOST_AUTO_TEST_CASE(RegularizedSVDFunctionGradient)
{
// Define useful constants.
const size_t numUsers = 50;
const size_t numItems = 50;
const size_t numRatings = 100;
const size_t maxRating = 5;
const size_t rank = 10;
// Make a random rating dataset.
arma::mat data = arma::randu(3, numRatings);
data.row(0) = floor(data.row(0) * numUsers);
data.row(1) = floor(data.row(1) * numItems);
data.row(2) = floor(data.row(2) * maxRating + 0.5);
// Manually set last row to maximum user and maximum item.
data(0, numRatings - 1) = numUsers - 1;
data(1, numRatings - 1) = numItems - 1;
arma::mat parameters = arma::randu(rank, numUsers + numItems);
// Make two RegularizedSVDFunction objects, one with regularization and one
// without.
RegularizedSVDFunction rSVDFunc1(data, rank, 0);
RegularizedSVDFunction rSVDFunc2(data, rank, 0.5);
// Calculate gradients for both the objects.
arma::mat gradient1, gradient2;
rSVDFunc1.Gradient(parameters, gradient1);
rSVDFunc2.Gradient(parameters, gradient2);
// Perturbation constant.
const double epsilon = 0.0001;
double costPlus1, costMinus1, numGradient1;
double costPlus2, costMinus2, numGradient2;
for (size_t i = 0; i < rank; i++)
{
for (size_t j = 0; j < numUsers + numItems; j++)
{
// Perturb parameter with a positive constant and get costs.
parameters(i, j) += epsilon;
costPlus1 = rSVDFunc1.Evaluate(parameters);
costPlus2 = rSVDFunc2.Evaluate(parameters);
// Perturb parameter with a negative constant and get costs.
parameters(i, j) -= 2 * epsilon;
costMinus1 = rSVDFunc1.Evaluate(parameters);
costMinus2 = rSVDFunc2.Evaluate(parameters);
// Compute numerical gradients using the costs calculated above.
numGradient1 = (costPlus1 - costMinus1) / (2 * epsilon);
numGradient2 = (costPlus2 - costMinus2) / (2 * epsilon);
// Restore the parameter value.
parameters(i, j) += epsilon;
// Compare numerical and backpropagation gradient values.
BOOST_REQUIRE_CLOSE(numGradient1, gradient1(i, j), 1e-2);
BOOST_REQUIRE_CLOSE(numGradient2, gradient2(i, j), 1e-2);
}
}
}
BOOST_AUTO_TEST_CASE(RegularizedSVDFunctionOptimize)
{
// Define useful constants.
const size_t numUsers = 50;
const size_t numItems = 50;
const size_t numRatings = 100;
const size_t iterations = 30;
const size_t rank = 10;
const double alpha = 0.01;
const double lambda = 0.01;
// Initiate random parameters.
arma::mat parameters = arma::randu(rank, numUsers + numItems);
// Make a random rating dataset.
arma::mat data = arma::randu(3, numRatings);
data.row(0) = floor(data.row(0) * numUsers);
data.row(1) = floor(data.row(1) * numItems);
// Manually set last row to maximum user and maximum item.
data(0, numRatings - 1) = numUsers - 1;
data(1, numRatings - 1) = numItems - 1;
// Make rating entries based on the parameters.
for (size_t i = 0; i < numRatings; i++)
{
data(2, i) = arma::dot(parameters.col(data(0, i)),
parameters.col(numUsers + data(1, i)));
}
// Make the Reg SVD function and the optimizer.
RegularizedSVDFunction rSVDFunc(data, rank, lambda);
mlpack::optimization::SGD<RegularizedSVDFunction> optimizer(rSVDFunc,
alpha, iterations * numRatings);
// Obtain optimized parameters after training.
arma::mat optParameters = arma::randu(rank, numUsers + numItems);
optimizer.Optimize(optParameters);
// Get predicted ratings from optimized parameters.
arma::mat predictedData(1, numRatings);
for (size_t i = 0; i < numRatings; i++)
{
predictedData(0, i) = arma::dot(optParameters.col(data(0, i)),
optParameters.col(numUsers + data(1, i)));
}
// Calculate relative error.
const double relativeError = arma::norm(data.row(2) - predictedData, "frob") /
arma::norm(data, "frob");
// Relative error should be small.
BOOST_REQUIRE_SMALL(relativeError, 1e-2);
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "catch.hpp"
#include "dll/rbm.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE( "rbm/mnist_1", "rbm::simple" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
REQUIRE(error < 1e-2);
}
TEST_CASE( "rbm/mnist_2", "rbm::momentum" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::momentum
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
REQUIRE(error < 1e-2);
}
TEST_CASE( "rbm/mnist_3", "rbm::pcd_trainer" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::momentum,
dll::trainer<dll::pcd1_trainer_t>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
REQUIRE(error < 1e-1);
}
TEST_CASE( "rbm/mnist_4", "rbm::decay_l1" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::weight_decay<dll::decay_type::L1>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
REQUIRE(error < 1e-2);
}
TEST_CASE( "rbm/mnist_5", "rbm::decay_l2" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::weight_decay<dll::decay_type::L2>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
REQUIRE(error < 1e-2);
}
TEST_CASE( "rbm/mnist_6", "rbm::sparsity" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::sparsity
>::rbm_t rbm;
//0.01 (default) is way too low for 100 hidden units
rbm.sparsity_target = 0.1;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
REQUIRE(error < 1e-2);
}
TEST_CASE( "rbm/mnist_7", "rbm::gaussian" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::visible<dll::unit_type::GAUSSIAN>
>::rbm_t rbm;
rbm.learning_rate *= 10;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::normalize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 200);
REQUIRE(error < 1e-2);
}
TEST_CASE( "rbm/mnist_8", "rbm::softmax" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::hidden<dll::unit_type::SOFTMAX>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
//This test is kind of fake since softmax unit are not really made for
//reconstruction. It is here to ensure that softmax units are working.
REQUIRE(error < 1e-2);
}
TEST_CASE( "rbm/mnist_9", "rbm::nrlu" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::hidden<dll::unit_type::RELU>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 200);
REQUIRE(error < 1e-1);
}
TEST_CASE( "rbm/mnist_10", "rbm::nrlu1" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::hidden<dll::unit_type::RELU1>
>::rbm_t rbm;
rbm.learning_rate *= 2.0;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 200);
REQUIRE(error < 1e-1);
}
TEST_CASE( "rbm/mnist_11", "rbm::nrlu6" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::hidden<dll::unit_type::RELU6>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 200);
REQUIRE(error < 1e-1);
}
TEST_CASE( "rbm/mnist_12", "rbm::init_weights" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::init_weights
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 200);
REQUIRE(error < 1e-3);
}
TEST_CASE( "rbm/mnist_13", "rbm::exp" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::hidden<dll::unit_type::EXP>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
//This test is kind of fake since exp unit are not really made for
//reconstruction. It is here to ensure that exp units are working.
//exponential units are not even made for training
REQUIRE(std::isnan(error));
}<commit_msg>Clean<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "catch.hpp"
#include "dll/rbm.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE( "rbm/mnist_1", "rbm::simple" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
REQUIRE(error < 1e-2);
}
TEST_CASE( "rbm/mnist_2", "rbm::momentum" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::momentum
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
REQUIRE(error < 1e-2);
}
TEST_CASE( "rbm/mnist_3", "rbm::pcd_trainer" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::momentum,
dll::trainer<dll::pcd1_trainer_t>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
REQUIRE(error < 1e-1);
}
TEST_CASE( "rbm/mnist_4", "rbm::decay_l1" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::weight_decay<dll::decay_type::L1>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
REQUIRE(error < 1e-2);
}
TEST_CASE( "rbm/mnist_5", "rbm::decay_l2" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::weight_decay<dll::decay_type::L2>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
REQUIRE(error < 1e-2);
}
TEST_CASE( "rbm/mnist_6", "rbm::sparsity" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::sparsity
>::rbm_t rbm;
//0.01 (default) is way too low for 100 hidden units
rbm.sparsity_target = 0.1;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
REQUIRE(error < 1e-2);
}
TEST_CASE( "rbm/mnist_7", "rbm::gaussian" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::visible<dll::unit_type::GAUSSIAN>
>::rbm_t rbm;
rbm.learning_rate *= 10;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::normalize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 200);
REQUIRE(error < 1e-2);
}
TEST_CASE( "rbm/mnist_8", "rbm::softmax" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::hidden<dll::unit_type::SOFTMAX>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
REQUIRE(error < 1e-2);
}
TEST_CASE( "rbm/mnist_9", "rbm::relu" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::hidden<dll::unit_type::RELU>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 200);
REQUIRE(error < 1e-1);
}
TEST_CASE( "rbm/mnist_10", "rbm::relu1" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::hidden<dll::unit_type::RELU1>
>::rbm_t rbm;
rbm.learning_rate *= 2.0;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 200);
REQUIRE(error < 1e-1);
}
TEST_CASE( "rbm/mnist_11", "rbm::relu6" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::hidden<dll::unit_type::RELU6>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 200);
REQUIRE(error < 1e-1);
}
TEST_CASE( "rbm/mnist_12", "rbm::init_weights" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::init_weights
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 200);
REQUIRE(error < 1e-3);
}
TEST_CASE( "rbm/mnist_13", "rbm::exp" ) {
dll::rbm_desc<
28 * 28, 100,
dll::batch_size<25>,
dll::hidden<dll::unit_type::EXP>
>::rbm_t rbm;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(100);
mnist::binarize_dataset(dataset);
auto error = rbm.train(dataset.training_images, 100);
//This test is kind of fake since exp unit are not really made for
//reconstruction. It is here to ensure that exp units are working.
//exponential units are not even made for training
REQUIRE(std::isnan(error));
}<|endoftext|> |
<commit_before>/*
* mainGame.cpp
*
* Created on: Nov 26, 2017
* Author: lowji
*/
//created this source file to make the compiler work properly
#include <iostream>
#include <string>
#include "Player.h"
#include "ConsoleUI.h"
//method to determine if a string is an integer
bool isInt(string input){
//Reference: https://stackoverflow.com/questions/20287186/how-to-check-if-the-input-is-a-valid-integer-without-any-other-chars
int x; //temporary int variable for checking input validity
char c; //temporary char variable for checking input validity
istringstream s(input);
if (!(s >> x)) {
return false;
}
if (s >> c) {
return false;
}
return true;
}
int main(){
//set up user interface
ConsoleUI*ui=new ConsoleUI();
ui->welcome();
string inputTemp;
inputTemp=ui->input("Input your name: ");
string name = inputTemp;
Player* human = new Player(inputTemp);
Player* AI = new Player("AI");
//Preflop
inputTemp=ui->input("How much do you want the blind to be? ");
human->setTotalChips(stoi(inputTemp));
AI->setTotalChips(stoi(inputTemp));
ui->output("Your name is "+human->getName());
ui->output("Your opponent name is "+AI->getName());
ui->output("Your blind is "+human->getTotalChips());
ui->output("AI has blind of "+AI->getTotalChips());
//shuffling
//draw cards
//print user's hand
//print table: your pocket, small blind, big blind, pot(needs to make)
//prompt user decision: raise, bet, check, fold
//Postflop: prompt user, update pot and each player stack size(money), user's decision, draw 3 cards into communitycards, print pot and stacksize, print hands, print communitycards
//Turn: prompt user, update pot and each player stack size(money), user's decision, draw 1 cards into communitycards, print pot and stacksize, print hands, print communitycards
//River: repeat Turn, and go back to preflop...
}
<commit_msg>mainGame changed<commit_after>/*
* mainGame.cpp
*
* Created on: Nov 26, 2017
* Author: lowji
*/
//created this source file to make the compiler work properly
#include <sstream>
#include <iostream>
#include <string>
#include "Player.h"
#include "ConsoleUI.h"
//method to determine if a string is an integer
bool isInt(string input){
//Reference: https://stackoverflow.com/questions/20287186/how-to-check-if-the-input-is-a-valid-integer-without-any-other-chars
int x; //temporary int variable for checking input validity
char c; //temporary char variable for checking input validity
istringstream s(input);
if (!(s >> x)) {
return false;
}
if (s >> c) {
return false;
}
return true;
}
int main(){
//set up user interface
ConsoleUI*ui=new ConsoleUI();
ui->welcome();
string inputTemp;
inputTemp=ui->input("Input your name: ");
string name = inputTemp;
Player* human = new Player(inputTemp);
Player* AI = new Player("AI");
//Preflop
inputTemp=ui->input("How much do you want the blind to be? ");
human->setTotalChips(stoi(inputTemp));
AI->setTotalChips(stoi(inputTemp));
ui->output("Your name is "+human->getName());
ui->output("Your opponent name is "+AI->getName());
ui->output("Your blind is "+human->getTotalChips());
ui->output("AI has blind of "+AI->getTotalChips());
//shuffling(automatic shuffled)
Deck* deck = new Deck();
//draw cards
human->addOne(deck->draw());
human->addTwo(deck->draw());
//print user's hand
(human->getHandOne()).printCard();
(human->getHandTwo()).printCard();
//print table: your pocket, small blind, big blind, pot(needs to make)
//prompt user decision: raise, bet, check, fold
//Postflop: prompt user, update pot and each player stack size(money), user's decision, draw 3 cards into communitycards, print pot and stacksize, print hands, print communitycards
//Turn: prompt user, update pot and each player stack size(money), user's decision, draw 1 cards into communitycards, print pot and stacksize, print hands, print communitycards
//River: repeat Turn, and go back to preflop...
}
<|endoftext|> |
<commit_before>/* vision/vision_processing.cpp
*
* Copyright (c) 2011, 2012 Chantilly Robotics <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Entry points for vision processing: distance and angle from image
*/
/*
* Calculated angles are relative to perpendicular.
*/
#include <vector>
#include <cmath>
#include <Vision/ColorImage.h>
#include <Vision/BinaryImage.h>
#include <Vision2009/VisionAPI.h>
#include <nivision.h>
#include "vision_processing.h"
#include "../ports.h"
#include "../ranges.h"
#include "../trajectory.h"
#include "../visionalg.h"
using namespace vision_processing;
typedef struct particle_rect_struct {
int top; //Location of the top edge of the rectangle.
int left; //Location of the left edge of the rectangle.
int height; //Height of the rectangle.
int width; //Width of the rectangle.
} particle_rect;
//constants
HSLImage old_image;
BinaryImage* image_mask;
vector<ParticleAnalysisReport>* targets;
BinaryImage* get_image_mask(ColorImage*);
vector<ParticleAnalysisReport>* get_image_targets(BinaryImage*);
double inline degrees_from_ratio(double); // ratio: width/height
double inline radians_from_ratio(double);
double inline distance_from_height(int);
double inline deviation_from_angle(double);
ColorImage* vision_processing::get_image() {
camera().GetImage(&old_image);
return &old_image;
}
ColorImage* vision_processing::get_old_image() {
return &old_image;
}
unsigned int vision_processing::determine_aim_target() {
// TODO make it do stuff
return 0;
}
vector<double> vision_processing::get_distance() {
vector<double> distance;
for(unsigned int i = 0; i < targets->size(); i++) {
ParticleAnalysisReport target = targets->at(i);
Rect target_rect=target.boundingRect;
int height = target_rect.height;
int width = target_rect.width;
double ratio = 1.0 * width/height;
double image_degrees = degrees_from_ratio(ratio);
double ground_distance = distance_from_height(height) + deviation_from_angle(image_degrees);
distance.push_back(ground_distance);
}
return distance;
}
vector<double> vision_processing::get_degrees() {
vector<double> degrees;
for(unsigned int i = 0; i < targets->size(); i++) {
ParticleAnalysisReport target = targets->at(i);
Rect target_rect = target.boundingRect;
int height = target_rect.height;
int width = target_rect.width;
double ratio = 1.0 * width/height;
double image_degrees = degrees_from_ratio(ratio);
degrees.push_back(image_degrees);
}
return degrees;
}
vector<double> vision_processing::get_radians() {
vector<double> degrees = get_degrees();
vector<double> radians;
for(unsigned int i = 0; i< degrees.size(); i++) {
radians.push_back(deg2rad(degrees[i]));
}
return radians;
}
BinaryImage* get_image_mask(ColorImage* image) {
if(image == NULL) {
return image_mask;
}
if (COLOR_MODE == HSV) {
image_mask = image->ThresholdHSV(HSV_HMIN, HSV_HMAX, HSV_SMIN, HSV_SMAX, HSV_VMIN, HSV_VMAX);
}
else if(COLOR_MODE == HSI) {
image_mask = image->ThresholdHSI(HSI_HMIN, HSI_HMAX, HSI_SMIN, HSI_SMAX, HSI_IMIN, HSI_IMAX);
}
else { // HSL is implied (not assumed)
image_mask = image->ThresholdHSL(HSL_HMIN, HSL_HMAX, HSL_SMIN, HSL_SMAX, HSL_LMIN, HSL_LMAX);
}
return image_mask;
}
vector<ParticleAnalysisReport>* get_image_targets(BinaryImage* image) {
vector<ParticleAnalysisReport>* targets = new vector<ParticleAnalysisReport>();
if(image == NULL) {
return targets;
}
vector<ParticleAnalysisReport>* particles=image->GetOrderedParticleAnalysisReports();
for(unsigned int i = 0; i < particles->size(); i++) {
ParticleAnalysisReport particle = particles->at(i);
double particle_area = particle.particleArea;
if(particle_area > PARTICLE_AREA_MIN && particle_area <= PARTICLE_AREA_MAX) {
if(targets->size() >= 4) {
// TODO change min and max
// call function again
// if depth is more than 2
// explode
break;
}
targets->push_back(particle);
}
}
delete particles;
return targets;
}
void vision_processing::update() {
if(!camera().IsFreshImage()) {
return;
}
delete image_mask;
image_mask = get_image_mask(&old_image);
delete targets;
targets = get_image_targets(image_mask);
}
//TODO: Someone else (Jeff?) sanity check this and make sure it's right. I tried to copy your logic
//from above.
double get_distance_from_report(const ParticleAnalysisReport& report) {
double ratio = ((double)(report.boundingRect.width))/(report.boundingRect.height);
double degrees = degrees_from_ratio(ratio);
double dist = distance_from_height(report.boundingRect.height) + deviation_from_angle(degrees);
return dist;
}
double get_height_offset_from_report(const ParticleAnalysisReport& r, double dist) {
//meant to be called once you have dist from get_distance_from_report
//this way we don't need to have target detection
double theta = angle_offset(RESOLUTION().Y()/2 - r.center_mass_y, RESOLUTION().Y(), FOV().Y());
return std::tan(theta)*dist;
}
double inline degrees_from_ratio(double ratio) {
//a quadratic regression. Fits rather well.
//aspect ratio is constant 4:3, so no need to adjust ratio
return (-94.637 * ratio * ratio) + (119.86 * ratio) + 9.7745;
}
double inline radians_from_ratio(double ratio) {
return deg2rad(degrees_from_ratio(ratio));
}
double inline distance_from_height(int height) {
//magic numbers are gross but they do the job...
//a tad worried about the -0.8. Not sure what this will do at close distances
#ifdef RESOLUTION_640_480
//no need to do anything
#elif defined RESOLUTION_320_240
height *= 2; //adjust for resolution
#elif defined RESOLUTION_160_120
height *= 4;
#endif
return ((1277.686246075*(1/height)) - 0.8265433113);
}
double inline deviation_from_angle(double angle) {
return ((0.0188*angle) + 0.017);
}
<commit_msg>Small update to vision processing (streamline)<commit_after>/* vision/vision_processing.cpp
*
* Copyright (c) 2011, 2012 Chantilly Robotics <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Entry points for vision processing: distance and angle from image
*/
/*
* Calculated angles are relative to perpendicular.
*/
#include <vector>
#include <cmath>
#include <Vision/ColorImage.h>
#include <Vision/BinaryImage.h>
#include <Vision2009/VisionAPI.h>
#include <nivision.h>
#include "vision_processing.h"
#include "../ports.h"
#include "../ranges.h"
#include "../trajectory.h"
#include "../visionalg.h"
using namespace vision_processing;
typedef struct particle_rect_struct {
int top; //Location of the top edge of the rectangle.
int left; //Location of the left edge of the rectangle.
int height; //Height of the rectangle.
int width; //Width of the rectangle.
} particle_rect;
//constants
HSLImage old_image;
BinaryImage* image_mask;
vector<ParticleAnalysisReport>* targets;
BinaryImage* get_image_mask(ColorImage*);
vector<ParticleAnalysisReport>* get_image_targets(BinaryImage*);
double inline degrees_from_ratio(double); // ratio: width/height
double inline radians_from_ratio(double);
double inline distance_from_height(int);
double inline deviation_from_angle(double);
ColorImage* vision_processing::get_image() {
camera().GetImage(&old_image);
return &old_image;
}
ColorImage* vision_processing::get_old_image() {
return &old_image;
}
unsigned int vision_processing::determine_aim_target() {
// TODO make it do stuff
return 0;
}
vector<double> vision_processing::get_distance() {
vector<double> distance;
for (unsigned int i = 0; i < targets->size(); i++) {
distance.push_back(get_distance_from_report(targets->at(i)));
}
return distance;
}
vector<double> vision_processing::get_degrees() {
vector<double> degrees;
for (unsigned int i = 0; i < targets->size(); i++) {
degrees.push_back(get_degrees_from_report(targets->at(i)));
}
return degrees;
}
vector<double> vision_processing::get_radians() {
vector<double> degrees = get_degrees();
vector<double> radians;
for(unsigned int i = 0; i< degrees.size(); i++) {
radians.push_back(deg2rad(degrees[i]));
}
return radians;
}
BinaryImage* get_image_mask(ColorImage* image) {
if(image == NULL) {
return image_mask;
}
if (COLOR_MODE == HSV) {
image_mask = image->ThresholdHSV(HSV_HMIN, HSV_HMAX, HSV_SMIN, HSV_SMAX, HSV_VMIN, HSV_VMAX);
}
else if(COLOR_MODE == HSI) {
image_mask = image->ThresholdHSI(HSI_HMIN, HSI_HMAX, HSI_SMIN, HSI_SMAX, HSI_IMIN, HSI_IMAX);
}
else { // HSL is implied (not assumed)
image_mask = image->ThresholdHSL(HSL_HMIN, HSL_HMAX, HSL_SMIN, HSL_SMAX, HSL_LMIN, HSL_LMAX);
}
return image_mask;
}
vector<ParticleAnalysisReport>* get_image_targets(BinaryImage* image) {
vector<ParticleAnalysisReport>* targets = new vector<ParticleAnalysisReport>();
if(image == NULL) {
return targets;
}
vector<ParticleAnalysisReport>* particles=image->GetOrderedParticleAnalysisReports();
for(unsigned int i = 0; i < particles->size(); i++) {
ParticleAnalysisReport particle = particles->at(i);
double particle_area = particle.particleArea;
if(particle_area > PARTICLE_AREA_MIN && particle_area <= PARTICLE_AREA_MAX) {
if(targets->size() >= 4) {
// TODO change min and max
// call function again
// if depth is more than 2
// explode
break;
}
targets->push_back(particle);
}
}
delete particles;
return targets;
}
void vision_processing::update() {
if(!camera().IsFreshImage()) {
return;
}
delete image_mask;
image_mask = get_image_mask(&old_image);
delete targets;
targets = get_image_targets(image_mask);
}
//TODO: Someone else (Jeff?) sanity check this and make sure it's right. I tried to copy your logic
//from above.
double get_distance_from_report(const ParticleAnalysisReport& report) {
double ratio = ((double)(report.boundingRect.width))/(report.boundingRect.height);
double degrees = degrees_from_ratio(ratio);
double dist = distance_from_height(report.boundingRect.height) + deviation_from_angle(degrees);
return dist;
}
double get_degrees_from_report(const ParticleAnalysisReport& r) {
double ratio = ((double)(r.boundingRect.width)/(r.boundingRect.height);
return degrees_from_ratio(ratio);
}
double get_height_offset_from_report(const ParticleAnalysisReport& r, double dist) {
//meant to be called once you have dist from get_distance_from_report
//this way we don't need to have target detection
double theta = angle_offset(RESOLUTION().Y()/2 - r.center_mass_y, RESOLUTION().Y(), FOV().Y());
return std::tan(theta)*dist;
}
double inline degrees_from_ratio(double ratio) {
//a quadratic regression. Fits rather well.
//aspect ratio is constant 4:3, so no need to adjust ratio
return (-94.637 * ratio * ratio) + (119.86 * ratio) + 9.7745;
}
double inline radians_from_ratio(double ratio) {
return deg2rad(degrees_from_ratio(ratio));
}
double inline distance_from_height(int height) {
//magic numbers are gross but they do the job...
//a tad worried about the -0.8. Not sure what this will do at close distances
#ifdef RESOLUTION_640_480
//no need to do anything
#elif defined RESOLUTION_320_240
height *= 2; //adjust for resolution
#elif defined RESOLUTION_160_120
height *= 4;
#endif
return ((1277.686246075*(1/height)) - 0.8265433113);
}
double inline deviation_from_angle(double angle) {
return ((0.0188*angle) + 0.017);
}
<|endoftext|> |
<commit_before>#include "Effekseer.Parameters.h"
#include "../Effekseer.EffectImplemented.h"
#include "../Effekseer.Instance.h"
#include "../Effekseer.InstanceGlobal.h"
#include "../Effekseer.InternalScript.h"
#include "DynamicParameter.h"
namespace Effekseer
{
void LoadGradient(Gradient& gradient, uint8_t*& pos, int32_t version)
{
BinaryReader<true> reader(pos, std::numeric_limits<int>::max());
reader.Read(gradient.ColorCount);
for (int i = 0; i < gradient.ColorCount; i++)
{
reader.Read(gradient.Colors[i]);
}
reader.Read(gradient.AlphaCount);
for (int i = 0; i < gradient.AlphaCount; i++)
{
reader.Read(gradient.Alphas[i]);
}
pos += reader.GetOffset();
}
void NodeRendererTextureUVTypeParameter::Load(uint8_t*& pos, int32_t version)
{
memcpy(&Type, pos, sizeof(int));
pos += sizeof(int);
if (Type == TextureUVType::Strech)
{
}
else if (Type == TextureUVType::Tile)
{
memcpy(&TileEdgeHead, pos, sizeof(TileEdgeHead));
pos += sizeof(TileEdgeHead);
memcpy(&TileEdgeTail, pos, sizeof(TileEdgeTail));
pos += sizeof(TileEdgeTail);
memcpy(&TileLoopAreaBegin, pos, sizeof(TileLoopAreaBegin));
pos += sizeof(TileLoopAreaBegin);
memcpy(&TileLoopAreaEnd, pos, sizeof(TileLoopAreaEnd));
pos += sizeof(TileLoopAreaEnd);
}
}
template <typename T, typename U>
void ApplyEq_(T& dstParam, const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, int dpInd, const U& originalParam)
{
static_assert(sizeof(T) == sizeof(U), "size is not mismatched");
const int count = sizeof(T) / 4;
EFK_ASSERT(e != nullptr);
EFK_ASSERT(0 <= dpInd && dpInd < static_cast<int>(instg->dynamicEqResults.size()));
auto dst = reinterpret_cast<float*>(&(dstParam));
auto src = reinterpret_cast<const float*>(&(originalParam));
auto eqresult = instg->dynamicEqResults[dpInd];
std::array<float, 1> globals;
globals[0] = instg->GetUpdatedFrame() / 60.0f;
std::array<float, 5> locals;
for (int i = 0; i < count; i++)
{
locals[i] = src[i];
}
for (int i = count; i < 4; i++)
{
locals[i] = 0.0f;
}
locals[4] = parrentInstance != nullptr ? parrentInstance->m_LivingTime / 60.0f : 0.0f;
auto e_ = static_cast<const EffectImplemented*>(e);
auto& dp = e_->GetDynamicEquation()[dpInd];
if (dp.GetRunningPhase() == InternalScript::RunningPhaseType::Local)
{
eqresult = dp.Execute(instg->GetDynamicInputParameters(), globals, locals, RandCallback::Rand, RandCallback::RandSeed, rand);
}
for (int i = 0; i < count; i++)
{
dst[i] = eqresult[i];
}
}
void ApplyEq(float& dstParam, const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, int dpInd, const float& originalParam)
{
ApplyEq_(dstParam, e, instg, parrentInstance, rand, dpInd, originalParam);
}
template <typename S>
SIMD::Vec3f ApplyEq_(
const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const int& dpInd, const SIMD::Vec3f& originalParam, const S& scale, const S& scaleInv)
{
SIMD::Vec3f param = originalParam;
if (dpInd >= 0)
{
param *= SIMD::Vec3f(scaleInv[0], scaleInv[1], scaleInv[2]);
ApplyEq_(param, e, instg, parrentInstance, rand, dpInd, param);
param *= SIMD::Vec3f(scale[0], scale[1], scale[2]);
}
return param;
}
SIMD::Vec3f ApplyEq(
const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const int& dpInd, const SIMD::Vec3f& originalParam, const std::array<float, 3>& scale, const std::array<float, 3>& scaleInv)
{
return ApplyEq_(e, instg, parrentInstance, rand, dpInd, originalParam, scale, scaleInv);
}
random_float ApplyEq(const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const RefMinMax& dpInd, random_float originalParam)
{
if (dpInd.Max >= 0)
{
ApplyEq_(originalParam.max, e, instg, parrentInstance, rand, dpInd.Max, originalParam.max);
}
if (dpInd.Min >= 0)
{
ApplyEq_(originalParam.min, e, instg, parrentInstance, rand, dpInd.Min, originalParam.min);
}
return originalParam;
}
template <typename S>
random_vector3d ApplyEq_(const Effect* e,
const InstanceGlobal* instg,
const Instance* parrentInstance,
IRandObject* rand,
const RefMinMax& dpInd,
random_vector3d originalParam,
const S& scale,
const S& scaleInv)
{
if (dpInd.Max >= 0)
{
originalParam.max.x *= scaleInv[0];
originalParam.max.y *= scaleInv[1];
originalParam.max.z *= scaleInv[2];
ApplyEq_(originalParam.max, e, instg, parrentInstance, rand, dpInd.Max, originalParam.max);
originalParam.max.x *= scale[0];
originalParam.max.y *= scale[1];
originalParam.max.z *= scale[2];
}
if (dpInd.Min >= 0)
{
originalParam.min.x *= scaleInv[0];
originalParam.min.y *= scaleInv[1];
originalParam.min.z *= scaleInv[2];
ApplyEq_(originalParam.min, e, instg, parrentInstance, rand, dpInd.Min, originalParam.min);
originalParam.min.x *= scale[0];
originalParam.min.y *= scale[1];
originalParam.min.z *= scale[2];
}
return originalParam;
}
random_vector3d ApplyEq(const Effect* e,
const InstanceGlobal* instg,
const Instance* parrentInstance,
IRandObject* rand,
const RefMinMax& dpInd,
random_vector3d originalParam,
const std::array<float, 3>& scale,
const std::array<float, 3>& scaleInv)
{
return ApplyEq_(e,
instg,
parrentInstance,
rand,
dpInd,
originalParam,
scale,
scaleInv);
}
random_int ApplyEq(const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const RefMinMax& dpInd, random_int originalParam)
{
if (dpInd.Max >= 0)
{
float value = static_cast<float>(originalParam.max);
ApplyEq_(value, e, instg, parrentInstance, rand, dpInd.Max, value);
originalParam.max = static_cast<int32_t>(value);
}
if (dpInd.Min >= 0)
{
float value = static_cast<float>(originalParam.min);
ApplyEq_(value, e, instg, parrentInstance, rand, dpInd.Min, value);
originalParam.min = static_cast<int32_t>(value);
}
return originalParam;
}
std::array<float, 4> Gradient::GetColor(float x) const
{
const auto c = GetColorAndIntensity(x);
return std::array<float, 4>{c[0] * c[3], c[1] * c[3], c[2] * c[3], GetAlpha(x)};
}
std::array<float, 4> Gradient::GetColorAndIntensity(float x) const
{
if (ColorCount == 0)
{
return std::array<float, 4>{1.0f, 1.0f, 1.0f, 1.0f};
}
if (x < Colors[0].Position)
{
const auto c = Colors[0].Color;
return {c[0], c[1], c[2], Colors[0].Intensity};
}
if (Colors[ColorCount - 1].Position <= x)
{
const auto c = Colors[ColorCount - 1].Color;
return {c[0], c[1], c[2], Colors[ColorCount - 1].Intensity};
}
auto key = ColorKey();
key.Position = x;
auto it = std::lower_bound(Colors.begin(), Colors.begin() + ColorCount, key, [](const ColorKey& a, const ColorKey& b)
{ return a.Position < b.Position; });
auto ind = static_cast<int32_t>(std::distance(Colors.begin(), it));
{
if (Colors[ind].Position != x)
{
ind--;
}
if (Colors[ind].Position <= x && x <= Colors[ind + 1].Position)
{
const auto area = Colors[ind + 1].Position - Colors[ind].Position;
if (area == 0)
{
return std::array<float, 4>{Colors[ind].Color[0], Colors[ind].Color[1], Colors[ind].Color[2], Colors[ind].Intensity};
}
const auto alpha = (x - Colors[ind].Position) / area;
const auto r = Colors[ind + 1].Color[0] * alpha + Colors[ind].Color[0] * (1.0f - alpha);
const auto g = Colors[ind + 1].Color[1] * alpha + Colors[ind].Color[1] * (1.0f - alpha);
const auto b = Colors[ind + 1].Color[2] * alpha + Colors[ind].Color[2] * (1.0f - alpha);
const auto intensity = Colors[ind + 1].Intensity * alpha + Colors[ind].Intensity * (1.0f - alpha);
return std::array<float, 4>{r, g, b, intensity};
}
else
{
assert(0);
}
}
return std::array<float, 4>{1.0f, 1.0f, 1.0f, 1.0f};
}
float Gradient::GetAlpha(float x) const
{
if (AlphaCount == 0)
{
return 1.0f;
}
if (x < Alphas[0].Position)
{
return Alphas[0].Alpha;
}
if (Alphas[AlphaCount - 1].Position <= x)
{
return Alphas[AlphaCount - 1].Alpha;
}
auto key = AlphaKey();
key.Position = x;
auto it = std::lower_bound(Alphas.begin(), Alphas.begin() + AlphaCount, key, [](const AlphaKey& a, const AlphaKey& b)
{ return a.Position < b.Position; });
auto ind = static_cast<int32_t>(std::distance(Alphas.begin(), it));
{
if (Alphas[ind].Position != x)
{
ind--;
}
if (Alphas[ind].Position <= x && x <= Alphas[ind + 1].Position)
{
const auto area = Alphas[ind + 1].Position - Alphas[ind].Position;
if (area == 0)
{
return Alphas[ind].Alpha;
}
const auto alpha = (x - Alphas[ind].Position) / area;
return Alphas[ind + 1].Alpha * alpha + Alphas[ind].Alpha * (1.0f - alpha);
}
else
{
assert(0);
}
}
return 1.0f;
}
} // namespace Effekseer<commit_msg>Fix a compile error in linux<commit_after>#include <algorithm>
#include "Effekseer.Parameters.h"
#include "../Effekseer.EffectImplemented.h"
#include "../Effekseer.Instance.h"
#include "../Effekseer.InstanceGlobal.h"
#include "../Effekseer.InternalScript.h"
#include "DynamicParameter.h"
namespace Effekseer
{
void LoadGradient(Gradient& gradient, uint8_t*& pos, int32_t version)
{
BinaryReader<true> reader(pos, std::numeric_limits<int>::max());
reader.Read(gradient.ColorCount);
for (int i = 0; i < gradient.ColorCount; i++)
{
reader.Read(gradient.Colors[i]);
}
reader.Read(gradient.AlphaCount);
for (int i = 0; i < gradient.AlphaCount; i++)
{
reader.Read(gradient.Alphas[i]);
}
pos += reader.GetOffset();
}
void NodeRendererTextureUVTypeParameter::Load(uint8_t*& pos, int32_t version)
{
memcpy(&Type, pos, sizeof(int));
pos += sizeof(int);
if (Type == TextureUVType::Strech)
{
}
else if (Type == TextureUVType::Tile)
{
memcpy(&TileEdgeHead, pos, sizeof(TileEdgeHead));
pos += sizeof(TileEdgeHead);
memcpy(&TileEdgeTail, pos, sizeof(TileEdgeTail));
pos += sizeof(TileEdgeTail);
memcpy(&TileLoopAreaBegin, pos, sizeof(TileLoopAreaBegin));
pos += sizeof(TileLoopAreaBegin);
memcpy(&TileLoopAreaEnd, pos, sizeof(TileLoopAreaEnd));
pos += sizeof(TileLoopAreaEnd);
}
}
template <typename T, typename U>
void ApplyEq_(T& dstParam, const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, int dpInd, const U& originalParam)
{
static_assert(sizeof(T) == sizeof(U), "size is not mismatched");
const int count = sizeof(T) / 4;
EFK_ASSERT(e != nullptr);
EFK_ASSERT(0 <= dpInd && dpInd < static_cast<int>(instg->dynamicEqResults.size()));
auto dst = reinterpret_cast<float*>(&(dstParam));
auto src = reinterpret_cast<const float*>(&(originalParam));
auto eqresult = instg->dynamicEqResults[dpInd];
std::array<float, 1> globals;
globals[0] = instg->GetUpdatedFrame() / 60.0f;
std::array<float, 5> locals;
for (int i = 0; i < count; i++)
{
locals[i] = src[i];
}
for (int i = count; i < 4; i++)
{
locals[i] = 0.0f;
}
locals[4] = parrentInstance != nullptr ? parrentInstance->m_LivingTime / 60.0f : 0.0f;
auto e_ = static_cast<const EffectImplemented*>(e);
auto& dp = e_->GetDynamicEquation()[dpInd];
if (dp.GetRunningPhase() == InternalScript::RunningPhaseType::Local)
{
eqresult = dp.Execute(instg->GetDynamicInputParameters(), globals, locals, RandCallback::Rand, RandCallback::RandSeed, rand);
}
for (int i = 0; i < count; i++)
{
dst[i] = eqresult[i];
}
}
void ApplyEq(float& dstParam, const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, int dpInd, const float& originalParam)
{
ApplyEq_(dstParam, e, instg, parrentInstance, rand, dpInd, originalParam);
}
template <typename S>
SIMD::Vec3f ApplyEq_(
const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const int& dpInd, const SIMD::Vec3f& originalParam, const S& scale, const S& scaleInv)
{
SIMD::Vec3f param = originalParam;
if (dpInd >= 0)
{
param *= SIMD::Vec3f(scaleInv[0], scaleInv[1], scaleInv[2]);
ApplyEq_(param, e, instg, parrentInstance, rand, dpInd, param);
param *= SIMD::Vec3f(scale[0], scale[1], scale[2]);
}
return param;
}
SIMD::Vec3f ApplyEq(
const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const int& dpInd, const SIMD::Vec3f& originalParam, const std::array<float, 3>& scale, const std::array<float, 3>& scaleInv)
{
return ApplyEq_(e, instg, parrentInstance, rand, dpInd, originalParam, scale, scaleInv);
}
random_float ApplyEq(const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const RefMinMax& dpInd, random_float originalParam)
{
if (dpInd.Max >= 0)
{
ApplyEq_(originalParam.max, e, instg, parrentInstance, rand, dpInd.Max, originalParam.max);
}
if (dpInd.Min >= 0)
{
ApplyEq_(originalParam.min, e, instg, parrentInstance, rand, dpInd.Min, originalParam.min);
}
return originalParam;
}
template <typename S>
random_vector3d ApplyEq_(const Effect* e,
const InstanceGlobal* instg,
const Instance* parrentInstance,
IRandObject* rand,
const RefMinMax& dpInd,
random_vector3d originalParam,
const S& scale,
const S& scaleInv)
{
if (dpInd.Max >= 0)
{
originalParam.max.x *= scaleInv[0];
originalParam.max.y *= scaleInv[1];
originalParam.max.z *= scaleInv[2];
ApplyEq_(originalParam.max, e, instg, parrentInstance, rand, dpInd.Max, originalParam.max);
originalParam.max.x *= scale[0];
originalParam.max.y *= scale[1];
originalParam.max.z *= scale[2];
}
if (dpInd.Min >= 0)
{
originalParam.min.x *= scaleInv[0];
originalParam.min.y *= scaleInv[1];
originalParam.min.z *= scaleInv[2];
ApplyEq_(originalParam.min, e, instg, parrentInstance, rand, dpInd.Min, originalParam.min);
originalParam.min.x *= scale[0];
originalParam.min.y *= scale[1];
originalParam.min.z *= scale[2];
}
return originalParam;
}
random_vector3d ApplyEq(const Effect* e,
const InstanceGlobal* instg,
const Instance* parrentInstance,
IRandObject* rand,
const RefMinMax& dpInd,
random_vector3d originalParam,
const std::array<float, 3>& scale,
const std::array<float, 3>& scaleInv)
{
return ApplyEq_(e,
instg,
parrentInstance,
rand,
dpInd,
originalParam,
scale,
scaleInv);
}
random_int ApplyEq(const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const RefMinMax& dpInd, random_int originalParam)
{
if (dpInd.Max >= 0)
{
float value = static_cast<float>(originalParam.max);
ApplyEq_(value, e, instg, parrentInstance, rand, dpInd.Max, value);
originalParam.max = static_cast<int32_t>(value);
}
if (dpInd.Min >= 0)
{
float value = static_cast<float>(originalParam.min);
ApplyEq_(value, e, instg, parrentInstance, rand, dpInd.Min, value);
originalParam.min = static_cast<int32_t>(value);
}
return originalParam;
}
std::array<float, 4> Gradient::GetColor(float x) const
{
const auto c = GetColorAndIntensity(x);
return std::array<float, 4>{c[0] * c[3], c[1] * c[3], c[2] * c[3], GetAlpha(x)};
}
std::array<float, 4> Gradient::GetColorAndIntensity(float x) const
{
if (ColorCount == 0)
{
return std::array<float, 4>{1.0f, 1.0f, 1.0f, 1.0f};
}
if (x < Colors[0].Position)
{
const auto c = Colors[0].Color;
return {c[0], c[1], c[2], Colors[0].Intensity};
}
if (Colors[ColorCount - 1].Position <= x)
{
const auto c = Colors[ColorCount - 1].Color;
return {c[0], c[1], c[2], Colors[ColorCount - 1].Intensity};
}
auto key = ColorKey();
key.Position = x;
auto it = std::lower_bound(Colors.begin(), Colors.begin() + ColorCount, key, [](const ColorKey& a, const ColorKey& b)
{ return a.Position < b.Position; });
auto ind = static_cast<int32_t>(std::distance(Colors.begin(), it));
{
if (Colors[ind].Position != x)
{
ind--;
}
if (Colors[ind].Position <= x && x <= Colors[ind + 1].Position)
{
const auto area = Colors[ind + 1].Position - Colors[ind].Position;
if (area == 0)
{
return std::array<float, 4>{Colors[ind].Color[0], Colors[ind].Color[1], Colors[ind].Color[2], Colors[ind].Intensity};
}
const auto alpha = (x - Colors[ind].Position) / area;
const auto r = Colors[ind + 1].Color[0] * alpha + Colors[ind].Color[0] * (1.0f - alpha);
const auto g = Colors[ind + 1].Color[1] * alpha + Colors[ind].Color[1] * (1.0f - alpha);
const auto b = Colors[ind + 1].Color[2] * alpha + Colors[ind].Color[2] * (1.0f - alpha);
const auto intensity = Colors[ind + 1].Intensity * alpha + Colors[ind].Intensity * (1.0f - alpha);
return std::array<float, 4>{r, g, b, intensity};
}
else
{
assert(0);
}
}
return std::array<float, 4>{1.0f, 1.0f, 1.0f, 1.0f};
}
float Gradient::GetAlpha(float x) const
{
if (AlphaCount == 0)
{
return 1.0f;
}
if (x < Alphas[0].Position)
{
return Alphas[0].Alpha;
}
if (Alphas[AlphaCount - 1].Position <= x)
{
return Alphas[AlphaCount - 1].Alpha;
}
auto key = AlphaKey();
key.Position = x;
auto it = std::lower_bound(Alphas.begin(), Alphas.begin() + AlphaCount, key, [](const AlphaKey& a, const AlphaKey& b)
{ return a.Position < b.Position; });
auto ind = static_cast<int32_t>(std::distance(Alphas.begin(), it));
{
if (Alphas[ind].Position != x)
{
ind--;
}
if (Alphas[ind].Position <= x && x <= Alphas[ind + 1].Position)
{
const auto area = Alphas[ind + 1].Position - Alphas[ind].Position;
if (area == 0)
{
return Alphas[ind].Alpha;
}
const auto alpha = (x - Alphas[ind].Position) / area;
return Alphas[ind + 1].Alpha * alpha + Alphas[ind].Alpha * (1.0f - alpha);
}
else
{
assert(0);
}
}
return 1.0f;
}
} // namespace Effekseer<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS changefileheader (1.6.36); FILE MERGED 2008/04/01 15:05:19 thb 1.6.36.3: #i85898# Stripping all external header guards 2008/04/01 12:26:24 thb 1.6.36.2: #i85898# Stripping all external header guards 2008/03/31 12:19:27 rt 1.6.36.1: #i87441# Change license header to LPGL v3.<commit_after><|endoftext|> |
<commit_before>/*
This file is part of Kontact.
Copyright (c) 2004 Tobias Koenig <[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 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qcheckbox.h>
#include <qlayout.h>
#include <dcopref.h>
#include <kaboutdata.h>
#include <kaccelmanager.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <klistview.h>
#include <klocale.h>
#include "kcmkmailsummary.h"
extern "C"
{
KCModule *create_kmailsummary( QWidget *parent, const char * )
{
return new KCMKMailSummary( parent, "kcmkmailsummary" );
}
}
KCMKMailSummary::KCMKMailSummary( QWidget *parent, const char *name )
: KCModule( parent, name )
{
initGUI();
connect( mFolderView, SIGNAL( clicked( QListViewItem* ) ), SLOT( modified() ) );
connect( mFullPath, SIGNAL( toggled( bool ) ), SLOT( modified() ) );
KAcceleratorManager::manage( this );
load();
}
void KCMKMailSummary::modified()
{
emit changed( true );
}
void KCMKMailSummary::initGUI()
{
QVBoxLayout *layout = new QVBoxLayout( this, KDialog::marginHint(),
KDialog::spacingHint() );
mFolderView = new KListView( this );
mFolderView->setRootIsDecorated( true );
mFolderView->setFullWidth( true );
mFolderView->addColumn( i18n( "Summary" ) );
mFullPath = new QCheckBox( i18n( "Show full path for folders" ), this );
layout->addWidget( mFolderView );
layout->addWidget( mFullPath );
}
void KCMKMailSummary::initFolders()
{
DCOPRef kmail( "kmail", "KMailIface" );
QStringList folderList;
kmail.call( "folderList" ).get( folderList );
mFolderView->clear();
mFolderMap.clear();
bool firstFound = false;
QStringList::Iterator it;
for ( it = folderList.begin(); it != folderList.end(); ++it ) {
QString displayName;
if ( !firstFound ) {
// The first one is the local folders. Can't test for *it to be "/Local", it's translated.
firstFound = true;
displayName = i18n( "prefix for local folders", "Local" );
} else {
DCOPRef folderRef = kmail.call( "getFolder(QString)", *it );
folderRef.call( "displayName()" ).get( displayName );
}
if ( (*it).contains( '/' ) == 1 ) {
if ( mFolderMap.find( *it ) == mFolderMap.end() )
mFolderMap.insert( *it, new QListViewItem( mFolderView,
displayName ) );
} else {
const int pos = (*it).findRev( '/' );
const QString parentFolder = (*it).left( pos );
mFolderMap.insert( *it,
new QCheckListItem( mFolderMap[ parentFolder ],
displayName,
QCheckListItem::CheckBox ) );
}
}
}
void KCMKMailSummary::loadFolders()
{
KConfig config( "kcmkmailsummaryrc" );
config.setGroup( "General" );
QStringList folders;
if ( !config.hasKey( "ActiveFolders" ) )
folders << "/Local/inbox";
else
folders = config.readListEntry( "ActiveFolders" );
QMap<QString, QListViewItem*>::Iterator it;
for ( it = mFolderMap.begin(); it != mFolderMap.end(); ++it ) {
if ( QCheckListItem *qli = dynamic_cast<QCheckListItem*>( it.data() ) ) {
if ( folders.contains( it.key() ) ) {
qli->setOn( true );
mFolderView->ensureItemVisible( it.data() );
} else {
qli->setOn( false );
}
}
}
mFullPath->setChecked( config.readBoolEntry( "ShowFullPath", false ) );
}
void KCMKMailSummary::storeFolders()
{
KConfig config( "kcmkmailsummaryrc" );
config.setGroup( "General" );
QStringList folders;
QMap<QString, QListViewItem*>::Iterator it;
for ( it = mFolderMap.begin(); it != mFolderMap.end(); ++it )
if ( QCheckListItem *qli = dynamic_cast<QCheckListItem*>( it.data() ) )
if ( qli->isOn() )
folders.append( it.key() );
config.writeEntry( "ActiveFolders", folders );
config.writeEntry( "ShowFullPath", mFullPath->isChecked() );
config.sync();
}
void KCMKMailSummary::load()
{
initFolders();
loadFolders();
emit changed( false );
}
void KCMKMailSummary::save()
{
storeFolders();
emit changed( false );
}
void KCMKMailSummary::defaults()
{
}
const KAboutData* KCMKMailSummary::aboutData() const
{
KAboutData *about = new KAboutData( I18N_NOOP( "kcmkmailsummary" ),
I18N_NOOP( "Mail Summary Configuration Dialog" ),
0, 0, KAboutData::License_GPL,
I18N_NOOP( "(c) 2004 Tobias Koenig" ) );
about->addAuthor( "Tobias Koenig", 0, "[email protected]" );
return about;
}
#include "kcmkmailsummary.moc"
<commit_msg>Ingo's kmkernel commit makes this fix unnecessary again<commit_after>/*
This file is part of Kontact.
Copyright (c) 2004 Tobias Koenig <[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 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qcheckbox.h>
#include <qlayout.h>
#include <dcopref.h>
#include <kaboutdata.h>
#include <kaccelmanager.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <klistview.h>
#include <klocale.h>
#include "kcmkmailsummary.h"
extern "C"
{
KCModule *create_kmailsummary( QWidget *parent, const char * )
{
return new KCMKMailSummary( parent, "kcmkmailsummary" );
}
}
KCMKMailSummary::KCMKMailSummary( QWidget *parent, const char *name )
: KCModule( parent, name )
{
initGUI();
connect( mFolderView, SIGNAL( clicked( QListViewItem* ) ), SLOT( modified() ) );
connect( mFullPath, SIGNAL( toggled( bool ) ), SLOT( modified() ) );
KAcceleratorManager::manage( this );
load();
}
void KCMKMailSummary::modified()
{
emit changed( true );
}
void KCMKMailSummary::initGUI()
{
QVBoxLayout *layout = new QVBoxLayout( this, KDialog::marginHint(),
KDialog::spacingHint() );
mFolderView = new KListView( this );
mFolderView->setRootIsDecorated( true );
mFolderView->setFullWidth( true );
mFolderView->addColumn( i18n( "Summary" ) );
mFullPath = new QCheckBox( i18n( "Show full path for folders" ), this );
layout->addWidget( mFolderView );
layout->addWidget( mFullPath );
}
void KCMKMailSummary::initFolders()
{
DCOPRef kmail( "kmail", "KMailIface" );
QStringList folderList;
kmail.call( "folderList" ).get( folderList );
mFolderView->clear();
mFolderMap.clear();
QStringList::Iterator it;
for ( it = folderList.begin(); it != folderList.end(); ++it ) {
QString displayName;
if ( (*it) == "/Local" )
displayName = i18n( "prefix for local folders", "Local" );
else {
DCOPRef folderRef = kmail.call( "getFolder(QString)", *it );
folderRef.call( "displayName()" ).get( displayName );
}
if ( (*it).contains( '/' ) == 1 ) {
if ( mFolderMap.find( *it ) == mFolderMap.end() )
mFolderMap.insert( *it, new QListViewItem( mFolderView,
displayName ) );
} else {
const int pos = (*it).findRev( '/' );
const QString parentFolder = (*it).left( pos );
mFolderMap.insert( *it,
new QCheckListItem( mFolderMap[ parentFolder ],
displayName,
QCheckListItem::CheckBox ) );
}
}
}
void KCMKMailSummary::loadFolders()
{
KConfig config( "kcmkmailsummaryrc" );
config.setGroup( "General" );
QStringList folders;
if ( !config.hasKey( "ActiveFolders" ) )
folders << "/Local/inbox";
else
folders = config.readListEntry( "ActiveFolders" );
QMap<QString, QListViewItem*>::Iterator it;
for ( it = mFolderMap.begin(); it != mFolderMap.end(); ++it ) {
if ( QCheckListItem *qli = dynamic_cast<QCheckListItem*>( it.data() ) ) {
if ( folders.contains( it.key() ) ) {
qli->setOn( true );
mFolderView->ensureItemVisible( it.data() );
} else {
qli->setOn( false );
}
}
}
mFullPath->setChecked( config.readBoolEntry( "ShowFullPath", false ) );
}
void KCMKMailSummary::storeFolders()
{
KConfig config( "kcmkmailsummaryrc" );
config.setGroup( "General" );
QStringList folders;
QMap<QString, QListViewItem*>::Iterator it;
for ( it = mFolderMap.begin(); it != mFolderMap.end(); ++it )
if ( QCheckListItem *qli = dynamic_cast<QCheckListItem*>( it.data() ) )
if ( qli->isOn() )
folders.append( it.key() );
config.writeEntry( "ActiveFolders", folders );
config.writeEntry( "ShowFullPath", mFullPath->isChecked() );
config.sync();
}
void KCMKMailSummary::load()
{
initFolders();
loadFolders();
emit changed( false );
}
void KCMKMailSummary::save()
{
storeFolders();
emit changed( false );
}
void KCMKMailSummary::defaults()
{
}
const KAboutData* KCMKMailSummary::aboutData() const
{
KAboutData *about = new KAboutData( I18N_NOOP( "kcmkmailsummary" ),
I18N_NOOP( "Mail Summary Configuration Dialog" ),
0, 0, KAboutData::License_GPL,
I18N_NOOP( "(c) 2004 Tobias Koenig" ) );
about->addAuthor( "Tobias Koenig", 0, "[email protected]" );
return about;
}
#include "kcmkmailsummary.moc"
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
// Author: Hadrien Courtecuisse
//
// Copyright: See COPYING file that comes with this distribution
#include <sofa/component/linearsolver/SparseTAUCSSolver.h>
#include <sofa/core/ObjectFactory.h>
#include <iostream>
#include "sofa/helper/system/thread/CTime.h"
#include <sofa/core/objectmodel/BaseContext.h>
#include <sofa/core/behavior/LinearSolver.h>
#include <math.h>
#include <sofa/helper/system/thread/CTime.h>
#include <sofa/component/linearsolver/CompressedRowSparseMatrix.inl>
namespace sofa
{
namespace component
{
namespace linearsolver
{
using namespace sofa::defaulttype;
using namespace sofa::core::behavior;
using namespace sofa::simulation;
using namespace sofa::core::objectmodel;
using sofa::helper::system::thread::CTime;
using sofa::helper::system::thread::ctime_t;
using std::cerr;
using std::endl;
template<class TMatrix, class TVector>
SparseTAUCSSolver<TMatrix,TVector>::SparseTAUCSSolver()
: f_options( initData(&f_options,"options","TAUCS unified solver list of space-separated options") )
, f_symmetric( initData(&f_symmetric,true,"symmetric","Consider the system matrix as symmetric") )
, f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") )
#ifdef SOFA_HAVE_CILK
, f_nproc( initData(&f_nproc,(unsigned) 1,"nproc","NB proc used in taucs library") )
#endif
{
}
template<class T>
int get_taucs_flags();
template<>
int get_taucs_flags<double>() { return TAUCS_DOUBLE; }
template<>
int get_taucs_flags<float>() { return TAUCS_SINGLE; }
template<class TMatrix, class TVector>
void SparseTAUCSSolver<TMatrix,TVector>::invert(Matrix& M)
{
M.compress();
SparseTAUCSSolverInvertData * data = (SparseTAUCSSolverInvertData *) getMatrixInvertData(&M);
if (f_symmetric.getValue())
{
data->Mfiltered.copyUpperNonZeros(M);
sout << "Filtered upper part of M, nnz = " << data->Mfiltered.getRowBegin().back() << sendl;
}
else
{
data->Mfiltered.copyNonZeros(M);
sout << "Filtered M, nnz = " << data->Mfiltered.getRowBegin().back() << sendl;
}
data->Mfiltered.fullRows();
data->matrix_taucs.n = data->Mfiltered.rowSize();
data->matrix_taucs.m = data->Mfiltered.colSize();
data->matrix_taucs.flags = get_taucs_flags<Real>();
if (f_symmetric.getValue())
{
data->matrix_taucs.flags |= TAUCS_SYMMETRIC;
data->matrix_taucs.flags |= TAUCS_LOWER; // Upper on row-major is actually lower on column-major transposed matrix
}
data->matrix_taucs.colptr = (int *) &(data->Mfiltered.getRowBegin()[0]);
data->matrix_taucs.rowind = (int *) &(data->Mfiltered.getColsIndex()[0]);
data->matrix_taucs.values.d = (double*) &(data->Mfiltered.getColsValue()[0]);
helper::vector<char*> opts;
const helper::vector<std::string>& options = f_options.getValue();
if (options.size()==0)
{
opts.push_back((char *) "taucs.factor.LLT=true");
opts.push_back((char *) "taucs.factor.ordering=metis");
}
else
{
for (unsigned int i=0; i<options.size(); ++i) opts.push_back((char*)options[i].c_str());
}
#ifdef SOFA_HAVE_CILK
if (f_nproc.getValue()>1)
{
char buf[64];
sprintf(buf,"taucs.cilk.nproc=%d",f_nproc.getValue());
opts.push_back(buf);
opts.push_back((char *) "taucs.factor.mf=true");
}
#endif
opts.push_back(NULL);
if (this->f_printLog.getValue())
taucs_logfile((char*)"stdout");
if (data->factorization) taucs_linsolve(NULL, &data->factorization, 0, NULL, NULL, NULL, NULL);
int rc = taucs_linsolve(&data->matrix_taucs, &data->factorization, 0, NULL, NULL, &(opts[0]), NULL);
if (this->f_printLog.getValue())
taucs_logfile((char*)"none");
if (rc != TAUCS_SUCCESS)
{
const char* er = "";
switch(rc)
{
case TAUCS_SUCCESS: er = "SUCCESS"; break;
case TAUCS_ERROR : er = "ERROR"; break;
case TAUCS_ERROR_NOMEM: er = "NOMEM"; break;
case TAUCS_ERROR_BADARGS: er = "BADARGS"; break;
case TAUCS_ERROR_MAXDEPTH: er = "MAXDEPTH"; break;
case TAUCS_ERROR_INDEFINITE: er = "INDEFINITE"; break;
}
serr << "TAUCS factorization failed: " << er << sendl;
}
}
template<class TMatrix, class TVector>
void SparseTAUCSSolver<TMatrix,TVector>::solve (Matrix& M, Vector& z, Vector& r)
{
SparseTAUCSSolverInvertData * data = (SparseTAUCSSolverInvertData *) getMatrixInvertData(&M);
helper::vector<char*> opts;
const helper::vector<std::string>& options = f_options.getValue();
if (options.size()==0)
{
opts.push_back((char *) "taucs.factor.LLT=true");
opts.push_back((char *) "taucs.factor.ordering=metis");
}
else
{
for (unsigned int i=0; i<options.size(); ++i) opts.push_back((char*)options[i].c_str());
}
opts.push_back((char*)"taucs.factor=false");
//opts.push_back((char*)"taucs.factor.symbolic=false");
//opts.push_back((char*)"taucs.factor.numeric=false");
opts.push_back(NULL);
if (this->f_printLog.getValue())
taucs_logfile((char*)"stdout");
int rc = taucs_linsolve(&data->matrix_taucs, &data->factorization, 1, z.ptr(), r.ptr(), &(opts[0]), NULL);
if (this->f_printLog.getValue())
taucs_logfile((char*)"none");
if (rc != TAUCS_SUCCESS)
{
const char* er = "";
switch(rc)
{
case TAUCS_SUCCESS: er = "SUCCESS"; break;
case TAUCS_ERROR : er = "ERROR"; break;
case TAUCS_ERROR_NOMEM: er = "NOMEM"; break;
case TAUCS_ERROR_BADARGS: er = "BADARGS"; break;
case TAUCS_ERROR_MAXDEPTH: er = "MAXDEPTH"; break;
case TAUCS_ERROR_INDEFINITE: er = "INDEFINITE"; break;
}
serr << "TAUCS solve failed: " << er << sendl;
}
}
SOFA_DECL_CLASS(SparseTAUCSSolver)
int SparseTAUCSSolverClass = core::RegisterObject("Direct linear solvers implemented with the TAUCS library")
.add< SparseTAUCSSolver< CompressedRowSparseMatrix<double>,FullVector<double> > >()
.add< SparseTAUCSSolver< CompressedRowSparseMatrix<defaulttype::Mat<3,3,double> >,FullVector<double> > >(true)
.add< SparseTAUCSSolver< CompressedRowSparseMatrix<float>,FullVector<float> > >()
.add< SparseTAUCSSolver< CompressedRowSparseMatrix<defaulttype::Mat<3,3,float> >,FullVector<float> > >()
.addAlias("TAUCSSolver")
;
} // namespace linearsolver
} // namespace component
} // namespace sofa
<commit_msg>r9716/sofa-dev : FIX : Remove trace.<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
// Author: Hadrien Courtecuisse
//
// Copyright: See COPYING file that comes with this distribution
#include <sofa/component/linearsolver/SparseTAUCSSolver.h>
#include <sofa/core/ObjectFactory.h>
#include <iostream>
#include "sofa/helper/system/thread/CTime.h"
#include <sofa/core/objectmodel/BaseContext.h>
#include <sofa/core/behavior/LinearSolver.h>
#include <math.h>
#include <sofa/helper/system/thread/CTime.h>
#include <sofa/component/linearsolver/CompressedRowSparseMatrix.inl>
namespace sofa
{
namespace component
{
namespace linearsolver
{
using namespace sofa::defaulttype;
using namespace sofa::core::behavior;
using namespace sofa::simulation;
using namespace sofa::core::objectmodel;
using sofa::helper::system::thread::CTime;
using sofa::helper::system::thread::ctime_t;
using std::cerr;
using std::endl;
template<class TMatrix, class TVector>
SparseTAUCSSolver<TMatrix,TVector>::SparseTAUCSSolver()
: f_options( initData(&f_options,"options","TAUCS unified solver list of space-separated options") )
, f_symmetric( initData(&f_symmetric,true,"symmetric","Consider the system matrix as symmetric") )
, f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") )
#ifdef SOFA_HAVE_CILK
, f_nproc( initData(&f_nproc,(unsigned) 1,"nproc","NB proc used in taucs library") )
#endif
{
}
template<class T>
int get_taucs_flags();
template<>
int get_taucs_flags<double>() { return TAUCS_DOUBLE; }
template<>
int get_taucs_flags<float>() { return TAUCS_SINGLE; }
template<class TMatrix, class TVector>
void SparseTAUCSSolver<TMatrix,TVector>::invert(Matrix& M)
{
M.compress();
SparseTAUCSSolverInvertData * data = (SparseTAUCSSolverInvertData *) getMatrixInvertData(&M);
if (f_symmetric.getValue())
{
data->Mfiltered.copyUpperNonZeros(M);
if (this->f_printLog.getValue())
sout << "Filtered upper part of M, nnz = " << data->Mfiltered.getRowBegin().back() << sendl;
}
else
{
data->Mfiltered.copyNonZeros(M);
if (this->f_printLog.getValue())
sout << "Filtered M, nnz = " << data->Mfiltered.getRowBegin().back() << sendl;
}
data->Mfiltered.fullRows();
data->matrix_taucs.n = data->Mfiltered.rowSize();
data->matrix_taucs.m = data->Mfiltered.colSize();
data->matrix_taucs.flags = get_taucs_flags<Real>();
if (f_symmetric.getValue())
{
data->matrix_taucs.flags |= TAUCS_SYMMETRIC;
data->matrix_taucs.flags |= TAUCS_LOWER; // Upper on row-major is actually lower on column-major transposed matrix
}
data->matrix_taucs.colptr = (int *) &(data->Mfiltered.getRowBegin()[0]);
data->matrix_taucs.rowind = (int *) &(data->Mfiltered.getColsIndex()[0]);
data->matrix_taucs.values.d = (double*) &(data->Mfiltered.getColsValue()[0]);
helper::vector<char*> opts;
const helper::vector<std::string>& options = f_options.getValue();
if (options.size()==0)
{
opts.push_back((char *) "taucs.factor.LLT=true");
opts.push_back((char *) "taucs.factor.ordering=metis");
}
else
{
for (unsigned int i=0; i<options.size(); ++i) opts.push_back((char*)options[i].c_str());
}
#ifdef SOFA_HAVE_CILK
if (f_nproc.getValue()>1)
{
char buf[64];
sprintf(buf,"taucs.cilk.nproc=%d",f_nproc.getValue());
opts.push_back(buf);
opts.push_back((char *) "taucs.factor.mf=true");
}
#endif
opts.push_back(NULL);
if (this->f_printLog.getValue())
taucs_logfile((char*)"stdout");
if (data->factorization) taucs_linsolve(NULL, &data->factorization, 0, NULL, NULL, NULL, NULL);
int rc = taucs_linsolve(&data->matrix_taucs, &data->factorization, 0, NULL, NULL, &(opts[0]), NULL);
if (this->f_printLog.getValue())
taucs_logfile((char*)"none");
if (rc != TAUCS_SUCCESS)
{
const char* er = "";
switch(rc)
{
case TAUCS_SUCCESS: er = "SUCCESS"; break;
case TAUCS_ERROR : er = "ERROR"; break;
case TAUCS_ERROR_NOMEM: er = "NOMEM"; break;
case TAUCS_ERROR_BADARGS: er = "BADARGS"; break;
case TAUCS_ERROR_MAXDEPTH: er = "MAXDEPTH"; break;
case TAUCS_ERROR_INDEFINITE: er = "INDEFINITE"; break;
}
serr << "TAUCS factorization failed: " << er << sendl;
}
}
template<class TMatrix, class TVector>
void SparseTAUCSSolver<TMatrix,TVector>::solve (Matrix& M, Vector& z, Vector& r)
{
SparseTAUCSSolverInvertData * data = (SparseTAUCSSolverInvertData *) getMatrixInvertData(&M);
helper::vector<char*> opts;
const helper::vector<std::string>& options = f_options.getValue();
if (options.size()==0)
{
opts.push_back((char *) "taucs.factor.LLT=true");
opts.push_back((char *) "taucs.factor.ordering=metis");
}
else
{
for (unsigned int i=0; i<options.size(); ++i) opts.push_back((char*)options[i].c_str());
}
opts.push_back((char*)"taucs.factor=false");
//opts.push_back((char*)"taucs.factor.symbolic=false");
//opts.push_back((char*)"taucs.factor.numeric=false");
opts.push_back(NULL);
if (this->f_printLog.getValue())
taucs_logfile((char*)"stdout");
int rc = taucs_linsolve(&data->matrix_taucs, &data->factorization, 1, z.ptr(), r.ptr(), &(opts[0]), NULL);
if (this->f_printLog.getValue())
taucs_logfile((char*)"none");
if (rc != TAUCS_SUCCESS)
{
const char* er = "";
switch(rc)
{
case TAUCS_SUCCESS: er = "SUCCESS"; break;
case TAUCS_ERROR : er = "ERROR"; break;
case TAUCS_ERROR_NOMEM: er = "NOMEM"; break;
case TAUCS_ERROR_BADARGS: er = "BADARGS"; break;
case TAUCS_ERROR_MAXDEPTH: er = "MAXDEPTH"; break;
case TAUCS_ERROR_INDEFINITE: er = "INDEFINITE"; break;
}
serr << "TAUCS solve failed: " << er << sendl;
}
}
SOFA_DECL_CLASS(SparseTAUCSSolver)
int SparseTAUCSSolverClass = core::RegisterObject("Direct linear solvers implemented with the TAUCS library")
.add< SparseTAUCSSolver< CompressedRowSparseMatrix<double>,FullVector<double> > >()
.add< SparseTAUCSSolver< CompressedRowSparseMatrix<defaulttype::Mat<3,3,double> >,FullVector<double> > >(true)
.add< SparseTAUCSSolver< CompressedRowSparseMatrix<float>,FullVector<float> > >()
.add< SparseTAUCSSolver< CompressedRowSparseMatrix<defaulttype::Mat<3,3,float> >,FullVector<float> > >()
.addAlias("TAUCSSolver")
;
} // namespace linearsolver
} // namespace component
} // namespace sofa
<|endoftext|> |
<commit_before>
#include <cnoid/Plugin>
#include <cnoid/ItemTreeView>
#include <cnoid/BodyItem>
#include <cnoid/ToolBar>
using namespace std;
using namespace cnoid;
class PrototypePlugin : public Plugin
{
public:
PrototypePlugin() : Plugin("PrototypePlugin")
{
require("Body");
}
virtual bool initialize()
{
ToolBar* toolbar = new ToolBar("PrototypeToolbar");
toolbar->addButton("Movement++")
->sigClicked().connect(bind(&PrototypePlugin::onButtonClicked, this, +0.04));
toolbar->addButton("Movement--")
->sigClicked().connect(bind(&PrototypePlugin::onButtonClicked, this, -0.04));
addToolBar(toolbar);
return true;
}
void onButtonClicked(double dq)
{
ItemList<BodyItem> bodyItems =
ItemTreeView::mainInstance()->selectedItems<BodyItem>();
for(size_t i=0; i < bodyItems.size(); ++i){
BodyPtr body = bodyItems[i]->body();
for(int j=0; j < body->numJoints(); ++j){
body->joint(j)->q() += dq;
}
bodyItems[i]->notifyKinematicStateChange(true);
}
}
};
CNOID_IMPLEMENT_PLUGIN_ENTRY(PrototypePlugin)
<commit_msg>test prototype<commit_after>#include <cnoid/Plugin>
#include <cnoid/ItemTreeView>
#include <cnoid/BodyItem>
#include <cnoid/ToolBar>
#include <cnoid/SimpleController>
#include <cnoid/MenuManager>
#include <cnoid/MessageView>
#include <string>
#include <stdlib.h>
using namespace std;
using namespace cnoid;
class PrototypePlugin : public Plugin
{
public:
bool leftLeg;
int frame_count;
Action* menuItem = menuManager().setPath("/View").addItem("Frame Count");
PrototypePlugin() : Plugin("PrototypePlugin")
{
require("Body");
}
virtual bool initialize()
{
leftLeg = true;
frame_count = 0;
ToolBar* TB = new ToolBar("InMoov Kinematics");
TB->addButton("Walk")
->sigClicked()
.connect(bind(&PrototypePlugin::onButtonClicked, this, +0.02));
/* From here, add buttons and functionality to the TB.
ToolBar class has member functions for adding buttons
and defining how the joint sliders react when clicked.
It is a self-bound function. Look around at the other
predefined functions for guidance. */
TB->addButton("SwingLegs")
->sigClicked()
.connect(bind(&PrototypePlugin::swingLegs, this, 0.04));
TB->addButton("RotateRLEG")
->sigClicked()
.connect(bind(&PrototypePlugin::changeOrientationR, this, 0.04));
TB->addButton("RotateLLEG")
->sigClicked()
.connect(bind(&PrototypePlugin::changeOrientationL, this, 0.04));
TB->addButton("Frames++")
->sigClicked()
.connect(bind(&PrototypePlugin::changeFrame, this, 100));
menuItem->sigTriggered().connect(bind(&PrototypePlugin::frameTrigger, this));
/* Note that this virtual function must return true.
It may be a good idea to use this restriction as a
testing parameter */
addToolBar(TB);
return true;
}
void onButtonClicked(double dq)
{
/* vector of type BodyItem */
ItemList<BodyItem> bodyItems =
ItemTreeView::mainInstance()->selectedItems<BodyItem>();
/* size_t is defined as unsigned long long - to be used for large iterative values > 0 */
/* for loop: for each body item, assign a pointer to it, same with joints internal loop */
for(size_t i=0; i < bodyItems.size(); ++i){
BodyPtr body = bodyItems[i]->body();
for(int j=0; j < body->numJoints(); ++j){
body->joint(j)->q() += dq;
}
bodyItems[i]->notifyKinematicStateChange(true);
}
}
void swingLegs(double dq)
{
ItemList<BodyItem> bodyItems =
ItemTreeView::mainInstance()->selectedItems<BodyItem>();
for(size_t i=0; i < bodyItems.size(); ++i){
BodyPtr body = bodyItems[i]->body();
int lleg_hip_p = body->link("LLEG_HIP_P")->jointId();
int rleg_hip_p = body->link("RLEG_HIP_P")->jointId();
int lleg_knee = body->link("LLEG_KNEE")->jointId();
int rleg_knee = body->link("RLEG_KNEE")->jointId();
if(body->joint(lleg_hip_p)->q() < -1) {
this->leftLeg = true;
} else if(body->joint(lleg_hip_p)->q() > 1) {
this->leftLeg = false;
}
if(this->leftLeg) {
body->joint(lleg_hip_p)->q() += dq;
if(body->joint(lleg_knee)->q() > 0)
body->joint(lleg_knee)->q() -= dq;
body->joint(rleg_hip_p)->q() -= dq;
body->joint(rleg_knee)->q() += dq;
} else {
body->joint(lleg_hip_p)->q() -= dq;
body->joint(lleg_knee)->q() += dq;
body->joint(rleg_hip_p)->q() += dq;
if(body->joint(rleg_knee)->q() > 0)
body->joint(rleg_knee)->q() -= dq;
}
bodyItems[i]->notifyKinematicStateChange(true);
}
}
void changeOrientationL(double dq)
{
ItemList<BodyItem> bodyItems =
ItemTreeView::mainInstance()->selectedItems<BodyItem>();
for(size_t i=0; i < bodyItems.size(); ++i){
BodyPtr body = bodyItems[i]->body();
int LLEG_HIP_Y = body->link("LLEG_HIP_Y")->jointId();
int RLEG_HIP_Y = body->link("RLEG_HIP_Y")->jointId();
body->joint(LLEG_HIP_Y)->q() += dq;
bodyItems[i]->notifyKinematicStateChange(true);
}
}
void changeOrientationR(double dq) {
ItemList<BodyItem> bodyItems =
ItemTreeView::mainInstance()->selectedItems<BodyItem>();
for(size_t i=0; i < bodyItems.size(); ++i){
BodyPtr body = bodyItems[i]->body();
int LLEG_HIP_Y = body->link("LLEG_HIP_Y")->jointId();
int RLEG_HIP_Y = body->link("RLEG_HIP_Y")->jointId();
body->joint(RLEG_HIP_Y)->q() += dq;
bodyItems[i]->notifyKinematicStateChange(true);
}
}
void changeFrame(int frames) {
frame_count += frames;
}
void frameTrigger()
{
string frameNum = to_string(frame_count);
MessageView::instance()->putln("Frames to be walked: ");
MessageView::instance()->putln(frameNum);
}
};
CNOID_IMPLEMENT_PLUGIN_ENTRY(PrototypePlugin)
<|endoftext|> |
<commit_before>///
/// \file PWGCF/FEMTOSCOPY/macros/Train/PionPionFemto/AddNuTaskPionPionRoot6.C
/// \author Andrew Kubera, Ohio State University, [email protected]
///
#include <TROOT.h>
#include <TString.h>
#include <TList.h>
#include <TObjArray.h>
#include <TObjString.h>
#include <AliAnalysisManager.h>
#include "AliAnalysisTaskFemtoNu.h"
/// \class MacroCfg
/// \brief All parameters for this macro
///
struct MacroCfg : public TNamed {
TString macro = "%%/ConfigNuFemtoAnalysisR6.C",
auto_directory = "$ALICE_PHYSICS/PWGCF/FEMTOSCOPY/macros/Train/PionPionFemto",
output_filename,
output_container = "PWG2FEMTO",
subwagon_array = "",
subwagon_type = "centrality";
MacroCfg()
: TNamed("cfg", "MacroCfg")
, output_filename(AliAnalysisManager::GetAnalysisManager()->GetCommonFileName())
{}
TString GetFilename()
{
return (output_container == "")
? output_filename
: TString::Format("%s:%s", output_filename.Data(), output_container.Data());
}
};
/// \brief Adds an AliAnalysisTaskFemtoNu analysis object, constructed
/// with parameters provided, to the global AliAnalysisManager.
///
/// This macro creates and returns an :class:`AliAnalysisTaskFemto` object.
/// The task object is given a macro
/// is given the config macro "Train/PionPionFemto/ConfigFemtoAnalysis.C"
/// which is run to create the analysis objects.
/// This is fixed (for now), and if an alternative is required, you
/// should use the general AddTaskFemto.C macro.
///
/// Subwagons are supported, the name of which will be appended to
/// the task name.
/// The task name by default is "TaskPionPionFemto" which cannot be
/// changed.
///
/// The output container name is fixed at the standard "femtolist".
///
/// \param configuration
/// A string containing commands to execute, separated by semicolons.
/// Assign the old parameters using this command.
/// Single quotes are turned to double quotes.
///
/// * macro: Path to the FemtoConfig macro to load; "%%" is
/// expaneded to directory containing this file.
/// * output_filename: Name of the output file to produce.
/// Default generated by AliAnalysisManager::GetCommonFileName()
/// * output_container: Name of top-level ROOT directory in the output file.
/// Default is the classic 'PWG2FEMTO'.
/// * container: Name of the AliAnalysis container.
/// * task_name: Name of the AliAnalysisTask - May need to be unique...
/// * verbose: Task created in verbose mode
///
/// \param params
/// A string forwarded to the ConfigFemtoAnalysis macro for parsing.
/// This string is wrapped in double-quotes so escaping some to
/// ensure results is a string is unneccessary.
///
/// \param subwagon_suffix
/// If this macro is run in a train with subwagons, this will be
/// set with the identifier.
///
AliAnalysisTask* AddNuTaskPionPionRoot6(TString container,
TString configuration,
TString params,
TString subwagon_suffix)
{
std::cout << "\n\n============== AddNuTaskPionPion (ROOT6 Version) ===============\n";
// Get the global analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddNuTaskPionPion", "Could not get the global AliAnalysisManager.");
return nullptr;
}
MacroCfg cfg;
bool verbose = kFALSE;
TObjArray* lines = configuration.Tokenize("\n;");
TIter next_line(lines);
TObject *line_obj = nullptr;
gDirectory->Add(&cfg);
while ((line_obj = next_line())) {
TObjString *s = static_cast<TObjString*>(line_obj);
TString cmd = s->String().Strip(TString::kBoth, ' ');
if (cmd.IsWhitespace()) {
continue;
}
cmd.ReplaceAll("'", '"');
cmd = "static_cast<MacroCfg*>(cfg)->" + cmd + ";";
std::cout << "running `" << cmd << "`\n";
gROOT->ProcessLineFast(cmd);
}
gDirectory->Remove(&cfg);
// Replace %% with this directory for convenience
cfg.macro.ReplaceAll("%%", cfg.auto_directory);
// Dealing with subwagons
if (!subwagon_suffix.IsWhitespace()) {
Int_t index = subwagon_suffix.Atoi();
TObjArray *values = cfg.subwagon_array.Tokenize(",");
TIter next_value(values);
if (values->GetEntries() < index) {
std::cerr << "Could not use subwagon-index " << index << " in subwagon_array of only " << values->GetEntries() << " entries\n";
return nullptr;
}
for (int i=0; i<index; ++i) {
next_value();
}
TString ss = ((TObjString*)next_value())->String();
params += ";" + cfg.subwagon_type + " = " + ss;
container += "_" + subwagon_suffix;
}
std::cout << "[AddTaskPionPion]\n"
" container: " << container << "\n"
" output: '" << cfg.output_filename << "'\n"
" macro: '" << cfg.macro << "'\n"
" params: '" << params << "'\n";
// The analysis config macro for PionPionFemto accepts a single string
// argument, which it interprets.
// This line escapes some escapable characters (backslash, newline, tab)
// and wraps that string in double quotes, ensuring that the interpreter
// reads a string when passing to the macro.
const TString analysis_params = '"' + params.ReplaceAll("\\", "\\\\")
.ReplaceAll("\n", "\\n")
.ReplaceAll("\"", "\\\"")
.ReplaceAll("\t", "\\t") + '"';
std::cout << " params-normalized: '" << analysis_params << "'\n";
AliAnalysisTaskFemto *femtotask = new AliAnalysisTaskFemtoNu(
container,
cfg.macro,
analysis_params,
verbose
);
mgr->AddTask(femtotask);
const TString outputfile = cfg.GetFilename();
auto *out_container = mgr->CreateContainer(container,
AliFemtoResultStorage::Class(),
AliAnalysisManager::kOutputContainer,
outputfile);
mgr->ConnectInput(femtotask, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(femtotask, AliAnalysisTaskFemtoNu::RESULT_STORAGE_OUTPUT_SLOT, out_container);
// quiet a warning
out_container = mgr->CreateContainer(container + "_list",
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputfile);
mgr->ConnectOutput(femtotask, 0, out_container);
std::cout << "============== AddNuTaskPionPion : Done ===============\n\n";
return femtotask;
}
AliAnalysisTask*
AddNuTaskPionPionRoot6(TString container,
TString configuration,
TString params="")
{
return AddNuTaskPionPionRoot6(container, configuration, params, "");
}
AliAnalysisTask*
AddNuTaskPionPionRoot6(TString container)
{
AddNuTaskPionPionRoot6(container, "", "");
return nullptr;
}
<commit_msg>FemtoAnalysisPion - Update train-macro to tokenize using ~ and compile config-macro by default<commit_after>///
/// \file PWGCF/FEMTOSCOPY/macros/Train/PionPionFemto/AddNuTaskPionPionRoot6.C
/// \author Andrew Kubera, Ohio State University, [email protected]
///
#include <TROOT.h>
#include <TString.h>
#include <TList.h>
#include <TObjArray.h>
#include <TObjString.h>
#include <AliAnalysisManager.h>
#include "AliAnalysisTaskFemtoNu.h"
/// \class MacroCfg
/// \brief All parameters for this macro
///
struct MacroCfg : public TNamed {
TString macro = "%%/ConfigNuFemtoAnalysisR6.C+",
auto_directory = "$ALICE_PHYSICS/PWGCF/FEMTOSCOPY/macros/Train/PionPionFemto",
output_filename,
output_container = "PWG2FEMTO",
subwagon_array = "",
subwagon_type = "centrality";
MacroCfg()
: TNamed("cfg", "MacroCfg")
, output_filename(AliAnalysisManager::GetAnalysisManager()->GetCommonFileName())
{}
TString GetFilename()
{
return (output_container == "")
? output_filename
: TString::Format("%s:%s", output_filename.Data(), output_container.Data());
}
};
/// \brief Adds an AliAnalysisTaskFemtoNu analysis object, constructed
/// with parameters provided, to the global AliAnalysisManager.
///
/// This macro creates and returns an :class:`AliAnalysisTaskFemto` object.
/// The task object is given a macro
/// is given the config macro "Train/PionPionFemto/ConfigFemtoAnalysis.C"
/// which is run to create the analysis objects.
/// This is fixed (for now), and if an alternative is required, you
/// should use the general AddTaskFemto.C macro.
///
/// Subwagons are supported, the name of which will be appended to
/// the task name.
/// The task name by default is "TaskPionPionFemto" which cannot be
/// changed.
///
/// The output container name is fixed at the standard "femtolist".
///
/// \param configuration
/// A string containing commands to execute, separated by semicolons.
/// Assign the old parameters using this command.
/// Single quotes are turned to double quotes.
///
/// * macro: Path to the FemtoConfig macro to load; "%%" is
/// expaneded to directory containing this file.
/// * output_filename: Name of the output file to produce.
/// Default generated by AliAnalysisManager::GetCommonFileName()
/// * output_container: Name of top-level ROOT directory in the output file.
/// Default is the classic 'PWG2FEMTO'.
/// * container: Name of the AliAnalysis container.
/// * task_name: Name of the AliAnalysisTask - May need to be unique...
/// * verbose: Task created in verbose mode
///
/// \param params
/// A string forwarded to the ConfigFemtoAnalysis macro for parsing.
/// This string is wrapped in double-quotes so escaping some to
/// ensure results is a string is unneccessary.
///
/// \param subwagon_suffix
/// If this macro is run in a train with subwagons, this will be
/// set with the identifier.
///
AliAnalysisTask* AddNuTaskPionPionRoot6(TString container,
TString configuration,
TString params,
TString subwagon_suffix)
{
std::cout << "\n\n============== AddNuTaskPionPion (ROOT6 Version) ===============\n";
// Get the global analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddNuTaskPionPion", "Could not get the global AliAnalysisManager.");
return nullptr;
}
MacroCfg cfg;
bool verbose = kFALSE;
TObjArray* lines = configuration.Tokenize("\n;");
TIter next_line(lines);
TObject *line_obj = nullptr;
gDirectory->Add(&cfg);
while ((line_obj = next_line())) {
TObjString *s = static_cast<TObjString*>(line_obj);
TString cmd = s->String().Strip(TString::kBoth, ' ');
if (cmd.IsWhitespace()) {
continue;
}
cmd.ReplaceAll("'", '"');
cmd = "static_cast<MacroCfg*>(cfg)->" + cmd + ";";
std::cout << "running `" << cmd << "`\n";
gROOT->ProcessLineFast(cmd);
}
gDirectory->Remove(&cfg);
// Replace %% with this directory for convenience
cfg.macro.ReplaceAll("%%", cfg.auto_directory);
// Dealing with subwagons
if (!subwagon_suffix.IsWhitespace()) {
Int_t index = subwagon_suffix.Atoi();
TObjArray *values = cfg.subwagon_array.Tokenize("~");
TIter next_value(values);
if (values->GetEntries() < index) {
std::cerr << "Could not use subwagon-index " << index << " in subwagon_array of only " << values->GetEntries() << " entries\n";
return nullptr;
}
for (int i=0; i<index; ++i) {
next_value();
}
TString ss = ((TObjString*)next_value())->String();
params += ";" + cfg.subwagon_type + " = " + ss;
container += "_" + subwagon_suffix;
}
std::cout << "[AddTaskPionPion]\n"
" container: " << container << "\n"
" output: '" << cfg.output_filename << "'\n"
" macro: '" << cfg.macro << "'\n"
" params: '" << params << "'\n";
// The analysis config macro for PionPionFemto accepts a single string
// argument, which it interprets.
// This line escapes some escapable characters (backslash, newline, tab)
// and wraps that string in double quotes, ensuring that the interpreter
// reads a string when passing to the macro.
const TString analysis_params = '"' + params.ReplaceAll("\\", "\\\\")
.ReplaceAll("\n", "\\n")
.ReplaceAll("\"", "\\\"")
.ReplaceAll("\t", "\\t") + '"';
std::cout << " params-normalized: '" << analysis_params << "'\n";
AliAnalysisTaskFemto *femtotask = new AliAnalysisTaskFemtoNu(
container,
cfg.macro,
analysis_params,
verbose
);
mgr->AddTask(femtotask);
const TString outputfile = cfg.GetFilename();
auto *out_container = mgr->CreateContainer(container,
AliFemtoResultStorage::Class(),
AliAnalysisManager::kOutputContainer,
outputfile);
mgr->ConnectInput(femtotask, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(femtotask, AliAnalysisTaskFemtoNu::RESULT_STORAGE_OUTPUT_SLOT, out_container);
// quiet a warning
out_container = mgr->CreateContainer(container + "_list",
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputfile);
mgr->ConnectOutput(femtotask, 0, out_container);
std::cout << "============== AddNuTaskPionPion : Done ===============\n\n";
return femtotask;
}
AliAnalysisTask*
AddNuTaskPionPionRoot6(TString container,
TString configuration,
TString params="")
{
return AddNuTaskPionPionRoot6(container, configuration, params, "");
}
AliAnalysisTask*
AddNuTaskPionPionRoot6(TString container)
{
AddNuTaskPionPionRoot6(container, "", "");
return nullptr;
}
<|endoftext|> |
<commit_before><commit_msg>Avoid undefined signed integer overflow<commit_after><|endoftext|> |
<commit_before>/*
avdeviceconfig.cpp - Kopete Video Device Configuration Panel
Copyright (c) 2005-2006 by Cláudio da Silveira Pinheiro <[email protected]>
Copyright (c) 2010 by Frank Schaefer <[email protected]>
Kopete (c) 2002-2003 by the Kopete developers <[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 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include "avdeviceconfig.h"
#include <qcheckbox.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qbuttongroup.h>
#include <qspinbox.h>
#include <qcombobox.h>
#include <qslider.h>
//Added by qt3to4:
#include <QVBoxLayout>
#include <kplugininfo.h>
#include <klocale.h>
#include <kpushbutton.h>
#include <kpluginfactory.h>
#include <ktrader.h>
#include <kconfig.h>
#include <kcombobox.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qtabwidget.h>
#include "IdGuiElements.h"
K_PLUGIN_FACTORY( KopeteAVDeviceConfigFactory,
registerPlugin<AVDeviceConfig>(); )
K_EXPORT_PLUGIN( KopeteAVDeviceConfigFactory("kcm_kopete_avdeviceconfig") )
AVDeviceConfig::AVDeviceConfig(QWidget *parent, const QVariantList &args)
: KCModule( KopeteAVDeviceConfigFactory::componentData(), parent, args )
{
kDebug() << "kopete:config (avdevice): KopeteAVDeviceConfigFactory::componentData() called. ";
// "Video" TAB ============================================================
mPrfsVideoDevice = new Ui_AVDeviceConfig_VideoDevice();
mPrfsVideoDevice->setupUi(this);
// set a default image for the webcam widget, in case the user does not have a video device
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(false);
mPrfsVideoDevice->mVideoImageLabel->setPixmap(KIcon("camera-web").pixmap(128,128));
connect(mPrfsVideoDevice->mDeviceKComboBox, SIGNAL(activated(int)), this, SLOT(slotDeviceKComboBoxChanged(int)));
connect(mPrfsVideoDevice->mInputKComboBox, SIGNAL(activated(int)), this, SLOT(slotInputKComboBoxChanged(int)));
connect(mPrfsVideoDevice->mStandardKComboBox, SIGNAL(activated(int)), this, SLOT(slotStandardKComboBoxChanged(int)));
mVideoDevicePool = Kopete::AV::VideoDevicePool::self();
mVideoDevicePool->open();
mVideoDevicePool->setSize(320, 240);
setupControls();
mVideoDevicePool->fillDeviceKComboBox(mPrfsVideoDevice->mDeviceKComboBox);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
mVideoDevicePool->startCapturing();
connect(mVideoDevicePool, SIGNAL(deviceRegistered(const QString &) ),
SLOT(deviceRegistered(const QString &)) );
connect(mVideoDevicePool, SIGNAL(deviceUnregistered(const QString &) ),
SLOT(deviceUnregistered(const QString &)) );
connect(&qtimer, SIGNAL(timeout()), this, SLOT(slotUpdateImage()) );
#define DONT_TRY_TO_GRAB 1
#if DONT_TRY_TO_GRAB
if ( mVideoDevicePool->hasDevices() ) {
qtimer.start(40);
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(true);
}
#endif
}
AVDeviceConfig::~AVDeviceConfig()
{
mVideoDevicePool->close();
clearControlGUIElements();
}
void AVDeviceConfig::setupControls()
{
int k = 0;
qint32 cval = 0;
clearControlGUIElements();
QList<Kopete::AV::NumericVideoControl> numericCtrls;
QList<Kopete::AV::BooleanVideoControl> booleanCtrls;
QList<Kopete::AV::MenuVideoControl> menuCtrls;
QList<Kopete::AV::ActionVideoControl> actionCtrls;
numericCtrls = mVideoDevicePool->getSupportedNumericControls();
booleanCtrls = mVideoDevicePool->getSupportedBooleanControls();
menuCtrls = mVideoDevicePool->getSupportedMenuControls();
actionCtrls = mVideoDevicePool->getSupportedActionControls();
kDebug() << "Supported controls:" << numericCtrls.size() << "numeric," << booleanCtrls.size()
<< "boolean," << menuCtrls.size() << "menus," << actionCtrls.size() << "actions.";
/* SETUP GUI-elements */
// Numeric Controls: => Slider
for (k=0; k<numericCtrls.size(); k++)
{
mVideoDevicePool->getControlValue(numericCtrls.at(k).id, &cval);
addSliderControlElement(numericCtrls.at(k).id, numericCtrls.at(k).name, numericCtrls.at(k).value_min, numericCtrls.at(k).value_max, numericCtrls.at(k).value_step, cval);
}
// Boolean Controls: => Checkbox
for (k=0; k<booleanCtrls.size(); k++)
{
mVideoDevicePool->getControlValue(booleanCtrls.at(k).id, &cval);
addCheckBoxControlElement(booleanCtrls.at(k).id, booleanCtrls.at(k).name, cval);
}
// Menu Controls: => Combobox
for (k=0; k<menuCtrls.size(); k++)
{
mVideoDevicePool->getControlValue(menuCtrls.at(k).id, &cval);
addPopupMenuControlElement(menuCtrls.at(k).id, menuCtrls.at(k).name, menuCtrls.at(k).options, cval);
}
// Action Controls: => Button
for (k=0; k<actionCtrls.size(); k++)
{
mVideoDevicePool->getControlValue(actionCtrls.at(k).id, &cval);
addButtonControlElement(actionCtrls.at(k).id, actionCtrls.at(k).name);
}
/* TODO: check success of mVideoDevicePool->getControlValue() */
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(1, numericCtrls.size());
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(2, booleanCtrls.size() + menuCtrls.size());
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(3, actionCtrls.size());
}
void AVDeviceConfig::clearControlGUIElements()
{
for (int k=0; k<ctrlWidgets.size(); k++)
delete ctrlWidgets.at(k);
ctrlWidgets.clear();
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(1, false);
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(2, false);
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(3, false);
}
void AVDeviceConfig::addSliderControlElement(int cid, QString title, int min, int max, int step, int value)
{
int insert_row = mPrfsVideoDevice->sliders_gridLayout->rowCount();
QLabel *label = new QLabel( title + ":", mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->sliders_gridLayout->addWidget( label, insert_row, 0 );
IdSlider *slider = new IdSlider(cid, Qt::Horizontal, mPrfsVideoDevice->VideoTabWidget);
mPrfsVideoDevice->sliders_gridLayout->addWidget( slider, insert_row, 1 );
slider->setMinimum( min );
slider->setMaximum( max );
slider->setSliderPosition( value );
slider->setTickInterval( step );
connect( slider, SIGNAL( valueChanged(uint, int) ), this, SLOT( changeVideoControlValue(uint, int) ) );
ctrlWidgets.push_back(label);
ctrlWidgets.push_back(slider);
}
void AVDeviceConfig::addCheckBoxControlElement(int cid, QString title, bool value)
{
IdCheckBox *checkbox = new IdCheckBox( cid, mPrfsVideoDevice->VideoTabWidget );
checkbox->setText( title );
mPrfsVideoDevice->checkboxOptions_verticalLayout->addWidget( checkbox );
checkbox->setChecked( value );
connect( checkbox, SIGNAL( stateChanged(uint, int) ), this, SLOT( changeVideoControlValue(uint, int) ) );
ctrlWidgets.push_back(checkbox);
}
void AVDeviceConfig::addPopupMenuControlElement(int cid, QString title, QStringList options, int menuindex)
{
int insert_row = mPrfsVideoDevice->menuOptions_gridLayout->rowCount();
QLabel *label = new QLabel( title + ":", mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->menuOptions_gridLayout->addWidget( label, insert_row, 0 );
IdComboBox *combobox = new IdComboBox( cid, mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->menuOptions_gridLayout->addWidget( combobox, insert_row, 1 );
combobox->addItems( options );
combobox->setCurrentIndex( menuindex );
connect( combobox, SIGNAL( currentIndexChanged(uint, int) ), this, SLOT( changeVideoControlValue(uint, int) ) );
ctrlWidgets.push_back(label);
ctrlWidgets.push_back(combobox);
}
void AVDeviceConfig::addButtonControlElement(int cid, QString title)
{
int insert_row = mPrfsVideoDevice->actions_gridLayout->rowCount();
QLabel *label = new QLabel( title + ":", mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->actions_gridLayout->addWidget( label, insert_row, 0 );
IdPushButton *button = new IdPushButton( cid, mPrfsVideoDevice->VideoTabWidget );
button->setText( i18n("Execute") );
mPrfsVideoDevice->actions_gridLayout->addWidget( button, insert_row, 1 );
connect( button, SIGNAL( pressed(uint) ), this, SLOT( changeVideoControlValue(uint) ) );
ctrlWidgets.push_back(label);
ctrlWidgets.push_back(button);
}
/*!
\fn VideoDeviceConfig::save()
*/
void AVDeviceConfig::save()
{
/// @todo implement me
kDebug() << "kopete:config (avdevice): save() called. ";
mVideoDevicePool->saveConfig();
}
/*!
\fn VideoDeviceConfig::load()
*/
void AVDeviceConfig::load()
{
/// @todo implement me
}
void AVDeviceConfig::slotSettingsChanged(bool){
emit changed(true);
}
void AVDeviceConfig::slotValueChanged(int){
emit changed( true );
}
void AVDeviceConfig::slotDeviceKComboBoxChanged(int){
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) called. ";
int newdevice = mPrfsVideoDevice->mDeviceKComboBox->currentIndex();
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) Current device: " << mVideoDevicePool->currentDevice() << "New device: " << newdevice;
if ((newdevice >= 0 && newdevice < mVideoDevicePool->size()) && (newdevice != mVideoDevicePool->currentDevice()))
{
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) should change device. ";
mVideoDevicePool->open(newdevice);
mVideoDevicePool->setSize(320, 240);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
mVideoDevicePool->startCapturing();
setupControls();
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) called. ";
emit changed( true );
}
}
void AVDeviceConfig::slotInputKComboBoxChanged(int){
int newinput = mPrfsVideoDevice->mInputKComboBox->currentIndex();
if((newinput < mVideoDevicePool->inputs()) && ( newinput !=mVideoDevicePool->currentInput()))
{
mVideoDevicePool->selectInput(mPrfsVideoDevice->mInputKComboBox->currentIndex());
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
setupControls(); // NOTE: supported controls+values may be different for each input !
emit changed( true );
}
}
// ATTENTION: The 65535.0 value must be used instead of 65535 because the trailing ".0" converts the resulting value to floating point number.
// Otherwise the resulting division operation would return 0 or 1 exclusively.
void AVDeviceConfig::slotStandardKComboBoxChanged(int){
emit changed( true );
}
void AVDeviceConfig::changeVideoControlValue(unsigned int id, int value)
{
mVideoDevicePool->setControlValue(id, value);
emit changed( true );
/* TODO: Check success, fallback */
}
void AVDeviceConfig::slotUpdateImage()
{
mVideoDevicePool->getFrame();
mVideoDevicePool->getImage(&qimage);
mPrfsVideoDevice->mVideoImageLabel->setPixmap(QPixmap::fromImage(qimage));
//kDebug() << "kopete (avdeviceconfig_videoconfig): Image updated.";
}
void AVDeviceConfig::deviceRegistered( const QString & udi )
{
mVideoDevicePool->fillDeviceKComboBox(mPrfsVideoDevice->mDeviceKComboBox);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
// update the mVideoImageLabel to show the camera frames
mVideoDevicePool->open();
mVideoDevicePool->setSize(320, 240);
mVideoDevicePool->startCapturing();
setupControls();
qtimer.start(40);
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(true);
}
void AVDeviceConfig::deviceUnregistered( const QString & udi )
{
qtimer.stop();
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(false);
mPrfsVideoDevice->mVideoImageLabel->setPixmap(KIcon("camera-web").pixmap(128,128));
mVideoDevicePool->fillDeviceKComboBox(mPrfsVideoDevice->mDeviceKComboBox);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
clearControlGUIElements();
}
<commit_msg>avdeviceconfig: do not read the values of action-video-controls<commit_after>/*
avdeviceconfig.cpp - Kopete Video Device Configuration Panel
Copyright (c) 2005-2006 by Cláudio da Silveira Pinheiro <[email protected]>
Copyright (c) 2010 by Frank Schaefer <[email protected]>
Kopete (c) 2002-2003 by the Kopete developers <[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 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include "avdeviceconfig.h"
#include <qcheckbox.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qbuttongroup.h>
#include <qspinbox.h>
#include <qcombobox.h>
#include <qslider.h>
//Added by qt3to4:
#include <QVBoxLayout>
#include <kplugininfo.h>
#include <klocale.h>
#include <kpushbutton.h>
#include <kpluginfactory.h>
#include <ktrader.h>
#include <kconfig.h>
#include <kcombobox.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qtabwidget.h>
#include "IdGuiElements.h"
K_PLUGIN_FACTORY( KopeteAVDeviceConfigFactory,
registerPlugin<AVDeviceConfig>(); )
K_EXPORT_PLUGIN( KopeteAVDeviceConfigFactory("kcm_kopete_avdeviceconfig") )
AVDeviceConfig::AVDeviceConfig(QWidget *parent, const QVariantList &args)
: KCModule( KopeteAVDeviceConfigFactory::componentData(), parent, args )
{
kDebug() << "kopete:config (avdevice): KopeteAVDeviceConfigFactory::componentData() called. ";
// "Video" TAB ============================================================
mPrfsVideoDevice = new Ui_AVDeviceConfig_VideoDevice();
mPrfsVideoDevice->setupUi(this);
// set a default image for the webcam widget, in case the user does not have a video device
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(false);
mPrfsVideoDevice->mVideoImageLabel->setPixmap(KIcon("camera-web").pixmap(128,128));
connect(mPrfsVideoDevice->mDeviceKComboBox, SIGNAL(activated(int)), this, SLOT(slotDeviceKComboBoxChanged(int)));
connect(mPrfsVideoDevice->mInputKComboBox, SIGNAL(activated(int)), this, SLOT(slotInputKComboBoxChanged(int)));
connect(mPrfsVideoDevice->mStandardKComboBox, SIGNAL(activated(int)), this, SLOT(slotStandardKComboBoxChanged(int)));
mVideoDevicePool = Kopete::AV::VideoDevicePool::self();
mVideoDevicePool->open();
mVideoDevicePool->setSize(320, 240);
setupControls();
mVideoDevicePool->fillDeviceKComboBox(mPrfsVideoDevice->mDeviceKComboBox);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
mVideoDevicePool->startCapturing();
connect(mVideoDevicePool, SIGNAL(deviceRegistered(const QString &) ),
SLOT(deviceRegistered(const QString &)) );
connect(mVideoDevicePool, SIGNAL(deviceUnregistered(const QString &) ),
SLOT(deviceUnregistered(const QString &)) );
connect(&qtimer, SIGNAL(timeout()), this, SLOT(slotUpdateImage()) );
#define DONT_TRY_TO_GRAB 1
#if DONT_TRY_TO_GRAB
if ( mVideoDevicePool->hasDevices() ) {
qtimer.start(40);
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(true);
}
#endif
}
AVDeviceConfig::~AVDeviceConfig()
{
mVideoDevicePool->close();
clearControlGUIElements();
}
void AVDeviceConfig::setupControls()
{
int k = 0;
qint32 cval = 0;
clearControlGUIElements();
QList<Kopete::AV::NumericVideoControl> numericCtrls;
QList<Kopete::AV::BooleanVideoControl> booleanCtrls;
QList<Kopete::AV::MenuVideoControl> menuCtrls;
QList<Kopete::AV::ActionVideoControl> actionCtrls;
numericCtrls = mVideoDevicePool->getSupportedNumericControls();
booleanCtrls = mVideoDevicePool->getSupportedBooleanControls();
menuCtrls = mVideoDevicePool->getSupportedMenuControls();
actionCtrls = mVideoDevicePool->getSupportedActionControls();
kDebug() << "Supported controls:" << numericCtrls.size() << "numeric," << booleanCtrls.size()
<< "boolean," << menuCtrls.size() << "menus," << actionCtrls.size() << "actions.";
/* SETUP GUI-elements */
// Numeric Controls: => Slider
for (k=0; k<numericCtrls.size(); k++)
{
mVideoDevicePool->getControlValue(numericCtrls.at(k).id, &cval);
addSliderControlElement(numericCtrls.at(k).id, numericCtrls.at(k).name, numericCtrls.at(k).value_min, numericCtrls.at(k).value_max, numericCtrls.at(k).value_step, cval);
}
// Boolean Controls: => Checkbox
for (k=0; k<booleanCtrls.size(); k++)
{
mVideoDevicePool->getControlValue(booleanCtrls.at(k).id, &cval);
addCheckBoxControlElement(booleanCtrls.at(k).id, booleanCtrls.at(k).name, cval);
}
// Menu Controls: => Combobox
for (k=0; k<menuCtrls.size(); k++)
{
mVideoDevicePool->getControlValue(menuCtrls.at(k).id, &cval);
addPopupMenuControlElement(menuCtrls.at(k).id, menuCtrls.at(k).name, menuCtrls.at(k).options, cval);
}
// Action Controls: => Button
for (k=0; k<actionCtrls.size(); k++)
addButtonControlElement(actionCtrls.at(k).id, actionCtrls.at(k).name);
/* TODO: check success of mVideoDevicePool->getControlValue() */
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(1, numericCtrls.size());
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(2, booleanCtrls.size() + menuCtrls.size());
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(3, actionCtrls.size());
}
void AVDeviceConfig::clearControlGUIElements()
{
for (int k=0; k<ctrlWidgets.size(); k++)
delete ctrlWidgets.at(k);
ctrlWidgets.clear();
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(1, false);
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(2, false);
mPrfsVideoDevice->VideoTabWidget->setTabEnabled(3, false);
}
void AVDeviceConfig::addSliderControlElement(int cid, QString title, int min, int max, int step, int value)
{
int insert_row = mPrfsVideoDevice->sliders_gridLayout->rowCount();
QLabel *label = new QLabel( title + ":", mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->sliders_gridLayout->addWidget( label, insert_row, 0 );
IdSlider *slider = new IdSlider(cid, Qt::Horizontal, mPrfsVideoDevice->VideoTabWidget);
mPrfsVideoDevice->sliders_gridLayout->addWidget( slider, insert_row, 1 );
slider->setMinimum( min );
slider->setMaximum( max );
slider->setSliderPosition( value );
slider->setTickInterval( step );
connect( slider, SIGNAL( valueChanged(uint, int) ), this, SLOT( changeVideoControlValue(uint, int) ) );
ctrlWidgets.push_back(label);
ctrlWidgets.push_back(slider);
}
void AVDeviceConfig::addCheckBoxControlElement(int cid, QString title, bool value)
{
IdCheckBox *checkbox = new IdCheckBox( cid, mPrfsVideoDevice->VideoTabWidget );
checkbox->setText( title );
mPrfsVideoDevice->checkboxOptions_verticalLayout->addWidget( checkbox );
checkbox->setChecked( value );
connect( checkbox, SIGNAL( stateChanged(uint, int) ), this, SLOT( changeVideoControlValue(uint, int) ) );
ctrlWidgets.push_back(checkbox);
}
void AVDeviceConfig::addPopupMenuControlElement(int cid, QString title, QStringList options, int menuindex)
{
int insert_row = mPrfsVideoDevice->menuOptions_gridLayout->rowCount();
QLabel *label = new QLabel( title + ":", mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->menuOptions_gridLayout->addWidget( label, insert_row, 0 );
IdComboBox *combobox = new IdComboBox( cid, mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->menuOptions_gridLayout->addWidget( combobox, insert_row, 1 );
combobox->addItems( options );
combobox->setCurrentIndex( menuindex );
connect( combobox, SIGNAL( currentIndexChanged(uint, int) ), this, SLOT( changeVideoControlValue(uint, int) ) );
ctrlWidgets.push_back(label);
ctrlWidgets.push_back(combobox);
}
void AVDeviceConfig::addButtonControlElement(int cid, QString title)
{
int insert_row = mPrfsVideoDevice->actions_gridLayout->rowCount();
QLabel *label = new QLabel( title + ":", mPrfsVideoDevice->VideoTabWidget );
mPrfsVideoDevice->actions_gridLayout->addWidget( label, insert_row, 0 );
IdPushButton *button = new IdPushButton( cid, mPrfsVideoDevice->VideoTabWidget );
button->setText( i18n("Execute") );
mPrfsVideoDevice->actions_gridLayout->addWidget( button, insert_row, 1 );
connect( button, SIGNAL( pressed(uint) ), this, SLOT( changeVideoControlValue(uint) ) );
ctrlWidgets.push_back(label);
ctrlWidgets.push_back(button);
}
/*!
\fn VideoDeviceConfig::save()
*/
void AVDeviceConfig::save()
{
/// @todo implement me
kDebug() << "kopete:config (avdevice): save() called. ";
mVideoDevicePool->saveConfig();
}
/*!
\fn VideoDeviceConfig::load()
*/
void AVDeviceConfig::load()
{
/// @todo implement me
}
void AVDeviceConfig::slotSettingsChanged(bool){
emit changed(true);
}
void AVDeviceConfig::slotValueChanged(int){
emit changed( true );
}
void AVDeviceConfig::slotDeviceKComboBoxChanged(int){
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) called. ";
int newdevice = mPrfsVideoDevice->mDeviceKComboBox->currentIndex();
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) Current device: " << mVideoDevicePool->currentDevice() << "New device: " << newdevice;
if ((newdevice >= 0 && newdevice < mVideoDevicePool->size()) && (newdevice != mVideoDevicePool->currentDevice()))
{
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) should change device. ";
mVideoDevicePool->open(newdevice);
mVideoDevicePool->setSize(320, 240);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
mVideoDevicePool->startCapturing();
setupControls();
kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) called. ";
emit changed( true );
}
}
void AVDeviceConfig::slotInputKComboBoxChanged(int){
int newinput = mPrfsVideoDevice->mInputKComboBox->currentIndex();
if((newinput < mVideoDevicePool->inputs()) && ( newinput !=mVideoDevicePool->currentInput()))
{
mVideoDevicePool->selectInput(mPrfsVideoDevice->mInputKComboBox->currentIndex());
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
setupControls(); // NOTE: supported controls+values may be different for each input !
emit changed( true );
}
}
// ATTENTION: The 65535.0 value must be used instead of 65535 because the trailing ".0" converts the resulting value to floating point number.
// Otherwise the resulting division operation would return 0 or 1 exclusively.
void AVDeviceConfig::slotStandardKComboBoxChanged(int){
emit changed( true );
}
void AVDeviceConfig::changeVideoControlValue(unsigned int id, int value)
{
mVideoDevicePool->setControlValue(id, value);
emit changed( true );
/* TODO: Check success, fallback */
}
void AVDeviceConfig::slotUpdateImage()
{
mVideoDevicePool->getFrame();
mVideoDevicePool->getImage(&qimage);
mPrfsVideoDevice->mVideoImageLabel->setPixmap(QPixmap::fromImage(qimage));
//kDebug() << "kopete (avdeviceconfig_videoconfig): Image updated.";
}
void AVDeviceConfig::deviceRegistered( const QString & udi )
{
mVideoDevicePool->fillDeviceKComboBox(mPrfsVideoDevice->mDeviceKComboBox);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
// update the mVideoImageLabel to show the camera frames
mVideoDevicePool->open();
mVideoDevicePool->setSize(320, 240);
mVideoDevicePool->startCapturing();
setupControls();
qtimer.start(40);
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(true);
}
void AVDeviceConfig::deviceUnregistered( const QString & udi )
{
qtimer.stop();
mPrfsVideoDevice->mVideoImageLabel->setScaledContents(false);
mPrfsVideoDevice->mVideoImageLabel->setPixmap(KIcon("camera-web").pixmap(128,128));
mVideoDevicePool->fillDeviceKComboBox(mPrfsVideoDevice->mDeviceKComboBox);
mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox);
mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox);
clearControlGUIElements();
}
<|endoftext|> |
<commit_before>//-----本文件是对于maincall.h中部分函数的实现部分-----
#include "maincall.h"
void maincall::StartGame()//入口函数
{
/*QVector<QString>addr;
addr<<"D:/梦影测试/陈的混混/2.jpg";
addr<<"D:/梦影测试/陈的混混/1.jpg";
addr<<"D:/梦影测试/陈的混混/3.jpg";
//addr<<"D:/梦影测试/陈的混混/2.jpg";
AddPicAnimation(addr,0,0,700);
AddTextItem("C++是垃圾语言","宋体",20,0,0,230,0,0);*/
QPixmap *pixmap=NewQPixmap("D:/梦影测试/陈的混混/2.jpg");
AddPixmapItem(pixmap,0,0);
AddPixmapItem(pixmap,200,300);
}
<commit_msg>Beta v2.56<commit_after>//-----本文件是对于maincall.h中部分函数的实现部分-----
#include "maincall.h"
void maincall::StartGame()//入口函数
{
}
<|endoftext|> |
<commit_before>#pragma comment(lib, "Shlwapi.lib")
#pragma warning(disable:4996)
#include "Observer.h"
#include <cstdio>
#include <cstdlib>
#include <tchar.h>
#include <string>
#include <utility>
#include <functional>
#include <concurrent_unordered_map.h>
#include <Windows.h>
#include <Shlwapi.h>
#include "bass.h"
#include "bass_fx.h"
#include "Hooker.h"
#include "Server.h"
#define AUDIO_FILE_INFO_TOKEN "AudioFilename:"
std::shared_ptr<Observer> Observer::instance;
std::once_flag Observer::once_flag;
BOOL WINAPI Observer::ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
Observer *instance = Observer::GetInstance();
if (!instance->hookerReadFile.GetFunction()(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped))
{
return FALSE;
}
TCHAR szFilePath[MAX_PATH];
DWORD nFilePathLength = GetFinalPathNameByHandle(hFile, szFilePath, MAX_PATH, VOLUME_NAME_DOS);
// 1: \\?\D:\Games\osu!\...
DWORD dwFilePosition = SetFilePointer(hFile, 0, NULL, FILE_CURRENT) - (*lpNumberOfBytesRead);
// д Ʈ ̰ պκ оٸ :
// AudioFilename պκп / ڵ !
if (wcsncmp(L".osu", &szFilePath[nFilePathLength - 4], 4) == 0 && dwFilePosition == 0)
{
// strtok ҽ ϹǷ ϴ
// .osu UTF-8(Multibyte) ڵ
/* ٸ strtok ߶ AudioFilename: ã. */
char *buffer = strdup((const char*)(lpBuffer));
for (char *line = strtok(buffer, "\n"); line != NULL; line = strtok(NULL, "\n"))
{
if (strnicmp(line, AUDIO_FILE_INFO_TOKEN, 14) != 0)
{
continue;
}
// AudioFilename
TCHAR szAudioFileName[MAX_PATH];
mbstowcs(szAudioFileName, &line[14], MAX_PATH);
StrTrimW(szAudioFileName, L" \r");
TCHAR szAudioFilePath[MAX_PATH];
/* պκ ̻ ڸ ϱ 4° ں . */
wcscpy(szAudioFilePath, &szFilePath[4]);
PathRemoveFileSpecW(szAudioFilePath);
PathCombineW(szAudioFilePath, szAudioFilePath, szAudioFileName);
EnterCriticalSection(&instance->hCritiaclSection);
instance->currentPlaying.audioPath = tstring(szAudioFilePath);
/* պκ ̻ ڸ ϱ 4° ں . */
instance->currentPlaying.beatmapPath = (tstring(&szFilePath[4]));
LeaveCriticalSection(&instance->hCritiaclSection);
break;
}
free(buffer);
}
return TRUE;
}
inline long long GetCurrentSysTime()
{
long long t;
GetSystemTimeAsFileTime(reinterpret_cast<LPFILETIME>(&t));
return t;
}
BOOL WINAPI Observer::BASS_ChannelPlay(DWORD handle, BOOL restart)
{
Observer *instance = Observer::GetInstance();
if (!instance->hookerBASS_ChannelPlay.GetFunction()(handle, restart))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if (info.ctype & BASS_CTYPE_STREAM)
{
double currentTimePos = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));
float tempo; BASS_ChannelGetAttribute(handle, BASS_ATTRIB_TEMPO, &tempo);
instance->SendInfomation(GetCurrentSysTime(), currentTimePos, tempo);
}
return TRUE;
}
BOOL WINAPI Observer::BASS_ChannelSetPosition(DWORD handle, QWORD pos, DWORD mode)
{
Observer *instance = Observer::GetInstance();
if (!instance->hookerBASS_ChannelSetPosition.GetFunction()(handle, pos, mode))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if (info.ctype & BASS_CTYPE_STREAM)
{
double currentTime = BASS_ChannelBytes2Seconds(handle, pos);
float CurrentTempo; BASS_ChannelGetAttribute(handle, BASS_ATTRIB_TEMPO, &CurrentTempo);
// !! pos ,
// ϸ BASS_ChannelPlay Լ ȣǰ,
// BASS_ChannelIsActive BASS_ACTIVE_PAUSED.
if (BASS_ChannelIsActive(handle) == BASS_ACTIVE_PAUSED)
{
CurrentTempo = -100;
}
instance->SendInfomation(GetCurrentSysTime(), currentTime, CurrentTempo);
}
return TRUE;
}
BOOL WINAPI Observer::BASS_ChannelSetAttribute(DWORD handle, DWORD attrib, float value)
{
Observer *instance = Observer::GetInstance();
if (!instance->hookerBASS_ChannelSetAttribute.GetFunction()(handle, attrib, value))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if ((info.ctype & BASS_CTYPE_STREAM) && attrib == BASS_ATTRIB_TEMPO)
{
double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));
instance->SendInfomation(GetCurrentSysTime(), currentTime, value);
}
return TRUE;
}
BOOL WINAPI Observer::BASS_ChannelPause(DWORD handle)
{
Observer *instance = Observer::GetInstance();
if (!instance->hookerBASS_ChannelPause.GetFunction()(handle))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if (info.ctype & BASS_CTYPE_STREAM)
{
double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));
instance->SendInfomation(GetCurrentSysTime(), currentTime, -100);
}
return TRUE;
}
void Observer::SendInfomation(long long calledAt, double currentTime, float tempo)
{
TCHAR message[Server::nMessageLength];
Observer *instance = Observer::GetInstance();
/* Get Current Playing */
EnterCriticalSection(&instance->hCritiaclSection);
swprintf(message, L"%llx|%s|%lf|%f|%s\n",
calledAt,
instance->currentPlaying.audioPath.c_str(),
currentTime,
tempo,
instance->currentPlaying.beatmapPath.c_str());
LeaveCriticalSection(&instance->hCritiaclSection);
Server::GetInstance()->PushMessage(message);
}
void Observer::Initalize()
{
this->hookerReadFile.Hook();
this->hookerBASS_ChannelPlay.Hook();
this->hookerBASS_ChannelSetPosition.Hook();
this->hookerBASS_ChannelSetAttribute.Hook();
this->hookerBASS_ChannelPause.Hook();
}
void Observer::Release()
{
this->hookerBASS_ChannelPause.Unhook();
this->hookerBASS_ChannelSetAttribute.Unhook();
this->hookerBASS_ChannelSetPosition.Unhook();
this->hookerBASS_ChannelPlay.Unhook();
this->hookerReadFile.Unhook();
}
<commit_msg>instance가 static이라 GetInstance 없어도 됨<commit_after>#pragma comment(lib, "Shlwapi.lib")
#pragma warning(disable:4996)
#include "Observer.h"
#include <cstdio>
#include <cstdlib>
#include <tchar.h>
#include <string>
#include <utility>
#include <functional>
#include <concurrent_unordered_map.h>
#include <Windows.h>
#include <Shlwapi.h>
#include "bass.h"
#include "bass_fx.h"
#include "Hooker.h"
#include "Server.h"
#define AUDIO_FILE_INFO_TOKEN "AudioFilename:"
std::shared_ptr<Observer> Observer::instance;
std::once_flag Observer::once_flag;
BOOL WINAPI Observer::ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
if (!instance->hookerReadFile.GetFunction()(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped))
{
return FALSE;
}
TCHAR szFilePath[MAX_PATH];
DWORD nFilePathLength = GetFinalPathNameByHandle(hFile, szFilePath, MAX_PATH, VOLUME_NAME_DOS);
// 1: \\?\D:\Games\osu!\...
DWORD dwFilePosition = SetFilePointer(hFile, 0, NULL, FILE_CURRENT) - (*lpNumberOfBytesRead);
// д Ʈ ̰ պκ оٸ :
// AudioFilename պκп / ڵ !
if (wcsncmp(L".osu", &szFilePath[nFilePathLength - 4], 4) == 0 && dwFilePosition == 0)
{
// strtok ҽ ϹǷ ϴ
// .osu UTF-8(Multibyte) ڵ
/* ٸ strtok ߶ AudioFilename: ã. */
char *buffer = strdup((const char*)(lpBuffer));
for (char *line = strtok(buffer, "\n"); line != NULL; line = strtok(NULL, "\n"))
{
if (strnicmp(line, AUDIO_FILE_INFO_TOKEN, 14) != 0)
{
continue;
}
// AudioFilename
TCHAR szAudioFileName[MAX_PATH];
mbstowcs(szAudioFileName, &line[14], MAX_PATH);
StrTrimW(szAudioFileName, L" \r");
TCHAR szAudioFilePath[MAX_PATH];
/* պκ ̻ ڸ ϱ 4° ں . */
wcscpy(szAudioFilePath, &szFilePath[4]);
PathRemoveFileSpecW(szAudioFilePath);
PathCombineW(szAudioFilePath, szAudioFilePath, szAudioFileName);
EnterCriticalSection(&instance->hCritiaclSection);
instance->currentPlaying.audioPath = tstring(szAudioFilePath);
/* պκ ̻ ڸ ϱ 4° ں . */
instance->currentPlaying.beatmapPath = (tstring(&szFilePath[4]));
LeaveCriticalSection(&instance->hCritiaclSection);
break;
}
free(buffer);
}
return TRUE;
}
inline long long GetCurrentSysTime()
{
long long t;
GetSystemTimeAsFileTime(reinterpret_cast<LPFILETIME>(&t));
return t;
}
BOOL WINAPI Observer::BASS_ChannelPlay(DWORD handle, BOOL restart)
{
if (!instance->hookerBASS_ChannelPlay.GetFunction()(handle, restart))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if (info.ctype & BASS_CTYPE_STREAM)
{
double currentTimePos = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));
float tempo; BASS_ChannelGetAttribute(handle, BASS_ATTRIB_TEMPO, &tempo);
instance->SendInfomation(GetCurrentSysTime(), currentTimePos, tempo);
}
return TRUE;
}
BOOL WINAPI Observer::BASS_ChannelSetPosition(DWORD handle, QWORD pos, DWORD mode)
{
if (!instance->hookerBASS_ChannelSetPosition.GetFunction()(handle, pos, mode))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if (info.ctype & BASS_CTYPE_STREAM)
{
double currentTime = BASS_ChannelBytes2Seconds(handle, pos);
float CurrentTempo; BASS_ChannelGetAttribute(handle, BASS_ATTRIB_TEMPO, &CurrentTempo);
// !! pos ,
// ϸ BASS_ChannelPlay Լ ȣǰ,
// BASS_ChannelIsActive BASS_ACTIVE_PAUSED.
if (BASS_ChannelIsActive(handle) == BASS_ACTIVE_PAUSED)
{
CurrentTempo = -100;
}
instance->SendInfomation(GetCurrentSysTime(), currentTime, CurrentTempo);
}
return TRUE;
}
BOOL WINAPI Observer::BASS_ChannelSetAttribute(DWORD handle, DWORD attrib, float value)
{
if (!instance->hookerBASS_ChannelSetAttribute.GetFunction()(handle, attrib, value))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if ((info.ctype & BASS_CTYPE_STREAM) && attrib == BASS_ATTRIB_TEMPO)
{
double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));
instance->SendInfomation(GetCurrentSysTime(), currentTime, value);
}
return TRUE;
}
BOOL WINAPI Observer::BASS_ChannelPause(DWORD handle)
{
if (!instance->hookerBASS_ChannelPause.GetFunction()(handle))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if (info.ctype & BASS_CTYPE_STREAM)
{
double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));
instance->SendInfomation(GetCurrentSysTime(), currentTime, -100);
}
return TRUE;
}
void Observer::SendInfomation(long long calledAt, double currentTime, float tempo)
{
TCHAR message[Server::nMessageLength];
/* Get Current Playing */
EnterCriticalSection(&instance->hCritiaclSection);
swprintf(message, L"%llx|%s|%lf|%f|%s\n",
calledAt,
instance->currentPlaying.audioPath.c_str(),
currentTime,
tempo,
instance->currentPlaying.beatmapPath.c_str());
LeaveCriticalSection(&instance->hCritiaclSection);
Server::GetInstance()->PushMessage(message);
}
void Observer::Initalize()
{
this->hookerReadFile.Hook();
this->hookerBASS_ChannelPlay.Hook();
this->hookerBASS_ChannelSetPosition.Hook();
this->hookerBASS_ChannelSetAttribute.Hook();
this->hookerBASS_ChannelPause.Hook();
}
void Observer::Release()
{
this->hookerBASS_ChannelPause.Unhook();
this->hookerBASS_ChannelSetAttribute.Unhook();
this->hookerBASS_ChannelSetPosition.Unhook();
this->hookerBASS_ChannelPlay.Unhook();
this->hookerReadFile.Unhook();
}
<|endoftext|> |
<commit_before>// Copyright © 2011, Université catholique de Louvain
// 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.
//
// 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.
#ifndef MOZART_BOOSTENV_H
#define MOZART_BOOSTENV_H
#include <csignal>
#include <exception>
#include <fstream>
#include "boostenv-decl.hh"
#include "boostvm.hh"
#include "boostenvutils.hh"
#include "boostenvtcp.hh"
#include "boostenvpipe.hh"
#include "boostenvbigint.hh"
#ifndef MOZART_GENERATOR
namespace mozart { namespace boostenv {
//////////////////////
// BoostEnvironment //
//////////////////////
namespace {
/* TODO It might be worth, someday, to investigate how we can lift this
* decoding to the Oz level.
* It should somewhere in Resolve.oz and/or URL.oz.
* But at the same time, not forgetting that this function implements
* bootURLLoad (not a hypothetical bootFileLoad)!
*
* In fact it is already a duplicate of the logic in OS.oz.
*/
inline
char hexDigitToValue(char digit) {
// Don't care to give meaningful results if the digit is not valid
if (digit <= '9')
return digit - '0';
else if (digit <= 'Z')
return digit - ('A'-10);
else
return digit - ('a'-10);
}
inline
std::string decodeURL(const std::string& encoded) {
// Fast path when there is nothing to do
if (encoded.find('%') == std::string::npos)
return encoded;
// Relevant reminder: Unicode URLs are UTF-8 encoded then %-escaped
std::string decoded;
decoded.reserve(encoded.size());
for (size_t i = 0; i < encoded.size(); ++i) {
char c = encoded[i];
if (c == '%' && (i+2 < encoded.size())) {
char v1 = hexDigitToValue(encoded[++i]);
char v2 = hexDigitToValue(encoded[++i]);
decoded.push_back((v1 << 4) | v2);
} else {
decoded.push_back(c);
}
}
return decoded;
}
inline
std::string decodedURLToFilename(const std::string& url) {
// Not sure this is the right test (why not // ?), but it was so in Mozart 1
if (url.substr(0, 5) == "file:")
return url.substr(5);
else
return url;
}
bool defaultBootLoader(VM vm, const std::string& url, UnstableNode& result) {
std::string filename = decodedURLToFilename(decodeURL(url));
std::ifstream input(filename, std::ios::binary);
if (!input.is_open())
return false;
result = bootUnpickle(vm, input);
return true;
}
}
BoostEnvironment::BoostEnvironment(const VMStarter& vmStarter) :
_nextVMIdentifier(InitialVMIdentifier), _exitCode(0),
vmStarter(vmStarter) {
// Set up a default boot loader
setBootLoader(&defaultBootLoader);
// Ignore SIGPIPE ourselves since Boost does not always do it
#ifdef SIGPIPE
std::signal(SIGPIPE, SIG_IGN);
#endif
}
VMIdentifier BoostEnvironment::addVM(const std::string& app, bool isURL,
VirtualMachineOptions options) {
std::lock_guard<std::mutex> lock(_vmsMutex);
_vms.emplace_front(*this, _nextVMIdentifier++, options, app, isURL);
return _vms.front().identifier;
}
VMIdentifier BoostEnvironment::checkValidIdentifier(VM vm, RichNode vmIdentifier) {
VMIdentifier identifier = getArgument<VMIdentifier>(vm, vmIdentifier);
if (identifier > 0 && identifier < _nextVMIdentifier) {
return identifier;
} else {
raiseError(vm, buildTuple(vm, "vm", "invalidVMIdent"));
}
}
/* Calls onSuccess if a VM with the given identifier is found.
The _vmsMutex is hold during the call, so it is safe to assume that
the BoostVM will not be terminated during the call.
Returns whether it found the VM represented by identifier. */
bool BoostEnvironment::findVM(VMIdentifier identifier,
std::function<void(BoostVM& boostVM)> onSuccess) {
std::lock_guard<std::mutex> lock(_vmsMutex);
for (BoostVM& vm : _vms) {
if (vm.identifier == identifier) {
onSuccess(vm);
return true;
}
}
return false;
}
UnstableNode BoostEnvironment::listVMs(VM vm) {
std::lock_guard<std::mutex> lock(_vmsMutex);
UnstableNode list = buildList(vm);
for (BoostVM& boostVM : _vms)
list = buildCons(vm, build(vm, boostVM.identifier), list);
return list;
}
void BoostEnvironment::killVM(VMIdentifier identifier, nativeint exitCode,
const std::string& reason) {
findVM(identifier, [this, exitCode, reason] (BoostVM& targetVM) {
targetVM.requestTermination(exitCode, reason);
});
}
void BoostEnvironment::removeTerminatedVM(VMIdentifier identifier,
nativeint exitCode,
boost::asio::io_service::work* work) {
std::lock_guard<std::mutex> lock(_vmsMutex);
// Warning: the BoostVM is calling its own destructor with remove_if().
// We also need VirtualMachine destructor to do its cleanup before dying.
_vms.remove_if([=] (const BoostVM& vm) {
return vm.identifier == identifier;
});
if (identifier == InitialVMIdentifier) // only the exitCode of the initial VM is considered
_exitCode = exitCode;
// Tell the IO thread it does not need to wait anymore for us
delete work;
// Here the VM thread ends.
}
void BoostEnvironment::sendOnVMPort(VM from, VMIdentifier to, RichNode value) {
BoostVM::forVM(from).sendOnVMPort(to, value);
}
int BoostEnvironment::runIO() {
// This will end when all VMs are done.
io_service.run();
return _exitCode;
}
void BoostEnvironment::withSecondMemoryManager(const std::function<void(MemoryManager&)>& doGC) {
// Disallow concurrent GCs, so only one has access to the second MemoryManager
// at a time and we have a much lower maximal memory footprint.
std::lock_guard<std::mutex> lock(_gcMutex);
doGC(_secondMemoryManager);
}
///////////////
// Utilities //
///////////////
template <typename T>
void raiseOSError(VM vm, const char* function, nativeint errnum, T&& message) {
raiseSystem(vm, "os", "os", function, errnum, std::forward<T>(message));
}
void raiseOSError(VM vm, const char* function, int errnum) {
raiseOSError(vm, function, errnum, vm->getAtom(std::strerror(errnum)));
}
void raiseLastOSError(VM vm, const char* function) {
raiseOSError(vm, function, errno);
}
void raiseOSError(VM vm, const char* function, boost::system::error_code& ec) {
raiseOSError(vm, function, ec.value(), vm->getAtom(ec.message()));
}
void raiseOSError(VM vm, const char* function,
const boost::system::system_error& error) {
raiseOSError(vm, function, error.code().value(), vm->getAtom(error.what()));
}
} }
#endif
#endif // MOZART_BOOSTENV_H
<commit_msg>Name the unnamed namespace as is it useless in a .hh<commit_after>// Copyright © 2011, Université catholique de Louvain
// 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.
//
// 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.
#ifndef MOZART_BOOSTENV_H
#define MOZART_BOOSTENV_H
#include <csignal>
#include <exception>
#include <fstream>
#include "boostenv-decl.hh"
#include "boostvm.hh"
#include "boostenvutils.hh"
#include "boostenvtcp.hh"
#include "boostenvpipe.hh"
#include "boostenvbigint.hh"
#ifndef MOZART_GENERATOR
namespace mozart { namespace boostenv {
//////////////////////
// BoostEnvironment //
//////////////////////
namespace internal {
/* TODO It might be worth, someday, to investigate how we can lift this
* decoding to the Oz level.
* It should somewhere in Resolve.oz and/or URL.oz.
* But at the same time, not forgetting that this function implements
* bootURLLoad (not a hypothetical bootFileLoad)!
*
* In fact it is already a duplicate of the logic in OS.oz.
*/
inline
char hexDigitToValue(char digit) {
// Don't care to give meaningful results if the digit is not valid
if (digit <= '9')
return digit - '0';
else if (digit <= 'Z')
return digit - ('A'-10);
else
return digit - ('a'-10);
}
inline
std::string decodeURL(const std::string& encoded) {
// Fast path when there is nothing to do
if (encoded.find('%') == std::string::npos)
return encoded;
// Relevant reminder: Unicode URLs are UTF-8 encoded then %-escaped
std::string decoded;
decoded.reserve(encoded.size());
for (size_t i = 0; i < encoded.size(); ++i) {
char c = encoded[i];
if (c == '%' && (i+2 < encoded.size())) {
char v1 = hexDigitToValue(encoded[++i]);
char v2 = hexDigitToValue(encoded[++i]);
decoded.push_back((v1 << 4) | v2);
} else {
decoded.push_back(c);
}
}
return decoded;
}
inline
std::string decodedURLToFilename(const std::string& url) {
// Not sure this is the right test (why not // ?), but it was so in Mozart 1
if (url.substr(0, 5) == "file:")
return url.substr(5);
else
return url;
}
inline
bool defaultBootLoader(VM vm, const std::string& url, UnstableNode& result) {
std::string filename = decodedURLToFilename(decodeURL(url));
std::ifstream input(filename, std::ios::binary);
if (!input.is_open())
return false;
result = bootUnpickle(vm, input);
return true;
}
}
BoostEnvironment::BoostEnvironment(const VMStarter& vmStarter) :
_nextVMIdentifier(InitialVMIdentifier), _exitCode(0),
vmStarter(vmStarter) {
// Set up a default boot loader
setBootLoader(&internal::defaultBootLoader);
// Ignore SIGPIPE ourselves since Boost does not always do it
#ifdef SIGPIPE
std::signal(SIGPIPE, SIG_IGN);
#endif
}
VMIdentifier BoostEnvironment::addVM(const std::string& app, bool isURL,
VirtualMachineOptions options) {
std::lock_guard<std::mutex> lock(_vmsMutex);
_vms.emplace_front(*this, _nextVMIdentifier++, options, app, isURL);
return _vms.front().identifier;
}
VMIdentifier BoostEnvironment::checkValidIdentifier(VM vm, RichNode vmIdentifier) {
VMIdentifier identifier = getArgument<VMIdentifier>(vm, vmIdentifier);
if (identifier > 0 && identifier < _nextVMIdentifier) {
return identifier;
} else {
raiseError(vm, buildTuple(vm, "vm", "invalidVMIdent"));
}
}
/* Calls onSuccess if a VM with the given identifier is found.
The _vmsMutex is hold during the call, so it is safe to assume that
the BoostVM will not be terminated during the call.
Returns whether it found the VM represented by identifier. */
bool BoostEnvironment::findVM(VMIdentifier identifier,
std::function<void(BoostVM& boostVM)> onSuccess) {
std::lock_guard<std::mutex> lock(_vmsMutex);
for (BoostVM& vm : _vms) {
if (vm.identifier == identifier) {
onSuccess(vm);
return true;
}
}
return false;
}
UnstableNode BoostEnvironment::listVMs(VM vm) {
std::lock_guard<std::mutex> lock(_vmsMutex);
UnstableNode list = buildList(vm);
for (BoostVM& boostVM : _vms)
list = buildCons(vm, build(vm, boostVM.identifier), list);
return list;
}
void BoostEnvironment::killVM(VMIdentifier identifier, nativeint exitCode,
const std::string& reason) {
findVM(identifier, [this, exitCode, reason] (BoostVM& targetVM) {
targetVM.requestTermination(exitCode, reason);
});
}
void BoostEnvironment::removeTerminatedVM(VMIdentifier identifier,
nativeint exitCode,
boost::asio::io_service::work* work) {
std::lock_guard<std::mutex> lock(_vmsMutex);
// Warning: the BoostVM is calling its own destructor with remove_if().
// We also need VirtualMachine destructor to do its cleanup before dying.
_vms.remove_if([=] (const BoostVM& vm) {
return vm.identifier == identifier;
});
if (identifier == InitialVMIdentifier) // only the exitCode of the initial VM is considered
_exitCode = exitCode;
// Tell the IO thread it does not need to wait anymore for us
delete work;
// Here the VM thread ends.
}
void BoostEnvironment::sendOnVMPort(VM from, VMIdentifier to, RichNode value) {
BoostVM::forVM(from).sendOnVMPort(to, value);
}
int BoostEnvironment::runIO() {
// This will end when all VMs are done.
io_service.run();
return _exitCode;
}
void BoostEnvironment::withSecondMemoryManager(const std::function<void(MemoryManager&)>& doGC) {
// Disallow concurrent GCs, so only one has access to the second MemoryManager
// at a time and we have a much lower maximal memory footprint.
std::lock_guard<std::mutex> lock(_gcMutex);
doGC(_secondMemoryManager);
}
///////////////
// Utilities //
///////////////
template <typename T>
void raiseOSError(VM vm, const char* function, nativeint errnum, T&& message) {
raiseSystem(vm, "os", "os", function, errnum, std::forward<T>(message));
}
void raiseOSError(VM vm, const char* function, int errnum) {
raiseOSError(vm, function, errnum, vm->getAtom(std::strerror(errnum)));
}
void raiseLastOSError(VM vm, const char* function) {
raiseOSError(vm, function, errno);
}
void raiseOSError(VM vm, const char* function, boost::system::error_code& ec) {
raiseOSError(vm, function, ec.value(), vm->getAtom(ec.message()));
}
void raiseOSError(VM vm, const char* function,
const boost::system::system_error& error) {
raiseOSError(vm, function, error.code().value(), vm->getAtom(error.what()));
}
} }
#endif
#endif // MOZART_BOOSTENV_H
<|endoftext|> |
<commit_before>#include "motor/multirotor_tri_motor_mapper.hpp"
#include <array>
#include <cstddef>
#include "protocol/messages.hpp"
#include "util/time.hpp"
#include <chprintf.h>
MultirotorTriMotorMapper::MultirotorTriMotorMapper(PWMDeviceGroup<3>& motors, PWMDeviceGroup<1>& servos, Communicator& communicator, Logger& logger)
: motors(motors),
servos(servos),
throttleStream(communicator, 5),
logger(logger){
}
void MultirotorTriMotorMapper::run(bool armed, ActuatorSetpoint& input) {
// TODO(yoos): comment on motor indexing convention starting from positive
// X in counterclockwise order.
// Calculate servo output
std::array<float, 1> sOutputs;
sOutputs[0] = 0.540 - 0.5*input.yaw; // Magic number servo bias for pusher yaw prop.
sOutputs[0] = std::min(1.0, std::max(-1.0, sOutputs[0]));
servos.set(armed, sOutputs);
// Calculate motor outputs
std::array<float, 3> mOutputs;
mOutputs[0] = input.throttle + 0.866025*input.roll - 0.5*input.pitch; // Left
mOutputs[1] = input.throttle + input.pitch; // Tail
mOutputs[2] = input.throttle - 0.866025*input.roll - 0.5*input.pitch; // Right
motors.set(armed, mOutputs);
// Scale tail thrust per servo tilt
// TODO(yoos): Again, resolve magic number.
mOutputs[1] /= std::cos(3.1415926535/4*input.yaw);
// DEBUG
//static int loop=0;
//if (loop == 0) {
// chprintf((BaseSequentialStream*)&SD4, "MM %f %f %f %f\r\n", mOutputs[0], mOutputs[1], mOutputs[2], sOutputs[0]);
//}
//loop = (loop+1) % 50;
protocol::message::motor_throttle_message_t m {
.time = ST2MS(chibios_rt::System::getTime()),
.throttles = { mOutputs[0], mOutputs[1], mOutputs[2], sOutputs[0] }
};
if(throttleStream.ready()) {
throttleStream.publish(m);
}
logger.write(m);
}
<commit_msg>Scale throttle to compensate for tilt.<commit_after>#include "motor/multirotor_tri_motor_mapper.hpp"
#include <array>
#include <cstddef>
#include "protocol/messages.hpp"
#include "util/time.hpp"
#include <unit_config.hpp>
#include <chprintf.h>
MultirotorTriMotorMapper::MultirotorTriMotorMapper(PWMDeviceGroup<3>& motors, PWMDeviceGroup<1>& servos, Communicator& communicator, Logger& logger)
: motors(motors),
servos(servos),
throttleStream(communicator, 5),
logger(logger){
}
void MultirotorTriMotorMapper::run(bool armed, ActuatorSetpoint& input) {
// TODO(yoos): comment on motor indexing convention starting from positive
// X in counterclockwise order.
// Calculate servo output
std::array<float, 1> sOutputs;
sOutputs[0] = 0.540 - 0.5*input.yaw; // Magic number servo bias for pusher yaw prop.
sOutputs[0] = std::min(1.0, std::max(-1.0, sOutputs[0]));
servos.set(armed, sOutputs);
// Scale throttle to compensate for roll and pitch up to max angles
input.throttle /= std::cos(std::min(std::fabs(input.roll), unit_config::MAX_PITCH_ROLL_POS));
input.throttle /= std::cos(std::min(std::fabs(input.pitch), unit_config::MAX_PITCH_ROLL_POS));
input.throttle = std::min(input.throttle, 1.0); // Not entirely necessary, but perhaps preserve some control authority.
// Calculate motor outputs
std::array<float, 3> mOutputs;
mOutputs[0] = input.throttle + 0.866025*input.roll - 0.5*input.pitch; // Left
mOutputs[1] = input.throttle + input.pitch; // Tail
mOutputs[2] = input.throttle - 0.866025*input.roll - 0.5*input.pitch; // Right
motors.set(armed, mOutputs);
// Scale tail thrust per servo tilt
// TODO(yoos): Again, resolve magic number.
mOutputs[1] /= std::cos(3.1415926535/4*input.yaw);
// DEBUG
//static int loop=0;
//if (loop == 0) {
// chprintf((BaseSequentialStream*)&SD4, "MM %f %f %f %f\r\n", mOutputs[0], mOutputs[1], mOutputs[2], sOutputs[0]);
//}
//loop = (loop+1) % 50;
protocol::message::motor_throttle_message_t m {
.time = ST2MS(chibios_rt::System::getTime()),
.throttles = { mOutputs[0], mOutputs[1], mOutputs[2], sOutputs[0] }
};
if(throttleStream.ready()) {
throttleStream.publish(m);
}
logger.write(m);
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#ifndef _Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_
#define _Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <type_traits>
#include "../Math/Common.h"
#include "../Execution/Exceptions.h"
namespace Stroika {
namespace Foundation {
namespace DataExchangeFormat {
/*
********************************************************************************
*********************** DataExchangeFormat::Private_ ***************************
********************************************************************************
*/
namespace Private_ {
template <typename T>
inline typename std::enable_if < !std::is_floating_point<T>::value, T >::type CheckedConverter_Range_Helper_Pinner_ (T t, T lower, T upper)
{
return t;
}
template <typename T>
inline typename std::enable_if<std::is_floating_point<T>::value, T>::type CheckedConverter_Range_Helper_Pinner_ (T t, T lower, T upper)
{
return Math::PinToSpecialPoint (PinToSpecialPoint (t, lower), upper);
}
}
/*
********************************************************************************
************** DataExchangeFormat::CheckedConverter_Range **********************
********************************************************************************
*/
template <typename RANGE_TYPE>
RANGE_TYPE CheckedConverter_Range (const typename RANGE_TYPE::ElementType& s, const typename RANGE_TYPE::ElementType& e)
{
typename RANGE_TYPE::ElementType useS = Private_::CheckedConverter_Range_Helper_Pinner_ (s, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
typename RANGE_TYPE::ElementType useE = Private_::CheckedConverter_Range_Helper_Pinner_ (e, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
if (not (RANGE_TYPE::TraitsType::kMin <= useS)) {
Execution::DoThrow (BadFormatException ());
}
if (not (useS <= useE)) {
Execution::DoThrow (BadFormatException ());
}
if (not (useE <= RANGE_TYPE::TraitsType::kMax)) {
Execution::DoThrow (BadFormatException ());
}
return RANGE_TYPE (useS, useE);
}
/*
********************************************************************************
********* DataExchangeFormat::CheckedConverter_ValueInRange ********************
********************************************************************************
*/
template <typename RANGE_TYPE>
typename RANGE_TYPE::ElementType CheckedConverter_ValueInRange (typename RANGE_TYPE::ElementType val, const RANGE_TYPE& r)
{
typename RANGE_TYPE::ElementType useVal = Private_::CheckedConverter_Range_Helper_Pinner_ (val, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
if (not (RANGE_TYPE::TraitsType::kMin <= useVal)) {
Execution::DoThrow (BadFormatException ());
}
if (not (useVal <= RANGE_TYPE::TraitsType::kMax)) {
Execution::DoThrow (BadFormatException ());
}
return useVal;
}
}
}
}
#endif /*_Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_*/
<commit_msg>use new Math::PinToSpecialPoint () in DataExchangeFormat/CheckedConverter<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#ifndef _Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_
#define _Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <type_traits>
#include "../Math/Common.h"
#include "../Execution/Exceptions.h"
namespace Stroika {
namespace Foundation {
namespace DataExchangeFormat {
/*
********************************************************************************
*********************** DataExchangeFormat::Private_ ***************************
********************************************************************************
*/
namespace Private_ {
template <typename T>
inline typename std::enable_if < !std::is_floating_point<T>::value, T >::type CheckedConverter_Range_Helper_Pinner_ (T t, T lower, T upper)
{
return t;
}
template <typename T>
inline typename std::enable_if<std::is_floating_point<T>::value, T>::type CheckedConverter_Range_Helper_Pinner_ (T t, T lower, T upper)
{
return Math::PinToSpecialPoint (Math::PinToSpecialPoint (t, lower), upper);
}
}
/*
********************************************************************************
************** DataExchangeFormat::CheckedConverter_Range **********************
********************************************************************************
*/
template <typename RANGE_TYPE>
RANGE_TYPE CheckedConverter_Range (const typename RANGE_TYPE::ElementType& s, const typename RANGE_TYPE::ElementType& e)
{
typename RANGE_TYPE::ElementType useS = Private_::CheckedConverter_Range_Helper_Pinner_ (s, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
typename RANGE_TYPE::ElementType useE = Private_::CheckedConverter_Range_Helper_Pinner_ (e, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
if (not (RANGE_TYPE::TraitsType::kMin <= useS)) {
Execution::DoThrow (BadFormatException ());
}
if (not (useS <= useE)) {
Execution::DoThrow (BadFormatException ());
}
if (not (useE <= RANGE_TYPE::TraitsType::kMax)) {
Execution::DoThrow (BadFormatException ());
}
return RANGE_TYPE (useS, useE);
}
/*
********************************************************************************
********* DataExchangeFormat::CheckedConverter_ValueInRange ********************
********************************************************************************
*/
template <typename RANGE_TYPE>
typename RANGE_TYPE::ElementType CheckedConverter_ValueInRange (typename RANGE_TYPE::ElementType val, const RANGE_TYPE& r)
{
typename RANGE_TYPE::ElementType useVal = Private_::CheckedConverter_Range_Helper_Pinner_ (val, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
if (not (RANGE_TYPE::TraitsType::kMin <= useVal)) {
Execution::DoThrow (BadFormatException ());
}
if (not (useVal <= RANGE_TYPE::TraitsType::kMax)) {
Execution::DoThrow (BadFormatException ());
}
return useVal;
}
}
}
}
#endif /*_Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_*/
<|endoftext|> |
<commit_before>
// Bindings
#include "CPyCppyy.h"
#include "PyROOTPythonize.h"
#include "CPPInstance.h"
#include "ProxyWrappers.h"
#include "Converters.h"
#include "Utility.h"
// ROOT
#include "TClass.h"
#include "TTree.h"
#include "TBranch.h"
#include "TBranchElement.h"
#include "TBranchObject.h"
#include "TLeaf.h"
#include "TLeafElement.h"
#include "TLeafObject.h"
#include "TStreamerElement.h"
#include "TStreamerInfo.h"
using namespace CPyCppyy;
static TClass *GetClass(const CPPInstance *pyobj)
{
return TClass::GetClass(Cppyy::GetFinalName(pyobj->ObjectIsA()).c_str());
}
static TBranch *SearchForBranch(TTree *tree, const char *name)
{
TBranch *branch = tree->GetBranch(name);
if (!branch) {
// for benefit of naming of sub-branches, the actual name may have a trailing '.'
branch = tree->GetBranch((std::string(name) + '.').c_str());
}
return branch;
}
static TLeaf *SearchForLeaf(TTree *tree, const char *name, TBranch *branch)
{
TLeaf *leaf = tree->GetLeaf(name);
if (branch && !leaf) {
leaf = branch->GetLeaf(name);
if (!leaf) {
TObjArray *leaves = branch->GetListOfLeaves();
if (leaves->GetSize() && (leaves->First() == leaves->Last())) {
// i.e., if unambiguously only this one
leaf = (TLeaf *)leaves->At(0);
}
}
}
return leaf;
}
static PyObject *BindBranchToProxy(TTree *tree, const char *name, TBranch *branch)
{
// for partial return of a split object
if (branch->InheritsFrom(TBranchElement::Class())) {
TBranchElement *be = (TBranchElement *)branch;
if (be->GetCurrentClass() && (be->GetCurrentClass() != be->GetTargetClass()) && (0 <= be->GetID())) {
Long_t offset = ((TStreamerElement *)be->GetInfo()->GetElements()->At(be->GetID()))->GetOffset();
return BindCppObjectNoCast(be->GetObject() + offset, Cppyy::GetScope(be->GetCurrentClass()->GetName()));
}
}
// for return of a full object
if (branch->IsA() == TBranchElement::Class() || branch->IsA() == TBranchObject::Class()) {
TClass *klass = TClass::GetClass(branch->GetClassName());
if (klass && branch->GetAddress())
return BindCppObjectNoCast(*(void **)branch->GetAddress(), Cppyy::GetScope(branch->GetClassName()));
// try leaf, otherwise indicate failure by returning a typed null-object
TObjArray *leaves = branch->GetListOfLeaves();
if (klass && !tree->GetLeaf(name) && !(leaves->GetSize() && (leaves->First() == leaves->Last())))
return BindCppObjectNoCast(nullptr, Cppyy::GetScope(branch->GetClassName()));
}
return nullptr;
}
static PyObject *WrapLeaf(TLeaf *leaf)
{
if (1 < leaf->GetLenStatic() || leaf->GetLeafCount()) {
// array types
std::string typeName = leaf->GetTypeName();
Converter *pcnv = CreateConverter(typeName + '*', leaf->GetNdata());
void *address = 0;
if (leaf->GetBranch())
address = (void *)leaf->GetBranch()->GetAddress();
if (!address)
address = (void *)leaf->GetValuePointer();
PyObject *value = pcnv->FromMemory(&address);
delete pcnv;
return value;
} else if (leaf->GetValuePointer()) {
// value types
Converter *pcnv = CreateConverter(leaf->GetTypeName());
PyObject *value = 0;
if (leaf->IsA() == TLeafElement::Class() || leaf->IsA() == TLeafObject::Class())
value = pcnv->FromMemory((void *)*(void **)leaf->GetValuePointer());
else
value = pcnv->FromMemory((void *)leaf->GetValuePointer());
delete pcnv;
return value;
}
return nullptr;
}
// Allow access to branches/leaves as if they were data members
PyObject *GetAttr(const CPPInstance *self, PyObject *pyname)
{
const char *name_possibly_alias = CPyCppyy_PyUnicode_AsString(pyname);
if (!name_possibly_alias)
return 0;
// get hold of actual tree
TTree *tree = (TTree *)GetClass(self)->DynamicCast(TTree::Class(), self->GetObject());
if (!tree) {
PyErr_SetString(PyExc_ReferenceError, "attempt to access a null-pointer");
return 0;
}
// deal with possible aliasing
const char *name = tree->GetAlias(name_possibly_alias);
if (!name)
name = name_possibly_alias;
// search for branch first (typical for objects)
TBranch *branch = SearchForBranch(tree, name);
if (branch) {
// found a branched object, wrap its address for the object it represents
auto proxy = BindBranchToProxy(tree, name, branch);
if (proxy != nullptr)
return proxy;
}
// if not, try leaf
TLeaf *leaf = SearchForLeaf(tree, name, branch);
if (leaf) {
// found a leaf, extract value and wrap with a Python object according to its type
auto wrapper = WrapLeaf(leaf);
if (wrapper != nullptr)
return wrapper;
}
// confused
PyErr_Format(PyExc_AttributeError, "\'%s\' object has no attribute \'%s\'", tree->IsA()->GetName(), name);
return 0;
}
////////////////////////////////////////////////////////////////////////////
/// \brief Allow branches to be accessed as attributes of a tree.
/// \param[in] self Always null, since this is a module function.
/// \param[in] args Pointer to a Python tuple object containing the arguments
/// received from Python.
///
/// Allow access to branches/leaves as if they were Python data attributes of the tree
/// (e.g. mytree.branch)
PyObject *PyROOT::AddBranchAttrSyntax(PyObject * /* self */, PyObject *args)
{
PyObject *pyclass = PyTuple_GetItem(args, 0);
Utility::AddToClass(pyclass, "__getattr__", (PyCFunction)GetAttr, METH_O);
Py_RETURN_NONE;
}
////////////////////////////////////////////////////////////////////////////
/// \brief Add pythonization for TTree::SetBranchAddress.
/// \param[in] self Always null, since this is a module function.
/// \param[in] args Pointer to a Python tuple object containing the arguments
/// received from Python.
///
/// Modify the behaviour of SetBranchAddress so that proxy references can be passed
/// as arguments from the Python side, more precisely in cases where the C++
/// implementation of the method expects the address of a pointer.
///
/// For example:
/// ~~~{.python}
/// v = ROOT.std.vector('int')()
/// t.SetBranchAddress("my_vector_branch", v)
/// ~~~
PyObject *PyROOT::SetBranchAddressPyz(PyObject * /* self */, PyObject *args)
{
PyObject *treeObj = nullptr, *name = nullptr, *address = nullptr;
int argc = PyTuple_GET_SIZE(args);
// Look for the (const char*, void*) overload
#if PY_VERSION_HEX < 0x03000000
auto argParseStr = "OSO:SetBranchAddress";
#else
auto argParseStr = "OUO:SetBranchAddress";
#endif
if (argc == 3 && PyArg_ParseTuple(args, const_cast<char *>(argParseStr), &treeObj, &name, &address)) {
auto treeProxy = (CPPInstance *)treeObj;
TTree *tree = (TTree *)GetClass(treeProxy)->DynamicCast(TTree::Class(), treeProxy->GetObject());
if (!tree) {
PyErr_SetString(PyExc_TypeError,
"TTree::SetBranchAddress must be called with a TTree instance as first argument");
return nullptr;
}
auto branchName = CPyCppyy_PyUnicode_AsString(name);
auto branch = tree->GetBranch(branchName);
if (!branch) {
PyErr_SetString(PyExc_TypeError, "TTree::SetBranchAddress must be called with a valid branch name");
return nullptr;
}
bool isLeafList = branch->IsA() == TBranch::Class();
void *buf = 0;
if (CPPInstance_Check(address)) {
if (((CPPInstance *)address)->fFlags & CPPInstance::kIsReference || isLeafList)
buf = (void *)((CPPInstance *)address)->fObject;
else
buf = (void *)&((CPPInstance *)address)->fObject;
} else
Utility::GetBuffer(address, '*', 1, buf, false);
if (buf != nullptr) {
auto res = tree->SetBranchAddress(CPyCppyy_PyUnicode_AsString(name), buf);
return PyInt_FromLong(res);
}
}
// Not the overload we wanted to pythonize, return None
Py_RETURN_NONE;
}
// Try ( const char*, void*, const char*, Int_t = 32000 )
PyObject *TryBranchLeafListOverload(int argc, PyObject *args)
{
PyObject *treeObj = nullptr;
PyObject *name = nullptr, *address = nullptr, *leaflist = nullptr, *bufsize = nullptr;
if (PyArg_ParseTuple(args, const_cast<char *>("OO!OO!|O!:Branch"),
&treeObj,
&CPyCppyy_PyUnicode_Type, &name,
&address,
&CPyCppyy_PyUnicode_Type, &leaflist,
&PyInt_Type, &bufsize)) {
auto treeProxy = (CPPInstance *)treeObj;
TTree *tree = (TTree *)GetClass(treeProxy)->DynamicCast(TTree::Class(), treeProxy->GetObject());
if (!tree) {
PyErr_SetString(PyExc_TypeError, "TTree::Branch must be called with a TTree instance as first argument");
return nullptr;
}
void *buf = nullptr;
if (CPPInstance_Check(address))
buf = (void *)((CPPInstance *)address)->GetObject();
else
Utility::GetBuffer(address, '*', 1, buf, false);
if (buf) {
TBranch *branch = nullptr;
if (argc == 5) {
branch = tree->Branch(CPyCppyy_PyUnicode_AsString(name), buf, CPyCppyy_PyUnicode_AsString(leaflist),
PyInt_AS_LONG(bufsize));
} else {
branch = tree->Branch(CPyCppyy_PyUnicode_AsString(name), buf, CPyCppyy_PyUnicode_AsString(leaflist));
}
return BindCppObject(branch, Cppyy::GetScope("TBranch"));
}
}
PyErr_Clear();
Py_RETURN_NONE;
}
// Try ( const char*, const char*, T**, Int_t = 32000, Int_t = 99 )
// or ( const char*, T**, Int_t = 32000, Int_t = 99 )
PyObject *TryBranchPtrToPtrOverloads(int argc, PyObject *args)
{
PyObject *treeObj = nullptr;
PyObject *name = nullptr, *clName = nullptr, *address = nullptr, *bufsize = nullptr, *splitlevel = nullptr;
auto bIsMatch = false;
if (PyArg_ParseTuple(args, const_cast<char *>("OO!O!O|O!O!:Branch"),
&treeObj,
&CPyCppyy_PyUnicode_Type, &name,
&CPyCppyy_PyUnicode_Type, &clName,
&address,
&PyInt_Type, &bufsize,
&PyInt_Type, &splitlevel)) {
bIsMatch = true;
} else {
PyErr_Clear();
if (PyArg_ParseTuple(args, const_cast<char *>("OO!O|O!O!"),
&treeObj,
&CPyCppyy_PyUnicode_Type, &name,
&address,
&PyInt_Type, &bufsize,
&PyInt_Type, &splitlevel)) {
bIsMatch = true;
} else
PyErr_Clear();
}
if (bIsMatch) {
auto treeProxy = (CPPInstance *)treeObj;
TTree *tree = (TTree *)GetClass(treeProxy)->DynamicCast(TTree::Class(), treeProxy->GetObject());
if (!tree) {
PyErr_SetString(PyExc_TypeError, "TTree::Branch must be called with a TTree instance as first argument");
return nullptr;
}
std::string klName = clName ? CPyCppyy_PyUnicode_AsString(clName) : "";
void *buf = nullptr;
if (CPPInstance_Check(address)) {
if (((CPPInstance *)address)->fFlags & CPPInstance::kIsReference)
buf = (void *)((CPPInstance *)address)->fObject;
else
buf = (void *)&((CPPInstance *)address)->fObject;
if (!clName) {
klName = GetClass((CPPInstance *)address)->GetName();
argc += 1;
}
} else
Utility::GetBuffer(address, '*', 1, buf, false);
if (buf && !klName.empty()) {
TBranch *branch = 0;
if (argc == 4) {
branch = tree->Branch(CPyCppyy_PyUnicode_AsString(name), klName.c_str(), buf);
} else if (argc == 5) {
branch = tree->Branch(CPyCppyy_PyUnicode_AsString(name), klName.c_str(), buf, PyInt_AS_LONG(bufsize));
} else if (argc == 6) {
branch = tree->Branch(CPyCppyy_PyUnicode_AsString(name), klName.c_str(), buf, PyInt_AS_LONG(bufsize),
PyInt_AS_LONG(splitlevel));
}
return BindCppObject(branch, Cppyy::GetScope("TBranch"));
}
}
Py_RETURN_NONE;
}
////////////////////////////////////////////////////////////////////////////
/// \brief Add pythonization for TTree::Branch.
/// \param[in] self Always null, since this is a module function.
/// \param[in] args Pointer to a Python tuple object containing the arguments
/// received from Python.
///
/// Modify the behaviour of Branch so that proxy references can be passed
/// as arguments from the Python side, more precisely in cases where the C++
/// implementation of the method expects the address of a pointer.
///
/// For example:
/// ~~~{.python}
/// v = ROOT.std.vector('int')()
/// t.Branch('my_vector_branch', v)
/// ~~~
PyObject *PyROOT::BranchPyz(PyObject * /* self */, PyObject *args)
{
// Acceptable signatures:
// ( const char*, void*, const char*, Int_t = 32000 )
// ( const char*, const char*, T**, Int_t = 32000, Int_t = 99 )
// ( const char*, T**, Int_t = 32000, Int_t = 99 )
int argc = PyTuple_GET_SIZE(args);
if (argc >= 3) { // We count the TTree proxy object too
auto branch = TryBranchLeafListOverload(argc, args);
if (branch != Py_None)
return branch;
branch = TryBranchPtrToPtrOverloads(argc, args);
if (branch != Py_None)
return branch;
}
// Not the overload we wanted to pythonize, return None
Py_RETURN_NONE;
}
<commit_msg>[Exp PyROOT] Add doxygen documentation to helper functions<commit_after>
// Bindings
#include "CPyCppyy.h"
#include "PyROOTPythonize.h"
#include "CPPInstance.h"
#include "ProxyWrappers.h"
#include "Converters.h"
#include "Utility.h"
// ROOT
#include "TClass.h"
#include "TTree.h"
#include "TBranch.h"
#include "TBranchElement.h"
#include "TBranchObject.h"
#include "TLeaf.h"
#include "TLeafElement.h"
#include "TLeafObject.h"
#include "TStreamerElement.h"
#include "TStreamerInfo.h"
using namespace CPyCppyy;
static TClass *GetClass(const CPPInstance *pyobj)
{
return TClass::GetClass(Cppyy::GetFinalName(pyobj->ObjectIsA()).c_str());
}
static TBranch *SearchForBranch(TTree *tree, const char *name)
{
TBranch *branch = tree->GetBranch(name);
if (!branch) {
// for benefit of naming of sub-branches, the actual name may have a trailing '.'
branch = tree->GetBranch((std::string(name) + '.').c_str());
}
return branch;
}
static TLeaf *SearchForLeaf(TTree *tree, const char *name, TBranch *branch)
{
TLeaf *leaf = tree->GetLeaf(name);
if (branch && !leaf) {
leaf = branch->GetLeaf(name);
if (!leaf) {
TObjArray *leaves = branch->GetListOfLeaves();
if (leaves->GetSize() && (leaves->First() == leaves->Last())) {
// i.e., if unambiguously only this one
leaf = (TLeaf *)leaves->At(0);
}
}
}
return leaf;
}
static PyObject *BindBranchToProxy(TTree *tree, const char *name, TBranch *branch)
{
// for partial return of a split object
if (branch->InheritsFrom(TBranchElement::Class())) {
TBranchElement *be = (TBranchElement *)branch;
if (be->GetCurrentClass() && (be->GetCurrentClass() != be->GetTargetClass()) && (0 <= be->GetID())) {
Long_t offset = ((TStreamerElement *)be->GetInfo()->GetElements()->At(be->GetID()))->GetOffset();
return BindCppObjectNoCast(be->GetObject() + offset, Cppyy::GetScope(be->GetCurrentClass()->GetName()));
}
}
// for return of a full object
if (branch->IsA() == TBranchElement::Class() || branch->IsA() == TBranchObject::Class()) {
TClass *klass = TClass::GetClass(branch->GetClassName());
if (klass && branch->GetAddress())
return BindCppObjectNoCast(*(void **)branch->GetAddress(), Cppyy::GetScope(branch->GetClassName()));
// try leaf, otherwise indicate failure by returning a typed null-object
TObjArray *leaves = branch->GetListOfLeaves();
if (klass && !tree->GetLeaf(name) && !(leaves->GetSize() && (leaves->First() == leaves->Last())))
return BindCppObjectNoCast(nullptr, Cppyy::GetScope(branch->GetClassName()));
}
return nullptr;
}
static PyObject *WrapLeaf(TLeaf *leaf)
{
if (1 < leaf->GetLenStatic() || leaf->GetLeafCount()) {
// array types
std::string typeName = leaf->GetTypeName();
Converter *pcnv = CreateConverter(typeName + '*', leaf->GetNdata());
void *address = 0;
if (leaf->GetBranch())
address = (void *)leaf->GetBranch()->GetAddress();
if (!address)
address = (void *)leaf->GetValuePointer();
PyObject *value = pcnv->FromMemory(&address);
delete pcnv;
return value;
} else if (leaf->GetValuePointer()) {
// value types
Converter *pcnv = CreateConverter(leaf->GetTypeName());
PyObject *value = 0;
if (leaf->IsA() == TLeafElement::Class() || leaf->IsA() == TLeafObject::Class())
value = pcnv->FromMemory((void *)*(void **)leaf->GetValuePointer());
else
value = pcnv->FromMemory((void *)leaf->GetValuePointer());
delete pcnv;
return value;
}
return nullptr;
}
// Allow access to branches/leaves as if they were data members
PyObject *GetAttr(const CPPInstance *self, PyObject *pyname)
{
const char *name_possibly_alias = CPyCppyy_PyUnicode_AsString(pyname);
if (!name_possibly_alias)
return 0;
// get hold of actual tree
TTree *tree = (TTree *)GetClass(self)->DynamicCast(TTree::Class(), self->GetObject());
if (!tree) {
PyErr_SetString(PyExc_ReferenceError, "attempt to access a null-pointer");
return 0;
}
// deal with possible aliasing
const char *name = tree->GetAlias(name_possibly_alias);
if (!name)
name = name_possibly_alias;
// search for branch first (typical for objects)
TBranch *branch = SearchForBranch(tree, name);
if (branch) {
// found a branched object, wrap its address for the object it represents
auto proxy = BindBranchToProxy(tree, name, branch);
if (proxy != nullptr)
return proxy;
}
// if not, try leaf
TLeaf *leaf = SearchForLeaf(tree, name, branch);
if (leaf) {
// found a leaf, extract value and wrap with a Python object according to its type
auto wrapper = WrapLeaf(leaf);
if (wrapper != nullptr)
return wrapper;
}
// confused
PyErr_Format(PyExc_AttributeError, "\'%s\' object has no attribute \'%s\'", tree->IsA()->GetName(), name);
return 0;
}
////////////////////////////////////////////////////////////////////////////
/// \brief Allow branches to be accessed as attributes of a tree.
/// \param[in] self Always null, since this is a module function.
/// \param[in] args Pointer to a Python tuple object containing the arguments
/// received from Python.
///
/// Allow access to branches/leaves as if they were Python data attributes of the tree
/// (e.g. mytree.branch)
PyObject *PyROOT::AddBranchAttrSyntax(PyObject * /* self */, PyObject *args)
{
PyObject *pyclass = PyTuple_GetItem(args, 0);
Utility::AddToClass(pyclass, "__getattr__", (PyCFunction)GetAttr, METH_O);
Py_RETURN_NONE;
}
////////////////////////////////////////////////////////////////////////////
/// \brief Add pythonization for TTree::SetBranchAddress.
/// \param[in] self Always null, since this is a module function.
/// \param[in] args Pointer to a Python tuple object containing the arguments
/// received from Python.
///
/// Modify the behaviour of SetBranchAddress so that proxy references can be passed
/// as arguments from the Python side, more precisely in cases where the C++
/// implementation of the method expects the address of a pointer.
///
/// For example:
/// ~~~{.python}
/// v = ROOT.std.vector('int')()
/// t.SetBranchAddress("my_vector_branch", v)
/// ~~~
PyObject *PyROOT::SetBranchAddressPyz(PyObject * /* self */, PyObject *args)
{
PyObject *treeObj = nullptr, *name = nullptr, *address = nullptr;
int argc = PyTuple_GET_SIZE(args);
// Look for the (const char*, void*) overload
#if PY_VERSION_HEX < 0x03000000
auto argParseStr = "OSO:SetBranchAddress";
#else
auto argParseStr = "OUO:SetBranchAddress";
#endif
if (argc == 3 && PyArg_ParseTuple(args, const_cast<char *>(argParseStr), &treeObj, &name, &address)) {
auto treeProxy = (CPPInstance *)treeObj;
TTree *tree = (TTree *)GetClass(treeProxy)->DynamicCast(TTree::Class(), treeProxy->GetObject());
if (!tree) {
PyErr_SetString(PyExc_TypeError,
"TTree::SetBranchAddress must be called with a TTree instance as first argument");
return nullptr;
}
auto branchName = CPyCppyy_PyUnicode_AsString(name);
auto branch = tree->GetBranch(branchName);
if (!branch) {
PyErr_SetString(PyExc_TypeError, "TTree::SetBranchAddress must be called with a valid branch name");
return nullptr;
}
bool isLeafList = branch->IsA() == TBranch::Class();
void *buf = 0;
if (CPPInstance_Check(address)) {
if (((CPPInstance *)address)->fFlags & CPPInstance::kIsReference || isLeafList)
buf = (void *)((CPPInstance *)address)->fObject;
else
buf = (void *)&((CPPInstance *)address)->fObject;
} else
Utility::GetBuffer(address, '*', 1, buf, false);
if (buf != nullptr) {
auto res = tree->SetBranchAddress(CPyCppyy_PyUnicode_AsString(name), buf);
return PyInt_FromLong(res);
}
}
// Not the overload we wanted to pythonize, return None
Py_RETURN_NONE;
}
////////////////////////////////////////////////////////////////////////////
/// Try to match the arguments of TTree::Branch to the following overload:
/// - ( const char*, void*, const char*, Int_t = 32000 )
/// If the match succeeds, invoke Branch on the C++ tree with the right
/// arguments.
PyObject *TryBranchLeafListOverload(int argc, PyObject *args)
{
PyObject *treeObj = nullptr;
PyObject *name = nullptr, *address = nullptr, *leaflist = nullptr, *bufsize = nullptr;
if (PyArg_ParseTuple(args, const_cast<char *>("OO!OO!|O!:Branch"),
&treeObj,
&CPyCppyy_PyUnicode_Type, &name,
&address,
&CPyCppyy_PyUnicode_Type, &leaflist,
&PyInt_Type, &bufsize)) {
auto treeProxy = (CPPInstance *)treeObj;
TTree *tree = (TTree *)GetClass(treeProxy)->DynamicCast(TTree::Class(), treeProxy->GetObject());
if (!tree) {
PyErr_SetString(PyExc_TypeError, "TTree::Branch must be called with a TTree instance as first argument");
return nullptr;
}
void *buf = nullptr;
if (CPPInstance_Check(address))
buf = (void *)((CPPInstance *)address)->GetObject();
else
Utility::GetBuffer(address, '*', 1, buf, false);
if (buf) {
TBranch *branch = nullptr;
if (argc == 5) {
branch = tree->Branch(CPyCppyy_PyUnicode_AsString(name), buf, CPyCppyy_PyUnicode_AsString(leaflist),
PyInt_AS_LONG(bufsize));
} else {
branch = tree->Branch(CPyCppyy_PyUnicode_AsString(name), buf, CPyCppyy_PyUnicode_AsString(leaflist));
}
return BindCppObject(branch, Cppyy::GetScope("TBranch"));
}
}
PyErr_Clear();
Py_RETURN_NONE;
}
////////////////////////////////////////////////////////////////////////////
/// Try to match the arguments of TTree::Branch to one of the following
/// overloads:
/// - ( const char*, const char*, T**, Int_t = 32000, Int_t = 99 )
/// - ( const char*, T**, Int_t = 32000, Int_t = 99 )
/// If the match succeeds, invoke Branch on the C++ tree with the right
/// arguments.
PyObject *TryBranchPtrToPtrOverloads(int argc, PyObject *args)
{
PyObject *treeObj = nullptr;
PyObject *name = nullptr, *clName = nullptr, *address = nullptr, *bufsize = nullptr, *splitlevel = nullptr;
auto bIsMatch = false;
if (PyArg_ParseTuple(args, const_cast<char *>("OO!O!O|O!O!:Branch"),
&treeObj,
&CPyCppyy_PyUnicode_Type, &name,
&CPyCppyy_PyUnicode_Type, &clName,
&address,
&PyInt_Type, &bufsize,
&PyInt_Type, &splitlevel)) {
bIsMatch = true;
} else {
PyErr_Clear();
if (PyArg_ParseTuple(args, const_cast<char *>("OO!O|O!O!"),
&treeObj,
&CPyCppyy_PyUnicode_Type, &name,
&address,
&PyInt_Type, &bufsize,
&PyInt_Type, &splitlevel)) {
bIsMatch = true;
} else
PyErr_Clear();
}
if (bIsMatch) {
auto treeProxy = (CPPInstance *)treeObj;
TTree *tree = (TTree *)GetClass(treeProxy)->DynamicCast(TTree::Class(), treeProxy->GetObject());
if (!tree) {
PyErr_SetString(PyExc_TypeError, "TTree::Branch must be called with a TTree instance as first argument");
return nullptr;
}
std::string klName = clName ? CPyCppyy_PyUnicode_AsString(clName) : "";
void *buf = nullptr;
if (CPPInstance_Check(address)) {
if (((CPPInstance *)address)->fFlags & CPPInstance::kIsReference)
buf = (void *)((CPPInstance *)address)->fObject;
else
buf = (void *)&((CPPInstance *)address)->fObject;
if (!clName) {
klName = GetClass((CPPInstance *)address)->GetName();
argc += 1;
}
} else
Utility::GetBuffer(address, '*', 1, buf, false);
if (buf && !klName.empty()) {
TBranch *branch = 0;
if (argc == 4) {
branch = tree->Branch(CPyCppyy_PyUnicode_AsString(name), klName.c_str(), buf);
} else if (argc == 5) {
branch = tree->Branch(CPyCppyy_PyUnicode_AsString(name), klName.c_str(), buf, PyInt_AS_LONG(bufsize));
} else if (argc == 6) {
branch = tree->Branch(CPyCppyy_PyUnicode_AsString(name), klName.c_str(), buf, PyInt_AS_LONG(bufsize),
PyInt_AS_LONG(splitlevel));
}
return BindCppObject(branch, Cppyy::GetScope("TBranch"));
}
}
Py_RETURN_NONE;
}
////////////////////////////////////////////////////////////////////////////
/// \brief Add pythonization for TTree::Branch.
/// \param[in] self Always null, since this is a module function.
/// \param[in] args Pointer to a Python tuple object containing the arguments
/// received from Python.
///
/// Modify the behaviour of Branch so that proxy references can be passed
/// as arguments from the Python side, more precisely in cases where the C++
/// implementation of the method expects the address of a pointer.
///
/// For example:
/// ~~~{.python}
/// v = ROOT.std.vector('int')()
/// t.Branch('my_vector_branch', v)
/// ~~~
PyObject *PyROOT::BranchPyz(PyObject * /* self */, PyObject *args)
{
// Acceptable signatures:
// ( const char*, void*, const char*, Int_t = 32000 )
// ( const char*, const char*, T**, Int_t = 32000, Int_t = 99 )
// ( const char*, T**, Int_t = 32000, Int_t = 99 )
int argc = PyTuple_GET_SIZE(args);
if (argc >= 3) { // We count the TTree proxy object too
auto branch = TryBranchLeafListOverload(argc, args);
if (branch != Py_None)
return branch;
branch = TryBranchPtrToPtrOverloads(argc, args);
if (branch != Py_None)
return branch;
}
// Not the overload we wanted to pythonize, return None
Py_RETURN_NONE;
}
<|endoftext|> |
<commit_before><commit_msg>Add extra blank line after ctor definition.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2011 Timo Savola
*
* 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.
*/
#include <cstddef>
#include <memory>
namespace concrete {
template <typename ResourceType, typename... Args>
ResourceManager::Allocation<ResourceType> ResourceManager::new_resource(Args... args)
{
std::auto_ptr<ResourceType> resource(new ResourceType(args...));
auto id = append_resource(resource.get());
auto ptr = resource.get();
resource.release();
return Allocation<ResourceType> {
id,
*ptr,
};
}
template <typename ResourceType>
ResourceType &ResourceManager::resource(ResourceId id) const
{
auto plain = find_resource(id);
if (plain == NULL)
throw ResourceError();
auto typed = dynamic_cast<ResourceType *> (plain);
if (typed == NULL)
throw ResourceError();
return *typed;
}
} // namespace
<commit_msg>use unique_ptr instead of auto_ptr<commit_after>/*
* Copyright (c) 2011 Timo Savola
*
* 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.
*/
#include <cstddef>
#include <memory>
namespace concrete {
template <typename ResourceType, typename... Args>
ResourceManager::Allocation<ResourceType> ResourceManager::new_resource(Args... args)
{
std::unique_ptr<ResourceType> resource(new ResourceType(args...));
auto id = append_resource(resource.get());
auto ptr = resource.get();
resource.release();
return Allocation<ResourceType> {
id,
*ptr,
};
}
template <typename ResourceType>
ResourceType &ResourceManager::resource(ResourceId id) const
{
auto plain = find_resource(id);
if (plain == NULL)
throw ResourceError();
auto typed = dynamic_cast<ResourceType *> (plain);
if (typed == NULL)
throw ResourceError();
return *typed;
}
} // namespace
<|endoftext|> |
<commit_before>
#include "CubeScape.h"
#include <array>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glbinding/gl/enum.h>
#include <glbinding/gl/bitfield.h>
#include <globjects/globjects.h>
#include <globjects/logging.h>
#include <globjects/DebugMessage.h>
#include <globjects/VertexAttributeBinding.h>
#include <gloperate/resources/RawFile.h>
#include <gloperate/base/RenderTargetType.h>
#include <gloperate/painter/Camera.h>
#include <gloperate/painter/TargetFramebufferCapability.h>
#include <gloperate/painter/ViewportCapability.h>
#include <gloperate/painter/PerspectiveProjectionCapability.h>
#include <gloperate/painter/CameraCapability.h>
#include <gloperate/painter/TypedRenderTargetCapability.h>
#include <gloperate/painter/VirtualTimeCapability.h>
using namespace gl;
using namespace glm;
using namespace globjects;
CubeScape::CubeScape(gloperate::ResourceManager & resourceManager, const std::string & relDataPath)
: Painter("CubeScape", resourceManager, relDataPath)
, m_animation{true}
, m_numCubes{25}
, a_vertex{-1}
, u_transform{-1}
, u_time{-1}
, u_numcubes{-1}
{
// Setup painter
m_targetFramebufferCapability = addCapability(new gloperate::TargetFramebufferCapability());
m_viewportCapability = addCapability(new gloperate::ViewportCapability());
m_projectionCapability = addCapability(new gloperate::PerspectiveProjectionCapability(m_viewportCapability));
m_typedRenderTargetCapability = addCapability(new gloperate::TypedRenderTargetCapability());
m_cameraCapability = addCapability(new gloperate::CameraCapability());
m_timeCapability = addCapability(new gloperate::VirtualTimeCapability());
m_timeCapability->setLoopDuration(20.0f * pi<float>());
m_targetFramebufferCapability->changed.connect([this](){ this->onTargetFramebufferChanged();});
// Register properties
addProperty<bool>("Animation", this, &CubeScape::animation, &CubeScape::setAnimation);
auto * propNumCubes = addProperty<int>("NumCubes", this, &CubeScape::numberOfCubes, &CubeScape::setNumberOfCubes);
propNumCubes->setOption("minimum", 0);
// Register scripting functions
addFunction("randomize", this, &CubeScape::randomize);
}
CubeScape::~CubeScape()
{
}
void CubeScape::setupProjection()
{
m_projectionCapability->setZNear(0.3f);
m_projectionCapability->setZFar(15.f);
m_projectionCapability->setFovy(radians(50.f));
}
void CubeScape::onInitialize()
{
// create program
globjects::init();
onTargetFramebufferChanged();
#ifdef __APPLE__
Shader::clearGlobalReplacements();
Shader::globalReplace("#version 140", "#version 150");
debug() << "Using global OS X shader replacement '#version 140' -> '#version 150'" << std::endl;
#endif
m_program = new globjects::Program;
m_program->attach(
globjects::Shader::fromFile(GL_VERTEX_SHADER, m_relDataPath + "data/cubescape/cubescape.vert"),
globjects::Shader::fromFile(GL_GEOMETRY_SHADER, m_relDataPath + "data/cubescape/cubescape.geom"),
globjects::Shader::fromFile(GL_FRAGMENT_SHADER, m_relDataPath + "data/cubescape/cubescape.frag")
);
// create textures
m_textures[0] = new globjects::Texture;
m_textures[1] = new globjects::Texture;
for (int i=0; i < 2; ++i)
{
m_textures[i]->setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);
m_textures[i]->setParameter(GL_TEXTURE_WRAP_T, GL_REPEAT);
m_textures[i]->setParameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR);
m_textures[i]->setParameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
{
gloperate::RawFile terrain(m_relDataPath + "data/cubescape/terrain.512.512.r.ub.raw");
if (!terrain.isValid())
std::cout << "warning: loading texture from " << terrain.filePath() << " failed.";
m_textures[0]->image2D(0, GL_RED_NV, 512, 512, 0, GL_RED, GL_UNSIGNED_BYTE, terrain.data());
}
{
gloperate::RawFile patches(m_relDataPath + "data/cubescape/patches.64.16.rgb.ub.raw");
if (!patches.isValid())
std::cout << "warning: loading texture from " << patches.filePath() << " failed.";
m_textures[1]->image2D(0, GL_RGB8, 64, 16, 0, GL_RGB, GL_UNSIGNED_BYTE, patches.data());
}
m_vao = new globjects::VertexArray;
m_vao->bind();
m_vertices = new globjects::Buffer;
m_indices = new globjects::Buffer;
const std::array<vec3, 8> vertices =
{
vec3(-1.f, -1.f, -1.f ), // 0
vec3(-1.f, -1.f, 1.f ), // 1
vec3(-1.f, 1.f, -1.f ), // 2
vec3(-1.f, 1.f, 1.f ), // 3
vec3( 1.f, -1.f, -1.f ), // 4
vec3( 1.f, -1.f, 1.f ), // 5
vec3( 1.f, 1.f, -1.f ), // 6
vec3( 1.f, 1.f, 1.f ) // 7
};
m_vertices->setData(vertices, GL_STATIC_DRAW);
const std::array<unsigned char, 18> indices =
{ 2, 3, 6, 0, 1, 2, 1, 5, 3, 5, 4, 7, 4, 0, 6, 5, 1, 4 };
m_indices->setData(indices, GL_STATIC_DRAW);
m_indices->bind(GL_ELEMENT_ARRAY_BUFFER);
// setup uniforms
a_vertex = m_program->getAttributeLocation("a_vertex");
m_vao->binding(0)->setAttribute(a_vertex);
m_vao->binding(0)->setBuffer(m_vertices, 0, sizeof(vec3));
m_vao->binding(0)->setFormat(3, GL_FLOAT, GL_FALSE, 0);
m_vao->enable(a_vertex);
u_transform = m_program->getUniformLocation("modelViewProjection");
u_time = m_program->getUniformLocation("time");
u_numcubes = m_program->getUniformLocation("numcubes");
GLint terrain = m_program->getUniformLocation("terrain");
GLint patches = m_program->getUniformLocation("patches");
// since only single program and single data is used, bind only once
glClearColor(0.f, 0.f, 0.f, 1.0f);
m_program->setUniform(terrain, 0);
m_program->setUniform(patches, 1);
setupProjection();
}
void CubeScape::onPaint()
{
if (m_viewportCapability->hasChanged())
{
glViewport(m_viewportCapability->x(), m_viewportCapability->y(), m_viewportCapability->width(), m_viewportCapability->height());
m_viewportCapability->setChanged(false);
}
globjects::Framebuffer * fbo = m_targetFramebufferCapability->framebuffer();
if (!fbo)
{
fbo = globjects::Framebuffer::defaultFBO();
}
fbo->bind(GL_FRAMEBUFFER);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
mat4 transform = m_projectionCapability->projection() * m_cameraCapability->view();
m_vao->bind();
m_indices->bind(GL_ELEMENT_ARRAY_BUFFER);
m_program->use();
m_program->setUniform(u_transform, transform);
m_program->setUniform(u_time, m_timeCapability->time());
m_program->setUniform(u_numcubes, m_numCubes);
m_textures[0]->bindActive(GL_TEXTURE0);
m_textures[1]->bindActive(GL_TEXTURE1);
m_vao->drawElementsInstanced(GL_TRIANGLES, 18, GL_UNSIGNED_BYTE, nullptr, m_numCubes * m_numCubes);
m_program->release();
m_vao->unbind();
globjects::Framebuffer::unbind(GL_FRAMEBUFFER);
}
bool CubeScape::animation() const
{
return m_animation;
}
void CubeScape::setAnimation(const bool & enabled)
{
m_animation = enabled;
m_timeCapability->setEnabled(m_animation);
}
int CubeScape::numberOfCubes() const
{
return m_numCubes;
}
void CubeScape::setNumberOfCubes(const int & number)
{
m_numCubes = number;
}
void CubeScape::onTargetFramebufferChanged()
{
globjects::Framebuffer * fbo = m_targetFramebufferCapability->framebuffer();
if (!fbo)
{
fbo = globjects::Framebuffer::defaultFBO();
}
m_typedRenderTargetCapability->setRenderTarget(gloperate::RenderTargetType::Depth, fbo, gl::GLenum::GL_DEPTH_ATTACHMENT, gl::GLenum::GL_DEPTH_COMPONENT);
}
void CubeScape::randomize()
{
setNumberOfCubes(rand() % 40 + 1);
}
<commit_msg>Adjust default camera for cubescape example<commit_after>
#include "CubeScape.h"
#include <array>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glbinding/gl/enum.h>
#include <glbinding/gl/bitfield.h>
#include <globjects/globjects.h>
#include <globjects/logging.h>
#include <globjects/DebugMessage.h>
#include <globjects/VertexAttributeBinding.h>
#include <gloperate/resources/RawFile.h>
#include <gloperate/base/RenderTargetType.h>
#include <gloperate/painter/Camera.h>
#include <gloperate/painter/TargetFramebufferCapability.h>
#include <gloperate/painter/ViewportCapability.h>
#include <gloperate/painter/PerspectiveProjectionCapability.h>
#include <gloperate/painter/CameraCapability.h>
#include <gloperate/painter/TypedRenderTargetCapability.h>
#include <gloperate/painter/VirtualTimeCapability.h>
using namespace gl;
using namespace glm;
using namespace globjects;
CubeScape::CubeScape(gloperate::ResourceManager & resourceManager, const std::string & relDataPath)
: Painter("CubeScape", resourceManager, relDataPath)
, m_animation{true}
, m_numCubes{25}
, a_vertex{-1}
, u_transform{-1}
, u_time{-1}
, u_numcubes{-1}
{
// Setup painter
m_targetFramebufferCapability = addCapability(new gloperate::TargetFramebufferCapability());
m_viewportCapability = addCapability(new gloperate::ViewportCapability());
m_projectionCapability = addCapability(new gloperate::PerspectiveProjectionCapability(m_viewportCapability));
m_typedRenderTargetCapability = addCapability(new gloperate::TypedRenderTargetCapability());
m_cameraCapability = addCapability(new gloperate::CameraCapability(glm::vec3(0.0, 2.0, 1.5), glm::vec3(0.0, 0.0, 0.5), glm::vec3(0.0, 1.0, 0.0)));
m_timeCapability = addCapability(new gloperate::VirtualTimeCapability());
m_timeCapability->setLoopDuration(20.0f * pi<float>());
m_targetFramebufferCapability->changed.connect([this](){ this->onTargetFramebufferChanged();});
// Register properties
addProperty<bool>("Animation", this, &CubeScape::animation, &CubeScape::setAnimation);
auto * propNumCubes = addProperty<int>("NumCubes", this, &CubeScape::numberOfCubes, &CubeScape::setNumberOfCubes);
propNumCubes->setOption("minimum", 0);
// Register scripting functions
addFunction("randomize", this, &CubeScape::randomize);
}
CubeScape::~CubeScape()
{
}
void CubeScape::setupProjection()
{
m_projectionCapability->setZNear(0.3f);
m_projectionCapability->setZFar(15.f);
m_projectionCapability->setFovy(radians(50.f));
}
void CubeScape::onInitialize()
{
// create program
globjects::init();
onTargetFramebufferChanged();
#ifdef __APPLE__
Shader::clearGlobalReplacements();
Shader::globalReplace("#version 140", "#version 150");
debug() << "Using global OS X shader replacement '#version 140' -> '#version 150'" << std::endl;
#endif
m_program = new globjects::Program;
m_program->attach(
globjects::Shader::fromFile(GL_VERTEX_SHADER, m_relDataPath + "data/cubescape/cubescape.vert"),
globjects::Shader::fromFile(GL_GEOMETRY_SHADER, m_relDataPath + "data/cubescape/cubescape.geom"),
globjects::Shader::fromFile(GL_FRAGMENT_SHADER, m_relDataPath + "data/cubescape/cubescape.frag")
);
// create textures
m_textures[0] = new globjects::Texture;
m_textures[1] = new globjects::Texture;
for (int i=0; i < 2; ++i)
{
m_textures[i]->setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);
m_textures[i]->setParameter(GL_TEXTURE_WRAP_T, GL_REPEAT);
m_textures[i]->setParameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR);
m_textures[i]->setParameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
{
gloperate::RawFile terrain(m_relDataPath + "data/cubescape/terrain.512.512.r.ub.raw");
if (!terrain.isValid())
std::cout << "warning: loading texture from " << terrain.filePath() << " failed.";
m_textures[0]->image2D(0, GL_RED_NV, 512, 512, 0, GL_RED, GL_UNSIGNED_BYTE, terrain.data());
}
{
gloperate::RawFile patches(m_relDataPath + "data/cubescape/patches.64.16.rgb.ub.raw");
if (!patches.isValid())
std::cout << "warning: loading texture from " << patches.filePath() << " failed.";
m_textures[1]->image2D(0, GL_RGB8, 64, 16, 0, GL_RGB, GL_UNSIGNED_BYTE, patches.data());
}
m_vao = new globjects::VertexArray;
m_vao->bind();
m_vertices = new globjects::Buffer;
m_indices = new globjects::Buffer;
const std::array<vec3, 8> vertices =
{
vec3(-1.f, -1.f, -1.f ), // 0
vec3(-1.f, -1.f, 1.f ), // 1
vec3(-1.f, 1.f, -1.f ), // 2
vec3(-1.f, 1.f, 1.f ), // 3
vec3( 1.f, -1.f, -1.f ), // 4
vec3( 1.f, -1.f, 1.f ), // 5
vec3( 1.f, 1.f, -1.f ), // 6
vec3( 1.f, 1.f, 1.f ) // 7
};
m_vertices->setData(vertices, GL_STATIC_DRAW);
const std::array<unsigned char, 18> indices =
{ 2, 3, 6, 0, 1, 2, 1, 5, 3, 5, 4, 7, 4, 0, 6, 5, 1, 4 };
m_indices->setData(indices, GL_STATIC_DRAW);
m_indices->bind(GL_ELEMENT_ARRAY_BUFFER);
// setup uniforms
a_vertex = m_program->getAttributeLocation("a_vertex");
m_vao->binding(0)->setAttribute(a_vertex);
m_vao->binding(0)->setBuffer(m_vertices, 0, sizeof(vec3));
m_vao->binding(0)->setFormat(3, GL_FLOAT, GL_FALSE, 0);
m_vao->enable(a_vertex);
u_transform = m_program->getUniformLocation("modelViewProjection");
u_time = m_program->getUniformLocation("time");
u_numcubes = m_program->getUniformLocation("numcubes");
GLint terrain = m_program->getUniformLocation("terrain");
GLint patches = m_program->getUniformLocation("patches");
// since only single program and single data is used, bind only once
glClearColor(0.f, 0.f, 0.f, 1.0f);
m_program->setUniform(terrain, 0);
m_program->setUniform(patches, 1);
setupProjection();
}
void CubeScape::onPaint()
{
if (m_viewportCapability->hasChanged())
{
glViewport(m_viewportCapability->x(), m_viewportCapability->y(), m_viewportCapability->width(), m_viewportCapability->height());
m_viewportCapability->setChanged(false);
}
globjects::Framebuffer * fbo = m_targetFramebufferCapability->framebuffer();
if (!fbo)
{
fbo = globjects::Framebuffer::defaultFBO();
}
fbo->bind(GL_FRAMEBUFFER);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
mat4 transform = m_projectionCapability->projection() * m_cameraCapability->view();
m_vao->bind();
m_indices->bind(GL_ELEMENT_ARRAY_BUFFER);
m_program->use();
m_program->setUniform(u_transform, transform);
m_program->setUniform(u_time, m_timeCapability->time());
m_program->setUniform(u_numcubes, m_numCubes);
m_textures[0]->bindActive(GL_TEXTURE0);
m_textures[1]->bindActive(GL_TEXTURE1);
m_vao->drawElementsInstanced(GL_TRIANGLES, 18, GL_UNSIGNED_BYTE, nullptr, m_numCubes * m_numCubes);
m_program->release();
m_vao->unbind();
globjects::Framebuffer::unbind(GL_FRAMEBUFFER);
}
bool CubeScape::animation() const
{
return m_animation;
}
void CubeScape::setAnimation(const bool & enabled)
{
m_animation = enabled;
m_timeCapability->setEnabled(m_animation);
}
int CubeScape::numberOfCubes() const
{
return m_numCubes;
}
void CubeScape::setNumberOfCubes(const int & number)
{
m_numCubes = number;
}
void CubeScape::onTargetFramebufferChanged()
{
globjects::Framebuffer * fbo = m_targetFramebufferCapability->framebuffer();
if (!fbo)
{
fbo = globjects::Framebuffer::defaultFBO();
}
m_typedRenderTargetCapability->setRenderTarget(gloperate::RenderTargetType::Depth, fbo, gl::GLenum::GL_DEPTH_ATTACHMENT, gl::GLenum::GL_DEPTH_COMPONENT);
}
void CubeScape::randomize()
{
setNumberOfCubes(rand() % 40 + 1);
}
<|endoftext|> |
<commit_before>#include <spdlog/spdlog.h>
#include <Gateway.hh>
#include <Babble.hh>
#include <Authenticator.hh>
static const std::string welcomeMsg =
"\n\n"
" . . .. ............,.,...,.,..,...,.......... . \n"
" ......... ......,...,,,,,.,,,,,,,,,,,,...,.......... . . \n"
" .. .... ..........,..,,,,,,,,,,,,***,,,,,,,,,,.......... . \n"
" . ................,,,,,,,*****////////**,,,,,.,.......... . . \n"
" .. ......,......,.,,,,*,*****//((&@@&((//****,,,,,,,............ \n"
" ........,.......,,,,,,,*****/%@@@@#((((///******,*,,..,,............ . . \n"
" . .........,,,,,,,,******/@@@@@@@&%(((/////******,,,,.,,.......,... \n"
" . ........,.,,,,*********///((#&@@@@@@@@(///*****,,,,......... . .. . \n"
" . .............,,,,,,,,,****////(((#%@@@@@@@@@@@@///****,,*,,............ . . \n"
" . . ..........,,,,,,,,,,,****///((#@@@@@@@@@@@(((////***,,,,,,..,......... . \n"
" ..........,,,,,,,,,,,****//((#@@@@@@@@@@@###((((////******,,*,,,,......... . \n"
" . . .. ......,.,,,,,,,*****//(((#%@@@@@@@@@@@@#((((///*****,,*,,,.....,.... . \n"
" . .. .. ......,.,,,,,,*****///((#@@@@@@@@@@@@@@@@@@@#(((////***,,,,,,,.,,.... . . \n"
" . . .. . ....,.,,,,,,******//(#@@@@@@@@@@@@@@@@@@@@@@@#((///****,,,,,,,,......... . \n"
" ............,,,,,******//(#@@@@@@@@@@@@@@@@@@@@@@@@@%((//*****,,,,,...,.... . \n"
" . .. .........,,,,*****//(#@@@@@@@@@@@@@@@@@@@@@@@@@@@%(//*****,,,,,,....... \n"
" . . ...........,,,,,,****/((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(//*****,,,,.,...... .. \n"
" . . ...........,,,,,,***/(#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(//****,,,,,,....... \n"
" . .. ...........,,,,,,,***//(@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(//*****,,,.,..... .. \n"
" .. .........,.,,,,,***//(&@@@@@@@@@@@@@@@@@@@@@@@@@@@%(//*****,,,,,.......... \n"
" . ........,,,,,,****//(&@@@@@@@@@@@@@@@@@@@@@@@@@&(//****,,,,........... \n"
" ...........,,,,,****//(@@@@@@@@@@@@@@@@@@@@@@@@%///****,,,,,,........ \n"
" .. ...........,,,,,****///#@@@@@@@@@@@@@@@@@@@@&(//*****,,,,,........ \n"
" .. ..........,,,,,,****//((&@@@@@@@@@@@@@@@#(//*****,,,,.......... . \n"
" . ............,,,,,,,,*****///(#&@@@@@@&%(////*****,,,,,,,........ . \n"
" . ........,.,,,,,,,,,*******//////////*******,,,,,,,,,,.......... \n"
" .......,,,,,,,,,,,,,,*************,,,,,,,,,,,.......... . . \n\n"
"oooooooooooo .oooooo. . \n"
"`888' `8 d8P' `Y8b .o8 \n"
" 888 oooo ooo .oooo.o 888 .oooo. .o888oo .ooooo. oooo oooo ooo .oooo. oooo ooo \n"
" 888oooo8 `88. .8' d88( \"8 888 `P )88b 888 d88' `88b `88. `88. .8' `P )88b `88. .8' \n"
" 888 \" `88..8' `\"Y88b. 888 ooooo .oP\"888 888 888ooo888 `88..]88..8' .oP\"888 `88..8' \n"
" 888 `888' o. )88b `88. .88' d8( 888 888 . 888 .o `888'`888' d8( 888 `888' \n"
"o888o .8' 8\"\"888P' `Y8bood8P' `Y888\"\"8o \"888\" `Y8bod8P' `8' `8' `Y888\"\"8o .8' \n"
" .o..P' .o..P' \n"
" `Y8P' `Y8P' \n"
" \n\n\n";
void welcome(bool verbose) {
spdlog::set_async_mode(1024, spdlog::async_overflow_policy::discard_log_msg);
std::vector<spdlog::sink_ptr> sinks;
if (verbose) {
auto stdout_sink = spdlog::sinks::stdout_sink_mt::instance();
auto color_sink = std::make_shared<spdlog::sinks::ansicolor_sink>(stdout_sink);
sinks.push_back(color_sink);
}
auto sys_logger = std::make_shared<spdlog::logger>("c", begin(sinks), end(sinks));
#ifdef DEBUG_LEVEL
sys_logger->set_level(spdlog::level::debug);
#else
sys_logger->set_level(spdlog::level::debug);
#endif
spdlog::register_logger(sys_logger);
spdlog::set_pattern("[%x %H:%M:%S] [%t] [%l] %v");
sys_logger->info("Logger set to level {}\n>> log formatting>> [time] [thread] [logLevel] message logged", spdlog::get("c")->level());
spdlog::get("c")->info(welcomeMsg);
}
int main(int argc, const char * const *argv) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
fys::gateway::Context ctx(argc, argv);
welcome(ctx.isVerbose());
ctx.logContext();
fys::gateway::Gateway::start(ctx);
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
<commit_msg>fix spdlog<commit_after>#include <spdlog/spdlog.h>
#include <Gateway.hh>
#include <memory>
#include <Babble.hh>
#include <Authenticator.hh>
static const std::string welcomeMsg =
"\n\n"
" . . .. ............,.,...,.,..,...,.......... . \n"
" ......... ......,...,,,,,.,,,,,,,,,,,,...,.......... . . \n"
" .. .... ..........,..,,,,,,,,,,,,***,,,,,,,,,,.......... . \n"
" . ................,,,,,,,*****////////**,,,,,.,.......... . . \n"
" .. ......,......,.,,,,*,*****//((&@@&((//****,,,,,,,............ \n"
" ........,.......,,,,,,,*****/%@@@@#((((///******,*,,..,,............ . . \n"
" . .........,,,,,,,,******/@@@@@@@&%(((/////******,,,,.,,.......,... \n"
" . ........,.,,,,*********///((#&@@@@@@@@(///*****,,,,......... . .. . \n"
" . .............,,,,,,,,,****////(((#%@@@@@@@@@@@@///****,,*,,............ . . \n"
" . . ..........,,,,,,,,,,,****///((#@@@@@@@@@@@(((////***,,,,,,..,......... . \n"
" ..........,,,,,,,,,,,****//((#@@@@@@@@@@@###((((////******,,*,,,,......... . \n"
" . . .. ......,.,,,,,,,*****//(((#%@@@@@@@@@@@@#((((///*****,,*,,,.....,.... . \n"
" . .. .. ......,.,,,,,,*****///((#@@@@@@@@@@@@@@@@@@@#(((////***,,,,,,,.,,.... . . \n"
" . . .. . ....,.,,,,,,******//(#@@@@@@@@@@@@@@@@@@@@@@@#((///****,,,,,,,,......... . \n"
" ............,,,,,******//(#@@@@@@@@@@@@@@@@@@@@@@@@@%((//*****,,,,,...,.... . \n"
" . .. .........,,,,*****//(#@@@@@@@@@@@@@@@@@@@@@@@@@@@%(//*****,,,,,,....... \n"
" . . ...........,,,,,,****/((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(//*****,,,,.,...... .. \n"
" . . ...........,,,,,,***/(#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(//****,,,,,,....... \n"
" . .. ...........,,,,,,,***//(@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(//*****,,,.,..... .. \n"
" .. .........,.,,,,,***//(&@@@@@@@@@@@@@@@@@@@@@@@@@@@%(//*****,,,,,.......... \n"
" . ........,,,,,,****//(&@@@@@@@@@@@@@@@@@@@@@@@@@&(//****,,,,........... \n"
" ...........,,,,,****//(@@@@@@@@@@@@@@@@@@@@@@@@%///****,,,,,,........ \n"
" .. ...........,,,,,****///#@@@@@@@@@@@@@@@@@@@@&(//*****,,,,,........ \n"
" .. ..........,,,,,,****//((&@@@@@@@@@@@@@@@#(//*****,,,,.......... . \n"
" . ............,,,,,,,,*****///(#&@@@@@@&%(////*****,,,,,,,........ . \n"
" . ........,.,,,,,,,,,*******//////////*******,,,,,,,,,,.......... \n"
" .......,,,,,,,,,,,,,,*************,,,,,,,,,,,.......... . . \n\n"
"oooooooooooo .oooooo. . \n"
"`888' `8 d8P' `Y8b .o8 \n"
" 888 oooo ooo .oooo.o 888 .oooo. .o888oo .ooooo. oooo oooo ooo .oooo. oooo ooo \n"
" 888oooo8 `88. .8' d88( \"8 888 `P )88b 888 d88' `88b `88. `88. .8' `P )88b `88. .8' \n"
" 888 \" `88..8' `\"Y88b. 888 ooooo .oP\"888 888 888ooo888 `88..]88..8' .oP\"888 `88..8' \n"
" 888 `888' o. )88b `88. .88' d8( 888 888 . 888 .o `888'`888' d8( 888 `888' \n"
"o888o .8' 8\"\"888P' `Y8bood8P' `Y888\"\"8o \"888\" `Y8bod8P' `8' `8' `Y888\"\"8o .8' \n"
" .o..P' .o..P' \n"
" `Y8P' `Y8P' \n"
" \n\n\n";
void welcome(bool verbose) {
spdlog::set_async_mode(1024, spdlog::async_overflow_policy::discard_log_msg);
std::vector<spdlog::sink_ptr> sinks;
auto sys_logger = spdlog::stdout_color_mt("c");
#ifdef DEBUG_LEVEL
sys_logger->set_level(spdlog::level::debug);
#else
sys_logger->set_level(spdlog::level::debug);
#endif
// spdlog::register_logger(sys_logger);
spdlog::set_pattern("[%x %H:%M:%S] [%t] [%l] %v");
sys_logger->info("Logger set to level {}\n>> log formatting>> [time] [thread] [logLevel] message logged", spdlog::get("c")->level());
spdlog::get("c")->info(welcomeMsg);
}
int main(int argc, const char * const *argv) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
fys::gateway::Context ctx(argc, argv);
welcome(ctx.isVerbose());
ctx.logContext();
fys::gateway::Gateway::start(ctx);
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright 2021 The TensorFlow 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 "tensorflow/compiler/tf2tensorrt/convert/weights.h"
#include <functional>
#include <numeric>
#include "absl/strings/str_cat.h"
#include "tensorflow/compiler/tf2tensorrt/convert/utils.h"
#if GOOGLE_CUDA && GOOGLE_TENSORRT
namespace tensorflow {
namespace tensorrt {
namespace convert {
TRT_ShapedWeights::TRT_ShapedWeights(nvinfer1::DataType type)
: shape_(0, DimsAdapter::StorageType{}), type_(type), volume_(0) {}
StatusOr<TRT_ShapedWeights> TRT_ShapedWeights::CreateWithTensor(
nvinfer1::DataType type, DimsAdapter dims, Tensor tensor) {
TRT_ShapedWeights weights(type);
weights.shape_ = dims;
weights.tensor_ = std::forward<Tensor>(tensor);
weights.volume_ = weights.shape_.Volume();
if (weights.shape_.NumDims() == 0) {
DCHECK(weights.shape_.IsEmpty() || weights.shape_.IsScalar());
}
return weights;
}
nvinfer1::Weights TRT_ShapedWeights::GetTrtWeights() const {
return nvinfer1::Weights{type_, GetPointer<int8>(), volume_};
}
Status TRT_ShapedWeights::SetShape(DimsAdapter dims) {
if (volume_ != dims.Volume()) {
VLOG(2) << "Changing shape from " << shape_.DebugString() << ", to "
<< dims.DebugString();
return errors::Internal("SetShape would change number of elements");
}
shape_ = std::move(dims);
return OkStatus();
}
size_t TRT_ShapedWeights::size_bytes() const {
size_t data_type_size = -1;
switch (type_) {
case nvinfer1::DataType::kFLOAT:
case nvinfer1::DataType::kINT32:
data_type_size = 4;
break;
case nvinfer1::DataType::kHALF:
data_type_size = 2;
break;
#if IS_TRT_VERSION_GE(8, 5, 0, 0)
case nvinfer1::DataType::kUINT8:
#endif
case nvinfer1::DataType::kINT8:
case nvinfer1::DataType::kBOOL:
data_type_size = 1;
break;
}
return volume_ * data_type_size;
}
string TRT_ShapedWeights::DebugString() const {
return absl::StrCat(
"TRT_ShapedWeights(shape=", shape_.DebugString(),
", type=", tensorflow::tensorrt::DebugString(type_),
", values=", reinterpret_cast<uintptr_t>(GetPointer<int8>()), ")");
}
TRT_TensorOrWeights::TRT_TensorOrWeights(ITensorProxyPtr tensor)
: tensor_proxy_ptr_(tensor),
initialized_(true),
arg_type_(TRT_ArgumentType::TENSOR) {}
TRT_TensorOrWeights::TRT_TensorOrWeights(ITensorProxyPtr tensor, int batch_size)
: tensor_proxy_ptr_(tensor),
batch_size_(batch_size),
initialized_(true),
arg_type_(TRT_ArgumentType::TENSOR) {}
TRT_TensorOrWeights::TRT_TensorOrWeights(nvinfer1::ITensor* tensor,
int batch_size)
: tensor_proxy_ptr_(tensor),
batch_size_(batch_size),
initialized_(true),
arg_type_(TRT_ArgumentType::TENSOR) {}
TRT_TensorOrWeights::TRT_TensorOrWeights(nvinfer1::DataType trt_dtype,
const nvinfer1::Dims& trt_dims,
int batch_size)
: tensor_proxy_ptr_(new SimpleITensor(trt_dtype, trt_dims)),
batch_size_(batch_size),
initialized_(true),
arg_type_(TRT_ArgumentType::TENSOR) {}
TRT_TensorOrWeights::TRT_TensorOrWeights(const TRT_ShapedWeights& weights)
: weights_(weights),
initialized_(true),
arg_type_(TRT_ArgumentType::WEIGHTS) {}
TRT_TensorOrWeights::TRT_TensorOrWeights(const ResourceHandle& resource)
: resource_(resource),
initialized_(true),
arg_type_(TRT_ArgumentType::RESOURCE) {}
TRT_TensorOrWeights::TRT_TensorOrWeights(const TRT_TensorOrWeights& rhs)
: tensor_proxy_ptr_(rhs.tensor_proxy_ptr_),
batch_size_(rhs.batch_size_),
resource_(rhs.resource_),
weights_(rhs.weights_),
initialized_(rhs.initialized_),
arg_type_(rhs.arg_type_) {}
void TRT_TensorOrWeights::operator=(const TRT_TensorOrWeights& rhs) {
tensor_proxy_ptr_ = rhs.tensor_proxy_ptr_;
batch_size_ = rhs.batch_size_;
weights_ = rhs.weights_;
resource_ = rhs.resource_;
initialized_ = rhs.initialized_;
arg_type_ = rhs.arg_type_;
}
ITensorProxyPtr TRT_TensorOrWeights::tensor() const {
DCHECK(is_tensor());
return tensor_proxy_ptr_;
}
ResourceHandle TRT_TensorOrWeights::resource() const {
DCHECK(is_resource());
return resource_;
}
nvinfer1::Dims TRT_TensorOrWeights::GetTrtDims() const {
switch (arg_type_) {
case TRT_ArgumentType::TENSOR:
return tensor()->getDimensions();
case TRT_ArgumentType::WEIGHTS:
return weights().Shape().AsTrtDims();
case TRT_ArgumentType::RESOURCE:
return {0, {}}; // Scalar.
}
}
Status TRT_TensorOrWeights::GetTfType(DataType* tf_type) const {
if (!initialized_) {
return errors::Internal("The object is not initialized");
}
switch (arg_type_) {
case TRT_ArgumentType::TENSOR: {
nvinfer1::DataType trt_type = tensor()->getType();
return TrtTypeToTfType(trt_type, tf_type);
}
case TRT_ArgumentType::WEIGHTS:
*tf_type = weights().GetTensor().dtype();
return OkStatus();
case TRT_ArgumentType::RESOURCE:
*tf_type = DataType::DT_RESOURCE;
return OkStatus();
}
}
string TRT_TensorOrWeights::DebugString() const {
string output = "TRT_TensorOrWeights(type=";
if (is_tensor()) {
absl::StrAppend(&output,
"tensor=", tensorflow::tensorrt::DebugString(tensor()),
", batch_size=", batch_size_);
} else {
absl::StrAppend(&output, "weights=", weights_.DebugString());
}
absl::StrAppend(&output, ")");
return output;
}
StatusOr<TRT_ShapedWeights> TrtWeightStore::GetTempWeights(
nvinfer1::DataType trt_dtype, const DimsAdapter& dims) {
DataType tf_dtype;
TF_RETURN_IF_ERROR(TrtTypeToTfType(trt_dtype, &tf_dtype));
TensorShape shape;
TF_RETURN_IF_ERROR(dims.TensorShape(&shape));
// TODO(jie): check weights size_bytes. 0 means type error
Tensor tensor(tf_dtype, shape);
StatusOr<TRT_ShapedWeights> weights =
TRT_ShapedWeights::CreateWithTensor(trt_dtype, dims, tensor);
TRT_ENSURE_OK(weights);
store_.emplace_back(std::move(tensor));
return weights;
}
} // namespace convert
} // namespace tensorrt
} // namespace tensorflow
#endif // GOOGLE_CUDA && GOOGLE_TENSORRT
<commit_msg>Hotfix tftrt compile error<commit_after>/* Copyright 2021 The TensorFlow 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 "tensorflow/compiler/tf2tensorrt/convert/weights.h"
#include <functional>
#include <numeric>
#include "absl/strings/str_cat.h"
#include "tensorflow/compiler/tf2tensorrt/convert/utils.h"
#if GOOGLE_CUDA && GOOGLE_TENSORRT
namespace tensorflow {
namespace tensorrt {
namespace convert {
TRT_ShapedWeights::TRT_ShapedWeights(nvinfer1::DataType type)
: shape_(0, DimsAdapter::StorageType{}), type_(type), volume_(0) {}
StatusOr<TRT_ShapedWeights> TRT_ShapedWeights::CreateWithTensor(
nvinfer1::DataType type, DimsAdapter dims, Tensor tensor) {
TRT_ShapedWeights weights(type);
weights.shape_ = dims;
weights.tensor_ = std::forward<Tensor>(tensor);
weights.volume_ = weights.shape_.Volume();
if (weights.shape_.NumDims() == 0) {
DCHECK(weights.shape_.IsEmpty() || weights.shape_.IsScalar());
}
return weights;
}
nvinfer1::Weights TRT_ShapedWeights::GetTrtWeights() const {
return nvinfer1::Weights{type_, GetPointer<int8>(), volume_};
}
Status TRT_ShapedWeights::SetShape(DimsAdapter dims) {
if (volume_ != dims.Volume()) {
VLOG(2) << "Changing shape from " << shape_.DebugString() << ", to "
<< dims.DebugString();
return errors::Internal("SetShape would change number of elements");
}
shape_ = std::move(dims);
return OkStatus();
}
size_t TRT_ShapedWeights::size_bytes() const {
size_t data_type_size = -1;
switch (type_) {
case nvinfer1::DataType::kFLOAT:
case nvinfer1::DataType::kINT32:
data_type_size = 4;
break;
case nvinfer1::DataType::kHALF:
data_type_size = 2;
break;
#if IS_TRT_VERSION_GE(8, 5, 0, 0)
case nvinfer1::DataType::kUINT8:
#endif
case nvinfer1::DataType::kINT8:
case nvinfer1::DataType::kBOOL:
data_type_size = 1;
break;
default: break;
}
return volume_ * data_type_size;
}
string TRT_ShapedWeights::DebugString() const {
return absl::StrCat(
"TRT_ShapedWeights(shape=", shape_.DebugString(),
", type=", tensorflow::tensorrt::DebugString(type_),
", values=", reinterpret_cast<uintptr_t>(GetPointer<int8>()), ")");
}
TRT_TensorOrWeights::TRT_TensorOrWeights(ITensorProxyPtr tensor)
: tensor_proxy_ptr_(tensor),
initialized_(true),
arg_type_(TRT_ArgumentType::TENSOR) {}
TRT_TensorOrWeights::TRT_TensorOrWeights(ITensorProxyPtr tensor, int batch_size)
: tensor_proxy_ptr_(tensor),
batch_size_(batch_size),
initialized_(true),
arg_type_(TRT_ArgumentType::TENSOR) {}
TRT_TensorOrWeights::TRT_TensorOrWeights(nvinfer1::ITensor* tensor,
int batch_size)
: tensor_proxy_ptr_(tensor),
batch_size_(batch_size),
initialized_(true),
arg_type_(TRT_ArgumentType::TENSOR) {}
TRT_TensorOrWeights::TRT_TensorOrWeights(nvinfer1::DataType trt_dtype,
const nvinfer1::Dims& trt_dims,
int batch_size)
: tensor_proxy_ptr_(new SimpleITensor(trt_dtype, trt_dims)),
batch_size_(batch_size),
initialized_(true),
arg_type_(TRT_ArgumentType::TENSOR) {}
TRT_TensorOrWeights::TRT_TensorOrWeights(const TRT_ShapedWeights& weights)
: weights_(weights),
initialized_(true),
arg_type_(TRT_ArgumentType::WEIGHTS) {}
TRT_TensorOrWeights::TRT_TensorOrWeights(const ResourceHandle& resource)
: resource_(resource),
initialized_(true),
arg_type_(TRT_ArgumentType::RESOURCE) {}
TRT_TensorOrWeights::TRT_TensorOrWeights(const TRT_TensorOrWeights& rhs)
: tensor_proxy_ptr_(rhs.tensor_proxy_ptr_),
batch_size_(rhs.batch_size_),
resource_(rhs.resource_),
weights_(rhs.weights_),
initialized_(rhs.initialized_),
arg_type_(rhs.arg_type_) {}
void TRT_TensorOrWeights::operator=(const TRT_TensorOrWeights& rhs) {
tensor_proxy_ptr_ = rhs.tensor_proxy_ptr_;
batch_size_ = rhs.batch_size_;
weights_ = rhs.weights_;
resource_ = rhs.resource_;
initialized_ = rhs.initialized_;
arg_type_ = rhs.arg_type_;
}
ITensorProxyPtr TRT_TensorOrWeights::tensor() const {
DCHECK(is_tensor());
return tensor_proxy_ptr_;
}
ResourceHandle TRT_TensorOrWeights::resource() const {
DCHECK(is_resource());
return resource_;
}
nvinfer1::Dims TRT_TensorOrWeights::GetTrtDims() const {
switch (arg_type_) {
case TRT_ArgumentType::TENSOR:
return tensor()->getDimensions();
case TRT_ArgumentType::WEIGHTS:
return weights().Shape().AsTrtDims();
case TRT_ArgumentType::RESOURCE:
return {0, {}}; // Scalar.
}
}
Status TRT_TensorOrWeights::GetTfType(DataType* tf_type) const {
if (!initialized_) {
return errors::Internal("The object is not initialized");
}
switch (arg_type_) {
case TRT_ArgumentType::TENSOR: {
nvinfer1::DataType trt_type = tensor()->getType();
return TrtTypeToTfType(trt_type, tf_type);
}
case TRT_ArgumentType::WEIGHTS:
*tf_type = weights().GetTensor().dtype();
return OkStatus();
case TRT_ArgumentType::RESOURCE:
*tf_type = DataType::DT_RESOURCE;
return OkStatus();
}
}
string TRT_TensorOrWeights::DebugString() const {
string output = "TRT_TensorOrWeights(type=";
if (is_tensor()) {
absl::StrAppend(&output,
"tensor=", tensorflow::tensorrt::DebugString(tensor()),
", batch_size=", batch_size_);
} else {
absl::StrAppend(&output, "weights=", weights_.DebugString());
}
absl::StrAppend(&output, ")");
return output;
}
StatusOr<TRT_ShapedWeights> TrtWeightStore::GetTempWeights(
nvinfer1::DataType trt_dtype, const DimsAdapter& dims) {
DataType tf_dtype;
TF_RETURN_IF_ERROR(TrtTypeToTfType(trt_dtype, &tf_dtype));
TensorShape shape;
TF_RETURN_IF_ERROR(dims.TensorShape(&shape));
// TODO(jie): check weights size_bytes. 0 means type error
Tensor tensor(tf_dtype, shape);
StatusOr<TRT_ShapedWeights> weights =
TRT_ShapedWeights::CreateWithTensor(trt_dtype, dims, tensor);
TRT_ENSURE_OK(weights);
store_.emplace_back(std::move(tensor));
return weights;
}
} // namespace convert
} // namespace tensorrt
} // namespace tensorflow
#endif // GOOGLE_CUDA && GOOGLE_TENSORRT
<|endoftext|> |
<commit_before>// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "syzygy/kasko/reporter.h"
#include <Windows.h> // NOLINT
#include <Dbgeng.h>
#include <Rpc.h>
#include <set>
#include <string>
#include "base/bind.h"
#include "base/callback.h"
#include "base/file_util.h"
#include "base/location.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_path_watcher.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/time/time.h"
#include "gtest/gtest.h"
#include "syzygy/common/rpc/helpers.h"
#include "syzygy/kasko/crash_keys_serialization.h"
#include "syzygy/kasko/kasko_rpc.h"
#include "syzygy/kasko/testing/minidump_unittest_helpers.h"
#include "syzygy/kasko/testing/test_server.h"
// The test server will respond to POSTs to /crash by writing all parameters to
// a report directory. Each file in the directory has the name of a parameter
// and the parameter value as its contents.
//
// This test instantiates a reporter process, points it at a test server, and
// then monitors the server's "incoming" director for new files named
// Reporter::kMinidumpUploadFilePart.
namespace kasko {
namespace {
// Invokes the diagnostic report RPC service at |endpoint|, requesting a dump of
// the current process, and including |protobuf|.
void DoInvokeService(const base::string16& endpoint,
const std::string& protobuf) {
common::rpc::ScopedRpcBinding rpc_binding;
ASSERT_TRUE(rpc_binding.Open(L"ncalrpc", endpoint));
common::rpc::RpcStatus status = common::rpc::InvokeRpc(
KaskoClient_SendDiagnosticReport, rpc_binding.Get(), NULL, 0,
protobuf.length(),
reinterpret_cast<const signed char*>(protobuf.c_str()));
ASSERT_FALSE(status.exception_occurred);
ASSERT_TRUE(status.succeeded());
}
// Verifies that the uploaded minidump is plausibly a dump of this test process.
void ValidateMinidump(IDebugClient4* debug_client,
IDebugControl* debug_control,
IDebugSymbols* debug_symbols) {
ASSERT_HRESULT_SUCCEEDED(
debug_symbols->GetModuleByModuleName("kasko_unittests", 0, NULL, NULL));
}
// Observes changes to the test server's 'incoming' directory. Notifications do
// not specify the individual file changed; for each notification we must scan
// for new minidump files. Once one is found, we verify that it is plausibly a
// crash report from this process and then quit the current message loop.
void WatchForUpload(const base::FilePath& path, bool error) {
if (error) {
ADD_FAILURE() << "Failure in path watching.";
base::MessageLoop::current()->Quit();
return;
}
base::FileEnumerator enumerator(path, true, base::FileEnumerator::FILES);
for (base::FilePath candidate = enumerator.Next(); !candidate.empty();
candidate = enumerator.Next()) {
if (candidate.BaseName() !=
base::FilePath(Reporter::kMinidumpUploadFilePart)) {
continue;
}
EXPECT_HRESULT_SUCCEEDED(
testing::VisitMinidump(candidate, base::Bind(&ValidateMinidump)));
base::MessageLoop::current()->Quit();
}
}
// Observes changes to the permanent failure destination. Once a complete report
// is found, validates that the report is plausibly a crash report from this
// process and then quits the current message loop.
void WatchForPermanentFailure(const base::FilePath& path, bool error) {
if (error) {
ADD_FAILURE() << "Failure in path watching.";
base::MessageLoop::current()->Quit();
return;
}
base::FileEnumerator enumerator(path, true, base::FileEnumerator::FILES);
for (base::FilePath candidate = enumerator.Next(); !candidate.empty();
candidate = enumerator.Next()) {
LOG(ERROR) << "Candidate: " << candidate.value();
if (candidate.FinalExtension() !=
Reporter::kPermanentFailureMinidumpExtension) {
LOG(ERROR) << "0";
continue;
}
base::FilePath crash_keys_file = candidate.ReplaceExtension(
Reporter::kPermanentFailureCrashKeysExtension);
if (!base::PathExists(crash_keys_file)) {
LOG(ERROR) << "No crash keys at " << crash_keys_file.value();
continue;
}
EXPECT_HRESULT_SUCCEEDED(
testing::VisitMinidump(candidate, base::Bind(&ValidateMinidump)));
std::map<base::string16, base::string16> crash_keys;
EXPECT_TRUE(ReadCrashKeysFromFile(crash_keys_file, &crash_keys));
base::MessageLoop::current()->Quit();
}
}
// Starts watching |path| using |watcher|. Must be invoked inside the IO message
// loop. |callback| will be invoked when a change to |path| or its contents is
// detected.
void StartWatch(base::FilePathWatcher* watcher,
const base::FilePath& path,
const base::FilePathWatcher::Callback& callback) {
if (!watcher->Watch(path, true, callback)) {
ADD_FAILURE() << "Failed to initiate file path watch.";
base::MessageLoop::current()->Quit();
return;
}
}
} // namespace
TEST(ReporterTest, BasicTest) {
testing::TestServer server;
ASSERT_TRUE(server.Start());
base::ScopedTempDir data_directory;
base::ScopedTempDir permanent_failure_directory;
ASSERT_TRUE(data_directory.CreateUniqueTempDir());
ASSERT_TRUE(permanent_failure_directory.CreateUniqueTempDir());
scoped_ptr<Reporter> instance(Reporter::Create(
L"test_endpoint",
L"http://127.0.0.1:" + base::UintToString16(server.port()) + L"/crash",
data_directory.path(), permanent_failure_directory.path(),
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromMilliseconds(1)));
ASSERT_TRUE(instance);
base::FilePathWatcher watcher;
base::MessageLoop watcher_loop(base::MessageLoop::TYPE_IO);
watcher_loop.PostTask(
FROM_HERE, base::Bind(&DoInvokeService, base::string16(L"test_endpoint"),
std::string("protobuf")));
watcher_loop.PostTask(
FROM_HERE,
base::Bind(&StartWatch, base::Unretained(&watcher),
server.incoming_directory(), base::Bind(&WatchForUpload)));
watcher_loop.Run();
Reporter::Shutdown(instance.Pass());
}
TEST(ReporterTest, PermanentFailureTest) {
testing::TestServer server;
ASSERT_TRUE(server.Start());
base::ScopedTempDir data_directory;
base::ScopedTempDir permanent_failure_directory;
ASSERT_TRUE(data_directory.CreateUniqueTempDir());
ASSERT_TRUE(permanent_failure_directory.CreateUniqueTempDir());
scoped_ptr<Reporter> instance(Reporter::Create(
L"test_endpoint",
L"http://127.0.0.1:" + base::UintToString16(server.port()) +
L"/crash_failure",
data_directory.path(), permanent_failure_directory.path(),
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromMilliseconds(1)));
ASSERT_TRUE(instance);
base::FilePathWatcher watcher;
base::MessageLoop watcher_loop(base::MessageLoop::TYPE_IO);
watcher_loop.PostTask(
FROM_HERE, base::Bind(&DoInvokeService, base::string16(L"test_endpoint"),
std::string("protobuf")));
watcher_loop.PostTask(FROM_HERE,
base::Bind(&StartWatch, base::Unretained(&watcher),
permanent_failure_directory.path(),
base::Bind(&WatchForPermanentFailure)));
watcher_loop.Run();
Reporter::Shutdown(instance.Pass());
}
} // namespace kasko
<commit_msg>Disable two flaky tests.<commit_after>// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "syzygy/kasko/reporter.h"
#include <Windows.h> // NOLINT
#include <Dbgeng.h>
#include <Rpc.h>
#include <set>
#include <string>
#include "base/bind.h"
#include "base/callback.h"
#include "base/file_util.h"
#include "base/location.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_path_watcher.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/time/time.h"
#include "gtest/gtest.h"
#include "syzygy/common/rpc/helpers.h"
#include "syzygy/kasko/crash_keys_serialization.h"
#include "syzygy/kasko/kasko_rpc.h"
#include "syzygy/kasko/testing/minidump_unittest_helpers.h"
#include "syzygy/kasko/testing/test_server.h"
// The test server will respond to POSTs to /crash by writing all parameters to
// a report directory. Each file in the directory has the name of a parameter
// and the parameter value as its contents.
//
// This test instantiates a reporter process, points it at a test server, and
// then monitors the server's "incoming" director for new files named
// Reporter::kMinidumpUploadFilePart.
namespace kasko {
namespace {
// Invokes the diagnostic report RPC service at |endpoint|, requesting a dump of
// the current process, and including |protobuf|.
void DoInvokeService(const base::string16& endpoint,
const std::string& protobuf) {
common::rpc::ScopedRpcBinding rpc_binding;
ASSERT_TRUE(rpc_binding.Open(L"ncalrpc", endpoint));
common::rpc::RpcStatus status = common::rpc::InvokeRpc(
KaskoClient_SendDiagnosticReport, rpc_binding.Get(), NULL, 0,
protobuf.length(),
reinterpret_cast<const signed char*>(protobuf.c_str()));
ASSERT_FALSE(status.exception_occurred);
ASSERT_TRUE(status.succeeded());
}
// Verifies that the uploaded minidump is plausibly a dump of this test process.
void ValidateMinidump(IDebugClient4* debug_client,
IDebugControl* debug_control,
IDebugSymbols* debug_symbols) {
ASSERT_HRESULT_SUCCEEDED(
debug_symbols->GetModuleByModuleName("kasko_unittests", 0, NULL, NULL));
}
// Observes changes to the test server's 'incoming' directory. Notifications do
// not specify the individual file changed; for each notification we must scan
// for new minidump files. Once one is found, we verify that it is plausibly a
// crash report from this process and then quit the current message loop.
void WatchForUpload(const base::FilePath& path, bool error) {
if (error) {
ADD_FAILURE() << "Failure in path watching.";
base::MessageLoop::current()->Quit();
return;
}
base::FileEnumerator enumerator(path, true, base::FileEnumerator::FILES);
for (base::FilePath candidate = enumerator.Next(); !candidate.empty();
candidate = enumerator.Next()) {
if (candidate.BaseName() !=
base::FilePath(Reporter::kMinidumpUploadFilePart)) {
continue;
}
EXPECT_HRESULT_SUCCEEDED(
testing::VisitMinidump(candidate, base::Bind(&ValidateMinidump)));
base::MessageLoop::current()->Quit();
}
}
// Observes changes to the permanent failure destination. Once a complete report
// is found, validates that the report is plausibly a crash report from this
// process and then quits the current message loop.
void WatchForPermanentFailure(const base::FilePath& path, bool error) {
if (error) {
ADD_FAILURE() << "Failure in path watching.";
base::MessageLoop::current()->Quit();
return;
}
base::FileEnumerator enumerator(path, true, base::FileEnumerator::FILES);
for (base::FilePath candidate = enumerator.Next(); !candidate.empty();
candidate = enumerator.Next()) {
LOG(ERROR) << "Candidate: " << candidate.value();
if (candidate.FinalExtension() !=
Reporter::kPermanentFailureMinidumpExtension) {
LOG(ERROR) << "0";
continue;
}
base::FilePath crash_keys_file = candidate.ReplaceExtension(
Reporter::kPermanentFailureCrashKeysExtension);
if (!base::PathExists(crash_keys_file)) {
LOG(ERROR) << "No crash keys at " << crash_keys_file.value();
continue;
}
EXPECT_HRESULT_SUCCEEDED(
testing::VisitMinidump(candidate, base::Bind(&ValidateMinidump)));
std::map<base::string16, base::string16> crash_keys;
EXPECT_TRUE(ReadCrashKeysFromFile(crash_keys_file, &crash_keys));
base::MessageLoop::current()->Quit();
}
}
// Starts watching |path| using |watcher|. Must be invoked inside the IO message
// loop. |callback| will be invoked when a change to |path| or its contents is
// detected.
void StartWatch(base::FilePathWatcher* watcher,
const base::FilePath& path,
const base::FilePathWatcher::Callback& callback) {
if (!watcher->Watch(path, true, callback)) {
ADD_FAILURE() << "Failed to initiate file path watch.";
base::MessageLoop::current()->Quit();
return;
}
}
} // namespace
TEST(ReporterTest, DISABLED_BasicTest) {
testing::TestServer server;
ASSERT_TRUE(server.Start());
base::ScopedTempDir data_directory;
base::ScopedTempDir permanent_failure_directory;
ASSERT_TRUE(data_directory.CreateUniqueTempDir());
ASSERT_TRUE(permanent_failure_directory.CreateUniqueTempDir());
scoped_ptr<Reporter> instance(Reporter::Create(
L"test_endpoint",
L"http://127.0.0.1:" + base::UintToString16(server.port()) + L"/crash",
data_directory.path(), permanent_failure_directory.path(),
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromMilliseconds(1)));
ASSERT_TRUE(instance);
base::FilePathWatcher watcher;
base::MessageLoop watcher_loop(base::MessageLoop::TYPE_IO);
watcher_loop.PostTask(
FROM_HERE, base::Bind(&DoInvokeService, base::string16(L"test_endpoint"),
std::string("protobuf")));
watcher_loop.PostTask(
FROM_HERE,
base::Bind(&StartWatch, base::Unretained(&watcher),
server.incoming_directory(), base::Bind(&WatchForUpload)));
watcher_loop.Run();
Reporter::Shutdown(instance.Pass());
}
TEST(ReporterTest, DISABLED_PermanentFailureTest) {
testing::TestServer server;
ASSERT_TRUE(server.Start());
base::ScopedTempDir data_directory;
base::ScopedTempDir permanent_failure_directory;
ASSERT_TRUE(data_directory.CreateUniqueTempDir());
ASSERT_TRUE(permanent_failure_directory.CreateUniqueTempDir());
scoped_ptr<Reporter> instance(Reporter::Create(
L"test_endpoint",
L"http://127.0.0.1:" + base::UintToString16(server.port()) +
L"/crash_failure",
data_directory.path(), permanent_failure_directory.path(),
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromMilliseconds(1)));
ASSERT_TRUE(instance);
base::FilePathWatcher watcher;
base::MessageLoop watcher_loop(base::MessageLoop::TYPE_IO);
watcher_loop.PostTask(
FROM_HERE, base::Bind(&DoInvokeService, base::string16(L"test_endpoint"),
std::string("protobuf")));
watcher_loop.PostTask(FROM_HERE,
base::Bind(&StartWatch, base::Unretained(&watcher),
permanent_failure_directory.path(),
base::Bind(&WatchForPermanentFailure)));
watcher_loop.Run();
Reporter::Shutdown(instance.Pass());
}
} // namespace kasko
<|endoftext|> |
<commit_before>/*! @file crp.cc
* @brief Chroma DCT-Reduced Log Pitch calculation.
* @author Markovtsev Vadim <[email protected]>
* @version 1.0
*
* @section Notes
* This code partially conforms to <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml">Google C++ Style Guide</a>.
*
* @section Copyright
* Copyright 2013 Samsung R&D Institute Russia
*/
#include <gtest/gtest.h>
#include "src/transform_tree.h"
#include "src/transform_registry.h"
#include "src/formats/array_format.h"
#include "tests/speech_sample.inc"
using sound_feature_extraction::TransformTree;
using sound_feature_extraction::BuffersBase;
TEST(Features, CRP) {
TransformTree tt( { 48000, 22050 } );
tt.set_validate_after_each_transform(true);
tt.AddFeature("CRP", { { "Window", "length=4096,step=2048" },{ "RDFT", "" },
{ "SpectralEnergy", "" }, { "FilterBank", "type=midi,number=100,"
"frequency_min=7.946364,frequency_max=8137.0754,squared=true" },
{ "Log", "add1=true,scale=1000" }, { "DCT", "" },
{ "Selector", "select=70,from=right" }, { "IDCT", "" },
{ "Reorder", "algorithm=chroma" },
{ "Stats", "types=average,interval=10" }
});
int16_t* buffers = new int16_t[48000];
memcpy(buffers, data, sizeof(data));
tt.PrepareForExecution();
auto res = tt.Execute(buffers);
delete[] buffers;
ASSERT_EQ(1U, res.size());
res["CRP"]->Validate();
tt.Dump("/tmp/crp.dot");
auto report = tt.ExecutionTimeReport();
for (auto r : report) {
printf("%s:\t%f\n", r.first.c_str(), r.second);
}
}
#include "tests/google/src/gtest_main.cc"
<commit_msg>Fixed bug in CRP test<commit_after>/*! @file crp.cc
* @brief Chroma DCT-Reduced Log Pitch calculation.
* @author Markovtsev Vadim <[email protected]>
* @version 1.0
*
* @section Notes
* This code partially conforms to <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml">Google C++ Style Guide</a>.
*
* @section Copyright
* Copyright 2013 Samsung R&D Institute Russia
*/
#include <gtest/gtest.h>
#include "src/transform_tree.h"
#include "src/transform_registry.h"
#include "src/formats/array_format.h"
#include "tests/speech_sample.inc"
using sound_feature_extraction::TransformTree;
using sound_feature_extraction::BuffersBase;
TEST(Features, CRP) {
TransformTree tt( { 48000, 22050 } );
tt.set_validate_after_each_transform(true);
tt.AddFeature("CRP", { { "Window", "length=4096,step=2048" },{ "RDFT", "" },
{ "SpectralEnergy", "" }, { "FilterBank", "type=midi,number=108,"
"frequency_min=7.946364,frequency_max=8137.0754,squared=true" },
{ "Log", "add1=true,scale=1000" }, { "DCT", "" },
{ "Selector", "select=70,from=right" }, { "IDCT", "" },
{ "Reorder", "algorithm=chroma" },
{ "Stats", "types=average,interval=10" }
});
int16_t* buffers = new int16_t[48000];
memcpy(buffers, data, sizeof(data));
tt.PrepareForExecution();
auto res = tt.Execute(buffers);
delete[] buffers;
ASSERT_EQ(1U, res.size());
res["CRP"]->Validate();
tt.Dump("/tmp/crp.dot");
auto report = tt.ExecutionTimeReport();
for (auto r : report) {
printf("%s:\t%f\n", r.first.c_str(), r.second);
}
}
#include "tests/google/src/gtest_main.cc"
<|endoftext|> |
<commit_before>/**
* \file
* \brief StaticThread class header
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-11-11
*/
#ifndef INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#define INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#include "distortos/Thread.hpp"
namespace distortos
{
/**
* \brief StaticThread class is a templated interface for thread that has automatic storage of stack.
*
* \param StackSize is the size of stack, bytes
* \param Function is the function that will be executed in separate thread
* \param Args are the arguments for Function
*/
template<size_t StackSize, typename Function, typename... Args>
class StaticThread : private Thread<Function, Args...>
{
public:
/// base of StaticThread
using Base = Thread<Function, Args...>;
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, Function&& function, Args&&... args) :
Base{&stack_, sizeof(stack_), priority, std::forward<Function>(function), std::forward<Args>(args)...}
{
}
using Base::getEffectivePriority;
using Base::getPriority;
using Base::join;
using Base::setPriority;
using Base::start;
private:
/// stack buffer
typename std::aligned_storage<StackSize>::type stack_;
};
/**
* \brief Helper factory function to make StaticThread object with partially deduced template arguments
*
* \param StackSize is the size of stack, bytes
* \param Function is the function that will be executed
* \param Args are the arguments for Function
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*
* \return StaticThread object with partially deduced template arguments
*/
template<size_t StackSize, typename Function, typename... Args>
StaticThread<StackSize, Function, Args...> makeStaticThread(const uint8_t priority, Function&& function, Args&&... args)
{
return {priority, std::forward<Function>(function), std::forward<Args>(args)...};
}
} // namespace distortos
#endif // INCLUDE_DISTORTOS_STATICTHREAD_HPP_
<commit_msg>StaticThread: expose ThreadControlBlock::getSchedulingPolicy() and ThreadControlBlock::setSchedulingPolicy()<commit_after>/**
* \file
* \brief StaticThread class header
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-11-16
*/
#ifndef INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#define INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#include "distortos/Thread.hpp"
namespace distortos
{
/**
* \brief StaticThread class is a templated interface for thread that has automatic storage of stack.
*
* \param StackSize is the size of stack, bytes
* \param Function is the function that will be executed in separate thread
* \param Args are the arguments for Function
*/
template<size_t StackSize, typename Function, typename... Args>
class StaticThread : private Thread<Function, Args...>
{
public:
/// base of StaticThread
using Base = Thread<Function, Args...>;
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, Function&& function, Args&&... args) :
Base{&stack_, sizeof(stack_), priority, std::forward<Function>(function), std::forward<Args>(args)...}
{
}
using Base::getEffectivePriority;
using Base::getPriority;
using Base::getSchedulingPolicy;
using Base::join;
using Base::setPriority;
using Base::setSchedulingPolicy;
using Base::start;
private:
/// stack buffer
typename std::aligned_storage<StackSize>::type stack_;
};
/**
* \brief Helper factory function to make StaticThread object with partially deduced template arguments
*
* \param StackSize is the size of stack, bytes
* \param Function is the function that will be executed
* \param Args are the arguments for Function
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*
* \return StaticThread object with partially deduced template arguments
*/
template<size_t StackSize, typename Function, typename... Args>
StaticThread<StackSize, Function, Args...> makeStaticThread(const uint8_t priority, Function&& function, Args&&... args)
{
return {priority, std::forward<Function>(function), std::forward<Args>(args)...};
}
} // namespace distortos
#endif // INCLUDE_DISTORTOS_STATICTHREAD_HPP_
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, 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 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: Dan Greenwalducan */
#include <moveit/warehouse/planning_scene_storage.h>
#include <moveit/warehouse/constraints_storage.h>
#include <moveit/warehouse/state_storage.h>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
#include <boost/algorithm/string/join.hpp>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <ros/ros.h>
#include <moveit_msgs/SaveRobotStateToWarehouse.h>
#include <moveit_msgs/ListRobotStatesInWarehouse.h>
#include <moveit_msgs/GetRobotStateFromWarehouse.h>
#include <moveit_msgs/CheckIfRobotStateExistsInWarehouse.h>
static const std::string ROBOT_DESCRIPTION="robot_description";
bool store_state(moveit_msgs::SaveRobotStateToWarehouse::Request& request,
moveit_msgs::SaveRobotStateToWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
const moveit_msgs::RobotState& state = request.state;
if ("" == request.name)
{
ROS_ERROR("You must specify a name to store a state");
return response.success = false;
}
rs->addRobotState(request.state, request.name, request.robot);
return response.success = true;
}
bool list_states(moveit_msgs::ListRobotStatesInWarehouse::Request& request,
moveit_msgs::ListRobotStatesInWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
if ("" == request.regex)
{
rs->getKnownRobotStates(response.states, request.robot);
}
else
{
rs->getKnownRobotStates(request.regex, response.states, request.robot);
}
return true;
}
bool has_state(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request& request,
moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
response.exists = rs->hasRobotState(request.name, request.robot);
return true;
}
bool get_state(moveit_msgs::GetRobotStateFromWarehouse::Request& request,
moveit_msgs::GetRobotStateFromWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
moveit_warehouse::RobotStateWithMetadata state_buffer;
rs->getRobotState(state_buffer, request.name, request.robot);
response.state = static_cast<const moveit_msgs::RobotState&>(*state_buffer);
return true;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "moveit_warehouse_services");
boost::program_options::options_description desc;
desc.add_options()
("help", "Show help message")
("host", boost::program_options::value<std::string>(), "Host for the MongoDB.")
("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.");
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
boost::program_options::notify(vm);
if (vm.count("help"))
{
std::cout << desc << std::endl;
return 1;
}
ros::AsyncSpinner spinner(1);
spinner.start();
moveit_warehouse::RobotStateStorage rs;
std::string host = vm.count("host") ? vm["host"].as<std::string>() : "";
std::size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0;
try
{
rs = moveit_warehouse::RobotStateStorage(host, port);
}
catch (...)
{
ROS_FATAL_STREAM("Couldn't connect to MongoDB on " << host << ":" << port);
return -1;
}
std::vector<std::string> names;
rs.getKnownRobotStates(names);
if (names.empty())
ROS_INFO("There are no previously stored robot states");
else
{
ROS_INFO("Previously stored robot states:");
for (std::size_t i = 0 ; i < names.size() ; ++i)
ROS_INFO(" * %s", names[i].c_str());
}
boost::function<bool(moveit_msgs::SaveRobotStateToWarehouse::Request& request,
moveit_msgs::SaveRobotStateToWarehouse::Response& response)>
save_cb = boost::bind(&store_state, _1, _2, &rs);
boost::function<bool(moveit_msgs::ListRobotStatesInWarehouse::Request& request,
moveit_msgs::ListRobotStatesInWarehouse::Response& response)>
list_cb = boost::bind(&list_states, _1, _2, &rs);
boost::function<bool(moveit_msgs::GetRobotStateFromWarehouse::Request& request,
moveit_msgs::GetRobotStateFromWarehouse::Response& response)>
get_cb = boost::bind(&get_state, _1, _2, &rs);
boost::function<bool(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request& request,
moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response)>
has_cb = boost::bind(&has_state, _1, _2, &rs);
ros::NodeHandle node("~");
ros::ServiceServer save_state_server = node.advertiseService("save_robot_state", save_cb);
ros::ServiceServer list_states_server = node.advertiseService("list_robot_states", list_cb);
ros::ServiceServer get_state_server = node.advertiseService("get_robot_state", get_cb);
ros::ServiceServer has_state_server = node.advertiseService("has_robot_state", has_cb);
ros::waitForShutdown();
return 0;
}
<commit_msg>now takes port + host from param server<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, 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 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: Dan Greenwald */
#include <moveit/warehouse/state_storage.h>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <ros/ros.h>
#include <moveit_msgs/SaveRobotStateToWarehouse.h>
#include <moveit_msgs/ListRobotStatesInWarehouse.h>
#include <moveit_msgs/GetRobotStateFromWarehouse.h>
#include <moveit_msgs/CheckIfRobotStateExistsInWarehouse.h>
static const std::string ROBOT_DESCRIPTION="robot_description";
bool store_state(moveit_msgs::SaveRobotStateToWarehouse::Request& request,
moveit_msgs::SaveRobotStateToWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
const moveit_msgs::RobotState& state = request.state;
if ("" == request.name)
{
ROS_ERROR("You must specify a name to store a state");
return response.success = false;
}
rs->addRobotState(request.state, request.name, request.robot);
return response.success = true;
}
bool list_states(moveit_msgs::ListRobotStatesInWarehouse::Request& request,
moveit_msgs::ListRobotStatesInWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
if ("" == request.regex)
{
rs->getKnownRobotStates(response.states, request.robot);
}
else
{
rs->getKnownRobotStates(request.regex, response.states, request.robot);
}
return true;
}
bool has_state(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request& request,
moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
response.exists = rs->hasRobotState(request.name, request.robot);
return true;
}
bool get_state(moveit_msgs::GetRobotStateFromWarehouse::Request& request,
moveit_msgs::GetRobotStateFromWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
moveit_warehouse::RobotStateWithMetadata state_buffer;
rs->getRobotState(state_buffer, request.name, request.robot);
response.state = static_cast<const moveit_msgs::RobotState&>(*state_buffer);
return true;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "moveit_warehouse_services");
ros::AsyncSpinner spinner(1);
spinner.start();
ros::NodeHandle node("~");
std::string host; int port;
node.param<std::string>("/warehouse_host", host, "");
node.param<int>("/warehouse_port", port, 0);
ROS_INFO("Connecting to warehouse on %s:%d", host.c_str(), port);
moveit_warehouse::RobotStateStorage rs(host, port);
std::vector<std::string> names;
rs.getKnownRobotStates(names);
if (names.empty())
ROS_INFO("There are no previously stored robot states");
else
{
ROS_INFO("Previously stored robot states:");
for (std::size_t i = 0 ; i < names.size() ; ++i)
ROS_INFO(" * %s", names[i].c_str());
}
boost::function<bool(moveit_msgs::SaveRobotStateToWarehouse::Request& request,
moveit_msgs::SaveRobotStateToWarehouse::Response& response)>
save_cb = boost::bind(&store_state, _1, _2, &rs);
boost::function<bool(moveit_msgs::ListRobotStatesInWarehouse::Request& request,
moveit_msgs::ListRobotStatesInWarehouse::Response& response)>
list_cb = boost::bind(&list_states, _1, _2, &rs);
boost::function<bool(moveit_msgs::GetRobotStateFromWarehouse::Request& request,
moveit_msgs::GetRobotStateFromWarehouse::Response& response)>
get_cb = boost::bind(&get_state, _1, _2, &rs);
boost::function<bool(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request& request,
moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response)>
has_cb = boost::bind(&has_state, _1, _2, &rs);
ros::ServiceServer save_state_server = node.advertiseService("save_robot_state", save_cb);
ros::ServiceServer list_states_server = node.advertiseService("list_robot_states", list_cb);
ros::ServiceServer get_state_server = node.advertiseService("get_robot_state", get_cb);
ros::ServiceServer has_state_server = node.advertiseService("has_robot_state", has_cb);
ros::waitForShutdown();
return 0;
}
<|endoftext|> |
<commit_before>// $Id: PointGrid_test.C,v 1.2 1999/12/29 08:52:52 oliver Exp $
#include <BALL/CONCEPT/classTest.h>
#include <BALL/DATATYPE/pointGrid.h>
START_TEST(PointGrid, "$Id: PointGrid_test.C,v 1.2 1999/12/29 08:52:52 oliver Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using BALL::PointGrid;
PointGrid<float>* grid;
CHECK(constructor/1)
grid = new PointGrid<float>(0.0, 0.0, 0.0,
10.0, 10.0, 10.0,
11, 11, 11);
TEST_NOT_EQUAL(grid, 0)
RESULT
CHECK(destructor)
delete grid;
RESULT
using BALL::Vector3;
Vector3 lower(0.0, 0.0, 0.0);
Vector3 upper(10.0, 10.0, 10.0);
CHECK(constructor/2)
grid = new PointGrid<float>(lower, upper, 1.0);
TEST_NOT_EQUAL(grid, 0)
RESULT
CHECK(constructor/3)
delete grid;
grid = new PointGrid<float>(lower, upper, 11, 11, 11);
TEST_NOT_EQUAL(grid, 0)
RESULT
CHECK(getSize)
TEST_EQUAL(grid->getSize(), 1331)
RESULT
CHECK(getDimension)
TEST_REAL_EQUAL(grid->getDimension().x, 10.0)
TEST_REAL_EQUAL(grid->getDimension().y, 10.0)
TEST_REAL_EQUAL(grid->getDimension().z, 10.0)
RESULT
CHECK(getOrigin)
lower = grid->getOrigin();
TEST_REAL_EQUAL(lower.x, 0.0)
TEST_REAL_EQUAL(lower.y, 0.0)
TEST_REAL_EQUAL(lower.z, 0.0)
RESULT
CHECK(setOrigin/1)
grid->setOrigin(1.0, 1.0, 1.0);
lower = grid->getOrigin();
TEST_REAL_EQUAL(lower.x, 1.0)
TEST_REAL_EQUAL(lower.y, 1.0)
TEST_REAL_EQUAL(lower.z, 1.0)
RESULT
CHECK(setOrigin/2)
lower.set(2.0, 2.0, 2.0);
grid->setOrigin(lower);
lower = grid->getOrigin();
TEST_REAL_EQUAL(lower.x, 2.0)
TEST_REAL_EQUAL(lower.y, 2.0)
TEST_REAL_EQUAL(lower.z, 2.0)
RESULT
CHECK(getMaxX)
TEST_REAL_EQUAL(grid->getMaxX(), 12.0)
RESULT
CHECK(getMaxY)
TEST_REAL_EQUAL(grid->getMaxY(), 12.0)
RESULT
CHECK(getMaxZ)
TEST_REAL_EQUAL(grid->getMaxZ(), 12.0)
RESULT
CHECK(getMinX)
TEST_REAL_EQUAL(grid->getMinX(), 2.0)
RESULT
CHECK(getMinY)
TEST_REAL_EQUAL(grid->getMinY(), 2.0)
RESULT
CHECK(getMinZ)
TEST_REAL_EQUAL(grid->getMinZ(), 2.0)
RESULT
CHECK(getXSpacing)
TEST_REAL_EQUAL(grid->getXSpacing(), 1.0)
RESULT
CHECK(getYSpacing)
TEST_REAL_EQUAL(grid->getYSpacing(), 1.0)
RESULT
CHECK(getZSpacing)
TEST_REAL_EQUAL(grid->getZSpacing(), 1.0)
RESULT
CHECK(getMaxXIndex)
TEST_EQUAL(grid->getMaxXIndex(), 10)
RESULT
CHECK(getMaxYIndex)
TEST_EQUAL(grid->getMaxYIndex(), 10)
RESULT
CHECK(getMaxZIndex)
TEST_EQUAL(grid->getMaxZIndex(), 10)
RESULT
CHECK(operator[])
(*grid)[3 + 11 * 3 + 11 * 11 * 3] = 1.2345;
lower.set(5.0, 5.0, 5.0);
TEST_EQUAL((*grid)[3 + 11 * 3 + 11 * 11 * 3], (*grid)[lower]);
RESULT
BALL::PointGrid<float>::GridIndex index;
CHECK(getIndex/1)
lower.set(3.49, 3.51, 3.0);
index = grid->getIndex(lower);
TEST_EQUAL(index.x, 1)
TEST_EQUAL(index.y, 2)
TEST_EQUAL(index.z, 1)
RESULT
CHECK(getIndex/2)
index = grid->getIndex(3.49, 3.51, 3.0);
TEST_EQUAL(index.x, 1)
TEST_EQUAL(index.y, 2)
TEST_EQUAL(index.z, 1)
RESULT
CHECK(getData)
*(grid->getData(0, 0, 0)) = 5.4321;
lower = grid->getOrigin();
TEST_REAL_EQUAL(*(grid->getData(0)), 5.4321);
TEST_REAL_EQUAL(*(grid->getData(0)), *(grid->getData(lower)));
RESULT
CHECK(getGridCoordinates/1)
lower = grid->getGridCoordinates(0, 0, 0);
TEST_REAL_EQUAL(lower.x, 2.0)
TEST_REAL_EQUAL(lower.y, 2.0)
TEST_REAL_EQUAL(lower.z, 2.0)
RESULT
CHECK(getGridCoordinates/2)
lower = grid->getGridCoordinates(2 + 2 * 11 + 2 * 11 * 11);
TEST_REAL_EQUAL(lower.x, 4.0)
TEST_REAL_EQUAL(lower.y, 4.0)
TEST_REAL_EQUAL(lower.z, 4.0)
RESULT
CHECK(getGridCoordinates/3)
upper.set(3.999999, 4.0, 3.0001);
lower = grid->getGridCoordinates(upper);
TEST_REAL_EQUAL(lower.x, 3.0)
TEST_REAL_EQUAL(lower.y, 4.0)
TEST_REAL_EQUAL(lower.z, 3.0)
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>cosmetic changes<commit_after>// $Id: PointGrid_test.C,v 1.3 2000/07/01 18:11:03 amoll Exp $
#include <BALL/CONCEPT/classTest.h>
#include <BALL/DATATYPE/pointGrid.h>
START_TEST(PointGrid, "$Id: PointGrid_test.C,v 1.3 2000/07/01 18:11:03 amoll Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
String filename;
using BALL::PointGrid;
PointGrid<float>* grid;
CHECK(constructor/0)
grid = new PointGrid<float>();
TEST_NOT_EQUAL(grid, 0)
RESULT
CHECK(destructor)
delete grid;
RESULT
CHECK(constructor/1)
grid = new PointGrid<float>(0.0, 0.0, 0.0,
10.0, 10.0, 10.0,
11, 11, 11);
TEST_NOT_EQUAL(grid, 0)
RESULT
using BALL::Vector3;
Vector3 lower(0.0, 0.0, 0.0);
Vector3 upper(10.0, 10.0, 10.0);
CHECK(constructor/2)
grid = new PointGrid<float>(lower, upper, 1.0);
TEST_NOT_EQUAL(grid, 0)
RESULT
CHECK(constructor/3)
delete grid;
grid = new PointGrid<float>(lower, upper, 11, 11, 11);
TEST_NOT_EQUAL(grid, 0)
RESULT
CHECK(getSize)
TEST_EQUAL(grid->getSize(), 1331)
RESULT
PointGrid<float> g(0.0, 0.0, 0.0, 10.0, 10.0, 10.0, 11, 11, 11);
CHECK(set)
PointGrid<float> g1;
g1.set(g);
TEST_EQUAL(g1.getSize(), 1331)
RESULT
CHECK(operator =)
PointGrid<float> g1;
g1 = g;
TEST_EQUAL(g1.getSize(), 1331)
RESULT
CHECK(dump)
String filename;
NEW_TMP_FILE(filename)
std::ofstream outfile(filename.c_str(), ios::out);
g.dump(outfile);
outfile.close();
TEST_FILE(filename.c_str(), "data/PointGrid_test.txt", true)
RESULT
CHECK(isValid)
TEST_EQUAL(g.isValid(), true)
RESULT
CHECK(getMaxX)
TEST_REAL_EQUAL(grid->getMaxX(), 10.0)
RESULT
CHECK(getMaxY)
TEST_REAL_EQUAL(grid->getMaxY(), 10.0)
RESULT
CHECK(getMaxZ)
TEST_REAL_EQUAL(grid->getMaxZ(), 10.0)
RESULT
CHECK(getMinX)
TEST_REAL_EQUAL(grid->getMinX(), 0.0)
RESULT
CHECK(getMinY)
TEST_REAL_EQUAL(grid->getMinY(), 0.0)
RESULT
CHECK(getMinZ)
TEST_REAL_EQUAL(grid->getMinZ(), 0.0)
RESULT
CHECK(getMaxXIndex)
TEST_EQUAL(grid->getMaxXIndex(), 10)
RESULT
CHECK(getMaxYIndex)
TEST_EQUAL(grid->getMaxYIndex(), 10)
RESULT
CHECK(getMaxZIndex)
TEST_EQUAL(grid->getMaxZIndex(), 10)
RESULT
CHECK(getXSpacing)
TEST_REAL_EQUAL(grid->getXSpacing(), 1.0)
RESULT
CHECK(getYSpacing)
TEST_REAL_EQUAL(grid->getYSpacing(), 1.0)
RESULT
CHECK(getZSpacing)
TEST_REAL_EQUAL(grid->getZSpacing(), 1.0)
RESULT
BALL::PointGrid<float>::GridIndex index;
CHECK(getIndex/1)
lower.set(3.49, 3.51, 3.0);
index = grid->getIndex(lower);
TEST_EQUAL(index.x, 3)
TEST_EQUAL(index.y, 4)
TEST_EQUAL(index.z, 3)
RESULT
CHECK(getIndex/2)
index = grid->getIndex(3.49, 3.51, 3.0);
TEST_EQUAL(index.x, 3)
TEST_EQUAL(index.y, 4)
TEST_EQUAL(index.z, 3)
RESULT
CHECK(getData/1/2)
*(grid->getData(0, 0, 0)) = 5.4321;
lower = grid->getOrigin();
TEST_REAL_EQUAL(*(grid->getData(0)), 5.4321);
TEST_REAL_EQUAL(*(grid->getData(0)), *(grid->getData(lower)));
RESULT
CHECK(operator[]/1/2)
(*grid)[3 + 11 * 3 + 11 * 11 * 3] = 1.2345;
lower.set(3.0, 3.0, 3.0);
TEST_EQUAL((*grid)[3 + 11 * 3 + 11 * 11 * 3], (*grid)[lower]);
RESULT
CHECK(getGridCoordinates/1)
lower = grid->getGridCoordinates(0, 0, 0);
TEST_REAL_EQUAL(lower.x, 0.0)
TEST_REAL_EQUAL(lower.y, 0.0)
TEST_REAL_EQUAL(lower.z, 0.0)
RESULT
CHECK(getGridCoordinates/2)
lower = grid->getGridCoordinates(2 + 2 * 11 + 2 * 11 * 11);
TEST_REAL_EQUAL(lower.x, 2.0)
TEST_REAL_EQUAL(lower.y, 2.0)
TEST_REAL_EQUAL(lower.z, 2.0)
RESULT
CHECK(getGridCoordinates/3)
upper.set(3.999999, 4.0, 3.0001);
lower = grid->getGridCoordinates(upper);
TEST_REAL_EQUAL(lower.x, 3.0)
TEST_REAL_EQUAL(lower.y, 4.0)
TEST_REAL_EQUAL(lower.z, 3.0)
RESULT
CHECK(getBoxIndices)
///
RESULT
CHECK(getBoxData)
///
RESULT
CHECK(getOrigin)
lower = grid->getOrigin();
TEST_REAL_EQUAL(lower.x, 0.0)
TEST_REAL_EQUAL(lower.y, 0.0)
TEST_REAL_EQUAL(lower.z, 0.0)
RESULT
CHECK(setOrigin/1)
grid->setOrigin(1.0, 1.0, 1.0);
lower = grid->getOrigin();
TEST_REAL_EQUAL(lower.x, 1.0)
TEST_REAL_EQUAL(lower.y, 1.0)
TEST_REAL_EQUAL(lower.z, 1.0)
index = grid->getIndex(3.49, 3.51, 3.0);
TEST_EQUAL(index.x, 2)
TEST_EQUAL(index.y, 3)
TEST_EQUAL(index.z, 2)
RESULT
CHECK(setOrigin/2)
lower.set(2.0, 2.0, 2.0);
grid->setOrigin(lower);
lower = grid->getOrigin();
TEST_REAL_EQUAL(lower.x, 2.0)
TEST_REAL_EQUAL(lower.y, 2.0)
TEST_REAL_EQUAL(lower.z, 2.0)
index = grid->getIndex(3.49, 3.51, 3.0);
TEST_EQUAL(index.x, 1)
TEST_EQUAL(index.y, 2)
TEST_EQUAL(index.z, 1)
RESULT
CHECK(getDimension)
TEST_REAL_EQUAL(grid->getDimension().x, 10.0)
TEST_REAL_EQUAL(grid->getDimension().y, 10.0)
TEST_REAL_EQUAL(grid->getDimension().z, 10.0)
RESULT
CHECK(getInterpolatedValue)
///
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkStoreSCPLauncher.h"
#include <QMessageBox>
#include <QProcessEnvironment>
#include <mitkLogMacros.h>
#include <fstream>
#include <iostream>
#include <QFile>
#include <QTextStream>
#include <QIODevice>
#include <QDir>
#include <QDirIterator>
#include <QCoreApplication>
#include "org_mitk_gui_qt_dicom_config.h"
QmitkStoreSCPLauncher::QmitkStoreSCPLauncher(QmitkStoreSCPLauncherBuilder* builder)
: m_StoreSCP(new QProcess())
{
connect( m_StoreSCP, SIGNAL(error(QProcess::ProcessError)),this, SLOT(OnProcessError(QProcess::ProcessError)));
connect( m_StoreSCP, SIGNAL(stateChanged(QProcess::ProcessState)),this, SLOT(OnStateChanged(QProcess::ProcessState)));
//connect( m_StoreSCP, SIGNAL(readyReadStandardError()),this, SLOT(OnReadyProcessError()));
connect( m_StoreSCP, SIGNAL(readyReadStandardOutput()),this, SLOT(OnReadyProcessOutput()));
SetArgumentList(builder);
//m_StoreSCP->setStandardOutputFile("OutputLog.log");
//m_StoreSCP->setStandardErrorFile("ErrorLog.log");
}
QmitkStoreSCPLauncher::~QmitkStoreSCPLauncher()
{
m_StoreSCP->close();
m_StoreSCP->waitForFinished(1000);
DeleteTemporaryData();
delete m_StoreSCP;
}
void QmitkStoreSCPLauncher::StartStoreSCP()
{
FindPathToStoreSCP();
MITK_INFO << m_PathToStoreSCP.toStdString();
MITK_INFO << m_ArgumentList[7].toStdString();
m_StoreSCP->start(m_PathToStoreSCP,m_ArgumentList);
}
void QmitkStoreSCPLauncher::FindPathToStoreSCP()
{
QString appPath= QCoreApplication::applicationDirPath();
if(m_PathToStoreSCP.isEmpty())
{
QString fileName;
#ifdef _WIN32
fileName = "/storescp.exe";
#else
fileName = "/storescp";
#endif
m_PathToStoreSCP = fileName;
//In developement the storescp isn't copied into bin directory
if(!QFile::exists(m_PathToStoreSCP))
{
m_PathToStoreSCP = static_cast<QString>(MITK_STORESCP);
}
}
}
void QmitkStoreSCPLauncher::OnReadyProcessOutput()
{
QString out(m_StoreSCP->readAllStandardOutput());
QStringList allDataList,importList;
allDataList = out.split("\n",QString::SkipEmptyParts);
QStringListIterator it(allDataList);
while(it.hasNext())
{
QString output = it.next();
if (output.contains("E: "))
{
output.replace("E: ","");
m_ErrorText = output;
OnProcessError(QProcess::UnknownError);
return;
}
if(output.contains("I: storing DICOM file: "))
{
output.replace("I: storing DICOM file: ","");
importList += output;
}
}
if(!importList.isEmpty())
{
QStringListIterator it2(importList);
while(it2.hasNext())
{
MITK_INFO << it2.next().toStdString();
}
m_StatusText = " storing DICOM files!";
OnStateChanged(QProcess::Running);
emit SignalStartImport(importList);
}
}
void QmitkStoreSCPLauncher::OnProcessError(QProcess::ProcessError err)
{
switch(err)
{
case QProcess::FailedToStart:
m_ErrorText.prepend("Failed to start storage provider: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::Crashed:
m_ErrorText.prepend("Storage provider crashed: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::Timedout:
m_ErrorText.prepend("Storage provider timeout: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::WriteError:
m_ErrorText.prepend("Storage provider write error: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::ReadError:
m_ErrorText.prepend("Storage provider read error: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::UnknownError:
m_ErrorText.prepend("Storage provider unknown error: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
default:
m_ErrorText.prepend("Storage provider unknown error: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
}
}
void QmitkStoreSCPLauncher::OnStateChanged(QProcess::ProcessState status)
{
switch(status)
{
case QProcess::NotRunning:
m_StatusText.prepend("Storage provider not running!");
emit SignalStatusOfStoreSCP(m_StatusText);
m_StatusText.clear();
break;
case QProcess::Starting:
m_StatusText.prepend("Starting storage provider!");
emit SignalStatusOfStoreSCP(m_StatusText);
m_StatusText.clear();
break;
case QProcess::Running:
m_StatusText.prepend(m_ArgumentList[0]).prepend(" Port: ").prepend(m_ArgumentList[2]).prepend(" AET: ").prepend("Storage provider running! ");
emit SignalStatusOfStoreSCP(m_StatusText);
m_StatusText.clear();
break;
default:
m_StatusText.prepend("Storage provider unknown error!");
emit SignalStatusOfStoreSCP(m_StatusText);
m_StatusText.clear();
break;
}
}
void QmitkStoreSCPLauncher::SetArgumentList(QmitkStoreSCPLauncherBuilder* builder)
{
m_ArgumentList << *builder->GetPort() << QString("-aet") <<*builder->GetAETitle() << *builder->GetTransferSyntax()
<< *builder->GetOtherNetworkOptions() << *builder->GetMode() << QString("-od") << *builder->GetOutputDirectory();
}
void QmitkStoreSCPLauncher::DeleteTemporaryData()
{
MITK_INFO << m_ArgumentList[7].toStdString();
QDir dir(m_ArgumentList[7]);
QDirIterator it(dir);
while(it.hasNext())
{
it.next();
dir.remove(it.fileInfo().absoluteFilePath());
}
}
QString QmitkStoreSCPLauncher::ArgumentListToQString()
{
QString argumentString;
QStringListIterator argumentIterator(m_ArgumentList);
while(argumentIterator.hasNext())
{
argumentString.append(" ");
argumentString.append(argumentIterator.next());
}
return argumentString;
}
<commit_msg>deleted output<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkStoreSCPLauncher.h"
#include <QMessageBox>
#include <QProcessEnvironment>
#include <mitkLogMacros.h>
#include <fstream>
#include <iostream>
#include <QFile>
#include <QTextStream>
#include <QIODevice>
#include <QDir>
#include <QDirIterator>
#include <QCoreApplication>
#include "org_mitk_gui_qt_dicom_config.h"
QmitkStoreSCPLauncher::QmitkStoreSCPLauncher(QmitkStoreSCPLauncherBuilder* builder)
: m_StoreSCP(new QProcess())
{
connect( m_StoreSCP, SIGNAL(error(QProcess::ProcessError)),this, SLOT(OnProcessError(QProcess::ProcessError)));
connect( m_StoreSCP, SIGNAL(stateChanged(QProcess::ProcessState)),this, SLOT(OnStateChanged(QProcess::ProcessState)));
//connect( m_StoreSCP, SIGNAL(readyReadStandardError()),this, SLOT(OnReadyProcessError()));
connect( m_StoreSCP, SIGNAL(readyReadStandardOutput()),this, SLOT(OnReadyProcessOutput()));
SetArgumentList(builder);
//m_StoreSCP->setStandardOutputFile("OutputLog.log");
//m_StoreSCP->setStandardErrorFile("ErrorLog.log");
}
QmitkStoreSCPLauncher::~QmitkStoreSCPLauncher()
{
m_StoreSCP->close();
m_StoreSCP->waitForFinished(1000);
DeleteTemporaryData();
delete m_StoreSCP;
}
void QmitkStoreSCPLauncher::StartStoreSCP()
{
FindPathToStoreSCP();
MITK_INFO << m_PathToStoreSCP.toStdString();
MITK_INFO << m_ArgumentList[7].toStdString();
m_StoreSCP->start(m_PathToStoreSCP,m_ArgumentList);
}
void QmitkStoreSCPLauncher::FindPathToStoreSCP()
{
QString appPath= QCoreApplication::applicationDirPath();
if(m_PathToStoreSCP.isEmpty())
{
QString fileName;
#ifdef _WIN32
fileName = "/storescp.exe";
#else
fileName = "/storescp";
#endif
m_PathToStoreSCP = fileName;
//In developement the storescp isn't copied into bin directory
if(!QFile::exists(m_PathToStoreSCP))
{
m_PathToStoreSCP = static_cast<QString>(MITK_STORESCP);
}
}
}
void QmitkStoreSCPLauncher::OnReadyProcessOutput()
{
QString out(m_StoreSCP->readAllStandardOutput());
QStringList allDataList,importList;
allDataList = out.split("\n",QString::SkipEmptyParts);
QStringListIterator it(allDataList);
while(it.hasNext())
{
QString output = it.next();
if (output.contains("E: "))
{
output.replace("E: ","");
m_ErrorText = output;
OnProcessError(QProcess::UnknownError);
return;
}
if(output.contains("I: storing DICOM file: "))
{
output.replace("I: storing DICOM file: ","");
importList += output;
}
}
if(!importList.isEmpty())
{
emit SignalStartImport(importList);
}
}
void QmitkStoreSCPLauncher::OnProcessError(QProcess::ProcessError err)
{
switch(err)
{
case QProcess::FailedToStart:
m_ErrorText.prepend("Failed to start storage provider: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::Crashed:
m_ErrorText.prepend("Storage provider crashed: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::Timedout:
m_ErrorText.prepend("Storage provider timeout: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::WriteError:
m_ErrorText.prepend("Storage provider write error: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::ReadError:
m_ErrorText.prepend("Storage provider read error: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::UnknownError:
m_ErrorText.prepend("Storage provider unknown error: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
default:
m_ErrorText.prepend("Storage provider unknown error: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
}
}
void QmitkStoreSCPLauncher::OnStateChanged(QProcess::ProcessState status)
{
switch(status)
{
case QProcess::NotRunning:
m_StatusText.prepend("Storage provider not running!");
emit SignalStatusOfStoreSCP(m_StatusText);
m_StatusText.clear();
break;
case QProcess::Starting:
m_StatusText.prepend("Starting storage provider!");
emit SignalStatusOfStoreSCP(m_StatusText);
m_StatusText.clear();
break;
case QProcess::Running:
m_StatusText.prepend(m_ArgumentList[0]).prepend(" Port: ").prepend(m_ArgumentList[2]).prepend(" AET: ").prepend("Storage provider running! ");
emit SignalStatusOfStoreSCP(m_StatusText);
m_StatusText.clear();
break;
default:
m_StatusText.prepend("Storage provider unknown error!");
emit SignalStatusOfStoreSCP(m_StatusText);
m_StatusText.clear();
break;
}
}
void QmitkStoreSCPLauncher::SetArgumentList(QmitkStoreSCPLauncherBuilder* builder)
{
m_ArgumentList << *builder->GetPort() << QString("-aet") <<*builder->GetAETitle() << *builder->GetTransferSyntax()
<< *builder->GetOtherNetworkOptions() << *builder->GetMode() << QString("-od") << *builder->GetOutputDirectory();
}
void QmitkStoreSCPLauncher::DeleteTemporaryData()
{
MITK_INFO << m_ArgumentList[7].toStdString();
QDir dir(m_ArgumentList[7]);
QDirIterator it(dir);
while(it.hasNext())
{
it.next();
dir.remove(it.fileInfo().absoluteFilePath());
}
}
QString QmitkStoreSCPLauncher::ArgumentListToQString()
{
QString argumentString;
QStringListIterator argumentIterator(m_ArgumentList);
while(argumentIterator.hasNext())
{
argumentString.append(" ");
argumentString.append(argumentIterator.next());
}
return argumentString;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
///
/// SoundStretch main routine.
///
/// Author : Copyright (c) Olli Parviainen
/// Author e-mail : oparviai 'at' iki.fi
/// SoundTouch WWW: http://www.surina.net/soundtouch
///
////////////////////////////////////////////////////////////////////////////////
//
// Last changed : $Date$
// File revision : $Revision: 4 $
//
// $Id$
//
////////////////////////////////////////////////////////////////////////////////
//
// License :
//
// SoundTouch audio processing library
// Copyright (c) Olli Parviainen
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////
#include <stdexcept>
#include <stdio.h>
#include <string.h>
#include "RunParameters.h"
#include "WavFile.h"
#include "SoundTouch.h"
#include "BPMDetect.h"
using namespace soundtouch;
using namespace std;
// Processing chunk size
#define BUFF_SIZE 2048
#if WIN32
#include <io.h>
#include <fcntl.h>
// Macro for Win32 standard input/output stream support: Sets a file stream into binary mode
#define SET_STREAM_TO_BIN_MODE(f) (_setmode(_fileno(f), _O_BINARY))
#else
// Not needed for GNU environment...
#define SET_STREAM_TO_BIN_MODE(f) {}
#endif
static const char _helloText[] =
"\n"
" SoundStretch v%s - Written by Olli Parviainen 2001 - 2009\n"
"==================================================================\n"
"author e-mail: <oparviai"
"@"
"iki.fi> - WWW: http://www.surina.net/soundtouch\n"
"\n"
"This program is subject to (L)GPL license. Run \"soundstretch -license\" for\n"
"more information.\n"
"\n";
static void openFiles(WavInFile **inFile, WavOutFile **outFile, const RunParameters *params)
{
int bits, samplerate, channels;
if (strcmp(params->inFileName, "stdin") == 0)
{
// used 'stdin' as input file
SET_STREAM_TO_BIN_MODE(stdin);
*inFile = new WavInFile(stdin);
}
else
{
// open input file...
*inFile = new WavInFile(params->inFileName);
}
// ... open output file with same sound parameters
bits = (int)(*inFile)->getNumBits();
samplerate = (int)(*inFile)->getSampleRate();
channels = (int)(*inFile)->getNumChannels();
if (params->outFileName)
{
if (strcmp(params->outFileName, "stdout") == 0)
{
SET_STREAM_TO_BIN_MODE(stdout);
*outFile = new WavOutFile(stdout, samplerate, bits, channels);
}
else
{
*outFile = new WavOutFile(params->outFileName, samplerate, bits, channels);
}
}
else
{
*outFile = NULL;
}
}
// Sets the 'SoundTouch' object up according to input file sound format &
// command line parameters
static void setup(SoundTouch *pSoundTouch, const WavInFile *inFile, const RunParameters *params)
{
int sampleRate;
int channels;
sampleRate = (int)inFile->getSampleRate();
channels = (int)inFile->getNumChannels();
pSoundTouch->setSampleRate(sampleRate);
pSoundTouch->setChannels(channels);
pSoundTouch->setTempoChange(params->tempoDelta);
pSoundTouch->setPitchSemiTones(params->pitchDelta);
pSoundTouch->setRateChange(params->rateDelta);
pSoundTouch->setSetting(SETTING_USE_QUICKSEEK, params->quick);
pSoundTouch->setSetting(SETTING_USE_AA_FILTER, !(params->noAntiAlias));
if (params->speech)
{
// use settings for speech processing
pSoundTouch->setSetting(SETTING_SEQUENCE_MS, 40);
pSoundTouch->setSetting(SETTING_SEEKWINDOW_MS, 15);
pSoundTouch->setSetting(SETTING_OVERLAP_MS, 8);
fprintf(stderr, "Tune processing parameters for speech processing.\n");
}
// print processing information
if (params->outFileName)
{
#ifdef SOUNDTOUCH_INTEGER_SAMPLES
fprintf(stderr, "Uses 16bit integer sample type in processing.\n\n");
#else
#ifndef SOUNDTOUCH_FLOAT_SAMPLES
#error "Sampletype not defined"
#endif
fprintf(stderr, "Uses 32bit floating point sample type in processing.\n\n");
#endif
// print processing information only if outFileName given i.e. some processing will happen
fprintf(stderr, "Processing the file with the following changes:\n");
fprintf(stderr, " tempo change = %+g %%\n", params->tempoDelta);
fprintf(stderr, " pitch change = %+g semitones\n", params->pitchDelta);
fprintf(stderr, " rate change = %+g %%\n\n", params->rateDelta);
fprintf(stderr, "Working...");
}
else
{
// outFileName not given
fprintf(stderr, "Warning: output file name missing, won't output anything.\n\n");
}
fflush(stderr);
}
// Processes the sound
static void process(SoundTouch *pSoundTouch, WavInFile *inFile, WavOutFile *outFile)
{
int nSamples;
int nChannels;
int buffSizeSamples;
SAMPLETYPE sampleBuffer[BUFF_SIZE];
if ((inFile == NULL) || (outFile == NULL)) return; // nothing to do.
nChannels = (int)inFile->getNumChannels();
assert(nChannels > 0);
buffSizeSamples = BUFF_SIZE / nChannels;
// Process samples read from the input file
while (inFile->eof() == 0)
{
int num;
// Read a chunk of samples from the input file
num = inFile->read(sampleBuffer, BUFF_SIZE);
nSamples = num / (int)inFile->getNumChannels();
// Feed the samples into SoundTouch processor
pSoundTouch->putSamples(sampleBuffer, nSamples);
// Read ready samples from SoundTouch processor & write them output file.
// NOTES:
// - 'receiveSamples' doesn't necessarily return any samples at all
// during some rounds!
// - On the other hand, during some round 'receiveSamples' may have more
// ready samples than would fit into 'sampleBuffer', and for this reason
// the 'receiveSamples' call is iterated for as many times as it
// outputs samples.
do
{
nSamples = pSoundTouch->receiveSamples(sampleBuffer, buffSizeSamples);
outFile->write(sampleBuffer, nSamples * nChannels);
} while (nSamples != 0);
}
// Now the input file is processed, yet 'flush' few last samples that are
// hiding in the SoundTouch's internal processing pipeline.
pSoundTouch->flush();
do
{
nSamples = pSoundTouch->receiveSamples(sampleBuffer, buffSizeSamples);
outFile->write(sampleBuffer, nSamples * nChannels);
} while (nSamples != 0);
}
// Detect BPM rate of inFile and adjust tempo setting accordingly if necessary
static void detectBPM(WavInFile *inFile, RunParameters *params)
{
float bpmValue;
int nChannels;
BPMDetect bpm(inFile->getNumChannels(), inFile->getSampleRate());
SAMPLETYPE sampleBuffer[BUFF_SIZE];
// detect bpm rate
fprintf(stderr, "Detecting BPM rate...");
fflush(stderr);
nChannels = (int)inFile->getNumChannels();
assert(BUFF_SIZE % nChannels == 0);
// Process the 'inFile' in small blocks, repeat until whole file has
// been processed
while (inFile->eof() == 0)
{
int num, samples;
// Read sample data from input file
num = inFile->read(sampleBuffer, BUFF_SIZE);
// Enter the new samples to the bpm analyzer class
samples = num / nChannels;
bpm.inputSamples(sampleBuffer, samples);
}
// Now the whole song data has been analyzed. Read the resulting bpm.
bpmValue = bpm.getBpm();
fprintf(stderr, "Done!\n");
// rewind the file after bpm detection
inFile->rewind();
if (bpmValue > 0)
{
fprintf(stderr, "Detected BPM rate %.1f\n\n", bpmValue);
}
else
{
fprintf(stderr, "Couldn't detect BPM rate.\n\n");
return;
}
if (params->goalBPM > 0)
{
// adjust tempo to given bpm
params->tempoDelta = (params->goalBPM / bpmValue - 1.0f) * 100.0f;
fprintf(stderr, "The file will be converted to %.1f BPM\n\n", params->goalBPM);
}
}
int main(const int nParams, const char * const paramStr[])
{
WavInFile *inFile;
WavOutFile *outFile;
RunParameters *params;
SoundTouch soundTouch;
fprintf(stderr, _helloText, SoundTouch::getVersionString());
try
{
// Parse command line parameters
params = new RunParameters(nParams, paramStr);
// Open input & output files
openFiles(&inFile, &outFile, params);
if (params->detectBPM == TRUE)
{
// detect sound BPM (and adjust processing parameters
// accordingly if necessary)
detectBPM(inFile, params);
}
// Setup the 'SoundTouch' object for processing the sound
setup(&soundTouch, inFile, params);
// Process the sound
process(&soundTouch, inFile, outFile);
// Close WAV file handles & dispose of the objects
delete inFile;
delete outFile;
delete params;
fprintf(stderr, "Done!\n");
}
catch (const runtime_error &e)
{
// An exception occurred during processing, display an error message
fprintf(stderr, "%s\n", e.what());
return -1;
}
return 0;
}
<commit_msg>Update copyright year<commit_after>////////////////////////////////////////////////////////////////////////////////
///
/// SoundStretch main routine.
///
/// Author : Copyright (c) Olli Parviainen
/// Author e-mail : oparviai 'at' iki.fi
/// SoundTouch WWW: http://www.surina.net/soundtouch
///
////////////////////////////////////////////////////////////////////////////////
//
// Last changed : $Date$
// File revision : $Revision: 4 $
//
// $Id$
//
////////////////////////////////////////////////////////////////////////////////
//
// License :
//
// SoundTouch audio processing library
// Copyright (c) Olli Parviainen
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////
#include <stdexcept>
#include <stdio.h>
#include <string.h>
#include "RunParameters.h"
#include "WavFile.h"
#include "SoundTouch.h"
#include "BPMDetect.h"
using namespace soundtouch;
using namespace std;
// Processing chunk size
#define BUFF_SIZE 2048
#if WIN32
#include <io.h>
#include <fcntl.h>
// Macro for Win32 standard input/output stream support: Sets a file stream into binary mode
#define SET_STREAM_TO_BIN_MODE(f) (_setmode(_fileno(f), _O_BINARY))
#else
// Not needed for GNU environment...
#define SET_STREAM_TO_BIN_MODE(f) {}
#endif
static const char _helloText[] =
"\n"
" SoundStretch v%s - Written by Olli Parviainen 2001 - 2011\n"
"==================================================================\n"
"author e-mail: <oparviai"
"@"
"iki.fi> - WWW: http://www.surina.net/soundtouch\n"
"\n"
"This program is subject to (L)GPL license. Run \"soundstretch -license\" for\n"
"more information.\n"
"\n";
static void openFiles(WavInFile **inFile, WavOutFile **outFile, const RunParameters *params)
{
int bits, samplerate, channels;
if (strcmp(params->inFileName, "stdin") == 0)
{
// used 'stdin' as input file
SET_STREAM_TO_BIN_MODE(stdin);
*inFile = new WavInFile(stdin);
}
else
{
// open input file...
*inFile = new WavInFile(params->inFileName);
}
// ... open output file with same sound parameters
bits = (int)(*inFile)->getNumBits();
samplerate = (int)(*inFile)->getSampleRate();
channels = (int)(*inFile)->getNumChannels();
if (params->outFileName)
{
if (strcmp(params->outFileName, "stdout") == 0)
{
SET_STREAM_TO_BIN_MODE(stdout);
*outFile = new WavOutFile(stdout, samplerate, bits, channels);
}
else
{
*outFile = new WavOutFile(params->outFileName, samplerate, bits, channels);
}
}
else
{
*outFile = NULL;
}
}
// Sets the 'SoundTouch' object up according to input file sound format &
// command line parameters
static void setup(SoundTouch *pSoundTouch, const WavInFile *inFile, const RunParameters *params)
{
int sampleRate;
int channels;
sampleRate = (int)inFile->getSampleRate();
channels = (int)inFile->getNumChannels();
pSoundTouch->setSampleRate(sampleRate);
pSoundTouch->setChannels(channels);
pSoundTouch->setTempoChange(params->tempoDelta);
pSoundTouch->setPitchSemiTones(params->pitchDelta);
pSoundTouch->setRateChange(params->rateDelta);
pSoundTouch->setSetting(SETTING_USE_QUICKSEEK, params->quick);
pSoundTouch->setSetting(SETTING_USE_AA_FILTER, !(params->noAntiAlias));
if (params->speech)
{
// use settings for speech processing
pSoundTouch->setSetting(SETTING_SEQUENCE_MS, 40);
pSoundTouch->setSetting(SETTING_SEEKWINDOW_MS, 15);
pSoundTouch->setSetting(SETTING_OVERLAP_MS, 8);
fprintf(stderr, "Tune processing parameters for speech processing.\n");
}
// print processing information
if (params->outFileName)
{
#ifdef SOUNDTOUCH_INTEGER_SAMPLES
fprintf(stderr, "Uses 16bit integer sample type in processing.\n\n");
#else
#ifndef SOUNDTOUCH_FLOAT_SAMPLES
#error "Sampletype not defined"
#endif
fprintf(stderr, "Uses 32bit floating point sample type in processing.\n\n");
#endif
// print processing information only if outFileName given i.e. some processing will happen
fprintf(stderr, "Processing the file with the following changes:\n");
fprintf(stderr, " tempo change = %+g %%\n", params->tempoDelta);
fprintf(stderr, " pitch change = %+g semitones\n", params->pitchDelta);
fprintf(stderr, " rate change = %+g %%\n\n", params->rateDelta);
fprintf(stderr, "Working...");
}
else
{
// outFileName not given
fprintf(stderr, "Warning: output file name missing, won't output anything.\n\n");
}
fflush(stderr);
}
// Processes the sound
static void process(SoundTouch *pSoundTouch, WavInFile *inFile, WavOutFile *outFile)
{
int nSamples;
int nChannels;
int buffSizeSamples;
SAMPLETYPE sampleBuffer[BUFF_SIZE];
if ((inFile == NULL) || (outFile == NULL)) return; // nothing to do.
nChannels = (int)inFile->getNumChannels();
assert(nChannels > 0);
buffSizeSamples = BUFF_SIZE / nChannels;
// Process samples read from the input file
while (inFile->eof() == 0)
{
int num;
// Read a chunk of samples from the input file
num = inFile->read(sampleBuffer, BUFF_SIZE);
nSamples = num / (int)inFile->getNumChannels();
// Feed the samples into SoundTouch processor
pSoundTouch->putSamples(sampleBuffer, nSamples);
// Read ready samples from SoundTouch processor & write them output file.
// NOTES:
// - 'receiveSamples' doesn't necessarily return any samples at all
// during some rounds!
// - On the other hand, during some round 'receiveSamples' may have more
// ready samples than would fit into 'sampleBuffer', and for this reason
// the 'receiveSamples' call is iterated for as many times as it
// outputs samples.
do
{
nSamples = pSoundTouch->receiveSamples(sampleBuffer, buffSizeSamples);
outFile->write(sampleBuffer, nSamples * nChannels);
} while (nSamples != 0);
}
// Now the input file is processed, yet 'flush' few last samples that are
// hiding in the SoundTouch's internal processing pipeline.
pSoundTouch->flush();
do
{
nSamples = pSoundTouch->receiveSamples(sampleBuffer, buffSizeSamples);
outFile->write(sampleBuffer, nSamples * nChannels);
} while (nSamples != 0);
}
// Detect BPM rate of inFile and adjust tempo setting accordingly if necessary
static void detectBPM(WavInFile *inFile, RunParameters *params)
{
float bpmValue;
int nChannels;
BPMDetect bpm(inFile->getNumChannels(), inFile->getSampleRate());
SAMPLETYPE sampleBuffer[BUFF_SIZE];
// detect bpm rate
fprintf(stderr, "Detecting BPM rate...");
fflush(stderr);
nChannels = (int)inFile->getNumChannels();
assert(BUFF_SIZE % nChannels == 0);
// Process the 'inFile' in small blocks, repeat until whole file has
// been processed
while (inFile->eof() == 0)
{
int num, samples;
// Read sample data from input file
num = inFile->read(sampleBuffer, BUFF_SIZE);
// Enter the new samples to the bpm analyzer class
samples = num / nChannels;
bpm.inputSamples(sampleBuffer, samples);
}
// Now the whole song data has been analyzed. Read the resulting bpm.
bpmValue = bpm.getBpm();
fprintf(stderr, "Done!\n");
// rewind the file after bpm detection
inFile->rewind();
if (bpmValue > 0)
{
fprintf(stderr, "Detected BPM rate %.1f\n\n", bpmValue);
}
else
{
fprintf(stderr, "Couldn't detect BPM rate.\n\n");
return;
}
if (params->goalBPM > 0)
{
// adjust tempo to given bpm
params->tempoDelta = (params->goalBPM / bpmValue - 1.0f) * 100.0f;
fprintf(stderr, "The file will be converted to %.1f BPM\n\n", params->goalBPM);
}
}
int main(const int nParams, const char * const paramStr[])
{
WavInFile *inFile;
WavOutFile *outFile;
RunParameters *params;
SoundTouch soundTouch;
fprintf(stderr, _helloText, SoundTouch::getVersionString());
try
{
// Parse command line parameters
params = new RunParameters(nParams, paramStr);
// Open input & output files
openFiles(&inFile, &outFile, params);
if (params->detectBPM == TRUE)
{
// detect sound BPM (and adjust processing parameters
// accordingly if necessary)
detectBPM(inFile, params);
}
// Setup the 'SoundTouch' object for processing the sound
setup(&soundTouch, inFile, params);
// Process the sound
process(&soundTouch, inFile, outFile);
// Close WAV file handles & dispose of the objects
delete inFile;
delete outFile;
delete params;
fprintf(stderr, "Done!\n");
}
catch (const runtime_error &e)
{
// An exception occurred during processing, display an error message
fprintf(stderr, "%s\n", e.what());
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
// * This source file is part of ArkGameFrame *
// * For the latest info, see https://github.com/ArkGame *
// * *
// * Copyright(c) 2013 - 2017 ArkGame 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 "SDK/Base/AFPlatform.hpp"
#if ARK_PLATFORM == PLATFORM_WIN
#pragma comment(lib, "Dbghelp.lib")
#pragma comment(lib, "ws2_32")
#pragma comment(lib, "event_core.lib")
#if ARK_RUN_MODE == ARK_RUN_MODE_DEBUG
#pragma comment(lib, "AFCore_d.lib")
#pragma comment(lib, "AFProto_d.lib")
#pragma comment(lib, "libprotobuf_d.lib")
#pragma comment(lib, "AFNet_d.lib")
#else
#pragma comment(lib, "AFCore.lib")
#pragma comment(lib, "AFProto.lib")
#pragma comment(lib, "libprotobuf.lib")
#pragma comment(lib, "AFNet.lib")
#endif
#endif<commit_msg>fix FileProcess debug directory<commit_after>/*
* This source file is part of ArkGameFrame
* For the latest info, see https://github.com/ArkGame
*
* Copyright (c) 2013-2017 ArkGame 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 "SDK/Base/AFPlatform.hpp"
#if ARK_PLATFORM == PLATFORM_WIN
#pragma comment(lib, "Dbghelp.lib")
#pragma comment(lib, "ws2_32")
#pragma comment(lib, "event_core.lib")
#if ARK_RUN_MODE == ARK_RUN_MODE_DEBUG
#pragma comment(lib, "AFCore_d.lib")
#pragma comment(lib, "AFProto_d.lib")
#pragma comment(lib, "libprotobuf_d.lib")
#pragma comment(lib, "AFNet_d.lib")
#else
#pragma comment(lib, "AFCore.lib")
#pragma comment(lib, "AFProto.lib")
#pragma comment(lib, "libprotobuf.lib")
#pragma comment(lib, "AFNet.lib")
#endif
#endif<|endoftext|> |
<commit_before>#include "Scene.h"
#include "Director.h"
#include "EngineShaderFactory.hpp"
using namespace Core;
using namespace std;
using namespace Structure;
using namespace Math;
using namespace Rendering;
using namespace Rendering::Manager;
using namespace Rendering::PostProcessing;
using namespace Rendering::TBDR;
using namespace Rendering::Shader;
using namespace UI::Manager;
using namespace Rendering::Camera;
using namespace Rendering::Texture;
using namespace Rendering::Shadow;
using namespace Rendering::GI;
Scene::Scene(void) :
_cameraMgr(nullptr), _uiManager(nullptr),
_renderMgr(nullptr), _backBufferMaker(nullptr),
_shadowRenderer(nullptr), _globalIllumination(nullptr)
{
_state = State::Init;
}
Scene::~Scene(void)
{
SAFE_DELETE(_cameraMgr);
SAFE_DELETE(_renderMgr);
SAFE_DELETE(_uiManager);
SAFE_DELETE(_lightManager);
SAFE_DELETE(_materialMgr);
SAFE_DELETE(_backBufferMaker);
SAFE_DELETE(_shadowRenderer);
SAFE_DELETE(_globalIllumination);
}
void Scene::Initialize()
{
_cameraMgr = new CameraManager;
_renderMgr = new RenderManager;
_renderMgr->Initialize();
_uiManager = new UIManager;
_dx = Device::Director::SharedInstance()->GetDirectX();
_lightManager = new LightManager;
_lightManager->InitializeAllShaderResourceBuffer();
_materialMgr = new MaterialManager;
_backBufferMaker = new BackBufferMaker;
_backBufferMaker->Initialize(false);
_shadowRenderer = new ShadowRenderer;
_shadowRenderer->Initialize(false);
uint value = 0xff7fffff;
float fltMin = (*(float*)&value);
value = 0x7f7fffff;
float fltMax = (*(float*)&value);
_boundBox.SetMinMax(Vector3(fltMax, fltMax, fltMax), Vector3(fltMin, fltMin, fltMin));
Matrix::Identity(_localMat);
NextState();
OnInitialize();
}
void Scene::Update(float dt)
{
OnUpdate(dt);
auto end = _rootObjects.GetVector().end();
for(auto iter = _rootObjects.GetVector().begin(); iter != end; ++iter)
(*iter)->Update(dt);
}
void Scene::RenderPreview()
{
OnRenderPreview();
Vector3 boundBoxMin = _boundBox.GetMin();
Vector3 boundBoxMax = _boundBox.GetMax();
const auto& objectVector = _rootObjects.GetVector();
for(auto iter = objectVector.begin(); iter != objectVector.end(); ++iter)
(*iter)->UpdateTransformCB_With_ComputeSceneMinMaxPos(_dx, boundBoxMin, boundBoxMax, _localMat);
_boundBox.SetMinMax(boundBoxMin, boundBoxMax);
_shadowRenderer->ComputeAllLightViewProj();
_lightManager->ComputeDirectionalLightViewProj(_boundBox, float(_shadowRenderer->GetDirectionalLightShadowMapResolution()));
_shadowRenderer->UpdateConstBuffer(_dx);
auto materials = _materialMgr->GetMaterials().GetVector();
for(auto iter = materials.begin(); iter != materials.end(); ++iter)
(*iter)->UpdateConstBuffer(_dx);
auto FetchLightIndex = [&](const Light::LightForm* light) -> uint
{
return _lightManager->FetchLightIndexInEachLights(light);
};
auto FetchShadowIndex = [&](const Light::LightForm* light) -> uint
{
return _shadowRenderer->FetchShadowIndexInEachShadowLights(light);
};
_lightManager->UpdateSRBuffer(_dx, FetchShadowIndex);
_shadowRenderer->UpdateSRBuffer(_dx, FetchLightIndex);
const std::vector<CameraForm*>& cameras = _cameraMgr->GetCameraVector();
for(auto iter = cameras.begin(); iter != cameras.end(); ++iter)
(*iter)->CullingWithUpdateCB(_dx, _rootObjects.GetVector(), _lightManager);
}
void Scene::Render()
{
_dx->ClearDeviceContext();
const RenderManager* renderMgr = _renderMgr;
_shadowRenderer->RenderShadowMap(_dx, renderMgr);
_dx->ClearDeviceContext();
auto GIPass = [&](MeshCamera* meshCam) -> const RenderTexture*
{
bool isMainCam = _cameraMgr->GetMainCamera() == meshCam;
const RenderTexture* indirectColorMap = nullptr;
if(_globalIllumination && isMainCam)
{
if(meshCam->GetUseIndirectColorMap() == false)
meshCam->ReCompileOffScreen(true);
_globalIllumination->Run(_dx, meshCam, _renderMgr, _shadowRenderer, _materialMgr);
indirectColorMap = _globalIllumination->GetIndirectColorMap();
}
else
{
if(meshCam->GetUseIndirectColorMap())
meshCam->ReCompileOffScreen(false);
}
return indirectColorMap;
};
const std::vector<CameraForm*>& cameras = _cameraMgr->GetCameraVector();
for(auto iter = cameras.begin(); iter != cameras.end(); ++iter)
{
if( (*iter)->GetUsage() == CameraForm::Usage::MeshRender )
{
// const Buffer::ConstBuffer* ڵ auto ü
auto shadowCB = _shadowRenderer->IsWorking() ?
_shadowRenderer->GetShadowGlobalParamConstBuffer() : nullptr;
dynamic_cast<MeshCamera*>(*iter)->Render(_dx, _renderMgr, _lightManager, shadowCB, _shadowRenderer->GetNeverUseVSM(), GIPass);
}
else if( (*iter)->GetUsage() == CameraForm::Usage::UI )
dynamic_cast<UICamera*>(*iter)->Render(_dx);
}
CameraForm* mainCam = _cameraMgr->GetMainCamera();
if(mainCam)
{
ID3D11RenderTargetView* backBufferRTV = _dx->GetBackBufferRTV();
const RenderTexture* camRT = mainCam->GetRenderTarget();
MeshCamera* mainMeshCam = dynamic_cast<MeshCamera*>(mainCam);
_backBufferMaker->Render(backBufferRTV, camRT, nullptr, mainMeshCam->GetTBRParamConstBuffer());
}
_dx->GetSwapChain()->Present(0, 0);
OnRenderPost();
}
void Scene::Destroy()
{
OnDestroy();
DeleteAllObject();
_materialMgr->DeleteAll();
_backBufferMaker->Destroy();
_shadowRenderer->Destroy();
_renderMgr->Destroy();
_uiManager->Destroy();
_lightManager->Destroy();
_cameraMgr->Destroy();
_globalIllumination->Destroy();
}
void Scene::NextState()
{
_state = (State)(((int)_state + 1) % (int)State::Num);
}
void Scene::StopState()
{
_state = State::Stop;
}
void Scene::AddObject(Core::Object* object)
{
_rootObjects.Add(object->GetName(), object);
}
Core::Object* Scene::FindObject(const std::string& key)
{
Core::Object** objAddr = _rootObjects.Find(key);
return objAddr ? (*objAddr) : nullptr;
}
void Scene::DeleteObject(Core::Object* object)
{
std::string key = object->GetName();
Core::Object** objectAddr = _rootObjects.Find(key);
if(objectAddr)
{
Core::Object* object = (*objectAddr);
SAFE_DELETE(object);
_rootObjects.Delete(key);
}
}
void Scene::DeleteAllObject()
{
auto& objects = _rootObjects.GetVector();
for(auto iter = objects.begin(); iter != objects.end(); ++iter)
{
Core::Object* object = (*iter);
SAFE_DELETE(object);
}
_rootObjects.DeleteAll();
}
void Scene::Input(const Device::Win32::Mouse& mouse, const Device::Win32::Keyboard& keyboard)
{
if(_state == State::Loop)
OnInput(mouse, keyboard);
}
void Scene::ActivateGI(bool activate, uint dimension, float giSize)
{
if(activate == false)
{
if(_globalIllumination)
_globalIllumination->Destroy();
SAFE_DELETE(_globalIllumination);
}
else
{
if(_globalIllumination)
return;
_globalIllumination = new GlobalIllumination;
_globalIllumination->Initialize(_dx, dimension, giSize);
}
}<commit_msg>Scene -GI::Run 호출 간소화<commit_after>#include "Scene.h"
#include "Director.h"
#include "EngineShaderFactory.hpp"
using namespace Core;
using namespace std;
using namespace Structure;
using namespace Math;
using namespace Rendering;
using namespace Rendering::Manager;
using namespace Rendering::PostProcessing;
using namespace Rendering::TBDR;
using namespace Rendering::Shader;
using namespace UI::Manager;
using namespace Rendering::Camera;
using namespace Rendering::Texture;
using namespace Rendering::Shadow;
using namespace Rendering::GI;
Scene::Scene(void) :
_cameraMgr(nullptr), _uiManager(nullptr),
_renderMgr(nullptr), _backBufferMaker(nullptr),
_shadowRenderer(nullptr), _globalIllumination(nullptr)
{
_state = State::Init;
}
Scene::~Scene(void)
{
SAFE_DELETE(_cameraMgr);
SAFE_DELETE(_renderMgr);
SAFE_DELETE(_uiManager);
SAFE_DELETE(_lightManager);
SAFE_DELETE(_materialMgr);
SAFE_DELETE(_backBufferMaker);
SAFE_DELETE(_shadowRenderer);
SAFE_DELETE(_globalIllumination);
}
void Scene::Initialize()
{
_cameraMgr = new CameraManager;
_renderMgr = new RenderManager;
_renderMgr->Initialize();
_uiManager = new UIManager;
_dx = Device::Director::SharedInstance()->GetDirectX();
_lightManager = new LightManager;
_lightManager->InitializeAllShaderResourceBuffer();
_materialMgr = new MaterialManager;
_backBufferMaker = new BackBufferMaker;
_backBufferMaker->Initialize(false);
_shadowRenderer = new ShadowRenderer;
_shadowRenderer->Initialize(false);
uint value = 0xff7fffff;
float fltMin = (*(float*)&value);
value = 0x7f7fffff;
float fltMax = (*(float*)&value);
_boundBox.SetMinMax(Vector3(fltMax, fltMax, fltMax), Vector3(fltMin, fltMin, fltMin));
Matrix::Identity(_localMat);
NextState();
OnInitialize();
}
void Scene::Update(float dt)
{
OnUpdate(dt);
auto end = _rootObjects.GetVector().end();
for(auto iter = _rootObjects.GetVector().begin(); iter != end; ++iter)
(*iter)->Update(dt);
}
void Scene::RenderPreview()
{
OnRenderPreview();
Vector3 boundBoxMin = _boundBox.GetMin();
Vector3 boundBoxMax = _boundBox.GetMax();
const auto& objectVector = _rootObjects.GetVector();
for(auto iter = objectVector.begin(); iter != objectVector.end(); ++iter)
(*iter)->UpdateTransformCB_With_ComputeSceneMinMaxPos(_dx, boundBoxMin, boundBoxMax, _localMat);
_boundBox.SetMinMax(boundBoxMin, boundBoxMax);
_shadowRenderer->ComputeAllLightViewProj();
_lightManager->ComputeDirectionalLightViewProj(_boundBox, float(_shadowRenderer->GetDirectionalLightShadowMapResolution()));
_shadowRenderer->UpdateConstBuffer(_dx);
auto materials = _materialMgr->GetMaterials().GetVector();
for(auto iter = materials.begin(); iter != materials.end(); ++iter)
(*iter)->UpdateConstBuffer(_dx);
auto FetchLightIndex = [&](const Light::LightForm* light) -> uint
{
return _lightManager->FetchLightIndexInEachLights(light);
};
auto FetchShadowIndex = [&](const Light::LightForm* light) -> uint
{
return _shadowRenderer->FetchShadowIndexInEachShadowLights(light);
};
_lightManager->UpdateSRBuffer(_dx, FetchShadowIndex);
_shadowRenderer->UpdateSRBuffer(_dx, FetchLightIndex);
const std::vector<CameraForm*>& cameras = _cameraMgr->GetCameraVector();
for(auto iter = cameras.begin(); iter != cameras.end(); ++iter)
(*iter)->CullingWithUpdateCB(_dx, _rootObjects.GetVector(), _lightManager);
}
void Scene::Render()
{
_dx->ClearDeviceContext();
const RenderManager* renderMgr = _renderMgr;
_shadowRenderer->RenderShadowMap(_dx, renderMgr);
_dx->ClearDeviceContext();
auto GIPass = [&](MeshCamera* meshCam) -> const RenderTexture*
{
bool isMainCam = _cameraMgr->GetMainCamera() == meshCam;
const RenderTexture* indirectColorMap = nullptr;
if(_globalIllumination && isMainCam)
{
if(meshCam->GetUseIndirectColorMap() == false)
meshCam->ReCompileOffScreen(true);
_globalIllumination->Run(_dx, meshCam, this);
indirectColorMap = _globalIllumination->GetIndirectColorMap();
}
else
{
if(meshCam->GetUseIndirectColorMap())
meshCam->ReCompileOffScreen(false);
}
return indirectColorMap;
};
const std::vector<CameraForm*>& cameras = _cameraMgr->GetCameraVector();
for(auto iter = cameras.begin(); iter != cameras.end(); ++iter)
{
if( (*iter)->GetUsage() == CameraForm::Usage::MeshRender )
{
// const Buffer::ConstBuffer* ڵ auto ü
auto shadowCB = _shadowRenderer->IsWorking() ?
_shadowRenderer->GetShadowGlobalParamConstBuffer() : nullptr;
dynamic_cast<MeshCamera*>(*iter)->Render(_dx, _renderMgr, _lightManager, shadowCB, _shadowRenderer->GetNeverUseVSM(), GIPass);
}
else if( (*iter)->GetUsage() == CameraForm::Usage::UI )
dynamic_cast<UICamera*>(*iter)->Render(_dx);
}
CameraForm* mainCam = _cameraMgr->GetMainCamera();
if(mainCam)
{
ID3D11RenderTargetView* backBufferRTV = _dx->GetBackBufferRTV();
const RenderTexture* camRT = mainCam->GetRenderTarget();
MeshCamera* mainMeshCam = dynamic_cast<MeshCamera*>(mainCam);
_backBufferMaker->Render(backBufferRTV, camRT, nullptr, mainMeshCam->GetTBRParamConstBuffer());
}
_dx->GetSwapChain()->Present(0, 0);
OnRenderPost();
}
void Scene::Destroy()
{
OnDestroy();
DeleteAllObject();
_materialMgr->DeleteAll();
_backBufferMaker->Destroy();
_shadowRenderer->Destroy();
_renderMgr->Destroy();
_uiManager->Destroy();
_lightManager->Destroy();
_cameraMgr->Destroy();
_globalIllumination->Destroy();
}
void Scene::NextState()
{
_state = (State)(((int)_state + 1) % (int)State::Num);
}
void Scene::StopState()
{
_state = State::Stop;
}
void Scene::AddObject(Core::Object* object)
{
_rootObjects.Add(object->GetName(), object);
}
Core::Object* Scene::FindObject(const std::string& key)
{
Core::Object** objAddr = _rootObjects.Find(key);
return objAddr ? (*objAddr) : nullptr;
}
void Scene::DeleteObject(Core::Object* object)
{
std::string key = object->GetName();
Core::Object** objectAddr = _rootObjects.Find(key);
if(objectAddr)
{
Core::Object* object = (*objectAddr);
SAFE_DELETE(object);
_rootObjects.Delete(key);
}
}
void Scene::DeleteAllObject()
{
auto& objects = _rootObjects.GetVector();
for(auto iter = objects.begin(); iter != objects.end(); ++iter)
{
Core::Object* object = (*iter);
SAFE_DELETE(object);
}
_rootObjects.DeleteAll();
}
void Scene::Input(const Device::Win32::Mouse& mouse, const Device::Win32::Keyboard& keyboard)
{
if(_state == State::Loop)
OnInput(mouse, keyboard);
}
void Scene::ActivateGI(bool activate, uint dimension, float giSize)
{
if(activate == false)
{
if(_globalIllumination)
_globalIllumination->Destroy();
SAFE_DELETE(_globalIllumination);
}
else
{
if(_globalIllumination)
return;
_globalIllumination = new GlobalIllumination;
_globalIllumination->Initialize(_dx, dimension, giSize);
}
}<|endoftext|> |
<commit_before>/*
** MAL-conduit.cc
**
** Copyright (C) 2002 by Reinhold Kainhofer
*/
/*
** 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 in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
**
**
** Specific permission is granted for this code to be linked to libmal
** (this is necessary because the libmal license is not GPL-compatible).
*/
/*
** Bug reports and questions can be sent to [email protected]
*/
#include "options.h"
#include <qregexp.h>
#include <kconfig.h>
#include <kdebug.h>
#include "mal-factory.h"
#include "mal-conduit.moc"
#include <libmal.h>
#include "malconduitSettings.h"
// Something to allow us to check what revision
// the modules are that make up a binary distribution.
const char *MAL_conduit_id =
"$Id$";
static MALConduit *conduitInstance=0L;
int malconduit_logf(const char *, ...) __attribute__ ((format (printf, 1, 2)));
int malconduit_logf(const char *format, ...)
{
FUNCTIONSETUP;
va_list val;
int rval;
va_start(val, format);
#define WRITE_MAX_BUF 4096
char msg[WRITE_MAX_BUF];
msg[0]='\0';
rval=vsnprintf(&msg[0], sizeof(msg), format, val);
va_end(val);
if (rval == -1) {
msg[WRITE_MAX_BUF-1] = '\0';
rval=WRITE_MAX_BUF-1;
}
if (conduitInstance)
{
conduitInstance->printLogMessage(msg);
}
else
{
// write out to stderr
kdWarning()<<msg<<endl;
}
return rval;
}
MALConduit::MALConduit(KPilotDeviceLink * o,
const char *n,
const QStringList & a) :
ConduitAction(o, n, a)
{
FUNCTIONSETUP;
#ifdef LIBMAL20
register_printStatusHook(malconduit_logf);
register_printErrorHook(malconduit_logf);
#endif
conduitInstance=this;
#ifdef DEBUG
DEBUGCONDUIT<<MAL_conduit_id<<endl;
#endif
fConduitName=i18n("MAL");
}
MALConduit::~MALConduit()
{
FUNCTIONSETUP;
}
void MALConduit::readConfig()
{
FUNCTIONSETUP;
MALConduitSettings::self()->readConfig();
#ifdef DEBUG
DEBUGCONDUIT<<"Last sync was "<<MALConduitSettings::lastMALSync().toString()<<endl;
#endif
}
void MALConduit::saveConfig()
{
FUNCTIONSETUP;
MALConduitSettings::setLastMALSync( QDateTime::currentDateTime() );
MALConduitSettings::self()->writeConfig();
}
bool MALConduit::skip()
{
QDateTime now=QDateTime::currentDateTime();
QDateTime lastSync=MALConduitSettings::lastMALSync();
if (!lastSync.isValid() || !now.isValid()) return false;
switch ( MALConduitSettings::syncFrequency() )
{
case MALConduitSettings::eEveryHour:
if ( (lastSync.secsTo(now)<=3600) && (lastSync.time().hour()==now.time().hour()) ) return true;
else return false;
case MALConduitSettings::eEveryDay:
if ( lastSync.date() == now.date() ) return true;
else return false;
case MALConduitSettings::eEveryWeek:
if ( (lastSync.daysTo(now)<=7) && ( lastSync.date().dayOfWeek()<=now.date().dayOfWeek()) ) return true;
else return false;
case MALConduitSettings::eEveryMonth:
if ( (lastSync.daysTo(now)<=31) && (lastSync.date().month()==now.date().month()) ) return true;
else return false;
case MALConduitSettings::eEverySync:
default:
return false;
}
return false;
}
/* virtual */ bool MALConduit::exec()
{
FUNCTIONSETUP;
DEBUGCONDUIT<<MAL_conduit_id<<endl;
readConfig();
// TODO: set the log/error message hooks of libmal here!!!
if (skip())
{
emit logMessage(i18n("Skipping MAL sync, because last synchronization was not long enough ago."));
emit syncDone(this);
return true;
}
// Now initiate the sync.
PalmSyncInfo* pInfo=syncInfoNew();
if (!pInfo) {
kdWarning() << k_funcinfo << ": Could not allocate SyncInfo!" << endl;
emit logError(i18n("MAL synchronization failed (no SyncInfo)."));
return false;
}
QString proxyServer( MALConduitSettings::proxyServer() );
int proxyPort( MALConduitSettings::proxyPort() );
// Set all proxy settings
switch (MALConduitSettings::proxyType())
{
case MALConduitSettings::eProxyHTTP:
if (proxyServer.isEmpty()) break;
#ifdef DEBUG
DEBUGCONDUIT<<" Using HTTP proxy server \""<<proxyServer<<
"\", Port "<<proxyPort<<", User "<<MALConduitSettings::proxyUser()<<
", Password "<<( (MALConduitSettings::proxyPassword().isEmpty())?QString("not "):QString())<<"set"
<<endl;
#endif
#ifdef LIBMAL20
setHttpProxy(const_cast<char *>(proxyServer.latin1()));
if (proxyPort>0 && proxyPort<65536) setHttpProxyPort( proxyPort );
else setHttpProxyPort(80);
#else
pInfo->httpProxy = new char[ proxyServer.length() + 1 ];
strncpy( pInfo->httpProxy, proxyServer.latin1(), proxyServer.length() );
if (proxyPort>0 && proxyPort<65536) pInfo->httpProxyPort = proxyPort;
else pInfo->httpProxyPort = 80;
#endif
if (!MALConduitSettings::proxyUser().isEmpty())
{
#ifdef LIBMAL20
setProxyUsername( const_cast<char *>(MALConduitSettings::proxyUser().latin1()) );
if (!MALConduitSettings::proxyPassword().isEmpty()) setProxyPassword( const_cast<char *>(MALConduitSettings::proxyPassword().latin1()) );
#else
pInfo->proxyUsername = new char[ MALConduitSettings::proxyUser().length() + 1 ];
strncpy( pInfo->proxyUsername, MALConduitSettings::proxyUser().latin1(), MALConduitSettings::proxyUser().length() );
// pInfo->proxyUsername = MALConduitSettings::proxyUser().latin1();
if (!MALConduitSettings::proxyPassword().isEmpty()) {
// pInfo->proxyPassword = MALConduitSettings::proxyPassword().latin1();
pInfo->proxyPassword = new char[ MALConduitSettings::proxyPassword().length() + 1 ];
strncpy( pInfo->proxyPassword, MALConduitSettings::proxyPassword().latin1(), MALConduitSettings::proxyPassword().length() );
}
#endif
}
break;
case MALConduitSettings::eProxySOCKS:
#ifdef DEBUG
DEBUGCONDUIT<<" Using SOCKS proxy server \""<<proxyServer<<"\", Port "<<proxyPort<<", User "<<MALConduitSettings::proxyUser()<<", Password "<<( (MALConduitSettings::proxyPassword().isEmpty())?QString("not "):QString() )<<"set"<<endl;
#endif
#ifdef LIBMAL20
setSocksProxy( const_cast<char *>(proxyServer.latin1()) );
if (proxyPort>0 && proxyPort<65536) setSocksProxyPort( proxyPort );
else setSocksProxyPort(1080);
#else
// pInfo->socksProxy = proxyServer.latin1();
pInfo->socksProxy = new char[ proxyServer.length() + 1 ];
strncpy( pInfo->socksProxy, proxyServer.latin1(), proxyServer.length() );
if (proxyPort>0 && proxyPort<65536) pInfo->socksProxyPort = proxyPort;
else pInfo->socksProxyPort = 1080;
#endif
break;
default:
break;
}
#ifdef LIBMAL20
malsync( pilotSocket(), pInfo);
#else
// TODO:
// register_printStatusHook(malconduit_logf);
// register_printErrorHook(malconduit_logf);
pInfo->pilot_rHandle = pilotSocket();
malsync( pInfo );
delete[] pInfo->httpProxy;
delete[] pInfo->proxyUsername;
delete[] pInfo->proxyPassword;
delete[] pInfo->socksProxy;
syncInfoFree(pInfo);
#endif
saveConfig();
emit syncDone(this);
return true;
}
void MALConduit::printLogMessage(QString msg)
{
FUNCTIONSETUP;
// Remove the pseudo-progressbar:
QString newmsg(msg);
newmsg.replace( QRegExp("^\\s*\\.*\\s*"), "");
newmsg.replace( QRegExp("\\s*\\.*\\s*$"), "");
if (newmsg.length()>0)
{
emit logMessage(newmsg);
}
}
<commit_msg>Update the malconduit to work correctly with libmal 0.40.<commit_after>/*
** MAL-conduit.cc
**
** Copyright (C) 2002 by Reinhold Kainhofer
*/
/*
** 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 in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
**
**
** Specific permission is granted for this code to be linked to libmal
** (this is necessary because the libmal license is not GPL-compatible).
*/
/*
** Bug reports and questions can be sent to [email protected]
*/
#include "options.h"
#include <qregexp.h>
#include <kconfig.h>
#include <kdebug.h>
#include "mal-factory.h"
#include "mal-conduit.moc"
#include <libmal.h>
#include "malconduitSettings.h"
// Something to allow us to check what revision
// the modules are that make up a binary distribution.
const char *MAL_conduit_id =
"$Id$";
static MALConduit *conduitInstance=0L;
int malconduit_logf(const char *, ...) __attribute__ ((format (printf, 1, 2)));
int malconduit_logf(const char *format, ...)
{
FUNCTIONSETUP;
va_list val;
int rval;
va_start(val, format);
#define WRITE_MAX_BUF 4096
char msg[WRITE_MAX_BUF];
msg[0]='\0';
rval=vsnprintf(&msg[0], sizeof(msg), format, val);
va_end(val);
if (rval == -1) {
msg[WRITE_MAX_BUF-1] = '\0';
rval=WRITE_MAX_BUF-1;
}
if (conduitInstance)
{
conduitInstance->printLogMessage(msg);
}
else
{
// write out to stderr
kdWarning()<<msg<<endl;
}
return rval;
}
#ifndef LIBMAL20
int32 cbTask (void * /*out*/,
int32 * /*returnErrorCode*/,
char *currentTask,
AGBool /*bufferable*/)
{
if (currentTask) {
malconduit_logf ("%s\n", currentTask);
}
return AGCLIENT_CONTINUE;
}
static int32 cbItem (void */*out*/,
int32 * /*returnErrorCode*/,
int32 /*currentItemNumber*/,
int32 /*totalItemCount*/,
char * /*currentItem*/)
{
// The log widget only supports writing out whole lines. You just can't add a single character
// to the last line. Thus I completely remove the pseudo-percentbar.
/* malconduit_logf (".");
if (currentItemNumber == totalItemCount) {
malconduit_logf ("\n");
}
*/
return AGCLIENT_CONTINUE;
}
#endif
MALConduit::MALConduit(KPilotDeviceLink * o,
const char *n,
const QStringList & a) :
ConduitAction(o, n, a)
{
FUNCTIONSETUP;
#ifdef LIBMAL20
register_printStatusHook(malconduit_logf);
register_printErrorHook(malconduit_logf);
#endif
conduitInstance=this;
#ifdef DEBUG
DEBUGCONDUIT<<MAL_conduit_id<<endl;
#endif
fConduitName=i18n("MAL");
}
MALConduit::~MALConduit()
{
FUNCTIONSETUP;
}
void MALConduit::readConfig()
{
FUNCTIONSETUP;
MALConduitSettings::self()->readConfig();
#ifdef DEBUG
DEBUGCONDUIT<<"Last sync was "<<MALConduitSettings::lastMALSync().toString()<<endl;
#endif
}
void MALConduit::saveConfig()
{
FUNCTIONSETUP;
MALConduitSettings::setLastMALSync( QDateTime::currentDateTime() );
MALConduitSettings::self()->writeConfig();
}
bool MALConduit::skip()
{
QDateTime now=QDateTime::currentDateTime();
QDateTime lastSync=MALConduitSettings::lastMALSync();
if (!lastSync.isValid() || !now.isValid()) return false;
switch ( MALConduitSettings::syncFrequency() )
{
case MALConduitSettings::eEveryHour:
if ( (lastSync.secsTo(now)<=3600) && (lastSync.time().hour()==now.time().hour()) ) return true;
else return false;
case MALConduitSettings::eEveryDay:
if ( lastSync.date() == now.date() ) return true;
else return false;
case MALConduitSettings::eEveryWeek:
if ( (lastSync.daysTo(now)<=7) && ( lastSync.date().dayOfWeek()<=now.date().dayOfWeek()) ) return true;
else return false;
case MALConduitSettings::eEveryMonth:
if ( (lastSync.daysTo(now)<=31) && (lastSync.date().month()==now.date().month()) ) return true;
else return false;
case MALConduitSettings::eEverySync:
default:
return false;
}
return false;
}
/* virtual */ bool MALConduit::exec()
{
FUNCTIONSETUP;
DEBUGCONDUIT<<MAL_conduit_id<<endl;
readConfig();
// TODO: set the log/error message hooks of libmal here!!!
if (skip())
{
emit logMessage(i18n("Skipping MAL sync, because last synchronization was not long enough ago."));
emit syncDone(this);
return true;
}
// Now initiate the sync.
PalmSyncInfo* pInfo=syncInfoNew();
if (!pInfo) {
kdWarning() << k_funcinfo << ": Could not allocate SyncInfo!" << endl;
emit logError(i18n("MAL synchronization failed (no SyncInfo)."));
return false;
}
QString proxyServer( MALConduitSettings::proxyServer() );
int proxyPort( MALConduitSettings::proxyPort() );
// Set all proxy settings
switch (MALConduitSettings::proxyType())
{
case MALConduitSettings::eProxyHTTP:
if (proxyServer.isEmpty()) break;
#ifdef DEBUG
DEBUGCONDUIT<<" Using HTTP proxy server \""<<proxyServer<<
"\", Port "<<proxyPort<<", User "<<MALConduitSettings::proxyUser()<<
", Password "<<( (MALConduitSettings::proxyPassword().isEmpty())?QString("not "):QString())<<"set"
<<endl;
#endif
#ifdef LIBMAL20
setHttpProxy(const_cast<char *>(proxyServer.latin1()));
if (proxyPort>0 && proxyPort<65536) setHttpProxyPort( proxyPort );
else setHttpProxyPort(80);
#else
pInfo->httpProxy = new char[ proxyServer.length() + 1 ];
strncpy( pInfo->httpProxy, proxyServer.latin1(), proxyServer.length() );
if (proxyPort>0 && proxyPort<65536) pInfo->httpProxyPort = proxyPort;
else pInfo->httpProxyPort = 80;
#endif
if (!MALConduitSettings::proxyUser().isEmpty())
{
#ifdef LIBMAL20
setProxyUsername( const_cast<char *>(MALConduitSettings::proxyUser().latin1()) );
if (!MALConduitSettings::proxyPassword().isEmpty()) setProxyPassword( const_cast<char *>(MALConduitSettings::proxyPassword().latin1()) );
#else
pInfo->proxyUsername = new char[ MALConduitSettings::proxyUser().length() + 1 ];
strncpy( pInfo->proxyUsername, MALConduitSettings::proxyUser().latin1(), MALConduitSettings::proxyUser().length() );
// pInfo->proxyUsername = MALConduitSettings::proxyUser().latin1();
if (!MALConduitSettings::proxyPassword().isEmpty()) {
// pInfo->proxyPassword = MALConduitSettings::proxyPassword().latin1();
pInfo->proxyPassword = new char[ MALConduitSettings::proxyPassword().length() + 1 ];
strncpy( pInfo->proxyPassword, MALConduitSettings::proxyPassword().latin1(), MALConduitSettings::proxyPassword().length() );
}
#endif
}
break;
case MALConduitSettings::eProxySOCKS:
#ifdef DEBUG
DEBUGCONDUIT<<" Using SOCKS proxy server \""<<proxyServer<<"\", Port "<<proxyPort<<", User "<<MALConduitSettings::proxyUser()<<", Password "<<( (MALConduitSettings::proxyPassword().isEmpty())?QString("not "):QString() )<<"set"<<endl;
#endif
#ifdef LIBMAL20
setSocksProxy( const_cast<char *>(proxyServer.latin1()) );
if (proxyPort>0 && proxyPort<65536) setSocksProxyPort( proxyPort );
else setSocksProxyPort(1080);
#else
// pInfo->socksProxy = proxyServer.latin1();
pInfo->socksProxy = new char[ proxyServer.length() + 1 ];
strncpy( pInfo->socksProxy, proxyServer.latin1(), proxyServer.length() );
if (proxyPort>0 && proxyPort<65536) pInfo->socksProxyPort = proxyPort;
else pInfo->socksProxyPort = 1080;
#endif
break;
default:
break;
}
#ifdef LIBMAL20
malsync( pilotSocket(), pInfo);
#else
pInfo->sd = pilotSocket();
pInfo->taskFunc = cbTask;
pInfo->itemFunc = cbItem;
malsync( pInfo );
delete[] pInfo->httpProxy;
delete[] pInfo->proxyUsername;
delete[] pInfo->proxyPassword;
delete[] pInfo->socksProxy;
syncInfoFree(pInfo);
#endif
saveConfig();
emit syncDone(this);
return true;
}
void MALConduit::printLogMessage(QString msg)
{
FUNCTIONSETUP;
// Remove the pseudo-progressbar:
QString newmsg(msg);
newmsg.replace( QRegExp("^\\s*\\.*\\s*"), "");
newmsg.replace( QRegExp("\\s*\\.*\\s*$"), "");
if (newmsg.length()>0)
{
emit logMessage(newmsg);
}
}
<|endoftext|> |
<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, [email protected]
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include <GL/glew.h>
#include "vvcanvas.h"
#include <virvo/vvdebugmsg.h>
#include <virvo/vvfileio.h>
#include <virvo/vvgltools.h>
#include <QSettings>
#include <QTimer>
#include <iostream>
using vox::vvObjView;
vvCanvas::vvCanvas(const QGLFormat& format, const QString& filename, QWidget* parent)
: QGLWidget(format, parent)
, _vd(NULL)
, _renderer(NULL)
, _projectionType(vox::vvObjView::PERSPECTIVE)
, _doubleBuffering(format.doubleBuffer())
, _superSamples(format.samples())
, _stillQuality(1.0f)
, _movingQuality(1.0f)
, _spinAnimation(false)
, _mouseButton(Qt::NoButton)
{
vvDebugMsg::msg(1, "vvCanvas::vvCanvas()");
if (filename != "")
{
_vd = new vvVolDesc(filename.toStdString().c_str());
}
else
{
// load default volume
_vd = new vvVolDesc;
_vd->vox[0] = 32;
_vd->vox[1] = 32;
_vd->vox[2] = 32;
_vd->frames = 0;
}
// init ui
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
// read persistent settings
QSettings settings;
QColor qcolor = settings.value("canvas/bgcolor").value<QColor>();
_bgColor = vvColor(qcolor.redF(), qcolor.greenF(), qcolor.blueF());
_animTimer = new QTimer(this);
connect(_animTimer, SIGNAL(timeout()), this, SLOT(incTimeStep()));
_spinTimer = new QTimer(this);
connect(_spinTimer, SIGNAL(timeout()), this, SLOT(repeatLastRotation()));
}
vvCanvas::~vvCanvas()
{
vvDebugMsg::msg(1, "vvCanvas::~vvCanvas()");
delete _renderer;
delete _vd;
}
void vvCanvas::setVolDesc(vvVolDesc* vd)
{
vvDebugMsg::msg(3, "vvCanvas::setVolDesc()");
delete _vd;
_vd = vd;
if (_vd != NULL)
{
createRenderer();
}
foreach (vvPlugin* plugin, _plugins)
{
plugin->setVolDesc(_vd);
}
std::string str;
_vd->makeInfoString(&str);
emit statusMessage(str);
emit newVolDesc(_vd);
}
void vvCanvas::setPlugins(const QList<vvPlugin*>& plugins)
{
vvDebugMsg::msg(3, "vvCanvas::setPlugins()");
_plugins = plugins;
}
vvVolDesc* vvCanvas::getVolDesc() const
{
vvDebugMsg::msg(3, "vvCanvas::getVolDesc()");
return _vd;
}
vvRenderer* vvCanvas::getRenderer() const
{
vvDebugMsg::msg(3, "vvCanvas::getRenderer()");
return _renderer;
}
void vvCanvas::loadCamera(const QString& filename)
{
vvDebugMsg::msg(3, "vvCanvas::loadCamera()");
QByteArray ba = filename.toLatin1();
_ov.loadCamera(ba.data());
}
void vvCanvas::saveCamera(const QString& filename)
{
vvDebugMsg::msg(3, "vvCanvas::saveCamera()");
QByteArray ba = filename.toLatin1();
_ov.saveCamera(ba.data());
}
void vvCanvas::initializeGL()
{
vvDebugMsg::msg(1, "vvCanvas::initializeGL()");
glewInit();
init();
}
void vvCanvas::paintGL()
{
vvDebugMsg::msg(3, "vvCanvas::paintGL()");
if (_renderer == NULL)
{
return;
}
if (_doubleBuffering)
{
glDrawBuffer(GL_BACK);
}
else
{
glDrawBuffer(GL_FRONT);
}
glClearColor(_bgColor[0], _bgColor[1], _bgColor[2], 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
_ov.setModelviewMatrix(vvObjView::CENTER);
foreach (vvPlugin* plugin, _plugins)
{
if (plugin->isActive())
{
plugin->prerender();
}
}
_renderer->renderVolumeGL();
foreach (vvPlugin* plugin, _plugins)
{
if (plugin->isActive())
{
plugin->postrender();
}
}
}
void vvCanvas::resizeGL(const int w, const int h)
{
vvDebugMsg::msg(3, "vvCanvas::resizeGL()");
glViewport(0, 0, w, h);
if (h > 0)
{
_ov.setAspectRatio(static_cast<float>(w) / static_cast<float>(h));
}
updateGL();
emit resized(QSize(w, h));
}
void vvCanvas::mouseMoveEvent(QMouseEvent* event)
{
vvDebugMsg::msg(3, "vvCanvas::mouseMoveEvent()");
switch (_mouseButton)
{
case Qt::LeftButton:
{
_lastRotation = _ov._camera.trackballRotation(width(), height(),
_lastMousePos.x(), _lastMousePos.y(),
event->pos().x(), event->pos().y());
if (_spinAnimation)
{
repeatLastRotation();
}
break;
}
case Qt::MiddleButton:
{
const float pixelInWorld = _ov.getViewportWidth() / static_cast<float>(width());
const float dx = static_cast<float>(event->pos().x() - _lastMousePos.x());
const float dy = static_cast<float>(event->pos().y() - _lastMousePos.y());
vvVector2f pan(pixelInWorld * dx, pixelInWorld * dy);
_ov._camera.translate(pan[0], -pan[1], 0.0f);
break;
}
case Qt::RightButton:
{
const float factor = event->pos().y() - _lastMousePos.y();
_ov._camera.translate(0.0f, 0.0f, factor);
break;
}
default:
break;
}
_lastMousePos = event->pos();
updateGL();
}
void vvCanvas::mousePressEvent(QMouseEvent* event)
{
vvDebugMsg::msg(3, "vvCanvas::mousePressEvent()");
_stillQuality = _renderer->getParameter(vvRenderer::VV_QUALITY);
_renderer->setParameter(vvRenderer::VV_QUALITY, _movingQuality);
_mouseButton = event->button();
_lastMousePos = event->pos();
_lastRotation.identity();
if (_spinAnimation)
{
_spinTimer->stop();
}
}
void vvCanvas::mouseReleaseEvent(QMouseEvent*)
{
vvDebugMsg::msg(3, "vvCanvas::mouseReleaseEvent()");
_mouseButton = Qt::NoButton;
_renderer->setParameter(vvRenderer::VV_QUALITY, _stillQuality);
updateGL();
}
void vvCanvas::init()
{
vvDebugMsg::msg(3, "vvCanvas::init()");
vvFileIO* fio = new vvFileIO;
fio->loadVolumeData(_vd, vvFileIO::ALL_DATA);
delete fio;
// default transfer function
if (_vd->tf.isEmpty())
{
_vd->tf.setDefaultAlpha(0, _vd->real[0], _vd->real[1]);
_vd->tf.setDefaultColors((_vd->chan == 1) ? 0 : 3, _vd->real[0], _vd->real[1]);
}
// init renderer
if (_vd != NULL)
{
_currentRenderer = "planar";
_currentOptions["voxeltype"] = "arb";
createRenderer();
}
updateProjection();
foreach (vvPlugin* plugin, _plugins)
{
plugin->setVolDesc(_vd);
}
emit newVolDesc(_vd);
}
void vvCanvas::createRenderer()
{
vvDebugMsg::msg(3, "vvCanvas::createRenderer()");
vvRenderState state;
if (_renderer)
{
state = *_renderer;
delete _renderer;
}
const float DEFAULT_OBJ_SIZE = 0.6f;
_vd->resizeEdgeMax(_ov.getViewportWidth() * DEFAULT_OBJ_SIZE);
_renderer = vvRendererFactory::create(_vd, state, _currentRenderer.c_str(), _currentOptions);
}
void vvCanvas::updateProjection()
{
vvDebugMsg::msg(3, "vvCanvas::updateProjection()");
if (_projectionType == vvObjView::PERSPECTIVE)
{
_ov.setProjection(vvObjView::PERSPECTIVE, vvObjView::DEF_FOV, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
}
else if (_projectionType == vvObjView::ORTHO)
{
_ov.setProjection(vvObjView::ORTHO, vvObjView::DEF_VIEWPORT_WIDTH, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
}
}
void vvCanvas::setCurrentFrame(const int frame)
{
vvDebugMsg::msg(3, "vvCanvas::setCurrentFrame()");
_renderer->setCurrentFrame(frame);
emit currentFrame(frame);
// inform plugins of new frame
foreach (vvPlugin* plugin, _plugins)
{
plugin->timestep();
}
updateGL();
}
void vvCanvas::setRenderer(const std::string& name, const vvRendererFactory::Options& options)
{
vvDebugMsg::msg(3, "vvCanvas::setRenderer()");
_currentRenderer = name;
_currentOptions = options;
createRenderer();
updateGL();
}
void vvCanvas::setParameter(vvParameters::ParameterType param, const vvParam& value)
{
vvDebugMsg::msg(3, "vvCanvas::setParameter()");
switch (param)
{
case vvParameters::VV_BG_COLOR:
_bgColor = value;
break;
case vvParameters::VV_DOUBLEBUFFERING:
_doubleBuffering = value;
break;
case vvParameters::VV_MOVING_QUALITY:
_movingQuality = value;
break;
case vvParameters::VV_SUPERSAMPLES:
_superSamples = value;
break;
case vvParameters::VV_PROJECTIONTYPE:
_projectionType = static_cast<vvObjView::ProjectionType>(value.asInt());
updateProjection();
case vvParameters::VV_SPIN_ANIMATION:
_spinAnimation = value;
break;
default:
break;
}
updateGL();
}
void vvCanvas::setParameter(vvRenderer::ParameterType param, const vvParam& value)
{
vvDebugMsg::msg(3, "vvCanvas::setParameter()");
if (_renderer != NULL)
{
_renderer->setParameter(param, value);
updateGL();
}
}
vvParam vvCanvas::getParameter(vvParameters::ParameterType param) const
{
switch (param)
{
case vvParameters::VV_BG_COLOR:
return _bgColor;
case vvParameters::VV_DOUBLEBUFFERING:
return _doubleBuffering;
case vvParameters::VV_SUPERSAMPLES:
return _superSamples;
case vvParameters::VV_PROJECTIONTYPE:
return static_cast<int>(_projectionType);
case vvParameters::VV_SPIN_ANIMATION:
return _spinAnimation;
default:
return vvParam();
}
}
vvParam vvCanvas::getParameter(vvRenderer::ParameterType param) const
{
if (_renderer != NULL)
{
return _renderer->getParameter(param);
}
return vvParam();
}
void vvCanvas::startAnimation(const double fps)
{
vvDebugMsg::msg(3, "vvCanvas::startAnimation()");
_vd->dt = 1.0f / static_cast<float>(fps);
const float delay = std::abs(_vd->dt * 1000.0f);
_animTimer->start(static_cast<int>(delay));
}
void vvCanvas::stopAnimation()
{
vvDebugMsg::msg(3, "vvCanvas::stopAnimation()");
_animTimer->stop();
}
void vvCanvas::setTimeStep(const int step)
{
vvDebugMsg::msg(3, "vvCanvas::setTimeStep()");
int f = step;
while (f < 0)
{
f += _vd->frames;
}
while (f >= _vd->frames)
{
f -= _vd->frames;
}
setCurrentFrame(f);
}
void vvCanvas::incTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::incTimeStep()");
int f = _renderer->getCurrentFrame();
f = (f >= _vd->frames - 1) ? 0 : f + 1;
setCurrentFrame(f);
}
void vvCanvas::decTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::decTimeStep()");
int f = _renderer->getCurrentFrame();
f = (f <= 0) ? _vd->frames - 1 : f - 1;
setCurrentFrame(f);
}
void vvCanvas::firstTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::firstTimeStep()");
setCurrentFrame(0);
}
void vvCanvas::lastTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::lastTimeStep()");
setCurrentFrame(_vd->frames - 1);
}
void vvCanvas::repeatLastRotation()
{
vvDebugMsg::msg(3, "vvCanvas::repeatLastRotation()");
_ov._camera.multiplyRight(_lastRotation);
updateGL();
const float spindelay = 0.05f;
const float delay = std::abs(spindelay * 1000.0f);
_spinTimer->start(static_cast<int>(delay));
}
<commit_msg>Adapt bound color to background color<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, [email protected]
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include <GL/glew.h>
#include "vvcanvas.h"
#include <virvo/vvdebugmsg.h>
#include <virvo/vvfileio.h>
#include <virvo/vvgltools.h>
#include <QSettings>
#include <QTimer>
#include <iostream>
using vox::vvObjView;
vvCanvas::vvCanvas(const QGLFormat& format, const QString& filename, QWidget* parent)
: QGLWidget(format, parent)
, _vd(NULL)
, _renderer(NULL)
, _projectionType(vox::vvObjView::PERSPECTIVE)
, _doubleBuffering(format.doubleBuffer())
, _superSamples(format.samples())
, _stillQuality(1.0f)
, _movingQuality(1.0f)
, _spinAnimation(false)
, _mouseButton(Qt::NoButton)
{
vvDebugMsg::msg(1, "vvCanvas::vvCanvas()");
if (filename != "")
{
_vd = new vvVolDesc(filename.toStdString().c_str());
}
else
{
// load default volume
_vd = new vvVolDesc;
_vd->vox[0] = 32;
_vd->vox[1] = 32;
_vd->vox[2] = 32;
_vd->frames = 0;
}
// init ui
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
// read persistent settings
QSettings settings;
QColor qcolor = settings.value("canvas/bgcolor").value<QColor>();
_bgColor = vvColor(qcolor.redF(), qcolor.greenF(), qcolor.blueF());
_animTimer = new QTimer(this);
connect(_animTimer, SIGNAL(timeout()), this, SLOT(incTimeStep()));
_spinTimer = new QTimer(this);
connect(_spinTimer, SIGNAL(timeout()), this, SLOT(repeatLastRotation()));
}
vvCanvas::~vvCanvas()
{
vvDebugMsg::msg(1, "vvCanvas::~vvCanvas()");
delete _renderer;
delete _vd;
}
void vvCanvas::setVolDesc(vvVolDesc* vd)
{
vvDebugMsg::msg(3, "vvCanvas::setVolDesc()");
delete _vd;
_vd = vd;
if (_vd != NULL)
{
createRenderer();
}
foreach (vvPlugin* plugin, _plugins)
{
plugin->setVolDesc(_vd);
}
std::string str;
_vd->makeInfoString(&str);
emit statusMessage(str);
emit newVolDesc(_vd);
}
void vvCanvas::setPlugins(const QList<vvPlugin*>& plugins)
{
vvDebugMsg::msg(3, "vvCanvas::setPlugins()");
_plugins = plugins;
}
vvVolDesc* vvCanvas::getVolDesc() const
{
vvDebugMsg::msg(3, "vvCanvas::getVolDesc()");
return _vd;
}
vvRenderer* vvCanvas::getRenderer() const
{
vvDebugMsg::msg(3, "vvCanvas::getRenderer()");
return _renderer;
}
void vvCanvas::loadCamera(const QString& filename)
{
vvDebugMsg::msg(3, "vvCanvas::loadCamera()");
QByteArray ba = filename.toLatin1();
_ov.loadCamera(ba.data());
}
void vvCanvas::saveCamera(const QString& filename)
{
vvDebugMsg::msg(3, "vvCanvas::saveCamera()");
QByteArray ba = filename.toLatin1();
_ov.saveCamera(ba.data());
}
void vvCanvas::initializeGL()
{
vvDebugMsg::msg(1, "vvCanvas::initializeGL()");
glewInit();
init();
}
void vvCanvas::paintGL()
{
vvDebugMsg::msg(3, "vvCanvas::paintGL()");
if (_renderer == NULL)
{
return;
}
if (_doubleBuffering)
{
glDrawBuffer(GL_BACK);
}
else
{
glDrawBuffer(GL_FRONT);
}
glClearColor(_bgColor[0], _bgColor[1], _bgColor[2], 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
_ov.setModelviewMatrix(vvObjView::CENTER);
foreach (vvPlugin* plugin, _plugins)
{
if (plugin->isActive())
{
plugin->prerender();
}
}
_renderer->renderVolumeGL();
foreach (vvPlugin* plugin, _plugins)
{
if (plugin->isActive())
{
plugin->postrender();
}
}
}
void vvCanvas::resizeGL(const int w, const int h)
{
vvDebugMsg::msg(3, "vvCanvas::resizeGL()");
glViewport(0, 0, w, h);
if (h > 0)
{
_ov.setAspectRatio(static_cast<float>(w) / static_cast<float>(h));
}
updateGL();
emit resized(QSize(w, h));
}
void vvCanvas::mouseMoveEvent(QMouseEvent* event)
{
vvDebugMsg::msg(3, "vvCanvas::mouseMoveEvent()");
switch (_mouseButton)
{
case Qt::LeftButton:
{
_lastRotation = _ov._camera.trackballRotation(width(), height(),
_lastMousePos.x(), _lastMousePos.y(),
event->pos().x(), event->pos().y());
if (_spinAnimation)
{
repeatLastRotation();
}
break;
}
case Qt::MiddleButton:
{
const float pixelInWorld = _ov.getViewportWidth() / static_cast<float>(width());
const float dx = static_cast<float>(event->pos().x() - _lastMousePos.x());
const float dy = static_cast<float>(event->pos().y() - _lastMousePos.y());
vvVector2f pan(pixelInWorld * dx, pixelInWorld * dy);
_ov._camera.translate(pan[0], -pan[1], 0.0f);
break;
}
case Qt::RightButton:
{
const float factor = event->pos().y() - _lastMousePos.y();
_ov._camera.translate(0.0f, 0.0f, factor);
break;
}
default:
break;
}
_lastMousePos = event->pos();
updateGL();
}
void vvCanvas::mousePressEvent(QMouseEvent* event)
{
vvDebugMsg::msg(3, "vvCanvas::mousePressEvent()");
_stillQuality = _renderer->getParameter(vvRenderer::VV_QUALITY);
_renderer->setParameter(vvRenderer::VV_QUALITY, _movingQuality);
_mouseButton = event->button();
_lastMousePos = event->pos();
_lastRotation.identity();
if (_spinAnimation)
{
_spinTimer->stop();
}
}
void vvCanvas::mouseReleaseEvent(QMouseEvent*)
{
vvDebugMsg::msg(3, "vvCanvas::mouseReleaseEvent()");
_mouseButton = Qt::NoButton;
_renderer->setParameter(vvRenderer::VV_QUALITY, _stillQuality);
updateGL();
}
void vvCanvas::init()
{
vvDebugMsg::msg(3, "vvCanvas::init()");
vvFileIO* fio = new vvFileIO;
fio->loadVolumeData(_vd, vvFileIO::ALL_DATA);
delete fio;
// default transfer function
if (_vd->tf.isEmpty())
{
_vd->tf.setDefaultAlpha(0, _vd->real[0], _vd->real[1]);
_vd->tf.setDefaultColors((_vd->chan == 1) ? 0 : 3, _vd->real[0], _vd->real[1]);
}
// init renderer
if (_vd != NULL)
{
_currentRenderer = "planar";
_currentOptions["voxeltype"] = "arb";
createRenderer();
}
updateProjection();
foreach (vvPlugin* plugin, _plugins)
{
plugin->setVolDesc(_vd);
}
emit newVolDesc(_vd);
}
void vvCanvas::createRenderer()
{
vvDebugMsg::msg(3, "vvCanvas::createRenderer()");
vvRenderState state;
if (_renderer)
{
state = *_renderer;
delete _renderer;
}
const float DEFAULT_OBJ_SIZE = 0.6f;
_vd->resizeEdgeMax(_ov.getViewportWidth() * DEFAULT_OBJ_SIZE);
_renderer = vvRendererFactory::create(_vd, state, _currentRenderer.c_str(), _currentOptions);
// set boundary color to inverse of background
vvColor invColor;
if (_bgColor[0] + _bgColor[1] + _bgColor[2] > 1.5f)
{
invColor = vvColor(0.0f, 0.0f, 0.0f);
}
else
{
invColor = vvColor(1.0f, 1.0f, 1.0f);
}
_renderer->setParameter(vvRenderState::VV_BOUND_COLOR, invColor);
_renderer->setParameter(vvRenderState::VV_CLIP_COLOR, invColor);
}
void vvCanvas::updateProjection()
{
vvDebugMsg::msg(3, "vvCanvas::updateProjection()");
if (_projectionType == vvObjView::PERSPECTIVE)
{
_ov.setProjection(vvObjView::PERSPECTIVE, vvObjView::DEF_FOV, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
}
else if (_projectionType == vvObjView::ORTHO)
{
_ov.setProjection(vvObjView::ORTHO, vvObjView::DEF_VIEWPORT_WIDTH, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
}
}
void vvCanvas::setCurrentFrame(const int frame)
{
vvDebugMsg::msg(3, "vvCanvas::setCurrentFrame()");
_renderer->setCurrentFrame(frame);
emit currentFrame(frame);
// inform plugins of new frame
foreach (vvPlugin* plugin, _plugins)
{
plugin->timestep();
}
updateGL();
}
void vvCanvas::setRenderer(const std::string& name, const vvRendererFactory::Options& options)
{
vvDebugMsg::msg(3, "vvCanvas::setRenderer()");
_currentRenderer = name;
_currentOptions = options;
createRenderer();
updateGL();
}
void vvCanvas::setParameter(vvParameters::ParameterType param, const vvParam& value)
{
vvDebugMsg::msg(3, "vvCanvas::setParameter()");
switch (param)
{
case vvParameters::VV_BG_COLOR:
_bgColor = value;
break;
case vvParameters::VV_DOUBLEBUFFERING:
_doubleBuffering = value;
break;
case vvParameters::VV_MOVING_QUALITY:
_movingQuality = value;
break;
case vvParameters::VV_SUPERSAMPLES:
_superSamples = value;
break;
case vvParameters::VV_PROJECTIONTYPE:
_projectionType = static_cast<vvObjView::ProjectionType>(value.asInt());
updateProjection();
case vvParameters::VV_SPIN_ANIMATION:
_spinAnimation = value;
break;
default:
break;
}
updateGL();
}
void vvCanvas::setParameter(vvRenderer::ParameterType param, const vvParam& value)
{
vvDebugMsg::msg(3, "vvCanvas::setParameter()");
if (_renderer != NULL)
{
_renderer->setParameter(param, value);
updateGL();
}
}
vvParam vvCanvas::getParameter(vvParameters::ParameterType param) const
{
switch (param)
{
case vvParameters::VV_BG_COLOR:
return _bgColor;
case vvParameters::VV_DOUBLEBUFFERING:
return _doubleBuffering;
case vvParameters::VV_SUPERSAMPLES:
return _superSamples;
case vvParameters::VV_PROJECTIONTYPE:
return static_cast<int>(_projectionType);
case vvParameters::VV_SPIN_ANIMATION:
return _spinAnimation;
default:
return vvParam();
}
}
vvParam vvCanvas::getParameter(vvRenderer::ParameterType param) const
{
if (_renderer != NULL)
{
return _renderer->getParameter(param);
}
return vvParam();
}
void vvCanvas::startAnimation(const double fps)
{
vvDebugMsg::msg(3, "vvCanvas::startAnimation()");
_vd->dt = 1.0f / static_cast<float>(fps);
const float delay = std::abs(_vd->dt * 1000.0f);
_animTimer->start(static_cast<int>(delay));
}
void vvCanvas::stopAnimation()
{
vvDebugMsg::msg(3, "vvCanvas::stopAnimation()");
_animTimer->stop();
}
void vvCanvas::setTimeStep(const int step)
{
vvDebugMsg::msg(3, "vvCanvas::setTimeStep()");
int f = step;
while (f < 0)
{
f += _vd->frames;
}
while (f >= _vd->frames)
{
f -= _vd->frames;
}
setCurrentFrame(f);
}
void vvCanvas::incTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::incTimeStep()");
int f = _renderer->getCurrentFrame();
f = (f >= _vd->frames - 1) ? 0 : f + 1;
setCurrentFrame(f);
}
void vvCanvas::decTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::decTimeStep()");
int f = _renderer->getCurrentFrame();
f = (f <= 0) ? _vd->frames - 1 : f - 1;
setCurrentFrame(f);
}
void vvCanvas::firstTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::firstTimeStep()");
setCurrentFrame(0);
}
void vvCanvas::lastTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::lastTimeStep()");
setCurrentFrame(_vd->frames - 1);
}
void vvCanvas::repeatLastRotation()
{
vvDebugMsg::msg(3, "vvCanvas::repeatLastRotation()");
_ov._camera.multiplyRight(_lastRotation);
updateGL();
const float spindelay = 0.05f;
const float delay = std::abs(spindelay * 1000.0f);
_spinTimer->start(static_cast<int>(delay));
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <algorithm>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include <drm_fourcc.h>
#include "kms++.h"
#include "test.h"
using namespace std;
using namespace kms;
static void main_loop(Card& card);
class OutputFlipHandler
{
public:
OutputFlipHandler(Connector* conn, Crtc* crtc, DumbFramebuffer* fb1, DumbFramebuffer* fb2)
: m_connector(conn), m_crtc(crtc), m_fbs { fb1, fb2 }, m_front_buf(1), m_bar_xpos(0)
{
}
~OutputFlipHandler()
{
delete m_fbs[0];
delete m_fbs[1];
}
OutputFlipHandler(const OutputFlipHandler& other) = delete;
OutputFlipHandler& operator=(const OutputFlipHandler& other) = delete;
void set_mode()
{
auto mode = m_connector->get_default_mode();
int r = m_crtc->set_mode(m_connector, *m_fbs[0], mode);
ASSERT(r == 0);
}
void handle_event()
{
m_front_buf = (m_front_buf + 1) % 2;
const int bar_width = 20;
const int bar_speed = 8;
auto crtc = m_crtc;
auto fb = m_fbs[(m_front_buf + 1) % 2];
ASSERT(crtc);
ASSERT(fb);
int current_xpos = m_bar_xpos;
int old_xpos = (current_xpos + (fb->width() - bar_width - bar_speed)) % (fb->width() - bar_width);
int new_xpos = (current_xpos + bar_speed) % (fb->width() - bar_width);
draw_color_bar(*fb, old_xpos, new_xpos, bar_width);
m_bar_xpos = new_xpos;
auto& card = crtc->card();
if (card.has_atomic()) {
int r;
AtomicReq req(card);
req.add(m_crtc, "FB_ID", fb->id());
r = req.test();
ASSERT(r == 0);
r = req.commit(this);
ASSERT(r == 0);
} else {
int r = crtc->page_flip(*fb, this);
ASSERT(r == 0);
}
}
private:
Connector* m_connector;
Crtc* m_crtc;
DumbFramebuffer* m_fbs[2];
int m_front_buf;
int m_bar_xpos;
};
int main()
{
Card card;
if (card.master() == false)
printf("Not DRM master, modeset may fail\n");
//card.print_short();
vector<OutputFlipHandler*> outputs;
for (auto pipe : card.get_connected_pipelines())
{
auto conn = pipe.connector;
auto crtc = pipe.crtc;
auto mode = conn->get_default_mode();
auto fb1 = new DumbFramebuffer(card, mode.hdisplay, mode.vdisplay, "XR24");
auto fb2 = new DumbFramebuffer(card, mode.hdisplay, mode.vdisplay, "XR24");
printf("conn %u, crtc %u, fb1 %u, fb2 %u\n", conn->id(), crtc->id(), fb1->id(), fb2->id());
auto output = new OutputFlipHandler(conn, crtc, fb1, fb2);
outputs.push_back(output);
}
for(auto out : outputs)
out->set_mode();
for(auto out : outputs)
out->handle_event();
main_loop(card);
for(auto out : outputs)
delete out;
}
static void page_flip_handler(int fd, unsigned int frame,
unsigned int sec, unsigned int usec,
void *data)
{
//printf("flip event %d, %d, %u, %u, %p\n", fd, frame, sec, usec, data);
auto out = (OutputFlipHandler*)data;
out->handle_event();
}
static void main_loop(Card& card)
{
drmEventContext ev = {
.version = DRM_EVENT_CONTEXT_VERSION,
.vblank_handler = 0,
.page_flip_handler = page_flip_handler,
};
fd_set fds;
FD_ZERO(&fds);
int fd = card.fd();
printf("press enter to exit\n");
while (true) {
int r;
FD_SET(0, &fds);
FD_SET(fd, &fds);
r = select(fd + 1, &fds, NULL, NULL, NULL);
if (r < 0) {
fprintf(stderr, "select() failed with %d: %m\n", errno);
break;
} else if (FD_ISSET(0, &fds)) {
fprintf(stderr, "exit due to user-input\n");
break;
} else if (FD_ISSET(fd, &fds)) {
drmHandleEvent(fd, &ev);
}
}
}
<commit_msg>db: use PageFlipHandler<commit_after>#include <cstdio>
#include <algorithm>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include <drm_fourcc.h>
#include "kms++.h"
#include "test.h"
using namespace std;
using namespace kms;
static void main_loop(Card& card);
class OutputFlipHandler : PageFlipHandlerBase
{
public:
OutputFlipHandler(Connector* conn, Crtc* crtc, DumbFramebuffer* fb1, DumbFramebuffer* fb2)
: m_connector(conn), m_crtc(crtc), m_fbs { fb1, fb2 }, m_front_buf(1), m_bar_xpos(0)
{
}
~OutputFlipHandler()
{
delete m_fbs[0];
delete m_fbs[1];
}
OutputFlipHandler(const OutputFlipHandler& other) = delete;
OutputFlipHandler& operator=(const OutputFlipHandler& other) = delete;
void set_mode()
{
auto mode = m_connector->get_default_mode();
int r = m_crtc->set_mode(m_connector, *m_fbs[0], mode);
ASSERT(r == 0);
}
void handle_page_flip(uint32_t frame, double time)
{
m_front_buf = (m_front_buf + 1) % 2;
const int bar_width = 20;
const int bar_speed = 8;
auto crtc = m_crtc;
auto fb = m_fbs[(m_front_buf + 1) % 2];
ASSERT(crtc);
ASSERT(fb);
int current_xpos = m_bar_xpos;
int old_xpos = (current_xpos + (fb->width() - bar_width - bar_speed)) % (fb->width() - bar_width);
int new_xpos = (current_xpos + bar_speed) % (fb->width() - bar_width);
draw_color_bar(*fb, old_xpos, new_xpos, bar_width);
m_bar_xpos = new_xpos;
auto& card = crtc->card();
if (card.has_atomic()) {
int r;
AtomicReq req(card);
req.add(m_crtc, "FB_ID", fb->id());
r = req.test();
ASSERT(r == 0);
r = req.commit(this);
ASSERT(r == 0);
} else {
int r = crtc->page_flip(*fb, this);
ASSERT(r == 0);
}
}
private:
Connector* m_connector;
Crtc* m_crtc;
DumbFramebuffer* m_fbs[2];
int m_front_buf;
int m_bar_xpos;
};
int main()
{
Card card;
if (card.master() == false)
printf("Not DRM master, modeset may fail\n");
//card.print_short();
vector<OutputFlipHandler*> outputs;
for (auto pipe : card.get_connected_pipelines())
{
auto conn = pipe.connector;
auto crtc = pipe.crtc;
auto mode = conn->get_default_mode();
auto fb1 = new DumbFramebuffer(card, mode.hdisplay, mode.vdisplay, "XR24");
auto fb2 = new DumbFramebuffer(card, mode.hdisplay, mode.vdisplay, "XR24");
printf("conn %u, crtc %u, fb1 %u, fb2 %u\n", conn->id(), crtc->id(), fb1->id(), fb2->id());
auto output = new OutputFlipHandler(conn, crtc, fb1, fb2);
outputs.push_back(output);
}
for(auto out : outputs)
out->set_mode();
for(auto out : outputs)
out->handle_page_flip(0, 0);
main_loop(card);
for(auto out : outputs)
delete out;
}
static void main_loop(Card& card)
{
fd_set fds;
FD_ZERO(&fds);
int fd = card.fd();
printf("press enter to exit\n");
while (true) {
int r;
FD_SET(0, &fds);
FD_SET(fd, &fds);
r = select(fd + 1, &fds, NULL, NULL, NULL);
if (r < 0) {
fprintf(stderr, "select() failed with %d: %m\n", errno);
break;
} else if (FD_ISSET(0, &fds)) {
fprintf(stderr, "exit due to user-input\n");
break;
} else if (FD_ISSET(fd, &fds)) {
card.call_page_flip_handlers();
}
}
}
<|endoftext|> |
<commit_before>// $Id: LogStream_test.C,v 1.6 2000/05/29 23:45:27 amoll Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/COMMON/logStream.h>
#include <sys/time.h>
#include <BALL/MATHS/common.h>
///////////////////////////
START_TEST(class_name, "$Id: LogStream_test.C,v 1.6 2000/05/29 23:45:27 amoll Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
using namespace std;
String filename;
LogStream* l1;
LogStream* l2;
CHECK(LogStream(bool associate_stdio = false))
l1 = new LogStream();
l2 = new LogStream(true);
TEST_NOT_EQUAL(l1, 0)
TEST_NOT_EQUAL(l2, 0)
RESULT
CHECK(~LogStream())
delete l1;
delete l2;
RESULT
CHECK(LogStream(LogStreamBuf* buf))
LogStream* l1;
LogStreamBuf* lb1;
l1 = new LogStream(lb1);
TEST_NOT_EQUAL(l1, 0)
RESULT
CHECK(rdbuf())
LogStream l1;
TEST_NOT_EQUAL(l1.rdbuf(), 0)
RESULT
CHECK(operator -> ())
LogStream l1;
l1->sync();
RESULT
CHECK(setLevel(int level))
LogStream l1;
l1 << "TEST1" <<endl;
l1.setLevel(99);
l1 << "TEST2" <<endl;
TEST_EQUAL(l1.getLineLevel(0), 0)
TEST_EQUAL(l1.getLineLevel(1), 99)
RESULT
CHECK(l1.getLevel())
LogStream l1;
TEST_EQUAL(l1.getLevel(), 0)
l1.setLevel(99);
TEST_EQUAL(l1.getLevel(), 99)
RESULT
CHECK(level(int n))
LogStream l1;
l1.level(99) << "TEST" <<endl;
TEST_EQUAL(l1.getNumberOfLines(), 1)
TEST_EQUAL(l1.getLineText(0), "TEST")
TEST_EQUAL(l1.getLineLevel(0), 99)
RESULT
CHECK(info(int n = 0))
LogStream l1;
l1.info() << "TEST" <<endl;
TEST_EQUAL(l1.getNumberOfLines(), 1)
TEST_EQUAL(l1.getLineText(0), "TEST")
TEST_EQUAL(l1.getLineLevel(0), LogStream::INFORMATION)
l1.info(1) << "TEST2" <<endl;
TEST_EQUAL(l1.getLineLevel(1), LogStream::INFORMATION + 1)
RESULT
CHECK(error(int n = 0))
LogStream l1;
l1.error() << "TEST" <<endl;
TEST_EQUAL(l1.getNumberOfLines(), 1)
TEST_EQUAL(l1.getLineText(0), "TEST")
TEST_EQUAL(l1.getLineLevel(0), LogStream::ERROR)
l1.error(1) << "TEST2" <<endl;
TEST_EQUAL(l1.getLineLevel(1), LogStream::ERROR + 1)
RESULT
CHECK(warn(int n = 0))
LogStream l1;
l1.warn() << "TEST" <<endl;
TEST_EQUAL(l1.getNumberOfLines(), 1)
TEST_EQUAL(l1.getLineText(0), "TEST")
TEST_EQUAL(l1.getLineLevel(0), LogStream::WARNING)
l1.warn(1) << "TEST2" <<endl;
TEST_EQUAL(l1.getLineLevel(1), LogStream::WARNING + 1)
RESULT
CHECK(insert(std::ostream& s, int min_level = INT_MIN, int max_level = INT_MAX))
NEW_TMP_FILE(filename)
LogStream l1;
ofstream s(filename.c_str(), std::ios::out);
l1.insert(s, 99, 99);
l1.level(98) << "X" << endl;
l1.level(99) << "1" << endl;
l1.info(99) << "2" << endl;
l1.level(100)<< "X" << endl;
TEST_EQUAL(l1.getNumberOfLines(), 4)
TEST_FILE(filename.c_str(), "data/LogStream_test_general.txt", false)
RESULT
CHECK(remove(std::ostream& s))
LogStream l1;
ofstream s;
l1.insert(s);
l1.remove(s);
RESULT
CHECK(insertNotification(const std::ostream& s, const Target& target))
// BAUSTELLE
RESULT
CHECK(removeNotification(const std::ostream& s))
// BAUSTELLE
RESULT
CHECK(setMinLevel(const std::ostream& s, int min_level))
NEW_TMP_FILE(filename)
LogStream l1;
ofstream s(filename.c_str(), std::ios::out);
l1.insert(s, 0);
l1.setMinLevel(s, 98);
l1.info(97) << "X" << endl;
l1.info(98) << "1" << endl;
l1.info(99) << "2" << endl;
TEST_EQUAL(l1.getNumberOfLines(), 3)
TEST_FILE(filename.c_str(), "data/LogStream_test_general.txt", false)
RESULT
CHECK(setMaxLevel(const std::ostream& s, int max_level))
NEW_TMP_FILE(filename)
LogStream l1;
ofstream s(filename.c_str(), std::ios::out);
l1.insert(s, 0);
l1.setMaxLevel(s, 98);
l1.info(97) << "1" << endl;
l1.info(98) << "2" << endl;
l1.info(99) << "X" << endl;
TEST_EQUAL(l1.getNumberOfLines(), 3)
TEST_FILE(filename.c_str(), "data/LogStream_test_general.txt", false)
RESULT
CHECK(setPrefix(const std::ostream& s, const string& prefix))
NEW_TMP_FILE(filename)
LogStream l1;
ofstream s(filename.c_str(), std::ios::out);;
l1.insert(s, 0);
l1.setPrefix(s, "%l"); //loglevel
l1.info(1) << " 1." << endl;
l1.setPrefix(s, "%y"); //message type ("Error", "Warning", "Information", "-")
l1.info(2) << " 2." << endl;
l1.setPrefix(s, "%T"); //time (HH:MM:SS)
l1.info(3) << " 3." << endl;
l1.setPrefix(s, "%t"); //time in short format (HH:MM)
l1.info(4) << " 4." << endl;
l1.setPrefix(s, "%D"); //date (DD.MM.YYYY)
l1.info(5) << " 5." << endl;
l1.setPrefix(s, "%d"); // date in short format (DD.MM.)
l1.info(6) << " 6." << endl;
l1.setPrefix(s, "%S"); //time and date (DD.MM.YYYY, HH:MM:SS)
l1.info(7) << " 7." << endl;
l1.setPrefix(s, "%s"); //time and date in short format (DD.MM., HH:MM)
l1.info(8) << " 8." << endl;
l1.setPrefix(s, "%%"); //percent sign (escape sequence)
l1.info(9) << " 9." << endl;
l1.setPrefix(s, ""); //no prefix
l1.info(10) << " 10." << endl;
TEST_EQUAL(l1.getNumberOfLines(), 10)
TEST_FILE(filename.c_str(), "data/LogStream_test_setPrefix.txt", true)
RESULT
CHECK(clear())
LogStream l1;
l1.error() << "TEST" <<endl;
l1.clear();
TEST_EQUAL(l1.getNumberOfLines(), 0)
RESULT
CHECK(getNumberOfLines(int min_level = INT_MIN, int max_level = INT_MAX))
LogStream l1;
TEST_EQUAL(l1.getNumberOfLines(), 0)
l1.error() << "TEST" <<endl;
TEST_EQUAL(l1.getNumberOfLines(), 1)
RESULT
CHECK(getLineText(Index index))
LogStream l1;
l1.error() << "TEST" <<endl;
TEST_EQUAL(l1.getLineText(0), "TEST")
RESULT
CHECK(getLineTime(Index index))
LogStream l1;
time_t timer;
timer = time(NULL);
l1.error() << "TEST" <<endl;
TEST_EQUAL(timer, l1.getLineTime(0))
TEST_EQUAL(Maths::isNear(timer, l1.getLineTime(0), (long)1), true)
RESULT
CHECK(getLineLevel(Index index))
LogStream l1;
l1.level(99) << "TEST" <<endl;
TEST_EQUAL(l1.getLineLevel(0), 99)
RESULT
CHECK(filterLines(const int min_level = INT_MIN, const int max_level = INT_MAX,
const time_t earliest = 0, const time_t latest = LONG_MAX, const string& s = ""))
LogStream l1;
using std::list;
list<int> liste;
l1.level(0) << "TEST1" << endl;
l1.level(1) << "TEST2" << endl;
l1.level(2) << "XXXXX" << endl;
time_t timer = time(NULL);
time_t x = timer;
while (x == timer)
{
x = time(NULL);
}
timer = time(NULL);
l1.level(3) << "XXXXX" << endl;
l1.level(4) << "TEST4" << endl;
TEST_EQUAL(l1.getNumberOfLines(), 5)
liste = l1.filterLines(1, 2, 0, LONG_MAX, "" );
TEST_EQUAL(liste.size(), 2)
TEST_EQUAL(liste.front(), 1)
liste.pop_front();
TEST_EQUAL(liste.front(), 2)
liste.clear();
liste = l1.filterLines(1, 2, 0, LONG_MAX, "XXXXX" );
TEST_EQUAL(liste.size(), 1)
TEST_EQUAL(liste.front(), 2)
liste.clear();
liste = l1.filterLines(3, 3, timer, LONG_MAX, "XXXXX");
TEST_EQUAL(liste.size(), 1)
TEST_EQUAL(liste.front(), 3)
liste.clear();
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>fixed: incorrect/incomplete test for constructor<commit_after>// $Id: LogStream_test.C,v 1.7 2000/06/07 09:35:07 oliver Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/COMMON/logStream.h>
#include <sys/time.h>
#include <BALL/MATHS/common.h>
///////////////////////////
START_TEST(class_name, "$Id: LogStream_test.C,v 1.7 2000/06/07 09:35:07 oliver Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
using namespace std;
String filename;
LogStream* l1;
LogStream* l2;
CHECK(LogStream(bool associate_stdio = false))
l1 = new LogStream();
l2 = new LogStream(true);
TEST_NOT_EQUAL(l1, 0)
TEST_NOT_EQUAL(l2, 0)
RESULT
CHECK(~LogStream())
delete l1;
delete l2;
RESULT
CHECK(LogStream(LogStreamBuf* buf))
LogStream* l1;
l1 = new LogStream((LogStreamBuf*)0);
TEST_NOT_EQUAL(l1, 0)
delete l1;
LogStream* l2;
LogStreamBuf* lb2 = new LogStreamBuf;
l2 = new LogStream(lb2);
TEST_NOT_EQUAL(l2, 0)
delete l2;
RESULT
CHECK(rdbuf())
LogStream l1;
TEST_NOT_EQUAL(l1.rdbuf(), 0)
RESULT
CHECK(operator -> ())
LogStream l1;
l1->sync();
RESULT
CHECK(setLevel(int level))
LogStream l1;
l1 << "TEST1" <<endl;
l1.setLevel(99);
l1 << "TEST2" <<endl;
TEST_EQUAL(l1.getLineLevel(0), 0)
TEST_EQUAL(l1.getLineLevel(1), 99)
RESULT
CHECK(l1.getLevel())
LogStream l1;
TEST_EQUAL(l1.getLevel(), 0)
l1.setLevel(99);
TEST_EQUAL(l1.getLevel(), 99)
RESULT
CHECK(level(int n))
LogStream l1;
l1.level(99) << "TEST" <<endl;
TEST_EQUAL(l1.getNumberOfLines(), 1)
TEST_EQUAL(l1.getLineText(0), "TEST")
TEST_EQUAL(l1.getLineLevel(0), 99)
RESULT
CHECK(info(int n = 0))
LogStream l1;
l1.info() << "TEST" <<endl;
TEST_EQUAL(l1.getNumberOfLines(), 1)
TEST_EQUAL(l1.getLineText(0), "TEST")
TEST_EQUAL(l1.getLineLevel(0), LogStream::INFORMATION)
l1.info(1) << "TEST2" <<endl;
TEST_EQUAL(l1.getLineLevel(1), LogStream::INFORMATION + 1)
RESULT
CHECK(error(int n = 0))
LogStream l1;
l1.error() << "TEST" <<endl;
TEST_EQUAL(l1.getNumberOfLines(), 1)
TEST_EQUAL(l1.getLineText(0), "TEST")
TEST_EQUAL(l1.getLineLevel(0), LogStream::ERROR)
l1.error(1) << "TEST2" <<endl;
TEST_EQUAL(l1.getLineLevel(1), LogStream::ERROR + 1)
RESULT
CHECK(warn(int n = 0))
LogStream l1;
l1.warn() << "TEST" <<endl;
TEST_EQUAL(l1.getNumberOfLines(), 1)
TEST_EQUAL(l1.getLineText(0), "TEST")
TEST_EQUAL(l1.getLineLevel(0), LogStream::WARNING)
l1.warn(1) << "TEST2" <<endl;
TEST_EQUAL(l1.getLineLevel(1), LogStream::WARNING + 1)
RESULT
CHECK(insert(std::ostream& s, int min_level = INT_MIN, int max_level = INT_MAX))
NEW_TMP_FILE(filename)
LogStream l1;
ofstream s(filename.c_str(), std::ios::out);
l1.insert(s, 99, 99);
l1.level(98) << "X" << endl;
l1.level(99) << "1" << endl;
l1.info(99) << "2" << endl;
l1.level(100)<< "X" << endl;
TEST_EQUAL(l1.getNumberOfLines(), 4)
TEST_FILE(filename.c_str(), "data/LogStream_test_general.txt", false)
RESULT
CHECK(remove(std::ostream& s))
LogStream l1;
ofstream s;
l1.insert(s);
l1.remove(s);
RESULT
CHECK(insertNotification(const std::ostream& s, const Target& target))
// BAUSTELLE
RESULT
CHECK(removeNotification(const std::ostream& s))
// BAUSTELLE
RESULT
CHECK(setMinLevel(const std::ostream& s, int min_level))
NEW_TMP_FILE(filename)
LogStream l1;
ofstream s(filename.c_str(), std::ios::out);
l1.insert(s, 0);
l1.setMinLevel(s, 98);
l1.info(97) << "X" << endl;
l1.info(98) << "1" << endl;
l1.info(99) << "2" << endl;
TEST_EQUAL(l1.getNumberOfLines(), 3)
TEST_FILE(filename.c_str(), "data/LogStream_test_general.txt", false)
RESULT
CHECK(setMaxLevel(const std::ostream& s, int max_level))
NEW_TMP_FILE(filename)
LogStream l1;
ofstream s(filename.c_str(), std::ios::out);
l1.insert(s, 0);
l1.setMaxLevel(s, 98);
l1.info(97) << "1" << endl;
l1.info(98) << "2" << endl;
l1.info(99) << "X" << endl;
TEST_EQUAL(l1.getNumberOfLines(), 3)
TEST_FILE(filename.c_str(), "data/LogStream_test_general.txt", false)
RESULT
CHECK(setPrefix(const std::ostream& s, const string& prefix))
NEW_TMP_FILE(filename)
LogStream l1;
ofstream s(filename.c_str(), std::ios::out);;
l1.insert(s, 0);
l1.setPrefix(s, "%l"); //loglevel
l1.info(1) << " 1." << endl;
l1.setPrefix(s, "%y"); //message type ("Error", "Warning", "Information", "-")
l1.info(2) << " 2." << endl;
l1.setPrefix(s, "%T"); //time (HH:MM:SS)
l1.info(3) << " 3." << endl;
l1.setPrefix(s, "%t"); //time in short format (HH:MM)
l1.info(4) << " 4." << endl;
l1.setPrefix(s, "%D"); //date (DD.MM.YYYY)
l1.info(5) << " 5." << endl;
l1.setPrefix(s, "%d"); // date in short format (DD.MM.)
l1.info(6) << " 6." << endl;
l1.setPrefix(s, "%S"); //time and date (DD.MM.YYYY, HH:MM:SS)
l1.info(7) << " 7." << endl;
l1.setPrefix(s, "%s"); //time and date in short format (DD.MM., HH:MM)
l1.info(8) << " 8." << endl;
l1.setPrefix(s, "%%"); //percent sign (escape sequence)
l1.info(9) << " 9." << endl;
l1.setPrefix(s, ""); //no prefix
l1.info(10) << " 10." << endl;
TEST_EQUAL(l1.getNumberOfLines(), 10)
TEST_FILE(filename.c_str(), "data/LogStream_test_setPrefix.txt", true)
RESULT
CHECK(clear())
LogStream l1;
l1.error() << "TEST" <<endl;
l1.clear();
TEST_EQUAL(l1.getNumberOfLines(), 0)
RESULT
CHECK(getNumberOfLines(int min_level = INT_MIN, int max_level = INT_MAX))
LogStream l1;
TEST_EQUAL(l1.getNumberOfLines(), 0)
l1.error() << "TEST" <<endl;
TEST_EQUAL(l1.getNumberOfLines(), 1)
RESULT
CHECK(getLineText(Index index))
LogStream l1;
l1.error() << "TEST" <<endl;
TEST_EQUAL(l1.getLineText(0), "TEST")
RESULT
CHECK(getLineTime(Index index))
LogStream l1;
time_t timer;
timer = time(NULL);
l1.error() << "TEST" <<endl;
TEST_EQUAL(timer, l1.getLineTime(0))
TEST_EQUAL(Maths::isNear(timer, l1.getLineTime(0), (long)1), true)
RESULT
CHECK(getLineLevel(Index index))
LogStream l1;
l1.level(99) << "TEST" <<endl;
TEST_EQUAL(l1.getLineLevel(0), 99)
RESULT
CHECK(filterLines(const int min_level = INT_MIN, const int max_level = INT_MAX,
const time_t earliest = 0, const time_t latest = LONG_MAX, const string& s = ""))
LogStream l1;
using std::list;
list<int> liste;
l1.level(0) << "TEST1" << endl;
l1.level(1) << "TEST2" << endl;
l1.level(2) << "XXXXX" << endl;
time_t timer = time(NULL);
time_t x = timer;
while (x == timer)
{
x = time(NULL);
}
timer = time(NULL);
l1.level(3) << "XXXXX" << endl;
l1.level(4) << "TEST4" << endl;
TEST_EQUAL(l1.getNumberOfLines(), 5)
liste = l1.filterLines(1, 2, 0, LONG_MAX, "" );
TEST_EQUAL(liste.size(), 2)
TEST_EQUAL(liste.front(), 1)
liste.pop_front();
TEST_EQUAL(liste.front(), 2)
liste.clear();
liste = l1.filterLines(1, 2, 0, LONG_MAX, "XXXXX" );
TEST_EQUAL(liste.size(), 1)
TEST_EQUAL(liste.front(), 2)
liste.clear();
liste = l1.filterLines(3, 3, timer, LONG_MAX, "XXXXX");
TEST_EQUAL(liste.size(), 1)
TEST_EQUAL(liste.front(), 3)
liste.clear();
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|> |
<commit_before>// Given an array S of n integers, are there elements a, b, c in S such that a +
// b + c = 0? Find all unique triplets in the array which gives the sum of zero.
// Note: The solution set must not contain duplicate triplets.
// For example, given array S = [-1, 0, 1, 2, -1, -4],
// A solution set is:
// [
// [-1, 0, 1],
// [-1, -1, 2]
// ]
class Solution {
public:
vector<vector<int>> threeSum(vector<int> &nums) {
sort(nums.begin(), nums.end());
if (*num.begin() > 0 || *(nums.end() - 1) < 0)
return vector<vector<int>>();
set<vector<int>> result;
if (nums[i] + nums[j] > 0)
return vector<vector<int>>(result.begin(), result.end());
}
};<commit_msg>working 015<commit_after>// Given an array S of n integers, are there elements a, b, c in S such that a +
// b + c = 0? Find all unique triplets in the array which gives the sum of zero.
// Note: The solution set must not contain duplicate triplets.
// For example, given array S = [-1, 0, 1, 2, -1, -4],
// A solution set is:
// [
// [-1, 0, 1],
// [-1, -1, 2]
// ]
class Solution {
public:
vector<vector<int>> threeSum(vector<int> &nums) {
sort(nums.begin(), nums.end()); // nlog(n)
vector<vector<int>> result;
int sz = nums.size();
// O(n^2)
for (int i = 0; i < sz - 2; ++i) {
int j = i + 1, k = sz - 1;
while (j < k) {
if (nums[j] + nums[k] < -nums[i])
++j;
else if (nums[j] + nums[k] > -nums[i])
--k;
else {
// acutally i, j, k; just combine j++ and k-- here.
result.push_back({nums[i], nums[j++], nums[k--]});
// bypassing same elements (j, k)
while (j < k && nums[j] == nums[j - 1])
++j;
while (j < k && nums[k] == nums[k + 1])
--k;
}
}
// bypassing same elements (i)
while (i < sz - 1 && nums[i + 1] == nums[i])
++i;
}
return result;
}
};<|endoftext|> |
<commit_before>/**
* Appcelerator Titanium Mobile
* Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include <jni.h>
#include <v8.h>
#include "TypeConverter.h"
#include "JNIUtil.h"
#include "JavaObject.h"
#include "ProxyFactory.h"
using namespace titanium;
/****************************** public methods ******************************/
jshort TypeConverter::jsNumberToJavaShort(v8::Handle<v8::Number> jsNumber)
{
return ((jshort) jsNumber->Value());
}
v8::Handle<v8::Number> TypeConverter::javaShortToJsNumber(jshort javaShort)
{
return v8::Number::New((double) javaShort);
}
jint TypeConverter::jsNumberToJavaInt(v8::Handle<v8::Number> jsNumber)
{
return ((jint) jsNumber->Value());
}
v8::Handle<v8::Number> TypeConverter::javaIntToJsNumber(jint javaInt)
{
return v8::Number::New((double) javaInt);
}
jlong TypeConverter::jsNumberToJavaLong(v8::Handle<v8::Number> jsNumber)
{
return ((jlong) jsNumber->Value());
}
v8::Handle<v8::Number> TypeConverter::javaLongToJsNumber(jlong javaLong)
{
return v8::Number::New((double) javaLong);
}
jfloat TypeConverter::jsNumberToJavaFloat(v8::Handle<v8::Number> jsNumber)
{
return ((jfloat) jsNumber->Value());
}
v8::Handle<v8::Number> TypeConverter::javaFloatToJsNumber(jfloat javaFloat)
{
return v8::Number::New((double) javaFloat);
}
jdouble TypeConverter::jsNumberToJavaDouble(v8::Handle<v8::Number> jsNumber)
{
return ((jdouble) jsNumber->Value());
}
v8::Handle<v8::Number> TypeConverter::javaDoubleToJsNumber(jdouble javaDouble)
{
return v8::Number::New(javaDouble);
}
jboolean TypeConverter::jsBooleanToJavaBoolean(v8::Handle<v8::Boolean> jsBoolean)
{
return (jsBoolean->Value()) == JNI_TRUE;
}
v8::Handle<v8::Boolean> TypeConverter::javaBooleanToJsBoolean(jboolean javaBoolean)
{
return v8::Boolean::New((bool) javaBoolean);
}
jstring TypeConverter::jsStringToJavaString(v8::Handle<v8::String> jsString)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return NULL;
}
v8::String::Value javaString(jsString);
return env->NewString(*javaString, javaString.length());
}
v8::Handle<v8::String> TypeConverter::javaStringToJsString(jstring javaString)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return v8::Handle<v8::String>();
}
const char *nativeString = env->GetStringUTFChars(javaString, 0);
int nativeStringLength = env->GetStringUTFLength(javaString);
v8::Handle<v8::String> jsString = v8::String::New(nativeString, nativeStringLength);
env->ReleaseStringUTFChars(javaString, nativeString);
return jsString;
}
jobject TypeConverter::jsDateToJavaDate(v8::Handle<v8::Date> jsDate)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return NULL;
}
return env->NewObject(JNIUtil::dateClass, JNIUtil::dateInitMethod, (jlong) jsDate->NumberValue());
}
jlong TypeConverter::jsDateToJavaLong(v8::Handle<v8::Date> jsDate)
{
return (jlong) jsDate->NumberValue();
}
v8::Handle<v8::Date> TypeConverter::javaDateToJsDate(jobject javaDate)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return v8::Handle<v8::Date>();
}
jlong epochTime = env->CallLongMethod(javaDate, JNIUtil::dateGetTimeMethod);
return v8::Handle<v8::Date>::Cast(v8::Date::New((double) epochTime));
}
v8::Handle<v8::Date> TypeConverter::javaLongToJsDate(jlong javaLong)
{
return v8::Handle<v8::Date>::Cast(v8::Date::New((double) javaLong));
}
jarray TypeConverter::jsArrayToJavaArray(v8::Handle<v8::Array> jsArray)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return NULL;
}
int arrayLength = jsArray->Length();
jobjectArray javaArray = env->NewObjectArray(arrayLength, JNIUtil::objectClass, NULL);
for (int i = 0; i < arrayLength; i++) {
v8::Local<v8::Value> element = jsArray->Get(i);
jobject javaObject = jsValueToJavaObject(element);
env->SetObjectArrayElement(javaArray, i, javaObject);
env->DeleteLocalRef(javaObject);
}
return javaArray;
}
v8::Handle<v8::Array> TypeConverter::javaArrayToJsArray(jbooleanArray javaBooleanArray)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return v8::Handle<v8::Array>();
}
int arrayLength = env->GetArrayLength(javaBooleanArray);
v8::Handle<v8::Array> jsArray = v8::Array::New(arrayLength);
jboolean *arrayElements = env->GetBooleanArrayElements(javaBooleanArray, 0);
for (int i = 0; i < arrayLength; i++) {
jsArray->Set((uint32_t) i, v8::Boolean::New(arrayElements[i]));
}
return jsArray;
}
v8::Handle<v8::Array> TypeConverter::javaArrayToJsArray(jshortArray javaShortArray)
{
return javaDoubleArrayToJsNumberArray((jdoubleArray) javaShortArray);
}
v8::Handle<v8::Array> TypeConverter::javaArrayToJsArray(jintArray javaIntArray)
{
return javaDoubleArrayToJsNumberArray((jdoubleArray) javaIntArray);
}
v8::Handle<v8::Array> TypeConverter::javaArrayToJsArray(jlongArray javaLongArray)
{
return javaDoubleArrayToJsNumberArray((jdoubleArray) javaLongArray);
}
v8::Handle<v8::Array> TypeConverter::javaArrayToJsArray(jfloatArray javaFloatArray)
{
return javaDoubleArrayToJsNumberArray((jdoubleArray) javaFloatArray);
}
v8::Handle<v8::Array> TypeConverter::javaArrayToJsArray(jdoubleArray javaDoubleArray)
{
return javaDoubleArrayToJsNumberArray((jdoubleArray) javaDoubleArray);
}
v8::Handle<v8::Array> TypeConverter::javaArrayToJsArray(jobjectArray javaObjectArray)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return v8::Handle<v8::Array>();
}
int arrayLength = env->GetArrayLength(javaObjectArray);
v8::Handle<v8::Array> jsArray = v8::Array::New(arrayLength);
for (int i = 0; i < arrayLength; i++) {
jobject javaArrayElement = env->GetObjectArrayElement(javaObjectArray, i);
v8::Handle<v8::Value> jsArrayElement = TypeConverter::javaObjectToJsValue(javaArrayElement);
jsArray->Set((uint32_t) i, jsArrayElement);
env->DeleteLocalRef(javaArrayElement);
}
return jsArray;
}
// converts js value to java object and recursively converts sub objects if this
// object is a container type
jobject TypeConverter::jsValueToJavaObject(v8::Local<v8::Value> jsValue)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return NULL;
}
if (jsValue->IsNumber()) {
jdouble javaDouble = TypeConverter::jsNumberToJavaDouble(jsValue->ToNumber());
return env->NewObject(JNIUtil::doubleClass, JNIUtil::doubleInitMethod, javaDouble);
} else if (jsValue->IsBoolean()) {
jboolean javaBoolean = TypeConverter::jsBooleanToJavaBoolean(jsValue->ToBoolean());
return env->NewObject(JNIUtil::booleanClass, JNIUtil::booleanInitMethod, javaBoolean);
} else if (jsValue->IsString()) {
return TypeConverter::jsStringToJavaString(jsValue->ToString());
} else if (jsValue->IsDate()) {
jlong javaLong = TypeConverter::jsDateToJavaLong(v8::Handle<v8::Date>::Cast(jsValue));
return env->NewObject(JNIUtil::longClass, JNIUtil::longInitMethod, javaLong);
} else if (jsValue->IsArray()) {
return TypeConverter::jsArrayToJavaArray(v8::Handle<v8::Array>::Cast(jsValue));
} else if (jsValue->IsObject()) {
v8::Handle<v8::Object> jsObject = jsValue->ToObject();
if (JavaObject::isJavaObject(jsObject)) {
JavaObject *javaObject = JavaObject::Unwrap<JavaObject>(jsObject);
return javaObject->getJavaObject();
} else {
v8::Handle<v8::Array> objectKeys = jsObject->GetOwnPropertyNames();
int numKeys = objectKeys->Length();
jobject javaHashMap = env->NewObject(JNIUtil::hashMapClass, JNIUtil::hashMapInitMethod, numKeys);
for (int i = 0; i < numKeys; i++) {
v8::Local<v8::Value> jsObjectPropertyKey = objectKeys->Get((uint32_t) i);
jobject javaObjectPropertyKey = TypeConverter::jsValueToJavaObject(jsObjectPropertyKey);
v8::Local<v8::Value> jsObjectPropertyValue = jsObject->Get(jsObjectPropertyKey);
jobject javaObjectPropertyValue = TypeConverter::jsValueToJavaObject(jsObjectPropertyValue);
env->CallObjectMethod(javaHashMap, JNIUtil::hashMapPutMethod, javaObjectPropertyKey,
javaObjectPropertyValue);
}
return javaHashMap;
}
}
return NULL;
}
// converts java object to js value and recursively converts sub objects if this
// object is a container type
v8::Handle<v8::Value> TypeConverter::javaObjectToJsValue(jobject javaObject)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return v8::Handle<v8::Value>();
}
jclass javaObjectClass = env->GetObjectClass(javaObject);
if (env->IsInstanceOf(javaObjectClass, JNIUtil::numberClass)) {
jdouble javaDouble = env->CallDoubleMethod(javaObject, JNIUtil::numberDoubleValueMethod);
return v8::Number::New((double) javaDouble);
} else if (env->IsInstanceOf(javaObject, JNIUtil::stringClass)) {
return v8::String::New(env->GetStringChars((jstring) javaObject, 0));
} else if (env->IsInstanceOf(javaObjectClass, JNIUtil::dateClass)) {
return TypeConverter::javaDateToJsDate(javaObject);
} else if (env->IsInstanceOf(javaObjectClass, JNIUtil::hashMapClass)) {
v8::Handle<v8::Object> jsObject = v8::Object::New();
jobject hashMapSet = env->CallObjectMethod(javaObject, JNIUtil::hashMapKeySetMethod);
jobjectArray hashMapKeys = (jobjectArray) env->CallObjectMethod(hashMapSet, JNIUtil::setToArrayMethod);
env->DeleteLocalRef(hashMapSet);
int hashMapKeysLength = env->GetArrayLength(hashMapKeys);
for (int i = 0; i < hashMapKeysLength; i++) {
jobject javaPairKey = env->GetObjectArrayElement(hashMapKeys, i);
v8::Handle<v8::Value> jsPairKey = TypeConverter::javaObjectToJsValue(javaPairKey);
jobject javaPairValue = env->CallObjectMethod(javaObject, JNIUtil::hashMapGetMethod, javaPairKey);
env->DeleteLocalRef(javaPairKey);
jsObject->Set(jsPairKey, TypeConverter::javaObjectToJsValue(javaPairValue));
env->DeleteLocalRef(javaPairValue);
}
env->DeleteLocalRef(hashMapKeys);
return jsObject;
} else if (env->IsInstanceOf(javaObjectClass, JNIUtil::krollProxyClass)) {
jlong v8ObjectPointer = env->CallLongMethod(javaObject, JNIUtil::krollProxyGetV8ObjectPointerMethod);
if (v8ObjectPointer > 0) {
v8::Handle<v8::Object> v8ObjectPointerHandle((v8::Object*) v8ObjectPointer);
return v8ObjectPointerHandle;
} else {
ProxyFactory *proxyFactory = ProxyFactory::factoryForClass(javaObjectClass);
v8::Handle<v8::Object> proxyHandle = proxyFactory->create(javaObject);
return proxyHandle;
}
}
return v8::Handle<v8::Value>();
}
/****************************** private methods ******************************/
// used mainly by the array conversion methods when converting java numeric types
// arrays to to the generic js number type
v8::Handle<v8::Array> TypeConverter::javaDoubleArrayToJsNumberArray(jdoubleArray javaDoubleArray)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return v8::Handle<v8::Array>();
}
int arrayLength = env->GetArrayLength(javaDoubleArray);
v8::Handle<v8::Array> jsArray = v8::Array::New(arrayLength);
jdouble *arrayElements = env->GetDoubleArrayElements(javaDoubleArray, 0);
for (int i = 0; i < arrayLength; i++) {
jsArray->Set((uint32_t) i, v8::Number::New(arrayElements[i]));
}
return jsArray;
}
<commit_msg>changes to converter when changing proxy types<commit_after>/**
* Appcelerator Titanium Mobile
* Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include <jni.h>
#include <v8.h>
#include "TypeConverter.h"
#include "JNIUtil.h"
#include "JavaObject.h"
#include "ProxyFactory.h"
#include "V8Runtime.h"
using namespace titanium;
/****************************** public methods ******************************/
jshort TypeConverter::jsNumberToJavaShort(v8::Handle<v8::Number> jsNumber)
{
return ((jshort) jsNumber->Value());
}
v8::Handle<v8::Number> TypeConverter::javaShortToJsNumber(jshort javaShort)
{
return v8::Number::New((double) javaShort);
}
jint TypeConverter::jsNumberToJavaInt(v8::Handle<v8::Number> jsNumber)
{
return ((jint) jsNumber->Value());
}
v8::Handle<v8::Number> TypeConverter::javaIntToJsNumber(jint javaInt)
{
return v8::Number::New((double) javaInt);
}
jlong TypeConverter::jsNumberToJavaLong(v8::Handle<v8::Number> jsNumber)
{
return ((jlong) jsNumber->Value());
}
v8::Handle<v8::Number> TypeConverter::javaLongToJsNumber(jlong javaLong)
{
return v8::Number::New((double) javaLong);
}
jfloat TypeConverter::jsNumberToJavaFloat(v8::Handle<v8::Number> jsNumber)
{
return ((jfloat) jsNumber->Value());
}
v8::Handle<v8::Number> TypeConverter::javaFloatToJsNumber(jfloat javaFloat)
{
return v8::Number::New((double) javaFloat);
}
jdouble TypeConverter::jsNumberToJavaDouble(v8::Handle<v8::Number> jsNumber)
{
return ((jdouble) jsNumber->Value());
}
v8::Handle<v8::Number> TypeConverter::javaDoubleToJsNumber(jdouble javaDouble)
{
return v8::Number::New(javaDouble);
}
jboolean TypeConverter::jsBooleanToJavaBoolean(v8::Handle<v8::Boolean> jsBoolean)
{
return (jsBoolean->Value()) == JNI_TRUE;
}
v8::Handle<v8::Boolean> TypeConverter::javaBooleanToJsBoolean(jboolean javaBoolean)
{
return v8::Boolean::New((bool) javaBoolean);
}
jstring TypeConverter::jsStringToJavaString(v8::Handle<v8::String> jsString)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return NULL;
}
v8::String::Value javaString(jsString);
return env->NewString(*javaString, javaString.length());
}
v8::Handle<v8::String> TypeConverter::javaStringToJsString(jstring javaString)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return v8::Handle<v8::String>();
}
const char *nativeString = env->GetStringUTFChars(javaString, 0);
int nativeStringLength = env->GetStringUTFLength(javaString);
v8::Handle<v8::String> jsString = v8::String::New(nativeString, nativeStringLength);
env->ReleaseStringUTFChars(javaString, nativeString);
return jsString;
}
jobject TypeConverter::jsDateToJavaDate(v8::Handle<v8::Date> jsDate)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return NULL;
}
return env->NewObject(JNIUtil::dateClass, JNIUtil::dateInitMethod, (jlong) jsDate->NumberValue());
}
jlong TypeConverter::jsDateToJavaLong(v8::Handle<v8::Date> jsDate)
{
return (jlong) jsDate->NumberValue();
}
v8::Handle<v8::Date> TypeConverter::javaDateToJsDate(jobject javaDate)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return v8::Handle<v8::Date>();
}
jlong epochTime = env->CallLongMethod(javaDate, JNIUtil::dateGetTimeMethod);
return v8::Handle<v8::Date>::Cast(v8::Date::New((double) epochTime));
}
v8::Handle<v8::Date> TypeConverter::javaLongToJsDate(jlong javaLong)
{
return v8::Handle<v8::Date>::Cast(v8::Date::New((double) javaLong));
}
jarray TypeConverter::jsArrayToJavaArray(v8::Handle<v8::Array> jsArray)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return NULL;
}
int arrayLength = jsArray->Length();
jobjectArray javaArray = env->NewObjectArray(arrayLength, JNIUtil::objectClass, NULL);
for (int i = 0; i < arrayLength; i++) {
v8::Local<v8::Value> element = jsArray->Get(i);
jobject javaObject = jsValueToJavaObject(element);
env->SetObjectArrayElement(javaArray, i, javaObject);
env->DeleteLocalRef(javaObject);
}
return javaArray;
}
v8::Handle<v8::Array> TypeConverter::javaArrayToJsArray(jbooleanArray javaBooleanArray)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return v8::Handle<v8::Array>();
}
int arrayLength = env->GetArrayLength(javaBooleanArray);
v8::Handle<v8::Array> jsArray = v8::Array::New(arrayLength);
jboolean *arrayElements = env->GetBooleanArrayElements(javaBooleanArray, 0);
for (int i = 0; i < arrayLength; i++) {
jsArray->Set((uint32_t) i, v8::Boolean::New(arrayElements[i]));
}
return jsArray;
}
v8::Handle<v8::Array> TypeConverter::javaArrayToJsArray(jshortArray javaShortArray)
{
return javaDoubleArrayToJsNumberArray((jdoubleArray) javaShortArray);
}
v8::Handle<v8::Array> TypeConverter::javaArrayToJsArray(jintArray javaIntArray)
{
return javaDoubleArrayToJsNumberArray((jdoubleArray) javaIntArray);
}
v8::Handle<v8::Array> TypeConverter::javaArrayToJsArray(jlongArray javaLongArray)
{
return javaDoubleArrayToJsNumberArray((jdoubleArray) javaLongArray);
}
v8::Handle<v8::Array> TypeConverter::javaArrayToJsArray(jfloatArray javaFloatArray)
{
return javaDoubleArrayToJsNumberArray((jdoubleArray) javaFloatArray);
}
v8::Handle<v8::Array> TypeConverter::javaArrayToJsArray(jdoubleArray javaDoubleArray)
{
return javaDoubleArrayToJsNumberArray((jdoubleArray) javaDoubleArray);
}
v8::Handle<v8::Array> TypeConverter::javaArrayToJsArray(jobjectArray javaObjectArray)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return v8::Handle<v8::Array>();
}
int arrayLength = env->GetArrayLength(javaObjectArray);
v8::Handle<v8::Array> jsArray = v8::Array::New(arrayLength);
for (int i = 0; i < arrayLength; i++) {
jobject javaArrayElement = env->GetObjectArrayElement(javaObjectArray, i);
v8::Handle<v8::Value> jsArrayElement = TypeConverter::javaObjectToJsValue(javaArrayElement);
jsArray->Set((uint32_t) i, jsArrayElement);
env->DeleteLocalRef(javaArrayElement);
}
return jsArray;
}
// converts js value to java object and recursively converts sub objects if this
// object is a container type
jobject TypeConverter::jsValueToJavaObject(v8::Local<v8::Value> jsValue)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return NULL;
}
if (jsValue->IsNumber()) {
jdouble javaDouble = TypeConverter::jsNumberToJavaDouble(jsValue->ToNumber());
return env->NewObject(JNIUtil::doubleClass, JNIUtil::doubleInitMethod, javaDouble);
} else if (jsValue->IsBoolean()) {
jboolean javaBoolean = TypeConverter::jsBooleanToJavaBoolean(jsValue->ToBoolean());
return env->NewObject(JNIUtil::booleanClass, JNIUtil::booleanInitMethod, javaBoolean);
} else if (jsValue->IsString()) {
return TypeConverter::jsStringToJavaString(jsValue->ToString());
} else if (jsValue->IsDate()) {
jlong javaLong = TypeConverter::jsDateToJavaLong(v8::Handle<v8::Date>::Cast(jsValue));
return env->NewObject(JNIUtil::longClass, JNIUtil::longInitMethod, javaLong);
} else if (jsValue->IsArray()) {
return TypeConverter::jsArrayToJavaArray(v8::Handle<v8::Array>::Cast(jsValue));
} else if (jsValue->IsObject()) {
v8::Handle<v8::Object> jsObject = jsValue->ToObject();
if (JavaObject::isJavaObject(jsObject)) {
JavaObject *javaObject = JavaObject::Unwrap<JavaObject>(jsObject);
return javaObject->getJavaObject();
} else {
v8::Handle<v8::Array> objectKeys = jsObject->GetOwnPropertyNames();
int numKeys = objectKeys->Length();
jobject javaHashMap = env->NewObject(JNIUtil::hashMapClass, JNIUtil::hashMapInitMethod, numKeys);
for (int i = 0; i < numKeys; i++) {
v8::Local<v8::Value> jsObjectPropertyKey = objectKeys->Get((uint32_t) i);
jobject javaObjectPropertyKey = TypeConverter::jsValueToJavaObject(jsObjectPropertyKey);
v8::Local<v8::Value> jsObjectPropertyValue = jsObject->Get(jsObjectPropertyKey);
jobject javaObjectPropertyValue = TypeConverter::jsValueToJavaObject(jsObjectPropertyValue);
env->CallObjectMethod(javaHashMap, JNIUtil::hashMapPutMethod, javaObjectPropertyKey,
javaObjectPropertyValue);
}
return javaHashMap;
}
}
return NULL;
}
// converts java object to js value and recursively converts sub objects if this
// object is a container type
v8::Handle<v8::Value> TypeConverter::javaObjectToJsValue(jobject javaObject)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return v8::Handle<v8::Value>();
}
jclass javaObjectClass = env->GetObjectClass(javaObject);
if (env->IsInstanceOf(javaObjectClass, JNIUtil::numberClass)) {
jdouble javaDouble = env->CallDoubleMethod(javaObject, JNIUtil::numberDoubleValueMethod);
return v8::Number::New((double) javaDouble);
} else if (env->IsInstanceOf(javaObject, JNIUtil::stringClass)) {
return v8::String::New(env->GetStringChars((jstring) javaObject, 0));
} else if (env->IsInstanceOf(javaObjectClass, JNIUtil::dateClass)) {
return TypeConverter::javaDateToJsDate(javaObject);
} else if (env->IsInstanceOf(javaObjectClass, JNIUtil::hashMapClass)) {
v8::Handle<v8::Object> jsObject = v8::Object::New();
jobject hashMapSet = env->CallObjectMethod(javaObject, JNIUtil::hashMapKeySetMethod);
jobjectArray hashMapKeys = (jobjectArray) env->CallObjectMethod(hashMapSet, JNIUtil::setToArrayMethod);
env->DeleteLocalRef(hashMapSet);
int hashMapKeysLength = env->GetArrayLength(hashMapKeys);
for (int i = 0; i < hashMapKeysLength; i++) {
jobject javaPairKey = env->GetObjectArrayElement(hashMapKeys, i);
v8::Handle<v8::Value> jsPairKey = TypeConverter::javaObjectToJsValue(javaPairKey);
jobject javaPairValue = env->CallObjectMethod(javaObject, JNIUtil::hashMapGetMethod, javaPairKey);
env->DeleteLocalRef(javaPairKey);
jsObject->Set(jsPairKey, TypeConverter::javaObjectToJsValue(javaPairValue));
env->DeleteLocalRef(javaPairValue);
}
env->DeleteLocalRef(hashMapKeys);
return jsObject;
} else if (env->IsInstanceOf(javaObjectClass, JNIUtil::krollProxyClass)) {
jlong v8ObjectPointer = env->CallLongMethod(javaObject, JNIUtil::krollProxyGetV8ObjectPointerMethod);
if (v8ObjectPointer > 0) {
v8::Handle<v8::Object> v8ObjectPointerHandle((v8::Object*) v8ObjectPointer);
return v8ObjectPointerHandle;
} else {
ProxyFactory *proxyFactory = ProxyFactory::factoryForClass(javaObjectClass);
v8::Handle<v8::Object> proxyHandle = proxyFactory->create(javaObject);
// set the pointer back on the java proxy
V8Runtime::newObject(proxyHandle);
return proxyHandle;
}
}
return v8::Handle<v8::Value>();
}
/****************************** private methods ******************************/
// used mainly by the array conversion methods when converting java numeric types
// arrays to to the generic js number type
v8::Handle<v8::Array> TypeConverter::javaDoubleArrayToJsNumberArray(jdoubleArray javaDoubleArray)
{
JNIEnv *env = JNIUtil::getJNIEnv();
if (env == NULL) {
return v8::Handle<v8::Array>();
}
int arrayLength = env->GetArrayLength(javaDoubleArray);
v8::Handle<v8::Array> jsArray = v8::Array::New(arrayLength);
jdouble *arrayElements = env->GetDoubleArrayElements(javaDoubleArray, 0);
for (int i = 0; i < arrayLength; i++) {
jsArray->Set((uint32_t) i, v8::Number::New(arrayElements[i]));
}
return jsArray;
}
<|endoftext|> |
<commit_before><commit_msg>lib/core/object/io/writer: support tag values.<commit_after><|endoftext|> |
<commit_before>//
// Copyright 2014, 2015 Razer Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "OSVRPrivatePCH.h"
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
#include "OSVRInterfaceCollection.h"
#endif
#include "OSVREntryPoint.h"
#include <osvr/ClientKit/ServerAutoStartC.h>
#include "Runtime/Core/Public/Misc/DateTime.h"
DEFINE_LOG_CATEGORY(OSVREntryPointLog);
OSVREntryPoint::OSVREntryPoint()
{
osvrClientAttemptServerAutoStart();
osvrClientContext = osvrClientInit("com.osvr.unreal.plugin");
{
bool bClientContextOK = false;
bool bFailure = false;
auto begin = FDateTime::Now().GetSecond();
auto end = begin + 3;
while (FDateTime::Now().GetSecond() < end && !bClientContextOK && !bFailure)
{
bClientContextOK = osvrClientCheckStatus(osvrClientContext) == OSVR_RETURN_SUCCESS;
if (!bClientContextOK)
{
bFailure = osvrClientUpdate(osvrClientContext) == OSVR_RETURN_FAILURE;
if (bFailure)
{
UE_LOG(OSVREntryPointLog, Warning, TEXT("osvrClientUpdate failed during startup. Treating this as \"HMD not connected\""));
break;
}
FPlatformProcess::Sleep(0.2f);
}
}
if (!bClientContextOK)
{
UE_LOG(OSVREntryPointLog, Warning, TEXT("OSVR client context did not initialize correctly. Most likely the server isn't running. Treating this as if the HMD is not connected."));
}
}
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
InterfaceCollection = MakeShareable(new OSVRInterfaceCollection(osvrClientContext));
#endif
}
OSVREntryPoint::~OSVREntryPoint()
{
FScopeLock lock(this->GetClientContextMutex());
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
InterfaceCollection = nullptr;
#endif
osvrClientShutdown(osvrClientContext);
osvrClientReleaseAutoStartedServer();
}
void OSVREntryPoint::Tick(float DeltaTime)
{
FScopeLock lock(this->GetClientContextMutex());
osvrClientUpdate(osvrClientContext);
}
bool OSVREntryPoint::IsOSVRConnected()
{
return osvrClientContext && osvrClientCheckStatus(osvrClientContext) == OSVR_RETURN_SUCCESS;
}
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
OSVRInterfaceCollection* OSVREntryPoint::GetInterfaceCollection()
{
return InterfaceCollection.Get();
}
#endif
<commit_msg>Avoid infinite hang BuildCookRun commandlet due to OSVR server connect failure<commit_after>//
// Copyright 2014, 2015 Razer Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "OSVRPrivatePCH.h"
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
#include "OSVRInterfaceCollection.h"
#endif
#include "OSVREntryPoint.h"
#include <osvr/ClientKit/ServerAutoStartC.h>
#include "Runtime/Core/Public/Misc/DateTime.h"
DEFINE_LOG_CATEGORY(OSVREntryPointLog);
OSVREntryPoint::OSVREntryPoint()
{
// avoid BuildCookRun hangs
if (IsRunningCommandlet() || IsRunningDedicatedServer())
{
return;
}
osvrClientAttemptServerAutoStart();
osvrClientContext = osvrClientInit("com.osvr.unreal.plugin");
{
bool bClientContextOK = false;
bool bFailure = false;
auto begin = FDateTime::Now().GetSecond();
auto end = begin + 3;
while (FDateTime::Now().GetSecond() < end && !bClientContextOK && !bFailure)
{
bClientContextOK = osvrClientCheckStatus(osvrClientContext) == OSVR_RETURN_SUCCESS;
if (!bClientContextOK)
{
bFailure = osvrClientUpdate(osvrClientContext) == OSVR_RETURN_FAILURE;
if (bFailure)
{
UE_LOG(OSVREntryPointLog, Warning, TEXT("osvrClientUpdate failed during startup. Treating this as \"HMD not connected\""));
break;
}
FPlatformProcess::Sleep(0.2f);
}
}
if (!bClientContextOK)
{
UE_LOG(OSVREntryPointLog, Warning, TEXT("OSVR client context did not initialize correctly. Most likely the server isn't running. Treating this as if the HMD is not connected."));
}
}
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
InterfaceCollection = MakeShareable(new OSVRInterfaceCollection(osvrClientContext));
#endif
}
OSVREntryPoint::~OSVREntryPoint()
{
FScopeLock lock(this->GetClientContextMutex());
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
InterfaceCollection = nullptr;
#endif
osvrClientShutdown(osvrClientContext);
osvrClientReleaseAutoStartedServer();
}
void OSVREntryPoint::Tick(float DeltaTime)
{
FScopeLock lock(this->GetClientContextMutex());
osvrClientUpdate(osvrClientContext);
}
bool OSVREntryPoint::IsOSVRConnected()
{
return osvrClientContext && osvrClientCheckStatus(osvrClientContext) == OSVR_RETURN_SUCCESS;
}
#if OSVR_DEPRECATED_BLUEPRINT_API_ENABLED
OSVRInterfaceCollection* OSVREntryPoint::GetInterfaceCollection()
{
return InterfaceCollection.Get();
}
#endif
<|endoftext|> |
<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, [email protected]
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include <GL/glew.h>
#include "vvcanvas.h"
#include <virvo/vvdebugmsg.h>
#include <virvo/vvfileio.h>
#include <virvo/vvgltools.h>
#include <QSettings>
#include <QTimer>
#include <iostream>
using vox::vvObjView;
vvCanvas::vvCanvas(const QGLFormat& format, const QString& filename, QWidget* parent)
: QGLWidget(format, parent)
, _vd(NULL)
, _renderer(NULL)
, _projectionType(vox::vvObjView::PERSPECTIVE)
, _doubleBuffering(format.doubleBuffer())
, _superSamples(format.samples())
{
vvDebugMsg::msg(1, "vvCanvas::vvCanvas()");
if (filename != "")
{
_vd = new vvVolDesc(filename.toStdString().c_str());
}
else
{
// load default volume
_vd = new vvVolDesc;
_vd->vox[0] = 32;
_vd->vox[1] = 32;
_vd->vox[2] = 32;
_vd->frames = 0;
}
// init ui
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
// read persistent settings
QSettings settings;
QColor qcolor = settings.value("canvas/bgcolor").value<QColor>();
_bgColor = vvColor(qcolor.redF(), qcolor.greenF(), qcolor.blueF());
_animTimer = new QTimer(this);
connect(_animTimer, SIGNAL(timeout()), this, SLOT(incTimeStep()));
}
vvCanvas::~vvCanvas()
{
vvDebugMsg::msg(1, "vvCanvas::~vvCanvas()");
delete _renderer;
delete _vd;
}
void vvCanvas::setParameter(ParameterType param, const vvParam& value)
{
vvDebugMsg::msg(3, "vvCanvas::setParameter()");
switch (param)
{
case VV_BG_COLOR:
_bgColor = value;
break;
case VV_DOUBLEBUFFERING:
_doubleBuffering = value;
break;
case VV_SUPERSAMPLES:
_superSamples = value;
break;
default:
break;
}
}
void vvCanvas::setVolDesc(vvVolDesc* vd)
{
vvDebugMsg::msg(3, "vvCanvas::setVolDesc()");
delete _vd;
_vd = vd;
if (_vd != NULL)
{
createRenderer();
}
foreach (vvPlugin* plugin, _plugins)
{
plugin->setVolDesc(_vd);
}
emit newVolDesc(_vd);
}
void vvCanvas::setPlugins(const QList<vvPlugin*>& plugins)
{
vvDebugMsg::msg(3, "vvCanvas::setPlugins()");
_plugins = plugins;
}
vvVolDesc* vvCanvas::getVolDesc() const
{
vvDebugMsg::msg(3, "vvCanvas::getVolDesc()");
return _vd;
}
vvRenderer* vvCanvas::getRenderer() const
{
vvDebugMsg::msg(3, "vvCanvas::getRenderer()");
return _renderer;
}
void vvCanvas::loadCamera(const QString& filename)
{
vvDebugMsg::msg(3, "vvCanvas::loadCamera()");
QByteArray ba = filename.toLatin1();
_ov.loadCamera(ba.data());
}
void vvCanvas::saveCamera(const QString& filename)
{
vvDebugMsg::msg(3, "vvCanvas::saveCamera()");
QByteArray ba = filename.toLatin1();
_ov.saveCamera(ba.data());
}
void vvCanvas::initializeGL()
{
vvDebugMsg::msg(1, "vvCanvas::initializeGL()");
glewInit();
init();
}
void vvCanvas::paintGL()
{
vvDebugMsg::msg(3, "vvCanvas::paintGL()");
if (_renderer == NULL)
{
return;
}
if (_doubleBuffering)
{
glDrawBuffer(GL_BACK);
}
else
{
glDrawBuffer(GL_FRONT);
}
glClearColor(_bgColor[0], _bgColor[1], _bgColor[2], 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
_ov.setModelviewMatrix(vvObjView::CENTER);
foreach (vvPlugin* plugin, _plugins)
{
if (plugin->isActive())
{
plugin->prerender();
}
}
_renderer->renderVolumeGL();
foreach (vvPlugin* plugin, _plugins)
{
if (plugin->isActive())
{
plugin->postrender();
}
}
}
void vvCanvas::resizeGL(const int w, const int h)
{
vvDebugMsg::msg(3, "vvCanvas::resizeGL()");
glViewport(0, 0, w, h);
if (h > 0)
{
_ov.setAspectRatio(static_cast<float>(w) / static_cast<float>(h));
}
updateGL();
emit resized(QSize(w, h));
}
void vvCanvas::mouseMoveEvent(QMouseEvent* event)
{
vvDebugMsg::msg(3, "vvCanvas::mouseMoveEvent()");
switch (_mouseButton)
{
case Qt::LeftButton:
{
_ov._camera.trackballRotation(width(), height(),
_lastMousePos.x(), _lastMousePos.y(),
event->pos().x(), event->pos().y());
break;
}
case Qt::MiddleButton:
{
const float pixelInWorld = _ov.getViewportWidth() / static_cast<float>(width());
const float dx = static_cast<float>(event->pos().x() - _lastMousePos.x());
const float dy = static_cast<float>(event->pos().y() - _lastMousePos.y());
vvVector2f pan(pixelInWorld * dx, pixelInWorld * dy);
_ov._camera.translate(pan[0], -pan[1], 0.0f);
break;
}
case Qt::RightButton:
{
const float factor = event->pos().y() - _lastMousePos.y();
_ov._camera.translate(0.0f, 0.0f, factor);
break;
}
default:
break;
}
_lastMousePos = event->pos();
updateGL();
}
void vvCanvas::mousePressEvent(QMouseEvent* event)
{
vvDebugMsg::msg(3, "vvCanvas::mousePressEvent()");
_mouseButton = event->button();
_lastMousePos = event->pos();
}
void vvCanvas::mouseReleaseEvent(QMouseEvent*)
{
vvDebugMsg::msg(3, "vvCanvas::mouseReleaseEvent()");
_mouseButton = Qt::NoButton;
}
void vvCanvas::init()
{
vvDebugMsg::msg(3, "vvCanvas::init()");
vvFileIO* fio = new vvFileIO;
fio->loadVolumeData(_vd, vvFileIO::ALL_DATA);
delete fio;
// default transfer function
if (_vd->tf.isEmpty())
{
_vd->tf.setDefaultAlpha(0, _vd->real[0], _vd->real[1]);
_vd->tf.setDefaultColors((_vd->chan == 1) ? 0 : 3, _vd->real[0], _vd->real[1]);
}
// init renderer
if (_vd != NULL)
{
_currentRenderer = "viewport";
_currentOptions["voxeltype"] = "arb";
createRenderer();
}
updateProjection();
foreach (vvPlugin* plugin, _plugins)
{
plugin->setVolDesc(_vd);
}
emit newVolDesc(_vd);
}
void vvCanvas::createRenderer()
{
vvDebugMsg::msg(3, "vvCanvas::createRenderer()");
vvRenderState state;
if (_renderer)
{
state = *_renderer;
delete _renderer;
}
vvRendererFactory::Options opt(_currentOptions);
_renderer = vvRendererFactory::create(_vd, state, _currentRenderer.c_str(), opt);
}
void vvCanvas::updateProjection()
{
vvDebugMsg::msg(3, "vvCanvas::updateProjection()");
if (_projectionType == vvObjView::PERSPECTIVE)
{
_ov.setProjection(vvObjView::PERSPECTIVE, vvObjView::DEF_FOV, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
}
else if (_projectionType == vvObjView::ORTHO)
{
_ov.setProjection(vvObjView::ORTHO, vvObjView::DEF_VIEWPORT_WIDTH, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
}
}
void vvCanvas::setCurrentFrame(const int frame)
{
vvDebugMsg::msg(3, "vvCanvas::setCurrentFrame()");
_renderer->setCurrentFrame(frame);
emit currentFrame(frame);
updateGL();
}
void vvCanvas::startAnimation(const double fps)
{
vvDebugMsg::msg(3, "vvCanvas::startAnimation()");
_vd->dt = 1.0f / static_cast<float>(fps);
const float delay = std::abs(_vd->dt * 1000.0f);
_animTimer->start(static_cast<int>(delay));
}
void vvCanvas::stopAnimation()
{
vvDebugMsg::msg(3, "vvCanvas::stopAnimation()");
_animTimer->stop();
}
void vvCanvas::setTimeStep(const int step)
{
vvDebugMsg::msg(3, "vvCanvas::setTimeStep()");
int f = step;
while (f < 0)
{
f += _vd->frames;
}
while (f >= _vd->frames)
{
f -= _vd->frames;
}
setCurrentFrame(f);
}
void vvCanvas::incTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::incTimeStep()");
int f = _renderer->getCurrentFrame();
f = (f >= _vd->frames - 1) ? 0 : f + 1;
setCurrentFrame(f);
}
void vvCanvas::decTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::decTimeStep()");
int f = _renderer->getCurrentFrame();
f = (f <= 0) ? _vd->frames - 1 : f - 1;
setCurrentFrame(f);
}
void vvCanvas::firstTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::firstTimeStep()");
setCurrentFrame(0);
}
void vvCanvas::lastTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::lastTimeStep()");
setCurrentFrame(_vd->frames - 1);
}
<commit_msg>Resize volume to fit the viewport<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, [email protected]
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include <GL/glew.h>
#include "vvcanvas.h"
#include <virvo/vvdebugmsg.h>
#include <virvo/vvfileio.h>
#include <virvo/vvgltools.h>
#include <QSettings>
#include <QTimer>
#include <iostream>
using vox::vvObjView;
vvCanvas::vvCanvas(const QGLFormat& format, const QString& filename, QWidget* parent)
: QGLWidget(format, parent)
, _vd(NULL)
, _renderer(NULL)
, _projectionType(vox::vvObjView::PERSPECTIVE)
, _doubleBuffering(format.doubleBuffer())
, _superSamples(format.samples())
{
vvDebugMsg::msg(1, "vvCanvas::vvCanvas()");
if (filename != "")
{
_vd = new vvVolDesc(filename.toStdString().c_str());
}
else
{
// load default volume
_vd = new vvVolDesc;
_vd->vox[0] = 32;
_vd->vox[1] = 32;
_vd->vox[2] = 32;
_vd->frames = 0;
}
// init ui
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
// read persistent settings
QSettings settings;
QColor qcolor = settings.value("canvas/bgcolor").value<QColor>();
_bgColor = vvColor(qcolor.redF(), qcolor.greenF(), qcolor.blueF());
_animTimer = new QTimer(this);
connect(_animTimer, SIGNAL(timeout()), this, SLOT(incTimeStep()));
}
vvCanvas::~vvCanvas()
{
vvDebugMsg::msg(1, "vvCanvas::~vvCanvas()");
delete _renderer;
delete _vd;
}
void vvCanvas::setParameter(ParameterType param, const vvParam& value)
{
vvDebugMsg::msg(3, "vvCanvas::setParameter()");
switch (param)
{
case VV_BG_COLOR:
_bgColor = value;
break;
case VV_DOUBLEBUFFERING:
_doubleBuffering = value;
break;
case VV_SUPERSAMPLES:
_superSamples = value;
break;
default:
break;
}
}
void vvCanvas::setVolDesc(vvVolDesc* vd)
{
vvDebugMsg::msg(3, "vvCanvas::setVolDesc()");
delete _vd;
_vd = vd;
if (_vd != NULL)
{
createRenderer();
}
foreach (vvPlugin* plugin, _plugins)
{
plugin->setVolDesc(_vd);
}
emit newVolDesc(_vd);
}
void vvCanvas::setPlugins(const QList<vvPlugin*>& plugins)
{
vvDebugMsg::msg(3, "vvCanvas::setPlugins()");
_plugins = plugins;
}
vvVolDesc* vvCanvas::getVolDesc() const
{
vvDebugMsg::msg(3, "vvCanvas::getVolDesc()");
return _vd;
}
vvRenderer* vvCanvas::getRenderer() const
{
vvDebugMsg::msg(3, "vvCanvas::getRenderer()");
return _renderer;
}
void vvCanvas::loadCamera(const QString& filename)
{
vvDebugMsg::msg(3, "vvCanvas::loadCamera()");
QByteArray ba = filename.toLatin1();
_ov.loadCamera(ba.data());
}
void vvCanvas::saveCamera(const QString& filename)
{
vvDebugMsg::msg(3, "vvCanvas::saveCamera()");
QByteArray ba = filename.toLatin1();
_ov.saveCamera(ba.data());
}
void vvCanvas::initializeGL()
{
vvDebugMsg::msg(1, "vvCanvas::initializeGL()");
glewInit();
init();
}
void vvCanvas::paintGL()
{
vvDebugMsg::msg(3, "vvCanvas::paintGL()");
if (_renderer == NULL)
{
return;
}
if (_doubleBuffering)
{
glDrawBuffer(GL_BACK);
}
else
{
glDrawBuffer(GL_FRONT);
}
glClearColor(_bgColor[0], _bgColor[1], _bgColor[2], 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
_ov.setModelviewMatrix(vvObjView::CENTER);
foreach (vvPlugin* plugin, _plugins)
{
if (plugin->isActive())
{
plugin->prerender();
}
}
_renderer->renderVolumeGL();
foreach (vvPlugin* plugin, _plugins)
{
if (plugin->isActive())
{
plugin->postrender();
}
}
}
void vvCanvas::resizeGL(const int w, const int h)
{
vvDebugMsg::msg(3, "vvCanvas::resizeGL()");
glViewport(0, 0, w, h);
if (h > 0)
{
_ov.setAspectRatio(static_cast<float>(w) / static_cast<float>(h));
}
updateGL();
emit resized(QSize(w, h));
}
void vvCanvas::mouseMoveEvent(QMouseEvent* event)
{
vvDebugMsg::msg(3, "vvCanvas::mouseMoveEvent()");
switch (_mouseButton)
{
case Qt::LeftButton:
{
_ov._camera.trackballRotation(width(), height(),
_lastMousePos.x(), _lastMousePos.y(),
event->pos().x(), event->pos().y());
break;
}
case Qt::MiddleButton:
{
const float pixelInWorld = _ov.getViewportWidth() / static_cast<float>(width());
const float dx = static_cast<float>(event->pos().x() - _lastMousePos.x());
const float dy = static_cast<float>(event->pos().y() - _lastMousePos.y());
vvVector2f pan(pixelInWorld * dx, pixelInWorld * dy);
_ov._camera.translate(pan[0], -pan[1], 0.0f);
break;
}
case Qt::RightButton:
{
const float factor = event->pos().y() - _lastMousePos.y();
_ov._camera.translate(0.0f, 0.0f, factor);
break;
}
default:
break;
}
_lastMousePos = event->pos();
updateGL();
}
void vvCanvas::mousePressEvent(QMouseEvent* event)
{
vvDebugMsg::msg(3, "vvCanvas::mousePressEvent()");
_mouseButton = event->button();
_lastMousePos = event->pos();
}
void vvCanvas::mouseReleaseEvent(QMouseEvent*)
{
vvDebugMsg::msg(3, "vvCanvas::mouseReleaseEvent()");
_mouseButton = Qt::NoButton;
}
void vvCanvas::init()
{
vvDebugMsg::msg(3, "vvCanvas::init()");
vvFileIO* fio = new vvFileIO;
fio->loadVolumeData(_vd, vvFileIO::ALL_DATA);
delete fio;
// default transfer function
if (_vd->tf.isEmpty())
{
_vd->tf.setDefaultAlpha(0, _vd->real[0], _vd->real[1]);
_vd->tf.setDefaultColors((_vd->chan == 1) ? 0 : 3, _vd->real[0], _vd->real[1]);
}
// init renderer
if (_vd != NULL)
{
_currentRenderer = "viewport";
_currentOptions["voxeltype"] = "arb";
createRenderer();
}
updateProjection();
foreach (vvPlugin* plugin, _plugins)
{
plugin->setVolDesc(_vd);
}
emit newVolDesc(_vd);
}
void vvCanvas::createRenderer()
{
vvDebugMsg::msg(3, "vvCanvas::createRenderer()");
vvRenderState state;
if (_renderer)
{
state = *_renderer;
delete _renderer;
}
const float DEFAULT_OBJ_SIZE = 0.6f;
_vd->resizeEdgeMax(_ov.getViewportWidth() * DEFAULT_OBJ_SIZE);
vvRendererFactory::Options opt(_currentOptions);
_renderer = vvRendererFactory::create(_vd, state, _currentRenderer.c_str(), opt);
}
void vvCanvas::updateProjection()
{
vvDebugMsg::msg(3, "vvCanvas::updateProjection()");
if (_projectionType == vvObjView::PERSPECTIVE)
{
_ov.setProjection(vvObjView::PERSPECTIVE, vvObjView::DEF_FOV, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
}
else if (_projectionType == vvObjView::ORTHO)
{
_ov.setProjection(vvObjView::ORTHO, vvObjView::DEF_VIEWPORT_WIDTH, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
}
}
void vvCanvas::setCurrentFrame(const int frame)
{
vvDebugMsg::msg(3, "vvCanvas::setCurrentFrame()");
_renderer->setCurrentFrame(frame);
emit currentFrame(frame);
updateGL();
}
void vvCanvas::startAnimation(const double fps)
{
vvDebugMsg::msg(3, "vvCanvas::startAnimation()");
_vd->dt = 1.0f / static_cast<float>(fps);
const float delay = std::abs(_vd->dt * 1000.0f);
_animTimer->start(static_cast<int>(delay));
}
void vvCanvas::stopAnimation()
{
vvDebugMsg::msg(3, "vvCanvas::stopAnimation()");
_animTimer->stop();
}
void vvCanvas::setTimeStep(const int step)
{
vvDebugMsg::msg(3, "vvCanvas::setTimeStep()");
int f = step;
while (f < 0)
{
f += _vd->frames;
}
while (f >= _vd->frames)
{
f -= _vd->frames;
}
setCurrentFrame(f);
}
void vvCanvas::incTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::incTimeStep()");
int f = _renderer->getCurrentFrame();
f = (f >= _vd->frames - 1) ? 0 : f + 1;
setCurrentFrame(f);
}
void vvCanvas::decTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::decTimeStep()");
int f = _renderer->getCurrentFrame();
f = (f <= 0) ? _vd->frames - 1 : f - 1;
setCurrentFrame(f);
}
void vvCanvas::firstTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::firstTimeStep()");
setCurrentFrame(0);
}
void vvCanvas::lastTimeStep()
{
vvDebugMsg::msg(3, "vvCanvas::lastTimeStep()");
setCurrentFrame(_vd->frames - 1);
}
<|endoftext|> |
<commit_before>#include "connection-manager.h"
#include "glib-helpers.h"
#include "protocol.h"
G_DEFINE_TYPE(SteamConnectionManager, steam_connection_manager, TP_TYPE_BASE_CONNECTION_MANAGER);
static void stema_connection_manager_constructed (GObject * object)
{
GLIB_CALL_PARENT(steam_connection_manager_parent_class, constructed, object);
tp_base_connection_manager_add_protocol(TP_BASE_CONNECTION_MANAGER(object), steam_protocol_new());
}
void steam_connection_manager_class_init(SteamConnectionManagerClass * klass)
{
GObjectClass *object_class = G_OBJECT_CLASS(klass);
object_class->constructed = stema_connection_manager_constructed;
klass->parent_class.cm_dbus_name = "steam";
}
void steam_connection_manager_init(SteamConnectionManager * scm)
{
}
<commit_msg>connection-manager: unref created protocol<commit_after>#include "connection-manager.h"
#include "glib-helpers.h"
#include "protocol.h"
G_DEFINE_TYPE(SteamConnectionManager, steam_connection_manager, TP_TYPE_BASE_CONNECTION_MANAGER);
static void stema_connection_manager_constructed (GObject * object)
{
GLIB_CALL_PARENT(steam_connection_manager_parent_class, constructed, object);
TpBaseProtocol * p = steam_protocol_new();
tp_base_connection_manager_add_protocol(TP_BASE_CONNECTION_MANAGER(object), p);
g_object_unref(p);
}
void steam_connection_manager_class_init(SteamConnectionManagerClass * klass)
{
GObjectClass *object_class = G_OBJECT_CLASS(klass);
object_class->constructed = stema_connection_manager_constructed;
klass->parent_class.cm_dbus_name = "steam";
}
void steam_connection_manager_init(SteamConnectionManager * scm)
{
}
<|endoftext|> |
<commit_before>#pragma once
#include <mapbox/geometry.hpp>
#include <mapbox/variant.hpp>
#include <algorithm>
#include <string>
#include <unordered_map>
#include <vector>
namespace mapbox {
namespace geojsonvt {
namespace detail {
struct vt_point : mapbox::geometry::point<double> {
double z = 0.0; // simplification tolerance
vt_point(double x_, double y_, double z_) : mapbox::geometry::point<double>(x_, y_), z(z_) {
}
vt_point(double x_, double y_) : vt_point(x_, y_, 0.0) {
}
};
template <uint8_t I, typename T>
inline double get(const T&);
template <>
inline double get<0>(const vt_point& p) {
return p.x;
}
template <>
inline double get<1>(const vt_point& p) {
return p.y;
}
template <>
inline double get<0>(const mapbox::geometry::point<double>& p) {
return p.x;
}
template <>
inline double get<1>(const mapbox::geometry::point<double>& p) {
return p.y;
}
template <uint8_t I>
inline vt_point intersect(const vt_point&, const vt_point&, const double);
template <>
inline vt_point intersect<0>(const vt_point& a, const vt_point& b, const double x) {
const double y = (x - a.x) * (b.y - a.y) / (b.x - a.x) + a.y;
return { x, y, 1.0 };
}
template <>
inline vt_point intersect<1>(const vt_point& a, const vt_point& b, const double y) {
const double x = (y - a.y) * (b.x - a.x) / (b.y - a.y) + a.x;
return { x, y, 1.0 };
}
using vt_multi_point = std::vector<vt_point>;
struct vt_line_string : std::vector<vt_point> {
using container_type = std::vector<vt_point>;
using container_type::container_type;
double dist = 0.0; // line length
};
struct vt_linear_ring : std::vector<vt_point> {
using container_type = std::vector<vt_point>;
using container_type::container_type;
double area = 0.0; // polygon ring area
};
using vt_multi_line_string = std::vector<vt_line_string>;
using vt_polygon = std::vector<vt_linear_ring>;
using vt_multi_polygon = std::vector<vt_polygon>;
struct vt_geometry_collection;
using vt_geometry = mapbox::util::variant<vt_point,
vt_line_string,
vt_polygon,
vt_multi_point,
vt_multi_line_string,
vt_multi_polygon,
vt_geometry_collection>;
struct vt_geometry_collection : std::vector<vt_geometry> {};
using property_map = mapbox::geometry::property_map;
using identifier = mapbox::geometry::identifier;
template <class T>
using optional = std::experimental::optional<T>;
template <class T>
struct vt_geometry_type;
template <>
struct vt_geometry_type<geometry::point<double>> {
using type = vt_point;
};
template <>
struct vt_geometry_type<geometry::line_string<double>> {
using type = vt_line_string;
};
template <>
struct vt_geometry_type<geometry::polygon<double>> {
using type = vt_polygon;
};
template <>
struct vt_geometry_type<geometry::multi_point<double>> {
using type = vt_multi_point;
};
template <>
struct vt_geometry_type<geometry::multi_line_string<double>> {
using type = vt_multi_line_string;
};
template <>
struct vt_geometry_type<geometry::multi_polygon<double>> {
using type = vt_multi_polygon;
};
template <>
struct vt_geometry_type<geometry::geometry<double>> {
using type = vt_geometry;
};
template <>
struct vt_geometry_type<geometry::geometry_collection<double>> {
using type = vt_geometry_collection;
};
struct vt_feature {
vt_geometry geometry;
property_map properties;
optional<identifier> id;
mapbox::geometry::box<double> bbox = { { 2, 1 }, { -1, 0 } };
uint32_t num_points = 0;
vt_feature(const vt_geometry& geom, const property_map& props, const optional<identifier>& id_)
: geometry(geom), properties(props), id(id_) {
mapbox::geometry::for_each_point(geom, [&](const vt_point& p) {
bbox.min.x = std::min(p.x, bbox.min.x);
bbox.min.y = std::min(p.y, bbox.min.y);
bbox.max.x = std::max(p.x, bbox.max.x);
bbox.max.y = std::max(p.y, bbox.max.y);
++num_points;
});
}
};
using vt_features = std::vector<vt_feature>;
} // namespace detail
} // namespace geojsonvt
} // namespace mapbox
<commit_msg>Fix compilation errors with libc++ on QNX 7<commit_after>#pragma once
#include <mapbox/geometry.hpp>
#include <mapbox/variant.hpp>
#include <algorithm>
#include <string>
#include <unordered_map>
#include <vector>
namespace mapbox {
namespace geojsonvt {
namespace detail {
struct vt_point : mapbox::geometry::point<double> {
double z = 0.0; // simplification tolerance
vt_point(double x_, double y_, double z_) : mapbox::geometry::point<double>(x_, y_), z(z_) {
}
vt_point(double x_, double y_) : vt_point(x_, y_, 0.0) {
}
};
template <uint8_t I, typename T>
inline double get(const T&);
template <>
inline double get<0>(const vt_point& p) {
return p.x;
}
template <>
inline double get<1>(const vt_point& p) {
return p.y;
}
template <>
inline double get<0>(const mapbox::geometry::point<double>& p) {
return p.x;
}
template <>
inline double get<1>(const mapbox::geometry::point<double>& p) {
return p.y;
}
template <uint8_t I>
inline vt_point intersect(const vt_point&, const vt_point&, const double);
template <>
inline vt_point intersect<0>(const vt_point& a, const vt_point& b, const double x) {
const double y = (x - a.x) * (b.y - a.y) / (b.x - a.x) + a.y;
return { x, y, 1.0 };
}
template <>
inline vt_point intersect<1>(const vt_point& a, const vt_point& b, const double y) {
const double x = (y - a.y) * (b.x - a.x) / (b.y - a.y) + a.x;
return { x, y, 1.0 };
}
using vt_multi_point = std::vector<vt_point>;
struct vt_line_string : std::vector<vt_point> {
using container_type = std::vector<vt_point>;
vt_line_string() = default;
vt_line_string(std::initializer_list<vt_point> args)
: container_type(std::move(args)) {}
double dist = 0.0; // line length
};
struct vt_linear_ring : std::vector<vt_point> {
using container_type = std::vector<vt_point>;
vt_linear_ring() = default;
vt_linear_ring(std::initializer_list<vt_point> args)
: container_type(std::move(args)) {}
double area = 0.0; // polygon ring area
};
using vt_multi_line_string = std::vector<vt_line_string>;
using vt_polygon = std::vector<vt_linear_ring>;
using vt_multi_polygon = std::vector<vt_polygon>;
struct vt_geometry_collection;
using vt_geometry = mapbox::util::variant<vt_point,
vt_line_string,
vt_polygon,
vt_multi_point,
vt_multi_line_string,
vt_multi_polygon,
vt_geometry_collection>;
struct vt_geometry_collection : std::vector<vt_geometry> {};
using property_map = mapbox::geometry::property_map;
using identifier = mapbox::geometry::identifier;
template <class T>
using optional = std::experimental::optional<T>;
template <class T>
struct vt_geometry_type;
template <>
struct vt_geometry_type<geometry::point<double>> {
using type = vt_point;
};
template <>
struct vt_geometry_type<geometry::line_string<double>> {
using type = vt_line_string;
};
template <>
struct vt_geometry_type<geometry::polygon<double>> {
using type = vt_polygon;
};
template <>
struct vt_geometry_type<geometry::multi_point<double>> {
using type = vt_multi_point;
};
template <>
struct vt_geometry_type<geometry::multi_line_string<double>> {
using type = vt_multi_line_string;
};
template <>
struct vt_geometry_type<geometry::multi_polygon<double>> {
using type = vt_multi_polygon;
};
template <>
struct vt_geometry_type<geometry::geometry<double>> {
using type = vt_geometry;
};
template <>
struct vt_geometry_type<geometry::geometry_collection<double>> {
using type = vt_geometry_collection;
};
struct vt_feature {
vt_geometry geometry;
property_map properties;
optional<identifier> id;
mapbox::geometry::box<double> bbox = { { 2, 1 }, { -1, 0 } };
uint32_t num_points = 0;
vt_feature(const vt_geometry& geom, const property_map& props, const optional<identifier>& id_)
: geometry(geom), properties(props), id(id_) {
mapbox::geometry::for_each_point(geom, [&](const vt_point& p) {
bbox.min.x = std::min(p.x, bbox.min.x);
bbox.min.y = std::min(p.y, bbox.min.y);
bbox.max.x = std::max(p.x, bbox.max.x);
bbox.max.y = std::max(p.y, bbox.max.y);
++num_points;
});
}
};
using vt_features = std::vector<vt_feature>;
} // namespace detail
} // namespace geojsonvt
} // namespace mapbox
<|endoftext|> |
<commit_before>#include <babylon/materials/textures/hdr_cube_texture.h>
#include <nlohmann/json.hpp>
#include <babylon/babylon_stl_util.h>
#include <babylon/core/logging.h>
#include <babylon/engines/constants.h>
#include <babylon/engines/engine.h>
#include <babylon/engines/scene.h>
#include <babylon/materials/material.h>
#include <babylon/materials/textures/internal_texture.h>
#include <babylon/materials/textures/texture_constants.h>
#include <babylon/misc/highdynamicrange/cube_map_to_spherical_polynomial_tools.h>
#include <babylon/misc/highdynamicrange/hdr_tools.h>
#include <babylon/misc/tools.h>
namespace BABYLON {
std::vector<std::string> HDRCubeTexture::_facesMapping{
"right", //
"left", //
"up", //
"down", //
"front", //
"back" //
};
HDRCubeTexture::HDRCubeTexture(
const std::string& iUrl, Scene* scene, size_t size, bool iNoMipmap, bool generateHarmonics,
bool iGammaSpace, bool /*reserved*/, const std::function<void()>& onLoad,
const std::function<void(const std::string& message, const std::string& exception)>& onError)
: BaseTexture(scene)
, url{iUrl}
, rotationY{this, &HDRCubeTexture::get_rotationY, &HDRCubeTexture::set_rotationY}
, boundingBoxPosition{Vector3::Zero()}
, _isBlocking{true}
, _rotationY{0.f}
, _generateHarmonics{generateHarmonics}
, _noMipmap{iNoMipmap}
, _size{size}
, _onLoad{onLoad}
, _onError{onError}
, _boundingBoxSize{std::nullopt}
{
if (iUrl.empty()) {
return;
}
name = iUrl;
url = iUrl;
hasAlpha = false;
isCube = true;
_textureMatrix = Matrix::Identity();
_onLoad = onLoad;
_onError = onError;
gammaSpace = iGammaSpace;
coordinatesMode = TextureConstants::CUBIC_MODE;
_noMipmap = noMipmap;
_size = size;
_texture = _getFromCache(url, _noMipmap);
if (!_texture) {
if (!scene->useDelayedTextureLoading) {
loadTexture();
}
else {
delayLoadState = Constants::DELAYLOADSTATE_NOTLOADED;
}
}
else if (onLoad) {
if (_texture->isReady) {
Tools::SetImmediate([&onLoad]() -> void { onLoad(); });
}
else {
// _texture->onLoadedObservable.add(onLoad);
}
}
}
HDRCubeTexture::~HDRCubeTexture() = default;
std::string HDRCubeTexture::getClassName() const
{
return "HDRCubeTexture";
}
void HDRCubeTexture::set_isBlocking(bool value)
{
_isBlocking = value;
}
bool HDRCubeTexture::get_isBlocking() const
{
return _isBlocking;
}
void HDRCubeTexture::set_rotationY(float value)
{
_rotationY = value;
auto mat = Matrix::RotationY(_rotationY);
setReflectionTextureMatrix(mat);
}
float HDRCubeTexture::get_rotationY() const
{
return _rotationY;
}
void HDRCubeTexture::set_boundingBoxSize(const std::optional<Vector3>& value)
{
if (!value.has_value()) {
return;
}
if (_boundingBoxSize && (*_boundingBoxSize).equals(*value)) {
return;
}
_boundingBoxSize = value;
auto scene = getScene();
if (scene) {
scene->markAllMaterialsAsDirty(Constants::MATERIAL_TextureDirtyFlag);
}
}
std::optional<Vector3>& HDRCubeTexture::get_boundingBoxSize()
{
return _boundingBoxSize;
}
void HDRCubeTexture::loadTexture()
{
const auto callback = [this](const ArrayBuffer& buffer) -> std::vector<ArrayBufferView> {
lodGenerationOffset = 0.f;
lodGenerationScale = 0.8f;
auto scene = getScene();
if (!scene) {
return {};
}
// Extract the raw linear data.
auto data = HDRTools::GetCubeMapTextureData(buffer, _size);
// Generate harmonics if needed.
if (_generateHarmonics) {
auto _sphericalPolynomial
= CubeMapToSphericalPolynomialTools::ConvertCubeMapToSphericalPolynomial(data);
sphericalPolynomial = _sphericalPolynomial;
}
std::vector<ArrayBufferView> results;
Uint8Array byteArray;
// Push each faces.
for (unsigned int j = 0; j < 6; ++j) {
// Create uintarray fallback.
if (!scene->getEngine()->getCaps().textureFloat) {
// 3 channels of 1 bytes per pixel in bytes.
byteArray.resize(_size * _size * 3);
}
auto dataFace = data[HDRCubeTexture::_facesMapping[j]].float32Array();
// If special cases.
if (gammaSpace || !byteArray.empty()) {
for (size_t i = 0; i < _size * _size; ++i) {
// Put in gamma space if requested.
if (gammaSpace) {
dataFace[(i * 3) + 0] = std::pow(dataFace[(i * 3) + 0], Math::ToGammaSpace);
dataFace[(i * 3) + 1] = std::pow(dataFace[(i * 3) + 1], Math::ToGammaSpace);
dataFace[(i * 3) + 2] = std::pow(dataFace[(i * 3) + 2], Math::ToGammaSpace);
}
// Convert to int texture for fallback.
if (!byteArray.empty()) {
auto r = std::max(dataFace[(i * 3) + 0] * 255, 0.f);
auto g = std::max(dataFace[(i * 3) + 1] * 255, 0.f);
auto b = std::max(dataFace[(i * 3) + 2] * 255, 0.f);
// May use luminance instead if the result is not accurate.
auto max = std::max(std::max(r, g), b);
if (max > 255) {
auto scale = 255.f / max;
r *= scale;
g *= scale;
b *= scale;
}
byteArray[(i * 3) + 0] = static_cast<uint8_t>(r);
byteArray[(i * 3) + 1] = static_cast<uint8_t>(g);
byteArray[(i * 3) + 2] = static_cast<uint8_t>(b);
}
}
}
if (!byteArray.empty()) {
results.emplace_back(byteArray);
}
else {
results.emplace_back(dataFace);
}
}
return results;
};
auto scene = getScene();
if (scene) {
_texture = scene->getEngine()->createRawCubeTextureFromUrl(
url, scene, static_cast<int>(_size), Constants::TEXTUREFORMAT_RGB,
scene->getEngine()->getCaps().textureFloat ? Constants::TEXTURETYPE_FLOAT :
Constants::TEXTURETYPE_UNSIGNED_INT,
_noMipmap, callback, nullptr, _onLoad, _onError);
}
}
HDRCubeTexturePtr HDRCubeTexture::clone() const
{
auto scene = getScene();
if (!scene) {
return nullptr;
}
auto newTexture
= HDRCubeTexture::New(url, scene, _size, _noMipmap, _generateHarmonics, gammaSpace);
// Base texture
newTexture->level = level;
newTexture->wrapU = wrapU;
newTexture->wrapV = wrapV;
newTexture->coordinatesIndex = coordinatesIndex;
newTexture->coordinatesMode = coordinatesMode();
return newTexture;
}
void HDRCubeTexture::delayLoad(const std::string& /*forcedExtension*/)
{
if (delayLoadState != Constants::DELAYLOADSTATE_NOTLOADED) {
return;
}
delayLoadState = Constants::DELAYLOADSTATE_LOADED;
_texture = _getFromCache(url, _noMipmap);
if (!_texture) {
loadTexture();
}
}
Matrix* HDRCubeTexture::getReflectionTextureMatrix()
{
return &_textureMatrix;
}
void HDRCubeTexture::setReflectionTextureMatrix(Matrix& value)
{
_textureMatrix = value;
if (value.updateFlag == _textureMatrix.updateFlag) {
return;
}
if (value.isIdentity() != _textureMatrix.isIdentity()) {
getScene()->markAllMaterialsAsDirty(
Constants::MATERIAL_TextureDirtyFlag, [this](Material* mat) -> bool {
auto activeTextures = mat->getActiveTextures();
auto it
= std::find_if(activeTextures.begin(), activeTextures.end(),
[this](const BaseTexturePtr& texture) { return texture.get() == this; });
return it != activeTextures.end();
});
}
}
HDRCubeTexture* HDRCubeTexture::Parse(const json& /*parsedTexture*/, Scene* /*scene*/,
const std::string& /*rootUrl*/)
{
return nullptr;
}
json HDRCubeTexture::serialize() const
{
return nullptr;
}
} // end of namespace BABYLON
<commit_msg>Updated HDRCubeTexture class to v4.1.0<commit_after>#include <babylon/materials/textures/hdr_cube_texture.h>
#include <nlohmann/json.hpp>
#include <babylon/babylon_stl_util.h>
#include <babylon/core/logging.h>
#include <babylon/engines/constants.h>
#include <babylon/engines/engine.h>
#include <babylon/engines/scene.h>
#include <babylon/materials/material.h>
#include <babylon/materials/textures/internal_texture.h>
#include <babylon/materials/textures/texture_constants.h>
#include <babylon/misc/highdynamicrange/cube_map_to_spherical_polynomial_tools.h>
#include <babylon/misc/highdynamicrange/hdr_tools.h>
#include <babylon/misc/tools.h>
namespace BABYLON {
std::vector<std::string> HDRCubeTexture::_facesMapping{
"right", //
"left", //
"up", //
"down", //
"front", //
"back" //
};
HDRCubeTexture::HDRCubeTexture(
const std::string& iUrl, Scene* scene, size_t size, bool iNoMipmap, bool generateHarmonics,
bool iGammaSpace, bool /*reserved*/, const std::function<void()>& onLoad,
const std::function<void(const std::string& message, const std::string& exception)>& onError)
: BaseTexture(scene)
, url{iUrl}
, rotationY{this, &HDRCubeTexture::get_rotationY, &HDRCubeTexture::set_rotationY}
, boundingBoxPosition{Vector3::Zero()}
, _isBlocking{true}
, _rotationY{0.f}
, _noMipmap{iNoMipmap}
, _size{size}
, _onLoad{onLoad}
, _onError{onError}
, _boundingBoxSize{std::nullopt}
{
if (iUrl.empty()) {
return;
}
name = iUrl;
url = iUrl;
hasAlpha = false;
isCube = true;
_textureMatrix = Matrix::Identity();
_onLoad = onLoad;
_onError = onError;
gammaSpace = iGammaSpace;
coordinatesMode = TextureConstants::CUBIC_MODE;
_noMipmap = noMipmap;
_size = size;
_generateHarmonics = generateHarmonics;
_texture = _getFromCache(url, _noMipmap);
if (!_texture) {
if (!scene->useDelayedTextureLoading) {
loadTexture();
}
else {
delayLoadState = Constants::DELAYLOADSTATE_NOTLOADED;
}
}
else if (onLoad) {
if (_texture->isReady) {
Tools::SetImmediate([&onLoad]() -> void { onLoad(); });
}
else {
// _texture->onLoadedObservable.add(onLoad);
}
}
}
HDRCubeTexture::~HDRCubeTexture() = default;
std::string HDRCubeTexture::getClassName() const
{
return "HDRCubeTexture";
}
void HDRCubeTexture::set_isBlocking(bool value)
{
_isBlocking = value;
}
bool HDRCubeTexture::get_isBlocking() const
{
return _isBlocking;
}
void HDRCubeTexture::set_rotationY(float value)
{
_rotationY = value;
auto mat = Matrix::RotationY(_rotationY);
setReflectionTextureMatrix(mat);
}
float HDRCubeTexture::get_rotationY() const
{
return _rotationY;
}
void HDRCubeTexture::set_boundingBoxSize(const std::optional<Vector3>& value)
{
if (!value.has_value()) {
return;
}
if (_boundingBoxSize && (*_boundingBoxSize).equals(*value)) {
return;
}
_boundingBoxSize = value;
auto scene = getScene();
if (scene) {
scene->markAllMaterialsAsDirty(Constants::MATERIAL_TextureDirtyFlag);
}
}
std::optional<Vector3>& HDRCubeTexture::get_boundingBoxSize()
{
return _boundingBoxSize;
}
void HDRCubeTexture::loadTexture()
{
const auto callback = [this](const ArrayBuffer& buffer) -> std::vector<ArrayBufferView> {
lodGenerationOffset = 0.f;
lodGenerationScale = 0.8f;
auto scene = getScene();
if (!scene) {
return {};
}
// Extract the raw linear data.
auto data = HDRTools::GetCubeMapTextureData(buffer, _size);
// Generate harmonics if needed.
if (_generateHarmonics) {
auto _sphericalPolynomial
= CubeMapToSphericalPolynomialTools::ConvertCubeMapToSphericalPolynomial(data);
sphericalPolynomial = _sphericalPolynomial;
}
std::vector<ArrayBufferView> results;
Uint8Array byteArray;
// Push each faces.
for (unsigned int j = 0; j < 6; ++j) {
// Create uintarray fallback.
if (!scene->getEngine()->getCaps().textureFloat) {
// 3 channels of 1 bytes per pixel in bytes.
byteArray.resize(_size * _size * 3);
}
auto dataFace = data[HDRCubeTexture::_facesMapping[j]].float32Array();
// If special cases.
if (gammaSpace || !byteArray.empty()) {
for (size_t i = 0; i < _size * _size; ++i) {
// Put in gamma space if requested.
if (gammaSpace) {
dataFace[(i * 3) + 0] = std::pow(dataFace[(i * 3) + 0], Math::ToGammaSpace);
dataFace[(i * 3) + 1] = std::pow(dataFace[(i * 3) + 1], Math::ToGammaSpace);
dataFace[(i * 3) + 2] = std::pow(dataFace[(i * 3) + 2], Math::ToGammaSpace);
}
// Convert to int texture for fallback.
if (!byteArray.empty()) {
auto r = std::max(dataFace[(i * 3) + 0] * 255, 0.f);
auto g = std::max(dataFace[(i * 3) + 1] * 255, 0.f);
auto b = std::max(dataFace[(i * 3) + 2] * 255, 0.f);
// May use luminance instead if the result is not accurate.
auto max = std::max(std::max(r, g), b);
if (max > 255) {
auto scale = 255.f / max;
r *= scale;
g *= scale;
b *= scale;
}
byteArray[(i * 3) + 0] = static_cast<uint8_t>(r);
byteArray[(i * 3) + 1] = static_cast<uint8_t>(g);
byteArray[(i * 3) + 2] = static_cast<uint8_t>(b);
}
}
}
if (!byteArray.empty()) {
results.emplace_back(byteArray);
}
else {
results.emplace_back(dataFace);
}
}
return results;
};
auto scene = getScene();
if (scene) {
_texture = scene->getEngine()->createRawCubeTextureFromUrl(
url, scene, static_cast<int>(_size), Constants::TEXTUREFORMAT_RGB,
scene->getEngine()->getCaps().textureFloat ? Constants::TEXTURETYPE_FLOAT :
Constants::TEXTURETYPE_UNSIGNED_INT,
_noMipmap, callback, nullptr, _onLoad, _onError);
}
}
HDRCubeTexturePtr HDRCubeTexture::clone() const
{
auto scene = getScene();
if (!scene) {
return nullptr;
}
auto newTexture
= HDRCubeTexture::New(url, scene, _size, _noMipmap, _generateHarmonics, gammaSpace);
// Base texture
newTexture->level = level;
newTexture->wrapU = wrapU;
newTexture->wrapV = wrapV;
newTexture->coordinatesIndex = coordinatesIndex;
newTexture->coordinatesMode = coordinatesMode();
return newTexture;
}
void HDRCubeTexture::delayLoad(const std::string& /*forcedExtension*/)
{
if (delayLoadState != Constants::DELAYLOADSTATE_NOTLOADED) {
return;
}
delayLoadState = Constants::DELAYLOADSTATE_LOADED;
_texture = _getFromCache(url, _noMipmap);
if (!_texture) {
loadTexture();
}
}
Matrix* HDRCubeTexture::getReflectionTextureMatrix()
{
return &_textureMatrix;
}
void HDRCubeTexture::setReflectionTextureMatrix(Matrix& value)
{
_textureMatrix = value;
if (value.updateFlag == _textureMatrix.updateFlag) {
return;
}
if (value.isIdentity() != _textureMatrix.isIdentity()) {
getScene()->markAllMaterialsAsDirty(
Constants::MATERIAL_TextureDirtyFlag, [this](Material* mat) -> bool {
auto activeTextures = mat->getActiveTextures();
auto it
= std::find_if(activeTextures.begin(), activeTextures.end(),
[this](const BaseTexturePtr& texture) { return texture.get() == this; });
return it != activeTextures.end();
});
}
}
HDRCubeTexture* HDRCubeTexture::Parse(const json& /*parsedTexture*/, Scene* /*scene*/,
const std::string& /*rootUrl*/)
{
return nullptr;
}
json HDRCubeTexture::serialize() const
{
return nullptr;
}
} // end of namespace BABYLON
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#include "Stroika/Frameworks/StroikaPreComp.h"
#include <iostream>
#include "Stroika/Foundation/Characters/FloatConversion.h"
#include "Stroika/Foundation/Characters/String2Int.h"
#include "Stroika/Foundation/Characters/ToString.h"
#include "Stroika/Foundation/DataExchange/InternetMediaTypeRegistry.h"
#include "Stroika/Foundation/IO/Network/HTTP/Exception.h"
#include "Stroika/Foundation/IO/Network/HTTP/Headers.h"
#include "Stroika/Foundation/IO/Network/HTTP/Methods.h"
#include "Stroika/Foundation/Streams/TextReader.h"
#include "Stroika/Frameworks/WebServer/ConnectionManager.h"
#include "Stroika/Frameworks/WebServer/Router.h"
#include "Stroika/Frameworks/WebService/Server/Basic.h"
#include "Stroika/Frameworks/WebService/Server/VariantValue.h"
#include "WebServer.h"
#include "AppVersion.h"
using namespace std;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::IO::Network;
using namespace Stroika::Foundation::IO::Network::HTTP;
using namespace Stroika::Frameworks::WebServer;
using namespace Stroika::Frameworks::WebService;
using namespace Stroika::Frameworks::WebService::Server;
using namespace Stroika::Frameworks::WebService::Server::VariantValue;
using Memory::BLOB;
using namespace StroikaSample::WebServices;
/*
* It's often helpful to structure together, routes, special interceptors, with your connection manager, to package up
* all the logic /options for HTTP interface.
*
* This particular organization also makes it easy to save instance variables with the webserver (like a pointer to a handler)
* and accesss them from the Route handler functions.
*/
class WebServer::Rep_ {
public:
const Sequence<Route> kRoutes_; // rules saying how to map urls to code
shared_ptr<IWSAPI> fWSImpl_; // application logic actually handling webservices
ConnectionManager fConnectionMgr_; // manage http connection objects, thread pool, etc
static const WebServiceMethodDescription kVariables_;
static const WebServiceMethodDescription kPlus_;
static const WebServiceMethodDescription kMinus;
static const WebServiceMethodDescription kTimes;
static const WebServiceMethodDescription kDivide;
Rep_ (uint16_t portNumber, const shared_ptr<IWSAPI>& wsImpl)
: kRoutes_{
Route{L""_RegEx, DefaultPage_},
Route{MethodsRegEx::kPost, L"SetAppState"_RegEx, SetAppState_},
Route{L"FRED"_RegEx, [] (Request*, Response* response) {
response->write (L"FRED");
response->SetContentType (DataExchange::InternetMediaTypes::kText_PLAIN);
}},
/*
* the 'variable' API demonstrates a typical REST style CRUD usage - where the 'arguments' mainly come from
* the URL itself.
*/
Route{L"variables(/?)"_RegEx, [this] (Message* m) {
WriteResponse (&m->rwResponse (), kVariables_, kMapper.FromObject (fWSImpl_->Variables_GET ()));
}},
Route{L"variables/(.+)"_RegEx, [this] (Message* m, const String& varName) {
WriteResponse (&m->rwResponse (), kVariables_, kMapper.FromObject (fWSImpl_->Variables_GET (varName)));
}},
Route{MethodsRegEx::kPostOrPut, L"variables/(.+)"_RegEx, [this] (Message* m, const String& varName) {
optional<Number> number;
// demo getting argument from the body
if (not number) {
// read if content-type is text (not json)
if (m->request ().contentType () and DataExchange::InternetMediaTypeRegistry::Get ().IsA (DataExchange::InternetMediaTypes::kText_PLAIN, *m->request ().contentType ())) {
String argsAsString = Streams::TextReader::New (m->rwRequest ().GetBody ()).ReadAll ();
number = kMapper.ToObject<Number> (DataExchange::VariantValue (argsAsString));
}
}
// demo getting argument from the query argument
if (not number) {
static const String kValueParamName_ = L"value"sv;
Mapping<String, DataExchange::VariantValue> args = PickoutParamValuesFromURL (&m->request ());
number = Model::kMapper.ToObject<Number> (args.LookupValue (kValueParamName_));
}
// demo getting either query arg, or url encoded arg
if (not number) {
static const String kValueParamName_ = L"value"sv;
// NOTE - PickoutParamValues combines PickoutParamValuesFromURL, and PickoutParamValuesFromBody. You can use
// Either one of those instead. PickoutParamValuesFromURL assumes you know the name of the parameter, and its
// encoded in the query string. PickoutParamValuesFromBody assumes you have something equivilent you can parse ouf
// of the body, either json encoded or form-encoded (as of 2.1d23, only json encoded supported)
Mapping<String, DataExchange::VariantValue> args = PickoutParamValues (&m->rwRequest ());
number = Model::kMapper.ToObject<Number> (args.LookupValue (kValueParamName_));
}
if (not number) {
Execution::Throw (ClientErrorException{L"Expected argument to PUT/POST variable"sv});
}
fWSImpl_->Variables_SET (varName, *number);
WriteResponse (&m->rwResponse (), kVariables_);
}},
Route{MethodsRegEx::kDelete, L"variables/(.+)"_RegEx, [this] (Message* m, const String& varName) {
fWSImpl_->Variables_DELETE (varName);
WriteResponse (&m->rwResponse (), kVariables_);
}},
/*
* plus, minus, times, and divide, test-void-return all all demonstrate passing in variables through either the POST body, or query-arguments.
*/
Route{L"plus"_RegEx, mkRequestHandler (kPlus_, Model::kMapper, Traversal::Iterable<String>{L"arg1", L"arg2"}, function<Number (Number, Number)>{[this] (Number arg1, Number arg2) { return fWSImpl_->plus (arg1, arg2); }})},
Route{L"minus"_RegEx, mkRequestHandler (kMinus, Model::kMapper, Traversal::Iterable<String>{L"arg1", L"arg2"}, function<Number (Number, Number)>{[this] (Number arg1, Number arg2) { return fWSImpl_->minus (arg1, arg2); }})},
Route{L"times"_RegEx, mkRequestHandler (kTimes, Model::kMapper, Traversal::Iterable<String>{L"arg1", L"arg2"}, function<Number (Number, Number)>{[this] (Number arg1, Number arg2) { return fWSImpl_->times (arg1, arg2); }})},
Route{L"divide"_RegEx, mkRequestHandler (kDivide, Model::kMapper, Traversal::Iterable<String>{L"arg1", L"arg2"}, function<Number (Number, Number)>{[this] (Number arg1, Number arg2) { return fWSImpl_->divide (arg1, arg2); }})},
Route{L"test-void-return"_RegEx, mkRequestHandler (WebServiceMethodDescription{}, Model::kMapper, Traversal::Iterable<String>{L"err-if-more-than-10"}, function<void (double)>{[] (double check) {
if (check > 10) {
Execution::Throw (Execution::Exception (L"more than 10"sv));
} }})},
}
, fWSImpl_
{
wsImpl
}
#if __cpp_designated_initializers
, fConnectionMgr_
{
SocketAddresses (InternetAddresses_Any (), portNumber), kRoutes_, ConnectionManager::Options { .fBindFlags = Socket::BindFlags{}, .fServerHeader = L"Stroika-Sample-WebServices/"_k + AppVersion::kVersion.AsMajorMinorString () }
}
#else
, fConnectionMgr_
{
SocketAddresses (InternetAddresses_Any (), portNumber), kRoutes_, ConnectionManager::Options { nullopt, nullopt, Socket::BindFlags{}, L"Stroika-Sample-WebServices/"_k + AppVersion::kVersion.AsMajorMinorString () }
}
#endif
{
// @todo - move this to some framework-specific regtests...
using VariantValue = DataExchange::VariantValue;
Sequence<VariantValue> tmp = OrderParamValues (Iterable<String>{L"page", L"xxx"}, PickoutParamValuesFromURL (URI{L"http://www.sophist.com?page=5"}));
Assert (tmp.size () == 2);
Assert (tmp[0] == 5);
Assert (tmp[1] == nullptr);
}
// Can declare arguments as Request*,Response*
static void DefaultPage_ (Request*, Response* response)
{
WriteDocsPage (
response,
Sequence<WebServiceMethodDescription>{
kVariables_,
kPlus_,
kMinus,
kTimes,
kDivide,
},
DocsOptions{L"Stroika Sample WebService - Web Methods"_k});
}
static void SetAppState_ (Message* message)
{
String argsAsString = Streams::TextReader::New (message->rwRequest ().GetBody ()).ReadAll ();
message->rwResponse ().writeln (L"<html><body><p>Hi SetAppState (" + argsAsString.As<wstring> () + L")</p></body></html>");
message->rwResponse ().SetContentType (DataExchange::InternetMediaTypes::kHTML);
}
};
/*
* Documentation on WSAPIs
*/
const WebServiceMethodDescription WebServer::Rep_::kVariables_{
L"variables"_k,
Set<String>{Methods::kGet, Methods::kPost, Methods::kDelete},
DataExchange::InternetMediaTypes::kJSON,
{},
Sequence<String>{
L"curl http://localhost:8080/variables -v --output -",
L"curl http://localhost:8080/variables/x -v --output -",
L"curl -X POST http://localhost:8080/variables/x -v --output -",
L"curl -H \"Content-Type: application/json\" -X POST -d '{\"value\": 3}' http://localhost:8080/variables/x --output -",
L"curl -H \"Content-Type: text/plain\" -X POST -d '3' http://localhost:8080/variables/x --output -"},
Sequence<String>{L"@todo - this is a rough draft (but functional). It could use alot of cleanup and review to see WHICH way I recommend using, and just provide the recommended ways in samples"},
};
const WebServiceMethodDescription WebServer::Rep_::kPlus_{
L"plus"_k,
Set<String>{Methods::kPost},
DataExchange::InternetMediaTypes::kJSON,
{},
Sequence<String>{
L"curl -H \"Content-Type: application/json\" -X POST -d '{\"arg1\": 3, \"arg2\": 5 }' http://localhost:8080/plus --output -",
},
Sequence<String>{L"add the two argument numbers"},
};
const WebServiceMethodDescription WebServer::Rep_::kMinus{
L"minus"_k,
Set<String>{Methods::kPost},
DataExchange::InternetMediaTypes::kJSON,
{},
Sequence<String>{
L"curl -H \"Content-Type: application/json\" -X POST -d '{\"arg1\": 4.5, \"arg2\": -3.23 }' http://localhost:8080/minus --output -",
},
Sequence<String>{L"subtract the two argument numbers"},
};
const WebServiceMethodDescription WebServer::Rep_::kTimes{
L"times"_k,
Set<String>{Methods::kPost},
DataExchange::InternetMediaTypes::kJSON,
{},
Sequence<String>{
L"curl -H \"Content-Type: application/json\" -X POST -d '{\"arg1\":\"2 + 4i\", \"arg2\": 3.2 }' http://localhost:8080/times --output -",
L"curl -H \"Content-Type: application/json\" -X POST -d '{\"arg1\":\"2 + i\", \"arg2\": \"2 - i\" }' http://localhost:8080/times --output -",
},
Sequence<String>{L"multiply the two argument numbers"},
};
const WebServiceMethodDescription WebServer::Rep_::kDivide{
L"divide"_k,
Set<String>{Methods::kPost},
DataExchange::InternetMediaTypes::kJSON,
{},
Sequence<String>{
L"curl -H \"Content-Type: application/json\" -X POST -d '{\"arg1\":\"2 + i\", \"arg2\": 0 }' http://localhost:8080/divide --output -",
},
Sequence<String>{L"divide the two argument numbers"},
};
WebServer::WebServer (uint16_t portNumber, const shared_ptr<IWSAPI>& wsImpl)
: fRep_ (make_shared<Rep_> (portNumber, wsImpl))
{
}
<commit_msg>minor cleanups<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#include "Stroika/Frameworks/StroikaPreComp.h"
#include <iostream>
#include "Stroika/Foundation/Characters/FloatConversion.h"
#include "Stroika/Foundation/Characters/String2Int.h"
#include "Stroika/Foundation/Characters/ToString.h"
#include "Stroika/Foundation/DataExchange/InternetMediaTypeRegistry.h"
#include "Stroika/Foundation/IO/Network/HTTP/Exception.h"
#include "Stroika/Foundation/IO/Network/HTTP/Headers.h"
#include "Stroika/Foundation/IO/Network/HTTP/Methods.h"
#include "Stroika/Foundation/Streams/TextReader.h"
#include "Stroika/Frameworks/WebServer/ConnectionManager.h"
#include "Stroika/Frameworks/WebServer/Router.h"
#include "Stroika/Frameworks/WebService/Server/Basic.h"
#include "Stroika/Frameworks/WebService/Server/VariantValue.h"
#include "WebServer.h"
#include "AppVersion.h"
using namespace std;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::IO::Network;
using namespace Stroika::Foundation::IO::Network::HTTP;
using namespace Stroika::Frameworks::WebServer;
using namespace Stroika::Frameworks::WebService;
using namespace Stroika::Frameworks::WebService::Server;
using namespace Stroika::Frameworks::WebService::Server::VariantValue;
using Memory::BLOB;
using namespace StroikaSample::WebServices;
/*
* It's often helpful to structure together, routes, special interceptors, with your connection manager, to package up
* all the logic /options for HTTP interface.
*
* This particular organization also makes it easy to save instance variables with the webserver (like a pointer to a handler)
* and accesss them from the Route handler functions.
*/
class WebServer::Rep_ {
public:
const Sequence<Route> kRoutes_; // rules saying how to map urls to code
shared_ptr<IWSAPI> fWSImpl_; // application logic actually handling webservices
ConnectionManager fConnectionMgr_; // manage http connection objects, thread pool, etc
static const WebServiceMethodDescription kVariables_;
static const WebServiceMethodDescription kPlus_;
static const WebServiceMethodDescription kMinus;
static const WebServiceMethodDescription kTimes;
static const WebServiceMethodDescription kDivide;
Rep_ (uint16_t portNumber, const shared_ptr<IWSAPI>& wsImpl)
: kRoutes_{
Route{L""_RegEx, DefaultPage_},
Route{MethodsRegEx::kPost, L"SetAppState"_RegEx, SetAppState_},
Route{L"FRED"_RegEx, [] (Request*, Response* response) {
response->write (L"FRED");
response->SetContentType (DataExchange::InternetMediaTypes::kText_PLAIN);
}},
/*
* the 'variable' API demonstrates a typical REST style CRUD usage - where the 'arguments' mainly come from
* the URL itself.
*/
Route{L"variables(/?)"_RegEx, [this] (Message* m) {
WriteResponse (&m->rwResponse (), kVariables_, kMapper.FromObject (fWSImpl_->Variables_GET ()));
}},
Route{L"variables/(.+)"_RegEx, [this] (Message* m, const String& varName) {
WriteResponse (&m->rwResponse (), kVariables_, kMapper.FromObject (fWSImpl_->Variables_GET (varName)));
}},
Route{MethodsRegEx::kPostOrPut, L"variables/(.+)"_RegEx, [this] (Message* m, const String& varName) {
optional<Number> number;
// demo getting argument from the body
if (not number) {
// read if content-type is text (not json)
if (m->request ().contentType () and DataExchange::InternetMediaTypeRegistry::Get ().IsA (DataExchange::InternetMediaTypes::kText_PLAIN, *m->request ().contentType ())) {
String argsAsString = Streams::TextReader::New (m->rwRequest ().GetBody ()).ReadAll ();
number = kMapper.ToObject<Number> (DataExchange::VariantValue (argsAsString));
}
}
// demo getting argument from the query argument
if (not number) {
static const String kValueParamName_ = L"value"sv;
Mapping<String, DataExchange::VariantValue> args = PickoutParamValuesFromURL (&m->request ());
number = Model::kMapper.ToObject<Number> (args.LookupValue (kValueParamName_));
}
// demo getting either query arg, or url encoded arg
if (not number) {
static const String kValueParamName_ = L"value"sv;
// NOTE - PickoutParamValues combines PickoutParamValuesFromURL, and PickoutParamValuesFromBody. You can use
// Either one of those instead. PickoutParamValuesFromURL assumes you know the name of the parameter, and its
// encoded in the query string. PickoutParamValuesFromBody assumes you have something equivilent you can parse ouf
// of the body, either json encoded or form-encoded (as of 2.1d23, only json encoded supported)
Mapping<String, DataExchange::VariantValue> args = PickoutParamValues (&m->rwRequest ());
number = Model::kMapper.ToObject<Number> (args.LookupValue (kValueParamName_));
}
if (not number) {
Execution::Throw (ClientErrorException{L"Expected argument to PUT/POST variable"sv});
}
fWSImpl_->Variables_SET (varName, *number);
WriteResponse (&m->rwResponse (), kVariables_);
}},
Route{MethodsRegEx::kDelete, L"variables/(.+)"_RegEx, [this] (Message* m, const String& varName) {
fWSImpl_->Variables_DELETE (varName);
WriteResponse (&m->rwResponse (), kVariables_);
}},
/*
* plus, minus, times, and divide, test-void-return all all demonstrate passing in variables through either the POST body, or query-arguments.
*/
Route{L"plus"_RegEx, mkRequestHandler (kPlus_, Model::kMapper, Traversal::Iterable<String>{L"arg1", L"arg2"}, function<Number (Number, Number)>{[this] (Number arg1, Number arg2) { return fWSImpl_->plus (arg1, arg2); }})},
Route{L"minus"_RegEx, mkRequestHandler (kMinus, Model::kMapper, Traversal::Iterable<String>{L"arg1", L"arg2"}, function<Number (Number, Number)>{[this] (Number arg1, Number arg2) { return fWSImpl_->minus (arg1, arg2); }})},
Route{L"times"_RegEx, mkRequestHandler (kTimes, Model::kMapper, Traversal::Iterable<String>{L"arg1", L"arg2"}, function<Number (Number, Number)>{[this] (Number arg1, Number arg2) { return fWSImpl_->times (arg1, arg2); }})},
Route{L"divide"_RegEx, mkRequestHandler (kDivide, Model::kMapper, Traversal::Iterable<String>{L"arg1", L"arg2"}, function<Number (Number, Number)>{[this] (Number arg1, Number arg2) { return fWSImpl_->divide (arg1, arg2); }})},
Route{L"test-void-return"_RegEx, mkRequestHandler (WebServiceMethodDescription{}, Model::kMapper, Traversal::Iterable<String>{L"err-if-more-than-10"}, function<void (double)>{[] (double check) {
if (check > 10) {
Execution::Throw (Execution::Exception{L"more than 10"sv});
} }})},
}
, fWSImpl_
{
wsImpl
}
#if __cpp_designated_initializers
, fConnectionMgr_
{
SocketAddresses (InternetAddresses_Any (), portNumber), kRoutes_, ConnectionManager::Options { .fBindFlags = Socket::BindFlags{}, .fServerHeader = L"Stroika-Sample-WebServices/"_k + AppVersion::kVersion.AsMajorMinorString () }
}
#else
, fConnectionMgr_
{
SocketAddresses (InternetAddresses_Any (), portNumber), kRoutes_, ConnectionManager::Options { nullopt, nullopt, Socket::BindFlags{}, L"Stroika-Sample-WebServices/"_k + AppVersion::kVersion.AsMajorMinorString () }
}
#endif
{
// @todo - move this to some framework-specific regtests...
using VariantValue = DataExchange::VariantValue;
Sequence<VariantValue> tmp = OrderParamValues (Iterable<String>{L"page", L"xxx"}, PickoutParamValuesFromURL (URI{L"http://www.sophist.com?page=5"}));
Assert (tmp.size () == 2);
Assert (tmp[0] == 5);
Assert (tmp[1] == nullptr);
}
// Can declare arguments as Request*,Response*
static void DefaultPage_ (Request*, Response* response)
{
WriteDocsPage (
response,
Sequence<WebServiceMethodDescription>{
kVariables_,
kPlus_,
kMinus,
kTimes,
kDivide,
},
DocsOptions{L"Stroika Sample WebService - Web Methods"_k});
}
static void SetAppState_ (Message* message)
{
String argsAsString = Streams::TextReader::New (message->rwRequest ().GetBody ()).ReadAll ();
message->rwResponse ().writeln (L"<html><body><p>Hi SetAppState (" + argsAsString.As<wstring> () + L")</p></body></html>");
message->rwResponse ().SetContentType (DataExchange::InternetMediaTypes::kHTML);
}
};
/*
* Documentation on WSAPIs
*/
const WebServiceMethodDescription WebServer::Rep_::kVariables_{
L"variables"_k,
Set<String>{Methods::kGet, Methods::kPost, Methods::kDelete},
DataExchange::InternetMediaTypes::kJSON,
{},
Sequence<String>{
L"curl http://localhost:8080/variables -v --output -",
L"curl http://localhost:8080/variables/x -v --output -",
L"curl -X POST http://localhost:8080/variables/x -v --output -",
L"curl -H \"Content-Type: application/json\" -X POST -d '{\"value\": 3}' http://localhost:8080/variables/x --output -",
L"curl -H \"Content-Type: text/plain\" -X POST -d '3' http://localhost:8080/variables/x --output -"},
Sequence<String>{L"@todo - this is a rough draft (but functional). It could use alot of cleanup and review to see WHICH way I recommend using, and just provide the recommended ways in samples"},
};
const WebServiceMethodDescription WebServer::Rep_::kPlus_{
L"plus"_k,
Set<String>{Methods::kPost},
DataExchange::InternetMediaTypes::kJSON,
{},
Sequence<String>{
L"curl -H \"Content-Type: application/json\" -X POST -d '{\"arg1\": 3, \"arg2\": 5 }' http://localhost:8080/plus --output -",
},
Sequence<String>{L"add the two argument numbers"},
};
const WebServiceMethodDescription WebServer::Rep_::kMinus{
L"minus"_k,
Set<String>{Methods::kPost},
DataExchange::InternetMediaTypes::kJSON,
{},
Sequence<String>{
L"curl -H \"Content-Type: application/json\" -X POST -d '{\"arg1\": 4.5, \"arg2\": -3.23 }' http://localhost:8080/minus --output -",
},
Sequence<String>{L"subtract the two argument numbers"},
};
const WebServiceMethodDescription WebServer::Rep_::kTimes{
L"times"_k,
Set<String>{Methods::kPost},
DataExchange::InternetMediaTypes::kJSON,
{},
Sequence<String>{
L"curl -H \"Content-Type: application/json\" -X POST -d '{\"arg1\":\"2 + 4i\", \"arg2\": 3.2 }' http://localhost:8080/times --output -",
L"curl -H \"Content-Type: application/json\" -X POST -d '{\"arg1\":\"2 + i\", \"arg2\": \"2 - i\" }' http://localhost:8080/times --output -",
},
Sequence<String>{L"multiply the two argument numbers"},
};
const WebServiceMethodDescription WebServer::Rep_::kDivide{
L"divide"_k,
Set<String>{Methods::kPost},
DataExchange::InternetMediaTypes::kJSON,
{},
Sequence<String>{
L"curl -H \"Content-Type: application/json\" -X POST -d '{\"arg1\":\"2 + i\", \"arg2\": 0 }' http://localhost:8080/divide --output -",
},
Sequence<String>{L"divide the two argument numbers"},
};
WebServer::WebServer (uint16_t portNumber, const shared_ptr<IWSAPI>& wsImpl)
: fRep_ (make_shared<Rep_> (portNumber, wsImpl))
{
}
<|endoftext|> |
<commit_before>/*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
// CTK includes
#include "ctkVTKScalarBarWidget.h"
#include "ui_ctkVTKScalarBarWidget.h"
// VTK includes
#include <vtkScalarBarActor.h>
#include <vtkScalarBarWidget.h>
//-----------------------------------------------------------------------------
class ctkVTKScalarBarWidgetPrivate: public Ui_ctkVTKScalarBarWidget
{
Q_DECLARE_PUBLIC(ctkVTKScalarBarWidget);
protected:
ctkVTKScalarBarWidget* const q_ptr;
public:
ctkVTKScalarBarWidgetPrivate(ctkVTKScalarBarWidget& object);
void init();
void updateFromScalarBarWidget();
vtkScalarBarWidget* ScalarBarWidget;
};
//-----------------------------------------------------------------------------
ctkVTKScalarBarWidgetPrivate::ctkVTKScalarBarWidgetPrivate(ctkVTKScalarBarWidget& object)
:q_ptr(&object)
{
this->ScalarBarWidget = 0;
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidgetPrivate::init()
{
Q_Q(ctkVTKScalarBarWidget);
this->setupUi(q);
q->setEnabled(this->ScalarBarWidget != 0);
QObject::connect(this->DisplayScalarBarCheckBox, SIGNAL(toggled(bool)),
q, SLOT(setDisplay(bool)));
QObject::connect(this->MaxNumberOfColorsSpinBox, SIGNAL(valueChanged(int)),
q, SLOT(setMaxNumberOfColors(int)));
QObject::connect(this->NumberOfLabelsSpinBox, SIGNAL(valueChanged(int)),
q, SLOT(setNumberOfLabels(int)));
QObject::connect(this->TitleTextPropertyWidget, SIGNAL(textChanged(QString)),
q, SLOT(setTitle(QString)));
QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(textChanged(QString)),
q, SLOT(setLabelsFormat(QString)));
QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(colorChanged(QColor)),
q, SIGNAL(modified()));
QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(opacityChanged(double)),
q, SIGNAL(modified()));
QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(fontFamilyChanged(QString)),
q, SIGNAL(modified()));
QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(boldChanged(bool)),
q, SIGNAL(modified()));
QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(italicChanged(bool)),
q, SIGNAL(modified()));
QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(shadowChanged(bool)),
q, SIGNAL(modified()));
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidgetPrivate::updateFromScalarBarWidget()
{
Q_Q(ctkVTKScalarBarWidget);
vtkScalarBarActor* actor =
this->ScalarBarWidget ? this->ScalarBarWidget->GetScalarBarActor() : 0;
q->setEnabled(actor != 0);
if (actor == 0)
{
return;
}
this->DisplayScalarBarCheckBox->setChecked(this->ScalarBarWidget->GetEnabled() != 0);
this->MaxNumberOfColorsSpinBox->setValue(actor->GetMaximumNumberOfColors());
this->NumberOfLabelsSpinBox->setValue(actor->GetNumberOfLabels());
this->TitleTextPropertyWidget->setTextProperty(
actor->GetTitleTextProperty());
this->LabelsTextPropertyWidget->setTextProperty(
actor->GetLabelTextProperty());
this->TitleTextPropertyWidget->setText(actor->GetTitle());
this->LabelsTextPropertyWidget->setText(actor->GetLabelFormat());
}
//-----------------------------------------------------------------------------
ctkVTKScalarBarWidget::ctkVTKScalarBarWidget(QWidget* parentWidget)
:QWidget(parentWidget)
, d_ptr(new ctkVTKScalarBarWidgetPrivate(*this))
{
Q_D(ctkVTKScalarBarWidget);
d->init();
}
//-----------------------------------------------------------------------------
ctkVTKScalarBarWidget::ctkVTKScalarBarWidget(vtkScalarBarWidget* scalarBarWidget, QWidget* parentWidget)
:QWidget(parentWidget)
, d_ptr(new ctkVTKScalarBarWidgetPrivate(*this))
{
Q_D(ctkVTKScalarBarWidget);
d->init();
this->setScalarBarWidget(scalarBarWidget);
}
//-----------------------------------------------------------------------------
ctkVTKScalarBarWidget::~ctkVTKScalarBarWidget()
{
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setScalarBarWidget(vtkScalarBarWidget* scalarBarWidget)
{
Q_D(ctkVTKScalarBarWidget);
if (scalarBarWidget == d->ScalarBarWidget)
{
return;
}
vtkScalarBarActor* oldActor =
d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
vtkScalarBarActor* newActor =
scalarBarWidget ? scalarBarWidget->GetScalarBarActor() : 0;
qvtkReconnect(d->ScalarBarWidget, scalarBarWidget, vtkCommand::EnableEvent,
this, SLOT(onScalarBarModified()));
qvtkReconnect(d->ScalarBarWidget, scalarBarWidget, vtkCommand::DisableEvent,
this, SLOT(onScalarBarModified()));
qvtkReconnect(oldActor, newActor, vtkCommand::ModifiedEvent,
this, SLOT(onScalarBarModified()));
d->ScalarBarWidget = scalarBarWidget;
this->onScalarBarModified();
}
//-----------------------------------------------------------------------------
vtkScalarBarWidget* ctkVTKScalarBarWidget::scalarBarWidget()const
{
Q_D(const ctkVTKScalarBarWidget);
return d->ScalarBarWidget;
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::onScalarBarModified()
{
Q_D(ctkVTKScalarBarWidget);
d->updateFromScalarBarWidget();
emit modified();
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setDisplay(bool visible)
{
Q_D(ctkVTKScalarBarWidget);
if (d->ScalarBarWidget == 0)
{
return;
}
d->ScalarBarWidget->SetEnabled(visible);
// calling SetEnabled might fail, make sure the checkbox is up-to-date
d->DisplayScalarBarCheckBox->setChecked(d->ScalarBarWidget->GetEnabled());
}
//-----------------------------------------------------------------------------
bool ctkVTKScalarBarWidget::display()const
{
Q_D(const ctkVTKScalarBarWidget);
return d->DisplayScalarBarCheckBox->isChecked();
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setMaxNumberOfColors(int colorCount)
{
Q_D(ctkVTKScalarBarWidget);
vtkScalarBarActor* actor =
d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
if (actor == 0)
{
return;
}
actor->SetMaximumNumberOfColors(colorCount);
}
//-----------------------------------------------------------------------------
int ctkVTKScalarBarWidget::maxNumberOfColors()const
{
Q_D(const ctkVTKScalarBarWidget);
return d->MaxNumberOfColorsSpinBox->value();
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setNumberOfLabels(int labelCount)
{
Q_D(ctkVTKScalarBarWidget);
vtkScalarBarActor* actor =
d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
if (actor == 0)
{
return;
}
actor->SetNumberOfLabels(labelCount);
}
//-----------------------------------------------------------------------------
int ctkVTKScalarBarWidget::numberOfLabels()const
{
Q_D(const ctkVTKScalarBarWidget);
return d->NumberOfLabelsSpinBox->value();
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setTitle(const QString& title)
{
Q_D(ctkVTKScalarBarWidget);
vtkScalarBarActor* actor =
d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
if (actor == 0)
{
return;
}
actor->SetTitle(title.toLatin1());
}
//-----------------------------------------------------------------------------
QString ctkVTKScalarBarWidget::title()const
{
Q_D(const ctkVTKScalarBarWidget);
return d->TitleTextPropertyWidget->text();
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setLabelsFormat(const QString& format)
{
Q_D(ctkVTKScalarBarWidget);
vtkScalarBarActor* actor =
d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
if (actor == 0)
{
return;
}
actor->SetLabelFormat(format.toLatin1());
}
//-----------------------------------------------------------------------------
QString ctkVTKScalarBarWidget::labelsFormat()const
{
Q_D(const ctkVTKScalarBarWidget);
return d->LabelsTextPropertyWidget->text();
}
<commit_msg>BUG: listen for unique signals from the title text property<commit_after>/*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
// CTK includes
#include "ctkVTKScalarBarWidget.h"
#include "ui_ctkVTKScalarBarWidget.h"
// VTK includes
#include <vtkScalarBarActor.h>
#include <vtkScalarBarWidget.h>
//-----------------------------------------------------------------------------
class ctkVTKScalarBarWidgetPrivate: public Ui_ctkVTKScalarBarWidget
{
Q_DECLARE_PUBLIC(ctkVTKScalarBarWidget);
protected:
ctkVTKScalarBarWidget* const q_ptr;
public:
ctkVTKScalarBarWidgetPrivate(ctkVTKScalarBarWidget& object);
void init();
void updateFromScalarBarWidget();
vtkScalarBarWidget* ScalarBarWidget;
};
//-----------------------------------------------------------------------------
ctkVTKScalarBarWidgetPrivate::ctkVTKScalarBarWidgetPrivate(ctkVTKScalarBarWidget& object)
:q_ptr(&object)
{
this->ScalarBarWidget = 0;
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidgetPrivate::init()
{
Q_Q(ctkVTKScalarBarWidget);
this->setupUi(q);
q->setEnabled(this->ScalarBarWidget != 0);
QObject::connect(this->DisplayScalarBarCheckBox, SIGNAL(toggled(bool)),
q, SLOT(setDisplay(bool)));
QObject::connect(this->MaxNumberOfColorsSpinBox, SIGNAL(valueChanged(int)),
q, SLOT(setMaxNumberOfColors(int)));
QObject::connect(this->NumberOfLabelsSpinBox, SIGNAL(valueChanged(int)),
q, SLOT(setNumberOfLabels(int)));
QObject::connect(this->TitleTextPropertyWidget, SIGNAL(textChanged(QString)),
q, SLOT(setTitle(QString)));
QObject::connect(this->TitleTextPropertyWidget, SIGNAL(colorChanged(QColor)),
q, SIGNAL(modified()));
QObject::connect(this->TitleTextPropertyWidget, SIGNAL(opacityChanged(double)),
q, SIGNAL(modified()));
QObject::connect(this->TitleTextPropertyWidget, SIGNAL(fontFamilyChanged(QString)),
q, SIGNAL(modified()));
QObject::connect(this->TitleTextPropertyWidget, SIGNAL(boldChanged(bool)),
q, SIGNAL(modified()));
QObject::connect(this->TitleTextPropertyWidget, SIGNAL(italicChanged(bool)),
q, SIGNAL(modified()));
QObject::connect(this->TitleTextPropertyWidget, SIGNAL(shadowChanged(bool)),
q, SIGNAL(modified()));
QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(textChanged(QString)),
q, SLOT(setLabelsFormat(QString)));
QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(colorChanged(QColor)),
q, SIGNAL(modified()));
QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(opacityChanged(double)),
q, SIGNAL(modified()));
QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(fontFamilyChanged(QString)),
q, SIGNAL(modified()));
QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(boldChanged(bool)),
q, SIGNAL(modified()));
QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(italicChanged(bool)),
q, SIGNAL(modified()));
QObject::connect(this->LabelsTextPropertyWidget, SIGNAL(shadowChanged(bool)),
q, SIGNAL(modified()));
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidgetPrivate::updateFromScalarBarWidget()
{
Q_Q(ctkVTKScalarBarWidget);
vtkScalarBarActor* actor =
this->ScalarBarWidget ? this->ScalarBarWidget->GetScalarBarActor() : 0;
q->setEnabled(actor != 0);
if (actor == 0)
{
return;
}
this->DisplayScalarBarCheckBox->setChecked(this->ScalarBarWidget->GetEnabled() != 0);
this->MaxNumberOfColorsSpinBox->setValue(actor->GetMaximumNumberOfColors());
this->NumberOfLabelsSpinBox->setValue(actor->GetNumberOfLabels());
this->TitleTextPropertyWidget->setTextProperty(
actor->GetTitleTextProperty());
this->LabelsTextPropertyWidget->setTextProperty(
actor->GetLabelTextProperty());
this->TitleTextPropertyWidget->setText(actor->GetTitle());
this->LabelsTextPropertyWidget->setText(actor->GetLabelFormat());
}
//-----------------------------------------------------------------------------
ctkVTKScalarBarWidget::ctkVTKScalarBarWidget(QWidget* parentWidget)
:QWidget(parentWidget)
, d_ptr(new ctkVTKScalarBarWidgetPrivate(*this))
{
Q_D(ctkVTKScalarBarWidget);
d->init();
}
//-----------------------------------------------------------------------------
ctkVTKScalarBarWidget::ctkVTKScalarBarWidget(vtkScalarBarWidget* scalarBarWidget, QWidget* parentWidget)
:QWidget(parentWidget)
, d_ptr(new ctkVTKScalarBarWidgetPrivate(*this))
{
Q_D(ctkVTKScalarBarWidget);
d->init();
this->setScalarBarWidget(scalarBarWidget);
}
//-----------------------------------------------------------------------------
ctkVTKScalarBarWidget::~ctkVTKScalarBarWidget()
{
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setScalarBarWidget(vtkScalarBarWidget* scalarBarWidget)
{
Q_D(ctkVTKScalarBarWidget);
if (scalarBarWidget == d->ScalarBarWidget)
{
return;
}
vtkScalarBarActor* oldActor =
d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
vtkScalarBarActor* newActor =
scalarBarWidget ? scalarBarWidget->GetScalarBarActor() : 0;
qvtkReconnect(d->ScalarBarWidget, scalarBarWidget, vtkCommand::EnableEvent,
this, SLOT(onScalarBarModified()));
qvtkReconnect(d->ScalarBarWidget, scalarBarWidget, vtkCommand::DisableEvent,
this, SLOT(onScalarBarModified()));
qvtkReconnect(oldActor, newActor, vtkCommand::ModifiedEvent,
this, SLOT(onScalarBarModified()));
d->ScalarBarWidget = scalarBarWidget;
this->onScalarBarModified();
}
//-----------------------------------------------------------------------------
vtkScalarBarWidget* ctkVTKScalarBarWidget::scalarBarWidget()const
{
Q_D(const ctkVTKScalarBarWidget);
return d->ScalarBarWidget;
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::onScalarBarModified()
{
Q_D(ctkVTKScalarBarWidget);
d->updateFromScalarBarWidget();
emit modified();
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setDisplay(bool visible)
{
Q_D(ctkVTKScalarBarWidget);
if (d->ScalarBarWidget == 0)
{
return;
}
d->ScalarBarWidget->SetEnabled(visible);
// calling SetEnabled might fail, make sure the checkbox is up-to-date
d->DisplayScalarBarCheckBox->setChecked(d->ScalarBarWidget->GetEnabled());
}
//-----------------------------------------------------------------------------
bool ctkVTKScalarBarWidget::display()const
{
Q_D(const ctkVTKScalarBarWidget);
return d->DisplayScalarBarCheckBox->isChecked();
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setMaxNumberOfColors(int colorCount)
{
Q_D(ctkVTKScalarBarWidget);
vtkScalarBarActor* actor =
d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
if (actor == 0)
{
return;
}
actor->SetMaximumNumberOfColors(colorCount);
}
//-----------------------------------------------------------------------------
int ctkVTKScalarBarWidget::maxNumberOfColors()const
{
Q_D(const ctkVTKScalarBarWidget);
return d->MaxNumberOfColorsSpinBox->value();
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setNumberOfLabels(int labelCount)
{
Q_D(ctkVTKScalarBarWidget);
vtkScalarBarActor* actor =
d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
if (actor == 0)
{
return;
}
actor->SetNumberOfLabels(labelCount);
}
//-----------------------------------------------------------------------------
int ctkVTKScalarBarWidget::numberOfLabels()const
{
Q_D(const ctkVTKScalarBarWidget);
return d->NumberOfLabelsSpinBox->value();
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setTitle(const QString& title)
{
Q_D(ctkVTKScalarBarWidget);
vtkScalarBarActor* actor =
d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
if (actor == 0)
{
return;
}
actor->SetTitle(title.toLatin1());
}
//-----------------------------------------------------------------------------
QString ctkVTKScalarBarWidget::title()const
{
Q_D(const ctkVTKScalarBarWidget);
return d->TitleTextPropertyWidget->text();
}
//-----------------------------------------------------------------------------
void ctkVTKScalarBarWidget::setLabelsFormat(const QString& format)
{
Q_D(ctkVTKScalarBarWidget);
vtkScalarBarActor* actor =
d->ScalarBarWidget ? d->ScalarBarWidget->GetScalarBarActor() : 0;
if (actor == 0)
{
return;
}
actor->SetLabelFormat(format.toLatin1());
}
//-----------------------------------------------------------------------------
QString ctkVTKScalarBarWidget::labelsFormat()const
{
Q_D(const ctkVTKScalarBarWidget);
return d->LabelsTextPropertyWidget->text();
}
<|endoftext|> |
<commit_before>#include "pfasst/quadrature/polynomial.hpp"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <complex>
using namespace std;
namespace pfasst
{
namespace quadrature
{
/**
* @todo Consider issuing a warning/assertion when `n` is zero.
*/
template<typename CoeffT>
Polynomial<CoeffT>::Polynomial(size_t n)
: c(n, CoeffT(0.0))
{}
template<typename CoeffT>
size_t Polynomial<CoeffT>::order() const
{
return c.size() - 1;
}
template<typename CoeffT>
CoeffT& Polynomial<CoeffT>::operator[](const size_t i)
{
return c.at(i);
}
template<typename CoeffT>
Polynomial<CoeffT> Polynomial<CoeffT>::differentiate() const
{
Polynomial<CoeffT> p(c.size() - 1);
for (size_t j = 1; j < c.size(); j++) {
p[j - 1] = j * c[j];
}
return p;
}
template<typename CoeffT>
Polynomial<CoeffT> Polynomial<CoeffT>::integrate() const
{
Polynomial<CoeffT> p(c.size() + 1);
for (size_t j = 0; j < c.size(); j++) {
p[j + 1] = c[j] / (j + 1);
}
return p;
}
template<typename CoeffT>
Polynomial<CoeffT> Polynomial<CoeffT>::normalize() const
{
Polynomial<CoeffT> p(c.size());
for (size_t j = 0; j < c.size(); j++) {
p[j] = c[j] / c.back();
}
return p;
}
/**
* @internals
* @note Asserts this polynomial has at least order 1 if `NDEBUG` is not defined.
* @endinternals
*/
template<typename CoeffT>
vector<CoeffT> Polynomial<CoeffT>::roots(size_t num_iterations, CoeffT ztol) const
{
assert(c.size() >= 1);
size_t n = c.size() - 1;
// initial guess
vector<complex<CoeffT>> z0(n), z1(n);
for (size_t j = 0; j < n; j++) {
z0[j] = pow(complex<double>(0.4, 0.9), j);
z1[j] = z0[j];
}
// durand-kerner-weierstrass iterations
Polynomial<CoeffT> p = this->normalize();
for (size_t k = 0; k < num_iterations; k++) {
complex<CoeffT> num, den;
for (size_t i = 0; i < n; i++) {
num = p.evaluate(z0[i]);
den = 1.0;
for (size_t j = 0; j < n; j++) {
if (j == i) { continue; }
den = den * (z0[i] - z0[j]);
}
z0[i] = z0[i] - num / den;
}
z1 = z0;
}
vector<CoeffT> roots(n);
for (size_t j = 0; j < n; j++) {
roots[j] = abs(z0[j]) < ztol ? 0.0 : real(z0[j]);
}
sort(roots.begin(), roots.end());
return roots;
}
template<typename CoeffT>
Polynomial<CoeffT> Polynomial<CoeffT>::legendre(const size_t order)
{
if (order == 0) {
Polynomial<CoeffT> p(1);
p[0] = 1.0;
return p;
}
if (order == 1) {
Polynomial<CoeffT> p(2);
p[0] = 0.0;
p[1] = 1.0;
return p;
}
Polynomial<CoeffT> p0(order + 1), p1(order + 1), p2(order + 1);
p0[0] = 1.0; p1[1] = 1.0;
// (n + 1) P_{n+1} = (2n + 1) x P_{n} - n P_{n-1}
for (size_t m = 1; m < order; m++) {
for (size_t j = 1; j < order + 1; j++) {
p2[j] = ((2 * m + 1) * p1[j - 1] - m * p0[j]) / (m + 1);
}
p2[0] = - int(m) * p0[0] / (m + 1);
for (size_t j = 0; j < order + 1; j++) {
p0[j] = p1[j];
p1[j] = p2[j];
}
}
return p2;
}
} // ::pfasst::quadrature
} // ::pfasst
<commit_msg>Remove z1.<commit_after>#include "pfasst/quadrature/polynomial.hpp"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <complex>
using namespace std;
namespace pfasst
{
namespace quadrature
{
/**
* @todo Consider issuing a warning/assertion when `n` is zero.
*/
template<typename CoeffT>
Polynomial<CoeffT>::Polynomial(size_t n)
: c(n, CoeffT(0.0))
{}
template<typename CoeffT>
size_t Polynomial<CoeffT>::order() const
{
return c.size() - 1;
}
template<typename CoeffT>
CoeffT& Polynomial<CoeffT>::operator[](const size_t i)
{
return c.at(i);
}
template<typename CoeffT>
Polynomial<CoeffT> Polynomial<CoeffT>::differentiate() const
{
Polynomial<CoeffT> p(c.size() - 1);
for (size_t j = 1; j < c.size(); j++) {
p[j - 1] = j * c[j];
}
return p;
}
template<typename CoeffT>
Polynomial<CoeffT> Polynomial<CoeffT>::integrate() const
{
Polynomial<CoeffT> p(c.size() + 1);
for (size_t j = 0; j < c.size(); j++) {
p[j + 1] = c[j] / (j + 1);
}
return p;
}
template<typename CoeffT>
Polynomial<CoeffT> Polynomial<CoeffT>::normalize() const
{
Polynomial<CoeffT> p(c.size());
for (size_t j = 0; j < c.size(); j++) {
p[j] = c[j] / c.back();
}
return p;
}
/**
* @internals
* @note Asserts this polynomial has at least order 1 if `NDEBUG` is not defined.
* @endinternals
*/
template<typename CoeffT>
vector<CoeffT> Polynomial<CoeffT>::roots(size_t num_iterations, CoeffT ztol) const
{
assert(c.size() >= 1);
size_t n = c.size() - 1;
// initial guess
vector<complex<CoeffT>> z0(n);
for (size_t j = 0; j < n; j++) {
z0[j] = pow(complex<double>(0.4, 0.9), j);
}
// durand-kerner-weierstrass iterations
Polynomial<CoeffT> p = this->normalize();
for (size_t k = 0; k < num_iterations; k++) {
complex<CoeffT> num, den;
for (size_t i = 0; i < n; i++) {
num = p.evaluate(z0[i]);
den = 1.0;
for (size_t j = 0; j < n; j++) {
if (j == i) { continue; }
den = den * (z0[i] - z0[j]);
}
z0[i] = z0[i] - num / den;
}
}
vector<CoeffT> roots(n);
for (size_t j = 0; j < n; j++) {
roots[j] = abs(z0[j]) < ztol ? 0.0 : real(z0[j]);
}
sort(roots.begin(), roots.end());
return roots;
}
template<typename CoeffT>
Polynomial<CoeffT> Polynomial<CoeffT>::legendre(const size_t order)
{
if (order == 0) {
Polynomial<CoeffT> p(1);
p[0] = 1.0;
return p;
}
if (order == 1) {
Polynomial<CoeffT> p(2);
p[0] = 0.0;
p[1] = 1.0;
return p;
}
Polynomial<CoeffT> p0(order + 1), p1(order + 1), p2(order + 1);
p0[0] = 1.0; p1[1] = 1.0;
// (n + 1) P_{n+1} = (2n + 1) x P_{n} - n P_{n-1}
for (size_t m = 1; m < order; m++) {
for (size_t j = 1; j < order + 1; j++) {
p2[j] = ((2 * m + 1) * p1[j - 1] - m * p0[j]) / (m + 1);
}
p2[0] = - int(m) * p0[0] / (m + 1);
for (size_t j = 0; j < order + 1; j++) {
p0[j] = p1[j];
p1[j] = p2[j];
}
}
return p2;
}
} // ::pfasst::quadrature
} // ::pfasst
<|endoftext|> |
<commit_before>///
/// @file PrintPrimes.hpp
///
/// Copyright (C) 2018 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PRIMEGENERATOR_HPP
#define PRIMEGENERATOR_HPP
#include "Erat.hpp"
#include "PreSieve.hpp"
#include "PrimeSieve.hpp"
#include "types.hpp"
#include <stdint.h>
#include <vector>
namespace primesieve {
class Store;
/// After a segment has been sieved PrintPrimes is
/// used to reconstruct primes and prime k-tuplets from
/// 1 bits of the sieve array
///
class PrintPrimes : public Erat
{
public:
PrintPrimes(PrimeSieve&);
void sieve();
private:
enum { END = 0xff + 1 };
static const uint64_t bitmasks_[6][5];
uint64_t low_ = 0;
/// Count lookup tables for prime k-tuplets
std::vector<byte_t> kCounts_[6];
PreSieve preSieve_;
counts_t& counts_;
/// Reference to the associated PrimeSieve object
PrimeSieve& ps_;
void initCounts();
void print();
void countPrimes();
void countkTuplets();
void printPrimes() const;
void printkTuplets() const;
};
} // namespace
#endif
<commit_msg>Fix include guards<commit_after>///
/// @file PrintPrimes.hpp
///
/// Copyright (C) 2018 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PRINTPRIMES_HPP
#define PRINTPRIMES_HPP
#include "Erat.hpp"
#include "PreSieve.hpp"
#include "PrimeSieve.hpp"
#include "types.hpp"
#include <stdint.h>
#include <vector>
namespace primesieve {
class Store;
/// After a segment has been sieved PrintPrimes is
/// used to reconstruct primes and prime k-tuplets from
/// 1 bits of the sieve array
///
class PrintPrimes : public Erat
{
public:
PrintPrimes(PrimeSieve&);
void sieve();
private:
enum { END = 0xff + 1 };
static const uint64_t bitmasks_[6][5];
uint64_t low_ = 0;
/// Count lookup tables for prime k-tuplets
std::vector<byte_t> kCounts_[6];
PreSieve preSieve_;
counts_t& counts_;
/// Reference to the associated PrimeSieve object
PrimeSieve& ps_;
void initCounts();
void print();
void countPrimes();
void countkTuplets();
void printPrimes() const;
void printkTuplets() const;
};
} // namespace
#endif
<|endoftext|> |
<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_SHARED_INPUT_HPP
#define RJ_SHARED_INPUT_HPP
#include <rectojump/global/common.hpp>
#include <mlk/containers/container_utl.h>
#include <mlk/signals_slots/slot.h>
#include <mlk/tools/bitset.h>
#include <map>
namespace rj
{
class game_window;
using key_vec = std::vector<key>;
class input
{
friend class game_window;
mlk::bitset<btn, btn::ButtonCount> m_mousebtn_bits;
mlk::bitset<key, key::KeyCount> m_key_bits;
public:
mlk::event_delegates<key> on_key_pressed;
mlk::event_delegates<key_vec> on_keys_pressed;
mlk::event_delegates<btn, const vec2f&> on_btn_pressed;
input() = default;
static input& get() noexcept
{static input i; return i;}
bool is_key_valid(key k) const noexcept
{return k != key::Unknown;}
private:
void update(const vec2f& mousepos)
{
for(auto& a : on_btn_pressed)
if(m_mousebtn_bits & a.first)
a.second(mousepos);
}
void key_pressed(key k)
{
if(!this->is_key_valid(k))
return;
if(mlk::cnt::exists_if(
[=](const std::pair<key, mlk::slot<>>& p)
{return p.first == k;}, on_key_pressed))
on_key_pressed[k]();
m_key_bits |= k;
for(auto& keys : on_keys_pressed)
{
auto all_pressed(false);
for(auto& key : keys.first)
{
if(!this->is_key_valid(key))
break;
// check if key 'key' is currently pressed
if(!(m_key_bits & key))
{
all_pressed = false;
break;
}
all_pressed = true;
}
// not all keys were pressed
if(!all_pressed)
continue;
// call slot
keys.second();
}
}
void key_released(key k)
{
if(!this->is_key_valid(k))
return;
m_key_bits.remove(k);
}
void btn_pressed(btn b)
{m_mousebtn_bits |= b;}
void btn_released(btn b)
{m_mousebtn_bits.remove(b);}
};
inline auto on_key_pressed(key k)
-> decltype(input::get().on_key_pressed[k])&
{
if(!input::get().is_key_valid(k))
throw std::runtime_error{"invalid key passed"};
return input::get().on_key_pressed[k];
}
template<typename... Keys>
auto on_keys_pressed(Keys&&... keys)
-> decltype(input::get().on_keys_pressed[key_vec{}])
{
key_vec keys_vec;
mlk::cnt::make_vector(keys_vec, std::forward<Keys>(keys)...);
return input::get().on_keys_pressed[keys_vec];
}
inline auto on_btn_pressed(btn b)
-> decltype(input::get().on_btn_pressed[b])&
{return input::get().on_btn_pressed[b];}
}
#endif // RJ_SHARED_INPUT_HPP
<commit_msg>input: added functions to test currently pressed keys/buttons<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_SHARED_INPUT_HPP
#define RJ_SHARED_INPUT_HPP
#include <rectojump/global/common.hpp>
#include <mlk/containers/container_utl.h>
#include <mlk/signals_slots/slot.h>
#include <mlk/tools/bitset.h>
#include <map>
namespace rj
{
class game_window;
using key_vec = std::vector<key>;
class input
{
friend class game_window;
mlk::bitset<btn, btn::ButtonCount> m_mousebtn_bits;
mlk::bitset<key, key::KeyCount> m_key_bits;
mlk::event_delegates<key> m_on_key_pressed;
mlk::event_delegates<key_vec> m_on_keys_pressed;
mlk::event_delegates<btn, const vec2f&> m_on_btn_pressed;
public:
input() = default;
static input& get() noexcept
{static input i; return i;}
bool is_key_valid(key k) const noexcept
{return k != key::Unknown;}
private:
void update(const vec2f& mousepos)
{
for(auto& a : m_on_btn_pressed)
if(m_mousebtn_bits & a.first)
a.second(mousepos);
}
void key_pressed(key k)
{
if(!this->is_key_valid(k))
return;
if(mlk::cnt::exists_if(
[=](const std::pair<key, mlk::slot<>>& p)
{return p.first == k;}, m_on_key_pressed))
m_on_key_pressed[k]();
m_key_bits |= k;
for(auto& keys : m_on_keys_pressed)
{
auto all_pressed(false);
for(auto& key : keys.first)
{
if(!this->is_key_valid(key))
break;
// check if key 'key' is currently pressed
if(!(m_key_bits & key))
{
all_pressed = false;
break;
}
all_pressed = true;
}
// not all keys were pressed
if(!all_pressed)
continue;
// call slot
keys.second();
}
}
void key_released(key k)
{
if(!this->is_key_valid(k))
return;
m_key_bits.remove(k);
}
void btn_pressed(btn b)
{m_mousebtn_bits |= b;}
void btn_released(btn b)
{m_mousebtn_bits.remove(b);}
friend auto on_key_pressed(key k)
-> decltype(m_on_key_pressed[k])&;
template<typename... Keys>
friend auto on_keys_pressed(Keys&&...)
-> decltype(m_on_keys_pressed[key_vec{}]);
friend bool is_key_pressed(key);
friend inline auto on_btn_pressed(btn b)
-> decltype(m_on_btn_pressed[b])&;
friend bool is_btn_pressed(btn);
};
inline auto on_key_pressed(key k)
-> decltype(input::get().m_on_key_pressed[k])&
{
if(!input::get().is_key_valid(k))
throw std::runtime_error{"invalid key passed"};
return input::get().m_on_key_pressed[k];
}
template<typename... Keys>
auto on_keys_pressed(Keys&&... keys)
-> decltype(input::get().m_on_keys_pressed[key_vec{}])
{
key_vec keys_vec;
mlk::cnt::make_vector(keys_vec, std::forward<Keys>(keys)...);
return input::get().m_on_keys_pressed[keys_vec];
}
inline bool is_key_pressed(key k)
{return input::get().m_key_bits & k;}
inline auto on_btn_pressed(btn b)
-> decltype(input::get().m_on_btn_pressed[b])&
{return input::get().m_on_btn_pressed[b];}
inline bool is_btn_pressed(btn b)
{return input::get().m_mousebtn_bits & b;}
}
#endif // RJ_SHARED_INPUT_HPP
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2018 ScyllaDB
*/
#pragma once
#include <optional>
#include <string_view>
#include <variant>
#include <filesystem>
#include <memory_resource>
namespace seastar {
/// \cond internal
namespace compat {
using memory_resource = std::pmr::memory_resource;
template<typename T>
using polymorphic_allocator = std::pmr::polymorphic_allocator<T>;
static inline
memory_resource* pmr_get_default_resource() {
return std::pmr::get_default_resource();
}
}
}
// Defining SEASTAR_ASAN_ENABLED in here is a bit of a hack, but
// convenient since it is build system independent and in practice
// everything includes this header.
#ifndef __has_feature
#define __has_feature(x) 0
#endif
// clang uses __has_feature, gcc defines __SANITIZE_ADDRESS__
#if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)
#define SEASTAR_ASAN_ENABLED
#endif
namespace seastar {
/// \cond internal
namespace compat {
template <typename T>
using optional = std::optional<T>;
using nullopt_t = std::nullopt_t;
inline constexpr auto nullopt = std::nullopt;
template <typename T>
inline constexpr optional<std::decay_t<T>> make_optional(T&& value) {
return std::make_optional(std::forward<T>(value));
}
template <typename CharT, typename Traits = std::char_traits<CharT>>
using basic_string_view = std::basic_string_view<CharT, Traits>;
template <typename CharT, typename Traits = std::char_traits<CharT>>
std::string string_view_to_string(const basic_string_view<CharT, Traits>& v) {
return std::string(v);
}
template <typename... Types>
using variant = std::variant<Types...>;
template <std::size_t I, typename... Types>
constexpr std::variant_alternative_t<I, variant<Types...>>& get(variant<Types...>& v) {
return std::get<I>(v);
}
template <std::size_t I, typename... Types>
constexpr const std::variant_alternative_t<I, variant<Types...>>& get(const variant<Types...>& v) {
return std::get<I>(v);
}
template <std::size_t I, typename... Types>
constexpr std::variant_alternative_t<I, variant<Types...>>&& get(variant<Types...>&& v) {
return std::get<I>(v);
}
template <std::size_t I, typename... Types>
constexpr const std::variant_alternative_t<I, variant<Types...>>&& get(const variant<Types...>&& v) {
return std::get<I>(v);
}
template <typename U, typename... Types>
constexpr U& get(variant<Types...>& v) {
return std::get<U>(v);
}
template <typename U, typename... Types>
constexpr const U& get(const variant<Types...>& v) {
return std::get<U>(v);
}
template <typename U, typename... Types>
constexpr U&& get(variant<Types...>&& v) {
return std::get<U>(v);
}
template <typename U, typename... Types>
constexpr const U&& get(const variant<Types...>&& v) {
return std::get<U>(v);
}
template <typename U, typename... Types>
constexpr U* get_if(variant<Types...>* v) {
return std::get_if<U>(v);
}
template <typename U, typename... Types>
constexpr const U* get_if(const variant<Types...>* v) {
return std::get_if<U>(v);
}
using string_view = basic_string_view<char>;
} // namespace compat
/// \endcond
} // namespace seastar
#define SEASTAR_COPY_ELISION(x) x
<commit_msg>std-compat: Delete SEASTAR_COPY_ELISION<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2018 ScyllaDB
*/
#pragma once
#include <optional>
#include <string_view>
#include <variant>
#include <filesystem>
#include <memory_resource>
namespace seastar {
/// \cond internal
namespace compat {
using memory_resource = std::pmr::memory_resource;
template<typename T>
using polymorphic_allocator = std::pmr::polymorphic_allocator<T>;
static inline
memory_resource* pmr_get_default_resource() {
return std::pmr::get_default_resource();
}
}
}
// Defining SEASTAR_ASAN_ENABLED in here is a bit of a hack, but
// convenient since it is build system independent and in practice
// everything includes this header.
#ifndef __has_feature
#define __has_feature(x) 0
#endif
// clang uses __has_feature, gcc defines __SANITIZE_ADDRESS__
#if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)
#define SEASTAR_ASAN_ENABLED
#endif
namespace seastar {
/// \cond internal
namespace compat {
template <typename T>
using optional = std::optional<T>;
using nullopt_t = std::nullopt_t;
inline constexpr auto nullopt = std::nullopt;
template <typename T>
inline constexpr optional<std::decay_t<T>> make_optional(T&& value) {
return std::make_optional(std::forward<T>(value));
}
template <typename CharT, typename Traits = std::char_traits<CharT>>
using basic_string_view = std::basic_string_view<CharT, Traits>;
template <typename CharT, typename Traits = std::char_traits<CharT>>
std::string string_view_to_string(const basic_string_view<CharT, Traits>& v) {
return std::string(v);
}
template <typename... Types>
using variant = std::variant<Types...>;
template <std::size_t I, typename... Types>
constexpr std::variant_alternative_t<I, variant<Types...>>& get(variant<Types...>& v) {
return std::get<I>(v);
}
template <std::size_t I, typename... Types>
constexpr const std::variant_alternative_t<I, variant<Types...>>& get(const variant<Types...>& v) {
return std::get<I>(v);
}
template <std::size_t I, typename... Types>
constexpr std::variant_alternative_t<I, variant<Types...>>&& get(variant<Types...>&& v) {
return std::get<I>(v);
}
template <std::size_t I, typename... Types>
constexpr const std::variant_alternative_t<I, variant<Types...>>&& get(const variant<Types...>&& v) {
return std::get<I>(v);
}
template <typename U, typename... Types>
constexpr U& get(variant<Types...>& v) {
return std::get<U>(v);
}
template <typename U, typename... Types>
constexpr const U& get(const variant<Types...>& v) {
return std::get<U>(v);
}
template <typename U, typename... Types>
constexpr U&& get(variant<Types...>&& v) {
return std::get<U>(v);
}
template <typename U, typename... Types>
constexpr const U&& get(const variant<Types...>&& v) {
return std::get<U>(v);
}
template <typename U, typename... Types>
constexpr U* get_if(variant<Types...>* v) {
return std::get_if<U>(v);
}
template <typename U, typename... Types>
constexpr const U* get_if(const variant<Types...>* v) {
return std::get_if<U>(v);
}
using string_view = basic_string_view<char>;
} // namespace compat
/// \endcond
} // namespace seastar
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* Copyright (c) Serge Guelton *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XSIMD_SSSE3_HPP
#define XSIMD_SSSE3_HPP
#include <cstddef>
#include <type_traits>
#include "../types/xsimd_ssse3_register.hpp"
#include "../types/xsimd_utils.hpp"
namespace xsimd
{
namespace kernel
{
using namespace types;
// abs
template <class A, class T, typename std::enable_if<std::is_integral<T>::value && std::is_signed<T>::value, void>::type>
inline batch<T, A> abs(batch<T, A> const& self, requires_arch<ssse3>) noexcept
{
switch (sizeof(T))
{
case 1:
return _mm_abs_epi8(self);
case 2:
return _mm_abs_epi16(self);
case 4:
return _mm_abs_epi32(self);
case 8:
return _mm_abs_epi64(self);
default:
assert(false && "unsupported arch/op combination");
return {};
}
}
// extract_pair
namespace detail
{
template <class T, class A>
inline batch<T, A> extract_pair(batch<T, A> const&, batch<T, A> const& other, std::size_t, ::xsimd::detail::index_sequence<>) noexcept
{
return other;
}
template <class T, class A, std::size_t I, std::size_t... Is>
inline batch<T, A> extract_pair(batch<T, A> const& self, batch<T, A> const& other, std::size_t i, ::xsimd::detail::index_sequence<I, Is...>) noexcept
{
if (i == I)
{
return _mm_alignr_epi8(self, other, sizeof(T) * I);
}
else
return extract_pair(self, other, i, ::xsimd::detail::index_sequence<Is...>());
}
}
template <class A, class T, class _ = typename std::enable_if<std::is_integral<T>::value, void>::type>
inline batch<T, A> extract_pair(batch<T, A> const& self, batch<T, A> const& other, std::size_t i, requires_arch<ssse3>) noexcept
{
constexpr std::size_t size = batch<T, A>::size;
assert(0 <= i && i < size && "index in bounds");
return detail::extract_pair(self, other, i, ::xsimd::detail::make_index_sequence<size>());
}
// hadd
template <class A, class T, class = typename std::enable_if<std::is_integral<T>::value, void>::type>
inline T hadd(batch<T, A> const& self, requires_arch<ssse3>) noexcept
{
switch (sizeof(T))
{
case 2:
{
__m128i tmp1 = _mm_hadd_epi16(self, self);
__m128i tmp2 = _mm_hadd_epi16(tmp1, tmp1);
__m128i tmp3 = _mm_hadd_epi16(tmp2, tmp2);
return _mm_cvtsi128_si32(tmp3) & 0xFFFF;
}
case 4:
{
__m128i tmp1 = _mm_hadd_epi32(self, self);
__m128i tmp2 = _mm_hadd_epi32(tmp1, tmp1);
return _mm_cvtsi128_si32(tmp2);
}
default:
return hadd(self, sse3 {});
}
}
// swizzle
template <class A, uint16_t V0, uint16_t V1, uint16_t V2, uint16_t V3, uint16_t V4, uint16_t V5, uint16_t V6, uint16_t V7>
inline batch<uint16_t, A> swizzle(batch<uint16_t, A> const& self, batch_constant<batch<uint16_t, A>, V0, V1, V2, V3, V4, V5, V6, V7>, requires_arch<ssse3>) noexcept
{
constexpr batch_constant<batch<uint8_t, A>, 2 * V0, 2 * V0 + 1, 2 * V1, 2 * V1 + 1, 2 * V2, 2 * V2 + 1, 2 * V3, 2 * V3 + 1,
2 * V4, 2 * V4 + 1, 2 * V5, 2 * V5 + 1, 2 * V6, 2 * V6 + 1, 2 * V7, 2 * V7 + 1>
mask8;
return _mm_shuffle_epi8(self, (batch<uint8_t, A>)mask8);
}
template <class A, uint16_t V0, uint16_t V1, uint16_t V2, uint16_t V3, uint16_t V4, uint16_t V5, uint16_t V6, uint16_t V7>
inline batch<int16_t, A> swizzle(batch<int16_t, A> const& self, batch_constant<batch<uint16_t, A>, V0, V1, V2, V3, V4, V5, V6, V7> mask, requires_arch<ssse3>) noexcept
{
return bitwise_cast<int16_t>(swizzle(bitwise_cast<uint16_t>(self), mask, ssse3 {}));
}
template <class A, uint8_t V0, uint8_t V1, uint8_t V2, uint8_t V3, uint8_t V4, uint8_t V5, uint8_t V6, uint8_t V7,
uint8_t V8, uint8_t V9, uint8_t V10, uint8_t V11, uint8_t V12, uint8_t V13, uint8_t V14, uint8_t V15>
inline batch<uint8_t, A> swizzle(batch<uint8_t, A> const& self, batch_constant<batch<uint8_t, A>, V0, V1, V2, V3, V4, V5, V6, V7, V8, V9, V10, V11, V12, V13, V14, V15> mask, requires_arch<ssse3>) noexcept
{
return _mm_shuffle_epi8(self, (batch<uint8_t, A>)mask);
}
template <class A, uint8_t V0, uint8_t V1, uint8_t V2, uint8_t V3, uint8_t V4, uint8_t V5, uint8_t V6, uint8_t V7,
uint8_t V8, uint8_t V9, uint8_t V10, uint8_t V11, uint8_t V12, uint8_t V13, uint8_t V14, uint8_t V15>
inline batch<int8_t, A> swizzle(batch<int8_t, A> const& self, batch_constant<batch<uint8_t, A>, V0, V1, V2, V3, V4, V5, V6, V7, V8, V9, V10, V11, V12, V13, V14, V15> mask, requires_arch<ssse3>) noexcept
{
return bitwise_cast<int8_t>(swizzle(bitwise_cast<uint8_t>(self), mask, ssse3 {}));
}
}
}
#endif
<commit_msg>Converted the switch cases to XSIMD_IF in xsimd_ssse3.hpp<commit_after>/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* Copyright (c) Serge Guelton *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XSIMD_SSSE3_HPP
#define XSIMD_SSSE3_HPP
#include <cstddef>
#include <type_traits>
#include "../types/xsimd_ssse3_register.hpp"
#include "../types/xsimd_utils.hpp"
namespace xsimd
{
namespace kernel
{
using namespace types;
// abs
template <class A, class T, typename std::enable_if<std::is_integral<T>::value && std::is_signed<T>::value, void>::type>
inline batch<T, A> abs(batch<T, A> const& self, requires_arch<ssse3>) noexcept
{
XSIMD_IF(sizeof(T) == 1)
{
return _mm_abs_epi8(self);
}
else XSIMD_IF(sizeof(T) == 2)
{
return _mm_abs_epi16(self);
}
else XSIMD_IF(sizeof(T) == 4)
{
return _mm_abs_epi32(self);
}
else XSIMD_IF(sizeof(T) == 8)
{
return _mm_abs_epi64(self);
}
else
{
assert(false && "unsupported arch/op combination");
return {};
}
}
// extract_pair
namespace detail
{
template <class T, class A>
inline batch<T, A> extract_pair(batch<T, A> const&, batch<T, A> const& other, std::size_t, ::xsimd::detail::index_sequence<>) noexcept
{
return other;
}
template <class T, class A, std::size_t I, std::size_t... Is>
inline batch<T, A> extract_pair(batch<T, A> const& self, batch<T, A> const& other, std::size_t i, ::xsimd::detail::index_sequence<I, Is...>) noexcept
{
if (i == I)
{
return _mm_alignr_epi8(self, other, sizeof(T) * I);
}
else
return extract_pair(self, other, i, ::xsimd::detail::index_sequence<Is...>());
}
}
template <class A, class T, class _ = typename std::enable_if<std::is_integral<T>::value, void>::type>
inline batch<T, A> extract_pair(batch<T, A> const& self, batch<T, A> const& other, std::size_t i, requires_arch<ssse3>) noexcept
{
constexpr std::size_t size = batch<T, A>::size;
assert(0 <= i && i < size && "index in bounds");
return detail::extract_pair(self, other, i, ::xsimd::detail::make_index_sequence<size>());
}
// hadd
template <class A, class T, class = typename std::enable_if<std::is_integral<T>::value, void>::type>
inline T hadd(batch<T, A> const& self, requires_arch<ssse3>) noexcept
{
XSIMD_IF(sizeof(T) == 2)
{
__m128i tmp1 = _mm_hadd_epi16(self, self);
__m128i tmp2 = _mm_hadd_epi16(tmp1, tmp1);
__m128i tmp3 = _mm_hadd_epi16(tmp2, tmp2);
return _mm_cvtsi128_si32(tmp3) & 0xFFFF;
}
else XSIMD_IF(sizeof(T) == 4)
{
__m128i tmp1 = _mm_hadd_epi32(self, self);
__m128i tmp2 = _mm_hadd_epi32(tmp1, tmp1);
return _mm_cvtsi128_si32(tmp2);
}
else
{
return hadd(self, sse3 {});
}
}
// swizzle
template <class A, uint16_t V0, uint16_t V1, uint16_t V2, uint16_t V3, uint16_t V4, uint16_t V5, uint16_t V6, uint16_t V7>
inline batch<uint16_t, A> swizzle(batch<uint16_t, A> const& self, batch_constant<batch<uint16_t, A>, V0, V1, V2, V3, V4, V5, V6, V7>, requires_arch<ssse3>) noexcept
{
constexpr batch_constant<batch<uint8_t, A>, 2 * V0, 2 * V0 + 1, 2 * V1, 2 * V1 + 1, 2 * V2, 2 * V2 + 1, 2 * V3, 2 * V3 + 1,
2 * V4, 2 * V4 + 1, 2 * V5, 2 * V5 + 1, 2 * V6, 2 * V6 + 1, 2 * V7, 2 * V7 + 1>
mask8;
return _mm_shuffle_epi8(self, (batch<uint8_t, A>)mask8);
}
template <class A, uint16_t V0, uint16_t V1, uint16_t V2, uint16_t V3, uint16_t V4, uint16_t V5, uint16_t V6, uint16_t V7>
inline batch<int16_t, A> swizzle(batch<int16_t, A> const& self, batch_constant<batch<uint16_t, A>, V0, V1, V2, V3, V4, V5, V6, V7> mask, requires_arch<ssse3>) noexcept
{
return bitwise_cast<int16_t>(swizzle(bitwise_cast<uint16_t>(self), mask, ssse3 {}));
}
template <class A, uint8_t V0, uint8_t V1, uint8_t V2, uint8_t V3, uint8_t V4, uint8_t V5, uint8_t V6, uint8_t V7,
uint8_t V8, uint8_t V9, uint8_t V10, uint8_t V11, uint8_t V12, uint8_t V13, uint8_t V14, uint8_t V15>
inline batch<uint8_t, A> swizzle(batch<uint8_t, A> const& self, batch_constant<batch<uint8_t, A>, V0, V1, V2, V3, V4, V5, V6, V7, V8, V9, V10, V11, V12, V13, V14, V15> mask, requires_arch<ssse3>) noexcept
{
return _mm_shuffle_epi8(self, (batch<uint8_t, A>)mask);
}
template <class A, uint8_t V0, uint8_t V1, uint8_t V2, uint8_t V3, uint8_t V4, uint8_t V5, uint8_t V6, uint8_t V7,
uint8_t V8, uint8_t V9, uint8_t V10, uint8_t V11, uint8_t V12, uint8_t V13, uint8_t V14, uint8_t V15>
inline batch<int8_t, A> swizzle(batch<int8_t, A> const& self, batch_constant<batch<uint8_t, A>, V0, V1, V2, V3, V4, V5, V6, V7, V8, V9, V10, V11, V12, V13, V14, V15> mask, requires_arch<ssse3>) noexcept
{
return bitwise_cast<int8_t>(swizzle(bitwise_cast<uint8_t>(self), mask, ssse3 {}));
}
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef MINIASCAPE_PERIODIC_BOUNDARY
#define MINIASCAPE_PERIODIC_BOUNDARY
#include <array>
#include "util/zip_iterator.hpp"
#include "Cell.hpp"
namespace miniascape
{
template<typename T_neighbor>
class PeriodicBoundary
{
public:
using neighbor_type = T_neighbor;
using cell_index_type = typename neighbor_type::cell_index_type;
constexpr static std::size_t dimension = neighbor_type::dimension;
public:
PeriodicBoundary() = default;
PeriodicBoundary(const cell_index_type& begin, const cell_index_type& end)
:begin_(begin), end_(end)
{}
~PeriodicBoundary() = default;
template<typename T_world>
typename T_world::cell_ptr const&
access(const cell_index_type& id, const T_world& world) const;
template<typename T_world>
typename T_world::cell_ptr &
access(const cell_index_type& id, T_world& container) const;
private:
// [begin, end)
cell_index_type begin_; // = (0, ..., 0), normally
cell_index_type end_;
};
template<typename T_neighbor>
template<typename T_world>
typename T_world::cell_ptr const&
PeriodicBoundary<T_neighbor>::access(
const cell_index_type& id, const T_world& container) const
{
cell_index_type index = id;
for(auto iter = make_zip(index.begin(), begin_.cbegin(), end_.cbegin());
iter != make_zip(index.end(), begin_.cend(), end_.cend());
++iter)
{
const std::size_t range = *get<2>(iter) - *get<1>(iter);
if((*get<0>(iter) < *get<1>(iter)) /* index < begin */||
(*get<0>(iter) >= *get<2>(iter))/* end <= index */)
{
const int idx = *get<0>(iter) % range;
*get<0>(iter) = (idx < 0) ? idx + range : idx;
}
}
return container(index);
}
template<typename T_neighbor>
template<typename T_world>
typename T_world::cell_ptr &
PeriodicBoundary<T_neighbor>::access(
const cell_index_type& id, T_world& container) const
{
cell_index_type index = id;
for(auto iter = make_zip(index.begin(), begin_.cbegin(), end_.cbegin());
iter != make_zip(index.end(), begin_.cend(), end_.cend());
++iter)
{
const std::size_t range = *get<2>(iter) - *get<1>(iter);
if((*get<0>(iter) < *get<1>(iter)) /* index < begin */||
(*get<0>(iter) >= *get<2>(iter))/* end <= index */)
{
const int idx = *get<0>(iter) % range;
*get<0>(iter) = (idx < 0) ? idx + range : idx;
}
}
return container(index);
}
}
#endif /* MINIASCAPE_PERIODIC_BOUNDARY */
<commit_msg>change type of range in Periodic<commit_after>#ifndef MINIASCAPE_PERIODIC_BOUNDARY
#define MINIASCAPE_PERIODIC_BOUNDARY
#include <array>
#include "util/zip_iterator.hpp"
#include "Cell.hpp"
namespace miniascape
{
template<typename T_neighbor>
class PeriodicBoundary
{
public:
using neighbor_type = T_neighbor;
using cell_index_type = typename neighbor_type::cell_index_type;
constexpr static std::size_t dimension = neighbor_type::dimension;
public:
PeriodicBoundary() = default;
PeriodicBoundary(const cell_index_type& begin, const cell_index_type& end)
:begin_(begin), end_(end)
{}
~PeriodicBoundary() = default;
template<typename T_world>
typename T_world::cell_ptr const&
access(const cell_index_type& id, const T_world& world) const;
template<typename T_world>
typename T_world::cell_ptr &
access(const cell_index_type& id, T_world& container) const;
private:
// [begin, end)
cell_index_type begin_; // = (0, ..., 0), normally
cell_index_type end_;
};
template<typename T_neighbor>
template<typename T_world>
typename T_world::cell_ptr const&
PeriodicBoundary<T_neighbor>::access(
const cell_index_type& id, const T_world& container) const
{
cell_index_type index = id;
for(auto iter = make_zip(index.begin(), begin_.cbegin(), end_.cbegin());
iter != make_zip(index.end(), begin_.cend(), end_.cend());
++iter)
{
const int range = *get<2>(iter) - *get<1>(iter);
if((*get<0>(iter) < *get<1>(iter)) /* index < begin */||
(*get<0>(iter) >= *get<2>(iter))/* end <= index */)
{
const int idx = *get<0>(iter) % range;
*get<0>(iter) = (idx < 0) ? idx + range : idx;
}
}
return container(index);
}
template<typename T_neighbor>
template<typename T_world>
typename T_world::cell_ptr &
PeriodicBoundary<T_neighbor>::access(
const cell_index_type& id, T_world& container) const
{
cell_index_type index = id;
for(auto iter = make_zip(index.begin(), begin_.cbegin(), end_.cbegin());
iter != make_zip(index.end(), begin_.cend(), end_.cend());
++iter)
{
const int range = *get<2>(iter) - *get<1>(iter);
if((*get<0>(iter) < *get<1>(iter)) /* index < begin */||
(*get<0>(iter) >= *get<2>(iter))/* end <= index */)
{
const int idx = *get<0>(iter) % range;
*get<0>(iter) = (idx < 0) ? idx + range : idx;
}
}
return container(index);
}
}
#endif /* MINIASCAPE_PERIODIC_BOUNDARY */
<|endoftext|> |
<commit_before>/**
* @file llchannelmanager.cpp
* @brief This class rules screen notification channels.
*
* $LicenseInfo:firstyear=2000&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h" // must be first include
#include "llchannelmanager.h"
#include "llappviewer.h"
#include "lldonotdisturbnotificationstorage.h"
#include "llpersistentnotificationstorage.h"
#include "llviewercontrol.h"
#include "llviewerwindow.h"
#include "llrootview.h"
#include "llsyswellwindow.h"
#include "llfloaterreg.h"
#include <algorithm>
using namespace LLNotificationsUI;
//--------------------------------------------------------------------------
LLChannelManager::LLChannelManager()
{
LLAppViewer::instance()->setOnLoginCompletedCallback(boost::bind(&LLChannelManager::onLoginCompleted, this));
mChannelList.clear();
mStartUpChannel = NULL;
if(!gViewerWindow)
{
llerrs << "LLChannelManager::LLChannelManager() - viwer window is not initialized yet" << llendl;
}
}
//--------------------------------------------------------------------------
LLChannelManager::~LLChannelManager()
{
// <FS:ND> HACK/Test FIRE-11884 / Crash on exit. After making sure no ScreenChannel gets destroyed in a LLView dtor, this can still
// crash when the static singleton of LLChannelManager is destroyed.
// Leak those few channels on shutdown here to test if that fixes the rest of the crash. As this is shutdown code, the OS will clean up after us.
// Not nice or recommended, but not harmful either here.
// for(std::vector<ChannelElem>::iterator it = mChannelList.begin(); it != mChannelList.end(); ++it)
// {
// LLScreenChannelBase* channel = it->channel.get();
// if (!channel) continue;
//
// delete channel;
// }
// </FS:ND>
mChannelList.clear();
}
//--------------------------------------------------------------------------
LLScreenChannel* LLChannelManager::createNotificationChannel()
{
// creating params for a channel
LLScreenChannelBase::Params p;
p.id = LLUUID(gSavedSettings.getString("NotificationChannelUUID"));
p.channel_align = CA_RIGHT;
// <FS:Ansariel> Group notices, IMs and chiclets position
//p.toast_align = NA_TOP;
if (gSavedSettings.getBOOL("InternalShowGroupNoticesTopRight"))
{
p.toast_align = NA_TOP;
}
else
{
p.toast_align = NA_BOTTOM;
}
// </FS:Ansariel> Group notices, IMs and chiclets position
// Getting a Channel for our notifications
return dynamic_cast<LLScreenChannel*> (LLChannelManager::getInstance()->getChannel(p));
}
//--------------------------------------------------------------------------
void LLChannelManager::onLoginCompleted()
{
S32 away_notifications = 0;
// calc a number of all offline notifications
for(std::vector<ChannelElem>::iterator it = mChannelList.begin(); it != mChannelList.end(); ++it)
{
LLScreenChannelBase* channel = it->channel.get();
if (!channel) continue;
// don't calc notifications for Nearby Chat
if(channel->getChannelID() == LLUUID(gSavedSettings.getString("NearByChatChannelUUID")))
{
continue;
}
// don't calc notifications for channels that always show their notifications
if(!channel->getDisplayToastsAlways())
{
away_notifications +=channel->getNumberOfHiddenToasts();
}
}
away_notifications += gIMMgr->getNumberOfUnreadIM();
if(!away_notifications)
{
onStartUpToastClose();
}
else
{
// TODO: Seems this code leads to MAINT-3536 new crash in XML_ParserFree.
// Need to investigate this and fix possible problems with notifications in startup time
// Viewer can normally receive and show of postponed notifications about purchasing in marketplace on startup time.
// Other types of postponed notifications did not tested.
//// create a channel for the StartUp Toast
//LLScreenChannelBase::Params p;
//p.id = LLUUID(gSavedSettings.getString("StartUpChannelUUID"));
//p.channel_align = CA_RIGHT;
//mStartUpChannel = createChannel(p);
//if(!mStartUpChannel)
//{
// onStartUpToastClose();
//}
//else
//{
// gViewerWindow->getRootView()->addChild(mStartUpChannel);
// // init channel's position and size
// S32 channel_right_bound = gViewerWindow->getWorldViewRectScaled().mRight - gSavedSettings.getS32("NotificationChannelRightMargin");
// S32 channel_width = gSavedSettings.getS32("NotifyBoxWidth");
// mStartUpChannel->init(channel_right_bound - channel_width, channel_right_bound);
// mStartUpChannel->setMouseDownCallback(boost::bind(&LLNotificationWellWindow::onStartUpToastClick, LLNotificationWellWindow::getInstance(), _2, _3, _4));
// mStartUpChannel->setCommitCallback(boost::bind(&LLChannelManager::onStartUpToastClose, this));
// mStartUpChannel->createStartUpToast(away_notifications, gSavedSettings.getS32("StartUpToastLifeTime"));
//}
}
LLPersistentNotificationStorage::getInstance()->loadNotifications();
LLDoNotDisturbNotificationStorage::getInstance()->loadNotifications();
}
//--------------------------------------------------------------------------
void LLChannelManager::onStartUpToastClose()
{
if(mStartUpChannel)
{
mStartUpChannel->setVisible(FALSE);
mStartUpChannel->closeStartUpToast();
removeChannelByID(LLUUID(gSavedSettings.getString("StartUpChannelUUID")));
mStartUpChannel = NULL;
}
// set StartUp Toast Flag to allow all other channels to show incoming toasts
LLScreenChannel::setStartUpToastShown();
}
//--------------------------------------------------------------------------
LLScreenChannelBase* LLChannelManager::addChannel(LLScreenChannelBase* channel)
{
if(!channel)
return 0;
ChannelElem new_elem;
new_elem.id = channel->getChannelID();
new_elem.channel = channel->getHandle();
mChannelList.push_back(new_elem);
return channel;
}
LLScreenChannel* LLChannelManager::createChannel(LLScreenChannelBase::Params& p)
{
LLScreenChannel* new_channel = new LLScreenChannel(p);
addChannel(new_channel);
return new_channel;
}
LLScreenChannelBase* LLChannelManager::getChannel(LLScreenChannelBase::Params& p)
{
LLScreenChannelBase* new_channel = findChannelByID(p.id);
if(new_channel)
return new_channel;
return createChannel(p);
}
//--------------------------------------------------------------------------
LLScreenChannelBase* LLChannelManager::findChannelByID(const LLUUID& id)
{
std::vector<ChannelElem>::iterator it = find(mChannelList.begin(), mChannelList.end(), id);
if(it != mChannelList.end())
{
return (*it).channel.get();
}
return NULL;
}
//--------------------------------------------------------------------------
void LLChannelManager::removeChannelByID(const LLUUID& id)
{
std::vector<ChannelElem>::iterator it = find(mChannelList.begin(), mChannelList.end(), id);
if(it != mChannelList.end())
{
mChannelList.erase(it);
}
}
//--------------------------------------------------------------------------
void LLChannelManager::muteAllChannels(bool mute)
{
for (std::vector<ChannelElem>::iterator it = mChannelList.begin();
it != mChannelList.end(); it++)
{
if (it->channel.get())
{
it->channel.get()->setShowToasts(!mute);
}
}
}
void LLChannelManager::killToastsFromChannel(const LLUUID& channel_id, const LLScreenChannel::Matcher& matcher)
{
LLScreenChannel
* screen_channel =
dynamic_cast<LLScreenChannel*> (findChannelByID(channel_id));
if (screen_channel != NULL)
{
screen_channel->killMatchedToasts(matcher);
}
}
// static
LLNotificationsUI::LLScreenChannel* LLChannelManager::getNotificationScreenChannel()
{
LLNotificationsUI::LLScreenChannel* channel = static_cast<LLNotificationsUI::LLScreenChannel*>
(LLNotificationsUI::LLChannelManager::getInstance()->
findChannelByID(LLUUID(gSavedSettings.getString("NotificationChannelUUID"))));
if (channel == NULL)
{
llwarns << "Can't find screen channel by NotificationChannelUUID" << llendl;
llassert(!"Can't find screen channel by NotificationChannelUUID");
}
return channel;
}
<commit_msg>Activate missed notifications at startup again; crash was caused by c-style cast in LLFloaterView and is fixed already<commit_after>/**
* @file llchannelmanager.cpp
* @brief This class rules screen notification channels.
*
* $LicenseInfo:firstyear=2000&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h" // must be first include
#include "llchannelmanager.h"
#include "llappviewer.h"
#include "lldonotdisturbnotificationstorage.h"
#include "llpersistentnotificationstorage.h"
#include "llviewercontrol.h"
#include "llviewerwindow.h"
#include "llrootview.h"
#include "llsyswellwindow.h"
#include "llfloaterreg.h"
#include <algorithm>
using namespace LLNotificationsUI;
//--------------------------------------------------------------------------
LLChannelManager::LLChannelManager()
{
LLAppViewer::instance()->setOnLoginCompletedCallback(boost::bind(&LLChannelManager::onLoginCompleted, this));
mChannelList.clear();
mStartUpChannel = NULL;
if(!gViewerWindow)
{
llerrs << "LLChannelManager::LLChannelManager() - viwer window is not initialized yet" << llendl;
}
}
//--------------------------------------------------------------------------
LLChannelManager::~LLChannelManager()
{
// <FS:ND> HACK/Test FIRE-11884 / Crash on exit. After making sure no ScreenChannel gets destroyed in a LLView dtor, this can still
// crash when the static singleton of LLChannelManager is destroyed.
// Leak those few channels on shutdown here to test if that fixes the rest of the crash. As this is shutdown code, the OS will clean up after us.
// Not nice or recommended, but not harmful either here.
// for(std::vector<ChannelElem>::iterator it = mChannelList.begin(); it != mChannelList.end(); ++it)
// {
// LLScreenChannelBase* channel = it->channel.get();
// if (!channel) continue;
//
// delete channel;
// }
// </FS:ND>
mChannelList.clear();
}
//--------------------------------------------------------------------------
LLScreenChannel* LLChannelManager::createNotificationChannel()
{
// creating params for a channel
LLScreenChannelBase::Params p;
p.id = LLUUID(gSavedSettings.getString("NotificationChannelUUID"));
p.channel_align = CA_RIGHT;
// <FS:Ansariel> Group notices, IMs and chiclets position
//p.toast_align = NA_TOP;
if (gSavedSettings.getBOOL("InternalShowGroupNoticesTopRight"))
{
p.toast_align = NA_TOP;
}
else
{
p.toast_align = NA_BOTTOM;
}
// </FS:Ansariel> Group notices, IMs and chiclets position
// Getting a Channel for our notifications
return dynamic_cast<LLScreenChannel*> (LLChannelManager::getInstance()->getChannel(p));
}
//--------------------------------------------------------------------------
void LLChannelManager::onLoginCompleted()
{
S32 away_notifications = 0;
// calc a number of all offline notifications
for(std::vector<ChannelElem>::iterator it = mChannelList.begin(); it != mChannelList.end(); ++it)
{
LLScreenChannelBase* channel = it->channel.get();
if (!channel) continue;
// don't calc notifications for Nearby Chat
if(channel->getChannelID() == LLUUID(gSavedSettings.getString("NearByChatChannelUUID")))
{
continue;
}
// don't calc notifications for channels that always show their notifications
if(!channel->getDisplayToastsAlways())
{
away_notifications +=channel->getNumberOfHiddenToasts();
}
}
away_notifications += gIMMgr->getNumberOfUnreadIM();
if(!away_notifications)
{
onStartUpToastClose();
}
else
{
// TODO: Seems this code leads to MAINT-3536 new crash in XML_ParserFree.
// Need to investigate this and fix possible problems with notifications in startup time
// Viewer can normally receive and show of postponed notifications about purchasing in marketplace on startup time.
// Other types of postponed notifications did not tested.
// <FS:Ansariel> Uncomment this code again; crash was caused by c-style cast in LLFloaterView
// create a channel for the StartUp Toast
LLScreenChannelBase::Params p;
p.id = LLUUID(gSavedSettings.getString("StartUpChannelUUID"));
p.channel_align = CA_RIGHT;
mStartUpChannel = createChannel(p);
if(!mStartUpChannel)
{
onStartUpToastClose();
}
else
{
gViewerWindow->getRootView()->addChild(mStartUpChannel);
// init channel's position and size
S32 channel_right_bound = gViewerWindow->getWorldViewRectScaled().mRight - gSavedSettings.getS32("NotificationChannelRightMargin");
S32 channel_width = gSavedSettings.getS32("NotifyBoxWidth");
mStartUpChannel->init(channel_right_bound - channel_width, channel_right_bound);
mStartUpChannel->setMouseDownCallback(boost::bind(&LLNotificationWellWindow::onStartUpToastClick, LLNotificationWellWindow::getInstance(), _2, _3, _4));
mStartUpChannel->setCommitCallback(boost::bind(&LLChannelManager::onStartUpToastClose, this));
mStartUpChannel->createStartUpToast(away_notifications, gSavedSettings.getS32("StartUpToastLifeTime"));
}
}
// </FS:Ansariel>
LLPersistentNotificationStorage::getInstance()->loadNotifications();
LLDoNotDisturbNotificationStorage::getInstance()->loadNotifications();
}
//--------------------------------------------------------------------------
void LLChannelManager::onStartUpToastClose()
{
if(mStartUpChannel)
{
mStartUpChannel->setVisible(FALSE);
mStartUpChannel->closeStartUpToast();
removeChannelByID(LLUUID(gSavedSettings.getString("StartUpChannelUUID")));
mStartUpChannel = NULL;
}
// set StartUp Toast Flag to allow all other channels to show incoming toasts
LLScreenChannel::setStartUpToastShown();
}
//--------------------------------------------------------------------------
LLScreenChannelBase* LLChannelManager::addChannel(LLScreenChannelBase* channel)
{
if(!channel)
return 0;
ChannelElem new_elem;
new_elem.id = channel->getChannelID();
new_elem.channel = channel->getHandle();
mChannelList.push_back(new_elem);
return channel;
}
LLScreenChannel* LLChannelManager::createChannel(LLScreenChannelBase::Params& p)
{
LLScreenChannel* new_channel = new LLScreenChannel(p);
addChannel(new_channel);
return new_channel;
}
LLScreenChannelBase* LLChannelManager::getChannel(LLScreenChannelBase::Params& p)
{
LLScreenChannelBase* new_channel = findChannelByID(p.id);
if(new_channel)
return new_channel;
return createChannel(p);
}
//--------------------------------------------------------------------------
LLScreenChannelBase* LLChannelManager::findChannelByID(const LLUUID& id)
{
std::vector<ChannelElem>::iterator it = find(mChannelList.begin(), mChannelList.end(), id);
if(it != mChannelList.end())
{
return (*it).channel.get();
}
return NULL;
}
//--------------------------------------------------------------------------
void LLChannelManager::removeChannelByID(const LLUUID& id)
{
std::vector<ChannelElem>::iterator it = find(mChannelList.begin(), mChannelList.end(), id);
if(it != mChannelList.end())
{
mChannelList.erase(it);
}
}
//--------------------------------------------------------------------------
void LLChannelManager::muteAllChannels(bool mute)
{
for (std::vector<ChannelElem>::iterator it = mChannelList.begin();
it != mChannelList.end(); it++)
{
if (it->channel.get())
{
it->channel.get()->setShowToasts(!mute);
}
}
}
void LLChannelManager::killToastsFromChannel(const LLUUID& channel_id, const LLScreenChannel::Matcher& matcher)
{
LLScreenChannel
* screen_channel =
dynamic_cast<LLScreenChannel*> (findChannelByID(channel_id));
if (screen_channel != NULL)
{
screen_channel->killMatchedToasts(matcher);
}
}
// static
LLNotificationsUI::LLScreenChannel* LLChannelManager::getNotificationScreenChannel()
{
LLNotificationsUI::LLScreenChannel* channel = static_cast<LLNotificationsUI::LLScreenChannel*>
(LLNotificationsUI::LLChannelManager::getInstance()->
findChannelByID(LLUUID(gSavedSettings.getString("NotificationChannelUUID"))));
if (channel == NULL)
{
llwarns << "Can't find screen channel by NotificationChannelUUID" << llendl;
llassert(!"Can't find screen channel by NotificationChannelUUID");
}
return channel;
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "cpplocalsymbols.h"
#include "cppsemanticinfo.h"
#include <cplusplus/CppDocument.h>
#include <ASTVisitor.h>
#include <AST.h>
#include <Scope.h>
#include <Symbols.h>
#include <CoreTypes.h>
#include <Names.h>
#include <Literals.h>
using namespace CPlusPlus;
using namespace CppEditor::Internal;
namespace {
class FindLocalSymbols: protected ASTVisitor
{
Scope *_functionScope;
Document::Ptr _doc;
public:
FindLocalSymbols(Document::Ptr doc)
: ASTVisitor(doc->translationUnit()), _doc(doc), hasD(false), hasQ(false)
{ }
// local and external uses.
SemanticInfo::LocalUseMap localUses;
bool hasD;
bool hasQ;
void operator()(DeclarationAST *ast)
{
localUses.clear();
if (!ast)
return;
if (FunctionDefinitionAST *def = ast->asFunctionDefinition()) {
if (def->symbol) {
_functionScope = def->symbol;
accept(ast);
}
} else if (ObjCMethodDeclarationAST *decl = ast->asObjCMethodDeclaration()) {
if (decl->method_prototype->symbol) {
_functionScope = decl->method_prototype->symbol;
accept(ast);
}
}
}
protected:
using ASTVisitor::visit;
using ASTVisitor::endVisit;
void enterScope(Scope *scope)
{
_scopeStack.append(scope);
for (unsigned i = 0; i < scope->memberCount(); ++i) {
if (Symbol *member = scope->memberAt(i)) {
if (member->isTypedef())
continue;
else if (! member->isGenerated() && (member->isDeclaration() || member->isArgument())) {
if (member->name() && member->name()->isNameId()) {
const Identifier *id = member->identifier();
unsigned line, column;
getTokenStartPosition(member->sourceLocation(), &line, &column);
localUses[member].append(SemanticInfo::Use(line, column, id->size(), SemanticInfo::LocalUse));
}
}
}
}
}
bool checkLocalUse(NameAST *nameAst, unsigned firstToken)
{
if (SimpleNameAST *simpleName = nameAst->asSimpleName()) {
const Identifier *id = identifier(simpleName->identifier_token);
for (int i = _scopeStack.size() - 1; i != -1; --i) {
if (Symbol *member = _scopeStack.at(i)->find(id)) {
if (member->isTypedef() || !member->isDeclaration())
continue;
else if (!member->isGenerated() && (member->sourceLocation() < firstToken || member->enclosingScope()->isFunction())) {
unsigned line, column;
getTokenStartPosition(simpleName->identifier_token, &line, &column);
localUses[member].append(SemanticInfo::Use(line, column, id->size(), SemanticInfo::LocalUse));
return false;
}
}
}
}
return true;
}
virtual bool visit(IdExpressionAST *ast)
{
return checkLocalUse(ast->name, ast->firstToken());
}
virtual bool visit(SizeofExpressionAST *ast)
{
if (ast->expression && ast->expression->asTypeId()) {
TypeIdAST *typeId = ast->expression->asTypeId();
if (!typeId->declarator && typeId->type_specifier_list && !typeId->type_specifier_list->next) {
if (NamedTypeSpecifierAST *namedTypeSpec = typeId->type_specifier_list->value->asNamedTypeSpecifier()) {
if (checkLocalUse(namedTypeSpec->name, namedTypeSpec->firstToken()))
return false;
}
}
}
return true;
}
virtual bool visit(QtMemberDeclarationAST *ast)
{
if (tokenKind(ast->q_token) == T_Q_D)
hasD = true;
else
hasQ = true;
return true;
}
virtual bool visit(FunctionDefinitionAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(FunctionDefinitionAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(CompoundStatementAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(CompoundStatementAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(IfStatementAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(IfStatementAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(WhileStatementAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(WhileStatementAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(ForStatementAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(ForStatementAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(ForeachStatementAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(ForeachStatementAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(SwitchStatementAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(SwitchStatementAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(CatchClauseAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(CatchClauseAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(ExpressionOrDeclarationStatementAST *ast)
{
accept(ast->declaration);
return false;
}
private:
QList<Scope *> _scopeStack;
};
} // end of anonymous namespace
LocalSymbols::LocalSymbols(CPlusPlus::Document::Ptr doc, CPlusPlus::DeclarationAST *ast)
{
FindLocalSymbols findLocalSymbols(doc);
findLocalSymbols(ast);
hasD = findLocalSymbols.hasD;
hasQ = findLocalSymbols.hasQ;
uses = findLocalSymbols.localUses;
}
<commit_msg>C++: fix highlighting again, this time for arguments.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "cpplocalsymbols.h"
#include "cppsemanticinfo.h"
#include <cplusplus/CppDocument.h>
#include <ASTVisitor.h>
#include <AST.h>
#include <Scope.h>
#include <Symbols.h>
#include <CoreTypes.h>
#include <Names.h>
#include <Literals.h>
using namespace CPlusPlus;
using namespace CppEditor::Internal;
namespace {
class FindLocalSymbols: protected ASTVisitor
{
Scope *_functionScope;
Document::Ptr _doc;
public:
FindLocalSymbols(Document::Ptr doc)
: ASTVisitor(doc->translationUnit()), _doc(doc), hasD(false), hasQ(false)
{ }
// local and external uses.
SemanticInfo::LocalUseMap localUses;
bool hasD;
bool hasQ;
void operator()(DeclarationAST *ast)
{
localUses.clear();
if (!ast)
return;
if (FunctionDefinitionAST *def = ast->asFunctionDefinition()) {
if (def->symbol) {
_functionScope = def->symbol;
accept(ast);
}
} else if (ObjCMethodDeclarationAST *decl = ast->asObjCMethodDeclaration()) {
if (decl->method_prototype->symbol) {
_functionScope = decl->method_prototype->symbol;
accept(ast);
}
}
}
protected:
using ASTVisitor::visit;
using ASTVisitor::endVisit;
void enterScope(Scope *scope)
{
_scopeStack.append(scope);
for (unsigned i = 0; i < scope->memberCount(); ++i) {
if (Symbol *member = scope->memberAt(i)) {
if (member->isTypedef())
continue;
else if (! member->isGenerated() && (member->isDeclaration() || member->isArgument())) {
if (member->name() && member->name()->isNameId()) {
const Identifier *id = member->identifier();
unsigned line, column;
getTokenStartPosition(member->sourceLocation(), &line, &column);
localUses[member].append(SemanticInfo::Use(line, column, id->size(), SemanticInfo::LocalUse));
}
}
}
}
}
bool checkLocalUse(NameAST *nameAst, unsigned firstToken)
{
if (SimpleNameAST *simpleName = nameAst->asSimpleName()) {
const Identifier *id = identifier(simpleName->identifier_token);
for (int i = _scopeStack.size() - 1; i != -1; --i) {
if (Symbol *member = _scopeStack.at(i)->find(id)) {
if (member->isTypedef() ||
!(member->isDeclaration() || member->isArgument()))
continue;
else if (!member->isGenerated() && (member->sourceLocation() < firstToken || member->enclosingScope()->isFunction())) {
unsigned line, column;
getTokenStartPosition(simpleName->identifier_token, &line, &column);
localUses[member].append(SemanticInfo::Use(line, column, id->size(), SemanticInfo::LocalUse));
return false;
}
}
}
}
return true;
}
virtual bool visit(IdExpressionAST *ast)
{
return checkLocalUse(ast->name, ast->firstToken());
}
virtual bool visit(SizeofExpressionAST *ast)
{
if (ast->expression && ast->expression->asTypeId()) {
TypeIdAST *typeId = ast->expression->asTypeId();
if (!typeId->declarator && typeId->type_specifier_list && !typeId->type_specifier_list->next) {
if (NamedTypeSpecifierAST *namedTypeSpec = typeId->type_specifier_list->value->asNamedTypeSpecifier()) {
if (checkLocalUse(namedTypeSpec->name, namedTypeSpec->firstToken()))
return false;
}
}
}
return true;
}
virtual bool visit(QtMemberDeclarationAST *ast)
{
if (tokenKind(ast->q_token) == T_Q_D)
hasD = true;
else
hasQ = true;
return true;
}
virtual bool visit(FunctionDefinitionAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(FunctionDefinitionAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(CompoundStatementAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(CompoundStatementAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(IfStatementAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(IfStatementAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(WhileStatementAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(WhileStatementAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(ForStatementAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(ForStatementAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(ForeachStatementAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(ForeachStatementAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(SwitchStatementAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(SwitchStatementAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(CatchClauseAST *ast)
{
if (ast->symbol)
enterScope(ast->symbol);
return true;
}
virtual void endVisit(CatchClauseAST *ast)
{
if (ast->symbol)
_scopeStack.removeLast();
}
virtual bool visit(ExpressionOrDeclarationStatementAST *ast)
{
accept(ast->declaration);
return false;
}
private:
QList<Scope *> _scopeStack;
};
} // end of anonymous namespace
LocalSymbols::LocalSymbols(CPlusPlus::Document::Ptr doc, CPlusPlus::DeclarationAST *ast)
{
FindLocalSymbols findLocalSymbols(doc);
findLocalSymbols(ast);
hasD = findLocalSymbols.hasD;
hasQ = findLocalSymbols.hasQ;
uses = findLocalSymbols.localUses;
}
<|endoftext|> |
<commit_before>#include "lightfield_pattern.h"
namespace possumwood { namespace opencv {
LightfieldPattern::LightfieldPattern() : m_lensPitch(0.0), m_pixelPitch(0.0), m_rotation(0.0) {
}
LightfieldPattern::LightfieldPattern(double lensPitch, double pixelPitch, double rotation,
cv::Vec2d scaleFactor, cv::Vec3d sensorOffset, cv::Vec2i sensorResolution) :
m_lensPitch(lensPitch), m_pixelPitch(pixelPitch), m_rotation(rotation),
m_scaleFactor(scaleFactor), m_sensorOffset(sensorOffset), m_sensorResolution(sensorResolution)
{
}
bool LightfieldPattern::operator == (const LightfieldPattern& f) const {
return m_lensPitch == f.m_lensPitch &&
m_pixelPitch == f.m_pixelPitch &&
m_rotation == f.m_rotation &&
m_scaleFactor == f.m_scaleFactor &&
m_sensorOffset == f.m_sensorOffset &&
m_sensorResolution == f.m_sensorResolution;
}
bool LightfieldPattern::operator != (const LightfieldPattern& f) const {
return m_lensPitch != f.m_lensPitch ||
m_pixelPitch != f.m_pixelPitch ||
m_rotation != f.m_rotation ||
m_scaleFactor != f.m_scaleFactor ||
m_sensorOffset != f.m_sensorOffset ||
m_sensorResolution != f.m_sensorResolution;
}
cv::Vec4d LightfieldPattern::sample(const cv::Vec2i& pixelPos) const {
cv::Vec4d result;
result[0] = (double)pixelPos[0];
result[1] = (double)pixelPos[1];
const double xDiff = m_lensPitch / m_pixelPitch * m_scaleFactor[0];
const double yDiff = m_lensPitch / m_pixelPitch * sqrt(3.0/4.0) * m_scaleFactor[1];
cv::Vec2d vect(
(double)pixelPos[0] / m_scaleFactor[0],
(double)pixelPos[1] / m_scaleFactor[1]
);
const double cs = cos(m_rotation);
const double sn = sin(m_rotation);
vect = cv::Vec2d (
(vect[0] * cs + vect[1] * sn),
(-vect[0] * sn + vect[1] * cs)
);
vect[0] += m_sensorOffset[0] / m_pixelPitch;
vect[1] += m_sensorOffset[1] / m_pixelPitch;
result[3] = vect[1] / yDiff;
if(((int)round(result[3])) % 2 == 0)
result[2] = fmod(vect[0] / xDiff + 100.5, 1.0) - 0.5;
else
result[2] = fmod(vect[0] / xDiff + 100.0, 1.0) - 0.5;
result[3] = fmod(result[3] + 100.5, 1.0) - 0.5;
result[2] *= 2.0;
result[3] *= 2.0;
return result;
}
const cv::Vec2i& LightfieldPattern::sensorResolution() const {
return m_sensorResolution;
}
std::ostream& operator << (std::ostream& out, const LightfieldPattern& f) {
out << "(lightfields pattern)";
return out;
}
} }
<commit_msg>LightfieldPattern no longer produces nans when uninitialised<commit_after>#include "lightfield_pattern.h"
namespace possumwood { namespace opencv {
LightfieldPattern::LightfieldPattern() : m_lensPitch(1.0), m_pixelPitch(1.0), m_rotation(0.0), m_scaleFactor(1.0, 1.0), m_sensorResolution(100, 100) {
}
LightfieldPattern::LightfieldPattern(double lensPitch, double pixelPitch, double rotation,
cv::Vec2d scaleFactor, cv::Vec3d sensorOffset, cv::Vec2i sensorResolution) :
m_lensPitch(lensPitch), m_pixelPitch(pixelPitch), m_rotation(rotation),
m_scaleFactor(scaleFactor), m_sensorOffset(sensorOffset), m_sensorResolution(sensorResolution)
{
}
bool LightfieldPattern::operator == (const LightfieldPattern& f) const {
return m_lensPitch == f.m_lensPitch &&
m_pixelPitch == f.m_pixelPitch &&
m_rotation == f.m_rotation &&
m_scaleFactor == f.m_scaleFactor &&
m_sensorOffset == f.m_sensorOffset &&
m_sensorResolution == f.m_sensorResolution;
}
bool LightfieldPattern::operator != (const LightfieldPattern& f) const {
return m_lensPitch != f.m_lensPitch ||
m_pixelPitch != f.m_pixelPitch ||
m_rotation != f.m_rotation ||
m_scaleFactor != f.m_scaleFactor ||
m_sensorOffset != f.m_sensorOffset ||
m_sensorResolution != f.m_sensorResolution;
}
cv::Vec4d LightfieldPattern::sample(const cv::Vec2i& pixelPos) const {
cv::Vec4d result;
result[0] = (double)pixelPos[0];
result[1] = (double)pixelPos[1];
const double xDiff = m_lensPitch / m_pixelPitch * m_scaleFactor[0];
const double yDiff = m_lensPitch / m_pixelPitch * sqrt(3.0/4.0) * m_scaleFactor[1];
cv::Vec2d vect(
(double)pixelPos[0] / m_scaleFactor[0],
(double)pixelPos[1] / m_scaleFactor[1]
);
const double cs = cos(m_rotation);
const double sn = sin(m_rotation);
vect = cv::Vec2d (
(vect[0] * cs + vect[1] * sn),
(-vect[0] * sn + vect[1] * cs)
);
vect[0] += m_sensorOffset[0] / m_pixelPitch;
vect[1] += m_sensorOffset[1] / m_pixelPitch;
result[3] = vect[1] / yDiff;
if(((int)round(result[3])) % 2 == 0)
result[2] = fmod(vect[0] / xDiff + 100.5, 1.0) - 0.5;
else
result[2] = fmod(vect[0] / xDiff + 100.0, 1.0) - 0.5;
result[3] = fmod(result[3] + 100.5, 1.0) - 0.5;
result[2] *= 2.0;
result[3] *= 2.0;
return result;
}
const cv::Vec2i& LightfieldPattern::sensorResolution() const {
return m_sensorResolution;
}
std::ostream& operator << (std::ostream& out, const LightfieldPattern& f) {
out << "(lightfields pattern)";
return out;
}
} }
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/
#include "qmlconsoleview.h"
#include "qmlconsoleitemdelegate.h"
#include "qmlconsoleitemmodel.h"
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/manhattanstyle.h>
#include <utils/hostosinfo.h>
#include <QMouseEvent>
#include <QPainter>
#include <QApplication>
#include <QClipboard>
#include <QAbstractProxyModel>
#include <QFileInfo>
#include <QScrollBar>
#include <QStyleFactory>
#include <QString>
#include <QUrl>
using namespace QmlJS;
namespace QmlJSTools {
namespace Internal {
class QmlConsoleViewStyle : public ManhattanStyle
{
public:
QmlConsoleViewStyle(const QString &baseStyleName) : ManhattanStyle(baseStyleName) {}
void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter,
const QWidget *widget = 0) const
{
if (element != QStyle::PE_PanelItemViewRow)
ManhattanStyle::drawPrimitive(element, option, painter, widget);
}
int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0,
QStyleHintReturn *returnData = 0) const {
if (hint == SH_ItemView_ShowDecorationSelected)
return 0;
else
return ManhattanStyle::styleHint(hint, option, widget, returnData);
}
};
///////////////////////////////////////////////////////////////////////
//
// QmlConsoleView
//
///////////////////////////////////////////////////////////////////////
QmlConsoleView::QmlConsoleView(QWidget *parent) :
QTreeView(parent)
{
setFrameStyle(QFrame::NoFrame);
setHeaderHidden(true);
setRootIsDecorated(false);
setUniformRowHeights(true);
setEditTriggers(QAbstractItemView::AllEditTriggers);
setStyleSheet(QLatin1String("QTreeView::branch:has-siblings:!adjoins-item {"
"border-image: none;"
"image: none; }"
"QTreeView::branch:has-siblings:adjoins-item {"
"border-image: none;"
"image: none; }"
"QTreeView::branch:!has-children:!has-siblings:adjoins-item {"
"border-image: none;"
"image: none; }"
"QTreeView::branch:has-children:!has-siblings:closed,"
"QTreeView::branch:closed:has-children:has-siblings {"
"border-image: none;"
"image: none; }"
"QTreeView::branch:open:has-children:!has-siblings,"
"QTreeView::branch:open:has-children:has-siblings {"
"border-image: none;"
"image: none; }"));
QString baseName = QApplication::style()->objectName();
if (Utils::HostOsInfo::isAnyUnixHost() && !Utils::HostOsInfo::isMacHost()
&& baseName == QLatin1String("windows")) {
// Sometimes we get the standard windows 95 style as a fallback
if (QStyleFactory::keys().contains(QLatin1String("Fusion"))) {
baseName = QLatin1String("fusion"); // Qt5
} else { // Qt4
// e.g. if we are running on a KDE4 desktop
QByteArray desktopEnvironment = qgetenv("DESKTOP_SESSION");
if (desktopEnvironment == "kde")
baseName = QLatin1String("plastique");
else
baseName = QLatin1String("cleanlooks");
}
}
QmlConsoleViewStyle *style = new QmlConsoleViewStyle(baseName);
setStyle(style);
style->setParent(this);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
horizontalScrollBar()->setSingleStep(20);
verticalScrollBar()->setSingleStep(20);
connect(this, SIGNAL(activated(QModelIndex)), SLOT(onRowActivated(QModelIndex)));
}
void QmlConsoleView::onScrollToBottom()
{
// Keep scrolling to bottom if scroll bar is at maximum()
if (verticalScrollBar()->value() == verticalScrollBar()->maximum())
scrollToBottom();
}
void QmlConsoleView::mousePressEvent(QMouseEvent *event)
{
QPoint pos = event->pos();
QModelIndex index = indexAt(pos);
if (index.isValid()) {
ConsoleItem::ItemType type = (ConsoleItem::ItemType)index.data(
QmlConsoleItemModel::TypeRole).toInt();
bool handled = false;
if (type == ConsoleItem::UndefinedType) {
bool showTypeIcon = index.parent() == QModelIndex();
ConsoleItemPositions positions(visualRect(index), viewOptions().font, showTypeIcon,
true);
if (positions.expandCollapseIcon().contains(pos)) {
if (isExpanded(index))
setExpanded(index, false);
else
setExpanded(index, true);
handled = true;
}
}
if (!handled)
QTreeView::mousePressEvent(event);
} else {
selectionModel()->setCurrentIndex(model()->index(model()->rowCount() - 1, 0),
QItemSelectionModel::ClearAndSelect);
}
}
void QmlConsoleView::keyPressEvent(QKeyEvent *e)
{
if (!e->modifiers() && e->key() == Qt::Key_Return) {
emit activated(currentIndex());
e->accept();
return;
}
QTreeView::keyPressEvent(e);
}
void QmlConsoleView::resizeEvent(QResizeEvent *e)
{
static_cast<QmlConsoleItemDelegate *>(itemDelegate())->emitSizeHintChanged(
selectionModel()->currentIndex());
QTreeView::resizeEvent(e);
}
void QmlConsoleView::drawBranches(QPainter *painter, const QRect &rect,
const QModelIndex &index) const
{
static_cast<QmlConsoleItemDelegate *>(itemDelegate())->drawBackground(painter, rect, index,
false);
QTreeView::drawBranches(painter, rect, index);
}
void QmlConsoleView::contextMenuEvent(QContextMenuEvent *event)
{
QModelIndex itemIndex = indexAt(event->pos());
QMenu menu;
QAction *copy = new QAction(tr("&Copy"), this);
copy->setEnabled(itemIndex.isValid());
menu.addAction(copy);
QAction *show = new QAction(tr("&Show in Editor"), this);
show->setEnabled(canShowItemInTextEditor(itemIndex));
menu.addAction(show);
menu.addSeparator();
QAction *clear = new QAction(tr("C&lear"), this);
menu.addAction(clear);
QAction *a = menu.exec(event->globalPos());
if (a == 0)
return;
if (a == copy) {
copyToClipboard(itemIndex);
} else if (a == show) {
onRowActivated(itemIndex);
} else if (a == clear) {
QAbstractProxyModel *proxyModel = qobject_cast<QAbstractProxyModel *>(model());
QmlConsoleItemModel *handler = qobject_cast<QmlConsoleItemModel *>(
proxyModel->sourceModel());
handler->clear();
}
}
void QmlConsoleView::onRowActivated(const QModelIndex &index)
{
if (!index.isValid())
return;
// See if we have file and line Info
QString filePath = model()->data(index, QmlConsoleItemModel::FileRole).toString();
const QUrl fileUrl = QUrl(filePath);
if (fileUrl.isLocalFile())
filePath = fileUrl.toLocalFile();
if (!filePath.isEmpty()) {
QFileInfo fi(filePath);
if (fi.exists() && fi.isFile() && fi.isReadable()) {
int line = model()->data(index, QmlConsoleItemModel::LineRole).toInt();
Core::EditorManager::openEditorAt(fi.canonicalFilePath(), line);
}
}
}
void QmlConsoleView::copyToClipboard(const QModelIndex &index)
{
if (!index.isValid())
return;
QString contents = model()->data(index, QmlConsoleItemModel::ExpressionRole).toString();
// See if we have file and line Info
QString filePath = model()->data(index, QmlConsoleItemModel::FileRole).toString();
const QUrl fileUrl = QUrl(filePath);
if (fileUrl.isLocalFile())
filePath = fileUrl.toLocalFile();
if (!filePath.isEmpty()) {
contents = QString(QLatin1String("%1 %2: %3")).arg(contents).arg(filePath).arg(
model()->data(index, QmlConsoleItemModel::LineRole).toString());
}
QClipboard *cb = QApplication::clipboard();
cb->setText(contents);
}
bool QmlConsoleView::canShowItemInTextEditor(const QModelIndex &index)
{
if (!index.isValid())
return false;
// See if we have file and line Info
QString filePath = model()->data(index, QmlConsoleItemModel::FileRole).toString();
const QUrl fileUrl = QUrl(filePath);
if (fileUrl.isLocalFile())
filePath = fileUrl.toLocalFile();
if (!filePath.isEmpty()) {
QFileInfo fi(filePath);
if (fi.exists() && fi.isFile() && fi.isReadable())
return true;
}
return false;
}
} // Internal
} // QmlJSTools
<commit_msg>QmlJSConsole: Fix scrolling behavior<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/
#include "qmlconsoleview.h"
#include "qmlconsoleitemdelegate.h"
#include "qmlconsoleitemmodel.h"
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/manhattanstyle.h>
#include <utils/hostosinfo.h>
#include <QMouseEvent>
#include <QPainter>
#include <QApplication>
#include <QClipboard>
#include <QAbstractProxyModel>
#include <QFileInfo>
#include <QScrollBar>
#include <QStyleFactory>
#include <QString>
#include <QUrl>
using namespace QmlJS;
namespace QmlJSTools {
namespace Internal {
class QmlConsoleViewStyle : public ManhattanStyle
{
public:
QmlConsoleViewStyle(const QString &baseStyleName) : ManhattanStyle(baseStyleName) {}
void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter,
const QWidget *widget = 0) const
{
if (element != QStyle::PE_PanelItemViewRow)
ManhattanStyle::drawPrimitive(element, option, painter, widget);
}
int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0,
QStyleHintReturn *returnData = 0) const {
if (hint == SH_ItemView_ShowDecorationSelected)
return 0;
else
return ManhattanStyle::styleHint(hint, option, widget, returnData);
}
};
///////////////////////////////////////////////////////////////////////
//
// QmlConsoleView
//
///////////////////////////////////////////////////////////////////////
QmlConsoleView::QmlConsoleView(QWidget *parent) :
QTreeView(parent)
{
setFrameStyle(QFrame::NoFrame);
setHeaderHidden(true);
setRootIsDecorated(false);
setUniformRowHeights(true);
setEditTriggers(QAbstractItemView::AllEditTriggers);
setStyleSheet(QLatin1String("QTreeView::branch:has-siblings:!adjoins-item {"
"border-image: none;"
"image: none; }"
"QTreeView::branch:has-siblings:adjoins-item {"
"border-image: none;"
"image: none; }"
"QTreeView::branch:!has-children:!has-siblings:adjoins-item {"
"border-image: none;"
"image: none; }"
"QTreeView::branch:has-children:!has-siblings:closed,"
"QTreeView::branch:closed:has-children:has-siblings {"
"border-image: none;"
"image: none; }"
"QTreeView::branch:open:has-children:!has-siblings,"
"QTreeView::branch:open:has-children:has-siblings {"
"border-image: none;"
"image: none; }"));
QString baseName = QApplication::style()->objectName();
if (Utils::HostOsInfo::isAnyUnixHost() && !Utils::HostOsInfo::isMacHost()
&& baseName == QLatin1String("windows")) {
// Sometimes we get the standard windows 95 style as a fallback
if (QStyleFactory::keys().contains(QLatin1String("Fusion"))) {
baseName = QLatin1String("fusion"); // Qt5
} else { // Qt4
// e.g. if we are running on a KDE4 desktop
QByteArray desktopEnvironment = qgetenv("DESKTOP_SESSION");
if (desktopEnvironment == "kde")
baseName = QLatin1String("plastique");
else
baseName = QLatin1String("cleanlooks");
}
}
QmlConsoleViewStyle *style = new QmlConsoleViewStyle(baseName);
setStyle(style);
style->setParent(this);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
horizontalScrollBar()->setSingleStep(20);
verticalScrollBar()->setSingleStep(20);
connect(this, SIGNAL(activated(QModelIndex)), SLOT(onRowActivated(QModelIndex)));
}
void QmlConsoleView::onScrollToBottom()
{
// Keep scrolling to bottom if scroll bar is not at maximum()
if (verticalScrollBar()->value() != verticalScrollBar()->maximum())
scrollToBottom();
}
void QmlConsoleView::mousePressEvent(QMouseEvent *event)
{
QPoint pos = event->pos();
QModelIndex index = indexAt(pos);
if (index.isValid()) {
ConsoleItem::ItemType type = (ConsoleItem::ItemType)index.data(
QmlConsoleItemModel::TypeRole).toInt();
bool handled = false;
if (type == ConsoleItem::UndefinedType) {
bool showTypeIcon = index.parent() == QModelIndex();
ConsoleItemPositions positions(visualRect(index), viewOptions().font, showTypeIcon,
true);
if (positions.expandCollapseIcon().contains(pos)) {
if (isExpanded(index))
setExpanded(index, false);
else
setExpanded(index, true);
handled = true;
}
}
if (!handled)
QTreeView::mousePressEvent(event);
} else {
selectionModel()->setCurrentIndex(model()->index(model()->rowCount() - 1, 0),
QItemSelectionModel::ClearAndSelect);
}
}
void QmlConsoleView::keyPressEvent(QKeyEvent *e)
{
if (!e->modifiers() && e->key() == Qt::Key_Return) {
emit activated(currentIndex());
e->accept();
return;
}
QTreeView::keyPressEvent(e);
}
void QmlConsoleView::resizeEvent(QResizeEvent *e)
{
static_cast<QmlConsoleItemDelegate *>(itemDelegate())->emitSizeHintChanged(
selectionModel()->currentIndex());
QTreeView::resizeEvent(e);
}
void QmlConsoleView::drawBranches(QPainter *painter, const QRect &rect,
const QModelIndex &index) const
{
static_cast<QmlConsoleItemDelegate *>(itemDelegate())->drawBackground(painter, rect, index,
false);
QTreeView::drawBranches(painter, rect, index);
}
void QmlConsoleView::contextMenuEvent(QContextMenuEvent *event)
{
QModelIndex itemIndex = indexAt(event->pos());
QMenu menu;
QAction *copy = new QAction(tr("&Copy"), this);
copy->setEnabled(itemIndex.isValid());
menu.addAction(copy);
QAction *show = new QAction(tr("&Show in Editor"), this);
show->setEnabled(canShowItemInTextEditor(itemIndex));
menu.addAction(show);
menu.addSeparator();
QAction *clear = new QAction(tr("C&lear"), this);
menu.addAction(clear);
QAction *a = menu.exec(event->globalPos());
if (a == 0)
return;
if (a == copy) {
copyToClipboard(itemIndex);
} else if (a == show) {
onRowActivated(itemIndex);
} else if (a == clear) {
QAbstractProxyModel *proxyModel = qobject_cast<QAbstractProxyModel *>(model());
QmlConsoleItemModel *handler = qobject_cast<QmlConsoleItemModel *>(
proxyModel->sourceModel());
handler->clear();
}
}
void QmlConsoleView::onRowActivated(const QModelIndex &index)
{
if (!index.isValid())
return;
// See if we have file and line Info
QString filePath = model()->data(index, QmlConsoleItemModel::FileRole).toString();
const QUrl fileUrl = QUrl(filePath);
if (fileUrl.isLocalFile())
filePath = fileUrl.toLocalFile();
if (!filePath.isEmpty()) {
QFileInfo fi(filePath);
if (fi.exists() && fi.isFile() && fi.isReadable()) {
int line = model()->data(index, QmlConsoleItemModel::LineRole).toInt();
Core::EditorManager::openEditorAt(fi.canonicalFilePath(), line);
}
}
}
void QmlConsoleView::copyToClipboard(const QModelIndex &index)
{
if (!index.isValid())
return;
QString contents = model()->data(index, QmlConsoleItemModel::ExpressionRole).toString();
// See if we have file and line Info
QString filePath = model()->data(index, QmlConsoleItemModel::FileRole).toString();
const QUrl fileUrl = QUrl(filePath);
if (fileUrl.isLocalFile())
filePath = fileUrl.toLocalFile();
if (!filePath.isEmpty()) {
contents = QString(QLatin1String("%1 %2: %3")).arg(contents).arg(filePath).arg(
model()->data(index, QmlConsoleItemModel::LineRole).toString());
}
QClipboard *cb = QApplication::clipboard();
cb->setText(contents);
}
bool QmlConsoleView::canShowItemInTextEditor(const QModelIndex &index)
{
if (!index.isValid())
return false;
// See if we have file and line Info
QString filePath = model()->data(index, QmlConsoleItemModel::FileRole).toString();
const QUrl fileUrl = QUrl(filePath);
if (fileUrl.isLocalFile())
filePath = fileUrl.toLocalFile();
if (!filePath.isEmpty()) {
QFileInfo fi(filePath);
if (fi.exists() && fi.isFile() && fi.isReadable())
return true;
}
return false;
}
} // Internal
} // QmlJSTools
<|endoftext|> |
<commit_before>
#include "../../Flare.h"
#include "FlareDashboard.h"
#include "../../Game/FlareGame.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlareMenuPawn.h"
#include "../../Player/FlarePlayerController.h"
#include "../Components/FlareObjectiveInfo.h"
#define LOCTEXT_NAMESPACE "FlareDashboard"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareDashboard::Construct(const FArguments& InArgs)
{
// Data
MenuManager = InArgs._MenuManager;
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
AFlarePlayerController* PC = MenuManager->GetPC();
// Build structure
ChildSlot
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SHorizontalBox)
// Icon
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SImage).Image(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Dashboard))
]
// Title
+ SHorizontalBox::Slot()
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.TextStyle(&Theme.TitleFont)
.Text(LOCTEXT("Dashboard", "DASHBOARD"))
]
// Close
+ SHorizontalBox::Slot()
.HAlign(HAlign_Right)
.VAlign(VAlign_Bottom)
.Padding(Theme.TitleButtonPadding)
.AutoWidth()
[
SNew(SFlareRoundButton)
.Text(LOCTEXT("Close", "Close"))
.HelpText(LOCTEXT("CloseInfo", "Close the menu and go back to flying the ship"))
.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Exit, true))
.OnClicked(this, &SFlareDashboard::OnExit)
]
]
// Separator
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(FMargin(200, 20))
[
SNew(SImage).Image(&Theme.SeparatorBrush)
]
// Action list
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SHorizontalBox)
// Objective
+ SHorizontalBox::Slot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Bottom)
.Padding(Theme.ContentPadding)
[
SNew(SFlareObjectiveInfo).PC(PC)
]
// Ship
+ SHorizontalBox::Slot()
.HAlign(HAlign_Right)
.VAlign(VAlign_Bottom)
.Padding(Theme.TitleButtonPadding)
[
SNew(SFlareRoundButton)
.Text(LOCTEXT("InspectShip", "Ship"))
.HelpText(LOCTEXT("InspectShipInfo", "Inspect your current ship"))
.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Ship, true))
.OnClicked(this, &SFlareDashboard::OnInspectShip)
]
// Ship upgrade
+ SHorizontalBox::Slot()
.HAlign(HAlign_Right)
.VAlign(VAlign_Bottom)
.Padding(Theme.TitleButtonPadding)
.AutoWidth()
[
SNew(SFlareRoundButton)
.Text(LOCTEXT("UpgradeShip", "Upgrade ship"))
.HelpText(LOCTEXT("UpgradeShipInfo", "Upgrade your current ship"))
.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_ShipConfig, true))
.OnClicked(this, &SFlareDashboard::OnConfigureShip)
.Visibility(this, &SFlareDashboard::GetDockedVisibility)
]
// Orbit
+ SHorizontalBox::Slot()
.HAlign(HAlign_Center)
.VAlign(VAlign_Bottom)
.Padding(Theme.TitleButtonPadding)
.AutoWidth()
[
SNew(SFlareRoundButton)
.Text(LOCTEXT("GoOrbit", "Orbital map"))
.HelpText(LOCTEXT("GoOrbitInfo", "Exit the navigation mode and go back to the orbital map"))
.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Orbit, true))
.OnClicked(this, &SFlareDashboard::OnOrbit)
]
// Undock
+ SHorizontalBox::Slot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Bottom)
.Padding(Theme.TitleButtonPadding)
.AutoWidth()
[
SNew(SFlareRoundButton)
.Text(LOCTEXT("Undock", "Undock"))
.HelpText(LOCTEXT("UndockInfo", "Undock from this spacecraft and go back to flying the ship"))
.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Undock, true))
.OnClicked(this, &SFlareDashboard::OnUndock)
.Visibility(this, &SFlareDashboard::GetDockedVisibility)
]
// Company
+ SHorizontalBox::Slot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Bottom)
.Padding(Theme.TitleButtonPadding)
[
SNew(SFlareRoundButton)
.Text(LOCTEXT("InspectCompany", "Company"))
.HelpText(LOCTEXT("InspectCompanyInfo", "Inspect your company"))
.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Company, true))
.OnClicked(this, &SFlareDashboard::OnInspectCompany)
]
]
// Content block
+ SVerticalBox::Slot()
[
SNew(SScrollBox)
.Style(&Theme.ScrollBoxStyle)
.ScrollBarStyle(&Theme.ScrollBarStyle)
+ SScrollBox::Slot()
[
SNew(SHorizontalBox)
// Owned
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
[
SAssignNew(OwnedShipList, SFlareShipList)
.MenuManager(MenuManager)
.Title(LOCTEXT("DashboardMyListTitle", "OWNED SPACECRAFTS IN SECTOR"))
]
// Others
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
[
SAssignNew(OtherShipList, SFlareShipList)
.MenuManager(MenuManager)
.Title(LOCTEXT("DashboardOtherListTitle", "OTHER SPACECRAFTS IN SECTOR"))
]
]
]
];
}
/*----------------------------------------------------
Interaction
----------------------------------------------------*/
void SFlareDashboard::Setup()
{
SetEnabled(false);
SetVisibility(EVisibility::Hidden);
}
void SFlareDashboard::Enter()
{
FLOG("SFlareDashboard::Enter");
SetEnabled(true);
SetVisibility(EVisibility::Visible);
// Find all ships here
AFlarePlayerController* PC = MenuManager->GetPC();
if (PC)
{
AFlareSpacecraft* PlayerShip = PC->GetShipPawn();
for (TActorIterator<AActor> ActorItr(PC->GetWorld()); ActorItr; ++ActorItr)
{
AFlareSpacecraft* ShipCandidate = Cast<AFlareSpacecraft>(*ActorItr);
if (ShipCandidate && ShipCandidate->GetDamageSystem()->IsAlive())
{
// Owned ship
if (PlayerShip && ShipCandidate->GetCompany() == PlayerShip->GetCompany())
{
OwnedShipList->AddShip(ShipCandidate);
}
// other
else
{
OtherShipList->AddShip(ShipCandidate);
}
}
}
}
OwnedShipList->RefreshList();
OtherShipList->RefreshList();
}
void SFlareDashboard::Exit()
{
OwnedShipList->Reset();
OtherShipList->Reset();
SetEnabled(false);
SetVisibility(EVisibility::Hidden);
}
/*----------------------------------------------------
Callbacks
----------------------------------------------------*/
EVisibility SFlareDashboard::GetDockedVisibility() const
{
AFlarePlayerController* PC = MenuManager->GetPC();
if (PC)
{
AFlareSpacecraft* Ship = PC->GetShipPawn();
if (Ship)
{
return (Ship->GetNavigationSystem()->IsDocked() ? EVisibility::Visible : EVisibility::Collapsed);
}
}
return EVisibility::Collapsed;
}
void SFlareDashboard::OnInspectShip()
{
MenuManager->OpenMenu(EFlareMenu::MENU_Ship);
}
void SFlareDashboard::OnConfigureShip()
{
MenuManager->OpenMenu(EFlareMenu::MENU_ShipConfig);
}
void SFlareDashboard::OnOrbit()
{
//MenuManager->Notify(LOCTEXT("Unavailable", "Unavailable feature !"), LOCTEXT("Info", "The full game will be released later :)"));
MenuManager->OpenMenu(EFlareMenu::MENU_Orbit);
}
void SFlareDashboard::OnUndock()
{
// Ask to undock, and close the menu
AFlarePlayerController* PC = MenuManager->GetPC();
if (PC)
{
AFlareSpacecraft* Ship = PC->GetShipPawn();
if (Ship)
{
Ship->GetNavigationSystem()->Undock();
MenuManager->CloseMenu();
}
}
}
void SFlareDashboard::OnInspectCompany()
{
MenuManager->OpenMenu(EFlareMenu::MENU_Company);
}
void SFlareDashboard::OnExit()
{
MenuManager->CloseMenu();
}
#undef LOCTEXT_NAMESPACE
<commit_msg>Fixed RCS sound, removed comment<commit_after>
#include "../../Flare.h"
#include "FlareDashboard.h"
#include "../../Game/FlareGame.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlareMenuPawn.h"
#include "../../Player/FlarePlayerController.h"
#include "../Components/FlareObjectiveInfo.h"
#define LOCTEXT_NAMESPACE "FlareDashboard"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareDashboard::Construct(const FArguments& InArgs)
{
// Data
MenuManager = InArgs._MenuManager;
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
AFlarePlayerController* PC = MenuManager->GetPC();
// Build structure
ChildSlot
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SHorizontalBox)
// Icon
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SImage).Image(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Dashboard))
]
// Title
+ SHorizontalBox::Slot()
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(STextBlock)
.TextStyle(&Theme.TitleFont)
.Text(LOCTEXT("Dashboard", "DASHBOARD"))
]
// Close
+ SHorizontalBox::Slot()
.HAlign(HAlign_Right)
.VAlign(VAlign_Bottom)
.Padding(Theme.TitleButtonPadding)
.AutoWidth()
[
SNew(SFlareRoundButton)
.Text(LOCTEXT("Close", "Close"))
.HelpText(LOCTEXT("CloseInfo", "Close the menu and go back to flying the ship"))
.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Exit, true))
.OnClicked(this, &SFlareDashboard::OnExit)
]
]
// Separator
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(FMargin(200, 20))
[
SNew(SImage).Image(&Theme.SeparatorBrush)
]
// Action list
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Fill)
.VAlign(VAlign_Center)
.Padding(Theme.ContentPadding)
[
SNew(SHorizontalBox)
// Objective
+ SHorizontalBox::Slot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Bottom)
.Padding(Theme.ContentPadding)
[
SNew(SFlareObjectiveInfo).PC(PC)
]
// Ship
+ SHorizontalBox::Slot()
.HAlign(HAlign_Right)
.VAlign(VAlign_Bottom)
.Padding(Theme.TitleButtonPadding)
[
SNew(SFlareRoundButton)
.Text(LOCTEXT("InspectShip", "Ship"))
.HelpText(LOCTEXT("InspectShipInfo", "Inspect your current ship"))
.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Ship, true))
.OnClicked(this, &SFlareDashboard::OnInspectShip)
]
// Ship upgrade
+ SHorizontalBox::Slot()
.HAlign(HAlign_Right)
.VAlign(VAlign_Bottom)
.Padding(Theme.TitleButtonPadding)
.AutoWidth()
[
SNew(SFlareRoundButton)
.Text(LOCTEXT("UpgradeShip", "Upgrade ship"))
.HelpText(LOCTEXT("UpgradeShipInfo", "Upgrade your current ship"))
.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_ShipConfig, true))
.OnClicked(this, &SFlareDashboard::OnConfigureShip)
.Visibility(this, &SFlareDashboard::GetDockedVisibility)
]
// Orbit
+ SHorizontalBox::Slot()
.HAlign(HAlign_Center)
.VAlign(VAlign_Bottom)
.Padding(Theme.TitleButtonPadding)
.AutoWidth()
[
SNew(SFlareRoundButton)
.Text(LOCTEXT("GoOrbit", "Orbital map"))
.HelpText(LOCTEXT("GoOrbitInfo", "Exit the navigation mode and go back to the orbital map"))
.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Orbit, true))
.OnClicked(this, &SFlareDashboard::OnOrbit)
]
// Undock
+ SHorizontalBox::Slot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Bottom)
.Padding(Theme.TitleButtonPadding)
.AutoWidth()
[
SNew(SFlareRoundButton)
.Text(LOCTEXT("Undock", "Undock"))
.HelpText(LOCTEXT("UndockInfo", "Undock from this spacecraft and go back to flying the ship"))
.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Undock, true))
.OnClicked(this, &SFlareDashboard::OnUndock)
.Visibility(this, &SFlareDashboard::GetDockedVisibility)
]
// Company
+ SHorizontalBox::Slot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Bottom)
.Padding(Theme.TitleButtonPadding)
[
SNew(SFlareRoundButton)
.Text(LOCTEXT("InspectCompany", "Company"))
.HelpText(LOCTEXT("InspectCompanyInfo", "Inspect your company"))
.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Company, true))
.OnClicked(this, &SFlareDashboard::OnInspectCompany)
]
]
// Content block
+ SVerticalBox::Slot()
[
SNew(SScrollBox)
.Style(&Theme.ScrollBoxStyle)
.ScrollBarStyle(&Theme.ScrollBarStyle)
+ SScrollBox::Slot()
[
SNew(SHorizontalBox)
// Owned
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
[
SAssignNew(OwnedShipList, SFlareShipList)
.MenuManager(MenuManager)
.Title(LOCTEXT("DashboardMyListTitle", "OWNED SPACECRAFTS IN SECTOR"))
]
// Others
+ SHorizontalBox::Slot()
.Padding(Theme.ContentPadding)
[
SAssignNew(OtherShipList, SFlareShipList)
.MenuManager(MenuManager)
.Title(LOCTEXT("DashboardOtherListTitle", "OTHER SPACECRAFTS IN SECTOR"))
]
]
]
];
}
/*----------------------------------------------------
Interaction
----------------------------------------------------*/
void SFlareDashboard::Setup()
{
SetEnabled(false);
SetVisibility(EVisibility::Hidden);
}
void SFlareDashboard::Enter()
{
FLOG("SFlareDashboard::Enter");
SetEnabled(true);
SetVisibility(EVisibility::Visible);
// Find all ships here
AFlarePlayerController* PC = MenuManager->GetPC();
if (PC)
{
AFlareSpacecraft* PlayerShip = PC->GetShipPawn();
for (TActorIterator<AActor> ActorItr(PC->GetWorld()); ActorItr; ++ActorItr)
{
AFlareSpacecraft* ShipCandidate = Cast<AFlareSpacecraft>(*ActorItr);
if (ShipCandidate && ShipCandidate->GetDamageSystem()->IsAlive())
{
// Owned ship
if (PlayerShip && ShipCandidate->GetCompany() == PlayerShip->GetCompany())
{
OwnedShipList->AddShip(ShipCandidate);
}
// other
else
{
OtherShipList->AddShip(ShipCandidate);
}
}
}
}
OwnedShipList->RefreshList();
OtherShipList->RefreshList();
}
void SFlareDashboard::Exit()
{
OwnedShipList->Reset();
OtherShipList->Reset();
SetEnabled(false);
SetVisibility(EVisibility::Hidden);
}
/*----------------------------------------------------
Callbacks
----------------------------------------------------*/
EVisibility SFlareDashboard::GetDockedVisibility() const
{
AFlarePlayerController* PC = MenuManager->GetPC();
if (PC)
{
AFlareSpacecraft* Ship = PC->GetShipPawn();
if (Ship)
{
return (Ship->GetNavigationSystem()->IsDocked() ? EVisibility::Visible : EVisibility::Collapsed);
}
}
return EVisibility::Collapsed;
}
void SFlareDashboard::OnInspectShip()
{
MenuManager->OpenMenu(EFlareMenu::MENU_Ship);
}
void SFlareDashboard::OnConfigureShip()
{
MenuManager->OpenMenu(EFlareMenu::MENU_ShipConfig);
}
void SFlareDashboard::OnOrbit()
{
MenuManager->OpenMenu(EFlareMenu::MENU_Orbit);
}
void SFlareDashboard::OnUndock()
{
// Ask to undock, and close the menu
AFlarePlayerController* PC = MenuManager->GetPC();
if (PC)
{
AFlareSpacecraft* Ship = PC->GetShipPawn();
if (Ship)
{
Ship->GetNavigationSystem()->Undock();
MenuManager->CloseMenu();
}
}
}
void SFlareDashboard::OnInspectCompany()
{
MenuManager->OpenMenu(EFlareMenu::MENU_Company);
}
void SFlareDashboard::OnExit()
{
MenuManager->CloseMenu();
}
#undef LOCTEXT_NAMESPACE
<|endoftext|> |
<commit_before>/**
* Unit Tests for Piezas
**/
#include <gtest/gtest.h>
#include "Piezas.h"
class PiezasTest : public ::testing::Test
{
protected:
PiezasTest(){} //constructor runs before each test
virtual ~PiezasTest(){} //destructor cleans up after tests
virtual void SetUp(){} //sets up before each test (after constructor)
virtual void TearDown(){} //clean up after each test, (before destructor)
};
TEST(PiezasTest, sanityCheck)
{
ASSERT_TRUE(true);
}
TEST(PiezasTest, blankBoard)
{
Piezas game;
Piece board[3][4];
int count = 0;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 4; j++)
{
if(board[i][j] == Blank)
{
count++;
}
}
}
ASSERT_EQ(count, 12);
}
TEST(PiezasTest, placeFirstX)
{
Piezas game;
Piece board[3][4];
Piece confirm;
confirm = game.dropPiece(2);
ASSERT_EQ(confirm, board[2][2]);
}<commit_msg>Add files via upload<commit_after>/**
* Unit Tests for Piezas
**/
#include <gtest/gtest.h>
#include "Piezas.h"
class PiezasTest : public ::testing::Test
{
protected:
PiezasTest(){} //constructor runs before each test
virtual ~PiezasTest(){} //destructor cleans up after tests
virtual void SetUp(){} //sets up before each test (after constructor)
virtual void TearDown(){} //clean up after each test, (before destructor)
};
TEST(PiezasTest, sanityCheck)
{
ASSERT_TRUE(true);
}
TEST(PiezasTest, blankBoard)
{
Piezas game;
Piece board[3][4];
int count = 0;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 4; j++)
{
if(board[i][j] == Blank)
{
count++;
std::cout<<count<<endl;
}
}
}
ASSERT_EQ(count, 12);
}
TEST(PiezasTest, placeFirstX)
{
Piezas game;
Piece board[3][4];
Piece confirm;
confirm = game.dropPiece(2);
ASSERT_EQ(confirm, board[2][2]);
}<|endoftext|> |
<commit_before>/// Copyright 2015 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#include "SantaDriverClient.h"
#define super IOUserClient
#define SantaDriverClient com_google_SantaDriverClient
// The defines above can'be used in this function, must use the full names.
OSDefineMetaClassAndStructors(com_google_SantaDriverClient, IOUserClient);
#pragma mark Driver Management
bool SantaDriverClient::initWithTask(
task_t owningTask, void *securityID, UInt32 type) {
if (clientHasPrivilege(
owningTask, kIOClientPrivilegeAdministrator) != KERN_SUCCESS) {
LOGW("Unprivileged client attempted to connect.");
return false;
}
if (!super::initWithTask(owningTask, securityID, type)) return false;
return true;
}
bool SantaDriverClient::start(IOService *provider) {
fProvider = OSDynamicCast(com_google_SantaDriver, provider);
if (!fProvider) return false;
if (!super::start(provider)) return false;
fSDM = fProvider->GetDecisionManager();
return true;
}
void SantaDriverClient::stop(IOService *provider) {
super::stop(provider);
fProvider = NULL;
}
IOReturn SantaDriverClient::clientClose() {
terminate(kIOServiceSynchronous);
return kIOReturnSuccess;
}
bool SantaDriverClient::terminate(IOOptionBits options) {
fSDM->DisconnectClient();
LOGI("Client disconnected.");
fSharedMemory->release();
fDataQueue->release();
fSharedMemory = NULL;
fDataQueue = NULL;
if (fProvider && fProvider->isOpen(this)) fProvider->close(this);
return super::terminate(options);
}
#pragma mark Fetching memory and data queue notifications
IOReturn SantaDriverClient::registerNotificationPort(mach_port_t port,
UInt32 type,
UInt32 ref) {
if ((!fDataQueue) || (port == MACH_PORT_NULL)) return kIOReturnError;
fDataQueue->setNotificationPort(port);
return kIOReturnSuccess;
}
IOReturn SantaDriverClient::clientMemoryForType(UInt32 type,
IOOptionBits *options,
IOMemoryDescriptor **memory) {
*memory = NULL;
*options = 0;
if (type == kIODefaultMemoryType) {
if (!fSharedMemory) return kIOReturnNoMemory;
fSharedMemory->retain(); // client will decrement this ref
*memory = fSharedMemory;
fSDM->ConnectClient(fDataQueue, proc_selfpid());
LOGI("Client connected, PID: %d.", proc_selfpid());
return kIOReturnSuccess;
}
return kIOReturnNoMemory;
}
#pragma mark Callable Methods
IOReturn SantaDriverClient::open() {
if (isInactive()) return kIOReturnNotAttached;
if (!fProvider->open(this)) {
LOGW("A second client tried to connect.");
return kIOReturnExclusiveAccess;
}
fDataQueue = IOSharedDataQueue::withCapacity((sizeof(santa_message_t) +
DATA_QUEUE_ENTRY_HEADER_SIZE)
* kMaxQueueEvents);
if (!fDataQueue) return kIOReturnNoMemory;
fSharedMemory = fDataQueue->getMemoryDescriptor();
if (!fSharedMemory) {
fDataQueue->release();
fDataQueue = NULL;
return kIOReturnVMError;
}
return kIOReturnSuccess;
}
IOReturn SantaDriverClient::static_open(
SantaDriverClient *target,
void *reference,
IOExternalMethodArguments *arguments) {
if (!target) return kIOReturnBadArgument;
return target->open();
}
IOReturn SantaDriverClient::allow_binary(const uint64_t vnode_id) {
char vnode_id_str[21];
snprintf(vnode_id_str, sizeof(vnode_id_str), "%llu", vnode_id);
fSDM->AddToCache(vnode_id_str,
ACTION_RESPOND_CHECKBW_ALLOW,
fSDM->GetCurrentUptime());
return kIOReturnSuccess;
}
IOReturn SantaDriverClient::static_allow_binary(
SantaDriverClient *target,
void *reference,
IOExternalMethodArguments *arguments) {
if (!target) return kIOReturnBadArgument;
return target->allow_binary(
*(static_cast<const uint64_t *>(arguments->scalarInput)));
}
IOReturn SantaDriverClient::deny_binary(const uint64_t vnode_id) {
char vnode_id_str[21];
snprintf(vnode_id_str, sizeof(vnode_id_str), "%llu", vnode_id);
fSDM->AddToCache(vnode_id_str,
ACTION_RESPOND_CHECKBW_DENY,
fSDM->GetCurrentUptime());
return kIOReturnSuccess;
}
IOReturn SantaDriverClient::static_deny_binary(
com_google_SantaDriverClient *target,
void *reference,
IOExternalMethodArguments *arguments) {
if (!target) return kIOReturnBadArgument;
return target->deny_binary(
*(static_cast<const uint64_t *>(arguments->scalarInput)));
}
IOReturn SantaDriverClient::clear_cache() {
fSDM->ClearCache();
return kIOReturnSuccess;
}
IOReturn SantaDriverClient::static_clear_cache(
com_google_SantaDriverClient *target,
void *reference,
IOExternalMethodArguments *arguments) {
if (!target) return kIOReturnBadArgument;
return target->clear_cache();
}
IOReturn SantaDriverClient::cache_count(uint64_t *output) {
*output = fSDM->CacheCount();
return kIOReturnSuccess;
}
IOReturn SantaDriverClient::static_cache_count(
com_google_SantaDriverClient *target,
void *reference,
IOExternalMethodArguments *arguments) {
if (!target) return kIOReturnBadArgument;
return target->cache_count(&(arguments->scalarOutput[0]));
}
#pragma mark Method Resolution
IOReturn SantaDriverClient::externalMethod(
UInt32 selector,
IOExternalMethodArguments *arguments,
IOExternalMethodDispatch *dispatch,
OSObject *target,
void *reference) {
/// Array of methods callable by clients. The order of these must match the
/// order of the items in SantaDriverMethods in SNTKernelCommon.h
IOExternalMethodDispatch sMethods[kSantaUserClientNMethods] = {
{
reinterpret_cast<IOExternalMethodAction>(&SantaDriverClient::static_open),
0, // input scalar
0, // input struct
0, // output scalar
0 // output struct
},
{
reinterpret_cast<IOExternalMethodAction>(
&SantaDriverClient::static_allow_binary),
1,
0,
0,
0
},
{
reinterpret_cast<IOExternalMethodAction>(
&SantaDriverClient::static_deny_binary),
1,
0,
0,
0
},
{
reinterpret_cast<IOExternalMethodAction>(
&SantaDriverClient::static_clear_cache),
0,
0,
0,
0
},
{
reinterpret_cast<IOExternalMethodAction>(
&SantaDriverClient::static_cache_count),
0,
0,
1,
0
}
};
if (selector < static_cast<UInt32>(kSantaUserClientNMethods)) {
dispatch = &(sMethods[selector]);
if (!target) target = this;
} else {
return kIOReturnBadArgument;
}
return super::externalMethod(selector,
arguments,
dispatch,
target,
reference);
}
#undef super
<commit_msg>santa-driver: Ensure fSDM and fDataQueue are NULL'd ASAP.<commit_after>/// Copyright 2015 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#include "SantaDriverClient.h"
#define super IOUserClient
#define SantaDriverClient com_google_SantaDriverClient
// The defines above can'be used in this function, must use the full names.
OSDefineMetaClassAndStructors(com_google_SantaDriverClient, IOUserClient);
#pragma mark Driver Management
bool SantaDriverClient::initWithTask(
task_t owningTask, void *securityID, UInt32 type) {
if (clientHasPrivilege(
owningTask, kIOClientPrivilegeAdministrator) != KERN_SUCCESS) {
LOGW("Unprivileged client attempted to connect.");
return false;
}
if (!super::initWithTask(owningTask, securityID, type)) return false;
return true;
}
bool SantaDriverClient::start(IOService *provider) {
fProvider = OSDynamicCast(com_google_SantaDriver, provider);
if (!fProvider) return false;
if (!super::start(provider)) return false;
fSDM = fProvider->GetDecisionManager();
return true;
}
void SantaDriverClient::stop(IOService *provider) {
super::stop(provider);
fSDM = NULL;
fProvider = NULL;
}
IOReturn SantaDriverClient::clientClose() {
terminate(kIOServiceSynchronous);
return kIOReturnSuccess;
}
bool SantaDriverClient::terminate(IOOptionBits options) {
fSDM->DisconnectClient();
LOGI("Client disconnected.");
fSharedMemory->release();
fSharedMemory = NULL;
fDataQueue->release();
fDataQueue = NULL;
if (fProvider && fProvider->isOpen(this)) fProvider->close(this);
return super::terminate(options);
}
#pragma mark Fetching memory and data queue notifications
IOReturn SantaDriverClient::registerNotificationPort(mach_port_t port,
UInt32 type,
UInt32 ref) {
if ((!fDataQueue) || (port == MACH_PORT_NULL)) return kIOReturnError;
fDataQueue->setNotificationPort(port);
return kIOReturnSuccess;
}
IOReturn SantaDriverClient::clientMemoryForType(UInt32 type,
IOOptionBits *options,
IOMemoryDescriptor **memory) {
*memory = NULL;
*options = 0;
if (type == kIODefaultMemoryType) {
if (!fSharedMemory) return kIOReturnNoMemory;
fSharedMemory->retain(); // client will decrement this ref
*memory = fSharedMemory;
fSDM->ConnectClient(fDataQueue, proc_selfpid());
LOGI("Client connected, PID: %d.", proc_selfpid());
return kIOReturnSuccess;
}
return kIOReturnNoMemory;
}
#pragma mark Callable Methods
IOReturn SantaDriverClient::open() {
if (isInactive()) return kIOReturnNotAttached;
if (!fProvider->open(this)) {
LOGW("A second client tried to connect.");
return kIOReturnExclusiveAccess;
}
fDataQueue = IOSharedDataQueue::withCapacity((sizeof(santa_message_t) +
DATA_QUEUE_ENTRY_HEADER_SIZE)
* kMaxQueueEvents);
if (!fDataQueue) return kIOReturnNoMemory;
fSharedMemory = fDataQueue->getMemoryDescriptor();
if (!fSharedMemory) {
fDataQueue->release();
fDataQueue = NULL;
return kIOReturnVMError;
}
return kIOReturnSuccess;
}
IOReturn SantaDriverClient::static_open(
SantaDriverClient *target,
void *reference,
IOExternalMethodArguments *arguments) {
if (!target) return kIOReturnBadArgument;
return target->open();
}
IOReturn SantaDriverClient::allow_binary(const uint64_t vnode_id) {
char vnode_id_str[21];
snprintf(vnode_id_str, sizeof(vnode_id_str), "%llu", vnode_id);
fSDM->AddToCache(vnode_id_str,
ACTION_RESPOND_CHECKBW_ALLOW,
fSDM->GetCurrentUptime());
return kIOReturnSuccess;
}
IOReturn SantaDriverClient::static_allow_binary(
SantaDriverClient *target,
void *reference,
IOExternalMethodArguments *arguments) {
if (!target) return kIOReturnBadArgument;
return target->allow_binary(
*(static_cast<const uint64_t *>(arguments->scalarInput)));
}
IOReturn SantaDriverClient::deny_binary(const uint64_t vnode_id) {
char vnode_id_str[21];
snprintf(vnode_id_str, sizeof(vnode_id_str), "%llu", vnode_id);
fSDM->AddToCache(vnode_id_str,
ACTION_RESPOND_CHECKBW_DENY,
fSDM->GetCurrentUptime());
return kIOReturnSuccess;
}
IOReturn SantaDriverClient::static_deny_binary(
com_google_SantaDriverClient *target,
void *reference,
IOExternalMethodArguments *arguments) {
if (!target) return kIOReturnBadArgument;
return target->deny_binary(
*(static_cast<const uint64_t *>(arguments->scalarInput)));
}
IOReturn SantaDriverClient::clear_cache() {
fSDM->ClearCache();
return kIOReturnSuccess;
}
IOReturn SantaDriverClient::static_clear_cache(
com_google_SantaDriverClient *target,
void *reference,
IOExternalMethodArguments *arguments) {
if (!target) return kIOReturnBadArgument;
return target->clear_cache();
}
IOReturn SantaDriverClient::cache_count(uint64_t *output) {
*output = fSDM->CacheCount();
return kIOReturnSuccess;
}
IOReturn SantaDriverClient::static_cache_count(
com_google_SantaDriverClient *target,
void *reference,
IOExternalMethodArguments *arguments) {
if (!target) return kIOReturnBadArgument;
return target->cache_count(&(arguments->scalarOutput[0]));
}
#pragma mark Method Resolution
IOReturn SantaDriverClient::externalMethod(
UInt32 selector,
IOExternalMethodArguments *arguments,
IOExternalMethodDispatch *dispatch,
OSObject *target,
void *reference) {
/// Array of methods callable by clients. The order of these must match the
/// order of the items in SantaDriverMethods in SNTKernelCommon.h
IOExternalMethodDispatch sMethods[kSantaUserClientNMethods] = {
{
reinterpret_cast<IOExternalMethodAction>(&SantaDriverClient::static_open),
0, // input scalar
0, // input struct
0, // output scalar
0 // output struct
},
{
reinterpret_cast<IOExternalMethodAction>(
&SantaDriverClient::static_allow_binary),
1,
0,
0,
0
},
{
reinterpret_cast<IOExternalMethodAction>(
&SantaDriverClient::static_deny_binary),
1,
0,
0,
0
},
{
reinterpret_cast<IOExternalMethodAction>(
&SantaDriverClient::static_clear_cache),
0,
0,
0,
0
},
{
reinterpret_cast<IOExternalMethodAction>(
&SantaDriverClient::static_cache_count),
0,
0,
1,
0
}
};
if (selector < static_cast<UInt32>(kSantaUserClientNMethods)) {
dispatch = &(sMethods[selector]);
if (!target) target = this;
} else {
return kIOReturnBadArgument;
}
return super::externalMethod(selector,
arguments,
dispatch,
target,
reference);
}
#undef super
<|endoftext|> |
<commit_before>/*
* Jamoma NodeLib
* Copyright © 2008, Tim Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "NodeLib.h"
JamomaNode::JamomaNode(TTSymbolPtr oscAddress, TTSymbolPtr newType, ObjectPtr newObject):TTObject(oscAddress->getCString())
{
TTSymbolPtr oscAddress_parent;
TTSymbolPtr oscAddress_name;
TTSymbolPtr oscAddress_instance;
TTSymbolPtr oscAddress_attribute;
TTBoolean parent_created;
TTErr err;
// split the oscAddress in /parent/name
err = splitOSCAddress(oscAddress,&oscAddress_parent,&oscAddress_name, &oscAddress_instance, &oscAddress_attribute);
// DEBUG
post("JamomaNode : %s",oscAddress->getCString());
if(oscAddress_parent)
post(" parent : %s ",oscAddress_parent->getCString());
if(oscAddress_name)
post(" name : %s ",oscAddress_name->getCString());
if(oscAddress_instance)
post(" instance : %s ",oscAddress_instance->getCString());
if(oscAddress_attribute)
post(" attribute : %s ",oscAddress_attribute->getCString());
if(err == kTTErrNone){
this->name = oscAddress_name;
this->type = newType;
this->maxObject = newObject;
this->instance = oscAddress_instance;
// create a hashtab
this->children = new TTHash();
// ensure that the path to the new node exists
if(oscAddress_parent){
parent_created = false;
JamomaNodeCheck(oscAddress_parent, &this->parent, &parent_created);
}
// register the node with his OSC address in the jamoma_node_hashtab
jamoma_node_hashtab->append(TT(oscAddress->getCString()),this);
}
}
JamomaNode::~JamomaNode()
{
;
}
#if 0
#pragma mark -
#pragma mark Static Methods
#endif
TTSymbolPtr JamomaNode::getName(){return this->name;}
TTSymbolPtr JamomaNode::getInstance(){return this->instance;}
TTSymbolPtr JamomaNode::getType(){return this->type;}
ObjectPtr JamomaNode::getMaxObject(){return this->maxObject;}
JamomaNodePtr JamomaNode::getParent(){return this->parent;}
TTHashPtr JamomaNode::getChildren(){return this->children;}
TTErr JamomaNode::getDump()
{
uint i;
TTValue *hk = NULL;
TTValue *c = NULL;
JamomaNodePtr* n_c = NULL;
// CRASH !!!
post("dump : here I tried to display the name and the instance of the node");
post("!!! BUT IT CRASHES !!!");
//post("%s.%s",this->name->getCString(),this->instance->getCString());
// DON'T CRASH
post("dump : here I display the type of the node");
post("type %s",this->type->getCString());
//this->children->getKeys(*hk);
//post("%d children",this->children->getSize());
//for(i=0; i<this->children->getSize(); i++){
// this->children->lookup(hk[i],*c);
// c->get(0,(TTPtr*)n_c);
// (*n_c)->getDump();
//}
return kTTErrNone;
}
TTErr JamomaNode::getNodeForOSC(const char* oscAddress, JamomaNodePtr* returnedNode)
{
return getNodeForOSC(TT((char*)oscAddress), returnedNode);
}
TTErr JamomaNode::getNodeForOSC(TTSymbolPtr oscAddress, JamomaNodePtr* returnedNode)
{
TTValue* found = new TTValue();
// look into the hashtab to check if the address exist in the tree
jamoma_node_hashtab->lookup(oscAddress,*found);
// if this address doesn't exist
if(found == kTTErrValueNotFound)
return kTTErrGeneric;
else{
found->get(0,(TTPtr*)returnedNode);
return kTTErrNone;
}
}
TTErr JamomaNodeLookup(TTSymbolPtr oscAddress, LinkedListPtr* returnedNodes, JamomaNodePtr* firstReturnedNode)
{
return kTTErrNone;
}
TTErr JamomaNodeCreate(TTSymbolPtr oscAddress, TTSymbolPtr newType, ObjectPtr newObject, JamomaNodePtr* returnedNode, TTBoolean* created)
{
TTValue* found;
TTErr err;
// look into the hashtab to check if the address exist in the tree
found = new TTValue();
err = jamoma_node_hashtab->lookup(oscAddress,*found);
// if this address doesn't exist
if(err == kTTErrValueNotFound){
// we create the node
JamomaNodePtr new_node = new JamomaNode(oscAddress, newType, newObject);
// if the node have parent
if(new_node->getParent())
// add this node as a children of his parent
new_node->getParent()->getChildren()->append(oscAddress,new_node);
else
// this is the root
;
*returnedNode = new_node;
*created = true;
return kTTErrNone;
}
// else this address already exist
else{
// TODO: create an instance
found->get(0,(TTPtr*)returnedNode);
*created = true;
return kTTErrNone;
}
}
TTErr JamomaNodeCheck(TTSymbolPtr oscAddress, JamomaNodePtr* returnedNode, TTBoolean* created)
{
TTValue* found;
TTErr err;
TTBoolean parent_created;
// look into the hashtab to check if the address exist in the tree
found = new TTValue();
err = jamoma_node_hashtab->lookup(oscAddress,*found);
//// if the address doesn't exist
if(err == kTTErrValueNotFound){
post("JamomaNodeCheck : %s doesn't exists", oscAddress->getCString());
// // we create a container node
JamomaNodePtr new_node = new JamomaNode(oscAddress, TT("container"), NULL);
// // if the node have parent
// if(new_node->getParent())
// // add this node as a children of his parent
// new_node->getParent()->getChildren()->append(key,new_node);
// else
// // this is the root
// ;
*returnedNode = new_node;
*created = true;
}
return kTTErrNone;
}
TTErr splitOSCAddress(TTSymbolPtr oscAddress, TTSymbolPtr* returnedParentOscAdress, TTSymbolPtr* returnedNodeName, TTSymbolPtr* returnedNodeInstance, TTSymbolPtr* returnedNodeAttribute)
{
int i, len, pos;
bool stop;
char *last_colon, *last_slash, *last_dot;
char *attribute, *parent, *node, *instance;
char *to_split;
// Make sure we are dealing with valid OSC input by looking for a leading slash
if(oscAddress->getCString()[0] != '/')
return kTTErrGeneric;
to_split = (char *)malloc(sizeof(char)*(strlen(oscAddress->getCString())+1));
strcpy(to_split,oscAddress->getCString());
// find the last ':' in the OSCaddress
// if exists, split the OSC address in an address part (to split) and an attribute part
len = strlen(to_split);
last_colon = strrchr(to_split,':');
pos = (int)last_colon - (int)to_split;
if(last_colon){
attribute = (char *)malloc(sizeof(char)*(len - (pos+1)));
strcpy(attribute,to_split + pos+1);
*returnedNodeAttribute = TT(attribute);
to_split[pos] = NULL; // split to keep only the address part
}
else
*returnedNodeAttribute = NULL;
// find the last '/' in the address part
// if exists, split the address part in a node part (to split) and a parent part
len = strlen(to_split);
last_slash = strrchr(to_split,'/');
pos = (int)last_slash - (int)to_split;
if(last_slash && pos){ // && pos to avoid the root
parent = (char *)malloc(sizeof(char)*(pos+1));
strncpy(parent,to_split,pos);
parent[pos] = NULL;
*returnedParentOscAdress = TT(parent);
to_split = last_slash+1; // split to keep only the node part
}
else
*returnedParentOscAdress = NULL;
// find the last '.' in the node part
// if exists, split the node part in a name part and an instance part
len = strlen(to_split);
last_dot = strrchr(to_split,'.');
pos = (int)last_dot - (int)to_split;
if(last_dot > 0){
instance = (char *)malloc(sizeof(char)*(len - (pos+1)));
strcpy(instance,to_split + pos+1);
*returnedNodeInstance = TT(instance);
to_split[pos] = NULL; // split to keep only the name part
}
else
*returnedNodeInstance = NULL;
// TODO : ??? (detect unusual characters in a node name)
if(strlen(to_split) > 0){
if(*returnedParentOscAdress)
*returnedNodeName = TT(to_split);
else
*returnedNodeName = TT(to_split+1); // to remove the slash when it's the root
}
else
*returnedNodeName = NULL;
return kTTErrNone;
}
/************************************************************************************/
JamomaError jamoma_node_init()
{
if(jamoma_node_root)
return JAMOMA_ERR_NONE; // already have a root, do nothing...
post("> CREATION OF AN EXPERIMENTAL TREE");
post("");
jamoma_node_hashtab = new TTHash();
jamoma_node_root = new JamomaNode(TT("/jamoma"), TT("container"), NULL);
// TEST : an experimental tree
JamomaNodePtr test;
test = new JamomaNode(TT("/jamoma/degrade~/bitdepth"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/degrade~/bypass"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/degrade~/gain"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/input.1/pan"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/input.1/gain"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/input.2/pan"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/input.2/gain"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/output/audio/gain"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/output/limiter"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/output/preamp"), TT("parameter"), NULL);
post("");
post("> DUMP THE TREE");
post("");
post("> dump the root");
jamoma_node_root->getDump();
post("");
post("> dump the node /jamoma/output/preamp");
test->getDump();
return JAMOMA_ERR_NONE;
}
void jamoma_node_free(void)
{
;
}
<commit_msg>a dump function to display the tree<commit_after>/*
* Jamoma NodeLib
* Copyright © 2008, Tim Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "NodeLib.h"
JamomaNode::JamomaNode(TTSymbolPtr oscAddress, TTSymbolPtr newType, ObjectPtr newObject):TTObject(oscAddress->getCString())
{
TTSymbolPtr oscAddress_parent;
TTSymbolPtr oscAddress_name;
TTSymbolPtr oscAddress_instance;
TTSymbolPtr oscAddress_attribute;
TTBoolean parent_created;
TTErr err;
// split the oscAddress in /parent/name
err = splitOSCAddress(oscAddress,&oscAddress_parent,&oscAddress_name, &oscAddress_instance, &oscAddress_attribute);
// DEBUG
post("JamomaNode : %s",oscAddress->getCString());
if(oscAddress_parent)
post(" parent : %s ",oscAddress_parent->getCString());
if(oscAddress_name)
post(" name : %s ",oscAddress_name->getCString());
if(oscAddress_instance)
post(" instance : %s ",oscAddress_instance->getCString());
if(oscAddress_attribute)
post(" attribute : %s ",oscAddress_attribute->getCString());
if(err == kTTErrNone){
this->name = oscAddress_name;
this->type = newType;
this->maxObject = newObject;
this->instance = oscAddress_instance;
// create a hashtab
this->children = new TTHash();
// ensure that the path to the new node exists
if(oscAddress_parent){
parent_created = false;
JamomaNodeCheck(oscAddress_parent, &this->parent, &parent_created);
// add this node as a children of his parent
this->getParent()->getChildren()->append(oscAddress_name,this);
}
else
// this is the root
;
// register the node with his OSC address in the jamoma_node_hashtab
jamoma_node_hashtab->append(TT(oscAddress->getCString()),this);
}
}
JamomaNode::~JamomaNode()
{
;
}
#if 0
#pragma mark -
#pragma mark Static Methods
#endif
TTSymbolPtr JamomaNode::getName(){return this->name;}
TTSymbolPtr JamomaNode::getInstance(){return this->instance;}
TTSymbolPtr JamomaNode::getType(){return this->type;}
ObjectPtr JamomaNode::getMaxObject(){return this->maxObject;}
JamomaNodePtr JamomaNode::getParent(){return this->parent;}
TTHashPtr JamomaNode::getChildren(){return this->children;}
TTErr JamomaNode::getDump()
{
uint i;
TTValue *hk;
TTSymbolPtr key;
TTValue *c;
JamomaNodePtr n_c;
if(this->name && this->instance)
post("%s.%s",this->name->getCString(),this->instance->getCString());
else
if(this->name)
post("%s",this->name->getCString());
if(this->children->getSize()){
post("{");
hk = new TTValue();
c = new TTValue();
this->children->getKeys(*hk);
for(i=0; i<this->children->getSize(); i++){
hk->get(i,(TTSymbol**)&key);
this->children->lookup(key,*c);
c->get(0,(TTPtr*)&n_c);
n_c->getDump();
}
post("}");
}
return kTTErrNone;
}
TTErr JamomaNode::getNodeForOSC(const char* oscAddress, JamomaNodePtr* returnedNode)
{
return getNodeForOSC(TT((char*)oscAddress), returnedNode);
}
TTErr JamomaNode::getNodeForOSC(TTSymbolPtr oscAddress, JamomaNodePtr* returnedNode)
{
TTValue* found = new TTValue();
// look into the hashtab to check if the address exist in the tree
jamoma_node_hashtab->lookup(oscAddress,*found);
// if this address doesn't exist
if(found == kTTErrValueNotFound)
return kTTErrGeneric;
else{
found->get(0,(TTPtr*)returnedNode);
return kTTErrNone;
}
}
TTErr JamomaNodeLookup(TTSymbolPtr oscAddress, LinkedListPtr* returnedNodes, JamomaNodePtr* firstReturnedNode)
{
return kTTErrNone;
}
TTErr JamomaNodeCreate(TTSymbolPtr oscAddress, TTSymbolPtr newType, ObjectPtr newObject, JamomaNodePtr* returnedNode, TTBoolean* created)
{
TTValue* found;
TTErr err;
// look into the hashtab to check if the address exist in the tree
found = new TTValue();
err = jamoma_node_hashtab->lookup(oscAddress,*found);
// if this address doesn't exist
if(err == kTTErrValueNotFound){
// we create the node
JamomaNodePtr new_node = new JamomaNode(oscAddress, newType, newObject);
*returnedNode = new_node;
*created = true;
return kTTErrNone;
}
// else this address already exist
else{
// TODO: create an instance
found->get(0,(TTPtr*)returnedNode);
*created = true;
return kTTErrNone;
}
}
TTErr JamomaNodeCheck(TTSymbolPtr oscAddress, JamomaNodePtr* returnedNode, TTBoolean* created)
{
TTValue* found;
TTErr err;
TTBoolean parent_created;
// look into the hashtab to check if the address exist in the tree
found = new TTValue();
*created = false;
err = jamoma_node_hashtab->lookup(oscAddress,*found);
//// if the address doesn't exist
if(err == kTTErrValueNotFound){
post("JamomaNodeCheck : %s doesn't exists", oscAddress->getCString());
// we create a container node
JamomaNodePtr new_node = new JamomaNode(oscAddress, TT("container"), NULL);
*returnedNode = new_node;
*created = true;
}
else
found->get(0,(TTPtr*)returnedNode);
return kTTErrNone;
}
TTErr splitOSCAddress(TTSymbolPtr oscAddress, TTSymbolPtr* returnedParentOscAdress, TTSymbolPtr* returnedNodeName, TTSymbolPtr* returnedNodeInstance, TTSymbolPtr* returnedNodeAttribute)
{
int i, len, pos;
bool stop;
char *last_colon, *last_slash, *last_dot;
char *attribute, *parent, *node, *instance;
char *to_split;
// Make sure we are dealing with valid OSC input by looking for a leading slash
if(oscAddress->getCString()[0] != '/')
return kTTErrGeneric;
to_split = (char *)malloc(sizeof(char)*(strlen(oscAddress->getCString())+1));
strcpy(to_split,oscAddress->getCString());
// find the last ':' in the OSCaddress
// if exists, split the OSC address in an address part (to split) and an attribute part
len = strlen(to_split);
last_colon = strrchr(to_split,':');
pos = (int)last_colon - (int)to_split;
if(last_colon){
attribute = (char *)malloc(sizeof(char)*(len - (pos+1)));
strcpy(attribute,to_split + pos+1);
*returnedNodeAttribute = TT(attribute);
to_split[pos] = NULL; // split to keep only the address part
}
else
*returnedNodeAttribute = NULL;
// find the last '/' in the address part
// if exists, split the address part in a node part (to split) and a parent part
len = strlen(to_split);
last_slash = strrchr(to_split,'/');
pos = (int)last_slash - (int)to_split;
if(last_slash && pos){ // && pos to avoid the root
parent = (char *)malloc(sizeof(char)*(pos+1));
strncpy(parent,to_split,pos);
parent[pos] = NULL;
*returnedParentOscAdress = TT(parent);
to_split = last_slash+1; // split to keep only the node part
}
else
*returnedParentOscAdress = NULL;
// find the last '.' in the node part
// if exists, split the node part in a name part and an instance part
len = strlen(to_split);
last_dot = strrchr(to_split,'.');
pos = (int)last_dot - (int)to_split;
if(last_dot > 0){
instance = (char *)malloc(sizeof(char)*(len - (pos+1)));
strcpy(instance,to_split + pos+1);
*returnedNodeInstance = TT(instance);
to_split[pos] = NULL; // split to keep only the name part
}
else
*returnedNodeInstance = NULL;
// TODO : ??? (detect unusual characters in a node name)
if(strlen(to_split) > 0){
if(*returnedParentOscAdress)
*returnedNodeName = TT(to_split);
else
*returnedNodeName = TT(to_split+1); // to remove the slash when it's the root
}
else
*returnedNodeName = NULL;
return kTTErrNone;
}
/************************************************************************************/
JamomaError jamoma_node_init()
{
if(jamoma_node_root)
return JAMOMA_ERR_NONE; // already have a root, do nothing...
post("> CREATION OF AN EXPERIMENTAL TREE");
post("");
jamoma_node_hashtab = new TTHash();
jamoma_node_root = new JamomaNode(TT("/jamoma"), TT("container"), NULL);
// TEST : an experimental tree
JamomaNodePtr test;
test = new JamomaNode(TT("/jamoma/degrade~/bitdepth"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/degrade~/bypass"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/degrade~/gain"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/input.1/pan"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/input.1/gain"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/input.2/pan"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/input.2/gain"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/output/audio/gain"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/output/limiter"), TT("parameter"), NULL);
test = new JamomaNode(TT("/jamoma/output/preamp"), TT("parameter"), NULL);
post("");
post("> DUMP THE TREE");
post("");
jamoma_node_root->getDump();
return JAMOMA_ERR_NONE;
}
void jamoma_node_free(void)
{
;
}
<|endoftext|> |
<commit_before>/*
* Jamoma RampLib Base Class
* Copyright © 2008, Tim Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#ifdef WIN_VERSION
#pragma warning(disable:4083) //warning C4083: expected 'newline'; found identifier 's'
#endif // WIN_VERSION
#include "RampLib.h"
#include "ext.h"
RampUnit::RampUnit(const char* rampName, RampUnitCallback aCallbackMethod, void *aBaton)
: TTObject(rampName), startValue(NULL), targetValue(NULL), currentValue(NULL), normalizedValue(0.0), numValues(0), functionUnit(NULL)
{
callback = aCallbackMethod;
baton = aBaton;
setNumValues(1);
currentValue[0] = 0.0;
targetValue[0] = 0.0;
startValue[0] = 0.0;
registerAttribute(TT("function"), kTypeSymbol, &attrFunction, (TTSetterMethod)&RampUnit::setFunction);
setAttributeValue(TT("function"), TT("linear"));
}
RampUnit::~RampUnit()
{
delete functionUnit;
delete [] currentValue;
delete [] targetValue;
delete [] startValue;
}
void RampUnit::set(TTUInt32 newNumValues, TTFloat64 *newValues)
{
TTUInt32 i;
stop();
setNumValues(newNumValues);
for(i=0; i<newNumValues; i++)
currentValue[i] = newValues[i];
}
TTErr RampUnit::setFunction(const TTValue& functionName)
{
TTErr err;
attrFunction = functionName;
err = FunctionLib::createUnit(attrFunction, &functionUnit);
if(err)
logError("Jamoma ramp unit failed to load the requested FunctionUnit from TTBlue.");
return err;
}
TTErr RampUnit::getFunctionParameterNames(TTSymbol* parameterName, TTValue& names)
{
functionUnit->getAttributeNames(names);
return kTTErrNone;
}
TTErr RampUnit::setFunctionParameterValue(TTSymbol* parameterName, const TTValue& newValue)
{
functionUnit->setAttributeValue(parameterName, newValue);
return kTTErrNone;
}
TTErr RampUnit::getFunctionParameterValue(TTSymbol* parameterName, TTValue& value)
{
functionUnit->getAttributeValue(parameterName, value);
return kTTErrNone;
}
void RampUnit::setNumValues(TTUInt32 newNumValues)
{
if(newNumValues != numValues){
if(numValues != 0){
delete [] currentValue;
delete [] targetValue;
delete [] startValue;
}
currentValue = new TTFloat64[newNumValues];
targetValue = new TTFloat64[newNumValues];
startValue = new TTFloat64[newNumValues];
numValues = newNumValues;
}
sendMessage(TT("numValuesChanged")); // Notify sub-classes (if they respond to this message)
}
/***************************************************************************
RampLib
***************************************************************************/
#include "AsyncRamp.h"
#include "NoneRamp.h"
#include "QueueRamp.h"
#include "SchedulerRamp.h"
JamomaError RampLib::createUnit(const TTSymbol* unitName, RampUnit **unit, RampUnitCallback callback, void* baton)
{
if(*unit)
delete *unit;
// These should be alphabetized
if(unitName == TT("async"))
*unit = (RampUnit*) new AsyncRamp(callback, baton);
else if(unitName == TT("none"))
*unit = (RampUnit*) new NoneRamp(callback, baton);
else if(unitName == TT("queue"))
*unit = (RampUnit*) new QueueRamp(callback, baton);
else if(unitName == TT("scheduler"))
*unit = (RampUnit*) new SchedulerRamp(callback, baton);
else {
// Invalid function specified default to linear
// TTLogError("rampLib: Invalid rampUnit: %s", (char*)unitName);
error("puke");
*unit = (RampUnit*) new NoneRamp(callback, baton);
}
return JAMOMA_ERR_NONE;
}
void RampLib::getUnitNames(TTValue& unitNames)
{
unitNames.clear();
unitNames.append(TT("async"));
unitNames.append(TT("none"));
unitNames.append(TT("queue"));
unitNames.append(TT("scheduler"));
}
<commit_msg>If 'none' is specified for a ramp function, then linear is used.<commit_after>/*
* Jamoma RampLib Base Class
* Copyright © 2008, Tim Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#ifdef WIN_VERSION
#pragma warning(disable:4083) //warning C4083: expected 'newline'; found identifier 's'
#endif // WIN_VERSION
#include "RampLib.h"
#include "ext.h"
RampUnit::RampUnit(const char* rampName, RampUnitCallback aCallbackMethod, void *aBaton)
: TTObject(rampName), startValue(NULL), targetValue(NULL), currentValue(NULL), normalizedValue(0.0), numValues(0), functionUnit(NULL)
{
callback = aCallbackMethod;
baton = aBaton;
setNumValues(1);
currentValue[0] = 0.0;
targetValue[0] = 0.0;
startValue[0] = 0.0;
registerAttribute(TT("function"), kTypeSymbol, &attrFunction, (TTSetterMethod)&RampUnit::setFunction);
setAttributeValue(TT("function"), TT("linear"));
}
RampUnit::~RampUnit()
{
delete functionUnit;
delete [] currentValue;
delete [] targetValue;
delete [] startValue;
}
void RampUnit::set(TTUInt32 newNumValues, TTFloat64 *newValues)
{
TTUInt32 i;
stop();
setNumValues(newNumValues);
for(i=0; i<newNumValues; i++)
currentValue[i] = newValues[i];
}
TTErr RampUnit::setFunction(const TTValue& functionName)
{
TTErr err;
attrFunction = functionName;
if(attrFunction == TT("none"))
attrFunction = TT("linear");
err = FunctionLib::createUnit(attrFunction, &functionUnit);
if(err)
logError("Jamoma ramp unit failed to load the requested FunctionUnit from TTBlue.");
return err;
}
TTErr RampUnit::getFunctionParameterNames(TTSymbol* parameterName, TTValue& names)
{
functionUnit->getAttributeNames(names);
return kTTErrNone;
}
TTErr RampUnit::setFunctionParameterValue(TTSymbol* parameterName, const TTValue& newValue)
{
functionUnit->setAttributeValue(parameterName, newValue);
return kTTErrNone;
}
TTErr RampUnit::getFunctionParameterValue(TTSymbol* parameterName, TTValue& value)
{
functionUnit->getAttributeValue(parameterName, value);
return kTTErrNone;
}
void RampUnit::setNumValues(TTUInt32 newNumValues)
{
if(newNumValues != numValues){
if(numValues != 0){
delete [] currentValue;
delete [] targetValue;
delete [] startValue;
}
currentValue = new TTFloat64[newNumValues];
targetValue = new TTFloat64[newNumValues];
startValue = new TTFloat64[newNumValues];
numValues = newNumValues;
}
sendMessage(TT("numValuesChanged")); // Notify sub-classes (if they respond to this message)
}
/***************************************************************************
RampLib
***************************************************************************/
#include "AsyncRamp.h"
#include "NoneRamp.h"
#include "QueueRamp.h"
#include "SchedulerRamp.h"
JamomaError RampLib::createUnit(const TTSymbol* unitName, RampUnit **unit, RampUnitCallback callback, void* baton)
{
if(*unit)
delete *unit;
// These should be alphabetized
if(unitName == TT("async"))
*unit = (RampUnit*) new AsyncRamp(callback, baton);
else if(unitName == TT("none"))
*unit = (RampUnit*) new NoneRamp(callback, baton);
else if(unitName == TT("queue"))
*unit = (RampUnit*) new QueueRamp(callback, baton);
else if(unitName == TT("scheduler"))
*unit = (RampUnit*) new SchedulerRamp(callback, baton);
else {
// Invalid function specified default to linear
// TTLogError("rampLib: Invalid rampUnit: %s", (char*)unitName);
error("puke");
*unit = (RampUnit*) new NoneRamp(callback, baton);
}
return JAMOMA_ERR_NONE;
}
void RampLib::getUnitNames(TTValue& unitNames)
{
unitNames.clear();
unitNames.append(TT("async"));
unitNames.append(TT("none"));
unitNames.append(TT("queue"));
unitNames.append(TT("scheduler"));
}
<|endoftext|> |
<commit_before>#include "ofApp.h"
//#include "ECURabbitObject.h"
#include "ecuaObject.h"
ofVec3f p;
//--------------------------------------------------------------
void ofApp::setup(){
ofSetVerticalSync(true);
// mesh.load("lofi-bunny.ply");
// cout << cam.getTarget().getPosition() << endl;
universe = new ECUUniverse();
universe->addObject(new ecuaObject(ofVec3f(0, 0, -1000)));
// cam.disableMouseInput();
// cam.set
ofSetSmoothLighting(true);
pointLight2.setDiffuseColor( ofFloatColor(.3, .3, .3));
pointLight2.setSpecularColor(ofFloatColor(10, 10, 10));
pointLight2.setPosition(120, 80, 500);
<<<<<<< HEAD
=======
currentEditingObj = NULL;
>>>>>>> b2dd5efc5cac1a8e1fe86c0dd15be4646f103e27
// ofAddListener(ofEvent::mousePressed, &control, control::mousePressed)
// ofAddListener(ofEvents().mouseDragged , &control, &ctrls::mouseDragged);
// ofAddListener(ofEvents().mousePressed, &control, &ctrls::mousePressed);
// ofAddListener(ofEvents().mouseReleased, &control, &ctrls::mouseReleased);
// ofAddListener(ofEvents().mouseScrolled, &control, &ctrls::mouseScrolled);
// ofRegisterMouseEvents(control);
}
void ofApp::exit() {
delete universe;
}
//--------------------------------------------------------------
void ofApp::update(){
universe->update();
control.update();
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackgroundGradient(ofColor(64), ofColor(0));
ofSetColor(255);
ofEnableDepthTest();
ofEnableLighting();
pointLight2.enable();
universe->draw();
ofDisableLighting();
ofDisableDepthTest();
if(currentEditingObj != NULL) {
control.draw();
}
}
bool zDown = false;
#define KEY(k, f) if(key == (k)) { (f); }
void ofApp::createObject() {
if(currentEditingObj != NULL) {
//we are now going to turn off, this means that we need to place the object in
currentEditingObj = NULL;
}
else {
ECUBaseObject *obj = new ecuaObject(ofVec3f(universe->pos.x, universe->pos.y, universe->pos.z-1000));
currentEditingObj = obj;
universe->addObject(obj);
}
// creatingObject = !creatingObject;
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
KEY('z', zDown = true)
KEY('a', createObject())
// KEY('s', currentEditingObj = NULL)
cout << "current pos = " << universe->pos << endl;
cout << "there are " << universe->objects.size() << " objects" << endl;
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
zDown = false;
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
control.mouseMoved(x, y);
}
ofVec3f downPosition;
ofQuaternion downOrientation;
float mouseRange = 0;
void ofApp::mouseDragged(int x, int y, int button) {
control.mouseDragged(x, y, button);
for (int i = 0; i < control.amnt; i++) {
currentEditingObj->setParam(i, control.fadersPos[i]);
//if we found an object, set the of the control to the object so there is no jump
}
}
//--------------------------------------------------------------
void ofApp::mouseScrolled(float x, float y) {
if (zDown) {
universe->pos.z+= -y;
}
else {
universe->pos.x-= x;
universe->pos.y+= y;
}
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
mouseRange = mouseX;
downPosition = universe->cam.getPosition(); // ofCamera::getGlobalPosition();
cout << "cam pos = " << downPosition << endl;
downOrientation = universe->cam.getOrientationQuat(); // ofCamera::getGlobalOrientation();
control.mousePressed(x, y, button);
if(currentEditingObj == NULL) {
currentEditingObj = universe->findEditObject(x, y);
if (currentEditingObj != NULL) {
//if we found an object, set the of the control to the object so there is no jump
for (int i = 0; i < control.amnt; i++) {
control.fadersPos[i] = currentEditingObj->getParam(i);
}
}
}
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
control.mouseReleased(x, y, button);
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<commit_msg>manual fix of conflict<commit_after>#include "ofApp.h"
//#include "ECURabbitObject.h"
#include "ecuaObject.h"
ofVec3f p;
//--------------------------------------------------------------
void ofApp::setup(){
ofSetVerticalSync(true);
// mesh.load("lofi-bunny.ply");
// cout << cam.getTarget().getPosition() << endl;
universe = new ECUUniverse();
universe->addObject(new ecuaObject(ofVec3f(0, 0, -1000)));
// cam.disableMouseInput();
// cam.set
ofSetSmoothLighting(true);
pointLight2.setDiffuseColor( ofFloatColor(.3, .3, .3));
pointLight2.setSpecularColor(ofFloatColor(10, 10, 10));
pointLight2.setPosition(120, 80, 500);
currentEditingObj = NULL;
// ofAddListener(ofEvent::mousePressed, &control, control::mousePressed)
// ofAddListener(ofEvents().mouseDragged , &control, &ctrls::mouseDragged);
// ofAddListener(ofEvents().mousePressed, &control, &ctrls::mousePressed);
// ofAddListener(ofEvents().mouseReleased, &control, &ctrls::mouseReleased);
// ofAddListener(ofEvents().mouseScrolled, &control, &ctrls::mouseScrolled);
// ofRegisterMouseEvents(control);
}
void ofApp::exit() {
delete universe;
}
//--------------------------------------------------------------
void ofApp::update(){
universe->update();
control.update();
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackgroundGradient(ofColor(64), ofColor(0));
ofSetColor(255);
ofEnableDepthTest();
ofEnableLighting();
pointLight2.enable();
universe->draw();
ofDisableLighting();
ofDisableDepthTest();
if(currentEditingObj != NULL) {
control.draw();
}
}
bool zDown = false;
#define KEY(k, f) if(key == (k)) { (f); }
void ofApp::createObject() {
if(currentEditingObj != NULL) {
//we are now going to turn off, this means that we need to place the object in
currentEditingObj = NULL;
}
else {
ECUBaseObject *obj = new ecuaObject(ofVec3f(universe->pos.x, universe->pos.y, universe->pos.z-1000));
currentEditingObj = obj;
universe->addObject(obj);
}
// creatingObject = !creatingObject;
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
KEY('z', zDown = true)
KEY('a', createObject())
// KEY('s', currentEditingObj = NULL)
cout << "current pos = " << universe->pos << endl;
cout << "there are " << universe->objects.size() << " objects" << endl;
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
zDown = false;
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
control.mouseMoved(x, y);
}
ofVec3f downPosition;
ofQuaternion downOrientation;
float mouseRange = 0;
void ofApp::mouseDragged(int x, int y, int button) {
control.mouseDragged(x, y, button);
for (int i = 0; i < control.amnt; i++) {
currentEditingObj->setParam(i, control.fadersPos[i]);
//if we found an object, set the of the control to the object so there is no jump
}
}
//--------------------------------------------------------------
void ofApp::mouseScrolled(float x, float y) {
if (zDown) {
universe->pos.z+= -y;
}
else {
universe->pos.x-= x;
universe->pos.y+= y;
}
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
mouseRange = mouseX;
downPosition = universe->cam.getPosition(); // ofCamera::getGlobalPosition();
cout << "cam pos = " << downPosition << endl;
downOrientation = universe->cam.getOrientationQuat(); // ofCamera::getGlobalOrientation();
control.mousePressed(x, y, button);
if(currentEditingObj == NULL) {
currentEditingObj = universe->findEditObject(x, y);
if (currentEditingObj != NULL) {
//if we found an object, set the of the control to the object so there is no jump
for (int i = 0; i < control.amnt; i++) {
control.fadersPos[i] = currentEditingObj->getParam(i);
}
}
}
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
control.mouseReleased(x, y, button);
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkHistogramImageToImageMetricTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkGaussianImageSource.h"
#include "itkImage.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkMeanSquaresHistogramImageToImageMetric.h"
#include "itkTranslationTransform.h"
int itkHistogramImageToImageMetricTest(int , char*[] )
{
// Create two simple images.
const unsigned int ImageDimension = 2;
typedef double PixelType;
typedef double CoordinateRepresentationType;
//Allocate Images
typedef itk::Image<PixelType,ImageDimension> MovingImageType;
typedef itk::Image<PixelType,ImageDimension> FixedImageType;
// Declare Gaussian Sources
typedef itk::GaussianImageSource<MovingImageType> MovingImageSourceType;
typedef itk::GaussianImageSource<FixedImageType> FixedImageSourceType;
typedef MovingImageSourceType::Pointer MovingImageSourcePointer;
typedef FixedImageSourceType::Pointer FixedImageSourcePointer;
// Note: the following declarations are classical arrays
unsigned long fixedImageSize[] = {100, 100};
unsigned long movingImageSize[] = {100, 100};
float fixedImageSpacing[] = {1.0f, 1.0f};
float movingImageSpacing[] = {1.0f, 1.0f};
float fixedImageOrigin[] = {0.0f, 0.0f};
float movingImageOrigin[] = {0.0f, 0.0f};
MovingImageSourceType::Pointer movingImageSource =
MovingImageSourceType::New();
FixedImageSourceType::Pointer fixedImageSource =
FixedImageSourceType::New();
movingImageSource->SetSize(movingImageSize);
movingImageSource->SetOrigin(movingImageOrigin);
movingImageSource->SetSpacing(movingImageSpacing);
movingImageSource->SetNormalized(false);
movingImageSource->SetScale(250.0f);
fixedImageSource->SetSize(fixedImageSize);
fixedImageSource->SetOrigin(fixedImageOrigin);
fixedImageSource->SetSpacing(fixedImageSpacing);
fixedImageSource->SetNormalized(false);
fixedImageSource->SetScale(250.0f);
movingImageSource->Update(); // Force the filter to run
fixedImageSource->Update(); // Force the filter to run
MovingImageType::Pointer movingImage = movingImageSource->GetOutput();
FixedImageType::Pointer fixedImage = fixedImageSource->GetOutput();
// Set up the metric.
typedef itk::MeanSquaresHistogramImageToImageMetric<FixedImageType,
MovingImageType> MetricType;
typedef MetricType::TransformType TransformBaseType;
typedef MetricType::ScalesType ScalesType;
typedef MetricType::DerivativeType DerivativeType;
typedef TransformBaseType::ParametersType ParametersType;
MetricType::Pointer metric = MetricType::New();
unsigned int nBins = 256;
MetricType::HistogramType::SizeType histSize;
histSize[0] = nBins;
histSize[1] = nBins;
metric->SetHistogramSize(histSize);
// Plug the images into the metric.
metric->SetFixedImage(fixedImage);
metric->SetMovingImage(movingImage);
// Set up a transform.
typedef itk::TranslationTransform<CoordinateRepresentationType,
ImageDimension> TransformType;
TransformType::Pointer transform = TransformType::New();
metric->SetTransform(transform.GetPointer());
// Set up an interpolator.
typedef itk::LinearInterpolateImageFunction<MovingImageType,
double> InterpolatorType;
InterpolatorType::Pointer interpolator = InterpolatorType::New();
interpolator->SetInputImage(movingImage.GetPointer());
metric->SetInterpolator(interpolator.GetPointer());
// Define the region over which the metric will be computed.
metric->SetFixedImageRegion(fixedImage->GetBufferedRegion());
// Set up transform parameters.
const unsigned int numberOfParameters = transform->GetNumberOfParameters();
ParametersType parameters( numberOfParameters );
for (unsigned int k = 0; k < numberOfParameters; k++)
{
parameters[k] = 0.0;
}
// Set scales for derivative calculation.
ScalesType scales( numberOfParameters );
for (unsigned int k = 0; k < numberOfParameters; k++)
{
scales[k] = 1;
}
const double STEP_LENGTH = 0.001;
metric->SetDerivativeStepLength(STEP_LENGTH);
metric->SetDerivativeStepLengthScales(scales);
try
{
// Initialize the metric.
metric->Initialize();
// Test SetPaddingValue() and GetPaddingValue().
metric->SetPaddingValue(-1);
metric->SetUsePaddingValue(true);
if (metric->GetPaddingValue() != -1)
{
std::cerr << "Incorrect padding value." << std::endl;
return EXIT_FAILURE;
}
// Check to make sure the returned histogram size is the same as histSize.
if (histSize != metric->GetHistogramSize())
{
std::cout << "Incorrect histogram size." << std::endl;
return EXIT_FAILURE;
}
// Check GetDerivativeStepLength().
if (metric->GetDerivativeStepLength() != STEP_LENGTH)
{
std::cout << "Incorrect derivative step length." << std::endl;
return EXIT_FAILURE;
}
// Check GetDerivativeStepLengthScales().
if (metric->GetDerivativeStepLengthScales() != scales)
{
std::cout << "Incorrect scales." << std::endl;
return EXIT_FAILURE;
}
// Do some work
DerivativeType derivatives( numberOfParameters );
MetricType::MeasureType value;
for (double y = -50.0; y <= 50.0; y += 25.0)
{
parameters[1] = y;
for (double x = -50.0; x <= 50.0; x += 25.0)
{
parameters[0] = x;
metric->GetValueAndDerivative (parameters, value, derivatives);
std::cout << "Parameters: " << parameters
<< ", Value: " << value
<< ", Derivatives: " << derivatives << std::endl;
}
}
// Exercise Print() method.
metric->Print(std::cout);
std::cout << "Test passed." << std::endl;
}
catch (itk::ExceptionObject& ex)
{
std::cerr << "Exception caught!" << std::endl;
std::cerr << ex << std::endl;
return EXIT_FAILURE;
}
std::cout << "Exercise the SetLowerBound() and SetUpperBound() methods " << std::endl;
MetricType::MeasurementVectorType lowerBound;
MetricType::MeasurementVectorType upperBound;
metric->SetLowerBound( lowerBound );
metric->SetUpperBound( upperBound );
try
{
// Initialize the metric.
metric->Initialize();
// Exercise Print() method.
metric->Print(std::cout);
std::cout << "Test passed." << std::endl;
}
catch (itk::ExceptionObject& ex)
{
std::cerr << "Exception caught!" << std::endl;
std::cerr << ex << std::endl;
return EXIT_FAILURE;
}
// Force an exception
try
{
ParametersType parameters( 2 );
DerivativeType derivatives( 2 );
ScalesType badScales( 1 );
metric->SetDerivativeStepLengthScales(badScales);
metric->Initialize();
metric->GetDerivative (parameters, derivatives);
}
catch (itk::ExceptionObject &ex)
{
std::cerr << "Expected exception caught!" << std::endl;
std::cerr << ex << std::endl;
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
<commit_msg>ENH: initialize upper and lower bound.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkHistogramImageToImageMetricTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkGaussianImageSource.h"
#include "itkImage.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkMeanSquaresHistogramImageToImageMetric.h"
#include "itkTranslationTransform.h"
int itkHistogramImageToImageMetricTest(int , char*[] )
{
// Create two simple images.
const unsigned int ImageDimension = 2;
typedef double PixelType;
typedef double CoordinateRepresentationType;
//Allocate Images
typedef itk::Image<PixelType,ImageDimension> MovingImageType;
typedef itk::Image<PixelType,ImageDimension> FixedImageType;
// Declare Gaussian Sources
typedef itk::GaussianImageSource<MovingImageType> MovingImageSourceType;
typedef itk::GaussianImageSource<FixedImageType> FixedImageSourceType;
typedef MovingImageSourceType::Pointer MovingImageSourcePointer;
typedef FixedImageSourceType::Pointer FixedImageSourcePointer;
// Note: the following declarations are classical arrays
unsigned long fixedImageSize[] = {100, 100};
unsigned long movingImageSize[] = {100, 100};
float fixedImageSpacing[] = {1.0f, 1.0f};
float movingImageSpacing[] = {1.0f, 1.0f};
float fixedImageOrigin[] = {0.0f, 0.0f};
float movingImageOrigin[] = {0.0f, 0.0f};
MovingImageSourceType::Pointer movingImageSource =
MovingImageSourceType::New();
FixedImageSourceType::Pointer fixedImageSource =
FixedImageSourceType::New();
movingImageSource->SetSize(movingImageSize);
movingImageSource->SetOrigin(movingImageOrigin);
movingImageSource->SetSpacing(movingImageSpacing);
movingImageSource->SetNormalized(false);
movingImageSource->SetScale(250.0f);
fixedImageSource->SetSize(fixedImageSize);
fixedImageSource->SetOrigin(fixedImageOrigin);
fixedImageSource->SetSpacing(fixedImageSpacing);
fixedImageSource->SetNormalized(false);
fixedImageSource->SetScale(250.0f);
movingImageSource->Update(); // Force the filter to run
fixedImageSource->Update(); // Force the filter to run
MovingImageType::Pointer movingImage = movingImageSource->GetOutput();
FixedImageType::Pointer fixedImage = fixedImageSource->GetOutput();
// Set up the metric.
typedef itk::MeanSquaresHistogramImageToImageMetric<FixedImageType,
MovingImageType> MetricType;
typedef MetricType::TransformType TransformBaseType;
typedef MetricType::ScalesType ScalesType;
typedef MetricType::DerivativeType DerivativeType;
typedef TransformBaseType::ParametersType ParametersType;
MetricType::Pointer metric = MetricType::New();
unsigned int nBins = 256;
MetricType::HistogramType::SizeType histSize;
histSize[0] = nBins;
histSize[1] = nBins;
metric->SetHistogramSize(histSize);
// Plug the images into the metric.
metric->SetFixedImage(fixedImage);
metric->SetMovingImage(movingImage);
// Set up a transform.
typedef itk::TranslationTransform<CoordinateRepresentationType,
ImageDimension> TransformType;
TransformType::Pointer transform = TransformType::New();
metric->SetTransform(transform.GetPointer());
// Set up an interpolator.
typedef itk::LinearInterpolateImageFunction<MovingImageType,
double> InterpolatorType;
InterpolatorType::Pointer interpolator = InterpolatorType::New();
interpolator->SetInputImage(movingImage.GetPointer());
metric->SetInterpolator(interpolator.GetPointer());
// Define the region over which the metric will be computed.
metric->SetFixedImageRegion(fixedImage->GetBufferedRegion());
// Set up transform parameters.
const unsigned int numberOfParameters = transform->GetNumberOfParameters();
ParametersType parameters( numberOfParameters );
for (unsigned int k = 0; k < numberOfParameters; k++)
{
parameters[k] = 0.0;
}
// Set scales for derivative calculation.
ScalesType scales( numberOfParameters );
for (unsigned int k = 0; k < numberOfParameters; k++)
{
scales[k] = 1;
}
const double STEP_LENGTH = 0.001;
metric->SetDerivativeStepLength(STEP_LENGTH);
metric->SetDerivativeStepLengthScales(scales);
try
{
// Initialize the metric.
metric->Initialize();
// Test SetPaddingValue() and GetPaddingValue().
metric->SetPaddingValue(-1);
metric->SetUsePaddingValue(true);
if (metric->GetPaddingValue() != -1)
{
std::cerr << "Incorrect padding value." << std::endl;
return EXIT_FAILURE;
}
// Check to make sure the returned histogram size is the same as histSize.
if (histSize != metric->GetHistogramSize())
{
std::cout << "Incorrect histogram size." << std::endl;
return EXIT_FAILURE;
}
// Check GetDerivativeStepLength().
if (metric->GetDerivativeStepLength() != STEP_LENGTH)
{
std::cout << "Incorrect derivative step length." << std::endl;
return EXIT_FAILURE;
}
// Check GetDerivativeStepLengthScales().
if (metric->GetDerivativeStepLengthScales() != scales)
{
std::cout << "Incorrect scales." << std::endl;
return EXIT_FAILURE;
}
// Do some work
DerivativeType derivatives( numberOfParameters );
MetricType::MeasureType value;
for (double y = -50.0; y <= 50.0; y += 25.0)
{
parameters[1] = y;
for (double x = -50.0; x <= 50.0; x += 25.0)
{
parameters[0] = x;
metric->GetValueAndDerivative (parameters, value, derivatives);
std::cout << "Parameters: " << parameters
<< ", Value: " << value
<< ", Derivatives: " << derivatives << std::endl;
}
}
// Exercise Print() method.
metric->Print(std::cout);
std::cout << "Test passed." << std::endl;
}
catch (itk::ExceptionObject& ex)
{
std::cerr << "Exception caught!" << std::endl;
std::cerr << ex << std::endl;
return EXIT_FAILURE;
}
std::cout << "Exercise the SetLowerBound() and SetUpperBound() methods " << std::endl;
MetricType::MeasurementVectorType lowerBound;
lowerBound.Fill(0.0);
MetricType::MeasurementVectorType upperBound;
upperBound.Fill(0.0);
metric->SetLowerBound( lowerBound );
metric->SetUpperBound( upperBound );
try
{
// Initialize the metric.
metric->Initialize();
// Exercise Print() method.
metric->Print(std::cout);
std::cout << "Test passed." << std::endl;
}
catch (itk::ExceptionObject& ex)
{
std::cerr << "Exception caught!" << std::endl;
std::cerr << ex << std::endl;
return EXIT_FAILURE;
}
// Force an exception
try
{
ParametersType parameters( 2 );
DerivativeType derivatives( 2 );
ScalesType badScales( 1 );
metric->SetDerivativeStepLengthScales(badScales);
metric->Initialize();
metric->GetDerivative (parameters, derivatives);
}
catch (itk::ExceptionObject &ex)
{
std::cerr << "Expected exception caught!" << std::endl;
std::cerr << ex << std::endl;
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>#include "musicplayer.h"
#include "musicplaylist.h"
#include "musicsettingmanager.h"
#include "musicconnectionpool.h"
#include "soundcore.h"
#include <qmath.h>
#include <QDebug>
MusicPlayer::MusicPlayer(QObject *parent)
: QObject(parent)
{
m_playlist = 0;
m_music = 0;
m_state = StoppedState;
m_musicEnhanced = EnhancedOff;
m_music = new SoundCore(this);
m_posOnCircle = 0;
m_volumeMusic3D = 0;
setEnaleEffect(false);
connect(&m_timer, SIGNAL(timeout()), SLOT(setTimeOut()));
M_CONNECTION->setValue("MusicPlayer", this);
}
MusicPlayer::~MusicPlayer()
{
delete m_music;
}
MusicPlayer::State MusicPlayer::state() const
{
return m_state;
}
MusicPlaylist *MusicPlayer::playlist() const
{
return m_playlist;
}
qint64 MusicPlayer::duration() const
{
return m_music->totalTime();
}
qint64 MusicPlayer::position() const
{
return m_music->elapsed();
}
int MusicPlayer::volume() const
{
return m_music->volume();
}
bool MusicPlayer::isMuted() const
{
return m_music->isMuted();
}
void MusicPlayer::setMusicEnhanced(Enhanced type)
{
m_musicEnhanced = type;
if(m_musicEnhanced == Music3D)
{
m_volumeMusic3D = volume();
}
else
{
m_music->setVolume(m_volumeMusic3D, m_volumeMusic3D);
setMusicEnhancedCase();
}
}
MusicPlayer::Enhanced MusicPlayer::getMusicEnhanced() const
{
return m_musicEnhanced;
}
QStringList MusicPlayer::supportFormatsString()
{
return QStringList()<< "mp3" << "mp2" << "mp1" << "wav" << "ogg"
<< "flac" << "ac3" << "aac" << "oga" << "pcm";
}
QStringList MusicPlayer::supportFormatsFilterString()
{
return QStringList()<< "*.mp3" << "*.mp2" << "*.mp1" << "*.wav"
<< "*.ogg" << "*.flac" << "*.ac3" << "*.aac"
<< "*.oga" << "*.pcm";
}
QStringList MusicPlayer::supportFormatsFilterDialogString()
{
return QStringList()<< "Mp3 File(*.mp3)" << "Mp2 File(*.mp2)" << "Mp1 File(*.mp1)"
<< "Wav File(*.wav)" << "Ogg File(*.ogg)" << "Flac File(*.flac)"
<< "Ac3 File(*.ac3)" << "Aac File(*.aac)" << "Oga File(*.oga)"
<< "Pcm File(*.pcm)";
}
void MusicPlayer::play()
{
if(m_playlist->isEmpty())
{
m_state = StoppedState;
return;
}
m_state = PlayingState;
Qmmp::State state = m_music->state(); ///Get the current state of play
if(m_currentMedia == m_playlist->currentMediaString() && state == Qmmp::Paused)
{
m_music->pause(); ///When the pause time for recovery
m_timer.start(1000);
return;
}
m_currentMedia = m_playlist->currentMediaString();
///The current playback path
if(!m_music->play(m_currentMedia))
{
m_state = StoppedState;
return;
}
m_timer.start(1000);
///Every second emits a signal change information
emit positionChanged(0);
emit durationChanged( duration() );
////////////////////////////////////////////////
///Read the configuration settings for the sound
int volumn = M_SETTING->value(MusicSettingManager::VolumeChoiced).toInt();
if(volumn != -1)
{
setVolume(volumn);
}
////////////////////////////////////////////////
}
void MusicPlayer::playNext()
{
int index = m_playlist->currentIndex();
m_playlist->setCurrentIndex((++index >= m_playlist->mediaCount()) ? 0 : index);
}
void MusicPlayer::playPrivious()
{
int index = m_playlist->currentIndex();
m_playlist->setCurrentIndex((--index < 0) ? 0 : index );
}
void MusicPlayer::pause()
{
m_music->pause();
m_timer.stop();
m_state = PausedState;
}
void MusicPlayer::stop()
{
m_music->stop();
m_timer.stop();
m_state = StoppedState;
}
void MusicPlayer::setPosition(qint64 position)
{
m_music->seek(position);
}
void MusicPlayer::setVolume(int volume)
{
m_music->setVolume(volume);
}
void MusicPlayer::setMuted(bool muted)
{
m_music->setMuted(muted);
}
void MusicPlayer::setPlaylist(MusicPlaylist *playlist)
{
m_playlist = playlist;
connect(m_playlist, SIGNAL(removeCurrentMedia()), SLOT(removeCurrentMedia()));
}
void MusicPlayer::setTimeOut()
{
emit positionChanged( position() );
if(m_musicEnhanced == Music3D)
{
///3D music settings
setEnaleEffect(false);
m_posOnCircle += 0.5f;
m_music->setVolume(abs(100 * cosf(m_posOnCircle)), abs(100 * sinf(m_posOnCircle * 0.5f)));
}
Qmmp::State state = m_music->state();
if(state != Qmmp::Playing && state != Qmmp::Paused)
{
m_timer.stop();
if(m_playlist->playbackMode() == MusicObject::MC_PlayOnce)
{
m_music->stop();
emit positionChanged(0);
emit stateChanged(StoppedState);
return;
}
m_playlist->setCurrentIndex();
if(m_playlist->playbackMode() == MusicObject::MC_PlayOrder &&
m_playlist->currentIndex() == -1)
{
m_music->stop();
emit positionChanged(0);
emit stateChanged(StoppedState);
return;
}
play();
}
}
void MusicPlayer::setMusicEnhancedCase()
{
switch(m_musicEnhanced)
{
case EnhancedOff:
setEqEffect(MIntList()<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0);
break;
case MusicVocal:
setEqEffect(MIntList()<< 0<< 0<< 4<< 1<< -5<< -1<< 2<< -2<< -4<< -4<< 0);
break;
case MusicNICAM:
setEqEffect(MIntList()<< 6<<-12<<-12<< -9<< -6<< -3<<-12<< -9<< -6<< -3<<-12);
break;
case MusicSubwoofer:
setEqEffect(MIntList()<< 6<< 6<<-10<<-10<< 0<< 0<< -3<< -5<< -7<< -9<<-11);
break;
default:
break;
}
}
void MusicPlayer::removeCurrentMedia()
{
if(m_music)
{
m_timer.stop();
m_music->stop();
}
}
void MusicPlayer::setEqEffect(const MIntList &hz)
{
if(hz.count() != 11)
{
return;
}
EqSettings eq = m_music->eqSettings();
eq.setPreamp(hz[0]);
eq.setEnabled(true);
for(int i=0; i<EqSettings::EQ_BANDS_10; ++i)
{
eq.setGain(i, hz[i + 1]);
}
m_music->setEqSettings(eq);
}
void MusicPlayer::setEnaleEffect(bool enable)
{
if(enable == false)
{
setEqEffect(MIntList()<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0);
}
}
void MusicPlayer::setEqInformation()
{
///Read the equalizer parameters from a configuration file
if(M_SETTING->value(MusicSettingManager::EqualizerEnableChoiced).toInt())
{
setEnaleEffect(true);
QStringList eqValue = M_SETTING->value(MusicSettingManager::EqualizerValueChoiced).toString().split(',');
if(eqValue.count() == 11)
{
MIntList hz;
hz<<eqValue[0].toInt()<<eqValue[1].toInt()<<eqValue[2].toInt()
<<eqValue[3].toInt()<<eqValue[4].toInt()<<eqValue[5].toInt()
<<eqValue[6].toInt()<<eqValue[7].toInt()<<eqValue[8].toInt()
<<eqValue[9].toInt()<<eqValue[10].toInt();
setEqEffect(hz);
}
}
}
<commit_msg>fix set volume error in new core[785412]<commit_after>#include "musicplayer.h"
#include "musicplaylist.h"
#include "musicsettingmanager.h"
#include "musicconnectionpool.h"
#include "soundcore.h"
#include <qmath.h>
#include <QDebug>
MusicPlayer::MusicPlayer(QObject *parent)
: QObject(parent)
{
m_playlist = 0;
m_music = 0;
m_state = StoppedState;
m_musicEnhanced = EnhancedOff;
m_music = new SoundCore(this);
m_posOnCircle = 0;
m_volumeMusic3D = 0;
setEnaleEffect(false);
connect(&m_timer, SIGNAL(timeout()), SLOT(setTimeOut()));
M_CONNECTION->setValue("MusicPlayer", this);
}
MusicPlayer::~MusicPlayer()
{
delete m_music;
}
MusicPlayer::State MusicPlayer::state() const
{
return m_state;
}
MusicPlaylist *MusicPlayer::playlist() const
{
return m_playlist;
}
qint64 MusicPlayer::duration() const
{
return m_music->totalTime();
}
qint64 MusicPlayer::position() const
{
return m_music->elapsed();
}
int MusicPlayer::volume() const
{
return m_music->volume();
}
bool MusicPlayer::isMuted() const
{
return m_music->isMuted();
}
void MusicPlayer::setMusicEnhanced(Enhanced type)
{
m_musicEnhanced = type;
if(m_musicEnhanced == Music3D)
{
m_volumeMusic3D = volume();
}
else
{
m_music->setVolume(m_volumeMusic3D, m_volumeMusic3D);
setMusicEnhancedCase();
}
}
MusicPlayer::Enhanced MusicPlayer::getMusicEnhanced() const
{
return m_musicEnhanced;
}
QStringList MusicPlayer::supportFormatsString()
{
return QStringList()<< "mp3" << "mp2" << "mp1" << "wav" << "ogg"
<< "flac" << "ac3" << "aac" << "oga" << "pcm";
}
QStringList MusicPlayer::supportFormatsFilterString()
{
return QStringList()<< "*.mp3" << "*.mp2" << "*.mp1" << "*.wav"
<< "*.ogg" << "*.flac" << "*.ac3" << "*.aac"
<< "*.oga" << "*.pcm";
}
QStringList MusicPlayer::supportFormatsFilterDialogString()
{
return QStringList()<< "Mp3 File(*.mp3)" << "Mp2 File(*.mp2)" << "Mp1 File(*.mp1)"
<< "Wav File(*.wav)" << "Ogg File(*.ogg)" << "Flac File(*.flac)"
<< "Ac3 File(*.ac3)" << "Aac File(*.aac)" << "Oga File(*.oga)"
<< "Pcm File(*.pcm)";
}
void MusicPlayer::play()
{
if(m_playlist->isEmpty())
{
m_state = StoppedState;
return;
}
m_state = PlayingState;
Qmmp::State state = m_music->state(); ///Get the current state of play
if(m_currentMedia == m_playlist->currentMediaString() && state == Qmmp::Paused)
{
m_music->pause(); ///When the pause time for recovery
m_timer.start(1000);
return;
}
m_currentMedia = m_playlist->currentMediaString();
///The current playback path
if(!m_music->play(m_currentMedia))
{
m_state = StoppedState;
return;
}
m_timer.start(1000);
///Every second emits a signal change information
emit positionChanged(0);
emit durationChanged( duration() );
////////////////////////////////////////////////
///Read the configuration settings for the sound
int volumn = M_SETTING->value(MusicSettingManager::VolumeChoiced).toInt();
if(volumn != -1)
{
setVolume(volumn);
}
////////////////////////////////////////////////
}
void MusicPlayer::playNext()
{
int index = m_playlist->currentIndex();
m_playlist->setCurrentIndex((++index >= m_playlist->mediaCount()) ? 0 : index);
}
void MusicPlayer::playPrivious()
{
int index = m_playlist->currentIndex();
m_playlist->setCurrentIndex((--index < 0) ? 0 : index );
}
void MusicPlayer::pause()
{
m_music->pause();
m_timer.stop();
m_state = PausedState;
}
void MusicPlayer::stop()
{
m_music->stop();
m_timer.stop();
m_state = StoppedState;
}
void MusicPlayer::setPosition(qint64 position)
{
m_music->seek(position);
}
void MusicPlayer::setVolume(int volume)
{
m_volumeMusic3D = volume;
m_music->setVolume(volume);
}
void MusicPlayer::setMuted(bool muted)
{
m_volumeMusic3D = muted ? 0 : m_music->volume();
m_music->setMuted(muted);
}
void MusicPlayer::setPlaylist(MusicPlaylist *playlist)
{
m_playlist = playlist;
connect(m_playlist, SIGNAL(removeCurrentMedia()), SLOT(removeCurrentMedia()));
}
void MusicPlayer::setTimeOut()
{
emit positionChanged( position() );
if(m_musicEnhanced == Music3D && !m_music->isMuted())
{
///3D music settings
setEnaleEffect(false);
m_posOnCircle += 0.5f;
m_music->setVolume(abs(100 * cosf(m_posOnCircle)), abs(100 * sinf(m_posOnCircle * 0.5f)));
}
Qmmp::State state = m_music->state();
if(state != Qmmp::Playing && state != Qmmp::Paused)
{
m_timer.stop();
if(m_playlist->playbackMode() == MusicObject::MC_PlayOnce)
{
m_music->stop();
emit positionChanged(0);
emit stateChanged(StoppedState);
return;
}
m_playlist->setCurrentIndex();
if(m_playlist->playbackMode() == MusicObject::MC_PlayOrder &&
m_playlist->currentIndex() == -1)
{
m_music->stop();
emit positionChanged(0);
emit stateChanged(StoppedState);
return;
}
play();
}
}
void MusicPlayer::setMusicEnhancedCase()
{
switch(m_musicEnhanced)
{
case EnhancedOff:
setEqEffect(MIntList()<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0);
break;
case MusicVocal:
setEqEffect(MIntList()<< 0<< 0<< 4<< 1<< -5<< -1<< 2<< -2<< -4<< -4<< 0);
break;
case MusicNICAM:
setEqEffect(MIntList()<< 6<<-12<<-12<< -9<< -6<< -3<<-12<< -9<< -6<< -3<<-12);
break;
case MusicSubwoofer:
setEqEffect(MIntList()<< 6<< 6<<-10<<-10<< 0<< 0<< -3<< -5<< -7<< -9<<-11);
break;
default:
break;
}
}
void MusicPlayer::removeCurrentMedia()
{
if(m_music)
{
m_timer.stop();
m_music->stop();
}
}
void MusicPlayer::setEqEffect(const MIntList &hz)
{
if(hz.count() != 11)
{
return;
}
EqSettings eq = m_music->eqSettings();
eq.setPreamp(hz[0]);
eq.setEnabled(true);
for(int i=0; i<EqSettings::EQ_BANDS_10; ++i)
{
eq.setGain(i, hz[i + 1]);
}
m_music->setEqSettings(eq);
}
void MusicPlayer::setEnaleEffect(bool enable)
{
if(enable == false)
{
setEqEffect(MIntList()<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0);
}
}
void MusicPlayer::setEqInformation()
{
///Read the equalizer parameters from a configuration file
if(M_SETTING->value(MusicSettingManager::EqualizerEnableChoiced).toInt())
{
setEnaleEffect(true);
QStringList eqValue = M_SETTING->value(MusicSettingManager::EqualizerValueChoiced).toString().split(',');
if(eqValue.count() == 11)
{
MIntList hz;
hz<<eqValue[0].toInt()<<eqValue[1].toInt()<<eqValue[2].toInt()
<<eqValue[3].toInt()<<eqValue[4].toInt()<<eqValue[5].toInt()
<<eqValue[6].toInt()<<eqValue[7].toInt()<<eqValue[8].toInt()
<<eqValue[9].toInt()<<eqValue[10].toInt();
setEqEffect(hz);
}
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkQuadEdgeTest1.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "itkQuadEdge.h"
#include <iostream>
int itkQuadEdgeTest1( int , char* [] )
{
typedef itk::QuadEdge QuadEdgeType;
// Tests for the GetRot() SetRot() methods
{ // create a local scope for these tests
QuadEdgeType * quadEdge1 = new QuadEdgeType;
QuadEdgeType * quadEdge2 = new QuadEdgeType;
QuadEdgeType * quadEdge3 = new QuadEdgeType;
quadEdge1->GetRot();
// Verify that it can be set.
quadEdge1->SetRot( quadEdge2 );
if( quadEdge1->GetRot() != quadEdge2 )
{
std::cerr << "Error in SetRot() / GetRot() " << std::endl;
return EXIT_FAILURE;
}
// Verify that it can be changed.
quadEdge1->SetRot( quadEdge3 );
if( quadEdge1->GetRot() != quadEdge3 )
{
std::cerr << "Error in SetRot() / GetRot() " << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed" << std::endl;
delete quadEdge1;
delete quadEdge2;
delete quadEdge3;
} // end of local scope for tests
// Tests for the GetOnext() SetOnext() methods
{ // create a local scope for these tests
QuadEdgeType * quadEdge1 = new QuadEdgeType;
QuadEdgeType * quadEdge2 = new QuadEdgeType;
QuadEdgeType * quadEdge3 = new QuadEdgeType;
quadEdge1->GetOnext();
// Verify that it can be set.
quadEdge1->SetOnext( quadEdge2 );
if( quadEdge1->GetOnext() != quadEdge2 )
{
std::cerr << "Error in SetOnext() / GetOnext() " << std::endl;
return EXIT_FAILURE;
}
// Verify that it can be changed.
quadEdge1->SetOnext( quadEdge3 );
if( quadEdge1->GetOnext() != quadEdge3 )
{
std::cerr << "Error in SetOnext() / GetOnext() " << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed" << std::endl;
delete quadEdge1;
delete quadEdge2;
delete quadEdge3;
} // end of local scope for tests
// Tests for the IsEdgeIn*() methods
{ // create a local scope for these tests
QuadEdgeType * quadEdge1 = new QuadEdgeType;
QuadEdgeType * quadEdge2 = new QuadEdgeType;
bool itis = quadEdge1->IsEdgeInOnextRing( quadEdge2 );
if( itis )
{
}
delete quadEdge1;
delete quadEdge2;
} // end of local scope for tests
return EXIT_SUCCESS;
}
<commit_msg>ENH: Adding tests for const versions of GetRot() and GetOnext().<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkQuadEdgeTest1.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "itkQuadEdge.h"
#include <iostream>
int itkQuadEdgeTest1( int , char* [] )
{
typedef itk::QuadEdge QuadEdgeType;
// Tests for the GetRot() SetRot() methods
{ // create a local scope for these tests
QuadEdgeType * quadEdge1 = new QuadEdgeType;
QuadEdgeType * quadEdge2 = new QuadEdgeType;
QuadEdgeType * quadEdge3 = new QuadEdgeType;
const QuadEdgeType * quadEdge1c = quadEdge1;
quadEdge1->GetRot();
// Verify that it can be set.
quadEdge1->SetRot( quadEdge2 );
if( quadEdge1->GetRot() != quadEdge2 )
{
std::cerr << "Error in SetRot() / GetRot() " << std::endl;
return EXIT_FAILURE;
}
// Test the const version
if( quadEdge1c->GetRot() != quadEdge2 )
{
std::cerr << "Error in SetRot() / GetRot() " << std::endl;
return EXIT_FAILURE;
}
// Verify that it can be changed.
quadEdge1->SetRot( quadEdge3 );
if( quadEdge1->GetRot() != quadEdge3 )
{
std::cerr << "Error in SetRot() / GetRot() " << std::endl;
return EXIT_FAILURE;
}
// Test the const version
if( quadEdge1c->GetRot() != quadEdge2 )
{
std::cerr << "Error in SetRot() / GetRot() " << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed" << std::endl;
delete quadEdge1;
delete quadEdge2;
delete quadEdge3;
} // end of local scope for tests
// Tests for the GetOnext() SetOnext() methods
{ // create a local scope for these tests
QuadEdgeType * quadEdge1 = new QuadEdgeType;
QuadEdgeType * quadEdge2 = new QuadEdgeType;
QuadEdgeType * quadEdge3 = new QuadEdgeType;
const QuadEdgeType * quadEdge1c = quadEdge1;
quadEdge1->GetOnext();
// Verify that it can be set.
quadEdge1->SetOnext( quadEdge2 );
if( quadEdge1->GetOnext() != quadEdge2 )
{
std::cerr << "Error in SetOnext() / GetOnext() " << std::endl;
return EXIT_FAILURE;
}
// Test the const version
if( quadEdge1c->GetOnext() != quadEdge2 )
{
std::cerr << "Error in SetOnext() / GetOnext() " << std::endl;
return EXIT_FAILURE;
}
// Verify that it can be changed.
quadEdge1->SetOnext( quadEdge3 );
if( quadEdge1->GetOnext() != quadEdge3 )
{
std::cerr << "Error in SetOnext() / GetOnext() " << std::endl;
return EXIT_FAILURE;
}
// Test the const version
if( quadEdge1c->GetOnext() != quadEdge2 )
{
std::cerr << "Error in SetOnext() / GetOnext() " << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed" << std::endl;
delete quadEdge1;
delete quadEdge2;
delete quadEdge3;
} // end of local scope for tests
// Tests for the IsEdgeIn*() methods
{ // create a local scope for these tests
QuadEdgeType * quadEdge1 = new QuadEdgeType;
QuadEdgeType * quadEdge2 = new QuadEdgeType;
bool itis = quadEdge1->IsEdgeInOnextRing( quadEdge2 );
if( itis )
{
}
delete quadEdge1;
delete quadEdge2;
} // end of local scope for tests
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "CinderImGui.h"
#include "imgui/imgui.h"
#include "imgui/imgui_internal.h"
#include "imgui_user.h"
#include "Choreograph.h"
#include "Channel.hpp"
using namespace ci;
using namespace ci::app;
using namespace std;
void drawChannelGui(ch::Channel<float> &channel) {
ImDrawList* draw_list = ImGui::GetWindowDrawList();
for (auto i = 0; i < channel.keys().size(); i += 1) {
ui::SliderFloat(("Value " + to_string(i)).c_str(), &channel.mutableKeys()[i].value, -100.0f, 100.0f);
if (i > 0 && i < channel.keys().size() - 1) {
auto *previous = &channel.mutableKeys()[i - 1];
auto *current = &channel.mutableKeys()[i];
auto *next = &channel.mutableKeys()[i + 1];
auto timef = (float)current->time;
if (ui::SliderFloat(("Time " + to_string(i)).c_str(), &timef, previous->time, next->time)) {
current->time = timef;
}
}
}
auto const outer_size = vec2(ui::GetWindowWidth(), 100.0f);
auto const padding = vec2(20, 10);
auto const top_left = vec2(0);
auto const bottom_right = outer_size - padding;
auto const value_range = vec2(-100.0f, 100.0f);
auto const time_range = vec2(0, channel.duration());
auto const cursor_position = vec2(ui::GetCursorScreenPos());
auto color = vec4(1.0f,1.0f,0.4f,1.0f);
auto color32 = ImColor(color);
auto background_color = ImColor(vec4(0.3, 0.3, 0.3f, 1.0f));
auto const value_to_space = [=] (const ci::vec2 &values) {
auto x = values.x / channel.duration();
auto y = (values.y - value_range.x) / (value_range.y - value_range.x);
return mix(top_left, bottom_right, vec2(x, y)) + cursor_position;
};
auto const space_to_value = [=] (const ci::vec2 &space) {
auto pos = space - cursor_position;
auto normalized = pos / (bottom_right - top_left);
return mix(vec2(time_range.x, value_range.x), vec2(time_range.y, value_range.y), normalized);
};
draw_list->AddRectFilled(cursor_position + top_left, cursor_position + bottom_right, background_color);
auto id = 0;
for (auto &key: channel.mutableKeys()) {
auto pos = value_to_space(vec2(key.time, key.value));
auto radius = 12.0f;
// Use an invisible button to handle interaction with circles.
ui::SetCursorScreenPos(pos - vec2(radius));
ui::PushID("temp_key");
ui::InvisibleButton("", vec2(radius * 2.0f));
ui::SetCursorScreenPos(cursor_position);
if (ui::IsItemHovered()) {
// Maybe use DragBehavior to handle changing value? Mapping back from space to value
// ui::DragBehavior(<#const ImRect &frame_bb#>, <#ImGuiID id#>, <#float *v#>, <#float v_speed#>, <#float v_min#>, <#float v_max#>, <#int decimal_precision#>, <#float power#>)
// Or use is mouse dragging and handle change more directly?
if (ui::IsMouseDragging()) {
auto delta = vec2(ui::GetIO().MouseDelta);
auto value = space_to_value(pos + delta);
console() << "Changing value of " << id << " with deltas: " << delta << ", new value: " << value << " mouse: " << vec2(ui::GetMousePos()) << endl;
key.time = value.x;
key.value = value.y;
}
}
ui::PopID();
id += 1;
draw_list->AddCircle(pos, radius, color32);
}
ui::Dummy(outer_size);
}
class TimelineEditorApp : public App {
public:
void setup() override;
void mouseDown( MouseEvent event ) override;
void update() override;
void draw() override;
private:
ch::Channel<float> _channel;
};
void TimelineEditorApp::setup()
{
ui::initialize();
_channel.insertKey(10.0f, 0);
_channel.insertKey(20.0f, 1);
_channel.insertKey(30.0f, 3);
CI_ASSERT(_channel.duration() == 3);
}
void TimelineEditorApp::mouseDown( MouseEvent event )
{
}
void TimelineEditorApp::update()
{
ui::Text("Hello");
drawChannelGui(_channel);
}
void TimelineEditorApp::draw()
{
gl::clear( Color( 0, 0, 0 ) );
auto t = std::fmod(getElapsedSeconds(), _channel.duration());
gl::drawSolidCircle(getWindowCenter() + vec2(0, _channel.value(t)), 24.0f);
}
CINDER_APP( TimelineEditorApp, RendererGl )
<commit_msg>Better dragging using ui::IsItemActive.<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "CinderImGui.h"
#include "imgui/imgui.h"
#include "imgui/imgui_internal.h"
#include "imgui_user.h"
#include "Choreograph.h"
#include "Channel.hpp"
using namespace ci;
using namespace ci::app;
using namespace std;
void drawChannelGui(ch::Channel<float> &channel) {
ImDrawList* draw_list = ImGui::GetWindowDrawList();
for (auto i = 0; i < channel.keys().size(); i += 1) {
ui::SliderFloat(("Value " + to_string(i)).c_str(), &channel.mutableKeys()[i].value, -100.0f, 100.0f);
if (i > 0 && i < channel.keys().size() - 1) {
auto *previous = &channel.mutableKeys()[i - 1];
auto *current = &channel.mutableKeys()[i];
auto *next = &channel.mutableKeys()[i + 1];
auto timef = (float)current->time;
if (ui::SliderFloat(("Time " + to_string(i)).c_str(), &timef, previous->time, next->time)) {
current->time = timef;
}
}
}
auto const outer_size = vec2(ui::GetWindowWidth(), 100.0f);
auto const padding = vec2(20, 10);
auto const top_left = vec2(0);
auto const bottom_right = outer_size - padding;
auto const value_range = vec2(-100.0f, 100.0f);
auto const time_range = vec2(0, channel.duration());
auto const cursor_position = vec2(ui::GetCursorScreenPos());
auto color = vec4(1.0f,1.0f,0.4f,1.0f);
auto color32 = ImColor(color);
auto background_color = ImColor(vec4(0.3, 0.3, 0.3f, 1.0f));
auto const value_to_space = [=] (const ci::vec2 &values) {
auto x = values.x / channel.duration();
auto y = (values.y - value_range.x) / (value_range.y - value_range.x);
return mix(top_left, bottom_right, vec2(x, y)) + cursor_position;
};
auto const space_to_value = [=] (const ci::vec2 &space) {
auto pos = space - cursor_position;
auto normalized = pos / (bottom_right - top_left);
return mix(vec2(time_range.x, value_range.x), vec2(time_range.y, value_range.y), normalized);
};
draw_list->AddRectFilled(cursor_position + top_left, cursor_position + bottom_right, background_color);
auto id = 0;
for (auto &key: channel.mutableKeys()) {
auto pos = value_to_space(vec2(key.time, key.value));
auto radius = 12.0f;
// Use an invisible button to handle interaction with circles.
ui::SetCursorScreenPos(pos - vec2(radius));
ui::PushID(("temp_key" + to_string(id)).c_str());
ui::InvisibleButton("", vec2(radius * 2.0f));
ui::SetCursorScreenPos(cursor_position);
if (ui::IsItemActive()) {
if (ui::IsMouseDown(0)) {
auto value = space_to_value(ui::GetMousePos());
console() << "Changing value of " << id << ", new value: " << value << " mouse: " << vec2(ui::GetMousePos()) << endl;
key.time = value.x;
key.value = value.y;
}
}
ui::PopID();
id += 1;
draw_list->AddCircle(pos, radius, color32);
}
ui::Dummy(outer_size);
}
class TimelineEditorApp : public App {
public:
void setup() override;
void mouseDown( MouseEvent event ) override;
void update() override;
void draw() override;
private:
ch::Channel<float> _channel;
};
void TimelineEditorApp::setup()
{
ui::initialize();
_channel.insertKey(10.0f, 0);
_channel.insertKey(20.0f, 1);
_channel.insertKey(30.0f, 3);
CI_ASSERT(_channel.duration() == 3);
}
void TimelineEditorApp::mouseDown( MouseEvent event )
{
}
void TimelineEditorApp::update()
{
ui::Text("Hello");
drawChannelGui(_channel);
}
void TimelineEditorApp::draw()
{
gl::clear( Color( 0, 0, 0 ) );
auto t = std::fmod(getElapsedSeconds(), _channel.duration());
gl::drawSolidCircle(getWindowCenter() + vec2(0, _channel.value(t)), 24.0f);
}
CINDER_APP( TimelineEditorApp, RendererGl )
<|endoftext|> |
<commit_before>/*====================================================================
Copyright(c) 2016 Adam Rankin
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.
====================================================================*/
// Local includes
#include "pch.h"
#include "IGTLinkClient.h"
#include "IGTCommon.h"
#include "TrackedFrameMessage.h"
// IGT includes
#include "igtlCommandMessage.h"
#include "igtlCommon.h"
#include "igtlMessageHeader.h"
#include "igtlOSUtil.h"
#include "igtlStatusMessage.h"
// STD includes
#include <chrono>
#include <regex>
// Windows includes
#include <collection.h>
#include <pplawait.h>
#include <ppltasks.h>
#include <robuffer.h>
using namespace Concurrency;
using namespace Windows::Foundation;
using namespace Platform::Collections;
using namespace Windows::Storage::Streams;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::Data::Xml::Dom;
namespace UWPOpenIGTLink
{
const int IGTLinkClient::CLIENT_SOCKET_TIMEOUT_MSEC = 500;
const uint32 IGTLinkClient::MESSAGE_LIST_MAX_SIZE = 200;
//----------------------------------------------------------------------------
IGTLinkClient::IGTLinkClient()
: m_igtlMessageFactory(igtl::MessageFactory::New())
, m_clientSocket(igtl::ClientSocket::New())
{
m_igtlMessageFactory->AddMessageType("TRACKEDFRAME", (igtl::MessageFactory::PointerToMessageBaseNew)&igtl::TrackedFrameMessage::New);
ServerHost = L"127.0.0.1";
ServerPort = 18944;
ServerIGTLVersion = IGTL_HEADER_VERSION_2;
m_frameSize.assign(3, 0);
}
//----------------------------------------------------------------------------
IGTLinkClient::~IGTLinkClient()
{
Disconnect();
auto disconnectTask = concurrency::create_task([this]()
{
while (Connected)
{
std::this_thread::sleep_for(std::chrono::milliseconds(33));
}
});
disconnectTask.wait();
}
//----------------------------------------------------------------------------
IAsyncOperation<bool>^ IGTLinkClient::ConnectAsync(double timeoutSec)
{
Disconnect();
m_receiverPumpTokenSource = cancellation_token_source();
return create_async([ = ]() -> bool
{
const int retryDelaySec = 1.0;
int errorCode = 1;
auto start = std::chrono::high_resolution_clock::now();
while (errorCode != 0)
{
std::wstring wideStr(ServerHost->Begin());
std::string str(wideStr.begin(), wideStr.end());
errorCode = m_clientSocket->ConnectToServer(str.c_str(), ServerPort);
if (errorCode == 0)
{
break;
}
std::chrono::duration<double, std::milli> timeDiff = std::chrono::high_resolution_clock::now() - start;
if (timeDiff.count() > timeoutSec * 1000)
{
// time is up
break;
}
std::this_thread::sleep_for(std::chrono::seconds(retryDelaySec));
}
if (errorCode != 0)
{
return false;
}
m_clientSocket->SetTimeout(CLIENT_SOCKET_TIMEOUT_MSEC);
m_clientSocket->SetReceiveBlocking(true);
// We're connected, start the data receiver thread
create_task([this]()
{
DataReceiverPump(this, m_receiverPumpTokenSource.get_token());
});
return true;
});
}
//----------------------------------------------------------------------------
void IGTLinkClient::Disconnect()
{
m_receiverPumpTokenSource.cancel();
{
std::lock_guard<std::mutex> guard(m_socketMutex);
m_clientSocket->CloseSocket();
}
}
//----------------------------------------------------------------------------
TrackedFrame^ IGTLinkClient::GetTrackedFrame(double lastKnownTimestamp)
{
igtl::TrackedFrameMessage::Pointer trackedFrameMsg = nullptr;
{
// Retrieve the next available tracked frame reply
std::lock_guard<std::mutex> guard(m_messageListMutex);
for (auto replyIter = m_receivedMessages.rbegin(); replyIter != m_receivedMessages.rend(); ++replyIter)
{
if (typeid(*(*replyIter)) == typeid(igtl::TrackedFrameMessage))
{
trackedFrameMsg = dynamic_cast<igtl::TrackedFrameMessage*>((*replyIter).GetPointer());
break;
}
}
if (trackedFrameMsg == nullptr)
{
// No message found
return nullptr;
}
}
auto ts = igtl::TimeStamp::New();
trackedFrameMsg->GetTimeStamp(ts);
if (ts->GetTimeStamp() <= lastKnownTimestamp)
{
// No new messages since requested timestamp
if (m_receivedUWPMessages.find(lastKnownTimestamp) != m_receivedUWPMessages.end())
{
return m_receivedUWPMessages.at(lastKnownTimestamp);
}
return nullptr;
}
auto frame = ref new TrackedFrame();
m_receivedUWPMessages[ts->GetTimeStamp()] = frame;
// Tracking/other related fields
for (auto& pair : trackedFrameMsg->GetMetaData())
{
std::wstring keyWideStr(pair.first.begin(), pair.first.end());
std::wstring valueWideStr(pair.second.begin(), pair.second.end());
frame->SetCustomFrameField(keyWideStr, valueWideStr);
}
for (auto& pair : trackedFrameMsg->GetCustomFrameFields())
{
frame->SetCustomFrameField(pair.first, pair.second);
}
// Image related fields
frame->SetFrameSize(trackedFrameMsg->GetFrameSize());
frame->Timestamp = ts->GetTimeStamp();
frame->ImageSizeBytes = trackedFrameMsg->GetImageSizeInBytes();
frame->SetImageData(trackedFrameMsg->GetImage());
frame->NumberOfComponents = trackedFrameMsg->GetNumberOfComponents();
frame->ScalarType = trackedFrameMsg->GetScalarType();
frame->SetEmbeddedImageTransform(trackedFrameMsg->GetEmbeddedImageTransform());
frame->ImageType = (uint16)trackedFrameMsg->GetImageType();
frame->ImageOrientation = (uint16)trackedFrameMsg->GetImageOrientation();
frame->SetFrameTransformsInternal(trackedFrameMsg->GetFrameTransforms());
return frame;
}
//----------------------------------------------------------------------------
Command^ IGTLinkClient::GetCommand(double lastKnownTimestamp)
{
igtl::MessageBase::Pointer igtMessage = nullptr;
{
// Retrieve the next available tracked frame reply
std::lock_guard<std::mutex> guard(m_messageListMutex);
for (auto replyIter = m_receivedMessages.rbegin(); replyIter != m_receivedMessages.rend(); ++replyIter)
{
if (typeid(*(*replyIter)) == typeid(igtl::RTSCommandMessage))
{
igtMessage = *replyIter;
break;
}
}
if (igtMessage == nullptr)
{
return nullptr;
}
}
auto ts = igtl::TimeStamp::New();
igtMessage->GetTimeStamp(ts);
if (ts->GetTimeStamp() <= lastKnownTimestamp)
{
return nullptr;
}
auto cmd = ref new Command();
auto cmdMsg = dynamic_cast<igtl::RTSCommandMessage*>(igtMessage.GetPointer());
cmd->CommandContent = ref new Platform::String(std::wstring(cmdMsg->GetCommandContent().begin(), cmdMsg->GetCommandContent().end()).c_str());
cmd->CommandName = ref new Platform::String(std::wstring(cmdMsg->GetCommandName().begin(), cmdMsg->GetCommandName().end()).c_str());
cmd->OriginalCommandId = cmdMsg->GetCommandId();
cmd->Timestamp = lastKnownTimestamp;
XmlDocument^ doc = ref new XmlDocument();
doc->LoadXml(cmd->CommandContent);
for (IXmlNode^ node : doc->ChildNodes)
{
if (dynamic_cast<Platform::String^>(node->NodeName) == L"Result")
{
cmd->Result = (dynamic_cast<Platform::String^>(node->NodeValue) == L"true");
break;
}
}
if (!cmd->Result)
{
bool found(false);
// Parse for the error string
for (IXmlNode^ node : doc->ChildNodes)
{
if (dynamic_cast<Platform::String^>(node->NodeName) == L"Error")
{
cmd->ErrorString = dynamic_cast<Platform::String^>(node->NodeValue);
found = true;
break;
}
}
if (!found)
{
// TODO : quiet error reporting
}
}
for (auto& pair : cmdMsg->GetMetaData())
{
std::wstring keyWideStr(pair.first.begin(), pair.first.end());
std::wstring valueWideStr(pair.second.begin(), pair.second.end());
cmd->Parameters->Insert(ref new Platform::String(keyWideStr.c_str()), ref new Platform::String(valueWideStr.c_str()));
}
return cmd;
}
//----------------------------------------------------------------------------
bool IGTLinkClient::SendMessage(igtl::MessageBase::Pointer packedMessage)
{
int success = 0;
{
std::lock_guard<std::mutex> guard(m_socketMutex);
success = m_clientSocket->Send(packedMessage->GetBufferPointer(), packedMessage->GetBufferSize());
}
if (!success)
{
std::cerr << "OpenIGTLink client couldn't send message to server." << std::endl;
return false;
}
return true;
}
//----------------------------------------------------------------------------
bool IGTLinkClient::SendMessage(MessageBasePointerPtr messageBasePointerPtr)
{
igtl::MessageBase::Pointer* messageBasePointer = (igtl::MessageBase::Pointer*)(messageBasePointerPtr);
return SendMessage(*messageBasePointer);
}
//----------------------------------------------------------------------------
void IGTLinkClient::DataReceiverPump(IGTLinkClient^ self, concurrency::cancellation_token token)
{
LOG_TRACE(L"IGTLinkClient::DataReceiverPump");
while (!token.is_canceled())
{
auto headerMsg = self->m_igtlMessageFactory->CreateHeaderMessage(IGTL_HEADER_VERSION_1);
// Receive generic header from the socket
int numOfBytesReceived = 0;
{
std::lock_guard<std::mutex> guard(self->m_socketMutex);
if (!self->m_clientSocket->GetConnected())
{
// We've become disconnected while waiting for the socket, we're done here!
return;
}
numOfBytesReceived = self->m_clientSocket->Receive(headerMsg->GetBufferPointer(), headerMsg->GetBufferSize());
}
if (numOfBytesReceived == 0 // No message received
|| numOfBytesReceived != headerMsg->GetBufferSize() // Received data is not as we expected
)
{
// Failed to receive data, maybe the socket is disconnected
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
}
int c = headerMsg->Unpack(1);
if (!(c & igtl::MessageHeader::UNPACK_HEADER))
{
std::cerr << "Failed to receive message (invalid header)" << std::endl;
continue;
}
igtl::MessageBase::Pointer bodyMsg = nullptr;
try
{
bodyMsg = self->m_igtlMessageFactory->CreateReceiveMessage(headerMsg);
}
catch (const std::exception&)
{
// Message header was not correct, skip this message
// Will be impossible to tell if the body of this message is in the socket... this is a pretty bad corruption.
// Force re-connect?
LOG_TRACE("Corruption in the message header. Serious error.");
continue;
}
if (bodyMsg.IsNull())
{
LOG_TRACE("Unable to create message of type: " << headerMsg->GetMessageType());
continue;
}
// Accept all messages but status messages, they are used as a keep alive mechanism
if (typeid(*bodyMsg) != typeid(igtl::StatusMessage))
{
{
std::lock_guard<std::mutex> guard(self->m_socketMutex);
if (!self->m_clientSocket->GetConnected())
{
// We've become disconnected while waiting for the socket, we're done here!
return;
}
self->m_clientSocket->Receive(bodyMsg->GetBufferBodyPointer(), bodyMsg->GetBufferBodySize());
}
int c = bodyMsg->Unpack(1);
if (!(c & igtl::MessageHeader::UNPACK_BODY))
{
LOG_TRACE("Failed to receive reply (invalid body)");
continue;
}
{
// save reply
std::lock_guard<std::mutex> guard(self->m_messageListMutex);
self->m_receivedMessages.push_back(bodyMsg);
}
}
else
{
std::lock_guard<std::mutex> guard(self->m_socketMutex);
self->m_clientSocket->Skip(headerMsg->GetBodySizeToRead(), 0);
}
if (self->m_receivedMessages.size() > MESSAGE_LIST_MAX_SIZE)
{
std::lock_guard<std::mutex> guard(self->m_messageListMutex);
// erase the front N results
uint32 toErase = self->m_receivedMessages.size() - MESSAGE_LIST_MAX_SIZE;
self->m_receivedMessages.erase(self->m_receivedMessages.begin(), self->m_receivedMessages.begin() + toErase);
}
auto oldestTimestamp = self->GetOldestTrackedFrameTimestamp();
if (oldestTimestamp > 0)
{
for (auto it = self->m_receivedUWPMessages.begin(); it != self->m_receivedUWPMessages.end();)
{
if (it->first < oldestTimestamp)
{
it = self->m_receivedUWPMessages.erase(it);
}
else
{
++it;
}
}
}
}
return;
}
//----------------------------------------------------------------------------
int IGTLinkClient::SocketReceive(void* data, int length)
{
std::lock_guard<std::mutex> guard(m_socketMutex);
return m_clientSocket->Receive(data, length);
}
//----------------------------------------------------------------------------
double IGTLinkClient::GetLatestTrackedFrameTimestamp()
{
// Retrieve the next available tracked frame reply
std::lock_guard<std::mutex> guard(m_messageListMutex);
for (auto replyIter = m_receivedMessages.rbegin(); replyIter != m_receivedMessages.rend(); ++replyIter)
{
if (typeid(*(*replyIter)) == typeid(igtl::TrackedFrameMessage))
{
igtl::TimeStamp::Pointer ts = igtl::TimeStamp::New();
(*replyIter)->GetTimeStamp(ts);
return ts->GetTimeStamp();
}
}
return -1.0;
}
//----------------------------------------------------------------------------
double IGTLinkClient::GetOldestTrackedFrameTimestamp()
{
// Retrieve the next available tracked frame reply
std::lock_guard<std::mutex> guard(m_messageListMutex);
for (auto replyIter = m_receivedMessages.begin(); replyIter != m_receivedMessages.end(); ++replyIter)
{
if (typeid(*(*replyIter)) == typeid(igtl::TrackedFrameMessage))
{
igtl::TimeStamp::Pointer ts = igtl::TimeStamp::New();
(*replyIter)->GetTimeStamp(ts);
return ts->GetTimeStamp();
}
}
return -1.0;
}
//----------------------------------------------------------------------------
int IGTLinkClient::ServerPort::get()
{
return m_serverPort;
}
//----------------------------------------------------------------------------
void IGTLinkClient::ServerPort::set(int arg)
{
m_serverPort = arg;
}
//----------------------------------------------------------------------------
Platform::String^ IGTLinkClient::ServerHost::get()
{
return m_serverHost;
}
//----------------------------------------------------------------------------
void IGTLinkClient::ServerHost::set(Platform::String^ arg)
{
m_serverHost = arg;
}
//----------------------------------------------------------------------------
int IGTLinkClient::ServerIGTLVersion::get()
{
return m_serverIGTLVersion;
}
//----------------------------------------------------------------------------
void IGTLinkClient::ServerIGTLVersion::set(int arg)
{
m_serverIGTLVersion = arg;
}
//----------------------------------------------------------------------------
bool IGTLinkClient::Connected::get()
{
return m_clientSocket->GetConnected();
}
}<commit_msg>Adding quiet reporting<commit_after>/*====================================================================
Copyright(c) 2016 Adam Rankin
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.
====================================================================*/
// Local includes
#include "pch.h"
#include "IGTLinkClient.h"
#include "IGTCommon.h"
#include "TrackedFrameMessage.h"
// IGT includes
#include "igtlCommandMessage.h"
#include "igtlCommon.h"
#include "igtlMessageHeader.h"
#include "igtlOSUtil.h"
#include "igtlStatusMessage.h"
// STD includes
#include <chrono>
#include <regex>
// Windows includes
#include <collection.h>
#include <pplawait.h>
#include <ppltasks.h>
#include <robuffer.h>
using namespace Concurrency;
using namespace Windows::Foundation;
using namespace Platform::Collections;
using namespace Windows::Storage::Streams;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::Data::Xml::Dom;
namespace UWPOpenIGTLink
{
const int IGTLinkClient::CLIENT_SOCKET_TIMEOUT_MSEC = 500;
const uint32 IGTLinkClient::MESSAGE_LIST_MAX_SIZE = 200;
//----------------------------------------------------------------------------
IGTLinkClient::IGTLinkClient()
: m_igtlMessageFactory(igtl::MessageFactory::New())
, m_clientSocket(igtl::ClientSocket::New())
{
m_igtlMessageFactory->AddMessageType("TRACKEDFRAME", (igtl::MessageFactory::PointerToMessageBaseNew)&igtl::TrackedFrameMessage::New);
ServerHost = L"127.0.0.1";
ServerPort = 18944;
ServerIGTLVersion = IGTL_HEADER_VERSION_2;
m_frameSize.assign(3, 0);
}
//----------------------------------------------------------------------------
IGTLinkClient::~IGTLinkClient()
{
Disconnect();
auto disconnectTask = concurrency::create_task([this]()
{
while (Connected)
{
std::this_thread::sleep_for(std::chrono::milliseconds(33));
}
});
disconnectTask.wait();
}
//----------------------------------------------------------------------------
IAsyncOperation<bool>^ IGTLinkClient::ConnectAsync(double timeoutSec)
{
Disconnect();
m_receiverPumpTokenSource = cancellation_token_source();
return create_async([ = ]() -> bool
{
const int retryDelaySec = 1.0;
int errorCode = 1;
auto start = std::chrono::high_resolution_clock::now();
while (errorCode != 0)
{
std::wstring wideStr(ServerHost->Begin());
std::string str(wideStr.begin(), wideStr.end());
errorCode = m_clientSocket->ConnectToServer(str.c_str(), ServerPort);
if (errorCode == 0)
{
break;
}
std::chrono::duration<double, std::milli> timeDiff = std::chrono::high_resolution_clock::now() - start;
if (timeDiff.count() > timeoutSec * 1000)
{
// time is up
break;
}
std::this_thread::sleep_for(std::chrono::seconds(retryDelaySec));
}
if (errorCode != 0)
{
return false;
}
m_clientSocket->SetTimeout(CLIENT_SOCKET_TIMEOUT_MSEC);
m_clientSocket->SetReceiveBlocking(true);
// We're connected, start the data receiver thread
create_task([this]()
{
DataReceiverPump(this, m_receiverPumpTokenSource.get_token());
});
return true;
});
}
//----------------------------------------------------------------------------
void IGTLinkClient::Disconnect()
{
m_receiverPumpTokenSource.cancel();
{
std::lock_guard<std::mutex> guard(m_socketMutex);
m_clientSocket->CloseSocket();
}
}
//----------------------------------------------------------------------------
TrackedFrame^ IGTLinkClient::GetTrackedFrame(double lastKnownTimestamp)
{
igtl::TrackedFrameMessage::Pointer trackedFrameMsg = nullptr;
{
// Retrieve the next available tracked frame reply
std::lock_guard<std::mutex> guard(m_messageListMutex);
for (auto replyIter = m_receivedMessages.rbegin(); replyIter != m_receivedMessages.rend(); ++replyIter)
{
if (typeid(*(*replyIter)) == typeid(igtl::TrackedFrameMessage))
{
trackedFrameMsg = dynamic_cast<igtl::TrackedFrameMessage*>((*replyIter).GetPointer());
break;
}
}
if (trackedFrameMsg == nullptr)
{
// No message found
return nullptr;
}
}
auto ts = igtl::TimeStamp::New();
trackedFrameMsg->GetTimeStamp(ts);
if (ts->GetTimeStamp() <= lastKnownTimestamp)
{
// No new messages since requested timestamp
if (m_receivedUWPMessages.find(lastKnownTimestamp) != m_receivedUWPMessages.end())
{
return m_receivedUWPMessages.at(lastKnownTimestamp);
}
return nullptr;
}
auto frame = ref new TrackedFrame();
m_receivedUWPMessages[ts->GetTimeStamp()] = frame;
// Tracking/other related fields
for (auto& pair : trackedFrameMsg->GetMetaData())
{
std::wstring keyWideStr(pair.first.begin(), pair.first.end());
std::wstring valueWideStr(pair.second.begin(), pair.second.end());
frame->SetCustomFrameField(keyWideStr, valueWideStr);
}
for (auto& pair : trackedFrameMsg->GetCustomFrameFields())
{
frame->SetCustomFrameField(pair.first, pair.second);
}
// Image related fields
frame->SetFrameSize(trackedFrameMsg->GetFrameSize());
frame->Timestamp = ts->GetTimeStamp();
frame->ImageSizeBytes = trackedFrameMsg->GetImageSizeInBytes();
frame->SetImageData(trackedFrameMsg->GetImage());
frame->NumberOfComponents = trackedFrameMsg->GetNumberOfComponents();
frame->ScalarType = trackedFrameMsg->GetScalarType();
frame->SetEmbeddedImageTransform(trackedFrameMsg->GetEmbeddedImageTransform());
frame->ImageType = (uint16)trackedFrameMsg->GetImageType();
frame->ImageOrientation = (uint16)trackedFrameMsg->GetImageOrientation();
frame->SetFrameTransformsInternal(trackedFrameMsg->GetFrameTransforms());
return frame;
}
//----------------------------------------------------------------------------
Command^ IGTLinkClient::GetCommand(double lastKnownTimestamp)
{
igtl::MessageBase::Pointer igtMessage = nullptr;
{
// Retrieve the next available tracked frame reply
std::lock_guard<std::mutex> guard(m_messageListMutex);
for (auto replyIter = m_receivedMessages.rbegin(); replyIter != m_receivedMessages.rend(); ++replyIter)
{
if (typeid(*(*replyIter)) == typeid(igtl::RTSCommandMessage))
{
igtMessage = *replyIter;
break;
}
}
if (igtMessage == nullptr)
{
return nullptr;
}
}
auto ts = igtl::TimeStamp::New();
igtMessage->GetTimeStamp(ts);
if (ts->GetTimeStamp() <= lastKnownTimestamp)
{
return nullptr;
}
auto cmd = ref new Command();
auto cmdMsg = dynamic_cast<igtl::RTSCommandMessage*>(igtMessage.GetPointer());
cmd->CommandContent = ref new Platform::String(std::wstring(cmdMsg->GetCommandContent().begin(), cmdMsg->GetCommandContent().end()).c_str());
cmd->CommandName = ref new Platform::String(std::wstring(cmdMsg->GetCommandName().begin(), cmdMsg->GetCommandName().end()).c_str());
cmd->OriginalCommandId = cmdMsg->GetCommandId();
cmd->Timestamp = lastKnownTimestamp;
XmlDocument^ doc = ref new XmlDocument();
doc->LoadXml(cmd->CommandContent);
for (IXmlNode^ node : doc->ChildNodes)
{
if (dynamic_cast<Platform::String^>(node->NodeName) == L"Result")
{
cmd->Result = (dynamic_cast<Platform::String^>(node->NodeValue) == L"true");
break;
}
}
if (!cmd->Result)
{
bool found(false);
// Parse for the error string
for (IXmlNode^ node : doc->ChildNodes)
{
if (dynamic_cast<Platform::String^>(node->NodeName) == L"Error")
{
cmd->ErrorString = dynamic_cast<Platform::String^>(node->NodeValue);
found = true;
break;
}
}
if (!found)
{
OutputDebugStringA("Error string not found even though error was reported. Check IGT server implementation.");
}
}
for (auto& pair : cmdMsg->GetMetaData())
{
std::wstring keyWideStr(pair.first.begin(), pair.first.end());
std::wstring valueWideStr(pair.second.begin(), pair.second.end());
cmd->Parameters->Insert(ref new Platform::String(keyWideStr.c_str()), ref new Platform::String(valueWideStr.c_str()));
}
return cmd;
}
//----------------------------------------------------------------------------
bool IGTLinkClient::SendMessage(igtl::MessageBase::Pointer packedMessage)
{
int success = 0;
{
std::lock_guard<std::mutex> guard(m_socketMutex);
success = m_clientSocket->Send(packedMessage->GetBufferPointer(), packedMessage->GetBufferSize());
}
if (!success)
{
std::cerr << "OpenIGTLink client couldn't send message to server." << std::endl;
return false;
}
return true;
}
//----------------------------------------------------------------------------
bool IGTLinkClient::SendMessage(MessageBasePointerPtr messageBasePointerPtr)
{
igtl::MessageBase::Pointer* messageBasePointer = (igtl::MessageBase::Pointer*)(messageBasePointerPtr);
return SendMessage(*messageBasePointer);
}
//----------------------------------------------------------------------------
void IGTLinkClient::DataReceiverPump(IGTLinkClient^ self, concurrency::cancellation_token token)
{
LOG_TRACE(L"IGTLinkClient::DataReceiverPump");
while (!token.is_canceled())
{
auto headerMsg = self->m_igtlMessageFactory->CreateHeaderMessage(IGTL_HEADER_VERSION_1);
// Receive generic header from the socket
int numOfBytesReceived = 0;
{
std::lock_guard<std::mutex> guard(self->m_socketMutex);
if (!self->m_clientSocket->GetConnected())
{
// We've become disconnected while waiting for the socket, we're done here!
return;
}
numOfBytesReceived = self->m_clientSocket->Receive(headerMsg->GetBufferPointer(), headerMsg->GetBufferSize());
}
if (numOfBytesReceived == 0 // No message received
|| numOfBytesReceived != headerMsg->GetBufferSize() // Received data is not as we expected
)
{
// Failed to receive data, maybe the socket is disconnected
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
}
int c = headerMsg->Unpack(1);
if (!(c & igtl::MessageHeader::UNPACK_HEADER))
{
std::cerr << "Failed to receive message (invalid header)" << std::endl;
continue;
}
igtl::MessageBase::Pointer bodyMsg = nullptr;
try
{
bodyMsg = self->m_igtlMessageFactory->CreateReceiveMessage(headerMsg);
}
catch (const std::exception&)
{
// Message header was not correct, skip this message
// Will be impossible to tell if the body of this message is in the socket... this is a pretty bad corruption.
// Force re-connect?
LOG_TRACE("Corruption in the message header. Serious error.");
continue;
}
if (bodyMsg.IsNull())
{
LOG_TRACE("Unable to create message of type: " << headerMsg->GetMessageType());
continue;
}
// Accept all messages but status messages, they are used as a keep alive mechanism
if (typeid(*bodyMsg) != typeid(igtl::StatusMessage))
{
{
std::lock_guard<std::mutex> guard(self->m_socketMutex);
if (!self->m_clientSocket->GetConnected())
{
// We've become disconnected while waiting for the socket, we're done here!
return;
}
self->m_clientSocket->Receive(bodyMsg->GetBufferBodyPointer(), bodyMsg->GetBufferBodySize());
}
int c = bodyMsg->Unpack(1);
if (!(c & igtl::MessageHeader::UNPACK_BODY))
{
LOG_TRACE("Failed to receive reply (invalid body)");
continue;
}
{
// save reply
std::lock_guard<std::mutex> guard(self->m_messageListMutex);
self->m_receivedMessages.push_back(bodyMsg);
}
}
else
{
std::lock_guard<std::mutex> guard(self->m_socketMutex);
self->m_clientSocket->Skip(headerMsg->GetBodySizeToRead(), 0);
}
if (self->m_receivedMessages.size() > MESSAGE_LIST_MAX_SIZE)
{
std::lock_guard<std::mutex> guard(self->m_messageListMutex);
// erase the front N results
uint32 toErase = self->m_receivedMessages.size() - MESSAGE_LIST_MAX_SIZE;
self->m_receivedMessages.erase(self->m_receivedMessages.begin(), self->m_receivedMessages.begin() + toErase);
}
auto oldestTimestamp = self->GetOldestTrackedFrameTimestamp();
if (oldestTimestamp > 0)
{
for (auto it = self->m_receivedUWPMessages.begin(); it != self->m_receivedUWPMessages.end();)
{
if (it->first < oldestTimestamp)
{
it = self->m_receivedUWPMessages.erase(it);
}
else
{
++it;
}
}
}
}
return;
}
//----------------------------------------------------------------------------
int IGTLinkClient::SocketReceive(void* data, int length)
{
std::lock_guard<std::mutex> guard(m_socketMutex);
return m_clientSocket->Receive(data, length);
}
//----------------------------------------------------------------------------
double IGTLinkClient::GetLatestTrackedFrameTimestamp()
{
// Retrieve the next available tracked frame reply
std::lock_guard<std::mutex> guard(m_messageListMutex);
for (auto replyIter = m_receivedMessages.rbegin(); replyIter != m_receivedMessages.rend(); ++replyIter)
{
if (typeid(*(*replyIter)) == typeid(igtl::TrackedFrameMessage))
{
igtl::TimeStamp::Pointer ts = igtl::TimeStamp::New();
(*replyIter)->GetTimeStamp(ts);
return ts->GetTimeStamp();
}
}
return -1.0;
}
//----------------------------------------------------------------------------
double IGTLinkClient::GetOldestTrackedFrameTimestamp()
{
// Retrieve the next available tracked frame reply
std::lock_guard<std::mutex> guard(m_messageListMutex);
for (auto replyIter = m_receivedMessages.begin(); replyIter != m_receivedMessages.end(); ++replyIter)
{
if (typeid(*(*replyIter)) == typeid(igtl::TrackedFrameMessage))
{
igtl::TimeStamp::Pointer ts = igtl::TimeStamp::New();
(*replyIter)->GetTimeStamp(ts);
return ts->GetTimeStamp();
}
}
return -1.0;
}
//----------------------------------------------------------------------------
int IGTLinkClient::ServerPort::get()
{
return m_serverPort;
}
//----------------------------------------------------------------------------
void IGTLinkClient::ServerPort::set(int arg)
{
m_serverPort = arg;
}
//----------------------------------------------------------------------------
Platform::String^ IGTLinkClient::ServerHost::get()
{
return m_serverHost;
}
//----------------------------------------------------------------------------
void IGTLinkClient::ServerHost::set(Platform::String^ arg)
{
m_serverHost = arg;
}
//----------------------------------------------------------------------------
int IGTLinkClient::ServerIGTLVersion::get()
{
return m_serverIGTLVersion;
}
//----------------------------------------------------------------------------
void IGTLinkClient::ServerIGTLVersion::set(int arg)
{
m_serverIGTLVersion = arg;
}
//----------------------------------------------------------------------------
bool IGTLinkClient::Connected::get()
{
return m_clientSocket->GetConnected();
}
}<|endoftext|> |
<commit_before>//
// DiskController.cpp
// Clock Signal
//
// Created by Thomas Harte on 14/07/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "DiskController.hpp"
#include "UnformattedTrack.hpp"
#include "../../NumberTheory/Factors.hpp"
#include <cassert>
using namespace Storage::Disk;
Controller::Controller(Cycles clock_rate, int clock_rate_multiplier, int revolutions_per_minute) :
clock_rate_(clock_rate.as_int() * clock_rate_multiplier),
clock_rate_multiplier_(clock_rate_multiplier),
rotational_multiplier_(60, revolutions_per_minute),
cycles_since_index_hole_(0),
motor_is_on_(false),
is_reading_(true),
TimedEventLoop((unsigned int)(clock_rate.as_int() * clock_rate_multiplier)) {
// seed this class with a PLL, any PLL, so that it's safe to assume non-nullptr later
Time one(1);
set_expected_bit_length(one);
}
void Controller::setup_track() {
track_ = drive_->get_track();
if(!track_) {
track_.reset(new UnformattedTrack);
}
Time offset;
Time track_time_now = get_time_into_track();
assert(track_time_now >= Time(0) && current_event_.length <= Time(1));
Time time_found = track_->seek_to(track_time_now);
assert(time_found >= Time(0) && time_found <= track_time_now);
offset = track_time_now - time_found;
get_next_event(offset);
}
void Controller::run_for(const Cycles cycles) {
Time zero(0);
if(drive_ && drive_->has_disk() && motor_is_on_) {
if(!track_) setup_track();
int number_of_cycles = clock_rate_multiplier_ * cycles.as_int();
while(number_of_cycles) {
int cycles_until_next_event = (int)get_cycles_until_next_event();
int cycles_to_run_for = std::min(cycles_until_next_event, number_of_cycles);
if(!is_reading_ && cycles_until_bits_written_ > zero) {
int write_cycles_target = (int)cycles_until_bits_written_.get_unsigned_int();
if(cycles_until_bits_written_.length % cycles_until_bits_written_.clock_rate) write_cycles_target++;
cycles_to_run_for = std::min(cycles_to_run_for, write_cycles_target);
}
cycles_since_index_hole_ += (unsigned int)cycles_to_run_for;
number_of_cycles -= cycles_to_run_for;
if(is_reading_) {
pll_->run_for(Cycles(cycles_to_run_for));
} else {
if(cycles_until_bits_written_ > zero) {
Storage::Time cycles_to_run_for_time(cycles_to_run_for);
if(cycles_until_bits_written_ <= cycles_to_run_for_time) {
process_write_completed();
if(cycles_until_bits_written_ <= cycles_to_run_for_time)
cycles_until_bits_written_.set_zero();
else
cycles_until_bits_written_ -= cycles_to_run_for_time;
} else {
cycles_until_bits_written_ -= cycles_to_run_for_time;
}
}
}
TimedEventLoop::run_for(Cycles(cycles_to_run_for));
}
}
}
#pragma mark - Track timed event loop
void Controller::get_next_event(const Time &duration_already_passed) {
if(track_) {
current_event_ = track_->get_next_event();
} else {
current_event_.length.length = 1;
current_event_.length.clock_rate = 1;
current_event_.type = Track::Event::IndexHole;
}
// divide interval, which is in terms of a single rotation of the disk, by rotation speed to
// convert it into revolutions per second; this is achieved by multiplying by rotational_multiplier_
assert(current_event_.length <= Time(1) && current_event_.length >= Time(0));
Time interval = (current_event_.length - duration_already_passed) * rotational_multiplier_;
set_next_event_time_interval(interval);
}
void Controller::process_next_event()
{
switch(current_event_.type) {
case Track::Event::FluxTransition:
if(is_reading_) pll_->add_pulse();
break;
case Track::Event::IndexHole:
// printf("%p %d [/%d = %d]\n", this, cycles_since_index_hole_, clock_rate_multiplier_, cycles_since_index_hole_ / clock_rate_multiplier_);
cycles_since_index_hole_ = 0;
process_index_hole();
break;
}
get_next_event(Time(0));
}
Storage::Time Controller::get_time_into_track() {
// this is proportion of a second
Time result(cycles_since_index_hole_, 8000000 * clock_rate_multiplier_);
result /= rotational_multiplier_;
result.simplify();
return result;
}
#pragma mark - Writing
void Controller::begin_writing(bool clamp_to_index_hole) {
is_reading_ = false;
clamp_writing_to_index_hole_ = clamp_to_index_hole;
write_segment_.length_of_a_bit = bit_length_ / rotational_multiplier_;
write_segment_.data.clear();
write_segment_.number_of_bits = 0;
write_start_time_ = get_time_into_track();
}
void Controller::write_bit(bool value) {
bool needs_new_byte = !(write_segment_.number_of_bits&7);
if(needs_new_byte) write_segment_.data.push_back(0);
if(value) write_segment_.data[write_segment_.number_of_bits >> 3] |= 0x80 >> (write_segment_.number_of_bits & 7);
write_segment_.number_of_bits++;
cycles_until_bits_written_ += cycles_per_bit_;
}
void Controller::end_writing() {
is_reading_ = true;
if(!patched_track_) {
// Avoid creating a new patched track if this one is already patched
patched_track_ = std::dynamic_pointer_cast<PCMPatchedTrack>(track_);
if(!patched_track_) {
patched_track_.reset(new PCMPatchedTrack(track_));
} else {
printf("");
}
} else {
printf("");
}
patched_track_->add_segment(write_start_time_, write_segment_, clamp_writing_to_index_hole_);
cycles_since_index_hole_ %= 8000000 * clock_rate_multiplier_;
invalidate_track(); // TEMPORARY: to force a seek
}
#pragma mark - PLL control and delegate
void Controller::set_expected_bit_length(Time bit_length) {
bit_length_ = bit_length;
bit_length_.simplify();
cycles_per_bit_ = Storage::Time(clock_rate_) * bit_length;
cycles_per_bit_.simplify();
// this conversion doesn't need to be exact because there's a lot of variation to be taken
// account of in rotation speed, air turbulence, etc, so a direct conversion will do
int clocks_per_bit = (int)cycles_per_bit_.get_unsigned_int();
pll_.reset(new DigitalPhaseLockedLoop(clocks_per_bit, 3));
pll_->set_delegate(this);
}
void Controller::digital_phase_locked_loop_output_bit(int value) {
process_input_bit(value, (unsigned int)cycles_since_index_hole_);
}
#pragma mark - Drive actions
bool Controller::get_is_track_zero() {
if(!drive_) return false;
return drive_->get_is_track_zero();
}
bool Controller::get_drive_is_ready() {
if(!drive_) return false;
return drive_->has_disk();
}
bool Controller::get_drive_is_read_only() {
if(!drive_) return false;
return drive_->get_is_read_only();
}
void Controller::step(int direction) {
invalidate_track();
if(drive_) drive_->step(direction);
}
void Controller::set_motor_on(bool motor_on) {
motor_is_on_ = motor_on;
}
bool Controller::get_motor_on() {
return motor_is_on_;
}
void Controller::set_drive(std::shared_ptr<Drive> drive) {
if(drive_ != drive) {
invalidate_track();
drive_ = drive;
}
}
void Controller::invalidate_track() {
track_ = nullptr;
if(patched_track_) {
drive_->set_track(patched_track_);
patched_track_ = nullptr;
}
}
void Controller::process_write_completed() {}
<commit_msg>Removed debugging nonsense.<commit_after>//
// DiskController.cpp
// Clock Signal
//
// Created by Thomas Harte on 14/07/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "DiskController.hpp"
#include "UnformattedTrack.hpp"
#include "../../NumberTheory/Factors.hpp"
#include <cassert>
using namespace Storage::Disk;
Controller::Controller(Cycles clock_rate, int clock_rate_multiplier, int revolutions_per_minute) :
clock_rate_(clock_rate.as_int() * clock_rate_multiplier),
clock_rate_multiplier_(clock_rate_multiplier),
rotational_multiplier_(60, revolutions_per_minute),
cycles_since_index_hole_(0),
motor_is_on_(false),
is_reading_(true),
TimedEventLoop((unsigned int)(clock_rate.as_int() * clock_rate_multiplier)) {
// seed this class with a PLL, any PLL, so that it's safe to assume non-nullptr later
Time one(1);
set_expected_bit_length(one);
}
void Controller::setup_track() {
track_ = drive_->get_track();
if(!track_) {
track_.reset(new UnformattedTrack);
}
Time offset;
Time track_time_now = get_time_into_track();
assert(track_time_now >= Time(0) && current_event_.length <= Time(1));
Time time_found = track_->seek_to(track_time_now);
assert(time_found >= Time(0) && time_found <= track_time_now);
offset = track_time_now - time_found;
get_next_event(offset);
}
void Controller::run_for(const Cycles cycles) {
Time zero(0);
if(drive_ && drive_->has_disk() && motor_is_on_) {
if(!track_) setup_track();
int number_of_cycles = clock_rate_multiplier_ * cycles.as_int();
while(number_of_cycles) {
int cycles_until_next_event = (int)get_cycles_until_next_event();
int cycles_to_run_for = std::min(cycles_until_next_event, number_of_cycles);
if(!is_reading_ && cycles_until_bits_written_ > zero) {
int write_cycles_target = (int)cycles_until_bits_written_.get_unsigned_int();
if(cycles_until_bits_written_.length % cycles_until_bits_written_.clock_rate) write_cycles_target++;
cycles_to_run_for = std::min(cycles_to_run_for, write_cycles_target);
}
cycles_since_index_hole_ += (unsigned int)cycles_to_run_for;
number_of_cycles -= cycles_to_run_for;
if(is_reading_) {
pll_->run_for(Cycles(cycles_to_run_for));
} else {
if(cycles_until_bits_written_ > zero) {
Storage::Time cycles_to_run_for_time(cycles_to_run_for);
if(cycles_until_bits_written_ <= cycles_to_run_for_time) {
process_write_completed();
if(cycles_until_bits_written_ <= cycles_to_run_for_time)
cycles_until_bits_written_.set_zero();
else
cycles_until_bits_written_ -= cycles_to_run_for_time;
} else {
cycles_until_bits_written_ -= cycles_to_run_for_time;
}
}
}
TimedEventLoop::run_for(Cycles(cycles_to_run_for));
}
}
}
#pragma mark - Track timed event loop
void Controller::get_next_event(const Time &duration_already_passed) {
if(track_) {
current_event_ = track_->get_next_event();
} else {
current_event_.length.length = 1;
current_event_.length.clock_rate = 1;
current_event_.type = Track::Event::IndexHole;
}
// divide interval, which is in terms of a single rotation of the disk, by rotation speed to
// convert it into revolutions per second; this is achieved by multiplying by rotational_multiplier_
assert(current_event_.length <= Time(1) && current_event_.length >= Time(0));
Time interval = (current_event_.length - duration_already_passed) * rotational_multiplier_;
set_next_event_time_interval(interval);
}
void Controller::process_next_event()
{
switch(current_event_.type) {
case Track::Event::FluxTransition:
if(is_reading_) pll_->add_pulse();
break;
case Track::Event::IndexHole:
// printf("%p %d [/%d = %d]\n", this, cycles_since_index_hole_, clock_rate_multiplier_, cycles_since_index_hole_ / clock_rate_multiplier_);
cycles_since_index_hole_ = 0;
process_index_hole();
break;
}
get_next_event(Time(0));
}
Storage::Time Controller::get_time_into_track() {
// this is proportion of a second
Time result(cycles_since_index_hole_, 8000000 * clock_rate_multiplier_);
result /= rotational_multiplier_;
result.simplify();
return result;
}
#pragma mark - Writing
void Controller::begin_writing(bool clamp_to_index_hole) {
is_reading_ = false;
clamp_writing_to_index_hole_ = clamp_to_index_hole;
write_segment_.length_of_a_bit = bit_length_ / rotational_multiplier_;
write_segment_.data.clear();
write_segment_.number_of_bits = 0;
write_start_time_ = get_time_into_track();
}
void Controller::write_bit(bool value) {
bool needs_new_byte = !(write_segment_.number_of_bits&7);
if(needs_new_byte) write_segment_.data.push_back(0);
if(value) write_segment_.data[write_segment_.number_of_bits >> 3] |= 0x80 >> (write_segment_.number_of_bits & 7);
write_segment_.number_of_bits++;
cycles_until_bits_written_ += cycles_per_bit_;
}
void Controller::end_writing() {
is_reading_ = true;
if(!patched_track_) {
// Avoid creating a new patched track if this one is already patched
patched_track_ = std::dynamic_pointer_cast<PCMPatchedTrack>(track_);
if(!patched_track_) {
patched_track_.reset(new PCMPatchedTrack(track_));
}
}
patched_track_->add_segment(write_start_time_, write_segment_, clamp_writing_to_index_hole_);
cycles_since_index_hole_ %= 8000000 * clock_rate_multiplier_;
invalidate_track(); // TEMPORARY: to force a seek
}
#pragma mark - PLL control and delegate
void Controller::set_expected_bit_length(Time bit_length) {
bit_length_ = bit_length;
bit_length_.simplify();
cycles_per_bit_ = Storage::Time(clock_rate_) * bit_length;
cycles_per_bit_.simplify();
// this conversion doesn't need to be exact because there's a lot of variation to be taken
// account of in rotation speed, air turbulence, etc, so a direct conversion will do
int clocks_per_bit = (int)cycles_per_bit_.get_unsigned_int();
pll_.reset(new DigitalPhaseLockedLoop(clocks_per_bit, 3));
pll_->set_delegate(this);
}
void Controller::digital_phase_locked_loop_output_bit(int value) {
process_input_bit(value, (unsigned int)cycles_since_index_hole_);
}
#pragma mark - Drive actions
bool Controller::get_is_track_zero() {
if(!drive_) return false;
return drive_->get_is_track_zero();
}
bool Controller::get_drive_is_ready() {
if(!drive_) return false;
return drive_->has_disk();
}
bool Controller::get_drive_is_read_only() {
if(!drive_) return false;
return drive_->get_is_read_only();
}
void Controller::step(int direction) {
invalidate_track();
if(drive_) drive_->step(direction);
}
void Controller::set_motor_on(bool motor_on) {
motor_is_on_ = motor_on;
}
bool Controller::get_motor_on() {
return motor_is_on_;
}
void Controller::set_drive(std::shared_ptr<Drive> drive) {
if(drive_ != drive) {
invalidate_track();
drive_ = drive;
}
}
void Controller::invalidate_track() {
track_ = nullptr;
if(patched_track_) {
drive_->set_track(patched_track_);
patched_track_ = nullptr;
}
}
void Controller::process_write_completed() {}
<|endoftext|> |
<commit_before>//
// DiskController.cpp
// Clock Signal
//
// Created by Thomas Harte on 14/07/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "DiskController.hpp"
#include "../../NumberTheory/Factors.hpp"
using namespace Storage::Disk;
Controller::Controller(Cycles clock_rate, int clock_rate_multiplier, int revolutions_per_minute) :
clock_rate_(clock_rate.as_int() * clock_rate_multiplier),
clock_rate_multiplier_(clock_rate_multiplier),
rotational_multiplier_(60, revolutions_per_minute),
cycles_since_index_hole_(0),
motor_is_on_(false),
is_reading_(true),
TimedEventLoop((unsigned int)(clock_rate.as_int() * clock_rate_multiplier)) {
// seed this class with a PLL, any PLL, so that it's safe to assume non-nullptr later
Time one(1);
set_expected_bit_length(one);
}
void Controller::setup_track() {
track_ = drive_->get_track();
Time offset;
Time track_time_now = get_time_into_track();
if(track_) {
Time time_found = track_->seek_to(track_time_now);
offset = track_time_now - time_found;
}
get_next_event(offset);
}
void Controller::run_for(const Cycles cycles) {
Time zero(0);
if(drive_ && drive_->has_disk() && motor_is_on_) {
if(!track_) setup_track();
int number_of_cycles = clock_rate_multiplier_ * cycles.as_int();
while(number_of_cycles) {
int cycles_until_next_event = (int)get_cycles_until_next_event();
int cycles_to_run_for = std::min(cycles_until_next_event, number_of_cycles);
if(!is_reading_ && cycles_until_bits_written_ > zero) {
int write_cycles_target = (int)cycles_until_bits_written_.get_unsigned_int();
if(cycles_until_bits_written_.length % cycles_until_bits_written_.clock_rate) write_cycles_target++;
cycles_to_run_for = std::min(cycles_to_run_for, write_cycles_target);
}
cycles_since_index_hole_ += (unsigned int)cycles_to_run_for;
number_of_cycles -= cycles_to_run_for;
if(is_reading_) {
pll_->run_for(Cycles(cycles_to_run_for));
} else {
if(cycles_until_bits_written_ > zero) {
Storage::Time cycles_to_run_for_time(cycles_to_run_for);
if(cycles_until_bits_written_ <= cycles_to_run_for_time) {
process_write_completed();
if(cycles_until_bits_written_ <= cycles_to_run_for_time)
cycles_until_bits_written_.set_zero();
else
cycles_until_bits_written_ -= cycles_to_run_for_time;
} else {
cycles_until_bits_written_ -= cycles_to_run_for_time;
}
}
}
TimedEventLoop::run_for(Cycles(cycles_to_run_for));
}
}
}
#pragma mark - Track timed event loop
void Controller::get_next_event(const Time &duration_already_passed) {
if(track_) {
current_event_ = track_->get_next_event();
} else {
current_event_.length.length = 1;
current_event_.length.clock_rate = 1;
current_event_.type = Track::Event::IndexHole;
}
// divide interval, which is in terms of a single rotation of the disk, by rotation speed to
// convert it into revolutions per second; this is achieved by multiplying by rotational_multiplier_
set_next_event_time_interval((current_event_.length - duration_already_passed) * rotational_multiplier_);
}
void Controller::process_next_event()
{
switch(current_event_.type) {
case Track::Event::FluxTransition:
if(is_reading_) pll_->add_pulse();
break;
case Track::Event::IndexHole:
printf("%p %d [/%d = %d]\n", this, cycles_since_index_hole_, clock_rate_multiplier_, cycles_since_index_hole_ / clock_rate_multiplier_);
cycles_since_index_hole_ = 0;
process_index_hole();
break;
}
get_next_event(Time(0));
}
Storage::Time Controller::get_time_into_track() {
// this is proportion of a second
Time result(cycles_since_index_hole_, 8000000 * clock_rate_multiplier_);
result /= rotational_multiplier_;
result.simplify();
return result;
}
#pragma mark - Writing
void Controller::begin_writing() {
is_reading_ = false;
write_segment_.length_of_a_bit = bit_length_ / rotational_multiplier_;
write_segment_.data.clear();
write_segment_.number_of_bits = 0;
write_start_time_ = get_time_into_track();
}
void Controller::write_bit(bool value) {
bool needs_new_byte = !(write_segment_.number_of_bits&7);
if(needs_new_byte) write_segment_.data.push_back(0);
if(value) write_segment_.data[write_segment_.number_of_bits >> 3] |= 0x80 >> (write_segment_.number_of_bits & 7);
write_segment_.number_of_bits++;
cycles_until_bits_written_ += cycles_per_bit_;
}
void Controller::end_writing() {
is_reading_ = true;
if(!patched_track_) {
// Avoid creating a new patched track if this one is already patched
patched_track_ = std::dynamic_pointer_cast<PCMPatchedTrack>(track_);
if(!patched_track_) {
patched_track_.reset(new PCMPatchedTrack(track_));
}
}
patched_track_->add_segment(write_start_time_, write_segment_);
invalidate_track(); // TEMPORARY: to force a seek
}
#pragma mark - PLL control and delegate
void Controller::set_expected_bit_length(Time bit_length) {
bit_length_ = bit_length;
bit_length_.simplify();
cycles_per_bit_ = Storage::Time(clock_rate_) * bit_length;
cycles_per_bit_.simplify();
// this conversion doesn't need to be exact because there's a lot of variation to be taken
// account of in rotation speed, air turbulence, etc, so a direct conversion will do
int clocks_per_bit = (int)cycles_per_bit_.get_unsigned_int();
pll_.reset(new DigitalPhaseLockedLoop(clocks_per_bit, 3));
pll_->set_delegate(this);
}
void Controller::digital_phase_locked_loop_output_bit(int value) {
process_input_bit(value, (unsigned int)cycles_since_index_hole_);
}
#pragma mark - Drive actions
bool Controller::get_is_track_zero() {
if(!drive_) return false;
return drive_->get_is_track_zero();
}
bool Controller::get_drive_is_ready() {
if(!drive_) return false;
return drive_->has_disk();
}
bool Controller::get_drive_is_read_only() {
if(!drive_) return false;
return drive_->get_is_read_only();
}
void Controller::step(int direction) {
invalidate_track();
if(drive_) drive_->step(direction);
}
void Controller::set_motor_on(bool motor_on) {
motor_is_on_ = motor_on;
}
bool Controller::get_motor_on() {
return motor_is_on_;
}
void Controller::set_drive(std::shared_ptr<Drive> drive) {
if(drive_ != drive)
{
invalidate_track();
drive_ = drive;
}
}
void Controller::invalidate_track() {
track_ = nullptr;
if(patched_track_) {
drive_->set_track(patched_track_);
patched_track_ = nullptr;
}
}
void Controller::process_write_completed() {}
<commit_msg>Removed index-hole announcement.<commit_after>//
// DiskController.cpp
// Clock Signal
//
// Created by Thomas Harte on 14/07/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "DiskController.hpp"
#include "../../NumberTheory/Factors.hpp"
using namespace Storage::Disk;
Controller::Controller(Cycles clock_rate, int clock_rate_multiplier, int revolutions_per_minute) :
clock_rate_(clock_rate.as_int() * clock_rate_multiplier),
clock_rate_multiplier_(clock_rate_multiplier),
rotational_multiplier_(60, revolutions_per_minute),
cycles_since_index_hole_(0),
motor_is_on_(false),
is_reading_(true),
TimedEventLoop((unsigned int)(clock_rate.as_int() * clock_rate_multiplier)) {
// seed this class with a PLL, any PLL, so that it's safe to assume non-nullptr later
Time one(1);
set_expected_bit_length(one);
}
void Controller::setup_track() {
track_ = drive_->get_track();
Time offset;
Time track_time_now = get_time_into_track();
if(track_) {
Time time_found = track_->seek_to(track_time_now);
offset = track_time_now - time_found;
}
get_next_event(offset);
}
void Controller::run_for(const Cycles cycles) {
Time zero(0);
if(drive_ && drive_->has_disk() && motor_is_on_) {
if(!track_) setup_track();
int number_of_cycles = clock_rate_multiplier_ * cycles.as_int();
while(number_of_cycles) {
int cycles_until_next_event = (int)get_cycles_until_next_event();
int cycles_to_run_for = std::min(cycles_until_next_event, number_of_cycles);
if(!is_reading_ && cycles_until_bits_written_ > zero) {
int write_cycles_target = (int)cycles_until_bits_written_.get_unsigned_int();
if(cycles_until_bits_written_.length % cycles_until_bits_written_.clock_rate) write_cycles_target++;
cycles_to_run_for = std::min(cycles_to_run_for, write_cycles_target);
}
cycles_since_index_hole_ += (unsigned int)cycles_to_run_for;
number_of_cycles -= cycles_to_run_for;
if(is_reading_) {
pll_->run_for(Cycles(cycles_to_run_for));
} else {
if(cycles_until_bits_written_ > zero) {
Storage::Time cycles_to_run_for_time(cycles_to_run_for);
if(cycles_until_bits_written_ <= cycles_to_run_for_time) {
process_write_completed();
if(cycles_until_bits_written_ <= cycles_to_run_for_time)
cycles_until_bits_written_.set_zero();
else
cycles_until_bits_written_ -= cycles_to_run_for_time;
} else {
cycles_until_bits_written_ -= cycles_to_run_for_time;
}
}
}
TimedEventLoop::run_for(Cycles(cycles_to_run_for));
}
}
}
#pragma mark - Track timed event loop
void Controller::get_next_event(const Time &duration_already_passed) {
if(track_) {
current_event_ = track_->get_next_event();
} else {
current_event_.length.length = 1;
current_event_.length.clock_rate = 1;
current_event_.type = Track::Event::IndexHole;
}
// divide interval, which is in terms of a single rotation of the disk, by rotation speed to
// convert it into revolutions per second; this is achieved by multiplying by rotational_multiplier_
set_next_event_time_interval((current_event_.length - duration_already_passed) * rotational_multiplier_);
}
void Controller::process_next_event()
{
switch(current_event_.type) {
case Track::Event::FluxTransition:
if(is_reading_) pll_->add_pulse();
break;
case Track::Event::IndexHole:
// printf("%p %d [/%d = %d]\n", this, cycles_since_index_hole_, clock_rate_multiplier_, cycles_since_index_hole_ / clock_rate_multiplier_);
cycles_since_index_hole_ = 0;
process_index_hole();
break;
}
get_next_event(Time(0));
}
Storage::Time Controller::get_time_into_track() {
// this is proportion of a second
Time result(cycles_since_index_hole_, 8000000 * clock_rate_multiplier_);
result /= rotational_multiplier_;
result.simplify();
return result;
}
#pragma mark - Writing
void Controller::begin_writing() {
is_reading_ = false;
write_segment_.length_of_a_bit = bit_length_ / rotational_multiplier_;
write_segment_.data.clear();
write_segment_.number_of_bits = 0;
write_start_time_ = get_time_into_track();
}
void Controller::write_bit(bool value) {
bool needs_new_byte = !(write_segment_.number_of_bits&7);
if(needs_new_byte) write_segment_.data.push_back(0);
if(value) write_segment_.data[write_segment_.number_of_bits >> 3] |= 0x80 >> (write_segment_.number_of_bits & 7);
write_segment_.number_of_bits++;
cycles_until_bits_written_ += cycles_per_bit_;
}
void Controller::end_writing() {
is_reading_ = true;
if(!patched_track_) {
// Avoid creating a new patched track if this one is already patched
patched_track_ = std::dynamic_pointer_cast<PCMPatchedTrack>(track_);
if(!patched_track_) {
patched_track_.reset(new PCMPatchedTrack(track_));
}
}
patched_track_->add_segment(write_start_time_, write_segment_);
invalidate_track(); // TEMPORARY: to force a seek
}
#pragma mark - PLL control and delegate
void Controller::set_expected_bit_length(Time bit_length) {
bit_length_ = bit_length;
bit_length_.simplify();
cycles_per_bit_ = Storage::Time(clock_rate_) * bit_length;
cycles_per_bit_.simplify();
// this conversion doesn't need to be exact because there's a lot of variation to be taken
// account of in rotation speed, air turbulence, etc, so a direct conversion will do
int clocks_per_bit = (int)cycles_per_bit_.get_unsigned_int();
pll_.reset(new DigitalPhaseLockedLoop(clocks_per_bit, 3));
pll_->set_delegate(this);
}
void Controller::digital_phase_locked_loop_output_bit(int value) {
process_input_bit(value, (unsigned int)cycles_since_index_hole_);
}
#pragma mark - Drive actions
bool Controller::get_is_track_zero() {
if(!drive_) return false;
return drive_->get_is_track_zero();
}
bool Controller::get_drive_is_ready() {
if(!drive_) return false;
return drive_->has_disk();
}
bool Controller::get_drive_is_read_only() {
if(!drive_) return false;
return drive_->get_is_read_only();
}
void Controller::step(int direction) {
invalidate_track();
if(drive_) drive_->step(direction);
}
void Controller::set_motor_on(bool motor_on) {
motor_is_on_ = motor_on;
}
bool Controller::get_motor_on() {
return motor_is_on_;
}
void Controller::set_drive(std::shared_ptr<Drive> drive) {
if(drive_ != drive)
{
invalidate_track();
drive_ = drive;
}
}
void Controller::invalidate_track() {
track_ = nullptr;
if(patched_track_) {
drive_->set_track(patched_track_);
patched_track_ = nullptr;
}
}
void Controller::process_write_completed() {}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// //
// This file is part of Swift2D. //
// //
// Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer //
// //
////////////////////////////////////////////////////////////////////////////////
// includes -------------------------------------------------------------------
#include <swift2d/network/NetworkObjectBase.hpp>
#include <swift2d/utils/Logger.hpp>
#include <raknet/RakPeerInterface.h>
#include <raknet/GetTime.h>
namespace swift {
////////////////////////////////////////////////////////////////////////////////
void NetworkObjectBase::WriteAllocationID(RakNet::Connection_RM3 *con, RakNet::BitStream* stream) const {
stream->Write(get_type());
}
////////////////////////////////////////////////////////////////////////////////
RakNet::RM3ConstructionState NetworkObjectBase::QueryConstruction(RakNet::Connection_RM3 *con, RakNet::ReplicaManager3 *replicaManager3) {
return QueryConstruction_PeerToPeer(con);
}
////////////////////////////////////////////////////////////////////////////////
bool NetworkObjectBase::QueryRemoteConstruction(RakNet::Connection_RM3 *con) {
return QueryRemoteConstruction_PeerToPeer(con);
}
////////////////////////////////////////////////////////////////////////////////
void NetworkObjectBase::SerializeConstruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) {
vd_serializer_.AddRemoteSystemVariableHistory(con->GetRakNetGUID());
std::cout << "SerializeConstruction Begin" << std::endl;
for (auto& member: distributed_members_) {
member.print(std::cout);
std::cout << std::endl;
member.serialize(stream);
}
std::cout << "SerializeConstruction End" << std::endl;
}
////////////////////////////////////////////////////////////////////////////////
bool NetworkObjectBase::DeserializeConstruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) {
std::cout << "DeserializeConstruction Begin" << std::endl;
for (auto& member: distributed_members_) {
member.print(std::cout);
std::cout << std::endl;
member.deserialize(stream);
}
std::cout << "DeserializeConstruction End" << std::endl;
return true;
}
////////////////////////////////////////////////////////////////////////////////
void NetworkObjectBase::SerializeDestruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) {
vd_serializer_.RemoveRemoteSystemVariableHistory(con->GetRakNetGUID());
for (auto& member: distributed_members_) {
member.serialize(stream);
}
}
////////////////////////////////////////////////////////////////////////////////
bool NetworkObjectBase::DeserializeDestruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) {
for (auto& member: distributed_members_) {
member.deserialize(stream);
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
RakNet::RM3ActionOnPopConnection NetworkObjectBase::QueryActionOnPopConnection(RakNet::Connection_RM3 *con) const {
return QueryActionOnPopConnection_PeerToPeer(con);
}
////////////////////////////////////////////////////////////////////////////////
void NetworkObjectBase::DeallocReplica(RakNet::Connection_RM3 *con) {
on_remote_delete();
}
////////////////////////////////////////////////////////////////////////////////
RakNet::RM3QuerySerializationResult NetworkObjectBase::QuerySerialization(RakNet::Connection_RM3 *con) {
return QuerySerialization_PeerToPeer(con);
}
////////////////////////////////////////////////////////////////////////////////
RakNet::RM3SerializationResult NetworkObjectBase::Serialize(RakNet::SerializeParameters *serializeParameters) {
RakNet::VariableDeltaSerializer::SerializationContext ctx;
serializeParameters->pro[0].reliability=RELIABLE_ORDERED;
vd_serializer_.BeginIdenticalSerialize(
&ctx,
serializeParameters->whenLastSerialized==0,
&serializeParameters->outputBitstream[0]
);
for (auto& member: distributed_members_) {
member.serialize(&ctx, &vd_serializer_);
}
vd_serializer_.EndSerialize(&ctx);
return RakNet::RM3SR_SERIALIZED_ALWAYS_IDENTICALLY;
}
////////////////////////////////////////////////////////////////////////////////
void NetworkObjectBase::Deserialize(RakNet::DeserializeParameters *deserializeParameters) {
RakNet::VariableDeltaSerializer::DeserializationContext ctx;
vd_serializer_.BeginDeserialize(&ctx, &deserializeParameters->serializationBitstream[0]);
for (auto& member: distributed_members_) {
member.deserialize(&ctx, &vd_serializer_);
}
vd_serializer_.EndDeserialize(&ctx);
}
////////////////////////////////////////////////////////////////////////////////
void NetworkObjectBase::OnUserReplicaPreSerializeTick(void) {
vd_serializer_.OnPreSerializeTick();
}
////////////////////////////////////////////////////////////////////////////////
void NetworkObjectBase::distribute_member(SerializableReference const& value) {
distributed_members_.push_back(value);
}
////////////////////////////////////////////////////////////////////////////////
}
<commit_msg>removed output<commit_after>////////////////////////////////////////////////////////////////////////////////
// //
// This file is part of Swift2D. //
// //
// Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer //
// //
////////////////////////////////////////////////////////////////////////////////
// includes -------------------------------------------------------------------
#include <swift2d/network/NetworkObjectBase.hpp>
#include <swift2d/utils/Logger.hpp>
#include <raknet/RakPeerInterface.h>
#include <raknet/GetTime.h>
namespace swift {
////////////////////////////////////////////////////////////////////////////////
void NetworkObjectBase::WriteAllocationID(RakNet::Connection_RM3 *con, RakNet::BitStream* stream) const {
stream->Write(get_type());
}
////////////////////////////////////////////////////////////////////////////////
RakNet::RM3ConstructionState NetworkObjectBase::QueryConstruction(RakNet::Connection_RM3 *con, RakNet::ReplicaManager3 *replicaManager3) {
return QueryConstruction_PeerToPeer(con);
}
////////////////////////////////////////////////////////////////////////////////
bool NetworkObjectBase::QueryRemoteConstruction(RakNet::Connection_RM3 *con) {
return QueryRemoteConstruction_PeerToPeer(con);
}
////////////////////////////////////////////////////////////////////////////////
void NetworkObjectBase::SerializeConstruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) {
vd_serializer_.AddRemoteSystemVariableHistory(con->GetRakNetGUID());
for (auto& member: distributed_members_) {
member.serialize(stream);
}
}
////////////////////////////////////////////////////////////////////////////////
bool NetworkObjectBase::DeserializeConstruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) {
for (auto& member: distributed_members_) {
member.deserialize(stream);
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
void NetworkObjectBase::SerializeDestruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) {
vd_serializer_.RemoveRemoteSystemVariableHistory(con->GetRakNetGUID());
for (auto& member: distributed_members_) {
member.serialize(stream);
}
}
////////////////////////////////////////////////////////////////////////////////
bool NetworkObjectBase::DeserializeDestruction(RakNet::BitStream* stream, RakNet::Connection_RM3 *con) {
for (auto& member: distributed_members_) {
member.deserialize(stream);
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
RakNet::RM3ActionOnPopConnection NetworkObjectBase::QueryActionOnPopConnection(RakNet::Connection_RM3 *con) const {
return QueryActionOnPopConnection_PeerToPeer(con);
}
////////////////////////////////////////////////////////////////////////////////
void NetworkObjectBase::DeallocReplica(RakNet::Connection_RM3 *con) {
on_remote_delete();
}
////////////////////////////////////////////////////////////////////////////////
RakNet::RM3QuerySerializationResult NetworkObjectBase::QuerySerialization(RakNet::Connection_RM3 *con) {
return QuerySerialization_PeerToPeer(con);
}
////////////////////////////////////////////////////////////////////////////////
RakNet::RM3SerializationResult NetworkObjectBase::Serialize(RakNet::SerializeParameters *serializeParameters) {
RakNet::VariableDeltaSerializer::SerializationContext ctx;
serializeParameters->pro[0].reliability=RELIABLE_ORDERED;
vd_serializer_.BeginIdenticalSerialize(
&ctx,
serializeParameters->whenLastSerialized==0,
&serializeParameters->outputBitstream[0]
);
for (auto& member: distributed_members_) {
member.serialize(&ctx, &vd_serializer_);
}
vd_serializer_.EndSerialize(&ctx);
return RakNet::RM3SR_SERIALIZED_ALWAYS_IDENTICALLY;
}
////////////////////////////////////////////////////////////////////////////////
void NetworkObjectBase::Deserialize(RakNet::DeserializeParameters *deserializeParameters) {
RakNet::VariableDeltaSerializer::DeserializationContext ctx;
vd_serializer_.BeginDeserialize(&ctx, &deserializeParameters->serializationBitstream[0]);
for (auto& member: distributed_members_) {
member.deserialize(&ctx, &vd_serializer_);
}
vd_serializer_.EndDeserialize(&ctx);
}
////////////////////////////////////////////////////////////////////////////////
void NetworkObjectBase::OnUserReplicaPreSerializeTick(void) {
vd_serializer_.OnPreSerializeTick();
}
////////////////////////////////////////////////////////////////////////////////
void NetworkObjectBase::distribute_member(SerializableReference const& value) {
distributed_members_.push_back(value);
}
////////////////////////////////////////////////////////////////////////////////
}
<|endoftext|> |
<commit_before>/*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
fpa2bv_model_converter.h
Abstract:
Model conversion for fpa2bv_converter
Author:
Christoph (cwinter) 2012-02-09
Notes:
--*/
#include"ast_smt2_pp.h"
#include"fpa2bv_model_converter.h"
void fpa2bv_model_converter::display(std::ostream & out) {
out << "(fpa2bv-model-converter";
for (obj_map<func_decl, expr*>::iterator it = m_const2bv.begin();
it != m_const2bv.end();
it++) {
const symbol & n = it->m_key->get_name();
out << "\n (" << n << " ";
unsigned indent = n.size() + 4;
out << mk_ismt2_pp(it->m_value, m, indent) << ")";
}
for (obj_map<func_decl, expr*>::iterator it = m_rm_const2bv.begin();
it != m_rm_const2bv.end();
it++) {
const symbol & n = it->m_key->get_name();
out << "\n (" << n << " ";
unsigned indent = n.size() + 4;
out << mk_ismt2_pp(it->m_value, m, indent) << ")";
}
for (obj_map<func_decl, func_decl*>::iterator it = m_uf2bvuf.begin();
it != m_uf2bvuf.end();
it++) {
const symbol & n = it->m_key->get_name();
out << "\n (" << n << " ";
unsigned indent = n.size() + 4;
out << mk_ismt2_pp(it->m_value, m, indent) << ")";
}
out << ")" << std::endl;
}
model_converter * fpa2bv_model_converter::translate(ast_translation & translator) {
fpa2bv_model_converter * res = alloc(fpa2bv_model_converter, translator.to());
for (obj_map<func_decl, expr*>::iterator it = m_const2bv.begin();
it != m_const2bv.end();
it++)
{
func_decl * k = translator(it->m_key);
expr * v = translator(it->m_value);
res->m_const2bv.insert(k, v);
translator.to().inc_ref(k);
translator.to().inc_ref(v);
}
for (obj_map<func_decl, expr*>::iterator it = m_rm_const2bv.begin();
it != m_rm_const2bv.end();
it++)
{
func_decl * k = translator(it->m_key);
expr * v = translator(it->m_value);
res->m_rm_const2bv.insert(k, v);
translator.to().inc_ref(k);
translator.to().inc_ref(v);
}
return res;
}
expr_ref fpa2bv_model_converter::convert_bv2fp(sort * s, expr * sgn, expr * exp, expr * sig) const {
fpa_util fu(m);
bv_util bu(m);
unsynch_mpz_manager & mpzm = fu.fm().mpz_manager();
unsynch_mpq_manager & mpqm = fu.fm().mpq_manager();
expr_ref res(m);
mpf fp_val;
unsigned ebits = fu.get_ebits(s);
unsigned sbits = fu.get_sbits(s);
unsigned sgn_sz = 1;
unsigned exp_sz = ebits;
unsigned sig_sz = sbits - 1;
rational sgn_q(0), sig_q(0), exp_q(0);
if (sgn) bu.is_numeral(sgn, sgn_q, sgn_sz);
if (exp) bu.is_numeral(exp, exp_q, exp_sz);
if (sig) bu.is_numeral(sig, sig_q, sig_sz);
// un-bias exponent
rational exp_unbiased_q;
exp_unbiased_q = exp_q - fu.fm().m_powers2.m1(ebits - 1);
mpz sig_z; mpf_exp_t exp_z;
mpzm.set(sig_z, sig_q.to_mpq().numerator());
exp_z = mpzm.get_int64(exp_unbiased_q.to_mpq().numerator());
fu.fm().set(fp_val, ebits, sbits, !mpqm.is_zero(sgn_q.to_mpq()), sig_z, exp_z);
mpzm.del(sig_z);
res = fu.mk_value(fp_val);
TRACE("fpa2bv_mc", tout << "[" << mk_ismt2_pp(sgn, m) <<
" " << mk_ismt2_pp(exp, m) <<
" " << mk_ismt2_pp(sig, m) << "] == " <<
mk_ismt2_pp(res, m) << std::endl;);
return res;
}
expr_ref fpa2bv_model_converter::convert_bv2fp(model * bv_mdl, sort * s, expr * bv) const {
fpa_util fu(m);
bv_util bu(m);
SASSERT(bu.is_bv(bv));
unsigned ebits = fu.get_ebits(s);
unsigned sbits = fu.get_sbits(s);
unsigned bv_sz = sbits + ebits;
expr_ref sgn(m), exp(m), sig(m);
sgn = bu.mk_extract(bv_sz - 1, bv_sz - 1, bv);
exp = bu.mk_extract(bv_sz - 2, sbits - 1, bv);
sig = bu.mk_extract(sbits - 2, 0, bv);
expr_ref v_sgn(m), v_exp(m), v_sig(m);
bv_mdl->eval(sgn, v_sgn);
bv_mdl->eval(exp, v_exp);
bv_mdl->eval(sig, v_sig);
return convert_bv2fp(s, v_sgn, v_exp, v_sig);
}
expr_ref fpa2bv_model_converter::convert_bv2rm(expr * eval_v) const {
fpa_util fu(m);
bv_util bu(m);
expr_ref res(m);
rational bv_val(0);
unsigned sz = 0;
if (bu.is_numeral(eval_v, bv_val, sz)) {
SASSERT(bv_val.is_uint64());
switch (bv_val.get_uint64()) {
case BV_RM_TIES_TO_AWAY: res = fu.mk_round_nearest_ties_to_away(); break;
case BV_RM_TIES_TO_EVEN: res = fu.mk_round_nearest_ties_to_even(); break;
case BV_RM_TO_NEGATIVE: res = fu.mk_round_toward_negative(); break;
case BV_RM_TO_POSITIVE: res = fu.mk_round_toward_positive(); break;
case BV_RM_TO_ZERO:
default: res = fu.mk_round_toward_zero();
}
}
return res;
}
expr_ref fpa2bv_model_converter::convert_bv2rm(model * bv_mdl, func_decl * var, expr * val) const {
fpa_util fu(m);
bv_util bu(m);
expr_ref res(m);
expr_ref eval_v(m);
if (val && bv_mdl->eval(val, eval_v, true))
res = convert_bv2rm(eval_v);
return res;
}
void fpa2bv_model_converter::convert(model * bv_mdl, model * float_mdl) {
fpa_util fu(m);
bv_util bu(m);
unsynch_mpz_manager & mpzm = fu.fm().mpz_manager();
unsynch_mpq_manager & mpqm = fu.fm().mpq_manager();
TRACE("fpa2bv_mc", tout << "BV Model: " << std::endl;
for (unsigned i = 0; i < bv_mdl->get_num_constants(); i++)
tout << bv_mdl->get_constant(i)->get_name() << " --> " <<
mk_ismt2_pp(bv_mdl->get_const_interp(bv_mdl->get_constant(i)), m) << std::endl;
);
obj_hashtable<func_decl> seen;
for (obj_map<func_decl, expr*>::iterator it = m_const2bv.begin();
it != m_const2bv.end();
it++)
{
func_decl * var = it->m_key;
app * val = to_app(it->m_value);
SASSERT(fu.is_float(var->get_range()));
SASSERT(var->get_range()->get_num_parameters() == 2);
expr_ref sgn(m), sig(m), exp(m);
bv_mdl->eval(val->get_arg(0), sgn, true);
bv_mdl->eval(val->get_arg(1), exp, true);
bv_mdl->eval(val->get_arg(2), sig, true);
SASSERT(val->is_app_of(fu.get_family_id(), OP_FPA_FP));
#ifdef Z3DEBUG
SASSERT(to_app(val->get_arg(0))->get_decl()->get_arity() == 0);
SASSERT(to_app(val->get_arg(1))->get_decl()->get_arity() == 0);
SASSERT(to_app(val->get_arg(2))->get_decl()->get_arity() == 0);
seen.insert(to_app(val->get_arg(0))->get_decl());
seen.insert(to_app(val->get_arg(1))->get_decl());
seen.insert(to_app(val->get_arg(2))->get_decl());
#else
SASSERT(a->get_arg(0)->get_kind() == OP_EXTRACT);
SASSERT(to_app(a->get_arg(0))->get_arg(0)->get_kind() == OP_EXTRACT);
seen.insert(to_app(to_app(a->get_arg(0))->get_arg(0))->get_decl());
#endif
if (!sgn && !sig && !exp)
continue;
expr_ref cv(m);
cv = convert_bv2fp(var->get_range(), sgn, exp, sig);
float_mdl->register_decl(var, cv);
TRACE("fpa2bv_mc", tout << var->get_name() << " == " << mk_ismt2_pp(cv, m) << std::endl;);
}
for (obj_map<func_decl, expr*>::iterator it = m_rm_const2bv.begin();
it != m_rm_const2bv.end();
it++)
{
func_decl * var = it->m_key;
SASSERT(fu.is_rm(var->get_range()));
expr * val = it->m_value;
expr_ref fv(m);
fv = convert_bv2rm(bv_mdl, var, val);
TRACE("fpa2bv_mc", tout << var->get_name() << " == " << mk_ismt2_pp(fv, m) << std::endl;);
float_mdl->register_decl(var, fv);
seen.insert(to_app(val)->get_decl());
}
for (obj_map<func_decl, func_decl*>::iterator it = m_uf2bvuf.begin();
it != m_uf2bvuf.end();
it++) {
seen.insert(it->m_value);
func_decl * f = it->m_key;
unsigned arity = f->get_arity();
sort * rng = f->get_range();
func_interp * flt_fi = alloc(func_interp, m, f->get_arity());
func_interp * bv_fi = bv_mdl->get_func_interp(it->m_value);
SASSERT(bv_fi->args_are_values());
for (unsigned i = 0; i < bv_fi->num_entries(); i++) {
func_entry const * bv_fe = bv_fi->get_entry(i);
expr * const * bv_args = bv_fe->get_args();
expr_ref_buffer new_args(m);
for (unsigned j = 0; j < arity; j++) {
sort * dj = f->get_domain(j);
expr * aj = bv_args[j];
if (fu.is_float(dj))
new_args.push_back(convert_bv2fp(bv_mdl, dj, aj));
else if (fu.is_rm(dj)) {
expr_ref fv(m);
fv = convert_bv2rm(aj);
new_args.push_back(fv);
}
else
new_args.push_back(aj);
}
expr_ref ret(m);
ret = bv_fe->get_result();
if (fu.is_float(rng))
ret = convert_bv2fp(bv_mdl, rng, ret);
else if (fu.is_rm(rng))
ret = convert_bv2rm(ret);
flt_fi->insert_new_entry(new_args.c_ptr(), ret);
}
expr_ref els(m);
els = bv_fi->get_else();
if (fu.is_float(rng))
els = convert_bv2fp(bv_mdl, rng, els);
else if (fu.is_rm(rng))
els = convert_bv2rm(els);
flt_fi->set_else(els);
float_mdl->register_decl(f, flt_fi);
}
// Keep all the non-float constants.
unsigned sz = bv_mdl->get_num_constants();
for (unsigned i = 0; i < sz; i++)
{
func_decl * c = bv_mdl->get_constant(i);
if (!seen.contains(c))
float_mdl->register_decl(c, bv_mdl->get_const_interp(c));
}
// And keep everything else
sz = bv_mdl->get_num_functions();
for (unsigned i = 0; i < sz; i++)
{
func_decl * f = bv_mdl->get_function(i);
if (!seen.contains(f))
{
TRACE("fpa2bv_mc", tout << "Keeping: " << mk_ismt2_pp(f, m) << std::endl;);
func_interp * val = bv_mdl->get_func_interp(f);
float_mdl->register_decl(f, val);
}
}
sz = bv_mdl->get_num_uninterpreted_sorts();
for (unsigned i = 0; i < sz; i++)
{
sort * s = bv_mdl->get_uninterpreted_sort(i);
ptr_vector<expr> u = bv_mdl->get_universe(s);
float_mdl->register_usort(s, u.size(), u.c_ptr());
}
}
model_converter * mk_fpa2bv_model_converter(ast_manager & m,
obj_map<func_decl, expr*> const & const2bv,
obj_map<func_decl, expr*> const & rm_const2bv,
obj_map<func_decl, func_decl*> const & uf2bvuf) {
return alloc(fpa2bv_model_converter, m, const2bv, rm_const2bv, uf2bvuf);
}
<commit_msg>build fix<commit_after>/*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
fpa2bv_model_converter.h
Abstract:
Model conversion for fpa2bv_converter
Author:
Christoph (cwinter) 2012-02-09
Notes:
--*/
#include"ast_smt2_pp.h"
#include"fpa2bv_model_converter.h"
void fpa2bv_model_converter::display(std::ostream & out) {
out << "(fpa2bv-model-converter";
for (obj_map<func_decl, expr*>::iterator it = m_const2bv.begin();
it != m_const2bv.end();
it++) {
const symbol & n = it->m_key->get_name();
out << "\n (" << n << " ";
unsigned indent = n.size() + 4;
out << mk_ismt2_pp(it->m_value, m, indent) << ")";
}
for (obj_map<func_decl, expr*>::iterator it = m_rm_const2bv.begin();
it != m_rm_const2bv.end();
it++) {
const symbol & n = it->m_key->get_name();
out << "\n (" << n << " ";
unsigned indent = n.size() + 4;
out << mk_ismt2_pp(it->m_value, m, indent) << ")";
}
for (obj_map<func_decl, func_decl*>::iterator it = m_uf2bvuf.begin();
it != m_uf2bvuf.end();
it++) {
const symbol & n = it->m_key->get_name();
out << "\n (" << n << " ";
unsigned indent = n.size() + 4;
out << mk_ismt2_pp(it->m_value, m, indent) << ")";
}
out << ")" << std::endl;
}
model_converter * fpa2bv_model_converter::translate(ast_translation & translator) {
fpa2bv_model_converter * res = alloc(fpa2bv_model_converter, translator.to());
for (obj_map<func_decl, expr*>::iterator it = m_const2bv.begin();
it != m_const2bv.end();
it++)
{
func_decl * k = translator(it->m_key);
expr * v = translator(it->m_value);
res->m_const2bv.insert(k, v);
translator.to().inc_ref(k);
translator.to().inc_ref(v);
}
for (obj_map<func_decl, expr*>::iterator it = m_rm_const2bv.begin();
it != m_rm_const2bv.end();
it++)
{
func_decl * k = translator(it->m_key);
expr * v = translator(it->m_value);
res->m_rm_const2bv.insert(k, v);
translator.to().inc_ref(k);
translator.to().inc_ref(v);
}
return res;
}
expr_ref fpa2bv_model_converter::convert_bv2fp(sort * s, expr * sgn, expr * exp, expr * sig) const {
fpa_util fu(m);
bv_util bu(m);
unsynch_mpz_manager & mpzm = fu.fm().mpz_manager();
unsynch_mpq_manager & mpqm = fu.fm().mpq_manager();
expr_ref res(m);
mpf fp_val;
unsigned ebits = fu.get_ebits(s);
unsigned sbits = fu.get_sbits(s);
unsigned sgn_sz = 1;
unsigned exp_sz = ebits;
unsigned sig_sz = sbits - 1;
rational sgn_q(0), sig_q(0), exp_q(0);
if (sgn) bu.is_numeral(sgn, sgn_q, sgn_sz);
if (exp) bu.is_numeral(exp, exp_q, exp_sz);
if (sig) bu.is_numeral(sig, sig_q, sig_sz);
// un-bias exponent
rational exp_unbiased_q;
exp_unbiased_q = exp_q - fu.fm().m_powers2.m1(ebits - 1);
mpz sig_z; mpf_exp_t exp_z;
mpzm.set(sig_z, sig_q.to_mpq().numerator());
exp_z = mpzm.get_int64(exp_unbiased_q.to_mpq().numerator());
fu.fm().set(fp_val, ebits, sbits, !mpqm.is_zero(sgn_q.to_mpq()), sig_z, exp_z);
mpzm.del(sig_z);
res = fu.mk_value(fp_val);
TRACE("fpa2bv_mc", tout << "[" << mk_ismt2_pp(sgn, m) <<
" " << mk_ismt2_pp(exp, m) <<
" " << mk_ismt2_pp(sig, m) << "] == " <<
mk_ismt2_pp(res, m) << std::endl;);
return res;
}
expr_ref fpa2bv_model_converter::convert_bv2fp(model * bv_mdl, sort * s, expr * bv) const {
fpa_util fu(m);
bv_util bu(m);
SASSERT(bu.is_bv(bv));
unsigned ebits = fu.get_ebits(s);
unsigned sbits = fu.get_sbits(s);
unsigned bv_sz = sbits + ebits;
expr_ref sgn(m), exp(m), sig(m);
sgn = bu.mk_extract(bv_sz - 1, bv_sz - 1, bv);
exp = bu.mk_extract(bv_sz - 2, sbits - 1, bv);
sig = bu.mk_extract(sbits - 2, 0, bv);
expr_ref v_sgn(m), v_exp(m), v_sig(m);
bv_mdl->eval(sgn, v_sgn);
bv_mdl->eval(exp, v_exp);
bv_mdl->eval(sig, v_sig);
return convert_bv2fp(s, v_sgn, v_exp, v_sig);
}
expr_ref fpa2bv_model_converter::convert_bv2rm(expr * eval_v) const {
fpa_util fu(m);
bv_util bu(m);
expr_ref res(m);
rational bv_val(0);
unsigned sz = 0;
if (bu.is_numeral(eval_v, bv_val, sz)) {
SASSERT(bv_val.is_uint64());
switch (bv_val.get_uint64()) {
case BV_RM_TIES_TO_AWAY: res = fu.mk_round_nearest_ties_to_away(); break;
case BV_RM_TIES_TO_EVEN: res = fu.mk_round_nearest_ties_to_even(); break;
case BV_RM_TO_NEGATIVE: res = fu.mk_round_toward_negative(); break;
case BV_RM_TO_POSITIVE: res = fu.mk_round_toward_positive(); break;
case BV_RM_TO_ZERO:
default: res = fu.mk_round_toward_zero();
}
}
return res;
}
expr_ref fpa2bv_model_converter::convert_bv2rm(model * bv_mdl, func_decl * var, expr * val) const {
fpa_util fu(m);
bv_util bu(m);
expr_ref res(m);
expr_ref eval_v(m);
if (val && bv_mdl->eval(val, eval_v, true))
res = convert_bv2rm(eval_v);
return res;
}
void fpa2bv_model_converter::convert(model * bv_mdl, model * float_mdl) {
fpa_util fu(m);
bv_util bu(m);
unsynch_mpz_manager & mpzm = fu.fm().mpz_manager();
unsynch_mpq_manager & mpqm = fu.fm().mpq_manager();
TRACE("fpa2bv_mc", tout << "BV Model: " << std::endl;
for (unsigned i = 0; i < bv_mdl->get_num_constants(); i++)
tout << bv_mdl->get_constant(i)->get_name() << " --> " <<
mk_ismt2_pp(bv_mdl->get_const_interp(bv_mdl->get_constant(i)), m) << std::endl;
);
obj_hashtable<func_decl> seen;
for (obj_map<func_decl, expr*>::iterator it = m_const2bv.begin();
it != m_const2bv.end();
it++)
{
func_decl * var = it->m_key;
app * val = to_app(it->m_value);
SASSERT(fu.is_float(var->get_range()));
SASSERT(var->get_range()->get_num_parameters() == 2);
expr_ref sgn(m), sig(m), exp(m);
bv_mdl->eval(val->get_arg(0), sgn, true);
bv_mdl->eval(val->get_arg(1), exp, true);
bv_mdl->eval(val->get_arg(2), sig, true);
SASSERT(val->is_app_of(fu.get_family_id(), OP_FPA_FP));
#ifdef Z3DEBUG
SASSERT(to_app(val->get_arg(0))->get_decl()->get_arity() == 0);
SASSERT(to_app(val->get_arg(1))->get_decl()->get_arity() == 0);
SASSERT(to_app(val->get_arg(2))->get_decl()->get_arity() == 0);
seen.insert(to_app(val->get_arg(0))->get_decl());
seen.insert(to_app(val->get_arg(1))->get_decl());
seen.insert(to_app(val->get_arg(2))->get_decl());
#else
SASSERT(a->get_arg(0)->get_kind() == OP_EXTRACT);
SASSERT(to_app(a->get_arg(0))->get_arg(0)->get_kind() == OP_EXTRACT);
seen.insert(to_app(to_app(val->get_arg(0))->get_arg(0))->get_decl());
#endif
if (!sgn && !sig && !exp)
continue;
expr_ref cv(m);
cv = convert_bv2fp(var->get_range(), sgn, exp, sig);
float_mdl->register_decl(var, cv);
TRACE("fpa2bv_mc", tout << var->get_name() << " == " << mk_ismt2_pp(cv, m) << std::endl;);
}
for (obj_map<func_decl, expr*>::iterator it = m_rm_const2bv.begin();
it != m_rm_const2bv.end();
it++)
{
func_decl * var = it->m_key;
SASSERT(fu.is_rm(var->get_range()));
expr * val = it->m_value;
expr_ref fv(m);
fv = convert_bv2rm(bv_mdl, var, val);
TRACE("fpa2bv_mc", tout << var->get_name() << " == " << mk_ismt2_pp(fv, m) << std::endl;);
float_mdl->register_decl(var, fv);
seen.insert(to_app(val)->get_decl());
}
for (obj_map<func_decl, func_decl*>::iterator it = m_uf2bvuf.begin();
it != m_uf2bvuf.end();
it++) {
seen.insert(it->m_value);
func_decl * f = it->m_key;
unsigned arity = f->get_arity();
sort * rng = f->get_range();
func_interp * flt_fi = alloc(func_interp, m, f->get_arity());
func_interp * bv_fi = bv_mdl->get_func_interp(it->m_value);
SASSERT(bv_fi->args_are_values());
for (unsigned i = 0; i < bv_fi->num_entries(); i++) {
func_entry const * bv_fe = bv_fi->get_entry(i);
expr * const * bv_args = bv_fe->get_args();
expr_ref_buffer new_args(m);
for (unsigned j = 0; j < arity; j++) {
sort * dj = f->get_domain(j);
expr * aj = bv_args[j];
if (fu.is_float(dj))
new_args.push_back(convert_bv2fp(bv_mdl, dj, aj));
else if (fu.is_rm(dj)) {
expr_ref fv(m);
fv = convert_bv2rm(aj);
new_args.push_back(fv);
}
else
new_args.push_back(aj);
}
expr_ref ret(m);
ret = bv_fe->get_result();
if (fu.is_float(rng))
ret = convert_bv2fp(bv_mdl, rng, ret);
else if (fu.is_rm(rng))
ret = convert_bv2rm(ret);
flt_fi->insert_new_entry(new_args.c_ptr(), ret);
}
expr_ref els(m);
els = bv_fi->get_else();
if (fu.is_float(rng))
els = convert_bv2fp(bv_mdl, rng, els);
else if (fu.is_rm(rng))
els = convert_bv2rm(els);
flt_fi->set_else(els);
float_mdl->register_decl(f, flt_fi);
}
// Keep all the non-float constants.
unsigned sz = bv_mdl->get_num_constants();
for (unsigned i = 0; i < sz; i++)
{
func_decl * c = bv_mdl->get_constant(i);
if (!seen.contains(c))
float_mdl->register_decl(c, bv_mdl->get_const_interp(c));
}
// And keep everything else
sz = bv_mdl->get_num_functions();
for (unsigned i = 0; i < sz; i++)
{
func_decl * f = bv_mdl->get_function(i);
if (!seen.contains(f))
{
TRACE("fpa2bv_mc", tout << "Keeping: " << mk_ismt2_pp(f, m) << std::endl;);
func_interp * val = bv_mdl->get_func_interp(f);
float_mdl->register_decl(f, val);
}
}
sz = bv_mdl->get_num_uninterpreted_sorts();
for (unsigned i = 0; i < sz; i++)
{
sort * s = bv_mdl->get_uninterpreted_sort(i);
ptr_vector<expr> u = bv_mdl->get_universe(s);
float_mdl->register_usort(s, u.size(), u.c_ptr());
}
}
model_converter * mk_fpa2bv_model_converter(ast_manager & m,
obj_map<func_decl, expr*> const & const2bv,
obj_map<func_decl, expr*> const & rm_const2bv,
obj_map<func_decl, func_decl*> const & uf2bvuf) {
return alloc(fpa2bv_model_converter, m, const2bv, rm_const2bv, uf2bvuf);
}
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include <ostream>
#include <istream>
#include <fstream>
struct VabHeader
{
VabHeader( std::istream& aStream )
{
Read( aStream );
}
void Read( std::istream& aStream )
{
aStream.read( reinterpret_cast< char* > ( &iForm ), sizeof( iForm ) );
aStream.read( reinterpret_cast< char* > ( &iVersion ), sizeof( iVersion ) );
aStream.read( reinterpret_cast< char* > ( &iId ), sizeof( iId ) );
aStream.read( reinterpret_cast< char* > ( &iFileSize ), sizeof( iFileSize ) );
aStream.read( reinterpret_cast< char* > ( &iReserved0 ), sizeof( iReserved0 ) );
aStream.read( reinterpret_cast< char* > ( &iNumProgs ), sizeof( iNumProgs ) );
aStream.read( reinterpret_cast< char* > ( &iNumTones ), sizeof( iNumTones ) );
aStream.read( reinterpret_cast< char* > ( &iNumVags ), sizeof( iNumVags ) );
aStream.read( reinterpret_cast< char* > ( &iMasterVol ), sizeof( iMasterVol ) );
aStream.read( reinterpret_cast< char* > ( &iMasterPan ), sizeof( iMasterPan ) );
aStream.read( reinterpret_cast< char* > ( &iAttr1 ), sizeof( iAttr1 ) );
aStream.read( reinterpret_cast< char* > ( &iAttr2 ), sizeof( iAttr2 ) );
aStream.read( reinterpret_cast< char* > ( &iReserved1 ), sizeof( iReserved1 ) );
}
unsigned int iForm; // Always "VABp"
unsigned int iVersion; // Header version
unsigned int iId; // Bank Id
unsigned int iFileSize; // File size
unsigned short int iReserved0; // Not used
unsigned short int iNumProgs;
unsigned short int iNumTones;
unsigned short int iNumVags;
unsigned char iMasterVol;
unsigned char iMasterPan;
unsigned char iAttr1;
unsigned char iAttr2;
unsigned int iReserved1;
};
// program (instrument) level for example "piano", "drum", "guitar" and "effect sound".
struct VagAtr;
struct ProgAtr
{
ProgAtr( std::istream& aStream )
{
Read( aStream );
}
void Read( std::istream& aStream )
{
aStream.read( reinterpret_cast< char* > ( &iNumTones ), sizeof( iNumTones ) );
aStream.read( reinterpret_cast< char* > ( &iVol ), sizeof( iVol ) );
aStream.read( reinterpret_cast< char* > ( &iPriority ), sizeof( iPriority ) );
aStream.read( reinterpret_cast< char* > ( &iMode ), sizeof( iMode ) );
aStream.read( reinterpret_cast< char* > ( &iPan ), sizeof( iPan ) );
aStream.read( reinterpret_cast< char* > ( &iReserved0 ), sizeof( iReserved0 ) );
aStream.read( reinterpret_cast< char* > ( &iAttr ), sizeof( iAttr ) );
aStream.read( reinterpret_cast< char* > ( &iReserved1 ), sizeof( iReserved1 ) );
aStream.read( reinterpret_cast< char* > ( &iReserved2 ), sizeof( iReserved2 ) );
}
unsigned char iNumTones; // Number of valid entries in iTones
unsigned char iVol;
unsigned char iPriority;
unsigned char iMode;
unsigned char iPan;
unsigned char iReserved0;
unsigned short int iAttr;
unsigned int iReserved1;
unsigned int iReserved2;
std::vector< VagAtr* > iTones;
};
// vag/tone/waves that are linked to an instrument
struct VagAtr
{
VagAtr( std::istream& aStream )
{
Read( aStream );
}
void Read( std::istream& aStream )
{
aStream.read( reinterpret_cast< char* > ( &iPriority ), sizeof( iPriority ) );
aStream.read( reinterpret_cast< char* > ( &iMode ), sizeof( iMode ) );
aStream.read( reinterpret_cast< char* > ( &iVol ), sizeof( iVol ) );
aStream.read( reinterpret_cast< char* > ( &iPan ), sizeof( iPan ) );
aStream.read( reinterpret_cast< char* > ( &iCenter ), sizeof( iCenter ) );
aStream.read( reinterpret_cast< char* > ( &iShift ), sizeof( iShift ) );
aStream.read( reinterpret_cast< char* > ( &iMin ), sizeof( iMin ) );
aStream.read( reinterpret_cast< char* > ( &iMax ), sizeof( iMax ) );
aStream.read( reinterpret_cast< char* > ( &iVibW ), sizeof( iVibW ) );
aStream.read( reinterpret_cast< char* > ( &iVibT ), sizeof( iVibT ) );
aStream.read( reinterpret_cast< char* > ( &iPorW ), sizeof( iPorW ) );
aStream.read( reinterpret_cast< char* > ( &iPorT ), sizeof( iPorT ) );
aStream.read( reinterpret_cast< char* > ( &iPitchBendMin ), sizeof( iPitchBendMin ) );
aStream.read( reinterpret_cast< char* > ( &iPitchBendMax ), sizeof( iPitchBendMax ) );
aStream.read( reinterpret_cast< char* > ( &iReserved1 ), sizeof( iReserved1 ) );
aStream.read( reinterpret_cast< char* > ( &iReserved2 ), sizeof( iReserved2 ) );
aStream.read( reinterpret_cast< char* > ( &iAdsr1 ), sizeof( iAdsr1 ) );
aStream.read( reinterpret_cast< char* > ( &iAdsr2 ), sizeof( iAdsr2 ) );
aStream.read( reinterpret_cast< char* > ( &iProg ), sizeof( iProg ) );
aStream.read( reinterpret_cast< char* > ( &iVag ), sizeof( iVag ) );
aStream.read( reinterpret_cast< char* > ( &iReserved[0] ), sizeof( iReserved ) );
}
unsigned char iPriority;
unsigned char iMode;
unsigned char iVol;
unsigned char iPan;
unsigned char iCenter;
unsigned char iShift;
unsigned char iMin;
unsigned char iMax;
unsigned char iVibW;
unsigned char iVibT;
unsigned char iPorW;
unsigned char iPorT;
unsigned char iPitchBendMin;
unsigned char iPitchBendMax;
unsigned char iReserved1;
unsigned char iReserved2;
unsigned short int iAdsr1;
unsigned short int iAdsr2;
short int iProg; // Which progAttr we live in?
short int iVag; // Sound index in the VB
short int iReserved[4];
};
// AE VAB header points into sounds.dat!
// A record in the VB!! file not the VH!!
struct AEVh
{
AEVh( std::istream& aStream )
{
Read( aStream );
}
void Read( std::istream& aStream )
{
aStream.read( reinterpret_cast< char* > ( &iLengthOrDuration ), sizeof( iLengthOrDuration ) );
aStream.read( reinterpret_cast< char* > ( &iUnusedByEngine ), sizeof( iUnusedByEngine ) );
aStream.read( reinterpret_cast< char* > ( &iFileOffset ), sizeof( iFileOffset ) );
}
unsigned int iLengthOrDuration;
unsigned int iUnusedByEngine; // khz, 44100, or 8000 seen? aka bit rate then?
unsigned int iFileOffset;
};
struct AoVag
{
unsigned int iSize;
unsigned int iSampleRate;
std::vector< unsigned char > iSampleData;
};
class Vab
{
public:
Vab();
Vab( std::string aVhFile, std::string aVbFile );
void LoadVbFile( std::string aFileName );
void ReadVb( std::istream& aStream );
void LoadVhFile( std::string aFileName );
void ReadVh( std::istream& aStream );
public:
VabHeader* iHeader; // File header
std::vector< ProgAtr* > iProgs; // Always 128 of these - must be what the midi data is indexing into?
std::vector< VagAtr* > iTones; // always 16 * num progs? Also called a tone??
// VAG Data body / (VB 254 VAG data) ("Samples" in AE?)
// 512bytes /2 = 256 samps max
std::vector< AEVh* > iOffs;
std::vector< AoVag* > iAoVags;
std::ifstream iSoundsDat;
// What about AO? Seems the same as sounds.dat but in each VB file
};
<commit_msg>Update vab.hpp<commit_after>#pragma once
#include <vector>
#include <ostream>
#include <istream>
#include <fstream>
struct VabHeader
{
VabHeader( std::istream& aStream )
{
Read( aStream );
}
void Read( std::istream& aStream )
{
aStream.read( reinterpret_cast< char* > ( &iForm ), sizeof( iForm ) );
aStream.read( reinterpret_cast< char* > ( &iVersion ), sizeof( iVersion ) );
aStream.read( reinterpret_cast< char* > ( &iId ), sizeof( iId ) );
aStream.read( reinterpret_cast< char* > ( &iFileSize ), sizeof( iFileSize ) );
aStream.read( reinterpret_cast< char* > ( &iReserved0 ), sizeof( iReserved0 ) );
aStream.read( reinterpret_cast< char* > ( &iNumProgs ), sizeof( iNumProgs ) );
aStream.read( reinterpret_cast< char* > ( &iNumTones ), sizeof( iNumTones ) );
aStream.read( reinterpret_cast< char* > ( &iNumVags ), sizeof( iNumVags ) );
aStream.read( reinterpret_cast< char* > ( &iMasterVol ), sizeof( iMasterVol ) );
aStream.read( reinterpret_cast< char* > ( &iMasterPan ), sizeof( iMasterPan ) );
aStream.read( reinterpret_cast< char* > ( &iAttr1 ), sizeof( iAttr1 ) );
aStream.read( reinterpret_cast< char* > ( &iAttr2 ), sizeof( iAttr2 ) );
aStream.read( reinterpret_cast< char* > ( &iReserved1 ), sizeof( iReserved1 ) );
}
unsigned int iForm; // Always "VABp"
unsigned int iVersion; // Header version
unsigned int iId; // Bank Id
unsigned int iFileSize; // File size
unsigned short int iReserved0; // Not used
unsigned short int iNumProgs;
unsigned short int iNumTones;
unsigned short int iNumVags;
unsigned char iMasterVol;
unsigned char iMasterPan;
unsigned char iAttr1;
unsigned char iAttr2;
unsigned int iReserved1;
};
// program (instrument) level for example "piano", "drum", "guitar" and "effect sound".
struct VagAtr;
struct ProgAtr
{
ProgAtr( std::istream& aStream )
{
Read( aStream );
}
void Read( std::istream& aStream )
{
aStream.read( reinterpret_cast< char* > ( &iNumTones ), sizeof( iNumTones ) );
aStream.read( reinterpret_cast< char* > ( &iVol ), sizeof( iVol ) );
aStream.read( reinterpret_cast< char* > ( &iPriority ), sizeof( iPriority ) );
aStream.read( reinterpret_cast< char* > ( &iMode ), sizeof( iMode ) );
aStream.read( reinterpret_cast< char* > ( &iPan ), sizeof( iPan ) );
aStream.read( reinterpret_cast< char* > ( &iReserved0 ), sizeof( iReserved0 ) );
aStream.read( reinterpret_cast< char* > ( &iAttr ), sizeof( iAttr ) );
aStream.read( reinterpret_cast< char* > ( &iReserved1 ), sizeof( iReserved1 ) );
aStream.read( reinterpret_cast< char* > ( &iReserved2 ), sizeof( iReserved2 ) );
}
unsigned char iNumTones; // Number of valid entries in iTones
unsigned char iVol;
unsigned char iPriority;
unsigned char iMode;
unsigned char iPan;
unsigned char iReserved0;
unsigned short int iAttr;
unsigned int iReserved1;
unsigned int iReserved2;
std::vector< VagAtr* > iTones;
};
// vag/tone/waves that are linked to an instrument
struct VagAtr
{
VagAtr( std::istream& aStream )
{
Read( aStream );
}
void Read( std::istream& aStream )
{
aStream.read( reinterpret_cast< char* > ( &iPriority ), sizeof( iPriority ) );
aStream.read( reinterpret_cast< char* > ( &iMode ), sizeof( iMode ) );
aStream.read( reinterpret_cast< char* > ( &iVol ), sizeof( iVol ) );
aStream.read( reinterpret_cast< char* > ( &iPan ), sizeof( iPan ) );
aStream.read( reinterpret_cast< char* > ( &iCenter ), sizeof( iCenter ) );
aStream.read( reinterpret_cast< char* > ( &iShift ), sizeof( iShift ) );
aStream.read( reinterpret_cast< char* > ( &iMin ), sizeof( iMin ) );
aStream.read( reinterpret_cast< char* > ( &iMax ), sizeof( iMax ) );
aStream.read( reinterpret_cast< char* > ( &iVibW ), sizeof( iVibW ) );
aStream.read( reinterpret_cast< char* > ( &iVibT ), sizeof( iVibT ) );
aStream.read( reinterpret_cast< char* > ( &iPorW ), sizeof( iPorW ) );
aStream.read( reinterpret_cast< char* > ( &iPorT ), sizeof( iPorT ) );
aStream.read( reinterpret_cast< char* > ( &iPitchBendMin ), sizeof( iPitchBendMin ) );
aStream.read( reinterpret_cast< char* > ( &iPitchBendMax ), sizeof( iPitchBendMax ) );
aStream.read( reinterpret_cast< char* > ( &iReserved1 ), sizeof( iReserved1 ) );
aStream.read( reinterpret_cast< char* > ( &iReserved2 ), sizeof( iReserved2 ) );
aStream.read( reinterpret_cast< char* > ( &iAdsr1 ), sizeof( iAdsr1 ) );
aStream.read( reinterpret_cast< char* > ( &iAdsr2 ), sizeof( iAdsr2 ) );
aStream.read( reinterpret_cast< char* > ( &iProg ), sizeof( iProg ) );
aStream.read( reinterpret_cast< char* > ( &iVag ), sizeof( iVag ) );
aStream.read( reinterpret_cast< char* > ( &iReserved[0] ), sizeof( iReserved ) );
}
unsigned char iPriority;
// 0 = normal, 4 = reverb
unsigned char iMode;
// volume 0-127
unsigned char iVol;
// panning 0-127
unsigned char iPan;
// "Default" note
unsigned char iCenter;
unsigned char iShift;
// Key range which this waveform maps to
unsigned char iMin;
unsigned char iMax;
// Maybe these are not used?
unsigned char iVibW;
unsigned char iVibT;
unsigned char iPorW;
unsigned char iPorT;
// Min/max pitch values
unsigned char iPitchBendMin;
unsigned char iPitchBendMax;
// Not used
unsigned char iReserved1;
unsigned char iReserved2;
// adsr1
// 0-127 attack rate (byte)
// 0-15 decay rate (nibble)
// 0-127 sustain rate (byte)
// adsr2
// 0-31 release rate (6bits)
// 0-15 sustain rate (nibble)
// 1+0.5+1+0.6+0.5=3.6 bytes
unsigned short int iAdsr1;
unsigned short int iAdsr2;
short int iProg; // Which progAttr we live in?
short int iVag; // Sound index in the VB
short int iReserved[4];
};
// AE VAB header points into sounds.dat!
// A record in the VB!! file not the VH!!
struct AEVh
{
AEVh( std::istream& aStream )
{
Read( aStream );
}
void Read( std::istream& aStream )
{
aStream.read( reinterpret_cast< char* > ( &iLengthOrDuration ), sizeof( iLengthOrDuration ) );
aStream.read( reinterpret_cast< char* > ( &iUnusedByEngine ), sizeof( iUnusedByEngine ) );
aStream.read( reinterpret_cast< char* > ( &iFileOffset ), sizeof( iFileOffset ) );
}
unsigned int iLengthOrDuration;
unsigned int iUnusedByEngine; // khz, 44100, or 8000 seen? aka bit rate then?
unsigned int iFileOffset;
};
struct AoVag
{
unsigned int iSize;
unsigned int iSampleRate;
std::vector< unsigned char > iSampleData;
};
class Vab
{
public:
Vab();
Vab( std::string aVhFile, std::string aVbFile );
void LoadVbFile( std::string aFileName );
void ReadVb( std::istream& aStream );
void LoadVhFile( std::string aFileName );
void ReadVh( std::istream& aStream );
public:
VabHeader* iHeader; // File header
std::vector< ProgAtr* > iProgs; // Always 128 of these - must be what the midi data is indexing into?
std::vector< VagAtr* > iTones; // always 16 * num progs? Also called a tone??
// VAG Data body / (VB 254 VAG data) ("Samples" in AE?)
// 512bytes /2 = 256 samps max
std::vector< AEVh* > iOffs;
std::vector< AoVag* > iAoVags;
std::ifstream iSoundsDat;
// What about AO? Seems the same as sounds.dat but in each VB file
};
<|endoftext|> |
<commit_before>#include <iostream>
#include <stack>
int main()
{
std::stack<int> s;
int val = 0;
while(std::cin >> val)
s.push(val);
std::cout << "popping..." << std::endl;
while(!s.empty())
{
// val = s.pop();
std::cout << s.top() << std::endl;
s.pop();
}
}<commit_msg>Stack STL test<commit_after>#include <iostream>
#include <stack>
int main()
{
std::stack<int> s;
int val = 0;
while(std::cin >> val)
s.push(val);
std::cout << "popping..." << std::endl;
while(!s.empty())
{
std::cout << s.top() << std::endl;
s.pop();
}
}<|endoftext|> |
<commit_before>/*
* qiaffine.cpp
*
* Copyright (c) 2015 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <iostream>
#include "itkImage.h"
#include "itkVersor.h"
#include "itkVersorRigid3DTransform.h"
#include "itkCenteredAffineTransform.h"
#include "itkTransformFileWriter.h"
#include "itkPermuteAxesImageFilter.h"
#include "itkFlipImageFilter.h"
#include "QI/Util.h"
#include "QI/IO.h"
#include "QI/Args.h"
using namespace std;
/*
* Declare arguments here so they are available to pipeline
*/
args::ArgumentParser parser("Applies simple affine transformations to images by manipulating the header\n"
"transforms. If an output file is not specified, the input file will be\n"
"overwritten.\n"
"http://github.com/spinicist/QUIT");
args::Positional<std::string> source_path(parser, "SOURCE", "Source file");
args::Positional<std::string> dest_path(parser, "DEST", "Destination file");
args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"});
args::Flag verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
args::Flag center(parser, "CENTER", "Set the origin to the center of the image", {'c', "center"});
args::ValueFlag<std::string> tfm_path(parser, "TFM", "Write out the transformation to a file", {'t', "tfm"});
args::ValueFlag<double> scale(parser, "SCALE", "Scale by a constant", {'s', "scale"});
args::ValueFlag<double> offX(parser, "OFF_X", "Translate origin in X direction", {"offX"});
args::ValueFlag<double> offY(parser, "OFF_Y", "Translate origin in Y direction", {"offY"});
args::ValueFlag<double> offZ(parser, "OFF_Z", "Translate origin in Z direction", {"offZ"});
args::ValueFlag<double> rotX(parser, "ROT_X", "Rotate about X-axis by angle (degrees)", {"rotX"});
args::ValueFlag<double> rotY(parser, "ROT_Y", "Rotate about Y-axis by angle (degrees)", {"rotY"});
args::ValueFlag<double> rotZ(parser, "ROT_Z", "Rotate about Z-axis by angle (degrees)", {"rotZ"});
args::ValueFlag<std::string> permute(parser, "PERMUTE", "Permute axes, e.g. 2,0,1. Negative values mean flip as well", {"permute"});
args::ValueFlag<std::string> flip(parser, "FLIP", "Flip an axis, e.g. 0,1,0. Occurs AFTER any permutation.", {"flip"});
template<typename TImage>
int Pipeline() {
auto image = QI::ReadImage<TImage>(QI::CheckPos(source_path));
// Permute if required
if (permute) {
auto permute_filter = itk::PermuteAxesImageFilter<TImage>::New();
itk::FixedArray<unsigned int, TImage::ImageDimension> permute_order;
std::istringstream iss(permute.Get());
std::string el;
for (int i = 0; i < 3; i++) {
std::getline(iss, el, ',');
permute_order[i] = std::stoi(el);
}
for (int i = 3; i < TImage::ImageDimension; i++) {
permute_order[i] = i;
}
if (!iss)
QI_FAIL("Failed to read permutation order: " << permute.Get());
permute_filter->SetInput(image);
permute_filter->SetOrder(permute_order);
permute_filter->Update();
image = permute_filter->GetOutput();
image->DisconnectPipeline();
}
// Flip if required
if (flip) {
auto flip_filter = itk::FlipImageFilter<TImage>::New();
itk::FixedArray<bool, TImage::ImageDimension> flip_axes; // Save this
std::istringstream iss(flip.Get());
std::string el;
for (int i = 0; i < 3; i++) {
std::getline(iss, el, ',');
flip_axes[i] = (std::stoi(el) > 0);
}
for (int i = 3; i < TImage::ImageDimension; i++) {
flip_axes[i] = false;
}
if (!iss)
QI_FAIL("Failed to read flip: " << flip.Get());
if (verbose) std::cout << "Flipping: " << flip_axes << std::endl;
flip_filter->SetInput(image);
flip_filter->SetFlipAxes(flip_axes);
flip_filter->SetFlipAboutOrigin(false);
flip_filter->Update();
image = flip_filter->GetOutput();
image->DisconnectPipeline();
}
typename TImage::DirectionType fullDir = image->GetDirection();
typename TImage::SpacingType fullSpacing = image->GetSpacing();
typename TImage::PointType fullOrigin = image->GetOrigin();
typename TImage::SizeType fullSize = image->GetLargestPossibleRegion().GetSize();
QI::VolumeF::DirectionType direction;
QI::VolumeF::SpacingType spacing;
typedef itk::CenteredAffineTransform<double, 3> TAffine;
TAffine::OutputVectorType origin;
QI::VolumeF::SizeType size;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
direction[i][j] = fullDir[i][j];
}
origin[i] = fullOrigin[i];
spacing[i] = fullSpacing[i];
size[i] = fullSize[i];
}
auto img_tfm = TAffine::New();
img_tfm->SetMatrix(direction);
img_tfm->Scale(spacing);
img_tfm->Translate(origin);
if (verbose) std::cout << "Start transform:\n" << img_tfm->GetMatrix() << std::endl;
auto tfm = TAffine::New();
if (scale) {
if (verbose) cout << "Scaling by factor " << scale.Get() << endl;
tfm->Scale(scale.Get());
}
if (rotX != 0.0) {
if (verbose) cout << "Rotating image by " << rotX.Get() << " around X axis." << endl;
tfm->Rotate(1,2,rotX.Get() * M_PI / 180.0);
}
if (rotY != 0.0) {
if (verbose) cout << "Rotating image by " << rotY.Get() << " around X axis." << endl;
tfm->Rotate(2,0,rotY.Get() * M_PI / 180.0);
}
if (rotZ != 0.0) {
if (verbose) cout << "Rotating image by " << rotZ.Get() << " around X axis." << endl;
tfm->Rotate(0,1,rotZ.Get() * M_PI / 180.0);
}
itk::Versor<double>::VectorType offset; offset.Fill(0);
if (center) {
for (int i = 0; i < 3; i++) {
offset[i] = origin[i]-spacing[i]*size[i] / 2;
}
if (verbose) std::cout << "Centering image" << std::endl;
tfm->Translate(-offset);
} else if (offX || offY || offZ) {
offset[0] = offX.Get();
offset[1] = offY.Get();
offset[2] = offZ.Get();
if (verbose) std::cout << "Translating by: " << offset << std::endl;
tfm->Translate(-offset);
}
if (tfm_path) { // Output the transform file
auto writer = itk::TransformFileWriterTemplate<double>::New();
writer->SetInput(tfm);
writer->SetFileName(tfm_path.Get());
writer->Update();
}
img_tfm->Compose(tfm);
itk::CenteredAffineTransform<double, 3>::MatrixType fmat = img_tfm->GetMatrix();
if (verbose) std::cout << "Final transform:\n" << fmat << std::endl;
for (int i = 0; i < 3; i++) {
fullOrigin[i] = img_tfm->GetOffset()[i];
}
for (int j = 0; j < 3; j++) {
double scale = 0.;
for (int i = 0; i < 3; i++) {
scale += fmat[i][j]*fmat[i][j];
}
scale = sqrt(scale);
fullSpacing[j] = scale;
for (int i = 0; i < 3; i++) {
fullDir[i][j] = fmat[i][j] / scale;
}
}
image->SetDirection(fullDir);
image->SetOrigin(fullOrigin);
image->SetSpacing(fullSpacing);
// Write out the edited file
if (dest_path) {
QI::WriteImage(image, dest_path.Get());
} else {
QI::WriteImage(image, source_path.Get());
}
return EXIT_SUCCESS;
}
int main(int argc, char **argv) {
QI::ParseArgs(parser, argc, argv);
if (verbose) std::cout << "Reading header for: " << QI::CheckPos(source_path) << std::endl;
auto header = itk::ImageIOFactory::CreateImageIO(QI::CheckPos(source_path).c_str(), itk::ImageIOFactory::ReadMode);
header->SetFileName(source_path.Get());
header->ReadImageInformation();
auto dims = header->GetNumberOfDimensions();
auto dtype = header->GetComponentType();
if (verbose) std::cout << "Datatype is " << header->GetComponentTypeAsString( dtype ) << std::endl;
#define DIM_SWITCH( TYPE ) \
switch (dims) { \
case 3: return Pipeline<itk::Image< TYPE , 3 >>(); \
case 4: return Pipeline<itk::Image< TYPE , 4 >>(); \
default: QI_FAIL("Unsupported dimension: " << dims); return EXIT_FAILURE; \
}
switch (dtype) {
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: QI_FAIL("Unknown component type in image " << source_path);
case itk::ImageIOBase::UCHAR: DIM_SWITCH( unsigned char ); break;
case itk::ImageIOBase::CHAR: DIM_SWITCH( char ); break;
case itk::ImageIOBase::USHORT: DIM_SWITCH( unsigned short ); break;
case itk::ImageIOBase::SHORT: DIM_SWITCH( short ); break;
case itk::ImageIOBase::UINT: DIM_SWITCH( unsigned int ); break;
case itk::ImageIOBase::INT: DIM_SWITCH( int ); break;
case itk::ImageIOBase::ULONG: DIM_SWITCH( unsigned long ); break;
case itk::ImageIOBase::LONG: DIM_SWITCH( long ); break;
case itk::ImageIOBase::FLOAT: DIM_SWITCH( float ); break;
case itk::ImageIOBase::DOUBLE: DIM_SWITCH( double ); break;
}
}
<commit_msg>ENH: Added CoG centering<commit_after>/*
* qiaffine.cpp
*
* Copyright (c) 2015 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <iostream>
#include "itkImage.h"
#include "itkVersor.h"
#include "itkVersorRigid3DTransform.h"
#include "itkCenteredAffineTransform.h"
#include "itkTransformFileWriter.h"
#include "itkPermuteAxesImageFilter.h"
#include "itkFlipImageFilter.h"
#include "itkImageMomentsCalculator.h"
#include "QI/Util.h"
#include "QI/IO.h"
#include "QI/Args.h"
using namespace std;
/*
* Declare arguments here so they are available to pipeline
*/
args::ArgumentParser parser("Applies simple affine transformations to images by manipulating the header\n"
"transforms. If an output file is not specified, the input file will be\n"
"overwritten.\n"
"http://github.com/spinicist/QUIT");
args::Positional<std::string> source_path(parser, "SOURCE", "Source file");
args::Positional<std::string> dest_path(parser, "DEST", "Destination file");
args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"});
args::Flag verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
args::ValueFlag<std::string> center(parser, "CENTER", "Set the origin to geometric center (geo) or (cog)", {'c', "center"});
args::ValueFlag<std::string> tfm_path(parser, "TFM", "Write out the transformation to a file", {'t', "tfm"});
args::ValueFlag<double> scale(parser, "SCALE", "Scale by a constant", {'s', "scale"});
args::ValueFlag<double> offX(parser, "OFF_X", "Translate origin in X direction", {"offX"});
args::ValueFlag<double> offY(parser, "OFF_Y", "Translate origin in Y direction", {"offY"});
args::ValueFlag<double> offZ(parser, "OFF_Z", "Translate origin in Z direction", {"offZ"});
args::ValueFlag<double> rotX(parser, "ROT_X", "Rotate about X-axis by angle (degrees)", {"rotX"});
args::ValueFlag<double> rotY(parser, "ROT_Y", "Rotate about Y-axis by angle (degrees)", {"rotY"});
args::ValueFlag<double> rotZ(parser, "ROT_Z", "Rotate about Z-axis by angle (degrees)", {"rotZ"});
args::ValueFlag<std::string> permute(parser, "PERMUTE", "Permute axes, e.g. 2,0,1. Negative values mean flip as well", {"permute"});
args::ValueFlag<std::string> flip(parser, "FLIP", "Flip an axis, e.g. 0,1,0. Occurs AFTER any permutation.", {"flip"});
template<typename TImage>
int Pipeline() {
auto image = QI::ReadImage<TImage>(QI::CheckPos(source_path));
// Permute if required
if (permute) {
auto permute_filter = itk::PermuteAxesImageFilter<TImage>::New();
itk::FixedArray<unsigned int, TImage::ImageDimension> permute_order;
std::istringstream iss(permute.Get());
std::string el;
for (int i = 0; i < 3; i++) {
std::getline(iss, el, ',');
permute_order[i] = std::stoi(el);
}
for (int i = 3; i < TImage::ImageDimension; i++) {
permute_order[i] = i;
}
if (!iss)
QI_FAIL("Failed to read permutation order: " << permute.Get());
permute_filter->SetInput(image);
permute_filter->SetOrder(permute_order);
permute_filter->Update();
image = permute_filter->GetOutput();
image->DisconnectPipeline();
}
// Flip if required
if (flip) {
auto flip_filter = itk::FlipImageFilter<TImage>::New();
itk::FixedArray<bool, TImage::ImageDimension> flip_axes; // Save this
std::istringstream iss(flip.Get());
std::string el;
for (int i = 0; i < 3; i++) {
std::getline(iss, el, ',');
flip_axes[i] = (std::stoi(el) > 0);
}
for (int i = 3; i < TImage::ImageDimension; i++) {
flip_axes[i] = false;
}
if (!iss)
QI_FAIL("Failed to read flip: " << flip.Get());
if (verbose) std::cout << "Flipping: " << flip_axes << std::endl;
flip_filter->SetInput(image);
flip_filter->SetFlipAxes(flip_axes);
flip_filter->SetFlipAboutOrigin(false);
flip_filter->Update();
image = flip_filter->GetOutput();
image->DisconnectPipeline();
}
typename TImage::DirectionType fullDir = image->GetDirection();
typename TImage::SpacingType fullSpacing = image->GetSpacing();
typename TImage::PointType fullOrigin = image->GetOrigin();
typename TImage::SizeType fullSize = image->GetLargestPossibleRegion().GetSize();
QI::VolumeF::DirectionType direction;
QI::VolumeF::SpacingType spacing;
typedef itk::CenteredAffineTransform<double, 3> TAffine;
TAffine::OutputVectorType origin;
QI::VolumeF::SizeType size;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
direction[i][j] = fullDir[i][j];
}
origin[i] = fullOrigin[i];
spacing[i] = fullSpacing[i];
size[i] = fullSize[i];
}
auto img_tfm = TAffine::New();
img_tfm->SetMatrix(direction);
img_tfm->Scale(spacing);
img_tfm->Translate(origin);
if (verbose) std::cout << "Start transform:\n" << img_tfm->GetMatrix() << std::endl;
auto tfm = TAffine::New();
if (scale) {
if (verbose) cout << "Scaling by factor " << scale.Get() << endl;
tfm->Scale(scale.Get());
}
if (rotX != 0.0) {
if (verbose) cout << "Rotating image by " << rotX.Get() << " around X axis." << endl;
tfm->Rotate(1,2,rotX.Get() * M_PI / 180.0);
}
if (rotY != 0.0) {
if (verbose) cout << "Rotating image by " << rotY.Get() << " around X axis." << endl;
tfm->Rotate(2,0,rotY.Get() * M_PI / 180.0);
}
if (rotZ != 0.0) {
if (verbose) cout << "Rotating image by " << rotZ.Get() << " around X axis." << endl;
tfm->Rotate(0,1,rotZ.Get() * M_PI / 180.0);
}
itk::Versor<double>::VectorType offset; offset.Fill(0);
if (center) {
if (center.Get() == "geo") {
if (verbose) std::cout << "Setting geometric center" << std::endl;
for (int i = 0; i < 3; i++) {
offset[i] = origin[i]-spacing[i]*size[i] / 2;
}
} else if (center.Get() == "cog") {
if (verbose) std::cout << "Setting center to center of gravity" << std::endl;
auto moments = itk::ImageMomentsCalculator<TImage>::New();
moments->SetImage(image);
moments->Compute();
// ITK seems to put a negative sign on the CoG
for (int i = 0; i < 3; i++) {
offset[i] = moments->GetCenterOfGravity()[i];
}
}
std::cout << "Translation will be: " << offset << std::endl;
tfm->Translate(-offset);
} else if (offX || offY || offZ) {
offset[0] = offX.Get();
offset[1] = offY.Get();
offset[2] = offZ.Get();
if (verbose) std::cout << "Translating by: " << offset << std::endl;
tfm->Translate(-offset);
}
if (tfm_path) { // Output the transform file
auto writer = itk::TransformFileWriterTemplate<double>::New();
writer->SetInput(tfm);
writer->SetFileName(tfm_path.Get());
writer->Update();
}
img_tfm->Compose(tfm);
itk::CenteredAffineTransform<double, 3>::MatrixType fmat = img_tfm->GetMatrix();
if (verbose) std::cout << "Final transform:\n" << fmat << std::endl;
for (int i = 0; i < 3; i++) {
fullOrigin[i] = img_tfm->GetOffset()[i];
}
for (int j = 0; j < 3; j++) {
double scale = 0.;
for (int i = 0; i < 3; i++) {
scale += fmat[i][j]*fmat[i][j];
}
scale = sqrt(scale);
fullSpacing[j] = scale;
for (int i = 0; i < 3; i++) {
fullDir[i][j] = fmat[i][j] / scale;
}
}
image->SetDirection(fullDir);
image->SetOrigin(fullOrigin);
image->SetSpacing(fullSpacing);
// Write out the edited file
if (dest_path) {
if (verbose) std::cout << "Writing: " << dest_path.Get() << std::endl;
QI::WriteImage(image, dest_path.Get());
} else {
if (verbose) std::cout << "Writing: " << source_path.Get() << std::endl;
QI::WriteImage(image, source_path.Get());
}
return EXIT_SUCCESS;
}
int main(int argc, char **argv) {
QI::ParseArgs(parser, argc, argv);
if (verbose) std::cout << "Reading header for: " << QI::CheckPos(source_path) << std::endl;
auto header = itk::ImageIOFactory::CreateImageIO(QI::CheckPos(source_path).c_str(), itk::ImageIOFactory::ReadMode);
header->SetFileName(source_path.Get());
header->ReadImageInformation();
auto dims = header->GetNumberOfDimensions();
auto dtype = header->GetComponentType();
if (verbose) std::cout << "Datatype is " << header->GetComponentTypeAsString( dtype ) << std::endl;
#define DIM_SWITCH( TYPE ) \
switch (dims) { \
case 3: return Pipeline<itk::Image< TYPE , 3 >>(); \
case 4: return Pipeline<itk::Image< TYPE , 4 >>(); \
default: QI_FAIL("Unsupported dimension: " << dims); return EXIT_FAILURE; \
}
switch (dtype) {
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: QI_FAIL("Unknown component type in image " << source_path);
case itk::ImageIOBase::UCHAR: DIM_SWITCH( unsigned char ); break;
case itk::ImageIOBase::CHAR: DIM_SWITCH( char ); break;
case itk::ImageIOBase::USHORT: DIM_SWITCH( unsigned short ); break;
case itk::ImageIOBase::SHORT: DIM_SWITCH( short ); break;
case itk::ImageIOBase::UINT: DIM_SWITCH( unsigned int ); break;
case itk::ImageIOBase::INT: DIM_SWITCH( int ); break;
case itk::ImageIOBase::ULONG: DIM_SWITCH( unsigned long ); break;
case itk::ImageIOBase::LONG: DIM_SWITCH( long ); break;
case itk::ImageIOBase::FLOAT: DIM_SWITCH( float ); break;
case itk::ImageIOBase::DOUBLE: DIM_SWITCH( double ); break;
}
}
<|endoftext|> |
<commit_before>
#include <sstream>
#include <random>
#include <functional>
#include <layout/form_layout.h>
#include <layout/box_layout.h>
#include <layout/grid_layout.h>
#include <layout/tree_layout.h>
#include <gui/application.h>
#include <gui/cocoa_style.h>
namespace {
////////////////////////////////////////
void build_form_layout( const std::shared_ptr<gui::window> &win )
{
gui::builder builder( win );
auto layout = builder.new_layout<layout::form_layout>( layout::direction::RIGHT );
layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
layout->set_spacing( 12.0, 12.0 );
auto row = layout->new_row();
builder.make_label( row.first, "Hello World" );
builder.make_button( row.second, "Press Me" );
row = layout->new_row();
builder.make_label( row.first, "Goodbye World" );
builder.make_button( row.second, "Me Too" );
}
void build_box_layout( const std::shared_ptr<gui::window> &win )
{
gui::builder builder( win );
auto layout = builder.new_layout<layout::box_layout>( layout::direction::DOWN );
layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
layout->set_spacing( 12.0, 12.0 );
builder.make_label( layout->new_area(), "Hello World" );
builder.make_button( layout->new_area(), "Press Me" );
builder.make_label( layout->new_area(), "Goodbye World" );
builder.make_button( layout->new_area(), "Me Too" );
}
void build_grid_layout( const std::shared_ptr<gui::window> &win )
{
gui::builder builder( win );
auto layout = builder.new_layout<layout::grid_layout>();
layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
layout->set_spacing( 12.0, 12.0 );
for ( size_t i = 0; i < 5; ++i )
layout->new_column( 1.0 );
int count = 0;
for ( size_t i = 0; i < 5; ++i )
{
auto cols = layout->new_row();
for ( auto a: cols )
{
std::stringstream tmp;
tmp << ++count;
builder.make_label( a, tmp.str() );
}
}
}
void build_tree_layout( const std::shared_ptr<gui::window> &win )
{
gui::builder builder( win );
auto layout = builder.new_layout<layout::tree_layout>( 24.0 );
layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
layout->set_spacing( 12.0 );
std::random_device rd;
std::default_random_engine rand( rd() );
std::uniform_int_distribution<int> uniform_dist( 1, 6 );
std::function<void(std::shared_ptr<layout::tree_layout>,int)> make_tree =
[&]( std::shared_ptr<layout::tree_layout> l, int level )
{
int count = uniform_dist( rand );
for ( int i = 0; i < count; ++i )
{
std::stringstream tmp;
tmp << char( 'A' + i );
builder.make_label( l->new_area( 0.0 ), tmp.str() );
if ( level < 2 )
make_tree( l->new_branch( 0.0 ), level + 1 );
}
};
make_tree( layout, 0 );
}
////////////////////////////////////////
int safemain( int argc, char **argv )
{
auto app = std::make_shared<gui::application>();
app->push();
app->set_style( std::make_shared<gui::cocoa_style>() );
auto win1 = app->new_window();
build_form_layout( win1 );
win1->show();
auto win2 = app->new_window();
build_box_layout( win2 );
win2->show();
auto win3 = app->new_window();
build_grid_layout( win3 );
win3->show();
auto win4 = app->new_window();
build_tree_layout( win4 );
win4->show();
int code = app->run();
app->pop();
return code;
}
////////////////////////////////////////
}
////////////////////////////////////////
int main( int argc, char *argv[] )
{
int ret = -1;
try
{
ret = safemain( argc, argv );
}
catch ( std::exception &e )
{
print_exception( std::cerr, e );
}
return ret;
}
////////////////////////////////////////
<commit_msg>Added button test.<commit_after>
#include <sstream>
#include <random>
#include <functional>
#include <layout/form_layout.h>
#include <layout/box_layout.h>
#include <layout/grid_layout.h>
#include <layout/tree_layout.h>
#include <gui/application.h>
#include <gui/cocoa_style.h>
namespace {
////////////////////////////////////////
void build_form_layout( const std::shared_ptr<gui::window> &win )
{
gui::builder builder( win );
auto layout = builder.new_layout<layout::form_layout>( layout::direction::RIGHT );
layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
layout->set_spacing( 12.0, 12.0 );
auto row = layout->new_row();
builder.make_label( row.first, "Hello World" );
builder.make_button( row.second, "Press Me" );
row = layout->new_row();
builder.make_label( row.first, "Goodbye World" );
builder.make_button( row.second, "Me Too" );
}
void build_box_layout( const std::shared_ptr<gui::window> &win )
{
gui::builder builder( win );
auto layout = builder.new_layout<layout::box_layout>( layout::direction::DOWN );
layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
layout->set_spacing( 12.0, 12.0 );
builder.make_label( layout->new_area(), "Hello World" );
builder.make_button( layout->new_area(), "Press Me" );
builder.make_label( layout->new_area(), "Goodbye World" );
builder.make_button( layout->new_area(), "Me Too" );
}
void build_grid_layout( const std::shared_ptr<gui::window> &win )
{
gui::builder builder( win );
auto layout = builder.new_layout<layout::grid_layout>();
layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
layout->set_spacing( 12.0, 12.0 );
for ( size_t i = 0; i < 5; ++i )
layout->new_column( 1.0 );
int count = 0;
for ( size_t i = 0; i < 5; ++i )
{
auto cols = layout->new_row();
for ( auto a: cols )
{
std::stringstream tmp;
tmp << ++count;
builder.make_label( a, tmp.str() );
}
}
}
void build_tree_layout( const std::shared_ptr<gui::window> &win )
{
gui::builder builder( win );
auto layout = builder.new_layout<layout::tree_layout>( 24.0 );
layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
layout->set_spacing( 12.0 );
std::random_device rd;
std::default_random_engine rand( rd() );
std::uniform_int_distribution<int> uniform_dist( 1, 6 );
std::function<void(std::shared_ptr<layout::tree_layout>,int)> make_tree =
[&]( std::shared_ptr<layout::tree_layout> l, int level )
{
int count = uniform_dist( rand );
for ( int i = 0; i < count; ++i )
{
std::stringstream tmp;
tmp << char( 'A' + i );
builder.make_label( l->new_area( 0.0 ), tmp.str() );
if ( level < 2 )
make_tree( l->new_branch( 0.0 ), level + 1 );
}
};
make_tree( layout, 0 );
}
////////////////////////////////////////
void build_button( const std::shared_ptr<gui::window> &win )
{
gui::builder builder( win );
auto layout = builder.new_layout<layout::box_layout>( layout::direction::DOWN );
layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
layout->set_spacing( 12.0, 12.0 );
auto area = layout->new_area();
builder.make_button( area, "Button" );
}
////////////////////////////////////////
int safemain( int argc, char **argv )
{
auto app = std::make_shared<gui::application>();
app->push();
app->set_style( std::make_shared<gui::cocoa_style>() );
// auto win1 = app->new_window();
// build_form_layout( win1 );
// win1->show();
// auto win2 = app->new_window();
// build_box_layout( win2 );
// win2->show();
// auto win3 = app->new_window();
// build_grid_layout( win3 );
// win3->show();
// auto win4 = app->new_window();
// build_tree_layout( win4 );
// win4->show();
auto win5 = app->new_window();
build_button( win5 );
win5->show();
int code = app->run();
app->pop();
return code;
}
////////////////////////////////////////
}
////////////////////////////////////////
int main( int argc, char *argv[] )
{
int ret = -1;
try
{
ret = safemain( argc, argv );
}
catch ( std::exception &e )
{
print_exception( std::cerr, e );
}
return ret;
}
////////////////////////////////////////
<|endoftext|> |
<commit_before>#include <iostream>
int main(int, char**){
#ifdef __AVX__
std::cout << "AVX available\n";
#else
std::cout << "No AVX\n";
#endif
return 0;
}
<commit_msg>tossing the test_avx file<commit_after><|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief v8 client connection
///
/// @file
///
/// DISCLAIMER
///
/// Copyright by triAGENS GmbH - All rights reserved.
///
/// The Programs (which include both the software and documentation)
/// contain proprietary information of triAGENS GmbH; they are
/// provided under a license agreement containing restrictions on use and
/// disclosure and are also protected by copyright, patent and other
/// intellectual and industrial property laws. Reverse engineering,
/// disassembly or decompilation of the Programs, except to the extent
/// required to obtain interoperability with other independently created
/// software or as specified by law, is prohibited.
///
/// The Programs are not intended for use in any nuclear, aviation, mass
/// transit, medical, or other inherently dangerous applications. It shall
/// be the licensee's responsibility to take all appropriate fail-safe,
/// backup, redundancy, and other measures to ensure the safe use of such
/// applications if the Programs are used for such purposes, and triAGENS
/// GmbH disclaims liability for any damages caused by such use of
/// the Programs.
///
/// This software is the confidential and proprietary information of
/// triAGENS GmbH. You shall not disclose such confidential and
/// proprietary information and shall use it only in accordance with the
/// terms of the license agreement you entered into with triAGENS GmbH.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
/// @author Copyright 2008-2011, triagens GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "V8ClientConnection.h"
#include <sstream>
#include "Basics/StringUtils.h"
#include "Variant/VariantArray.h"
#include "Variant/VariantString.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
#include "json.h"
#include "V8/v8-conv.h"
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace std;
namespace triagens {
namespace v8client {
////////////////////////////////////////////////////////////////////////////////
/// constructor and destructor
////////////////////////////////////////////////////////////////////////////////
V8ClientConnection::V8ClientConnection (const std::string& hostname,
int port,
double requestTimeout,
size_t retries,
double connectionTimeout) : _client(0), _httpResult(0) {
_connected = false;
_lastHttpReturnCode = 0;
_lastErrorMessage = "";
_client = new SimpleHttpClient(hostname, port, requestTimeout, retries, connectionTimeout);
// connect to server and get version number
map<string, string> headerFields;
SimpleHttpResult* result = _client->request(SimpleHttpClient::GET, "/version", 0, 0, headerFields);
if (!result->isComplete()) {
// save error message
_lastErrorMessage = _client->getErrorMessage();
_lastHttpReturnCode = 500;
}
else {
_lastHttpReturnCode = result->getHttpReturnCode();
if (result->getHttpReturnCode() == SimpleHttpResult::HTTP_STATUS_OK) {
triagens::basics::VariantArray* json = result->getBodyAsVariantArray();
if (json) {
triagens::basics::VariantString* vs = json->lookupString("server");
if (vs && vs->getValue() == "arango") {
// connected to arango server
_connected = true;
vs = json->lookupString("version");
if (vs) {
_version = vs->getValue();
}
}
delete json;
}
}
}
delete result;
}
V8ClientConnection::~V8ClientConnection () {
if (_httpResult) {
delete _httpResult;
}
if (_client) {
delete _client;
}
}
v8::Handle<v8::Value> V8ClientConnection::getData (std::string const& location, map<string, string> const& headerFields) {
return requestData(SimpleHttpClient::GET, location, "", headerFields);
}
v8::Handle<v8::Value> V8ClientConnection::deleteData (std::string const& location, map<string, string> const& headerFields) {
return requestData(SimpleHttpClient::DELETE, location, "", headerFields);
}
v8::Handle<v8::Value> V8ClientConnection::headData (std::string const& location, map<string, string> const& headerFields) {
return requestData(SimpleHttpClient::HEAD, location, "", headerFields);
}
v8::Handle<v8::Value> V8ClientConnection::postData (std::string const& location, std::string const& body, map<string, string> const& headerFields) {
return requestData(SimpleHttpClient::POST, location, body, headerFields);
}
v8::Handle<v8::Value> V8ClientConnection::putData (std::string const& location, std::string const& body, map<string, string> const& headerFields) {
return requestData(SimpleHttpClient::PUT, location, body, headerFields);
}
const std::string& V8ClientConnection::getHostname () {
return _client->getHostname();
}
int V8ClientConnection::getPort () {
return _client->getPort();
}
v8::Handle<v8::Value> V8ClientConnection::requestData (int method, string const& location, string const& body, map<string, string> const& headerFields) {
_lastErrorMessage = "";
_lastHttpReturnCode = 0;
if (_httpResult) {
delete _httpResult;
}
if (body.empty()) {
_httpResult = _client->request(method, location, 0, 0, headerFields);
}
else {
_httpResult = _client->request(method, location, body.c_str(), body.length(), headerFields);
}
if (!_httpResult->isComplete()) {
// not complete
_lastErrorMessage = _client->getErrorMessage();
if (_lastErrorMessage == "") {
_lastErrorMessage = "Unknown error";
}
_lastHttpReturnCode = SimpleHttpResult::HTTP_STATUS_SERVER_ERROR;
v8::Handle<v8::Object> result = v8::Object::New();
result->Set(v8::String::New("error"), v8::Boolean::New(true));
result->Set(v8::String::New("code"), v8::Integer::New(SimpleHttpResult::HTTP_STATUS_SERVER_ERROR));
int errorNumber = 0;
switch (_httpResult->getResultType()) {
case (SimpleHttpResult::COULD_NOT_CONNECT) :
errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_CONNECT;
break;
case (SimpleHttpResult::READ_ERROR) :
errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_READ;
break;
case (SimpleHttpResult::WRITE_ERROR) :
errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_WRITE;
break;
default:
errorNumber = TRI_SIMPLE_CLIENT_UNKNOWN_ERROR;
}
result->Set(v8::String::New("errorNum"), v8::Integer::New(errorNumber));
result->Set(v8::String::New("errorMessage"), v8::String::New(_lastErrorMessage.c_str(), _lastErrorMessage.length()));
return result;
}
else {
// complete
_lastHttpReturnCode = _httpResult->getHttpReturnCode();
// got a body
if (_httpResult->getBody().str().length() > 0) {
string contentType = _httpResult->getContentType(true);
if (contentType == "application/json") {
TRI_json_t* js = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, _httpResult->getBody().str().c_str());
if (js != NULL) {
// return v8 object
v8::Handle<v8::Value> result = TRI_ObjectJson(js);
TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, js);
return result;
}
}
// return body as string
v8::Handle<v8::String> result = v8::String::New(_httpResult->getBody().str().c_str(), _httpResult->getBody().str().length());
return result;
}
else {
// no body
// this should not happen
v8::Handle<v8::Object> result;
result->Set(v8::String::New("error"), v8::Boolean::New(false));
result->Set(v8::String::New("code"), v8::Integer::New(_httpResult->getHttpReturnCode()));
return result;
}
}
}
}
}
<commit_msg>fixed version path<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief v8 client connection
///
/// @file
///
/// DISCLAIMER
///
/// Copyright by triAGENS GmbH - All rights reserved.
///
/// The Programs (which include both the software and documentation)
/// contain proprietary information of triAGENS GmbH; they are
/// provided under a license agreement containing restrictions on use and
/// disclosure and are also protected by copyright, patent and other
/// intellectual and industrial property laws. Reverse engineering,
/// disassembly or decompilation of the Programs, except to the extent
/// required to obtain interoperability with other independently created
/// software or as specified by law, is prohibited.
///
/// The Programs are not intended for use in any nuclear, aviation, mass
/// transit, medical, or other inherently dangerous applications. It shall
/// be the licensee's responsibility to take all appropriate fail-safe,
/// backup, redundancy, and other measures to ensure the safe use of such
/// applications if the Programs are used for such purposes, and triAGENS
/// GmbH disclaims liability for any damages caused by such use of
/// the Programs.
///
/// This software is the confidential and proprietary information of
/// triAGENS GmbH. You shall not disclose such confidential and
/// proprietary information and shall use it only in accordance with the
/// terms of the license agreement you entered into with triAGENS GmbH.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
/// @author Copyright 2008-2011, triagens GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "V8ClientConnection.h"
#include <sstream>
#include "Basics/StringUtils.h"
#include "Variant/VariantArray.h"
#include "Variant/VariantString.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
#include "json.h"
#include "V8/v8-conv.h"
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace std;
namespace triagens {
namespace v8client {
////////////////////////////////////////////////////////////////////////////////
/// constructor and destructor
////////////////////////////////////////////////////////////////////////////////
V8ClientConnection::V8ClientConnection (const std::string& hostname,
int port,
double requestTimeout,
size_t retries,
double connectionTimeout) : _client(0), _httpResult(0) {
_connected = false;
_lastHttpReturnCode = 0;
_lastErrorMessage = "";
_client = new SimpleHttpClient(hostname, port, requestTimeout, retries, connectionTimeout);
// connect to server and get version number
map<string, string> headerFields;
SimpleHttpResult* result = _client->request(SimpleHttpClient::GET, "/_admin/version", 0, 0, headerFields);
if (!result->isComplete()) {
// save error message
_lastErrorMessage = _client->getErrorMessage();
_lastHttpReturnCode = 500;
}
else {
_lastHttpReturnCode = result->getHttpReturnCode();
if (result->getHttpReturnCode() == SimpleHttpResult::HTTP_STATUS_OK) {
triagens::basics::VariantArray* json = result->getBodyAsVariantArray();
if (json) {
triagens::basics::VariantString* vs = json->lookupString("server");
if (vs && vs->getValue() == "arango") {
// connected to arango server
_connected = true;
vs = json->lookupString("version");
if (vs) {
_version = vs->getValue();
}
}
delete json;
}
}
}
delete result;
}
V8ClientConnection::~V8ClientConnection () {
if (_httpResult) {
delete _httpResult;
}
if (_client) {
delete _client;
}
}
v8::Handle<v8::Value> V8ClientConnection::getData (std::string const& location, map<string, string> const& headerFields) {
return requestData(SimpleHttpClient::GET, location, "", headerFields);
}
v8::Handle<v8::Value> V8ClientConnection::deleteData (std::string const& location, map<string, string> const& headerFields) {
return requestData(SimpleHttpClient::DELETE, location, "", headerFields);
}
v8::Handle<v8::Value> V8ClientConnection::headData (std::string const& location, map<string, string> const& headerFields) {
return requestData(SimpleHttpClient::HEAD, location, "", headerFields);
}
v8::Handle<v8::Value> V8ClientConnection::postData (std::string const& location, std::string const& body, map<string, string> const& headerFields) {
return requestData(SimpleHttpClient::POST, location, body, headerFields);
}
v8::Handle<v8::Value> V8ClientConnection::putData (std::string const& location, std::string const& body, map<string, string> const& headerFields) {
return requestData(SimpleHttpClient::PUT, location, body, headerFields);
}
const std::string& V8ClientConnection::getHostname () {
return _client->getHostname();
}
int V8ClientConnection::getPort () {
return _client->getPort();
}
v8::Handle<v8::Value> V8ClientConnection::requestData (int method, string const& location, string const& body, map<string, string> const& headerFields) {
_lastErrorMessage = "";
_lastHttpReturnCode = 0;
if (_httpResult) {
delete _httpResult;
}
if (body.empty()) {
_httpResult = _client->request(method, location, 0, 0, headerFields);
}
else {
_httpResult = _client->request(method, location, body.c_str(), body.length(), headerFields);
}
if (!_httpResult->isComplete()) {
// not complete
_lastErrorMessage = _client->getErrorMessage();
if (_lastErrorMessage == "") {
_lastErrorMessage = "Unknown error";
}
_lastHttpReturnCode = SimpleHttpResult::HTTP_STATUS_SERVER_ERROR;
v8::Handle<v8::Object> result = v8::Object::New();
result->Set(v8::String::New("error"), v8::Boolean::New(true));
result->Set(v8::String::New("code"), v8::Integer::New(SimpleHttpResult::HTTP_STATUS_SERVER_ERROR));
int errorNumber = 0;
switch (_httpResult->getResultType()) {
case (SimpleHttpResult::COULD_NOT_CONNECT) :
errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_CONNECT;
break;
case (SimpleHttpResult::READ_ERROR) :
errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_READ;
break;
case (SimpleHttpResult::WRITE_ERROR) :
errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_WRITE;
break;
default:
errorNumber = TRI_SIMPLE_CLIENT_UNKNOWN_ERROR;
}
result->Set(v8::String::New("errorNum"), v8::Integer::New(errorNumber));
result->Set(v8::String::New("errorMessage"), v8::String::New(_lastErrorMessage.c_str(), _lastErrorMessage.length()));
return result;
}
else {
// complete
_lastHttpReturnCode = _httpResult->getHttpReturnCode();
// got a body
if (_httpResult->getBody().str().length() > 0) {
string contentType = _httpResult->getContentType(true);
if (contentType == "application/json") {
TRI_json_t* js = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, _httpResult->getBody().str().c_str());
if (js != NULL) {
// return v8 object
v8::Handle<v8::Value> result = TRI_ObjectJson(js);
TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, js);
return result;
}
}
// return body as string
v8::Handle<v8::String> result = v8::String::New(_httpResult->getBody().str().c_str(), _httpResult->getBody().str().length());
return result;
}
else {
// no body
// this should not happen
v8::Handle<v8::Object> result;
result->Set(v8::String::New("error"), v8::Boolean::New(false));
result->Set(v8::String::New("code"), v8::Integer::New(_httpResult->getHttpReturnCode()));
return result;
}
}
}
}
}
<|endoftext|> |
<commit_before>#include "SuffixTree\SuffixTreeBuilder.h"
#include <iostream>
#include <string>
#include <cassert>
#include <ctime>
using namespace std;
int main()
{
unsigned int length = 100000;
char* source = new char[length + 1];
for (unsigned int i = 0; i < length; i++)
{
source[i] = rand() % 26 + 'A';
}
source[length] = 0;
string s = source;
clock_t s_time = clock();
SuffixTreeBuilder builder(s);
SuffixTree suffixTree;
builder.BuildSuffixTree(&suffixTree);
clock_t e_time = clock();
cout << e_time - s_time << endl;
// cout << suffixTree.Show(s, &builder) << endl;
return 0;
}
<commit_msg>Fix build error on OSX<commit_after>#include "SuffixTree/SuffixTreeBuilder.h"
#include <iostream>
#include <string>
#include <cassert>
#include <ctime>
using namespace std;
int main()
{
unsigned int length = 100000;
char* source = new char[length + 1];
for (unsigned int i = 0; i < length; i++)
{
source[i] = rand() % 26 + 'A';
}
source[length] = 0;
string s = source;
clock_t s_time = clock();
SuffixTreeBuilder builder(s);
SuffixTree suffixTree;
builder.BuildSuffixTree(&suffixTree);
clock_t e_time = clock();
cout << e_time - s_time << endl;
// cout << suffixTree.Show(s, &builder) << endl;
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.