text stringlengths 54 60.6k |
|---|
<commit_before>#include <iostream>
#include <cstdint>
#include <random>
#include <chrono>
#include <vector>
#include <boost/dynamic_bitset.hpp>
#include <numeric>
/**
* Lessons learned so far:
* - SIMD registers are used as soon as we compile with -03
* - If we want to get the real speed up (and use all SIMD registers by unfolding both loops,
* we have to know both, input-size and number of comparisons, at compile time.
* - Otherwise, only some of the SIMD registers are used, and speedup is 0, compared to
* code optimized with 02.
* - Example compile command: g++ -std=c++11 -march=native -O3 simd.cpp -o simd
* - Command for getting assembly code: g++ -std=c++11 -march=native -O3 -S simd.cpp
*/
typedef std::mt19937 Engine;
typedef std::uniform_int_distribution<unsigned> Intdistr;
template <typename T, typename U>
void smaller (const T *input, U outputs, const T *comparison_values, const unsigned array_size, const unsigned comparisons) {
for (unsigned i = 0; i < array_size; ++i)
{
for (unsigned m = 0; m < comparisons; ++m) {
outputs[m*array_size+i] = (float) (input[i] < comparison_values[m]);
}
}
}
template <typename T>
void pretty_print (T *arr, unsigned size, std::string s = "Pretty Print") {
std::cout << s << ":" << std::endl;
for (auto r = arr; r < arr+size; ++r ) {
std::cout << *r << std::endl;
}
}
template <typename T>
void compute_stats(const std::vector<T> stats, double &mean, double &stdev) {
double sum = std::accumulate(stats.begin(), stats.end(), 0.0);
mean = sum / stats.size();
std::vector<double> diff(stats.size());
std::transform(stats.begin(), stats.end(), diff.begin(),
std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
stdev = std::sqrt(sq_sum / stats.size());
}
template <typename T>
void fill (T *arr, unsigned size) {
Engine engine (0);
Intdistr distr (0, 100000);
for (auto r = arr; r < arr+size; ++r ) {
*r = distr(engine);
}
}
int main (int argc, char *argv[]) {
//**** PARAMS ****/
typedef unsigned TestType;
static constexpr unsigned repetitions = 10000;
constexpr unsigned input_size = 500000;
constexpr unsigned comparisons = 1;
// if (argc != 3)
// {
// std::cout << "Usage: ./simd <input-size> <comparisons>" << std::endl;
// return -1;
// }
unsigned long input_size = std::stoi(argv[1]);
unsigned comparisons = std::stoi(argv[2]);
std::cout << "input size: " << input_size << std::endl;
std::cout << "comparisons: " << comparisons<< std::endl;
//**** INPUT ****/
TestType test_input [input_size];
fill(test_input, input_size);
// pretty_print(test_input, input_size, "Input");
TestType comparison_values [comparisons];
for (unsigned c = 0; c < comparisons; ++c) {
comparison_values[c] = test_input[c];
}
// pretty_print(comparison_values, comparisons, "Comparison values");
//**** COMPUTE ****/
std::vector<unsigned long> stats (repetitions);
bool results [comparisons * input_size];
// std::vector<bool> results (comparisons * input_size);
// boost::dynamic_bitset<> results(comparisons * input_size);
for (unsigned i = 0; i < repetitions; ++i) {
auto start = std::chrono::high_resolution_clock::now();
smaller(test_input, results, comparison_values, input_size, comparisons);
auto end = std::chrono::high_resolution_clock::now();
stats [i] =
std::chrono::duration_cast<std::chrono::microseconds>(end-start).count();
}
//**** REPORT ****/
double mean, stdev;
compute_stats(stats, mean, stdev);
std::cout
// << "Avg Time [microsecs]: "
<< mean
<< "\t"
// << "(+/- "
<< stdev
// << ")"
<< std::endl;
// pretty_print(stats.data(), repetitions, "Stats");
// for (unsigned c = 0; c < comparisons; ++c) {
// pretty_print(&results[c*input_size], input_size, "Result");
// }
return 0;
}
<commit_msg>finished simd experiments for all-same-operator (smaller)<commit_after>#include <iostream>
#include <cstdint>
#include <random>
#include <chrono>
#include <vector>
#include <boost/dynamic_bitset.hpp>
#include <numeric>
/**
* Lessons learned so far:
* - SIMD registers are used as soon as we compile with -03
* - If we want to get the real speed up (and use all SIMD registers by unfolding both loops,
* we have to know both, input-size and number of comparisons, at compile time.
* - Otherwise, only some of the SIMD registers are used, and speedup is 0, compared to
* code optimized with 02.
* - Example compile command: g++ -std=c++11 -march=native -O3 simd.cpp -o simd
* - Command for getting assembly code: g++ -std=c++11 -march=native -O3 -S simd.cpp
*/
typedef std::mt19937 Engine;
typedef std::uniform_int_distribution<unsigned> Intdistr;
template <typename T, typename U>
void smaller (const T *input, U outputs, const T *comparison_values, const unsigned array_size, const unsigned comparisons) {
for (unsigned i = 0; i < array_size; ++i)
{
for (unsigned m = 0; m < comparisons; ++m) {
outputs[m*array_size+i] = (float) (input[i] < comparison_values[m]);
}
}
}
template <typename T>
void pretty_print (T *arr, unsigned size, std::string s = "Pretty Print") {
std::cout << s << ":" << std::endl;
for (auto r = arr; r < arr+size; ++r ) {
std::cout << *r << std::endl;
}
}
template <typename T>
void compute_stats(const std::vector<T> stats, double &mean, double &stdev) {
double sum = std::accumulate(stats.begin(), stats.end(), 0.0);
mean = sum / stats.size();
std::vector<double> diff(stats.size());
std::transform(stats.begin(), stats.end(), diff.begin(),
std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
stdev = std::sqrt(sq_sum / stats.size());
}
template <typename T>
void fill (T *arr, unsigned size) {
Engine engine (0);
Intdistr distr (0, 100000);
for (auto r = arr; r < arr+size; ++r ) {
*r = distr(engine);
}
}
int main (int argc, char *argv[]) {
//**** PARAMS ****/
typedef unsigned TestType;
static constexpr unsigned repetitions = 10000;
constexpr unsigned input_size = 500000;
constexpr unsigned comparisons = 1;
// if (argc != 3)
// {
// std::cout << "Usage: ./simd <input-size> <comparisons>" << std::endl;
// return -1;
// }
// unsigned long input_size = std::stoi(argv[1]);
// unsigned comparisons = std::stoi(argv[2]);
std::cout << "input size: " << input_size << std::endl;
std::cout << "comparisons: " << comparisons<< std::endl;
//**** INPUT ****/
TestType test_input [input_size];
fill(test_input, input_size);
// pretty_print(test_input, input_size, "Input");
TestType comparison_values [comparisons];
for (unsigned c = 0; c < comparisons; ++c) {
comparison_values[c] = test_input[c];
}
// pretty_print(comparison_values, comparisons, "Comparison values");
//**** COMPUTE ****/
std::vector<unsigned long> stats (repetitions);
bool results [comparisons * input_size];
// std::vector<bool> results (comparisons * input_size);
// boost::dynamic_bitset<> results(comparisons * input_size);
for (unsigned i = 0; i < repetitions; ++i) {
auto start = std::chrono::high_resolution_clock::now();
smaller(test_input, results, comparison_values, input_size, comparisons);
auto end = std::chrono::high_resolution_clock::now();
stats [i] =
std::chrono::duration_cast<std::chrono::microseconds>(end-start).count();
}
//**** REPORT ****/
double mean, stdev;
compute_stats(stats, mean, stdev);
std::cout
// << "Avg Time [microsecs]: "
<< mean
<< "\t"
// << "(+/- "
<< stdev
// << ")"
<< std::endl;
// pretty_print(stats.data(), repetitions, "Stats");
// for (unsigned c = 0; c < comparisons; ++c) {
// pretty_print(&results[c*input_size], input_size, "Result");
// }
return 0;
}
<|endoftext|> |
<commit_before>/*
* This file is part of Poedit (https://poedit.net)
*
* Copyright (C) 2017 Vaclav Slavik
*
* 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 "qa_checks.h"
#include <unicode/uchar.h>
#include <wx/translation.h>
// -------------------------------------------------------------
// QACheck implementations
// -------------------------------------------------------------
namespace QA
{
class NotAllPlurals : public QACheck
{
public:
bool CheckItem(CatalogItemPtr item) override
{
if (!item->HasPlural())
return false;
bool foundTranslated = false;
bool foundEmpty = false;
for (auto& s: item->GetTranslations())
{
if (s.empty())
foundEmpty = true;
else
foundTranslated = true;
}
if (foundEmpty && foundTranslated)
{
item->SetIssue(CatalogItem::Issue::Warning, _("Not all plural forms are translated."));
return true;
}
return false;
}
};
class CaseMismatch : public QACheck
{
public:
CaseMismatch(Language lang) : m_lang(lang.Lang())
{
}
bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override
{
if (u_isupper(source[0]) && u_islower(translation[0]))
{
item->SetIssue(CatalogItem::Issue::Warning, _("The translation should start as a sentence."));
return true;
}
if (u_islower(source[0]) && u_isupper(translation[0]))
{
if (m_lang != "de")
{
item->SetIssue(CatalogItem::Issue::Warning, _("The translation should start with a lowercase character."));
return true;
}
// else: German nouns start uppercased, this would cause too many false positives
}
return false;
}
private:
std::string m_lang;
};
class WhitespaceMismatch : public QACheck
{
public:
bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override
{
if (u_isspace(source[0]) && !u_isspace(translation[0]))
{
item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation doesn’t start with a space."));
return true;
}
if (!u_isspace(source[0]) && u_isspace(translation[0]))
{
item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation starts with a space, but the source text doesn’t."));
return true;
}
if (source.Last() == '\n' && translation.Last() != '\n')
{
item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation is missing a newline at the end."));
return true;
}
if (source.Last() != '\n' && translation.Last() == '\n')
{
item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation ends with a newline, but the source text doesn’t."));
return true;
}
if (u_isspace(source.Last()) && !u_isspace(translation.Last()))
{
item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation is missing a space at the end."));
return true;
}
if (!u_isspace(source.Last()) && u_isspace(translation.Last()))
{
item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation ends with a space, but the source text doesn’t."));
return true;
}
return false;
}
};
class PunctuationMismatch : public QACheck
{
public:
PunctuationMismatch(Language lang) : m_lang(lang.Lang())
{
}
bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override
{
const UChar32 s_last = source.Last();
const UChar32 t_last = translation.Last();
const bool s_punct = u_ispunct(s_last);
const bool t_punct = u_ispunct(t_last);
if (s_punct && !t_punct)
{
item->SetIssue(CatalogItem::Issue::Warning,
wxString::Format(_(L"The translation should end with “%s”."), wxString(wxUniChar(s_last))));
return true;
}
else if (!s_punct && t_punct)
{
item->SetIssue(CatalogItem::Issue::Warning,
wxString::Format(_(L"The translation should not end with “%s”."), wxString(wxUniChar(t_last))));
return true;
}
else if (s_punct && t_punct && s_last != t_last)
{
if (t_last == L'…' && source.EndsWith("..."))
{
// as a special case, allow translating ... (3 dots) as … (ellipsis)
}
else if (u_hasBinaryProperty(s_last, UCHAR_QUOTATION_MARK) && u_hasBinaryProperty(t_last, UCHAR_QUOTATION_MARK))
{
// don't check for correct quotes for now, accept any quotations marks as equal
}
else if (IsEquivalent(s_last, t_last))
{
// some characters are mostly equivalent and we shouldn't warn about them
}
else
{
item->SetIssue(CatalogItem::Issue::Warning,
wxString::Format(_(L"The translation ends with “%s”, but the source text ends with “%s”."),
wxString(wxUniChar(t_last)), wxString(wxUniChar(s_last))));
return true;
}
}
return false;
}
private:
bool IsEquivalent(UChar32 src, UChar32 trans) const
{
if (src == trans)
return true;
if (m_lang == "zh" || m_lang == "ja")
{
// Chinese uses full-width punctuation.
// See https://en.wikipedia.org/wiki/Chinese_punctuation
switch (src)
{
case '.':
return trans == L'。';
case '!':
return trans == L'!';
case '?':
return trans == L'?';
case ':':
return trans == L':';
default:
break;
}
}
return false;
}
std::string m_lang;
};
} // namespace QA
// -------------------------------------------------------------
// QACheck support code
// -------------------------------------------------------------
bool QACheck::CheckItem(CatalogItemPtr item)
{
if (!item->GetTranslation().empty() && CheckString(item, item->GetString(), item->GetTranslation()))
return true;
if (item->HasPlural())
{
unsigned count = item->GetNumberOfTranslations();
for (unsigned i = 1; i < count; i++)
{
auto t = item->GetTranslation(i);
if (!t.empty() && CheckString(item, item->GetPluralString(), t))
return true;
}
}
return false;
}
bool QACheck::CheckString(CatalogItemPtr /*item*/, const wxString& /*source*/, const wxString& /*translation*/)
{
wxFAIL_MSG("not implemented - must override CheckString OR CheckItem");
return false;
}
// -------------------------------------------------------------
// QAChecker
// -------------------------------------------------------------
int QAChecker::Check(Catalog& catalog)
{
// TODO: parallelize this (make async tasks for chunks of the catalog)
// doing it per-checker is MT-unsafe with API that calls SetIssue()!
int issues = 0;
for (auto& i: catalog.items())
issues += Check(i);
return issues;
}
int QAChecker::Check(CatalogItemPtr item)
{
int issues = 0;
for (auto& c: m_checks)
{
if (item->GetString().empty() || (item->HasPlural() && item->GetPluralString().empty()))
continue;
if (c->CheckItem(item))
issues++;
}
return issues;
}
std::shared_ptr<QAChecker> QAChecker::GetFor(Catalog& catalog)
{
auto lang = catalog.GetLanguage();
auto c = std::make_shared<QAChecker>();
c->AddCheck<QA::NotAllPlurals>();
c->AddCheck<QA::CaseMismatch>(lang);
c->AddCheck<QA::WhitespaceMismatch>();
c->AddCheck<QA::PunctuationMismatch>(lang);
return c;
}
<commit_msg>Fix false positive warnings on Arabic punctuation<commit_after>/*
* This file is part of Poedit (https://poedit.net)
*
* Copyright (C) 2017 Vaclav Slavik
*
* 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 "qa_checks.h"
#include <unicode/uchar.h>
#include <wx/translation.h>
// -------------------------------------------------------------
// QACheck implementations
// -------------------------------------------------------------
namespace QA
{
class NotAllPlurals : public QACheck
{
public:
bool CheckItem(CatalogItemPtr item) override
{
if (!item->HasPlural())
return false;
bool foundTranslated = false;
bool foundEmpty = false;
for (auto& s: item->GetTranslations())
{
if (s.empty())
foundEmpty = true;
else
foundTranslated = true;
}
if (foundEmpty && foundTranslated)
{
item->SetIssue(CatalogItem::Issue::Warning, _("Not all plural forms are translated."));
return true;
}
return false;
}
};
class CaseMismatch : public QACheck
{
public:
CaseMismatch(Language lang) : m_lang(lang.Lang())
{
}
bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override
{
if (u_isupper(source[0]) && u_islower(translation[0]))
{
item->SetIssue(CatalogItem::Issue::Warning, _("The translation should start as a sentence."));
return true;
}
if (u_islower(source[0]) && u_isupper(translation[0]))
{
if (m_lang != "de")
{
item->SetIssue(CatalogItem::Issue::Warning, _("The translation should start with a lowercase character."));
return true;
}
// else: German nouns start uppercased, this would cause too many false positives
}
return false;
}
private:
std::string m_lang;
};
class WhitespaceMismatch : public QACheck
{
public:
bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override
{
if (u_isspace(source[0]) && !u_isspace(translation[0]))
{
item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation doesn’t start with a space."));
return true;
}
if (!u_isspace(source[0]) && u_isspace(translation[0]))
{
item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation starts with a space, but the source text doesn’t."));
return true;
}
if (source.Last() == '\n' && translation.Last() != '\n')
{
item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation is missing a newline at the end."));
return true;
}
if (source.Last() != '\n' && translation.Last() == '\n')
{
item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation ends with a newline, but the source text doesn’t."));
return true;
}
if (u_isspace(source.Last()) && !u_isspace(translation.Last()))
{
item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation is missing a space at the end."));
return true;
}
if (!u_isspace(source.Last()) && u_isspace(translation.Last()))
{
item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation ends with a space, but the source text doesn’t."));
return true;
}
return false;
}
};
class PunctuationMismatch : public QACheck
{
public:
PunctuationMismatch(Language lang) : m_lang(lang.Lang())
{
}
bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override
{
const UChar32 s_last = source.Last();
const UChar32 t_last = translation.Last();
const bool s_punct = u_ispunct(s_last);
const bool t_punct = u_ispunct(t_last);
if (s_punct && !t_punct)
{
item->SetIssue(CatalogItem::Issue::Warning,
wxString::Format(_(L"The translation should end with “%s”."), wxString(wxUniChar(s_last))));
return true;
}
else if (!s_punct && t_punct)
{
item->SetIssue(CatalogItem::Issue::Warning,
wxString::Format(_(L"The translation should not end with “%s”."), wxString(wxUniChar(t_last))));
return true;
}
else if (s_punct && t_punct && s_last != t_last)
{
if (t_last == L'…' && source.EndsWith("..."))
{
// as a special case, allow translating ... (3 dots) as … (ellipsis)
}
else if (u_hasBinaryProperty(s_last, UCHAR_QUOTATION_MARK) && u_hasBinaryProperty(t_last, UCHAR_QUOTATION_MARK))
{
// don't check for correct quotes for now, accept any quotations marks as equal
}
else if (IsEquivalent(s_last, t_last))
{
// some characters are mostly equivalent and we shouldn't warn about them
}
else
{
item->SetIssue(CatalogItem::Issue::Warning,
wxString::Format(_(L"The translation ends with “%s”, but the source text ends with “%s”."),
wxString(wxUniChar(t_last)), wxString(wxUniChar(s_last))));
return true;
}
}
return false;
}
private:
bool IsEquivalent(UChar32 src, UChar32 trans) const
{
if (src == trans)
return true;
if (m_lang == "zh" || m_lang == "ja")
{
// Chinese uses full-width punctuation.
// See https://en.wikipedia.org/wiki/Chinese_punctuation
switch (src)
{
case '.':
return trans == L'。';
case '!':
return trans == L'!';
case '?':
return trans == L'?';
case ':':
return trans == L':';
default:
break;
}
}
else if (m_lang == "ar")
{
// In Arabic (but not other RTL languages), some punctuation is mirrored.
switch (src)
{
case ';':
return trans == L'؛';
case '?':
return trans == L'؟';
case ',':
return trans == L'،';
default:
break;
}
}
return false;
}
std::string m_lang;
};
} // namespace QA
// -------------------------------------------------------------
// QACheck support code
// -------------------------------------------------------------
bool QACheck::CheckItem(CatalogItemPtr item)
{
if (!item->GetTranslation().empty() && CheckString(item, item->GetString(), item->GetTranslation()))
return true;
if (item->HasPlural())
{
unsigned count = item->GetNumberOfTranslations();
for (unsigned i = 1; i < count; i++)
{
auto t = item->GetTranslation(i);
if (!t.empty() && CheckString(item, item->GetPluralString(), t))
return true;
}
}
return false;
}
bool QACheck::CheckString(CatalogItemPtr /*item*/, const wxString& /*source*/, const wxString& /*translation*/)
{
wxFAIL_MSG("not implemented - must override CheckString OR CheckItem");
return false;
}
// -------------------------------------------------------------
// QAChecker
// -------------------------------------------------------------
int QAChecker::Check(Catalog& catalog)
{
// TODO: parallelize this (make async tasks for chunks of the catalog)
// doing it per-checker is MT-unsafe with API that calls SetIssue()!
int issues = 0;
for (auto& i: catalog.items())
issues += Check(i);
return issues;
}
int QAChecker::Check(CatalogItemPtr item)
{
int issues = 0;
for (auto& c: m_checks)
{
if (item->GetString().empty() || (item->HasPlural() && item->GetPluralString().empty()))
continue;
if (c->CheckItem(item))
issues++;
}
return issues;
}
std::shared_ptr<QAChecker> QAChecker::GetFor(Catalog& catalog)
{
auto lang = catalog.GetLanguage();
auto c = std::make_shared<QAChecker>();
c->AddCheck<QA::NotAllPlurals>();
c->AddCheck<QA::CaseMismatch>(lang);
c->AddCheck<QA::WhitespaceMismatch>();
c->AddCheck<QA::PunctuationMismatch>(lang);
return c;
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
/// \file pcapcut.cpp
//------------------------------------------------------------------------------
/// \brief Utility for cutting a part of a large pcap file
//------------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com>
// Created: 2016-11-28
//------------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2016 Serge Aleynikov <saleyn@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.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
***** END LICENSE BLOCK *****
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <signal.h>
#include <utxx/pcap.hpp>
#include <utxx/string.hpp>
#include <utxx/path.hpp>
#include <utxx/get_option.hpp>
#include <utxx/buffer.hpp>
#include <utxx/version.hpp>
using namespace std;
//------------------------------------------------------------------------------
void usage(std::string const& err="")
{
if (!err.empty())
std::cerr << "Invalid option: " << err << "\n\n";
std::cerr <<
utxx::path::program::name() <<
" - Tool for extracting packets from a pcap file\n"
"Copyright (c) 2016 Serge Aleynikov\n\n"
"Usage: " << utxx::path::program::name() <<
"[-V] [-h] -f InputFile -s StartPktNum -e EndPktNum [-n PktCount]"
" -o OutputFile [-h]\n\n"
" -V|--version - Version\n"
" -h|--help - Help screen\n"
" -f InputFile - Input file name\n"
" -o OutputFile - Ouput file name (don't overwrite if exists)\n"
" -O OutputFile - Ouput file name (overwrite if exists)\n"
" -s|--start StartPktNum - Starting packet number (counting from 1)\n"
" -e|--end EndPktNum - Ending packet number (must be >= StartPktNum)\n"
" -n|--count PktCount - Number of packets to save\n"
" -r|--raw - Output raw packet payload only without pcap format\n\n";
exit(1);
}
//------------------------------------------------------------------------------
void unhandled_exception() {
auto p = current_exception();
try { rethrow_exception(p); }
catch ( exception& e ) { cerr << e.what() << endl; }
catch ( ... ) { cerr << "Unknown exception" << endl; }
exit(1);
}
//------------------------------------------------------------------------------
// MAIN
//------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
string in_file;
string out_file;
size_t pk_start = 1, pk_end = 0, pk_cnt = 0;
bool overwrite = false;
bool raw_mode = false;
set_terminate (&unhandled_exception);
utxx::opts_parser opts(argc, argv);
while (opts.next()) {
if (opts.match("-f", "", &in_file)) continue;
if (opts.match("-o", "", &out_file)) continue;
if (opts.match("-O", "", &out_file)){ overwrite=true; continue; }
if (opts.match("-r", "--raw", &raw_mode)) continue;
if (opts.match("-s", "--start", &pk_start)) continue;
if (opts.match("-e", "--end", &pk_end)) continue;
if (opts.match("-n", "--count", &pk_cnt)) continue;
if (opts.match("-V", "--version")) {
std::cerr << VERSION() << '\n';
exit(1);
}
if (opts.is_help()) usage();
usage(utxx::to_string("Invalid option: ", opts()));
}
if (pk_end > 0 && pk_cnt > 0)
throw std::runtime_error("Cannot specify both -n and -e options!");
else if (!pk_end && !pk_cnt)
throw std::runtime_error("Must specify either -n or -e option!");
else if (!pk_start)
throw std::runtime_error("PktStartNumber (-s) must be greater than 0!");
else if (pk_end && pk_end < pk_start)
throw std::runtime_error
("Ending packet number (-e) must not be less than starting packet number (-s)!");
else if (in_file.empty() || out_file.empty())
throw std::runtime_error("Must specify -f and -o options!");
else if (utxx::path::file_exists(out_file)) {
if (!overwrite)
throw std::runtime_error("Found existing output file: " + out_file);
if (!utxx::path::file_unlink(out_file))
throw std::runtime_error("Error deleting file " + out_file +
": " + strerror(errno));
}
if (pk_cnt) {
pk_end = pk_start + pk_cnt - 1;
pk_cnt = 0;
}
utxx::pcap fin;
if (fin.open_read(in_file) < 0)
throw std::runtime_error("Error opening " + in_file + ": " + strerror(errno));
else if (fin.read_file_header() < 0)
throw std::runtime_error("File " + in_file + " is not in PCAP format!");
int n;
utxx::pcap fout(fin.big_endian(), fin.nsec_time());
n = raw_mode ? fout.open(out_file.c_str(), "wb")
: fout.open_write(out_file, false, fin.get_link_type());
if (n < 0)
throw std::runtime_error("Error creating file " + out_file + ": " + strerror(errno));
utxx::basic_io_buffer<(64*1024)> buf;
while ((n = fin.read(buf.wr_ptr(), buf.capacity())) > 0) {
buf.commit(n);
while (buf.size() > sizeof(utxx::pcap::packet_header)) {
const char* header;
const char* begin = header = buf.rd_ptr();
int frame_sz, sz;
utxx::pcap::proto proto;
// sz - total size of payload including frame_sz
std::tie(frame_sz, sz, proto) = fin.read_packet_hdr_and_frame(begin, n);
if (frame_sz < 0 || int(buf.size()) < sz) { // Not enough data in the buffer
buf.reserve(sz);
break;
}
if (++pk_cnt >= pk_start) {
if (pk_cnt > pk_end)
goto DONE;
// Write to the output file
if (!raw_mode) {
fout.write_packet_header(fin.packet());
buf.read(sizeof(utxx::pcap::packet_header));
sz -= sizeof(utxx::pcap::packet_header);
} else {
buf.read(frame_sz);
sz -= frame_sz;
}
if (fout.write(buf.rd_ptr(), sz) < 0)
throw std::runtime_error(string("Error writing to file: ") + strerror(errno));
}
buf.read(sz);
}
buf.crunch();
}
DONE:
fout.close();
fin.close();
return 0;
}<commit_msg>Cleanup<commit_after>//------------------------------------------------------------------------------
/// \file pcapcut.cpp
//------------------------------------------------------------------------------
/// \brief Utility for cutting a part of a large pcap file
//------------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com>
// Created: 2016-11-28
//------------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2016 Serge Aleynikov <saleyn@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.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
***** END LICENSE BLOCK *****
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <signal.h>
#include <utxx/pcap.hpp>
#include <utxx/string.hpp>
#include <utxx/path.hpp>
#include <utxx/get_option.hpp>
#include <utxx/buffer.hpp>
#include <utxx/version.hpp>
using namespace std;
//------------------------------------------------------------------------------
void usage(std::string const& err="")
{
auto prog = utxx::path::basename(
utxx::path::program::name().c_str(),
utxx::path::program::name().c_str() + utxx::path::program::name().size()
);
if (!err.empty())
cerr << "Invalid option: " << err << "\n\n";
else {
cerr << prog <<
" - Tool for extracting packets from a pcap file\n"
"Copyright (c) 2016 Serge Aleynikov\n" <<
VERSION() << "\n\n" <<
"Usage: " << prog <<
"[-V] [-h] -f InputFile -s StartPktNum -e EndPktNum [-n PktCount]"
" -o|-O OutputFile [-h]\n\n"
" -V|--version - Version\n"
" -h|--help - Help screen\n"
" -f InputFile - Input file name\n"
" -o OutputFile - Ouput file name (don't overwrite if exists)\n"
" -O OutputFile - Ouput file name (overwrite if exists)\n"
" -s|--start StartPktNum - Starting packet number (counting from 1)\n"
" -e|--end EndPktNum - Ending packet number (must be >= StartPktNum)\n"
" -n|--count PktCount - Number of packets to save\n"
" -r|--raw - Output raw packet payload only without pcap format\n\n";
}
exit(1);
}
//------------------------------------------------------------------------------
void unhandled_exception() {
auto p = current_exception();
try { rethrow_exception(p); }
catch ( exception& e ) { cerr << e.what() << endl; }
catch ( ... ) { cerr << "Unknown exception" << endl; }
exit(1);
}
//------------------------------------------------------------------------------
// MAIN
//------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
string in_file;
string out_file;
size_t pk_start = 1, pk_end = 0, pk_cnt = 0;
bool overwrite = false;
bool raw_mode = false;
set_terminate (&unhandled_exception);
utxx::opts_parser opts(argc, argv);
while (opts.next()) {
if (opts.match("-f", "", &in_file)) continue;
if (opts.match("-o", "", &out_file)) continue;
if (opts.match("-O", "", &out_file)){overwrite=true; continue;}
if (opts.match("-r", "--raw", &raw_mode)) continue;
if (opts.match("-s", "--start", &pk_start)) continue;
if (opts.match("-e", "--end", &pk_end)) continue;
if (opts.match("-n", "--count", &pk_cnt)) continue;
if (opts.match("-V", "--version")) throw std::runtime_error(VERSION());
if (opts.is_help()) usage();
usage(opts());
}
if (pk_end > 0 && pk_cnt > 0)
throw std::runtime_error("Cannot specify both -n and -e options!");
else if (!pk_end && !pk_cnt)
throw std::runtime_error("Must specify either -n or -e option!");
else if (!pk_start)
throw std::runtime_error("PktStartNumber (-s) must be greater than 0!");
else if (pk_end && pk_end < pk_start)
throw std::runtime_error
("Ending packet number (-e) must not be less than starting packet number (-s)!");
else if (in_file.empty() || out_file.empty())
throw std::runtime_error("Must specify -f and -o options!");
else if (utxx::path::file_exists(out_file)) {
if (!overwrite)
throw std::runtime_error("Found existing output file: " + out_file);
if (!utxx::path::file_unlink(out_file))
throw std::runtime_error("Error deleting file " + out_file +
": " + strerror(errno));
}
if (pk_cnt) {
pk_end = pk_start + pk_cnt - 1;
pk_cnt = 0;
}
utxx::pcap fin;
if (fin.open_read(in_file) < 0)
throw std::runtime_error("Error opening " + in_file + ": " + strerror(errno));
else if (fin.read_file_header() < 0)
throw std::runtime_error("File " + in_file + " is not in PCAP format!");
int n;
utxx::pcap fout(fin.big_endian(), fin.nsec_time());
n = raw_mode ? fout.open(out_file.c_str(), "wb")
: fout.open_write(out_file, false, fin.get_link_type());
if (n < 0)
throw std::runtime_error("Error creating file " + out_file + ": " + strerror(errno));
utxx::basic_io_buffer<(64*1024)> buf;
while ((n = fin.read(buf.wr_ptr(), buf.capacity())) > 0) {
buf.commit(n);
while (buf.size() > sizeof(utxx::pcap::packet_header)) {
const char* header;
const char* begin = header = buf.rd_ptr();
int frame_sz, sz;
utxx::pcap::proto proto;
// sz - total size of payload including frame_sz
std::tie(frame_sz, sz, proto) = fin.read_packet_hdr_and_frame(begin, n);
if (frame_sz < 0 || int(buf.size()) < sz) { // Not enough data in the buffer
buf.reserve(sz);
break;
}
if (++pk_cnt >= pk_start) {
if (pk_cnt > pk_end)
goto DONE;
// Write to the output file
if (!raw_mode) {
fout.write_packet_header(fin.packet());
buf.read(sizeof(utxx::pcap::packet_header));
sz -= sizeof(utxx::pcap::packet_header);
} else {
buf.read(frame_sz);
sz -= frame_sz;
}
if (fout.write(buf.rd_ptr(), sz) < 0)
throw std::runtime_error(string("Error writing to file: ") + strerror(errno));
}
buf.read(sz);
}
buf.crunch();
}
DONE:
fout.close();
fin.close();
return 0;
}<|endoftext|> |
<commit_before>// Copyright 2012-2019 Richard Copley
//
// 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 "polymorph.h"
#include "aligned-arrays.h"
#include "compiler.h"
#include "glinit.h"
#include "print.h"
#include "qpc.h"
#include "resources.h"
#include <windowsx.h>
#define WC_MAIN TEXT ("M")
#if MONITOR_SELECT_ENABLED
struct monitor_enum_param_t
{
RECT * r;
int n;
};
BOOL CALLBACK monitor_enum_proc (HMONITOR, HDC, LPRECT rect, LPARAM lparam)
{
monitor_enum_param_t * pparam = (monitor_enum_param_t *) lparam;
if (pparam->n == 0) * pparam->r = * rect;
-- pparam->n;
return TRUE;
}
#endif
// Initial top, left, width and height (not right and bottom).
void get_rect (RECT & rect, const arguments_t & arguments)
{
if (arguments.mode == parented) {
::GetClientRect ((HWND) arguments.numeric_arg, & rect);
return;
}
#if MONITOR_SELECT_ENABLED
int n = (int) arguments.numeric_arg;
if (n >= 1) {
monitor_enum_param_t param = { & rect, n - 1 };
::EnumDisplayMonitors (
nullptr, nullptr, & monitor_enum_proc, (LPARAM) ¶m);
if (param.n < 0) {
rect.right -= rect.left;
rect.bottom -= rect.top;
return;
}
}
#endif
rect.left = ::GetSystemMetrics (SM_XVIRTUALSCREEN);
rect.top = ::GetSystemMetrics (SM_YVIRTUALSCREEN);
rect.right = ::GetSystemMetrics (SM_CXVIRTUALSCREEN);
rect.bottom = ::GetSystemMetrics (SM_CYVIRTUALSCREEN);
}
ALIGN_STACK
LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// Retrieve the window-struct pointer from the window userdata.
window_struct_t * ws =
(window_struct_t *) ::GetWindowLongPtr (hwnd, GWLP_USERDATA);
LRESULT result = 0;
bool no_defwndproc = true;
bool close_window = false;
if (! ws) {
if (msg == WM_CREATE) {
result = -1; // Destroy window.
// Retrieve the window-struct pointer from the window createstruct.
CREATESTRUCT * cs = (CREATESTRUCT *) lParam;
ws = (window_struct_t *) cs->lpCreateParams;
if (HDC hdc = ::GetDC (hwnd)) {
ws->hglrc = install_rendering_context (hdc);
if (ws->hglrc) {
// Successfully installed the rendering context.
// Store the window-struct pointer in userdata.
::SetWindowLongPtr (hwnd, GWLP_USERDATA, LONG_PTR (ws));
// Once-only model/graphics allocation and initialization.
// Abort window creation if shader program compilation fails.
result = ws->model.initialize (qpc ()) - 1;
}
::ReleaseDC (hwnd, hdc);
}
}
else {
no_defwndproc = false;
}
}
else {
run_mode_t mode = ws->arguments.mode;
switch (msg) {
case WM_APP: {
RECT rc;
get_rect (rc, ws->arguments);
// Show the window.
::SetWindowPos (hwnd, HWND_TOP, rc.left, rc.top, rc.right, rc.bottom,
SWP_SHOWWINDOW | SWP_NOOWNERZORDER | SWP_NOCOPYBITS);
// Remember initial cursor position to detect mouse movement.
::GetCursorPos (& ws->initial_cursor_position);
::InvalidateRect (hwnd, nullptr, FALSE);
break;
}
case WM_WINDOWPOSCHANGED: {
WINDOWPOS * wp = (WINDOWPOS *) lParam;
if (! (wp->flags & SWP_NOSIZE) || wp->flags & SWP_SHOWWINDOW) {
ws->model.start (wp->cx, wp->cy, ws->settings);
}
break;
}
case WM_PAINT: {
ws->model.draw_next ();
PAINTSTRUCT ps;
::BeginPaint (hwnd, & ps);
::SwapBuffers (ps.hdc);
::EndPaint (hwnd, & ps);
::InvalidateRect (hwnd, nullptr, FALSE);
break;
}
case WM_SETCURSOR:
::SetCursor (mode == screensaver || mode == configure
? nullptr
: ::LoadCursor (nullptr, IDC_ARROW));
break;
case WM_MOUSEMOVE:
if (mode == screensaver || mode == configure) {
// Compare current mouse position with that stored in the window struct.
DWORD pos = ::GetMessagePos ();
int dx = GET_X_LPARAM (pos) - ws->initial_cursor_position.x;
int dy = GET_Y_LPARAM (pos) - ws->initial_cursor_position.y;
close_window = (dx < -10 || dx > 10) || (dy < -10 || dy > 10);
}
break;
case WM_KEYDOWN:
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
close_window = mode != parented;
break;
case WM_ACTIVATE:
case WM_ACTIVATEAPP:
case WM_NCACTIVATE:
no_defwndproc = false;
close_window = (mode == screensaver || mode == configure)
&& LOWORD (wParam) == WA_INACTIVE;
break;
case WM_SYSCOMMAND:
no_defwndproc = (mode == screensaver || mode == configure)
&& wParam == SC_SCREENSAVE;
break;
case WM_CLOSE:
if (mode == configure) {
if (::GetWindowLongPtr (hwnd, GWL_STYLE) & WS_VISIBLE) {
// A simple "ShowWindow (SW_HIDE)" suffices to replace SetWindowPos
// and SetActiveWindow, but fails to actually hide the window if it
// occupies the full primary monitor rect and the pixel format
// specifies SWAP_EXCHANGE; now that we use SWAP_COPY, that problem
// no longer exists, but we still do it this way just in case.
::SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0, SWP_HIDEWINDOW
| SWP_NOSIZE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOACTIVATE);
::SetActiveWindow (ws->hdlg);
}
}
else
::DestroyWindow (hwnd);
break;
case WM_DESTROY:
::wglMakeCurrent (nullptr, nullptr);
::wglDeleteContext (ws->hglrc);
::PostQuitMessage (0);
break;
default:
no_defwndproc = false;
break;
}
}
if (close_window) {
::PostMessage (hwnd, WM_CLOSE, 0, 0);
}
if (!no_defwndproc) {
result = ::DefWindowProc (hwnd, msg, wParam, lParam);
}
return result;
}
HWND create_screensaver_window (window_struct_t & ws)
{
if (! glinit (ws.hInstance)) return 0;
LPCTSTR display_name;
::LoadString (ws.hInstance, 1, (LPTSTR) (& display_name), 0);
// Register the window class.
WNDCLASSEX wndclass = { sizeof (WNDCLASSEX), 0, & MainWndProc, 0, 0,
ws.hInstance, ws.icon, nullptr, nullptr, nullptr, WC_MAIN, ws.icon_small };
ATOM wc_main_atom = ::RegisterClassEx (&wndclass);
// Create the screen saver window.
HWND hwnd;
const arguments_t & args = ws.arguments;
HWND parent = args.mode == parented ? (HWND) args.numeric_arg : nullptr;
DWORD style = args.mode == parented ? WS_CHILD : WS_POPUP;
DWORD ex_style =
(args.mode == screensaver || args.mode == configure ? WS_EX_TOPMOST : 0) |
(args.mode == persistent ? WS_EX_APPWINDOW : WS_EX_TOOLWINDOW);
// Retry once on failure (works around sporadic SetPixelFormat
// failure observed on Intel integrated graphics on Windows 7).
for (unsigned retries = 0; retries != 2; ++ retries) {
hwnd = ::CreateWindowEx (ex_style, MAKEINTATOM (wc_main_atom), display_name,
style, 0, 0, 0, 0, parent, nullptr, ws.hInstance, & ws);
if (hwnd) {
break;
}
// Window creation failed (window has been destroyed).
}
return hwnd;
}
<commit_msg>monitor select: Do conditional compilation with constexpr-if.<commit_after>// Copyright 2012-2019 Richard Copley
//
// 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 "polymorph.h"
#include "aligned-arrays.h"
#include "compiler.h"
#include "glinit.h"
#include "print.h"
#include "qpc.h"
#include "resources.h"
#include <windowsx.h>
#define WC_MAIN TEXT ("M")
struct monitor_enum_param_t
{
RECT * r;
int n;
};
BOOL CALLBACK monitor_enum_proc (HMONITOR, HDC, LPRECT rect, LPARAM lparam)
{
monitor_enum_param_t * pparam = (monitor_enum_param_t *) lparam;
if (pparam->n == 0) * pparam->r = * rect;
-- pparam->n;
return TRUE;
}
// Initial top, left, width and height (not right and bottom).
void get_rect (RECT & rect, const arguments_t & arguments)
{
if (arguments.mode == parented) {
::GetClientRect ((HWND) arguments.numeric_arg, & rect);
return;
}
if constexpr (MONITOR_SELECT_ENABLED) {
int n = (int) arguments.numeric_arg;
if (n >= 1) {
monitor_enum_param_t param = { & rect, n - 1 };
::EnumDisplayMonitors (nullptr, nullptr,
& monitor_enum_proc, (LPARAM) & param);
if (param.n < 0) {
rect.right -= rect.left;
rect.bottom -= rect.top;
return;
}
}
}
rect.left = ::GetSystemMetrics (SM_XVIRTUALSCREEN);
rect.top = ::GetSystemMetrics (SM_YVIRTUALSCREEN);
rect.right = ::GetSystemMetrics (SM_CXVIRTUALSCREEN);
rect.bottom = ::GetSystemMetrics (SM_CYVIRTUALSCREEN);
}
ALIGN_STACK
LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// Retrieve the window-struct pointer from the window userdata.
window_struct_t * ws =
(window_struct_t *) ::GetWindowLongPtr (hwnd, GWLP_USERDATA);
LRESULT result = 0;
bool no_defwndproc = true;
bool close_window = false;
if (! ws) {
if (msg == WM_CREATE) {
result = -1; // Destroy window.
// Retrieve the window-struct pointer from the window createstruct.
CREATESTRUCT * cs = (CREATESTRUCT *) lParam;
ws = (window_struct_t *) cs->lpCreateParams;
if (HDC hdc = ::GetDC (hwnd)) {
ws->hglrc = install_rendering_context (hdc);
if (ws->hglrc) {
// Successfully installed the rendering context.
// Store the window-struct pointer in userdata.
::SetWindowLongPtr (hwnd, GWLP_USERDATA, LONG_PTR (ws));
// Once-only model/graphics allocation and initialization.
// Abort window creation if shader program compilation fails.
result = ws->model.initialize (qpc ()) - 1;
}
::ReleaseDC (hwnd, hdc);
}
}
else {
no_defwndproc = false;
}
}
else {
run_mode_t mode = ws->arguments.mode;
switch (msg) {
case WM_APP: {
RECT rc;
get_rect (rc, ws->arguments);
// Show the window.
::SetWindowPos (hwnd, HWND_TOP, rc.left, rc.top, rc.right, rc.bottom,
SWP_SHOWWINDOW | SWP_NOOWNERZORDER | SWP_NOCOPYBITS);
// Remember initial cursor position to detect mouse movement.
::GetCursorPos (& ws->initial_cursor_position);
::InvalidateRect (hwnd, nullptr, FALSE);
break;
}
case WM_WINDOWPOSCHANGED: {
WINDOWPOS * wp = (WINDOWPOS *) lParam;
if (! (wp->flags & SWP_NOSIZE) || wp->flags & SWP_SHOWWINDOW) {
ws->model.start (wp->cx, wp->cy, ws->settings);
}
break;
}
case WM_PAINT: {
ws->model.draw_next ();
PAINTSTRUCT ps;
::BeginPaint (hwnd, & ps);
::SwapBuffers (ps.hdc);
::EndPaint (hwnd, & ps);
::InvalidateRect (hwnd, nullptr, FALSE);
break;
}
case WM_SETCURSOR:
::SetCursor (mode == screensaver || mode == configure
? nullptr
: ::LoadCursor (nullptr, IDC_ARROW));
break;
case WM_MOUSEMOVE:
if (mode == screensaver || mode == configure) {
// Compare current mouse position with that stored in the window struct.
DWORD pos = ::GetMessagePos ();
int dx = GET_X_LPARAM (pos) - ws->initial_cursor_position.x;
int dy = GET_Y_LPARAM (pos) - ws->initial_cursor_position.y;
close_window = (dx < -10 || dx > 10) || (dy < -10 || dy > 10);
}
break;
case WM_KEYDOWN:
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
close_window = mode != parented;
break;
case WM_ACTIVATE:
case WM_ACTIVATEAPP:
case WM_NCACTIVATE:
no_defwndproc = false;
close_window = (mode == screensaver || mode == configure)
&& LOWORD (wParam) == WA_INACTIVE;
break;
case WM_SYSCOMMAND:
no_defwndproc = (mode == screensaver || mode == configure)
&& wParam == SC_SCREENSAVE;
break;
case WM_CLOSE:
if (mode == configure) {
if (::GetWindowLongPtr (hwnd, GWL_STYLE) & WS_VISIBLE) {
// A simple "ShowWindow (SW_HIDE)" suffices to replace SetWindowPos
// and SetActiveWindow, but fails to actually hide the window if it
// occupies the full primary monitor rect and the pixel format
// specifies SWAP_EXCHANGE; now that we use SWAP_COPY, that problem
// no longer exists, but we still do it this way just in case.
::SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0, SWP_HIDEWINDOW
| SWP_NOSIZE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOACTIVATE);
::SetActiveWindow (ws->hdlg);
}
}
else
::DestroyWindow (hwnd);
break;
case WM_DESTROY:
::wglMakeCurrent (nullptr, nullptr);
::wglDeleteContext (ws->hglrc);
::PostQuitMessage (0);
break;
default:
no_defwndproc = false;
break;
}
}
if (close_window) {
::PostMessage (hwnd, WM_CLOSE, 0, 0);
}
if (!no_defwndproc) {
result = ::DefWindowProc (hwnd, msg, wParam, lParam);
}
return result;
}
HWND create_screensaver_window (window_struct_t & ws)
{
if (! glinit (ws.hInstance)) return 0;
LPCTSTR display_name;
::LoadString (ws.hInstance, 1, (LPTSTR) (& display_name), 0);
// Register the window class.
WNDCLASSEX wndclass = { sizeof (WNDCLASSEX), 0, & MainWndProc, 0, 0,
ws.hInstance, ws.icon, nullptr, nullptr, nullptr, WC_MAIN, ws.icon_small };
ATOM wc_main_atom = ::RegisterClassEx (&wndclass);
// Create the screen saver window.
HWND hwnd;
const arguments_t & args = ws.arguments;
HWND parent = args.mode == parented ? (HWND) args.numeric_arg : nullptr;
DWORD style = args.mode == parented ? WS_CHILD : WS_POPUP;
DWORD ex_style =
(args.mode == screensaver || args.mode == configure ? WS_EX_TOPMOST : 0) |
(args.mode == persistent ? WS_EX_APPWINDOW : WS_EX_TOOLWINDOW);
// Retry once on failure (works around sporadic SetPixelFormat
// failure observed on Intel integrated graphics on Windows 7).
for (unsigned retries = 0; retries != 2; ++ retries) {
hwnd = ::CreateWindowEx (ex_style, MAKEINTATOM (wc_main_atom), display_name,
style, 0, 0, 0, 0, parent, nullptr, ws.hInstance, & ws);
if (hwnd) {
break;
}
// Window creation failed (window has been destroyed).
}
return hwnd;
}
<|endoftext|> |
<commit_before>/*
* Publisher
*/
#include "constants.hpp"
#include "publisher.hpp"
#include <unistd.h>
#include <zmqpp/zmqpp.hpp>
#include <string>
#include <sstream>
#include <iostream>
#include <boost/thread.hpp>
Publisher::Publisher(zmqpp::context* z_ctx_, host_t data_) :
Transmitter(z_ctx_),
z_heartbeater(nullptr),
z_publisher(nullptr),
data(data_) {
tac = (char*)"pub";
this->connectToHeartbeater();
}
Publisher::~Publisher() {
z_heartbeater->close();
z_publisher->close();
delete z_heartbeater;
delete z_publisher;
}
int Publisher::connectToHeartbeater()
{
// connect to process broadcast
z_heartbeater = new zmqpp::socket(*z_ctx, zmqpp::socket_type::pair);
z_heartbeater->connect("inproc://pub_hb_pair");
return 0;
}
int Publisher::run()
{
// internal check if publisher was correctly initialized
if ( z_ctx == nullptr || data.endpoint.compare("") == 0 )
return 1;
if (SB_MSG_DEBUG) printf("pub: setting up authentication...\n");
zmqpp::auth authenticator(*z_ctx);
if (SB_MSG_DEBUG) authenticator.set_verbose (true);
authenticator.configure_domain("*");
Config* conf = Config::getInstance();
std::vector<std::string> node_endpoints = conf->getNodePublicKeys();
for (std::vector<std::string>::iterator i=node_endpoints.begin();
i != node_endpoints.end(); ++i) {
authenticator.configure_curve(*i);
}
if (SB_MSG_DEBUG) printf("pub: starting pub socket and sending...\n");
z_publisher = new zmqpp::socket(*z_ctx, zmqpp::socket_type::pub);
z_publisher->set(zmqpp::socket_option::identity, data.uid->getHash());
z_publisher->set(zmqpp::socket_option::curve_server, 1);
z_publisher->set(zmqpp::socket_option::curve_secret_key, data.keypair.secret_key);
z_publisher->bind(data.endpoint.c_str());
std::stringstream* sstream;
int msg_type, msg_signal;
while(true)
{
// waiting for boxoffice input in non-blocking mode
sstream = new std::stringstream();
s_recv(*z_boxoffice_push, *z_broadcast, *z_heartbeater, *sstream);
*sstream >> msg_type >> msg_signal;
if ( msg_type == SB_SIGTYPE_LIFE && msg_signal == SB_SIGLIFE_INTERRUPT ) break;
// send a message
std::string infomessage;
*sstream >> infomessage;
if (SB_MSG_DEBUG) printf("pub: %d %s\n", msg_signal, infomessage.c_str());
std::stringstream message;
message << msg_signal << " " << infomessage.c_str();
zmqpp::message z_msg;
z_msg << message.str();
z_publisher->send(z_msg);
delete sstream;
}
delete sstream;
return 0;
}<commit_msg>fixed publisher<->heartbeater bug where none was binding the connection<commit_after>/*
* Publisher
*/
#include "constants.hpp"
#include "publisher.hpp"
#include <unistd.h>
#include <zmqpp/zmqpp.hpp>
#include <string>
#include <sstream>
#include <iostream>
#include <boost/thread.hpp>
Publisher::Publisher(zmqpp::context* z_ctx_, host_t data_) :
Transmitter(z_ctx_),
z_heartbeater(nullptr),
z_publisher(nullptr),
data(data_) {
tac = (char*)"pub";
this->connectToHeartbeater();
}
Publisher::~Publisher() {
z_heartbeater->close();
z_publisher->close();
delete z_heartbeater;
delete z_publisher;
}
int Publisher::connectToHeartbeater()
{
// connect to process broadcast
z_heartbeater = new zmqpp::socket(*z_ctx, zmqpp::socket_type::pair);
z_heartbeater->bind("inproc://pub_hb_pair");
return 0;
}
int Publisher::run()
{
// internal check if publisher was correctly initialized
if ( z_ctx == nullptr || data.endpoint.compare("") == 0 )
return 1;
if (SB_MSG_DEBUG) printf("pub: setting up authentication...\n");
zmqpp::auth authenticator(*z_ctx);
if (SB_MSG_DEBUG) authenticator.set_verbose (true);
authenticator.configure_domain("*");
Config* conf = Config::getInstance();
std::vector<std::string> node_endpoints = conf->getNodePublicKeys();
for (std::vector<std::string>::iterator i=node_endpoints.begin();
i != node_endpoints.end(); ++i) {
authenticator.configure_curve(*i);
}
if (SB_MSG_DEBUG) printf("pub: starting pub socket and sending...\n");
z_publisher = new zmqpp::socket(*z_ctx, zmqpp::socket_type::pub);
z_publisher->set(zmqpp::socket_option::identity, data.uid->getHash());
z_publisher->set(zmqpp::socket_option::curve_server, 1);
z_publisher->set(zmqpp::socket_option::curve_secret_key, data.keypair.secret_key);
z_publisher->bind(data.endpoint.c_str());
std::stringstream* sstream;
int msg_type, msg_signal;
while(true)
{
// waiting for boxoffice input in non-blocking mode
sstream = new std::stringstream();
s_recv(*z_boxoffice_push, *z_broadcast, *z_heartbeater, *sstream);
*sstream >> msg_type >> msg_signal;
if ( msg_type == SB_SIGTYPE_LIFE && msg_signal == SB_SIGLIFE_INTERRUPT ) break;
// send a message
std::string infomessage;
*sstream >> infomessage;
if (SB_MSG_DEBUG) printf("pub: %d %s\n", msg_signal, infomessage.c_str());
std::stringstream message;
message << msg_signal << " " << infomessage.c_str();
zmqpp::message z_msg;
z_msg << message.str();
z_publisher->send(z_msg);
delete sstream;
}
delete sstream;
return 0;
}<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <fstream>
#include <sstream>
#include "recurring.hpp"
#include "args.hpp"
#include "accounts.hpp"
#include "data.hpp"
#include "guid.hpp"
#include "config.hpp"
#include "utils.hpp"
#include "console.hpp"
#include "budget_exception.hpp"
#include "expenses.hpp"
#include "writer.hpp"
using namespace budget;
namespace {
static data_handler<recurring> recurrings { "recurrings", "recurrings.data" };
} //end of anonymous namespace
std::map<std::string, std::string> budget::recurring::get_params(){
std::map<std::string, std::string> params;
params["input_id"] = budget::to_string(id);
params["input_guid"] = guid;
params["input_name"] = name;
params["input_old_account"] = budget::to_string(old_account);
params["input_amount"] = budget::to_string(amount);
params["input_recurs"] = recurs;
params["input_account"] = account;
return params;
}
void budget::recurring_module::preload() {
// In server mode, there is no need to generate recurring expenses
// the server will take charge of that
if (is_server_mode()) {
return;
}
load_recurrings();
load_accounts();
load_expenses();
// In random mode, we do not try to create recurrings
if (config_contains("random")) {
return;
}
auto now = budget::local_day();
bool changed = false;
for (auto& recurring : recurrings.data) {
auto l_year = last_year(recurring);
auto l_month = last_month(recurring, l_year);
budget::date recurring_date(l_year, l_month, 1);
while (!(recurring_date.year() == now.year() && recurring_date.month() == now.month())) {
// Get to the next month
recurring_date += budget::months(1);
budget::expense recurring_expense;
recurring_expense.guid = generate_guid();
recurring_expense.date = recurring_date;
recurring_expense.account = get_account(recurring.account, recurring_date.year(), recurring_date.month()).id;
recurring_expense.amount = recurring.amount;
recurring_expense.name = recurring.name;
add_expense(std::move(recurring_expense));
changed = true;
}
}
if(changed){
save_expenses();
}
internal_config_remove("recurring:last_checked");
}
void budget::recurring_module::load(){
// Only need to load in server mode
if (is_server_mode()) {
load_recurrings();
load_accounts();
load_expenses();
}
}
void budget::recurring_module::unload(){
save_recurrings();
}
void budget::recurring_module::handle(const std::vector<std::string>& args){
budget::console_writer w(std::cout);
if(args.size() == 1){
show_recurrings(w);
} else {
auto& subcommand = args[1];
if(subcommand == "show"){
show_recurrings(w);
} else if(subcommand == "add"){
recurring recurring;
recurring.guid = generate_guid();
recurring.recurs = "monthly";
edit_string_complete(recurring.account, "Account", all_account_names(), not_empty_checker(), account_checker());
edit_string(recurring.name, "Name", not_empty_checker());
edit_money(recurring.amount, "Amount", not_negative_checker());
// Create the equivalent expense
auto date = budget::local_day();
budget::expense recurring_expense;
recurring_expense.guid = generate_guid();
recurring_expense.account = get_account(recurring.account, date.year(), date.month()).id;
recurring_expense.date = date;
recurring_expense.amount = recurring.amount;
recurring_expense.name = recurring.name;
add_expense(std::move(recurring_expense));
save_expenses();
auto id = recurrings.add(std::move(recurring));
std::cout << "Recurring expense " << id << " has been created" << std::endl;
} else if(subcommand == "delete"){
enough_args(args, 3);
size_t id = to_number<size_t>(args[2]);
if(!recurrings.exists(id)){
throw budget_exception("There are no recurring expense with id " + args[2]);
}
recurrings.remove(id);
std::cout << "Recurring expense " << id << " has been deleted" << std::endl;
std::cout << "Note: The generated expenses have not been deleted" << std::endl;
} else if(subcommand == "edit"){
enough_args(args, 3);
size_t id = to_number<size_t>(args[2]);
if(!recurrings.exists(id)){
throw budget_exception("There are no recurring expense with id " + args[2]);
}
auto& recurring = recurrings[id];
auto previous_recurring = recurring; // Temporary Copy
auto now = budget::local_day();
edit_string_complete(recurring.account, "Account", all_account_names(), not_empty_checker(), account_checker());
edit_string(recurring.name, "Name", not_empty_checker());
edit_money(recurring.amount, "Amount", not_negative_checker());
// Update the corresponding expense
for(auto& expense : all_expenses()){
if(expense.date.year() == now.year() && expense.date.month() == now.month()
&& expense.name == previous_recurring.name && expense.amount == previous_recurring.amount
&& get_account(expense.account).name == previous_recurring.account){
expense.name = recurring.name;
expense.amount = recurring.amount;
expense.account = get_account(recurring.account, now.year(), now.month()).id;
edit_expense(expense);
break;
}
}
save_expenses();
if (recurrings.edit(recurring)) {
std::cout << "Recurring expense " << id << " has been modified" << std::endl;
}
} else {
throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
}
}
}
void budget::load_recurrings(){
recurrings.load();
}
void budget::save_recurrings(){
recurrings.save();
}
std::ostream& budget::operator<<(std::ostream& stream, const recurring& recurring){
return stream << recurring.id << ':' << recurring.guid << ':' << recurring.account << ':' << recurring.name << ':' << recurring.amount << ":" << recurring.recurs;
}
void budget::migrate_recurring_1_to_2(){
load_accounts();
recurrings.load([](const std::vector<std::string>& parts, recurring& recurring){
recurring.id = to_number<size_t>(parts[0]);
recurring.guid = parts[1];
recurring.old_account = to_number<size_t>(parts[2]);
recurring.name = parts[3];
recurring.amount = parse_money(parts[4]);
recurring.recurs = parts[5];
});
for(auto& recurring : all_recurrings()){
recurring.account = get_account(recurring.old_account).name;
}
recurrings.set_changed();
recurrings.save();
}
void budget::operator>>(const std::vector<std::string>& parts, recurring& recurring){
bool random = config_contains("random");
recurring.id = to_number<size_t>(parts[0]);
recurring.guid = parts[1];
recurring.account = parts[2];
recurring.name = parts[3];
recurring.recurs = parts[5];
if(random){
recurring.amount = budget::random_money(100, 1000);
} else {
recurring.amount = parse_money(parts[4]);
}
}
budget::year budget::first_year(const budget::recurring& recurring){
budget::year year(1400);
for(auto& expense : all_expenses()){
if(expense.name == recurring.name && expense.amount == recurring.amount && get_account(expense.account).name == recurring.account){
if(year == 1400 || expense.date.year() < year){
year = expense.date.year();
}
}
}
return year;
}
budget::month budget::first_month(const budget::recurring& recurring, budget::year year){
budget::month month(13);
for(auto& expense : all_expenses()){
if(expense.date.year() == year && expense.name == recurring.name && expense.amount == recurring.amount && get_account(expense.account).name == recurring.account){
if(month == 13 || expense.date.month() < month){
month = expense.date.month();
}
}
}
return month;
}
budget::year budget::last_year(const budget::recurring& recurring){
budget::year year(1400);
for(auto& expense : all_expenses()){
if(expense.name == recurring.name && expense.amount == recurring.amount && get_account(expense.account).name == recurring.account){
if(year == 1400 || expense.date.year() > year){
year = expense.date.year();
}
}
}
return year;
}
budget::month budget::last_month(const budget::recurring& recurring, budget::year year){
budget::month month(13);
for(auto& expense : all_expenses()){
if(expense.date.year() == year && expense.name == recurring.name && expense.amount == recurring.amount && get_account(expense.account).name == recurring.account){
if(month == 13 || expense.date.month() > month){
month = expense.date.month();
}
}
}
return month;
}
std::vector<recurring>& budget::all_recurrings(){
return recurrings.data;
}
void budget::set_recurrings_changed(){
recurrings.set_changed();
}
void budget::set_recurrings_next_id(size_t next_id){
recurrings.next_id = next_id;
}
void budget::show_recurrings(budget::writer& w) {
w << title_begin << "Recurring expenses " << add_button("recurrings") << title_end;
if (recurrings.data.empty()) {
w << "No recurring expenses" << end_of_line;
} else {
std::vector<std::string> columns = {"ID", "Account", "Name", "Amount", "Recurs", "Edit"};
std::vector<std::vector<std::string>> contents;
money total;
for (auto& recurring : recurrings.data) {
contents.push_back({to_string(recurring.id), recurring.account, recurring.name, to_string(recurring.amount), recurring.recurs, "::edit::recurrings::" + to_string(recurring.id)});
total += recurring.amount;
}
contents.push_back({"", "", "", "", "", ""});
contents.push_back({"", "", "Total", to_string(total), "", ""});
w.display_table(columns, contents);
}
}
bool budget::recurring_exists(size_t id){
return recurrings.exists(id);
}
void budget::recurring_delete(size_t id) {
if (!recurrings.exists(id)) {
throw budget_exception("There are no recurring with id ");
}
recurrings.remove(id);
}
recurring& budget::recurring_get(size_t id) {
if (!recurrings.exists(id)) {
throw budget_exception("There are no recurring with id ");
}
return recurrings[id];
}
void budget::add_recurring(budget::recurring&& recurring){
recurrings.add(std::forward<budget::recurring>(recurring));
}
<commit_msg>Cleanup code style<commit_after>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <fstream>
#include <sstream>
#include "recurring.hpp"
#include "args.hpp"
#include "accounts.hpp"
#include "data.hpp"
#include "guid.hpp"
#include "config.hpp"
#include "utils.hpp"
#include "console.hpp"
#include "budget_exception.hpp"
#include "expenses.hpp"
#include "writer.hpp"
using namespace budget;
namespace {
static data_handler<recurring> recurrings { "recurrings", "recurrings.data" };
} //end of anonymous namespace
std::map<std::string, std::string> budget::recurring::get_params() {
std::map<std::string, std::string> params;
params["input_id"] = budget::to_string(id);
params["input_guid"] = guid;
params["input_name"] = name;
params["input_old_account"] = budget::to_string(old_account);
params["input_amount"] = budget::to_string(amount);
params["input_recurs"] = recurs;
params["input_account"] = account;
return params;
}
void budget::recurring_module::preload() {
// In server mode, there is no need to generate recurring expenses
// the server will take charge of that
if (is_server_mode()) {
return;
}
load_recurrings();
load_accounts();
load_expenses();
// In random mode, we do not try to create recurrings
if (config_contains("random")) {
return;
}
auto now = budget::local_day();
bool changed = false;
for (auto& recurring : recurrings.data) {
auto l_year = last_year(recurring);
auto l_month = last_month(recurring, l_year);
budget::date recurring_date(l_year, l_month, 1);
while (!(recurring_date.year() == now.year() && recurring_date.month() == now.month())) {
// Get to the next month
recurring_date += budget::months(1);
budget::expense recurring_expense;
recurring_expense.guid = generate_guid();
recurring_expense.date = recurring_date;
recurring_expense.account = get_account(recurring.account, recurring_date.year(), recurring_date.month()).id;
recurring_expense.amount = recurring.amount;
recurring_expense.name = recurring.name;
add_expense(std::move(recurring_expense));
changed = true;
}
}
if (changed) {
save_expenses();
}
internal_config_remove("recurring:last_checked");
}
void budget::recurring_module::load() {
// Only need to load in server mode
if (is_server_mode()) {
load_recurrings();
load_accounts();
load_expenses();
}
}
void budget::recurring_module::unload() {
save_recurrings();
}
void budget::recurring_module::handle(const std::vector<std::string>& args) {
budget::console_writer w(std::cout);
if (args.size() == 1) {
show_recurrings(w);
} else {
auto& subcommand = args[1];
if (subcommand == "show") {
show_recurrings(w);
} else if (subcommand == "add") {
recurring recurring;
recurring.guid = generate_guid();
recurring.recurs = "monthly";
edit_string_complete(recurring.account, "Account", all_account_names(), not_empty_checker(), account_checker());
edit_string(recurring.name, "Name", not_empty_checker());
edit_money(recurring.amount, "Amount", not_negative_checker());
// Create the equivalent expense
auto date = budget::local_day();
budget::expense recurring_expense;
recurring_expense.guid = generate_guid();
recurring_expense.account = get_account(recurring.account, date.year(), date.month()).id;
recurring_expense.date = date;
recurring_expense.amount = recurring.amount;
recurring_expense.name = recurring.name;
add_expense(std::move(recurring_expense));
save_expenses();
auto id = recurrings.add(std::move(recurring));
std::cout << "Recurring expense " << id << " has been created" << std::endl;
} else if (subcommand == "delete") {
enough_args(args, 3);
size_t id = to_number<size_t>(args[2]);
if (!recurrings.exists(id)) {
throw budget_exception("There are no recurring expense with id " + args[2]);
}
recurrings.remove(id);
std::cout << "Recurring expense " << id << " has been deleted" << std::endl;
std::cout << "Note: The generated expenses have not been deleted" << std::endl;
} else if (subcommand == "edit") {
enough_args(args, 3);
size_t id = to_number<size_t>(args[2]);
if (!recurrings.exists(id)) {
throw budget_exception("There are no recurring expense with id " + args[2]);
}
auto& recurring = recurrings[id];
auto previous_recurring = recurring; // Temporary Copy
auto now = budget::local_day();
edit_string_complete(recurring.account, "Account", all_account_names(), not_empty_checker(), account_checker());
edit_string(recurring.name, "Name", not_empty_checker());
edit_money(recurring.amount, "Amount", not_negative_checker());
// Update the corresponding expense
for (auto& expense : all_expenses()) {
if (expense.date.year() == now.year() && expense.date.month() == now.month() && expense.name == previous_recurring.name && expense.amount == previous_recurring.amount && get_account(expense.account).name == previous_recurring.account) {
expense.name = recurring.name;
expense.amount = recurring.amount;
expense.account = get_account(recurring.account, now.year(), now.month()).id;
edit_expense(expense);
break;
}
}
save_expenses();
if (recurrings.edit(recurring)) {
std::cout << "Recurring expense " << id << " has been modified" << std::endl;
}
} else {
throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
}
}
}
void budget::load_recurrings() {
recurrings.load();
}
void budget::save_recurrings() {
recurrings.save();
}
std::ostream& budget::operator<<(std::ostream& stream, const recurring& recurring) {
return stream << recurring.id << ':' << recurring.guid << ':' << recurring.account << ':' << recurring.name << ':' << recurring.amount << ":" << recurring.recurs;
}
void budget::migrate_recurring_1_to_2() {
load_accounts();
recurrings.load([](const std::vector<std::string>& parts, recurring& recurring) {
recurring.id = to_number<size_t>(parts[0]);
recurring.guid = parts[1];
recurring.old_account = to_number<size_t>(parts[2]);
recurring.name = parts[3];
recurring.amount = parse_money(parts[4]);
recurring.recurs = parts[5];
});
for (auto& recurring : all_recurrings()) {
recurring.account = get_account(recurring.old_account).name;
}
recurrings.set_changed();
recurrings.save();
}
void budget::operator>>(const std::vector<std::string>& parts, recurring& recurring) {
bool random = config_contains("random");
recurring.id = to_number<size_t>(parts[0]);
recurring.guid = parts[1];
recurring.account = parts[2];
recurring.name = parts[3];
recurring.recurs = parts[5];
if (random) {
recurring.amount = budget::random_money(100, 1000);
} else {
recurring.amount = parse_money(parts[4]);
}
}
budget::year budget::first_year(const budget::recurring& recurring) {
budget::year year(1400);
for (auto& expense : all_expenses()) {
if (expense.name == recurring.name && expense.amount == recurring.amount && get_account(expense.account).name == recurring.account) {
if (year == 1400 || expense.date.year() < year) {
year = expense.date.year();
}
}
}
return year;
}
budget::month budget::first_month(const budget::recurring& recurring, budget::year year) {
budget::month month(13);
for (auto& expense : all_expenses()) {
if (expense.date.year() == year && expense.name == recurring.name && expense.amount == recurring.amount && get_account(expense.account).name == recurring.account) {
if (month == 13 || expense.date.month() < month) {
month = expense.date.month();
}
}
}
return month;
}
budget::year budget::last_year(const budget::recurring& recurring) {
budget::year year(1400);
for (auto& expense : all_expenses()) {
if (expense.name == recurring.name && expense.amount == recurring.amount && get_account(expense.account).name == recurring.account) {
if (year == 1400 || expense.date.year() > year) {
year = expense.date.year();
}
}
}
return year;
}
budget::month budget::last_month(const budget::recurring& recurring, budget::year year) {
budget::month month(13);
for (auto& expense : all_expenses()) {
if (expense.date.year() == year && expense.name == recurring.name && expense.amount == recurring.amount && get_account(expense.account).name == recurring.account) {
if (month == 13 || expense.date.month() > month) {
month = expense.date.month();
}
}
}
return month;
}
std::vector<recurring>& budget::all_recurrings() {
return recurrings.data;
}
void budget::set_recurrings_changed() {
recurrings.set_changed();
}
void budget::set_recurrings_next_id(size_t next_id) {
recurrings.next_id = next_id;
}
void budget::show_recurrings(budget::writer& w) {
w << title_begin << "Recurring expenses " << add_button("recurrings") << title_end;
if (recurrings.data.empty()) {
w << "No recurring expenses" << end_of_line;
} else {
std::vector<std::string> columns = {"ID", "Account", "Name", "Amount", "Recurs", "Edit"};
std::vector<std::vector<std::string>> contents;
money total;
for (auto& recurring : recurrings.data) {
contents.push_back({to_string(recurring.id), recurring.account, recurring.name, to_string(recurring.amount), recurring.recurs, "::edit::recurrings::" + to_string(recurring.id)});
total += recurring.amount;
}
contents.push_back({"", "", "", "", "", ""});
contents.push_back({"", "", "Total", to_string(total), "", ""});
w.display_table(columns, contents);
}
}
bool budget::recurring_exists(size_t id) {
return recurrings.exists(id);
}
void budget::recurring_delete(size_t id) {
if (!recurrings.exists(id)) {
throw budget_exception("There are no recurring with id ");
}
recurrings.remove(id);
}
recurring& budget::recurring_get(size_t id) {
if (!recurrings.exists(id)) {
throw budget_exception("There are no recurring with id ");
}
return recurrings[id];
}
void budget::add_recurring(budget::recurring&& recurring) {
recurrings.add(std::forward<budget::recurring>(recurring));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <set>
#include "rpcclient.h"
#include "rpcprotocol.h"
#include "util.h"
#include "ui_interface.h"
#include "chainparams.h" // for Params().RPCPort()
#include <stdint.h>
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include "json/json_spirit_writer_template.h"
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl", false);
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
bool fWait = GetBoolArg("-rpcwait", false); // -rpcwait means try until server has started
do {
bool fConnected = d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(Params().RPCPort())));
if (fConnected) break;
if (fWait)
MilliSleep(1000);
else
throw runtime_error("couldn't connect to server");
} while (fWait);
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive HTTP reply status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Receive HTTP reply message headers and body
map<string, string> mapHeaders;
string strReply;
ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
class CRPCConvertParam
{
public:
std::string methodName; // method whose params want conversion
int paramIdx; // 0-based idx of param to convert
};
static const CRPCConvertParam vRPCConvertParams[] =
{
{ "stop", 0 },
{ "getaddednodeinfo", 0 },
{ "sendtoaddress", 1 },
{ "settxfee", 0 },
{ "getreceivedbyaddress", 1 },
{ "getreceivedbyaccount", 1 },
{ "listreceivedbyaddress", 0 },
{ "listreceive"
"dbyaddress", 1 },
{ "listreceivedbyaccount", 0 },
{ "listreceivedbyaccount", 1 },
{ "getbalance", 1 },
{ "getblock", 1 },
{ "getblockbynumber", 0 },
{ "getblockbynumber", 1 },
{ "getblockhash", 0 },
{ "move", 2 },
{ "move", 3 },
{ "sendfrom", 2 },
{ "sendfrom", 3 },
{ "listtransactions", 1 },
{ "listtransactions", 2 },
{ "listaccounts", 0 },
{ "walletpassphrase", 1 },
{ "walletpassphrase", 2 },
{ "getblocktemplate", 0 },
{ "listsinceblock", 1 },
{ "sendalert", 2 },
{ "sendalert", 3 },
{ "sendalert", 4 },
{ "sendalert", 5 },
{ "sendalert", 6 },
{ "sendmany", 1 },
{ "sendmany", 2 },
{ "reservebalance", 0 },
{ "reservebalance", 1 },
{ "addmultisigaddress", 0 },
{ "addmultisigaddress", 1 },
{ "listunspent", 0 },
{ "listunspent", 1 },
{ "listunspent", 2 },
{ "getrawtransaction", 1 },
{ "createrawtransaction", 0 },
{ "createrawtransaction", 1 },
{ "signrawtransaction", 1 },
{ "signrawtransaction", 2 },
{ "keypoolrefill", 0 },
{ "importprivkey", 2 },
{ "checkkernel", 0 },
{ "checkkernel", 1 },
{ "submitblock", 1 },
};
class CRPCConvertTable
{
private:
std::set<std::pair<std::string, int> > members;
public:
CRPCConvertTable();
bool convert(const std::string& method, int idx) {
return (members.count(std::make_pair(method, idx)) > 0);
}
};
CRPCConvertTable::CRPCConvertTable()
{
const unsigned int n_elem =
(sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0]));
for (unsigned int i = 0; i < n_elem; i++) {
members.insert(std::make_pair(vRPCConvertParams[i].methodName,
vRPCConvertParams[i].paramIdx));
}
}
static CRPCConvertTable rpcCvtTable;
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
for (unsigned int idx = 0; idx < strParams.size(); idx++) {
const std::string& strVal = strParams[idx];
// insert string value directly
if (!rpcCvtTable.convert(strMethod, idx)) {
params.push_back(strVal);
}
// parse string as JSON, insert bool/number/object/etc. value
else {
Value jVal;
if (!read_string(strVal, jVal))
throw runtime_error(string("Error parsing JSON:")+strVal);
params.push_back(jVal);
}
}
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...) {
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
<commit_msg>Fix typo<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <set>
#include "rpcclient.h"
#include "rpcprotocol.h"
#include "util.h"
#include "ui_interface.h"
#include "chainparams.h" // for Params().RPCPort()
#include <stdint.h>
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include "json/json_spirit_writer_template.h"
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl", false);
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
bool fWait = GetBoolArg("-rpcwait", false); // -rpcwait means try until server has started
do {
bool fConnected = d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(Params().RPCPort())));
if (fConnected) break;
if (fWait)
MilliSleep(1000);
else
throw runtime_error("couldn't connect to server");
} while (fWait);
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive HTTP reply status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Receive HTTP reply message headers and body
map<string, string> mapHeaders;
string strReply;
ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
class CRPCConvertParam
{
public:
std::string methodName; // method whose params want conversion
int paramIdx; // 0-based idx of param to convert
};
static const CRPCConvertParam vRPCConvertParams[] =
{
{ "stop", 0 },
{ "getaddednodeinfo", 0 },
{ "sendtoaddress", 1 },
{ "settxfee", 0 },
{ "getreceivedbyaddress", 1 },
{ "getreceivedbyaccount", 1 },
{ "listreceivedbyaddress", 0 },
{ "listreceivedbyaddress", 1 },
{ "listreceivedbyaccount", 0 },
{ "listreceivedbyaccount", 1 },
{ "getbalance", 1 },
{ "getblock", 1 },
{ "getblockbynumber", 0 },
{ "getblockbynumber", 1 },
{ "getblockhash", 0 },
{ "move", 2 },
{ "move", 3 },
{ "sendfrom", 2 },
{ "sendfrom", 3 },
{ "listtransactions", 1 },
{ "listtransactions", 2 },
{ "listaccounts", 0 },
{ "walletpassphrase", 1 },
{ "walletpassphrase", 2 },
{ "getblocktemplate", 0 },
{ "listsinceblock", 1 },
{ "sendalert", 2 },
{ "sendalert", 3 },
{ "sendalert", 4 },
{ "sendalert", 5 },
{ "sendalert", 6 },
{ "sendmany", 1 },
{ "sendmany", 2 },
{ "reservebalance", 0 },
{ "reservebalance", 1 },
{ "addmultisigaddress", 0 },
{ "addmultisigaddress", 1 },
{ "listunspent", 0 },
{ "listunspent", 1 },
{ "listunspent", 2 },
{ "getrawtransaction", 1 },
{ "createrawtransaction", 0 },
{ "createrawtransaction", 1 },
{ "signrawtransaction", 1 },
{ "signrawtransaction", 2 },
{ "keypoolrefill", 0 },
{ "importprivkey", 2 },
{ "checkkernel", 0 },
{ "checkkernel", 1 },
{ "submitblock", 1 },
};
class CRPCConvertTable
{
private:
std::set<std::pair<std::string, int> > members;
public:
CRPCConvertTable();
bool convert(const std::string& method, int idx) {
return (members.count(std::make_pair(method, idx)) > 0);
}
};
CRPCConvertTable::CRPCConvertTable()
{
const unsigned int n_elem =
(sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0]));
for (unsigned int i = 0; i < n_elem; i++) {
members.insert(std::make_pair(vRPCConvertParams[i].methodName,
vRPCConvertParams[i].paramIdx));
}
}
static CRPCConvertTable rpcCvtTable;
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
for (unsigned int idx = 0; idx < strParams.size(); idx++) {
const std::string& strVal = strParams[idx];
// insert string value directly
if (!rpcCvtTable.convert(strMethod, idx)) {
params.push_back(strVal);
}
// parse string as JSON, insert bool/number/object/etc. value
else {
Value jVal;
if (!read_string(strVal, jVal))
throw runtime_error(string("Error parsing JSON:")+strVal);
params.push_back(jVal);
}
}
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...) {
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "db.h"
#include "init.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
Value getgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getgenerate\n"
"Returns true or false.");
return GetBoolArg("-gen");
}
Value setgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setgenerate <generate> [genproclimit]\n"
"<generate> is true or false to turn generation on or off.\n"
"Generation is limited to [genproclimit] processors, -1 is unlimited.");
bool fGenerate = true;
if (params.size() > 0)
fGenerate = params[0].get_bool();
if (params.size() > 1)
{
int nGenProcLimit = params[1].get_int();
mapArgs["-genproclimit"] = itostr(nGenProcLimit);
if (nGenProcLimit == 0)
fGenerate = false;
}
mapArgs["-gen"] = (fGenerate ? "1" : "0");
GenerateBitcoins(fGenerate, pwalletMain);
return Value::null;
}
Value gethashespersec(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gethashespersec\n"
"Returns a recent hashes per second performance measurement while generating.");
if (GetTimeMillis() - nHPSTimerStart > 8000)
return (boost::int64_t)0;
return (boost::int64_t)dHashesPerSec;
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
Object obj;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("generate", GetBoolArg("-gen")));
obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("testnet", fTestNet));
return obj;
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlockTemplate*> vNewBlockTemplate;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
delete pblocktemplate;
vNewBlockTemplate.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblocktemplate = CreateNewBlock(reservekey);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlockTemplate.push_back(pblocktemplate);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
static CReserveKey reservekey(pwalletMain);
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblocktemplate)
{
delete pblocktemplate;
pblocktemplate = NULL;
}
pblocktemplate = CreateNewBlock(reservekey);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
Array deps;
BOOST_FOREACH (const CTxIn &in, tx.vin)
{
if (setTxIndex.count(in.prevout.hash))
deps.push_back(setTxIndex[in.prevout.hash]);
}
entry.push_back(Pair("depends", deps));
int index_in_template = &tx - pblock->vtx.data();
entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", HexBits(pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock pblock;
try {
ssBlock >> pblock;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
CValidationState state;
bool fAccepted = ProcessBlock(state, NULL, &pblock);
if (!fAccepted)
return "rejected"; // TODO: report validation state
return Value::null;
}
<commit_msg>Do not use C++11 std::vector.data()<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "db.h"
#include "init.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
Value getgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getgenerate\n"
"Returns true or false.");
return GetBoolArg("-gen");
}
Value setgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setgenerate <generate> [genproclimit]\n"
"<generate> is true or false to turn generation on or off.\n"
"Generation is limited to [genproclimit] processors, -1 is unlimited.");
bool fGenerate = true;
if (params.size() > 0)
fGenerate = params[0].get_bool();
if (params.size() > 1)
{
int nGenProcLimit = params[1].get_int();
mapArgs["-genproclimit"] = itostr(nGenProcLimit);
if (nGenProcLimit == 0)
fGenerate = false;
}
mapArgs["-gen"] = (fGenerate ? "1" : "0");
GenerateBitcoins(fGenerate, pwalletMain);
return Value::null;
}
Value gethashespersec(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gethashespersec\n"
"Returns a recent hashes per second performance measurement while generating.");
if (GetTimeMillis() - nHPSTimerStart > 8000)
return (boost::int64_t)0;
return (boost::int64_t)dHashesPerSec;
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
Object obj;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("generate", GetBoolArg("-gen")));
obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("testnet", fTestNet));
return obj;
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlockTemplate*> vNewBlockTemplate;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
delete pblocktemplate;
vNewBlockTemplate.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblocktemplate = CreateNewBlock(reservekey);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlockTemplate.push_back(pblocktemplate);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
static CReserveKey reservekey(pwalletMain);
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblocktemplate)
{
delete pblocktemplate;
pblocktemplate = NULL;
}
pblocktemplate = CreateNewBlock(reservekey);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
Array deps;
BOOST_FOREACH (const CTxIn &in, tx.vin)
{
if (setTxIndex.count(in.prevout.hash))
deps.push_back(setTxIndex[in.prevout.hash]);
}
entry.push_back(Pair("depends", deps));
int index_in_template = i - 1;
entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", HexBits(pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock pblock;
try {
ssBlock >> pblock;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
CValidationState state;
bool fAccepted = ProcessBlock(state, NULL, &pblock);
if (!fAccepted)
return "rejected"; // TODO: report validation state
return Value::null;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "db.h"
#include "init.h"
#include "miner.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
// Key used by getwork/getblocktemplate miners.
// Allocated in InitRPCMining, free'd in ShutdownRPCMining
static CReserveKey* pMiningKey = NULL;
void InitRPCMining()
{
// getwork/getblocktemplate mining rewards paid here:
pMiningKey = new CReserveKey(pwalletMain);
}
void ShutdownRPCMining()
{
delete pMiningKey; pMiningKey = NULL;
}
Value getgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getgenerate\n"
"Returns true or false.");
return GetBoolArg("-gen", false);
}
Value setgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setgenerate <generate> [genproclimit]\n"
"<generate> is true or false to turn generation on or off.\n"
"Generation is limited to [genproclimit] processors, -1 is unlimited.");
bool fGenerate = true;
if (params.size() > 0)
fGenerate = params[0].get_bool();
if (params.size() > 1)
{
int nGenProcLimit = params[1].get_int();
mapArgs["-genproclimit"] = itostr(nGenProcLimit);
if (nGenProcLimit == 0)
fGenerate = false;
}
mapArgs["-gen"] = (fGenerate ? "1" : "0");
GenerateBitcoins(fGenerate, pwalletMain);
return Value::null;
}
Value gethashespersec(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gethashespersec\n"
"Returns a recent hashes per second performance measurement while generating.");
if (GetTimeMillis() - nHPSTimerStart > 8000)
return (boost::int64_t)0;
return (boost::int64_t)dHashesPerSec;
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
Object obj;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("generate", GetBoolArg("-gen", false)));
obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("testnet", TestNet()));
return obj;
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlockTemplate*> vNewBlockTemplate;
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
delete pblocktemplate;
vNewBlockTemplate.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblocktemplate = CreateNewBlockWithKey(*pMiningKey);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlockTemplate.push_back(pblocktemplate);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
UpdateTime(*pblock, pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, *pMiningKey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblocktemplate)
{
delete pblocktemplate;
pblocktemplate = NULL;
}
pblocktemplate = CreateNewBlockWithKey(*pMiningKey);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
UpdateTime(*pblock, pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
Array deps;
BOOST_FOREACH (const CTxIn &in, tx.vin)
{
if (setTxIndex.count(in.prevout.hash))
deps.push_back(setTxIndex[in.prevout.hash]);
}
entry.push_back(Pair("depends", deps));
int index_in_template = i - 1;
entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", HexBits(pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock pblock;
try {
ssBlock >> pblock;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
CValidationState state;
bool fAccepted = ProcessBlock(state, NULL, &pblock);
if (!fAccepted)
return "rejected"; // TODO: report validation state
return Value::null;
}
<commit_msg>RPC: getblocktemplate does not require a key, to create a block template<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "db.h"
#include "init.h"
#include "miner.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
// Key used by getwork/getblocktemplate miners.
// Allocated in InitRPCMining, free'd in ShutdownRPCMining
static CReserveKey* pMiningKey = NULL;
void InitRPCMining()
{
// getwork/getblocktemplate mining rewards paid here:
pMiningKey = new CReserveKey(pwalletMain);
}
void ShutdownRPCMining()
{
delete pMiningKey; pMiningKey = NULL;
}
Value getgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getgenerate\n"
"Returns true or false.");
return GetBoolArg("-gen", false);
}
Value setgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setgenerate <generate> [genproclimit]\n"
"<generate> is true or false to turn generation on or off.\n"
"Generation is limited to [genproclimit] processors, -1 is unlimited.");
bool fGenerate = true;
if (params.size() > 0)
fGenerate = params[0].get_bool();
if (params.size() > 1)
{
int nGenProcLimit = params[1].get_int();
mapArgs["-genproclimit"] = itostr(nGenProcLimit);
if (nGenProcLimit == 0)
fGenerate = false;
}
mapArgs["-gen"] = (fGenerate ? "1" : "0");
GenerateBitcoins(fGenerate, pwalletMain);
return Value::null;
}
Value gethashespersec(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gethashespersec\n"
"Returns a recent hashes per second performance measurement while generating.");
if (GetTimeMillis() - nHPSTimerStart > 8000)
return (boost::int64_t)0;
return (boost::int64_t)dHashesPerSec;
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
Object obj;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("generate", GetBoolArg("-gen", false)));
obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("testnet", TestNet()));
return obj;
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlockTemplate*> vNewBlockTemplate;
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
delete pblocktemplate;
vNewBlockTemplate.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblocktemplate = CreateNewBlockWithKey(*pMiningKey);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlockTemplate.push_back(pblocktemplate);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
UpdateTime(*pblock, pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, *pMiningKey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblocktemplate)
{
delete pblocktemplate;
pblocktemplate = NULL;
}
CScript scriptDummy = CScript() << OP_TRUE;
pblocktemplate = CreateNewBlock(scriptDummy);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
UpdateTime(*pblock, pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
Array deps;
BOOST_FOREACH (const CTxIn &in, tx.vin)
{
if (setTxIndex.count(in.prevout.hash))
deps.push_back(setTxIndex[in.prevout.hash]);
}
entry.push_back(Pair("depends", deps));
int index_in_template = i - 1;
entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", HexBits(pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock pblock;
try {
ssBlock >> pblock;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
CValidationState state;
bool fAccepted = ProcessBlock(state, NULL, &pblock);
if (!fAccepted)
return "rejected"; // TODO: report validation state
return Value::null;
}
<|endoftext|> |
<commit_before>#include "Mouse.h"
#include <cmath>
#include <iostream>
#include "Constants.h"
#include "Utilities.h"
#include "units/MetersPerSecond.h"
#include "units/Polar.h"
namespace sim {
Mouse::Mouse() : m_translation(Cartesian(0, 0)), m_rotation(Radians(0)),
m_rightWheel(Meters(0.02), Meters(0.025), Cartesian(P()->wallLength() + P()->wallWidth() - 0.06, 0.085)),
m_leftWheel(Meters(0.02), Meters(0.025), Cartesian(0.06, 0.085)) {
// TODO: Read in a mouse file here
// TODO: Validate the contents of the mouse file (like valid mouse starting position)
// TODO: Right now, the size of the mouse is dependent on the size of the maze- we should fix this...
// TODO: SOM
// Create the vertices for the mouse
std::vector<Cartesian> vertices;
vertices.push_back(Cartesian(0.06, 0.06));
vertices.push_back(Cartesian(0.06, P()->wallLength() + P()->wallWidth() - 0.06));
vertices.push_back(Cartesian(P()->wallLength() + P()->wallWidth() - 0.06, P()->wallLength() + P()->wallWidth() - 0.06));
vertices.push_back(Cartesian(P()->wallLength() + P()->wallWidth() - 0.06, 0.06));
m_body.setVertices(vertices);
}
// TODO: Shouldn't need this method
Cartesian Mouse::getTranslation() const {
Cartesian centerOfMass((m_rightWheel.getPosition().getX() + m_leftWheel.getPosition().getX())/2.0, m_rightWheel.getPosition().getY());
Polar vec(centerOfMass.getRho(), m_rotation.getRadians() + centerOfMass.getTheta()); // The current rotation vector
Cartesian disp(vec.getX() - centerOfMass.getX(), vec.getY() - centerOfMass.getY());
return Cartesian(m_translation.getX() - disp.getX(), m_translation.getY() - disp.getY());
}
// TODO: Better interface for polygons
std::vector<Polygon> Mouse::getShapes() const {
// Create the shapes vector
std::vector<Polygon> shapes;
// The mouse body
shapes.push_back(m_body);
// TODO: We really only need to do this logic once
// TODO: This is *really* ugly... fix this...
// Right wheel
std::vector<Cartesian> rightWheelPolygon;
Meters rightWheelHalfWidth = m_rightWheel.getWidth() / 2.0;
Meters rightWheelRadius = m_rightWheel.getRadius();
Cartesian rightWheelPosition = m_rightWheel.getPosition();
rightWheelPolygon.push_back(rightWheelPosition + Cartesian(
(rightWheelHalfWidth * -1).getMeters(), (rightWheelRadius * -1).getMeters()));
rightWheelPolygon.push_back(rightWheelPosition + Cartesian(
(rightWheelHalfWidth * -1).getMeters(), (rightWheelRadius * 1).getMeters()));
rightWheelPolygon.push_back(rightWheelPosition + Cartesian(
(rightWheelHalfWidth * 1).getMeters(), (rightWheelRadius * 1).getMeters()));
rightWheelPolygon.push_back(rightWheelPosition + Cartesian(
(rightWheelHalfWidth * 1).getMeters(), (rightWheelRadius * -1).getMeters()));
Polygon rightPoly;
rightPoly.setVertices(rightWheelPolygon);
shapes.push_back(rightPoly);
// Left wheel
std::vector<Cartesian> leftWheelPolygon;
Meters leftWheelHalfWidth = m_leftWheel.getWidth() / 2.0;
Meters leftWheelRadius = m_leftWheel.getRadius();
Cartesian leftWheelPosition = m_leftWheel.getPosition();
leftWheelPolygon.push_back(leftWheelPosition + Cartesian(
(leftWheelHalfWidth * -1).getMeters(), (leftWheelRadius * -1).getMeters()));
leftWheelPolygon.push_back(leftWheelPosition + Cartesian(
(leftWheelHalfWidth * -1).getMeters(), (leftWheelRadius * 1).getMeters()));
leftWheelPolygon.push_back(leftWheelPosition + Cartesian(
(leftWheelHalfWidth * 1).getMeters(), (leftWheelRadius * 1).getMeters()));
leftWheelPolygon.push_back(leftWheelPosition + Cartesian(
(leftWheelHalfWidth * 1).getMeters(), (leftWheelRadius * -1).getMeters()));
Polygon leftPoly;
leftPoly.setVertices(leftWheelPolygon);
shapes.push_back(leftPoly);
// TODO : Clear this
std::vector<Polygon> adjustedShapes;
for (int i = 0; i < shapes.size(); i += 1) {
adjustedShapes.push_back(shapes.at(i).rotate(m_rotation).translate(getTranslation()));
}
return adjustedShapes;
}
void Mouse::update(const Time& elapsed) {
// The "elapsed" argument signifies how much time has passed since our last update. Thus
// we should adjust the mouses position so that it's where it would be after moving for
// the "elapsed" duration.
// TODO: Document this...
// Left wheel
MetersPerSecond dtl(m_leftWheel.getAngularVelocity().getRadiansPerSecond() * m_leftWheel.getRadius().getMeters());
// Right wheel
MetersPerSecond dtr(m_rightWheel.getAngularVelocity().getRadiansPerSecond() * m_rightWheel.getRadius().getMeters());
float BASELINE(m_rightWheel.getPosition().getX() - m_leftWheel.getPosition().getX());
Radians theta((dtr.getMetersPerSecond() - (-dtl.getMetersPerSecond())) / BASELINE * elapsed.getSeconds());
m_rotation = m_rotation + theta;
/*
Cartesian WHEEL_CENTER(BASELINE, m_rightWheel.getPosition().getY());
Polar vec(WHEEL_CENTER.getRho(), m_rotation.getRadians() + WHEEL_CENTER.getTheta()); // The current displacement vector
Cartesian disp(vec.getX() - WHEEL_CENTER.getX(), vec.getY() - WHEEL_CENTER.getY());
*/
// TODO: Direction...
Meters distance((-0.5 * dtl.getMetersPerSecond() + 0.5 * dtr.getMetersPerSecond()) * elapsed.getSeconds());
m_translation = m_translation + Polar(distance.getMeters(), M_PI / 2.0 + m_rotation.getRadians()); // TODO
//m_translation = Cartesian(m_translation.getX() + disp.getX(), m_translation.getY() + disp.getY());
}
// TODO... better interface
Wheel* Mouse::getRightWheel() {
return &m_rightWheel;
}
Wheel* Mouse::getLeftWheel() {
return &m_leftWheel;
}
/*
void Mouse::stepBoth() {
m_leftWheel.rotate(Radians(M_PI/100.0));
m_rightWheel.rotate(Radians(M_PI/100.0));
}
void Mouse::update() {
Radians leftRotation = m_leftWheel.popRotation();
Radians rightRotation = m_rightWheel.popRotation();
}
*/
} // namespace sim
<commit_msg>Got the "correct" implementation of mouse movement, but no improvement over easy method<commit_after>#include "Mouse.h"
#include <cmath>
#include <iostream>
#include "Constants.h"
#include "Utilities.h"
#include "units/MetersPerSecond.h"
#include "units/Polar.h"
namespace sim {
Mouse::Mouse() : m_translation(Cartesian(0, 0)), m_rotation(Radians(0)),
m_rightWheel(Meters(0.02), Meters(0.025), Cartesian(P()->wallLength() + P()->wallWidth() - 0.06, 0.085)),
m_leftWheel(Meters(0.02), Meters(0.025), Cartesian(0.06, 0.085)) {
// TODO: Read in a mouse file here
// TODO: Validate the contents of the mouse file (like valid mouse starting position)
// TODO: Right now, the size of the mouse is dependent on the size of the maze- we should fix this...
// TODO: SOM
// Create the vertices for the mouse
std::vector<Cartesian> vertices;
vertices.push_back(Cartesian(0.06, 0.06));
vertices.push_back(Cartesian(0.06, P()->wallLength() + P()->wallWidth() - 0.06));
vertices.push_back(Cartesian(P()->wallLength() + P()->wallWidth() - 0.06, P()->wallLength() + P()->wallWidth() - 0.06));
vertices.push_back(Cartesian(P()->wallLength() + P()->wallWidth() - 0.06, 0.06));
m_body.setVertices(vertices);
}
// TODO: Shouldn't need this method
Cartesian Mouse::getTranslation() const {
Cartesian centerOfMass((m_rightWheel.getPosition().getX() + m_leftWheel.getPosition().getX())/2.0, m_rightWheel.getPosition().getY());
Polar vec(centerOfMass.getRho(), m_rotation.getRadians() + centerOfMass.getTheta()); // The current rotation vector
Cartesian disp(vec.getX() - centerOfMass.getX(), vec.getY() - centerOfMass.getY());
return Cartesian(m_translation.getX() - disp.getX(), m_translation.getY() - disp.getY());
}
// TODO: Better interface for polygons
std::vector<Polygon> Mouse::getShapes() const {
// Create the shapes vector
std::vector<Polygon> shapes;
// The mouse body
shapes.push_back(m_body);
// TODO: We really only need to do this logic once
// TODO: This is *really* ugly... fix this...
// Right wheel
std::vector<Cartesian> rightWheelPolygon;
Meters rightWheelHalfWidth = m_rightWheel.getWidth() / 2.0;
Meters rightWheelRadius = m_rightWheel.getRadius();
Cartesian rightWheelPosition = m_rightWheel.getPosition();
rightWheelPolygon.push_back(rightWheelPosition + Cartesian(
(rightWheelHalfWidth * -1).getMeters(), (rightWheelRadius * -1).getMeters()));
rightWheelPolygon.push_back(rightWheelPosition + Cartesian(
(rightWheelHalfWidth * -1).getMeters(), (rightWheelRadius * 1).getMeters()));
rightWheelPolygon.push_back(rightWheelPosition + Cartesian(
(rightWheelHalfWidth * 1).getMeters(), (rightWheelRadius * 1).getMeters()));
rightWheelPolygon.push_back(rightWheelPosition + Cartesian(
(rightWheelHalfWidth * 1).getMeters(), (rightWheelRadius * -1).getMeters()));
Polygon rightPoly;
rightPoly.setVertices(rightWheelPolygon);
shapes.push_back(rightPoly);
// Left wheel
std::vector<Cartesian> leftWheelPolygon;
Meters leftWheelHalfWidth = m_leftWheel.getWidth() / 2.0;
Meters leftWheelRadius = m_leftWheel.getRadius();
Cartesian leftWheelPosition = m_leftWheel.getPosition();
leftWheelPolygon.push_back(leftWheelPosition + Cartesian(
(leftWheelHalfWidth * -1).getMeters(), (leftWheelRadius * -1).getMeters()));
leftWheelPolygon.push_back(leftWheelPosition + Cartesian(
(leftWheelHalfWidth * -1).getMeters(), (leftWheelRadius * 1).getMeters()));
leftWheelPolygon.push_back(leftWheelPosition + Cartesian(
(leftWheelHalfWidth * 1).getMeters(), (leftWheelRadius * 1).getMeters()));
leftWheelPolygon.push_back(leftWheelPosition + Cartesian(
(leftWheelHalfWidth * 1).getMeters(), (leftWheelRadius * -1).getMeters()));
Polygon leftPoly;
leftPoly.setVertices(leftWheelPolygon);
shapes.push_back(leftPoly);
// TODO : Clear this
std::vector<Polygon> adjustedShapes;
for (int i = 0; i < shapes.size(); i += 1) {
adjustedShapes.push_back(shapes.at(i).rotate(m_rotation).translate(getTranslation()));
}
return adjustedShapes;
}
void Mouse::update(const Time& elapsed) {
// The "elapsed" argument signifies how much time has passed since our last update. Thus
// we should adjust the mouses position so that it's where it would be after moving for
// the "elapsed" duration.
// TODO: Document this more...
// Left wheel
MetersPerSecond dtl(m_leftWheel.getAngularVelocity().getRadiansPerSecond() * m_leftWheel.getRadius().getMeters());
// Right wheel
MetersPerSecond dtr(m_rightWheel.getAngularVelocity().getRadiansPerSecond() * m_rightWheel.getRadius().getMeters());
// TODO: SOM
// TODO: There's a better closed form equation for x,y position. Right now, we're under the assumption that
// the elapsed time is small, so that the rotation doesn't change too much. But as we're moving, our rotation
// changes and thus our direction changes, so this will affect trajectory.
// See http://rossum.sourceforge.net/papers/DiffSteer/ for derivation of the kinematic equations and more
// information about the more accurate closed form solution
// Instantaneous change in x,y is only valid for one instant (not the whole duration) so we need a better formula
float BASELINE(m_rightWheel.getPosition().getX() - m_leftWheel.getPosition().getX());
if (fabs((dtr+dtl).getMetersPerSecond()) < 1) { // TODO
Meters distance((-0.5 * dtl.getMetersPerSecond() + 0.5 * dtr.getMetersPerSecond()) * elapsed.getSeconds());
m_translation = m_translation + Polar(distance.getMeters(), M_PI / 2.0 + m_rotation.getRadians()); // TODO
static int i = 0;
//std::cout << i++ << std::endl;
}
else {
dtl = MetersPerSecond(-1*dtl.getMetersPerSecond());
// TODO
float x_0 = m_translation.getY();
float y_0 = -1*m_translation.getX();
float x = x_0 +
(BASELINE*(dtr+dtl).getMetersPerSecond())
/(2.0*(dtr-dtl).getMetersPerSecond())
*(sin((dtr-dtl).getMetersPerSecond() * elapsed.getSeconds() / BASELINE + m_rotation.getRadians())
-sin(m_rotation.getRadians()));
float y = y_0 -
(BASELINE*(dtr+dtl).getMetersPerSecond())
/(2.0*(dtr-dtl).getMetersPerSecond())
*(cos((dtr-dtl).getMetersPerSecond() * elapsed.getSeconds() / BASELINE + m_rotation.getRadians())
-cos(m_rotation.getRadians()));
m_translation = Cartesian(-y, x);
dtl = MetersPerSecond(-1*dtl.getMetersPerSecond());
}
// TODO: This is correct
Radians theta((dtr.getMetersPerSecond() - (-dtl.getMetersPerSecond())) / BASELINE * elapsed.getSeconds());
m_rotation = m_rotation + theta;
}
// TODO... better interface
Wheel* Mouse::getRightWheel() {
return &m_rightWheel;
}
Wheel* Mouse::getLeftWheel() {
return &m_leftWheel;
}
/*
void Mouse::stepBoth() {
m_leftWheel.rotate(Radians(M_PI/100.0));
m_rightWheel.rotate(Radians(M_PI/100.0));
}
void Mouse::update() {
Radians leftRotation = m_leftWheel.popRotation();
Radians rightRotation = m_rightWheel.popRotation();
}
*/
} // namespace sim
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2000-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Nathan Binkert
*/
/* @file
* EventQueue interfaces
*/
#ifndef __SIM_EVENTQ_HH__
#define __SIM_EVENTQ_HH__
#include <assert.h>
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#include "sim/host.hh" // for Tick
#include "base/fast_alloc.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "sim/serialize.hh"
class EventQueue; // forward declaration
//////////////////////
//
// Main Event Queue
//
// Events on this queue are processed at the *beginning* of each
// cycle, before the pipeline simulation is performed.
//
// defined in eventq.cc
//
//////////////////////
extern EventQueue mainEventQueue;
/*
* An item on an event queue. The action caused by a given
* event is specified by deriving a subclass and overriding the
* process() member function.
*/
class Event : public Serializable, public FastAlloc
{
friend class EventQueue;
private:
/// queue to which this event belongs (though it may or may not be
/// scheduled on this queue yet)
EventQueue *queue;
Event *next;
Tick _when; //!< timestamp when event should be processed
int _priority; //!< event priority
char _flags;
protected:
enum Flags {
None = 0x0,
Squashed = 0x1,
Scheduled = 0x2,
AutoDelete = 0x4,
AutoSerialize = 0x8,
IsExitEvent = 0x10
};
bool getFlags(Flags f) const { return (_flags & f) == f; }
void setFlags(Flags f) { _flags |= f; }
void clearFlags(Flags f) { _flags &= ~f; }
protected:
EventQueue *theQueue() const { return queue; }
#if TRACING_ON
Tick when_created; //!< Keep track of creation time For debugging
Tick when_scheduled; //!< Keep track of creation time For debugging
virtual void trace(const char *action); //!< trace event activity
#else
void trace(const char *) {}
#endif
unsigned annotated_value;
public:
/// Event priorities, to provide tie-breakers for events scheduled
/// at the same cycle. Most events are scheduled at the default
/// priority; these values are used to control events that need to
/// be ordered within a cycle.
enum Priority {
/// Breakpoints should happen before anything else, so we
/// don't miss any action when debugging.
Debug_Break_Pri = -100,
/// For some reason "delayed" inter-cluster writebacks are
/// scheduled before regular writebacks (which have default
/// priority). Steve?
Delayed_Writeback_Pri = -1,
/// Default is zero for historical reasons.
Default_Pri = 0,
/// CPU switches schedule the new CPU's tick event for the
/// same cycle (after unscheduling the old CPU's tick event).
/// The switch needs to come before any tick events to make
/// sure we don't tick both CPUs in the same cycle.
CPU_Switch_Pri = -31,
/// Serailization needs to occur before tick events also, so
/// that a serialize/unserialize is identical to an on-line
/// CPU switch.
Serialize_Pri = 32,
/// CPU ticks must come after other associated CPU events
/// (such as writebacks).
CPU_Tick_Pri = 50,
/// Statistics events (dump, reset, etc.) come after
/// everything else, but before exit.
Stat_Event_Pri = 90,
/// If we want to exit on this cycle, it's the very last thing
/// we do.
Sim_Exit_Pri = 100
};
/*
* Event constructor
* @param queue that the event gets scheduled on
*/
Event(EventQueue *q, Priority p = Default_Pri)
: queue(q), next(NULL), _priority(p), _flags(None),
#if TRACING_ON
when_created(curTick), when_scheduled(0),
#endif
annotated_value(0)
{
}
~Event() {}
virtual const std::string name() const {
return csprintf("Event_%x", (uintptr_t)this);
}
/// Determine if the current event is scheduled
bool scheduled() const { return getFlags(Scheduled); }
/// Schedule the event with the current priority or default priority
void schedule(Tick t);
/// Reschedule the event with the current priority
void reschedule(Tick t);
/// Remove the event from the current schedule
void deschedule();
/// Return a C string describing the event. This string should
/// *not* be dynamically allocated; just a const char array
/// describing the event class.
virtual const char *description();
/// Dump the current event data
void dump();
/*
* This member function is invoked when the event is processed
* (occurs). There is no default implementation; each subclass
* must provide its own implementation. The event is not
* automatically deleted after it is processed (to allow for
* statically allocated event objects).
*
* If the AutoDestroy flag is set, the object is deleted once it
* is processed.
*/
virtual void process() = 0;
void annotate(unsigned value) { annotated_value = value; };
unsigned annotation() { return annotated_value; }
/// Squash the current event
void squash() { setFlags(Squashed); }
/// Check whether the event is squashed
bool squashed() { return getFlags(Squashed); }
/// See if this is a SimExitEvent (without resorting to RTTI)
bool isExitEvent() { return getFlags(IsExitEvent); }
/// Get the time that the event is scheduled
Tick when() const { return _when; }
/// Get the event priority
int priority() const { return _priority; }
struct priority_compare :
public std::binary_function<Event *, Event *, bool>
{
bool operator()(const Event *l, const Event *r) const {
return l->when() >= r->when() || l->priority() >= r->priority();
}
};
virtual void serialize(std::ostream &os);
virtual void unserialize(Checkpoint *cp, const std::string §ion);
};
template <class T, void (T::* F)()>
void
DelayFunction(Tick when, T *object)
{
class DelayEvent : public Event
{
private:
T *object;
public:
DelayEvent(Tick when, T *o)
: Event(&mainEventQueue), object(o)
{ setFlags(this->AutoDestroy); schedule(when); }
void process() { (object->*F)(); }
const char *description() { return "delay"; }
};
new DelayEvent(when, object);
}
template <class T, void (T::* F)()>
class EventWrapper : public Event
{
private:
T *object;
public:
EventWrapper(T *obj, bool del = false, EventQueue *q = &mainEventQueue,
Priority p = Default_Pri)
: Event(q, p), object(obj)
{
if (del)
setFlags(AutoDelete);
}
void process() { (object->*F)(); }
};
/*
* Queue of events sorted in time order
*/
class EventQueue : public Serializable
{
protected:
std::string objName;
private:
Event *head;
void insert(Event *event);
void remove(Event *event);
public:
// constructor
EventQueue(const std::string &n)
: objName(n), head(NULL)
{}
virtual const std::string name() const { return objName; }
// schedule the given event on this queue
void schedule(Event *ev);
void deschedule(Event *ev);
void reschedule(Event *ev);
Tick nextTick() { return head->when(); }
Event *serviceOne();
// process all events up to the given timestamp. we inline a
// quick test to see if there are any events to process; if so,
// call the internal out-of-line version to process them all.
void serviceEvents(Tick when) {
while (!empty()) {
if (nextTick() > when)
break;
/**
* @todo this assert is a good bug catcher. I need to
* make it true again.
*/
//assert(head->when() >= when && "event scheduled in the past");
serviceOne();
}
}
// default: process all events up to 'now' (curTick)
void serviceEvents() { serviceEvents(curTick); }
// return true if no events are queued
bool empty() { return head == NULL; }
void dump();
Tick nextEventTime() { return empty() ? curTick : head->when(); }
virtual void serialize(std::ostream &os);
virtual void unserialize(Checkpoint *cp, const std::string §ion);
};
//////////////////////
//
// inline functions
//
// can't put these inside declaration due to circular dependence
// between Event and EventQueue classes.
//
//////////////////////
// schedule at specified time (place on event queue specified via
// constructor)
inline void
Event::schedule(Tick t)
{
assert(!scheduled());
// if (t < curTick)
// warn("t is less than curTick, ensure you don't want cycles");
setFlags(Scheduled);
#if TRACING_ON
when_scheduled = curTick;
#endif
_when = t;
queue->schedule(this);
}
inline void
Event::deschedule()
{
assert(scheduled());
clearFlags(Squashed);
clearFlags(Scheduled);
queue->deschedule(this);
}
inline void
Event::reschedule(Tick t)
{
assert(scheduled());
clearFlags(Squashed);
#if TRACING_ON
when_scheduled = curTick;
#endif
_when = t;
queue->reschedule(this);
}
inline void
EventQueue::schedule(Event *event)
{
insert(event);
if (DTRACE(Event))
event->trace("scheduled");
}
inline void
EventQueue::deschedule(Event *event)
{
remove(event);
if (DTRACE(Event))
event->trace("descheduled");
}
inline void
EventQueue::reschedule(Event *event)
{
remove(event);
insert(event);
if (DTRACE(Event))
event->trace("rescheduled");
}
#endif // __SIM_EVENTQ_HH__
<commit_msg>Add new event priority for trace enable events so that tracing gets turned on as the very first thing in the selected cycle (tick).<commit_after>/*
* Copyright (c) 2000-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Nathan Binkert
*/
/* @file
* EventQueue interfaces
*/
#ifndef __SIM_EVENTQ_HH__
#define __SIM_EVENTQ_HH__
#include <assert.h>
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#include "sim/host.hh" // for Tick
#include "base/fast_alloc.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "sim/serialize.hh"
class EventQueue; // forward declaration
//////////////////////
//
// Main Event Queue
//
// Events on this queue are processed at the *beginning* of each
// cycle, before the pipeline simulation is performed.
//
// defined in eventq.cc
//
//////////////////////
extern EventQueue mainEventQueue;
/*
* An item on an event queue. The action caused by a given
* event is specified by deriving a subclass and overriding the
* process() member function.
*/
class Event : public Serializable, public FastAlloc
{
friend class EventQueue;
private:
/// queue to which this event belongs (though it may or may not be
/// scheduled on this queue yet)
EventQueue *queue;
Event *next;
Tick _when; //!< timestamp when event should be processed
int _priority; //!< event priority
char _flags;
protected:
enum Flags {
None = 0x0,
Squashed = 0x1,
Scheduled = 0x2,
AutoDelete = 0x4,
AutoSerialize = 0x8,
IsExitEvent = 0x10
};
bool getFlags(Flags f) const { return (_flags & f) == f; }
void setFlags(Flags f) { _flags |= f; }
void clearFlags(Flags f) { _flags &= ~f; }
protected:
EventQueue *theQueue() const { return queue; }
#if TRACING_ON
Tick when_created; //!< Keep track of creation time For debugging
Tick when_scheduled; //!< Keep track of creation time For debugging
virtual void trace(const char *action); //!< trace event activity
#else
void trace(const char *) {}
#endif
unsigned annotated_value;
public:
/// Event priorities, to provide tie-breakers for events scheduled
/// at the same cycle. Most events are scheduled at the default
/// priority; these values are used to control events that need to
/// be ordered within a cycle.
enum Priority {
/// If we enable tracing on a particular cycle, do that as the
/// very first thing so we don't miss any of the events on
/// that cycle (even if we enter the debugger).
Trace_Enable_Pri = -101,
/// Breakpoints should happen before anything else (except
/// enabling trace output), so we don't miss any action when
/// debugging.
Debug_Break_Pri = -100,
/// CPU switches schedule the new CPU's tick event for the
/// same cycle (after unscheduling the old CPU's tick event).
/// The switch needs to come before any tick events to make
/// sure we don't tick both CPUs in the same cycle.
CPU_Switch_Pri = -31,
/// For some reason "delayed" inter-cluster writebacks are
/// scheduled before regular writebacks (which have default
/// priority). Steve?
Delayed_Writeback_Pri = -1,
/// Default is zero for historical reasons.
Default_Pri = 0,
/// Serailization needs to occur before tick events also, so
/// that a serialize/unserialize is identical to an on-line
/// CPU switch.
Serialize_Pri = 32,
/// CPU ticks must come after other associated CPU events
/// (such as writebacks).
CPU_Tick_Pri = 50,
/// Statistics events (dump, reset, etc.) come after
/// everything else, but before exit.
Stat_Event_Pri = 90,
/// If we want to exit on this cycle, it's the very last thing
/// we do.
Sim_Exit_Pri = 100
};
/*
* Event constructor
* @param queue that the event gets scheduled on
*/
Event(EventQueue *q, Priority p = Default_Pri)
: queue(q), next(NULL), _priority(p), _flags(None),
#if TRACING_ON
when_created(curTick), when_scheduled(0),
#endif
annotated_value(0)
{
}
~Event() {}
virtual const std::string name() const {
return csprintf("Event_%x", (uintptr_t)this);
}
/// Determine if the current event is scheduled
bool scheduled() const { return getFlags(Scheduled); }
/// Schedule the event with the current priority or default priority
void schedule(Tick t);
/// Reschedule the event with the current priority
void reschedule(Tick t);
/// Remove the event from the current schedule
void deschedule();
/// Return a C string describing the event. This string should
/// *not* be dynamically allocated; just a const char array
/// describing the event class.
virtual const char *description();
/// Dump the current event data
void dump();
/*
* This member function is invoked when the event is processed
* (occurs). There is no default implementation; each subclass
* must provide its own implementation. The event is not
* automatically deleted after it is processed (to allow for
* statically allocated event objects).
*
* If the AutoDestroy flag is set, the object is deleted once it
* is processed.
*/
virtual void process() = 0;
void annotate(unsigned value) { annotated_value = value; };
unsigned annotation() { return annotated_value; }
/// Squash the current event
void squash() { setFlags(Squashed); }
/// Check whether the event is squashed
bool squashed() { return getFlags(Squashed); }
/// See if this is a SimExitEvent (without resorting to RTTI)
bool isExitEvent() { return getFlags(IsExitEvent); }
/// Get the time that the event is scheduled
Tick when() const { return _when; }
/// Get the event priority
int priority() const { return _priority; }
struct priority_compare :
public std::binary_function<Event *, Event *, bool>
{
bool operator()(const Event *l, const Event *r) const {
return l->when() >= r->when() || l->priority() >= r->priority();
}
};
virtual void serialize(std::ostream &os);
virtual void unserialize(Checkpoint *cp, const std::string §ion);
};
template <class T, void (T::* F)()>
void
DelayFunction(Tick when, T *object)
{
class DelayEvent : public Event
{
private:
T *object;
public:
DelayEvent(Tick when, T *o)
: Event(&mainEventQueue), object(o)
{ setFlags(this->AutoDestroy); schedule(when); }
void process() { (object->*F)(); }
const char *description() { return "delay"; }
};
new DelayEvent(when, object);
}
template <class T, void (T::* F)()>
class EventWrapper : public Event
{
private:
T *object;
public:
EventWrapper(T *obj, bool del = false, EventQueue *q = &mainEventQueue,
Priority p = Default_Pri)
: Event(q, p), object(obj)
{
if (del)
setFlags(AutoDelete);
}
void process() { (object->*F)(); }
};
/*
* Queue of events sorted in time order
*/
class EventQueue : public Serializable
{
protected:
std::string objName;
private:
Event *head;
void insert(Event *event);
void remove(Event *event);
public:
// constructor
EventQueue(const std::string &n)
: objName(n), head(NULL)
{}
virtual const std::string name() const { return objName; }
// schedule the given event on this queue
void schedule(Event *ev);
void deschedule(Event *ev);
void reschedule(Event *ev);
Tick nextTick() { return head->when(); }
Event *serviceOne();
// process all events up to the given timestamp. we inline a
// quick test to see if there are any events to process; if so,
// call the internal out-of-line version to process them all.
void serviceEvents(Tick when) {
while (!empty()) {
if (nextTick() > when)
break;
/**
* @todo this assert is a good bug catcher. I need to
* make it true again.
*/
//assert(head->when() >= when && "event scheduled in the past");
serviceOne();
}
}
// default: process all events up to 'now' (curTick)
void serviceEvents() { serviceEvents(curTick); }
// return true if no events are queued
bool empty() { return head == NULL; }
void dump();
Tick nextEventTime() { return empty() ? curTick : head->when(); }
virtual void serialize(std::ostream &os);
virtual void unserialize(Checkpoint *cp, const std::string §ion);
};
//////////////////////
//
// inline functions
//
// can't put these inside declaration due to circular dependence
// between Event and EventQueue classes.
//
//////////////////////
// schedule at specified time (place on event queue specified via
// constructor)
inline void
Event::schedule(Tick t)
{
assert(!scheduled());
// if (t < curTick)
// warn("t is less than curTick, ensure you don't want cycles");
setFlags(Scheduled);
#if TRACING_ON
when_scheduled = curTick;
#endif
_when = t;
queue->schedule(this);
}
inline void
Event::deschedule()
{
assert(scheduled());
clearFlags(Squashed);
clearFlags(Scheduled);
queue->deschedule(this);
}
inline void
Event::reschedule(Tick t)
{
assert(scheduled());
clearFlags(Squashed);
#if TRACING_ON
when_scheduled = curTick;
#endif
_when = t;
queue->reschedule(this);
}
inline void
EventQueue::schedule(Event *event)
{
insert(event);
if (DTRACE(Event))
event->trace("scheduled");
}
inline void
EventQueue::deschedule(Event *event)
{
remove(event);
if (DTRACE(Event))
event->trace("descheduled");
}
inline void
EventQueue::reschedule(Event *event)
{
remove(event);
insert(event);
if (DTRACE(Event))
event->trace("rescheduled");
}
#endif // __SIM_EVENTQ_HH__
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nathan Binkert
* Gabe Black
*/
#include "arch/isa_traits.hh"
#include "base/misc.hh"
#include "cpu/thread_context.hh"
#include "cpu/base.hh"
#include "sim/faults.hh"
#include "sim/process.hh"
#include "mem/page_table.hh"
#if !FULL_SYSTEM
void FaultBase::invoke(ThreadContext * tc)
{
fatal("fault (%s) detected @ PC %p", name(), tc->readPC());
}
#else
void FaultBase::invoke(ThreadContext * tc)
{
DPRINTF(Fault, "Fault %s at PC: %#x\n", name(), tc->readPC());
tc->getCpuPtr()->recordEvent(csprintf("Fault %s", name()));
assert(!tc->misspeculating());
}
#endif
void UnimpFault::invoke(ThreadContext * tc)
{
panic("Unimpfault: %s\n", panicStr.c_str());
}
void PageTableFault::invoke(ThreadContext *tc)
{
Process *p = tc->getProcessPtr();
// We've accessed the next page of the stack, so extend the stack
// to cover it.
if(vaddr < p->stack_min && vaddr >= p->stack_min - TheISA::PageBytes)
{
p->stack_min -= TheISA::PageBytes;
if(p->stack_base - p->stack_min > 8*1024*1024)
fatal("Over max stack size for one thread\n");
p->pTable->allocate(p->stack_min, TheISA::PageBytes);
warn("Increasing stack size by one page.");
}
// Otherwise, we have an unexpected page fault. Report that fact,
// and what address was accessed to cause the fault.
else
{
panic("Page table fault when accessing virtual address %#x\n", vaddr);
}
}
<commit_msg>fix compiling of FS after Gabe's last compile<commit_after>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nathan Binkert
* Gabe Black
*/
#include "arch/isa_traits.hh"
#include "base/misc.hh"
#include "cpu/thread_context.hh"
#include "cpu/base.hh"
#include "sim/faults.hh"
#include "sim/process.hh"
#include "mem/page_table.hh"
#if !FULL_SYSTEM
void FaultBase::invoke(ThreadContext * tc)
{
fatal("fault (%s) detected @ PC %p", name(), tc->readPC());
}
#else
void FaultBase::invoke(ThreadContext * tc)
{
DPRINTF(Fault, "Fault %s at PC: %#x\n", name(), tc->readPC());
tc->getCpuPtr()->recordEvent(csprintf("Fault %s", name()));
assert(!tc->misspeculating());
}
#endif
void UnimpFault::invoke(ThreadContext * tc)
{
panic("Unimpfault: %s\n", panicStr.c_str());
}
#if !FULL_SYSTEM
void PageTableFault::invoke(ThreadContext *tc)
{
Process *p = tc->getProcessPtr();
// We've accessed the next page of the stack, so extend the stack
// to cover it.
if(vaddr < p->stack_min && vaddr >= p->stack_min - TheISA::PageBytes)
{
p->stack_min -= TheISA::PageBytes;
if(p->stack_base - p->stack_min > 8*1024*1024)
fatal("Over max stack size for one thread\n");
p->pTable->allocate(p->stack_min, TheISA::PageBytes);
warn("Increasing stack size by one page.");
}
// Otherwise, we have an unexpected page fault. Report that fact,
// and what address was accessed to cause the fault.
else
{
panic("Page table fault when accessing virtual address %#x\n", vaddr);
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef NFA_HXX
#define NFA_HXX
#include <string>
#include <set>
#include <map>
#include <utility>
typedef std::string StateT;
typedef std::string LetterT;
typedef std::set<StateT > SetOfStatesT;
typedef std::map<LetterT, SetOfStatesT > StateDeltaT;
typedef std::map<StateT, StateDeltaT > DeltaMappingT;
struct NFA {
std::string name;
StateT start;
SetOfStatesT final;
DeltaMappingT delta;
};
/*
Pomocne typy urcene prevazne pro pouziti v parseru.
*/
typedef std::pair<StateT, StateDeltaT > StateAndDeltaPairT;
typedef std::pair<LetterT, SetOfStatesT > LetterAndSetOfStatesPairT;
#endif
<commit_msg>Novy typ struct NFA_conv. Obsahuje automat po prevedeni z NFA, jednotlive Novy typ struct NFA_conv. Obsahuje automat po prevedeni z NFA, jednotlive stavy jsou tvoreny mnozinami stavu puvodniho automatu.<commit_after>#ifndef NFA_HXX
#define NFA_HXX
#include <string>
#include <set>
#include <map>
#include <utility>
#include <iostream>
typedef std::string StateT;
typedef std::string LetterT;
typedef std::set<StateT > SetOfStatesT;
typedef std::map<LetterT, SetOfStatesT > StateDeltaT;
typedef std::map<StateT, StateDeltaT > DeltaMappingT;
struct NFA {
std::string name;
StateT initial;
SetOfStatesT final;
DeltaMappingT delta;
};
struct NFA_conv {
std::string name;
SetOfStatesT initial;
std::set<SetOfStatesT > final;
std::map<SetOfStatesT, StateDeltaT > delta;
};
/*
Pomocne typy urcene prevazne pro pouziti v parseru.
*/
typedef std::pair<StateT, StateDeltaT > StateAndDeltaPairT;
typedef std::pair<LetterT, SetOfStatesT > LetterAndSetOfStatesPairT;
#endif
<|endoftext|> |
<commit_before>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* 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 "aa.hpp"
#include "temporal.hpp"
#include "fxaa.hpp"
#include "smaa.hpp"
#include <string.h>
namespace Granite
{
constexpr bool upscale_linear = false;
constexpr bool allow_external_upscale = true;
constexpr bool allow_external_sharpen = true;
bool setup_after_post_chain_upscaling(RenderGraph &graph, const std::string &input, const std::string &output)
{
auto &upscale = graph.add_pass(output + "-scale", RenderGraph::get_default_post_graphics_queue());
AttachmentInfo upscale_info;
auto *fs = GRANITE_FILESYSTEM();
FileStat s;
bool use_custom = allow_external_upscale &&
fs->stat("assets://shaders/upscale.vert", s) && s.type == PathType::File &&
fs->stat("assets://shaders/upscale.frag", s) && s.type == PathType::File;
bool use_sharpen = allow_external_sharpen &&
fs->stat("assets://shaders/sharpen.vert", s) && s.type == PathType::File &&
fs->stat("assets://shaders/sharpen.frag", s) && s.type == PathType::File;
upscale_info.supports_prerotate = !use_custom;
if (use_sharpen)
{
upscale_info.format = VK_FORMAT_R8G8B8A8_UNORM;
upscale_info.unorm_srgb_alias = true;
}
auto &upscale_tex_out = upscale.add_color_output(!use_sharpen ? output : (output + "-scale"), upscale_info);
if (!upscale_linear)
graph.get_texture_resource(input).get_attachment_info().unorm_srgb_alias = true;
auto &tex = upscale.add_texture_input(input);
upscale.set_build_render_pass([&, use_custom](Vulkan::CommandBuffer &cmd) {
auto &view = graph.get_physical_texture_resource(tex);
if (upscale_linear)
cmd.set_texture(0, 0, view);
else
cmd.set_unorm_texture(0, 0, view);
cmd.set_sampler(0, 0, Vulkan::StockSampler::NearestClamp);
auto *params = cmd.allocate_typed_constant_data<vec4>(1, 0, 2);
auto width = float(view.get_image().get_width());
auto height = float(view.get_image().get_height());
params[0] = vec4(width, height, 1.0f / width, 1.0f / height);
width = cmd.get_viewport().width;
height = cmd.get_viewport().height;
params[1] = vec4(width, height, 1.0f / width, 1.0f / height);
bool srgb = !upscale_linear && Vulkan::format_is_srgb(graph.get_physical_texture_resource(upscale_tex_out).get_format());
const char *vert = use_custom ? "assets://shaders/upscale.vert" : "builtin://shaders/quad.vert";
const char *frag = use_custom ? "assets://shaders/upscale.frag" : "builtin://shaders/post/lanczos2.frag";
Vulkan::CommandBufferUtil::draw_fullscreen_quad(cmd, vert, frag,
{{ "TARGET_SRGB", srgb ? 1 : 0 }});
});
if (use_sharpen)
{
AttachmentInfo sharpen_info;
sharpen_info.supports_prerotate = !use_custom;
auto &sharpen = graph.add_pass(output + "-sharpen", RenderGraph::get_default_post_graphics_queue());
auto &sharpen_tex_out = sharpen.add_color_output(output, sharpen_info);
auto &upscale_tex = sharpen.add_texture_input(output + "-scale");
sharpen.set_build_render_pass([&, use_custom](Vulkan::CommandBuffer &cmd) {
bool srgb = Vulkan::format_is_srgb(graph.get_physical_texture_resource(sharpen_tex_out).get_format());
auto &view = graph.get_physical_texture_resource(upscale_tex);
if (srgb)
cmd.set_srgb_texture(0, 0, view);
else
cmd.set_unorm_texture(0, 0, view);
cmd.set_sampler(0, 0, Vulkan::StockSampler::NearestClamp);
auto *params = cmd.allocate_typed_constant_data<vec4>(1, 0, 2);
auto width = float(view.get_image().get_width());
auto height = float(view.get_image().get_height());
params[0] = vec4(width, height, 1.0f / width, 1.0f / height);
width = cmd.get_viewport().width;
height = cmd.get_viewport().height;
params[1] = vec4(width, height, 1.0f / width, 1.0f / height);
const char *vert = "assets://shaders/sharpen.vert";
const char *frag = "assets://shaders/sharpen.frag";
Vulkan::CommandBufferUtil::draw_fullscreen_quad(cmd, vert, frag);
});
}
return true;
}
bool setup_before_post_chain_antialiasing(PostAAType type, RenderGraph &graph, TemporalJitter &jitter,
float scaling_factor,
const std::string &input, const std::string &input_depth,
const std::string &output)
{
TAAQuality taa_quality;
switch (type)
{
case PostAAType::TAA_Low: taa_quality = TAAQuality::Low; break;
case PostAAType::TAA_Medium: taa_quality = TAAQuality::Medium; break;
case PostAAType::TAA_High: taa_quality = TAAQuality::High; break;
case PostAAType::TAA_Ultra: taa_quality = TAAQuality::Ultra; break;
case PostAAType::TAA_Extreme: taa_quality = TAAQuality::Extreme; break;
case PostAAType::TAA_Nightmare: taa_quality = TAAQuality::Nightmare; break;
default: return false;
}
setup_taa_resolve(graph, jitter, scaling_factor, input, input_depth, output, taa_quality);
return true;
}
bool setup_after_post_chain_antialiasing(PostAAType type, RenderGraph &graph, TemporalJitter &jitter,
float scaling_factor,
const std::string &input, const std::string &input_depth,
const std::string &output)
{
switch (type)
{
case PostAAType::None:
jitter.init(TemporalJitter::Type::None, vec2(0.0f));
return false;
case PostAAType::FXAA:
setup_fxaa_postprocess(graph, input, output);
return true;
case PostAAType::FXAA_2Phase:
setup_fxaa_2phase_postprocess(graph, jitter, input, input_depth, output);
return true;
case PostAAType::SMAA_Low:
setup_smaa_postprocess(graph, jitter, scaling_factor, input, input_depth, output, SMAAPreset::Low);
return true;
case PostAAType::SMAA_Medium:
setup_smaa_postprocess(graph, jitter, scaling_factor, input, input_depth, output, SMAAPreset::Medium);
return true;
case PostAAType::SMAA_High:
setup_smaa_postprocess(graph, jitter, scaling_factor, input, input_depth, output, SMAAPreset::High);
return true;
case PostAAType::SMAA_Ultra:
setup_smaa_postprocess(graph, jitter, scaling_factor, input, input_depth, output, SMAAPreset::Ultra);
return true;
case PostAAType::SMAA_Ultra_T2X:
setup_smaa_postprocess(graph, jitter, scaling_factor, input, input_depth, output, SMAAPreset::Ultra_T2X);
return true;
default:
return false;
}
}
PostAAType string_to_post_antialiasing_type(const char *type)
{
if (strcmp(type, "fxaa") == 0)
return PostAAType::FXAA;
else if (strcmp(type, "fxaa2phase") == 0)
return PostAAType::FXAA_2Phase;
else if (strcmp(type, "smaaLow") == 0)
return PostAAType::SMAA_Low;
else if (strcmp(type, "smaaMedium") == 0)
return PostAAType::SMAA_Medium;
else if (strcmp(type, "smaaHigh") == 0)
return PostAAType::SMAA_High;
else if (strcmp(type, "smaaUltra") == 0)
return PostAAType::SMAA_Ultra;
else if (strcmp(type, "smaaUltraT2X") == 0)
return PostAAType::SMAA_Ultra_T2X;
else if (strcmp(type, "taaLow") == 0)
return PostAAType::TAA_Low;
else if (strcmp(type, "taaMedium") == 0)
return PostAAType::TAA_Medium;
else if (strcmp(type, "taaHigh") == 0)
return PostAAType::TAA_High;
else if (strcmp(type, "taaUltra") == 0)
return PostAAType::TAA_Ultra;
else if (strcmp(type, "taaExtreme") == 0)
return PostAAType::TAA_Extreme;
else if (strcmp(type, "taaNightmare") == 0)
return PostAAType::TAA_Nightmare;
else if (strcmp(type, "none") == 0)
return PostAAType::None;
else
{
LOGE("Unrecognized AA type: %s\n", type);
return PostAAType::None;
}
}
}
<commit_msg>Fix lambda warning.<commit_after>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* 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 "aa.hpp"
#include "temporal.hpp"
#include "fxaa.hpp"
#include "smaa.hpp"
#include <string.h>
namespace Granite
{
constexpr bool upscale_linear = false;
constexpr bool allow_external_upscale = true;
constexpr bool allow_external_sharpen = true;
bool setup_after_post_chain_upscaling(RenderGraph &graph, const std::string &input, const std::string &output)
{
auto &upscale = graph.add_pass(output + "-scale", RenderGraph::get_default_post_graphics_queue());
AttachmentInfo upscale_info;
auto *fs = GRANITE_FILESYSTEM();
FileStat s;
bool use_custom = allow_external_upscale &&
fs->stat("assets://shaders/upscale.vert", s) && s.type == PathType::File &&
fs->stat("assets://shaders/upscale.frag", s) && s.type == PathType::File;
bool use_sharpen = allow_external_sharpen &&
fs->stat("assets://shaders/sharpen.vert", s) && s.type == PathType::File &&
fs->stat("assets://shaders/sharpen.frag", s) && s.type == PathType::File;
upscale_info.supports_prerotate = !use_custom;
if (use_sharpen)
{
upscale_info.format = VK_FORMAT_R8G8B8A8_UNORM;
upscale_info.unorm_srgb_alias = true;
}
auto &upscale_tex_out = upscale.add_color_output(!use_sharpen ? output : (output + "-scale"), upscale_info);
if (!upscale_linear)
graph.get_texture_resource(input).get_attachment_info().unorm_srgb_alias = true;
auto &tex = upscale.add_texture_input(input);
upscale.set_build_render_pass([&, use_custom](Vulkan::CommandBuffer &cmd) {
auto &view = graph.get_physical_texture_resource(tex);
if (upscale_linear)
cmd.set_texture(0, 0, view);
else
cmd.set_unorm_texture(0, 0, view);
cmd.set_sampler(0, 0, Vulkan::StockSampler::NearestClamp);
auto *params = cmd.allocate_typed_constant_data<vec4>(1, 0, 2);
auto width = float(view.get_image().get_width());
auto height = float(view.get_image().get_height());
params[0] = vec4(width, height, 1.0f / width, 1.0f / height);
width = cmd.get_viewport().width;
height = cmd.get_viewport().height;
params[1] = vec4(width, height, 1.0f / width, 1.0f / height);
bool srgb = !upscale_linear && Vulkan::format_is_srgb(graph.get_physical_texture_resource(upscale_tex_out).get_format());
const char *vert = use_custom ? "assets://shaders/upscale.vert" : "builtin://shaders/quad.vert";
const char *frag = use_custom ? "assets://shaders/upscale.frag" : "builtin://shaders/post/lanczos2.frag";
Vulkan::CommandBufferUtil::draw_fullscreen_quad(cmd, vert, frag,
{{ "TARGET_SRGB", srgb ? 1 : 0 }});
});
if (use_sharpen)
{
AttachmentInfo sharpen_info;
sharpen_info.supports_prerotate = !use_custom;
auto &sharpen = graph.add_pass(output + "-sharpen", RenderGraph::get_default_post_graphics_queue());
auto &sharpen_tex_out = sharpen.add_color_output(output, sharpen_info);
auto &upscale_tex = sharpen.add_texture_input(output + "-scale");
sharpen.set_build_render_pass([&](Vulkan::CommandBuffer &cmd) {
bool srgb = Vulkan::format_is_srgb(graph.get_physical_texture_resource(sharpen_tex_out).get_format());
auto &view = graph.get_physical_texture_resource(upscale_tex);
if (srgb)
cmd.set_srgb_texture(0, 0, view);
else
cmd.set_unorm_texture(0, 0, view);
cmd.set_sampler(0, 0, Vulkan::StockSampler::NearestClamp);
auto *params = cmd.allocate_typed_constant_data<vec4>(1, 0, 2);
auto width = float(view.get_image().get_width());
auto height = float(view.get_image().get_height());
params[0] = vec4(width, height, 1.0f / width, 1.0f / height);
width = cmd.get_viewport().width;
height = cmd.get_viewport().height;
params[1] = vec4(width, height, 1.0f / width, 1.0f / height);
const char *vert = "assets://shaders/sharpen.vert";
const char *frag = "assets://shaders/sharpen.frag";
Vulkan::CommandBufferUtil::draw_fullscreen_quad(cmd, vert, frag);
});
}
return true;
}
bool setup_before_post_chain_antialiasing(PostAAType type, RenderGraph &graph, TemporalJitter &jitter,
float scaling_factor,
const std::string &input, const std::string &input_depth,
const std::string &output)
{
TAAQuality taa_quality;
switch (type)
{
case PostAAType::TAA_Low: taa_quality = TAAQuality::Low; break;
case PostAAType::TAA_Medium: taa_quality = TAAQuality::Medium; break;
case PostAAType::TAA_High: taa_quality = TAAQuality::High; break;
case PostAAType::TAA_Ultra: taa_quality = TAAQuality::Ultra; break;
case PostAAType::TAA_Extreme: taa_quality = TAAQuality::Extreme; break;
case PostAAType::TAA_Nightmare: taa_quality = TAAQuality::Nightmare; break;
default: return false;
}
setup_taa_resolve(graph, jitter, scaling_factor, input, input_depth, output, taa_quality);
return true;
}
bool setup_after_post_chain_antialiasing(PostAAType type, RenderGraph &graph, TemporalJitter &jitter,
float scaling_factor,
const std::string &input, const std::string &input_depth,
const std::string &output)
{
switch (type)
{
case PostAAType::None:
jitter.init(TemporalJitter::Type::None, vec2(0.0f));
return false;
case PostAAType::FXAA:
setup_fxaa_postprocess(graph, input, output);
return true;
case PostAAType::FXAA_2Phase:
setup_fxaa_2phase_postprocess(graph, jitter, input, input_depth, output);
return true;
case PostAAType::SMAA_Low:
setup_smaa_postprocess(graph, jitter, scaling_factor, input, input_depth, output, SMAAPreset::Low);
return true;
case PostAAType::SMAA_Medium:
setup_smaa_postprocess(graph, jitter, scaling_factor, input, input_depth, output, SMAAPreset::Medium);
return true;
case PostAAType::SMAA_High:
setup_smaa_postprocess(graph, jitter, scaling_factor, input, input_depth, output, SMAAPreset::High);
return true;
case PostAAType::SMAA_Ultra:
setup_smaa_postprocess(graph, jitter, scaling_factor, input, input_depth, output, SMAAPreset::Ultra);
return true;
case PostAAType::SMAA_Ultra_T2X:
setup_smaa_postprocess(graph, jitter, scaling_factor, input, input_depth, output, SMAAPreset::Ultra_T2X);
return true;
default:
return false;
}
}
PostAAType string_to_post_antialiasing_type(const char *type)
{
if (strcmp(type, "fxaa") == 0)
return PostAAType::FXAA;
else if (strcmp(type, "fxaa2phase") == 0)
return PostAAType::FXAA_2Phase;
else if (strcmp(type, "smaaLow") == 0)
return PostAAType::SMAA_Low;
else if (strcmp(type, "smaaMedium") == 0)
return PostAAType::SMAA_Medium;
else if (strcmp(type, "smaaHigh") == 0)
return PostAAType::SMAA_High;
else if (strcmp(type, "smaaUltra") == 0)
return PostAAType::SMAA_Ultra;
else if (strcmp(type, "smaaUltraT2X") == 0)
return PostAAType::SMAA_Ultra_T2X;
else if (strcmp(type, "taaLow") == 0)
return PostAAType::TAA_Low;
else if (strcmp(type, "taaMedium") == 0)
return PostAAType::TAA_Medium;
else if (strcmp(type, "taaHigh") == 0)
return PostAAType::TAA_High;
else if (strcmp(type, "taaUltra") == 0)
return PostAAType::TAA_Ultra;
else if (strcmp(type, "taaExtreme") == 0)
return PostAAType::TAA_Extreme;
else if (strcmp(type, "taaNightmare") == 0)
return PostAAType::TAA_Nightmare;
else if (strcmp(type, "none") == 0)
return PostAAType::None;
else
{
LOGE("Unrecognized AA type: %s\n", type);
return PostAAType::None;
}
}
}
<|endoftext|> |
<commit_before>/***********************************************************************
created: Tue Feb 17 2009
author: Henri I Hyyryläinen (based on code by Paul D Turner)
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"
#include "CEGUI/RendererModules/Ogre/Texture.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/RenderEffect.h"
#include <OgreRenderSystem.h>
#include <OgreQuaternion.h>
#include <OgreHardwareBufferManager.h>
#include "CEGUI/Exceptions.h"
#include "CEGUI/ShaderParameterBindings.h"
#include "OgreManualObject.h"
#include "OgreRenderOperation.h"
#include "OgreSceneManager.h"
#define INITIAL_BUFFER_SIZE 24
#define FLOATS_PER_TEXTURED 9
#define FLOATS_PER_COLOURED 7
// Start of CEGUI namespace section
namespace CEGUI
{
OgreGeometryBuffer::OgreGeometryBuffer(OgreRenderer& owner,
Ogre::RenderSystem& rs, CEGUI::RefCounted<RenderMaterial> renderMaterial) :
GeometryBuffer(renderMaterial),
d_owner(owner),
d_renderSystem(rs),
d_clipRect(0, 0, 0, 0),
d_vertexHolder(0),
d_expectedData(MANUALOBJECT_TYPE_INVALID),
d_renderOp(0),
d_dataAppended(false),
d_firstMOUpdate(true)
{
}
//----------------------------------------------------------------------------//
OgreGeometryBuffer::~OgreGeometryBuffer()
{
cleanUpVertexAttributes();
}
//----------------------------------------------------------------------------//
void OgreGeometryBuffer::draw() const
{
if (d_vertexData.empty())
return;
if (d_dataAppended)
syncManualObject();
if (!d_renderOp)
return;
// setup clip region
if (d_clippingActive)
{
setScissorRects();
}
// Update the model matrix if necessary
if (!d_matrixValid)
updateMatrix();
CEGUI::ShaderParameterBindings* shaderParameterBindings =
(*d_renderMaterial).getShaderParamBindings();
// Set the ModelViewProjection matrix in the bindings
Ogre::Matrix4 omat = d_owner.getWorldViewProjMatrix()*d_matrix;
shaderParameterBindings->setParameter("modelViewPerspMatrix", &omat);
const int pass_count = d_effect ? d_effect->getPassCount() : 1;
for (int pass = 0; pass < pass_count; ++pass)
{
// set up RenderEffect
if (d_effect)
d_effect->performPreRenderFunctions(pass);
//initialiseTextureStates();
//Prepare for the rendering process according to the used render material
d_renderMaterial->prepareForRendering();
// draw the geometry
d_renderSystem._render(*d_renderOp);
}
// clean up RenderEffect
if (d_effect)
d_effect->performPostRenderFunctions();
// Disable clipping after rendering
if (d_clippingActive)
{
d_renderSystem.setScissorTest(false);
}
}
//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setClippingRegion(const Rectf& region)
{
d_clipRect.top(ceguimax(0.0f, region.top()));
d_clipRect.bottom(ceguimax(0.0f, region.bottom()));
d_clipRect.left(ceguimax(0.0f, region.left()));
d_clipRect.right(ceguimax(0.0f, region.right()));
}
//----------------------------------------------------------------------------//
void OgreGeometryBuffer::appendGeometry(const std::vector<float>& vertex_data)
{
d_vertexData.insert(d_vertexData.end(), vertex_data.begin(),
vertex_data.end());
d_dataAppended = true;
size_t float_per_element;
switch(d_expectedData){
case MANUALOBJECT_TYPE_COLOURED: float_per_element = FLOATS_PER_COLOURED; break;
case MANUALOBJECT_TYPE_TEXTURED: float_per_element = FLOATS_PER_TEXTURED; break;
}
d_vertexCount = d_vertexData.size()/float_per_element;
}
void OgreGeometryBuffer::syncManualObject() const
{
if (!d_dataAppended)
return;
// First update needs to create the section that subsequent calls can update
if (d_firstMOUpdate)
{
// Blank material initially
d_vertexHolder->begin("BaseWhiteNoLighting",
Ogre::RenderOperation::OT_TRIANGLE_LIST);
d_vertexHolder->estimateVertexCount(d_vertexCount > INITIAL_BUFFER_SIZE
? d_vertexCount: INITIAL_BUFFER_SIZE);
d_firstMOUpdate = false;
}
else
{
// Only the first section is ever used
d_vertexHolder->beginUpdate(0);
d_vertexHolder->estimateVertexCount(d_vertexCount);
}
// Append the data to the manual object
if (d_expectedData == MANUALOBJECT_TYPE_TEXTURED)
{
for (size_t i = 0; i < d_vertexData.size(); i += FLOATS_PER_TEXTURED)
{
assert(i+FLOATS_PER_TEXTURED <= d_vertexData.size() &&
"invalid vertex data passed to OgreGeometryBuffer");
// First the position
d_vertexHolder->position(d_vertexData[i], d_vertexData[i+1],
d_vertexData[i+2]);
// And then the colour
d_vertexHolder->colour(d_vertexData[i+3], d_vertexData[i+4],
d_vertexData[i+5], d_vertexData[i+6]);
// And finally texture coordinate
d_vertexHolder->textureCoord(d_vertexData[i+7], d_vertexData[i+8]);
}
}
else if (d_expectedData == MANUALOBJECT_TYPE_COLOURED)
{
for (size_t i = 0; i < d_vertexData.size(); i += FLOATS_PER_COLOURED)
{
assert(i+FLOATS_PER_COLOURED <= d_vertexData.size() &&
"invalid vertex data passed to OgreGeometryBuffer");
// First the position
d_vertexHolder->position(d_vertexData[i], d_vertexData[i+1],
d_vertexData[i+2]);
// And then the colour
d_vertexHolder->colour(d_vertexData[i+3], d_vertexData[i+4],
d_vertexData[i+5], d_vertexData[i+6]);
}
}
auto section = d_vertexHolder->end();
d_renderOp = section->getRenderOperation();
d_dataAppended = false;
}
//----------------------------------------------------------------------------//
void OgreGeometryBuffer::updateMatrix() const
{
// translation to position geometry and offset to pivot point
Ogre::Matrix4 trans;
trans.makeTrans(d_translation.d_x + d_pivot.d_x,
d_translation.d_y + d_pivot.d_y,
d_translation.d_z + d_pivot.d_z);
// rotation
Ogre::Matrix4 rot(Ogre::Quaternion(
d_rotation.d_w, d_rotation.d_x, d_rotation.d_y, d_rotation.d_z));
// translation to remove rotation pivot offset
Ogre::Matrix4 inv_pivot_trans;
inv_pivot_trans.makeTrans(-d_pivot.d_x, -d_pivot.d_y, -d_pivot.d_z);
// calculate final matrix
d_matrix = trans * rot * inv_pivot_trans;
d_matrixValid = true;
}
//----------------------------------------------------------------------------//
const Ogre::Matrix4& OgreGeometryBuffer::getMatrix() const{
if (!d_matrixValid)
updateMatrix();
return d_matrix;
}
//----------------------------------------------------------------------------//
void OgreGeometryBuffer::finaliseVertexAttributes(MANUALOBJECT_TYPE type)
{
d_expectedData = type;
if (d_expectedData >= MANUALOBJECT_TYPE_INVALID)
{
CEGUI_THROW(RendererException(
"Unknown d_expectedData type."));
}
setVertexBuffer();
}
void OgreGeometryBuffer::setVertexBuffer(){
// create the vertex container
d_vertexHolder = d_owner.getDummyScene().createManualObject(
Ogre::SCENE_STATIC);
if (!d_vertexHolder)
{
CEGUI_THROW(RendererException("Failed to create Ogre vertex buffer, "
"probably because the vertex layout is invalid."));
}
d_vertexHolder->setDynamic(true);
}
void OgreGeometryBuffer::cleanUpVertexAttributes()
{
d_renderOp = 0;
d_owner.getDummyScene().destroyManualObject(d_vertexHolder);
d_vertexHolder = 0;
}
// ------------------------------------ //
void OgreGeometryBuffer::setScissorRects() const
{
d_renderSystem.setScissorTest(true, d_clipRect.left(),
d_clipRect.top(), d_clipRect.right(), d_clipRect.bottom());
}
// ------------------------------------ //
void OgreGeometryBuffer::reset()
{
d_vertexData.clear();
d_clippingActive = true;
d_vertexHolder->clear();
d_firstMOUpdate = true;
d_renderOp = 0;
}
} // End of CEGUI namespace section
<commit_msg>correct blend state is now set (at least it looks different)<commit_after>/***********************************************************************
created: Tue Feb 17 2009
author: Henri I Hyyryläinen (based on code by Paul D Turner)
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"
#include "CEGUI/RendererModules/Ogre/Texture.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/RenderEffect.h"
#include <OgreRenderSystem.h>
#include <OgreQuaternion.h>
#include <OgreHardwareBufferManager.h>
#include "CEGUI/Exceptions.h"
#include "CEGUI/ShaderParameterBindings.h"
#include "OgreManualObject.h"
#include "OgreRenderOperation.h"
#include "OgreSceneManager.h"
#define INITIAL_BUFFER_SIZE 24
#define FLOATS_PER_TEXTURED 9
#define FLOATS_PER_COLOURED 7
// Start of CEGUI namespace section
namespace CEGUI
{
OgreGeometryBuffer::OgreGeometryBuffer(OgreRenderer& owner,
Ogre::RenderSystem& rs, CEGUI::RefCounted<RenderMaterial> renderMaterial) :
GeometryBuffer(renderMaterial),
d_owner(owner),
d_renderSystem(rs),
d_clipRect(0, 0, 0, 0),
d_vertexHolder(0),
d_expectedData(MANUALOBJECT_TYPE_INVALID),
d_renderOp(0),
d_dataAppended(false),
d_firstMOUpdate(true)
{
}
//----------------------------------------------------------------------------//
OgreGeometryBuffer::~OgreGeometryBuffer()
{
cleanUpVertexAttributes();
}
//----------------------------------------------------------------------------//
void OgreGeometryBuffer::draw() const
{
if (d_vertexData.empty())
return;
if (d_dataAppended)
syncManualObject();
if (!d_renderOp)
return;
// setup clip region
if (d_clippingActive)
{
setScissorRects();
}
// Update the model matrix if necessary
if (!d_matrixValid)
updateMatrix();
CEGUI::ShaderParameterBindings* shaderParameterBindings =
(*d_renderMaterial).getShaderParamBindings();
// Set the ModelViewProjection matrix in the bindings
Ogre::Matrix4 omat = d_owner.getWorldViewProjMatrix()*d_matrix;
shaderParameterBindings->setParameter("modelViewPerspMatrix", &omat);
// activate the desired blending mode
d_owner.bindBlendMode(d_blendMode);
const int pass_count = d_effect ? d_effect->getPassCount() : 1;
for (int pass = 0; pass < pass_count; ++pass)
{
// set up RenderEffect
if (d_effect)
d_effect->performPreRenderFunctions(pass);
//initialiseTextureStates();
//Prepare for the rendering process according to the used render material
d_renderMaterial->prepareForRendering();
// draw the geometry
d_renderSystem._render(*d_renderOp);
}
// clean up RenderEffect
if (d_effect)
d_effect->performPostRenderFunctions();
// Disable clipping after rendering
if (d_clippingActive)
{
d_renderSystem.setScissorTest(false);
}
}
//----------------------------------------------------------------------------//
void OgreGeometryBuffer::setClippingRegion(const Rectf& region)
{
d_clipRect.top(ceguimax(0.0f, region.top()));
d_clipRect.bottom(ceguimax(0.0f, region.bottom()));
d_clipRect.left(ceguimax(0.0f, region.left()));
d_clipRect.right(ceguimax(0.0f, region.right()));
}
//----------------------------------------------------------------------------//
void OgreGeometryBuffer::appendGeometry(const std::vector<float>& vertex_data)
{
d_vertexData.insert(d_vertexData.end(), vertex_data.begin(),
vertex_data.end());
d_dataAppended = true;
size_t float_per_element;
switch(d_expectedData){
case MANUALOBJECT_TYPE_COLOURED: float_per_element = FLOATS_PER_COLOURED; break;
case MANUALOBJECT_TYPE_TEXTURED: float_per_element = FLOATS_PER_TEXTURED; break;
}
d_vertexCount = d_vertexData.size()/float_per_element;
}
void OgreGeometryBuffer::syncManualObject() const
{
if (!d_dataAppended)
return;
// First update needs to create the section that subsequent calls can update
if (d_firstMOUpdate)
{
// Blank material initially
d_vertexHolder->begin("BaseWhiteNoLighting",
Ogre::RenderOperation::OT_TRIANGLE_LIST);
d_vertexHolder->estimateVertexCount(d_vertexCount > INITIAL_BUFFER_SIZE
? d_vertexCount: INITIAL_BUFFER_SIZE);
d_firstMOUpdate = false;
}
else
{
// Only the first section is ever used
d_vertexHolder->beginUpdate(0);
d_vertexHolder->estimateVertexCount(d_vertexCount);
}
// Append the data to the manual object
if (d_expectedData == MANUALOBJECT_TYPE_TEXTURED)
{
for (size_t i = 0; i < d_vertexData.size(); i += FLOATS_PER_TEXTURED)
{
assert(i+FLOATS_PER_TEXTURED <= d_vertexData.size() &&
"invalid vertex data passed to OgreGeometryBuffer");
// First the position
d_vertexHolder->position(d_vertexData[i], d_vertexData[i+1],
d_vertexData[i+2]);
// And then the colour
d_vertexHolder->colour(d_vertexData[i+3], d_vertexData[i+4],
d_vertexData[i+5], d_vertexData[i+6]);
// And finally texture coordinate
d_vertexHolder->textureCoord(d_vertexData[i+7], d_vertexData[i+8]);
}
}
else if (d_expectedData == MANUALOBJECT_TYPE_COLOURED)
{
for (size_t i = 0; i < d_vertexData.size(); i += FLOATS_PER_COLOURED)
{
assert(i+FLOATS_PER_COLOURED <= d_vertexData.size() &&
"invalid vertex data passed to OgreGeometryBuffer");
// First the position
d_vertexHolder->position(d_vertexData[i], d_vertexData[i+1],
d_vertexData[i+2]);
// And then the colour
d_vertexHolder->colour(d_vertexData[i+3], d_vertexData[i+4],
d_vertexData[i+5], d_vertexData[i+6]);
}
}
auto section = d_vertexHolder->end();
d_renderOp = section->getRenderOperation();
d_dataAppended = false;
}
//----------------------------------------------------------------------------//
void OgreGeometryBuffer::updateMatrix() const
{
// translation to position geometry and offset to pivot point
Ogre::Matrix4 trans;
trans.makeTrans(d_translation.d_x + d_pivot.d_x,
d_translation.d_y + d_pivot.d_y,
d_translation.d_z + d_pivot.d_z);
// rotation
Ogre::Matrix4 rot(Ogre::Quaternion(
d_rotation.d_w, d_rotation.d_x, d_rotation.d_y, d_rotation.d_z));
// translation to remove rotation pivot offset
Ogre::Matrix4 inv_pivot_trans;
inv_pivot_trans.makeTrans(-d_pivot.d_x, -d_pivot.d_y, -d_pivot.d_z);
// calculate final matrix
d_matrix = trans * rot * inv_pivot_trans;
d_matrixValid = true;
}
//----------------------------------------------------------------------------//
const Ogre::Matrix4& OgreGeometryBuffer::getMatrix() const{
if (!d_matrixValid)
updateMatrix();
return d_matrix;
}
//----------------------------------------------------------------------------//
void OgreGeometryBuffer::finaliseVertexAttributes(MANUALOBJECT_TYPE type)
{
d_expectedData = type;
if (d_expectedData >= MANUALOBJECT_TYPE_INVALID)
{
CEGUI_THROW(RendererException(
"Unknown d_expectedData type."));
}
setVertexBuffer();
}
void OgreGeometryBuffer::setVertexBuffer(){
// create the vertex container
d_vertexHolder = d_owner.getDummyScene().createManualObject(
Ogre::SCENE_STATIC);
if (!d_vertexHolder)
{
CEGUI_THROW(RendererException("Failed to create Ogre vertex buffer, "
"probably because the vertex layout is invalid."));
}
d_vertexHolder->setDynamic(true);
}
void OgreGeometryBuffer::cleanUpVertexAttributes()
{
d_renderOp = 0;
d_owner.getDummyScene().destroyManualObject(d_vertexHolder);
d_vertexHolder = 0;
}
// ------------------------------------ //
void OgreGeometryBuffer::setScissorRects() const
{
d_renderSystem.setScissorTest(true, d_clipRect.left(),
d_clipRect.top(), d_clipRect.right(), d_clipRect.bottom());
}
// ------------------------------------ //
void OgreGeometryBuffer::reset()
{
d_vertexData.clear();
d_clippingActive = true;
d_vertexHolder->clear();
d_firstMOUpdate = true;
d_renderOp = 0;
}
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before><commit_msg>disable that code for now<commit_after><|endoftext|> |
<commit_before>#include <engine/Widget.hpp>
#include <engine/Screen.hpp>
Widget::Widget(Widget* parent) : _parent(nullptr), _layout(), _theme(),
_pos(), _size(), _fixed_size(), _visible(true), _enabled(true), _focused(false), _mouse_focus(false),
_tooltip(), _font_size(-1), _cursor(Cursor::Arrow)
{
if (parent)
{
parent->add_child(this);
_theme = parent->_theme;
}
}
Widget::~Widget()
{
for (auto child : _children)
if (child) child->dec_ref();
}
void Widget::add_child(Widget* child)
{
_children.push_back(child);
child->add_ref();
child->parent(this);
}
void Widget::remove_child(uint64 index)
{
Widget* widget = _children[index];
_children.erase(_children.begin() + index);
widget->dec_ref();
}
void Widget::remove_child(Widget const* child)
{
_children.erase(std::remove(_children.begin(), _children.end(), child), _children.end());
child->dec_ref();
}
/*Window* Widget::window()
{
Widget *widget = this;
while (true)
{
if (!widget)
throw std::runtime_error("Widget:internal error (could not find parent window)");
Window *window = dynamic_cast<Window*>(widget);
if (window)
return window;
widget = widget->parent();
}
}*/
void Widget::request_focus()
{
/*Widget* widget = this;
while (widget->parent())
widget = widget->parent();
dynamic_cast<Screen*>(widget)->update_focus(this);*/
}
int Widget::font_size() const
{
return _font_size < 0 ? _theme->_standard_font_size : _font_size;
}
Widget* Widget::find_widget(ivec2 const& p)
{
for (auto it = _children.rbegin(); it != _children.rend(); ++it)
{
Widget* child = *it;
if (child->visible() && child->contains(p))
return child->find_widget(p - _pos);
}
return contains(p) ? this : nullptr;
}
bool Widget::mouse_button_event(ivec2 const& p, Mouse button, bool down, int modifiers)
{
for (auto it = _children.rbegin(); it != _children.rend(); ++it)
{
Widget* child = *it;
if (child->visible() && child->contains(p - _pos) &&
child->mouse_button_event(p - _pos, button, down, modifiers))
return true;
}
if (button == Mouse::Left && down && !_focused)
request_focus();
return false;
}
bool Widget::mouse_motion_event(ivec2 const& p, const ivec2& rel, Mouse button, int modifiers)
{
for (auto it = _children.rbegin(); it != _children.rend(); ++it)
{
Widget* child = *it;
if (!child->visible())
continue;
bool contained = child->contains(p - _pos), prev_contained = child->contains(p - _pos - rel);
if (contained != prev_contained)
child->mouse_enter_event(p, contained);
if ((contained || prev_contained) && child->mouse_motion_event(p - _pos, rel, button, modifiers))
return true;
}
return false;
}
bool Widget::mouse_drag_event(ivec2 const& p, const ivec2& rel, Mouse button, int modifiers)
{
return false;
}
bool Widget::mouse_enter_event(ivec2 const& p, bool enter)
{
_mouse_focus = enter;
return false;
}
bool Widget::scroll_event(ivec2 const& p, ivec2 const& rel)
{
for (auto it = _children.rbegin(); it != _children.rend(); ++it)
{
Widget* child = *it;
if (!child->visible())
continue;
if (child->contains(p - _pos) && child->scroll_event(p - _pos, rel))
return true;
}
return false;
}
bool Widget::focus_event(bool focused)
{
_focused = focused;
return false;
}
bool Widget::keyboard_event(Key key, int scancode, Action action, int modifiers)
{
return false;
}
bool Widget::keyboard_character_event(unsigned int codepoint)
{
return false;
}
ivec2 Widget::preferred_size(Ref<Painter> p)
{
return _layout ? _layout->preferred_size(p, this) : _size;
}
void Widget::perform_layout(Ref<Painter> p)
{
if (_layout)
_layout->perform_layout(p, this);
else
for (auto child : _children)
{
ivec2 pref = child->preferred_size(p), fix = child->fixed_size();
child->size(ivec2(fix.x ? fix.x : pref.x, fix.y ? fix.y : pref.y));
child->perform_layout(p);
}
}
void Widget::draw(Ref<Painter> p)
{
if (_children.empty())
return;
p->translate(vec2(_pos.x, _pos.y));
for (auto child : _children)
if (child->visible())
child->draw(p);
p->translate(vec2(-_pos.x, -_pos.y));
}
<commit_msg>Fixed compilation warnings in Widget's source file<commit_after>#include <engine/Widget.hpp>
#include <engine/Screen.hpp>
#include <algorithm>
Widget::Widget(Widget* parent) : _parent(nullptr), _layout(), _theme(),
_pos(), _size(), _fixed_size(), _visible(true), _enabled(true), _focused(false), _mouse_focus(false),
_tooltip(), _font_size(-1), _cursor(Cursor::Arrow)
{
if (parent)
{
parent->add_child(this);
_theme = parent->_theme;
}
}
Widget::~Widget()
{
for (auto child : _children)
if (child) child->dec_ref();
}
void Widget::add_child(Widget* child)
{
_children.push_back(child);
child->add_ref();
child->parent(this);
}
void Widget::remove_child(uint64 index)
{
Widget* widget = _children[index];
_children.erase(_children.begin() + index);
widget->dec_ref();
}
void Widget::remove_child(Widget const* child)
{
_children.erase(std::remove(_children.begin(), _children.end(), child), _children.end());
child->dec_ref();
}
/*Window* Widget::window()
{
Widget *widget = this;
while (true)
{
if (!widget)
throw std::runtime_error("Widget:internal error (could not find parent window)");
Window *window = dynamic_cast<Window*>(widget);
if (window)
return window;
widget = widget->parent();
}
}*/
void Widget::request_focus()
{
/*Widget* widget = this;
while (widget->parent())
widget = widget->parent();
dynamic_cast<Screen*>(widget)->update_focus(this);*/
}
int Widget::font_size() const
{
return _font_size < 0 ? _theme->_standard_font_size : _font_size;
}
Widget* Widget::find_widget(ivec2 const& p)
{
for (auto it = _children.rbegin(); it != _children.rend(); ++it)
{
Widget* child = *it;
if (child->visible() && child->contains(p))
return child->find_widget(p - _pos);
}
return contains(p) ? this : nullptr;
}
bool Widget::mouse_button_event(ivec2 const& p, Mouse button, bool down, int modifiers)
{
for (auto it = _children.rbegin(); it != _children.rend(); ++it)
{
Widget* child = *it;
if (child->visible() && child->contains(p - _pos) &&
child->mouse_button_event(p - _pos, button, down, modifiers))
return true;
}
if (button == Mouse::Left && down && !_focused)
request_focus();
return false;
}
bool Widget::mouse_motion_event(ivec2 const& p, const ivec2& rel, Mouse button, int modifiers)
{
for (auto it = _children.rbegin(); it != _children.rend(); ++it)
{
Widget* child = *it;
if (!child->visible())
continue;
bool contained = child->contains(p - _pos), prev_contained = child->contains(p - _pos - rel);
if (contained != prev_contained)
child->mouse_enter_event(p, contained);
if ((contained || prev_contained) && child->mouse_motion_event(p - _pos, rel, button, modifiers))
return true;
}
return false;
}
bool Widget::mouse_drag_event(ivec2 const&, const ivec2&, Mouse, int)
{
return false;
}
bool Widget::mouse_enter_event(ivec2 const&, bool enter)
{
_mouse_focus = enter;
return false;
}
bool Widget::scroll_event(ivec2 const& p, ivec2 const& rel)
{
for (auto it = _children.rbegin(); it != _children.rend(); ++it)
{
Widget* child = *it;
if (!child->visible())
continue;
if (child->contains(p - _pos) && child->scroll_event(p - _pos, rel))
return true;
}
return false;
}
bool Widget::focus_event(bool focused)
{
_focused = focused;
return false;
}
bool Widget::keyboard_event(Key, int, Action, int)
{
return false;
}
bool Widget::keyboard_character_event(unsigned int)
{
return false;
}
ivec2 Widget::preferred_size(Ref<Painter> p)
{
return _layout ? _layout->preferred_size(p, this) : _size;
}
void Widget::perform_layout(Ref<Painter> p)
{
if (_layout)
_layout->perform_layout(p, this);
else
for (auto child : _children)
{
ivec2 pref = child->preferred_size(p), fix = child->fixed_size();
child->size(ivec2(fix.x ? fix.x : pref.x, fix.y ? fix.y : pref.y));
child->perform_layout(p);
}
}
void Widget::draw(Ref<Painter> p)
{
if (_children.empty())
return;
p->translate(vec2(_pos.x, _pos.y));
for (auto child : _children)
if (child->visible())
child->draw(p);
p->translate(vec2(-_pos.x, -_pos.y));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_install_ui.h"
#include <map>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#if defined(TOOLKIT_VIEWS) // TODO(port)
#include "chrome/browser/views/extensions/extension_installed_bubble.h"
#elif defined(TOOLKIT_GTK)
#include "chrome/browser/gtk/extension_installed_bubble_gtk.h"
#endif
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/platform_util.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/cocoa/extension_installed_bubble_bridge.h"
#endif
// static
const int ExtensionInstallUI::kTitleIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_TITLE,
IDS_EXTENSION_UNINSTALL_PROMPT_TITLE
};
// static
const int ExtensionInstallUI::kHeadingIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_HEADING,
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING
};
// static
const int ExtensionInstallUI::kButtonIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_PROMPT_INSTALL_BUTTON,
IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON
};
namespace {
// We also show the severe warning if the extension has access to any file://
// URLs. They aren't *quite* as dangerous as full access to the system via
// NPAPI, but pretty dang close. Content scripts are currently the only way
// that extension can get access to file:// URLs.
static bool ExtensionHasFileAccess(Extension* extension) {
for (UserScriptList::const_iterator script =
extension->content_scripts().begin();
script != extension->content_scripts().end();
++script) {
for (UserScript::PatternList::const_iterator pattern =
script->url_patterns().begin();
pattern != script->url_patterns().end();
++pattern) {
if (pattern->scheme() == chrome::kFileScheme)
return true;
}
}
return false;
}
static void GetV2Warnings(Extension* extension,
std::vector<string16>* warnings) {
if (!extension->plugins().empty() || ExtensionHasFileAccess(extension)) {
// TODO(aa): This one is a bit awkward. Should we have a separate
// presentation for this case?
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_FULL_ACCESS));
return;
}
if (extension->HasAccessToAllHosts()) {
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_ALL_HOSTS));
} else {
std::set<std::string> hosts = extension->GetEffectiveHostPermissions();
if (hosts.size() == 1) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_1_HOST,
UTF8ToUTF16(*hosts.begin())));
} else if (hosts.size() == 2) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_2_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin()))));
} else if (hosts.size() == 3) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_3_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
UTF8ToUTF16(*(++++hosts.begin()))));
} else if (hosts.size() >= 4) {
warnings->push_back(
l10n_util::GetStringFUTF16(
IDS_EXTENSION_PROMPT2_WARNING_4_OR_MORE_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
IntToString16(hosts.size() - 2)));
}
}
if (extension->HasEffectiveBrowsingHistoryPermission()) {
warnings->push_back(
l10n_util::GetStringUTF16(
IDS_EXTENSION_PROMPT2_WARNING_BROWSING_HISTORY));
}
// TODO(aa): Geolocation, camera/mic, what else?
}
} // namespace
ExtensionInstallUI::ExtensionInstallUI(Profile* profile)
: profile_(profile),
ui_loop_(MessageLoop::current()),
previous_use_system_theme_(false),
extension_(NULL),
delegate_(NULL),
prompt_type_(NUM_PROMPT_TYPES),
ALLOW_THIS_IN_INITIALIZER_LIST(tracker_(this)) {}
void ExtensionInstallUI::ConfirmInstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
// We special-case themes to not show any confirm UI. Instead they are
// immediately installed, and then we show an infobar (see OnInstallSuccess)
// to allow the user to revert if they don't like it.
if (extension->IsTheme()) {
// Remember the current theme in case the user pressed undo.
Extension* previous_theme = profile_->GetTheme();
if (previous_theme)
previous_theme_id_ = previous_theme->id();
#if defined(TOOLKIT_GTK)
// On Linux, we also need to take the user's system settings into account
// to undo theme installation.
previous_use_system_theme_ =
GtkThemeProvider::GetFrom(profile_)->UseGtkTheme();
#else
DCHECK(!previous_use_system_theme_);
#endif
delegate->InstallUIProceed(false);
return;
}
ShowConfirmation(INSTALL_PROMPT);
}
void ExtensionInstallUI::ConfirmUninstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
ShowConfirmation(UNINSTALL_PROMPT);
}
void ExtensionInstallUI::OnInstallSuccess(Extension* extension) {
if (extension->IsTheme()) {
ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,
extension, profile_);
return;
}
// GetLastActiveWithProfile will fail on the build bots. This needs to be
// implemented differently if any test is created which depends on
// ExtensionInstalledBubble showing.
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
#if defined(TOOLKIT_VIEWS)
if (!browser)
return;
ExtensionInstalledBubble::Show(extension, browser, icon_);
#elif defined(OS_MACOSX)
DCHECK(browser);
// Note that browser actions don't appear in incognito mode initially,
// so fall back to the generic case.
if ((extension->browser_action() && !browser->profile()->IsOffTheRecord()) ||
(extension->page_action() &&
!extension->page_action()->default_icon_path().empty())) {
ExtensionInstalledBubbleCocoa::ShowExtensionInstalledBubble(
browser->window()->GetNativeHandle(),
extension, browser, icon_);
} else {
// If the extension is of type GENERIC, meaning it doesn't have a UI
// surface to display for this window, launch infobar instead of popup
// bubble, because we have no guaranteed wrench menu button to point to.
ShowGenericExtensionInstalledInfoBar(extension);
}
#elif defined(TOOLKIT_GTK)
if (!browser)
return;
ExtensionInstalledBubbleGtk::Show(extension, browser, icon_);
#endif // TOOLKIT_VIEWS
}
void ExtensionInstallUI::OnInstallFailure(const std::string& error) {
DCHECK(ui_loop_ == MessageLoop::current());
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
platform_util::SimpleErrorBox(
browser ? browser->window()->GetNativeHandle() : NULL,
l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALL_FAILURE_TITLE),
UTF8ToUTF16(error));
}
void ExtensionInstallUI::OnOverinstallAttempted(Extension* extension) {
ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,
extension, profile_);
}
void ExtensionInstallUI::OnImageLoaded(
SkBitmap* image, ExtensionResource resource, int index) {
if (image)
icon_ = *image;
else
icon_ = SkBitmap();
if (icon_.empty()) {
icon_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_EXTENSION_DEFAULT_ICON);
}
switch (prompt_type_) {
case INSTALL_PROMPT: {
NotificationService* service = NotificationService::current();
service->Notify(NotificationType::EXTENSION_WILL_SHOW_CONFIRM_DIALOG,
Source<ExtensionInstallUI>(this),
NotificationService::NoDetails());
std::vector<string16> warnings;
GetV2Warnings(extension_, &warnings);
ShowExtensionInstallUIPrompt2Impl(
profile_, delegate_, extension_, &icon_, warnings);
break;
}
case UNINSTALL_PROMPT: {
string16 message =
l10n_util::GetStringUTF16(IDS_EXTENSION_UNINSTALL_CONFIRMATION);
ShowExtensionInstallUIPromptImpl(profile_, delegate_, extension_, &icon_,
message, UNINSTALL_PROMPT);
break;
}
default:
NOTREACHED() << "Unknown message";
break;
}
}
void ExtensionInstallUI::ShowThemeInfoBar(
const std::string& previous_theme_id, bool previous_use_system_theme,
Extension* new_theme, Profile* profile) {
if (!new_theme->IsTheme())
return;
Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
// First find any previous theme preview infobars.
InfoBarDelegate* old_delegate = NULL;
for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) {
InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i);
if (delegate->AsThemePreviewInfobarDelegate()) {
old_delegate = delegate;
break;
}
}
// Then either replace that old one or add a new one.
InfoBarDelegate* new_delegate =
GetNewThemeInstalledInfoBarDelegate(
tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
if (old_delegate)
tab_contents->ReplaceInfoBar(old_delegate, new_delegate);
else
tab_contents->AddInfoBar(new_delegate);
}
void ExtensionInstallUI::ShowConfirmation(PromptType prompt_type) {
// Load the image asynchronously. For the response, check OnImageLoaded.
prompt_type_ = prompt_type;
ExtensionResource image =
extension_->GetIconPath(Extension::EXTENSION_ICON_LARGE);
tracker_.LoadImage(extension_, image,
gfx::Size(Extension::EXTENSION_ICON_LARGE,
Extension::EXTENSION_ICON_LARGE),
ImageLoadingTracker::DONT_CACHE);
}
#if defined(OS_MACOSX)
void ExtensionInstallUI::ShowGenericExtensionInstalledInfoBar(
Extension* new_extension) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
std::wstring msg = l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING,
UTF8ToWide(new_extension->name())) +
L" " + l10n_util::GetString(IDS_EXTENSION_INSTALLED_MANAGE_INFO_MAC);
InfoBarDelegate* delegate = new SimpleAlertInfoBarDelegate(
tab_contents, msg, new SkBitmap(icon_), true);
tab_contents->AddInfoBar(delegate);
}
#endif
InfoBarDelegate* ExtensionInstallUI::GetNewThemeInstalledInfoBarDelegate(
TabContents* tab_contents, Extension* new_theme,
const std::string& previous_theme_id, bool previous_use_system_theme) {
#if defined(TOOLKIT_GTK)
return new GtkThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
#else
return new ThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id);
#endif
}
<commit_msg>Auto-launch apps after installation.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_install_ui.h"
#include <map>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#if defined(TOOLKIT_VIEWS) // TODO(port)
#include "chrome/browser/views/extensions/extension_installed_bubble.h"
#elif defined(TOOLKIT_GTK)
#include "chrome/browser/gtk/extension_installed_bubble_gtk.h"
#endif
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/platform_util.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/cocoa/extension_installed_bubble_bridge.h"
#endif
// static
const int ExtensionInstallUI::kTitleIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_TITLE,
IDS_EXTENSION_UNINSTALL_PROMPT_TITLE
};
// static
const int ExtensionInstallUI::kHeadingIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_HEADING,
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING
};
// static
const int ExtensionInstallUI::kButtonIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_PROMPT_INSTALL_BUTTON,
IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON
};
namespace {
// We also show the severe warning if the extension has access to any file://
// URLs. They aren't *quite* as dangerous as full access to the system via
// NPAPI, but pretty dang close. Content scripts are currently the only way
// that extension can get access to file:// URLs.
static bool ExtensionHasFileAccess(Extension* extension) {
for (UserScriptList::const_iterator script =
extension->content_scripts().begin();
script != extension->content_scripts().end();
++script) {
for (UserScript::PatternList::const_iterator pattern =
script->url_patterns().begin();
pattern != script->url_patterns().end();
++pattern) {
if (pattern->scheme() == chrome::kFileScheme)
return true;
}
}
return false;
}
static void GetV2Warnings(Extension* extension,
std::vector<string16>* warnings) {
if (!extension->plugins().empty() || ExtensionHasFileAccess(extension)) {
// TODO(aa): This one is a bit awkward. Should we have a separate
// presentation for this case?
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_FULL_ACCESS));
return;
}
if (extension->HasAccessToAllHosts()) {
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_ALL_HOSTS));
} else {
std::set<std::string> hosts = extension->GetEffectiveHostPermissions();
if (hosts.size() == 1) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_1_HOST,
UTF8ToUTF16(*hosts.begin())));
} else if (hosts.size() == 2) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_2_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin()))));
} else if (hosts.size() == 3) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_3_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
UTF8ToUTF16(*(++++hosts.begin()))));
} else if (hosts.size() >= 4) {
warnings->push_back(
l10n_util::GetStringFUTF16(
IDS_EXTENSION_PROMPT2_WARNING_4_OR_MORE_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
IntToString16(hosts.size() - 2)));
}
}
if (extension->HasEffectiveBrowsingHistoryPermission()) {
warnings->push_back(
l10n_util::GetStringUTF16(
IDS_EXTENSION_PROMPT2_WARNING_BROWSING_HISTORY));
}
// TODO(aa): Geolocation, camera/mic, what else?
}
} // namespace
ExtensionInstallUI::ExtensionInstallUI(Profile* profile)
: profile_(profile),
ui_loop_(MessageLoop::current()),
previous_use_system_theme_(false),
extension_(NULL),
delegate_(NULL),
prompt_type_(NUM_PROMPT_TYPES),
ALLOW_THIS_IN_INITIALIZER_LIST(tracker_(this)) {}
void ExtensionInstallUI::ConfirmInstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
// We special-case themes to not show any confirm UI. Instead they are
// immediately installed, and then we show an infobar (see OnInstallSuccess)
// to allow the user to revert if they don't like it.
if (extension->IsTheme()) {
// Remember the current theme in case the user pressed undo.
Extension* previous_theme = profile_->GetTheme();
if (previous_theme)
previous_theme_id_ = previous_theme->id();
#if defined(TOOLKIT_GTK)
// On Linux, we also need to take the user's system settings into account
// to undo theme installation.
previous_use_system_theme_ =
GtkThemeProvider::GetFrom(profile_)->UseGtkTheme();
#else
DCHECK(!previous_use_system_theme_);
#endif
delegate->InstallUIProceed(false);
return;
}
ShowConfirmation(INSTALL_PROMPT);
}
void ExtensionInstallUI::ConfirmUninstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
ShowConfirmation(UNINSTALL_PROMPT);
}
void ExtensionInstallUI::OnInstallSuccess(Extension* extension) {
if (extension->IsTheme()) {
ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,
extension, profile_);
return;
}
if (extension->GetFullLaunchURL().is_valid()) {
Browser::OpenApplicationTab(profile_, extension);
return;
}
// GetLastActiveWithProfile will fail on the build bots. This needs to be
// implemented differently if any test is created which depends on
// ExtensionInstalledBubble showing.
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
#if defined(TOOLKIT_VIEWS)
if (!browser)
return;
ExtensionInstalledBubble::Show(extension, browser, icon_);
#elif defined(OS_MACOSX)
DCHECK(browser);
// Note that browser actions don't appear in incognito mode initially,
// so fall back to the generic case.
if ((extension->browser_action() && !browser->profile()->IsOffTheRecord()) ||
(extension->page_action() &&
!extension->page_action()->default_icon_path().empty())) {
ExtensionInstalledBubbleCocoa::ShowExtensionInstalledBubble(
browser->window()->GetNativeHandle(),
extension, browser, icon_);
} else {
// If the extension is of type GENERIC, meaning it doesn't have a UI
// surface to display for this window, launch infobar instead of popup
// bubble, because we have no guaranteed wrench menu button to point to.
ShowGenericExtensionInstalledInfoBar(extension);
}
#elif defined(TOOLKIT_GTK)
if (!browser)
return;
ExtensionInstalledBubbleGtk::Show(extension, browser, icon_);
#endif // TOOLKIT_VIEWS
}
void ExtensionInstallUI::OnInstallFailure(const std::string& error) {
DCHECK(ui_loop_ == MessageLoop::current());
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
platform_util::SimpleErrorBox(
browser ? browser->window()->GetNativeHandle() : NULL,
l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALL_FAILURE_TITLE),
UTF8ToUTF16(error));
}
void ExtensionInstallUI::OnOverinstallAttempted(Extension* extension) {
ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,
extension, profile_);
}
void ExtensionInstallUI::OnImageLoaded(
SkBitmap* image, ExtensionResource resource, int index) {
if (image)
icon_ = *image;
else
icon_ = SkBitmap();
if (icon_.empty()) {
icon_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_EXTENSION_DEFAULT_ICON);
}
switch (prompt_type_) {
case INSTALL_PROMPT: {
NotificationService* service = NotificationService::current();
service->Notify(NotificationType::EXTENSION_WILL_SHOW_CONFIRM_DIALOG,
Source<ExtensionInstallUI>(this),
NotificationService::NoDetails());
std::vector<string16> warnings;
GetV2Warnings(extension_, &warnings);
ShowExtensionInstallUIPrompt2Impl(
profile_, delegate_, extension_, &icon_, warnings);
break;
}
case UNINSTALL_PROMPT: {
string16 message =
l10n_util::GetStringUTF16(IDS_EXTENSION_UNINSTALL_CONFIRMATION);
ShowExtensionInstallUIPromptImpl(profile_, delegate_, extension_, &icon_,
message, UNINSTALL_PROMPT);
break;
}
default:
NOTREACHED() << "Unknown message";
break;
}
}
void ExtensionInstallUI::ShowThemeInfoBar(
const std::string& previous_theme_id, bool previous_use_system_theme,
Extension* new_theme, Profile* profile) {
if (!new_theme->IsTheme())
return;
Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
// First find any previous theme preview infobars.
InfoBarDelegate* old_delegate = NULL;
for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) {
InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i);
if (delegate->AsThemePreviewInfobarDelegate()) {
old_delegate = delegate;
break;
}
}
// Then either replace that old one or add a new one.
InfoBarDelegate* new_delegate =
GetNewThemeInstalledInfoBarDelegate(
tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
if (old_delegate)
tab_contents->ReplaceInfoBar(old_delegate, new_delegate);
else
tab_contents->AddInfoBar(new_delegate);
}
void ExtensionInstallUI::ShowConfirmation(PromptType prompt_type) {
// Load the image asynchronously. For the response, check OnImageLoaded.
prompt_type_ = prompt_type;
ExtensionResource image =
extension_->GetIconPath(Extension::EXTENSION_ICON_LARGE);
tracker_.LoadImage(extension_, image,
gfx::Size(Extension::EXTENSION_ICON_LARGE,
Extension::EXTENSION_ICON_LARGE),
ImageLoadingTracker::DONT_CACHE);
}
#if defined(OS_MACOSX)
void ExtensionInstallUI::ShowGenericExtensionInstalledInfoBar(
Extension* new_extension) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
std::wstring msg = l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING,
UTF8ToWide(new_extension->name())) +
L" " + l10n_util::GetString(IDS_EXTENSION_INSTALLED_MANAGE_INFO_MAC);
InfoBarDelegate* delegate = new SimpleAlertInfoBarDelegate(
tab_contents, msg, new SkBitmap(icon_), true);
tab_contents->AddInfoBar(delegate);
}
#endif
InfoBarDelegate* ExtensionInstallUI::GetNewThemeInstalledInfoBarDelegate(
TabContents* tab_contents, Extension* new_theme,
const std::string& previous_theme_id, bool previous_use_system_theme) {
#if defined(TOOLKIT_GTK)
return new GtkThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
#else
return new ThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id);
#endif
}
<|endoftext|> |
<commit_before>/*
* Copyright 2020 Google LLC
*
* 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 "aistreams/base/util/auth_helpers.h"
#include "absl/strings/str_format.h"
#include "absl/strings/strip.h"
#include "aistreams/base/util/grpc_helpers.h"
#include "aistreams/port/canonical_errors.h"
#include "aistreams/util/file_helpers.h"
#include "google/iam/credentials/v1/common.grpc.pb.h"
#include "google/iam/credentials/v1/common.pb.h"
#include "google/iam/credentials/v1/iamcredentials.grpc.pb.h"
#include "google/iam/credentials/v1/iamcredentials.pb.h"
#include "rapidjson/document.h"
namespace aistreams {
namespace {
using ::google::iam::credentials::v1::GenerateIdTokenRequest;
using ::google::iam::credentials::v1::GenerateIdTokenResponse;
using ::google::iam::credentials::v1::IAMCredentials;
constexpr char kIAMGoogleAPI[] = "iamcredentials.googleapis.com";
constexpr char kAudiance[] = "https://aistreams.googleapis.com/";
constexpr char kResourceNameFormat[] = "projects/-/serviceAccounts/%s";
constexpr char kGoogleApplicationCredentials[] =
"GOOGLE_APPLICATION_CREDENTIALS";
constexpr char kClientEmailKey[] = "client_email";
} // namespace
StatusOr<std::string> GetIdToken(const std::string& service_account) {
auto channel =
grpc::CreateChannel(kIAMGoogleAPI, grpc::GoogleDefaultCredentials());
std::unique_ptr<IAMCredentials::Stub> stub(IAMCredentials::NewStub(channel));
GenerateIdTokenRequest request;
GenerateIdTokenResponse response;
request.set_name(absl::StrFormat(kResourceNameFormat, service_account));
request.set_audience(kAudiance);
request.set_include_email(true);
grpc::ClientContext ctx;
auto status = stub->GenerateIdToken(&ctx, request, &response);
if (!status.ok()) {
LOG(ERROR) << status.error_message();
return InternalError(
"Encountered error while calling IAM service to generate ID token.");
}
return response.token();
}
StatusOr<std::string> GetIdTokenWithDefaultServiceAccount() {
const char* cred_path = std::getenv(kGoogleApplicationCredentials);
if (cred_path == nullptr) {
return InternalError(
"GOOGLE_APPLICATION_CREDENTIALS is not set. Please follow "
"https://cloud.google.com/docs/authentication/getting-started to setup "
"authentication.");
}
// Read json key file.
std::string file_contents;
auto status = file::GetContents(cred_path, &file_contents);
if (!status.ok()) {
LOG(ERROR) << status;
return InvalidArgumentError(
absl::StrFormat("Failed to get contents from file %s", cred_path));
}
rapidjson::Document doc;
doc.Parse(file_contents);
if (!doc.HasMember(kClientEmailKey)) {
return InternalError("Failed to find client_email from the file.");
}
return GetIdToken(doc[kClientEmailKey].GetString());
}
} // namespace aistreams
<commit_msg>set RAPIDJSON_HAS_STDSTRING<commit_after>/*
* Copyright 2020 Google LLC
*
* 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.
*/
#undef RAPIDJSON_HAS_STDSTRING
#define RAPIDJSON_HAS_STDSTRING 1
#include "aistreams/base/util/auth_helpers.h"
#include "absl/strings/str_format.h"
#include "absl/strings/strip.h"
#include "aistreams/base/util/grpc_helpers.h"
#include "aistreams/port/canonical_errors.h"
#include "aistreams/util/file_helpers.h"
#include "google/iam/credentials/v1/common.grpc.pb.h"
#include "google/iam/credentials/v1/common.pb.h"
#include "google/iam/credentials/v1/iamcredentials.grpc.pb.h"
#include "google/iam/credentials/v1/iamcredentials.pb.h"
#include "rapidjson/document.h"
namespace aistreams {
namespace {
using ::google::iam::credentials::v1::GenerateIdTokenRequest;
using ::google::iam::credentials::v1::GenerateIdTokenResponse;
using ::google::iam::credentials::v1::IAMCredentials;
constexpr char kIAMGoogleAPI[] = "iamcredentials.googleapis.com";
constexpr char kAudiance[] = "https://aistreams.googleapis.com/";
constexpr char kResourceNameFormat[] = "projects/-/serviceAccounts/%s";
constexpr char kGoogleApplicationCredentials[] =
"GOOGLE_APPLICATION_CREDENTIALS";
constexpr char kClientEmailKey[] = "client_email";
} // namespace
StatusOr<std::string> GetIdToken(const std::string& service_account) {
auto channel =
grpc::CreateChannel(kIAMGoogleAPI, grpc::GoogleDefaultCredentials());
std::unique_ptr<IAMCredentials::Stub> stub(IAMCredentials::NewStub(channel));
GenerateIdTokenRequest request;
GenerateIdTokenResponse response;
request.set_name(absl::StrFormat(kResourceNameFormat, service_account));
request.set_audience(kAudiance);
request.set_include_email(true);
grpc::ClientContext ctx;
auto status = stub->GenerateIdToken(&ctx, request, &response);
if (!status.ok()) {
LOG(ERROR) << status.error_message();
return InternalError(
"Encountered error while calling IAM service to generate ID token.");
}
return response.token();
}
StatusOr<std::string> GetIdTokenWithDefaultServiceAccount() {
const char* cred_path = std::getenv(kGoogleApplicationCredentials);
if (cred_path == nullptr) {
return InternalError(
"GOOGLE_APPLICATION_CREDENTIALS is not set. Please follow "
"https://cloud.google.com/docs/authentication/getting-started to setup "
"authentication.");
}
// Read json key file.
std::string file_contents;
auto status = file::GetContents(cred_path, &file_contents);
if (!status.ok()) {
LOG(ERROR) << status;
return InvalidArgumentError(
absl::StrFormat("Failed to get contents from file %s", cred_path));
}
rapidjson::Document doc;
doc.Parse(file_contents);
if (!doc.HasMember(kClientEmailKey)) {
return InternalError("Failed to find client_email from the file.");
}
return GetIdToken(doc[kClientEmailKey].GetString());
}
} // namespace aistreams
<|endoftext|> |
<commit_before>#pragma once
#include "queue.hpp"
#include <pqrs/osx/system_preferences.hpp>
namespace krbn {
namespace manipulator {
namespace manipulators {
namespace post_event_to_virtual_devices {
class mouse_key_handler final : public pqrs::dispatcher::extra::dispatcher_client {
public:
class count_converter final {
public:
count_converter(int threshold) : threshold_(threshold),
count_(0) {
}
uint8_t update(int value) {
int result = 0;
count_ += value;
while (count_ <= -threshold_) {
--result;
count_ += threshold_;
}
while (count_ >= threshold_) {
++result;
count_ -= threshold_;
}
return static_cast<uint8_t>(result);
}
void reset(void) {
count_ = 0;
}
private:
int threshold_;
int count_;
};
mouse_key_handler(queue& queue) : dispatcher_client(),
queue_(queue),
active_(false),
x_count_converter_(128),
y_count_converter_(128),
vertical_wheel_count_converter_(128),
horizontal_wheel_count_converter_(128),
timer_(*this) {
}
virtual ~mouse_key_handler(void) {
detach_from_dispatcher([this] {
timer_.stop();
});
}
void set_virtual_hid_keyboard_configuration(const core_configuration::details::virtual_hid_keyboard& value) {
virtual_hid_keyboard_configuration_ = value;
logger::get_logger()->info("mouse_key_xy_scale: {0}", virtual_hid_keyboard_configuration_.get_mouse_key_xy_scale());
}
void set_system_preferences_properties(const pqrs::osx::system_preferences::properties& value) {
system_preferences_properties_ = value;
}
void push_back_mouse_key(device_id device_id,
const mouse_key& mouse_key,
const std::weak_ptr<event_queue::queue>& weak_output_event_queue,
absolute_time_point time_stamp) {
erase_entry(device_id, mouse_key);
entries_.emplace_back(device_id, mouse_key);
active_ = !entries_.empty();
weak_output_event_queue_ = weak_output_event_queue;
start_timer(time_stamp);
}
void erase_mouse_key(device_id device_id,
const mouse_key& mouse_key,
const std::weak_ptr<event_queue::queue>& weak_output_event_queue,
absolute_time_point time_stamp) {
erase_entry(device_id, mouse_key);
weak_output_event_queue_ = weak_output_event_queue;
start_timer(time_stamp);
}
void erase_mouse_keys_by_device_id(device_id device_id,
absolute_time_point time_stamp) {
entries_.erase(std::remove_if(std::begin(entries_),
std::end(entries_),
[&](const auto& pair) {
return pair.first == device_id;
}),
std::end(entries_));
active_ = !entries_.empty();
start_timer(time_stamp);
}
bool active(void) const {
return active_;
}
private:
void erase_entry(device_id device_id,
const mouse_key& mouse_key) {
entries_.erase(std::remove_if(std::begin(entries_),
std::end(entries_),
[&](const auto& pair) {
return pair.first == device_id &&
pair.second == mouse_key;
}),
std::end(entries_));
active_ = !entries_.empty();
}
void start_timer(absolute_time_point time_stamp) {
timer_.start(
[this, time_stamp] {
absolute_time_point t = time_stamp;
if (post_event(t)) {
t += pqrs::osx::chrono::make_absolute_time_duration(std::chrono::milliseconds(20));
krbn_notification_center::get_instance().enqueue_input_event_arrived(*this);
} else {
timer_.stop();
}
},
std::chrono::milliseconds(20));
}
bool post_event(absolute_time_point time_stamp) {
if (auto oeq = weak_output_event_queue_.lock()) {
mouse_key total;
for (const auto& pair : entries_) {
total += pair.second;
}
if (!system_preferences_properties_.get_scroll_direction_is_natural()) {
total.invert_wheel();
}
if (total.is_zero()) {
last_mouse_key_total_ = std::nullopt;
return false;
} else {
if (last_mouse_key_total_ != total) {
last_mouse_key_total_ = total;
x_count_converter_.reset();
y_count_converter_.reset();
vertical_wheel_count_converter_.reset();
horizontal_wheel_count_converter_.reset();
}
double xy_scale = static_cast<double>(virtual_hid_keyboard_configuration_.get_mouse_key_xy_scale()) / 100.0;
pqrs::karabiner_virtual_hid_device::hid_report::pointing_input report;
report.buttons = oeq->get_pointing_button_manager().make_hid_report_buttons();
report.x = x_count_converter_.update(static_cast<int>(total.get_x() * total.get_speed_multiplier() * xy_scale));
report.y = y_count_converter_.update(static_cast<int>(total.get_y() * total.get_speed_multiplier() * xy_scale));
report.vertical_wheel = vertical_wheel_count_converter_.update(static_cast<int>(total.get_vertical_wheel() * total.get_speed_multiplier()));
report.horizontal_wheel = horizontal_wheel_count_converter_.update(static_cast<int>(total.get_horizontal_wheel() * total.get_speed_multiplier()));
queue_.emplace_back_pointing_input(report,
event_type::single,
time_stamp);
return true;
}
}
return false;
}
queue& queue_;
core_configuration::details::virtual_hid_keyboard virtual_hid_keyboard_configuration_;
pqrs::osx::system_preferences::properties system_preferences_properties_;
std::vector<std::pair<device_id, mouse_key>> entries_;
std::atomic<bool> active_;
std::weak_ptr<event_queue::queue> weak_output_event_queue_;
std::optional<mouse_key> last_mouse_key_total_;
count_converter x_count_converter_;
count_converter y_count_converter_;
count_converter vertical_wheel_count_converter_;
count_converter horizontal_wheel_count_converter_;
pqrs::dispatcher::extra::timer timer_;
};
} // namespace post_event_to_virtual_devices
} // namespace manipulators
} // namespace manipulator
} // namespace krbn
<commit_msg>suppress log message<commit_after>#pragma once
#include "queue.hpp"
#include <pqrs/osx/system_preferences.hpp>
namespace krbn {
namespace manipulator {
namespace manipulators {
namespace post_event_to_virtual_devices {
class mouse_key_handler final : public pqrs::dispatcher::extra::dispatcher_client {
public:
class count_converter final {
public:
count_converter(int threshold) : threshold_(threshold),
count_(0) {
}
uint8_t update(int value) {
int result = 0;
count_ += value;
while (count_ <= -threshold_) {
--result;
count_ += threshold_;
}
while (count_ >= threshold_) {
++result;
count_ -= threshold_;
}
return static_cast<uint8_t>(result);
}
void reset(void) {
count_ = 0;
}
private:
int threshold_;
int count_;
};
mouse_key_handler(queue& queue) : dispatcher_client(),
queue_(queue),
active_(false),
x_count_converter_(128),
y_count_converter_(128),
vertical_wheel_count_converter_(128),
horizontal_wheel_count_converter_(128),
timer_(*this) {
}
virtual ~mouse_key_handler(void) {
detach_from_dispatcher([this] {
timer_.stop();
});
}
void set_virtual_hid_keyboard_configuration(const core_configuration::details::virtual_hid_keyboard& value) {
virtual_hid_keyboard_configuration_ = value;
}
void set_system_preferences_properties(const pqrs::osx::system_preferences::properties& value) {
system_preferences_properties_ = value;
}
void push_back_mouse_key(device_id device_id,
const mouse_key& mouse_key,
const std::weak_ptr<event_queue::queue>& weak_output_event_queue,
absolute_time_point time_stamp) {
erase_entry(device_id, mouse_key);
entries_.emplace_back(device_id, mouse_key);
active_ = !entries_.empty();
weak_output_event_queue_ = weak_output_event_queue;
start_timer(time_stamp);
}
void erase_mouse_key(device_id device_id,
const mouse_key& mouse_key,
const std::weak_ptr<event_queue::queue>& weak_output_event_queue,
absolute_time_point time_stamp) {
erase_entry(device_id, mouse_key);
weak_output_event_queue_ = weak_output_event_queue;
start_timer(time_stamp);
}
void erase_mouse_keys_by_device_id(device_id device_id,
absolute_time_point time_stamp) {
entries_.erase(std::remove_if(std::begin(entries_),
std::end(entries_),
[&](const auto& pair) {
return pair.first == device_id;
}),
std::end(entries_));
active_ = !entries_.empty();
start_timer(time_stamp);
}
bool active(void) const {
return active_;
}
private:
void erase_entry(device_id device_id,
const mouse_key& mouse_key) {
entries_.erase(std::remove_if(std::begin(entries_),
std::end(entries_),
[&](const auto& pair) {
return pair.first == device_id &&
pair.second == mouse_key;
}),
std::end(entries_));
active_ = !entries_.empty();
}
void start_timer(absolute_time_point time_stamp) {
timer_.start(
[this, time_stamp] {
absolute_time_point t = time_stamp;
if (post_event(t)) {
t += pqrs::osx::chrono::make_absolute_time_duration(std::chrono::milliseconds(20));
krbn_notification_center::get_instance().enqueue_input_event_arrived(*this);
} else {
timer_.stop();
}
},
std::chrono::milliseconds(20));
}
bool post_event(absolute_time_point time_stamp) {
if (auto oeq = weak_output_event_queue_.lock()) {
mouse_key total;
for (const auto& pair : entries_) {
total += pair.second;
}
if (!system_preferences_properties_.get_scroll_direction_is_natural()) {
total.invert_wheel();
}
if (total.is_zero()) {
last_mouse_key_total_ = std::nullopt;
return false;
} else {
if (last_mouse_key_total_ != total) {
last_mouse_key_total_ = total;
x_count_converter_.reset();
y_count_converter_.reset();
vertical_wheel_count_converter_.reset();
horizontal_wheel_count_converter_.reset();
}
double xy_scale = static_cast<double>(virtual_hid_keyboard_configuration_.get_mouse_key_xy_scale()) / 100.0;
pqrs::karabiner_virtual_hid_device::hid_report::pointing_input report;
report.buttons = oeq->get_pointing_button_manager().make_hid_report_buttons();
report.x = x_count_converter_.update(static_cast<int>(total.get_x() * total.get_speed_multiplier() * xy_scale));
report.y = y_count_converter_.update(static_cast<int>(total.get_y() * total.get_speed_multiplier() * xy_scale));
report.vertical_wheel = vertical_wheel_count_converter_.update(static_cast<int>(total.get_vertical_wheel() * total.get_speed_multiplier()));
report.horizontal_wheel = horizontal_wheel_count_converter_.update(static_cast<int>(total.get_horizontal_wheel() * total.get_speed_multiplier()));
queue_.emplace_back_pointing_input(report,
event_type::single,
time_stamp);
return true;
}
}
return false;
}
queue& queue_;
core_configuration::details::virtual_hid_keyboard virtual_hid_keyboard_configuration_;
pqrs::osx::system_preferences::properties system_preferences_properties_;
std::vector<std::pair<device_id, mouse_key>> entries_;
std::atomic<bool> active_;
std::weak_ptr<event_queue::queue> weak_output_event_queue_;
std::optional<mouse_key> last_mouse_key_total_;
count_converter x_count_converter_;
count_converter y_count_converter_;
count_converter vertical_wheel_count_converter_;
count_converter horizontal_wheel_count_converter_;
pqrs::dispatcher::extra::timer timer_;
};
} // namespace post_event_to_virtual_devices
} // namespace manipulators
} // namespace manipulator
} // namespace krbn
<|endoftext|> |
<commit_before>//! Libs: -lLLVM-3.1svn -lclangFrontend -lclangParse -lclangDriver -lclangSerialization -lclangSema -lclangEdit -lclangAnalysis -lclangAST -lclangLex -lclangBasic
#include <iostream>
using namespace std;
#include "PPContext.h"
using namespace clang;
int main(int argc, char* argv[])
{
if (argc != 2) {
cerr << "No filename given" << endl;
return EXIT_FAILURE;
}
// Create Preprocessor object
PPContext context;
// Add input file
const FileEntry* File = context.fm.getFile(argv[1]);
if (!File) {
cerr << "Failed to open \'" << argv[1] << "\'";
return EXIT_FAILURE;
}
context.sm.createMainFileID(File);
context.pp.EnterMainSourceFile();
// Parse it
Token Tok;
do {
context.pp.Lex(Tok);
if (context.diagsEngine.hasErrorOccurred())
break;
context.pp.DumpToken(Tok);
cerr << endl;
} while (Tok.isNot(tok::eof));
return EXIT_SUCCESS;
}
<commit_msg>Fix assertion in TextDiagnosticPrinter<commit_after>//! Libs: -lLLVM-3.1svn -lclangFrontend -lclangParse -lclangDriver -lclangSerialization -lclangSema -lclangEdit -lclangAnalysis -lclangAST -lclangLex -lclangBasic
#include <iostream>
using namespace std;
#include "PPContext.h"
using namespace clang;
int main(int argc, char* argv[])
{
if (argc != 2) {
cerr << "No filename given" << endl;
return EXIT_FAILURE;
}
// Create Preprocessor object
PPContext context;
// Add input file
const FileEntry* File = context.fm.getFile(argv[1]);
if (!File) {
cerr << "Failed to open \'" << argv[1] << "\'";
return EXIT_FAILURE;
}
context.sm.createMainFileID(File);
context.pp.EnterMainSourceFile();
context.diagClient->BeginSourceFile(context.opts, &context.pp);
// Parse it
Token Tok;
do {
context.pp.Lex(Tok);
if (context.diagsEngine.hasErrorOccurred())
break;
context.pp.DumpToken(Tok);
cerr << endl;
} while (Tok.isNot(tok::eof));
context.diagClient->EndSourceFile();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "AnimSymLoader.h"
#include "FilepathHelper.h"
#include "EasyAnimLoader.h"
#include "SpineAnimLoader.h"
#include <sprite2/AnimSymbol.h>
#include <json/json.h>
#include <fstream>
namespace gum
{
AnimSymLoader::AnimSymLoader(s2::AnimSymbol* sym,
const SymbolLoader* sym_loader,
const SpriteLoader* spr_loader)
: m_sym(sym)
, m_spr_loader(spr_loader)
, m_sym_loader(sym_loader)
{
if (m_sym) {
m_sym->AddReference();
}
}
AnimSymLoader::~AnimSymLoader()
{
if (m_sym) {
m_sym->RemoveReference();
}
}
void AnimSymLoader::LoadJson(const std::string& filepath)
{
if (!m_sym) {
return;
}
std::string dir = FilepathHelper::Dir(filepath);
Json::Value val;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, val);
fin.close();
if (val.isMember("skeleton") && val["skeleton"].isMember("spine")) {
SpineAnimLoader loader(m_sym, m_sym_loader, m_spr_loader);
loader.LoadJson(val, dir, filepath);
} else {
EasyAnimLoader loader(m_sym, m_spr_loader);
loader.LoadJson(val, dir);
}
m_sym->LoadCopy();
}
void AnimSymLoader::LoadBin(const simp::NodeAnimation* node)
{
EasyAnimLoader loader(m_sym, m_spr_loader);
loader.LoadBin(node);
}
}<commit_msg>up s2 anim<commit_after>#include "AnimSymLoader.h"
#include "FilepathHelper.h"
#include "EasyAnimLoader.h"
#include "SpineAnimLoader.h"
#include <sprite2/AnimSymbol.h>
#include <json/json.h>
#include <fstream>
namespace gum
{
AnimSymLoader::AnimSymLoader(s2::AnimSymbol* sym,
const SymbolLoader* sym_loader,
const SpriteLoader* spr_loader)
: m_sym(sym)
, m_spr_loader(spr_loader)
, m_sym_loader(sym_loader)
{
if (m_sym) {
m_sym->AddReference();
}
}
AnimSymLoader::~AnimSymLoader()
{
if (m_sym) {
m_sym->RemoveReference();
}
}
void AnimSymLoader::LoadJson(const std::string& filepath)
{
if (!m_sym) {
return;
}
std::string dir = FilepathHelper::Dir(filepath);
Json::Value val;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, val);
fin.close();
if (val.isMember("skeleton") && val["skeleton"].isMember("spine")) {
SpineAnimLoader loader(m_sym, m_sym_loader, m_spr_loader);
loader.LoadJson(val, dir, filepath);
} else {
EasyAnimLoader loader(m_sym, m_spr_loader);
loader.LoadJson(val, dir);
}
m_sym->LoadCopy();
}
void AnimSymLoader::LoadBin(const simp::NodeAnimation* node)
{
EasyAnimLoader loader(m_sym, m_spr_loader);
loader.LoadBin(node);
m_sym->LoadCopy();
}
}<|endoftext|> |
<commit_before>#include "AnimSymLoader.h"
#include "FilepathHelper.h"
#include "EasyAnimLoader.h"
#include "SpineAnimLoader.h"
#include <sprite2/AnimSymbol.h>
#include <json/json.h>
#include <fstream>
namespace gum
{
AnimSymLoader::AnimSymLoader(s2::AnimSymbol* sym,
const SymbolLoader* sym_loader,
const SpriteLoader* spr_loader)
: m_sym(sym)
, m_spr_loader(spr_loader)
, m_sym_loader(sym_loader)
{
if (m_sym) {
m_sym->AddReference();
}
}
AnimSymLoader::~AnimSymLoader()
{
if (m_sym) {
m_sym->RemoveReference();
}
}
void AnimSymLoader::LoadJson(const std::string& filepath)
{
if (!m_sym) {
return;
}
std::string dir = FilepathHelper::Dir(filepath);
Json::Value val;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, val);
fin.close();
if (val.isMember("skeleton") && val["skeleton"].isMember("spine")) {
SpineAnimLoader loader(m_sym, m_sym_loader, m_spr_loader);
loader.LoadJson(val, dir, filepath);
} else {
EasyAnimLoader loader(m_sym, m_spr_loader);
loader.LoadJson(val, dir);
}
}
void AnimSymLoader::LoadBin(const simp::NodeAnimation* node)
{
EasyAnimLoader loader(m_sym, m_spr_loader);
loader.LoadBin(node);
}
}<commit_msg>up s2 anim<commit_after>#include "AnimSymLoader.h"
#include "FilepathHelper.h"
#include "EasyAnimLoader.h"
#include "SpineAnimLoader.h"
#include <sprite2/AnimSymbol.h>
#include <json/json.h>
#include <fstream>
namespace gum
{
AnimSymLoader::AnimSymLoader(s2::AnimSymbol* sym,
const SymbolLoader* sym_loader,
const SpriteLoader* spr_loader)
: m_sym(sym)
, m_spr_loader(spr_loader)
, m_sym_loader(sym_loader)
{
if (m_sym) {
m_sym->AddReference();
}
}
AnimSymLoader::~AnimSymLoader()
{
if (m_sym) {
m_sym->RemoveReference();
}
}
void AnimSymLoader::LoadJson(const std::string& filepath)
{
if (!m_sym) {
return;
}
std::string dir = FilepathHelper::Dir(filepath);
Json::Value val;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, val);
fin.close();
if (val.isMember("skeleton") && val["skeleton"].isMember("spine")) {
SpineAnimLoader loader(m_sym, m_sym_loader, m_spr_loader);
loader.LoadJson(val, dir, filepath);
} else {
EasyAnimLoader loader(m_sym, m_spr_loader);
loader.LoadJson(val, dir);
}
m_sym->LoadCopy();
}
void AnimSymLoader::LoadBin(const simp::NodeAnimation* node)
{
EasyAnimLoader loader(m_sym, m_spr_loader);
loader.LoadBin(node);
}
}<|endoftext|> |
<commit_before>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the chemkit project nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/
#include "fragmenttest.h"
#include <algorithm>
#include <chemkit/fragment.h>
#include <chemkit/molecule.h>
void FragmentTest::basic()
{
chemkit::Molecule waters;
chemkit::Atom *O1 = waters.addAtom("O");
chemkit::Atom *H2 = waters.addAtom("H");
chemkit::Atom *H3 = waters.addAtom("H");
chemkit::Atom *O4 = waters.addAtom("O");
chemkit::Atom *H5 = waters.addAtom("H");
chemkit::Atom *H6 = waters.addAtom("H");
waters.addBond(O1, H2);
waters.addBond(O1, H3);
waters.addBond(O4, H5);
waters.addBond(O4, H6);
QCOMPARE(waters.fragmentCount(), 2);
}
void FragmentTest::molecule()
{
chemkit::Molecule molecule;
chemkit::Atom *atom = molecule.addAtom("H");
const chemkit::Fragment *fragment = atom->fragment();
QVERIFY(fragment->molecule() == &molecule);
}
void FragmentTest::atoms()
{
chemkit::Molecule molecule;
chemkit::Atom *C1 = molecule.addAtom("C");
chemkit::Atom *C2 = molecule.addAtom("C");
chemkit::Atom *C3 = molecule.addAtom("C");
molecule.addBond(C1, C2);
const std::vector<chemkit::Atom *> C1_atoms = C1->fragment()->atoms();
QCOMPARE(C1->fragment()->atomCount(), 2);
QCOMPARE(C1_atoms.size(), 2UL);
QVERIFY(std::find(C1_atoms.begin(), C1_atoms.end(), C1) != C1_atoms.end());
QVERIFY(std::find(C1_atoms.begin(), C1_atoms.end(), C2) != C1_atoms.end());
QVERIFY(std::find(C1_atoms.begin(), C1_atoms.end(), C3) == C1_atoms.end());
const std::vector<chemkit::Atom *> C3_atoms = C3->fragment()->atoms();
QCOMPARE(C3->fragment()->atomCount(), 1);
QCOMPARE(C3_atoms.size(), 1UL);
QVERIFY(std::find(C3_atoms.begin(), C3_atoms.end(), C1) == C3_atoms.end());
QVERIFY(std::find(C3_atoms.begin(), C3_atoms.end(), C2) == C3_atoms.end());
QVERIFY(std::find(C3_atoms.begin(), C3_atoms.end(), C3) != C3_atoms.end());
}
void FragmentTest::contains()
{
chemkit::Molecule molecule;
chemkit::Atom *C1 = molecule.addAtom("C");
chemkit::Atom *C2 = molecule.addAtom("C");
chemkit::Atom *C3 = molecule.addAtom("C");
QCOMPARE(C1->fragment()->contains(C1), true);
QCOMPARE(C2->fragment()->contains(C1), false);
QCOMPARE(C3->fragment()->contains(C3), true);
molecule.addBond(C1, C2);
QCOMPARE(C1->fragment()->contains(C1), true);
QCOMPARE(C1->fragment()->contains(C2), true);
QCOMPARE(C1->fragment()->contains(C3), false);
QCOMPARE(C3->fragment()->contains(C1), false);
QCOMPARE(C3->fragment()->contains(C2), false);
QCOMPARE(C3->fragment()->contains(C3), true);
}
void FragmentTest::bonds()
{
chemkit::Molecule molecule;
chemkit::Atom *C1 = molecule.addAtom("C");
chemkit::Atom *C2 = molecule.addAtom("C");
chemkit::Atom *C3 = molecule.addAtom("C");
chemkit::Bond *C1_C2 = molecule.addBond(C1, C2);
QCOMPARE(C1->fragment()->bondCount(), 1);
const std::vector<chemkit::Bond *> &C1_bonds = C1->fragment()->bonds();
QVERIFY(std::find(C1_bonds.begin(), C1_bonds.end(), C1_C2) != C1_bonds.end());
chemkit::Bond *C2_C3 = molecule.addBond(C2, C3);
QCOMPARE(C2->fragment()->bondCount(), 2);
const std::vector<chemkit::Bond *> &C2_bonds = C2->fragment()->bonds();
QVERIFY(std::find(C2_bonds.begin(), C2_bonds.end(), C2_C3) != C2_bonds.end());
}
QTEST_APPLESS_MAIN(FragmentTest)
<commit_msg>Fix compilation error in FragmentTest<commit_after>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the chemkit project nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/
#include "fragmenttest.h"
#include <algorithm>
#include <chemkit/fragment.h>
#include <chemkit/molecule.h>
void FragmentTest::basic()
{
chemkit::Molecule waters;
chemkit::Atom *O1 = waters.addAtom("O");
chemkit::Atom *H2 = waters.addAtom("H");
chemkit::Atom *H3 = waters.addAtom("H");
chemkit::Atom *O4 = waters.addAtom("O");
chemkit::Atom *H5 = waters.addAtom("H");
chemkit::Atom *H6 = waters.addAtom("H");
waters.addBond(O1, H2);
waters.addBond(O1, H3);
waters.addBond(O4, H5);
waters.addBond(O4, H6);
QCOMPARE(waters.fragmentCount(), 2);
}
void FragmentTest::molecule()
{
chemkit::Molecule molecule;
chemkit::Atom *atom = molecule.addAtom("H");
const chemkit::Fragment *fragment = atom->fragment();
QVERIFY(fragment->molecule() == &molecule);
}
void FragmentTest::atoms()
{
chemkit::Molecule molecule;
chemkit::Atom *C1 = molecule.addAtom("C");
chemkit::Atom *C2 = molecule.addAtom("C");
chemkit::Atom *C3 = molecule.addAtom("C");
molecule.addBond(C1, C2);
const std::vector<chemkit::Atom *> C1_atoms = C1->fragment()->atoms();
QCOMPARE(C1->fragment()->atomCount(), 2);
QCOMPARE(C1_atoms.size(), size_t(2));
QVERIFY(std::find(C1_atoms.begin(), C1_atoms.end(), C1) != C1_atoms.end());
QVERIFY(std::find(C1_atoms.begin(), C1_atoms.end(), C2) != C1_atoms.end());
QVERIFY(std::find(C1_atoms.begin(), C1_atoms.end(), C3) == C1_atoms.end());
const std::vector<chemkit::Atom *> C3_atoms = C3->fragment()->atoms();
QCOMPARE(C3->fragment()->atomCount(), 1);
QCOMPARE(C3_atoms.size(), size_t(1));
QVERIFY(std::find(C3_atoms.begin(), C3_atoms.end(), C1) == C3_atoms.end());
QVERIFY(std::find(C3_atoms.begin(), C3_atoms.end(), C2) == C3_atoms.end());
QVERIFY(std::find(C3_atoms.begin(), C3_atoms.end(), C3) != C3_atoms.end());
}
void FragmentTest::contains()
{
chemkit::Molecule molecule;
chemkit::Atom *C1 = molecule.addAtom("C");
chemkit::Atom *C2 = molecule.addAtom("C");
chemkit::Atom *C3 = molecule.addAtom("C");
QCOMPARE(C1->fragment()->contains(C1), true);
QCOMPARE(C2->fragment()->contains(C1), false);
QCOMPARE(C3->fragment()->contains(C3), true);
molecule.addBond(C1, C2);
QCOMPARE(C1->fragment()->contains(C1), true);
QCOMPARE(C1->fragment()->contains(C2), true);
QCOMPARE(C1->fragment()->contains(C3), false);
QCOMPARE(C3->fragment()->contains(C1), false);
QCOMPARE(C3->fragment()->contains(C2), false);
QCOMPARE(C3->fragment()->contains(C3), true);
}
void FragmentTest::bonds()
{
chemkit::Molecule molecule;
chemkit::Atom *C1 = molecule.addAtom("C");
chemkit::Atom *C2 = molecule.addAtom("C");
chemkit::Atom *C3 = molecule.addAtom("C");
chemkit::Bond *C1_C2 = molecule.addBond(C1, C2);
QCOMPARE(C1->fragment()->bondCount(), 1);
const std::vector<chemkit::Bond *> &C1_bonds = C1->fragment()->bonds();
QVERIFY(std::find(C1_bonds.begin(), C1_bonds.end(), C1_C2) != C1_bonds.end());
chemkit::Bond *C2_C3 = molecule.addBond(C2, C3);
QCOMPARE(C2->fragment()->bondCount(), 2);
const std::vector<chemkit::Bond *> &C2_bonds = C2->fragment()->bonds();
QVERIFY(std::find(C2_bonds.begin(), C2_bonds.end(), C2_C3) != C2_bonds.end());
}
QTEST_APPLESS_MAIN(FragmentTest)
<|endoftext|> |
<commit_before>// $Id$
//
// Test Suite for geos::noding::SegmentNode class.
#include <tut.hpp>
// geos
#include <geos/noding/SegmentNode.h>
#include <geos/noding/NodedSegmentString.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/CoordinateArraySequenceFactory.h>
// std
#include <memory>
namespace tut
{
//
// Test Group
//
// Common data used by all tests
struct test_segmentnode_data
{
typedef std::auto_ptr<geos::geom::CoordinateSequence>
CoordSeqPtr;
typedef std::auto_ptr<geos::noding::SegmentString>
SegmentStringPtr;
const geos::geom::CoordinateSequenceFactory* factory_;
test_segmentnode_data()
: factory_(geos::geom::CoordinateArraySequenceFactory::instance())
{}
};
typedef test_group<test_segmentnode_data> group;
typedef group::object object;
group test_segmentnode_group("geos::noding::SegmentNode");
//
// Test Cases
//
// Test of overriden constructor
template<>
template<>
void object::test<1>()
{
using geos::geom::Coordinate;
using geos::noding::NodedSegmentString;
using geos::noding::SegmentNode;
// Create coordinates sequence
const size_t coords_size = 2;
CoordSeqPtr cs( factory_->create(0, coords_size) );
ensure( 0 != cs.get() );
Coordinate c0(0, 0);
Coordinate c1(3, 3);
cs->add(c0);
cs->add(c1);
ensure_equals( cs->size(), coords_size );
// Create SegmentString instance
NodedSegmentString segment(cs.get(), 0);
ensure_equals( segment.size(), coords_size );
// Construct a node on the given NodedSegmentString
{
const size_t segment_index = 0;
SegmentNode node( segment, Coordinate(3,3), segment_index,
segment.getSegmentOctant(segment_index) );
ensure_equals( node.segmentIndex, segment_index );
// only first endpoint is considered interior
ensure( node.isInterior() );
//
// TODO - mloskot
// 1. What's the purpose of isEndPoint() and how to test it?
// 2. Add new test cases
//
}
}
template<>
template<>
void object::test<2>()
{
using geos::geom::Coordinate;
using geos::noding::NodedSegmentString;
using geos::noding::SegmentNode;
// Create coordinates sequence
const size_t coords_size = 2;
CoordSeqPtr cs( factory_->create(0, coords_size) );
ensure( 0 != cs.get() );
Coordinate c0(0, 0);
Coordinate c1(3, 3);
cs->add(c0);
cs->add(c1);
ensure_equals( cs->size(), coords_size );
// Create SegmentString instance
NodedSegmentString segment(cs.get(), 0);
ensure_equals( segment.size(), coords_size );
// Construct an interior node on the given NodedSegmentString
{
const size_t segment_index = 0;
SegmentNode node( segment, Coordinate(0,0), segment_index,
segment.getSegmentOctant(segment_index) );
ensure_equals( node.segmentIndex, segment_index );
// on first endpoint ...
ensure( ! node.isInterior() );
}
}
template<>
template<>
void object::test<3>()
{
using geos::geom::Coordinate;
using geos::noding::NodedSegmentString;
using geos::noding::SegmentNode;
// Create coordinates sequence
const size_t coords_size = 2;
CoordSeqPtr cs( factory_->create(0, coords_size) );
ensure( 0 != cs.get() );
Coordinate c0(0, 0);
Coordinate c1(3, 3);
cs->add(c0);
cs->add(c1);
ensure_equals( cs->size(), coords_size );
// Create SegmentString instance
NodedSegmentString segment(cs.get(), 0);
ensure_equals( segment.size(), coords_size );
// Construct an interior node on the given NodedSegmentString
{
const size_t segment_index = 0;
SegmentNode node( segment, Coordinate(2,2), segment_index,
segment.getSegmentOctant(segment_index) );
ensure_equals( node.segmentIndex, segment_index );
// on first endpoint ...
ensure( node.isInterior() );
}
}
template<>
template<>
void object::test<4>()
{
using geos::geom::Coordinate;
using geos::noding::NodedSegmentString;
using geos::noding::SegmentNode;
// Create coordinates sequence
const size_t coords_size = 2;
CoordSeqPtr cs( factory_->create(0, coords_size) );
ensure( 0 != cs.get() );
Coordinate c0(0, 0);
Coordinate c1(3, 3);
cs->add(c0);
cs->add(c1);
ensure_equals( cs->size(), coords_size );
// Create SegmentString instance
NodedSegmentString segment(cs.get(), 0);
ensure_equals( segment.size(), coords_size );
// Construct a node that doesn't even intersect !!
{
const size_t segment_index = 0;
SegmentNode node( segment, Coordinate(1,2), segment_index,
segment.getSegmentOctant(segment_index) );
ensure_equals( node.segmentIndex, segment_index );
// on first endpoint ...
ensure( node.isInterior() );
}
}
} // namespace tut
<commit_msg>disamiguate create args (#345)<commit_after>// $Id$
//
// Test Suite for geos::noding::SegmentNode class.
#include <tut.hpp>
// geos
#include <geos/noding/SegmentNode.h>
#include <geos/noding/NodedSegmentString.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/CoordinateArraySequenceFactory.h>
// std
#include <memory>
namespace tut
{
//
// Test Group
//
// Common data used by all tests
struct test_segmentnode_data
{
typedef std::auto_ptr<geos::geom::CoordinateSequence>
CoordSeqPtr;
typedef std::auto_ptr<geos::noding::SegmentString>
SegmentStringPtr;
const geos::geom::CoordinateSequenceFactory* factory_;
test_segmentnode_data()
: factory_(geos::geom::CoordinateArraySequenceFactory::instance())
{}
};
typedef test_group<test_segmentnode_data> group;
typedef group::object object;
group test_segmentnode_group("geos::noding::SegmentNode");
//
// Test Cases
//
// Test of overriden constructor
template<>
template<>
void object::test<1>()
{
using geos::geom::Coordinate;
using geos::noding::NodedSegmentString;
using geos::noding::SegmentNode;
// Create coordinates sequence
const size_t coords_size = 2;
CoordSeqPtr cs( factory_->create((size_t)0, coords_size) );
ensure( 0 != cs.get() );
Coordinate c0(0, 0);
Coordinate c1(3, 3);
cs->add(c0);
cs->add(c1);
ensure_equals( cs->size(), coords_size );
// Create SegmentString instance
NodedSegmentString segment(cs.get(), 0);
ensure_equals( segment.size(), coords_size );
// Construct a node on the given NodedSegmentString
{
const size_t segment_index = 0;
SegmentNode node( segment, Coordinate(3,3), segment_index,
segment.getSegmentOctant(segment_index) );
ensure_equals( node.segmentIndex, segment_index );
// only first endpoint is considered interior
ensure( node.isInterior() );
//
// TODO - mloskot
// 1. What's the purpose of isEndPoint() and how to test it?
// 2. Add new test cases
//
}
}
template<>
template<>
void object::test<2>()
{
using geos::geom::Coordinate;
using geos::noding::NodedSegmentString;
using geos::noding::SegmentNode;
// Create coordinates sequence
const size_t coords_size = 2;
CoordSeqPtr cs( factory_->create((size_t)0, coords_size) );
ensure( 0 != cs.get() );
Coordinate c0(0, 0);
Coordinate c1(3, 3);
cs->add(c0);
cs->add(c1);
ensure_equals( cs->size(), coords_size );
// Create SegmentString instance
NodedSegmentString segment(cs.get(), 0);
ensure_equals( segment.size(), coords_size );
// Construct an interior node on the given NodedSegmentString
{
const size_t segment_index = 0;
SegmentNode node( segment, Coordinate(0,0), segment_index,
segment.getSegmentOctant(segment_index) );
ensure_equals( node.segmentIndex, segment_index );
// on first endpoint ...
ensure( ! node.isInterior() );
}
}
template<>
template<>
void object::test<3>()
{
using geos::geom::Coordinate;
using geos::noding::NodedSegmentString;
using geos::noding::SegmentNode;
// Create coordinates sequence
const size_t coords_size = 2;
CoordSeqPtr cs( factory_->create((size_t)0, coords_size) );
ensure( 0 != cs.get() );
Coordinate c0(0, 0);
Coordinate c1(3, 3);
cs->add(c0);
cs->add(c1);
ensure_equals( cs->size(), coords_size );
// Create SegmentString instance
NodedSegmentString segment(cs.get(), 0);
ensure_equals( segment.size(), coords_size );
// Construct an interior node on the given NodedSegmentString
{
const size_t segment_index = 0;
SegmentNode node( segment, Coordinate(2,2), segment_index,
segment.getSegmentOctant(segment_index) );
ensure_equals( node.segmentIndex, segment_index );
// on first endpoint ...
ensure( node.isInterior() );
}
}
template<>
template<>
void object::test<4>()
{
using geos::geom::Coordinate;
using geos::noding::NodedSegmentString;
using geos::noding::SegmentNode;
// Create coordinates sequence
const size_t coords_size = 2;
CoordSeqPtr cs( factory_->create((size_t)0, coords_size) );
ensure( 0 != cs.get() );
Coordinate c0(0, 0);
Coordinate c1(3, 3);
cs->add(c0);
cs->add(c1);
ensure_equals( cs->size(), coords_size );
// Create SegmentString instance
NodedSegmentString segment(cs.get(), 0);
ensure_equals( segment.size(), coords_size );
// Construct a node that doesn't even intersect !!
{
const size_t segment_index = 0;
SegmentNode node( segment, Coordinate(1,2), segment_index,
segment.getSegmentOctant(segment_index) );
ensure_equals( node.segmentIndex, segment_index );
// on first endpoint ...
ensure( node.isInterior() );
}
}
} // namespace tut
<|endoftext|> |
<commit_before>/*
** Author(s):
** - Chris Kilner <ckilner@aldebaran-robotics.com>
**
** Copyright (C) 2010 Aldebaran Robotics
*/
#include <qi/transport/detail/network/ip_address.hpp>
#include <boost/algorithm/string.hpp>
#ifdef _WIN32
# include <windows.h>
# include <winsock2.h>
# include <iphlpapi.h>
# include <Ws2tcpip.h>
#else
# include <arpa/inet.h>
# include <sys/socket.h>
# include <netdb.h>
# include <ifaddrs.h>
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
#endif
namespace qi {
namespace detail {
std::string getPrimaryPublicIPAddress() {
std::vector<std::string> ips = getIPAddresses();
static const std::string ipLocalHost = "127.0.0.1";
// todo: some logic to choose between good addresses
for(unsigned int i = 0; i< ips.size(); i++) {
if (ipLocalHost.compare(ips[i]) != 0) {
return ips[i];
}
}
if (ips.size() > 0) {
return ips[0];
}
return "";
}
bool isValidAddress(const std::string& userHostString,
std::pair<std::string, int>& outHostAndPort)
{
if (userHostString.empty()) {
return false;
}
std::vector<std::string> parts;
boost::split(parts, userHostString, boost::is_any_of(":"));
if (parts.empty() || parts.size() > 2) {
return false;
}
if (parts[0].empty()) {
return false;
}
outHostAndPort.first = parts[0];
if (parts.size() == 2) {
int i;
i = atoi (parts[1].c_str());
outHostAndPort.second = i;
} else {
outHostAndPort.second = 0;
parts.push_back(""); /// hmmm
}
return isValidHostAndPort(outHostAndPort.first, parts[1]);
}
bool isValidHostAndPort(const std::string& hostName, std::string& port) {
bool ret = true;
#ifdef _WIN32
WSADATA WSAData;
if(::WSAStartup(MAKEWORD(1, 0), &WSAData))
ret = false;
#endif
addrinfo req;
memset(&req, 0, sizeof(req));
req.ai_family = AF_INET;
req.ai_socktype = SOCK_STREAM;
req.ai_flags = AI_NUMERICSERV;
addrinfo *res;
if(getaddrinfo(hostName.c_str(), port.c_str(), &req, &res))
ret = false;; // lookup failed
if (res == NULL) {
ret = false;
}
freeaddrinfo(res);
#ifdef _WIN32
WSACleanup();
#endif
return ret;
}
std::vector<std::string> getIPAddresses() {
std::vector<std::string> ret;
#ifdef _WIN32
// win version
char szHostName[128] = "";
WSADATA WSAData;
if(::WSAStartup(MAKEWORD(1, 0), &WSAData))
return ret;
if(::gethostname(szHostName, sizeof(szHostName)))
return ret;
struct sockaddr_in socketAddress;
struct hostent* host = 0;
host = ::gethostbyname(szHostName);
if(!host)
return ret;
for(int i = 0; ((host->h_addr_list[i]) && (i < 10)); ++i)
{
memcpy(&socketAddress.sin_addr, host->h_addr_list[i], host->h_length);
ret.push_back(inet_ntoa(socketAddress.sin_addr));
}
WSACleanup();
#else
// linux version
struct ifaddrs *ifaddr, *ifa;
int family, s;
char host[NI_MAXHOST];
if (getifaddrs(&ifaddr) == -1)
return ret;
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL)
continue;
family = ifa->ifa_addr->sa_family;
// Don't include AF_INET6 for the moment
if (family == AF_INET) {
s = getnameinfo(ifa->ifa_addr,
(family == AF_INET) ? sizeof(struct sockaddr_in) :
sizeof(struct sockaddr_in6),
host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if (s != 0) {
break;
}
ret.push_back(host);
}
}
freeifaddrs(ifaddr);
#endif
return ret;
}
}
}
<commit_msg>ip_address ... fix segfault linux<commit_after>/*
** Author(s):
** - Chris Kilner <ckilner@aldebaran-robotics.com>
**
** Copyright (C) 2010 Aldebaran Robotics
*/
#include <qi/transport/detail/network/ip_address.hpp>
#include <boost/algorithm/string.hpp>
#ifdef _WIN32
# include <windows.h>
# include <winsock2.h>
# include <iphlpapi.h>
# include <Ws2tcpip.h>
#else
# include <arpa/inet.h>
# include <sys/socket.h>
# include <netdb.h>
# include <ifaddrs.h>
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
#endif
namespace qi {
namespace detail {
std::string getPrimaryPublicIPAddress() {
std::vector<std::string> ips = getIPAddresses();
static const std::string ipLocalHost = "127.0.0.1";
// todo: some logic to choose between good addresses
for(unsigned int i = 0; i< ips.size(); i++) {
if (ipLocalHost.compare(ips[i]) != 0) {
return ips[i];
}
}
if (ips.size() > 0) {
return ips[0];
}
return "";
}
bool isValidAddress(const std::string& userHostString,
std::pair<std::string, int>& outHostAndPort)
{
if (userHostString.empty()) {
return false;
}
std::vector<std::string> parts;
boost::split(parts, userHostString, boost::is_any_of(":"));
if (parts.empty() || parts.size() > 2) {
return false;
}
if (parts[0].empty()) {
return false;
}
outHostAndPort.first = parts[0];
if (parts.size() == 2) {
int i;
i = atoi (parts[1].c_str());
outHostAndPort.second = i;
} else {
outHostAndPort.second = 0;
parts.push_back(""); /// hmmm
}
return isValidHostAndPort(outHostAndPort.first, parts[1]);
}
bool isValidHostAndPort(const std::string& hostName, std::string& port) {
bool ret = true;
#ifdef _WIN32
WSADATA WSAData;
if(::WSAStartup(MAKEWORD(1, 0), &WSAData))
ret = false;
#endif
addrinfo req;
memset(&req, 0, sizeof(req));
req.ai_family = AF_INET;
req.ai_socktype = SOCK_STREAM;
req.ai_flags = AI_NUMERICSERV;
addrinfo *res;
if(getaddrinfo(hostName.c_str(), port.c_str(), &req, &res)) {
ret = false; // lookup failed
} else {
if (res == NULL) {
ret = false;
} else {
freeaddrinfo(res);
}
}
#ifdef _WIN32
WSACleanup();
#endif
return ret;
}
std::vector<std::string> getIPAddresses() {
std::vector<std::string> ret;
#ifdef _WIN32
// win version
char szHostName[128] = "";
WSADATA WSAData;
if(::WSAStartup(MAKEWORD(1, 0), &WSAData))
return ret;
if(::gethostname(szHostName, sizeof(szHostName)))
return ret;
struct sockaddr_in socketAddress;
struct hostent* host = 0;
host = ::gethostbyname(szHostName);
if(!host)
return ret;
for(int i = 0; ((host->h_addr_list[i]) && (i < 10)); ++i)
{
memcpy(&socketAddress.sin_addr, host->h_addr_list[i], host->h_length);
ret.push_back(inet_ntoa(socketAddress.sin_addr));
}
WSACleanup();
#else
// linux version
struct ifaddrs *ifaddr, *ifa;
int family, s;
char host[NI_MAXHOST];
if (getifaddrs(&ifaddr) == -1)
return ret;
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL)
continue;
family = ifa->ifa_addr->sa_family;
// Don't include AF_INET6 for the moment
if (family == AF_INET) {
s = getnameinfo(ifa->ifa_addr,
(family == AF_INET) ? sizeof(struct sockaddr_in) :
sizeof(struct sockaddr_in6),
host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if (s != 0) {
break;
}
ret.push_back(host);
}
}
freeifaddrs(ifaddr);
#endif
return ret;
}
}
}
<|endoftext|> |
<commit_before>#include "display.hh"
Display::Display(){
for(int i=0;i<NUMBER_OF_PARENTWINDOW;i++){
this->freeWindows.push(i);
}
}
Display::~Display(){
}
void Display::initDisplay(bool cursset){
initscr();
raw();
keypad(stdscr, TRUE);
noecho();
curs_set(cursset);
}
WINDOW* Display::createWindow(int height,int width,int y,int x){
if(!this->freeWindows.empty()){
WINDOW * w =newwin(height,width,y,x);
parentWindows[w]=this->freeWindows.top();
return w;
}
//~
//~ WINDOW * childs[NUMBER_OF_CHILDWINDOW];
//~ windows[w];
//~
return 0;
}
//~ void deleteWindowByName(WINDOW * w){
//~ map<WINDOW*,int]>::iterator it;
//~ it = windows.find(w);
//~ windows.erase(it);
//~ delwin(w);
//~ }
//~ void refreshAllWindows(){
//~ for(map<WINDOW*,WINDOW*[NUMBER_OF_CHILDWINDOW]>::iterator it = windows.begin(); it != windows.end();++it){
//~ wrefresh(it->first);
//~ }
//~ }
//~
//~ void initDisplay(){
//~ initscr();
//~ raw();
//~ keypad(stdscr, TRUE);
//~ noecho();
//~ curs_set(FALSE);
//~ }
//~
//~ void clearAllWindows(){
//~ for(map<string,MainWindow>::iterator it = windows.begin(); it != windows.end();++it){
//~ wclear(it->second.parentWindow);
//~ }
//~ }
//~
//~ void deinitDisplay(){
//~ for(map<string,MainWindow>::iterator it = windows.begin(); it != windows.end();++it){
//~ delwin(it->second.parentWindow);
//~ windows.erase(it->first);
//~ }
//~ endwin();
//~ }
/////////////////////////////////// subWindow
WINDOW* createSubWindow(WINDOW * w, string name, int height, int width, int y, int x){
WINDOW * result = subwin(w,height,width,y,x);
return result;
}
<commit_msg>fix createWindow()<commit_after>#include "display.hh"
Display::Display(){
for(int i=0;i<NUMBER_OF_PARENTWINDOW;i++){
this->freeWindows.push(i);
}
}
Display::~Display(){
}
void Display::initDisplay(bool cursset){
initscr();
raw();
keypad(stdscr, TRUE);
noecho();
curs_set(cursset);
}
WINDOW* Display::createWindow(int height,int width,int y,int x){
if(!this->freeWindows.empty()){
WINDOW * w =newwin(height,width,y,x);
parentWindows[w]=this->freeWindows.top();
this->freeWindows.pop();
return w;
}
return 0;
}
//~ void deleteWindowByName(WINDOW * w){
//~ map<WINDOW*,int]>::iterator it;
//~ it = windows.find(w);
//~ windows.erase(it);
//~ delwin(w);
//~ }
//~ void refreshAllWindows(){
//~ for(map<WINDOW*,WINDOW*[NUMBER_OF_CHILDWINDOW]>::iterator it = windows.begin(); it != windows.end();++it){
//~ wrefresh(it->first);
//~ }
//~ }
//~
//~ void initDisplay(){
//~ initscr();
//~ raw();
//~ keypad(stdscr, TRUE);
//~ noecho();
//~ curs_set(FALSE);
//~ }
//~
//~ void clearAllWindows(){
//~ for(map<string,MainWindow>::iterator it = windows.begin(); it != windows.end();++it){
//~ wclear(it->second.parentWindow);
//~ }
//~ }
//~
//~ void deinitDisplay(){
//~ for(map<string,MainWindow>::iterator it = windows.begin(); it != windows.end();++it){
//~ delwin(it->second.parentWindow);
//~ windows.erase(it->first);
//~ }
//~ endwin();
//~ }
/////////////////////////////////// subWindow
WINDOW* createSubWindow(WINDOW * w, string name, int height, int width, int y, int x){
WINDOW * result = subwin(w,height,width,y,x);
return result;
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <vector>
#include <iterator>
#include <iostream>
#include <string>
#include "lensfun.h"
class Image {
public:
int width, height;
int channel_size;
lfPixelFormat pixel_format;
std::vector<char> data;
Image(int width, int height, lfPixelFormat pixel_format);
Image() {};
int get(int x, int y, int channel);
void set(int x, int y, int channel, int value);
};
Image::Image(int width, int height, lfPixelFormat pixel_format) :
width(width), height(height), pixel_format(pixel_format)
{
switch (pixel_format) {
case LF_PF_U8:
channel_size = 1;
break;
case LF_PF_U16:
channel_size = 2;
break;
default:
throw std::runtime_error("Invalid pixel format");
}
data.resize(width * height * channel_size * 3);
}
int Image::get(int x, int y, int channel) {
if (x < 0 || x >= width || y < 0 || y >= height)
return 0;
int position = channel_size * (3 * (y * width + x) + channel);
return int(data[position]);
}
void Image::set(int x, int y, int channel, int value) {
if (x >= 0 && x < width && y >= 0 && y < height) {
int position = channel_size * (3 * (y * width + x) + channel);
data[position] = char(value);
}
}
std::istream& operator >>(std::istream &inputStream, Image &other)
{
std::string magic_number;
int maximum_color_value;
inputStream >> magic_number;
if (magic_number != "P6")
throw std::runtime_error("Invalid input file. Must start with 'P6'.");
inputStream >> other.width >> other.height >> maximum_color_value;
inputStream.get(); // skip the trailing white space
switch (maximum_color_value) {
case 255:
other.pixel_format = LF_PF_U8;
other.channel_size = 1;
break;
case 65535:
other.pixel_format = LF_PF_U16;
other.channel_size = 2;
break;
default:
throw std::runtime_error("Invalid PPM file: Maximum color value must be 255 or 65535.");
}
size_t size = other.width * other.height * other.channel_size * 3;
other.data.resize(size);
inputStream.read(other.data.data(), size);
return inputStream;
}
std::ostream& operator <<(std::ostream &outputStream, const Image &other)
{
outputStream << "P6" << "\n"
<< other.width << " "
<< other.height << "\n"
<< (other.pixel_format == LF_PF_U8 ? "255" : "65535") << "\n";
outputStream.write(other.data.data(), other.data.size());
return outputStream;
}
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "You must give path to input file.\n";
return -1;
}
lfDatabase ldb;
if (ldb.Load() != LF_NO_ERROR) {
std::cerr << "Database could not be loaded\n";
return -1;
}
const lfCamera *camera;
const lfCamera **cameras = ldb.FindCamerasExt(NULL, "NEX-7");
if (cameras && !cameras[1])
camera = cameras[0];
else {
std::cerr << "Cannot find unique camera in database. " << sizeof(cameras) << " cameras found.\n";
lf_free(cameras);
return -1;
}
lf_free(cameras);
const lfLens *lens;
const lfLens **lenses = ldb.FindLenses(camera, NULL, "E 50mm f/1.8 OSS");
if (lenses && !lenses[1])
lens = lenses[0];
else if (!lenses[1]) {
std::cerr << "Lens name ambiguous\n";
} else {
std::cerr << "Cannot find lens in database\n";
lf_free(lenses);
return -1;
}
lf_free(lenses);
Image image;
{
std::ifstream file(argv[1], std::ios::binary);
file >> image;
}
lfModifier modifier(camera->CropFactor, image.width, image.height, image.pixel_format);
if (!modifier.EnableDistortionCorrection(lens, 50)) {
std::cerr << "Failed to activate undistortion\n";
return -1;
}
if (!modifier.EnableTCACorrection(lens, 50)) {
std::cerr << "Failed to activate un-TCA\n";
return -1;
}
if (!modifier.EnableVignettingCorrection(lens, 50, 4.0, 1000)) {
std::cerr << "Failed to activate devignetting\n";
return -1;
}
modifier.ApplyColorModification(image.data.data(), 0, 0, image.width, image.height,
LF_CR_3(RED, GREEN, BLUE), image.width * 3 * image.channel_size);
std::vector<float> res(image.width * image.height * 2 * 3);
modifier.ApplySubpixelGeometryDistortion(0, 0, image.width, image.height, res.data());
Image new_image(image.width, image.height, image.pixel_format);
for (int x = 0; x < image.width; x++)
for (int y = 0; y < image.height; y++) {
int position = 2 * 3 * (y * image.width + x);
int source_x_R = int(res[position]);
int source_y_R = int(res[position + 1]);
int source_x_G = int(res[position + 2]);
int source_y_G = int(res[position + 3]);
int source_x_B = int(res[position + 4]);
int source_y_B = int(res[position + 5]);
new_image.set(x, y, 0, image.get(source_x_R, source_y_R, 0));
new_image.set(x, y, 1, image.get(source_x_G, source_y_G, 1));
new_image.set(x, y, 2, image.get(source_x_B, source_y_B, 2));
}
std::ofstream file("out.ppm", std::ios::binary);
file << new_image;
return 0;
}
<commit_msg>Fixed check whether lens search was successful.<commit_after>#include <fstream>
#include <vector>
#include <iterator>
#include <iostream>
#include <string>
#include "lensfun.h"
class Image {
public:
int width, height;
int channel_size;
lfPixelFormat pixel_format;
std::vector<char> data;
Image(int width, int height, lfPixelFormat pixel_format);
Image() {};
int get(int x, int y, int channel);
void set(int x, int y, int channel, int value);
};
Image::Image(int width, int height, lfPixelFormat pixel_format) :
width(width), height(height), pixel_format(pixel_format)
{
switch (pixel_format) {
case LF_PF_U8:
channel_size = 1;
break;
case LF_PF_U16:
channel_size = 2;
break;
default:
throw std::runtime_error("Invalid pixel format");
}
data.resize(width * height * channel_size * 3);
}
int Image::get(int x, int y, int channel) {
if (x < 0 || x >= width || y < 0 || y >= height)
return 0;
int position = channel_size * (3 * (y * width + x) + channel);
return int(data[position]);
}
void Image::set(int x, int y, int channel, int value) {
if (x >= 0 && x < width && y >= 0 && y < height) {
int position = channel_size * (3 * (y * width + x) + channel);
data[position] = char(value);
}
}
std::istream& operator >>(std::istream &inputStream, Image &other)
{
std::string magic_number;
int maximum_color_value;
inputStream >> magic_number;
if (magic_number != "P6")
throw std::runtime_error("Invalid input file. Must start with 'P6'.");
inputStream >> other.width >> other.height >> maximum_color_value;
inputStream.get(); // skip the trailing white space
switch (maximum_color_value) {
case 255:
other.pixel_format = LF_PF_U8;
other.channel_size = 1;
break;
case 65535:
other.pixel_format = LF_PF_U16;
other.channel_size = 2;
break;
default:
throw std::runtime_error("Invalid PPM file: Maximum color value must be 255 or 65535.");
}
size_t size = other.width * other.height * other.channel_size * 3;
other.data.resize(size);
inputStream.read(other.data.data(), size);
return inputStream;
}
std::ostream& operator <<(std::ostream &outputStream, const Image &other)
{
outputStream << "P6" << "\n"
<< other.width << " "
<< other.height << "\n"
<< (other.pixel_format == LF_PF_U8 ? "255" : "65535") << "\n";
outputStream.write(other.data.data(), other.data.size());
return outputStream;
}
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "You must give path to input file.\n";
return -1;
}
lfDatabase ldb;
if (ldb.Load() != LF_NO_ERROR) {
std::cerr << "Database could not be loaded\n";
return -1;
}
const lfCamera *camera;
const lfCamera **cameras = ldb.FindCamerasExt(NULL, "NEX-7");
if (cameras && !cameras[1])
camera = cameras[0];
else {
std::cerr << "Cannot find unique camera in database. " << sizeof(cameras) << " cameras found.\n";
lf_free(cameras);
return -1;
}
lf_free(cameras);
const lfLens *lens;
const lfLens **lenses = ldb.FindLenses(camera, NULL, "E 50mm f/1.8 OSS");
if (lenses && !lenses[1]) {
lens = lenses[0];
} else if (!lenses) {
std::cerr << "Cannot find lens in database\n";
lf_free(lenses);
return -1;
} else {
std::cerr << "Lens name ambiguous\n";
}
lf_free(lenses);
Image image;
{
std::ifstream file(argv[1], std::ios::binary);
file >> image;
}
lfModifier modifier(camera->CropFactor, image.width, image.height, image.pixel_format);
if (!modifier.EnableDistortionCorrection(lens, 50)) {
std::cerr << "Failed to activate undistortion\n";
return -1;
}
if (!modifier.EnableTCACorrection(lens, 50)) {
std::cerr << "Failed to activate un-TCA\n";
return -1;
}
if (!modifier.EnableVignettingCorrection(lens, 50, 4.0, 1000)) {
std::cerr << "Failed to activate devignetting\n";
return -1;
}
modifier.ApplyColorModification(image.data.data(), 0, 0, image.width, image.height,
LF_CR_3(RED, GREEN, BLUE), image.width * 3 * image.channel_size);
std::vector<float> res(image.width * image.height * 2 * 3);
modifier.ApplySubpixelGeometryDistortion(0, 0, image.width, image.height, res.data());
Image new_image(image.width, image.height, image.pixel_format);
for (int x = 0; x < image.width; x++)
for (int y = 0; y < image.height; y++) {
int position = 2 * 3 * (y * image.width + x);
int source_x_R = int(res[position]);
int source_y_R = int(res[position + 1]);
int source_x_G = int(res[position + 2]);
int source_y_G = int(res[position + 3]);
int source_x_B = int(res[position + 4]);
int source_y_B = int(res[position + 5]);
new_image.set(x, y, 0, image.get(source_x_R, source_y_R, 0));
new_image.set(x, y, 1, image.get(source_x_G, source_y_G, 1));
new_image.set(x, y, 2, image.get(source_x_B, source_y_B, 2));
}
std::ofstream file("out.ppm", std::ios::binary);
file << new_image;
return 0;
}
<|endoftext|> |
<commit_before>#include "PrimaryTreeIndex.h"
template <typename T>
void PrimaryTreeIndex<T>::buildIndex(Table & table, int column) {
int rowno = 0;
for(auto currentRow : table) {
index.emplace(currentRow[column], rowno++);
}
}
template <typename T>
int PrimaryTreeIndex<T>::size() const {
return index.size();
}
template <typename T>
T PrimaryTreeIndex<T>::exactMatch(const std::string& key) const {
auto it = index.find(key);
return it == index.end() ? -1 : it->second;
}
template <typename T>
T PrimaryTreeIndex<T>::bestMatch(const std::string& key) const {
auto lower_bound = index.lower_bound(key);
if(lower_bound != index.end() && lower_bound->first == key) {
return lower_bound->second;
} else {
std::map<std::string,int>::const_reverse_iterator rbegin(lower_bound);
std::map<std::string,int>::const_reverse_iterator rend(index.begin());
for(auto it = rbegin; it!=rend; it++) {
auto idx = key.find(it->first);
if(idx != std::string::npos) {
return it->second;
}
}
}
return -1;
}
<commit_msg>reverse iterator T fix<commit_after>#include "PrimaryTreeIndex.h"
template <typename T>
void PrimaryTreeIndex<T>::buildIndex(Table & table, int column) {
int rowno = 0;
for(auto currentRow : table) {
index.emplace(currentRow[column], rowno++);
}
}
template <typename T>
int PrimaryTreeIndex<T>::size() const {
return index.size();
}
template <typename T>
T PrimaryTreeIndex<T>::exactMatch(const std::string& key) const {
auto it = index.find(key);
return it == index.end() ? -1 : it->second;
}
template <typename T>
T PrimaryTreeIndex<T>::bestMatch(const std::string& key) const {
auto lower_bound = index.lower_bound(key);
if(lower_bound != index.end() && lower_bound->first == key) {
return lower_bound->second;
} else {
typename std::map<std::string,T>::const_reverse_iterator rbegin(lower_bound);
typename std::map<std::string,T>::const_reverse_iterator rend(index.begin());
for(auto it = rbegin; it!=rend; it++) {
auto idx = key.find(it->first);
if(idx != std::string::npos) {
return it->second;
}
}
}
return -1;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLExportDDELinks.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: obo $ $Date: 2007-06-13 09:12:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#ifndef _SC_XMLEXPORTDDELINKS_HXX
#include "XMLExportDDELinks.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef SC_XMLEXPRT_HXX
#include "xmlexprt.hxx"
#endif
#ifndef SC_UNONAMES_HXX
#include "unonames.hxx"
#endif
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_MATRIX_HXX
#include "scmatrix.hxx"
#endif
#ifndef _COM_SUN_STAR_SHEET_XDDELINK_HPP_
#include <com/sun/star/sheet/XDDELink.hpp>
#endif
class ScMatrix;
using namespace com::sun::star;
using namespace xmloff::token;
ScXMLExportDDELinks::ScXMLExportDDELinks(ScXMLExport& rTempExport)
: rExport(rTempExport)
{
}
ScXMLExportDDELinks::~ScXMLExportDDELinks()
{
}
sal_Bool ScXMLExportDDELinks::CellsEqual(const sal_Bool bPrevEmpty, const sal_Bool bPrevString, const String& sPrevValue, const double& fPrevValue,
const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue)
{
if (bEmpty == bPrevEmpty)
if (bEmpty)
return sal_True;
else if (bString == bPrevString)
if (bString)
return (sPrevValue == sValue);
else
return (fPrevValue == fValue);
else
return sal_False;
else
return sal_False;
}
void ScXMLExportDDELinks::WriteCell(const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue, const sal_Int32 nRepeat)
{
rtl::OUStringBuffer sBuffer;
if (!bEmpty)
if (bString)
{
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_VALUE_TYPE, XML_STRING);
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_STRING_VALUE, rtl::OUString(sValue));
}
else
{
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_VALUE_TYPE, XML_FLOAT);
rExport.GetMM100UnitConverter().convertDouble(sBuffer, fValue);
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_VALUE, sBuffer.makeStringAndClear());
}
if (nRepeat > 1)
{
rExport.GetMM100UnitConverter().convertNumber(sBuffer, nRepeat);
rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_NUMBER_COLUMNS_REPEATED, sBuffer.makeStringAndClear());
}
SvXMLElementExport(rExport, XML_NAMESPACE_TABLE, XML_TABLE_CELL, sal_True, sal_True);
}
void ScXMLExportDDELinks::WriteTable(const sal_Int32 nPos)
{
const ScMatrix* pMatrix(NULL);
if (rExport.GetDocument())
pMatrix = rExport.GetDocument()->GetDdeLinkResultMatrix( static_cast<USHORT>(nPos) );
if (pMatrix)
{
SCSIZE nuCol;
SCSIZE nuRow;
pMatrix->GetDimensions( nuCol, nuRow );
sal_Int32 nRowCount = static_cast<sal_Int32>(nuRow);
sal_Int32 nColCount = static_cast<sal_Int32>(nuCol);
SvXMLElementExport aTableElem(rExport, XML_NAMESPACE_TABLE, XML_TABLE, sal_True, sal_True);
rtl::OUStringBuffer sBuffer;
if (nColCount > 1)
{
rExport.GetMM100UnitConverter().convertNumber(sBuffer, nColCount);
rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_NUMBER_COLUMNS_REPEATED, sBuffer.makeStringAndClear());
}
{
SvXMLElementExport aElemCol(rExport, XML_NAMESPACE_TABLE, XML_TABLE_COLUMN, sal_True, sal_True);
}
sal_Bool bPrevString(sal_True);
sal_Bool bPrevEmpty(sal_True);
double fPrevValue;
String sPrevValue;
sal_Int32 nRepeatColsCount(1);
for(sal_Int32 nRow = 0; nRow < nRowCount; ++nRow)
{
SvXMLElementExport aElemRow(rExport, XML_NAMESPACE_TABLE, XML_TABLE_ROW, sal_True, sal_True);
for(sal_Int32 nColumn = 0; nColumn < nColCount; ++nColumn)
{
ScMatValType nType = SC_MATVAL_VALUE;
const ScMatrixValue* pMatVal = pMatrix->Get( static_cast<SCSIZE>(nColumn), static_cast<SCSIZE>(nRow), nType );
BOOL bIsString = ScMatrix::IsStringType( nType);
if (nColumn == 0)
{
bPrevEmpty = !pMatVal;
bPrevString = bIsString;
if( bIsString )
sPrevValue = pMatVal->GetString();
else
fPrevValue = pMatVal->fVal;
}
else
{
double fValue;
String sValue;
sal_Bool bEmpty(!pMatVal);
sal_Bool bString(bIsString);
if( bIsString )
sValue = pMatVal->GetString();
else
fValue = pMatVal->fVal;
if (CellsEqual(bPrevEmpty, bPrevString, sPrevValue, fPrevValue,
bEmpty, bString, sValue, fValue))
++nRepeatColsCount;
else
{
WriteCell(bPrevEmpty, bPrevString, sPrevValue, fPrevValue, nRepeatColsCount);
nRepeatColsCount = 1;
bPrevEmpty = bEmpty;
fPrevValue = fValue;
sPrevValue = sValue;
}
}
}
WriteCell(bPrevEmpty, bPrevString, sPrevValue, fPrevValue, nRepeatColsCount);
nRepeatColsCount = 1;
}
}
}
void ScXMLExportDDELinks::WriteDDELinks(uno::Reference<sheet::XSpreadsheetDocument>& xSpreadDoc)
{
uno::Reference <beans::XPropertySet> xPropertySet (xSpreadDoc, uno::UNO_QUERY);
if (xPropertySet.is())
{
uno::Reference<container::XIndexAccess> xIndex(xPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_DDELINKS))), uno::UNO_QUERY);
if (xIndex.is())
{
sal_Int32 nCount = xIndex->getCount();
if (nCount)
{
SvXMLElementExport aElemDDEs(rExport, XML_NAMESPACE_TABLE, XML_DDE_LINKS, sal_True, sal_True);
for (sal_uInt16 nDDELink = 0; nDDELink < nCount; ++nDDELink)
{
uno::Reference<sheet::XDDELink> xDDELink(xIndex->getByIndex(nDDELink), uno::UNO_QUERY);
if (xDDELink.is())
{
SvXMLElementExport aElemDDE(rExport, XML_NAMESPACE_TABLE, XML_DDE_LINK, sal_True, sal_True);
{
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_APPLICATION, xDDELink->getApplication());
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_TOPIC, xDDELink->getTopic());
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_ITEM, xDDELink->getItem());
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_AUTOMATIC_UPDATE, XML_TRUE);
BYTE nMode;
if (rExport.GetDocument() &&
rExport.GetDocument()->GetDdeLinkMode(nDDELink, nMode))
{
switch (nMode)
{
case SC_DDE_ENGLISH :
rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_CONVERSION_MODE, XML_INTO_ENGLISH_NUMBER);
break;
case SC_DDE_TEXT :
rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_CONVERSION_MODE, XML_KEEP_TEXT);
break;
}
}
SvXMLElementExport(rExport, XML_NAMESPACE_OFFICE, XML_DDE_SOURCE, sal_True, sal_True);
}
WriteTable(nDDELink);
}
}
}
}
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.17.266); FILE MERGED 2008/04/01 15:30:26 thb 1.17.266.3: #i85898# Stripping all external header guards 2008/04/01 12:36:30 thb 1.17.266.2: #i85898# Stripping all external header guards 2008/03/31 17:14:55 rt 1.17.266.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLExportDDELinks.cxx,v $
* $Revision: 1.18 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#include "XMLExportDDELinks.hxx"
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmluconv.hxx>
#include "xmlexprt.hxx"
#include "unonames.hxx"
#include "document.hxx"
#include "scmatrix.hxx"
#include <com/sun/star/sheet/XDDELink.hpp>
class ScMatrix;
using namespace com::sun::star;
using namespace xmloff::token;
ScXMLExportDDELinks::ScXMLExportDDELinks(ScXMLExport& rTempExport)
: rExport(rTempExport)
{
}
ScXMLExportDDELinks::~ScXMLExportDDELinks()
{
}
sal_Bool ScXMLExportDDELinks::CellsEqual(const sal_Bool bPrevEmpty, const sal_Bool bPrevString, const String& sPrevValue, const double& fPrevValue,
const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue)
{
if (bEmpty == bPrevEmpty)
if (bEmpty)
return sal_True;
else if (bString == bPrevString)
if (bString)
return (sPrevValue == sValue);
else
return (fPrevValue == fValue);
else
return sal_False;
else
return sal_False;
}
void ScXMLExportDDELinks::WriteCell(const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue, const sal_Int32 nRepeat)
{
rtl::OUStringBuffer sBuffer;
if (!bEmpty)
if (bString)
{
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_VALUE_TYPE, XML_STRING);
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_STRING_VALUE, rtl::OUString(sValue));
}
else
{
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_VALUE_TYPE, XML_FLOAT);
rExport.GetMM100UnitConverter().convertDouble(sBuffer, fValue);
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_VALUE, sBuffer.makeStringAndClear());
}
if (nRepeat > 1)
{
rExport.GetMM100UnitConverter().convertNumber(sBuffer, nRepeat);
rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_NUMBER_COLUMNS_REPEATED, sBuffer.makeStringAndClear());
}
SvXMLElementExport(rExport, XML_NAMESPACE_TABLE, XML_TABLE_CELL, sal_True, sal_True);
}
void ScXMLExportDDELinks::WriteTable(const sal_Int32 nPos)
{
const ScMatrix* pMatrix(NULL);
if (rExport.GetDocument())
pMatrix = rExport.GetDocument()->GetDdeLinkResultMatrix( static_cast<USHORT>(nPos) );
if (pMatrix)
{
SCSIZE nuCol;
SCSIZE nuRow;
pMatrix->GetDimensions( nuCol, nuRow );
sal_Int32 nRowCount = static_cast<sal_Int32>(nuRow);
sal_Int32 nColCount = static_cast<sal_Int32>(nuCol);
SvXMLElementExport aTableElem(rExport, XML_NAMESPACE_TABLE, XML_TABLE, sal_True, sal_True);
rtl::OUStringBuffer sBuffer;
if (nColCount > 1)
{
rExport.GetMM100UnitConverter().convertNumber(sBuffer, nColCount);
rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_NUMBER_COLUMNS_REPEATED, sBuffer.makeStringAndClear());
}
{
SvXMLElementExport aElemCol(rExport, XML_NAMESPACE_TABLE, XML_TABLE_COLUMN, sal_True, sal_True);
}
sal_Bool bPrevString(sal_True);
sal_Bool bPrevEmpty(sal_True);
double fPrevValue;
String sPrevValue;
sal_Int32 nRepeatColsCount(1);
for(sal_Int32 nRow = 0; nRow < nRowCount; ++nRow)
{
SvXMLElementExport aElemRow(rExport, XML_NAMESPACE_TABLE, XML_TABLE_ROW, sal_True, sal_True);
for(sal_Int32 nColumn = 0; nColumn < nColCount; ++nColumn)
{
ScMatValType nType = SC_MATVAL_VALUE;
const ScMatrixValue* pMatVal = pMatrix->Get( static_cast<SCSIZE>(nColumn), static_cast<SCSIZE>(nRow), nType );
BOOL bIsString = ScMatrix::IsStringType( nType);
if (nColumn == 0)
{
bPrevEmpty = !pMatVal;
bPrevString = bIsString;
if( bIsString )
sPrevValue = pMatVal->GetString();
else
fPrevValue = pMatVal->fVal;
}
else
{
double fValue;
String sValue;
sal_Bool bEmpty(!pMatVal);
sal_Bool bString(bIsString);
if( bIsString )
sValue = pMatVal->GetString();
else
fValue = pMatVal->fVal;
if (CellsEqual(bPrevEmpty, bPrevString, sPrevValue, fPrevValue,
bEmpty, bString, sValue, fValue))
++nRepeatColsCount;
else
{
WriteCell(bPrevEmpty, bPrevString, sPrevValue, fPrevValue, nRepeatColsCount);
nRepeatColsCount = 1;
bPrevEmpty = bEmpty;
fPrevValue = fValue;
sPrevValue = sValue;
}
}
}
WriteCell(bPrevEmpty, bPrevString, sPrevValue, fPrevValue, nRepeatColsCount);
nRepeatColsCount = 1;
}
}
}
void ScXMLExportDDELinks::WriteDDELinks(uno::Reference<sheet::XSpreadsheetDocument>& xSpreadDoc)
{
uno::Reference <beans::XPropertySet> xPropertySet (xSpreadDoc, uno::UNO_QUERY);
if (xPropertySet.is())
{
uno::Reference<container::XIndexAccess> xIndex(xPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_DDELINKS))), uno::UNO_QUERY);
if (xIndex.is())
{
sal_Int32 nCount = xIndex->getCount();
if (nCount)
{
SvXMLElementExport aElemDDEs(rExport, XML_NAMESPACE_TABLE, XML_DDE_LINKS, sal_True, sal_True);
for (sal_uInt16 nDDELink = 0; nDDELink < nCount; ++nDDELink)
{
uno::Reference<sheet::XDDELink> xDDELink(xIndex->getByIndex(nDDELink), uno::UNO_QUERY);
if (xDDELink.is())
{
SvXMLElementExport aElemDDE(rExport, XML_NAMESPACE_TABLE, XML_DDE_LINK, sal_True, sal_True);
{
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_APPLICATION, xDDELink->getApplication());
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_TOPIC, xDDELink->getTopic());
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_ITEM, xDDELink->getItem());
rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_AUTOMATIC_UPDATE, XML_TRUE);
BYTE nMode;
if (rExport.GetDocument() &&
rExport.GetDocument()->GetDdeLinkMode(nDDELink, nMode))
{
switch (nMode)
{
case SC_DDE_ENGLISH :
rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_CONVERSION_MODE, XML_INTO_ENGLISH_NUMBER);
break;
case SC_DDE_TEXT :
rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_CONVERSION_MODE, XML_KEEP_TEXT);
break;
}
}
SvXMLElementExport(rExport, XML_NAMESPACE_OFFICE, XML_DDE_SOURCE, sal_True, sal_True);
}
WriteTable(nDDELink);
}
}
}
}
}
}
<|endoftext|> |
<commit_before>#include "rpc.h"
#include <exception>
#include <cstring>
#include <stdio.h>
#include <errno.h>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
namespace simpleprotorpc {
namespace {
// Throws an exception if result is non-zero.
void CheckAddrInfo(int result) {
if (result != 0) {
RPCException ex;
ex.stream() << "AddrInfo failure: "
<< gai_strerror(result);
throw ex;
}
}
// Throws an exception with error message error_msg if result
// is non-zero.
void CheckErrno(int result, const char* error_msg) {
if (result == -1) {
RPCException ex;
ex.stream() << error_msg << " (result: " << result
<< "errno: " << errno << ")";
throw ex;
}
}
void CleanupSocket(int sock_to_delete, deque<int>* sock_list) {
for (deque<int>::iterator it = sock_list->begin();
it != sock_list->end();
++it) {
if (*it == sock_to_delete) {
sock_list->erase(it);
break;
}
}
}
}
RPC* RPC::CreateClient(string host, string port) {
RPC* rpc = new RPC(host, port);
return rpc;
}
RPC* RPC::CreateServer(string port) {
RPC* rpc = new RPC(port);
return rpc;
}
RPC::RPC(string port) : port(port), async_send_thread_started(false),
server(true), send_policy(SEND_ALL),
async_recv_thread_started(false) {
addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // IPvWhatever
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // Whatever IP
CheckAddrInfo(getaddrinfo(NULL, port.c_str(), &hints, &res));
server_sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
CheckErrno(server_sock, "Error creating server sock.");
max_fd = server_sock;
CheckErrno(bind(server_sock, res->ai_addr, res->ai_addrlen), "Error binding server sock.");
// 10 = how many connections to let queue
CheckErrno(listen(server_sock, 10), "Error listening on server sock.");
}
RPC::RPC(string host, string port) : host(host), port(port),
async_send_thread_started(false),
server(false), send_policy(SEND_ALL),
async_recv_thread_started(false) {
addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
CheckAddrInfo(getaddrinfo(host.c_str(), port.c_str(), &hints, &res));
int sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
CheckErrno(sockfd, "Error creating client sock.");
max_fd = sockfd;
CheckErrno(connect(sockfd, res->ai_addr, res->ai_addrlen), "Error connecting to server.");
sock_list.push_back(sockfd);
}
void RPC::SetSendPolicy(RPC::AsyncSendPolicy new_send_policy) {
boost::mutex::scoped_lock l(send_policy_mutex);
send_policy = new_send_policy;
}
void RPC::AsyncSend() {
bool found = true;
while (true) {
if (!found) usleep(10 * 1000);
found = true;
string* cur_string;
{
boost::mutex::scoped_lock l(messages_mutex);
if (messages.size() == 0) {
found = false;
continue;
}
{
boost::mutex::scoped_lock ll(send_policy_mutex);
switch (send_policy) {
case SEND_LAST:
if (messages.size() > 2) {
cerr << "Queue backup: " << messages.size() << endl;
while (messages.size() > 1) {
// Check for ensured delivery
if (messages.front().second) break;
messages.pop_front();
}
}
break;
case SEND_ALL:
break;
}
}
cur_string = messages.front().first;
messages.pop_front();
}
SendMessage(*cur_string, false);
delete cur_string;
}
}
void RPC::SendMessage(string& msg, bool send_async, bool ensure_sent) {
if (send_async) {
if (!async_send_thread_started) {
// Start the async thread.
boost::thread(boost::bind(&RPC::AsyncSend, this));
async_send_thread_started = true;
}
boost::mutex::scoped_lock l(messages_mutex);
messages.push_back(pair<string*, bool>(new string(msg), ensure_sent));
} else {
boost::mutex::scoped_lock l(sending_mutex);
for (deque<int>::iterator it = sock_list.begin();
it != sock_list.end();
++it) {
int sock = *it;
int msglen = msg.size();
msglen = htonl(msglen);
int num_sent = send(sock, &msglen, 4, 0);
CheckErrno(num_sent, "Error sending length.");
if (num_sent != 4) {
RPCException ex;
ex.stream() << "Send length failed: num_sent " << num_sent << " != 4!";
throw ex;
}
unsigned int sent_so_far = 0;
while (sent_so_far != msg.size()) {
num_sent = send(sock, msg.c_str() + sent_so_far,
msg.size() - sent_so_far, 0);
CheckErrno(num_sent, "Error sending message.");
sent_so_far += num_sent;
}
}
}
}
string* RPC::PollMessage(bool blocking) {
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
fd_set socks;
FD_ZERO(&socks);
for (deque<int>::iterator it = sock_list.begin();
it != sock_list.end();
++it) {
FD_SET(*it, &socks);
}
if (server) {
FD_SET(server_sock, &socks);
}
CheckErrno(select(max_fd + 1, &socks, NULL, NULL, blocking ? NULL : &tv),
"Select failed.");
if (server && FD_ISSET(server_sock, &socks)) {
socklen_t addr_size;
sockaddr_storage their_addr;
int new_fd = accept(server_sock, (struct sockaddr *)&their_addr, &addr_size);
CheckErrno(new_fd, "Error accepting server socket.");
if (new_fd > max_fd) max_fd = new_fd;
cerr << "Adding " << new_fd << " to sock_list" << endl;
sock_list.push_back(new_fd);
return PollMessage(blocking);
}
int ss = -1;
for (deque<int>::iterator it = sock_list.begin();
it != sock_list.end();
++it) {
if (FD_ISSET(*it, &socks)) {
ss = *it;
break;
}
}
if (ss == -1) return NULL;
int msglen;
int num_read = recv(ss, &msglen, 4, 0);
if (num_read != 4) {
// TODO(frew): error handling for this
cerr << "Uh oh...msg length read " << num_read << " != 4."
<< " Killing socket." << endl;
CleanupSocket(ss, &sock_list);
return PollMessage(blocking);
}
msglen = htonl(msglen);
// TODO(frew): scoped_ptr
char * buf = new char[msglen];
int read_so_far = 0;
while (read_so_far < msglen) {
num_read = recv(ss, buf + read_so_far, msglen - read_so_far, 0);
if (num_read <= 0) {
cerr << "Got " << num_read << " from num_read. Killing socket. :(" << endl;
CleanupSocket(ss, &sock_list);
delete[] buf;
return PollMessage(blocking);
}
read_so_far += num_read;
}
string* ret_string = new string(buf, msglen);
delete[] buf;
return ret_string;
}
void RPC::AsyncRecv() {
while (async_recv_thread_started) {
string* msg = PollMessage(true);
async_recv_callback(msg);
delete msg;
}
}
void RPC::StartAsyncRecv(boost::function<void (string* s)> callback) {
async_recv_callback = callback;
if (!async_recv_thread_started) {
async_recv_thread_started = true;
boost::thread(boost::bind(&RPC::AsyncRecv, this));
}
}
void RPC::StopAsyncRecv() {
async_recv_thread_started = false;
}
}
<commit_msg>Uninitialized value<commit_after>#include "rpc.h"
#include <exception>
#include <cstring>
#include <stdio.h>
#include <errno.h>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
namespace simpleprotorpc {
namespace {
// Throws an exception if result is non-zero.
void CheckAddrInfo(int result) {
if (result != 0) {
RPCException ex;
ex.stream() << "AddrInfo failure: "
<< gai_strerror(result);
throw ex;
}
}
// Throws an exception with error message error_msg if result
// is non-zero.
void CheckErrno(int result, const char* error_msg) {
if (result == -1) {
RPCException ex;
ex.stream() << error_msg << " (result: " << result
<< "errno: " << errno << ")";
throw ex;
}
}
void CleanupSocket(int sock_to_delete, deque<int>* sock_list) {
for (deque<int>::iterator it = sock_list->begin();
it != sock_list->end();
++it) {
if (*it == sock_to_delete) {
sock_list->erase(it);
break;
}
}
}
}
RPC* RPC::CreateClient(string host, string port) {
RPC* rpc = new RPC(host, port);
return rpc;
}
RPC* RPC::CreateServer(string port) {
RPC* rpc = new RPC(port);
return rpc;
}
RPC::RPC(string port) : port(port), async_send_thread_started(false),
server(true), send_policy(SEND_ALL),
async_recv_thread_started(false) {
addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // IPvWhatever
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // Whatever IP
CheckAddrInfo(getaddrinfo(NULL, port.c_str(), &hints, &res));
server_sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
CheckErrno(server_sock, "Error creating server sock.");
max_fd = server_sock;
CheckErrno(bind(server_sock, res->ai_addr, res->ai_addrlen), "Error binding server sock.");
// 10 = how many connections to let queue
CheckErrno(listen(server_sock, 10), "Error listening on server sock.");
}
RPC::RPC(string host, string port) : host(host), port(port),
async_send_thread_started(false),
server(false), send_policy(SEND_ALL),
async_recv_thread_started(false) {
addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
CheckAddrInfo(getaddrinfo(host.c_str(), port.c_str(), &hints, &res));
int sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
CheckErrno(sockfd, "Error creating client sock.");
max_fd = sockfd;
CheckErrno(connect(sockfd, res->ai_addr, res->ai_addrlen), "Error connecting to server.");
sock_list.push_back(sockfd);
}
void RPC::SetSendPolicy(RPC::AsyncSendPolicy new_send_policy) {
boost::mutex::scoped_lock l(send_policy_mutex);
send_policy = new_send_policy;
}
void RPC::AsyncSend() {
bool found = true;
while (true) {
if (!found) usleep(10 * 1000);
found = true;
string* cur_string;
{
boost::mutex::scoped_lock l(messages_mutex);
if (messages.size() == 0) {
found = false;
continue;
}
{
boost::mutex::scoped_lock ll(send_policy_mutex);
switch (send_policy) {
case SEND_LAST:
if (messages.size() > 2) {
cerr << "Queue backup: " << messages.size() << endl;
while (messages.size() > 1) {
// Check for ensured delivery
if (messages.front().second) break;
messages.pop_front();
}
}
break;
case SEND_ALL:
break;
}
}
cur_string = messages.front().first;
messages.pop_front();
}
SendMessage(*cur_string, false);
delete cur_string;
}
}
void RPC::SendMessage(string& msg, bool send_async, bool ensure_sent) {
if (send_async) {
if (!async_send_thread_started) {
// Start the async thread.
boost::thread(boost::bind(&RPC::AsyncSend, this));
async_send_thread_started = true;
}
boost::mutex::scoped_lock l(messages_mutex);
messages.push_back(pair<string*, bool>(new string(msg), ensure_sent));
} else {
boost::mutex::scoped_lock l(sending_mutex);
for (deque<int>::iterator it = sock_list.begin();
it != sock_list.end();
++it) {
int sock = *it;
int msglen = msg.size();
msglen = htonl(msglen);
int num_sent = send(sock, &msglen, 4, 0);
CheckErrno(num_sent, "Error sending length.");
if (num_sent != 4) {
RPCException ex;
ex.stream() << "Send length failed: num_sent " << num_sent << " != 4!";
throw ex;
}
unsigned int sent_so_far = 0;
while (sent_so_far != msg.size()) {
num_sent = send(sock, msg.c_str() + sent_so_far,
msg.size() - sent_so_far, 0);
CheckErrno(num_sent, "Error sending message.");
sent_so_far += num_sent;
}
}
}
}
string* RPC::PollMessage(bool blocking) {
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
fd_set socks;
FD_ZERO(&socks);
for (deque<int>::iterator it = sock_list.begin();
it != sock_list.end();
++it) {
FD_SET(*it, &socks);
}
if (server) {
FD_SET(server_sock, &socks);
}
CheckErrno(select(max_fd + 1, &socks, NULL, NULL, blocking ? NULL : &tv),
"Select failed.");
if (server && FD_ISSET(server_sock, &socks)) {
socklen_t addr_size = sizeof(sockaddr_storage);
sockaddr_storage their_addr;
int new_fd = accept(server_sock, (struct sockaddr *)&their_addr, &addr_size);
CheckErrno(new_fd, "Error accepting server socket.");
if (new_fd > max_fd) max_fd = new_fd;
cerr << "Adding " << new_fd << " to sock_list" << endl;
sock_list.push_back(new_fd);
return PollMessage(blocking);
}
int ss = -1;
for (deque<int>::iterator it = sock_list.begin();
it != sock_list.end();
++it) {
if (FD_ISSET(*it, &socks)) {
ss = *it;
break;
}
}
if (ss == -1) return NULL;
int msglen;
int num_read = recv(ss, &msglen, 4, 0);
if (num_read != 4) {
// TODO(frew): error handling for this
cerr << "Uh oh...msg length read " << num_read << " != 4."
<< " Killing socket." << endl;
CleanupSocket(ss, &sock_list);
return PollMessage(blocking);
}
msglen = htonl(msglen);
// TODO(frew): scoped_ptr
char * buf = new char[msglen];
int read_so_far = 0;
while (read_so_far < msglen) {
num_read = recv(ss, buf + read_so_far, msglen - read_so_far, 0);
if (num_read <= 0) {
cerr << "Got " << num_read << " from num_read. Killing socket. :(" << endl;
CleanupSocket(ss, &sock_list);
delete[] buf;
return PollMessage(blocking);
}
read_so_far += num_read;
}
string* ret_string = new string(buf, msglen);
delete[] buf;
return ret_string;
}
void RPC::AsyncRecv() {
while (async_recv_thread_started) {
string* msg = PollMessage(true);
async_recv_callback(msg);
delete msg;
}
}
void RPC::StartAsyncRecv(boost::function<void (string* s)> callback) {
async_recv_callback = callback;
if (!async_recv_thread_started) {
async_recv_thread_started = true;
boost::thread(boost::bind(&RPC::AsyncRecv, this));
}
}
void RPC::StopAsyncRecv() {
async_recv_thread_started = false;
}
}
<|endoftext|> |
<commit_before><commit_msg>SSL: don't ask for next proto if we got an error.<commit_after><|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.
*
*=========================================================================*/
#ifdef _MFC_VER
#pragma warning(disable:4996)
#endif
#include "sitkImageFileReader.h"
#include <itkImageFileReader.h>
#include <itkExtractImageFilter.h>
#include "sitkMetaDataDictionaryCustomCast.hxx"
namespace itk {
namespace simple {
namespace {
// Simple ITK must use a zero based index
template< class TImageType>
static void FixNonZeroIndex( TImageType * img )
{
assert( img != SITK_NULLPTR );
typename TImageType::RegionType r = img->GetLargestPossibleRegion();
typename TImageType::IndexType idx = r.GetIndex();
for( unsigned int i = 0; i < TImageType::ImageDimension; ++i )
{
if ( idx[i] != 0 )
{
// if any of the indcies are non-zero, then just fix it
typename TImageType::PointType o;
img->TransformIndexToPhysicalPoint( idx, o );
img->SetOrigin( o );
idx.Fill( 0 );
r.SetIndex( idx );
// Need to set the buffered region to match largest
img->SetRegions( r );
return;
}
}
}
}
Image ReadImage ( const std::string &filename, PixelIDValueEnum outputPixelType )
{
ImageFileReader reader;
return reader.SetFileName ( filename ).SetOutputPixelType(outputPixelType).Execute();
}
ImageFileReader::~ImageFileReader()
{
}
ImageFileReader::ImageFileReader() :
m_PixelType(sitkUnknown),
m_Dimension(0),
m_NumberOfComponents(0)
{
// list of pixel types supported
typedef NonLabelPixelIDTypeList PixelIDTypeList;
this->m_MemberFactory.reset( new detail::MemberFunctionFactory<MemberFunctionType>( this ) );
this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 4 > ();
this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 3 > ();
this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > ();
}
std::string ImageFileReader::ToString() const {
std::ostringstream out;
out << "itk::simple::ImageFileReader";
out << std::endl;
out << " FileName: \"";
this->ToStringHelper(out, this->m_FileName) << "\"" << std::endl;
out << " ExtractSize: " << this->m_ExtractSize << std::endl;
out << " ExtractIndex: " << this->m_ExtractIndex << std::endl;
out << " Image Information:" << std::endl
<< " PixelType: ";
this->ToStringHelper(out, this->m_PixelType) << std::endl;
out << " Dimension: " << this->m_Dimension << std::endl;
out << " NumberOfComponents: " << this->m_NumberOfComponents << std::endl;
out << " Direction: " << this->m_Direction << std::endl;
out << " Origin: " << this->m_Origin << std::endl;
out << " Spacing: " << this->m_Spacing << std::endl;
out << " Size: " << this->m_Size << std::endl;
out << ImageReaderBase::ToString();
return out.str();
}
ImageFileReader& ImageFileReader::SetFileName ( const std::string &fn ) {
this->m_FileName = fn;
return *this;
}
std::string ImageFileReader::GetFileName() const {
return this->m_FileName;
}
void
ImageFileReader
::UpdateImageInformationFromImageIO(const itk::ImageIOBase* iobase)
{
PixelIDValueType pixelType;
this->GetPixelIDFromImageIO(iobase, pixelType, m_Dimension);
std::vector<double> direction;
direction.reserve(m_Dimension*m_Dimension);
std::vector<double> origin(m_Dimension);
std::vector<double> spacing(m_Dimension);
std::vector<uint64_t> size(m_Dimension);
for( unsigned int i = 0; i < m_Dimension; ++i)
{
origin[i] = iobase->GetOrigin(i);
spacing[i] = iobase->GetSpacing(i);
size[i] = iobase->GetDimensions(i);
const std::vector< double > temp_direction = iobase->GetDirection(i);
direction.insert(direction.end(), temp_direction.begin(), temp_direction.end());
}
// release functions bound to old meta data dictionary
if (m_MetaDataDictionary.get())
{
this->m_pfGetMetaDataKeys = SITK_NULLPTR;
this->m_pfHasMetaDataKey = SITK_NULLPTR;
this->m_pfGetMetaData = SITK_NULLPTR;
}
this->m_MetaDataDictionary.reset(new MetaDataDictionary(iobase->GetMetaDataDictionary()));
m_PixelType = static_cast<PixelIDValueEnum>(pixelType);
// Use the number of components as reported by the itk::Image
m_NumberOfComponents = iobase->GetNumberOfComponents();
using std::swap;
swap(direction, m_Direction);
swap(origin, m_Origin);
swap(spacing, m_Spacing);
swap(size, m_Size);
this->m_pfGetMetaDataKeys = nsstd::bind(&MetaDataDictionary::GetKeys, this->m_MetaDataDictionary.get());
this->m_pfHasMetaDataKey = nsstd::bind(&MetaDataDictionary::HasKey, this->m_MetaDataDictionary.get(), nsstd::placeholders::_1);
this->m_pfGetMetaData = nsstd::bind(&GetMetaDataDictionaryCustomCast::CustomCast, this->m_MetaDataDictionary.get(), nsstd::placeholders::_1);
}
PixelIDValueEnum
ImageFileReader
::GetPixelID( void ) const
{
return this->m_PixelType;
}
PixelIDValueType
ImageFileReader
::GetPixelIDValue( void ) const
{
return this->m_PixelType;
}
unsigned int
ImageFileReader
::GetDimension( void ) const
{
return this->m_Dimension;
}
unsigned int
ImageFileReader
::GetNumberOfComponents( void ) const
{
return this->m_NumberOfComponents;
}
const std::vector<double> &
ImageFileReader
::GetOrigin( void ) const
{
return this->m_Origin;
}
const std::vector<double> &
ImageFileReader
::GetSpacing( void ) const
{
return this->m_Spacing;
}
const std::vector<double> &
ImageFileReader
::GetDirection() const
{
return this->m_Direction;
}
const std::vector<uint64_t> &
ImageFileReader
::GetSize( void ) const
{
return this->m_Size;
}
void
ImageFileReader
::ReadImageInformation( void )
{
itk::ImageIOBase::Pointer imageio = this->GetImageIOBase( this->m_FileName );
this->UpdateImageInformationFromImageIO(imageio);
}
std::vector<std::string>
ImageFileReader
::GetMetaDataKeys( void ) const
{
return this->m_pfGetMetaDataKeys();
}
bool
ImageFileReader
::HasMetaDataKey( const std::string &key ) const
{
return this->m_pfHasMetaDataKey(key);
}
std::string
ImageFileReader
::GetMetaData( const std::string &key ) const
{
return this->m_pfGetMetaData(key);
}
ImageFileReader &ImageFileReader::SetExtractSize( const std::vector<unsigned int> &size)
{
this->m_ExtractSize = size;
return *this;
}
const std::vector<unsigned int> &ImageFileReader::GetExtractSize( ) const
{
return this->m_ExtractSize;
}
ImageFileReader &ImageFileReader::SetExtractIndex( const std::vector<int> &index )
{
this->m_ExtractIndex = index;
return *this;
}
const std::vector<int> &ImageFileReader::GetExtractIndex( ) const
{
return this->m_ExtractIndex;
}
Image ImageFileReader::Execute ()
{
PixelIDValueType type = this->GetOutputPixelType();
itk::ImageIOBase::Pointer imageio = this->GetImageIOBase( this->m_FileName );
this->UpdateImageInformationFromImageIO(imageio);
sitkDebugMacro( "ImageIO: " << imageio->GetNameOfClass() );
unsigned int dimension = this->GetDimension();
if (!m_ExtractSize.empty())
{
dimension = 0;
for(unsigned int i = 0; i < m_ExtractSize.size(); ++i )
{
if (m_ExtractSize[i] != 0)
{
++dimension;
}
}
}
if (type == sitkUnknown)
{
type = this->GetPixelIDValue();
}
#ifdef SITK_4D_IMAGES
if ( dimension != 2 && dimension != 3 && dimension != 4 )
#else
if ( dimension != 2 && dimension != 3 )
#endif
{
sitkExceptionMacro( "The file has unsupported " << dimension << " dimensions." );
}
if ( !this->m_MemberFactory->HasMemberFunction( type, dimension ) )
{
sitkExceptionMacro( << "PixelType is not supported!" << std::endl
<< "Pixel Type: "
<< GetPixelIDValueAsString( type ) << std::endl
<< "Refusing to load! " << std::endl );
}
return this->m_MemberFactory->GetMemberFunction( type, dimension )(imageio.GetPointer());
}
template <class TImageType>
Image
ImageFileReader::ExecuteInternal( itk::ImageIOBase *imageio )
{
const unsigned int MAX_DIMENSION = 5;
typedef TImageType ImageType;
typedef itk::ImageFileReader<ImageType> Reader;
typedef typename ImageType::template Rebind<typename ImageType::PixelType, MAX_DIMENSION>::Type InternalImageType;
typedef itk::ImageFileReader<InternalImageType> InternalReader;
// if the InstantiatedToken is correctly implemented this should
// not occur
assert( ImageTypeToPixelIDValue<ImageType>::Result != (int)sitkUnknown );
assert( imageio != SITK_NULLPTR );
if ( m_ExtractSize.empty() || m_ExtractSize.size() == ImageType::ImageDimension)
{
typename Reader::Pointer reader = Reader::New();
reader->SetImageIO( imageio );
reader->SetFileName( this->m_FileName.c_str() );
if ( m_ExtractSize.empty() )
{
this->PreUpdate( reader.GetPointer() );
reader->Update();
return Image( reader->GetOutput() );
}
return this->ExecuteExtract<ImageType>(reader->GetOutput());
}
else
{
// Perform Reading->Extractor pipeline to adjust dimensions and
// do streamed ImageIO
typename InternalReader::Pointer reader = InternalReader::New();
reader->SetImageIO( imageio );
reader->SetFileName( this->m_FileName.c_str() );
return this->ExecuteExtract<ImageType>(reader->GetOutput());
}
}
template <class TImageType, class TInternalImageType>
Image
ImageFileReader::ExecuteExtract( TInternalImageType * itkImage )
{
typedef TInternalImageType InternalImageType;
typedef TImageType ImageType;
typedef itk::ExtractImageFilter<InternalImageType, ImageType> ExtractType;
typename ExtractType::Pointer extractor = ExtractType::New();
extractor->InPlaceOn();
extractor->SetDirectionCollapseToSubmatrix();
extractor->SetInput(itkImage);
itkImage->UpdateOutputInformation();
const typename InternalImageType::RegionType largestRegion = itkImage->GetLargestPossibleRegion();
typename InternalImageType::RegionType region = largestRegion;
for (unsigned int i = 0; i < TInternalImageType::ImageDimension; ++i)
{
if ( i < m_ExtractSize.size() )
{
region.SetSize(i, m_ExtractSize[i]);
}
else if ( i >= ImageType::ImageDimension )
{
region.SetSize(i, 0u);
}
if ( i < m_ExtractIndex.size() )
{
region.SetIndex(i,m_ExtractIndex[i]);
}
}
extractor->SetExtractionRegion(region);
typename TInternalImageType::IndexType upperIndex = region.GetUpperIndex();
for (unsigned int i = 0; i < TInternalImageType::ImageDimension; ++i)
{
if (region.GetSize(i) == 0)
{
upperIndex[i] = region.GetIndex(i);
}
}
// check region is in largest possible
if ( !largestRegion.IsInside( region.GetIndex() ) ||
!largestRegion.IsInside( upperIndex ) )
{
sitkExceptionMacro( "The requested extraction region: "
<< region
<< " is not contained with in file's region: "
<< itkImage->GetLargestPossibleRegion() );
}
assert(itkImage->GetSource() != SITK_NULLPTR);
this->PreUpdate( itkImage->GetSource().GetPointer() );
extractor->Update();
ImageType *itkOutImage = extractor->GetOutput();
// copy meta-data dictionary
itkOutImage->SetMetaDataDictionary( itkImage->GetMetaDataDictionary() );
FixNonZeroIndex( itkOutImage );
return Image( itkOutImage );
}
}
}
<commit_msg>Add debugging information to ReadInformation<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.
*
*=========================================================================*/
#ifdef _MFC_VER
#pragma warning(disable:4996)
#endif
#include "sitkImageFileReader.h"
#include <itkImageFileReader.h>
#include <itkExtractImageFilter.h>
#include "sitkMetaDataDictionaryCustomCast.hxx"
namespace itk {
namespace simple {
namespace {
// Simple ITK must use a zero based index
template< class TImageType>
static void FixNonZeroIndex( TImageType * img )
{
assert( img != SITK_NULLPTR );
typename TImageType::RegionType r = img->GetLargestPossibleRegion();
typename TImageType::IndexType idx = r.GetIndex();
for( unsigned int i = 0; i < TImageType::ImageDimension; ++i )
{
if ( idx[i] != 0 )
{
// if any of the indcies are non-zero, then just fix it
typename TImageType::PointType o;
img->TransformIndexToPhysicalPoint( idx, o );
img->SetOrigin( o );
idx.Fill( 0 );
r.SetIndex( idx );
// Need to set the buffered region to match largest
img->SetRegions( r );
return;
}
}
}
}
Image ReadImage ( const std::string &filename, PixelIDValueEnum outputPixelType )
{
ImageFileReader reader;
return reader.SetFileName ( filename ).SetOutputPixelType(outputPixelType).Execute();
}
ImageFileReader::~ImageFileReader()
{
}
ImageFileReader::ImageFileReader() :
m_PixelType(sitkUnknown),
m_Dimension(0),
m_NumberOfComponents(0)
{
// list of pixel types supported
typedef NonLabelPixelIDTypeList PixelIDTypeList;
this->m_MemberFactory.reset( new detail::MemberFunctionFactory<MemberFunctionType>( this ) );
this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 4 > ();
this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 3 > ();
this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > ();
}
std::string ImageFileReader::ToString() const {
std::ostringstream out;
out << "itk::simple::ImageFileReader";
out << std::endl;
out << " FileName: \"";
this->ToStringHelper(out, this->m_FileName) << "\"" << std::endl;
out << " ExtractSize: " << this->m_ExtractSize << std::endl;
out << " ExtractIndex: " << this->m_ExtractIndex << std::endl;
out << " Image Information:" << std::endl
<< " PixelType: ";
this->ToStringHelper(out, this->m_PixelType) << std::endl;
out << " Dimension: " << this->m_Dimension << std::endl;
out << " NumberOfComponents: " << this->m_NumberOfComponents << std::endl;
out << " Direction: " << this->m_Direction << std::endl;
out << " Origin: " << this->m_Origin << std::endl;
out << " Spacing: " << this->m_Spacing << std::endl;
out << " Size: " << this->m_Size << std::endl;
out << ImageReaderBase::ToString();
return out.str();
}
ImageFileReader& ImageFileReader::SetFileName ( const std::string &fn ) {
this->m_FileName = fn;
return *this;
}
std::string ImageFileReader::GetFileName() const {
return this->m_FileName;
}
void
ImageFileReader
::UpdateImageInformationFromImageIO(const itk::ImageIOBase* iobase)
{
PixelIDValueType pixelType;
this->GetPixelIDFromImageIO(iobase, pixelType, m_Dimension);
std::vector<double> direction;
direction.reserve(m_Dimension*m_Dimension);
std::vector<double> origin(m_Dimension);
std::vector<double> spacing(m_Dimension);
std::vector<uint64_t> size(m_Dimension);
for( unsigned int i = 0; i < m_Dimension; ++i)
{
origin[i] = iobase->GetOrigin(i);
spacing[i] = iobase->GetSpacing(i);
size[i] = iobase->GetDimensions(i);
const std::vector< double > temp_direction = iobase->GetDirection(i);
direction.insert(direction.end(), temp_direction.begin(), temp_direction.end());
}
// release functions bound to old meta data dictionary
if (m_MetaDataDictionary.get())
{
this->m_pfGetMetaDataKeys = SITK_NULLPTR;
this->m_pfHasMetaDataKey = SITK_NULLPTR;
this->m_pfGetMetaData = SITK_NULLPTR;
}
this->m_MetaDataDictionary.reset(new MetaDataDictionary(iobase->GetMetaDataDictionary()));
m_PixelType = static_cast<PixelIDValueEnum>(pixelType);
// Use the number of components as reported by the itk::Image
m_NumberOfComponents = iobase->GetNumberOfComponents();
using std::swap;
swap(direction, m_Direction);
swap(origin, m_Origin);
swap(spacing, m_Spacing);
swap(size, m_Size);
this->m_pfGetMetaDataKeys = nsstd::bind(&MetaDataDictionary::GetKeys, this->m_MetaDataDictionary.get());
this->m_pfHasMetaDataKey = nsstd::bind(&MetaDataDictionary::HasKey, this->m_MetaDataDictionary.get(), nsstd::placeholders::_1);
this->m_pfGetMetaData = nsstd::bind(&GetMetaDataDictionaryCustomCast::CustomCast, this->m_MetaDataDictionary.get(), nsstd::placeholders::_1);
}
PixelIDValueEnum
ImageFileReader
::GetPixelID( void ) const
{
return this->m_PixelType;
}
PixelIDValueType
ImageFileReader
::GetPixelIDValue( void ) const
{
return this->m_PixelType;
}
unsigned int
ImageFileReader
::GetDimension( void ) const
{
return this->m_Dimension;
}
unsigned int
ImageFileReader
::GetNumberOfComponents( void ) const
{
return this->m_NumberOfComponents;
}
const std::vector<double> &
ImageFileReader
::GetOrigin( void ) const
{
return this->m_Origin;
}
const std::vector<double> &
ImageFileReader
::GetSpacing( void ) const
{
return this->m_Spacing;
}
const std::vector<double> &
ImageFileReader
::GetDirection() const
{
return this->m_Direction;
}
const std::vector<uint64_t> &
ImageFileReader
::GetSize( void ) const
{
return this->m_Size;
}
void
ImageFileReader
::ReadImageInformation( void )
{
itk::ImageIOBase::Pointer imageio = this->GetImageIOBase( this->m_FileName );
this->UpdateImageInformationFromImageIO(imageio);
sitkDebugMacro("ImageIO: " << imageio);
}
std::vector<std::string>
ImageFileReader
::GetMetaDataKeys( void ) const
{
return this->m_pfGetMetaDataKeys();
}
bool
ImageFileReader
::HasMetaDataKey( const std::string &key ) const
{
return this->m_pfHasMetaDataKey(key);
}
std::string
ImageFileReader
::GetMetaData( const std::string &key ) const
{
return this->m_pfGetMetaData(key);
}
ImageFileReader &ImageFileReader::SetExtractSize( const std::vector<unsigned int> &size)
{
this->m_ExtractSize = size;
return *this;
}
const std::vector<unsigned int> &ImageFileReader::GetExtractSize( ) const
{
return this->m_ExtractSize;
}
ImageFileReader &ImageFileReader::SetExtractIndex( const std::vector<int> &index )
{
this->m_ExtractIndex = index;
return *this;
}
const std::vector<int> &ImageFileReader::GetExtractIndex( ) const
{
return this->m_ExtractIndex;
}
Image ImageFileReader::Execute ()
{
PixelIDValueType type = this->GetOutputPixelType();
itk::ImageIOBase::Pointer imageio = this->GetImageIOBase( this->m_FileName );
this->UpdateImageInformationFromImageIO(imageio);
sitkDebugMacro( "ImageIO: " << imageio->GetNameOfClass() );
unsigned int dimension = this->GetDimension();
if (!m_ExtractSize.empty())
{
dimension = 0;
for(unsigned int i = 0; i < m_ExtractSize.size(); ++i )
{
if (m_ExtractSize[i] != 0)
{
++dimension;
}
}
}
if (type == sitkUnknown)
{
type = this->GetPixelIDValue();
}
#ifdef SITK_4D_IMAGES
if ( dimension != 2 && dimension != 3 && dimension != 4 )
#else
if ( dimension != 2 && dimension != 3 )
#endif
{
sitkExceptionMacro( "The file has unsupported " << dimension << " dimensions." );
}
if ( !this->m_MemberFactory->HasMemberFunction( type, dimension ) )
{
sitkExceptionMacro( << "PixelType is not supported!" << std::endl
<< "Pixel Type: "
<< GetPixelIDValueAsString( type ) << std::endl
<< "Refusing to load! " << std::endl );
}
return this->m_MemberFactory->GetMemberFunction( type, dimension )(imageio.GetPointer());
}
template <class TImageType>
Image
ImageFileReader::ExecuteInternal( itk::ImageIOBase *imageio )
{
const unsigned int MAX_DIMENSION = 5;
typedef TImageType ImageType;
typedef itk::ImageFileReader<ImageType> Reader;
typedef typename ImageType::template Rebind<typename ImageType::PixelType, MAX_DIMENSION>::Type InternalImageType;
typedef itk::ImageFileReader<InternalImageType> InternalReader;
// if the InstantiatedToken is correctly implemented this should
// not occur
assert( ImageTypeToPixelIDValue<ImageType>::Result != (int)sitkUnknown );
assert( imageio != SITK_NULLPTR );
if ( m_ExtractSize.empty() || m_ExtractSize.size() == ImageType::ImageDimension)
{
typename Reader::Pointer reader = Reader::New();
reader->SetImageIO( imageio );
reader->SetFileName( this->m_FileName.c_str() );
if ( m_ExtractSize.empty() )
{
this->PreUpdate( reader.GetPointer() );
reader->Update();
return Image( reader->GetOutput() );
}
return this->ExecuteExtract<ImageType>(reader->GetOutput());
}
else
{
// Perform Reading->Extractor pipeline to adjust dimensions and
// do streamed ImageIO
typename InternalReader::Pointer reader = InternalReader::New();
reader->SetImageIO( imageio );
reader->SetFileName( this->m_FileName.c_str() );
return this->ExecuteExtract<ImageType>(reader->GetOutput());
}
}
template <class TImageType, class TInternalImageType>
Image
ImageFileReader::ExecuteExtract( TInternalImageType * itkImage )
{
typedef TInternalImageType InternalImageType;
typedef TImageType ImageType;
typedef itk::ExtractImageFilter<InternalImageType, ImageType> ExtractType;
typename ExtractType::Pointer extractor = ExtractType::New();
extractor->InPlaceOn();
extractor->SetDirectionCollapseToSubmatrix();
extractor->SetInput(itkImage);
itkImage->UpdateOutputInformation();
const typename InternalImageType::RegionType largestRegion = itkImage->GetLargestPossibleRegion();
typename InternalImageType::RegionType region = largestRegion;
for (unsigned int i = 0; i < TInternalImageType::ImageDimension; ++i)
{
if ( i < m_ExtractSize.size() )
{
region.SetSize(i, m_ExtractSize[i]);
}
else if ( i >= ImageType::ImageDimension )
{
region.SetSize(i, 0u);
}
if ( i < m_ExtractIndex.size() )
{
region.SetIndex(i,m_ExtractIndex[i]);
}
}
extractor->SetExtractionRegion(region);
typename TInternalImageType::IndexType upperIndex = region.GetUpperIndex();
for (unsigned int i = 0; i < TInternalImageType::ImageDimension; ++i)
{
if (region.GetSize(i) == 0)
{
upperIndex[i] = region.GetIndex(i);
}
}
// check region is in largest possible
if ( !largestRegion.IsInside( region.GetIndex() ) ||
!largestRegion.IsInside( upperIndex ) )
{
sitkExceptionMacro( "The requested extraction region: "
<< region
<< " is not contained with in file's region: "
<< itkImage->GetLargestPossibleRegion() );
}
assert(itkImage->GetSource() != SITK_NULLPTR);
this->PreUpdate( itkImage->GetSource().GetPointer() );
extractor->Update();
ImageType *itkOutImage = extractor->GetOutput();
// copy meta-data dictionary
itkOutImage->SetMetaDataDictionary( itkImage->GetMetaDataDictionary() );
FixNonZeroIndex( itkOutImage );
return Image( itkOutImage );
}
}
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Disable logging in tests.<commit_after>#include <gtest/gtest.h>
#include <QLoggingCategory>
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
QLoggingCategory::setFilterRules("*=false");
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include "image.hpp"
#include "state_writer.hpp"
#include "com_ptr.hpp"
#include "d3d9state.hpp"
#include "d3dstate.hpp"
namespace d3dstate {
static image::Image *
getSurfaceImage(IDirect3DDevice9 *pDevice,
IDirect3DSurface9 *pSurface,
struct StateWriter::ImageDesc &imageDesc) {
image::Image *image = NULL;
HRESULT hr;
if (!pSurface) {
return NULL;
}
D3DSURFACE_DESC Desc;
hr = pSurface->GetDesc(&Desc);
assert(SUCCEEDED(hr));
if (Desc.Format == D3DFMT_NULL) {
// dummy rendertarget
return NULL;
}
D3DLOCKED_RECT LockedRect;
hr = pSurface->LockRect(&LockedRect, NULL, D3DLOCK_READONLY);
if (FAILED(hr)) {
return NULL;
}
image = ConvertImage(Desc.Format, LockedRect.pBits, LockedRect.Pitch, Desc.Width, Desc.Height);
pSurface->UnlockRect();
imageDesc.format = formatToString(Desc.Format);
return image;
}
static image::Image *
getRenderTargetImage(IDirect3DDevice9 *pDevice,
IDirect3DSurface9 *pRenderTarget,
struct StateWriter::ImageDesc &imageDesc) {
HRESULT hr;
if (!pRenderTarget) {
return NULL;
}
D3DSURFACE_DESC Desc;
hr = pRenderTarget->GetDesc(&Desc);
assert(SUCCEEDED(hr));
if (Desc.Format == D3DFMT_NULL) {
// dummy rendertarget
return NULL;
}
com_ptr<IDirect3DSurface9> pStagingSurface;
hr = pDevice->CreateOffscreenPlainSurface(Desc.Width, Desc.Height, Desc.Format, D3DPOOL_SYSTEMMEM, &pStagingSurface, NULL);
if (FAILED(hr)) {
return NULL;
}
hr = pDevice->GetRenderTargetData(pRenderTarget, pStagingSurface);
if (FAILED(hr)) {
std::cerr << "warning: GetRenderTargetData failed\n";
return NULL;
}
return getSurfaceImage(pDevice, pStagingSurface, imageDesc);
}
image::Image *
getRenderTargetImage(IDirect3DDevice9 *pDevice) {
HRESULT hr;
struct StateWriter::ImageDesc imageDesc;
com_ptr<IDirect3DSurface9> pRenderTarget;
hr = pDevice->GetRenderTarget(0, &pRenderTarget);
if (FAILED(hr)) {
return NULL;
}
assert(pRenderTarget);
return getRenderTargetImage(pDevice, pRenderTarget, imageDesc);
}
image::Image *
getRenderTargetImage(IDirect3DSwapChain9 *pSwapChain) {
HRESULT hr;
struct StateWriter::ImageDesc imageDesc;
com_ptr<IDirect3DDevice9> pDevice;
hr = pSwapChain->GetDevice(&pDevice);
if (FAILED(hr)) {
return NULL;
}
// TODO: Use GetFrontBufferData instead??
com_ptr<IDirect3DSurface9> pBackBuffer;
hr = pSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer);
if (FAILED(hr)) {
return NULL;
}
assert(pBackBuffer);
return getRenderTargetImage(pDevice, pBackBuffer, imageDesc);
}
static image::Image *
getTextureImage(IDirect3DDevice9 *pDevice,
IDirect3DBaseTexture9 *pTexture,
D3DCUBEMAP_FACES FaceType,
UINT Level,
struct StateWriter::ImageDesc &imageDesc)
{
HRESULT hr;
if (!pTexture) {
return NULL;
}
com_ptr<IDirect3DSurface9> pSurface;
D3DRESOURCETYPE Type = pTexture->GetType();
switch (Type) {
case D3DRTYPE_TEXTURE:
assert(FaceType == D3DCUBEMAP_FACE_POSITIVE_X);
hr = reinterpret_cast<IDirect3DTexture9 *>(pTexture)->GetSurfaceLevel(Level, &pSurface);
break;
case D3DRTYPE_CUBETEXTURE:
hr = reinterpret_cast<IDirect3DCubeTexture9 *>(pTexture)->GetCubeMapSurface(FaceType, Level, &pSurface);
break;
default:
/* TODO: support volume textures */
return NULL;
}
if (FAILED(hr) || !pSurface) {
return NULL;
}
D3DSURFACE_DESC Desc;
hr = pSurface->GetDesc(&Desc);
assert(SUCCEEDED(hr));
if (Desc.Pool != D3DPOOL_DEFAULT ||
Desc.Usage & D3DUSAGE_DYNAMIC) {
// Lockable texture
return getSurfaceImage(pDevice, pSurface, imageDesc);
} else if (Desc.Usage & D3DUSAGE_RENDERTARGET) {
// Rendertarget texture
return getRenderTargetImage(pDevice, pSurface, imageDesc);
} else {
// D3D constraints are such there is not much else that can be done.
return NULL;
}
}
void
dumpTextures(StateWriter &writer, IDirect3DDevice9 *pDevice)
{
HRESULT hr;
writer.beginMember("textures");
writer.beginObject();
for (DWORD Stage = 0; Stage < 16; ++Stage) {
com_ptr<IDirect3DBaseTexture9> pTexture;
hr = pDevice->GetTexture(Stage, &pTexture);
if (FAILED(hr)) {
continue;
}
if (!pTexture) {
continue;
}
D3DRESOURCETYPE Type = pTexture->GetType();
DWORD NumFaces = Type == D3DRTYPE_CUBETEXTURE ? 6 : 1;
DWORD NumLevels = pTexture->GetLevelCount();
for (DWORD Face = 0; Face < NumFaces; ++Face) {
for (DWORD Level = 0; Level < NumLevels; ++Level) {
image::Image *image;
struct StateWriter::ImageDesc imageDesc;
image = getTextureImage(pDevice, pTexture, static_cast<D3DCUBEMAP_FACES>(Face), Level, imageDesc);
if (image) {
char label[128];
if (Type == D3DRTYPE_CUBETEXTURE) {
_snprintf(label, sizeof label, "PS_RESOURCE_%lu_FACE_%lu_LEVEL_%lu", Stage, Face, Level);
} else {
_snprintf(label, sizeof label, "PS_RESOURCE_%lu_LEVEL_%lu", Stage, Level);
}
writer.beginMember(label);
writer.writeImage(image, imageDesc);
writer.endMember(); // PS_RESOURCE_*
delete image;
}
}
}
}
writer.endObject();
writer.endMember(); // textures
}
void
dumpFramebuffer(StateWriter &writer, IDirect3DDevice9 *pDevice)
{
HRESULT hr;
writer.beginMember("framebuffer");
writer.beginObject();
D3DCAPS9 Caps;
pDevice->GetDeviceCaps(&Caps);
for (UINT i = 0; i < Caps.NumSimultaneousRTs; ++i) {
com_ptr<IDirect3DSurface9> pRenderTarget;
hr = pDevice->GetRenderTarget(i, &pRenderTarget);
if (FAILED(hr)) {
continue;
}
if (!pRenderTarget) {
continue;
}
image::Image *image;
struct StateWriter::ImageDesc imageDesc;
image = getRenderTargetImage(pDevice, pRenderTarget, imageDesc);
if (image) {
char label[64];
_snprintf(label, sizeof label, "RENDER_TARGET_%u", i);
writer.beginMember(label);
writer.writeImage(image, imageDesc);
writer.endMember(); // RENDER_TARGET_*
delete image;
}
}
com_ptr<IDirect3DSurface9> pDepthStencil;
hr = pDevice->GetDepthStencilSurface(&pDepthStencil);
if (SUCCEEDED(hr) && pDepthStencil) {
image::Image *image;
struct StateWriter::ImageDesc imageDesc;
image = getSurfaceImage(pDevice, pDepthStencil, imageDesc);
if (image) {
writer.beginMember("DEPTH_STENCIL");
writer.writeImage(image, imageDesc);
writer.endMember(); // DEPTH_STENCIL
delete image;
}
}
writer.endObject();
writer.endMember(); // framebuffer
}
} /* namespace d3dstate */
<commit_msg>d3dretrace: Split dumpFramebuffer into two functions<commit_after>/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include "image.hpp"
#include "state_writer.hpp"
#include "com_ptr.hpp"
#include "d3d9state.hpp"
#include "d3dstate.hpp"
namespace d3dstate {
static image::Image *
getSurfaceImage(IDirect3DDevice9 *pDevice,
IDirect3DSurface9 *pSurface,
struct StateWriter::ImageDesc &imageDesc) {
image::Image *image = NULL;
HRESULT hr;
if (!pSurface) {
return NULL;
}
D3DSURFACE_DESC Desc;
hr = pSurface->GetDesc(&Desc);
assert(SUCCEEDED(hr));
if (Desc.Format == D3DFMT_NULL) {
// dummy rendertarget
return NULL;
}
D3DLOCKED_RECT LockedRect;
hr = pSurface->LockRect(&LockedRect, NULL, D3DLOCK_READONLY);
if (FAILED(hr)) {
return NULL;
}
image = ConvertImage(Desc.Format, LockedRect.pBits, LockedRect.Pitch, Desc.Width, Desc.Height);
pSurface->UnlockRect();
imageDesc.format = formatToString(Desc.Format);
return image;
}
static image::Image *
getRenderTargetImage(IDirect3DDevice9 *pDevice,
IDirect3DSurface9 *pRenderTarget,
struct StateWriter::ImageDesc &imageDesc) {
HRESULT hr;
if (!pRenderTarget) {
return NULL;
}
D3DSURFACE_DESC Desc;
hr = pRenderTarget->GetDesc(&Desc);
assert(SUCCEEDED(hr));
if (Desc.Format == D3DFMT_NULL) {
// dummy rendertarget
return NULL;
}
com_ptr<IDirect3DSurface9> pStagingSurface;
hr = pDevice->CreateOffscreenPlainSurface(Desc.Width, Desc.Height, Desc.Format, D3DPOOL_SYSTEMMEM, &pStagingSurface, NULL);
if (FAILED(hr)) {
return NULL;
}
hr = pDevice->GetRenderTargetData(pRenderTarget, pStagingSurface);
if (FAILED(hr)) {
std::cerr << "warning: GetRenderTargetData failed\n";
return NULL;
}
return getSurfaceImage(pDevice, pStagingSurface, imageDesc);
}
image::Image *
getRenderTargetImage(IDirect3DDevice9 *pDevice) {
HRESULT hr;
struct StateWriter::ImageDesc imageDesc;
com_ptr<IDirect3DSurface9> pRenderTarget;
hr = pDevice->GetRenderTarget(0, &pRenderTarget);
if (FAILED(hr)) {
return NULL;
}
assert(pRenderTarget);
return getRenderTargetImage(pDevice, pRenderTarget, imageDesc);
}
image::Image *
getRenderTargetImage(IDirect3DSwapChain9 *pSwapChain) {
HRESULT hr;
struct StateWriter::ImageDesc imageDesc;
com_ptr<IDirect3DDevice9> pDevice;
hr = pSwapChain->GetDevice(&pDevice);
if (FAILED(hr)) {
return NULL;
}
// TODO: Use GetFrontBufferData instead??
com_ptr<IDirect3DSurface9> pBackBuffer;
hr = pSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer);
if (FAILED(hr)) {
return NULL;
}
assert(pBackBuffer);
return getRenderTargetImage(pDevice, pBackBuffer, imageDesc);
}
static image::Image *
getTextureImage(IDirect3DDevice9 *pDevice,
IDirect3DBaseTexture9 *pTexture,
D3DCUBEMAP_FACES FaceType,
UINT Level,
struct StateWriter::ImageDesc &imageDesc)
{
HRESULT hr;
if (!pTexture) {
return NULL;
}
com_ptr<IDirect3DSurface9> pSurface;
D3DRESOURCETYPE Type = pTexture->GetType();
switch (Type) {
case D3DRTYPE_TEXTURE:
assert(FaceType == D3DCUBEMAP_FACE_POSITIVE_X);
hr = reinterpret_cast<IDirect3DTexture9 *>(pTexture)->GetSurfaceLevel(Level, &pSurface);
break;
case D3DRTYPE_CUBETEXTURE:
hr = reinterpret_cast<IDirect3DCubeTexture9 *>(pTexture)->GetCubeMapSurface(FaceType, Level, &pSurface);
break;
default:
/* TODO: support volume textures */
return NULL;
}
if (FAILED(hr) || !pSurface) {
return NULL;
}
D3DSURFACE_DESC Desc;
hr = pSurface->GetDesc(&Desc);
assert(SUCCEEDED(hr));
if (Desc.Pool != D3DPOOL_DEFAULT ||
Desc.Usage & D3DUSAGE_DYNAMIC) {
// Lockable texture
return getSurfaceImage(pDevice, pSurface, imageDesc);
} else if (Desc.Usage & D3DUSAGE_RENDERTARGET) {
// Rendertarget texture
return getRenderTargetImage(pDevice, pSurface, imageDesc);
} else {
// D3D constraints are such there is not much else that can be done.
return NULL;
}
}
void
dumpTextures(StateWriter &writer, IDirect3DDevice9 *pDevice)
{
HRESULT hr;
writer.beginMember("textures");
writer.beginObject();
for (DWORD Stage = 0; Stage < 16; ++Stage) {
com_ptr<IDirect3DBaseTexture9> pTexture;
hr = pDevice->GetTexture(Stage, &pTexture);
if (FAILED(hr)) {
continue;
}
if (!pTexture) {
continue;
}
D3DRESOURCETYPE Type = pTexture->GetType();
DWORD NumFaces = Type == D3DRTYPE_CUBETEXTURE ? 6 : 1;
DWORD NumLevels = pTexture->GetLevelCount();
for (DWORD Face = 0; Face < NumFaces; ++Face) {
for (DWORD Level = 0; Level < NumLevels; ++Level) {
image::Image *image;
struct StateWriter::ImageDesc imageDesc;
image = getTextureImage(pDevice, pTexture, static_cast<D3DCUBEMAP_FACES>(Face), Level, imageDesc);
if (image) {
char label[128];
if (Type == D3DRTYPE_CUBETEXTURE) {
_snprintf(label, sizeof label, "PS_RESOURCE_%lu_FACE_%lu_LEVEL_%lu", Stage, Face, Level);
} else {
_snprintf(label, sizeof label, "PS_RESOURCE_%lu_LEVEL_%lu", Stage, Level);
}
writer.beginMember(label);
writer.writeImage(image, imageDesc);
writer.endMember(); // PS_RESOURCE_*
delete image;
}
}
}
}
writer.endObject();
writer.endMember(); // textures
}
static void
dumpRenderTargets(StateWriter &writer,
IDirect3DDevice9 *pDevice)
{
HRESULT hr;
D3DCAPS9 Caps;
pDevice->GetDeviceCaps(&Caps);
for (UINT i = 0; i < Caps.NumSimultaneousRTs; ++i) {
com_ptr<IDirect3DSurface9> pRenderTarget;
hr = pDevice->GetRenderTarget(i, &pRenderTarget);
if (FAILED(hr)) {
continue;
}
if (!pRenderTarget) {
continue;
}
image::Image *image;
struct StateWriter::ImageDesc imageDesc;
image = getRenderTargetImage(pDevice, pRenderTarget, imageDesc);
if (image) {
char label[64];
_snprintf(label, sizeof label, "RENDER_TARGET_%u", i);
writer.beginMember(label);
writer.writeImage(image, imageDesc);
writer.endMember(); // RENDER_TARGET_*
delete image;
}
}
}
static void
dumpDepthStencil(StateWriter &writer,
IDirect3DDevice9 *pDevice,
com_ptr<IDirect3DSurface9> &pDepthStencil)
{
image::Image *image;
struct StateWriter::ImageDesc imageDesc;
if (!pDepthStencil)
return;
image = getSurfaceImage(pDevice, pDepthStencil, imageDesc);
if (image) {
writer.beginMember("DEPTH_STENCIL");
writer.writeImage(image, imageDesc);
writer.endMember(); // DEPTH_STENCIL
delete image;
}
}
void
dumpFramebuffer(StateWriter &writer, IDirect3DDevice9 *pDevice)
{
HRESULT hr;
writer.beginMember("framebuffer");
writer.beginObject();
dumpRenderTargets(writer, pDevice);
com_ptr<IDirect3DSurface9> pDepthStencil;
hr = pDevice->GetDepthStencilSurface(&pDepthStencil);
if (SUCCEEDED(hr))
dumpDepthStencil(writer, pDevice, pDepthStencil);
writer.endObject();
writer.endMember(); // framebuffer
}
} /* namespace d3dstate */
<|endoftext|> |
<commit_before>// Arkadij Doronin 24.05.2013
// ircBot
#include <cstdlib>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#ifdef WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#endif
const unsigned int MAX_LINE = 1024; // input Buffer Size
const int PORT = 6667;
const char *HOST = "irc.europa-irc.de"
using namespace std;
//--- Win. spezifisch ----------------
#ifdef WIN32
SOCKET sockfd;
#else
int sockfd;
#endif
void IrcDisconnect(){
#ifdef WIN32
closesocket(sockfd); // Win. spezifisch: Sockets-Freigabe
WSACleanup();
#else
close(sockfd); // Unix. spezifisch: Sockets-Freigabe
#endif
}
void IrcConnect(){
#ifdef WIN32
// Win. spezifisch: Sockets-Initialisierung
WSADATA wsa;
if(WSAStartup(MAKEWORD(2,0),&wsa) != 0) exit(1);
#endif
// Unix. spezifisch: Sockets-Initialisierung
sockfd = socket(AF_INET, SOCK_STREAM,0);
if (static_cast<int>(sockfd) < 0) {
perror("socket()");
IrcDisconnect();
exit(1);
}
hostent *hp = gethostbyname(HOST);
if (!hp) {
cerr << "gethostbyname()" << endl;
IrcDisconnect();
exit(1);
}
sockaddr_in sin;
memset((char*)&sin,0,sizeof(sin));
sin.sin_family = AF_INET;
memcpy((char*)&sin.sin_addr, hp->h_addr, hp->h_length);
sin.sin_port = htons(PORT);
memset(&(sin.sin_zero),0,8*sizeof(char));
if (connect(sockfd,(sockaddr*)&sin,sizeof(sin)) == -1) {
perror("connect()");
IrcDisconnect();
exit(1);
}
}
void SendToUplink(const char *msg){
send(sockfd, msg, strlen(msg), 0);
}
void IrcIdentify(){
SendToUplink("NICK_NAME Bot\r\n");
SendToUplink("USER_NAME Bot 0 0 :Bot\r\n");
SendToUplink("PRIVMSG NickServ IDENTIFY password\r\n");
SendToUplink("JOIN #channel\r\n");
SendToUplink("PRIVMSG #channel: Hallo!!!\r\n");
}
void PingParse(const string &buffer){
size_t pingPos = buffer.find("PING");
if (pingPos != string::npos) {
string pong("PONG" + buffer.substr(pingPos + 4) + "\r\n");
cout << pong;
SendToUplink(pong.c_str());
}
}
void BotFunctions(const string &buffer){
size_t pos = 0;
if ((pos = buffer.find(":say")) != string::npos) {
SendToUplink(("PRIVMSG #channel:" + buffer.substr(pos + 5) + "\r\n").c_str());
} else if (buffer.find(":User!User@User.user.insiderZ.DE") == 0 && buffer.find("exit") != string::npos){
SendToUplink("PRIVMSG #channel:Cya\r\n");
IrcDisconnect();
exit(0);
}
}
void IrcParse(string buffer){
if (buffer.find("\r\n") == buffer.length() - 2) {
buffer.erase(buffer.length() - 2);
BotFunctions(buffer);
}
}
<commit_msg>ircBot.cpp wurde modofiziert<commit_after>// Arkadij Doronin 24.05.2013
// ircBot
#include <cstdlib>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#ifdef WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#endif
const unsigned int MAX_LINE = 1024; // input Buffer Size
const int PORT = 6667;
const char *HOST = "irc.europa-irc.de"
void IrcDisconnect();
void IrcConnect();
void SendToUplink(const char *msg);
void IrcIdentify();
void PingParse(const string &buffer);
void BotFunctions(const string &buffer);
void IrcParse(string buffer);
using namespace std;
//--- Win. spezifisch ----------------
#ifdef WIN32
SOCKET sockfd;
#else
int sockfd;
#endif
void IrcDisconnect(){
#ifdef WIN32
closesocket(sockfd); // Win. spezifisch: Sockets-Freigabe
WSACleanup();
#else
close(sockfd); // Unix. spezifisch: Sockets-Freigabe
#endif
}
void IrcConnect(){
#ifdef WIN32
// Win. spezifisch: Sockets-Initialisierung
WSADATA wsa;
if(WSAStartup(MAKEWORD(2,0),&wsa) != 0) exit(1);
#endif
// Unix. spezifisch: Sockets-Initialisierung
sockfd = socket(AF_INET, SOCK_STREAM,0);
if (static_cast<int>(sockfd) < 0) {
perror("socket()");
IrcDisconnect();
exit(1);
}
hostent *hp = gethostbyname(HOST);
if (!hp) {
cerr << "gethostbyname()" << endl;
IrcDisconnect();
exit(1);
}
sockaddr_in sin;
memset((char*)&sin,0,sizeof(sin));
sin.sin_family = AF_INET;
memcpy((char*)&sin.sin_addr, hp->h_addr, hp->h_length);
sin.sin_port = htons(PORT);
memset(&(sin.sin_zero),0,8*sizeof(char));
if (connect(sockfd,(sockaddr*)&sin,sizeof(sin)) == -1) {
perror("connect()");
IrcDisconnect();
exit(1);
}
}
void SendToUplink(const char *msg){
send(sockfd, msg, strlen(msg), 0);
}
void IrcIdentify(){
SendToUplink("NICK_NAME Bot\r\n");
SendToUplink("USER_NAME Bot 0 0 :Bot\r\n");
SendToUplink("PRIVMSG NickServ IDENTIFY password\r\n");
SendToUplink("JOIN #channel\r\n");
SendToUplink("PRIVMSG #channel: Hallo!!!\r\n");
}
void PingParse(const string &buffer){
size_t pingPos = buffer.find("PING");
if (pingPos != string::npos) {
string pong("PONG" + buffer.substr(pingPos + 4) + "\r\n");
cout << pong;
SendToUplink(pong.c_str());
}
}
void BotFunctions(const string &buffer){
size_t pos = 0;
if ((pos = buffer.find(":say")) != string::npos) {
SendToUplink(("PRIVMSG #channel:" + buffer.substr(pos + 5) + "\r\n").c_str());
} else if (buffer.find(":User!User@User.user.insiderZ.DE") == 0 && buffer.find("exit") != string::npos){
SendToUplink("PRIVMSG #channel:Cya\r\n");
IrcDisconnect();
exit(0);
}
}
void IrcParse(string buffer){
if (buffer.find("\r\n") == buffer.length() - 2) {
buffer.erase(buffer.length() - 2);
PingParse(buffer);
BotFunctions(buffer);
}
}
<|endoftext|> |
<commit_before>// Arkadij Doronin 24.05.2013
// ircBot
#include <cstdlib>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#ifdef WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#endif
// 20
using namespace std;
const unsigned int BUFF_SIZE = 1024; // input Buffer Size
const int PORT = 6667;
const char *HOST = "irc.europa-irc.de";
void IrcDisconnect();
void IrcConnect();
void SendToUplink(const char *msg);
void IrcIdentify();
void PingParse(const string & buffer);
void BotFunctions(const string & buffer);
void IrcParse(string buffer);
//--- Win. spezifisch ----------------
#ifdef WIN32
SOCKET sockfd;
#else
int sockfd;
#endif
int main(){
IrcConnect();
IrcIdentify();
while (1) {
char buffer[BUFF_SIZE + 1] = {0};
if (recv(sockfd, buffer, BUFF_SIZE * sizeof(char), 0) < 0) {
perror("recv()");
IrcDisconnect();
exit(1);
}
cout << buffer;
IrcParse(buffer);
}
IrcDisconnect();
}
void IrcDisconnect(){
#ifdef WIN32
closesocket(sockfd); // Win. spezifisch: Sockets-Freigabe
WSACleanup();
#else
close(sockfd); // Unix. spezifisch: Sockets-Freigabe
#endif
}
void IrcConnect(){
#ifdef WIN32
// Win. spezifisch: Sockets-Initialisierung
WSADATA wsa;
if(WSAStartup(MAKEWORD(2,0),&wsa) != 0) exit(1);
#endif
// Unix. spezifisch: Sockets-Initialisierung
sockfd = socket(AF_INET, SOCK_STREAM,0);
if (static_cast<int>(sockfd) < 0) {
perror("socket()");
IrcDisconnect();
exit(1);
}
hostent *hp = gethostbyname(HOST);
if (!hp) {
cerr << "gethostbyname()" << endl;
IrcDisconnect();
exit(1);
}
sockaddr_in sin;
memset((char*)&sin,0,sizeof(sin));
sin.sin_family = AF_INET;
memcpy((char*)&sin.sin_addr, hp->h_addr, hp->h_length);
sin.sin_port = htons(PORT);
memset(&(sin.sin_zero),0,8*sizeof(char));
if (connect(sockfd,(sockaddr*)&sin,sizeof(sin)) == -1) {
perror("connect()");
IrcDisconnect();
exit(1);
}
}
void SendToUplink(const char *msg){
send(sockfd, msg, strlen(msg), 0);
}
void IrcIdentify(){
SendToUplink("NICK_NAME Bot\r\n");
SendToUplink("USER_NAME Bot 0 0 :Bot\r\n");
SendToUplink("PRIVMSG NickServ IDENTIFY password\r\n");
SendToUplink("JOIN #channel\r\n");
SendToUplink("PRIVMSG #channel: Hallo!!!\r\n");
}
void PingParse(const string &buffer){
size_t pingPos = buffer.find("PING");
if (pingPos != string::npos) {
string pong("PONG" + buffer.substr(pingPos + 4) + "\r\n");
cout << pong;
SendToUplink(pong.c_str());
}
}
void BotFunctions(const string &buffer){
size_t pos = 0;
if ((pos = buffer.find(":say")) != string::npos) {
SendToUplink(("PRIVMSG #channel:" + buffer.substr(pos + 5) + "\r\n").c_str());
} else if (buffer.find(":User!User@User.user.insiderZ.DE") == 0 && buffer.find("exit") != string::npos){
SendToUplink("PRIVMSG #channel:Cya\r\n");
IrcDisconnect();
exit(0);
}
}
void IrcParse(string buffer){
if (buffer.find("\r\n") == buffer.length() - 2) {
buffer.erase(buffer.length() - 2);
PingParse(buffer);
BotFunctions(buffer);
}
}
<commit_msg>ircBot.cpp wurde modofiziert<commit_after>// Arkadij Doronin 24.05.2013
// ircBot
#include <cstdlib>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#ifdef WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#endif
// 20
using namespace std;
const unsigned int BUFF_SIZE = 1024; // input Buffer Size
const int PORT = 6667;
const char *HOST = "irc.europa-irc.de";
void IrcDisconnect();
void IrcConnect();
void SendToUplink(const char *msg);
void IrcIdentify();
void PingParse(const string & buffer);
void BotFunctions(const string & buffer);
void IrcParse(string buffer);
//--- Win. spezifisch ----------------
#ifdef WIN32
SOCKET sockfd;
#else
int sockfd;
#endif
int main(){
IrcConnect();
IrcIdentify();
while (1) {
char buffer[BUFF_SIZE + 1] = {0};
if (recv(sockfd, buffer, BUFF_SIZE * sizeof(char), 0) < 0) {
perror("recv()");
IrcDisconnect();
exit(1);
}
cout << buffer;
IrcParse(buffer);
}
IrcDisconnect();
}
void IrcDisconnect(){
#ifdef WIN32
closesocket(sockfd); // Win. spezifisch: Sockets-Freigabe
WSACleanup();
#else
close(sockfd); // Unix. spezifisch: Sockets-Freigabe
#endif
}
void IrcConnect(){
#ifdef WIN32
// Win. spezifisch: Sockets-Initialisierung
WSADATA wsa;
if(WSAStartup(MAKEWORD(2,0),&wsa) != 0) exit(1);
#endif
// Unix. spezifisch: Sockets-Initialisierung
sockfd = socket(AF_INET, SOCK_STREAM,0);
if (static_cast<int>(sockfd) < 0) {
perror("socket()");
IrcDisconnect();
exit(1);
}
hostent *hp = gethostbyname(HOST);
if (!hp) {
cerr << "gethostbyname()" << endl;
IrcDisconnect();
exit(1);
}
sockaddr_in sin;
memset((char*)&sin,0,sizeof(sin));
sin.sin_family = AF_INET;
memcpy((char*)&sin.sin_addr, hp->h_addr, hp->h_length);
sin.sin_port = htons(PORT);
memset(&(sin.sin_zero),0,8*sizeof(char));
if (connect(sockfd,(sockaddr*)&sin,sizeof(sin)) == -1) {
perror("connect()");
IrcDisconnect();
exit(1);
}
}
void SendToUplink(const char *msg){
send(sockfd, msg, strlen(msg), 0);
}
void IrcIdentify(){
SendToUplink("NICK_NAME Bot\r\n"); // NICK
SendToUplink("USER_NAME Bot 0 0 :Bot\r\n"); // Userdaten
SendToUplink("PRIVMSG NickServ IDENTIFY password\r\n"); // Identifizieren
SendToUplink("JOIN #channel\r\n"); // Betreten Channel
SendToUplink("PRIVMSG #channel :Hallo, I'm a Mega-Bot!!!\r\n"); // Nachricht Nr.1
}
void PingParse(const string &buffer){
size_t pingPos = buffer.find("PING");
if (pingPos != string::npos) {
string pong("PONG" + buffer.substr(pingPos + 4) + "\r\n");
cout << pong;
SendToUplink(pong.c_str());
}
}
void BotFunctions(const string &buffer){
size_t pos = 0;
if ((pos = buffer.find(":say")) != string::npos) {
SendToUplink(("PRIVMSG #channel:" + buffer.substr(pos + 5) + "\r\n").c_str());
} else if (buffer.find(":User!User@User.user.insiderZ.DE") == 0 && buffer.find("exit") != string::npos){
SendToUplink("PRIVMSG #channel:Cya\r\n");
IrcDisconnect();
exit(0);
}
}
void IrcParse(string buffer){
if (buffer.find("\r\n") == buffer.length() - 2) {
buffer.erase(buffer.length() - 2);
PingParse(buffer);
BotFunctions(buffer);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DAVResourceAccess.hxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: hr $ $Date: 2006-06-20 05:34:16 $
*
* 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 _DAVRESOURCEACCESS_HXX_
#define _DAVRESOURCEACCESS_HXX_
#include <vector>
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_LOCK_HPP_
#include <com/sun/star/ucb/Lock.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#endif
#ifndef _DAVAUTHLISTENER_HXX_
#include "DAVAuthListener.hxx"
#endif
#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif
#ifndef _DAVSESSION_HXX_
#include "DAVSession.hxx"
#endif
#ifndef _DAVRESOURCE_HXX_
#include "DAVResource.hxx"
#endif
#ifndef _DAVTYPES_HXX_
#include "DAVTypes.hxx"
#endif
#ifndef _NEONURI_HXX_
#include "NeonUri.hxx"
#endif
namespace webdav_ucp
{
class DAVSessionFactory;
class DAVResourceAccess
{
osl::Mutex m_aMutex;
rtl::OUString m_aURL;
rtl::OUString m_aPath;
rtl::Reference< DAVSession > m_xSession;
rtl::Reference< DAVSessionFactory > m_xSessionFactory;
com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory > m_xSMgr;
std::vector< NeonUri > m_aRedirectURIs;
public:
DAVResourceAccess() : m_xSessionFactory( 0 ) {}
DAVResourceAccess( const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory > & rSMgr,
rtl::Reference<
DAVSessionFactory > const & rSessionFactory,
const rtl::OUString & rURL );
DAVResourceAccess( const DAVResourceAccess & rOther );
DAVResourceAccess & operator=( const DAVResourceAccess & rOther );
void setURL( const rtl::OUString & rNewURL )
throw( DAVException );
const rtl::OUString & getURL() const { return m_aURL; }
rtl::Reference< DAVSessionFactory > getSessionFactory() const
{ return m_xSessionFactory; }
// DAV methods
//
void
OPTIONS( DAVCapabilities & rCapabilities,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
// allprop & named
void
PROPFIND( const Depth nDepth,
const std::vector< rtl::OUString > & rPropertyNames,
std::vector< DAVResource > & rResources,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
// propnames
void
PROPFIND( const Depth nDepth,
std::vector< DAVResourceInfo > & rResInfo,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
PROPPATCH( const std::vector< ProppatchValue > & rValues,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment >& xEnv )
throw( DAVException );
void
HEAD( const std::vector< rtl::OUString > & rHeaderNames, // empty == 'all'
DAVResource & rResource,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment >& xEnv )
throw( DAVException );
com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
GET( const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
GET( com::sun::star::uno::Reference<
com::sun::star::io::XOutputStream > & rStream,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
GET( const std::vector< rtl::OUString > & rHeaderNames, // empty == 'all'
DAVResource & rResource,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
GET( com::sun::star::uno::Reference<
com::sun::star::io::XOutputStream > & rStream,
const std::vector< rtl::OUString > & rHeaderNames, // empty == 'all'
DAVResource & rResource,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
PUT( const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & rStream,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
POST( const rtl::OUString & rContentType,
const rtl::OUString & rReferer,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & rInputStream,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment >& xEnv )
throw ( DAVException );
void
POST( const rtl::OUString & rContentType,
const rtl::OUString & rReferer,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & rInputStream,
com::sun::star::uno::Reference<
com::sun::star::io::XOutputStream > & rOutputStream,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment >& xEnv )
throw ( DAVException );
void
MKCOL( const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
COPY( const ::rtl::OUString & rSourcePath,
const ::rtl::OUString & rDestinationURI,
sal_Bool bOverwrite,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
MOVE( const ::rtl::OUString & rSourcePath,
const ::rtl::OUString & rDestinationURI,
sal_Bool bOverwrite,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
DESTROY( const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
LOCK ( const com::sun::star::ucb::Lock & rLock,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
UNLOCK ( const com::sun::star::ucb::Lock & rLock,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
private:
const rtl::OUString & getRequestURI() const;
sal_Bool detectRedirectCycle( const rtl::OUString& rRedirectURL );
sal_Bool handleException( DAVException & e );
void initialize()
throw ( DAVException );
};
} // namespace webdav_ucp
#endif // _DAVRESOURCEACCESS_HXX_
<commit_msg>INTEGRATION: CWS updatefeed (1.14.42); FILE MERGED 2006/12/04 16:54:47 kso 1.14.42.1: #i72055# - Added support for XWebDAVCommandEnvironment.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DAVResourceAccess.hxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: kz $ $Date: 2006-12-13 15:04:16 $
*
* 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 _DAVRESOURCEACCESS_HXX_
#define _DAVRESOURCEACCESS_HXX_
#include <vector>
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_LOCK_HPP_
#include <com/sun/star/ucb/Lock.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#endif
#ifndef _DAVAUTHLISTENER_HXX_
#include "DAVAuthListener.hxx"
#endif
#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif
#ifndef _DAVSESSION_HXX_
#include "DAVSession.hxx"
#endif
#ifndef _DAVRESOURCE_HXX_
#include "DAVResource.hxx"
#endif
#ifndef _DAVTYPES_HXX_
#include "DAVTypes.hxx"
#endif
#ifndef _NEONURI_HXX_
#include "NeonUri.hxx"
#endif
namespace webdav_ucp
{
class DAVSessionFactory;
class DAVResourceAccess
{
osl::Mutex m_aMutex;
rtl::OUString m_aURL;
rtl::OUString m_aPath;
rtl::Reference< DAVSession > m_xSession;
rtl::Reference< DAVSessionFactory > m_xSessionFactory;
com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory > m_xSMgr;
std::vector< NeonUri > m_aRedirectURIs;
public:
DAVResourceAccess() : m_xSessionFactory( 0 ) {}
DAVResourceAccess( const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory > & rSMgr,
rtl::Reference<
DAVSessionFactory > const & rSessionFactory,
const rtl::OUString & rURL );
DAVResourceAccess( const DAVResourceAccess & rOther );
DAVResourceAccess & operator=( const DAVResourceAccess & rOther );
void setURL( const rtl::OUString & rNewURL )
throw( DAVException );
const rtl::OUString & getURL() const { return m_aURL; }
rtl::Reference< DAVSessionFactory > getSessionFactory() const
{ return m_xSessionFactory; }
// DAV methods
//
void
OPTIONS( DAVCapabilities & rCapabilities,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
// allprop & named
void
PROPFIND( const Depth nDepth,
const std::vector< rtl::OUString > & rPropertyNames,
std::vector< DAVResource > & rResources,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
// propnames
void
PROPFIND( const Depth nDepth,
std::vector< DAVResourceInfo > & rResInfo,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
PROPPATCH( const std::vector< ProppatchValue > & rValues,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment >& xEnv )
throw( DAVException );
void
HEAD( const std::vector< rtl::OUString > & rHeaderNames, // empty == 'all'
DAVResource & rResource,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment >& xEnv )
throw( DAVException );
com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
GET( const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
GET( com::sun::star::uno::Reference<
com::sun::star::io::XOutputStream > & rStream,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
GET( const std::vector< rtl::OUString > & rHeaderNames, // empty == 'all'
DAVResource & rResource,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
GET( com::sun::star::uno::Reference<
com::sun::star::io::XOutputStream > & rStream,
const std::vector< rtl::OUString > & rHeaderNames, // empty == 'all'
DAVResource & rResource,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
PUT( const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & rStream,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
POST( const rtl::OUString & rContentType,
const rtl::OUString & rReferer,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & rInputStream,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment >& xEnv )
throw ( DAVException );
void
POST( const rtl::OUString & rContentType,
const rtl::OUString & rReferer,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & rInputStream,
com::sun::star::uno::Reference<
com::sun::star::io::XOutputStream > & rOutputStream,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment >& xEnv )
throw ( DAVException );
void
MKCOL( const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
COPY( const ::rtl::OUString & rSourcePath,
const ::rtl::OUString & rDestinationURI,
sal_Bool bOverwrite,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
MOVE( const ::rtl::OUString & rSourcePath,
const ::rtl::OUString & rDestinationURI,
sal_Bool bOverwrite,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
DESTROY( const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
LOCK( const com::sun::star::ucb::Lock & rLock,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
void
UNLOCK( const com::sun::star::ucb::Lock & rLock,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( DAVException );
// helper
static void getUserRequestHeaders(
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv,
const rtl::OUString & rURI,
const rtl::OUString & rMethod,
DAVRequestHeaders & rRequestHeaders );
private:
const rtl::OUString & getRequestURI() const;
sal_Bool detectRedirectCycle( const rtl::OUString& rRedirectURL );
sal_Bool handleException( DAVException & e );
void initialize()
throw ( DAVException );
};
} // namespace webdav_ucp
#endif // _DAVRESOURCEACCESS_HXX_
<|endoftext|> |
<commit_before>/*
The MIT License
Copyright (c) 2012 by Jorrit Tyberghein
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 "cssysdef.h"
#include "csutil/csinput.h"
#include "cstool/cspixmap.h"
#include "csgeom/math3d.h"
#include "iutil/objreg.h"
#include "iutil/virtclk.h"
#include "ivideo/graph3d.h"
#include "ivideo/graph2d.h"
#include "ivideo/fontserv.h"
#include "ivideo/txtmgr.h"
#include "iengine/engine.h"
#include "iengine/texture.h"
#include "iengine/camera.h"
#include "iengine/movable.h"
#include "gamecontrol.h"
#include "physicallayer/pl.h"
#include "physicallayer/entity.h"
#include "propclass/camera.h"
#include "propclass/dynworld.h"
#include "propclass/dynmove.h"
#include "propclass/prop.h"
#include "ivaria/dynamics.h"
//---------------------------------------------------------------------------
CEL_IMPLEMENT_FACTORY (GameController, "ares.gamecontrol")
//---------------------------------------------------------------------------
csStringID celPcGameController::id_message = csInvalidStringID;
csStringID celPcGameController::id_timeout = csInvalidStringID;
PropertyHolder celPcGameController::propinfo;
celPcGameController::celPcGameController (iObjectRegistry* object_reg)
: scfImplementationType (this, object_reg)
{
// For SendMessage parameters.
if (id_message == csInvalidStringID)
{
id_message = pl->FetchStringID ("message");
id_timeout = pl->FetchStringID ("timeout");
}
propholder = &propinfo;
// For actions.
if (!propinfo.actions_done)
{
SetActionMask ("ares.controller.");
AddAction (action_message, "Message");
AddAction (action_startdrag, "StartDrag");
AddAction (action_stopdrag, "StopDrag");
AddAction (action_examine, "Examine");
}
// For properties.
propinfo.SetCount (0);
//AddProperty (propid_counter, "counter",
//CEL_DATA_LONG, false, "Print counter.", &counter);
//AddProperty (propid_max, "max",
//CEL_DATA_LONG, false, "Max length.", 0);
dragobj = 0;
mouse = csQueryRegistry<iMouseDriver> (object_reg);
g3d = csQueryRegistry<iGraphics3D> (object_reg);
vc = csQueryRegistry<iVirtualClock> (object_reg);
g2d = g3d->GetDriver2D ();
engine = csQueryRegistry<iEngine> (object_reg);
pl->CallbackEveryFrame ((iCelTimerListener*)this, CEL_EVENT_POST);
messageColor = g3d->GetDriver2D ()->FindRGB (255, 255, 255);
iFontServer* fontsrv = g3d->GetDriver2D ()->GetFontServer ();
//font = fontsrv->LoadFont (CSFONT_COURIER);
font = fontsrv->LoadFont ("DejaVuSansBold", 10);
font->GetMaxSize (fontW, fontH);
classNoteID = pl->FetchStringID ("ares.note");
classInfoID = pl->FetchStringID ("ares.info");
classDragRotYID = pl->FetchStringID ("ares.drag.roty");
LoadIcons ();
}
celPcGameController::~celPcGameController ()
{
pl->RemoveCallbackEveryFrame ((iCelTimerListener*)this, CEL_EVENT_POST);
delete iconCursor;
delete iconEye;
delete iconBook;
delete iconDot;
}
void celPcGameController::LoadIcons ()
{
iTextureWrapper* txt;
txt = engine->CreateTexture ("icon_cursor",
"/icons/iconic_cursor_32x32.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconCursor = new csSimplePixmap (txt->GetTextureHandle ());
txt = engine->CreateTexture ("icon_dot",
"/icons/icon_dot.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconDot = new csSimplePixmap (txt->GetTextureHandle ());
txt = engine->CreateTexture ("icon_eye",
"/icons/iconic_eye_32x24.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconEye = new csSimplePixmap (txt->GetTextureHandle ());
txt = engine->CreateTexture ("icon_book",
"/icons/iconic_book_alt2_32x28.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconBook = new csSimplePixmap (txt->GetTextureHandle ());
}
void celPcGameController::TryGetDynworld ()
{
if (dynworld) return;
dynworld = celQueryPropertyClassEntity<iPcDynamicWorld> (entity);
if (dynworld) return;
// Not very clean. We should only depend on the dynworld plugin
// to be in this entity but for the editor we actually have the
// dynworld plugin in the 'Zone' entity. Need to find a way for this
// that is cleaner.
csRef<iCelEntity> zone = pl->FindEntity ("Zone");
if (!zone)
{
printf ("Can't find entity 'Zone' and current entity has no dynworld PC!\n");
return;
}
dynworld = celQueryPropertyClassEntity<iPcDynamicWorld> (zone);
iDynamicSystem* dynSys = dynworld->GetCurrentCell ()->GetDynamicSystem ();
bullet_dynSys = scfQueryInterface<CS::Physics::Bullet::iDynamicSystem> (dynSys);
}
void celPcGameController::TryGetCamera ()
{
if (pccamera && pcdynmove) return;
csRef<iCelEntity> player = pl->FindEntity ("Player");
if (!player)
{
printf ("Can't find entity 'Player'!\n");
return;
}
pccamera = celQueryPropertyClassEntity<iPcCamera> (player);
pcdynmove = celQueryPropertyClassEntity<iPcDynamicMove> (player);
}
bool celPcGameController::PerformActionIndexed (int idx,
iCelParameterBlock* params,
celData& ret)
{
switch (idx)
{
case action_message:
{
CEL_FETCH_STRING_PAR (msg,params,id_message);
if (!p_msg) return false;
CEL_FETCH_FLOAT_PAR (timeout,params,id_timeout);
if (!p_timeout) timeout = 2.0f;
Message (msg, timeout);
return true;
}
case action_startdrag:
return StartDrag ();
case action_stopdrag:
StopDrag ();
return true;
case action_examine:
Examine ();
return true;
default:
return false;
}
return false;
}
void celPcGameController::Examine ()
{
iRigidBody* hitBody;
csVector3 start, isect;
iDynamicObject* obj = FindCenterObject (hitBody, start, isect);
if (obj)
{
iCelEntity* ent = obj->GetEntity ();
if (ent && ent->HasClass (classInfoID))
{
csRef<iPcProperties> prop = celQueryPropertyClassEntity<iPcProperties> (ent);
if (!prop)
{
Message ("ERROR: Entity has no properties!");
return;
}
size_t idx = prop->GetPropertyIndex ("ares.info");
if (idx == csArrayItemNotFound)
{
Message ("ERROR: Entity has no 'ares.info' property!");
return;
}
Message (prop->GetPropertyString (idx));
}
else
{
Message ("I see nothing special!");
}
}
else
{
Message ("Nothing to examine!");
}
}
void celPcGameController::Message (const char* message, float timeout)
{
TimedMessage m;
m.message = message;
m.timeleft = timeout;
messages.Push (m);
printf ("MSG: %s\n", message);
fflush (stdout);
}
iDynamicObject* celPcGameController::FindCenterObject (iRigidBody*& hitBody,
csVector3& start, csVector3& isect)
{
TryGetCamera ();
TryGetDynworld ();
iCamera* cam = pccamera->GetCamera ();
if (!cam) return 0;
int x = mouse->GetLastX ();
int y = mouse->GetLastY ();
csVector2 v2d (x, g2d->GetHeight () - y);
csVector3 v3d = cam->InvPerspective (v2d, 3.0f);
start = cam->GetTransform ().GetOrigin ();
csVector3 end = cam->GetTransform ().This2Other (v3d);
// Trace the physical beam
CS::Physics::Bullet::HitBeamResult result = bullet_dynSys->HitBeam (start, end);
if (!result.body) return 0;
hitBody = result.body->QueryRigidBody ();
isect = result.isect;
return dynworld->FindObject (hitBody);
}
bool celPcGameController::StartDrag ()
{
iRigidBody* hitBody;
csVector3 start, isect;
iDynamicObject* obj = FindCenterObject (hitBody, start, isect);
if (obj)
{
dragobj = obj;
iCelEntity* ent = obj->GetEntity ();
if (ent && ent->HasClass (classDragRotYID))
{
printf ("Start roty drag!\n"); fflush (stdout);
dragType = DRAGTYPE_ROTY;
pcdynmove->EnableMouselook (false);
dragOrigin = obj->GetMesh ()->GetMovable ()->GetTransform ().GetOrigin ();
dragOrigin.y = isect.y;
dragAnchor = isect;
dragDistance = (isect - dragOrigin).Norm ();
}
else
{
printf ("Start normal drag!\n"); fflush (stdout);
dragType = DRAGTYPE_NORMAL;
dragDistance = (isect - start).Norm ();
}
dragJoint = bullet_dynSys->CreatePivotJoint ();
dragJoint->Attach (hitBody, isect);
// Set some dampening on the rigid body to have a more stable dragging
csRef<CS::Physics::Bullet::iRigidBody> csBody =
scfQueryInterface<CS::Physics::Bullet::iRigidBody> (hitBody);
oldLinearDampening = csBody->GetLinearDampener ();
oldAngularDampening = csBody->GetRollingDampener ();
csBody->SetLinearDampener (0.9f);
csBody->SetRollingDampener (0.9f);
return true;
}
return false;
}
void celPcGameController::StopDrag ()
{
if (!dragobj) return;
printf ("Stop drag!\n"); fflush (stdout);
csRef<CS::Physics::Bullet::iRigidBody> csBody =
scfQueryInterface<CS::Physics::Bullet::iRigidBody> (dragJoint->GetAttachedBody ());
csBody->SetLinearDampener (oldLinearDampening);
csBody->SetRollingDampener (oldAngularDampening);
bullet_dynSys->RemovePivotJoint (dragJoint);
dragJoint = 0;
dragobj = 0;
if (dragType == DRAGTYPE_ROTY)
pcdynmove->EnableMouselook (true);
}
static float sgn (float x)
{
if (x < 0.0f) return -1.0f;
else return 1.0f;
}
void celPcGameController::TickEveryFrame ()
{
csSimplePixmap* icon = iconDot;
int sw = g2d->GetWidth ();
int sh = g2d->GetHeight ();
if (dragobj)
{
iCamera* cam = pccamera->GetCamera ();
if (!cam) return;
int x = mouse->GetLastX ();
int y = mouse->GetLastY ();
csVector3 newPosition;
if (dragType == DRAGTYPE_ROTY)
{
int sx = x - sw / 2;
int sy = y - sh / 2;
g2d->SetMousePosition (sw / 2, sh / 2);
dragAnchor.x -= float (sx) / 200.0f;
dragAnchor.z -= float (sy) / 200.0f;
newPosition = dragAnchor - dragOrigin;
newPosition.Normalize ();
newPosition = dragOrigin + newPosition * dragDistance;
icon = iconDot;
}
else
{
csVector2 v2d (x, sh - y);
csVector3 v3d = cam->InvPerspective (v2d, 3.0f);
csVector3 start = cam->GetTransform ().GetOrigin ();
csVector3 end = cam->GetTransform ().This2Other (v3d);
newPosition = end - start;
newPosition.Normalize ();
newPosition = cam->GetTransform ().GetOrigin () + newPosition * dragDistance;
icon = iconCursor;
}
dragJoint->SetPosition (newPosition);
}
else
{
iRigidBody* hitBody;
csVector3 start, isect;
iDynamicObject* obj = FindCenterObject (hitBody, start, isect);
if (obj)
{
iCelEntity* ent = obj->GetEntity ();
if (ent && ent->HasClass (classNoteID))
{
icon = iconBook;
}
else if (ent && ent->HasClass (classInfoID))
{
icon = iconEye;
}
else if (!obj->IsStatic ())
{
icon = iconCursor;
}
}
}
g3d->BeginDraw (CSDRAW_2DGRAPHICS);
if (messages.GetSize () > 0)
{
float elapsed = vc->GetElapsedSeconds ();
int y = 20;
size_t i = 0;
while (i < messages.GetSize ())
{
TimedMessage& m = messages[i];
m.timeleft -= elapsed;
if (m.timeleft <= 0)
messages.DeleteIndex (i);
else
{
int alpha = 255;
if (m.timeleft < 1.0f) alpha = int (255.0f * (m.timeleft));
messageColor = g3d->GetDriver2D ()->FindRGB (255, 255, 255, alpha);
g2d->Write (font, 20, y, messageColor, -1, m.message.GetData ());
y += fontH + 2;
i++;
}
}
}
icon->Draw (g3d, sw / 2, sh / 2);
}
//---------------------------------------------------------------------------
<commit_msg>Door swinging is a lot more stable now. Still not perfect but we're getting close.<commit_after>/*
The MIT License
Copyright (c) 2012 by Jorrit Tyberghein
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 "cssysdef.h"
#include "csutil/csinput.h"
#include "cstool/cspixmap.h"
#include "csgeom/math3d.h"
#include "iutil/objreg.h"
#include "iutil/virtclk.h"
#include "ivideo/graph3d.h"
#include "ivideo/graph2d.h"
#include "ivideo/fontserv.h"
#include "ivideo/txtmgr.h"
#include "iengine/engine.h"
#include "iengine/texture.h"
#include "iengine/camera.h"
#include "iengine/movable.h"
#include "gamecontrol.h"
#include "physicallayer/pl.h"
#include "physicallayer/entity.h"
#include "propclass/camera.h"
#include "propclass/dynworld.h"
#include "propclass/dynmove.h"
#include "propclass/prop.h"
#include "ivaria/dynamics.h"
//---------------------------------------------------------------------------
CEL_IMPLEMENT_FACTORY (GameController, "ares.gamecontrol")
//---------------------------------------------------------------------------
csStringID celPcGameController::id_message = csInvalidStringID;
csStringID celPcGameController::id_timeout = csInvalidStringID;
PropertyHolder celPcGameController::propinfo;
celPcGameController::celPcGameController (iObjectRegistry* object_reg)
: scfImplementationType (this, object_reg)
{
// For SendMessage parameters.
if (id_message == csInvalidStringID)
{
id_message = pl->FetchStringID ("message");
id_timeout = pl->FetchStringID ("timeout");
}
propholder = &propinfo;
// For actions.
if (!propinfo.actions_done)
{
SetActionMask ("ares.controller.");
AddAction (action_message, "Message");
AddAction (action_startdrag, "StartDrag");
AddAction (action_stopdrag, "StopDrag");
AddAction (action_examine, "Examine");
}
// For properties.
propinfo.SetCount (0);
//AddProperty (propid_counter, "counter",
//CEL_DATA_LONG, false, "Print counter.", &counter);
//AddProperty (propid_max, "max",
//CEL_DATA_LONG, false, "Max length.", 0);
dragobj = 0;
mouse = csQueryRegistry<iMouseDriver> (object_reg);
g3d = csQueryRegistry<iGraphics3D> (object_reg);
vc = csQueryRegistry<iVirtualClock> (object_reg);
g2d = g3d->GetDriver2D ();
engine = csQueryRegistry<iEngine> (object_reg);
pl->CallbackEveryFrame ((iCelTimerListener*)this, CEL_EVENT_POST);
messageColor = g3d->GetDriver2D ()->FindRGB (255, 255, 255);
iFontServer* fontsrv = g3d->GetDriver2D ()->GetFontServer ();
//font = fontsrv->LoadFont (CSFONT_COURIER);
font = fontsrv->LoadFont ("DejaVuSansBold", 10);
font->GetMaxSize (fontW, fontH);
classNoteID = pl->FetchStringID ("ares.note");
classInfoID = pl->FetchStringID ("ares.info");
classDragRotYID = pl->FetchStringID ("ares.drag.roty");
LoadIcons ();
}
celPcGameController::~celPcGameController ()
{
pl->RemoveCallbackEveryFrame ((iCelTimerListener*)this, CEL_EVENT_POST);
delete iconCursor;
delete iconEye;
delete iconBook;
delete iconDot;
}
void celPcGameController::LoadIcons ()
{
iTextureWrapper* txt;
txt = engine->CreateTexture ("icon_cursor",
"/icons/iconic_cursor_32x32.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconCursor = new csSimplePixmap (txt->GetTextureHandle ());
txt = engine->CreateTexture ("icon_dot",
"/icons/icon_dot.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconDot = new csSimplePixmap (txt->GetTextureHandle ());
txt = engine->CreateTexture ("icon_eye",
"/icons/iconic_eye_32x24.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconEye = new csSimplePixmap (txt->GetTextureHandle ());
txt = engine->CreateTexture ("icon_book",
"/icons/iconic_book_alt2_32x28.png", 0, CS_TEXTURE_2D | CS_TEXTURE_NOMIPMAPS);
txt->Register (g3d->GetTextureManager ());
iconBook = new csSimplePixmap (txt->GetTextureHandle ());
}
void celPcGameController::TryGetDynworld ()
{
if (dynworld) return;
dynworld = celQueryPropertyClassEntity<iPcDynamicWorld> (entity);
if (dynworld) return;
// Not very clean. We should only depend on the dynworld plugin
// to be in this entity but for the editor we actually have the
// dynworld plugin in the 'Zone' entity. Need to find a way for this
// that is cleaner.
csRef<iCelEntity> zone = pl->FindEntity ("Zone");
if (!zone)
{
printf ("Can't find entity 'Zone' and current entity has no dynworld PC!\n");
return;
}
dynworld = celQueryPropertyClassEntity<iPcDynamicWorld> (zone);
iDynamicSystem* dynSys = dynworld->GetCurrentCell ()->GetDynamicSystem ();
bullet_dynSys = scfQueryInterface<CS::Physics::Bullet::iDynamicSystem> (dynSys);
}
void celPcGameController::TryGetCamera ()
{
if (pccamera && pcdynmove) return;
csRef<iCelEntity> player = pl->FindEntity ("Player");
if (!player)
{
printf ("Can't find entity 'Player'!\n");
return;
}
pccamera = celQueryPropertyClassEntity<iPcCamera> (player);
pcdynmove = celQueryPropertyClassEntity<iPcDynamicMove> (player);
}
bool celPcGameController::PerformActionIndexed (int idx,
iCelParameterBlock* params,
celData& ret)
{
switch (idx)
{
case action_message:
{
CEL_FETCH_STRING_PAR (msg,params,id_message);
if (!p_msg) return false;
CEL_FETCH_FLOAT_PAR (timeout,params,id_timeout);
if (!p_timeout) timeout = 2.0f;
Message (msg, timeout);
return true;
}
case action_startdrag:
return StartDrag ();
case action_stopdrag:
StopDrag ();
return true;
case action_examine:
Examine ();
return true;
default:
return false;
}
return false;
}
void celPcGameController::Examine ()
{
iRigidBody* hitBody;
csVector3 start, isect;
iDynamicObject* obj = FindCenterObject (hitBody, start, isect);
if (obj)
{
iCelEntity* ent = obj->GetEntity ();
if (ent && ent->HasClass (classInfoID))
{
csRef<iPcProperties> prop = celQueryPropertyClassEntity<iPcProperties> (ent);
if (!prop)
{
Message ("ERROR: Entity has no properties!");
return;
}
size_t idx = prop->GetPropertyIndex ("ares.info");
if (idx == csArrayItemNotFound)
{
Message ("ERROR: Entity has no 'ares.info' property!");
return;
}
Message (prop->GetPropertyString (idx));
}
else
{
Message ("I see nothing special!");
}
}
else
{
Message ("Nothing to examine!");
}
}
void celPcGameController::Message (const char* message, float timeout)
{
TimedMessage m;
m.message = message;
m.timeleft = timeout;
messages.Push (m);
printf ("MSG: %s\n", message);
fflush (stdout);
}
iDynamicObject* celPcGameController::FindCenterObject (iRigidBody*& hitBody,
csVector3& start, csVector3& isect)
{
TryGetCamera ();
TryGetDynworld ();
iCamera* cam = pccamera->GetCamera ();
if (!cam) return 0;
int x = mouse->GetLastX ();
int y = mouse->GetLastY ();
csVector2 v2d (x, g2d->GetHeight () - y);
csVector3 v3d = cam->InvPerspective (v2d, 3.0f);
start = cam->GetTransform ().GetOrigin ();
csVector3 end = cam->GetTransform ().This2Other (v3d);
// Trace the physical beam
CS::Physics::Bullet::HitBeamResult result = bullet_dynSys->HitBeam (start, end);
if (!result.body) return 0;
hitBody = result.body->QueryRigidBody ();
isect = result.isect;
return dynworld->FindObject (hitBody);
}
bool celPcGameController::StartDrag ()
{
iRigidBody* hitBody;
csVector3 start, isect;
iDynamicObject* obj = FindCenterObject (hitBody, start, isect);
if (obj)
{
dragobj = obj;
iCelEntity* ent = obj->GetEntity ();
if (ent && ent->HasClass (classDragRotYID))
{
printf ("Start roty drag!\n"); fflush (stdout);
dragType = DRAGTYPE_ROTY;
pcdynmove->EnableMouselook (false);
dragOrigin = obj->GetMesh ()->GetMovable ()->GetTransform ().GetOrigin ();
//dragOrigin.y = isect.y;
isect.y = dragOrigin.y;
dragAnchor = isect;
dragDistance = (isect - dragOrigin).Norm ();
}
else
{
printf ("Start normal drag!\n"); fflush (stdout);
dragType = DRAGTYPE_NORMAL;
dragDistance = (isect - start).Norm ();
}
dragJoint = bullet_dynSys->CreatePivotJoint ();
dragJoint->Attach (hitBody, isect);
// Set some dampening on the rigid body to have a more stable dragging
csRef<CS::Physics::Bullet::iRigidBody> csBody =
scfQueryInterface<CS::Physics::Bullet::iRigidBody> (hitBody);
oldLinearDampening = csBody->GetLinearDampener ();
oldAngularDampening = csBody->GetRollingDampener ();
csBody->SetLinearDampener (0.9f);
csBody->SetRollingDampener (0.9f);
return true;
}
return false;
}
void celPcGameController::StopDrag ()
{
if (!dragobj) return;
printf ("Stop drag!\n"); fflush (stdout);
csRef<CS::Physics::Bullet::iRigidBody> csBody =
scfQueryInterface<CS::Physics::Bullet::iRigidBody> (dragJoint->GetAttachedBody ());
csBody->SetLinearDampener (oldLinearDampening);
csBody->SetRollingDampener (oldAngularDampening);
bullet_dynSys->RemovePivotJoint (dragJoint);
dragJoint = 0;
dragobj = 0;
if (dragType == DRAGTYPE_ROTY)
pcdynmove->EnableMouselook (true);
}
void celPcGameController::TickEveryFrame ()
{
csSimplePixmap* icon = iconDot;
int sw = g2d->GetWidth ();
int sh = g2d->GetHeight ();
if (dragobj)
{
iCamera* cam = pccamera->GetCamera ();
if (!cam) return;
int x = mouse->GetLastX ();
int y = mouse->GetLastY ();
csVector3 newPosition;
if (dragType == DRAGTYPE_ROTY)
{
int sx = x - sw / 2;
int sy = y - sh / 2;
g2d->SetMousePosition (sw / 2, sh / 2);
csVector3 v (float (sx) / 200.0f, 0, - float (sy) / 200.0f);
float len = v.Norm ();
v = cam->GetTransform ().This2OtherRelative (v);
v.y = 0;
if (v.Norm () > .0001f)
{
v.Normalize ();
v *= len;
dragAnchor += v;
newPosition = dragAnchor - dragOrigin;
newPosition.Normalize ();
newPosition = dragOrigin + newPosition * dragDistance;
dragJoint->SetPosition (newPosition);
}
icon = iconDot;
}
else
{
csVector2 v2d (x, sh - y);
csVector3 v3d = cam->InvPerspective (v2d, 3.0f);
csVector3 start = cam->GetTransform ().GetOrigin ();
csVector3 end = cam->GetTransform ().This2Other (v3d);
newPosition = end - start;
newPosition.Normalize ();
newPosition = cam->GetTransform ().GetOrigin () + newPosition * dragDistance;
dragJoint->SetPosition (newPosition);
icon = iconCursor;
}
}
else
{
iRigidBody* hitBody;
csVector3 start, isect;
iDynamicObject* obj = FindCenterObject (hitBody, start, isect);
if (obj)
{
iCelEntity* ent = obj->GetEntity ();
if (ent && ent->HasClass (classNoteID))
{
icon = iconBook;
}
else if (ent && ent->HasClass (classInfoID))
{
icon = iconEye;
}
else if (!obj->IsStatic ())
{
icon = iconCursor;
}
}
}
g3d->BeginDraw (CSDRAW_2DGRAPHICS);
if (messages.GetSize () > 0)
{
float elapsed = vc->GetElapsedSeconds ();
int y = 20;
size_t i = 0;
while (i < messages.GetSize ())
{
TimedMessage& m = messages[i];
m.timeleft -= elapsed;
if (m.timeleft <= 0)
messages.DeleteIndex (i);
else
{
int alpha = 255;
if (m.timeleft < 1.0f) alpha = int (255.0f * (m.timeleft));
messageColor = g3d->GetDriver2D ()->FindRGB (255, 255, 255, alpha);
g2d->Write (font, 20, y, messageColor, -1, m.message.GetData ());
y += fontH + 2;
i++;
}
}
}
icon->Draw (g3d, sw / 2, sh / 2);
}
//---------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/**
* \file PolygonArea.hpp
* \brief Header for GeographicLib::PolygonArea class
*
* Copyright (c) Charles Karney (2010, 2011) <charles@karney.com> and licensed
* under the LGPL. For more information, see
* http://geographiclib.sourceforge.net/
**********************************************************************/
#if !defined(GEOGRAPHICLIB_POLYGONAREA_HPP)
#define GEOGRAPHICLIB_POLYGONAREA_HPP "$Id$"
#include <GeographicLib/Geodesic.hpp>
#include <GeographicLib/Constants.hpp>
namespace GeographicLib {
/**
* \brief Polygon Areas.
*
* This computes the area of a geodesic polygon using the method given
* Section 15 of
* - C. F. F. Karney,
* <a href="http://arxiv.org/abs/1102.1215v1">Geodesics
* on an ellipsoid of revolution</a>,
* Feb. 2011;
* preprint
* <a href="http://arxiv.org/abs/1102.1215v1">arxiv:1102.1215v1</a>.
*
* This class lets you add vertices one at a time to the polygon. At any
* point you can ask for the perimeter and area so far. There's an option to
* treat the points as defining a polyline instead of a polygon; in that
* case, only the perimeter is computed.
**********************************************************************/
class GEOGRAPHIC_EXPORT PolygonArea {
private:
typedef Math::real real;
const Geodesic& _earth;
const real _area0; // Full ellipsoid area
const bool _polyline; // Assume polyline (don't close and skip area)
unsigned _num;
int _crossings;
Accumulator<real> _areasum, _perimetersum;
real _lat0, _lon0, _lat1, _lon1;
// Copied from Geodesic class
static inline real AngNormalize(real x) throw() {
// Place angle in [-180, 180). Assumes x is in [-540, 540).
//
// g++ 4.4.4 holds a temporary in an extended register causing an error
// with the triangle 89,0.1;89,90.1;89,-179.9. The volatile declaration
// fixes this. (The bug probably triggered because transit and
// AngNormalize are inline functions. So don't port this change over to
// Geodesic.hpp.)
volatile real y = x;
return y >= 180 ? y - 360 : y < -180 ? y + 360 : y;
}
static inline int transit(real lon1, real lon2) {
// Return 1 or -1 if crossing prime meridian in east or west direction.
// Otherwise return zero.
lon1 = AngNormalize(lon1);
lon2 = AngNormalize(lon2);
// treat lon12 = -180 as an eastward geodesic, so convert to 180.
real lon12 = -AngNormalize(lon1 - lon2); // In (-180, 180]
int cross =
lon1 < 0 && lon2 >= 0 && lon12 > 0 ? 1 :
lon2 < 0 && lon1 >= 0 && lon12 < 0 ? -1 : 0;
return cross;
}
public:
/**
* Constructor for PolygonArea.
*
* @param[in] earth the Geodesic object to use for geodesic calculations.
* By default this uses the WGS84 ellipsoid.
* @param[in] polyline if true that treat the points as defining a polyline
* instead of a polygon (default = false).
**********************************************************************/
PolygonArea(const Geodesic& earth, bool polyline = false) throw()
: _earth(earth)
, _area0(_earth.EllipsoidArea())
, _polyline(polyline)
{
Clear();
}
/**
* Clear PolygonArea, allowing a new polygon to be started.
**********************************************************************/
void Clear() throw() {
_num = 0;
_crossings = 0;
_areasum = 0;
_perimetersum = 0;
_lat0 = _lon0 = _lat1 = _lon1 = 0;
}
/**
* Add a point to the polygon or polyline.
*
* @param[in] lat the latitude of the point (degrees).
* @param[in] lon the latitude of the point (degrees).
*
* \e lat should be in the range [-90, 90] and \e lon should be in the
* range [-180, 360].
**********************************************************************/
void AddPoint(real lat, real lon) throw();
/**
* Return the results so far.
*
* @param[in] reverse if true then clockwise (instead of counter-clockwise)
* traversal counts as a positive area.
* @param[in] sign if true then return a signed result for the area if
* the polygon is traversed in the "wrong" direction instead of returning
* the area for the rest of the earth.
* @param[out] perimeter the perimeter of the polygon or length of the
* polyline (meters).
* @param[out] area the area of the polygon (meters^2); only set if
* polyline is false in the constructor.
* @return the number of points.
**********************************************************************/
unsigned Compute(bool reverse, bool sign,
real& perimeter, real& area) const throw();
/**
* Return the results assuming a final test point is added; however, the
* data for the test point is not saved. This lets you report a running
* result for the perimeter and area as the user moves the mouse cursor.
*
* @param[in] reverse if true then clockwise (instead of counter-clockwise)
* traversal counts as a positive area.
* @param[in] sign if true then return a signed result for the area if
* the polygon is traversed in the "wrong" direction instead of returning
* the area for the rest of the earth.
* @param[out] perimeter the perimeter of the polygon or length of the
* polyline (meters).
* @param[out] area the area of the polygon (meters^2); only set if
* polyline is false in the constructor.
* @param[in] lat the latitude of the test point (degrees).
* @param[in] lon the longitude of the test point (degrees).
* @return the number of points.
*
* \e lat should be in the range [-90, 90] and \e lon should be in the
* range [-180, 360].
**********************************************************************/
unsigned Compute(bool reverse, bool sign,
real& perimeter, real& area,
real lat, real lon) const throw();
};
} // namespace GeographicLib
#endif // GEOGRAPHICLIB_POLYGONAREA_HPP
<commit_msg>Add PolygonArea::TestCompute<commit_after>/**
* \file PolygonArea.hpp
* \brief Header for GeographicLib::PolygonArea class
*
* Copyright (c) Charles Karney (2010, 2011) <charles@karney.com> and licensed
* under the LGPL. For more information, see
* http://geographiclib.sourceforge.net/
**********************************************************************/
#if !defined(GEOGRAPHICLIB_POLYGONAREA_HPP)
#define GEOGRAPHICLIB_POLYGONAREA_HPP "$Id$"
#include <GeographicLib/Geodesic.hpp>
#include <GeographicLib/Constants.hpp>
namespace GeographicLib {
/**
* \brief Polygon Areas.
*
* This computes the area of a geodesic polygon using the method given
* Section 15 of
* - C. F. F. Karney,
* <a href="http://arxiv.org/abs/1102.1215v1">Geodesics
* on an ellipsoid of revolution</a>,
* Feb. 2011;
* preprint
* <a href="http://arxiv.org/abs/1102.1215v1">arxiv:1102.1215v1</a>.
*
* This class lets you add vertices one at a time to the polygon. The area
* and perimeter are accumulated in two times the standard floating point
* precision to guard against the loss of accuracy with many-sided polygons.
* At any point you can ask for the perimeter and area so far. There's an
* option to treat the points as defining a polyline instead of a polygon; in
* that case, only the perimeter is computed.
**********************************************************************/
class GEOGRAPHIC_EXPORT PolygonArea {
private:
typedef Math::real real;
const Geodesic& _earth;
const real _area0; // Full ellipsoid area
const bool _polyline; // Assume polyline (don't close and skip area)
const unsigned _mask;
unsigned _num;
int _crossings;
Accumulator<real> _areasum, _perimetersum;
real _lat0, _lon0, _lat1, _lon1;
// Copied from Geodesic class
static inline real AngNormalize(real x) throw() {
// Place angle in [-180, 180). Assumes x is in [-540, 540).
//
// g++ 4.4.4 holds a temporary in an extended register causing an error
// with the triangle 89,0.1;89,90.1;89,-179.9. The volatile declaration
// fixes this. (The bug probably triggered because transit and
// AngNormalize are inline functions. So don't port this change over to
// Geodesic.hpp.)
volatile real y = x;
return y >= 180 ? y - 360 : y < -180 ? y + 360 : y;
}
static inline int transit(real lon1, real lon2) {
// Return 1 or -1 if crossing prime meridian in east or west direction.
// Otherwise return zero.
lon1 = AngNormalize(lon1);
lon2 = AngNormalize(lon2);
// treat lon12 = -180 as an eastward geodesic, so convert to 180.
real lon12 = -AngNormalize(lon1 - lon2); // In (-180, 180]
int cross =
lon1 < 0 && lon2 >= 0 && lon12 > 0 ? 1 :
(lon2 < 0 && lon1 >= 0 && lon12 < 0 ? -1 : 0);
return cross;
}
public:
/**
* Constructor for PolygonArea.
*
* @param[in] earth the Geodesic object to use for geodesic calculations.
* By default this uses the WGS84 ellipsoid.
* @param[in] polyline if true that treat the points as defining a polyline
* instead of a polygon (default = false).
**********************************************************************/
PolygonArea(const Geodesic& earth, bool polyline = false) throw()
: _earth(earth)
, _area0(_earth.EllipsoidArea())
, _polyline(polyline)
, _mask(Geodesic::DISTANCE | (_polyline ? 0 : Geodesic::AREA))
{
Clear();
}
/**
* Clear PolygonArea, allowing a new polygon to be started.
**********************************************************************/
void Clear() throw() {
_num = 0;
_crossings = 0;
_areasum = 0;
_perimetersum = 0;
_lat0 = _lon0 = _lat1 = _lon1 = 0;
}
/**
* Add a point to the polygon or polyline.
*
* @param[in] lat the latitude of the point (degrees).
* @param[in] lon the latitude of the point (degrees).
*
* \e lat should be in the range [-90, 90] and \e lon should be in the
* range [-180, 360].
**********************************************************************/
void AddPoint(real lat, real lon) throw();
/**
* Return the results so far.
*
* @param[in] reverse if true then clockwise (instead of counter-clockwise)
* traversal counts as a positive area.
* @param[in] sign if true then return a signed result for the area if
* the polygon is traversed in the "wrong" direction instead of returning
* the area for the rest of the earth.
* @param[out] perimeter the perimeter of the polygon or length of the
* polyline (meters).
* @param[out] area the area of the polygon (meters^2); only set if
* polyline is false in the constructor.
* @return the number of points.
**********************************************************************/
unsigned Compute(bool reverse, bool sign,
real& perimeter, real& area) const throw();
/**
* Return the results assuming a tentative final test point is added;
* however, the data for the test point is not saved. This lets you report
* a running result for the perimeter and area as the user moves the mouse
* cursor. Ordinary floating point arithmetic is used to accumulate the
* data for the test point; thus the area and perimeter returned are less
* accurate than if AddPoint and Compute are used.
*
* @param[in] lat the latitude of the test point (degrees).
* @param[in] lon the longitude of the test point (degrees).
* @param[in] reverse if true then clockwise (instead of counter-clockwise)
* traversal counts as a positive area.
* @param[in] sign if true then return a signed result for the area if
* the polygon is traversed in the "wrong" direction instead of returning
* the area for the rest of the earth.
* @param[out] perimeter the approximate perimeter of the polygon or length
* of the polyline (meters).
* @param[out] area the approximate area of the polygon (meters^2); only
* set if polyline is false in the constructor.
* @return the number of points.
*
* \e lat should be in the range [-90, 90] and \e lon should be in the
* range [-180, 360].
**********************************************************************/
unsigned TestCompute(real lat, real lon, bool reverse, bool sign,
real& perimeter, real& area) const throw();
};
} // namespace GeographicLib
#endif // GEOGRAPHICLIB_POLYGONAREA_HPP
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rsckey.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-17 15:59:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_rsc.hxx"
/****************** I N C L U D E S **************************************/
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#ifndef _RSCALL_H
#include <rscall.h>
#endif
#ifndef _RSCTOOLS_HXX
#include <rsctools.hxx>
#endif
#ifndef _RSCHASH_HXX
#include <rschash.hxx>
#endif
#ifndef _RSCKEY_HXX
#include <rsckey.hxx>
#endif
#if defined(_MSC_VER) && (_MSC_VER >= 1200 )
#define _cdecl __cdecl
#endif
/****************** C o d e **********************************************/
/****************** keyword sort function ********************************/
extern "C" {
#if defined( ZTC ) && defined( PM2 )
int __CLIB KeyCompare( const void * pFirst, const void * pSecond );
#else
#if defined( WNT ) && !defined( WTC ) && !defined (ICC)
int _cdecl KeyCompare( const void * pFirst, const void * pSecond );
#else
int KeyCompare( const void * pFirst, const void * pSecond );
#endif
#endif
}
#if defined( WNT ) && !defined( WTC ) && !defined(ICC)
int _cdecl KeyCompare( const void * pFirst, const void * pSecond ){
#else
int KeyCompare( const void * pFirst, const void * pSecond ){
#endif
if( ((KEY_STRUCT *)pFirst)->nName > ((KEY_STRUCT *)pSecond)->nName )
return( 1 );
else if( ((KEY_STRUCT *)pFirst)->nName < ((KEY_STRUCT *)pSecond)->nName )
return( -1 );
else
return( 0 );
}
/*************************************************************************
|*
|* RscNameTable::RscNameTable()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
RscNameTable::RscNameTable() {
bSort = TRUE;
nEntries = 0;
pTable = NULL;
};
/*************************************************************************
|*
|* RscNameTable::~RscNameTable()
|*
|* Beschreibung
|* Ersterstellung MM 15.05.91
|* Letzte Aenderung MM 15.05.91
|*
*************************************************************************/
RscNameTable::~RscNameTable() {
if( pTable )
rtl_freeMemory( pTable );
};
/*************************************************************************
|*
|* RscNameTable::SetSort()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
void RscNameTable::SetSort( BOOL bSorted ){
bSort = bSorted;
if( bSort && pTable){
// Schluesselwort Feld sortieren
qsort( (void *)pTable, nEntries,
sizeof( KEY_STRUCT ), KeyCompare );
};
};
/*************************************************************************
|*
|* RscNameTable::Put()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
Atom RscNameTable::Put( Atom nName, sal_uInt32 nTyp, long nValue ){
if( pTable )
pTable = (KEY_STRUCT *)
rtl_reallocateMemory( (void *)pTable,
((nEntries +1) * sizeof( KEY_STRUCT )) );
else
pTable = (KEY_STRUCT *)
rtl_allocateMemory( ((nEntries +1)
* sizeof( KEY_STRUCT )) );
pTable[ nEntries ].nName = nName;
pTable[ nEntries ].nTyp = nTyp;
pTable[ nEntries ].yylval = nValue;
nEntries++;
if( bSort )
SetSort();
return( nName );
};
Atom RscNameTable::Put( const char * pName, sal_uInt32 nTyp, long nValue )
{
return( Put( pHS->getID( pName ), nTyp, nValue ) );
};
Atom RscNameTable::Put( Atom nName, sal_uInt32 nTyp )
{
return( Put( nName, nTyp, (long)nName ) );
};
Atom RscNameTable::Put( const char * pName, sal_uInt32 nTyp )
{
Atom nId;
nId = pHS->getID( pName );
return( Put( nId, nTyp, (long)nId ) );
};
Atom RscNameTable::Put( Atom nName, sal_uInt32 nTyp, RscTop * pClass )
{
return( Put( nName, nTyp, (long)pClass ) );
};
Atom RscNameTable::Put( const char * pName, sal_uInt32 nTyp, RscTop * pClass )
{
return( Put( pHS->getID( pName ), nTyp, (long)pClass ) );
};
/*************************************************************************
|*
|* RscNameTable::Get()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
BOOL RscNameTable::Get( Atom nName, KEY_STRUCT * pEle ){
KEY_STRUCT * pKey = NULL;
KEY_STRUCT aSearchName;
sal_uInt32 i;
if( bSort ){
// Suche nach dem Schluesselwort
aSearchName.nName = nName;
pKey = (KEY_STRUCT *)bsearch(
#ifdef UNX
(const char *) &aSearchName, (char *)pTable,
#else
(const void *) &aSearchName, (const void *)pTable,
#endif
nEntries, sizeof( KEY_STRUCT ), KeyCompare );
}
else{
i = 0;
while( i < nEntries && !pKey ){
if( pTable[ i ].nName == nName )
pKey = &pTable[ i ];
i++;
};
};
if( pKey ){ // Schluesselwort gefunden
*pEle = *pKey;
return( TRUE );
};
return( FALSE );
};
<commit_msg>INTEGRATION: CWS changefileheader (1.6.54); FILE MERGED 2008/04/01 12:33:29 thb 1.6.54.2: #i85898# Stripping all external header guards 2008/03/31 13:15:58 rt 1.6.54.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rsckey.cxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_rsc.hxx"
/****************** I N C L U D E S **************************************/
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <rscall.h>
#include <rsctools.hxx>
#include <rschash.hxx>
#include <rsckey.hxx>
#if defined(_MSC_VER) && (_MSC_VER >= 1200 )
#define _cdecl __cdecl
#endif
/****************** C o d e **********************************************/
/****************** keyword sort function ********************************/
extern "C" {
#if defined( ZTC ) && defined( PM2 )
int __CLIB KeyCompare( const void * pFirst, const void * pSecond );
#else
#if defined( WNT ) && !defined( WTC ) && !defined (ICC)
int _cdecl KeyCompare( const void * pFirst, const void * pSecond );
#else
int KeyCompare( const void * pFirst, const void * pSecond );
#endif
#endif
}
#if defined( WNT ) && !defined( WTC ) && !defined(ICC)
int _cdecl KeyCompare( const void * pFirst, const void * pSecond ){
#else
int KeyCompare( const void * pFirst, const void * pSecond ){
#endif
if( ((KEY_STRUCT *)pFirst)->nName > ((KEY_STRUCT *)pSecond)->nName )
return( 1 );
else if( ((KEY_STRUCT *)pFirst)->nName < ((KEY_STRUCT *)pSecond)->nName )
return( -1 );
else
return( 0 );
}
/*************************************************************************
|*
|* RscNameTable::RscNameTable()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
RscNameTable::RscNameTable() {
bSort = TRUE;
nEntries = 0;
pTable = NULL;
};
/*************************************************************************
|*
|* RscNameTable::~RscNameTable()
|*
|* Beschreibung
|* Ersterstellung MM 15.05.91
|* Letzte Aenderung MM 15.05.91
|*
*************************************************************************/
RscNameTable::~RscNameTable() {
if( pTable )
rtl_freeMemory( pTable );
};
/*************************************************************************
|*
|* RscNameTable::SetSort()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
void RscNameTable::SetSort( BOOL bSorted ){
bSort = bSorted;
if( bSort && pTable){
// Schluesselwort Feld sortieren
qsort( (void *)pTable, nEntries,
sizeof( KEY_STRUCT ), KeyCompare );
};
};
/*************************************************************************
|*
|* RscNameTable::Put()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
Atom RscNameTable::Put( Atom nName, sal_uInt32 nTyp, long nValue ){
if( pTable )
pTable = (KEY_STRUCT *)
rtl_reallocateMemory( (void *)pTable,
((nEntries +1) * sizeof( KEY_STRUCT )) );
else
pTable = (KEY_STRUCT *)
rtl_allocateMemory( ((nEntries +1)
* sizeof( KEY_STRUCT )) );
pTable[ nEntries ].nName = nName;
pTable[ nEntries ].nTyp = nTyp;
pTable[ nEntries ].yylval = nValue;
nEntries++;
if( bSort )
SetSort();
return( nName );
};
Atom RscNameTable::Put( const char * pName, sal_uInt32 nTyp, long nValue )
{
return( Put( pHS->getID( pName ), nTyp, nValue ) );
};
Atom RscNameTable::Put( Atom nName, sal_uInt32 nTyp )
{
return( Put( nName, nTyp, (long)nName ) );
};
Atom RscNameTable::Put( const char * pName, sal_uInt32 nTyp )
{
Atom nId;
nId = pHS->getID( pName );
return( Put( nId, nTyp, (long)nId ) );
};
Atom RscNameTable::Put( Atom nName, sal_uInt32 nTyp, RscTop * pClass )
{
return( Put( nName, nTyp, (long)pClass ) );
};
Atom RscNameTable::Put( const char * pName, sal_uInt32 nTyp, RscTop * pClass )
{
return( Put( pHS->getID( pName ), nTyp, (long)pClass ) );
};
/*************************************************************************
|*
|* RscNameTable::Get()
|*
|* Beschreibung RES.DOC
|* Ersterstellung MM 28.02.91
|* Letzte Aenderung MM 28.02.91
|*
*************************************************************************/
BOOL RscNameTable::Get( Atom nName, KEY_STRUCT * pEle ){
KEY_STRUCT * pKey = NULL;
KEY_STRUCT aSearchName;
sal_uInt32 i;
if( bSort ){
// Suche nach dem Schluesselwort
aSearchName.nName = nName;
pKey = (KEY_STRUCT *)bsearch(
#ifdef UNX
(const char *) &aSearchName, (char *)pTable,
#else
(const void *) &aSearchName, (const void *)pTable,
#endif
nEntries, sizeof( KEY_STRUCT ), KeyCompare );
}
else{
i = 0;
while( i < nEntries && !pKey ){
if( pTable[ i ].nName == nName )
pKey = &pTable[ i ];
i++;
};
};
if( pKey ){ // Schluesselwort gefunden
*pEle = *pKey;
return( TRUE );
};
return( FALSE );
};
<|endoftext|> |
<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/renderer/electron_renderer_client.h"
#include <string>
#include <vector>
#include "base/command_line.h"
#include "content/public/renderer/render_frame.h"
#include "electron/buildflags/buildflags.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/asar/asar_util.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/event_emitter_caller.h"
#include "shell/common/node_bindings.h"
#include "shell/common/node_includes.h"
#include "shell/common/node_util.h"
#include "shell/common/options_switches.h"
#include "shell/renderer/electron_render_frame_observer.h"
#include "shell/renderer/web_worker_observer.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_local_frame.h"
namespace electron {
namespace {
bool IsDevToolsExtension(content::RenderFrame* render_frame) {
return static_cast<GURL>(render_frame->GetWebFrame()->GetDocument().Url())
.SchemeIs("chrome-extension");
}
} // namespace
ElectronRendererClient::ElectronRendererClient()
: node_bindings_(
NodeBindings::Create(NodeBindings::BrowserEnvironment::RENDERER)),
electron_bindings_(new ElectronBindings(uv_default_loop())) {}
ElectronRendererClient::~ElectronRendererClient() {
asar::ClearArchives();
}
void ElectronRendererClient::RenderFrameCreated(
content::RenderFrame* render_frame) {
new ElectronRenderFrameObserver(render_frame, this);
RendererClientBase::RenderFrameCreated(render_frame);
}
void ElectronRendererClient::RunScriptsAtDocumentStart(
content::RenderFrame* render_frame) {
RendererClientBase::RunScriptsAtDocumentStart(render_frame);
// Inform the document start pharse.
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
node::Environment* env = GetEnvironment(render_frame);
if (env)
gin_helper::EmitEvent(env->isolate(), env->process_object(),
"document-start");
}
void ElectronRendererClient::RunScriptsAtDocumentEnd(
content::RenderFrame* render_frame) {
RendererClientBase::RunScriptsAtDocumentEnd(render_frame);
// Inform the document end pharse.
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
node::Environment* env = GetEnvironment(render_frame);
if (env)
gin_helper::EmitEvent(env->isolate(), env->process_object(),
"document-end");
}
void ElectronRendererClient::DidCreateScriptContext(
v8::Handle<v8::Context> renderer_context,
content::RenderFrame* render_frame) {
RendererClientBase::DidCreateScriptContext(renderer_context, render_frame);
// TODO(zcbenz): Do not create Node environment if node integration is not
// enabled.
auto* command_line = base::CommandLine::ForCurrentProcess();
// Only load node if we are a main frame or a devtools extension
// unless node support has been explicitly enabled for sub frames
bool reuse_renderer_processes_enabled =
command_line->HasSwitch(switches::kDisableElectronSiteInstanceOverrides);
// Consider the window not "opened" if it does not have an Opener, or if a
// user has manually opted in to leaking node in the renderer
bool is_not_opened =
!render_frame->GetWebFrame()->Opener() ||
command_line->HasSwitch(switches::kEnableNodeLeakageInRenderers);
// Consider this the main frame if it is both a Main Frame and it wasn't
// opened. We allow an opened main frame to have node if renderer process
// reuse is enabled as that will correctly free node environments prevent a
// leak in child windows.
bool is_main_frame = render_frame->IsMainFrame() &&
(is_not_opened || reuse_renderer_processes_enabled);
bool is_devtools = IsDevToolsExtension(render_frame);
bool allow_node_in_subframes =
command_line->HasSwitch(switches::kNodeIntegrationInSubFrames);
bool should_load_node =
(is_main_frame || is_devtools || allow_node_in_subframes) &&
!IsWebViewFrame(renderer_context, render_frame);
if (!should_load_node) {
return;
}
injected_frames_.insert(render_frame);
// If this is the first environment we are creating, prepare the node
// bindings.
if (!node_integration_initialized_) {
node_integration_initialized_ = true;
node_bindings_->Initialize();
node_bindings_->PrepareMessageLoop();
}
// Setup node tracing controller.
if (!node::tracing::TraceEventHelper::GetAgent())
node::tracing::TraceEventHelper::SetAgent(node::CreateAgent());
// Setup node environment for each window.
bool initialized = node::InitializeContext(renderer_context);
CHECK(initialized);
node::Environment* env =
node_bindings_->CreateEnvironment(renderer_context, nullptr);
// If we have disabled the site instance overrides we should prevent loading
// any non-context aware native module
if (command_line->HasSwitch(switches::kDisableElectronSiteInstanceOverrides))
env->ForceOnlyContextAwareNativeModules();
env->WarnNonContextAwareNativeModules();
environments_.insert(env);
// Add Electron extended APIs.
electron_bindings_->BindTo(env->isolate(), env->process_object());
AddRenderBindings(env->isolate(), env->process_object());
gin_helper::Dictionary process_dict(env->isolate(), env->process_object());
process_dict.SetReadOnly("isMainFrame", render_frame->IsMainFrame());
// Load everything.
node_bindings_->LoadEnvironment(env);
if (node_bindings_->uv_env() == nullptr) {
// Make uv loop being wrapped by window context.
node_bindings_->set_uv_env(env);
// Give the node loop a run to make sure everything is ready.
node_bindings_->RunMessageLoop();
}
}
void ElectronRendererClient::WillReleaseScriptContext(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
if (injected_frames_.erase(render_frame) == 0)
return;
node::Environment* env = node::Environment::GetCurrent(context);
if (environments_.erase(env) == 0)
return;
gin_helper::EmitEvent(env->isolate(), env->process_object(), "exit");
// The main frame may be replaced.
if (env == node_bindings_->uv_env())
node_bindings_->set_uv_env(nullptr);
// Destroy the node environment. We only do this if node support has been
// enabled for sub-frames to avoid a change-of-behavior / introduce crashes
// for existing users.
// We also do this if we have disable electron site instance overrides to
// avoid memory leaks
auto* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kNodeIntegrationInSubFrames) ||
command_line->HasSwitch(
switches::kDisableElectronSiteInstanceOverrides)) {
node::FreeEnvironment(env);
if (env == node_bindings_->uv_env())
node::FreeIsolateData(node_bindings_->isolate_data());
}
// ElectronBindings is tracking node environments.
electron_bindings_->EnvironmentDestroyed(env);
}
bool ElectronRendererClient::ShouldFork(blink::WebLocalFrame* frame,
const GURL& url,
const std::string& http_method,
bool is_initial_navigation,
bool is_server_redirect) {
// Handle all the navigations and reloads in browser.
// FIXME We only support GET here because http method will be ignored when
// the OpenURLFromTab is triggered, which means form posting would not work,
// we should solve this by patching Chromium in future.
return http_method == "GET";
}
void ElectronRendererClient::DidInitializeWorkerContextOnWorkerThread(
v8::Local<v8::Context> context) {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNodeIntegrationInWorker)) {
WebWorkerObserver::GetCurrent()->ContextCreated(context);
}
}
void ElectronRendererClient::WillDestroyWorkerContextOnWorkerThread(
v8::Local<v8::Context> context) {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNodeIntegrationInWorker)) {
WebWorkerObserver::GetCurrent()->ContextWillDestroy(context);
}
}
void ElectronRendererClient::SetupMainWorldOverrides(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
// We only need to run the isolated bundle if webview is enabled
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kWebviewTag))
return;
// Setup window overrides in the main world context
// Wrap the bundle into a function that receives the isolatedWorld as
// an argument.
auto* isolate = context->GetIsolate();
std::vector<v8::Local<v8::String>> isolated_bundle_params = {
node::FIXED_ONE_BYTE_STRING(isolate, "nodeProcess"),
node::FIXED_ONE_BYTE_STRING(isolate, "isolatedWorld")};
auto* env = GetEnvironment(render_frame);
DCHECK(env);
std::vector<v8::Local<v8::Value>> isolated_bundle_args = {
env->process_object(),
GetContext(render_frame->GetWebFrame(), isolate)->Global()};
util::CompileAndCall(context, "electron/js2c/isolated_bundle",
&isolated_bundle_params, &isolated_bundle_args, nullptr);
}
void ElectronRendererClient::SetupExtensionWorldOverrides(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame,
int world_id) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
NOTREACHED();
#else
auto* isolate = context->GetIsolate();
std::vector<v8::Local<v8::String>> isolated_bundle_params = {
node::FIXED_ONE_BYTE_STRING(isolate, "nodeProcess"),
node::FIXED_ONE_BYTE_STRING(isolate, "isolatedWorld"),
node::FIXED_ONE_BYTE_STRING(isolate, "worldId")};
auto* env = GetEnvironment(render_frame);
if (!env)
return;
std::vector<v8::Local<v8::Value>> isolated_bundle_args = {
env->process_object(),
GetContext(render_frame->GetWebFrame(), isolate)->Global(),
v8::Integer::New(isolate, world_id)};
util::CompileAndCall(context, "electron/js2c/content_script_bundle",
&isolated_bundle_params, &isolated_bundle_args, nullptr);
#endif
}
node::Environment* ElectronRendererClient::GetEnvironment(
content::RenderFrame* render_frame) const {
if (injected_frames_.find(render_frame) == injected_frames_.end())
return nullptr;
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
auto context =
GetContext(render_frame->GetWebFrame(), v8::Isolate::GetCurrent());
node::Environment* env = node::Environment::GetCurrent(context);
if (environments_.find(env) == environments_.end())
return nullptr;
return env;
}
} // namespace electron
<commit_msg>fix: run Node.js at-exit callbacks in renderer proc (#23419)<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/renderer/electron_renderer_client.h"
#include <string>
#include <vector>
#include "base/command_line.h"
#include "content/public/renderer/render_frame.h"
#include "electron/buildflags/buildflags.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/asar/asar_util.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/event_emitter_caller.h"
#include "shell/common/node_bindings.h"
#include "shell/common/node_includes.h"
#include "shell/common/node_util.h"
#include "shell/common/options_switches.h"
#include "shell/renderer/electron_render_frame_observer.h"
#include "shell/renderer/web_worker_observer.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_local_frame.h"
namespace electron {
namespace {
bool IsDevToolsExtension(content::RenderFrame* render_frame) {
return static_cast<GURL>(render_frame->GetWebFrame()->GetDocument().Url())
.SchemeIs("chrome-extension");
}
} // namespace
ElectronRendererClient::ElectronRendererClient()
: node_bindings_(
NodeBindings::Create(NodeBindings::BrowserEnvironment::RENDERER)),
electron_bindings_(new ElectronBindings(uv_default_loop())) {}
ElectronRendererClient::~ElectronRendererClient() {
asar::ClearArchives();
}
void ElectronRendererClient::RenderFrameCreated(
content::RenderFrame* render_frame) {
new ElectronRenderFrameObserver(render_frame, this);
RendererClientBase::RenderFrameCreated(render_frame);
}
void ElectronRendererClient::RunScriptsAtDocumentStart(
content::RenderFrame* render_frame) {
RendererClientBase::RunScriptsAtDocumentStart(render_frame);
// Inform the document start pharse.
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
node::Environment* env = GetEnvironment(render_frame);
if (env)
gin_helper::EmitEvent(env->isolate(), env->process_object(),
"document-start");
}
void ElectronRendererClient::RunScriptsAtDocumentEnd(
content::RenderFrame* render_frame) {
RendererClientBase::RunScriptsAtDocumentEnd(render_frame);
// Inform the document end pharse.
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
node::Environment* env = GetEnvironment(render_frame);
if (env)
gin_helper::EmitEvent(env->isolate(), env->process_object(),
"document-end");
}
void ElectronRendererClient::DidCreateScriptContext(
v8::Handle<v8::Context> renderer_context,
content::RenderFrame* render_frame) {
RendererClientBase::DidCreateScriptContext(renderer_context, render_frame);
// TODO(zcbenz): Do not create Node environment if node integration is not
// enabled.
auto* command_line = base::CommandLine::ForCurrentProcess();
// Only load node if we are a main frame or a devtools extension
// unless node support has been explicitly enabled for sub frames
bool reuse_renderer_processes_enabled =
command_line->HasSwitch(switches::kDisableElectronSiteInstanceOverrides);
// Consider the window not "opened" if it does not have an Opener, or if a
// user has manually opted in to leaking node in the renderer
bool is_not_opened =
!render_frame->GetWebFrame()->Opener() ||
command_line->HasSwitch(switches::kEnableNodeLeakageInRenderers);
// Consider this the main frame if it is both a Main Frame and it wasn't
// opened. We allow an opened main frame to have node if renderer process
// reuse is enabled as that will correctly free node environments prevent a
// leak in child windows.
bool is_main_frame = render_frame->IsMainFrame() &&
(is_not_opened || reuse_renderer_processes_enabled);
bool is_devtools = IsDevToolsExtension(render_frame);
bool allow_node_in_subframes =
command_line->HasSwitch(switches::kNodeIntegrationInSubFrames);
bool should_load_node =
(is_main_frame || is_devtools || allow_node_in_subframes) &&
!IsWebViewFrame(renderer_context, render_frame);
if (!should_load_node) {
return;
}
injected_frames_.insert(render_frame);
// If this is the first environment we are creating, prepare the node
// bindings.
if (!node_integration_initialized_) {
node_integration_initialized_ = true;
node_bindings_->Initialize();
node_bindings_->PrepareMessageLoop();
}
// Setup node tracing controller.
if (!node::tracing::TraceEventHelper::GetAgent())
node::tracing::TraceEventHelper::SetAgent(node::CreateAgent());
// Setup node environment for each window.
bool initialized = node::InitializeContext(renderer_context);
CHECK(initialized);
node::Environment* env =
node_bindings_->CreateEnvironment(renderer_context, nullptr);
// If we have disabled the site instance overrides we should prevent loading
// any non-context aware native module
if (command_line->HasSwitch(switches::kDisableElectronSiteInstanceOverrides))
env->ForceOnlyContextAwareNativeModules();
env->WarnNonContextAwareNativeModules();
environments_.insert(env);
// Add Electron extended APIs.
electron_bindings_->BindTo(env->isolate(), env->process_object());
AddRenderBindings(env->isolate(), env->process_object());
gin_helper::Dictionary process_dict(env->isolate(), env->process_object());
process_dict.SetReadOnly("isMainFrame", render_frame->IsMainFrame());
// Load everything.
node_bindings_->LoadEnvironment(env);
if (node_bindings_->uv_env() == nullptr) {
// Make uv loop being wrapped by window context.
node_bindings_->set_uv_env(env);
// Give the node loop a run to make sure everything is ready.
node_bindings_->RunMessageLoop();
}
}
void ElectronRendererClient::WillReleaseScriptContext(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
if (injected_frames_.erase(render_frame) == 0)
return;
node::Environment* env = node::Environment::GetCurrent(context);
if (environments_.erase(env) == 0)
return;
gin_helper::EmitEvent(env->isolate(), env->process_object(), "exit");
// The main frame may be replaced.
if (env == node_bindings_->uv_env())
node_bindings_->set_uv_env(nullptr);
// Destroy the node environment. We only do this if node support has been
// enabled for sub-frames to avoid a change-of-behavior / introduce crashes
// for existing users.
// We also do this if we have disable electron site instance overrides to
// avoid memory leaks
auto* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kNodeIntegrationInSubFrames) ||
command_line->HasSwitch(
switches::kDisableElectronSiteInstanceOverrides)) {
node::RunAtExit(env);
node::FreeEnvironment(env);
if (env == node_bindings_->uv_env())
node::FreeIsolateData(node_bindings_->isolate_data());
}
// ElectronBindings is tracking node environments.
electron_bindings_->EnvironmentDestroyed(env);
}
bool ElectronRendererClient::ShouldFork(blink::WebLocalFrame* frame,
const GURL& url,
const std::string& http_method,
bool is_initial_navigation,
bool is_server_redirect) {
// Handle all the navigations and reloads in browser.
// FIXME We only support GET here because http method will be ignored when
// the OpenURLFromTab is triggered, which means form posting would not work,
// we should solve this by patching Chromium in future.
return http_method == "GET";
}
void ElectronRendererClient::DidInitializeWorkerContextOnWorkerThread(
v8::Local<v8::Context> context) {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNodeIntegrationInWorker)) {
WebWorkerObserver::GetCurrent()->ContextCreated(context);
}
}
void ElectronRendererClient::WillDestroyWorkerContextOnWorkerThread(
v8::Local<v8::Context> context) {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNodeIntegrationInWorker)) {
WebWorkerObserver::GetCurrent()->ContextWillDestroy(context);
}
}
void ElectronRendererClient::SetupMainWorldOverrides(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
// We only need to run the isolated bundle if webview is enabled
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kWebviewTag))
return;
// Setup window overrides in the main world context
// Wrap the bundle into a function that receives the isolatedWorld as
// an argument.
auto* isolate = context->GetIsolate();
std::vector<v8::Local<v8::String>> isolated_bundle_params = {
node::FIXED_ONE_BYTE_STRING(isolate, "nodeProcess"),
node::FIXED_ONE_BYTE_STRING(isolate, "isolatedWorld")};
auto* env = GetEnvironment(render_frame);
DCHECK(env);
std::vector<v8::Local<v8::Value>> isolated_bundle_args = {
env->process_object(),
GetContext(render_frame->GetWebFrame(), isolate)->Global()};
util::CompileAndCall(context, "electron/js2c/isolated_bundle",
&isolated_bundle_params, &isolated_bundle_args, nullptr);
}
void ElectronRendererClient::SetupExtensionWorldOverrides(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame,
int world_id) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
NOTREACHED();
#else
auto* isolate = context->GetIsolate();
std::vector<v8::Local<v8::String>> isolated_bundle_params = {
node::FIXED_ONE_BYTE_STRING(isolate, "nodeProcess"),
node::FIXED_ONE_BYTE_STRING(isolate, "isolatedWorld"),
node::FIXED_ONE_BYTE_STRING(isolate, "worldId")};
auto* env = GetEnvironment(render_frame);
if (!env)
return;
std::vector<v8::Local<v8::Value>> isolated_bundle_args = {
env->process_object(),
GetContext(render_frame->GetWebFrame(), isolate)->Global(),
v8::Integer::New(isolate, world_id)};
util::CompileAndCall(context, "electron/js2c/content_script_bundle",
&isolated_bundle_params, &isolated_bundle_args, nullptr);
#endif
}
node::Environment* ElectronRendererClient::GetEnvironment(
content::RenderFrame* render_frame) const {
if (injected_frames_.find(render_frame) == injected_frames_.end())
return nullptr;
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
auto context =
GetContext(render_frame->GetWebFrame(), v8::Isolate::GetCurrent());
node::Environment* env = node::Environment::GetCurrent(context);
if (environments_.find(env) == environments_.end())
return nullptr;
return env;
}
} // namespace electron
<|endoftext|> |
<commit_before>/** @file editorviewscene.cpp
* @brief Сцена для отрисовки объектов
* */
#include "editorviewscene.h"
#include <QGraphicsTextItem>
#include <QtGui>
#include "editorviewmviface.h"
#include "editorview.h"
#include "mainwindow.h"
#include "../mainwindow/mainwindow.h"
#include "../model/model.h"
using namespace qReal;
EditorViewScene::EditorViewScene(QObject * parent)
: QGraphicsScene(parent), mWindow(NULL), mPrevParent(0)
{
setItemIndexMethod(NoIndex);
setEnabled(false);
}
void EditorViewScene::setEnabled(bool enabled)
{
foreach (QGraphicsView *view, views())
view->setEnabled(enabled);
}
void EditorViewScene::clearScene()
{
foreach (QGraphicsItem *item, items())
// Выглядит довольно безумно, но некоторые элементы
// оказываются уже удалены, потому как был удалён их родитель.
if (items().contains(item))
removeItem(item);
}
UML::Element * EditorViewScene::getElem(qReal::Id const &uuid)
{
if (uuid == ROOT_ID)
return NULL;
// FIXME: SLOW!
QList < QGraphicsItem * > list = items();
for (QList < QGraphicsItem * >::Iterator it = list.begin(); it != list.end(); ++it) {
if (UML::Element * elem = dynamic_cast < UML::Element * >(*it)) {
if (elem->uuid() == uuid) {
return elem;
}
}
}
return NULL;
}
UML::Element * EditorViewScene::getElemByModelIndex(const QModelIndex &ind)
{
// FIXME: SLOW!
QList < QGraphicsItem * > list = items();
for (QList < QGraphicsItem * >::Iterator it = list.begin(); it != list.end(); ++it) {
if (UML::Element * elem = dynamic_cast < UML::Element * >(*it)) {
if (elem->index() == ind)
return elem;
}
}
return NULL;
}
void EditorViewScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
const QMimeData *mimeData = event->mimeData();
if (mimeData->hasFormat("application/x-real-uml-data"))
QGraphicsScene::dragEnterEvent(event);
else
event->ignore();
}
void EditorViewScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_UNUSED(event);
}
void EditorViewScene::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_UNUSED(event);
}
bool EditorViewScene::canBeContainedBy(qReal::Id container, qReal::Id candidate)
{
bool allowed = false;
foreach (qReal::Id type, mWindow->manager()->getContainedTypes(container.type())){
if (candidate.element() == type.editor())
allowed = true;
}
return allowed;
}
void EditorViewScene::dropEvent(QGraphicsSceneDragDropEvent *event)
{
Q_ASSERT(mWindow); // Значение mWindow должно быть инициализировано
// отдельно, через конструктор это делать нехорошо,
// поскольку сцена создаётся в сгенерённом ui-шнике.
// если нет ни одной диаграммы, то ничего не создаем.
if (mv_iface->model()->rowCount(QModelIndex()) == 0)
return;
// Transform mime data to include coordinates.
const QMimeData *mimeData = event->mimeData();
QByteArray itemData = mimeData->data("application/x-real-uml-data");
QDataStream in_stream(&itemData, QIODevice::ReadOnly);
QString uuid = "";
QString pathToItem = "";
QString name;
QPointF pos;
in_stream >> uuid;
in_stream >> pathToItem;
in_stream >> name;
in_stream >> pos;
QByteArray newItemData;
QDataStream stream(&newItemData, QIODevice::WriteOnly);
UML::Element *newParent = NULL;
// TODO: возможно, это можно сделать проще
qReal::Id id = qReal::Id::loadFromString(uuid);
UML::Element *e = mWindow->manager()->graphicalObject(id);
// = UML::GUIObjectFactory(type_id);
if (dynamic_cast<UML::NodeElement*>(e))
newParent = getElemAt(event->scenePos());
if (e)
delete e;
if( newParent ){
if (!canBeContainedBy(newParent->uuid(), id)){
QMessageBox::critical(0, "Error!", "[some text]");
return;
}
}
stream << uuid; // uuid
stream << pathToItem;
stream << name;
if (!newParent)
stream << event->scenePos();
else
stream << newParent->mapToItem(newParent, newParent->mapFromScene(event->scenePos()));
QMimeData *newMimeData = new QMimeData;
newMimeData->setData("application/x-real-uml-data", newItemData);
QModelIndex parentIndex = newParent ? QModelIndex(newParent->index()) : mv_iface->rootIndex();
mv_iface->model()->dropMimeData(newMimeData, event->dropAction(),
mv_iface->model()->rowCount(parentIndex), 0, parentIndex);
delete newMimeData;
}
void EditorViewScene::keyPressEvent(QKeyEvent *event)
{
if (dynamic_cast<QGraphicsTextItem*>(this->focusItem())) {
// Forward event to text editor
QGraphicsScene::keyPressEvent(event);
} else if (event->key() == Qt::Key_Delete) {
// Delete selected elements from scene
mainWindow()->deleteFromScene();
} else
QGraphicsScene::keyPressEvent(event);
}
void EditorViewScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
// Let scene update selection and perform other operations
QGraphicsScene::mousePressEvent(event);
if( event->button() == Qt::LeftButton ){
QGraphicsItem *item = itemAt(event->scenePos());
qDebug() << "item: " << item;
UML::ElementTitle *title = dynamic_cast < UML::ElementTitle * >(item);
if( title ){ // проверяем, а не зацепились ли мы случайно за надпись, когда начали тащить эоемент
item = item->parentItem();
}
if( item ){
mPrevParent = item->parentItem();
mPrevPosition = item->pos();
qDebug() << "NEW mPrevParent: " << mPrevParent;
qDebug() << "NEW pos: " << mPrevPosition;
}
} else if (event->button() == Qt::RightButton){
UML::Element *e = getElemAt(event->scenePos());
if (!e)
return;
if (!e->isSelected()) {
clearSelection();
e->setSelected(true);
}
// Menu belongs to scene handler because it can delete elements.
// We cannot allow elements to commit suicide.
QMenu menu;
menu.addAction(mWindow->ui.actionDeleteFromDiagram);
QList<UML::ContextMenuAction*> elementActions = e->contextMenuActions();
if (!elementActions.isEmpty())
menu.addSeparator();
foreach (UML::ContextMenuAction* action, elementActions) {
action->setEventPos(e->mapFromScene(event->scenePos()));
menu.addAction(action);
}
// Пункты меню, отвечающие за провязку, "привязать к".
// TODO: Перенести это в элементы, они лучше знают, что они такое, а тут
// сцене модель и апи приходится спрашивать.
QMenu *connectToMenu = menu.addMenu(tr("Connect to"));
IdList possibleTypes = mWindow->manager()->getConnectedTypes(e->uuid().type());
qReal::model::Model *model = dynamic_cast<qReal::model::Model *>(mv_iface->model());
foreach (Id type, possibleTypes) {
foreach (Id element, model->api().elements(type)) {
if (model->api().outgoingConnections(e->uuid()).contains(element))
continue;
QAction *action = connectToMenu->addAction(model->api().name(element));
connect(action, SIGNAL(triggered()), SLOT(connectActionTriggered()));
QList<QVariant> tag;
tag << e->uuid().toVariant() << element.toVariant();
action->setData(tag);
}
}
QMenu *goToMenu = menu.addMenu(tr("Go to"));
foreach (Id element, model->api().outgoingConnections(e->uuid())) {
QAction *action = goToMenu->addAction(model->api().name(element));
connect(action, SIGNAL(triggered()), SLOT(goToActionTriggered()));
action->setData(element.toVariant());
}
QMenu *usedInMenu = menu.addMenu(tr("Used in"));
foreach (Id element, model->api().incomingConnections(e->uuid())) {
QAction *action = usedInMenu->addAction(model->api().name(element));
connect(action, SIGNAL(triggered()), SLOT(goToActionTriggered()));
action->setData(element.toVariant());
}
QMenu *disconnectMenu = menu.addMenu(tr("Disconnect"));
IdList list = model->api().outgoingConnections(e->uuid());
list.append(model->api().incomingConnections(e->uuid()));
foreach (Id element, list) {
QAction *action = disconnectMenu->addAction(model->api().name(element));
connect(action, SIGNAL(triggered()), SLOT(disconnectActionTriggered()));
QList<QVariant> tag;
tag << e->uuid().toVariant() << element.toVariant();
action->setData(tag);
}
// FIXME: add check for diagram
// if (selectedItems().count() == 1)
// menu.addAction(window->ui.actionJumpToAvatar);
menu.exec(QCursor::pos());
}
}
void EditorViewScene::mouseReleaseEvent ( QGraphicsSceneMouseEvent * event )
{
// Let scene update selection and perform other operations
QGraphicsScene::mouseReleaseEvent(event);
UML::Element *element = getElemAt(event->scenePos());
if (!element)
return;
qDebug() << "element" << element->uuid().toString();
UML::Element *parent = getElemByModelIndex(element->index().parent());
if (parent){
qDebug() << "parent: " << parent->uuid().toString();
if (!canBeContainedBy(parent->uuid(), element->uuid())){
QMessageBox::critical(0, "Ololo", "can't drop it here!111");
// фэйл, репарентим элемент обратно
foreach (QGraphicsItem *item, items(event->scenePos())) {
UML::Element * elem = dynamic_cast < UML::Element * >(item);
if (elem && elem->uuid() == element->uuid()) {
QModelIndex ind = mv_iface->rootIndex();
UML::Element * prevParent = dynamic_cast < UML::Element * >(mPrevParent);
qDebug() << "prev parent: " << mPrevParent;
if (prevParent)
ind = prevParent->index();
qReal::model::Model *model = dynamic_cast < qReal::model::Model *> (mv_iface->model());
if (model)
model->changeParent(element->index(), ind, mPrevPosition);
// elem->setParentItem(mPrevParent);
// elem->setPos(mPrevPosition);
qDebug() << "new pos: " << elem->scenePos() << elem->pos();
}
}
}
}
}
void EditorViewScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
// Double click on a title activates it
if (UML::ElementTitle *title = dynamic_cast<UML::ElementTitle*>(itemAt(event->scenePos()))) {
if (!title->hasFocus()) { // Do not activate already activated item
event->accept();
title->startTextInteraction();
return;
}
}
else if (UML::NodeElement *element = dynamic_cast<UML::NodeElement*>(itemAt(event->scenePos()))) {
event->accept();
qReal::model::Model *model = dynamic_cast<qReal::model::Model *>(mv_iface->model());
IdList outgoingLinks = model->api().outgoingConnections(element->uuid());
if (outgoingLinks.size() > 0)
mainWindow()->activateItemOrDiagram(outgoingLinks[0]);
// Now scene is changed from outside. Being a mere mortal I do not
// know whether it is good or not, but what is the destiny of
// workflow after this return?
return;
}
}
QGraphicsScene::mouseDoubleClickEvent(event);
}
UML::Element* EditorViewScene::getElemAt(QPointF const &position)
{
foreach (QGraphicsItem *item, items(position)) {
UML::Element *e = dynamic_cast<UML::Element *>(item);
if (e)
return e;
}
return NULL;
}
QPersistentModelIndex EditorViewScene::rootItem()
{
return mv_iface->rootIndex();
}
void EditorViewScene::setMainWindow(qReal::MainWindow *mainWindow)
{
mWindow = mainWindow;
}
qReal::MainWindow *EditorViewScene::mainWindow() const
{
return mWindow;
}
void EditorViewScene::connectActionTriggered()
{
QAction *action = static_cast<QAction *>(sender());
QList<QVariant> connection = action->data().toList();
Id source = connection[0].value<Id>();
Id destination = connection[1].value<Id>();
qReal::model::Model *model = dynamic_cast<qReal::model::Model *>(mv_iface->model());
// Модели нет дела до провязки, поскольку это свойство логической, а не
// графической модели.
model->mutableApi().connect(source, destination);
}
void EditorViewScene::goToActionTriggered()
{
QAction *action = static_cast<QAction *>(sender());
Id target = action->data().value<Id>();
mainWindow()->activateItemOrDiagram(target);
return;
}
void EditorViewScene::disconnectActionTriggered()
{
QAction *action = static_cast<QAction *>(sender());
QList<QVariant> connection = action->data().toList();
Id source = connection[0].value<Id>();
Id destination = connection[1].value<Id>();
qReal::model::Model *model = dynamic_cast<qReal::model::Model *>(mv_iface->model());
model->mutableApi().disconnect(source, destination);
}
<commit_msg>Убрал проверку типов при репарентинге (unfixed http://unreal.tepkom.ru/trac/ticket/232), надо сначала поправить все xml-ки, иначе риалом пользоваться нельзя.<commit_after>/** @file editorviewscene.cpp
* @brief Сцена для отрисовки объектов
* */
#include "editorviewscene.h"
#include <QGraphicsTextItem>
#include <QtGui>
#include "editorviewmviface.h"
#include "editorview.h"
#include "mainwindow.h"
#include "../mainwindow/mainwindow.h"
#include "../model/model.h"
using namespace qReal;
EditorViewScene::EditorViewScene(QObject * parent)
: QGraphicsScene(parent), mWindow(NULL), mPrevParent(0)
{
setItemIndexMethod(NoIndex);
setEnabled(false);
}
void EditorViewScene::setEnabled(bool enabled)
{
foreach (QGraphicsView *view, views())
view->setEnabled(enabled);
}
void EditorViewScene::clearScene()
{
foreach (QGraphicsItem *item, items())
// Выглядит довольно безумно, но некоторые элементы
// оказываются уже удалены, потому как был удалён их родитель.
if (items().contains(item))
removeItem(item);
}
UML::Element * EditorViewScene::getElem(qReal::Id const &uuid)
{
if (uuid == ROOT_ID)
return NULL;
// FIXME: SLOW!
QList < QGraphicsItem * > list = items();
for (QList < QGraphicsItem * >::Iterator it = list.begin(); it != list.end(); ++it) {
if (UML::Element * elem = dynamic_cast < UML::Element * >(*it)) {
if (elem->uuid() == uuid) {
return elem;
}
}
}
return NULL;
}
UML::Element * EditorViewScene::getElemByModelIndex(const QModelIndex &ind)
{
// FIXME: SLOW!
QList < QGraphicsItem * > list = items();
for (QList < QGraphicsItem * >::Iterator it = list.begin(); it != list.end(); ++it) {
if (UML::Element * elem = dynamic_cast < UML::Element * >(*it)) {
if (elem->index() == ind)
return elem;
}
}
return NULL;
}
void EditorViewScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
const QMimeData *mimeData = event->mimeData();
if (mimeData->hasFormat("application/x-real-uml-data"))
QGraphicsScene::dragEnterEvent(event);
else
event->ignore();
}
void EditorViewScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_UNUSED(event);
}
void EditorViewScene::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_UNUSED(event);
}
bool EditorViewScene::canBeContainedBy(qReal::Id container, qReal::Id candidate)
{
// Типизированные контейнеры временно закомментированы, надо сначала поправить xml-ки.
return true;
/*
bool allowed = false;
foreach (qReal::Id type, mWindow->manager()->getContainedTypes(container.type())){
if (candidate.element() == type.editor())
allowed = true;
}
return allowed;
*/
}
void EditorViewScene::dropEvent(QGraphicsSceneDragDropEvent *event)
{
Q_ASSERT(mWindow); // Значение mWindow должно быть инициализировано
// отдельно, через конструктор это делать нехорошо,
// поскольку сцена создаётся в сгенерённом ui-шнике.
// если нет ни одной диаграммы, то ничего не создаем.
if (mv_iface->model()->rowCount(QModelIndex()) == 0)
return;
// Transform mime data to include coordinates.
const QMimeData *mimeData = event->mimeData();
QByteArray itemData = mimeData->data("application/x-real-uml-data");
QDataStream in_stream(&itemData, QIODevice::ReadOnly);
QString uuid = "";
QString pathToItem = "";
QString name;
QPointF pos;
in_stream >> uuid;
in_stream >> pathToItem;
in_stream >> name;
in_stream >> pos;
QByteArray newItemData;
QDataStream stream(&newItemData, QIODevice::WriteOnly);
UML::Element *newParent = NULL;
// TODO: возможно, это можно сделать проще
qReal::Id id = qReal::Id::loadFromString(uuid);
UML::Element *e = mWindow->manager()->graphicalObject(id);
// = UML::GUIObjectFactory(type_id);
if (dynamic_cast<UML::NodeElement*>(e))
newParent = getElemAt(event->scenePos());
if (e)
delete e;
if( newParent ){
if (!canBeContainedBy(newParent->uuid(), id)){
QMessageBox::critical(0, "Error!", "[some text]");
return;
}
}
stream << uuid; // uuid
stream << pathToItem;
stream << name;
if (!newParent)
stream << event->scenePos();
else
stream << newParent->mapToItem(newParent, newParent->mapFromScene(event->scenePos()));
QMimeData *newMimeData = new QMimeData;
newMimeData->setData("application/x-real-uml-data", newItemData);
QModelIndex parentIndex = newParent ? QModelIndex(newParent->index()) : mv_iface->rootIndex();
mv_iface->model()->dropMimeData(newMimeData, event->dropAction(),
mv_iface->model()->rowCount(parentIndex), 0, parentIndex);
delete newMimeData;
}
void EditorViewScene::keyPressEvent(QKeyEvent *event)
{
if (dynamic_cast<QGraphicsTextItem*>(this->focusItem())) {
// Forward event to text editor
QGraphicsScene::keyPressEvent(event);
} else if (event->key() == Qt::Key_Delete) {
// Delete selected elements from scene
mainWindow()->deleteFromScene();
} else
QGraphicsScene::keyPressEvent(event);
}
void EditorViewScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
// Let scene update selection and perform other operations
QGraphicsScene::mousePressEvent(event);
if( event->button() == Qt::LeftButton ){
QGraphicsItem *item = itemAt(event->scenePos());
qDebug() << "item: " << item;
UML::ElementTitle *title = dynamic_cast < UML::ElementTitle * >(item);
if( title ){ // проверяем, а не зацепились ли мы случайно за надпись, когда начали тащить эоемент
item = item->parentItem();
}
if( item ){
mPrevParent = item->parentItem();
mPrevPosition = item->pos();
qDebug() << "NEW mPrevParent: " << mPrevParent;
qDebug() << "NEW pos: " << mPrevPosition;
}
} else if (event->button() == Qt::RightButton){
UML::Element *e = getElemAt(event->scenePos());
if (!e)
return;
if (!e->isSelected()) {
clearSelection();
e->setSelected(true);
}
// Menu belongs to scene handler because it can delete elements.
// We cannot allow elements to commit suicide.
QMenu menu;
menu.addAction(mWindow->ui.actionDeleteFromDiagram);
QList<UML::ContextMenuAction*> elementActions = e->contextMenuActions();
if (!elementActions.isEmpty())
menu.addSeparator();
foreach (UML::ContextMenuAction* action, elementActions) {
action->setEventPos(e->mapFromScene(event->scenePos()));
menu.addAction(action);
}
// Пункты меню, отвечающие за провязку, "привязать к".
// TODO: Перенести это в элементы, они лучше знают, что они такое, а тут
// сцене модель и апи приходится спрашивать.
QMenu *connectToMenu = menu.addMenu(tr("Connect to"));
IdList possibleTypes = mWindow->manager()->getConnectedTypes(e->uuid().type());
qReal::model::Model *model = dynamic_cast<qReal::model::Model *>(mv_iface->model());
foreach (Id type, possibleTypes) {
foreach (Id element, model->api().elements(type)) {
if (model->api().outgoingConnections(e->uuid()).contains(element))
continue;
QAction *action = connectToMenu->addAction(model->api().name(element));
connect(action, SIGNAL(triggered()), SLOT(connectActionTriggered()));
QList<QVariant> tag;
tag << e->uuid().toVariant() << element.toVariant();
action->setData(tag);
}
}
QMenu *goToMenu = menu.addMenu(tr("Go to"));
foreach (Id element, model->api().outgoingConnections(e->uuid())) {
QAction *action = goToMenu->addAction(model->api().name(element));
connect(action, SIGNAL(triggered()), SLOT(goToActionTriggered()));
action->setData(element.toVariant());
}
QMenu *usedInMenu = menu.addMenu(tr("Used in"));
foreach (Id element, model->api().incomingConnections(e->uuid())) {
QAction *action = usedInMenu->addAction(model->api().name(element));
connect(action, SIGNAL(triggered()), SLOT(goToActionTriggered()));
action->setData(element.toVariant());
}
QMenu *disconnectMenu = menu.addMenu(tr("Disconnect"));
IdList list = model->api().outgoingConnections(e->uuid());
list.append(model->api().incomingConnections(e->uuid()));
foreach (Id element, list) {
QAction *action = disconnectMenu->addAction(model->api().name(element));
connect(action, SIGNAL(triggered()), SLOT(disconnectActionTriggered()));
QList<QVariant> tag;
tag << e->uuid().toVariant() << element.toVariant();
action->setData(tag);
}
// FIXME: add check for diagram
// if (selectedItems().count() == 1)
// menu.addAction(window->ui.actionJumpToAvatar);
menu.exec(QCursor::pos());
}
}
void EditorViewScene::mouseReleaseEvent ( QGraphicsSceneMouseEvent * event )
{
// Let scene update selection and perform other operations
QGraphicsScene::mouseReleaseEvent(event);
UML::Element *element = getElemAt(event->scenePos());
if (!element)
return;
qDebug() << "element" << element->uuid().toString();
UML::Element *parent = getElemByModelIndex(element->index().parent());
if (parent){
qDebug() << "parent: " << parent->uuid().toString();
if (!canBeContainedBy(parent->uuid(), element->uuid())){
QMessageBox::critical(0, "Ololo", "can't drop it here!111");
// фэйл, репарентим элемент обратно
foreach (QGraphicsItem *item, items(event->scenePos())) {
UML::Element * elem = dynamic_cast < UML::Element * >(item);
if (elem && elem->uuid() == element->uuid()) {
QModelIndex ind = mv_iface->rootIndex();
UML::Element * prevParent = dynamic_cast < UML::Element * >(mPrevParent);
qDebug() << "prev parent: " << mPrevParent;
if (prevParent)
ind = prevParent->index();
qReal::model::Model *model = dynamic_cast < qReal::model::Model *> (mv_iface->model());
if (model)
model->changeParent(element->index(), ind, mPrevPosition);
// elem->setParentItem(mPrevParent);
// elem->setPos(mPrevPosition);
qDebug() << "new pos: " << elem->scenePos() << elem->pos();
}
}
}
}
}
void EditorViewScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
// Double click on a title activates it
if (UML::ElementTitle *title = dynamic_cast<UML::ElementTitle*>(itemAt(event->scenePos()))) {
if (!title->hasFocus()) { // Do not activate already activated item
event->accept();
title->startTextInteraction();
return;
}
}
else if (UML::NodeElement *element = dynamic_cast<UML::NodeElement*>(itemAt(event->scenePos()))) {
event->accept();
qReal::model::Model *model = dynamic_cast<qReal::model::Model *>(mv_iface->model());
IdList outgoingLinks = model->api().outgoingConnections(element->uuid());
if (outgoingLinks.size() > 0)
mainWindow()->activateItemOrDiagram(outgoingLinks[0]);
// Now scene is changed from outside. Being a mere mortal I do not
// know whether it is good or not, but what is the destiny of
// workflow after this return?
return;
}
}
QGraphicsScene::mouseDoubleClickEvent(event);
}
UML::Element* EditorViewScene::getElemAt(QPointF const &position)
{
foreach (QGraphicsItem *item, items(position)) {
UML::Element *e = dynamic_cast<UML::Element *>(item);
if (e)
return e;
}
return NULL;
}
QPersistentModelIndex EditorViewScene::rootItem()
{
return mv_iface->rootIndex();
}
void EditorViewScene::setMainWindow(qReal::MainWindow *mainWindow)
{
mWindow = mainWindow;
}
qReal::MainWindow *EditorViewScene::mainWindow() const
{
return mWindow;
}
void EditorViewScene::connectActionTriggered()
{
QAction *action = static_cast<QAction *>(sender());
QList<QVariant> connection = action->data().toList();
Id source = connection[0].value<Id>();
Id destination = connection[1].value<Id>();
qReal::model::Model *model = dynamic_cast<qReal::model::Model *>(mv_iface->model());
// Модели нет дела до провязки, поскольку это свойство логической, а не
// графической модели.
model->mutableApi().connect(source, destination);
}
void EditorViewScene::goToActionTriggered()
{
QAction *action = static_cast<QAction *>(sender());
Id target = action->data().value<Id>();
mainWindow()->activateItemOrDiagram(target);
return;
}
void EditorViewScene::disconnectActionTriggered()
{
QAction *action = static_cast<QAction *>(sender());
QList<QVariant> connection = action->data().toList();
Id source = connection[0].value<Id>();
Id destination = connection[1].value<Id>();
qReal::model::Model *model = dynamic_cast<qReal::model::Model *>(mv_iface->model());
model->mutableApi().disconnect(source, destination);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/GrPathRendererChain.h"
#include "include/gpu/GrDirectContext.h"
#include "include/gpu/GrRecordingContext.h"
#include "src/gpu/GrCaps.h"
#include "src/gpu/GrDirectContextPriv.h"
#include "src/gpu/GrGpu.h"
#include "src/gpu/GrRecordingContextPriv.h"
#include "src/gpu/GrShaderCaps.h"
#include "src/gpu/ccpr/GrCoverageCountingPathRenderer.h"
#include "src/gpu/geometry/GrStyledShape.h"
#include "src/gpu/ops/GrAAConvexPathRenderer.h"
#include "src/gpu/ops/GrAAHairLinePathRenderer.h"
#include "src/gpu/ops/GrAALinearizingConvexPathRenderer.h"
#include "src/gpu/ops/GrDashLinePathRenderer.h"
#include "src/gpu/ops/GrDefaultPathRenderer.h"
#include "src/gpu/ops/GrSmallPathRenderer.h"
#include "src/gpu/ops/GrTriangulatingPathRenderer.h"
#include "src/gpu/tessellate/GrTessellationPathRenderer.h"
GrPathRendererChain::GrPathRendererChain(GrRecordingContext* context, const Options& options) {
const GrCaps& caps = *context->priv().caps();
if (options.fGpuPathRenderers & GpuPathRenderers::kDashLine) {
fChain.push_back(sk_make_sp<GrDashLinePathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kAAConvex) {
fChain.push_back(sk_make_sp<GrAAConvexPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kCoverageCounting) {
// opsTask IDs for the atlas have an issue with --reduceOpsTaskSplitting: skbug.com/11731
if (context->priv().options().fReduceOpsTaskSplitting != GrContextOptions::Enable::kYes) {
fCoverageCountingPathRenderer = GrCoverageCountingPathRenderer::CreateIfSupported(caps);
if (fCoverageCountingPathRenderer) {
// Don't add to the chain. This is only for clips.
// TODO: Remove from here.
context->priv().addOnFlushCallbackObject(fCoverageCountingPathRenderer.get());
}
}
}
if (options.fGpuPathRenderers & GpuPathRenderers::kAAHairline) {
fChain.push_back(sk_make_sp<GrAAHairLinePathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kAALinearizing) {
fChain.push_back(sk_make_sp<GrAALinearizingConvexPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kSmall) {
fChain.push_back(sk_make_sp<GrSmallPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kTriangulating) {
fChain.push_back(sk_make_sp<GrTriangulatingPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kTessellation) {
if (GrTessellationPathRenderer::IsSupported(caps)) {
auto tess = sk_make_sp<GrTessellationPathRenderer>(context);
fTessellationPathRenderer = tess.get();
context->priv().addOnFlushCallbackObject(tess.get());
fChain.push_back(std::move(tess));
}
}
// We always include the default path renderer (as well as SW), so we can draw any path
fChain.push_back(sk_make_sp<GrDefaultPathRenderer>());
}
GrPathRenderer* GrPathRendererChain::getPathRenderer(
const GrPathRenderer::CanDrawPathArgs& args,
DrawType drawType,
GrPathRenderer::StencilSupport* stencilSupport) {
static_assert(GrPathRenderer::kNoSupport_StencilSupport <
GrPathRenderer::kStencilOnly_StencilSupport);
static_assert(GrPathRenderer::kStencilOnly_StencilSupport <
GrPathRenderer::kNoRestriction_StencilSupport);
GrPathRenderer::StencilSupport minStencilSupport;
if (DrawType::kStencil == drawType) {
minStencilSupport = GrPathRenderer::kStencilOnly_StencilSupport;
} else if (DrawType::kStencilAndColor == drawType) {
minStencilSupport = GrPathRenderer::kNoRestriction_StencilSupport;
} else {
minStencilSupport = GrPathRenderer::kNoSupport_StencilSupport;
}
if (minStencilSupport != GrPathRenderer::kNoSupport_StencilSupport) {
// We don't support (and shouldn't need) stenciling of non-fill paths.
if (!args.fShape->style().isSimpleFill()) {
return nullptr;
}
}
GrPathRenderer* bestPathRenderer = nullptr;
for (const sk_sp<GrPathRenderer>& pr : fChain) {
GrPathRenderer::StencilSupport support = GrPathRenderer::kNoSupport_StencilSupport;
if (GrPathRenderer::kNoSupport_StencilSupport != minStencilSupport) {
support = pr->getStencilSupport(*args.fShape);
if (support < minStencilSupport) {
continue;
}
}
GrPathRenderer::CanDrawPath canDrawPath = pr->canDrawPath(args);
if (GrPathRenderer::CanDrawPath::kNo == canDrawPath) {
continue;
}
if (GrPathRenderer::CanDrawPath::kAsBackup == canDrawPath && bestPathRenderer) {
continue;
}
if (stencilSupport) {
*stencilSupport = support;
}
bestPathRenderer = pr.get();
if (GrPathRenderer::CanDrawPath::kYes == canDrawPath) {
break;
}
}
return bestPathRenderer;
}
<commit_msg>Reland "Re-enable CCPR atlasing + reordering"<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/GrPathRendererChain.h"
#include "include/gpu/GrDirectContext.h"
#include "include/gpu/GrRecordingContext.h"
#include "src/gpu/GrCaps.h"
#include "src/gpu/GrDirectContextPriv.h"
#include "src/gpu/GrGpu.h"
#include "src/gpu/GrRecordingContextPriv.h"
#include "src/gpu/GrShaderCaps.h"
#include "src/gpu/ccpr/GrCoverageCountingPathRenderer.h"
#include "src/gpu/geometry/GrStyledShape.h"
#include "src/gpu/ops/GrAAConvexPathRenderer.h"
#include "src/gpu/ops/GrAAHairLinePathRenderer.h"
#include "src/gpu/ops/GrAALinearizingConvexPathRenderer.h"
#include "src/gpu/ops/GrDashLinePathRenderer.h"
#include "src/gpu/ops/GrDefaultPathRenderer.h"
#include "src/gpu/ops/GrSmallPathRenderer.h"
#include "src/gpu/ops/GrTriangulatingPathRenderer.h"
#include "src/gpu/tessellate/GrTessellationPathRenderer.h"
GrPathRendererChain::GrPathRendererChain(GrRecordingContext* context, const Options& options) {
const GrCaps& caps = *context->priv().caps();
if (options.fGpuPathRenderers & GpuPathRenderers::kDashLine) {
fChain.push_back(sk_make_sp<GrDashLinePathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kAAConvex) {
fChain.push_back(sk_make_sp<GrAAConvexPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kCoverageCounting) {
fCoverageCountingPathRenderer = GrCoverageCountingPathRenderer::CreateIfSupported(caps);
if (fCoverageCountingPathRenderer) {
// Don't add to the chain. This is only for clips.
// TODO: Remove from here.
context->priv().addOnFlushCallbackObject(fCoverageCountingPathRenderer.get());
}
}
if (options.fGpuPathRenderers & GpuPathRenderers::kAAHairline) {
fChain.push_back(sk_make_sp<GrAAHairLinePathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kAALinearizing) {
fChain.push_back(sk_make_sp<GrAALinearizingConvexPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kSmall) {
fChain.push_back(sk_make_sp<GrSmallPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kTriangulating) {
fChain.push_back(sk_make_sp<GrTriangulatingPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kTessellation) {
if (GrTessellationPathRenderer::IsSupported(caps)) {
auto tess = sk_make_sp<GrTessellationPathRenderer>(context);
fTessellationPathRenderer = tess.get();
context->priv().addOnFlushCallbackObject(tess.get());
fChain.push_back(std::move(tess));
}
}
// We always include the default path renderer (as well as SW), so we can draw any path
fChain.push_back(sk_make_sp<GrDefaultPathRenderer>());
}
GrPathRenderer* GrPathRendererChain::getPathRenderer(
const GrPathRenderer::CanDrawPathArgs& args,
DrawType drawType,
GrPathRenderer::StencilSupport* stencilSupport) {
static_assert(GrPathRenderer::kNoSupport_StencilSupport <
GrPathRenderer::kStencilOnly_StencilSupport);
static_assert(GrPathRenderer::kStencilOnly_StencilSupport <
GrPathRenderer::kNoRestriction_StencilSupport);
GrPathRenderer::StencilSupport minStencilSupport;
if (DrawType::kStencil == drawType) {
minStencilSupport = GrPathRenderer::kStencilOnly_StencilSupport;
} else if (DrawType::kStencilAndColor == drawType) {
minStencilSupport = GrPathRenderer::kNoRestriction_StencilSupport;
} else {
minStencilSupport = GrPathRenderer::kNoSupport_StencilSupport;
}
if (minStencilSupport != GrPathRenderer::kNoSupport_StencilSupport) {
// We don't support (and shouldn't need) stenciling of non-fill paths.
if (!args.fShape->style().isSimpleFill()) {
return nullptr;
}
}
GrPathRenderer* bestPathRenderer = nullptr;
for (const sk_sp<GrPathRenderer>& pr : fChain) {
GrPathRenderer::StencilSupport support = GrPathRenderer::kNoSupport_StencilSupport;
if (GrPathRenderer::kNoSupport_StencilSupport != minStencilSupport) {
support = pr->getStencilSupport(*args.fShape);
if (support < minStencilSupport) {
continue;
}
}
GrPathRenderer::CanDrawPath canDrawPath = pr->canDrawPath(args);
if (GrPathRenderer::CanDrawPath::kNo == canDrawPath) {
continue;
}
if (GrPathRenderer::CanDrawPath::kAsBackup == canDrawPath && bestPathRenderer) {
continue;
}
if (stencilSupport) {
*stencilSupport = support;
}
bestPathRenderer = pr.get();
if (GrPathRenderer::CanDrawPath::kYes == canDrawPath) {
break;
}
}
return bestPathRenderer;
}
<|endoftext|> |
<commit_before>#ifndef RCC_T_HH
#define RCC_T_HH
namespace hal {
struct ahb_devices_t {
uint32_t dma1:1;
uint32_t dma2:1;
uint32_t sram:1;
uint32_t _unused0:1;
uint32_t flitf:1;
uint32_t _unused1:1;
uint32_t crc:1;
uint32_t _unused2:10;
uint32_t gpioa:1;
uint32_t gpiob:1;
uint32_t gpioc:1;
uint32_t gpiod:1;
uint32_t gpioe:1;
uint32_t gpiof:1;
uint32_t _unused3:1;
uint32_t tsc:1;
uint32_t _unused4:3;
uint32_t adc12:1;
uint32_t adc32:1;
uint32_t _unused5:2;
};
struct rcc_t {
uint32_t cr;
uint32_t cfgr;
uint32_t cir;
uint32_t apb2rstr;
uint32_t apb1rstr;
ahb_devices_t ahb_enable;
uint32_t apb2enr;
uint32_t apb1enr;
uint32_t bdcr;
uint32_t csr;
ahb_devices_t ahb_reset;
uint32_t cfgr2;
uint32_t cfgr3;
};
} // namespace Hal
#endif // RCC_T_HH
<commit_msg>Update stm32f3xx hal/rcc_t to intrnal types<commit_after>#ifndef RCC_T_HH
#define RCC_T_HH
#include "lib/types.hh"
namespace hal {
struct ahb_devices_t {
lib::u32 dma1:1;
lib::u32 dma2:1;
lib::u32 sram:1;
lib::u32 _unused0:1;
lib::u32 flitf:1;
lib::u32 _unused1:1;
lib::u32 crc:1;
lib::u32 _unused2:10;
lib::u32 gpioa:1;
lib::u32 gpiob:1;
lib::u32 gpioc:1;
lib::u32 gpiod:1;
lib::u32 gpioe:1;
lib::u32 gpiof:1;
lib::u32 _unused3:1;
lib::u32 tsc:1;
lib::u32 _unused4:3;
lib::u32 adc12:1;
lib::u32 adc32:1;
lib::u32 _unused5:2;
};
struct rcc_t {
lib::u32 cr;
lib::u32 cfgr;
lib::u32 cir;
lib::u32 apb2rstr;
lib::u32 apb1rstr;
ahb_devices_t ahb_enable;
lib::u32 apb2enr;
lib::u32 apb1enr;
lib::u32 bdcr;
lib::u32 csr;
ahb_devices_t ahb_reset;
lib::u32 cfgr2;
lib::u32 cfgr3;
};
} // namespace Hal
#endif // RCC_T_HH
<|endoftext|> |
<commit_before>/*************************************************************************
This software allows for filtering in high-dimensional observation and
state spaces, as described in
M. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal.
Probabilistic Object Tracking using a Range Camera
IEEE/RSJ Intl Conf on Intelligent Robots and Systems, 2013
In a publication based on this software pleace cite the above reference.
Copyright (C) 2014 Manuel Wuthrich
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*************************************************************************/
#ifndef FAST_FILTERING_UTILS_HELPER_FUNCTIONS_HPP
#define FAST_FILTERING_UTILS_HELPER_FUNCTIONS_HPP
#include <vector>
#include <algorithm>
#include <iostream>
#include <limits>
#include <Eigen/Dense>
#include <cmath>
#include <ctime>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <boost/random/lagged_fibonacci.hpp>
#include <fl/util/random_seed.hpp>
// TODO: THIS HAS TO BE CLEANED, POSSIBLY SPLIT INTO SEVERAL FILES
namespace fl
{
namespace hf
{
// use std::min_element & std::max_element instead. better API if split into two functions
template <typename T> int BoundIndex(const std::vector<T> &values, bool bound_type) // bound type 1 for max and 0 for min
{
int BoundIndex = 0;
T bound_value = bound_type ? -std::numeric_limits<T>::max() : std::numeric_limits<T>::max();
for(int i = 0; i < int(values.size()); i++)
if(bound_type ? (values[i] > bound_value) : (values[i] < bound_value) )
{
BoundIndex = i;
bound_value = values[i];
}
return BoundIndex;
}
// use std::min_element & std::max_element instead
template <typename T> T bound_value(const std::vector<T> &values, bool bound_type) // bound type 1 for max and 0 for min
{
return values[BoundIndex(values, bound_type)];
}
// use std::transform or for_each instead
template <typename Tin, typename Tout>
std::vector<Tout> Apply(const std::vector<Tin> &input, Tout(*f)(Tin))
{
std::vector<Tout> output(input.size());
for(size_t i = 0; i < output.size(); i++)
output[i] = (*f)(input[i]);
return output;
}
// sampling class >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
class DiscreteDistribution
{
public:
template <typename T> DiscreteDistribution(std::vector<T> log_prob)
{
uniform_sampler_.seed(RANDOM_SEED);
// substract max to avoid numerical issues
double max = hf::bound_value(log_prob, true);
for(int i = 0; i < int(log_prob.size()); i++)
log_prob[i] -= max;
// compute probabilities
std::vector<double> prob(log_prob.size());
double sum = 0;
for(int i = 0; i < int(log_prob.size()); i++)
{
prob[i] = std::exp(log_prob[i]);
sum += prob[i];
}
for(int i = 0; i < int(prob.size()); i++)
prob[i] /= sum;
// compute the cumulative probability
cumulative_prob_.resize(prob.size());
cumulative_prob_[0] = prob[0];
for(size_t i = 1; i < prob.size(); i++)
cumulative_prob_[i] = cumulative_prob_[i-1] + prob[i];
}
~DiscreteDistribution() {}
int Sample()
{
return MapStandardUniform(uniform_sampler_());
}
int MapStandardGaussian(double gaussian_sample) const
{
double uniform_sample =
0.5 * (1.0 + std::erf(gaussian_sample / std::sqrt(2.0)));
return MapStandardUniform(uniform_sample);
}
int MapStandardUniform(double uniform_sample) const
{
std::vector<double>::const_iterator iterator =
std::lower_bound(cumulative_prob_.begin(),
cumulative_prob_.end(),
uniform_sample);
return iterator - cumulative_prob_.begin();
}
private:
boost::lagged_fibonacci607 uniform_sampler_;
std::vector<double> cumulative_prob_;
};
}
}
#endif
<commit_msg>removed Apply() since it can be replaced by std::for_each or std::transform<commit_after>/*************************************************************************
This software allows for filtering in high-dimensional observation and
state spaces, as described in
M. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal.
Probabilistic Object Tracking using a Range Camera
IEEE/RSJ Intl Conf on Intelligent Robots and Systems, 2013
In a publication based on this software pleace cite the above reference.
Copyright (C) 2014 Manuel Wuthrich
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*************************************************************************/
#ifndef FAST_FILTERING_UTILS_HELPER_FUNCTIONS_HPP
#define FAST_FILTERING_UTILS_HELPER_FUNCTIONS_HPP
#include <vector>
#include <algorithm>
#include <iostream>
#include <limits>
#include <Eigen/Dense>
#include <cmath>
#include <ctime>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <boost/random/lagged_fibonacci.hpp>
#include <fl/util/random_seed.hpp>
// TODO: THIS HAS TO BE CLEANED, POSSIBLY SPLIT INTO SEVERAL FILES
namespace fl
{
namespace hf
{
// use std::min_element & std::max_element instead. better API if split into two functions
template <typename T> int BoundIndex(const std::vector<T> &values, bool bound_type) // bound type 1 for max and 0 for min
{
int BoundIndex = 0;
T bound_value = bound_type ? -std::numeric_limits<T>::max() : std::numeric_limits<T>::max();
for(int i = 0; i < int(values.size()); i++)
if(bound_type ? (values[i] > bound_value) : (values[i] < bound_value) )
{
BoundIndex = i;
bound_value = values[i];
}
return BoundIndex;
}
// use std::min_element & std::max_element instead
template <typename T> T bound_value(const std::vector<T> &values, bool bound_type) // bound type 1 for max and 0 for min
{
return values[BoundIndex(values, bound_type)];
}
// sampling class >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
class DiscreteDistribution
{
public:
template <typename T> DiscreteDistribution(std::vector<T> log_prob)
{
uniform_sampler_.seed(RANDOM_SEED);
// substract max to avoid numerical issues
double max = hf::bound_value(log_prob, true);
for(int i = 0; i < int(log_prob.size()); i++)
log_prob[i] -= max;
// compute probabilities
std::vector<double> prob(log_prob.size());
double sum = 0;
for(int i = 0; i < int(log_prob.size()); i++)
{
prob[i] = std::exp(log_prob[i]);
sum += prob[i];
}
for(int i = 0; i < int(prob.size()); i++)
prob[i] /= sum;
// compute the cumulative probability
cumulative_prob_.resize(prob.size());
cumulative_prob_[0] = prob[0];
for(size_t i = 1; i < prob.size(); i++)
cumulative_prob_[i] = cumulative_prob_[i-1] + prob[i];
}
~DiscreteDistribution() {}
int Sample()
{
return MapStandardUniform(uniform_sampler_());
}
int MapStandardGaussian(double gaussian_sample) const
{
double uniform_sample =
0.5 * (1.0 + std::erf(gaussian_sample / std::sqrt(2.0)));
return MapStandardUniform(uniform_sample);
}
int MapStandardUniform(double uniform_sample) const
{
std::vector<double>::const_iterator iterator =
std::lower_bound(cumulative_prob_.begin(),
cumulative_prob_.end(),
uniform_sample);
return iterator - cumulative_prob_.begin();
}
private:
boost::lagged_fibonacci607 uniform_sampler_;
std::vector<double> cumulative_prob_;
};
}
}
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.
*
*=========================================================================*/
#ifndef itkAttenuationImageFilter_hxx
#define itkAttenuationImageFilter_hxx
#include <algorithm>
#include <cmath>
#include "itk_eigen.h"
#include ITK_EIGEN(Dense)
#include "itkMath.h"
#include "itkImageLinearConstIteratorWithIndex.h"
#include "itkImageSink.h"
#include "itkImageRegionSplitterDirection.h"
#include "itkSimpleDataObjectDecorator.h"
namespace itk
{
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::AttenuationImageFilter()
{
this->SetNumberOfRequiredInputs(1);
this->DynamicMultiThreadingOff();
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
void
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::SetFixedEstimationDepthMM(const float distanceMM)
{
this->SetFixedEstimationDepth(TransformPhysicalToPixelScanLineDistance(distanceMM));
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
float
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::GetFixedEstimationDepthMM() const
{
return this->TransformPixelToPhysicalScanLineDistance(this->GetFixedEstimationDepth());
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
void
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::SetPadUpperBoundsMM(const float distanceMM)
{
this->SetPadUpperBounds(TransformPhysicalToPixelScanLineDistance(distanceMM));
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
float
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::GetPadUpperBoundsMM() const
{
return this->TransformPixelToPhysicalScanLineDistance(this->GetPadUpperBounds());
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
void
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::SetPadLowerBoundsMM(const float distanceMM)
{
this->SetPadLowerBounds(TransformPhysicalToPixelScanLineDistance(distanceMM));
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
float
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::GetPadLowerBoundsMM() const
{
return this->TransformPixelToPhysicalScanLineDistance(this->GetPadLowerBounds());
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
const ImageRegionSplitterBase *
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::GetImageRegionSplitter() const
{
m_RegionSplitter->SetDirection(m_Direction);
return m_RegionSplitter.GetPointer();
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
void
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::VerifyPreconditions() const
{
Superclass::VerifyPreconditions();
if (this->GetInputMaskImage() == nullptr)
{
itkExceptionMacro("Filter requires a mask image for inclusion estimates!");
}
else
{
m_ThreadedInputMaskImage = this->GetInputMaskImage();
}
if (this->GetDirection() >= ImageDimension)
{
itkExceptionMacro("Scan line direction must be a valid image dimension!");
}
if (this->GetSamplingFrequencyMHz() < itk::Math::eps)
{
itkExceptionMacro("RF sampling frequency was not set!");
}
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
void
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::BeforeThreadedGenerateData()
{
Superclass::BeforeThreadedGenerateData();
// Initialize metric image
this->GetOutput()->Allocate();
this->GetOutput()->FillBuffer(0.0f);
// Initialize output mask image
const MaskImageType * inputMaskImage = this->GetInputMaskImage();
m_OutputMaskImage->CopyInformation(inputMaskImage);
m_OutputMaskImage->SetRegions(inputMaskImage->GetLargestPossibleRegion());
m_OutputMaskImage->Allocate();
m_OutputMaskImage->FillBuffer(0.0f);
// Initialize distance weights
unsigned fourSigma = std::max(m_FixedEstimationDepth, 16u); // An arbitrary default.
m_DistanceWeights.resize(fourSigma);
float twoSigmaSquared = fourSigma * fourSigma / 8.0f;
for (unsigned i = 0; i < fourSigma; ++i)
{
m_DistanceWeights[i] = 1.0f - std::exp(i * i / -twoSigmaSquared);
}
// Initialize iVars used in ComputeAttenuation()
float nyquistFrequency = m_SamplingFrequencyMHz / 2;
float numComponents = this->GetInput()->GetNumberOfComponentsPerPixel();
m_FrequencyDelta = nyquistFrequency / numComponents;
m_StartComponent = m_FrequencyBandStartMHz / m_FrequencyDelta;
m_EndComponent = m_FrequencyBandEndMHz / m_FrequencyDelta;
if (m_EndComponent == 0) // If m_FrequencyBandEndMHz is not set
{
m_EndComponent = numComponents - 1; // Use all components
}
m_ConsideredComponents = m_EndComponent - m_StartComponent + 1;
m_ScanStepMM = this->GetInput()->GetSpacing()[m_Direction];
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
void
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::ThreadedGenerateData(
const OutputRegionType & regionForThread,
ThreadIdType)
{
if (regionForThread.GetNumberOfPixels() == 0)
{
return;
}
const InputImageType * input = this->GetInput();
OutputImageType * output = this->GetOutput();
const MaskImageType * inputMaskImage = this->GetInputMaskImage();
ImageLinearConstIteratorWithIndex<TInputImage> it(input, regionForThread);
it.SetDirection(m_Direction);
it.GoToBegin();
unsigned int inclusionLength;
InputIndexType start, end;
thread_local std::vector<float> accumulatedWeight;
accumulatedWeight.resize(regionForThread.GetSize(m_Direction));
// make sure this is not recomputed in the inner loop
const unsigned distanceWeightsSize = m_DistanceWeights.size();
// do the work
while (!it.IsAtEnd())
{
inclusionLength = 0;
while (!it.IsAtEndOfLine())
{
// Advance until an inclusion is found
InputIndexType index = it.GetIndex();
if (ThreadedIsIncluded(index) && inclusionLength == 0)
{
// Step into inclusion
start = it.GetIndex();
}
else if (!ThreadedIsIncluded(index) && inclusionLength > 0)
{
// Stay at last pixel in the inclusion
end = it.GetIndex();
end[m_Direction] -= 1;
// Adjust for pixel padding
start[m_Direction] += m_PadLowerBounds;
end[m_Direction] -= m_PadUpperBounds;
if (start[m_Direction] != end[m_Direction]) // We need at least a pair of pixels to estimate attenuation
{
// Estimate attenuation for each inclusion pixel
// by weighted average of pair-wise attenuations for all pairs
while (start[m_Direction] <= end[m_Direction])
{
for (IndexValueType k = start[m_Direction] + 1; k <= end[m_Direction]; ++k)
{
unsigned pixelDistance = k - start[m_Direction];
InputIndexType target = start;
target[m_Direction] = k;
float estimatedAttenuation = ComputeAttenuation(target, start);
float weight = 1.0; // Weight for this pair's attenuation. 1 for large distances.
if (pixelDistance < distanceWeightsSize) // If pixels are close, weight is lower than 1.
{
weight = m_DistanceWeights[pixelDistance];
}
// Update this pixel
accumulatedWeight[start[m_Direction]] += weight;
output->SetPixel(start, estimatedAttenuation * weight + output->GetPixel(start));
// Update distant pair
accumulatedWeight[k] += weight;
output->SetPixel(target, estimatedAttenuation * weight + output->GetPixel(target));
}
// Normalize output by accumulated weight
output->SetPixel(start, output->GetPixel(start) / accumulatedWeight[start[m_Direction]]);
accumulatedWeight[start[m_Direction]] = 0.0f; // reset for next next inclusion segment
// Possibly eliminate negative attenuations
if (!m_ConsiderNegativeAttenuations && output->GetPixel(start) < 0.0)
{
output->SetPixel(start, 0.0);
}
// Dynamically generate the output mask with values corresponding to input
m_OutputMaskImage->SetPixel(start, inputMaskImage->GetPixel(start));
++start[m_Direction];
}
}
inclusionLength = 0;
}
if (ThreadedIsIncluded(index))
{
++inclusionLength;
}
++it;
}
it.NextLine();
}
};
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
typename AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::OutputPixelType
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::ComputeAttenuation(const InputIndexType & end,
const InputIndexType & start) const
{
// Get RF spectra frequency bins at start and end pixel positions
auto input = this->GetInput();
InputPixelType endSample = input->GetPixel(end);
InputPixelType startSample = input->GetPixel(start);
// Get distance between start and end pixel positions (assume mm units)
const unsigned int pixelDistance = end[m_Direction] - start[m_Direction];
float distanceMM = pixelDistance * m_ScanStepMM;
Eigen::Matrix<float, Eigen::Dynamic, 2> A(m_ConsideredComponents, 2);
Eigen::Matrix<float, Eigen::Dynamic, 1> b(m_ConsideredComponents);
for (unsigned i = 0; i < m_ConsideredComponents; i++)
{
A(i, 0) = 1;
A(i, 1) = (1 + i + m_StartComponent) * m_FrequencyDelta; // x_i = frequency
b(i) = endSample[i + m_StartComponent] / (startSample[i + m_StartComponent] + itk::Math::eps); // y_i = ratio
}
// from https://eigen.tuxfamily.org/dox/group__LeastSquares.html
Eigen::Matrix<float, 1, 2> lineFit = A.householderQr().solve(b);
float frequencySlope = -lineFit(1); // we expect attenuation to increase with frequency
// https://www.electronics-notes.com/articles/basic_concepts/decibel/neper-to-db-conversion.php
// Neper to dB conversion: 1Np = 20 log10e dB, approximately 1Np = 8.6858896 dB
float neper = 20 * itk::Math::log10e;
return 10 * neper * frequencySlope / distanceMM; // 10 converts mm into cm
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
float
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::TransformPhysicalToPixelScanLineDistance(
float distanceMM) const
{
if (distanceMM < 0)
{
itkExceptionMacro("Expected nonnegative spatial distance!");
}
auto input = this->GetInput();
if (input == nullptr)
{
itkExceptionMacro("Tried to translate spatial distance to pixel distance without reference input image!");
}
const float scanStepMM = input->GetSpacing()[m_Direction];
float distanceInPixels = distanceMM / scanStepMM;
return static_cast<unsigned int>(std::round(distanceInPixels));
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
float
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::TransformPixelToPhysicalScanLineDistance(
unsigned int distance) const
{
auto input = this->GetInput();
if (input == nullptr)
{
itkExceptionMacro("Tried to translate spatial distance to pixel distance without reference input image!");
}
const float scanStepMM = input->GetSpacing()[m_Direction];
return scanStepMM * distance;
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
bool
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::ThreadedIsIncluded(InputIndexType index) const
{
auto maskValue = m_ThreadedInputMaskImage->GetPixel(index);
return (m_LabelValue == 0 && maskValue > 0) || (m_LabelValue > 0 && maskValue == m_LabelValue);
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
void
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Image axis representing RF scanline: " << this->GetDirection() << std::endl;
os << indent << "Label value: " << static_cast<unsigned int>(this->GetLabelValue()) << std::endl;
os << indent << "Sampling frequency (MHz): " << this->GetSamplingFrequencyMHz() << std::endl;
os << indent << "Frequency band: [" << this->GetFrequencyBandStartMHz() << "," << this->GetFrequencyBandEndMHz()
<< "]" << std::endl;
os << indent << "Consider negative attenuations: " << (this->GetConsiderNegativeAttenuations() ? "Yes" : "No")
<< std::endl;
os << indent << "Fixed estimation distance: " << this->GetFixedEstimationDepthMM()
<< "mm == " << this->GetFixedEstimationDepth() << "px" << std::endl;
os << indent << "Inclusion padding on scanline: Lower: " << this->GetPadLowerBoundsMM()
<< "mm == " << this->GetPadLowerBounds() << "px ; Upper: " << this->GetPadUpperBoundsMM()
<< "mm == " << this->GetPadUpperBounds() << " px" << std::endl;
}
} // end namespace itk
#endif // itkAttenuationImageFilter_hxx
<commit_msg>ENH: Simplify the code a little<commit_after>/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.
*
*=========================================================================*/
#ifndef itkAttenuationImageFilter_hxx
#define itkAttenuationImageFilter_hxx
#include <algorithm>
#include <cmath>
#include "itk_eigen.h"
#include ITK_EIGEN(Dense)
#include "itkMath.h"
#include "itkImageLinearConstIteratorWithIndex.h"
#include "itkImageSink.h"
#include "itkImageRegionSplitterDirection.h"
#include "itkSimpleDataObjectDecorator.h"
namespace itk
{
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::AttenuationImageFilter()
{
this->SetNumberOfRequiredInputs(1);
this->DynamicMultiThreadingOff();
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
void
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::SetFixedEstimationDepthMM(const float distanceMM)
{
this->SetFixedEstimationDepth(TransformPhysicalToPixelScanLineDistance(distanceMM));
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
float
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::GetFixedEstimationDepthMM() const
{
return this->TransformPixelToPhysicalScanLineDistance(this->GetFixedEstimationDepth());
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
void
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::SetPadUpperBoundsMM(const float distanceMM)
{
this->SetPadUpperBounds(TransformPhysicalToPixelScanLineDistance(distanceMM));
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
float
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::GetPadUpperBoundsMM() const
{
return this->TransformPixelToPhysicalScanLineDistance(this->GetPadUpperBounds());
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
void
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::SetPadLowerBoundsMM(const float distanceMM)
{
this->SetPadLowerBounds(TransformPhysicalToPixelScanLineDistance(distanceMM));
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
float
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::GetPadLowerBoundsMM() const
{
return this->TransformPixelToPhysicalScanLineDistance(this->GetPadLowerBounds());
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
const ImageRegionSplitterBase *
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::GetImageRegionSplitter() const
{
m_RegionSplitter->SetDirection(m_Direction);
return m_RegionSplitter.GetPointer();
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
void
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::VerifyPreconditions() const
{
Superclass::VerifyPreconditions();
if (this->GetInputMaskImage() == nullptr)
{
itkExceptionMacro("Filter requires a mask image for inclusion estimates!");
}
else
{
m_ThreadedInputMaskImage = this->GetInputMaskImage();
}
if (this->GetDirection() >= ImageDimension)
{
itkExceptionMacro("Scan line direction must be a valid image dimension!");
}
if (this->GetSamplingFrequencyMHz() < itk::Math::eps)
{
itkExceptionMacro("RF sampling frequency was not set!");
}
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
void
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::BeforeThreadedGenerateData()
{
Superclass::BeforeThreadedGenerateData();
// Initialize metric image
this->GetOutput()->Allocate();
this->GetOutput()->FillBuffer(0.0f);
// Initialize output mask image
const MaskImageType * inputMaskImage = this->GetInputMaskImage();
m_OutputMaskImage->CopyInformation(inputMaskImage);
m_OutputMaskImage->SetRegions(inputMaskImage->GetLargestPossibleRegion());
m_OutputMaskImage->Allocate();
m_OutputMaskImage->FillBuffer(0.0f);
// Initialize distance weights
unsigned fourSigma = std::max(m_FixedEstimationDepth, 16u); // An arbitrary default.
m_DistanceWeights.resize(fourSigma);
float twoSigmaSquared = fourSigma * fourSigma / 8.0f;
for (unsigned i = 0; i < fourSigma; ++i)
{
m_DistanceWeights[i] = 1.0f - std::exp(i * i / -twoSigmaSquared);
}
// Initialize iVars used in ComputeAttenuation()
float nyquistFrequency = m_SamplingFrequencyMHz / 2;
float numComponents = this->GetInput()->GetNumberOfComponentsPerPixel();
m_FrequencyDelta = nyquistFrequency / numComponents;
m_StartComponent = m_FrequencyBandStartMHz / m_FrequencyDelta;
m_EndComponent = m_FrequencyBandEndMHz / m_FrequencyDelta;
if (m_EndComponent == 0) // If m_FrequencyBandEndMHz is not set
{
m_EndComponent = numComponents - 1; // Use all components
}
m_ConsideredComponents = m_EndComponent - m_StartComponent + 1;
m_ScanStepMM = this->GetInput()->GetSpacing()[m_Direction];
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
void
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::ThreadedGenerateData(
const OutputRegionType & regionForThread,
ThreadIdType)
{
if (regionForThread.GetNumberOfPixels() == 0)
{
return;
}
const InputImageType * input = this->GetInput();
OutputImageType * output = this->GetOutput();
const MaskImageType * inputMaskImage = this->GetInputMaskImage();
ImageLinearConstIteratorWithIndex<TInputImage> it(input, regionForThread);
it.SetDirection(m_Direction);
it.GoToBegin();
unsigned int inclusionLength;
InputIndexType start, end;
thread_local std::vector<float> accumulatedWeight;
accumulatedWeight.resize(regionForThread.GetSize(m_Direction));
// make sure this is not recomputed in the inner loop
const unsigned distanceWeightsSize = m_DistanceWeights.size();
// do the work
while (!it.IsAtEnd())
{
start = it.GetIndex();
inclusionLength = 0;
while (!it.IsAtEndOfLine())
{
// Advance until an inclusion is found
InputIndexType index = it.GetIndex();
bool inside = ThreadedIsIncluded(index);
if (inside)
{
if (inclusionLength == 0)
{
start = it.GetIndex(); // Mark the start
}
++inclusionLength;
}
else if (inclusionLength > 0) // End of a segment
{
inclusionLength = 0; // Prepare for the next one
// Stay at last pixel in the inclusion
end = it.GetIndex();
end[m_Direction] -= 1;
// Adjust for pixel padding
start[m_Direction] += m_PadLowerBounds;
end[m_Direction] -= m_PadUpperBounds;
if (start[m_Direction] != end[m_Direction]) // We need at least a pair of pixels to estimate attenuation
{
// Estimate attenuation for each inclusion pixel
// by weighted average of pair-wise attenuations for all pairs
while (start[m_Direction] <= end[m_Direction])
{
for (IndexValueType k = start[m_Direction] + 1; k <= end[m_Direction]; ++k)
{
unsigned pixelDistance = k - start[m_Direction];
InputIndexType target = start;
target[m_Direction] = k;
float estimatedAttenuation = ComputeAttenuation(target, start);
float weight = 1.0; // Weight for this pair's attenuation. 1 for large distances.
if (pixelDistance < distanceWeightsSize) // If pixels are close, weight is lower than 1.
{
weight = m_DistanceWeights[pixelDistance];
}
// Update this pixel
accumulatedWeight[start[m_Direction]] += weight;
output->SetPixel(start, estimatedAttenuation * weight + output->GetPixel(start));
// Update distant pair
accumulatedWeight[k] += weight;
output->SetPixel(target, estimatedAttenuation * weight + output->GetPixel(target));
} // for k
// Normalize output by accumulated weight
output->SetPixel(start, output->GetPixel(start) / accumulatedWeight[start[m_Direction]]);
accumulatedWeight[start[m_Direction]] = 0.0f; // reset for next next inclusion segment
// Possibly eliminate negative attenuations
if (!m_ConsiderNegativeAttenuations && output->GetPixel(start) < 0.0)
{
output->SetPixel(start, 0.0);
}
// Dynamically generate the output mask with values corresponding to input
m_OutputMaskImage->SetPixel(start, inputMaskImage->GetPixel(start));
++start[m_Direction];
} // while start<=end
} // if start<end
} // else !inside
++it;
}
it.NextLine();
}
};
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
typename AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::OutputPixelType
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::ComputeAttenuation(const InputIndexType & end,
const InputIndexType & start) const
{
// Get RF spectra frequency bins at start and end pixel positions
auto input = this->GetInput();
InputPixelType endSample = input->GetPixel(end);
InputPixelType startSample = input->GetPixel(start);
// Get distance between start and end pixel positions (assume mm units)
const unsigned int pixelDistance = end[m_Direction] - start[m_Direction];
float distanceMM = pixelDistance * m_ScanStepMM;
Eigen::Matrix<float, Eigen::Dynamic, 2> A(m_ConsideredComponents, 2);
Eigen::Matrix<float, Eigen::Dynamic, 1> b(m_ConsideredComponents);
for (unsigned i = 0; i < m_ConsideredComponents; i++)
{
A(i, 0) = 1;
A(i, 1) = (1 + i + m_StartComponent) * m_FrequencyDelta; // x_i = frequency
b(i) = endSample[i + m_StartComponent] / (startSample[i + m_StartComponent] + itk::Math::eps); // y_i = ratio
}
// from https://eigen.tuxfamily.org/dox/group__LeastSquares.html
Eigen::Matrix<float, 1, 2> lineFit = A.householderQr().solve(b);
float frequencySlope = -lineFit(1); // we expect attenuation to increase with frequency
// https://www.electronics-notes.com/articles/basic_concepts/decibel/neper-to-db-conversion.php
// Neper to dB conversion: 1Np = 20 log10e dB, approximately 1Np = 8.6858896 dB
float neper = 20 * itk::Math::log10e;
return 10 * neper * frequencySlope / distanceMM; // 10 converts mm into cm
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
float
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::TransformPhysicalToPixelScanLineDistance(
float distanceMM) const
{
if (distanceMM < 0)
{
itkExceptionMacro("Expected nonnegative spatial distance!");
}
auto input = this->GetInput();
if (input == nullptr)
{
itkExceptionMacro("Tried to translate spatial distance to pixel distance without reference input image!");
}
const float scanStepMM = input->GetSpacing()[m_Direction];
float distanceInPixels = distanceMM / scanStepMM;
return static_cast<unsigned int>(std::round(distanceInPixels));
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
float
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::TransformPixelToPhysicalScanLineDistance(
unsigned int distance) const
{
auto input = this->GetInput();
if (input == nullptr)
{
itkExceptionMacro("Tried to translate spatial distance to pixel distance without reference input image!");
}
const float scanStepMM = input->GetSpacing()[m_Direction];
return scanStepMM * distance;
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
bool
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::ThreadedIsIncluded(InputIndexType index) const
{
auto maskValue = m_ThreadedInputMaskImage->GetPixel(index);
return (m_LabelValue == 0 && maskValue > 0) || (m_LabelValue > 0 && maskValue == m_LabelValue);
}
template <typename TInputImage, typename TOutputImage, typename TMaskImage>
void
AttenuationImageFilter<TInputImage, TOutputImage, TMaskImage>::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Image axis representing RF scanline: " << this->GetDirection() << std::endl;
os << indent << "Label value: " << static_cast<unsigned int>(this->GetLabelValue()) << std::endl;
os << indent << "Sampling frequency (MHz): " << this->GetSamplingFrequencyMHz() << std::endl;
os << indent << "Frequency band: [" << this->GetFrequencyBandStartMHz() << "," << this->GetFrequencyBandEndMHz()
<< "]" << std::endl;
os << indent << "Consider negative attenuations: " << (this->GetConsiderNegativeAttenuations() ? "Yes" : "No")
<< std::endl;
os << indent << "Fixed estimation distance: " << this->GetFixedEstimationDepthMM()
<< "mm == " << this->GetFixedEstimationDepth() << "px" << std::endl;
os << indent << "Inclusion padding on scanline: Lower: " << this->GetPadLowerBoundsMM()
<< "mm == " << this->GetPadLowerBounds() << "px ; Upper: " << this->GetPadUpperBoundsMM()
<< "mm == " << this->GetPadUpperBounds() << " px" << std::endl;
}
} // end namespace itk
#endif // itkAttenuationImageFilter_hxx
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CHAINED_BUFFER_HPP_INCLUDED
#define TORRENT_CHAINED_BUFFER_HPP_INCLUDED
#include <boost/function.hpp>
#if BOOST_VERSION < 103500
#include <asio/buffer.hpp>
#else
#include <boost/asio/buffer.hpp>
#endif
#include <list>
#include <cstring>
namespace libtorrent
{
#if BOOST_VERSION >= 103500
namespace asio = boost::asio;
#endif
struct chained_buffer
{
chained_buffer(): m_bytes(0), m_capacity(0) {}
struct buffer_t
{
boost::function<void(char*)> free; // destructs the buffer
char* buf; // the first byte of the buffer
int size; // the total size of the buffer
char* start; // the first byte to send/receive in the buffer
int used_size; // this is the number of bytes to send/receive
};
bool empty() const { return m_bytes == 0; }
int size() const { return m_bytes; }
int capacity() const { return m_capacity; }
void pop_front(int bytes_to_pop)
{
TORRENT_ASSERT(bytes_to_pop <= m_bytes);
while (bytes_to_pop > 0 && !m_vec.empty())
{
buffer_t& b = m_vec.front();
if (b.used_size > bytes_to_pop)
{
b.start += bytes_to_pop;
b.used_size -= bytes_to_pop;
m_bytes -= bytes_to_pop;
TORRENT_ASSERT(m_bytes <= m_capacity);
TORRENT_ASSERT(m_bytes >= 0);
TORRENT_ASSERT(m_capacity >= 0);
break;
}
b.free(b.buf);
m_bytes -= b.used_size;
m_capacity -= b.size;
bytes_to_pop -= b.used_size;
TORRENT_ASSERT(m_bytes >= 0);
TORRENT_ASSERT(m_capacity >= 0);
TORRENT_ASSERT(m_bytes <= m_capacity);
m_vec.pop_front();
}
}
template <class D>
void append_buffer(char* buffer, int size, int used_size, D const& destructor)
{
TORRENT_ASSERT(size >= used_size);
buffer_t b;
b.buf = buffer;
b.size = size;
b.start = buffer;
b.used_size = used_size;
b.free = destructor;
m_vec.push_back(b);
m_bytes += used_size;
m_capacity += size;
TORRENT_ASSERT(m_bytes <= m_capacity);
}
// returns the number of bytes available at the
// end of the last chained buffer.
int space_in_last_buffer()
{
if (m_vec.empty()) return 0;
buffer_t& b = m_vec.back();
return b.size - b.used_size - (b.start - b.buf);
}
// tries to copy the given buffer to the end of the
// last chained buffer. If there's not enough room
// it returns false
bool append(char const* buf, int size)
{
char* insert = allocate_appendix(size);
if (insert == 0) return false;
std::memcpy(insert, buf, size);
return true;
}
// tries to allocate memory from the end
// of the last buffer. If there isn't
// enough room, returns 0
char* allocate_appendix(int size)
{
if (m_vec.empty()) return 0;
buffer_t& b = m_vec.back();
char* insert = b.start + b.used_size;
if (insert + size > b.buf + b.size) return 0;
b.used_size += size;
m_bytes += size;
TORRENT_ASSERT(m_bytes <= m_capacity);
return insert;
}
std::list<asio::const_buffer> const& build_iovec(int to_send)
{
m_tmp_vec.clear();
for (std::list<buffer_t>::iterator i = m_vec.begin()
, end(m_vec.end()); to_send > 0 && i != end; ++i)
{
if (i->used_size > to_send)
{
TORRENT_ASSERT(to_send > 0);
m_tmp_vec.push_back(asio::const_buffer(i->start, to_send));
break;
}
TORRENT_ASSERT(i->used_size > 0);
m_tmp_vec.push_back(asio::const_buffer(i->start, i->used_size));
to_send -= i->used_size;
}
return m_tmp_vec;
}
~chained_buffer()
{
for (std::list<buffer_t>::iterator i = m_vec.begin()
, end(m_vec.end()); i != end; ++i)
{
i->free(i->buf);
}
}
private:
// this is the list of all the buffers we want to
// send
std::list<buffer_t> m_vec;
// this is the number of bytes in the send buf.
// this will always be equal to the sum of the
// size of all buffers in vec
int m_bytes;
// the total size of all buffers in the chain
// including unused space
int m_capacity;
// this is the vector of buffers used when
// invoking the async write call
std::list<asio::const_buffer> m_tmp_vec;
};
}
#endif
<commit_msg>fixed boost version check. Fixes #337<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CHAINED_BUFFER_HPP_INCLUDED
#define TORRENT_CHAINED_BUFFER_HPP_INCLUDED
#include <boost/function.hpp>
#include <boost/version.hpp>
#if BOOST_VERSION < 103500
#include <asio/buffer.hpp>
#else
#include <boost/asio/buffer.hpp>
#endif
#include <list>
#include <cstring>
namespace libtorrent
{
#if BOOST_VERSION >= 103500
namespace asio = boost::asio;
#endif
struct chained_buffer
{
chained_buffer(): m_bytes(0), m_capacity(0) {}
struct buffer_t
{
boost::function<void(char*)> free; // destructs the buffer
char* buf; // the first byte of the buffer
int size; // the total size of the buffer
char* start; // the first byte to send/receive in the buffer
int used_size; // this is the number of bytes to send/receive
};
bool empty() const { return m_bytes == 0; }
int size() const { return m_bytes; }
int capacity() const { return m_capacity; }
void pop_front(int bytes_to_pop)
{
TORRENT_ASSERT(bytes_to_pop <= m_bytes);
while (bytes_to_pop > 0 && !m_vec.empty())
{
buffer_t& b = m_vec.front();
if (b.used_size > bytes_to_pop)
{
b.start += bytes_to_pop;
b.used_size -= bytes_to_pop;
m_bytes -= bytes_to_pop;
TORRENT_ASSERT(m_bytes <= m_capacity);
TORRENT_ASSERT(m_bytes >= 0);
TORRENT_ASSERT(m_capacity >= 0);
break;
}
b.free(b.buf);
m_bytes -= b.used_size;
m_capacity -= b.size;
bytes_to_pop -= b.used_size;
TORRENT_ASSERT(m_bytes >= 0);
TORRENT_ASSERT(m_capacity >= 0);
TORRENT_ASSERT(m_bytes <= m_capacity);
m_vec.pop_front();
}
}
template <class D>
void append_buffer(char* buffer, int size, int used_size, D const& destructor)
{
TORRENT_ASSERT(size >= used_size);
buffer_t b;
b.buf = buffer;
b.size = size;
b.start = buffer;
b.used_size = used_size;
b.free = destructor;
m_vec.push_back(b);
m_bytes += used_size;
m_capacity += size;
TORRENT_ASSERT(m_bytes <= m_capacity);
}
// returns the number of bytes available at the
// end of the last chained buffer.
int space_in_last_buffer()
{
if (m_vec.empty()) return 0;
buffer_t& b = m_vec.back();
return b.size - b.used_size - (b.start - b.buf);
}
// tries to copy the given buffer to the end of the
// last chained buffer. If there's not enough room
// it returns false
bool append(char const* buf, int size)
{
char* insert = allocate_appendix(size);
if (insert == 0) return false;
std::memcpy(insert, buf, size);
return true;
}
// tries to allocate memory from the end
// of the last buffer. If there isn't
// enough room, returns 0
char* allocate_appendix(int size)
{
if (m_vec.empty()) return 0;
buffer_t& b = m_vec.back();
char* insert = b.start + b.used_size;
if (insert + size > b.buf + b.size) return 0;
b.used_size += size;
m_bytes += size;
TORRENT_ASSERT(m_bytes <= m_capacity);
return insert;
}
std::list<asio::const_buffer> const& build_iovec(int to_send)
{
m_tmp_vec.clear();
for (std::list<buffer_t>::iterator i = m_vec.begin()
, end(m_vec.end()); to_send > 0 && i != end; ++i)
{
if (i->used_size > to_send)
{
TORRENT_ASSERT(to_send > 0);
m_tmp_vec.push_back(asio::const_buffer(i->start, to_send));
break;
}
TORRENT_ASSERT(i->used_size > 0);
m_tmp_vec.push_back(asio::const_buffer(i->start, i->used_size));
to_send -= i->used_size;
}
return m_tmp_vec;
}
~chained_buffer()
{
for (std::list<buffer_t>::iterator i = m_vec.begin()
, end(m_vec.end()); i != end; ++i)
{
i->free(i->buf);
}
}
private:
// this is the list of all the buffers we want to
// send
std::list<buffer_t> m_vec;
// this is the number of bytes in the send buf.
// this will always be equal to the sum of the
// size of all buffers in vec
int m_bytes;
// the total size of all buffers in the chain
// including unused space
int m_capacity;
// this is the vector of buffers used when
// invoking the async write call
std::list<asio::const_buffer> m_tmp_vec;
};
}
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2009 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef MAPNIK_EXPRESSIONS_GRAMMAR_HPP
#define MAPNIK_EXPRESSIONS_GRAMMAR_HPP
// mapnik
#include <mapnik/value.hpp>
#include <mapnik/expression_node.hpp>
// boost
#include <boost/variant.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/concept_check.hpp>
//spirit2
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_action.hpp>
//fusion
#include <boost/fusion/include/adapt_struct.hpp>
//phoenix
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/home/phoenix/object/construct.hpp>
namespace mapnik
{
namespace qi = boost::spirit::qi;
namespace standard_wide = boost::spirit::standard_wide;
using standard_wide::space_type;
struct unicode_impl
{
template <typename T>
struct result
{
typedef UnicodeString type;
};
explicit unicode_impl(mapnik::transcoder const& tr)
: tr_(tr) {}
UnicodeString operator()(std::string const& str) const
{
return tr_.transcode(str.c_str());
}
mapnik::transcoder const& tr_;
};
struct regex_match_impl
{
template <typename T0, typename T1>
struct result
{
typedef expr_node type;
};
explicit regex_match_impl(mapnik::transcoder const& tr)
: tr_(tr) {}
template <typename T0,typename T1>
expr_node operator() (T0 & node, T1 const& pattern) const
{
return regex_match_node(node,tr_.transcode(pattern.c_str()));
}
mapnik::transcoder const& tr_;
};
struct regex_replace_impl
{
template <typename T0, typename T1, typename T2>
struct result
{
typedef expr_node type;
};
explicit regex_replace_impl(mapnik::transcoder const& tr)
: tr_(tr) {}
template <typename T0,typename T1,typename T2>
expr_node operator() (T0 & node, T1 const& pattern, T2 const& format) const
{
return regex_replace_node(node,tr_.transcode(pattern.c_str()),tr_.transcode(format.c_str()));
}
mapnik::transcoder const& tr_;
};
template <typename Iterator>
struct expression_grammar : qi::grammar<Iterator, expr_node(), space_type>
{
typedef qi::rule<Iterator, expr_node(), space_type> rule_type;
explicit expression_grammar(mapnik::transcoder const& tr)
: expression_grammar::base_type(expr),
unicode_(unicode_impl(tr)),
regex_match_(regex_match_impl(tr)),
regex_replace_(regex_replace_impl(tr))
{
using boost::phoenix::construct;
using qi::_1;
using qi::_a;
using qi::_b;
using qi::_r1;
using qi::lexeme;
using qi::_val;
using qi::lit;
using qi::int_;
using qi::double_;
using standard_wide::char_;
expr = logical_expr.alias();
logical_expr = not_expr [_val = _1]
>>
*( ( ( lit("and") | lit("&&")) >> not_expr [_val && _1] )
| (( lit("or") | lit("||")) >> not_expr [_val || _1])
)
;
not_expr =
cond_expr [_val = _1 ]
| ((lit("not") | lit('!')) >> cond_expr [ _val = !_1 ])
;
cond_expr = equality_expr [_val = _1] | additive_expr [_val = _1]
;
equality_expr =
relational_expr [_val = _1]
>> *( ( (lit("=") | lit("eq")) >> relational_expr [_val == _1])
| (( lit("!=") | lit("<>") | lit("neq") ) >> relational_expr [_val != _1])
)
;
regex_match_expr = lit(".match")
>> lit('(')
>> lit('\'')
>> ustring [_val = _1]
>> lit('\'')
>> lit(')')
;
regex_replace_expr =
lit(".replace")
>> lit('(')
>> lit('\'')
>> ustring [_a = _1]
>> lit('\'') >> lit(',')
>> lit('\'')
>> ustring [_b = _1]
>> lit('\'')
>> lit(')') [_val = regex_replace_(_r1,_a,_b)]
;
relational_expr = additive_expr[_val = _1]
>>
*( ( (lit("<=") | lit("le") ) >> additive_expr [ _val <= _1 ])
| ( (lit('<') | lit("lt") ) >> additive_expr [ _val < _1 ])
| ( (lit(">=") | lit("ge") ) >> additive_expr [ _val >= _1 ])
| ( (lit('>') | lit("gt") ) >> additive_expr [ _val > _1 ])
)
;
additive_expr = multiplicative_expr [_val = _1]
>> * ( '+' >> multiplicative_expr[_val += _1]
| '-' >> multiplicative_expr[_val -= _1]
)
;
multiplicative_expr = primary_expr [_val = _1]
>> *( '*' >> primary_expr [_val *= _1]
| '/' >> primary_expr [_val /= _1]
| '%' >> primary_expr [_val %= _1]
| regex_match_expr[_val = regex_match_(_val, _1)]
| regex_replace_expr(_val) [_val = _1]
)
;
primary_expr = strict_double [_val = _1]
| int_ [_val = _1]
| lit("true") [_val = true]
| lit("false") [_val = false]
| '\'' >> ustring [_val = unicode_(_1) ] >> '\''
| '[' >> attr [_val = construct<attribute>( _1 ) ] >> ']'
| '(' >> expr [_val = _1 ] >> ')'
;
attr %= +(char_ - ']');
ustring %= lexeme[*(char_-'\'')];
}
qi::real_parser<double, qi::strict_real_policies<double> > strict_double;
boost::phoenix::function<unicode_impl> unicode_;
boost::phoenix::function<regex_match_impl> regex_match_;
boost::phoenix::function<regex_replace_impl> regex_replace_;
//
rule_type expr;
rule_type equality_expr;
rule_type cond_expr;
rule_type relational_expr;
rule_type logical_expr;
rule_type additive_expr;
rule_type multiplicative_expr;
rule_type not_expr;
rule_type primary_expr;
qi::rule<Iterator, std::string() > regex_match_expr;
qi::rule<Iterator, expr_node(expr_node), qi::locals<std::string,std::string>, space_type> regex_replace_expr;
qi::rule<Iterator, std::string() , space_type> attr;
qi::rule<Iterator, std::string() > ustring;
};
} // namespace
#endif // MAPNIK_EXPRESSIONS_GRAMMAR_HPP
<commit_msg>+ use no_skip[] instead of lexeme[] directive to avoid pre-skipping<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2009 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef MAPNIK_EXPRESSIONS_GRAMMAR_HPP
#define MAPNIK_EXPRESSIONS_GRAMMAR_HPP
// mapnik
#include <mapnik/value.hpp>
#include <mapnik/expression_node.hpp>
// boost
#include <boost/variant.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/concept_check.hpp>
//spirit2
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_action.hpp>
//fusion
#include <boost/fusion/include/adapt_struct.hpp>
//phoenix
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/home/phoenix/object/construct.hpp>
namespace mapnik
{
namespace qi = boost::spirit::qi;
namespace standard_wide = boost::spirit::standard_wide;
using standard_wide::space_type;
struct unicode_impl
{
template <typename T>
struct result
{
typedef UnicodeString type;
};
explicit unicode_impl(mapnik::transcoder const& tr)
: tr_(tr) {}
UnicodeString operator()(std::string const& str) const
{
return tr_.transcode(str.c_str());
}
mapnik::transcoder const& tr_;
};
struct regex_match_impl
{
template <typename T0, typename T1>
struct result
{
typedef expr_node type;
};
explicit regex_match_impl(mapnik::transcoder const& tr)
: tr_(tr) {}
template <typename T0,typename T1>
expr_node operator() (T0 & node, T1 const& pattern) const
{
return regex_match_node(node,tr_.transcode(pattern.c_str()));
}
mapnik::transcoder const& tr_;
};
struct regex_replace_impl
{
template <typename T0, typename T1, typename T2>
struct result
{
typedef expr_node type;
};
explicit regex_replace_impl(mapnik::transcoder const& tr)
: tr_(tr) {}
template <typename T0,typename T1,typename T2>
expr_node operator() (T0 & node, T1 const& pattern, T2 const& format) const
{
return regex_replace_node(node,tr_.transcode(pattern.c_str()),tr_.transcode(format.c_str()));
}
mapnik::transcoder const& tr_;
};
template <typename Iterator>
struct expression_grammar : qi::grammar<Iterator, expr_node(), space_type>
{
typedef qi::rule<Iterator, expr_node(), space_type> rule_type;
explicit expression_grammar(mapnik::transcoder const& tr)
: expression_grammar::base_type(expr),
unicode_(unicode_impl(tr)),
regex_match_(regex_match_impl(tr)),
regex_replace_(regex_replace_impl(tr))
{
using boost::phoenix::construct;
using qi::_1;
using qi::_a;
using qi::_b;
using qi::_r1;
using qi::no_skip;
using qi::_val;
using qi::lit;
using qi::int_;
using qi::double_;
using standard_wide::char_;
expr = logical_expr.alias();
logical_expr = not_expr [_val = _1]
>>
*( ( ( lit("and") | lit("&&")) >> not_expr [_val && _1] )
| (( lit("or") | lit("||")) >> not_expr [_val || _1])
)
;
not_expr =
cond_expr [_val = _1 ]
| ((lit("not") | lit('!')) >> cond_expr [ _val = !_1 ])
;
cond_expr = equality_expr [_val = _1] | additive_expr [_val = _1]
;
equality_expr =
relational_expr [_val = _1]
>> *( ( (lit("=") | lit("eq")) >> relational_expr [_val == _1])
| (( lit("!=") | lit("<>") | lit("neq") ) >> relational_expr [_val != _1])
)
;
regex_match_expr = lit(".match")
>> lit('(')
>> lit('\'')
>> ustring [_val = _1]
>> lit('\'')
>> lit(')')
;
regex_replace_expr =
lit(".replace")
>> lit('(')
>> lit('\'')
>> ustring [_a = _1]
>> lit('\'') >> lit(',')
>> lit('\'')
>> ustring [_b = _1]
>> lit('\'')
>> lit(')') [_val = regex_replace_(_r1,_a,_b)]
;
relational_expr = additive_expr[_val = _1]
>>
*( ( (lit("<=") | lit("le") ) >> additive_expr [ _val <= _1 ])
| ( (lit('<') | lit("lt") ) >> additive_expr [ _val < _1 ])
| ( (lit(">=") | lit("ge") ) >> additive_expr [ _val >= _1 ])
| ( (lit('>') | lit("gt") ) >> additive_expr [ _val > _1 ])
)
;
additive_expr = multiplicative_expr [_val = _1]
>> * ( '+' >> multiplicative_expr[_val += _1]
| '-' >> multiplicative_expr[_val -= _1]
)
;
multiplicative_expr = primary_expr [_val = _1]
>> *( '*' >> primary_expr [_val *= _1]
| '/' >> primary_expr [_val /= _1]
| '%' >> primary_expr [_val %= _1]
| regex_match_expr[_val = regex_match_(_val, _1)]
| regex_replace_expr(_val) [_val = _1]
)
;
primary_expr = strict_double [_val = _1]
| int_ [_val = _1]
| lit("true") [_val = true]
| lit("false") [_val = false]
| ustring [_val = unicode_(_1) ]
| attr [_val = construct<attribute>( _1 ) ]
| '(' >> expr [_val = _1 ] >> ')'
;
attr %= '[' >> +(char_ - ']') >> ']';
ustring %= '\'' >> no_skip[+~char_('\'')] >> '\'';
}
qi::real_parser<double, qi::strict_real_policies<double> > strict_double;
boost::phoenix::function<unicode_impl> unicode_;
boost::phoenix::function<regex_match_impl> regex_match_;
boost::phoenix::function<regex_replace_impl> regex_replace_;
//
rule_type expr;
rule_type equality_expr;
rule_type cond_expr;
rule_type relational_expr;
rule_type logical_expr;
rule_type additive_expr;
rule_type multiplicative_expr;
rule_type not_expr;
rule_type primary_expr;
qi::rule<Iterator, std::string() > regex_match_expr;
qi::rule<Iterator, expr_node(expr_node), qi::locals<std::string,std::string>, space_type> regex_replace_expr;
qi::rule<Iterator, std::string() , space_type> attr;
qi::rule<Iterator, std::string() > ustring;
};
} // namespace
#endif // MAPNIK_EXPRESSIONS_GRAMMAR_HPP
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2009 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef MAPNIK_EXPRESSIONS_GRAMMAR_HPP
#define MAPNIK_EXPRESSIONS_GRAMMAR_HPP
// mapnik
#include <mapnik/value.hpp>
#include <mapnik/expression_node.hpp>
// boost
#include <boost/version.hpp>
#include <boost/variant.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/concept_check.hpp>
//spirit2
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_action.hpp>
//fusion
#include <boost/fusion/include/adapt_struct.hpp>
//phoenix
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/home/phoenix/object/construct.hpp>
namespace mapnik
{
namespace qi = boost::spirit::qi;
namespace standard_wide = boost::spirit::standard_wide;
using standard_wide::space_type;
struct unicode_impl
{
template <typename T>
struct result
{
typedef UnicodeString type;
};
explicit unicode_impl(mapnik::transcoder const& tr)
: tr_(tr) {}
UnicodeString operator()(std::string const& str) const
{
return tr_.transcode(str.c_str());
}
mapnik::transcoder const& tr_;
};
struct regex_match_impl
{
template <typename T0, typename T1>
struct result
{
typedef expr_node type;
};
explicit regex_match_impl(mapnik::transcoder const& tr)
: tr_(tr) {}
template <typename T0,typename T1>
expr_node operator() (T0 & node, T1 const& pattern) const
{
#if defined(BOOST_REGEX_HAS_ICU)
return regex_match_node(node,tr_.transcode(pattern.c_str()));
#else
return regex_match_node(node,pattern);
#endif
}
mapnik::transcoder const& tr_;
};
struct regex_replace_impl
{
template <typename T0, typename T1, typename T2>
struct result
{
typedef expr_node type;
};
explicit regex_replace_impl(mapnik::transcoder const& tr)
: tr_(tr) {}
template <typename T0,typename T1,typename T2>
expr_node operator() (T0 & node, T1 const& pattern, T2 const& format) const
{
#if defined(BOOST_REGEX_HAS_ICU)
return regex_replace_node(node,tr_.transcode(pattern.c_str()),tr_.transcode(format.c_str()));
#else
return regex_replace_node(node,pattern,format);
#endif
}
mapnik::transcoder const& tr_;
};
template <typename Iterator>
struct expression_grammar : qi::grammar<Iterator, expr_node(), space_type>
{
typedef qi::rule<Iterator, expr_node(), space_type> rule_type;
explicit expression_grammar(mapnik::transcoder const& tr)
: expression_grammar::base_type(expr),
unicode_(unicode_impl(tr)),
regex_match_(regex_match_impl(tr)),
regex_replace_(regex_replace_impl(tr))
{
using boost::phoenix::construct;
using qi::_1;
using qi::_a;
using qi::_b;
using qi::_r1;
#if BOOST_VERSION > 104200
using qi::no_skip;
#else
using qi::lexeme;
#endif
using qi::_val;
using qi::lit;
using qi::int_;
using qi::double_;
using standard_wide::char_;
expr = logical_expr.alias();
logical_expr = not_expr [_val = _1]
>>
*( ( ( lit("and") | lit("&&")) >> not_expr [_val && _1] )
| (( lit("or") | lit("||")) >> not_expr [_val || _1])
)
;
not_expr =
cond_expr [_val = _1 ]
| ((lit("not") | lit('!')) >> cond_expr [ _val = !_1 ])
;
cond_expr = equality_expr [_val = _1] | additive_expr [_val = _1]
;
equality_expr =
relational_expr [_val = _1]
>> *( ( (lit("=") | lit("eq") | lit("is")) >> relational_expr [_val == _1])
| (( lit("!=") | lit("<>") | lit("neq") ) >> relational_expr [_val != _1])
)
;
regex_match_expr = lit(".match")
>> lit('(')
>> ustring [_val = _1]
>> lit(')')
;
regex_replace_expr =
lit(".replace")
>> lit('(')
>> ustring [_a = _1]
>> lit(',')
>> ustring [_b = _1]
>> lit(')') [_val = regex_replace_(_r1,_a,_b)]
;
relational_expr = additive_expr[_val = _1]
>>
*( ( (lit("<=") | lit("le") ) >> additive_expr [ _val <= _1 ])
| ( (lit('<') | lit("lt") ) >> additive_expr [ _val < _1 ])
| ( (lit(">=") | lit("ge") ) >> additive_expr [ _val >= _1 ])
| ( (lit('>') | lit("gt") ) >> additive_expr [ _val > _1 ])
)
;
additive_expr = multiplicative_expr [_val = _1]
>> * ( '+' >> multiplicative_expr[_val += _1]
| '-' >> multiplicative_expr[_val -= _1]
)
;
multiplicative_expr = primary_expr [_val = _1]
>> *( '*' >> primary_expr [_val *= _1]
| '/' >> primary_expr [_val /= _1]
| '%' >> primary_expr [_val %= _1]
| regex_match_expr[_val = regex_match_(_val, _1)]
| regex_replace_expr(_val) [_val = _1]
)
;
primary_expr = strict_double [_val = _1]
| int_ [_val = _1]
| lit("true") [_val = true]
| lit("false") [_val = false]
| lit("null") [_val = value_null() ]
| ustring [_val = unicode_(_1) ]
| attr [_val = construct<attribute>( _1 ) ]
| '(' >> expr [_val = _1 ] >> ')'
;
attr %= '[' >> +(char_ - ']') >> ']';
#if BOOST_VERSION > 104200
ustring %= '\'' >> no_skip[*~char_('\'')] >> '\'';
#else
ustring %= '\'' >> lexeme[*(char_-'\'')] >> '\'';
#endif
}
qi::real_parser<double, qi::strict_real_policies<double> > strict_double;
boost::phoenix::function<unicode_impl> unicode_;
boost::phoenix::function<regex_match_impl> regex_match_;
boost::phoenix::function<regex_replace_impl> regex_replace_;
//
rule_type expr;
rule_type equality_expr;
rule_type cond_expr;
rule_type relational_expr;
rule_type logical_expr;
rule_type additive_expr;
rule_type multiplicative_expr;
rule_type not_expr;
rule_type primary_expr;
qi::rule<Iterator, std::string() > regex_match_expr;
qi::rule<Iterator, expr_node(expr_node), qi::locals<std::string,std::string>, space_type> regex_replace_expr;
qi::rule<Iterator, std::string() , space_type> attr;
qi::rule<Iterator, std::string() > ustring;
};
} // namespace
#endif // MAPNIK_EXPRESSIONS_GRAMMAR_HPP
<commit_msg>qualify attribute -> mapnik::attribute (vc10)<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2009 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef MAPNIK_EXPRESSIONS_GRAMMAR_HPP
#define MAPNIK_EXPRESSIONS_GRAMMAR_HPP
// mapnik
#include <mapnik/value.hpp>
#include <mapnik/expression_node.hpp>
// boost
#include <boost/version.hpp>
#include <boost/variant.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/concept_check.hpp>
//spirit2
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_action.hpp>
//fusion
#include <boost/fusion/include/adapt_struct.hpp>
//phoenix
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/home/phoenix/object/construct.hpp>
namespace mapnik
{
using namespace boost;
namespace qi = boost::spirit::qi;
namespace standard_wide = boost::spirit::standard_wide;
using standard_wide::space_type;
struct unicode_impl
{
template <typename T>
struct result
{
typedef UnicodeString type;
};
explicit unicode_impl(mapnik::transcoder const& tr)
: tr_(tr) {}
UnicodeString operator()(std::string const& str) const
{
return tr_.transcode(str.c_str());
}
mapnik::transcoder const& tr_;
};
struct regex_match_impl
{
template <typename T0, typename T1>
struct result
{
typedef expr_node type;
};
explicit regex_match_impl(mapnik::transcoder const& tr)
: tr_(tr) {}
template <typename T0,typename T1>
expr_node operator() (T0 & node, T1 const& pattern) const
{
#if defined(BOOST_REGEX_HAS_ICU)
return regex_match_node(node,tr_.transcode(pattern.c_str()));
#else
return regex_match_node(node,pattern);
#endif
}
mapnik::transcoder const& tr_;
};
struct regex_replace_impl
{
template <typename T0, typename T1, typename T2>
struct result
{
typedef expr_node type;
};
explicit regex_replace_impl(mapnik::transcoder const& tr)
: tr_(tr) {}
template <typename T0,typename T1,typename T2>
expr_node operator() (T0 & node, T1 const& pattern, T2 const& format) const
{
#if defined(BOOST_REGEX_HAS_ICU)
return regex_replace_node(node,tr_.transcode(pattern.c_str()),tr_.transcode(format.c_str()));
#else
return regex_replace_node(node,pattern,format);
#endif
}
mapnik::transcoder const& tr_;
};
template <typename Iterator>
struct expression_grammar : qi::grammar<Iterator, expr_node(), space_type>
{
typedef qi::rule<Iterator, expr_node(), space_type> rule_type;
explicit expression_grammar(mapnik::transcoder const& tr)
: expression_grammar::base_type(expr),
unicode_(unicode_impl(tr)),
regex_match_(regex_match_impl(tr)),
regex_replace_(regex_replace_impl(tr))
{
using boost::phoenix::construct;
using qi::_1;
using qi::_a;
using qi::_b;
using qi::_r1;
#if BOOST_VERSION > 104200
using qi::no_skip;
#else
using qi::lexeme;
#endif
using qi::_val;
using qi::lit;
using qi::int_;
using qi::double_;
using standard_wide::char_;
expr = logical_expr.alias();
logical_expr = not_expr [_val = _1]
>>
*( ( ( lit("and") | lit("&&")) >> not_expr [_val && _1] )
| (( lit("or") | lit("||")) >> not_expr [_val || _1])
)
;
not_expr =
cond_expr [_val = _1 ]
| ((lit("not") | lit('!')) >> cond_expr [ _val = !_1 ])
;
cond_expr = equality_expr [_val = _1] | additive_expr [_val = _1]
;
equality_expr =
relational_expr [_val = _1]
>> *( ( (lit("=") | lit("eq") | lit("is")) >> relational_expr [_val == _1])
| (( lit("!=") | lit("<>") | lit("neq") ) >> relational_expr [_val != _1])
)
;
regex_match_expr = lit(".match")
>> lit('(')
>> ustring [_val = _1]
>> lit(')')
;
regex_replace_expr =
lit(".replace")
>> lit('(')
>> ustring [_a = _1]
>> lit(',')
>> ustring [_b = _1]
>> lit(')') [_val = regex_replace_(_r1,_a,_b)]
;
relational_expr = additive_expr[_val = _1]
>>
*( ( (lit("<=") | lit("le") ) >> additive_expr [ _val <= _1 ])
| ( (lit('<') | lit("lt") ) >> additive_expr [ _val < _1 ])
| ( (lit(">=") | lit("ge") ) >> additive_expr [ _val >= _1 ])
| ( (lit('>') | lit("gt") ) >> additive_expr [ _val > _1 ])
)
;
additive_expr = multiplicative_expr [_val = _1]
>> * ( '+' >> multiplicative_expr[_val += _1]
| '-' >> multiplicative_expr[_val -= _1]
)
;
multiplicative_expr = primary_expr [_val = _1]
>> *( '*' >> primary_expr [_val *= _1]
| '/' >> primary_expr [_val /= _1]
| '%' >> primary_expr [_val %= _1]
| regex_match_expr[_val = regex_match_(_val, _1)]
| regex_replace_expr(_val) [_val = _1]
)
;
primary_expr = strict_double [_val = _1]
| int_ [_val = _1]
| lit("true") [_val = true]
| lit("false") [_val = false]
| lit("null") [_val = value_null() ]
| ustring [_val = unicode_(_1) ]
| attr [_val = construct<mapnik::attribute>( _1 ) ]
| '(' >> expr [_val = _1 ] >> ')'
;
attr %= '[' >> +(char_ - ']') >> ']';
#if BOOST_VERSION > 104200
ustring %= '\'' >> no_skip[*~char_('\'')] >> '\'';
#else
ustring %= '\'' >> lexeme[*(char_-'\'')] >> '\'';
#endif
}
qi::real_parser<double, qi::strict_real_policies<double> > strict_double;
boost::phoenix::function<unicode_impl> unicode_;
boost::phoenix::function<regex_match_impl> regex_match_;
boost::phoenix::function<regex_replace_impl> regex_replace_;
//
rule_type expr;
rule_type equality_expr;
rule_type cond_expr;
rule_type relational_expr;
rule_type logical_expr;
rule_type additive_expr;
rule_type multiplicative_expr;
rule_type not_expr;
rule_type primary_expr;
qi::rule<Iterator, std::string() > regex_match_expr;
qi::rule<Iterator, expr_node(expr_node), qi::locals<std::string,std::string>, space_type> regex_replace_expr;
qi::rule<Iterator, std::string() , space_type> attr;
qi::rule<Iterator, std::string() > ustring;
};
} // namespace
#endif // MAPNIK_EXPRESSIONS_GRAMMAR_HPP
<|endoftext|> |
<commit_before>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#ifndef NOMLIB_AUDIO_ISOUND_SOURCE_HPP
#define NOMLIB_AUDIO_ISOUND_SOURCE_HPP
#include "nomlib/config.hpp"
namespace nom {
// Forward declarations
class ISoundBuffer;
/// Sound source is one of the three states: stopped, paused or playing
enum SoundStatus
{
Stopped = 0,
Paused = 1,
Playing = 2
};
class ISoundSource
{
public:
virtual ~ISoundSource( void )
{
NOM_LOG_TRACE_PRIO( NOM_LOG_CATEGORY_TRACE_AUDIO, nom::LogPriority::NOM_LOG_PRIORITY_VERBOSE );
}
virtual float getVolume ( void ) const = 0;
virtual float getMinVolume ( void ) const = 0;
virtual float getMaxVolume ( void ) const = 0;
virtual float getPitch ( void ) const = 0;
virtual bool getLooping ( void ) const = 0;
virtual Point3f getPosition ( void ) const = 0;
virtual Point3f getVelocity ( void ) const = 0;
virtual bool getPositionRelativeToListener ( void ) const = 0;
virtual float getMinDistance ( void ) const = 0;
virtual float getAttenuation ( void ) const = 0;
virtual int32 getBufferID ( void ) const = 0;
virtual float getPlayPosition ( void ) const = 0;
virtual SoundStatus getStatus ( void ) const = 0;
virtual void setVolume ( float gain ) = 0;
virtual void setMinVolume ( float gain ) = 0;
virtual void setMaxVolume ( float gain ) = 0;
virtual void setPitch ( float pitch ) = 0;
virtual void setLooping ( bool loops ) = 0;
virtual void setPosition ( float x, float y, float z ) = 0;
virtual void setPosition ( const Point3f& position ) = 0;
virtual void setVelocity ( float x, float y, float z ) = 0;
virtual void setVelocity ( const Point3f& velocity ) = 0;
virtual void setPositionRelativeToListener ( bool position ) = 0;
virtual void setMinDistance ( float distance ) = 0;
virtual void setAttenuation ( float attenuation ) = 0;
virtual void setPlayPosition ( float seconds ) = 0;
virtual void setBuffer( const ISoundBuffer& copy ) = 0;
virtual void Play( void ) = 0;
virtual void Stop( void ) = 0;
virtual void Pause( void ) = 0;
virtual void togglePause( void ) = 0;
virtual void fadeOut( float seconds ) = 0;
};
} // namespace nom
#endif // include guard defined
<commit_msg>ISoundSource.hpp: Add missing Point3.hpp<commit_after>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#ifndef NOMLIB_AUDIO_ISOUND_SOURCE_HPP
#define NOMLIB_AUDIO_ISOUND_SOURCE_HPP
#include "nomlib/config.hpp"
#include "nomlib/math/Point3.hpp"
namespace nom {
// Forward declarations
class ISoundBuffer;
/// Sound source is one of the three states: stopped, paused or playing
enum SoundStatus
{
Stopped = 0,
Paused = 1,
Playing = 2
};
class ISoundSource
{
public:
virtual ~ISoundSource( void )
{
NOM_LOG_TRACE_PRIO( NOM_LOG_CATEGORY_TRACE_AUDIO, nom::LogPriority::NOM_LOG_PRIORITY_VERBOSE );
}
virtual float getVolume ( void ) const = 0;
virtual float getMinVolume ( void ) const = 0;
virtual float getMaxVolume ( void ) const = 0;
virtual float getPitch ( void ) const = 0;
virtual bool getLooping ( void ) const = 0;
virtual Point3f getPosition ( void ) const = 0;
virtual Point3f getVelocity ( void ) const = 0;
virtual bool getPositionRelativeToListener ( void ) const = 0;
virtual float getMinDistance ( void ) const = 0;
virtual float getAttenuation ( void ) const = 0;
virtual int32 getBufferID ( void ) const = 0;
virtual float getPlayPosition ( void ) const = 0;
virtual SoundStatus getStatus ( void ) const = 0;
virtual void setVolume ( float gain ) = 0;
virtual void setMinVolume ( float gain ) = 0;
virtual void setMaxVolume ( float gain ) = 0;
virtual void setPitch ( float pitch ) = 0;
virtual void setLooping ( bool loops ) = 0;
virtual void setPosition ( float x, float y, float z ) = 0;
virtual void setPosition ( const Point3f& position ) = 0;
virtual void setVelocity ( float x, float y, float z ) = 0;
virtual void setVelocity ( const Point3f& velocity ) = 0;
virtual void setPositionRelativeToListener ( bool position ) = 0;
virtual void setMinDistance ( float distance ) = 0;
virtual void setAttenuation ( float attenuation ) = 0;
virtual void setPlayPosition ( float seconds ) = 0;
virtual void setBuffer( const ISoundBuffer& copy ) = 0;
virtual void Play( void ) = 0;
virtual void Stop( void ) = 0;
virtual void Pause( void ) = 0;
virtual void togglePause( void ) = 0;
virtual void fadeOut( float seconds ) = 0;
};
} // namespace nom
#endif // include guard defined
<|endoftext|> |
<commit_before>//=============================================================================================================
/**
* @file colormap.cpp
* @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>;
* @version 1.0
* @date March, 2013
*
* @section LICENSE
*
* Copyright (C) 2013, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief Implementation of the ColorMap class.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "colormap.h"
#include <math.h>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace DISPLIB;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
ColorMap::ColorMap()
{
}
//*************************************************************************************************************
ColorMap::~ColorMap()
{
}
//*************************************************************************************************************
double ColorMap::linearSlope(double x, double m, double n)
{
//f = m*x + n
return m*x + n;
}
//*************************************************************************************************************
// Jet
int ColorMap::jetR(double x)
{
//Describe the red fuzzy set
if(x < 0.375)
return 0;
else if(x >= 0.375 && x < 0.625)
return (int)floor(linearSlope(x, 4, -1.5)*255);
else if(x >= 0.625 && x < 0.875)
return (int)floor(1.0*255);
else if(x >= 0.875)
return (int)floor(linearSlope(x, -4, 4.5)*255);
else
return 0;
}
//*************************************************************************************************************
int ColorMap::jetG(double x)
{
//Describe the green fuzzy set
if(x < 0.125)
return 0;
else if(x >= 0.125 && x < 0.375)
return (int)floor(linearSlope(x, 4, -0.5)*255);
else if(x >= 0.375 && x < 0.625)
return (int)floor(1.0*255);
else if(x >= 0.625 && x < 0.875)
return (int)floor(linearSlope(x, -4, 2.5)*255);
else
return 0;
}
//*************************************************************************************************************
int ColorMap::jetB(double x)
{
//Describe the blue fuzzy set
if(x < 0.125)
return (int)floor(linearSlope(x, 4, 0.5)*255);
else if(x >= 0.125 && x < 0.375)
return (int)floor(1.0*255);
else if(x >= 0.375 && x < 0.625)
return (int)floor(linearSlope(x, -4, 2.5)*255);
else
return 0;
}
//*************************************************************************************************************
// Hot
int ColorMap::hotR(double x)
{
//Describe the red fuzzy set
if(x < 0.375)
return (int)floor(linearSlope(x, 2.5621, 0.0392)*255);
else
return (int)floor(1.0*255);
}
//*************************************************************************************************************
int ColorMap::hotG(double x)
{
//Describe the green fuzzy set
if(x < 0.375)
return 0;
else if(x >= 0.375 && x < 0.75)
return (int)floor(linearSlope(x, 2.6667, -1.0)*255);
else
return (int)floor(1.0*255);
}
//*************************************************************************************************************
int ColorMap::hotB(double x)
{
//Describe the blue fuzzy set
if(x < 0.75)
return 0;
else
return (int)floor(linearSlope(x,4,-3)*255);
}
//*************************************************************************************************************
// Hot negative skewed
int ColorMap::hotRNeg1(double x)
{
//Describe the red fuzzy set
if(x < 0.2188)
return 0;
else if(x < 0.5781)
return (int)floor(linearSlope(x, 2.7832, -0.6090)*255);
else
return (int)floor(1.0*255);
}
//*************************************************************************************************************
int ColorMap::hotGNeg1(double x)
{
//Describe the green fuzzy set
if(x < 0.5781)
return 0;
else if(x >= 0.5781 && x < 0.8125)
return (int)floor(linearSlope(x, 4.2662, -2.4663)*255);
else
return (int)floor(1.0*255);
}
//*************************************************************************************************************
int ColorMap::hotBNeg1(double x)
{
//Describe the blue fuzzy set
if(x < 0.8125)
return 0;
else
return (int)floor(linearSlope(x,5.3333,-4.3333)*255);
}
//*************************************************************************************************************
int ColorMap::hotRNeg2(double x)
{
//Describe the red fuzzy set
if(x < 0.5625)
return 0;
else if(x < 0.8438)
return (int)floor(linearSlope(x, 3.5549, -1.9996)*255);
else
return (int)floor(1.0*255);
}
//*************************************************************************************************************
int ColorMap::hotGNeg2(double x)
{
//Describe the green fuzzy set
if(x < 0.8438)
return 0;
else if(x >= 0.8438 && x < 0.9531)
return (int)floor(linearSlope(x, 9.1491, -7.72)*255);
else
return (int)floor(1.0*255);
}
//*************************************************************************************************************
int ColorMap::hotBNeg2(double x)
{
//Describe the blue fuzzy set
if(x < 0.9531)
return 0;
else
return (int)floor(linearSlope(x,21.3220,-20.3220)*255);
}
//*************************************************************************************************************
// Bone
int ColorMap::boneR(double x)
{
//Describe the red fuzzy set
if(x < 0.375)
return (int)floor(linearSlope(x, 0.8471, 0)*255);
else if(x >= 0.375 && x < 0.75)
return (int)floor(linearSlope(x, 0.8889, -0.0157)*255);
else
return (int)floor(linearSlope(x, 1.396, -0.396)*255);
}
//*************************************************************************************************************
int ColorMap::boneG(double x)
{
//Describe the green fuzzy set
if(x < 0.375)
return (int)floor(linearSlope(x, 0.8471, 0)*255);
else if(x >= 0.375 && x < 0.75)
return (int)floor(linearSlope(x, 1.2237, -0.1413)*255);
else
return (int)floor(linearSlope(x, 0.894, 0.106)*255);
}
//*************************************************************************************************************
int ColorMap::boneB(double x)
{
//Describe the blue fuzzy set
if(x < 0.375)
return (int)floor(linearSlope(x, 1.1712, 0.0039)*255);
else if(x >= 0.375 && x < 0.75)
return (int)floor(linearSlope(x, 0.8889, 0.1098)*255);
else
return (int)floor(linearSlope(x, 0.8941, 0.1059)*255);
}
//*************************************************************************************************************
// RedBlue
int ColorMap::rbR(double x)
{
//Describe the red fuzzy set
if(x < 0)
return (int)floor(linearSlope(x, 1, 1)*255);
else
return (int)floor(1.0*255);
}
//*************************************************************************************************************
int ColorMap::rbG(double x)
{
//Describe the green fuzzy set
if(x < 0)
return (int)floor(linearSlope(x, 1, 1)*255);
else
return (int)floor(linearSlope(x, -1, 1)*255);
}
//*************************************************************************************************************
int ColorMap::rbB(double x)
{
//Describe the blue fuzzy set
if(x < 0)
return (int)floor(1.0*255);
else
return (int)floor(linearSlope(x, -1, 1)*255);
}
<commit_msg>[LIB-23] Bug in JetColor bar fixed<commit_after>//=============================================================================================================
/**
* @file colormap.cpp
* @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>;
* @version 1.0
* @date March, 2013
*
* @section LICENSE
*
* Copyright (C) 2013, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief Implementation of the ColorMap class.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "colormap.h"
#include <math.h>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace DISPLIB;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
ColorMap::ColorMap()
{
}
//*************************************************************************************************************
ColorMap::~ColorMap()
{
}
//*************************************************************************************************************
double ColorMap::linearSlope(double x, double m, double n)
{
//f = m*x + n
return m*x + n;
}
//*************************************************************************************************************
// Jet
int ColorMap::jetR(double x)
{
//Describe the red fuzzy set
if(x < 0.375)
return 0;
else if(x >= 0.375 && x < 0.625)
return (int)floor(linearSlope(x, 4, -1.5)*255);
else if(x >= 0.625 && x < 0.875)
return (int)floor(1.0*255);
else if(x >= 0.875)
return (int)floor(linearSlope(x, -4, 4.5)*255);
else
return 0;
}
//*************************************************************************************************************
int ColorMap::jetG(double x)
{
//Describe the green fuzzy set
if(x < 0.125)
return 0;
else if(x >= 0.125 && x < 0.375)
return (int)floor(linearSlope(x, 4, -0.5)*255);
else if(x >= 0.375 && x < 0.625)
return (int)floor(1.0*255);
else if(x >= 0.625 && x < 0.875)
return (int)floor(linearSlope(x, -4, 3.5)*255);
else
return 0;
}
//*************************************************************************************************************
int ColorMap::jetB(double x)
{
//Describe the blue fuzzy set
if(x < 0.125)
return (int)floor(linearSlope(x, 4, 0.5)*255);
else if(x >= 0.125 && x < 0.375)
return (int)floor(1.0*255);
else if(x >= 0.375 && x < 0.625)
return (int)floor(linearSlope(x, -4, 2.5)*255);
else
return 0;
}
//*************************************************************************************************************
// Hot
int ColorMap::hotR(double x)
{
//Describe the red fuzzy set
if(x < 0.375)
return (int)floor(linearSlope(x, 2.5621, 0.0392)*255);
else
return (int)floor(1.0*255);
}
//*************************************************************************************************************
int ColorMap::hotG(double x)
{
//Describe the green fuzzy set
if(x < 0.375)
return 0;
else if(x >= 0.375 && x < 0.75)
return (int)floor(linearSlope(x, 2.6667, -1.0)*255);
else
return (int)floor(1.0*255);
}
//*************************************************************************************************************
int ColorMap::hotB(double x)
{
//Describe the blue fuzzy set
if(x < 0.75)
return 0;
else
return (int)floor(linearSlope(x,4,-3)*255);
}
//*************************************************************************************************************
// Hot negative skewed
int ColorMap::hotRNeg1(double x)
{
//Describe the red fuzzy set
if(x < 0.2188)
return 0;
else if(x < 0.5781)
return (int)floor(linearSlope(x, 2.7832, -0.6090)*255);
else
return (int)floor(1.0*255);
}
//*************************************************************************************************************
int ColorMap::hotGNeg1(double x)
{
//Describe the green fuzzy set
if(x < 0.5781)
return 0;
else if(x >= 0.5781 && x < 0.8125)
return (int)floor(linearSlope(x, 4.2662, -2.4663)*255);
else
return (int)floor(1.0*255);
}
//*************************************************************************************************************
int ColorMap::hotBNeg1(double x)
{
//Describe the blue fuzzy set
if(x < 0.8125)
return 0;
else
return (int)floor(linearSlope(x,5.3333,-4.3333)*255);
}
//*************************************************************************************************************
int ColorMap::hotRNeg2(double x)
{
//Describe the red fuzzy set
if(x < 0.5625)
return 0;
else if(x < 0.8438)
return (int)floor(linearSlope(x, 3.5549, -1.9996)*255);
else
return (int)floor(1.0*255);
}
//*************************************************************************************************************
int ColorMap::hotGNeg2(double x)
{
//Describe the green fuzzy set
if(x < 0.8438)
return 0;
else if(x >= 0.8438 && x < 0.9531)
return (int)floor(linearSlope(x, 9.1491, -7.72)*255);
else
return (int)floor(1.0*255);
}
//*************************************************************************************************************
int ColorMap::hotBNeg2(double x)
{
//Describe the blue fuzzy set
if(x < 0.9531)
return 0;
else
return (int)floor(linearSlope(x,21.3220,-20.3220)*255);
}
//*************************************************************************************************************
// Bone
int ColorMap::boneR(double x)
{
//Describe the red fuzzy set
if(x < 0.375)
return (int)floor(linearSlope(x, 0.8471, 0)*255);
else if(x >= 0.375 && x < 0.75)
return (int)floor(linearSlope(x, 0.8889, -0.0157)*255);
else
return (int)floor(linearSlope(x, 1.396, -0.396)*255);
}
//*************************************************************************************************************
int ColorMap::boneG(double x)
{
//Describe the green fuzzy set
if(x < 0.375)
return (int)floor(linearSlope(x, 0.8471, 0)*255);
else if(x >= 0.375 && x < 0.75)
return (int)floor(linearSlope(x, 1.2237, -0.1413)*255);
else
return (int)floor(linearSlope(x, 0.894, 0.106)*255);
}
//*************************************************************************************************************
int ColorMap::boneB(double x)
{
//Describe the blue fuzzy set
if(x < 0.375)
return (int)floor(linearSlope(x, 1.1712, 0.0039)*255);
else if(x >= 0.375 && x < 0.75)
return (int)floor(linearSlope(x, 0.8889, 0.1098)*255);
else
return (int)floor(linearSlope(x, 0.8941, 0.1059)*255);
}
//*************************************************************************************************************
// RedBlue
int ColorMap::rbR(double x)
{
//Describe the red fuzzy set
if(x < 0)
return (int)floor(linearSlope(x, 1, 1)*255);
else
return (int)floor(1.0*255);
}
//*************************************************************************************************************
int ColorMap::rbG(double x)
{
//Describe the green fuzzy set
if(x < 0)
return (int)floor(linearSlope(x, 1, 1)*255);
else
return (int)floor(linearSlope(x, -1, 1)*255);
}
//*************************************************************************************************************
int ColorMap::rbB(double x)
{
//Describe the blue fuzzy set
if(x < 0)
return (int)floor(1.0*255);
else
return (int)floor(linearSlope(x, -1, 1)*255);
}
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <type_traits>
#include <visionaray/math/vector.h>
#include <visionaray/array.h>
#include <visionaray/generic_material.h>
#include <visionaray/get_surface.h>
#include <visionaray/result_record.h>
#include <visionaray/spectrum.h>
#include <visionaray/traverse.h>
namespace visionaray
{
namespace whitted
{
namespace detail
{
//-------------------------------------------------------------------------------------------------
// TODO: consolidate this with "real" brdf sampling
// TODO: user should be able to customize this behavior
//
template <typename Vec3, typename Scalar>
struct bounce_result
{
Vec3 reflected_dir;
Vec3 refracted_dir;
Scalar kr;
Scalar kt;
};
// reflection
template <typename V, typename S>
VSNRAY_FUNC
inline auto make_bounce_result(V const& reflected_dir, S kr)
-> bounce_result<V, S>
{
return {
reflected_dir,
V(),
kr,
0.0f
};
}
// reflection and refraction
template <typename V, typename S>
VSNRAY_FUNC
inline auto make_bounce_result(
V const& reflected_dir,
V const& refracted_dir,
S kr,
S kt
)
-> bounce_result<V, S>
{
return {
reflected_dir,
refracted_dir,
kr,
kt
};
}
//-------------------------------------------------------------------------------------------------
// specular_bounce() overloads for some materials
//
// fall-through, e.g. for plastic, assigns a dflt. reflectivity and no refraction
template <typename V, typename M>
VSNRAY_FUNC
inline auto specular_bounce(
M const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
VSNRAY_UNUSED(mat);
return make_bounce_result(
reflect(view_dir, normal),
typename V::value_type(0.1)
);
}
// matte, no specular reflectivity, returns an arbitrary direction
template <typename V, typename S>
VSNRAY_FUNC
inline auto specular_bounce(
matte<S> const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
VSNRAY_UNUSED(mat);
VSNRAY_UNUSED(view_dir);
VSNRAY_UNUSED(normal);
return make_bounce_result(
V(),
typename V::value_type(0.0)
);
}
// mirror material, here we know kr
template <typename V, typename S>
VSNRAY_FUNC
inline auto specular_bounce(
mirror<S> const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
return make_bounce_result(
reflect(view_dir, normal),
mat.kr()
);
}
//-------------------------------------------------------------------------------------------------
// some special treatment for generic materials
//
template <typename V>
struct visitor
{
using return_type = decltype( make_bounce_result(V(), typename V::value_type()) );
VSNRAY_FUNC visitor(V const& vd, V const& n)
: view_dir(vd)
, normal(n)
{
}
template <typename X>
VSNRAY_FUNC
return_type operator()(X const& ref) const
{
return specular_bounce(ref, view_dir, normal);
}
V const& view_dir;
V const& normal;
};
template <typename V, typename ...Ts>
VSNRAY_FUNC
inline auto specular_bounce(
generic_material<Ts...> const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
return apply_visitor(visitor<V>(view_dir, normal), mat);
}
template <
unsigned N,
typename ...Ts,
typename T,
typename = typename std::enable_if<simd::is_simd_vector<T>::value>::type
>
inline auto specular_bounce(
simd::generic_material<N, Ts...> const& mat,
vector<3, T> const& view_dir,
vector<3, T> const& normal
)
-> bounce_result<vector<3, T>, T>
{
using float_array = simd::aligned_array_t<T>;
auto ms = unpack(mat);
auto vds = unpack(view_dir);
auto ns = unpack(normal);
array<vector<3, float>, N> refl_dir;
array<vector<3, float>, N> refr_dir;
float_array kr;
float_array kt;
for (unsigned i = 0; i < N; ++i)
{
auto res = specular_bounce(ms[i], vds[i], ns[i]);
refl_dir[i] = res.reflected_dir;
refr_dir[i] = res.refracted_dir;
kr[i] = res.kr;
kt[i] = res.kt;
}
return make_bounce_result(
simd::pack(refl_dir),
simd::pack(refr_dir),
T(kr),
T(kt)
);
}
} // detail
//-------------------------------------------------------------------------------------------------
// Whitted kernel
//
template <typename Params>
struct kernel
{
Params params;
template <typename Intersector, typename R>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(Intersector& isect, R ray) const
{
using S = typename R::scalar_type;
using V = vector<3, S>;
using C = spectrum<S>;
result_record<S> result;
auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);
if (any(hit_rec.hit))
{
result.hit = hit_rec.hit;
result.depth = hit_rec.t;
}
else
{
result.hit = false;
result.color = vector<4, S>(params.background.intensity(ray.dir), S(1.0));
return result;
}
C color(0.0);
unsigned depth = 0;
C no_hit_color(from_rgb(params.background.intensity(ray.dir)));
S throughput(1.0);
while (any(hit_rec.hit) && any(throughput > S(params.epsilon)) && depth++ < params.num_bounces)
{
hit_rec.isect_pos = ray.ori + ray.dir * hit_rec.t;
auto surf = get_surface(hit_rec, params);
auto env = params.amb_light.intensity(ray.dir);
auto bgcolor = params.background.intensity(ray.dir);
auto ambient = surf.material.ambient() * C(from_rgb(env));
auto shaded_clr = select( hit_rec.hit, ambient, C(from_rgb(bgcolor)) );
auto view_dir = -ray.dir;
for (auto it = params.lights.begin; it != params.lights.end; ++it)
{
auto light_dir = normalize( V(it->position()) - hit_rec.isect_pos );
auto clr = surf.shade(view_dir, light_dir, it->intensity(hit_rec.isect_pos));
R shadow_ray(
hit_rec.isect_pos + light_dir * S(params.epsilon), // origin
light_dir, // direction
S(0.0), // tmin
length(hit_rec.isect_pos - V(it->position())) // tmax
);
// only cast a shadow if occluder between light source and hit pos
auto shadow_rec = any_hit(
shadow_ray,
params.prims.begin,
params.prims.end,
isect
);
shaded_clr += select(
hit_rec.hit & !shadow_rec.hit,
clr,
C(0.0)
);
}
color += select( hit_rec.hit, shaded_clr, no_hit_color ) * throughput;
auto bounce = detail::specular_bounce(surf.material, view_dir, surf.shading_normal);
if (any(bounce.kr > S(0.0)))
{
auto dir = bounce.reflected_dir;
ray = R(
hit_rec.isect_pos + dir * S(params.epsilon),
dir
);
hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);
}
throughput *= bounce.kr;
no_hit_color = C(0.0);
}
result.color = select(
result.hit,
to_rgba(color),
vector<4, S>(params.amb_light.intensity(ray.dir), S(1.0))
);
return result;
}
template <typename R>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(R ray) const
{
default_intersector ignore;
return (*this)(ignore, ray);
}
};
} // whitted
} // visionaray
<commit_msg>Fewer relative paths<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <type_traits>
#include "../math/vector.h"
#include "../array.h"
#include "../generic_material.h"
#include "../get_surface.h"
#include "../result_record.h"
#include "../spectrum.h"
#include "../traverse.h"
namespace visionaray
{
namespace whitted
{
namespace detail
{
//-------------------------------------------------------------------------------------------------
// TODO: consolidate this with "real" brdf sampling
// TODO: user should be able to customize this behavior
//
template <typename Vec3, typename Scalar>
struct bounce_result
{
Vec3 reflected_dir;
Vec3 refracted_dir;
Scalar kr;
Scalar kt;
};
// reflection
template <typename V, typename S>
VSNRAY_FUNC
inline auto make_bounce_result(V const& reflected_dir, S kr)
-> bounce_result<V, S>
{
return {
reflected_dir,
V(),
kr,
0.0f
};
}
// reflection and refraction
template <typename V, typename S>
VSNRAY_FUNC
inline auto make_bounce_result(
V const& reflected_dir,
V const& refracted_dir,
S kr,
S kt
)
-> bounce_result<V, S>
{
return {
reflected_dir,
refracted_dir,
kr,
kt
};
}
//-------------------------------------------------------------------------------------------------
// specular_bounce() overloads for some materials
//
// fall-through, e.g. for plastic, assigns a dflt. reflectivity and no refraction
template <typename V, typename M>
VSNRAY_FUNC
inline auto specular_bounce(
M const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
VSNRAY_UNUSED(mat);
return make_bounce_result(
reflect(view_dir, normal),
typename V::value_type(0.1)
);
}
// matte, no specular reflectivity, returns an arbitrary direction
template <typename V, typename S>
VSNRAY_FUNC
inline auto specular_bounce(
matte<S> const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
VSNRAY_UNUSED(mat);
VSNRAY_UNUSED(view_dir);
VSNRAY_UNUSED(normal);
return make_bounce_result(
V(),
typename V::value_type(0.0)
);
}
// mirror material, here we know kr
template <typename V, typename S>
VSNRAY_FUNC
inline auto specular_bounce(
mirror<S> const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
return make_bounce_result(
reflect(view_dir, normal),
mat.kr()
);
}
//-------------------------------------------------------------------------------------------------
// some special treatment for generic materials
//
template <typename V>
struct visitor
{
using return_type = decltype( make_bounce_result(V(), typename V::value_type()) );
VSNRAY_FUNC visitor(V const& vd, V const& n)
: view_dir(vd)
, normal(n)
{
}
template <typename X>
VSNRAY_FUNC
return_type operator()(X const& ref) const
{
return specular_bounce(ref, view_dir, normal);
}
V const& view_dir;
V const& normal;
};
template <typename V, typename ...Ts>
VSNRAY_FUNC
inline auto specular_bounce(
generic_material<Ts...> const& mat,
V const& view_dir,
V const& normal
)
-> decltype( make_bounce_result(V(), typename V::value_type()) )
{
return apply_visitor(visitor<V>(view_dir, normal), mat);
}
template <
unsigned N,
typename ...Ts,
typename T,
typename = typename std::enable_if<simd::is_simd_vector<T>::value>::type
>
inline auto specular_bounce(
simd::generic_material<N, Ts...> const& mat,
vector<3, T> const& view_dir,
vector<3, T> const& normal
)
-> bounce_result<vector<3, T>, T>
{
using float_array = simd::aligned_array_t<T>;
auto ms = unpack(mat);
auto vds = unpack(view_dir);
auto ns = unpack(normal);
array<vector<3, float>, N> refl_dir;
array<vector<3, float>, N> refr_dir;
float_array kr;
float_array kt;
for (unsigned i = 0; i < N; ++i)
{
auto res = specular_bounce(ms[i], vds[i], ns[i]);
refl_dir[i] = res.reflected_dir;
refr_dir[i] = res.refracted_dir;
kr[i] = res.kr;
kt[i] = res.kt;
}
return make_bounce_result(
simd::pack(refl_dir),
simd::pack(refr_dir),
T(kr),
T(kt)
);
}
} // detail
//-------------------------------------------------------------------------------------------------
// Whitted kernel
//
template <typename Params>
struct kernel
{
Params params;
template <typename Intersector, typename R>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(Intersector& isect, R ray) const
{
using S = typename R::scalar_type;
using V = vector<3, S>;
using C = spectrum<S>;
result_record<S> result;
auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);
if (any(hit_rec.hit))
{
result.hit = hit_rec.hit;
result.depth = hit_rec.t;
}
else
{
result.hit = false;
result.color = vector<4, S>(params.background.intensity(ray.dir), S(1.0));
return result;
}
C color(0.0);
unsigned depth = 0;
C no_hit_color(from_rgb(params.background.intensity(ray.dir)));
S throughput(1.0);
while (any(hit_rec.hit) && any(throughput > S(params.epsilon)) && depth++ < params.num_bounces)
{
hit_rec.isect_pos = ray.ori + ray.dir * hit_rec.t;
auto surf = get_surface(hit_rec, params);
auto env = params.amb_light.intensity(ray.dir);
auto bgcolor = params.background.intensity(ray.dir);
auto ambient = surf.material.ambient() * C(from_rgb(env));
auto shaded_clr = select( hit_rec.hit, ambient, C(from_rgb(bgcolor)) );
auto view_dir = -ray.dir;
for (auto it = params.lights.begin; it != params.lights.end; ++it)
{
auto light_dir = normalize( V(it->position()) - hit_rec.isect_pos );
auto clr = surf.shade(view_dir, light_dir, it->intensity(hit_rec.isect_pos));
R shadow_ray(
hit_rec.isect_pos + light_dir * S(params.epsilon), // origin
light_dir, // direction
S(0.0), // tmin
length(hit_rec.isect_pos - V(it->position())) // tmax
);
// only cast a shadow if occluder between light source and hit pos
auto shadow_rec = any_hit(
shadow_ray,
params.prims.begin,
params.prims.end,
isect
);
shaded_clr += select(
hit_rec.hit & !shadow_rec.hit,
clr,
C(0.0)
);
}
color += select( hit_rec.hit, shaded_clr, no_hit_color ) * throughput;
auto bounce = detail::specular_bounce(surf.material, view_dir, surf.shading_normal);
if (any(bounce.kr > S(0.0)))
{
auto dir = bounce.reflected_dir;
ray = R(
hit_rec.isect_pos + dir * S(params.epsilon),
dir
);
hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);
}
throughput *= bounce.kr;
no_hit_color = C(0.0);
}
result.color = select(
result.hit,
to_rgba(color),
vector<4, S>(params.amb_light.intensity(ray.dir), S(1.0))
);
return result;
}
template <typename R>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(R ray) const
{
default_intersector ignore;
return (*this)(ignore, ray);
}
};
} // whitted
} // visionaray
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XSIMD_CONFIG_HPP
#define XSIMD_CONFIG_HPP
#include "xsimd_align.hpp"
#define XSIMD_VERSION_MAJOR 7
#define XSIMD_VERSION_MINOR 4
#define XSIMD_VERSION_PATCH 3
#ifndef XSIMD_DEFAULT_ALLOCATOR
#if XSIMD_X86_INSTR_SET_AVAILABLE
#define XSIMD_DEFAULT_ALLOCATOR(T) xsimd::aligned_allocator<T, XSIMD_DEFAULT_ALIGNMENT>
#else
#define XSIMD_DEFAULT_ALLOCATOR(T) std::allocator<T>
#endif
#endif
#ifndef XSIMD_STACK_ALLOCATION_LIMIT
#define XSIMD_STACK_ALLOCATION_LIMIT 20000
#endif
#if defined(__LP64__) || defined(_WIN64)
#define XSIMD_64_BIT_ABI
#else
#define XSIMD_32_BIT_ABI
#endif
#endif
<commit_msg>Release 7.4.4<commit_after>/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XSIMD_CONFIG_HPP
#define XSIMD_CONFIG_HPP
#include "xsimd_align.hpp"
#define XSIMD_VERSION_MAJOR 7
#define XSIMD_VERSION_MINOR 4
#define XSIMD_VERSION_PATCH 4
#ifndef XSIMD_DEFAULT_ALLOCATOR
#if XSIMD_X86_INSTR_SET_AVAILABLE
#define XSIMD_DEFAULT_ALLOCATOR(T) xsimd::aligned_allocator<T, XSIMD_DEFAULT_ALIGNMENT>
#else
#define XSIMD_DEFAULT_ALLOCATOR(T) std::allocator<T>
#endif
#endif
#ifndef XSIMD_STACK_ALLOCATION_LIMIT
#define XSIMD_STACK_ALLOCATION_LIMIT 20000
#endif
#if defined(__LP64__) || defined(_WIN64)
#define XSIMD_64_BIT_ABI
#else
#define XSIMD_32_BIT_ABI
#endif
#endif
<|endoftext|> |
<commit_before>#ifndef ORG_EEROS_SEQUENCER_SEQUENCE_HPP_
#define ORG_EEROS_SEQUENCER_SEQUENCE_HPP_
#include <string>
#include <map>
#include <functional>
#include <vector>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <eeros/logger/Logger.hpp>
#include <eeros/logger/LogWriter.hpp>
#include <eeros/sequencer/Sequencer.hpp>
#include <eeros/sequencer/SequenceResult.hpp>
namespace eeros {
namespace sequencer {
// Base class
class SequenceBase {
friend class eeros::sequencer::Sequencer;
public:
SequenceBase(std::string name, Sequencer* sequencer);
virtual std::string getName() const;
virtual bool checkPreCondition();
virtual bool checkPostCondition();
protected:
virtual void yield();
virtual void init();
virtual void exit();
eeros::logger::Logger<eeros::logger::LogWriter> log;
std::string name;
Sequencer* sequencer;
};
// Class template Sequence
template<typename Treturn = void, typename ... Targs>
class Sequence : public SequenceBase {
public:
Sequence(std::string name, Sequencer* sequencer) : SequenceBase(name, sequencer) { }
SequenceResult<Treturn> operator()(Targs ... args) {
init();
yield();
if(!checkPreCondition()) return SequenceResult<Treturn>(result::preConditionFailure);
yield();
Treturn res = run(args...);
yield();
if(!checkPreCondition()) return SequenceResult<Treturn>(result::postConditionFailure, res);
yield();
exit();
return SequenceResult<Treturn>(result::success, res);
}
protected:
virtual Treturn run(Targs... args) { }
};
// Specializations for class template Sequence
template<typename ... Targs>
class Sequence<void, Targs...> : public SequenceBase {
public:
Sequence(std::string name, Sequencer* sequencer) : SequenceBase(name, sequencer) { }
SequenceResult<void> operator()(Targs ... args) {
init();
yield();
if(!checkPreCondition()) return SequenceResult<void>(result::preConditionFailure);
yield();
run(args...);
yield();
if(!checkPreCondition()) return SequenceResult<void>(result::postConditionFailure);
yield();
exit();
return SequenceResult<void>(result::success);
}
protected:
virtual void run(Targs... args) { }
};
template<>
class Sequence<void> : public SequenceBase {
public:
Sequence(std::string name, Sequencer* sequencer) : SequenceBase(name, sequencer) {
sequencer->addCmdSequence(this);
}
SequenceResult<void> operator()() {
init();
yield();
if(!checkPreCondition()) return SequenceResult<void>(result::preConditionFailure);
yield();
run();
yield();
if(!checkPreCondition()) return SequenceResult<void>(result::postConditionFailure);
yield();
exit();
return SequenceResult<void>(result::success);
}
protected:
virtual void run() { }
};
}; // namespace sequencer
}; // namespace eeros
#endif // ORG_EEROS_SEQUENCER_SEQUENCE_HPP_
<commit_msg>bug fixed: pre condition checked instead of post condition<commit_after>#ifndef ORG_EEROS_SEQUENCER_SEQUENCE_HPP_
#define ORG_EEROS_SEQUENCER_SEQUENCE_HPP_
#include <string>
#include <map>
#include <functional>
#include <vector>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <eeros/logger/Logger.hpp>
#include <eeros/logger/LogWriter.hpp>
#include <eeros/sequencer/Sequencer.hpp>
#include <eeros/sequencer/SequenceResult.hpp>
namespace eeros {
namespace sequencer {
// Base class
class SequenceBase {
friend class eeros::sequencer::Sequencer;
public:
SequenceBase(std::string name, Sequencer* sequencer);
virtual std::string getName() const;
virtual bool checkPreCondition();
virtual bool checkPostCondition();
protected:
virtual void yield();
virtual void init();
virtual void exit();
eeros::logger::Logger<eeros::logger::LogWriter> log;
std::string name;
Sequencer* sequencer;
};
// Class template Sequence
template<typename Treturn = void, typename ... Targs>
class Sequence : public SequenceBase {
public:
Sequence(std::string name, Sequencer* sequencer) : SequenceBase(name, sequencer) { }
SequenceResult<Treturn> operator()(Targs ... args) {
init();
yield();
if(!checkPreCondition())
return SequenceResult<Treturn>(result::preConditionFailure);
yield();
Treturn res = run(args...);
yield();
if(!checkPostCondition())
return SequenceResult<Treturn>(result::postConditionFailure, res);
yield();
exit();
return SequenceResult<Treturn>(result::success, res);
}
protected:
virtual Treturn run(Targs... args) { }
};
// Specializations for class template Sequence
template<typename ... Targs>
class Sequence<void, Targs...> : public SequenceBase {
public:
Sequence(std::string name, Sequencer* sequencer) : SequenceBase(name, sequencer) { }
SequenceResult<void> operator()(Targs ... args) {
init();
yield();
if(!checkPreCondition())
return SequenceResult<void>(result::preConditionFailure);
yield();
run(args...);
yield();
if(!checkPostCondition())
return SequenceResult<void>(result::postConditionFailure);
yield();
exit();
return SequenceResult<void>(result::success);
}
protected:
virtual void run(Targs... args) { }
};
template<>
class Sequence<void> : public SequenceBase {
public:
Sequence(std::string name, Sequencer* sequencer) : SequenceBase(name, sequencer) {
sequencer->addCmdSequence(this);
}
SequenceResult<void> operator()() {
init();
yield();
if(!checkPreCondition())
return SequenceResult<void>(result::preConditionFailure);
yield();
run();
yield();
if(!checkPostCondition())
return SequenceResult<void>(result::postConditionFailure);
yield();
exit();
return SequenceResult<void>(result::success);
}
protected:
virtual void run() { }
};
}; // namespace sequencer
}; // namespace eeros
#endif // ORG_EEROS_SEQUENCER_SEQUENCE_HPP_
<|endoftext|> |
<commit_before>#ifndef LLVM_CLANG_CXTRANSLATIONUNIT_H
#define LLVM_CLANG_CXTRANSLATIONUNIT_H
extern "C" {
struct CXTranslationUnitImpl {
void *TUData;
void *StringPool;
};
}
#endif
#include <clang/AST/Stmt.h>
#include <clang/AST/Decl.h>
#include <clang/AST/Expr.h>
#include <clang/AST/ASTContext.h>
#include <clang/Frontend/ASTUnit.h>
#include "mo/util/CursorUtil.h"
Decl* CursorUtil::getDecl(CXCursor node) {
if (clang_isDeclaration(clang_getCursorKind(node))) {
return (Decl *)node.data[0];
}
return NULL;
}
Stmt* CursorUtil::getStmt(CXCursor node) {
if (clang_isStatement(clang_getCursorKind(node))) {
return (Stmt *)node.data[1];
}
return NULL;
}
Expr* CursorUtil::getExpr(CXCursor node) {
if (clang_isExpression(clang_getCursorKind(node))) {
return (Expr *)node.data[1];
}
return NULL;
}
ASTContext& CursorUtil::getASTContext(CXCursor node) {
CXTranslationUnit translationUnit = (CXTranslationUnit)node.data[2];
ASTUnit *astUnit = (ASTUnit *)translationUnit->TUData;
return astUnit->getASTContext();
}
<commit_msg>use static_cast, which is cast safer<commit_after>#ifndef LLVM_CLANG_CXTRANSLATIONUNIT_H
#define LLVM_CLANG_CXTRANSLATIONUNIT_H
extern "C" {
struct CXTranslationUnitImpl {
void *TUData;
void *StringPool;
};
}
#endif
#include <clang/AST/Stmt.h>
#include <clang/AST/Decl.h>
#include <clang/AST/Expr.h>
#include <clang/AST/ASTContext.h>
#include <clang/Frontend/ASTUnit.h>
#include "mo/util/CursorUtil.h"
Decl* CursorUtil::getDecl(CXCursor node) {
if (clang_isDeclaration(clang_getCursorKind(node))) {
return (Decl *)node.data[0];
}
return NULL;
}
Stmt* CursorUtil::getStmt(CXCursor node) {
if (clang_isStatement(clang_getCursorKind(node))) {
return (Stmt *)node.data[1];
}
return NULL;
}
Expr* CursorUtil::getExpr(CXCursor node) {
if (clang_isExpression(clang_getCursorKind(node))) {
return (Expr *)node.data[1];
}
return NULL;
}
ASTContext& CursorUtil::getASTContext(CXCursor node) {
ASTUnit *astUnit = static_cast<ASTUnit *>(static_cast<CXTranslationUnit>(node.data[2])->TUData);
return astUnit->getASTContext();
}
<|endoftext|> |
<commit_before>#pragma once
#include <gtest/gtest.h>
template <typename T, template <class...> typename A, template <class...> typename B>
testing::AssertionResult EXPECT_ARREQ(const A<T> &expected, const A<T> &actual) {
auto expectedLength = expected.size();
auto actualLength = actual.size();
if (expectedLength != actualLength) {
return testing::AssertionFailure() << "Size of expected and actual arrays do not match";
}
for (size_t i{}; i < expectedLength; ++i) {
if (expected[i] != actual[i])
return testing::AssertionFailure() << "array[" << i
<< "] (" << actual[i] << ") != expected[" << i
<< "] (" << expected[i] << ")";
}
return testing::AssertionSuccess();
}
<commit_msg>changed name to something more palatable<commit_after>#pragma once
#include <gtest/gtest.h>
template <typename T, template <class...> typename A, template <class...> typename B>
testing::AssertionResult arrayMatch(const A<T> &expected, const B<T> &actual) {
auto expectedLength = expected.size();
auto actualLength = actual.size();
if (expectedLength != actualLength) {
return testing::AssertionFailure() << "Size of expected and actual arrays do not match";
}
for (size_t i{}; i < expectedLength; ++i) {
if (expected[i] != actual[i])
return testing::AssertionFailure() << "array[" << i
<< "] (" << actual[i] << ") != expected[" << i
<< "] (" << expected[i] << ")";
}
return testing::AssertionSuccess();
}
<|endoftext|> |
<commit_before>
<commit_msg>Add Shader.hpp<commit_after>#pragma once
#include <string>
#include <GL/glew.h>
#include "app/Resources.hpp"
using namespace std;
using namespace s_engine::app;
namespace s_engine {
namespace graphics {
//using namespace app;
class Shader: public Resource {
protected:
string vertexSource;
string fragmentSource;
GLuint vertexShaderId;
GLuint fragmentShaderId;
GLuint shaderProgramId;
public:
Shader(const string& _fragmentSource, const string& _vertexSource);
void Use();
};
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/io/BufferedOutputStream.h"
using namespace db::io;
BufferedOutputStream::BufferedOutputStream(
ByteBuffer* b, OutputStream* os, bool cleanup) :
FilterOutputStream(os, cleanup)
{
mBuffer = b;
}
BufferedOutputStream::~BufferedOutputStream()
{
}
bool BufferedOutputStream::write(const char* b, int length)
{
bool rval = true;
while(rval && length > 0)
{
// put bytes into buffer
length -= mBuffer->put(b, length, false);
// flush buffer if full
if(mBuffer->isFull())
{
rval = flush();
}
}
return rval;
}
bool BufferedOutputStream::flush()
{
bool rval = mOutputStream->write(mBuffer->data(), mBuffer->length());
mBuffer->clear();
return rval;
}
<commit_msg>Added fix to buffered output stream write() algorithm.<commit_after>/*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/io/BufferedOutputStream.h"
using namespace db::io;
BufferedOutputStream::BufferedOutputStream(
ByteBuffer* b, OutputStream* os, bool cleanup) :
FilterOutputStream(os, cleanup)
{
mBuffer = b;
}
BufferedOutputStream::~BufferedOutputStream()
{
}
bool BufferedOutputStream::write(const char* b, int length)
{
bool rval = true;
int written = 0;
while(rval && written < length)
{
// put bytes into buffer
written += mBuffer->put(b + written, length - written, false);
// flush buffer if full
if(mBuffer->isFull())
{
rval = flush();
}
}
return rval;
}
bool BufferedOutputStream::flush()
{
bool rval = mOutputStream->write(mBuffer->data(), mBuffer->length());
mBuffer->clear();
return rval;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
// NoLifeNxBench - Part of the NoLifeStory project //
// Copyright (C) 2013 Peter Atashian //
// //
// This program is free software: you can redistribute it and/or modify //
// it under the terms of the GNU Affero General Public License as //
// published by the Free Software Foundation, either version 3 of the //
// License, or (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU Affero General Public License for more details. //
// //
// You should have received a copy of the GNU Affero General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
//////////////////////////////////////////////////////////////////////////////
#include "../NoLifeNx/NX.hpp"
#include <cstdio>
#include <cmath>
#include <ctime>
#include <Windows.h>
NL::File const file("Data.nx");
NL::Node const node = file.Base()["Map"]["Map"]["Map1"]["105060000.img"]["1"]["tile"];
size_t c;
int64_t freq;
void stringsearch() {
for (auto && n : node) if (node[n.NameFast()] != n) throw;
}
void fileload() {
delete new NL::File("Data.nx");
}
void recursealternate2(NL::Node n) {
NL::Node nn = n.begin();
for (auto i = n.Size(); i; --i, ++nn) recursealternate2(nn);
}
void recursealternate() {
recursealternate2(file.Base());
}
void recurse(NL::Node n) {
c++;
for (auto && nn : n) recurse(nn);
}
void initialrecurse() {
NL::File f("Data.nx");
recurse(f.Base());
}
void morerecurse() {
recurse(file.Base());
}
extern "C" {
extern void asmrecurse(char const *, char const *);
}
void recurseoptimal() {
NL::Node n = file.Base();
char const * f = *(reinterpret_cast<char const **>(&n) + 1);
char const * d = *reinterpret_cast<char const **>(&n);
asmrecurse(f, d);
}
int64_t gethpc() {
LARGE_INTEGER n;
QueryPerformanceCounter(&n);
return n.QuadPart;
}
void getfreq() {
LARGE_INTEGER n;
QueryPerformanceFrequency(&n);
freq = n.QuadPart;
}
template <typename T>
void test(const char * name, T f) {
int64_t best = std::numeric_limits<int64_t>::max();
int64_t c0 = gethpc();
do {
int64_t c1 = gethpc();
f();
int64_t c2 = gethpc();
int64_t dif = c2 - c1;
if (dif < best) best = dif;
} while (gethpc() - c0 < freq);
printf("%s: %lldus\n", name, best * 1000000ULL / freq);
}
std::pair<int64_t, int64_t> results[0x10000] = {};
void stringrecurse(NL::Node n) {
for (auto && nn : n) stringrecurse(nn);
int64_t c0 = gethpc();
for (size_t i = 0x10; i; --i) for (auto && nn : n) if (n[nn.NameFast()] != nn) throw;
int64_t c1 = gethpc();
results[n.Size()].first += c1 - c0;
results[n.Size()].second += 1;
}
void stringtest() {
stringrecurse(file.Base());
for (uint32_t i = 1; i < 0x10000; ++i) {
auto && r = results[i];
double t = r.first * 1000000000. / (r.second * freq * i * 0x10);
if (r.second) printf("%u: %fns\n", i, t);
}
}
int main() {
getfreq();
test("File Loading", fileload);
test("String Searching", stringsearch);
test("Initial Recursion", initialrecurse);
test("C++ Recursion", morerecurse);
test("Alternate C++ Recursion", recursealternate);
test("ASM Recursion", recurseoptimal);
stringtest();
}<commit_msg>Hopefully adds posix support.<commit_after>//////////////////////////////////////////////////////////////////////////////
// NoLifeNxBench - Part of the NoLifeStory project //
// Copyright (C) 2013 Peter Atashian //
// //
// This program is free software: you can redistribute it and/or modify //
// it under the terms of the GNU Affero General Public License as //
// published by the Free Software Foundation, either version 3 of the //
// License, or (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU Affero General Public License for more details. //
// //
// You should have received a copy of the GNU Affero General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
//////////////////////////////////////////////////////////////////////////////
#include "../NoLifeNx/NX.hpp"
#include <cstdio>
#include <cmath>
#include <ctime>
#ifdef NL_WINDOWS
# include <Windows.h>
#endif
NL::File const file("Data.nx");
NL::Node const node = file.Base()["Map"]["Map"]["Map1"]["105060000.img"]["1"]["tile"];
size_t c;
int64_t freq;
void stringsearch() {
for (auto && n : node) if (node[n.NameFast()] != n) throw;
}
void fileload() {
delete new NL::File("Data.nx");
}
void recursealternate2(NL::Node n) {
NL::Node nn = n.begin();
for (auto i = n.Size(); i; --i, ++nn) recursealternate2(nn);
}
void recursealternate() {
recursealternate2(file.Base());
}
void recurse(NL::Node n) {
c++;
for (auto && nn : n) recurse(nn);
}
void initialrecurse() {
NL::File f("Data.nx");
recurse(f.Base());
}
void morerecurse() {
recurse(file.Base());
}
extern "C" {
extern void asmrecurse(char const *, char const *);
}
void recurseoptimal() {
NL::Node n = file.Base();
char const * f = *(reinterpret_cast<char const **>(&n) + 1);
char const * d = *reinterpret_cast<char const **>(&n);
asmrecurse(f, d);
}
#ifdef NL_WINDOWS
int64_t gethpc() {
LARGE_INTEGER n;
QueryPerformanceCounter(&n);
return n.QuadPart;
}
void getfreq() {
LARGE_INTEGER n;
QueryPerformanceFrequency(&n);
freq = n.QuadPart;
}
#else
int64_t gethpc() {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC_RAW, &t);
return t.tv_sec * 1000000000LL + t.tv_nsec;
}
void getfreq() {
freq = 1000000000LL
}
#endif
template <typename T>
void test(const char * name, T f) {
int64_t best = std::numeric_limits<int64_t>::max();
int64_t c0 = gethpc();
do {
int64_t c1 = gethpc();
f();
int64_t c2 = gethpc();
int64_t dif = c2 - c1;
if (dif < best) best = dif;
} while (gethpc() - c0 < freq);
printf("%s: %lldus\n", name, best * 1000000LL / freq);
}
std::pair<int64_t, int64_t> results[0x10000] = {};
void stringrecurse(NL::Node n) {
for (auto && nn : n) stringrecurse(nn);
int64_t c0 = gethpc();
for (size_t i = 0x10; i; --i) for (auto && nn : n) if (n[nn.NameFast()] != nn) throw;
int64_t c1 = gethpc();
results[n.Size()].first += c1 - c0;
results[n.Size()].second += 1;
}
void stringtest() {
stringrecurse(file.Base());
for (uint32_t i = 1; i < 0x10000; ++i) {
auto && r = results[i];
double t = r.first * 1000000000. / (r.second * freq * i * 0x10);
if (r.second) printf("%u: %fns\n", i, t);
}
}
int main() {
getfreq();
test("File Loading", fileload);
test("String Searching", stringsearch);
test("Initial Recursion", initialrecurse);
test("C++ Recursion", morerecurse);
test("Alternate C++ Recursion", recursealternate);
test("ASM Recursion", recurseoptimal);
stringtest();
}<|endoftext|> |
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file InputMapper.h
* @brief Registers an InputContext from the Naali Input subsystem and uses it to translate
* given set of keys to Entity Actions on the entity the component is part of.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "MemoryLeakCheck.h"
#include "EC_InputMapper.h"
#include "IAttribute.h"
#include "InputAPI.h"
#include "Entity.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_InputMapper")
EC_InputMapper::~EC_InputMapper()
{
input_.reset();
}
void EC_InputMapper::RegisterMapping(const QKeySequence &keySeq, const QString &action, int eventType, int executionType)
{
ActionInvocation invocation;
invocation.name = action;
invocation.executionType = executionType;
mappings_[qMakePair(keySeq, (KeyEvent::EventType)eventType)] = invocation;
}
void EC_InputMapper::RegisterMapping(const QString &keySeq, const QString &action, int eventType, int executionType)
{
ActionInvocation invocation;
invocation.name = action;
invocation.executionType = executionType;
QKeySequence key(keySeq);
if(!key.isEmpty())
{
mappings_[qMakePair(key, (KeyEvent::EventType)eventType)] = invocation;
}
}
void EC_InputMapper::RemoveMapping(const QKeySequence &keySeq, int eventType)
{
Mappings_t::iterator it = mappings_.find(qMakePair(keySeq, (KeyEvent::EventType)eventType));
if (it != mappings_.end())
mappings_.erase(it);
}
void EC_InputMapper::RemoveMapping(const QString &keySeq, int eventType)
{
Mappings_t::iterator it = mappings_.find(qMakePair(QKeySequence(keySeq), (KeyEvent::EventType)eventType));
if (it != mappings_.end())
mappings_.erase(it);
}
EC_InputMapper::EC_InputMapper(IModule *module):
IComponent(module->GetFramework()),
contextName(this, "Input context name", "EC_InputMapper"),
contextPriority(this, "Input context priority", 90),
takeKeyboardEventsOverQt(this, "Take keyboard events over Qt", false),
takeMouseEventsOverQt(this, "Take mouse events over Qt", false),
mappings(this, "Mappings"),
executionType(this, "Action execution type", 1),
modifiersEnabled(this, "Key modifiers enable", true),
enabled(this, "Enable actions", true),
keyrepeatTrigger(this, "Trigger on keyrepeats", true)
{
static AttributeMetadata executionAttrData;
static bool metadataInitialized = false;
if(!metadataInitialized)
{
executionAttrData.enums[EntityAction::Local] = "Local";
executionAttrData.enums[EntityAction::Server] = "Server";
executionAttrData.enums[EntityAction::Server | EntityAction::Local] = "Local+Server";
executionAttrData.enums[EntityAction::Peers] = "Peers";
executionAttrData.enums[EntityAction::Peers | EntityAction::Local] = "Local+Peers";
executionAttrData.enums[EntityAction::Peers | EntityAction::Server] = "Local+Server";
executionAttrData.enums[EntityAction::Peers | EntityAction::Server | EntityAction::Local] = "Local+Server+Peers";
metadataInitialized = true;
}
executionType.SetMetadata(&executionAttrData);
connect(this, SIGNAL(OnAttributeChanged(IAttribute *, AttributeChange::Type)),
SLOT(HandleAttributeUpdated(IAttribute *, AttributeChange::Type)));
input_ = GetFramework()->Input()->RegisterInputContext(contextName.Get().toStdString().c_str(), contextPriority.Get());
input_->SetTakeKeyboardEventsOverQt(takeKeyboardEventsOverQt.Get());
input_->SetTakeMouseEventsOverQt(takeMouseEventsOverQt.Get());
connect(input_.get(), SIGNAL(OnKeyEvent(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *)));
connect(input_.get(), SIGNAL(OnMouseEvent(MouseEvent *)), SLOT(HandleMouseEvent(MouseEvent *)));
}
void EC_InputMapper::HandleAttributeUpdated(IAttribute *attribute, AttributeChange::Type change)
{
if(attribute == &contextName || attribute == &contextPriority)
{
input_.reset();
input_ = GetFramework()->Input()->RegisterInputContext(contextName.Get().toStdString().c_str(), contextPriority.Get());
connect(input_.get(), SIGNAL(OnKeyEvent(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *)));
connect(input_.get(), SIGNAL(OnMouseEvent(MouseEvent *)), SLOT(HandleMouseEvent(MouseEvent *)));
}
else if(attribute == &takeKeyboardEventsOverQt)
{
input_->SetTakeKeyboardEventsOverQt(takeKeyboardEventsOverQt.Get());
}
else if(attribute == &takeMouseEventsOverQt)
{
input_->SetTakeMouseEventsOverQt(takeMouseEventsOverQt.Get());
}
else if(attribute == &mappings)
{
}
}
void EC_InputMapper::HandleKeyEvent(KeyEvent *e)
{
if (!enabled.Get())
return;
if ( !keyrepeatTrigger.Get() )
{
// Now we do not repeat keypressed events.
if ( e != 0 && e->eventType == KeyEvent::KeyPressed && e->keyPressCount > 1 )
return;
}
Mappings_t::iterator it;
if (modifiersEnabled.Get())
it = mappings_.find(qMakePair(QKeySequence(e->keyCode | e->modifiers), e->eventType));
else
it = mappings_.find(qMakePair(QKeySequence(e->keyCode), e->eventType));
if (it == mappings_.end())
return;
Scene::Entity *entity = GetParentEntity();
if (!entity)
{
LogWarning("Parent entity not set. Cannot execute action.");
return;
}
ActionInvocation& invocation = it.value();
QString &action = invocation.name;
int execType = invocation.executionType;
// If zero executiontype, use default
if (!execType)
execType = executionType.Get();
// LogDebug("Invoking action " + action.toStdString() + " for entity " + ToString(entity->GetId()));
// If the action has parameters, parse them from the action string.
int idx = action.indexOf('(');
if (idx != -1)
{
QString act = action.left(idx);
QString parsedAction = action.mid(idx + 1);
parsedAction.remove('(');
parsedAction.remove(')');
QStringList parameters = parsedAction.split(',');
entity->Exec((EntityAction::ExecutionType)execType, act, parameters);
}
else
entity->Exec((EntityAction::ExecutionType)execType, action);
}
void EC_InputMapper::HandleMouseEvent(MouseEvent *e)
{
if (!enabled.Get())
return;
if (!GetParentEntity())
return;
//! \todo this hardcoding of look button logic (similar to RexMovementInput) is not nice!
if ((e->IsButtonDown(MouseEvent::RightButton)) && (!GetFramework()->Input()->IsMouseCursorVisible()))
{
if (e->relativeX != 0)
GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseLookX" , QString::number(e->relativeX));
if (e->relativeY != 0)
GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseLookY" , QString::number(e->relativeY));
}
if (e->relativeZ != 0 && e->relativeZ != -1) // For some reason this is -1 without scroll
GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseScroll" , QString::number(e->relativeZ));
}
<commit_msg>EC_InputMapper: Do not process already handled KeyEvents.<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file InputMapper.h
* @brief Registers an InputContext from the Naali Input subsystem and uses it to translate
* given set of keys to Entity Actions on the entity the component is part of.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "MemoryLeakCheck.h"
#include "EC_InputMapper.h"
#include "IAttribute.h"
#include "InputAPI.h"
#include "Entity.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_InputMapper")
EC_InputMapper::~EC_InputMapper()
{
input_.reset();
}
void EC_InputMapper::RegisterMapping(const QKeySequence &keySeq, const QString &action, int eventType, int executionType)
{
ActionInvocation invocation;
invocation.name = action;
invocation.executionType = executionType;
mappings_[qMakePair(keySeq, (KeyEvent::EventType)eventType)] = invocation;
}
void EC_InputMapper::RegisterMapping(const QString &keySeq, const QString &action, int eventType, int executionType)
{
ActionInvocation invocation;
invocation.name = action;
invocation.executionType = executionType;
QKeySequence key(keySeq);
if(!key.isEmpty())
{
mappings_[qMakePair(key, (KeyEvent::EventType)eventType)] = invocation;
}
}
void EC_InputMapper::RemoveMapping(const QKeySequence &keySeq, int eventType)
{
Mappings_t::iterator it = mappings_.find(qMakePair(keySeq, (KeyEvent::EventType)eventType));
if (it != mappings_.end())
mappings_.erase(it);
}
void EC_InputMapper::RemoveMapping(const QString &keySeq, int eventType)
{
Mappings_t::iterator it = mappings_.find(qMakePair(QKeySequence(keySeq), (KeyEvent::EventType)eventType));
if (it != mappings_.end())
mappings_.erase(it);
}
EC_InputMapper::EC_InputMapper(IModule *module):
IComponent(module->GetFramework()),
contextName(this, "Input context name", "EC_InputMapper"),
contextPriority(this, "Input context priority", 90),
takeKeyboardEventsOverQt(this, "Take keyboard events over Qt", false),
takeMouseEventsOverQt(this, "Take mouse events over Qt", false),
mappings(this, "Mappings"),
executionType(this, "Action execution type", 1),
modifiersEnabled(this, "Key modifiers enable", true),
enabled(this, "Enable actions", true),
keyrepeatTrigger(this, "Trigger on keyrepeats", true)
{
static AttributeMetadata executionAttrData;
static bool metadataInitialized = false;
if(!metadataInitialized)
{
executionAttrData.enums[EntityAction::Local] = "Local";
executionAttrData.enums[EntityAction::Server] = "Server";
executionAttrData.enums[EntityAction::Server | EntityAction::Local] = "Local+Server";
executionAttrData.enums[EntityAction::Peers] = "Peers";
executionAttrData.enums[EntityAction::Peers | EntityAction::Local] = "Local+Peers";
executionAttrData.enums[EntityAction::Peers | EntityAction::Server] = "Local+Server";
executionAttrData.enums[EntityAction::Peers | EntityAction::Server | EntityAction::Local] = "Local+Server+Peers";
metadataInitialized = true;
}
executionType.SetMetadata(&executionAttrData);
connect(this, SIGNAL(OnAttributeChanged(IAttribute *, AttributeChange::Type)),
SLOT(HandleAttributeUpdated(IAttribute *, AttributeChange::Type)));
input_ = GetFramework()->Input()->RegisterInputContext(contextName.Get().toStdString().c_str(), contextPriority.Get());
input_->SetTakeKeyboardEventsOverQt(takeKeyboardEventsOverQt.Get());
input_->SetTakeMouseEventsOverQt(takeMouseEventsOverQt.Get());
connect(input_.get(), SIGNAL(OnKeyEvent(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *)));
connect(input_.get(), SIGNAL(OnMouseEvent(MouseEvent *)), SLOT(HandleMouseEvent(MouseEvent *)));
}
void EC_InputMapper::HandleAttributeUpdated(IAttribute *attribute, AttributeChange::Type change)
{
if(attribute == &contextName || attribute == &contextPriority)
{
input_.reset();
input_ = GetFramework()->Input()->RegisterInputContext(contextName.Get().toStdString().c_str(), contextPriority.Get());
connect(input_.get(), SIGNAL(OnKeyEvent(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *)));
connect(input_.get(), SIGNAL(OnMouseEvent(MouseEvent *)), SLOT(HandleMouseEvent(MouseEvent *)));
}
else if(attribute == &takeKeyboardEventsOverQt)
{
input_->SetTakeKeyboardEventsOverQt(takeKeyboardEventsOverQt.Get());
}
else if(attribute == &takeMouseEventsOverQt)
{
input_->SetTakeMouseEventsOverQt(takeMouseEventsOverQt.Get());
}
else if(attribute == &mappings)
{
}
}
void EC_InputMapper::HandleKeyEvent(KeyEvent *e)
{
if (!enabled.Get())
return;
// Do not act on already handled key events.
if (!e || e->handled)
return;
if (!keyrepeatTrigger.Get())
{
// Now we do not repeat key pressed events.
if (e != 0 && e->eventType == KeyEvent::KeyPressed && e->keyPressCount > 1)
return;
}
Mappings_t::iterator it;
if (modifiersEnabled.Get())
it = mappings_.find(qMakePair(QKeySequence(e->keyCode | e->modifiers), e->eventType));
else
it = mappings_.find(qMakePair(QKeySequence(e->keyCode), e->eventType));
if (it == mappings_.end())
return;
Scene::Entity *entity = GetParentEntity();
if (!entity)
{
LogWarning("Parent entity not set. Cannot execute action.");
return;
}
ActionInvocation& invocation = it.value();
QString &action = invocation.name;
int execType = invocation.executionType;
// If zero execution type, use default
if (!execType)
execType = executionType.Get();
// If the action has parameters, parse them from the action string.
int idx = action.indexOf('(');
if (idx != -1)
{
QString act = action.left(idx);
QString parsedAction = action.mid(idx + 1);
parsedAction.remove('(');
parsedAction.remove(')');
QStringList parameters = parsedAction.split(',');
entity->Exec((EntityAction::ExecutionType)execType, act, parameters);
}
else
entity->Exec((EntityAction::ExecutionType)execType, action);
}
void EC_InputMapper::HandleMouseEvent(MouseEvent *e)
{
if (!enabled.Get())
return;
if (!GetParentEntity())
return;
//! \todo this hard coding of look button logic (similar to RexMovementInput) is not nice!
if ((e->IsButtonDown(MouseEvent::RightButton)) && (!GetFramework()->Input()->IsMouseCursorVisible()))
{
if (e->relativeX != 0)
GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseLookX" , QString::number(e->relativeX));
if (e->relativeY != 0)
GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseLookY" , QString::number(e->relativeY));
}
if (e->relativeZ != 0 && e->relativeZ != -1) // For some reason this is -1 without scroll
GetParentEntity()->Exec((EntityAction::ExecutionType)executionType.Get(), "MouseScroll" , QString::number(e->relativeZ));
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: $
*
*/
#ifndef PCL_SEARCH_IMPL_FLANN_SEARCH_H_
#define PCL_SEARCH_IMPL_FLANN_SEARCH_H_
#include "pcl/search/flann_search.h"
#include <flann/flann.hpp>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
typename pcl::search::FlannSearch<PointT>::IndexPtr
pcl::search::FlannSearch<PointT>::KdTreeIndexCreator::createIndex (MatrixConstPtr data)
{
return (IndexPtr (new flann::KDTreeSingleIndex<flann::L2<float> > (*data,flann::KDTreeSingleIndexParams (max_leaf_size_))));
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::search::FlannSearch<PointT>::FlannSearch(bool sorted, FlannIndexCreator *creator) : pcl::search::Search<PointT> ("FlannSearch",sorted),
creator_ (creator), eps_ (0), input_copied_for_flann_ (false)
{
point_representation_.reset (new DefaultPointRepresentation<PointT>);
dim_ = point_representation_->getNumberOfDimensions ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::search::FlannSearch<PointT>::~FlannSearch()
{
delete creator_;
if (input_copied_for_flann_)
delete [] input_flann_->ptr();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::setInputCloud (const PointCloudConstPtr& cloud, const IndicesConstPtr& indices)
{
input_ = cloud;
indices_ = indices;
convertInputToFlannMatrix ();
index_ = creator_->createIndex (input_flann_);
index_->buildIndex ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::FlannSearch<PointT>::nearestKSearch (const PointT &point, int k, std::vector<int> &indices, std::vector<float> &dists) const
{
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float [point_representation_->getNumberOfDimensions ()];
point_representation_->vectorize (point,data);
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&point)): data;
const flann::Matrix<float> m (cdata ,1, point_representation_->getNumberOfDimensions ());
flann::SearchParams p(-1);
p.eps = eps_;
p.sorted = sorted_results_;
if (indices.size() != (unsigned int) k)
indices.resize (k,-1);
if (dists.size() != (unsigned int) k)
dists.resize (k);
flann::Matrix<int> i (&indices[0],1,k);
flann::Matrix<float> d (&dists[0],1,k);
int result = index_->knnSearch (m,i,d,k, p);
delete [] data;
if (!identity_mapping_)
{
for (size_t i = 0; i < (size_t)k; ++i)
{
int& neighbor_index = indices[i];
neighbor_index = index_mapping_[neighbor_index];
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::nearestKSearch (
const PointCloud& cloud, const std::vector<int>& indices, int k, std::vector< std::vector<int> >& k_indices,
std::vector< std::vector<float> >& k_sqr_distances) const
{
if (indices.empty ())
{
k_indices.resize (cloud.size ());
k_sqr_distances.resize (cloud.size ());
bool can_cast = point_representation_->isTrivial ();
// full point cloud + trivial copy operation = no need to do any conversion/copying to the flann matrix!
float* data=0;
if (!can_cast)
{
data = new float[dim_*cloud.size ()];
for (size_t i = 0; i < cloud.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[i],out);
}
}
// const cast is evil, but the matrix constructor won't change the data, and the
// search won't change the matrix
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&cloud[0])): data;
const flann::Matrix<float> m (cdata ,cloud.size (), dim_, can_cast ? sizeof (PointT) : dim_ * sizeof (float) );
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
index_->knnSearch (m,k_indices,k_sqr_distances,k, p);
delete [] data;
}
else // if indices are present, the cloud has to be copied anyway. Only copy the relevant parts of the points here.
{
k_indices.resize (indices.size ());
k_sqr_distances.resize (indices.size ());
float* data=new float [dim_*indices.size ()];
for (size_t i = 0; i < indices.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[indices[i]],out);
}
const flann::Matrix<float> m (data ,indices.size (), point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
index_->knnSearch (m,k_indices,k_sqr_distances,k, p);
delete[] data;
}
if (!identity_mapping_)
{
for (size_t j = 0; j < k_indices.size (); ++j)
{
for (size_t i = 0; i < (size_t)k; ++i)
{
int& neighbor_index = k_indices[j][i];
neighbor_index = index_mapping_[neighbor_index];
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::FlannSearch<PointT>::radiusSearch (const PointT& point, double radius,
std::vector<int> &indices, std::vector<float> &distances,
unsigned int max_nn) const
{
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float [point_representation_->getNumberOfDimensions ()];
point_representation_->vectorize (point,data);
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&point)) : data;
const flann::Matrix<float> m (cdata ,1, point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
p.max_neighbors = max_nn > 0 ? max_nn : -1;
std::vector<std::vector<int> > i (1);
std::vector<std::vector<float> > d (1);
int result = index_->radiusSearch (m,i,d,radius*radius, p);
delete [] data;
indices = i [0];
distances = d [0];
if (!identity_mapping_)
{
for (size_t i = 0; i < indices.size (); ++i)
{
int& neighbor_index = indices [i];
neighbor_index = index_mapping_ [neighbor_index];
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::radiusSearch (
const PointCloud& cloud, const std::vector<int>& indices, double radius, std::vector< std::vector<int> >& k_indices,
std::vector< std::vector<float> >& k_sqr_distances, unsigned int max_nn) const
{
if (indices.empty ()) // full point cloud + trivial copy operation = no need to do any conversion/copying to the flann matrix!
{
k_indices.resize (cloud.size ());
k_sqr_distances.resize (cloud.size ());
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float[dim_*cloud.size ()];
for (size_t i = 0; i < cloud.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[i],out);
}
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&cloud[0])) : data;
const flann::Matrix<float> m (cdata ,cloud.size (), dim_, can_cast ? sizeof (PointT) : dim_ * sizeof (float));
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
// here: max_nn==0: take all neighbors. flann: max_nn==0: return no neighbors, only count them. max_nn==-1: return all neighbors
p.max_neighbors = max_nn > 0 ? max_nn : -1;
index_->radiusSearch (m,k_indices,k_sqr_distances,radius*radius, p);
delete [] data;
}
else // if indices are present, the cloud has to be copied anyway. Only copy the relevant parts of the points here.
{
k_indices.resize (indices.size ());
k_sqr_distances.resize (indices.size ());
float* data = new float [dim_ * indices.size ()];
for (size_t i = 0; i < indices.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[indices[i]], out);
}
const flann::Matrix<float> m (data, cloud.size (), point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
// here: max_nn==0: take all neighbors. flann: max_nn==0: return no neighbors, only count them. max_nn==-1: return all neighbors
p.max_neighbors = max_nn > 0 ? max_nn : -1;
index_->radiusSearch (m, k_indices, k_sqr_distances, radius * radius, p);
delete[] data;
}
if (!identity_mapping_)
{
for (size_t j = 0; j < k_indices.size (); ++j )
{
for (size_t i = 0; i < k_indices[j].size (); ++i)
{
int& neighbor_index = k_indices[j][i];
neighbor_index = index_mapping_[neighbor_index];
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::convertInputToFlannMatrix ()
{
int original_no_of_points = indices_ && !indices_->empty () ? indices_->size () : input_->size ();
if (input_copied_for_flann_)
delete input_flann_->ptr();
input_copied_for_flann_ = true;
index_mapping_.clear();
identity_mapping_ = true;
input_flann_ = MatrixPtr (new flann::Matrix<float> (new float[original_no_of_points*point_representation_->getNumberOfDimensions ()], original_no_of_points, point_representation_->getNumberOfDimensions ()));
//cloud_ = (float*)malloc (original_no_of_points * dim_ * sizeof (float));
float* cloud_ptr = input_flann_->ptr();
//index_mapping_.reserve(original_no_of_points);
//identity_mapping_ = true;
if (!indices_ || indices_->empty ())
{
// TODO: implement "no NaN check" option that just re-uses the cloud data in the flann matrix
for (int i = 0; i < original_no_of_points; ++i)
{
const PointT& point = (*input_)[i];
// Check if the point is invalid
if (!point_representation_->isValid (point))
{
identity_mapping_ = false;
continue;
}
index_mapping_.push_back (i); // If the returned index should be for the indices vector
point_representation_->vectorize (point, cloud_ptr);
cloud_ptr += dim_;
}
}
else
{
for (int indices_index = 0; indices_index < original_no_of_points; ++indices_index)
{
int cloud_index = (*indices_)[indices_index];
const PointT& point = (*input_)[cloud_index];
// Check if the point is invalid
if (!point_representation_->isValid (point))
{
identity_mapping_ = false;
continue;
}
index_mapping_.push_back (indices_index); // If the returned index should be for the indices vector
point_representation_->vectorize (point, cloud_ptr);
cloud_ptr += dim_;
}
}
input_flann_->rows = index_mapping_.size ();
}
#define PCL_INSTANTIATE_FlannSearch(T) template class PCL_EXPORTS pcl::search::FlannSearch<T>;
#endif
<commit_msg>FlannSearch: indentation error fixed<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: $
*
*/
#ifndef PCL_SEARCH_IMPL_FLANN_SEARCH_H_
#define PCL_SEARCH_IMPL_FLANN_SEARCH_H_
#include "pcl/search/flann_search.h"
#include <flann/flann.hpp>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
typename pcl::search::FlannSearch<PointT>::IndexPtr
pcl::search::FlannSearch<PointT>::KdTreeIndexCreator::createIndex (MatrixConstPtr data)
{
return (IndexPtr (new flann::KDTreeSingleIndex<flann::L2<float> > (*data,flann::KDTreeSingleIndexParams (max_leaf_size_))));
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::search::FlannSearch<PointT>::FlannSearch(bool sorted, FlannIndexCreator *creator) : pcl::search::Search<PointT> ("FlannSearch",sorted),
creator_ (creator), eps_ (0), input_copied_for_flann_ (false)
{
point_representation_.reset (new DefaultPointRepresentation<PointT>);
dim_ = point_representation_->getNumberOfDimensions ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::search::FlannSearch<PointT>::~FlannSearch()
{
delete creator_;
if (input_copied_for_flann_)
delete [] input_flann_->ptr();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::setInputCloud (const PointCloudConstPtr& cloud, const IndicesConstPtr& indices)
{
input_ = cloud;
indices_ = indices;
convertInputToFlannMatrix ();
index_ = creator_->createIndex (input_flann_);
index_->buildIndex ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::FlannSearch<PointT>::nearestKSearch (const PointT &point, int k, std::vector<int> &indices, std::vector<float> &dists) const
{
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float [point_representation_->getNumberOfDimensions ()];
point_representation_->vectorize (point,data);
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&point)): data;
const flann::Matrix<float> m (cdata ,1, point_representation_->getNumberOfDimensions ());
flann::SearchParams p(-1);
p.eps = eps_;
p.sorted = sorted_results_;
if (indices.size() != (unsigned int) k)
indices.resize (k,-1);
if (dists.size() != (unsigned int) k)
dists.resize (k);
flann::Matrix<int> i (&indices[0],1,k);
flann::Matrix<float> d (&dists[0],1,k);
int result = index_->knnSearch (m,i,d,k, p);
delete [] data;
if (!identity_mapping_)
{
for (size_t i = 0; i < (size_t)k; ++i)
{
int& neighbor_index = indices[i];
neighbor_index = index_mapping_[neighbor_index];
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::nearestKSearch (
const PointCloud& cloud, const std::vector<int>& indices, int k, std::vector< std::vector<int> >& k_indices,
std::vector< std::vector<float> >& k_sqr_distances) const
{
if (indices.empty ())
{
k_indices.resize (cloud.size ());
k_sqr_distances.resize (cloud.size ());
bool can_cast = point_representation_->isTrivial ();
// full point cloud + trivial copy operation = no need to do any conversion/copying to the flann matrix!
float* data=0;
if (!can_cast)
{
data = new float[dim_*cloud.size ()];
for (size_t i = 0; i < cloud.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[i],out);
}
}
// const cast is evil, but the matrix constructor won't change the data, and the
// search won't change the matrix
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&cloud[0])): data;
const flann::Matrix<float> m (cdata ,cloud.size (), dim_, can_cast ? sizeof (PointT) : dim_ * sizeof (float) );
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
index_->knnSearch (m,k_indices,k_sqr_distances,k, p);
delete [] data;
}
else // if indices are present, the cloud has to be copied anyway. Only copy the relevant parts of the points here.
{
k_indices.resize (indices.size ());
k_sqr_distances.resize (indices.size ());
float* data=new float [dim_*indices.size ()];
for (size_t i = 0; i < indices.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[indices[i]],out);
}
const flann::Matrix<float> m (data ,indices.size (), point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
index_->knnSearch (m,k_indices,k_sqr_distances,k, p);
delete[] data;
}
if (!identity_mapping_)
{
for (size_t j = 0; j < k_indices.size (); ++j)
{
for (size_t i = 0; i < (size_t)k; ++i)
{
int& neighbor_index = k_indices[j][i];
neighbor_index = index_mapping_[neighbor_index];
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> int
pcl::search::FlannSearch<PointT>::radiusSearch (const PointT& point, double radius,
std::vector<int> &indices, std::vector<float> &distances,
unsigned int max_nn) const
{
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float [point_representation_->getNumberOfDimensions ()];
point_representation_->vectorize (point,data);
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&point)) : data;
const flann::Matrix<float> m (cdata ,1, point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
p.max_neighbors = max_nn > 0 ? max_nn : -1;
std::vector<std::vector<int> > i (1);
std::vector<std::vector<float> > d (1);
int result = index_->radiusSearch (m,i,d,radius*radius, p);
delete [] data;
indices = i [0];
distances = d [0];
if (!identity_mapping_)
{
for (size_t i = 0; i < indices.size (); ++i)
{
int& neighbor_index = indices [i];
neighbor_index = index_mapping_ [neighbor_index];
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::radiusSearch (
const PointCloud& cloud, const std::vector<int>& indices, double radius, std::vector< std::vector<int> >& k_indices,
std::vector< std::vector<float> >& k_sqr_distances, unsigned int max_nn) const
{
if (indices.empty ()) // full point cloud + trivial copy operation = no need to do any conversion/copying to the flann matrix!
{
k_indices.resize (cloud.size ());
k_sqr_distances.resize (cloud.size ());
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float[dim_*cloud.size ()];
for (size_t i = 0; i < cloud.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[i],out);
}
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&cloud[0])) : data;
const flann::Matrix<float> m (cdata ,cloud.size (), dim_, can_cast ? sizeof (PointT) : dim_ * sizeof (float));
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
// here: max_nn==0: take all neighbors. flann: max_nn==0: return no neighbors, only count them. max_nn==-1: return all neighbors
p.max_neighbors = max_nn > 0 ? max_nn : -1;
index_->radiusSearch (m,k_indices,k_sqr_distances,radius*radius, p);
delete [] data;
}
else // if indices are present, the cloud has to be copied anyway. Only copy the relevant parts of the points here.
{
k_indices.resize (indices.size ());
k_sqr_distances.resize (indices.size ());
float* data = new float [dim_ * indices.size ()];
for (size_t i = 0; i < indices.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[indices[i]], out);
}
const flann::Matrix<float> m (data, cloud.size (), point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
// here: max_nn==0: take all neighbors. flann: max_nn==0: return no neighbors, only count them. max_nn==-1: return all neighbors
p.max_neighbors = max_nn > 0 ? max_nn : -1;
index_->radiusSearch (m, k_indices, k_sqr_distances, radius * radius, p);
delete[] data;
}
if (!identity_mapping_)
{
for (size_t j = 0; j < k_indices.size (); ++j )
{
for (size_t i = 0; i < k_indices[j].size (); ++i)
{
int& neighbor_index = k_indices[j][i];
neighbor_index = index_mapping_[neighbor_index];
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::search::FlannSearch<PointT>::convertInputToFlannMatrix ()
{
int original_no_of_points = indices_ && !indices_->empty () ? indices_->size () : input_->size ();
if (input_copied_for_flann_)
delete input_flann_->ptr();
input_copied_for_flann_ = true;
index_mapping_.clear();
identity_mapping_ = true;
input_flann_ = MatrixPtr (new flann::Matrix<float> (new float[original_no_of_points*point_representation_->getNumberOfDimensions ()], original_no_of_points, point_representation_->getNumberOfDimensions ()));
//cloud_ = (float*)malloc (original_no_of_points * dim_ * sizeof (float));
float* cloud_ptr = input_flann_->ptr();
//index_mapping_.reserve(original_no_of_points);
//identity_mapping_ = true;
if (!indices_ || indices_->empty ())
{
// TODO: implement "no NaN check" option that just re-uses the cloud data in the flann matrix
for (int i = 0; i < original_no_of_points; ++i)
{
const PointT& point = (*input_)[i];
// Check if the point is invalid
if (!point_representation_->isValid (point))
{
identity_mapping_ = false;
continue;
}
index_mapping_.push_back (i); // If the returned index should be for the indices vector
point_representation_->vectorize (point, cloud_ptr);
cloud_ptr += dim_;
}
}
else
{
for (int indices_index = 0; indices_index < original_no_of_points; ++indices_index)
{
int cloud_index = (*indices_)[indices_index];
const PointT& point = (*input_)[cloud_index];
// Check if the point is invalid
if (!point_representation_->isValid (point))
{
identity_mapping_ = false;
continue;
}
index_mapping_.push_back (indices_index); // If the returned index should be for the indices vector
point_representation_->vectorize (point, cloud_ptr);
cloud_ptr += dim_;
}
}
input_flann_->rows = index_mapping_.size ();
}
#define PCL_INSTANTIATE_FlannSearch(T) template class PCL_EXPORTS pcl::search::FlannSearch<T>;
#endif
<|endoftext|> |
<commit_before>// a wrapper to load netgen-dll into python
#include <iostream>
#include <boost/python.hpp>
#ifdef WIN32
#define DLL_HEADER __declspec(dllimport)
#else
#define DLL_HEADER
#endif
void DLL_HEADER ExportNetgenMeshing();
void DLL_HEADER ExportMeshVis();
void DLL_HEADER ExportCSG();
void DLL_HEADER ExportCSGVis();
void DLL_HEADER ExportGeom2d();
BOOST_PYTHON_MODULE(libngpy)
{
ExportCSG();
ExportCSGVis();
ExportNetgenMeshing();
ExportMeshVis();
ExportGeom2d();
}
<commit_msg>Guard inclusion of boost/python.hpp<commit_after>// a wrapper to load netgen-dll into python
#include <iostream>
#ifdef NG_PYTHON
#include <boost/python.hpp>
#endif
#ifdef WIN32
#define DLL_HEADER __declspec(dllimport)
#else
#define DLL_HEADER
#endif
void DLL_HEADER ExportNetgenMeshing();
void DLL_HEADER ExportMeshVis();
void DLL_HEADER ExportCSG();
void DLL_HEADER ExportCSGVis();
void DLL_HEADER ExportGeom2d();
#ifdef NG_PYTHON
BOOST_PYTHON_MODULE(libngpy)
{
ExportCSG();
ExportCSGVis();
ExportNetgenMeshing();
ExportMeshVis();
ExportGeom2d();
}
#endif
<|endoftext|> |
<commit_before>// Copyright 2015 Open Source Robotics Foundation, 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.
#ifndef RCLCPP_RCLCPP_PARAMETER_CLIENT_HPP_
#define RCLCPP_RCLCPP_PARAMETER_CLIENT_HPP_
#include <string>
#include <rmw/rmw.h>
#include <rclcpp/executors.hpp>
#include <rclcpp/macros.hpp>
#include <rclcpp/node.hpp>
#include <rclcpp/parameter.hpp>
#include <rcl_interfaces/GetParameters.h>
#include <rcl_interfaces/GetParameterTypes.h>
#include <rcl_interfaces/Parameter.h>
#include <rcl_interfaces/ParameterDescriptor.h>
#include <rcl_interfaces/ParameterType.h>
#include <rcl_interfaces/SetParameters.h>
#include <rcl_interfaces/SetParametersAtomically.h>
#include <rcl_interfaces/ListParameters.h>
#include <rcl_interfaces/DescribeParameters.h>
namespace rclcpp
{
namespace parameter_client
{
class AsyncParametersClient
{
public:
RCLCPP_MAKE_SHARED_DEFINITIONS(AsyncParametersClient);
AsyncParametersClient(const rclcpp::node::Node::SharedPtr & node)
: node_(node)
{
get_parameters_client_ = node_->create_client<rcl_interfaces::GetParameters>(
"get_parameters");
get_parameter_types_client_ = node_->create_client<rcl_interfaces::GetParameterTypes>(
"get_parameter_types");
set_parameters_client_ = node_->create_client<rcl_interfaces::SetParameters>(
"set_parameters");
list_parameters_client_ = node_->create_client<rcl_interfaces::ListParameters>(
"list_parameters");
describe_parameters_client_ = node_->create_client<rcl_interfaces::DescribeParameters>(
"describe_parameters");
}
std::shared_future<std::vector<rclcpp::parameter::ParameterVariant>>
get_parameters(
std::vector<std::string> names,
std::function<void(
std::shared_future<std::vector<rclcpp::parameter::ParameterVariant>>)> callback = nullptr)
{
std::promise<std::vector<rclcpp::parameter::ParameterVariant>> promise_result;
auto future_result = promise_result.get_future().share();
auto request = std::make_shared<rcl_interfaces::GetParameters::Request>();
request->names = names;
get_parameters_client_->async_send_request(
request,
[&names, &promise_result, &future_result, &callback](
rclcpp::client::Client<rcl_interfaces::GetParameters>::SharedFuture cb_f) {
std::vector<rclcpp::parameter::ParameterVariant> parameter_variants;
auto & pvalues = cb_f.get()->values;
std::transform(pvalues.begin(), pvalues.end(), std::back_inserter(parameter_variants),
[&names, &pvalues](rcl_interfaces::ParameterValue pvalue) {
auto i = &pvalue - &pvalues[0];
rcl_interfaces::Parameter parameter;
parameter.name = names[i];
parameter.value = pvalue;
return rclcpp::parameter::ParameterVariant::from_parameter(parameter);
});
promise_result.set_value(parameter_variants);
if (callback != nullptr) {
callback(future_result);
}
}
);
return future_result;
}
std::shared_future<std::vector<rclcpp::parameter::ParameterType>>
get_parameter_types(
std::vector<std::string> parameter_names,
std::function<void(
std::shared_future<std::vector<rclcpp::parameter::ParameterType>>)> callback = nullptr)
{
std::promise<std::vector<rclcpp::parameter::ParameterType>> promise_result;
auto future_result = promise_result.get_future().share();
auto request = std::make_shared<rcl_interfaces::GetParameterTypes::Request>();
request->parameter_names = parameter_names;
get_parameter_types_client_->async_send_request(
request,
[&promise_result, &future_result, &callback](
rclcpp::client::Client<rcl_interfaces::GetParameterTypes>::SharedFuture cb_f) {
std::vector<rclcpp::parameter::ParameterType> parameter_types;
auto & pts = cb_f.get()->parameter_types;
std::transform(pts.begin(), pts.end(), std::back_inserter(parameter_types),
[](uint8_t pt) {return static_cast<rclcpp::parameter::ParameterType>(pt); });
promise_result.set_value(parameter_types);
if (callback != nullptr) {
callback(future_result);
}
}
);
return future_result;
}
std::shared_future<std::vector<rcl_interfaces::SetParametersResult>>
set_parameters(
std::vector<rclcpp::parameter::ParameterVariant> parameters,
std::function<void(
std::shared_future<std::vector<rcl_interfaces::SetParametersResult>>)> callback = nullptr)
{
std::promise<std::vector<rcl_interfaces::SetParametersResult>> promise_result;
auto future_result = promise_result.get_future().share();
auto request = std::make_shared<rcl_interfaces::SetParameters::Request>();
std::transform(parameters.begin(), parameters.end(), std::back_inserter(
request->parameters), [](
rclcpp::parameter::ParameterVariant p) {return p.to_parameter(); });
set_parameters_client_->async_send_request(
request,
[&promise_result, &future_result, &callback](
rclcpp::client::Client<rcl_interfaces::SetParameters>::SharedFuture cb_f) {
promise_result.set_value(cb_f.get()->results);
if (callback != nullptr) {
callback(future_result);
}
}
);
return future_result;
}
std::shared_future<rcl_interfaces::SetParametersResult>
set_parameters_atomically(
std::vector<rclcpp::parameter::ParameterVariant> parameters,
std::function<void(
std::shared_future<rcl_interfaces::SetParametersResult>)> callback = nullptr)
{
std::promise<rcl_interfaces::SetParametersResult> promise_result;
auto future_result = promise_result.get_future().share();
auto request = std::make_shared<rcl_interfaces::SetParametersAtomically::Request>();
std::transform(parameters.begin(), parameters.end(), std::back_inserter(
request->parameters), [](
rclcpp::parameter::ParameterVariant p) {return p.to_parameter(); });
set_parameters_atomically_client_->async_send_request(
request,
[&promise_result, &future_result, &callback](
rclcpp::client::Client<rcl_interfaces::SetParametersAtomically>::SharedFuture cb_f) {
promise_result.set_value(cb_f.get()->result);
if (callback != nullptr) {
callback(future_result);
}
}
);
return future_result;
}
std::shared_future<rcl_interfaces::ListParametersResult>
list_parameters(
std::vector<std::string> parameter_prefixes,
uint64_t depth,
std::function<void(
std::shared_future<rcl_interfaces::ListParametersResult>)> callback = nullptr)
{
std::promise<rcl_interfaces::ListParametersResult> promise_result;
auto future_result = promise_result.get_future().share();
auto request = std::make_shared<rcl_interfaces::ListParameters::Request>();
request->parameter_prefixes = parameter_prefixes;
request->depth = depth;
list_parameters_client_->async_send_request(
request,
[&promise_result, &future_result, &callback](
rclcpp::client::Client<rcl_interfaces::ListParameters>::SharedFuture cb_f) {
promise_result.set_value(cb_f.get()->result);
if (callback != nullptr) {
callback(future_result);
}
}
);
return future_result;
}
private:
const rclcpp::node::Node::SharedPtr node_;
rclcpp::client::Client<rcl_interfaces::GetParameters>::SharedPtr get_parameters_client_;
rclcpp::client::Client<rcl_interfaces::GetParameterTypes>::SharedPtr get_parameter_types_client_;
rclcpp::client::Client<rcl_interfaces::SetParameters>::SharedPtr set_parameters_client_;
rclcpp::client::Client<rcl_interfaces::SetParametersAtomically>::SharedPtr
set_parameters_atomically_client_;
rclcpp::client::Client<rcl_interfaces::ListParameters>::SharedPtr list_parameters_client_;
rclcpp::client::Client<rcl_interfaces::DescribeParameters>::SharedPtr describe_parameters_client_;
};
class SyncParametersClient
{
public:
RCLCPP_MAKE_SHARED_DEFINITIONS(SyncParametersClient);
SyncParametersClient(
rclcpp::node::Node::SharedPtr & node)
: node_(node)
{
executor_ = std::make_shared<rclcpp::executors::SingleThreadedExecutor>();
async_parameters_client_ = std::make_shared<AsyncParametersClient>(node);
}
SyncParametersClient(
rclcpp::executor::Executor::SharedPtr & executor,
rclcpp::node::Node::SharedPtr & node)
: executor_(executor), node_(node)
{
async_parameters_client_ = std::make_shared<AsyncParametersClient>(node);
}
std::vector<rclcpp::parameter::ParameterVariant>
get_parameters(std::vector<std::string> parameter_names)
{
auto f = async_parameters_client_->get_parameters(parameter_names);
return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get();
}
std::vector<rclcpp::parameter::ParameterType>
get_parameter_types(std::vector<std::string> parameter_names)
{
auto f = async_parameters_client_->get_parameter_types(parameter_names);
return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get();
}
std::vector<rcl_interfaces::SetParametersResult>
set_parameters(std::vector<rclcpp::parameter::ParameterVariant> parameters)
{
auto f = async_parameters_client_->set_parameters(parameters);
return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get();
}
rcl_interfaces::SetParametersResult
set_parameters_atomically(std::vector<rclcpp::parameter::ParameterVariant> parameters)
{
auto f = async_parameters_client_->set_parameters_atomically(parameters);
return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get();
}
rcl_interfaces::ListParametersResult
list_parameters(
std::vector<std::string> parameter_prefixes,
uint64_t depth)
{
auto f = async_parameters_client_->list_parameters(parameter_prefixes, depth);
return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get();
}
private:
rclcpp::executor::Executor::SharedPtr executor_;
rclcpp::node::Node::SharedPtr node_;
AsyncParametersClient::SharedPtr async_parameters_client_;
};
} /* namespace parameter_client */
} /* namespace rclcpp */
#endif /* RCLCPP_RCLCPP_PARAMETER_CLIENT_HPP_ */
<commit_msg>Added remote_node_name<commit_after>// Copyright 2015 Open Source Robotics Foundation, 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.
#ifndef RCLCPP_RCLCPP_PARAMETER_CLIENT_HPP_
#define RCLCPP_RCLCPP_PARAMETER_CLIENT_HPP_
#include <string>
#include <rmw/rmw.h>
#include <rclcpp/executors.hpp>
#include <rclcpp/macros.hpp>
#include <rclcpp/node.hpp>
#include <rclcpp/parameter.hpp>
#include <rcl_interfaces/GetParameters.h>
#include <rcl_interfaces/GetParameterTypes.h>
#include <rcl_interfaces/Parameter.h>
#include <rcl_interfaces/ParameterDescriptor.h>
#include <rcl_interfaces/ParameterType.h>
#include <rcl_interfaces/SetParameters.h>
#include <rcl_interfaces/SetParametersAtomically.h>
#include <rcl_interfaces/ListParameters.h>
#include <rcl_interfaces/DescribeParameters.h>
namespace rclcpp
{
namespace parameter_client
{
class AsyncParametersClient
{
public:
RCLCPP_MAKE_SHARED_DEFINITIONS(AsyncParametersClient);
AsyncParametersClient(const rclcpp::node::Node::SharedPtr & node,
const std::string & remote_node_name = "")
: node_(node)
{
if (remote_node_name != "") {
remote_node_name_ = remote_node_name;
} else {
remote_node_name_ = node_->get_name();
}
get_parameters_client_ = node_->create_client<rcl_interfaces::GetParameters>(
"get_parameters_" + remote_node_name_);
get_parameter_types_client_ = node_->create_client<rcl_interfaces::GetParameterTypes>(
"get_parameter_types_" + remote_node_name_);
set_parameters_client_ = node_->create_client<rcl_interfaces::SetParameters>(
"set_parameters_" + remote_node_name_);
list_parameters_client_ = node_->create_client<rcl_interfaces::ListParameters>(
"list_parameters_" + remote_node_name_);
describe_parameters_client_ = node_->create_client<rcl_interfaces::DescribeParameters>(
"describe_parameters_" + remote_node_name_);
}
std::shared_future<std::vector<rclcpp::parameter::ParameterVariant>>
get_parameters(
std::vector<std::string> names,
std::function<void(
std::shared_future<std::vector<rclcpp::parameter::ParameterVariant>>)> callback = nullptr)
{
std::promise<std::vector<rclcpp::parameter::ParameterVariant>> promise_result;
auto future_result = promise_result.get_future().share();
auto request = std::make_shared<rcl_interfaces::GetParameters::Request>();
request->names = names;
get_parameters_client_->async_send_request(
request,
[&names, &promise_result, &future_result, &callback](
rclcpp::client::Client<rcl_interfaces::GetParameters>::SharedFuture cb_f) {
std::vector<rclcpp::parameter::ParameterVariant> parameter_variants;
auto & pvalues = cb_f.get()->values;
std::transform(pvalues.begin(), pvalues.end(), std::back_inserter(parameter_variants),
[&names, &pvalues](rcl_interfaces::ParameterValue pvalue) {
auto i = &pvalue - &pvalues[0];
rcl_interfaces::Parameter parameter;
parameter.name = names[i];
parameter.value = pvalue;
return rclcpp::parameter::ParameterVariant::from_parameter(parameter);
});
promise_result.set_value(parameter_variants);
if (callback != nullptr) {
callback(future_result);
}
}
);
return future_result;
}
std::shared_future<std::vector<rclcpp::parameter::ParameterType>>
get_parameter_types(
std::vector<std::string> parameter_names,
std::function<void(
std::shared_future<std::vector<rclcpp::parameter::ParameterType>>)> callback = nullptr)
{
std::promise<std::vector<rclcpp::parameter::ParameterType>> promise_result;
auto future_result = promise_result.get_future().share();
auto request = std::make_shared<rcl_interfaces::GetParameterTypes::Request>();
request->parameter_names = parameter_names;
get_parameter_types_client_->async_send_request(
request,
[&promise_result, &future_result, &callback](
rclcpp::client::Client<rcl_interfaces::GetParameterTypes>::SharedFuture cb_f) {
std::vector<rclcpp::parameter::ParameterType> parameter_types;
auto & pts = cb_f.get()->parameter_types;
std::transform(pts.begin(), pts.end(), std::back_inserter(parameter_types),
[](uint8_t pt) {return static_cast<rclcpp::parameter::ParameterType>(pt); });
promise_result.set_value(parameter_types);
if (callback != nullptr) {
callback(future_result);
}
}
);
return future_result;
}
std::shared_future<std::vector<rcl_interfaces::SetParametersResult>>
set_parameters(
std::vector<rclcpp::parameter::ParameterVariant> parameters,
std::function<void(
std::shared_future<std::vector<rcl_interfaces::SetParametersResult>>)> callback = nullptr)
{
std::promise<std::vector<rcl_interfaces::SetParametersResult>> promise_result;
auto future_result = promise_result.get_future().share();
auto request = std::make_shared<rcl_interfaces::SetParameters::Request>();
std::transform(parameters.begin(), parameters.end(), std::back_inserter(
request->parameters), [](
rclcpp::parameter::ParameterVariant p) {return p.to_parameter(); });
set_parameters_client_->async_send_request(
request,
[&promise_result, &future_result, &callback](
rclcpp::client::Client<rcl_interfaces::SetParameters>::SharedFuture cb_f) {
promise_result.set_value(cb_f.get()->results);
if (callback != nullptr) {
callback(future_result);
}
}
);
return future_result;
}
std::shared_future<rcl_interfaces::SetParametersResult>
set_parameters_atomically(
std::vector<rclcpp::parameter::ParameterVariant> parameters,
std::function<void(
std::shared_future<rcl_interfaces::SetParametersResult>)> callback = nullptr)
{
std::promise<rcl_interfaces::SetParametersResult> promise_result;
auto future_result = promise_result.get_future().share();
auto request = std::make_shared<rcl_interfaces::SetParametersAtomically::Request>();
std::transform(parameters.begin(), parameters.end(), std::back_inserter(
request->parameters), [](
rclcpp::parameter::ParameterVariant p) {return p.to_parameter(); });
set_parameters_atomically_client_->async_send_request(
request,
[&promise_result, &future_result, &callback](
rclcpp::client::Client<rcl_interfaces::SetParametersAtomically>::SharedFuture cb_f) {
promise_result.set_value(cb_f.get()->result);
if (callback != nullptr) {
callback(future_result);
}
}
);
return future_result;
}
std::shared_future<rcl_interfaces::ListParametersResult>
list_parameters(
std::vector<std::string> parameter_prefixes,
uint64_t depth,
std::function<void(
std::shared_future<rcl_interfaces::ListParametersResult>)> callback = nullptr)
{
std::promise<rcl_interfaces::ListParametersResult> promise_result;
auto future_result = promise_result.get_future().share();
auto request = std::make_shared<rcl_interfaces::ListParameters::Request>();
request->parameter_prefixes = parameter_prefixes;
request->depth = depth;
list_parameters_client_->async_send_request(
request,
[&promise_result, &future_result, &callback](
rclcpp::client::Client<rcl_interfaces::ListParameters>::SharedFuture cb_f) {
promise_result.set_value(cb_f.get()->result);
if (callback != nullptr) {
callback(future_result);
}
}
);
return future_result;
}
private:
const rclcpp::node::Node::SharedPtr node_;
rclcpp::client::Client<rcl_interfaces::GetParameters>::SharedPtr get_parameters_client_;
rclcpp::client::Client<rcl_interfaces::GetParameterTypes>::SharedPtr get_parameter_types_client_;
rclcpp::client::Client<rcl_interfaces::SetParameters>::SharedPtr set_parameters_client_;
rclcpp::client::Client<rcl_interfaces::SetParametersAtomically>::SharedPtr
set_parameters_atomically_client_;
rclcpp::client::Client<rcl_interfaces::ListParameters>::SharedPtr list_parameters_client_;
rclcpp::client::Client<rcl_interfaces::DescribeParameters>::SharedPtr describe_parameters_client_;
std::string remote_node_name_;
};
class SyncParametersClient
{
public:
RCLCPP_MAKE_SHARED_DEFINITIONS(SyncParametersClient);
SyncParametersClient(
rclcpp::node::Node::SharedPtr & node)
: node_(node)
{
executor_ = std::make_shared<rclcpp::executors::SingleThreadedExecutor>();
async_parameters_client_ = std::make_shared<AsyncParametersClient>(node);
}
SyncParametersClient(
rclcpp::executor::Executor::SharedPtr & executor,
rclcpp::node::Node::SharedPtr & node)
: executor_(executor), node_(node)
{
async_parameters_client_ = std::make_shared<AsyncParametersClient>(node);
}
std::vector<rclcpp::parameter::ParameterVariant>
get_parameters(std::vector<std::string> parameter_names)
{
auto f = async_parameters_client_->get_parameters(parameter_names);
return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get();
}
std::vector<rclcpp::parameter::ParameterType>
get_parameter_types(std::vector<std::string> parameter_names)
{
auto f = async_parameters_client_->get_parameter_types(parameter_names);
return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get();
}
std::vector<rcl_interfaces::SetParametersResult>
set_parameters(std::vector<rclcpp::parameter::ParameterVariant> parameters)
{
auto f = async_parameters_client_->set_parameters(parameters);
return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get();
}
rcl_interfaces::SetParametersResult
set_parameters_atomically(std::vector<rclcpp::parameter::ParameterVariant> parameters)
{
auto f = async_parameters_client_->set_parameters_atomically(parameters);
return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get();
}
rcl_interfaces::ListParametersResult
list_parameters(
std::vector<std::string> parameter_prefixes,
uint64_t depth)
{
auto f = async_parameters_client_->list_parameters(parameter_prefixes, depth);
return rclcpp::executors::spin_node_until_future_complete(*executor_, node_, f).get();
}
private:
rclcpp::executor::Executor::SharedPtr executor_;
rclcpp::node::Node::SharedPtr node_;
AsyncParametersClient::SharedPtr async_parameters_client_;
};
} /* namespace parameter_client */
} /* namespace rclcpp */
#endif /* RCLCPP_RCLCPP_PARAMETER_CLIENT_HPP_ */
<|endoftext|> |
<commit_before>// $Id: mesh_smoother_laplace.C,v 1.16 2005-06-11 03:59:18 jwpeterson Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// 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
// C++ includes
#include <algorithm> // for std::copy, std::sort
// Local includes
#include "mesh_smoother_laplace.h"
#include "mesh_tools.h"
#include "elem.h"
#include "mesh.h"
// Member functions for the Laplace smoother
void LaplaceMeshSmoother::smooth(unsigned int n_iterations)
{
if (!_initialized)
this->init();
// Don't smooth the nodes on the boundary...
// this would change the mesh geometry which
// is probably not something we want!
std::vector<bool> on_boundary;
MeshTools::find_boundary_nodes(_mesh, on_boundary);
// We can only update the nodes after all new positions were
// determined. We store the new positions here
std::vector<Point> new_positions;
for (unsigned int n=0; n<n_iterations; n++)
{
new_positions.resize(_mesh.n_nodes());
for (unsigned int i=0; i<_mesh.n_nodes(); ++i)
{
// leave the boundary intact
// Only relocate the nodes which are vertices of an element
// All other entries of _graph (the secondary nodes) are empty
if (!on_boundary[i] && (_graph[i].size() > 0) )
{
Point avg_position(0.,0.,0.);
for (unsigned int j=0; j<_graph[i].size(); ++j)
avg_position.add(_mesh.node(_graph[i][j]));
new_positions[i] = avg_position /
static_cast<Real>(_graph[i].size());
}
}
// now update the node positions
for (unsigned int i=0; i<_mesh.n_nodes(); ++i)
if (!on_boundary[i] && (_graph[i].size() > 0) )
_mesh.node(i) = new_positions[i];
}
// finally adjust the second order nodes (those located between vertices)
// these nodes will be located between their adjacent nodes
// do this element-wise
MeshBase::element_iterator el = _mesh.active_elements_begin();
const MeshBase::element_iterator end = _mesh.active_elements_end();
for (; el != end; ++el)
{
// Constant handle for the element
const Elem* elem = *el;
// get the second order nodes (son)
// their element indices start at n_vertices and go to n_nodes
const unsigned int son_begin = elem->n_vertices();
const unsigned int son_end = elem->n_nodes();
// loop over all second order nodes (son)
for (unsigned int son=son_begin; son<son_end; son++)
{
const unsigned int n_adjacent_vertices =
elem->n_second_order_adjacent_vertices(son);
// calculate the new position which is the average of the
// position of the adjacent vertices
Point avg_position(0,0,0);
for (unsigned int v=0; v<n_adjacent_vertices; v++)
avg_position +=
_mesh.point( elem->node( elem->second_order_adjacent_vertex(son,v) ) );
_mesh.node(elem->node(son)) = avg_position / n_adjacent_vertices;
}
}
}
void LaplaceMeshSmoother::init()
{
switch (_mesh.mesh_dimension())
{
// TODO:[BSK] Fix this to work for refined meshes... I think
// the implementation was done quickly for Damien, who did not have
// refined grids. Fix it here and in the original Mesh member.
case 2: // Stolen directly from build_L_graph in mesh_base.C
{
// Initialize space in the graph. It is n_nodes
// long and each node is assumed to be connected to
// approximately 4 neighbors.
_graph.resize(_mesh.n_nodes());
// for (unsigned int i=0; i<_mesh.n_nodes(); ++i)
// _graph[i].reserve(4);
MeshBase::element_iterator el = _mesh.active_elements_begin();
const MeshBase::element_iterator end = _mesh.active_elements_end();
for (; el != end; ++el)
{
// Constant handle for the element
const Elem* elem = *el;
for (unsigned int s=0; s<elem->n_neighbors(); s++)
{
// Only operate on sides which are on the
// boundary or for which the current element's
// id is greater than its neighbor's.
// Sides get only built once.
if ((elem->neighbor(s) == NULL) ||
(elem->id() > elem->neighbor(s)->id()))
{
AutoPtr<Elem> side(elem->build_side(s));
_graph[side->node(0)].push_back(side->node(1));
_graph[side->node(1)].push_back(side->node(0));
}
}
}
_initialized = true;
break;
}
case 3: // Stolen blatantly from build_L_graph in mesh_base.C
{
// Initialize space in the graph. In 3D, I've assumed
// that each node was connected to approximately 3 neighbors.
_graph.resize(_mesh.n_nodes());
// for (unsigned int i=0; i<_mesh.n_nodes(); ++i)
// _graph[i].reserve(8);
MeshBase::element_iterator el = _mesh.active_elements_begin();
const MeshBase::element_iterator end = _mesh.active_elements_end();
for (; el != end; ++el)
{
// Shortcut notation for simplicity
const Elem* elem = *el;
for (unsigned int f=0; f<elem->n_neighbors(); f++) // Loop over faces
if ((elem->neighbor(f) == NULL) ||
(elem->id() > elem->neighbor(f)->id()))
{
AutoPtr<Elem> face(elem->build_side(f));
for (unsigned int s=0; s<face->n_neighbors(); s++) // Loop over face's edges
{
AutoPtr<Elem> side(face->build_side(s));
// At this point, we just insert the node numbers
// again. At the end we'll call sort and unique
// to make sure there are no duplicates
_graph[side->node(0)].push_back(side->node(1));
_graph[side->node(1)].push_back(side->node(0));
}
}
}
// Now call sort and unique to remove duplicate entries.
for (unsigned int i=0; i<_mesh.n_nodes(); ++i)
{
std::sort (_graph[i].begin(), _graph[i].end());
_graph[i].erase(std::unique(_graph[i].begin(), _graph[i].end()), _graph[i].end());
}
_initialized = true;
break;
}
default:
{
std::cerr << "At this time it is not possible "
<< "to smooth a dimension "
<< _mesh.mesh_dimension()
<< "mesh. Aborting..."
<< std::endl;
error();
}
}
}
void LaplaceMeshSmoother::print_graph() const
{
for (unsigned int i=0; i<_graph.size(); ++i)
{
std::cout << i << ": ";
std::copy(_graph[i].begin(),
_graph[i].end(),
std::ostream_iterator<unsigned int>(std::cout, " "));
std::cout << std::endl;
}
}
<commit_msg>Use node iterators instead of looping over mesh nodes and do not move second-order vertices which are on the boundary.<commit_after>// $Id: mesh_smoother_laplace.C,v 1.17 2007-02-15 17:04:49 jwpeterson Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// 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
// C++ includes
#include <algorithm> // for std::copy, std::sort
// Local includes
#include "mesh_smoother_laplace.h"
#include "mesh_tools.h"
#include "elem.h"
#include "mesh.h"
// Member functions for the Laplace smoother
void LaplaceMeshSmoother::smooth(unsigned int n_iterations)
{
if (!_initialized)
this->init();
// Don't smooth the nodes on the boundary...
// this would change the mesh geometry which
// is probably not something we want!
std::vector<bool> on_boundary;
MeshTools::find_boundary_nodes(_mesh, on_boundary);
// We can only update the nodes after all new positions were
// determined. We store the new positions here
std::vector<Point> new_positions;
for (unsigned int n=0; n<n_iterations; n++)
{
new_positions.resize(_mesh.n_nodes());
for (MeshBase::node_iterator it = _mesh.nodes_begin();
it != _mesh.nodes_end();
++it)
{
Node* node = *it;
// leave the boundary intact
// Only relocate the nodes which are vertices of an element
// All other entries of _graph (the secondary nodes) are empty
if (!on_boundary[node->id()] && (_graph[node->id()].size() > 0) )
{
Point avg_position(0.,0.,0.);
for (unsigned int j=0; j<_graph[node->id()].size(); ++j)
avg_position.add(_mesh.node(_graph[node->id()][j]));
new_positions[node->id()] = avg_position /
static_cast<Real>(_graph[node->id()].size());
}
}
// now update the node positions
for (MeshBase::node_iterator it = _mesh.nodes_begin();
it != _mesh.nodes_end();
++it)
{
Node* node = *it;
if (!on_boundary[node->id()] && (_graph[node->id()].size() > 0) )
{
// Should call Point::op=
_mesh.node(node->id()) = new_positions[node->id()];
}
}
}
// finally adjust the second order nodes (those located between vertices)
// these nodes will be located between their adjacent nodes
// do this element-wise
MeshBase::element_iterator el = _mesh.active_elements_begin();
const MeshBase::element_iterator end = _mesh.active_elements_end();
for (; el != end; ++el)
{
// Constant handle for the element
const Elem* elem = *el;
// get the second order nodes (son)
// their element indices start at n_vertices and go to n_nodes
const unsigned int son_begin = elem->n_vertices();
const unsigned int son_end = elem->n_nodes();
// loop over all second order nodes (son)
for (unsigned int son=son_begin; son<son_end; son++)
{
// Don't smooth second-order nodes which are on the boundary
if (!on_boundary[elem->node(son)])
{
const unsigned int n_adjacent_vertices =
elem->n_second_order_adjacent_vertices(son);
// calculate the new position which is the average of the
// position of the adjacent vertices
Point avg_position(0,0,0);
for (unsigned int v=0; v<n_adjacent_vertices; v++)
avg_position +=
_mesh.point( elem->node( elem->second_order_adjacent_vertex(son,v) ) );
_mesh.node(elem->node(son)) = avg_position / n_adjacent_vertices;
}
}
}
}
void LaplaceMeshSmoother::init()
{
switch (_mesh.mesh_dimension())
{
// TODO:[BSK] Fix this to work for refined meshes... I think
// the implementation was done quickly for Damien, who did not have
// refined grids. Fix it here and in the original Mesh member.
case 2: // Stolen directly from build_L_graph in mesh_base.C
{
// Initialize space in the graph. It is n_nodes
// long and each node is assumed to be connected to
// approximately 4 neighbors.
_graph.resize(_mesh.n_nodes());
// for (unsigned int i=0; i<_mesh.n_nodes(); ++i)
// _graph[i].reserve(4);
MeshBase::element_iterator el = _mesh.active_elements_begin();
const MeshBase::element_iterator end = _mesh.active_elements_end();
for (; el != end; ++el)
{
// Constant handle for the element
const Elem* elem = *el;
for (unsigned int s=0; s<elem->n_neighbors(); s++)
{
// Only operate on sides which are on the
// boundary or for which the current element's
// id is greater than its neighbor's.
// Sides get only built once.
if ((elem->neighbor(s) == NULL) ||
(elem->id() > elem->neighbor(s)->id()))
{
AutoPtr<Elem> side(elem->build_side(s));
_graph[side->node(0)].push_back(side->node(1));
_graph[side->node(1)].push_back(side->node(0));
}
}
}
_initialized = true;
break;
}
case 3: // Stolen blatantly from build_L_graph in mesh_base.C
{
// Initialize space in the graph. In 3D, I've assumed
// that each node was connected to approximately 3 neighbors.
_graph.resize(_mesh.n_nodes());
// for (unsigned int i=0; i<_mesh.n_nodes(); ++i)
// _graph[i].reserve(8);
MeshBase::element_iterator el = _mesh.active_elements_begin();
const MeshBase::element_iterator end = _mesh.active_elements_end();
for (; el != end; ++el)
{
// Shortcut notation for simplicity
const Elem* elem = *el;
for (unsigned int f=0; f<elem->n_neighbors(); f++) // Loop over faces
if ((elem->neighbor(f) == NULL) ||
(elem->id() > elem->neighbor(f)->id()))
{
AutoPtr<Elem> face(elem->build_side(f));
for (unsigned int s=0; s<face->n_neighbors(); s++) // Loop over face's edges
{
AutoPtr<Elem> side(face->build_side(s));
// At this point, we just insert the node numbers
// again. At the end we'll call sort and unique
// to make sure there are no duplicates
_graph[side->node(0)].push_back(side->node(1));
_graph[side->node(1)].push_back(side->node(0));
}
}
}
// Now call sort and unique to remove duplicate entries.
for (unsigned int i=0; i<_mesh.n_nodes(); ++i)
{
std::sort (_graph[i].begin(), _graph[i].end());
_graph[i].erase(std::unique(_graph[i].begin(), _graph[i].end()), _graph[i].end());
}
_initialized = true;
break;
}
default:
{
std::cerr << "At this time it is not possible "
<< "to smooth a dimension "
<< _mesh.mesh_dimension()
<< "mesh. Aborting..."
<< std::endl;
error();
}
}
}
void LaplaceMeshSmoother::print_graph() const
{
for (unsigned int i=0; i<_graph.size(); ++i)
{
std::cout << i << ": ";
std::copy(_graph[i].begin(),
_graph[i].end(),
std::ostream_iterator<unsigned int>(std::cout, " "));
std::cout << std::endl;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include <llvm/PassManager.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#include "base/logging.h"
#include "driver/compiler_driver.h"
#include "sea_ir/ir/sea.h"
#include "sea_ir/code_gen/code_gen.h"
namespace sea_ir {
std::string CodeGenData::GetElf(art::InstructionSet instruction_set) {
std::string elf;
::llvm::raw_string_ostream out_stream(elf);
// Lookup the LLVM target
std::string target_triple;
std::string target_cpu;
std::string target_attr;
art::CompilerDriver::InstructionSetToLLVMTarget(instruction_set,
target_triple, target_cpu, target_attr);
std::string errmsg;
const ::llvm::Target* target =
::llvm::TargetRegistry::lookupTarget(target_triple, errmsg);
CHECK(target != NULL) << errmsg;
// Target options
::llvm::TargetOptions target_options;
target_options.FloatABIType = ::llvm::FloatABI::Soft;
target_options.NoFramePointerElim = true;
target_options.NoFramePointerElimNonLeaf = true;
target_options.UseSoftFloat = false;
target_options.EnableFastISel = false;
// Create the ::llvm::TargetMachine
::llvm::OwningPtr< ::llvm::TargetMachine> target_machine(
target->createTargetMachine(target_triple, target_cpu, target_attr, target_options,
::llvm::Reloc::Static, ::llvm::CodeModel::Small,
::llvm::CodeGenOpt::Aggressive));
CHECK(target_machine.get() != NULL) << "Failed to create target machine";
// Add target data
const ::llvm::DataLayout* data_layout = target_machine->getDataLayout();
// PassManager for code generation passes
::llvm::PassManager pm;
pm.add(new ::llvm::DataLayout(*data_layout));
// FunctionPassManager for optimization pass
::llvm::FunctionPassManager fpm(&module_);
fpm.add(new ::llvm::DataLayout(*data_layout));
// Add optimization pass
::llvm::PassManagerBuilder pm_builder;
// TODO: Use inliner after we can do IPO.
pm_builder.Inliner = NULL;
// pm_builder.Inliner = ::llvm::createFunctionInliningPass();
// pm_builder.Inliner = ::llvm::createAlwaysInlinerPass();
// pm_builder.Inliner = ::llvm::createPartialInliningPass();
pm_builder.OptLevel = 3;
pm_builder.DisableSimplifyLibCalls = 1;
pm_builder.DisableUnitAtATime = 1;
pm_builder.populateFunctionPassManager(fpm);
pm_builder.populateModulePassManager(pm);
pm.add(::llvm::createStripDeadPrototypesPass());
// Add passes to emit ELF image
{
::llvm::formatted_raw_ostream formatted_os(out_stream, false);
// Ask the target to add backend passes as necessary.
if (target_machine->addPassesToEmitFile(pm,
formatted_os,
::llvm::TargetMachine::CGFT_ObjectFile,
true)) {
LOG(FATAL) << "Unable to generate ELF for this target";
}
// Run the code generation passes
pm.run(module_);
}
return elf;
}
}
<commit_msg>Build fix.<commit_after>/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include <llvm/PassManager.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#include "base/logging.h"
#include "driver/compiler_driver.h"
#include "sea_ir/ir/sea.h"
#include "sea_ir/code_gen/code_gen.h"
namespace sea_ir {
std::string CodeGenData::GetElf(art::InstructionSet instruction_set) {
std::string elf;
::llvm::raw_string_ostream out_stream(elf);
// Lookup the LLVM target
std::string target_triple;
std::string target_cpu;
std::string target_attr;
art::CompilerDriver::InstructionSetToLLVMTarget(instruction_set,
target_triple, target_cpu, target_attr);
std::string errmsg;
const ::llvm::Target* target =
::llvm::TargetRegistry::lookupTarget(target_triple, errmsg);
CHECK(target != NULL) << errmsg;
// Target options
::llvm::TargetOptions target_options;
target_options.FloatABIType = ::llvm::FloatABI::Soft;
target_options.NoFramePointerElim = true;
target_options.NoFramePointerElimNonLeaf = true;
target_options.UseSoftFloat = false;
target_options.EnableFastISel = false;
// Create the ::llvm::TargetMachine
::llvm::OwningPtr< ::llvm::TargetMachine> target_machine(
target->createTargetMachine(target_triple, target_cpu, target_attr, target_options,
::llvm::Reloc::Static, ::llvm::CodeModel::Small,
::llvm::CodeGenOpt::Aggressive));
CHECK(target_machine.get() != NULL) << "Failed to create target machine";
// Add target data
const ::llvm::DataLayout* data_layout = target_machine->getDataLayout();
// PassManager for code generation passes
::llvm::PassManager pm;
pm.add(new ::llvm::DataLayout(*data_layout));
// FunctionPassManager for optimization pass
::llvm::FunctionPassManager fpm(&module_);
fpm.add(new ::llvm::DataLayout(*data_layout));
// Add optimization pass
::llvm::PassManagerBuilder pm_builder;
// TODO: Use inliner after we can do IPO.
pm_builder.Inliner = NULL;
// pm_builder.Inliner = ::llvm::createFunctionInliningPass();
// pm_builder.Inliner = ::llvm::createAlwaysInlinerPass();
// pm_builder.Inliner = ::llvm::createPartialInliningPass();
pm_builder.OptLevel = 3;
pm_builder.DisableSimplifyLibCalls = 1;
pm_builder.DisableUnitAtATime = 1;
pm_builder.populateFunctionPassManager(fpm);
pm_builder.populateModulePassManager(pm);
pm.add(::llvm::createStripDeadPrototypesPass());
// Add passes to emit ELF image
{
::llvm::formatted_raw_ostream formatted_os(out_stream, false);
// Ask the target to add backend passes as necessary.
if (target_machine->addPassesToEmitFile(pm,
formatted_os,
::llvm::TargetMachine::CGFT_ObjectFile,
true)) {
LOG(FATAL) << "Unable to generate ELF for this target";
}
// Run the code generation passes
pm.run(module_);
}
return elf;
}
} // namespace sea_ir
<|endoftext|> |
<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/ozone/platform/cast/overlay_manager_cast.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/single_thread_task_runner.h"
#include "chromecast/media/base/media_message_loop.h"
#include "chromecast/public/cast_media_shlib.h"
#include "chromecast/public/graphics_types.h"
#include "chromecast/public/video_plane.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/ozone/public/overlay_candidates_ozone.h"
namespace ui {
namespace {
void SetVideoPlaneGeometry(
const chromecast::RectF& display_rect,
chromecast::media::VideoPlane::CoordinateType coordinate_type,
chromecast::media::VideoPlane::Transform transform) {
chromecast::media::VideoPlane* video_plane =
chromecast::media::CastMediaShlib::GetVideoPlane();
CHECK(video_plane);
video_plane->SetGeometry(display_rect, coordinate_type, transform);
}
// Translates a gfx::OverlayTransform into a VideoPlane::Transform.
// Could be just a lookup table once we have unit tests for this code
// to ensure it stays in sync with OverlayTransform.
chromecast::media::VideoPlane::Transform ConvertTransform(
gfx::OverlayTransform transform) {
switch (transform) {
case gfx::OVERLAY_TRANSFORM_NONE:
return chromecast::media::VideoPlane::TRANSFORM_NONE;
case gfx::OVERLAY_TRANSFORM_FLIP_HORIZONTAL:
return chromecast::media::VideoPlane::FLIP_HORIZONTAL;
case gfx::OVERLAY_TRANSFORM_FLIP_VERTICAL:
return chromecast::media::VideoPlane::FLIP_VERTICAL;
case gfx::OVERLAY_TRANSFORM_ROTATE_90:
return chromecast::media::VideoPlane::ROTATE_90;
case gfx::OVERLAY_TRANSFORM_ROTATE_180:
return chromecast::media::VideoPlane::ROTATE_180;
case gfx::OVERLAY_TRANSFORM_ROTATE_270:
return chromecast::media::VideoPlane::ROTATE_270;
default:
NOTREACHED();
return chromecast::media::VideoPlane::TRANSFORM_NONE;
}
}
bool ExactlyEqual(const chromecast::RectF& r1, const chromecast::RectF& r2) {
return r1.x == r2.x && r1.y == r2.y && r1.width == r2.width &&
r1.height == r2.height;
}
class OverlayCandidatesCast : public OverlayCandidatesOzone {
public:
OverlayCandidatesCast()
: media_task_runner_(
chromecast::media::MediaMessageLoop::GetTaskRunner()),
transform_(gfx::OVERLAY_TRANSFORM_INVALID),
display_rect_(0, 0, 0, 0) {}
void CheckOverlaySupport(OverlaySurfaceCandidateList* surfaces) override;
private:
scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_;
gfx::OverlayTransform transform_;
chromecast::RectF display_rect_;
};
void OverlayCandidatesCast::CheckOverlaySupport(
OverlaySurfaceCandidateList* surfaces) {
for (auto& candidate : *surfaces) {
if (candidate.plane_z_order != -1)
continue;
candidate.overlay_handled = true;
// Compositor requires all overlay rectangles to have integer coords
candidate.display_rect = gfx::ToEnclosedRect(candidate.display_rect);
chromecast::RectF display_rect(
candidate.display_rect.x(), candidate.display_rect.y(),
candidate.display_rect.width(), candidate.display_rect.height());
// Update video plane geometry + transform to match compositor quad.
// This must be done on media thread - and no point doing if it hasn't
// changed.
if (candidate.transform != transform_ ||
!ExactlyEqual(display_rect, display_rect_)) {
transform_ = candidate.transform;
display_rect_ = display_rect;
media_task_runner_->PostTask(
FROM_HERE,
base::Bind(
&SetVideoPlaneGeometry, display_rect,
chromecast::media::VideoPlane::COORDINATE_TYPE_GRAPHICS_PLANE,
ConvertTransform(candidate.transform)));
}
return;
}
}
} // namespace
OverlayManagerCast::OverlayManagerCast() {
}
OverlayManagerCast::~OverlayManagerCast() {
}
scoped_ptr<OverlayCandidatesOzone> OverlayManagerCast::CreateOverlayCandidates(
gfx::AcceleratedWidget w) {
return make_scoped_ptr(new OverlayCandidatesCast());
}
bool OverlayManagerCast::CanShowPrimaryPlaneAsOverlay() {
return false;
}
} // namespace ui
<commit_msg>Limit rate of posted VideoPlane::SetGeometry calls from Cast overlays<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/ozone/platform/cast/overlay_manager_cast.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/single_thread_task_runner.h"
#include "chromecast/media/base/media_message_loop.h"
#include "chromecast/public/cast_media_shlib.h"
#include "chromecast/public/graphics_types.h"
#include "chromecast/public/video_plane.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/ozone/public/overlay_candidates_ozone.h"
namespace ui {
namespace {
// Helper class for calling VideoPlane::SetGeometry with rate-limiting.
// SetGeometry can take on the order of 100ms to run in some implementations
// and can be called on the order of 20x / second (as fast as graphics frames
// are produced). This creates an ever-growing backlog of tasks on the media
// thread.
// This class measures the time taken to run SetGeometry to determine a
// reasonable frequency at which to call it. Excess calls are coalesced
// to just set the most recent geometry.
class RateLimitedSetVideoPlaneGeometry
: public base::RefCountedThreadSafe<RateLimitedSetVideoPlaneGeometry> {
public:
RateLimitedSetVideoPlaneGeometry(
const scoped_refptr<base::SingleThreadTaskRunner>& task_runner)
: pending_display_rect_(0, 0, 0, 0),
pending_set_geometry_(false),
min_calling_interval_ms_(0),
sample_counter_(0),
task_runner_(task_runner) {}
void SetGeometry(
const chromecast::RectF& display_rect,
chromecast::media::VideoPlane::CoordinateType coordinate_type,
chromecast::media::VideoPlane::Transform transform) {
DCHECK(task_runner_->BelongsToCurrentThread());
base::TimeTicks now = base::TimeTicks::Now();
base::TimeDelta elapsed = now - last_set_geometry_time_;
if (elapsed < base::TimeDelta::FromMilliseconds(min_calling_interval_ms_)) {
if (!pending_set_geometry_) {
pending_set_geometry_ = true;
task_runner_->PostDelayedTask(
FROM_HERE,
base::Bind(
&RateLimitedSetVideoPlaneGeometry::ApplyPendingSetGeometry,
this),
base::TimeDelta::FromMilliseconds(2 * min_calling_interval_ms_));
}
pending_display_rect_ = display_rect;
pending_coordinate_type_ = coordinate_type;
pending_transform_ = transform;
return;
}
last_set_geometry_time_ = now;
chromecast::media::VideoPlane* video_plane =
chromecast::media::CastMediaShlib::GetVideoPlane();
CHECK(video_plane);
base::TimeTicks start = base::TimeTicks::Now();
video_plane->SetGeometry(display_rect, coordinate_type, transform);
base::TimeDelta set_geometry_time = base::TimeTicks::Now() - start;
UpdateAverageTime(set_geometry_time.InMilliseconds());
}
private:
friend class base::RefCountedThreadSafe<RateLimitedSetVideoPlaneGeometry>;
~RateLimitedSetVideoPlaneGeometry() {}
void UpdateAverageTime(int64 sample) {
const size_t kSampleCount = 5;
if (samples_.size() < kSampleCount)
samples_.push_back(sample);
else
samples_[sample_counter_++ % kSampleCount] = sample;
int64 total = 0;
for (int64 s : samples_)
total += s;
min_calling_interval_ms_ = 2 * total / samples_.size();
}
void ApplyPendingSetGeometry() {
if (pending_set_geometry_) {
pending_set_geometry_ = false;
SetGeometry(pending_display_rect_, pending_coordinate_type_,
pending_transform_);
}
}
chromecast::RectF pending_display_rect_;
chromecast::media::VideoPlane::CoordinateType pending_coordinate_type_;
chromecast::media::VideoPlane::Transform pending_transform_;
bool pending_set_geometry_;
base::TimeTicks last_set_geometry_time_;
// Don't call SetGeometry faster than this interval.
int64 min_calling_interval_ms_;
// Min calling interval is computed as double average of last few time samples
// (i.e. allow at least as much time between calls as the call itself takes).
std::vector<int64> samples_;
size_t sample_counter_;
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
DISALLOW_COPY_AND_ASSIGN(RateLimitedSetVideoPlaneGeometry);
};
// Translates a gfx::OverlayTransform into a VideoPlane::Transform.
// Could be just a lookup table once we have unit tests for this code
// to ensure it stays in sync with OverlayTransform.
chromecast::media::VideoPlane::Transform ConvertTransform(
gfx::OverlayTransform transform) {
switch (transform) {
case gfx::OVERLAY_TRANSFORM_NONE:
return chromecast::media::VideoPlane::TRANSFORM_NONE;
case gfx::OVERLAY_TRANSFORM_FLIP_HORIZONTAL:
return chromecast::media::VideoPlane::FLIP_HORIZONTAL;
case gfx::OVERLAY_TRANSFORM_FLIP_VERTICAL:
return chromecast::media::VideoPlane::FLIP_VERTICAL;
case gfx::OVERLAY_TRANSFORM_ROTATE_90:
return chromecast::media::VideoPlane::ROTATE_90;
case gfx::OVERLAY_TRANSFORM_ROTATE_180:
return chromecast::media::VideoPlane::ROTATE_180;
case gfx::OVERLAY_TRANSFORM_ROTATE_270:
return chromecast::media::VideoPlane::ROTATE_270;
default:
NOTREACHED();
return chromecast::media::VideoPlane::TRANSFORM_NONE;
}
}
bool ExactlyEqual(const chromecast::RectF& r1, const chromecast::RectF& r2) {
return r1.x == r2.x && r1.y == r2.y && r1.width == r2.width &&
r1.height == r2.height;
}
class OverlayCandidatesCast : public OverlayCandidatesOzone {
public:
OverlayCandidatesCast()
: media_task_runner_(
chromecast::media::MediaMessageLoop::GetTaskRunner()),
transform_(gfx::OVERLAY_TRANSFORM_INVALID),
display_rect_(0, 0, 0, 0),
video_plane_wrapper_(
new RateLimitedSetVideoPlaneGeometry(media_task_runner_)) {}
void CheckOverlaySupport(OverlaySurfaceCandidateList* surfaces) override;
private:
scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_;
gfx::OverlayTransform transform_;
chromecast::RectF display_rect_;
scoped_refptr<RateLimitedSetVideoPlaneGeometry> video_plane_wrapper_;
};
void OverlayCandidatesCast::CheckOverlaySupport(
OverlaySurfaceCandidateList* surfaces) {
for (auto& candidate : *surfaces) {
if (candidate.plane_z_order != -1)
continue;
candidate.overlay_handled = true;
// Compositor requires all overlay rectangles to have integer coords
candidate.display_rect = gfx::ToEnclosedRect(candidate.display_rect);
chromecast::RectF display_rect(
candidate.display_rect.x(), candidate.display_rect.y(),
candidate.display_rect.width(), candidate.display_rect.height());
// Update video plane geometry + transform to match compositor quad.
// This must be done on media thread - and no point doing if it hasn't
// changed.
if (candidate.transform != transform_ ||
!ExactlyEqual(display_rect, display_rect_)) {
transform_ = candidate.transform;
display_rect_ = display_rect;
media_task_runner_->PostTask(
FROM_HERE,
base::Bind(
&RateLimitedSetVideoPlaneGeometry::SetGeometry,
video_plane_wrapper_, display_rect,
chromecast::media::VideoPlane::COORDINATE_TYPE_GRAPHICS_PLANE,
ConvertTransform(candidate.transform)));
}
return;
}
}
} // namespace
OverlayManagerCast::OverlayManagerCast() {
}
OverlayManagerCast::~OverlayManagerCast() {
}
scoped_ptr<OverlayCandidatesOzone> OverlayManagerCast::CreateOverlayCandidates(
gfx::AcceleratedWidget w) {
return make_scoped_ptr(new OverlayCandidatesCast());
}
bool OverlayManagerCast::CanShowPrimaryPlaneAsOverlay() {
return false;
}
} // namespace ui
<|endoftext|> |
<commit_before>//
// sockets.c
// Packages
//
// Created by Theo Weidmann on 06.07.2016.
// Copyright (c) 2016 Theo Weidmann. All rights reserved.
//
#include "../../EmojicodeReal-TimeEngine/EmojicodeAPI.hpp"
#include "../../EmojicodeReal-TimeEngine/Thread.hpp"
#include "../../EmojicodeReal-TimeEngine/String.h"
#include "../../EmojicodeReal-TimeEngine/standard.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
using Emojicode::Thread;
using Emojicode::Value;
using Emojicode::String;
using Emojicode::Data;
using Emojicode::stringToCString;
static Emojicode::Class *CL_SOCKET;
void serverInitWithPort(Thread *thread, Value *destination) {
int listenerDescriptor = socket(PF_INET, SOCK_STREAM, 0);
if (listenerDescriptor == -1) {
destination->makeNothingness();
return;
}
struct sockaddr_in name;
name.sin_family = PF_INET;
name.sin_port = htons(thread->getVariable(0).raw);
name.sin_addr.s_addr = htonl(INADDR_ANY);
int reuse = 1;
if (setsockopt(listenerDescriptor, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(int)) == -1 ||
bind(listenerDescriptor, (struct sockaddr *)&name, sizeof(name)) == -1 ||
listen(listenerDescriptor, 10) == -1) {
destination->makeNothingness();
return;
}
*(int *)thread->getThisObject()->value = listenerDescriptor;
destination->optionalSet(thread->getThisObject());
}
void serverAccept(Thread *thread, Value *destination) {
int listenerDescriptor = *(int *)thread->getThisObject()->value;
struct sockaddr_storage clientAddress;
unsigned int addressSize = sizeof(clientAddress);
int connectionAddress = accept(listenerDescriptor, (struct sockaddr *)&clientAddress, &addressSize);
if (connectionAddress == -1) {
destination->makeNothingness();
return;
}
Emojicode::Object *socket = newObject(CL_SOCKET);
*(int *)socket->value = connectionAddress;
destination->optionalSet(socket);
}
void socketSendData(Thread *thread, Value *destination) {
int connectionAddress = *(int *)thread->getThisObject()->value;
Data *data = static_cast<Data *>(thread->getVariable(0).object->value);
destination->raw = send(connectionAddress, data->bytes, data->length, 0) == -1;
}
void socketClose(Thread *thread, Value *destination) {
int connectionAddress = *(int *)thread->getThisObject()->value;
close(connectionAddress);
}
void socketReadBytes(Thread *thread, Value *destination) {
int connectionAddress = *(int *)thread->getThisObject()->value;
Emojicode::EmojicodeInteger n = thread->getVariable(0).raw;
Emojicode::Object *const &bytesObject = Emojicode::newArray(n);
size_t read = recv(connectionAddress, bytesObject->value, n, 0);
if (read < 1) {
thread->release(1);
destination->makeNothingness();
return;
}
Emojicode::Object *obj = newObject(Emojicode::CL_DATA);
Data *data = static_cast<Data *>(obj->value);
data->length = read;
data->bytesObject = bytesObject;
data->bytes = static_cast<char *>(data->bytesObject->value);
thread->release(1);
destination->optionalSet(obj);
}
void socketInitWithHost(Thread *thread, Value *destination) {
struct hostent *server = gethostbyname(Emojicode::stringToCString(thread->getVariable(0).object));
if (!server) {
destination->makeNothingness();
return;
}
struct sockaddr_in address;
memset(&address, 0, sizeof(address));
memcpy(&address.sin_addr.s_addr, server->h_addr_list[0], server->h_length);
address.sin_family = PF_INET;
address.sin_port = htons(thread->getVariable(1).raw);
int socketDescriptor = socket(AF_INET, SOCK_STREAM, 0);
if (socketDescriptor == -1 || connect(socketDescriptor, (struct sockaddr *) &address, sizeof(address)) == -1) {
destination->makeNothingness();
return;
}
*(int *)thread->getThisObject()->value = socketDescriptor;
destination->optionalSet(thread->getThisObject());
}
void socketDestruct(void *d) {
close(*(int *)d);
}
Emojicode::PackageVersion version(0, 1);
LinkingTable {
nullptr,
serverAccept,
socketSendData,
socketClose,
socketReadBytes,
socketInitWithHost,
serverInitWithPort,
};
extern "C" Emojicode::Marker markerPointerForClass(EmojicodeChar cl) {
return NULL;
}
extern "C" uint_fast32_t sizeForClass(Emojicode::Class *cl, EmojicodeChar name) {
switch (name) {
case 0x1f3c4: //🏄
return sizeof(int);
case 0x1f4de: //📞
CL_SOCKET = cl;
return sizeof(int);
}
return 0;
}
<commit_msg>😦 Retain array<commit_after>//
// sockets.c
// Packages
//
// Created by Theo Weidmann on 06.07.2016.
// Copyright (c) 2016 Theo Weidmann. All rights reserved.
//
#include "../../EmojicodeReal-TimeEngine/EmojicodeAPI.hpp"
#include "../../EmojicodeReal-TimeEngine/Thread.hpp"
#include "../../EmojicodeReal-TimeEngine/String.h"
#include "../../EmojicodeReal-TimeEngine/standard.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
using Emojicode::Thread;
using Emojicode::Value;
using Emojicode::String;
using Emojicode::Data;
using Emojicode::stringToCString;
static Emojicode::Class *CL_SOCKET;
void serverInitWithPort(Thread *thread, Value *destination) {
int listenerDescriptor = socket(PF_INET, SOCK_STREAM, 0);
if (listenerDescriptor == -1) {
destination->makeNothingness();
return;
}
struct sockaddr_in name;
name.sin_family = PF_INET;
name.sin_port = htons(thread->getVariable(0).raw);
name.sin_addr.s_addr = htonl(INADDR_ANY);
int reuse = 1;
if (setsockopt(listenerDescriptor, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(int)) == -1 ||
bind(listenerDescriptor, (struct sockaddr *)&name, sizeof(name)) == -1 ||
listen(listenerDescriptor, 10) == -1) {
destination->makeNothingness();
return;
}
*(int *)thread->getThisObject()->value = listenerDescriptor;
destination->optionalSet(thread->getThisObject());
}
void serverAccept(Thread *thread, Value *destination) {
int listenerDescriptor = *(int *)thread->getThisObject()->value;
struct sockaddr_storage clientAddress;
unsigned int addressSize = sizeof(clientAddress);
int connectionAddress = accept(listenerDescriptor, (struct sockaddr *)&clientAddress, &addressSize);
if (connectionAddress == -1) {
destination->makeNothingness();
return;
}
Emojicode::Object *socket = newObject(CL_SOCKET);
*(int *)socket->value = connectionAddress;
destination->optionalSet(socket);
}
void socketSendData(Thread *thread, Value *destination) {
int connectionAddress = *(int *)thread->getThisObject()->value;
Data *data = static_cast<Data *>(thread->getVariable(0).object->value);
destination->raw = send(connectionAddress, data->bytes, data->length, 0) == -1;
}
void socketClose(Thread *thread, Value *destination) {
int connectionAddress = *(int *)thread->getThisObject()->value;
close(connectionAddress);
}
void socketReadBytes(Thread *thread, Value *destination) {
int connectionAddress = *(int *)thread->getThisObject()->value;
Emojicode::EmojicodeInteger n = thread->getVariable(0).raw;
Emojicode::Object *const &bytesObject = thread->retain(Emojicode::newArray(n));
size_t read = recv(connectionAddress, bytesObject->value, n, 0);
if (read < 1) {
thread->release(1);
destination->makeNothingness();
return;
}
Emojicode::Object *obj = newObject(Emojicode::CL_DATA);
Data *data = static_cast<Data *>(obj->value);
data->length = read;
data->bytesObject = bytesObject;
data->bytes = static_cast<char *>(data->bytesObject->value);
thread->release(1);
destination->optionalSet(obj);
}
void socketInitWithHost(Thread *thread, Value *destination) {
struct hostent *server = gethostbyname(Emojicode::stringToCString(thread->getVariable(0).object));
if (!server) {
destination->makeNothingness();
return;
}
struct sockaddr_in address;
memset(&address, 0, sizeof(address));
memcpy(&address.sin_addr.s_addr, server->h_addr_list[0], server->h_length);
address.sin_family = PF_INET;
address.sin_port = htons(thread->getVariable(1).raw);
int socketDescriptor = socket(AF_INET, SOCK_STREAM, 0);
if (socketDescriptor == -1 || connect(socketDescriptor, (struct sockaddr *) &address, sizeof(address)) == -1) {
destination->makeNothingness();
return;
}
*(int *)thread->getThisObject()->value = socketDescriptor;
destination->optionalSet(thread->getThisObject());
}
void socketDestruct(void *d) {
close(*(int *)d);
}
Emojicode::PackageVersion version(0, 1);
LinkingTable {
nullptr,
serverAccept,
socketSendData,
socketClose,
socketReadBytes,
socketInitWithHost,
serverInitWithPort,
};
extern "C" Emojicode::Marker markerPointerForClass(EmojicodeChar cl) {
return NULL;
}
extern "C" uint_fast32_t sizeForClass(Emojicode::Class *cl, EmojicodeChar name) {
switch (name) {
case 0x1f3c4: //🏄
return sizeof(int);
case 0x1f4de: //📞
CL_SOCKET = cl;
return sizeof(int);
}
return 0;
}
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file whisperMessage.cpp
* @author Vladislav Gluhovsky <vlad@ethdev.com>
* @date May 2015
*/
#include <boost/test/unit_test.hpp>
#include <libwhisper/Message.h>
using namespace std;
using namespace dev;
using namespace dev::shh;
struct VerbosityHolder
{
VerbosityHolder(int _temporaryValue) : oldLogVerbosity(g_logVerbosity) { g_logVerbosity = _temporaryValue; }
~VerbosityHolder() { g_logVerbosity = oldLogVerbosity; }
int oldLogVerbosity;
};
Topics createRandomTopics(unsigned int i)
{
Topics ret;
h256 t(i);
for (int j = 0; j < 8; ++j)
{
t = sha3(t);
ret.push_back(t);
}
return move(ret);
}
bytes createRandomPayload(unsigned int i)
{
bytes ret;
srand(i);
int const sz = rand() % 1024;
for (int j = 0; j < sz; ++j)
ret.push_back(rand() % 256);
return move(ret);
}
void comparePayloads(Message const& m1, Message const& m2)
{
bytes const& p1 = m1.payload();
bytes const& p2 = m2.payload();
BOOST_REQUIRE_EQUAL(p1.size(), p2.size());
for (size_t i = 0; i < p1.size(); ++i)
BOOST_REQUIRE_EQUAL(p1[i], p2[i]);
}
void sealAndOpenSingleMessage(unsigned int i)
{
Secret zero;
Topics topics = createRandomTopics(i);
bytes const payload = createRandomPayload(i);
Message m1(payload);
Envelope e = m1.seal(zero, topics, 1, 1);
for (auto const& t: topics)
{
Topics singleTopic;
singleTopic.push_back(t);
Message m2(e, singleTopic, zero);
comparePayloads(m1, m2);
}
}
BOOST_AUTO_TEST_SUITE(whisperMessage)
BOOST_AUTO_TEST_CASE(seal)
{
VerbosityHolder setTemporaryLevel(10);
cnote << "Testing Envelope encryption...";
for (unsigned int i = 1; i < 10; ++i)
sealAndOpenSingleMessage(i);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>fixed peer test<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file whisperMessage.cpp
* @author Vladislav Gluhovsky <vlad@ethdev.com>
* @date May 2015
*/
#include <boost/test/unit_test.hpp>
#include <libwhisper/Message.h>
using namespace std;
using namespace dev;
using namespace dev::shh;
Topics createRandomTopics(unsigned int i)
{
Topics ret;
h256 t(i);
for (int j = 0; j < 8; ++j)
{
t = sha3(t);
ret.push_back(t);
}
return move(ret);
}
bytes createRandomPayload(unsigned int i)
{
bytes ret;
srand(i);
int const sz = rand() % 1024;
for (int j = 0; j < sz; ++j)
ret.push_back(rand() % 256);
return move(ret);
}
void comparePayloads(Message const& m1, Message const& m2)
{
bytes const& p1 = m1.payload();
bytes const& p2 = m2.payload();
BOOST_REQUIRE_EQUAL(p1.size(), p2.size());
for (size_t i = 0; i < p1.size(); ++i)
BOOST_REQUIRE_EQUAL(p1[i], p2[i]);
}
void sealAndOpenSingleMessage(unsigned int i)
{
Secret zero;
Topics topics = createRandomTopics(i);
bytes const payload = createRandomPayload(i);
Message m1(payload);
Envelope e = m1.seal(zero, topics, 1, 1);
for (auto const& t: topics)
{
Topics singleTopic;
singleTopic.push_back(t);
Message m2(e, singleTopic, zero);
comparePayloads(m1, m2);
}
}
BOOST_AUTO_TEST_SUITE(whisperMessage)
BOOST_AUTO_TEST_CASE(seal)
{
VerbosityHolder setTemporaryLevel(10);
cnote << "Testing Envelope encryption...";
for (unsigned int i = 1; i < 10; ++i)
sealAndOpenSingleMessage(i);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include "../NULLC/nullc.h"
#if defined(_MSC_VER)
#pragma warning(disable: 4996)
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char* translationDependencies[128];
unsigned translationDependencyCount = 0;
void AddDependency(const char *fileName)
{
if(translationDependencyCount < 128)
translationDependencies[translationDependencyCount++] = fileName;
}
int main(int argc, char** argv)
{
nullcInit();
nullcAddImportPath("Modules/");
if(argc == 1)
{
printf("usage: nullcl [-o output.ncm] file.nc [-m module.name] [file2.nc [-m module.name] ...]\n");
printf("usage: nullcl -c output.cpp file.nc\n");
printf("usage: nullcl -x output.exe file.nc\n");
return 1;
}
int argIndex = 1;
FILE *mergeFile = NULL;
if(strcmp("-o", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 1;
}
mergeFile = fopen(argv[argIndex], "wb");
if(!mergeFile)
{
printf("Cannot create output file %s\n", argv[argIndex]);
nullcTerminate();
return 1;
}
argIndex++;
}else if(strcmp("-c", argv[argIndex]) == 0 || strcmp("-x", argv[argIndex]) == 0){
bool link = strcmp("-x", argv[argIndex]) == 0;
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 1;
}
const char *outputName = argv[argIndex++];
if(argIndex == argc)
{
printf("Input file name not found\n");
nullcTerminate();
return 1;
}
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
nullcTerminate();
return 1;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
if(!nullcTranslateToC(link ? "__temp.cpp" : outputName, "main", AddDependency))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
if(link)
{
// $$$ move this to a dependency file?
char cmdLine[4096];
char *pos = cmdLine;
strcpy(pos, "gcc -g -o ");
pos += strlen(pos);
strcpy(pos, outputName);
pos += strlen(pos);
strcpy(pos, " __temp.cpp");
pos += strlen(pos);
strcpy(pos, " -lstdc++");
pos += strlen(pos);
char tmp[256];
sprintf(tmp, "runtime.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
else
{
sprintf(tmp, "translation/runtime.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
}
for(unsigned i = 0; i < translationDependencyCount; i++)
{
const char *dependency = translationDependencies[i];
*(pos++) = ' ';
strcpy(pos, dependency);
pos += strlen(pos);
if(strstr(dependency, "import_"))
{
sprintf(tmp, "%s", dependency + strlen("import_"));
if(char *pos = strstr(tmp, "_nc.cpp"))
strcpy(pos, "_bind.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
else
{
sprintf(tmp, "translation/%s", dependency + strlen("import_"));
if(char *pos = strstr(tmp, "_nc.cpp"))
strcpy(pos, "_bind.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
}
}
}
printf("Command line: %s\n", cmdLine);
system(cmdLine);
}
delete[] fileContent;
nullcTerminate();
return 0;
}
int currIndex = argIndex;
while(argIndex < argc)
{
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
break;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
unsigned int *bytecode = NULL;
nullcGetBytecode((char**)&bytecode);
delete[] fileContent;
// Create module name
char moduleName[1024];
if(argIndex < argc && strcmp("-m", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Module name not found after -m\n");
break;
}
if(strlen(argv[argIndex]) + 1 >= 1024)
{
printf("Module name is too long\n");
break;
}
strcpy(moduleName, argv[argIndex]);
argIndex++;
}
else
{
if(strlen(fileName) + 1 >= 1024)
{
printf("File name is too long\n");
break;
}
strcpy(moduleName, fileName);
if(char *extensionPos = strchr(moduleName, '.'))
*extensionPos = '\0';
char *pos = moduleName;
while(*pos)
{
if(*pos++ == '\\' || *pos++ == '/')
pos[-1] = '.';
}
}
nullcLoadModuleByBinary(moduleName, (const char*)bytecode);
if(!mergeFile)
{
char newName[1024];
// Ont extra character for 'm' appended at the end
if(strlen(fileName) + 1 >= 1024 - 1)
{
printf("File name is too long\n");
break;
}
strcpy(newName, fileName);
strcat(newName, "m");
FILE *nmcFile = fopen(newName, "wb");
if(!nmcFile)
{
printf("Cannot create output file %s\n", newName);
break;
}
fwrite(moduleName, 1, strlen(moduleName) + 1, nmcFile);
fwrite(bytecode, 1, *bytecode, nmcFile);
fclose(nmcFile);
}else{
fwrite(moduleName, 1, strlen(moduleName) + 1, mergeFile);
fwrite(bytecode, 1, *bytecode, mergeFile);
}
}
if(currIndex == argIndex)
printf("None of the input files were found\n");
if(mergeFile)
fclose(mergeFile);
nullcTerminate();
return argIndex != argc;
}
<commit_msg>Fixed translation to C in nullcl: header and source file search improvement<commit_after>#include "../NULLC/nullc.h"
#if defined(_MSC_VER)
#pragma warning(disable: 4996)
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char* translationDependencies[128];
unsigned translationDependencyCount = 0;
void AddDependency(const char *fileName)
{
if(translationDependencyCount < 128)
translationDependencies[translationDependencyCount++] = fileName;
}
bool AddSourceFile(char *&buf, const char *name)
{
if(FILE *file = fopen(name, "r"))
{
*(buf++) = ' ';
strcpy(buf, name);
buf += strlen(buf);
fclose(file);
return true;
}
return false;
}
bool SearchAndAddSourceFile(char*& buf, const char* name)
{
char tmp[256];
sprintf(tmp, "%s", name);
if(AddSourceFile(buf, tmp))
return true;
sprintf(tmp, "translation/%s", name);
if(AddSourceFile(buf, tmp))
return true;
sprintf(tmp, "../NULLC/translation/%s", name);
if(AddSourceFile(buf, tmp))
return true;
return false;
}
int main(int argc, char** argv)
{
nullcInit();
nullcAddImportPath("Modules/");
if(argc == 1)
{
printf("usage: nullcl [-o output.ncm] file.nc [-m module.name] [file2.nc [-m module.name] ...]\n");
printf("usage: nullcl -c output.cpp file.nc\n");
printf("usage: nullcl -x output.exe file.nc\n");
return 1;
}
int argIndex = 1;
FILE *mergeFile = NULL;
bool verbose = false;
if(strcmp("-v", argv[argIndex]) == 0)
{
argIndex++;
verbose = true;
}
if(strcmp("-o", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 1;
}
mergeFile = fopen(argv[argIndex], "wb");
if(!mergeFile)
{
printf("Cannot create output file %s\n", argv[argIndex]);
nullcTerminate();
return 1;
}
argIndex++;
}else if(strcmp("-c", argv[argIndex]) == 0 || strcmp("-x", argv[argIndex]) == 0){
bool link = strcmp("-x", argv[argIndex]) == 0;
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 1;
}
const char *outputName = argv[argIndex++];
if(argIndex == argc)
{
printf("Input file name not found\n");
nullcTerminate();
return 1;
}
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
nullcTerminate();
return 1;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
if(!nullcTranslateToC(link ? "__temp.cpp" : outputName, "main", AddDependency))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
if(link)
{
// $$$ move this to a dependency file?
char cmdLine[4096];
char *pos = cmdLine;
strcpy(pos, "gcc -g -o ");
pos += strlen(pos);
strcpy(pos, outputName);
pos += strlen(pos);
strcpy(pos, " __temp.cpp");
pos += strlen(pos);
strcpy(pos, " -lstdc++");
pos += strlen(pos);
strcpy(pos, " -Itranslation");
pos += strlen(pos);
strcpy(pos, " -I../NULLC/translation");
pos += strlen(pos);
strcpy(pos, " -O2");
pos += strlen(pos);
if(!SearchAndAddSourceFile(pos, "runtime.cpp"))
printf("Failed to find 'runtime.cpp' input file");
for(unsigned i = 0; i < translationDependencyCount; i++)
{
const char *dependency = translationDependencies[i];
*(pos++) = ' ';
strcpy(pos, dependency);
pos += strlen(pos);
if(strstr(dependency, "import_"))
{
char tmp[256];
sprintf(tmp, "%s", dependency + strlen("import_"));
if(char *pos = strstr(tmp, "_nc.cpp"))
strcpy(pos, "_bind.cpp");
if(!SearchAndAddSourceFile(pos, tmp))
printf("Failed to find '%s' input file", tmp);
}
}
if (verbose)
printf("Command line: %s\n", cmdLine);
system(cmdLine);
}
delete[] fileContent;
nullcTerminate();
return 0;
}
int currIndex = argIndex;
while(argIndex < argc)
{
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
break;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
unsigned int *bytecode = NULL;
nullcGetBytecode((char**)&bytecode);
delete[] fileContent;
// Create module name
char moduleName[1024];
if(argIndex < argc && strcmp("-m", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Module name not found after -m\n");
break;
}
if(strlen(argv[argIndex]) + 1 >= 1024)
{
printf("Module name is too long\n");
break;
}
strcpy(moduleName, argv[argIndex]);
argIndex++;
}
else
{
if(strlen(fileName) + 1 >= 1024)
{
printf("File name is too long\n");
break;
}
strcpy(moduleName, fileName);
if(char *extensionPos = strchr(moduleName, '.'))
*extensionPos = '\0';
char *pos = moduleName;
while(*pos)
{
if(*pos++ == '\\' || *pos++ == '/')
pos[-1] = '.';
}
}
nullcLoadModuleByBinary(moduleName, (const char*)bytecode);
if(!mergeFile)
{
char newName[1024];
// Ont extra character for 'm' appended at the end
if(strlen(fileName) + 1 >= 1024 - 1)
{
printf("File name is too long\n");
break;
}
strcpy(newName, fileName);
strcat(newName, "m");
FILE *nmcFile = fopen(newName, "wb");
if(!nmcFile)
{
printf("Cannot create output file %s\n", newName);
break;
}
fwrite(moduleName, 1, strlen(moduleName) + 1, nmcFile);
fwrite(bytecode, 1, *bytecode, nmcFile);
fclose(nmcFile);
}else{
fwrite(moduleName, 1, strlen(moduleName) + 1, mergeFile);
fwrite(bytecode, 1, *bytecode, mergeFile);
}
}
if(currIndex == argIndex)
printf("None of the input files were found\n");
if(mergeFile)
fclose(mergeFile);
nullcTerminate();
return argIndex != argc;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: binaryreader.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2003-06-04 10:19:04 $
*
* 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 CONFIGMGR_BINARYREADER_HXX
#define CONFIGMGR_BINARYREADER_HXX
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_IOEXCEPTION_HPP_
#include <com/sun/star/io/IOException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XDATAINPUTSTREAM_HPP_
#include <com/sun/star/io/XDataInputStream.hpp>
#endif
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace backend
{
namespace css = com::sun::star;
namespace io = css::io;
namespace uno = css::uno;
namespace lang = css::lang;
typedef uno::Reference<lang::XMultiServiceFactory> MultiServiceFactory;
// -----------------------------------------------------------------------------
class BinaryReader
{
rtl::OUString m_sFileURL;
uno::Reference<io::XDataInputStream> m_xDataInputStream;
public:
explicit BinaryReader (rtl::OUString const & _sFileURL)
: m_sFileURL(_sFileURL)
{}
~BinaryReader()
{}
public:
bool open() SAL_THROW( (io::IOException, uno::RuntimeException) );
void reopen() SAL_THROW( (io::IOException, uno::RuntimeException) );
void close() SAL_THROW( (io::IOException, uno::RuntimeException) );
typedef uno::Sequence< sal_Int8 > Binary;
void read(sal_Bool &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );
void read(sal_Int8 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );
void read(sal_Int16 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );
void read(sal_Int32 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );
void read(sal_Int64 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );
void read(double &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );
void read(rtl::OUString& _aStr) SAL_THROW( (io::IOException, uno::RuntimeException) );
void read(Binary &_aValue) SAL_THROW( (io::IOException, uno::RuntimeException) );
private:
inline uno::Reference<io::XDataInputStream> getDataInputStream();
};
// --------------------------------------------------------------------------
bool readSequenceValue (
BinaryReader & _rReader,
uno::Any & _aValue,
uno::Type const & _aElementType) SAL_THROW( (io::IOException, uno::RuntimeException) );
// --------------------------------------------------------------------------
}
}
#endif<commit_msg>INTEGRATION: CWS rt02 (1.3.20); FILE MERGED 2003/10/01 13:15:17 rt 1.3.20.1: #i19697# Fixed compiler warnings<commit_after>/*************************************************************************
*
* $RCSfile: binaryreader.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2003-10-06 14:45:01 $
*
* 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 CONFIGMGR_BINARYREADER_HXX
#define CONFIGMGR_BINARYREADER_HXX
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_IOEXCEPTION_HPP_
#include <com/sun/star/io/IOException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XDATAINPUTSTREAM_HPP_
#include <com/sun/star/io/XDataInputStream.hpp>
#endif
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace backend
{
namespace css = com::sun::star;
namespace io = css::io;
namespace uno = css::uno;
namespace lang = css::lang;
typedef uno::Reference<lang::XMultiServiceFactory> MultiServiceFactory;
// -----------------------------------------------------------------------------
class BinaryReader
{
rtl::OUString m_sFileURL;
uno::Reference<io::XDataInputStream> m_xDataInputStream;
public:
explicit BinaryReader (rtl::OUString const & _sFileURL)
: m_sFileURL(_sFileURL)
{}
~BinaryReader()
{}
public:
bool open() SAL_THROW( (io::IOException, uno::RuntimeException) );
void reopen() SAL_THROW( (io::IOException, uno::RuntimeException) );
void close() SAL_THROW( (io::IOException, uno::RuntimeException) );
typedef uno::Sequence< sal_Int8 > Binary;
void read(sal_Bool &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );
void read(sal_Int8 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );
void read(sal_Int16 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );
void read(sal_Int32 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );
void read(sal_Int64 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );
void read(double &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );
void read(rtl::OUString& _aStr) SAL_THROW( (io::IOException, uno::RuntimeException) );
void read(Binary &_aValue) SAL_THROW( (io::IOException, uno::RuntimeException) );
private:
inline uno::Reference<io::XDataInputStream> getDataInputStream();
};
// --------------------------------------------------------------------------
bool readSequenceValue (
BinaryReader & _rReader,
uno::Any & _aValue,
uno::Type const & _aElementType) SAL_THROW( (io::IOException, uno::RuntimeException) );
// --------------------------------------------------------------------------
}
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: Blob.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2005-02-16 17:27:13 $
*
* 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 _CONNECTIVITY_JAVA_SQL_BLOB_HXX_
#include "java/sql/Blob.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_IO_INPUTSTREAM_HXX_
#include "java/io/InputStream.hxx"
#endif
#ifndef _INC_MEMORY
//#include <memory.h>
#endif
using namespace connectivity;
//**************************************************************
//************ Class: java.sql.Blob
//**************************************************************
jclass java_sql_Blob::theClass = 0;
java_sql_Blob::java_sql_Blob( JNIEnv * pEnv, jobject myObj )
: java_lang_Object( pEnv, myObj )
{
SDBThreadAttach::addRef();
}
java_sql_Blob::~java_sql_Blob()
{
SDBThreadAttach::releaseRef();
}
jclass java_sql_Blob::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t;
if( !t.pEnv ) return (jclass)NULL;
jclass tempClass = t.pEnv->FindClass( "java/sql/Blob" );
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
void java_sql_Blob::saveClassRef( jclass pClass )
{
if( pClass==NULL )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
sal_Int64 SAL_CALL java_sql_Blob::length( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
jlong out(0);
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
if( t.pEnv )
{
// temporaere Variable initialisieren
static char * cSignature = "()J";
static char * cMethodName = "length";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallLongMethod( object, mID );
ThrowSQLException(t.pEnv,*this);
// und aufraeumen
} //mID
} //t.pEnv
return (sal_Int64)out;
}
::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL java_sql_Blob::getBytes( sal_Int64 pos, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
::com::sun::star::uno::Sequence< sal_Int8 > aSeq;
if( t.pEnv ){
// temporaere Variable initialisieren
static char * cSignature = "(JI)[B";
static char * cMethodName = "getBytes";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
jbyteArray out = (jbyteArray)t.pEnv->CallObjectMethod( object, mID,pos,length);
ThrowSQLException(t.pEnv,*this);
if(out)
{
jboolean p = sal_False;
aSeq.realloc(t.pEnv->GetArrayLength(out));
memcpy(aSeq.getArray(),t.pEnv->GetByteArrayElements(out,&p),aSeq.getLength());
t.pEnv->DeleteLocalRef(out);
}
// und aufraeumen
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return aSeq;
}
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL java_sql_Blob::getBinaryStream( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
jobject out(0);
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
if( t.pEnv ){
// temporaere Variable initialisieren
static char * cSignature = "()Ljava/io/InputStream;";
static char * cMethodName = "getBinaryStream";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,*this);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return out==0 ? 0 : new java_io_InputStream( t.pEnv, out );
}
sal_Int64 SAL_CALL java_sql_Blob::position( const ::com::sun::star::uno::Sequence< sal_Int8 >& pattern, sal_Int64 start ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
jlong out(0);
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
if( t.pEnv )
{
// temporaere Variable initialisieren
static char * cSignature = "([BI)J";
static char * cMethodName = "position";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
// Parameter konvertieren
jbyteArray pByteArray = t.pEnv->NewByteArray(pattern.getLength());
t.pEnv->SetByteArrayRegion(pByteArray,0,pattern.getLength(),(jbyte*)pattern.getConstArray());
out = t.pEnv->CallLongMethod( object, mID, pByteArray,start );
t.pEnv->DeleteLocalRef(pByteArray);
ThrowSQLException(t.pEnv,*this);
// und aufraeumen
} //mID
} //t.pEnv
return (sal_Int64)out;
}
sal_Int64 SAL_CALL java_sql_Blob::positionOfBlob( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& pattern, sal_Int64 start ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
jlong out(0);
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
if( t.pEnv )
{
// temporaere Variable initialisieren
static char * cSignature = "(Ljava/sql/Blob;I)J";
static char * cMethodName = "positionOfBlob";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallLongMethod( object, mID,0,start );
ThrowSQLException(t.pEnv,*this);
// und aufraeumen
} //mID
} //t.pEnv
return (sal_Int64)out;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.78); FILE MERGED 2005/09/05 17:24:09 rt 1.7.78.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Blob.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-08 06:07: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 _CONNECTIVITY_JAVA_SQL_BLOB_HXX_
#include "java/sql/Blob.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_IO_INPUTSTREAM_HXX_
#include "java/io/InputStream.hxx"
#endif
#ifndef _INC_MEMORY
//#include <memory.h>
#endif
using namespace connectivity;
//**************************************************************
//************ Class: java.sql.Blob
//**************************************************************
jclass java_sql_Blob::theClass = 0;
java_sql_Blob::java_sql_Blob( JNIEnv * pEnv, jobject myObj )
: java_lang_Object( pEnv, myObj )
{
SDBThreadAttach::addRef();
}
java_sql_Blob::~java_sql_Blob()
{
SDBThreadAttach::releaseRef();
}
jclass java_sql_Blob::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t;
if( !t.pEnv ) return (jclass)NULL;
jclass tempClass = t.pEnv->FindClass( "java/sql/Blob" );
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
void java_sql_Blob::saveClassRef( jclass pClass )
{
if( pClass==NULL )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
sal_Int64 SAL_CALL java_sql_Blob::length( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
jlong out(0);
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
if( t.pEnv )
{
// temporaere Variable initialisieren
static char * cSignature = "()J";
static char * cMethodName = "length";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallLongMethod( object, mID );
ThrowSQLException(t.pEnv,*this);
// und aufraeumen
} //mID
} //t.pEnv
return (sal_Int64)out;
}
::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL java_sql_Blob::getBytes( sal_Int64 pos, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
::com::sun::star::uno::Sequence< sal_Int8 > aSeq;
if( t.pEnv ){
// temporaere Variable initialisieren
static char * cSignature = "(JI)[B";
static char * cMethodName = "getBytes";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
jbyteArray out = (jbyteArray)t.pEnv->CallObjectMethod( object, mID,pos,length);
ThrowSQLException(t.pEnv,*this);
if(out)
{
jboolean p = sal_False;
aSeq.realloc(t.pEnv->GetArrayLength(out));
memcpy(aSeq.getArray(),t.pEnv->GetByteArrayElements(out,&p),aSeq.getLength());
t.pEnv->DeleteLocalRef(out);
}
// und aufraeumen
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return aSeq;
}
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL java_sql_Blob::getBinaryStream( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
jobject out(0);
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
if( t.pEnv ){
// temporaere Variable initialisieren
static char * cSignature = "()Ljava/io/InputStream;";
static char * cMethodName = "getBinaryStream";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,*this);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return out==0 ? 0 : new java_io_InputStream( t.pEnv, out );
}
sal_Int64 SAL_CALL java_sql_Blob::position( const ::com::sun::star::uno::Sequence< sal_Int8 >& pattern, sal_Int64 start ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
jlong out(0);
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
if( t.pEnv )
{
// temporaere Variable initialisieren
static char * cSignature = "([BI)J";
static char * cMethodName = "position";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
// Parameter konvertieren
jbyteArray pByteArray = t.pEnv->NewByteArray(pattern.getLength());
t.pEnv->SetByteArrayRegion(pByteArray,0,pattern.getLength(),(jbyte*)pattern.getConstArray());
out = t.pEnv->CallLongMethod( object, mID, pByteArray,start );
t.pEnv->DeleteLocalRef(pByteArray);
ThrowSQLException(t.pEnv,*this);
// und aufraeumen
} //mID
} //t.pEnv
return (sal_Int64)out;
}
sal_Int64 SAL_CALL java_sql_Blob::positionOfBlob( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& pattern, sal_Int64 start ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
jlong out(0);
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
if( t.pEnv )
{
// temporaere Variable initialisieren
static char * cSignature = "(Ljava/sql/Blob;I)J";
static char * cMethodName = "positionOfBlob";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallLongMethod( object, mID,0,start );
ThrowSQLException(t.pEnv,*this);
// und aufraeumen
} //mID
} //t.pEnv
return (sal_Int64)out;
}
<|endoftext|> |
<commit_before>#include <silicium/config.hpp>
#include <boost/test/unit_test.hpp>
namespace dsl
{
namespace detail
{
template <class Type, class Name>
struct memory_variable
{
Type &location;
};
template <class Memory, class Name>
struct access;
template <class Type, class Name>
struct access<memory_variable<Type, Name>, Name>
{
Type &operator()(memory_variable<Type, Name> &memory) const
{
return memory.location;
}
};
}
template <class Variables, class EntryPoint>
struct program
{
EntryPoint entry_point;
template <class Parameter, class Argument>
void operator()(Parameter, Argument argument) const
{
detail::memory_variable<Argument, Parameter> memory{argument};
entry_point.evaluate(memory);
}
};
template <class FirstExpression, class SecondExpression>
struct sequence
{
FirstExpression first;
SecondExpression second;
template <class Memory>
void evaluate(Memory memory) const
{
first.evaluate(memory);
second.evaluate(memory);
}
};
template <class Type, class Name, bool HasValue>
struct variable
{
};
namespace detail
{
template <class Argument>
struct ref_expression
{
template <class Memory>
auto &evaluate(Memory memory) const
{
return access<Memory, Argument>()(memory);
}
};
template <class Argument>
struct move_expression
{
template <class Memory>
auto evaluate(Memory memory) const
{
return std::move(access<Memory, Argument>()(memory));
}
};
}
template <class Argument>
auto ref(Argument)
{
return detail::ref_expression<Argument>();
}
template <class Argument>
auto move(Argument)
{
return detail::move_expression<Argument>();
}
namespace detail
{
template <class Variables, class Argument>
struct evaluate_argument;
template <class Type, class Name, bool HasValue>
struct evaluate_argument<variable<Type, Name, HasValue>,
move_expression<Name>>
{
static_assert(HasValue, "Variable has already been moved from");
using type = variable<Type, Name, false>;
};
template <class Type, class Name, bool HasValue>
struct evaluate_argument<variable<Type, Name, HasValue>,
ref_expression<Name>>
{
static_assert(HasValue, "Variable cannot be referenced because is "
"has already been moved from");
using type = variable<Type, Name, HasValue>;
};
template <class Argument, class F>
struct call_expression
{
F f;
template <class Memory>
void evaluate(Memory memory) const
{
f(Argument().evaluate(memory));
}
};
template <class Variables, class EntryPoint, class Argument, class F>
auto operator, (program<Variables, EntryPoint> p,
call_expression<Argument, F> expression)
{
(void)expression;
return program<
typename evaluate_argument<Variables, Argument>::type,
sequence<EntryPoint, decltype(expression)>>{
{p.entry_point, std::move(expression)}};
}
}
template <class F, class Argument>
auto call(F &&f, Argument)
{
return detail::call_expression<Argument, F>{std::forward<F>(f)};
}
struct null_statement
{
template <class Memory>
void evaluate(Memory &) const
{
}
};
template <class Type, class Name>
program<variable<Type, Name, true>, null_statement> declare(Name)
{
return {};
}
}
BOOST_AUTO_TEST_CASE(dsl_test)
{
using namespace dsl;
bool called_f = false;
bool called_g = false;
auto f = [&](std::unique_ptr<int> &value)
{
BOOST_REQUIRE(!called_f);
BOOST_REQUIRE(!called_g);
called_f = true;
BOOST_REQUIRE_EQUAL(123, *value);
};
auto g = [&](std::unique_ptr<int> value)
{
BOOST_REQUIRE(called_f);
BOOST_REQUIRE(!called_g);
BOOST_REQUIRE_EQUAL(123, *value);
called_g = true;
};
struct
{
} x;
auto h = (declare<std::unique_ptr<int>>(x), //
call(f, ref(x)), //
call(g, move(x)));
BOOST_REQUIRE(!called_f);
BOOST_REQUIRE(!called_g);
h(x, std::make_unique<int>(123));
BOOST_REQUIRE(called_f);
BOOST_REQUIRE(called_g);
}
<commit_msg>port to GCC<commit_after>#include <silicium/config.hpp>
#include <boost/test/unit_test.hpp>
namespace dsl
{
namespace detail
{
template <class Type, class Name>
struct memory_variable
{
Type &location;
};
template <class Memory, class Name>
struct access;
template <class Type, class Name>
struct access<memory_variable<Type, Name>, Name>
{
Type &operator()(memory_variable<Type, Name> &memory) const
{
return memory.location;
}
};
}
template <class Variables, class EntryPoint>
struct program
{
EntryPoint entry_point;
template <class Parameter, class Argument>
void operator()(Parameter, Argument argument) const
{
detail::memory_variable<Argument, Parameter> memory{argument};
entry_point.evaluate(memory);
}
};
template <class FirstExpression, class SecondExpression>
struct sequence
{
FirstExpression first;
SecondExpression second;
template <class Memory>
void evaluate(Memory memory) const
{
first.evaluate(memory);
second.evaluate(memory);
}
};
template <class Type, class Name, bool HasValue>
struct variable
{
};
namespace detail
{
template <class Argument>
struct ref_expression
{
template <class Memory>
auto &evaluate(Memory memory) const
{
return access<Memory, Argument>()(memory);
}
};
template <class Argument>
struct move_expression
{
template <class Memory>
auto evaluate(Memory memory) const
{
return std::move(access<Memory, Argument>()(memory));
}
};
}
template <class Argument>
auto ref(Argument)
{
return detail::ref_expression<Argument>();
}
template <class Argument>
auto move(Argument)
{
return detail::move_expression<Argument>();
}
namespace detail
{
template <class Variables, class Argument>
struct evaluate_argument;
template <class Type, class Name, bool HasValue>
struct evaluate_argument<variable<Type, Name, HasValue>,
move_expression<Name>>
{
static_assert(HasValue, "Variable has already been moved from");
using type = variable<Type, Name, false>;
};
template <class Type, class Name, bool HasValue>
struct evaluate_argument<variable<Type, Name, HasValue>,
ref_expression<Name>>
{
static_assert(HasValue, "Variable cannot be referenced because is "
"has already been moved from");
using type = variable<Type, Name, HasValue>;
};
template <class Argument, class F>
struct call_expression
{
F f;
template <class Memory>
void evaluate(Memory memory) const
{
f(Argument().evaluate(memory));
}
};
template <class Variables, class EntryPoint, class Argument, class F>
auto operator, (program<Variables, EntryPoint> p,
call_expression<Argument, F> expression)
{
(void)expression;
return program<
typename evaluate_argument<Variables, Argument>::type,
sequence<EntryPoint, decltype(expression)>>{
{p.entry_point, std::move(expression)}};
}
}
template <class F, class Argument>
auto call(F &&f, Argument)
{
return detail::call_expression<Argument, F>{std::forward<F>(f)};
}
struct null_statement
{
template <class Memory>
void evaluate(Memory &) const
{
}
};
template <class Type, class Name>
program<variable<Type, Name, true>, null_statement> declare(Name)
{
return {
#ifndef _MSC_VER
{}, {}
#endif
};
}
}
BOOST_AUTO_TEST_CASE(dsl_test)
{
using namespace dsl;
bool called_f = false;
bool called_g = false;
auto f = [&](std::unique_ptr<int> &value)
{
BOOST_REQUIRE(!called_f);
BOOST_REQUIRE(!called_g);
called_f = true;
BOOST_REQUIRE_EQUAL(123, *value);
};
auto g = [&](std::unique_ptr<int> value)
{
BOOST_REQUIRE(called_f);
BOOST_REQUIRE(!called_g);
BOOST_REQUIRE_EQUAL(123, *value);
called_g = true;
};
struct
{
} x;
auto h = (declare<std::unique_ptr<int>>(x), //
call(f, ref(x)), //
call(g, move(x)));
BOOST_REQUIRE(!called_f);
BOOST_REQUIRE(!called_g);
h(x, std::make_unique<int>(123));
BOOST_REQUIRE(called_f);
BOOST_REQUIRE(called_g);
}
<|endoftext|> |
<commit_before><commit_msg>Fix uninitialized data error in HistoryURLProvider.<commit_after><|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// C++ includes
// Local Includes
#include "elem.h"
#include "libmesh_logging.h"
#include "mesh_base.h"
#include "mesh_tools.h"
#include "point_locator_tree.h"
#include "tree.h"
namespace libMesh
{
//------------------------------------------------------------------
// PointLocator methods
PointLocatorTree::PointLocatorTree (const MeshBase& mesh,
const PointLocatorBase* master) :
PointLocatorBase (mesh,master),
_tree (NULL),
_element (NULL),
_out_of_mesh_mode(false)
{
this->init(Trees::NODES);
}
PointLocatorTree::PointLocatorTree (const MeshBase& mesh,
const Trees::BuildType build_type,
const PointLocatorBase* master) :
PointLocatorBase (mesh,master),
_tree (NULL),
_element (NULL),
_out_of_mesh_mode(false)
{
this->init(build_type);
}
PointLocatorTree::~PointLocatorTree ()
{
this->clear ();
}
void PointLocatorTree::clear ()
{
// only delete the tree when we are the master
if (this->_tree != NULL)
{
if (this->_master == NULL)
// we own the tree
delete this->_tree;
else
// someone else owns and therefore deletes the tree
this->_tree = NULL;
}
}
void PointLocatorTree::init (const Trees::BuildType build_type)
{
libmesh_assert (this->_tree == NULL);
if (this->_initialized)
{
libMesh::err << "ERROR: Already initialized! Will ignore this call..."
<< std::endl;
}
else
{
if (this->_master == NULL)
{
START_LOG("init(no master)", "PointLocatorTree");
if (this->_mesh.mesh_dimension() == 3)
_tree = new Trees::OctTree (this->_mesh, 200, build_type);
else
{
// A 1D/2D mesh in 3D space needs special consideration.
// If the mesh is planar XY, we want to build a QuadTree
// to search efficiently. If the mesh is truly a manifold,
// then we need an octree
#if LIBMESH_DIM > 2
bool is_planar_xy = false;
// Build the bounding box for the mesh. If the delta-z bound is
// negligibly small then we can use a quadtree.
{
MeshTools::BoundingBox bbox = MeshTools::bounding_box(this->_mesh);
const Real
Dx = bbox.second(0) - bbox.first(0),
Dz = bbox.second(2) - bbox.first(2);
if (std::abs(Dz/(Dx + 1.e-20)) < 1e-10)
is_planar_xy = true;
}
if (!is_planar_xy)
_tree = new Trees::OctTree (this->_mesh, 200, build_type);
else
#endif
_tree = new Trees::QuadTree (this->_mesh, 200, build_type);
}
STOP_LOG("init(no master)", "PointLocatorTree");
}
else
{
// We are _not_ the master. Let our Tree point to
// the master's tree. But for this we first transform
// the master in a state for which we are friends.
// And make sure the master @e has a tree!
const PointLocatorTree* my_master =
libmesh_cast_ptr<const PointLocatorTree*>(this->_master);
if (my_master->initialized())
this->_tree = my_master->_tree;
else
{
libMesh::err << "ERROR: Initialize master first, then servants!"
<< std::endl;
libmesh_error();
}
}
// Not all PointLocators may own a tree, but all of them
// use their own element pointer. Let the element pointer
// be unique for every interpolator.
// Suppose the interpolators are used concurrently
// at different locations in the mesh, then it makes quite
// sense to have unique start elements.
this->_element = NULL;
}
// ready for take-off
this->_initialized = true;
}
const Elem* PointLocatorTree::operator() (const Point& p) const
{
libmesh_assert (this->_initialized);
START_LOG("operator()", "PointLocatorTree");
// First check the element from last time before asking the tree
if (this->_element==NULL || !(this->_element->contains_point(p)))
{
// ask the tree
this->_element = this->_tree->find_element (p);
if (this->_element == NULL)
{
/* No element seems to contain this point. If out-of-mesh
mode is enabled, just return NULL. If not, however, we
have to perform a linear search before we call \p
libmesh_error() since in the case of curved elements, the
bounding box computed in \p TreeNode::insert(const
Elem*) might be slightly inaccurate. */
START_LOG("linear search", "PointLocatorTree");
if(!_out_of_mesh_mode)
{
MeshBase::const_element_iterator pos = this->_mesh.active_elements_begin();
const MeshBase::const_element_iterator end_pos = this->_mesh.active_elements_end();
for ( ; pos != end_pos; ++pos)
if ((*pos)->contains_point(p))
{
STOP_LOG("linear search", "PointLocatorTree");
STOP_LOG("operator()", "PointLocatorTree");
return this->_element = (*pos);
}
if (this->_element == NULL)
{
libMesh::err << std::endl
<< " ******** Serious Problem. Could not find an Element "
<< "in the Mesh"
<< std:: endl
<< " ******** that contains the Point "
<< p;
libmesh_error();
}
}
STOP_LOG("linear search", "PointLocatorTree");
}
}
// If we found an element, it should be active
libmesh_assert (!this->_element || this->_element->active());
STOP_LOG("operator()", "PointLocatorTree");
// return the element
return this->_element;
}
void PointLocatorTree::enable_out_of_mesh_mode (void)
{
/* Out-of-mesh mode is currently only supported if all of the
elements have affine mappings. The reason is that for quadratic
mappings, it is not easy to construct a relyable bounding box of
the element, and thus, the fallback linear search in \p
operator() is required. Hence, out-of-mesh mode would be
extremely slow. */
if(!_out_of_mesh_mode)
{
#ifdef DEBUG
MeshBase::const_element_iterator pos = this->_mesh.active_elements_begin();
const MeshBase::const_element_iterator end_pos = this->_mesh.active_elements_end();
for ( ; pos != end_pos; ++pos)
if (!(*pos)->has_affine_map())
{
libMesh::err << "ERROR: Out-of-mesh mode is currently only supported if all elements have affine mappings." << std::endl;
libmesh_error();
}
#endif
_out_of_mesh_mode = true;
}
}
void PointLocatorTree::disable_out_of_mesh_mode (void)
{
_out_of_mesh_mode = false;
}
} // namespace libMesh
<commit_msg>Don't bother logging unless we're actually doing something<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// C++ includes
// Local Includes
#include "elem.h"
#include "libmesh_logging.h"
#include "mesh_base.h"
#include "mesh_tools.h"
#include "point_locator_tree.h"
#include "tree.h"
namespace libMesh
{
//------------------------------------------------------------------
// PointLocator methods
PointLocatorTree::PointLocatorTree (const MeshBase& mesh,
const PointLocatorBase* master) :
PointLocatorBase (mesh,master),
_tree (NULL),
_element (NULL),
_out_of_mesh_mode(false)
{
this->init(Trees::NODES);
}
PointLocatorTree::PointLocatorTree (const MeshBase& mesh,
const Trees::BuildType build_type,
const PointLocatorBase* master) :
PointLocatorBase (mesh,master),
_tree (NULL),
_element (NULL),
_out_of_mesh_mode(false)
{
this->init(build_type);
}
PointLocatorTree::~PointLocatorTree ()
{
this->clear ();
}
void PointLocatorTree::clear ()
{
// only delete the tree when we are the master
if (this->_tree != NULL)
{
if (this->_master == NULL)
// we own the tree
delete this->_tree;
else
// someone else owns and therefore deletes the tree
this->_tree = NULL;
}
}
void PointLocatorTree::init (const Trees::BuildType build_type)
{
libmesh_assert (this->_tree == NULL);
if (this->_initialized)
{
libMesh::err << "ERROR: Already initialized! Will ignore this call..."
<< std::endl;
}
else
{
if (this->_master == NULL)
{
START_LOG("init(no master)", "PointLocatorTree");
if (this->_mesh.mesh_dimension() == 3)
_tree = new Trees::OctTree (this->_mesh, 200, build_type);
else
{
// A 1D/2D mesh in 3D space needs special consideration.
// If the mesh is planar XY, we want to build a QuadTree
// to search efficiently. If the mesh is truly a manifold,
// then we need an octree
#if LIBMESH_DIM > 2
bool is_planar_xy = false;
// Build the bounding box for the mesh. If the delta-z bound is
// negligibly small then we can use a quadtree.
{
MeshTools::BoundingBox bbox = MeshTools::bounding_box(this->_mesh);
const Real
Dx = bbox.second(0) - bbox.first(0),
Dz = bbox.second(2) - bbox.first(2);
if (std::abs(Dz/(Dx + 1.e-20)) < 1e-10)
is_planar_xy = true;
}
if (!is_planar_xy)
_tree = new Trees::OctTree (this->_mesh, 200, build_type);
else
#endif
_tree = new Trees::QuadTree (this->_mesh, 200, build_type);
}
STOP_LOG("init(no master)", "PointLocatorTree");
}
else
{
// We are _not_ the master. Let our Tree point to
// the master's tree. But for this we first transform
// the master in a state for which we are friends.
// And make sure the master @e has a tree!
const PointLocatorTree* my_master =
libmesh_cast_ptr<const PointLocatorTree*>(this->_master);
if (my_master->initialized())
this->_tree = my_master->_tree;
else
{
libMesh::err << "ERROR: Initialize master first, then servants!"
<< std::endl;
libmesh_error();
}
}
// Not all PointLocators may own a tree, but all of them
// use their own element pointer. Let the element pointer
// be unique for every interpolator.
// Suppose the interpolators are used concurrently
// at different locations in the mesh, then it makes quite
// sense to have unique start elements.
this->_element = NULL;
}
// ready for take-off
this->_initialized = true;
}
const Elem* PointLocatorTree::operator() (const Point& p) const
{
libmesh_assert (this->_initialized);
START_LOG("operator()", "PointLocatorTree");
// First check the element from last time before asking the tree
if (this->_element==NULL || !(this->_element->contains_point(p)))
{
// ask the tree
this->_element = this->_tree->find_element (p);
if (this->_element == NULL)
{
/* No element seems to contain this point. If out-of-mesh
mode is enabled, just return NULL. If not, however, we
have to perform a linear search before we call \p
libmesh_error() since in the case of curved elements, the
bounding box computed in \p TreeNode::insert(const
Elem*) might be slightly inaccurate. */
if(!_out_of_mesh_mode)
{
START_LOG("linear search", "PointLocatorTree");
MeshBase::const_element_iterator pos = this->_mesh.active_elements_begin();
const MeshBase::const_element_iterator end_pos = this->_mesh.active_elements_end();
for ( ; pos != end_pos; ++pos)
if ((*pos)->contains_point(p))
{
STOP_LOG("linear search", "PointLocatorTree");
STOP_LOG("operator()", "PointLocatorTree");
return this->_element = (*pos);
}
if (this->_element == NULL)
{
libMesh::err << std::endl
<< " ******** Serious Problem. Could not find an Element "
<< "in the Mesh"
<< std:: endl
<< " ******** that contains the Point "
<< p;
libmesh_error();
}
STOP_LOG("linear search", "PointLocatorTree");
}
}
}
// If we found an element, it should be active
libmesh_assert (!this->_element || this->_element->active());
STOP_LOG("operator()", "PointLocatorTree");
// return the element
return this->_element;
}
void PointLocatorTree::enable_out_of_mesh_mode (void)
{
/* Out-of-mesh mode is currently only supported if all of the
elements have affine mappings. The reason is that for quadratic
mappings, it is not easy to construct a relyable bounding box of
the element, and thus, the fallback linear search in \p
operator() is required. Hence, out-of-mesh mode would be
extremely slow. */
if(!_out_of_mesh_mode)
{
#ifdef DEBUG
MeshBase::const_element_iterator pos = this->_mesh.active_elements_begin();
const MeshBase::const_element_iterator end_pos = this->_mesh.active_elements_end();
for ( ; pos != end_pos; ++pos)
if (!(*pos)->has_affine_map())
{
libMesh::err << "ERROR: Out-of-mesh mode is currently only supported if all elements have affine mappings." << std::endl;
libmesh_error();
}
#endif
_out_of_mesh_mode = true;
}
}
void PointLocatorTree::disable_out_of_mesh_mode (void)
{
_out_of_mesh_mode = false;
}
} // namespace libMesh
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
int opciones[][2] = {
{1, 51},
{2, 52},
{3, 53},
{4, 54},
{5, 55},
{6, 56}
};
for (int fila=0; fila<6; fila++){
for(int col=0; col<2; col++)
printf("%2i ", opciones[fila][col]);
printf("\n");
}
printf("\n");
return EXIT_SUCCESS;
}
<commit_msg>Delete multidimensional.cpp<commit_after><|endoftext|> |
<commit_before>#include "stdafx.h"
#include "ResponseWriter.h"
MultipartResponseWriter::MultipartResponseWriter(char *outputBuffer_, int outputSize_):
outputBuffer(outputBuffer_),
realOutputBuffer(outputBuffer_),
outputSize(0),
outputAvailableSize(outputSize_)
{
}
void MultipartResponseWriter::initialize()
{
writeBytes("[\"r\",");
}
void MultipartResponseWriter::finalize()
{
writeBytes("]");
}
void MultipartResponseWriter::createNewPage(const char *begin = nullptr, const char *end = nullptr)
{
if (begin && end)
{
multipartVector.emplace_back(begin, end);
}
else
{
multipartVector.emplace_back();
multipartVector.back().resize(outputAvailableSize + 1);
multipartVector.back()[0] = '\0';
}
}
void MultipartResponseWriter::writeBytes(const char* bytes)
{
for(auto p = bytes; *p; p++)
{
if (outputSize == outputAvailableSize)
{
// The page is full, create a new one
if (multipartVector.size() == 0)
{
// First time wrapping, copy data and create another page
createNewPage(outputBuffer, &outputBuffer[outputSize]);
}
createNewPage();
outputBuffer = multipartVector.back().data();
outputSize = 0;
}
outputBuffer[outputSize++] = *p;
}
outputBuffer[outputSize] = '\0'; // Maybe that's not needed?
}
std::vector<std::vector<char>> MultipartResponseWriter::getMultipart()
{
return multipartVector;
}
// ===================================
TestResponseWriter::TestResponseWriter(): MultipartResponseWriter(tempBuf, tempBufSize)
{
tempBuf[tempBufSize] = '\0';
}
void TestResponseWriter::initialize()
{
}
void TestResponseWriter::finalize()
{
}
std::string TestResponseWriter::getResponse()
{
auto multipartResponse = getMultipart();
if (multipartResponse.size() == 0)
return tempBuf;
std::string retval;
retval.reserve(tempBufSize * multipartResponse.size() + 1);
for (auto &v : multipartResponse)
{
retval.append(v.data(), tempBufSize);
}
return retval;
}
<commit_msg>Do not write `["r",` yourself from the writer<commit_after>#include "stdafx.h"
#include "ResponseWriter.h"
MultipartResponseWriter::MultipartResponseWriter(char *outputBuffer_, int outputSize_):
outputBuffer(outputBuffer_),
realOutputBuffer(outputBuffer_),
outputSize(0),
outputAvailableSize(outputSize_)
{
}
void MultipartResponseWriter::initialize()
{
//writeBytes("[\"r\",");
}
void MultipartResponseWriter::finalize()
{
//writeBytes("]");
}
void MultipartResponseWriter::createNewPage(const char *begin = nullptr, const char *end = nullptr)
{
if (begin && end)
{
multipartVector.emplace_back(begin, end);
}
else
{
multipartVector.emplace_back();
multipartVector.back().resize(outputAvailableSize + 1);
multipartVector.back()[0] = '\0';
}
}
void MultipartResponseWriter::writeBytes(const char* bytes)
{
for(auto p = bytes; *p; p++)
{
if (outputSize == outputAvailableSize)
{
// The page is full, create a new one
if (multipartVector.size() == 0)
{
// First time wrapping, copy data and create another page
createNewPage(outputBuffer, &outputBuffer[outputSize]);
}
createNewPage();
outputBuffer = multipartVector.back().data();
outputSize = 0;
}
outputBuffer[outputSize++] = *p;
}
outputBuffer[outputSize] = '\0'; // Maybe that's not needed?
}
std::vector<std::vector<char>> MultipartResponseWriter::getMultipart()
{
return multipartVector;
}
// ===================================
TestResponseWriter::TestResponseWriter(): MultipartResponseWriter(tempBuf, tempBufSize)
{
tempBuf[tempBufSize] = '\0';
}
void TestResponseWriter::initialize()
{
}
void TestResponseWriter::finalize()
{
}
std::string TestResponseWriter::getResponse()
{
auto multipartResponse = getMultipart();
if (multipartResponse.size() == 0)
return tempBuf;
std::string retval;
retval.reserve(tempBufSize * multipartResponse.size() + 1);
for (auto &v : multipartResponse)
{
retval.append(v.data(), tempBufSize);
}
return retval;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2008-2011 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/detail/config.h>
#include <thrust/detail/allocator/malloc_allocator.h>
#include <thrust/system/detail/generic/select_system.h>
#include <thrust/system/detail/generic/memory.h>
#include <thrust/system/detail/bad_alloc.h>
#include <thrust/detail/type_traits/pointer_traits.h>
#include <thrust/detail/malloc_and_free_adl_helper.h>
namespace thrust
{
namespace detail
{
template<typename T, typename Tag, typename Pointer>
typename malloc_allocator<T,Tag,Pointer>::super_t::pointer
malloc_allocator<T,Tag,Pointer>
::allocate(typename malloc_allocator<T,Tag,Pointer>::super_t::size_type cnt)
{
using thrust::system::detail::generic::select_system;
using thrust::system::detail::generic::malloc;
// XXX should use a hypothetical thrust::static_pointer_cast here
T* result = static_cast<T*>(thrust::detail::raw_pointer_cast(malloc(select_system(Tag()), sizeof(typename super_t::value_type) * cnt)));
if(result == 0)
{
throw thrust::system::detail::bad_alloc("tagged_allocator::allocate: malloc failed");
} // end if
return super_t::pointer(result);
} // end malloc_allocator::allocate()
template<typename T, typename Tag, typename Pointer>
void malloc_allocator<T,Tag,Pointer>
::deallocate(typename malloc_allocator<T,Tag,Pointer>::super_t::pointer p, typename malloc_allocator<T,Tag,Pointer>::super_t::size_type n)
{
using thrust::system::detail::generic::select_system;
using thrust::system::detail::generic::free;
free(select_system(Tag()), p);
} // end malloc_allocator
} // end detail
} // end thrust
<commit_msg>Add missing typename keyword in malloc_allocator::allocate<commit_after>/*
* Copyright 2008-2011 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/detail/config.h>
#include <thrust/detail/allocator/malloc_allocator.h>
#include <thrust/system/detail/generic/select_system.h>
#include <thrust/system/detail/generic/memory.h>
#include <thrust/system/detail/bad_alloc.h>
#include <thrust/detail/type_traits/pointer_traits.h>
#include <thrust/detail/malloc_and_free_adl_helper.h>
namespace thrust
{
namespace detail
{
template<typename T, typename Tag, typename Pointer>
typename malloc_allocator<T,Tag,Pointer>::super_t::pointer
malloc_allocator<T,Tag,Pointer>
::allocate(typename malloc_allocator<T,Tag,Pointer>::super_t::size_type cnt)
{
using thrust::system::detail::generic::select_system;
using thrust::system::detail::generic::malloc;
// XXX should use a hypothetical thrust::static_pointer_cast here
T* result = static_cast<T*>(thrust::detail::raw_pointer_cast(malloc(select_system(Tag()), sizeof(typename super_t::value_type) * cnt)));
if(result == 0)
{
throw thrust::system::detail::bad_alloc("tagged_allocator::allocate: malloc failed");
} // end if
return typename super_t::pointer(result);
} // end malloc_allocator::allocate()
template<typename T, typename Tag, typename Pointer>
void malloc_allocator<T,Tag,Pointer>
::deallocate(typename malloc_allocator<T,Tag,Pointer>::super_t::pointer p, typename malloc_allocator<T,Tag,Pointer>::super_t::size_type n)
{
using thrust::system::detail::generic::select_system;
using thrust::system::detail::generic::free;
free(select_system(Tag()), p);
} // end malloc_allocator
} // end detail
} // end thrust
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief RX24T ファースト・サンプル @n
・P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/cmt_io.hpp"
#include "common/sci_io.hpp"
#include "common/fifo.hpp"
#include "common/format.hpp"
#include "common/iica_io.hpp"
#include "common/command.hpp"
#include "chip/DS3231.hpp"
namespace {
class cmt_task {
public:
void operator() () {
}
};
device::cmt_io<device::CMT0, cmt_task> cmt_;
typedef utils::fifo<uint8_t, 128> buffer;
device::sci_io<device::SCI1, buffer, buffer> sci_;
typedef device::iica_io<device::RIIC0> I2C;
I2C i2c_;
chip::DS3231<I2C> rtc_(i2c_);
utils::command<128> command_;
time_t get_time_()
{
time_t t = 0;
if(!rtc_.get_time(t)) {
utils::format("Stall RTC read (%d)\n") % static_cast<uint32_t>(i2c_.get_last_error());
}
return t;
}
void disp_time_(time_t t)
{
struct tm *m = localtime(&t);
utils::format("%s %s %d %02d:%02d:%02d %4d\n")
% get_wday(m->tm_wday)
% get_mon(m->tm_mon)
% static_cast<uint32_t>(m->tm_mday)
% static_cast<uint32_t>(m->tm_hour)
% static_cast<uint32_t>(m->tm_min)
% static_cast<uint32_t>(m->tm_sec)
% static_cast<uint32_t>(m->tm_year + 1900);
}
const char* get_dec_(const char* p, char tmch, int& value) {
int v = 0;
char ch;
while((ch = *p) != 0) {
++p;
if(ch == tmch) {
break;
} else if(ch >= '0' && ch <= '9') {
v *= 10;
v += ch - '0';
} else {
return nullptr;
}
}
value = v;
return p;
}
void set_time_date_()
{
time_t t = get_time_();
if(t == 0) return;
struct tm *m = localtime(&t);
bool err = false;
if(command_.get_words() == 3) {
char buff[12];
if(command_.get_word(1, sizeof(buff), buff)) {
const char* p = buff;
int vs[3];
uint8_t i;
for(i = 0; i < 3; ++i) {
p = get_dec_(p, '/', vs[i]);
if(p == nullptr) {
break;
}
}
if(p != nullptr && p[0] == 0 && i == 3) {
if(vs[0] >= 1900 && vs[0] < 2100) m->tm_year = vs[0] - 1900;
if(vs[1] >= 1 && vs[1] <= 12) m->tm_mon = vs[1] - 1;
if(vs[2] >= 1 && vs[2] <= 31) m->tm_mday = vs[2];
} else {
err = true;
}
}
if(command_.get_word(2, sizeof(buff), buff)) {
const char* p = buff;
int vs[3];
uint8_t i;
for(i = 0; i < 3; ++i) {
p = get_dec_(p, ':', vs[i]);
if(p == nullptr) {
break;
}
}
if(p != nullptr && p[0] == 0 && (i == 2 || i == 3)) {
if(vs[0] >= 0 && vs[0] < 24) m->tm_hour = vs[0];
if(vs[1] >= 0 && vs[1] < 60) m->tm_min = vs[1];
if(i == 3 && vs[2] >= 0 && vs[2] < 60) m->tm_sec = vs[2];
else m->tm_sec = 0;
} else {
err = true;
}
}
}
if(err) {
utils::format("Can't analize Time/Date input.\n");
return;
}
time_t tt = mktime(m);
if(!rtc_.set_time(tt)) {
utils::format("Stall RTC write...\n");
}
}
}
extern "C" {
void sci_putch(char ch)
{
sci_.putch(ch);
}
void sci_puts(const char* str)
{
sci_.puts(str);
}
char sci_getch(void)
{
return sci_.getch();
}
uint16_t sci_length()
{
return sci_.recv_length();
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可
device::SYSTEM::MEMWAIT = 0b10; // 80MHz 動作 wait 設定
while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop");
device::SYSTEM::OPCCR = 0; // 高速モード選択
while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop");
// clock osc 10MHz
device::SYSTEM::MOSCWTCR = 9; // 4ms wait
// メインクロック・ドライブ能力設定、内部発信
device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(1);
device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作
while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm("nop");
device::SYSTEM::PLLCR.STC = 0b001111; // PLL input: 1, PLL 8 倍(80MHz)
device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作
while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm("nop");
device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(2) // 1/4 (80/4=20)
| device::SYSTEM::SCKCR.ICK.b(0) // 1/1 (80/1=80)
| device::SYSTEM::SCKCR.PCKA.b(0) // 1/1 (80/1=80)
| device::SYSTEM::SCKCR.PCKB.b(1) // 1/2 (80/2=40)
| device::SYSTEM::SCKCR.PCKD.b(1); // 1/2 (120/2=60)
device::SYSTEM::SCKCR3.CKSEL = 0b100; ///< PLL 選択
{ // タイマー設定(60Hz)
uint8_t intr_level = 4;
cmt_.start(60, intr_level);
}
{ // SCI 設定
uint8_t intr_level = 2;
sci_.start(115200, intr_level);
}
{ // IICA(I2C) の開始
uint8_t intr_level = 0;
if(!i2c_.start(I2C::speed::fast, intr_level)) {
utils::format("IICA start error (%d)\n") % static_cast<uint32_t>(i2c_.get_last_error());
}
}
utils::format("RX24T DS3231 sample\n");
// DS3231(RTC) の開始
if(!rtc_.start()) {
utils::format("Stall RTC start (%d)\n") % static_cast<uint32_t>(i2c_.get_last_error());
}
command_.set_prompt("# ");
device::PORT0::PDR.B0 = 1; // output
uint32_t cnt = 0;
while(1) {
cmt_.sync();
++cnt;
if(cnt >= 30) {
cnt = 0;
}
device::PORT0::PODR.B0 = (cnt < 10) ? 0 : 1;
// コマンド入力と、コマンド解析
if(command_.service()) {
uint8_t cmdn = command_.get_words();
if(cmdn >= 1) {
if(command_.cmp_word(0, "date")) {
if(cmdn == 1) {
time_t t = get_time_();
if(t != 0) {
disp_time_(t);
}
} else {
set_time_date_();
}
} else if(command_.cmp_word(0, "help")) {
utils::format("date\n");
utils::format("date yyyy/mm/dd hh:mm[:ss]\n");
} else {
char buff[128];
if(command_.get_word(0, sizeof(buff), buff)) {
utils::format("Command error: %s\n") % buff;
}
}
}
}
}
}
<commit_msg>update: command class API<commit_after>//=====================================================================//
/*! @file
@brief RX24T ファースト・サンプル @n
・P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/cmt_io.hpp"
#include "common/sci_io.hpp"
#include "common/fifo.hpp"
#include "common/format.hpp"
#include "common/iica_io.hpp"
#include "common/command.hpp"
#include "chip/DS3231.hpp"
namespace {
class cmt_task {
public:
void operator() () {
}
};
device::cmt_io<device::CMT0, cmt_task> cmt_;
typedef utils::fifo<uint8_t, 128> buffer;
device::sci_io<device::SCI1, buffer, buffer> sci_;
typedef device::iica_io<device::RIIC0> I2C;
I2C i2c_;
chip::DS3231<I2C> rtc_(i2c_);
utils::command<128> command_;
time_t get_time_()
{
time_t t = 0;
if(!rtc_.get_time(t)) {
utils::format("Stall RTC read (%d)\n") % static_cast<uint32_t>(i2c_.get_last_error());
}
return t;
}
void disp_time_(time_t t)
{
struct tm *m = localtime(&t);
utils::format("%s %s %d %02d:%02d:%02d %4d\n")
% get_wday(m->tm_wday)
% get_mon(m->tm_mon)
% static_cast<uint32_t>(m->tm_mday)
% static_cast<uint32_t>(m->tm_hour)
% static_cast<uint32_t>(m->tm_min)
% static_cast<uint32_t>(m->tm_sec)
% static_cast<uint32_t>(m->tm_year + 1900);
}
const char* get_dec_(const char* p, char tmch, int& value) {
int v = 0;
char ch;
while((ch = *p) != 0) {
++p;
if(ch == tmch) {
break;
} else if(ch >= '0' && ch <= '9') {
v *= 10;
v += ch - '0';
} else {
return nullptr;
}
}
value = v;
return p;
}
void set_time_date_()
{
time_t t = get_time_();
if(t == 0) return;
struct tm *m = localtime(&t);
bool err = false;
if(command_.get_words() == 3) {
char buff[12];
if(command_.get_word(1, buff, sizeof(buff))) {
const char* p = buff;
int vs[3];
uint8_t i;
for(i = 0; i < 3; ++i) {
p = get_dec_(p, '/', vs[i]);
if(p == nullptr) {
break;
}
}
if(p != nullptr && p[0] == 0 && i == 3) {
if(vs[0] >= 1900 && vs[0] < 2100) m->tm_year = vs[0] - 1900;
if(vs[1] >= 1 && vs[1] <= 12) m->tm_mon = vs[1] - 1;
if(vs[2] >= 1 && vs[2] <= 31) m->tm_mday = vs[2];
} else {
err = true;
}
}
if(command_.get_word(2, buff, sizeof(buff))) {
const char* p = buff;
int vs[3];
uint8_t i;
for(i = 0; i < 3; ++i) {
p = get_dec_(p, ':', vs[i]);
if(p == nullptr) {
break;
}
}
if(p != nullptr && p[0] == 0 && (i == 2 || i == 3)) {
if(vs[0] >= 0 && vs[0] < 24) m->tm_hour = vs[0];
if(vs[1] >= 0 && vs[1] < 60) m->tm_min = vs[1];
if(i == 3 && vs[2] >= 0 && vs[2] < 60) m->tm_sec = vs[2];
else m->tm_sec = 0;
} else {
err = true;
}
}
}
if(err) {
utils::format("Can't analize Time/Date input.\n");
return;
}
time_t tt = mktime(m);
if(!rtc_.set_time(tt)) {
utils::format("Stall RTC write...\n");
}
}
}
extern "C" {
void sci_putch(char ch)
{
sci_.putch(ch);
}
void sci_puts(const char* str)
{
sci_.puts(str);
}
char sci_getch(void)
{
return sci_.getch();
}
uint16_t sci_length()
{
return sci_.recv_length();
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可
device::SYSTEM::MEMWAIT = 0b10; // 80MHz 動作 wait 設定
while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop");
device::SYSTEM::OPCCR = 0; // 高速モード選択
while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop");
// clock osc 10MHz
device::SYSTEM::MOSCWTCR = 9; // 4ms wait
// メインクロック・ドライブ能力設定、内部発信
device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(1);
device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作
while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm("nop");
device::SYSTEM::PLLCR.STC = 0b001111; // PLL input: 1, PLL 8 倍(80MHz)
device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作
while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm("nop");
device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(2) // 1/4 (80/4=20)
| device::SYSTEM::SCKCR.ICK.b(0) // 1/1 (80/1=80)
| device::SYSTEM::SCKCR.PCKA.b(0) // 1/1 (80/1=80)
| device::SYSTEM::SCKCR.PCKB.b(1) // 1/2 (80/2=40)
| device::SYSTEM::SCKCR.PCKD.b(1); // 1/2 (120/2=60)
device::SYSTEM::SCKCR3.CKSEL = 0b100; ///< PLL 選択
{ // タイマー設定(60Hz)
uint8_t intr_level = 4;
cmt_.start(60, intr_level);
}
{ // SCI 設定
uint8_t intr_level = 2;
sci_.start(115200, intr_level);
}
{ // IICA(I2C) の開始
uint8_t intr_level = 0;
if(!i2c_.start(I2C::speed::fast, intr_level)) {
utils::format("IICA start error (%d)\n") % static_cast<uint32_t>(i2c_.get_last_error());
}
}
utils::format("RX24T DS3231 sample\n");
// DS3231(RTC) の開始
if(!rtc_.start()) {
utils::format("Stall RTC start (%d)\n") % static_cast<uint32_t>(i2c_.get_last_error());
}
command_.set_prompt("# ");
device::PORT0::PDR.B0 = 1; // output
uint32_t cnt = 0;
while(1) {
cmt_.sync();
++cnt;
if(cnt >= 30) {
cnt = 0;
}
device::PORT0::PODR.B0 = (cnt < 10) ? 0 : 1;
// コマンド入力と、コマンド解析
if(command_.service()) {
uint8_t cmdn = command_.get_words();
if(cmdn >= 1) {
if(command_.cmp_word(0, "date")) {
if(cmdn == 1) {
time_t t = get_time_();
if(t != 0) {
disp_time_(t);
}
} else {
set_time_date_();
}
} else if(command_.cmp_word(0, "help")) {
utils::format("date\n");
utils::format("date yyyy/mm/dd hh:mm[:ss]\n");
} else {
char buff[128];
if(command_.get_word(0, buff, sizeof(buff))) {
utils::format("Command error: %s\n") % buff;
}
}
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "diskstate.h"
#include <boost/lexical_cast.hpp>
#include <vespa/vespalib/text/stringtokenizer.h>
#include <vespa/document/util/stringutil.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/vespalib/stllike/asciistream.h>
#include <vespa/log/log.h>
LOG_SETUP(".vdslib.diskstate");
namespace storage {
namespace lib {
DiskState::DiskState()
: _state(0),
_description(""),
_capacity(1.0)
{
setState(State::UP);
}
DiskState::DiskState(const State& state, const vespalib::stringref & description,
double capacity)
: _state(0),
_description(description),
_capacity(1.0)
{
setState(state);
setCapacity(capacity);
}
DiskState::DiskState(const vespalib::stringref & serialized)
: _state(&State::UP),
_description(""),
_capacity(1.0)
{
vespalib::StringTokenizer st(serialized, " \t\f\r\n");
st.removeEmptyTokens();
for (vespalib::StringTokenizer::Iterator it = st.begin();
it != st.end(); ++it)
{
std::string::size_type index = it->find(':');
if (index == std::string::npos) {
throw vespalib::IllegalArgumentException(
"Token " + *it + " does not contain ':': " + serialized,
VESPA_STRLOC);
}
std::string key = it->substr(0, index);
std::string value = it->substr(index + 1);
if (key.size() > 0) switch (key[0]) {
case 's':
if (key.size() > 1) break;
setState(State::get(value));
continue;
case 'c':
if (key.size() > 1) break;
try{
setCapacity(boost::lexical_cast<double>(value));
} catch (...) {
throw vespalib::IllegalArgumentException(
"Illegal disk capacity '" + value + "'. Capacity "
"must be a positive floating point number",
VESPA_STRLOC);
}
//@fallthrough@
case 'm':
if (key.size() > 1) break;
_description = document::StringUtil::unescape(value);
continue;
default:
break;
}
LOG(debug, "Unknown key %s in diskstate. Ignoring it, assuming it's a "
"new feature from a newer version than ourself: %s",
key.c_str(), serialized.c_str());
}
}
void
DiskState::serialize(vespalib::asciistream & out, const vespalib::stringref & prefix,
bool includeDescription, bool useOldFormat) const
{
// Always give node state if not part of a system state
// to prevent empty serialization
bool empty = true;
if (*_state != State::UP || prefix.size() == 0) {
if (useOldFormat && prefix.size() > 0) {
out << prefix.substr(0, prefix.size() - 1)
<< ":" << _state->serialize();
} else {
out << prefix << "s:" << _state->serialize();
}
empty = false;
}
if (_capacity != 1.0) {
if (empty) { empty = false; } else { out << ' '; }
out << prefix << "c:" << _capacity;
}
if (includeDescription && _description.size() > 0) {
if (empty) { empty = false; } else { out << ' '; }
out << prefix << "m:"
<< document::StringUtil::escape(_description, ' ');
}
}
void
DiskState::setState(const State& state)
{
if (!state.validDiskState()) {
throw vespalib::IllegalArgumentException(
"State " + state.toString() + " is not a valid disk state.",
VESPA_STRLOC);
}
_state = &state;
}
void
DiskState::setCapacity(double capacity)
{
if (capacity < 0) {
throw vespalib::IllegalArgumentException(
"Negative capacity makes no sense.", VESPA_STRLOC);
}
_capacity = capacity;
}
void
DiskState::print(std::ostream& out, bool verbose,
const std::string& indent) const
{
(void) indent;
if (verbose) {
out << "DiskState(" << *_state;
} else {
out << _state->serialize();
}
if (_capacity != 1.0) {
out << (verbose ? ", capacity " : ", c ") << _capacity;
}
if (_description.size() > 0) {
out << ": " << _description;
}
if (verbose) {
out << ")";
}
}
bool
DiskState::operator==(const DiskState& other) const
{
return (_state == other._state && _capacity == other._capacity);
}
bool
DiskState::operator!=(const DiskState& other) const
{
return (_state != other._state || _capacity != other._capacity);
}
} // lib
} // storage
<commit_msg>continue instead of fallthrough.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "diskstate.h"
#include <boost/lexical_cast.hpp>
#include <vespa/vespalib/text/stringtokenizer.h>
#include <vespa/document/util/stringutil.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/vespalib/stllike/asciistream.h>
#include <vespa/log/log.h>
LOG_SETUP(".vdslib.diskstate");
namespace storage {
namespace lib {
DiskState::DiskState()
: _state(0),
_description(""),
_capacity(1.0)
{
setState(State::UP);
}
DiskState::DiskState(const State& state, const vespalib::stringref & description,
double capacity)
: _state(0),
_description(description),
_capacity(1.0)
{
setState(state);
setCapacity(capacity);
}
DiskState::DiskState(const vespalib::stringref & serialized)
: _state(&State::UP),
_description(""),
_capacity(1.0)
{
vespalib::StringTokenizer st(serialized, " \t\f\r\n");
st.removeEmptyTokens();
for (vespalib::StringTokenizer::Iterator it = st.begin();
it != st.end(); ++it)
{
std::string::size_type index = it->find(':');
if (index == std::string::npos) {
throw vespalib::IllegalArgumentException(
"Token " + *it + " does not contain ':': " + serialized,
VESPA_STRLOC);
}
std::string key = it->substr(0, index);
std::string value = it->substr(index + 1);
if (key.size() > 0) switch (key[0]) {
case 's':
if (key.size() > 1) break;
setState(State::get(value));
continue;
case 'c':
if (key.size() > 1) break;
try{
setCapacity(boost::lexical_cast<double>(value));
} catch (...) {
throw vespalib::IllegalArgumentException(
"Illegal disk capacity '" + value + "'. Capacity "
"must be a positive floating point number",
VESPA_STRLOC);
}
continue;
case 'm':
if (key.size() > 1) break;
_description = document::StringUtil::unescape(value);
continue;
default:
break;
}
LOG(debug, "Unknown key %s in diskstate. Ignoring it, assuming it's a "
"new feature from a newer version than ourself: %s",
key.c_str(), serialized.c_str());
}
}
void
DiskState::serialize(vespalib::asciistream & out, const vespalib::stringref & prefix,
bool includeDescription, bool useOldFormat) const
{
// Always give node state if not part of a system state
// to prevent empty serialization
bool empty = true;
if (*_state != State::UP || prefix.size() == 0) {
if (useOldFormat && prefix.size() > 0) {
out << prefix.substr(0, prefix.size() - 1)
<< ":" << _state->serialize();
} else {
out << prefix << "s:" << _state->serialize();
}
empty = false;
}
if (_capacity != 1.0) {
if (empty) { empty = false; } else { out << ' '; }
out << prefix << "c:" << _capacity;
}
if (includeDescription && _description.size() > 0) {
if (empty) { empty = false; } else { out << ' '; }
out << prefix << "m:"
<< document::StringUtil::escape(_description, ' ');
}
}
void
DiskState::setState(const State& state)
{
if (!state.validDiskState()) {
throw vespalib::IllegalArgumentException(
"State " + state.toString() + " is not a valid disk state.",
VESPA_STRLOC);
}
_state = &state;
}
void
DiskState::setCapacity(double capacity)
{
if (capacity < 0) {
throw vespalib::IllegalArgumentException(
"Negative capacity makes no sense.", VESPA_STRLOC);
}
_capacity = capacity;
}
void
DiskState::print(std::ostream& out, bool verbose,
const std::string& indent) const
{
(void) indent;
if (verbose) {
out << "DiskState(" << *_state;
} else {
out << _state->serialize();
}
if (_capacity != 1.0) {
out << (verbose ? ", capacity " : ", c ") << _capacity;
}
if (_description.size() > 0) {
out << ": " << _description;
}
if (verbose) {
out << ")";
}
}
bool
DiskState::operator==(const DiskState& other) const
{
return (_state == other._state && _capacity == other._capacity);
}
bool
DiskState::operator!=(const DiskState& other) const
{
return (_state != other._state || _capacity != other._capacity);
}
} // lib
} // storage
<|endoftext|> |
<commit_before>//
// Copyright (C) 2004-2006 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// SYSTEM INCLUDES
#include <assert.h>
// APPLICATION INCLUDES
#include <utl/UtlString.h>
#include <utl/UtlHashBagIterator.h>
#include <net/SipTransaction.h>
#include <net/SipTransactionList.h>
#include <net/SipMessage.h>
#include <os/OsTask.h>
#include <os/OsEvent.h>
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
//#define TIME_LOG /* turns on timestamping of finding and garbage collecting transactions */
#ifdef TIME_LOG
# include <os/OsTimeLog.h>
#endif
// STATIC VARIABLE INITIALIZATIONS
/* //////////////////////////// PUBLIC //////////////////////////////////// */
/* ============================ CREATORS ================================== */
// Constructor
SipTransactionList::SipTransactionList() :
mTransactions(),
mListMutex(OsMutex::Q_FIFO)
{
}
// Copy constructor
SipTransactionList::SipTransactionList(const SipTransactionList& rSipTransactionList) :
mListMutex(OsMutex::Q_FIFO)
{
}
// Destructor
SipTransactionList::~SipTransactionList()
{
mTransactions.destroyAll();
}
/* ============================ MANIPULATORS ============================== */
// Assignment operator
SipTransactionList&
SipTransactionList::operator=(const SipTransactionList& rhs)
{
if (this == &rhs) // handle the assignment to self case
return *this;
return *this;
}
void SipTransactionList::addTransaction(SipTransaction* transaction,
UtlBoolean lockList)
{
if(lockList) lock();
mTransactions.insert(transaction);
#ifdef TEST_PRINT
osPrintf("***************************************\n");
osPrintf("inserting transaction %X\n",transaction);
osPrintf("***************************************\n");
#endif
if(lockList) unlock();
}
//: Find a transaction for the given message
SipTransaction*
SipTransactionList::findTransactionFor(const SipMessage& message,
UtlBoolean isOutgoing,
enum SipTransaction::messageRelationship& relationship)
{
SipTransaction* transactionFound = NULL;
UtlString callId;
SipTransaction::buildHash(message, isOutgoing, callId);
lock();
// See if the message knows its transaction
// DO NOT TOUCH THE CONTENTS of this transaction as it may no
// longer exist. It can only be used as an ID for the transaction.
SipTransaction* messageTransaction = message.getSipTransaction();
UtlString matchTransaction(callId);
UtlHashBagIterator iterator(mTransactions, &matchTransaction);
relationship = SipTransaction::MESSAGE_UNKNOWN;
while ((transactionFound = (SipTransaction*) iterator()))
{
// If the message knows its SIP transaction
// and the found transaction pointer does not match, skip the
// expensive relationship calculation
// The messageTransaction MUST BE TREATED AS OPAQUE
// as it may have been deleted.
if( messageTransaction && transactionFound != messageTransaction )
{
continue;
}
// If the transaction has never sent the original rquest
// it should never get a match for any messages.
if( messageTransaction == NULL // this message does not point to this TX
&& ((transactionFound->getState()) == SipTransaction::TRANSACTION_LOCALLY_INIITATED)
)
{
continue;
}
relationship = transactionFound->whatRelation(message, isOutgoing);
if(relationship == SipTransaction::MESSAGE_REQUEST ||
relationship == SipTransaction::MESSAGE_PROVISIONAL ||
relationship == SipTransaction::MESSAGE_FINAL ||
relationship == SipTransaction::MESSAGE_NEW_FINAL ||
relationship == SipTransaction::MESSAGE_CANCEL ||
relationship == SipTransaction::MESSAGE_CANCEL_RESPONSE ||
relationship == SipTransaction::MESSAGE_ACK ||
relationship == SipTransaction::MESSAGE_2XX_ACK ||
relationship == SipTransaction::MESSAGE_DUPLICATE)
{
break;
}
}
UtlBoolean isBusy = FALSE;
if(transactionFound == NULL)
{
relationship =
SipTransaction::MESSAGE_UNKNOWN;
}
else
{
isBusy = transactionFound->isBusy();
if(!isBusy)
{
transactionFound->markBusy();
}
}
unlock();
if(transactionFound && isBusy)
{
// If we cannot lock it, it does not exist
if(!waitUntilAvailable(transactionFound, callId))
{
if (OsSysLog::willLog(FAC_SIP, PRI_WARNING))
{
UtlString relationString;
SipTransaction::getRelationshipString(relationship, relationString);
OsSysLog::add(FAC_SIP, PRI_WARNING,
"SipTransactionList::findTransactionFor %p not available relation: %s",
transactionFound, relationString.data());
}
transactionFound = NULL;
}
}
#if 0 // enable only for transaction match debugging - log is confusing otherwise
UtlString relationString;
SipTransaction::getRelationshipString(relationship, relationString);
UtlString bytes;
int len;
message.getBytes(&bytes, &len);
OsSysLog::add(FAC_SIP, PRI_DEBUG
,"SipTransactionList::findTransactionFor %p %s %s %s"
# ifdef TIME_LOG
"\n\tTime Log %s"
# endif
,&message
,isOutgoing ? "OUTGOING" : "INCOMING"
,transactionFound ? "FOUND" : "NOT FOUND"
,relationString.data()
# ifdef TIME_LOG
,findTimeLog.data()
# endif
);
#endif
return(transactionFound);
}
void SipTransactionList::removeOldTransactions(long oldTransaction,
long oldInviteTransaction)
{
SipTransaction** transactionsToBeDeleted = NULL;
int deleteCount = 0;
int busyCount = 0;
# ifdef TIME_LOG
OsTimeLog gcTimes;
gcTimes.addEvent("start");
# endif
lock();
int numTransactions = mTransactions.entries();
if(numTransactions > 0)
{
UtlHashBagIterator iterator(mTransactions);
SipTransaction* transactionFound = NULL;
long transTime;
// Pull all of the transactions to be deleted out of the list
while((transactionFound = (SipTransaction*) iterator()))
{
if(transactionFound->isBusy()) busyCount++;
transTime = transactionFound->getTimeStamp();
// Invites need to be kept longer than other transactions
if(((!transactionFound->isMethod(SIP_INVITE_METHOD) &&
transTime < oldTransaction) ||
transTime < oldInviteTransaction) &&
! transactionFound->isBusy())
{
// Remove it from the list
mTransactions.removeReference(transactionFound);
OsSysLog::add(FAC_SIP, PRI_DEBUG, "removing transaction %p\n",transactionFound);
// Make sure we have a pointer array to hold it
if(transactionsToBeDeleted == NULL)
{
transactionsToBeDeleted =
new SipTransaction*[numTransactions];
}
// Put it in the pointer array
transactionsToBeDeleted[deleteCount] = transactionFound;
deleteCount++;
// Make sure the events waiting for the transaction
// to be available are signaled before we delete
// any of the transactions or we end up with
// incomplete transaction trees (i.e. deleted branches)
transactionFound->signalAllAvailable();
transactionFound = NULL;
}
}
}
unlock();
// We do not need the lock if the transactions have been
// removed from the list
if ( deleteCount || busyCount ) // do not log 'doing nothing when nothing to do', even at debug level
{
OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::removeOldTransactions deleting %d of %d transactions (%d busy)\n",
deleteCount , numTransactions, busyCount);
}
// Delete the transactions in the array
if (transactionsToBeDeleted)
{
# ifdef TIME_LOG
gcTimes.addEvent("start delete");
# endif
for(int txIndex = 0; txIndex < deleteCount; txIndex++)
{
delete transactionsToBeDeleted[txIndex];
# ifdef TIME_LOG
gcTimes.addEvent("transaction deleted");
# endif
}
# ifdef TIME_LOG
gcTimes.addEvent("finish delete");
# endif
/*
while((transactionFound = (SipTransaction*) iterator()))
{
transactionFound->stopTimers();
}
*/
}
# ifdef TIME_LOG
UtlString timeString;
gcTimes.getLogString(timeString);
OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::removeOldTransactions "
"%s", timeString.data()
);
# endif
}
void SipTransactionList::stopTransactionTimers()
{
lock();
int numTransactions = mTransactions.entries();
if(numTransactions > 0)
{
UtlHashBagIterator iterator(mTransactions);
SipTransaction* transactionFound = NULL;
while((transactionFound = (SipTransaction*) iterator()))
{
transactionFound->stopTimers();
}
}
unlock();
}
void SipTransactionList::startTransactionTimers()
{
lock();
int numTransactions = mTransactions.entries();
if(numTransactions > 0)
{
UtlHashBagIterator iterator(mTransactions);
SipTransaction* transactionFound = NULL;
while((transactionFound = (SipTransaction*) iterator()))
{
transactionFound->startTimers();
}
}
unlock();
}
void SipTransactionList::deleteTransactionTimers()
{
lock();
int numTransactions = mTransactions.entries();
if(numTransactions > 0)
{
UtlHashBagIterator iterator(mTransactions);
SipTransaction* transactionFound = NULL;
while((transactionFound = (SipTransaction*) iterator()))
{
transactionFound->deleteTimers();
}
}
unlock();
}
void SipTransactionList::toString(UtlString& string)
{
lock();
string.remove(0);
UtlHashBagIterator iterator(mTransactions);
SipTransaction* transactionFound = NULL;
UtlString oneTransactionString;
while((transactionFound = (SipTransaction*) iterator()))
{
transactionFound->toString(oneTransactionString, FALSE);
string.append(oneTransactionString);
oneTransactionString.remove(0);
}
unlock();
}
void SipTransactionList::toStringWithRelations(UtlString& string,
SipMessage& message,
UtlBoolean isOutGoing)
{
lock();
string.remove(0);
UtlHashBagIterator iterator(mTransactions);
SipTransaction* transactionFound = NULL;
UtlString oneTransactionString;
SipTransaction::messageRelationship relation;
UtlString relationString;
while((transactionFound = (SipTransaction*) iterator()))
{
relation = transactionFound->whatRelation(message, isOutGoing);
SipTransaction::getRelationshipString(relation, relationString);
string.append(relationString);
string.append(" ");
transactionFound->toString(oneTransactionString, FALSE);
string.append(oneTransactionString);
oneTransactionString.remove(0);
string.append("\n");
}
unlock();
}
void SipTransactionList::lock()
{
mListMutex.acquire();
}
void SipTransactionList::unlock()
{
mListMutex.release();
}
UtlBoolean SipTransactionList::waitUntilAvailable(SipTransaction* transaction,
const UtlString& hash)
{
UtlBoolean exists;
UtlBoolean busy = FALSE;
int numTries = 0;
do
{
numTries++;
lock();
exists = transactionExists(transaction, hash);
if(exists)
{
busy = transaction->isBusy();
if(!busy)
{
transaction->markBusy();
unlock();
//#ifdef TEST_PRINT
OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p locked after %d tries\n",
transaction, numTries);
//#endif
}
else
{
// We set an event to be signaled when a
// transaction is released.
OsEvent* waitEvent = new OsEvent;
transaction->notifyWhenAvailable(waitEvent);
// Must unlock while we wait or there is a dead lock
unlock();
//#ifdef TEST_PRINT
OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p waiting on: %p after %d tries\n",
transaction, waitEvent, numTries);
//#endif
OsStatus waitStatus;
OsTime transBusyTimeout(1, 0);
int waitTime = 0;
do
{
if(waitTime > 0)
OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransactionList::waitUntilAvailable %p still waiting: %d",
transaction, waitTime);
waitStatus = waitEvent->wait(transBusyTimeout);
waitTime+=1;
}
while(waitStatus != OS_SUCCESS && waitTime < 30);
// If we were never signaled, then we signal the
// event so the other side knows that it has to
// free up the event
if(waitEvent->signal(-1) == OS_ALREADY_SIGNALED)
{
delete waitEvent;
waitEvent = NULL;
}
// If we bailed out before the event was signaled
// pretend the transaction does not exist.
if(waitStatus != OS_SUCCESS)
{
exists = FALSE;
}
if(waitTime > 1)
{
if (OsSysLog::willLog(FAC_SIP, PRI_WARNING))
{
UtlString transTree;
UtlString waitingTaskName;
OsTask* waitingTask = OsTask::getCurrentTask();
if(waitingTask) waitingTaskName = waitingTask->getName();
transaction->dumpTransactionTree(transTree, FALSE);
OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransactionList::waitUntilAvailable status: %d wait time: %d transaction: %p task: %s transaction tree: %s",
waitStatus, waitTime, transaction, waitingTaskName.data(), transTree.data());
}
}
//#ifdef TEST_PRINT
OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p done waiting after %d tries\n",
transaction, numTries);
//#endif
}
}
else
{
unlock();
//#ifdef TEST_PRINT
OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p gone after %d tries\n",
transaction, numTries);
//#endif
}
}
while(exists && busy);
return(exists && !busy);
}
void SipTransactionList::markAvailable(SipTransaction& transaction)
{
lock();
if(!transaction.isBusy())
{
UtlString transactionString;
transaction.toString(transactionString, FALSE);
OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransactionList::markAvailable transaction not locked: %s\n",
transactionString.data());
}
else
{
transaction.markAvailable();
}
unlock();
}
/* ============================ ACCESSORS ================================= */
/* ============================ INQUIRY =================================== */
UtlBoolean SipTransactionList::transactionExists(const SipTransaction* transaction,
const UtlString& hash)
{
UtlBoolean foundTransaction = FALSE;
SipTransaction* aTransaction = NULL;
UtlString matchTransaction(hash);
UtlHashBagIterator iterator(mTransactions, &matchTransaction);
while ((aTransaction = (SipTransaction*) iterator()))
{
if(aTransaction == transaction)
{
foundTransaction = TRUE;
break;
}
}
if(!foundTransaction)
{
OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::transactionExists transaction: %p hash: %s not found\n",
transaction, hash.data());
}
return(foundTransaction);
}
/* //////////////////////////// PROTECTED ///////////////////////////////// */
/* //////////////////////////// PRIVATE /////////////////////////////////// */
/* ============================ FUNCTIONS ================================= */
<commit_msg>Fixed memory leak in SipTransactionList::removeOldTransactions. Array of pointers - new SipTransaction*[] was allocated, but never freed by delete []. This leak caused 904 bytes to be lost each time SipTransactionList::removeOldTransactions was executed and garbage collected something. This method is normally called by garbageCollection(), which in turn is called in SipUserAgent when no messages are in queue. However, under high load, there will always be messages in queue, and garbage collector won't be executed.<commit_after>//
// Copyright (C) 2004-2006 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// SYSTEM INCLUDES
#include <assert.h>
// APPLICATION INCLUDES
#include <utl/UtlString.h>
#include <utl/UtlHashBagIterator.h>
#include <net/SipTransaction.h>
#include <net/SipTransactionList.h>
#include <net/SipMessage.h>
#include <os/OsTask.h>
#include <os/OsEvent.h>
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
//#define TIME_LOG /* turns on timestamping of finding and garbage collecting transactions */
#ifdef TIME_LOG
# include <os/OsTimeLog.h>
#endif
// STATIC VARIABLE INITIALIZATIONS
/* //////////////////////////// PUBLIC //////////////////////////////////// */
/* ============================ CREATORS ================================== */
// Constructor
SipTransactionList::SipTransactionList() :
mTransactions(),
mListMutex(OsMutex::Q_FIFO)
{
}
// Copy constructor
SipTransactionList::SipTransactionList(const SipTransactionList& rSipTransactionList) :
mListMutex(OsMutex::Q_FIFO)
{
}
// Destructor
SipTransactionList::~SipTransactionList()
{
mTransactions.destroyAll();
}
/* ============================ MANIPULATORS ============================== */
// Assignment operator
SipTransactionList&
SipTransactionList::operator=(const SipTransactionList& rhs)
{
if (this == &rhs) // handle the assignment to self case
return *this;
return *this;
}
void SipTransactionList::addTransaction(SipTransaction* transaction,
UtlBoolean lockList)
{
if(lockList) lock();
mTransactions.insert(transaction);
#ifdef TEST_PRINT
osPrintf("***************************************\n");
osPrintf("inserting transaction %X\n",transaction);
osPrintf("***************************************\n");
#endif
if(lockList) unlock();
}
//: Find a transaction for the given message
SipTransaction*
SipTransactionList::findTransactionFor(const SipMessage& message,
UtlBoolean isOutgoing,
enum SipTransaction::messageRelationship& relationship)
{
SipTransaction* transactionFound = NULL;
UtlString callId;
SipTransaction::buildHash(message, isOutgoing, callId);
lock();
// See if the message knows its transaction
// DO NOT TOUCH THE CONTENTS of this transaction as it may no
// longer exist. It can only be used as an ID for the transaction.
SipTransaction* messageTransaction = message.getSipTransaction();
UtlString matchTransaction(callId);
UtlHashBagIterator iterator(mTransactions, &matchTransaction);
relationship = SipTransaction::MESSAGE_UNKNOWN;
while ((transactionFound = (SipTransaction*) iterator()))
{
// If the message knows its SIP transaction
// and the found transaction pointer does not match, skip the
// expensive relationship calculation
// The messageTransaction MUST BE TREATED AS OPAQUE
// as it may have been deleted.
if( messageTransaction && transactionFound != messageTransaction )
{
continue;
}
// If the transaction has never sent the original rquest
// it should never get a match for any messages.
if( messageTransaction == NULL // this message does not point to this TX
&& ((transactionFound->getState()) == SipTransaction::TRANSACTION_LOCALLY_INIITATED)
)
{
continue;
}
relationship = transactionFound->whatRelation(message, isOutgoing);
if(relationship == SipTransaction::MESSAGE_REQUEST ||
relationship == SipTransaction::MESSAGE_PROVISIONAL ||
relationship == SipTransaction::MESSAGE_FINAL ||
relationship == SipTransaction::MESSAGE_NEW_FINAL ||
relationship == SipTransaction::MESSAGE_CANCEL ||
relationship == SipTransaction::MESSAGE_CANCEL_RESPONSE ||
relationship == SipTransaction::MESSAGE_ACK ||
relationship == SipTransaction::MESSAGE_2XX_ACK ||
relationship == SipTransaction::MESSAGE_DUPLICATE)
{
break;
}
}
UtlBoolean isBusy = FALSE;
if(transactionFound == NULL)
{
relationship =
SipTransaction::MESSAGE_UNKNOWN;
}
else
{
isBusy = transactionFound->isBusy();
if(!isBusy)
{
transactionFound->markBusy();
}
}
unlock();
if(transactionFound && isBusy)
{
// If we cannot lock it, it does not exist
if(!waitUntilAvailable(transactionFound, callId))
{
if (OsSysLog::willLog(FAC_SIP, PRI_WARNING))
{
UtlString relationString;
SipTransaction::getRelationshipString(relationship, relationString);
OsSysLog::add(FAC_SIP, PRI_WARNING,
"SipTransactionList::findTransactionFor %p not available relation: %s",
transactionFound, relationString.data());
}
transactionFound = NULL;
}
}
#if 0 // enable only for transaction match debugging - log is confusing otherwise
UtlString relationString;
SipTransaction::getRelationshipString(relationship, relationString);
UtlString bytes;
int len;
message.getBytes(&bytes, &len);
OsSysLog::add(FAC_SIP, PRI_DEBUG
,"SipTransactionList::findTransactionFor %p %s %s %s"
# ifdef TIME_LOG
"\n\tTime Log %s"
# endif
,&message
,isOutgoing ? "OUTGOING" : "INCOMING"
,transactionFound ? "FOUND" : "NOT FOUND"
,relationString.data()
# ifdef TIME_LOG
,findTimeLog.data()
# endif
);
#endif
return(transactionFound);
}
void SipTransactionList::removeOldTransactions(long oldTransaction,
long oldInviteTransaction)
{
SipTransaction** transactionsToBeDeleted = NULL;
int deleteCount = 0;
int busyCount = 0;
# ifdef TIME_LOG
OsTimeLog gcTimes;
gcTimes.addEvent("start");
# endif
lock();
int numTransactions = mTransactions.entries();
if(numTransactions > 0)
{
UtlHashBagIterator iterator(mTransactions);
SipTransaction* transactionFound = NULL;
long transTime;
// Pull all of the transactions to be deleted out of the list
while((transactionFound = (SipTransaction*) iterator()))
{
if(transactionFound->isBusy()) busyCount++;
transTime = transactionFound->getTimeStamp();
// Invites need to be kept longer than other transactions
if(((!transactionFound->isMethod(SIP_INVITE_METHOD) &&
transTime < oldTransaction) ||
transTime < oldInviteTransaction) &&
! transactionFound->isBusy())
{
// Remove it from the list
mTransactions.removeReference(transactionFound);
OsSysLog::add(FAC_SIP, PRI_DEBUG, "removing transaction %p\n",transactionFound);
// Make sure we have a pointer array to hold it
if(transactionsToBeDeleted == NULL)
{
transactionsToBeDeleted =
new SipTransaction*[numTransactions];
}
// Put it in the pointer array
transactionsToBeDeleted[deleteCount] = transactionFound;
deleteCount++;
// Make sure the events waiting for the transaction
// to be available are signaled before we delete
// any of the transactions or we end up with
// incomplete transaction trees (i.e. deleted branches)
transactionFound->signalAllAvailable();
transactionFound = NULL;
}
}
}
unlock();
// We do not need the lock if the transactions have been
// removed from the list
if ( deleteCount || busyCount ) // do not log 'doing nothing when nothing to do', even at debug level
{
OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::removeOldTransactions deleting %d of %d transactions (%d busy)\n",
deleteCount , numTransactions, busyCount);
}
// Delete the transactions in the array
if (transactionsToBeDeleted)
{
# ifdef TIME_LOG
gcTimes.addEvent("start delete");
# endif
for(int txIndex = 0; txIndex < deleteCount; txIndex++)
{
delete transactionsToBeDeleted[txIndex];
# ifdef TIME_LOG
gcTimes.addEvent("transaction deleted");
# endif
}
# ifdef TIME_LOG
gcTimes.addEvent("finish delete");
# endif
/*
while((transactionFound = (SipTransaction*) iterator()))
{
transactionFound->stopTimers();
}
*/
delete [] transactionsToBeDeleted;
}
# ifdef TIME_LOG
UtlString timeString;
gcTimes.getLogString(timeString);
OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::removeOldTransactions "
"%s", timeString.data()
);
# endif
}
void SipTransactionList::stopTransactionTimers()
{
lock();
int numTransactions = mTransactions.entries();
if(numTransactions > 0)
{
UtlHashBagIterator iterator(mTransactions);
SipTransaction* transactionFound = NULL;
while((transactionFound = (SipTransaction*) iterator()))
{
transactionFound->stopTimers();
}
}
unlock();
}
void SipTransactionList::startTransactionTimers()
{
lock();
int numTransactions = mTransactions.entries();
if(numTransactions > 0)
{
UtlHashBagIterator iterator(mTransactions);
SipTransaction* transactionFound = NULL;
while((transactionFound = (SipTransaction*) iterator()))
{
transactionFound->startTimers();
}
}
unlock();
}
void SipTransactionList::deleteTransactionTimers()
{
lock();
int numTransactions = mTransactions.entries();
if(numTransactions > 0)
{
UtlHashBagIterator iterator(mTransactions);
SipTransaction* transactionFound = NULL;
while((transactionFound = (SipTransaction*) iterator()))
{
transactionFound->deleteTimers();
}
}
unlock();
}
void SipTransactionList::toString(UtlString& string)
{
lock();
string.remove(0);
UtlHashBagIterator iterator(mTransactions);
SipTransaction* transactionFound = NULL;
UtlString oneTransactionString;
while((transactionFound = (SipTransaction*) iterator()))
{
transactionFound->toString(oneTransactionString, FALSE);
string.append(oneTransactionString);
oneTransactionString.remove(0);
}
unlock();
}
void SipTransactionList::toStringWithRelations(UtlString& string,
SipMessage& message,
UtlBoolean isOutGoing)
{
lock();
string.remove(0);
UtlHashBagIterator iterator(mTransactions);
SipTransaction* transactionFound = NULL;
UtlString oneTransactionString;
SipTransaction::messageRelationship relation;
UtlString relationString;
while((transactionFound = (SipTransaction*) iterator()))
{
relation = transactionFound->whatRelation(message, isOutGoing);
SipTransaction::getRelationshipString(relation, relationString);
string.append(relationString);
string.append(" ");
transactionFound->toString(oneTransactionString, FALSE);
string.append(oneTransactionString);
oneTransactionString.remove(0);
string.append("\n");
}
unlock();
}
void SipTransactionList::lock()
{
mListMutex.acquire();
}
void SipTransactionList::unlock()
{
mListMutex.release();
}
UtlBoolean SipTransactionList::waitUntilAvailable(SipTransaction* transaction,
const UtlString& hash)
{
UtlBoolean exists;
UtlBoolean busy = FALSE;
int numTries = 0;
do
{
numTries++;
lock();
exists = transactionExists(transaction, hash);
if(exists)
{
busy = transaction->isBusy();
if(!busy)
{
transaction->markBusy();
unlock();
//#ifdef TEST_PRINT
OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p locked after %d tries\n",
transaction, numTries);
//#endif
}
else
{
// We set an event to be signaled when a
// transaction is released.
OsEvent* waitEvent = new OsEvent;
transaction->notifyWhenAvailable(waitEvent);
// Must unlock while we wait or there is a dead lock
unlock();
//#ifdef TEST_PRINT
OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p waiting on: %p after %d tries\n",
transaction, waitEvent, numTries);
//#endif
OsStatus waitStatus;
OsTime transBusyTimeout(1, 0);
int waitTime = 0;
do
{
if(waitTime > 0)
OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransactionList::waitUntilAvailable %p still waiting: %d",
transaction, waitTime);
waitStatus = waitEvent->wait(transBusyTimeout);
waitTime+=1;
}
while(waitStatus != OS_SUCCESS && waitTime < 30);
// If we were never signaled, then we signal the
// event so the other side knows that it has to
// free up the event
if(waitEvent->signal(-1) == OS_ALREADY_SIGNALED)
{
delete waitEvent;
waitEvent = NULL;
}
// If we bailed out before the event was signaled
// pretend the transaction does not exist.
if(waitStatus != OS_SUCCESS)
{
exists = FALSE;
}
if(waitTime > 1)
{
if (OsSysLog::willLog(FAC_SIP, PRI_WARNING))
{
UtlString transTree;
UtlString waitingTaskName;
OsTask* waitingTask = OsTask::getCurrentTask();
if(waitingTask) waitingTaskName = waitingTask->getName();
transaction->dumpTransactionTree(transTree, FALSE);
OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransactionList::waitUntilAvailable status: %d wait time: %d transaction: %p task: %s transaction tree: %s",
waitStatus, waitTime, transaction, waitingTaskName.data(), transTree.data());
}
}
//#ifdef TEST_PRINT
OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p done waiting after %d tries\n",
transaction, numTries);
//#endif
}
}
else
{
unlock();
//#ifdef TEST_PRINT
OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p gone after %d tries\n",
transaction, numTries);
//#endif
}
}
while(exists && busy);
return(exists && !busy);
}
void SipTransactionList::markAvailable(SipTransaction& transaction)
{
lock();
if(!transaction.isBusy())
{
UtlString transactionString;
transaction.toString(transactionString, FALSE);
OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransactionList::markAvailable transaction not locked: %s\n",
transactionString.data());
}
else
{
transaction.markAvailable();
}
unlock();
}
/* ============================ ACCESSORS ================================= */
/* ============================ INQUIRY =================================== */
UtlBoolean SipTransactionList::transactionExists(const SipTransaction* transaction,
const UtlString& hash)
{
UtlBoolean foundTransaction = FALSE;
SipTransaction* aTransaction = NULL;
UtlString matchTransaction(hash);
UtlHashBagIterator iterator(mTransactions, &matchTransaction);
while ((aTransaction = (SipTransaction*) iterator()))
{
if(aTransaction == transaction)
{
foundTransaction = TRUE;
break;
}
}
if(!foundTransaction)
{
OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::transactionExists transaction: %p hash: %s not found\n",
transaction, hash.data());
}
return(foundTransaction);
}
/* //////////////////////////// PROTECTED ///////////////////////////////// */
/* //////////////////////////// PRIVATE /////////////////////////////////// */
/* ============================ FUNCTIONS ================================= */
<|endoftext|> |
<commit_before>///
/// @file S2LoadBalancer.cpp
/// @brief The S2LoadBalancer evenly distributes the work load between
/// the threads in the computation of the special leaves.
///
/// Simply parallelizing the computation of the special leaves in the
/// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by
/// subdividing the sieve interval by the number of threads into
/// equally sized subintervals does not scale because the distribution
/// of the special leaves is highly skewed, especially if the interval
/// size is large and if the intervals are not adjacent. Also most
/// special leaves are in the first few segments whereas later on
/// there are very few special leaves.
///
/// Based on the above observations it is clear that we need some kind
/// of load balancing in order to scale our parallel algorithm for
/// computing the special leaves. Below are the ideas I used to
/// develop a load balancing algorithm which scales linearly up to a
/// large number of CPU cores (tested with 300 threads).
///
/// 1) Start with a tiny segment size of x^(1/3) / (log x * log log x)
/// and one segment per thread. Our algorithm uses equally sized
/// intervals, for each thread the interval_size is
/// segment_size * segments_per_thread and the threads process
/// adjacent intervals i.e.
/// [base + interval_size * thread_id, base + interval_size * (thread_id + 1)].
///
/// 2) If the relative standard deviation of the run times of the
/// threads is low then increase the segment size and/or segments
/// per thread, else if the relative standard deviation is large
/// then decrease the segment size and/or segments per thread. This
/// rule is derived from the fact that intervals with roughly the
/// same number of special leaves take about the same time to
/// process and the next intervals tend to have a similar
/// distribution of special leaves (especially if the interval size
/// is small).
///
/// 3) We can't use a static threshold for as to when the relative
/// standard deviation is low or large as this threshold varies for
/// different PC architectures e.g. 15 might be large relative
/// standard deviation for a quad-core CPU system whereas it is a
/// low standard deviation for a dual-socket system with 64 CPU
/// cores. So instead of using a static threshold we compare the
/// current relative standard deviation to the previous one.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <S2LoadBalancer.hpp>
#include <primecount-internal.hpp>
#include <aligned_vector.hpp>
#include <pmath.hpp>
#include <int128.hpp>
#include <stdint.h>
#include <algorithm>
#include <cmath>
using namespace std;
using namespace primecount;
namespace {
double get_average(aligned_vector<double>& timings)
{
size_t n = timings.size();
double sum = 0;
for (size_t i = 0; i < n; i++)
sum += timings[i];
return sum / n;
}
double relative_standard_deviation(aligned_vector<double>& timings)
{
size_t n = timings.size();
double average = get_average(timings);
double sum = 0;
if (average == 0)
return 0;
for (size_t i = 0; i < n; i++)
{
double mean = timings[i] - average;
sum += mean * mean;
}
double std_dev = sqrt(sum / max(1.0, n - 1.0));
double rsd = 100 * std_dev / average;
return rsd;
}
} // namespace
namespace primecount {
S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t z, int64_t threads) :
x_((double) x),
z_((double) z),
rsd_(40),
avg_seconds_(0),
count_(0)
{
double log_threads = max(1.0, log((double) threads));
decrease_dividend_ = max(0.5, log_threads / 3);
min_seconds_ = 0.02 * log_threads;
max_size_ = next_power_of_2(isqrt(z));
update_min_size(log(x_) * log(log(x_)));
}
double S2LoadBalancer::get_rsd() const
{
return rsd_;
}
int64_t S2LoadBalancer::get_min_segment_size() const
{
return min_size_;
}
bool S2LoadBalancer::decrease_size(double seconds, double decrease) const
{
return seconds > min_seconds_ &&
rsd_ > decrease;
}
bool S2LoadBalancer::increase_size(double seconds, double decrease) const
{
return seconds < avg_seconds_ &&
!decrease_size(seconds, decrease);
}
/// Used to decide whether to use a smaller or larger
/// segment_size and/or segments_per_thread.
///
double S2LoadBalancer::get_decrease_threshold(double seconds) const
{
double log_seconds = max(min_seconds_, log(seconds));
double dont_decrease = min(decrease_dividend_ / (seconds * log_seconds), rsd_);
return rsd_ + dont_decrease;
}
void S2LoadBalancer::update_avg_seconds(double seconds)
{
seconds = max(seconds, min_seconds_);
double dividend = avg_seconds_ * count_ + seconds;
avg_seconds_ = dividend / (count_ + 1);
count_++;
}
void S2LoadBalancer::update_min_size(double divisor)
{
double size = sqrt(z_) / max(1.0, divisor);
min_size_ = max((int64_t) (1 << 9), (int64_t) size);
min_size_ = next_power_of_2(min_size_);
}
/// Balance the load in the computation of the special leaves
/// by dynamically adjusting the segment_size and segments_per_thread.
/// @param timings Timings of the threads.
///
void S2LoadBalancer::update(int64_t low,
int64_t threads,
int64_t* segment_size,
int64_t* segments_per_thread,
aligned_vector<double>& timings)
{
double seconds = get_average(timings);
update_avg_seconds(seconds);
double decrease_threshold = get_decrease_threshold(seconds);
rsd_ = max(0.1, relative_standard_deviation(timings));
// if low > sqrt(z) we use a larger min_size_ as the
// special leaves are distributed more evenly
if (low > max_size_)
{
update_min_size(log(x_));
*segment_size = max(*segment_size, min_size_);
}
// 1 segment per thread
if (*segment_size < max_size_)
{
if (increase_size(seconds, decrease_threshold))
*segment_size <<= 1;
else if (decrease_size(seconds, decrease_threshold))
if (*segment_size > min_size_)
*segment_size >>= 1;
// near sqrt(z) there is a short peak of special
// leaves so we use the minium segment size
int64_t high = low + *segment_size * *segments_per_thread * threads;
if (low <= max_size_ && high > max_size_)
*segment_size = min_size_;
}
else // many segments per thread
{
double factor = decrease_threshold / rsd_;
factor = in_between(0.5, factor, 2);
double n = *segments_per_thread * factor;
n = max(1.0, n);
if ((n < *segments_per_thread && seconds > min_seconds_) ||
(n > *segments_per_thread && seconds < avg_seconds_))
{
*segments_per_thread = (int) n;
}
}
}
} // namespace
<commit_msg>Update S2LoadBalancer.cpp<commit_after>///
/// @file S2LoadBalancer.cpp
/// @brief The S2LoadBalancer evenly distributes the work load between
/// the threads in the computation of the special leaves.
///
/// Simply parallelizing the computation of the special leaves in the
/// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by
/// subdividing the sieve interval by the number of threads into
/// equally sized subintervals does not scale because the distribution
/// of the special leaves is highly skewed, especially if the interval
/// size is large and if the intervals are not adjacent. Also most
/// special leaves are in the first few segments whereas later on
/// there are very few special leaves.
///
/// Based on the above observations it is clear that we need some kind
/// of load balancing in order to scale our parallel algorithm for
/// computing the special leaves. Below are the ideas I used to
/// develop a load balancing algorithm which scales linearly up to a
/// large number of CPU cores (tested with 300 threads).
///
/// 1) Start with a tiny segment size of x^(1/3) / (log x * log log x)
/// and one segment per thread. Our algorithm uses equally sized
/// intervals, for each thread the interval_size is
/// segment_size * segments_per_thread and the threads process
/// adjacent intervals i.e.
/// [base + interval_size * thread_id, base + interval_size * (thread_id + 1)].
///
/// 2) If the relative standard deviation of the run times of the
/// threads is low then increase the segment size and/or segments
/// per thread, else if the relative standard deviation is large
/// then decrease the segment size and/or segments per thread. This
/// rule is derived from the observation that intervals with
/// roughly the same number of special leaves take about the same
/// time to process and the next intervals tend to have a similar
/// distribution of special leaves (especially if the interval size
/// is small).
///
/// 3) We can't use a static threshold for as to when the relative
/// standard deviation is low or large as this threshold varies for
/// different PC architectures e.g. 15 might be large relative
/// standard deviation for a quad-core CPU system whereas it is a
/// low standard deviation for a dual-socket system with 64 CPU
/// cores. So instead of using a static threshold we compare the
/// current relative standard deviation to the previous one.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <S2LoadBalancer.hpp>
#include <primecount-internal.hpp>
#include <aligned_vector.hpp>
#include <pmath.hpp>
#include <int128.hpp>
#include <stdint.h>
#include <algorithm>
#include <cmath>
using namespace std;
using namespace primecount;
namespace {
double get_average(aligned_vector<double>& timings)
{
size_t n = timings.size();
double sum = 0;
for (size_t i = 0; i < n; i++)
sum += timings[i];
return sum / n;
}
double relative_standard_deviation(aligned_vector<double>& timings)
{
size_t n = timings.size();
double average = get_average(timings);
double sum = 0;
if (average == 0)
return 0;
for (size_t i = 0; i < n; i++)
{
double mean = timings[i] - average;
sum += mean * mean;
}
double std_dev = sqrt(sum / max(1.0, n - 1.0));
double rsd = 100 * std_dev / average;
return rsd;
}
} // namespace
namespace primecount {
S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t z, int64_t threads) :
x_((double) x),
z_((double) z),
rsd_(40),
avg_seconds_(0),
count_(0)
{
double log_threads = max(1.0, log((double) threads));
decrease_dividend_ = max(0.5, log_threads / 3);
min_seconds_ = 0.02 * log_threads;
max_size_ = next_power_of_2(isqrt(z));
update_min_size(log(x_) * log(log(x_)));
}
double S2LoadBalancer::get_rsd() const
{
return rsd_;
}
int64_t S2LoadBalancer::get_min_segment_size() const
{
return min_size_;
}
bool S2LoadBalancer::decrease_size(double seconds, double decrease) const
{
return seconds > min_seconds_ &&
rsd_ > decrease;
}
bool S2LoadBalancer::increase_size(double seconds, double decrease) const
{
return seconds < avg_seconds_ &&
!decrease_size(seconds, decrease);
}
/// Used to decide whether to use a smaller or larger
/// segment_size and/or segments_per_thread.
///
double S2LoadBalancer::get_decrease_threshold(double seconds) const
{
double log_seconds = max(min_seconds_, log(seconds));
double dont_decrease = min(decrease_dividend_ / (seconds * log_seconds), rsd_);
return rsd_ + dont_decrease;
}
void S2LoadBalancer::update_avg_seconds(double seconds)
{
seconds = max(seconds, min_seconds_);
double dividend = avg_seconds_ * count_ + seconds;
avg_seconds_ = dividend / (count_ + 1);
count_++;
}
void S2LoadBalancer::update_min_size(double divisor)
{
double size = sqrt(z_) / max(1.0, divisor);
min_size_ = max((int64_t) (1 << 9), (int64_t) size);
min_size_ = next_power_of_2(min_size_);
}
/// Balance the load in the computation of the special leaves
/// by dynamically adjusting the segment_size and segments_per_thread.
/// @param timings Timings of the threads.
///
void S2LoadBalancer::update(int64_t low,
int64_t threads,
int64_t* segment_size,
int64_t* segments_per_thread,
aligned_vector<double>& timings)
{
double seconds = get_average(timings);
update_avg_seconds(seconds);
double decrease_threshold = get_decrease_threshold(seconds);
rsd_ = max(0.1, relative_standard_deviation(timings));
// if low > sqrt(z) we use a larger min_size_ as the
// special leaves are distributed more evenly
if (low > max_size_)
{
update_min_size(log(x_));
*segment_size = max(*segment_size, min_size_);
}
// 1 segment per thread
if (*segment_size < max_size_)
{
if (increase_size(seconds, decrease_threshold))
*segment_size <<= 1;
else if (decrease_size(seconds, decrease_threshold))
if (*segment_size > min_size_)
*segment_size >>= 1;
// near sqrt(z) there is a short peak of special
// leaves so we use the minium segment size
int64_t high = low + *segment_size * *segments_per_thread * threads;
if (low <= max_size_ && high > max_size_)
*segment_size = min_size_;
}
else // many segments per thread
{
double factor = decrease_threshold / rsd_;
factor = in_between(0.5, factor, 2);
double n = *segments_per_thread * factor;
n = max(1.0, n);
if ((n < *segments_per_thread && seconds > min_seconds_) ||
(n > *segments_per_thread && seconds < avg_seconds_))
{
*segments_per_thread = (int) n;
}
}
}
} // namespace
<|endoftext|> |
<commit_before>// -*- mode: c++ -*-
/* Copyright (c) 2013, Eddie Kohler
*
* 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, subject to the conditions
* listed in the Tamer LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Tamer LICENSE file; the license in that file is
* legally binding.
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <tamer/tamer.hh>
#include <tamer/fd.hh>
#include <tamer/bufferedio.hh>
using namespace tamer;
tamed void child(struct sockaddr_in* saddr, socklen_t saddr_len) {
tvars { tamer::fd cfd; int ret; tamer::buffer buf; size_t nwritten;
int write_rounds = 0; int wret = 0; std::string str; }
cfd = tamer::fd::socket(AF_INET, SOCK_STREAM, 0);
twait { cfd.connect((struct sockaddr*) saddr, saddr_len, make_event(ret)); }
while (cfd) {
if (wret == 0) {
twait { cfd.write("Hello\n", 6, nwritten, make_event(wret)); }
if (wret == 0 && nwritten == 6) {
++write_rounds;
if (write_rounds <= 6)
printf("W 0: Hello\n");
} else if (wret == 0)
wret = -ECANCELED;
}
twait { buf.take_until(cfd, '\n', 1024, str, make_event(ret)); }
if (ret != 0) {
printf("W error %s after %d\n", strerror(-wret), write_rounds);
break;
} else if (str.length())
printf("R %d: %s", ret, str.c_str());
}
cfd.close();
}
tamed void parent(tamer::fd& listenfd) {
tvars { tamer::fd cfd; int ret; tamer::buffer buf;
int n = 0; std::string str; }
twait { listenfd.accept(make_event(cfd)); }
while (cfd && n < 6) {
++n;
twait { buf.take_until(cfd, '\n', 1024, str, make_event(ret)); }
assert(ret == 0);
str = "Ret " + str;
twait { cfd.write(str, make_event()); }
}
cfd.shutdown(SHUT_RD);
while (cfd && n < 12) {
++n;
twait { cfd.write("Heh\n", 4, make_event(ret)); }
assert(ret == 0);
}
cfd.close();
listenfd.close();
}
int main(int, char *[]) {
tamer::initialize();
signal(SIGPIPE, SIG_IGN);
tamer::fd listenfd = tamer::tcp_listen(0);
assert(listenfd);
struct sockaddr_in saddr;
socklen_t saddr_len = sizeof(saddr);
int r = getsockname(listenfd.value(), (struct sockaddr*) &saddr, &saddr_len);
assert(r == 0);
pid_t p = fork();
if (p != 0) {
listenfd.close();
child(&saddr, saddr_len);
} else
parent(listenfd);
tamer::loop();
tamer::cleanup();
if (p != 0)
printf("Done\n");
}
<commit_msg>Still trying to figure out why Travis dislikes shutdown test.<commit_after>// -*- mode: c++ -*-
/* Copyright (c) 2013, Eddie Kohler
*
* 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, subject to the conditions
* listed in the Tamer LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Tamer LICENSE file; the license in that file is
* legally binding.
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <tamer/tamer.hh>
#include <tamer/fd.hh>
#include <tamer/bufferedio.hh>
using namespace tamer;
tamed void child(struct sockaddr_in* saddr, socklen_t saddr_len) {
tvars { tamer::fd cfd; int ret; tamer::buffer buf; std::string str;
int n = 0; }
cfd = tamer::fd::socket(AF_INET, SOCK_STREAM, 0);
twait { cfd.connect((struct sockaddr*) saddr, saddr_len, make_event(ret)); }
while (cfd && n < 6) {
++n;
twait { buf.take_until(cfd, '\n', 1024, str, make_event(ret)); }
assert(ret == 0);
str = "Ret " + str;
twait { cfd.write(str, make_event()); }
}
cfd.shutdown(SHUT_RD);
while (cfd && n < 12) {
++n;
twait { cfd.write("Heh\n", 4, make_event(ret)); }
assert(ret == 0);
}
cfd.shutdown(SHUT_WR);
twait { tamer::at_delay(2, make_event()); }
cfd.close();
}
tamed void parent(tamer::fd& listenfd) {
tvars { tamer::fd cfd; int ret; tamer::buffer buf; std::string str;
size_t nwritten; int write_rounds = 0; int wret = 0; }
twait { listenfd.accept(make_event(cfd)); }
while (cfd) {
if (wret == 0) {
twait { cfd.write("Hello\n", 6, nwritten, make_event(wret)); }
if (wret == 0 && nwritten == 6) {
++write_rounds;
if (write_rounds <= 6)
printf("W 0: Hello\n");
} else if (wret == 0)
wret = -ECANCELED;
}
twait { buf.take_until(cfd, '\n', 1024, str, make_event(ret)); }
if (ret != 0) {
printf("W error %s after %d\n", strerror(-wret), write_rounds);
break;
} else if (str.length())
printf("R %d: %s", ret, str.c_str());
else
printf("EOF\n");
}
}
int main(int, char *[]) {
tamer::initialize();
signal(SIGPIPE, SIG_IGN);
tamer::fd listenfd = tamer::tcp_listen(0);
assert(listenfd);
struct sockaddr_in saddr;
socklen_t saddr_len = sizeof(saddr);
int r = getsockname(listenfd.value(), (struct sockaddr*) &saddr, &saddr_len);
assert(r == 0);
pid_t p = fork();
if (p != 0)
parent(listenfd);
else {
listenfd.close();
child(&saddr, saddr_len);
}
tamer::loop();
tamer::cleanup();
if (p != 0) {
kill(p, 9);
printf("Done\n");
}
}
<|endoftext|> |
<commit_before>///
/// @file S2LoadBalancer.cpp
/// @brief The S2LoadBalancer evenly distributes the work load between
/// the threads in the computation of the special leaves.
///
/// Simply parallelizing the computation of the special leaves in the
/// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by
/// subdividing the sieve interval by the number of threads into
/// equally sized subintervals does not scale because the distribution
/// of the special leaves is highly skewed and most special leaves are
/// in the first few segments whereas later on there are very few
/// special leaves.
///
/// Based on the above observations it is clear that we need some kind
/// of load balancing in order to scale our parallel algorithm for
/// computing special leaves. Below are the ideas I used to develop a
/// load balancing algorithm that achieves a high load balance by
/// dynamically increasing or decreasing the interval size based on
/// the relative standard deviation of the thread run-times.
///
/// 1) Start with a tiny segment size of x^(1/3) / (log x * log log x)
/// and one segment per thread. Our algorithm uses equally sized
/// intervals, for each thread the interval_size is
/// segment_size * segments_per_thread and the threads process
/// adjacent intervals i.e.
/// [base + interval_size * thread_id, base + interval_size * (thread_id + 1)].
///
/// 2) If the relative standard deviation of the thread run-times is
/// large then we know the special leaves are distributed unevenly,
/// else if the relative standard deviation is low the special
/// leaves are more evenly distributed.
///
/// 3) If the special leaves are distributed unevenly then we can
/// increase the load balance by decreasing the interval_size.
/// Contrary if the special leaves are more evenly distributed
/// we can increase the interval_size in order to improve the
/// algorithm's efficiency.
///
/// 4) We can't use a static threshold for as to when the relative
/// standard deviation is low or large as this threshold varies for
/// different PC architectures. So instead we compare the current
/// relative standard deviation to the previous one in order to
/// decide whether to increase or decrease the interval_size.
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <S2LoadBalancer.hpp>
#include <aligned_vector.hpp>
#include <pmath.hpp>
#include <int128.hpp>
#include <stdint.h>
#include <algorithm>
#include <cmath>
using namespace std;
using namespace primecount;
namespace {
double get_average(aligned_vector<double>& timings)
{
size_t n = timings.size();
double sum = 0;
for (size_t i = 0; i < n; i++)
sum += timings[i];
return sum / n;
}
double relative_standard_deviation(aligned_vector<double>& timings)
{
size_t n = timings.size();
double average = get_average(timings);
double sum = 0;
if (average == 0)
return 0;
for (size_t i = 0; i < n; i++)
{
double mean = timings[i] - average;
sum += mean * mean;
}
double std_dev = sqrt(sum / max(1.0, n - 1.0));
double rsd = 100 * std_dev / average;
return rsd;
}
} // namespace
namespace primecount {
S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t z, int64_t threads) :
x_((double) x),
z_((double) z),
rsd_(40),
avg_seconds_(0),
count_(0)
{
double log_threads = max(1.0, log((double) threads));
decrease_dividend_ = max(0.5, log_threads / 3);
min_seconds_ = 0.02 * log_threads;
max_size_ = next_power_of_2(isqrt(z));
update_min_size(log(x_) * log(log(x_)));
}
double S2LoadBalancer::get_rsd() const
{
return rsd_;
}
int64_t S2LoadBalancer::get_min_segment_size() const
{
return min_size_;
}
bool S2LoadBalancer::decrease_size(double seconds, double decrease) const
{
return seconds > min_seconds_ &&
rsd_ > decrease;
}
bool S2LoadBalancer::increase_size(double seconds, double decrease) const
{
return seconds < avg_seconds_ &&
!decrease_size(seconds, decrease);
}
/// Used to decide whether to use a smaller or larger
/// segment_size and/or segments_per_thread.
///
double S2LoadBalancer::get_decrease_threshold(double seconds) const
{
double log_seconds = max(min_seconds_, log(seconds));
double dont_decrease = min(decrease_dividend_ / (seconds * log_seconds), rsd_);
return rsd_ + dont_decrease;
}
void S2LoadBalancer::update_avg_seconds(double seconds)
{
seconds = max(seconds, min_seconds_);
double dividend = avg_seconds_ * count_ + seconds;
avg_seconds_ = dividend / (count_ + 1);
count_++;
}
void S2LoadBalancer::update_min_size(double divisor)
{
double size = sqrt(z_) / max(1.0, divisor);
min_size_ = max((int64_t) (1 << 9), (int64_t) size);
min_size_ = next_power_of_2(min_size_);
}
/// Balance the load in the computation of the special leaves
/// by dynamically adjusting the segment_size and segments_per_thread.
/// @param timings Timings of the threads.
///
void S2LoadBalancer::update(int64_t low,
int64_t threads,
int64_t* segment_size,
int64_t* segments_per_thread,
aligned_vector<double>& timings)
{
double seconds = get_average(timings);
update_avg_seconds(seconds);
double decrease_threshold = get_decrease_threshold(seconds);
rsd_ = max(0.1, relative_standard_deviation(timings));
// if low > sqrt(z) we use a larger min_size_ as the
// special leaves are distributed more evenly
if (low > max_size_)
{
update_min_size(log(x_));
*segment_size = max(*segment_size, min_size_);
}
// 1 segment per thread
if (*segment_size < max_size_)
{
if (increase_size(seconds, decrease_threshold))
*segment_size <<= 1;
else if (decrease_size(seconds, decrease_threshold))
if (*segment_size > min_size_)
*segment_size >>= 1;
// near sqrt(z) there is a short peak of special
// leaves so we use the minimum segment size
int64_t high = low + *segment_size * *segments_per_thread * threads;
if (low <= max_size_ && high > max_size_)
*segment_size = min_size_;
}
else // many segments per thread
{
double factor = decrease_threshold / rsd_;
factor = in_between(0.5, factor, 2);
double n = *segments_per_thread * factor;
n = max(1.0, n);
if ((n < *segments_per_thread && seconds > min_seconds_) ||
(n > *segments_per_thread && seconds < avg_seconds_))
{
*segments_per_thread = (int) n;
}
}
}
} // namespace
<commit_msg>Rename max_size_ to sqrtz_<commit_after>///
/// @file S2LoadBalancer.cpp
/// @brief The S2LoadBalancer evenly distributes the work load between
/// the threads in the computation of the special leaves.
///
/// Simply parallelizing the computation of the special leaves in the
/// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by
/// subdividing the sieve interval by the number of threads into
/// equally sized subintervals does not scale because the distribution
/// of the special leaves is highly skewed and most special leaves are
/// in the first few segments whereas later on there are very few
/// special leaves.
///
/// Based on the above observations it is clear that we need some kind
/// of load balancing in order to scale our parallel algorithm for
/// computing special leaves. Below are the ideas I used to develop a
/// load balancing algorithm that achieves a high load balance by
/// dynamically increasing or decreasing the interval size based on
/// the relative standard deviation of the thread run-times.
///
/// 1) Start with a tiny segment size of x^(1/3) / (log x * log log x)
/// and one segment per thread. Our algorithm uses equally sized
/// intervals, for each thread the interval_size is
/// segment_size * segments_per_thread and the threads process
/// adjacent intervals i.e.
/// [base + interval_size * thread_id, base + interval_size * (thread_id + 1)].
///
/// 2) If the relative standard deviation of the thread run-times is
/// large then we know the special leaves are distributed unevenly,
/// else if the relative standard deviation is low the special
/// leaves are more evenly distributed.
///
/// 3) If the special leaves are distributed unevenly then we can
/// increase the load balance by decreasing the interval_size.
/// Contrary if the special leaves are more evenly distributed
/// we can increase the interval_size in order to improve the
/// algorithm's efficiency.
///
/// 4) We can't use a static threshold for as to when the relative
/// standard deviation is low or large as this threshold varies for
/// different PC architectures. So instead we compare the current
/// relative standard deviation to the previous one in order to
/// decide whether to increase or decrease the interval_size.
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <S2LoadBalancer.hpp>
#include <aligned_vector.hpp>
#include <pmath.hpp>
#include <int128.hpp>
#include <stdint.h>
#include <algorithm>
#include <cmath>
using namespace std;
using namespace primecount;
namespace {
double get_average(aligned_vector<double>& timings)
{
size_t n = timings.size();
double sum = 0;
for (size_t i = 0; i < n; i++)
sum += timings[i];
return sum / n;
}
double relative_standard_deviation(aligned_vector<double>& timings)
{
size_t n = timings.size();
double average = get_average(timings);
double sum = 0;
if (average == 0)
return 0;
for (size_t i = 0; i < n; i++)
{
double mean = timings[i] - average;
sum += mean * mean;
}
double std_dev = sqrt(sum / max(1.0, n - 1.0));
double rsd = 100 * std_dev / average;
return rsd;
}
} // namespace
namespace primecount {
S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t z, int64_t threads) :
x_((double) x),
z_((double) z),
rsd_(40),
avg_seconds_(0),
count_(0)
{
sqrtz_ = isqrt(z);
double log_threads = max(1.0, log((double) threads));
decrease_dividend_ = max(0.5, log_threads / 3);
min_seconds_ = 0.02 * log_threads;
update_min_size(log(x_) * log(log(x_)));
}
double S2LoadBalancer::get_rsd() const
{
return rsd_;
}
int64_t S2LoadBalancer::get_min_segment_size() const
{
return min_size_;
}
bool S2LoadBalancer::decrease_size(double seconds, double decrease) const
{
return seconds > min_seconds_ &&
rsd_ > decrease;
}
bool S2LoadBalancer::increase_size(double seconds, double decrease) const
{
return seconds < avg_seconds_ &&
!decrease_size(seconds, decrease);
}
/// Used to decide whether to use a smaller or larger
/// segment_size and/or segments_per_thread.
///
double S2LoadBalancer::get_decrease_threshold(double seconds) const
{
double log_seconds = max(min_seconds_, log(seconds));
double dont_decrease = min(decrease_dividend_ / (seconds * log_seconds), rsd_);
return rsd_ + dont_decrease;
}
void S2LoadBalancer::update_avg_seconds(double seconds)
{
seconds = max(seconds, min_seconds_);
double dividend = avg_seconds_ * count_ + seconds;
avg_seconds_ = dividend / (count_ + 1);
count_++;
}
void S2LoadBalancer::update_min_size(double divisor)
{
double size = sqrt(z_) / max(1.0, divisor);
min_size_ = max((int64_t) (1 << 9), (int64_t) size);
min_size_ = next_power_of_2(min_size_);
}
/// Balance the load in the computation of the special leaves
/// by dynamically adjusting the segment_size and segments_per_thread.
/// @param timings Timings of the threads.
///
void S2LoadBalancer::update(int64_t low,
int64_t threads,
int64_t* segment_size,
int64_t* segments_per_thread,
aligned_vector<double>& timings)
{
double seconds = get_average(timings);
update_avg_seconds(seconds);
double decrease_threshold = get_decrease_threshold(seconds);
rsd_ = max(0.1, relative_standard_deviation(timings));
// if low > sqrt(z) we use a larger min_size_ as the
// special leaves are distributed more evenly
if (low > sqrtz_)
{
update_min_size(log(x_));
*segment_size = max(*segment_size, min_size_);
}
// 1 segment per thread
if (*segment_size < sqrtz_)
{
if (increase_size(seconds, decrease_threshold))
*segment_size <<= 1;
else if (decrease_size(seconds, decrease_threshold))
if (*segment_size > min_size_)
*segment_size >>= 1;
// near sqrt(z) there is a short peak of special
// leaves so we use the minimum segment size
int64_t high = low + *segment_size * *segments_per_thread * threads;
if (low <= sqrtz_ && high > sqrtz_)
*segment_size = min_size_;
}
else // many segments per thread
{
double factor = decrease_threshold / rsd_;
factor = in_between(0.5, factor, 2);
double n = *segments_per_thread * factor;
n = max(1.0, n);
if ((n < *segments_per_thread && seconds > min_seconds_) ||
(n > *segments_per_thread && seconds < avg_seconds_))
{
*segments_per_thread = (int) n;
}
}
}
} // namespace
<|endoftext|> |
<commit_before>#include <Transformation.h>
#include <MetaEvent.h>
#include <EventType.h>
#include <IO.h>
#include <IDIO.h>
#include <ostream>
#include <algorithm>
#include <numeric>
using namespace std;
class ScaleTransformer : public SimpleTransformer {
private:
using Storage = map<id::attribute::ID, MetaScale>;
Storage mScaleDeltas;
public:
using ScaleList = Storage;
static ScaleList scaleDiff(const EventType& a, const EventType& b) {
Storage result;
for(const AttributeType& aT : a) {
const AttributeType* temp = b.attribute(aT.id());
if(!temp)
continue;
ScaleType bS(temp->scale().num(), temp->scale().denom(), aT.scale().reference());
MetaScale mod=aT.scale();
mod/=bS;
result.insert(make_pair(aT.id(), mod));
}
return result;
}
ScaleTransformer(const EventType& out, const EventType& in)
: SimpleTransformer(out, in) {
mScaleDeltas = scaleDiff(out, in);
}
virtual void print(ostream& o) const {
o << "Rescale " << EventID(mOut) << ": \n";
for(const Storage::value_type& scaleOp : mScaleDeltas)
o << "\t" << id::attribute::name(scaleOp.first) << ": " << scaleOp.second << "\n";
}
protected:
virtual bool check(const MetaEvent& e) const { return true; }
virtual MetaEvent execute(const MetaEvent& event) const {
MetaEvent result = event;
for(MetaAttribute& a : result) {
auto it = mScaleDeltas.find(a.id());
if(it != mScaleDeltas.end() && (it->second.num() != 1 || it->second.denom() != 1))
a*=it->second;
}
return result;
}
};
class ScaleTransformation : public Transformation {
public:
ScaleTransformation()
: Transformation(Transformation::Type::attribute, 1, EventID::any)
{ }
virtual EventIDs in(EventID goal) const {
return {goal};
}
virtual vector<EventType> in(const EventType& goal, const EventType& provided) const {
ScaleTransformer::ScaleList scaleDiff = ScaleTransformer::scaleDiff(goal, provided);
auto apply = [](EventType eT, const pair<id::attribute::ID, MetaScale>& v){
EventType result = eT;
AttributeType& a = *result.attribute(v.first);
MetaScale aS = a.scale();
aS /= v.second;
a.scale() = aS;
return result;
};
return {accumulate(scaleDiff.begin(), scaleDiff.end(), goal, apply)};
}
virtual TransPtr create(const EventType& out, const EventTypes& in, const AbstractPolicy& policy) const {
if(in.size()!=1)
return TransPtr();
else
return TransPtr(new ScaleTransformer(out, in[0]));
}
virtual void print(ostream& o) const {
o << "Rescale Transformation";
}
} rescaleObj;
const Transformation& rescale=rescaleObj;
<commit_msg>ScaleTransform: remove unnecessary identity scales<commit_after>#include <Transformation.h>
#include <MetaEvent.h>
#include <EventType.h>
#include <IO.h>
#include <IDIO.h>
#include <ostream>
#include <algorithm>
#include <numeric>
using namespace std;
class ScaleTransformer : public SimpleTransformer {
private:
using Storage = map<id::attribute::ID, MetaScale>;
Storage mScaleDeltas;
public:
using ScaleList = Storage;
static ScaleList scaleDiff(const EventType& a, const EventType& b) {
Storage result;
for(const AttributeType& aT : a) {
const AttributeType* temp = b.attribute(aT.id());
if(!temp || (aT.scale().num() == temp->scale().num() && aT.scale().denom() == temp->scale().denom()))
continue;
ScaleType bS(temp->scale().num(), temp->scale().denom(), aT.scale().reference());
MetaScale mod=aT.scale();
mod/=bS;
result.insert(make_pair(aT.id(), mod));
}
return result;
}
ScaleTransformer(const EventType& out, const EventType& in)
: SimpleTransformer(out, in) {
mScaleDeltas = scaleDiff(out, in);
}
virtual void print(ostream& o) const {
o << "Rescale " << EventID(mOut) << ": \n";
for(const Storage::value_type& scaleOp : mScaleDeltas)
o << "\t" << id::attribute::name(scaleOp.first) << ": " << scaleOp.second << "\n";
}
protected:
virtual bool check(const MetaEvent& e) const { return true; }
virtual MetaEvent execute(const MetaEvent& event) const {
MetaEvent result = event;
for(MetaAttribute& a : result) {
auto it = mScaleDeltas.find(a.id());
if(it != mScaleDeltas.end() && (it->second.num() != 1 || it->second.denom() != 1))
a*=it->second;
}
return result;
}
};
class ScaleTransformation : public Transformation {
public:
ScaleTransformation()
: Transformation(Transformation::Type::attribute, 1, EventID::any)
{ }
virtual EventIDs in(EventID goal) const {
return {goal};
}
virtual vector<EventType> in(const EventType& goal, const EventType& provided) const {
ScaleTransformer::ScaleList scaleDiff = ScaleTransformer::scaleDiff(goal, provided);
auto apply = [](EventType eT, const pair<id::attribute::ID, MetaScale>& v){
EventType result = eT;
AttributeType& a = *result.attribute(v.first);
MetaScale aS = a.scale();
aS /= v.second;
a.scale() = aS;
return result;
};
return {accumulate(scaleDiff.begin(), scaleDiff.end(), goal, apply)};
}
virtual TransPtr create(const EventType& out, const EventTypes& in, const AbstractPolicy& policy) const {
if(in.size()!=1)
return TransPtr();
else
return TransPtr(new ScaleTransformer(out, in[0]));
}
virtual void print(ostream& o) const {
o << "Rescale Transformation";
}
} rescaleObj;
const Transformation& rescale=rescaleObj;
<|endoftext|> |
<commit_before>//---------------------------------------------------------------------------//
//!
//! \file GeneralEstimatorDimensionDiscretization.hpp
//! \author Alex Robinson
//! \brief General estimator dimension discretization class specialization
//! declarations
//!
//---------------------------------------------------------------------------//
// FACEMC Includes
#include "GeneralEstimatorDimensionDiscretization.hpp"
namespace FACEMC{
// Constructor
GeneralEstimatorDimensionDiscretization<COLLISION_NUMBER_DIMENSION>::GeneralEstimatorDimensionDiscretization( const Teuchos::Array<typename DT::dimensionType>& dimension_bin_boundaries )
: EstimatorDimensionDiscretization( COLLISION_NUMBER_DIMENSION ),
d_dimension_bin_boundaries( dimension_bin_boundaries )
{
// Make sure there is at least one bin
testPrecondition( dimension_bin_boundaries.size() >= 1 );
// Make sure the bins are valid
testPrecondition( dimension_bin_boundaries.front() >= DT::lowerBound() );
testPrecondition( dimension_bin_boundaries.back() <= DT::upperBound() );
// Make sure the bins are sorted
//testPrecondition( false );
}
// Return the dimension name that has been discretized
inline std::string GeneralEstimatorDimensionDiscretization<COLLISION_NUMBER_DIMENSION>::getDimensionName() const
{
return DT::name();
}
inline unsigned GeneralEstimatorDimensionDiscretization<COLLISION_NUMBER_DIMENSION>::getNumberOfBins() const
{
return d_dimension_bin_boundaries.size();
}
inline bool GeneralEstimatorDimensionDiscretization<COLLISION_NUMBER_DIMENSION>::isValueInDiscretization( const Teuchos::any& any_container ) const
{
typename DT::dimensionType value = DT::clarifyValue( any_container );
return value <= d_dimension_bin_boundaries.back();
}
// Calculate the index of the bin that the value falls in
unsigned GeneralEstimatorDimensionDiscretization<COLLISION_NUMBER_DIMENSION>::calculateBinIndex( const Teuchos::any& any_container ) const
{
// Make sure the value is in the dimension discretization
testPrecondition( isValueInDiscretization( any_container ) );
typename DT::dimensionType value = DT::clarifyValue( any_container );
typename Teuchos::Array<typename DT::dimensionType>::const_iterator
start, end, upper_bin_boundary;
start = d_dimension_bin_boundaries.begin();
end = d_dimension_bin_boundaries.end();
upper_bin_boundary = Search::binarySearchDiscreteData( start, end, value );
return std::distance(d_dimension_bin_boundaries.begin(), upper_bin_boundary);
}
// Print the boundaries of a bin
/*! \details Note: A new line character is not added after print the bin
* boundaries.
*/
void GeneralEstimatorDimensionDiscretization<COLLISION_NUMBER_DIMENSION>::printBoundariesOfBin( std::ostream& os, const unsigned bin_index ) const
{
// Make sure the bin requested is valid
testPrecondition( bin_index < getNumberOfBins() );
os << DT::name() << " Bin: [";
if( bin_index == 0u )
os << 0u;
else
os << d_dimension_bin_boundaries[bin_index-1u]+1u;
os << "," << d_dimension_bin_boundaries[bin_index] << "]";
}
// Print the dimension discretization
void GeneralEstimatorDimensionDiscretization<COLLISION_NUMBER_DIMENSION>::print( std::ostream& os ) const
{
os << DT::name() << " Bins: ";
for( unsigned i = 0; i < d_dimension_bin_boundaries.size(); ++i )
os << d_dimension_bin_boundaries[i] << " ";
}
} // end FACEMC namespace
//---------------------------------------------------------------------------//
// end GeneralEstimatorDimensionDiscretization.cpp
//---------------------------------------------------------------------------//
<commit_msg>Added a constructor precondition to the GeneralEstimatorDimensionDiscretization class that check that the bin boundaries are sorted.<commit_after>//---------------------------------------------------------------------------//
//!
//! \file GeneralEstimatorDimensionDiscretization.hpp
//! \author Alex Robinson
//! \brief General estimator dimension discretization class specialization
//! declarations
//!
//---------------------------------------------------------------------------//
// FACEMC Includes
#include "GeneralEstimatorDimensionDiscretization.hpp"
#include "SortAlgorithms.hpp"
namespace FACEMC{
// Constructor
GeneralEstimatorDimensionDiscretization<COLLISION_NUMBER_DIMENSION>::GeneralEstimatorDimensionDiscretization( const Teuchos::Array<typename DT::dimensionType>& dimension_bin_boundaries )
: EstimatorDimensionDiscretization( COLLISION_NUMBER_DIMENSION ),
d_dimension_bin_boundaries( dimension_bin_boundaries )
{
// Make sure there is at least one bin
testPrecondition( dimension_bin_boundaries.size() >= 1 );
// Make sure the bins are valid
testPrecondition( dimension_bin_boundaries.front() >= DT::lowerBound() );
testPrecondition( dimension_bin_boundaries.back() <= DT::upperBound() );
// Make sure the bins are sorted
testPrecondition( Sort::isSortedAscending( dimension_bin_boundaries.begin(),
dimension_bin_boundaries.end() ));
}
// Return the dimension name that has been discretized
inline std::string GeneralEstimatorDimensionDiscretization<COLLISION_NUMBER_DIMENSION>::getDimensionName() const
{
return DT::name();
}
inline unsigned GeneralEstimatorDimensionDiscretization<COLLISION_NUMBER_DIMENSION>::getNumberOfBins() const
{
return d_dimension_bin_boundaries.size();
}
inline bool GeneralEstimatorDimensionDiscretization<COLLISION_NUMBER_DIMENSION>::isValueInDiscretization( const Teuchos::any& any_container ) const
{
typename DT::dimensionType value = DT::clarifyValue( any_container );
return value <= d_dimension_bin_boundaries.back();
}
// Calculate the index of the bin that the value falls in
unsigned GeneralEstimatorDimensionDiscretization<COLLISION_NUMBER_DIMENSION>::calculateBinIndex( const Teuchos::any& any_container ) const
{
// Make sure the value is in the dimension discretization
testPrecondition( isValueInDiscretization( any_container ) );
typename DT::dimensionType value = DT::clarifyValue( any_container );
typename Teuchos::Array<typename DT::dimensionType>::const_iterator
start, end, upper_bin_boundary;
start = d_dimension_bin_boundaries.begin();
end = d_dimension_bin_boundaries.end();
upper_bin_boundary = Search::binarySearchDiscreteData( start, end, value );
return std::distance(d_dimension_bin_boundaries.begin(), upper_bin_boundary);
}
// Print the boundaries of a bin
/*! \details Note: A new line character is not added after print the bin
* boundaries.
*/
void GeneralEstimatorDimensionDiscretization<COLLISION_NUMBER_DIMENSION>::printBoundariesOfBin( std::ostream& os, const unsigned bin_index ) const
{
// Make sure the bin requested is valid
testPrecondition( bin_index < getNumberOfBins() );
os << DT::name() << " Bin: [";
if( bin_index == 0u )
os << 0u;
else
os << d_dimension_bin_boundaries[bin_index-1u]+1u;
os << "," << d_dimension_bin_boundaries[bin_index] << "]";
}
// Print the dimension discretization
void GeneralEstimatorDimensionDiscretization<COLLISION_NUMBER_DIMENSION>::print( std::ostream& os ) const
{
os << DT::name() << " Bins: ";
for( unsigned i = 0; i < d_dimension_bin_boundaries.size(); ++i )
os << d_dimension_bin_boundaries[i] << " ";
}
} // end FACEMC namespace
//---------------------------------------------------------------------------//
// end GeneralEstimatorDimensionDiscretization.cpp
//---------------------------------------------------------------------------//
<|endoftext|> |
<commit_before>/**
@file crema.cpp
@brief Main cremacc file and main() function
@copyright 2014 Assured Information Security, Inc.
@author Jacob Torrey <torreyj@ainfosec.com>
A main function to read in an input. It will parse and perform semantic
analysis on the input and either exit(0) if it passes both, -1 otherwise.
*/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "ast.h"
#include "codegen.h"
#include "ezOptionParser.hpp"
#include "llvm/CodeGen/AsmPrinter.h"
extern NBlock *rootBlock;
extern int yyparse();
int main(int argc, const char *argv[])
{
// Handling command-line options
ez::ezOptionParser opt;
opt.overview = "Crema Compiler for Sub-Turing Complete Programs";
opt.syntax = "cremacc [OPTIONS]";
opt.footer = "\n(C) 2014 Assured Information Security, Inc.\n";
opt.add("", 0, 0, 0, "Prints this help", "-h");
opt.add("", 0, 0, 0, "Parse only: Will halt after parsing and pretty-printing the AST for the input program", "-p");
opt.add("", 0, 0, 0, "Semantic check only: Will halt after parsing, pretty-printing and performing semantic checks on the AST for the input program", "-s");
opt.add("", 0, 1, 0, "Print LLVM Assembly to file.", "-c");
opt.add("", 0, 0, 0, "Run generated code", "-r");
opt.add("", 0, 1, 0, "Read input from file instead of stdin", "-f"); // TODO!
opt.parse(argc, argv);
if (opt.isSet("-h"))
{
std::string usage;
opt.getUsage(usage);
std::cout << usage;
return 0;
}
// Parse input
yyparse();
if (opt.isSet("-p"))
{
return 0;
}
// Perform semantic checks
if (rootBlock)
{
std::cout << *rootBlock << std::endl;
if (rootBlock->semanticAnalysis(&rootCtx))
{
std::cout << "Passed semantic analysis!" << std::endl;
}
else
{
std::cout << "Failed semantic analysis!" << std::endl;
return -1;
}
}
if (opt.isSet("-s"))
{
return 0;
}
// Code Generation
std::cout << "Generating LLVM IR bytecode" << std::endl;
rootCodeGenCtx.codeGen(rootBlock);
std::cout << "Dumping generated LLVM bytecode" << std::endl;
rootCodeGenCtx.dump();
if (opt.isSet("-c"))
{
FILE *outFile;
outFile = freopen(argv[2],"w",stderr);
rootCodeGenCtx.dump();
fclose(outFile);
std::ostringstream oss;
oss << "clang " << argv[2] << " stdlib/stdlib.c";
std::string cmd = oss.str();
std::system(cmd.c_str());
std::system("./a.out; echo $?;");
}
// LLVM IR JIT Execution
if (opt.isSet("-r"))
{
std::cout << "Running program:" << std::endl;
std::cout << "Return value: " << rootCodeGenCtx.runProgram().IntVal.toString(10, true) << std::endl;
std::cout << "Program run successfully!" << std::endl;
}
return 0;
}
<commit_msg>Now accepts input files with -f flag, outputs LLVM assembly with -c flag, and executes and prints the return value<commit_after>/**
@file crema.cpp
@brief Main cremacc file and main() function
@copyright 2014 Assured Information Security, Inc.
@author Jacob Torrey <torreyj@ainfosec.com>
A main function to read in an input. It will parse and perform semantic
analysis on the input and either exit(0) if it passes both, -1 otherwise.
*/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "ast.h"
#include "codegen.h"
#include "ezOptionParser.hpp"
#include "llvm/CodeGen/AsmPrinter.h"
extern NBlock *rootBlock;
extern int yyparse();
extern "C" FILE *yyin;
int main(int argc, const char *argv[])
{
// Handling command-line options
ez::ezOptionParser opt;
opt.overview = "Crema Compiler for Sub-Turing Complete Programs";
opt.syntax = "cremacc [OPTIONS]";
opt.footer = "\n(C) 2014 Assured Information Security, Inc.\n";
opt.add("", 0, 0, 0, "Prints this help", "-h");
opt.add("", 0, 0, 0, "Parse only: Will halt after parsing and pretty-printing the AST for the input program", "-p");
opt.add("", 0, 0, 0, "Semantic check only: Will halt after parsing, pretty-printing and performing semantic checks on the AST for the input program", "-s");
opt.add("", 0, 1, 0, "Print LLVM Assembly to file.", "-c");
opt.add("", 0, 0, 0, "Run generated code", "-r");
opt.add("", 0, 1, 0, "Read input from file instead of stdin", "-f"); // TODO!
opt.parse(argc, argv);
if (opt.isSet("-h"))
{
std::string usage;
opt.getUsage(usage);
std::cout << usage;
return 0;
}
// Parse input
if (opt.isSet("-f")) {
// searches for the -f flag
int i=0;
while (argv[i] != std::string("-f"))
++i;
// reads the file name string after the -f flag
FILE *inFile = fopen(argv[i+1],"r");
if (!inFile)
std::cout << "Cannot open file, " << argv[i+1] << ".\n" << "Usage: ./cremacc -f <input file>\n";
yyin = inFile;
// feeds the input file into cremacc
do {
yyparse();
} while (!feof(yyin));
}
else
yyparse(); // no -f flag will produce the commandline cremacc
if (opt.isSet("-p"))
{
return 0;
}
// Perform semantic checks
if (rootBlock)
{
std::cout << *rootBlock << std::endl;
if (rootBlock->semanticAnalysis(&rootCtx))
{
std::cout << "Passed semantic analysis!" << std::endl;
}
else
{
std::cout << "Failed semantic analysis!" << std::endl;
return -1;
}
}
if (opt.isSet("-s"))
{
return 0;
}
// Code Generation
std::cout << "Generating LLVM IR bytecode" << std::endl;
rootCodeGenCtx.codeGen(rootBlock);
std::cout << "Dumping generated LLVM bytecode" << std::endl;
rootCodeGenCtx.dump();
if (opt.isSet("-c"))
{
// searches for the -c flag
int i=0;
while (argv[i] != std::string("-c"))
++i;
// writes output LLVM assembly to argument after -c flag
FILE *outFile;
outFile = freopen(argv[i+1],"w",stderr);
rootCodeGenCtx.dump();
fclose(outFile);
std::ostringstream oss;
std::cout << "Linking with stdlib.c using clang...\n";
oss << "clang " << argv[i+1] << " stdlib/stdlib.c";
std::string cmd = oss.str();
// runs the command: clang <.ll filename> <library files>
std::system(cmd.c_str());
std::cout << "Executing program and printing the return value...\n";
// executes the program ./a.out and prints the return value
std::system("./a.out; echo $?;");
}
// LLVM IR JIT Execution
if (opt.isSet("-r"))
{
std::cout << "Running program:" << std::endl;
std::cout << "Return value: " << rootCodeGenCtx.runProgram().IntVal.toString(10, true) << std::endl;
std::cout << "Program run successfully!" << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "../include/TamuraDistance.h"
using namespace cv;
using namespace std;
double TamuraDistance::calc(const ImageData &dat1, const ImageData &dat2) {
Mat S_best1 = calc_granularity_sbest(dat1.rgb_img);
Mat S_best2 = calc_granularity_sbest(dat2.rgb_img);
cout << "S_best histograms:" << endl;
Vec2f hist_range(pow(2,kmin), pow(2,kmax)+1);
int nbins = hist_range[1] - hist_range[0];
cout << nbins << " bins, range " << hist_range << " (start inclusive, end exclusive)" << endl;
Mat hist1 = HistogramCalculator().calc_1d_hist(S_best1, nbins, hist_range);
Mat hist2 = HistogramCalculator().calc_1d_hist(S_best2, nbins, hist_range);
cout << hist1 << endl << hist2 << endl;
//cout << "total " << sum(hist1)[0] << "," << sum(hist2)[0] << " expected " << dat2.rgb_img.total() << endl;
double F_crs1 = mean(S_best1)[0], F_crs2 = mean(S_best2)[0];
cout << "F_crs: " << Vec2d(F_crs1, F_crs2) << endl;
return fabs(F_crs1 - F_crs2);
}
string TamuraDistance::get_class_name() {
return "Tamura-Granularity-Distance";
}
Mat TamuraDistance::calc_granularity_sbest(Mat bgr_img) {
//vector<Mat> A_k_list;
//vector<Mat> E_k_list;
Mat gray_img;
cvtColor(bgr_img, gray_img, CV_BGR2GRAY);
/*
imshow("a", gray_img);
imshow("b", translate_img(gray_img, 100, 50));
waitKey(0);
exit(1);
*/
Mat S_best_k(bgr_img.size(), CV_32F);
Mat S_best_maxval(bgr_img.size(), CV_64F, Scalar(0));
for (int k = kmin; k <= kmax; k++) {
if(k == 0) {
cout << "k=0: skipping mean calculation" << endl;
} else {
Mat A_k;
int k_pow = pow(2, k - 1);
/*
for (int x = 0; x < bgr_img.rows; x++) {
for (int y = 0; y < bgr_img.cols; y++) {
double sum = 0;
for (int i = x - k_pow; i < x + k_pow; i++) {
for (int j = y - k_pow; j < y + k_pow; j++) {
// Out of range pixels are obtained by mirroring at the edge alt: BORDER_WRAP
sum += gray_img.at<uchar>(borderInterpolate(i, gray_img.rows, BORDER_REFLECT_101), borderInterpolate(j, gray_img.cols, BORDER_REFLECT_101));
}
}
A_k.at<double>(x, y) = sum / pow(2, 2 * k);
}
}
*/
Size filter_size(2*k_pow, 2*k_pow);
boxFilter(gray_img, A_k, CV_64F, filter_size, Point(-1,-1), true, BORDER_REFLECT_101);
//cout << "A_k corners: " << Vec4f(A_k.at<float>(0,0),A_k.at<float>(A_k.rows-1,0),A_k.at<float>(0,A_k.cols-1),A_k.at<float>(A_k.rows-1,A_k.cols-1)) << endl;
//A_k /= pow(2, 2 * k);
//A_k_list.push_back(A_k);
/*
Mat E_k_h(bgr_img.size(), CV_64F), E_k_v(bgr_img.size(), CV_64F);
for (int x = 0; x < bgr_img.rows; x++) {
for (int y = 0; y < bgr_img.cols; y++) {
E_k_h.at<double>(x, y) = fabs(A_k.at<double>(borderInterpolate(x + k_pow, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y, A_k.cols, BORDER_REFLECT_101)) - A_k.at<double>(borderInterpolate(x - k_pow, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y, A_k.cols, BORDER_REFLECT_101)));
E_k_v.at<double>(x, y) = fabs(A_k.at<double>(borderInterpolate(x, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y + k_pow, A_k.cols, BORDER_REFLECT_101)) - A_k.at<double>(borderInterpolate(x, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y - k_pow, A_k.cols, BORDER_REFLECT_101)));
double maxval = max(E_k_h.at<double>(x, y), E_k_v.at<double>(x, y));
if (maxval > S_best_maxval.at<double>(x, y)) {
S_best_maxval.at<double>(x, y) = maxval;
S_best_k.at<int>(x, y) = pow(2, k);
}
}
}
*/
/*
Mat dst;
normalize(A_k, dst, 0, 1, cv::NORM_MINMAX);
imshow("test", dst);
imshow("test2", translateImg(dst, 20, 30));
waitKey(0);
*/
Mat E_k_h;
cv::absdiff(translate_img(A_k, k_pow, 0), translate_img(A_k, -k_pow, 0), E_k_h);
Mat E_k_v;
cv::absdiff(translate_img(A_k, 0, k_pow), translate_img(A_k, 0, -k_pow), E_k_v);
/*
for (int x = 0; x < bgr_img.rows; x++) {
for (int y = 0; y < bgr_img.cols; y++) {
double maxval = max(E_k_h.at<double>(x, y), E_k_v.at<double>(x, y));
if (maxval > S_best_maxval.at<double>(x, y)) {
S_best_maxval.at<double>(x, y) = maxval;
S_best_k.at<int>(x, y) = pow(2, k);
}
}
}
*/
MatExpr maxi_mask = (E_k_h > S_best_maxval) | (E_k_v > S_best_maxval);
S_best_k.setTo(pow(2, k), maxi_mask);
S_best_maxval = cv::max(S_best_maxval, cv::max(E_k_h, E_k_v));
}
//E_k_list.push_back(E_k_h);
//E_k_list.push_back(E_k_v);
}
//Mat F_crs;
//normalize(S_best_k, F_crs, )
/*
//Mat res;
//boxFilter(A_k_list[3], res, -1, Size(8, 8));
//cout << (res == A_k_list[3]) << endl;
Mat dst;
normalize(A_k_list.at(3), dst, 0, 1, cv::NORM_MINMAX);
imshow("test", dst);
waitKey(0);
//imshow("abc", A_k_list.front());
//waitKey(0);
return 8;
//*/
//double minv, maxv;
//minMaxLoc(S_best_k, &minv, &maxv);
//cout << "values min " << minv << " max " << maxv << endl;
//cout << "corners: " << Vec4f(S_best_k.at<float>(0,0),hist.at<float>(S_best_k.rows-1,0),hist.at<float>(0,S_best_k.cols-1),hist.at<float>(S_best_k.rows-1,S_best_k.cols-1)) << endl;
//vector<Point> locations;
//findNonZero(S_best_k == 0, locations);
//cout << "zero locations " << locations << endl;
//cout << "S_best_k" << S_best_k << endl;
//double F_crs = cv::sum(S_best_k)[0] / S_best_k.total();
//return mean(S_best_k)[0];
return S_best_k;
}
Mat TamuraDistance::translate_img(Mat img, int x, int y) {
Mat trans_mat = (Mat_<double>(2,3) << 1, 0, x, 0, 1, y);
Mat res;
warpAffine(img,res,trans_mat,img.size(), INTER_LINEAR, BORDER_REFLECT_101);
return res;
}
<commit_msg>added mean calculation of multiple max k<commit_after>#include "../include/TamuraDistance.h"
using namespace cv;
using namespace std;
double TamuraDistance::calc(const ImageData &dat1, const ImageData &dat2) {
Mat S_best1 = calc_granularity_sbest(dat1.rgb_img);
Mat S_best2 = calc_granularity_sbest(dat2.rgb_img);
cout << "S_best histograms:" << endl;
Vec2f hist_range(pow(2,kmin), pow(2,kmax)+1);
int nbins = hist_range[1] - hist_range[0];
cout << nbins << " bins, range " << hist_range << " (start inclusive, end exclusive)" << endl;
Mat hist1 = HistogramCalculator().calc_1d_hist(S_best1, nbins, hist_range);
Mat hist2 = HistogramCalculator().calc_1d_hist(S_best2, nbins, hist_range);
cout << hist1 << endl << hist2 << endl;
//cout << "total " << sum(hist1)[0] << "," << sum(hist2)[0] << " expected " << dat2.rgb_img.total() << endl;
double F_crs1 = mean(S_best1)[0], F_crs2 = mean(S_best2)[0];
cout << "F_crs: " << Vec2d(F_crs1, F_crs2) << endl;
return fabs(F_crs1 - F_crs2);
}
string TamuraDistance::get_class_name() {
return "Tamura-Granularity-Distance";
}
Mat TamuraDistance::calc_granularity_sbest(Mat bgr_img) {
//vector<Mat> A_k_list;
//vector<Mat> E_k_list;
Mat gray_img;
cvtColor(bgr_img, gray_img, CV_BGR2GRAY);
Mat S_best_k(bgr_img.size(), CV_32F);
Mat S_best_maxval(bgr_img.size(), CV_64F, Scalar(0));
Mat S_num_best_ks(bgr_img.size(), CV_32F, Scalar(1));
for (int k = kmin; k <= kmax; k++) {
if(k == 0) {
cout << "k=0: skipping mean calculation" << endl;
} else {
Mat A_k;
int k_pow = pow(2, k - 1);
/*
for (int x = 0; x < bgr_img.rows; x++) {
for (int y = 0; y < bgr_img.cols; y++) {
double sum = 0;
for (int i = x - k_pow; i < x + k_pow; i++) {
for (int j = y - k_pow; j < y + k_pow; j++) {
// Out of range pixels are obtained by mirroring at the edge alt: BORDER_WRAP
sum += gray_img.at<uchar>(borderInterpolate(i, gray_img.rows, BORDER_REFLECT_101), borderInterpolate(j, gray_img.cols, BORDER_REFLECT_101));
}
}
A_k.at<double>(x, y) = sum / pow(2, 2 * k);
}
}
*/
Size filter_size(2*k_pow, 2*k_pow);
boxFilter(gray_img, A_k, CV_64F, filter_size, Point(-1,-1), true, BORDER_REFLECT_101);
//cout << "A_k corners: " << Vec4f(A_k.at<float>(0,0),A_k.at<float>(A_k.rows-1,0),A_k.at<float>(0,A_k.cols-1),A_k.at<float>(A_k.rows-1,A_k.cols-1)) << endl;
//A_k /= pow(2, 2 * k);
//A_k_list.push_back(A_k);
/*
Mat E_k_h(bgr_img.size(), CV_64F), E_k_v(bgr_img.size(), CV_64F);
for (int x = 0; x < bgr_img.rows; x++) {
for (int y = 0; y < bgr_img.cols; y++) {
E_k_h.at<double>(x, y) = fabs(A_k.at<double>(borderInterpolate(x + k_pow, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y, A_k.cols, BORDER_REFLECT_101)) - A_k.at<double>(borderInterpolate(x - k_pow, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y, A_k.cols, BORDER_REFLECT_101)));
E_k_v.at<double>(x, y) = fabs(A_k.at<double>(borderInterpolate(x, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y + k_pow, A_k.cols, BORDER_REFLECT_101)) - A_k.at<double>(borderInterpolate(x, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y - k_pow, A_k.cols, BORDER_REFLECT_101)));
double maxval = max(E_k_h.at<double>(x, y), E_k_v.at<double>(x, y));
if (maxval > S_best_maxval.at<double>(x, y)) {
S_best_maxval.at<double>(x, y) = maxval;
S_best_k.at<int>(x, y) = pow(2, k);
}
}
}
*/
/*
Mat dst;
normalize(A_k, dst, 0, 1, cv::NORM_MINMAX);
imshow("test", dst);
imshow("test2", translateImg(dst, 20, 30));
waitKey(0);
*/
Mat E_k_h;
cv::absdiff(translate_img(A_k, k_pow, 0), translate_img(A_k, -k_pow, 0), E_k_h);
Mat E_k_v;
cv::absdiff(translate_img(A_k, 0, k_pow), translate_img(A_k, 0, -k_pow), E_k_v);
/*
for (int x = 0; x < bgr_img.rows; x++) {
for (int y = 0; y < bgr_img.cols; y++) {
double maxval = max(E_k_h.at<double>(x, y), E_k_v.at<double>(x, y));
if (maxval > S_best_maxval.at<double>(x, y)) {
S_best_maxval.at<double>(x, y) = maxval;
S_best_k.at<int>(x, y) = pow(2, k);
}
}
}
*/
/*
MatExpr maxi_mask = (E_k_h > S_best_maxval) | (E_k_v > S_best_maxval);
S_best_k.setTo(pow(2, k), maxi_mask);
MatExpr same_mask = E_k_h == S_best_maxval;
S_best_maxval = cv::max(S_best_maxval, cv::max(E_k_h, E_k_v));
*/
MatExpr greater_mask = E_k_h > S_best_maxval;
S_best_k.setTo(k, greater_mask);
S_num_best_ks.setTo(1, greater_mask);
MatExpr equal_mask = E_k_h == S_best_maxval;
add(S_best_k, k, S_best_k, equal_mask);
add(S_num_best_ks, 1, S_num_best_ks, equal_mask);
S_best_maxval = cv::max(S_best_maxval, E_k_h);
// TODO fun
MatExpr greater_mask2 = E_k_v > S_best_maxval;
S_best_k.setTo(k, greater_mask2);
S_num_best_ks.setTo(1, greater_mask2);
MatExpr equal_mask2 = E_k_v == S_best_maxval;
add(S_best_k, k, S_best_k, equal_mask2);
add(S_num_best_ks, 1, S_num_best_ks, equal_mask2);
S_best_maxval = cv::max(S_best_maxval, E_k_v);
}
}
divide(S_best_k, S_num_best_ks, S_best_k);
// S_best_k = 2 ^ S_best_k
exp(S_best_k * std::log(2), S_best_k);
return S_best_k;
}
Mat TamuraDistance::translate_img(Mat img, int x, int y) {
Mat trans_mat = (Mat_<double>(2,3) << 1, 0, x, 0, 1, y);
Mat res;
warpAffine(img,res,trans_mat,img.size(), INTER_LINEAR, BORDER_REFLECT_101);
return res;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2009, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "derive.h"
#include "output.h"
namespace ledger {
namespace {
struct xact_template_t
{
optional<date_t> date;
optional<string> code;
optional<string> note;
mask_t payee_mask;
struct post_template_t {
bool from;
optional<mask_t> account_mask;
optional<amount_t> amount;
post_template_t() : from(false) {}
};
std::list<post_template_t> posts;
xact_template_t() {}
void dump(std::ostream& out) const
{
if (date)
out << _("Date: ") << *date << std::endl;
else
out << _("Date: <today>") << std::endl;
if (code)
out << _("Code: ") << *code << std::endl;
if (note)
out << _("Note: ") << *note << std::endl;
if (payee_mask.empty())
out << _("Payee mask: INVALID (template expression will cause an error)")
<< std::endl;
else
out << _("Payee mask: ") << payee_mask << std::endl;
if (posts.empty()) {
out << std::endl
<< _("<Posting copied from last related transaction>")
<< std::endl;
} else {
bool has_only_from = true;
bool has_only_to = true;
foreach (const post_template_t& post, posts) {
if (post.from)
has_only_to = false;
else
has_only_from = false;
}
foreach (const post_template_t& post, posts) {
straccstream accum;
out << std::endl
<< ACCUM(accum << _("[Posting \"%1\"]_")
<< (post.from ? _("from") : _("to")))
<< std::endl;
if (post.account_mask)
out << _(" Account mask: ") << *post.account_mask << std::endl;
else if (post.from)
out << _(" Account mask: <use last of last related accounts>") << std::endl;
else
out << _(" Account mask: <use first of last related accounts>") << std::endl;
if (post.amount)
out << _(" Amount: ") << *post.amount << std::endl;
}
}
}
};
xact_template_t
args_to_xact_template(value_t::sequence_t::const_iterator begin,
value_t::sequence_t::const_iterator end)
{
regex date_mask(_("([0-9]+(?:[-/.][0-9]+)?(?:[-/.][0-9]+))?"));
regex dow_mask(_("(sun|mon|tue|wed|thu|fri|sat)"));
smatch what;
xact_template_t tmpl;
bool check_for_date = true;
xact_template_t::post_template_t * post = NULL;
for (; begin != end; begin++) {
if (check_for_date &&
regex_match((*begin).to_string(), what, date_mask)) {
tmpl.date = parse_date(what[0]);
check_for_date = false;
}
else if (check_for_date &&
regex_match((*begin).to_string(), what, dow_mask)) {
short dow = static_cast<short>(string_to_day_of_week(what[0]));
date_t date = CURRENT_DATE() - date_duration(1);
while (date.day_of_week() != dow)
date -= date_duration(1);
tmpl.date = date;
check_for_date = false;
}
else {
string arg = (*begin).to_string();
if (arg == "at") {
tmpl.payee_mask = (*++begin).to_string();
}
else if (arg == "to" || arg == "from") {
if (! post || post->account_mask) {
tmpl.posts.push_back(xact_template_t::post_template_t());
post = &tmpl.posts.back();
}
post->account_mask = mask_t((*++begin).to_string());
post->from = arg == "from";
}
else if (arg == "on") {
tmpl.date = parse_date((*++begin).to_string());
check_for_date = false;
}
else if (arg == "code") {
tmpl.code = (*++begin).to_string();
}
else if (arg == "note") {
tmpl.note = (*++begin).to_string();
}
else if (arg == "rest") {
; // just ignore this argument
}
else {
// Without a preposition, it is either:
//
// A payee, if we have not seen one
// An account or an amount, if we have
// An account if an amount has just been seen
// An amount if an account has just been seen
if (tmpl.payee_mask.empty()) {
tmpl.payee_mask = arg;
}
else {
amount_t amt;
optional<mask_t> account;
if (! amt.parse(arg, amount_t::PARSE_SOFT_FAIL |
amount_t::PARSE_NO_MIGRATE))
account = mask_t(arg);
if (! post ||
(account && post->account_mask) ||
(! account && post->amount)) {
tmpl.posts.push_back(xact_template_t::post_template_t());
post = &tmpl.posts.back();
}
if (account) {
post->from = false;
post->account_mask = account;
} else {
post->amount = amt;
}
}
}
}
}
if (! tmpl.posts.empty()) {
bool has_only_from = true;
bool has_only_to = true;
// A single account at the end of the line is the "from" account
if (tmpl.posts.size() > 1 &&
tmpl.posts.back().account_mask && ! tmpl.posts.back().amount)
tmpl.posts.back().from = true;
foreach (xact_template_t::post_template_t& post, tmpl.posts) {
if (post.from)
has_only_to = false;
else
has_only_from = false;
}
if (has_only_from) {
tmpl.posts.push_front(xact_template_t::post_template_t());
}
else if (has_only_to) {
tmpl.posts.push_back(xact_template_t::post_template_t());
tmpl.posts.back().from = true;
}
}
return tmpl;
}
xact_t * derive_xact_from_template(xact_template_t& tmpl,
report_t& report)
{
if (tmpl.payee_mask.empty())
throw std::runtime_error(_("'xact' command requires at least a payee"));
xact_t * matching = NULL;
journal_t& journal(*report.session.journal.get());
std::auto_ptr<xact_t> added(new xact_t);
xacts_list::reverse_iterator j;
for (j = journal.xacts.rbegin();
j != journal.xacts.rend();
j++) {
if (tmpl.payee_mask.match((*j)->payee)) {
matching = *j;
break;
}
}
if (! tmpl.date)
added->_date = CURRENT_DATE();
else
added->_date = tmpl.date;
added->set_state(item_t::UNCLEARED);
if (matching) {
added->payee = matching->payee;
added->code = matching->code;
added->note = matching->note;
} else {
added->payee = tmpl.payee_mask.expr.str();
}
if (tmpl.code)
added->code = tmpl.code;
if (tmpl.note)
added->note = tmpl.note;
if (tmpl.posts.empty()) {
if (matching) {
foreach (post_t * post, matching->posts) {
added->add_post(new post_t(*post));
added->posts.back()->set_state(item_t::UNCLEARED);
}
} else {
throw_(std::runtime_error,
_("No accounts, and no past transaction matching '%1'")
<< tmpl.payee_mask);
}
} else {
bool any_post_has_amount = false;
foreach (xact_template_t::post_template_t& post, tmpl.posts) {
if (post.amount) {
any_post_has_amount = true;
break;
}
}
foreach (xact_template_t::post_template_t& post, tmpl.posts) {
std::auto_ptr<post_t> new_post;
commodity_t * found_commodity = NULL;
if (matching) {
if (post.account_mask) {
foreach (post_t * x, matching->posts) {
if (post.account_mask->match(x->account->fullname())) {
new_post.reset(new post_t(*x));
break;
}
}
} else {
if (post.from)
new_post.reset(new post_t(*matching->posts.back()));
else
new_post.reset(new post_t(*matching->posts.front()));
}
}
if (! new_post.get())
new_post.reset(new post_t);
if (! new_post->account) {
if (post.account_mask) {
account_t * acct = NULL;
if (! acct)
acct = journal.find_account_re(post.account_mask->expr.str());
if (! acct)
acct = journal.find_account(post.account_mask->expr.str());
// Find out the default commodity to use by looking at the last
// commodity used in that account
xacts_list::reverse_iterator j;
for (j = journal.xacts.rbegin();
j != journal.xacts.rend();
j++) {
foreach (post_t * x, (*j)->posts) {
if (x->account == acct && ! x->amount.is_null()) {
new_post.reset(new post_t(*x));
break;
}
}
}
if (! new_post.get())
new_post.reset(new post_t);
new_post->account = acct;
} else {
if (post.from)
new_post->account = journal.find_account(_("Liabilities:Unknown"));
else
new_post->account = journal.find_account(_("Expenses:Unknown"));
}
}
if (new_post.get() && ! new_post->amount.is_null()) {
found_commodity = &new_post->amount.commodity();
if (any_post_has_amount)
new_post->amount = amount_t();
else
any_post_has_amount = true;
}
if (post.amount) {
new_post->amount = *post.amount;
if (post.from)
new_post->amount.in_place_negate();
}
if (found_commodity &&
! new_post->amount.is_null() &&
! new_post->amount.has_commodity()) {
new_post->amount.set_commodity(*found_commodity);
new_post->amount = new_post->amount.rounded();
}
added->add_post(new_post.release());
added->posts.back()->set_state(item_t::UNCLEARED);
}
}
if (! journal.xact_finalize_hooks.run_hooks(*added.get(), false) ||
! added->finalize() ||
! journal.xact_finalize_hooks.run_hooks(*added.get(), true))
throw_(std::runtime_error,
_("Failed to finalize derived transaction (check commodities)"));
return added.release();
}
}
value_t template_command(call_scope_t& args)
{
report_t& report(find_scope<report_t>(args));
std::ostream& out(report.output_stream);
value_t::sequence_t::const_iterator begin = args.value().begin();
value_t::sequence_t::const_iterator end = args.value().end();
out << _("--- Input arguments ---") << std::endl;
args.value().dump(out);
out << std::endl << std::endl;
xact_template_t tmpl = args_to_xact_template(begin, end);
out << _("--- Transaction template ---") << std::endl;
tmpl.dump(out);
return true;
}
value_t xact_command(call_scope_t& args)
{
value_t::sequence_t::const_iterator begin = args.value().begin();
value_t::sequence_t::const_iterator end = args.value().end();
report_t& report(find_scope<report_t>(args));
xact_template_t tmpl = args_to_xact_template(begin, end);
std::auto_ptr<xact_t> new_xact(derive_xact_from_template(tmpl, report));
report.xact_report(post_handler_ptr
(new format_posts(report,
report.HANDLER(print_format_).str())),
*new_xact.get());
return true;
}
} // namespace ledger
<commit_msg>The entry command now implies --actual<commit_after>/*
* Copyright (c) 2003-2009, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "derive.h"
#include "output.h"
namespace ledger {
namespace {
struct xact_template_t
{
optional<date_t> date;
optional<string> code;
optional<string> note;
mask_t payee_mask;
struct post_template_t {
bool from;
optional<mask_t> account_mask;
optional<amount_t> amount;
post_template_t() : from(false) {}
};
std::list<post_template_t> posts;
xact_template_t() {}
void dump(std::ostream& out) const
{
if (date)
out << _("Date: ") << *date << std::endl;
else
out << _("Date: <today>") << std::endl;
if (code)
out << _("Code: ") << *code << std::endl;
if (note)
out << _("Note: ") << *note << std::endl;
if (payee_mask.empty())
out << _("Payee mask: INVALID (template expression will cause an error)")
<< std::endl;
else
out << _("Payee mask: ") << payee_mask << std::endl;
if (posts.empty()) {
out << std::endl
<< _("<Posting copied from last related transaction>")
<< std::endl;
} else {
bool has_only_from = true;
bool has_only_to = true;
foreach (const post_template_t& post, posts) {
if (post.from)
has_only_to = false;
else
has_only_from = false;
}
foreach (const post_template_t& post, posts) {
straccstream accum;
out << std::endl
<< ACCUM(accum << _("[Posting \"%1\"]_")
<< (post.from ? _("from") : _("to")))
<< std::endl;
if (post.account_mask)
out << _(" Account mask: ") << *post.account_mask << std::endl;
else if (post.from)
out << _(" Account mask: <use last of last related accounts>") << std::endl;
else
out << _(" Account mask: <use first of last related accounts>") << std::endl;
if (post.amount)
out << _(" Amount: ") << *post.amount << std::endl;
}
}
}
};
xact_template_t
args_to_xact_template(value_t::sequence_t::const_iterator begin,
value_t::sequence_t::const_iterator end)
{
regex date_mask(_("([0-9]+(?:[-/.][0-9]+)?(?:[-/.][0-9]+))?"));
regex dow_mask(_("(sun|mon|tue|wed|thu|fri|sat)"));
smatch what;
xact_template_t tmpl;
bool check_for_date = true;
xact_template_t::post_template_t * post = NULL;
for (; begin != end; begin++) {
if (check_for_date &&
regex_match((*begin).to_string(), what, date_mask)) {
tmpl.date = parse_date(what[0]);
check_for_date = false;
}
else if (check_for_date &&
regex_match((*begin).to_string(), what, dow_mask)) {
short dow = static_cast<short>(string_to_day_of_week(what[0]));
date_t date = CURRENT_DATE() - date_duration(1);
while (date.day_of_week() != dow)
date -= date_duration(1);
tmpl.date = date;
check_for_date = false;
}
else {
string arg = (*begin).to_string();
if (arg == "at") {
tmpl.payee_mask = (*++begin).to_string();
}
else if (arg == "to" || arg == "from") {
if (! post || post->account_mask) {
tmpl.posts.push_back(xact_template_t::post_template_t());
post = &tmpl.posts.back();
}
post->account_mask = mask_t((*++begin).to_string());
post->from = arg == "from";
}
else if (arg == "on") {
tmpl.date = parse_date((*++begin).to_string());
check_for_date = false;
}
else if (arg == "code") {
tmpl.code = (*++begin).to_string();
}
else if (arg == "note") {
tmpl.note = (*++begin).to_string();
}
else if (arg == "rest") {
; // just ignore this argument
}
else {
// Without a preposition, it is either:
//
// A payee, if we have not seen one
// An account or an amount, if we have
// An account if an amount has just been seen
// An amount if an account has just been seen
if (tmpl.payee_mask.empty()) {
tmpl.payee_mask = arg;
}
else {
amount_t amt;
optional<mask_t> account;
if (! amt.parse(arg, amount_t::PARSE_SOFT_FAIL |
amount_t::PARSE_NO_MIGRATE))
account = mask_t(arg);
if (! post ||
(account && post->account_mask) ||
(! account && post->amount)) {
tmpl.posts.push_back(xact_template_t::post_template_t());
post = &tmpl.posts.back();
}
if (account) {
post->from = false;
post->account_mask = account;
} else {
post->amount = amt;
}
}
}
}
}
if (! tmpl.posts.empty()) {
bool has_only_from = true;
bool has_only_to = true;
// A single account at the end of the line is the "from" account
if (tmpl.posts.size() > 1 &&
tmpl.posts.back().account_mask && ! tmpl.posts.back().amount)
tmpl.posts.back().from = true;
foreach (xact_template_t::post_template_t& post, tmpl.posts) {
if (post.from)
has_only_to = false;
else
has_only_from = false;
}
if (has_only_from) {
tmpl.posts.push_front(xact_template_t::post_template_t());
}
else if (has_only_to) {
tmpl.posts.push_back(xact_template_t::post_template_t());
tmpl.posts.back().from = true;
}
}
return tmpl;
}
xact_t * derive_xact_from_template(xact_template_t& tmpl,
report_t& report)
{
if (tmpl.payee_mask.empty())
throw std::runtime_error(_("'xact' command requires at least a payee"));
xact_t * matching = NULL;
journal_t& journal(*report.session.journal.get());
std::auto_ptr<xact_t> added(new xact_t);
xacts_list::reverse_iterator j;
for (j = journal.xacts.rbegin();
j != journal.xacts.rend();
j++) {
if (tmpl.payee_mask.match((*j)->payee)) {
matching = *j;
break;
}
}
if (! tmpl.date)
added->_date = CURRENT_DATE();
else
added->_date = tmpl.date;
added->set_state(item_t::UNCLEARED);
if (matching) {
added->payee = matching->payee;
added->code = matching->code;
added->note = matching->note;
} else {
added->payee = tmpl.payee_mask.expr.str();
}
if (tmpl.code)
added->code = tmpl.code;
if (tmpl.note)
added->note = tmpl.note;
if (tmpl.posts.empty()) {
if (matching) {
foreach (post_t * post, matching->posts) {
added->add_post(new post_t(*post));
added->posts.back()->set_state(item_t::UNCLEARED);
}
} else {
throw_(std::runtime_error,
_("No accounts, and no past transaction matching '%1'")
<< tmpl.payee_mask);
}
} else {
bool any_post_has_amount = false;
foreach (xact_template_t::post_template_t& post, tmpl.posts) {
if (post.amount) {
any_post_has_amount = true;
break;
}
}
foreach (xact_template_t::post_template_t& post, tmpl.posts) {
std::auto_ptr<post_t> new_post;
commodity_t * found_commodity = NULL;
if (matching) {
if (post.account_mask) {
foreach (post_t * x, matching->posts) {
if (post.account_mask->match(x->account->fullname())) {
new_post.reset(new post_t(*x));
break;
}
}
} else {
if (post.from)
new_post.reset(new post_t(*matching->posts.back()));
else
new_post.reset(new post_t(*matching->posts.front()));
}
}
if (! new_post.get())
new_post.reset(new post_t);
if (! new_post->account) {
if (post.account_mask) {
account_t * acct = NULL;
if (! acct)
acct = journal.find_account_re(post.account_mask->expr.str());
if (! acct)
acct = journal.find_account(post.account_mask->expr.str());
// Find out the default commodity to use by looking at the last
// commodity used in that account
xacts_list::reverse_iterator j;
for (j = journal.xacts.rbegin();
j != journal.xacts.rend();
j++) {
foreach (post_t * x, (*j)->posts) {
if (x->account == acct && ! x->amount.is_null()) {
new_post.reset(new post_t(*x));
break;
}
}
}
if (! new_post.get())
new_post.reset(new post_t);
new_post->account = acct;
} else {
if (post.from)
new_post->account = journal.find_account(_("Liabilities:Unknown"));
else
new_post->account = journal.find_account(_("Expenses:Unknown"));
}
}
if (new_post.get() && ! new_post->amount.is_null()) {
found_commodity = &new_post->amount.commodity();
if (any_post_has_amount)
new_post->amount = amount_t();
else
any_post_has_amount = true;
}
if (post.amount) {
new_post->amount = *post.amount;
if (post.from)
new_post->amount.in_place_negate();
}
if (found_commodity &&
! new_post->amount.is_null() &&
! new_post->amount.has_commodity()) {
new_post->amount.set_commodity(*found_commodity);
new_post->amount = new_post->amount.rounded();
}
added->add_post(new_post.release());
added->posts.back()->set_state(item_t::UNCLEARED);
}
}
if (! journal.xact_finalize_hooks.run_hooks(*added.get(), false) ||
! added->finalize() ||
! journal.xact_finalize_hooks.run_hooks(*added.get(), true))
throw_(std::runtime_error,
_("Failed to finalize derived transaction (check commodities)"));
return added.release();
}
}
value_t template_command(call_scope_t& args)
{
report_t& report(find_scope<report_t>(args));
std::ostream& out(report.output_stream);
value_t::sequence_t::const_iterator begin = args.value().begin();
value_t::sequence_t::const_iterator end = args.value().end();
out << _("--- Input arguments ---") << std::endl;
args.value().dump(out);
out << std::endl << std::endl;
xact_template_t tmpl = args_to_xact_template(begin, end);
out << _("--- Transaction template ---") << std::endl;
tmpl.dump(out);
return true;
}
value_t xact_command(call_scope_t& args)
{
value_t::sequence_t::const_iterator begin = args.value().begin();
value_t::sequence_t::const_iterator end = args.value().end();
report_t& report(find_scope<report_t>(args));
xact_template_t tmpl = args_to_xact_template(begin, end);
std::auto_ptr<xact_t> new_xact(derive_xact_from_template(tmpl, report));
report.HANDLER(limit_).on("actual"); // jww (2009-02-27): make this more general
report.xact_report(post_handler_ptr
(new format_posts(report,
report.HANDLER(print_format_).str())),
*new_xact.get());
return true;
}
} // namespace ledger
<|endoftext|> |
<commit_before>#pragma once
#include "YukawaCartesian.hpp"
#include "SemiAnalytical.hpp"
#include "GaussQuadrature.hpp"
#include "BEMConfig.hpp"
class YukawaCartesianBEM : public YukawaCartesian
{
public:
//! # of quadrature points
unsigned K;
// forward declaration
struct Panel;
//! The dimension of the Kernel
static constexpr unsigned dimension = YukawaCartesian::dimension;
//! Point type
typedef YukawaCartesian::point_type point_type;
//! source type
typedef Panel source_type;
//! target type
typedef Panel target_type;
//! Charge type
typedef YukawaCartesian::charge_type charge_type;
//! The return type of a kernel evaluation
typedef double kernel_value_type;
//! The product of the kernel_value_type and the charge_type
typedef double result_type;
//! structure for Boundary elements
struct Panel
{
typedef enum { POTENTIAL, NORMAL_DERIV } BoundaryType;
//! center of the panel
point_type center;
//! panel normal
point_type normal;
//! vertices of the panel
std::vector<point_type> vertices;
//! Stored Quadrature Points
std::vector<point_type> quad_points;
double Area;
//! Boundary condition
BoundaryType BC;
Panel() : center(0), normal(0), Area(0), BC(POTENTIAL) {};
//! copy constructor
Panel(const Panel& p) {
vertices = p.vertices;
center = p.center;
normal = p.normal;
Area = p.Area;
BC = p.BC;
quad_points = p.quad_points;
}
//! main constructor
Panel(point_type p0, point_type p1, point_type p2) : BC(POTENTIAL) {
vertices.resize(3);
vertices[0] = p0;
vertices[1] = p1;
vertices[2] = p2;
// get the center
center = (p0+p1+p2)/3;
// area & normal
auto L0 = p2-p0;
auto L1 = p1-p0;
auto c = point_type(L0[1]*L1[2]-L0[2]*L1[1],
-(L0[0]*L1[2]-L0[2]*L1[0]),
L0[0]*L1[1]-L0[1]*L1[0]);
Area = 0.5*norm(c);
normal = c/2/Area;
// generate the quadrature points
// assume K = 3 for now
auto Config = BEMConfig::Instance();
unsigned k = Config->getK();
auto& points = Config->GaussPoints();
quad_points.resize(k);
// loop over K points performing matvecs
for (unsigned i=0; i<k; i++) {
double x = vertices[0][0]*points[i][0]+vertices[1][0]*points[i][1]+vertices[2][0]*points[i][2];
double y = vertices[0][1]*points[i][0]+vertices[1][1]*points[i][1]+vertices[2][1]*points[i][2];
double z = vertices[0][2]*points[i][0]+vertices[1][2]*points[i][1]+vertices[2][2]*points[i][2];
quad_points[i] = point_type(x,y,z);
}
}
/** cast to point_type */
operator point_type() const { return center; };
/** copy operator */
Panel& operator=(const Panel& p) {
center = p.center;
normal = p.normal;
vertices.resize(3);
for (unsigned i=0; i<3; i++) vertices[i] = p.vertices[i];
Area = p.Area;
quad_points = p.quad_points;
BC = p.BC;
return *this;
}
/** flip the boundary condition flag for calculating RHS */
void switch_BC(void) {
if (this->BC == POTENTIAL) { this->BC = NORMAL_DERIV; }
else { this->BC = POTENTIAL; }
};
};
//! Multipole expansion type
typedef std::vector<YukawaCartesian::multipole_type> multipole_type;
//! Local expansion type
typedef std::vector<YukawaCartesian::local_type> local_type;
//! Panel type (for BEM kernel(s)
typedef Panel panel_type;
//! default constructor - use delegating constructor
YukawaCartesianBEM() : YukawaCartesianBEM(5,0.125,3) {};
//! Constructor
YukawaCartesianBEM(int p, double kappa, unsigned k=3) : YukawaCartesian(p,kappa), K(k) {
BEMConfig::Init();
auto Config = BEMConfig::Instance();
Config->setK(K);
};
/** Initialize a multipole expansion with the size of a box at this level */
void init_multipole(multipole_type& M, point_type extents, unsigned level) const {
M.resize(2);
YukawaCartesian::init_multipole(M[0], extents, level);
YukawaCartesian::init_multipole(M[1], extents, level);
}
/** Initialize a local expansion with the size of a box at this level */
void init_local(local_type& L, point_type& extents, unsigned level) const {
L.resize(2);
YukawaCartesian::init_local(L[0], extents, level);
YukawaCartesian::init_local(L[1], extents, level);
}
/** perform Gaussian integration over panel to evaluate \int G */
double eval_G(const source_type source, const point_type target) const {
auto dist = norm(target-source.center);
// check whether I need Semi-Analytical or Gauss Quadrature
if (sqrt(2*source.Area)/dist >= 0.5) {
// perform semi-analytical integral
namespace AI = AnalyticalIntegral;
double G = 0., dGdn = 0.;
auto& vertices = source.vertices;
AI::SemiAnalytical<AI::YUKAWA>(G,dGdn,vertices[0],vertices[1],vertices[2],target,dist < 1e-10);
return G;
}
else
{
// loop over all my quadrature points, accumulating to get \int G
auto& gauss_weight = BEMConfig::Instance()->GaussWeights();
double r = 0.;
for (unsigned i=0; i<K; i++) {
auto dist = norm(target-source.quad_points[i]);
auto inv_dist = 1./dist;
if (dist < 1e-8) inv_dist = 0.;
r += gauss_weight[i]*source.Area*exp(-Kappa*dist)*inv_dist;
}
return r;
}
};
/** Perform gaussian integration from this panel to target */
double eval_dGdn(const source_type source, const point_type target) const {
double dist = norm(target-source.center);
// check for self-interaction
if (dist < 1e-8) return 2*M_PI;
// check for SA / GQ
if (sqrt(2*source.Area)/dist >= 0.5) {
namespace AI = AnalyticalIntegral;
// semi-analytical integral
auto& vertices = source.vertices;
double G = 0., dGdn = 0.;
AI::SemiAnalytical<AI::YUKAWA>(G,dGdn,vertices[0],vertices[1],vertices[2],target,dist < 1e-10);
return -dGdn;
} else {
auto& gauss_weight = BEMConfig::Instance()->GaussWeights(); // GQ.weights(K);
double res=0.;
for (unsigned i=0; i<K; i++) {
auto dx = target - source.quad_points[i];
// dG/dn = dx.n / |dx|^3
auto r = norm(dx);
auto inv_r = 1./r;
auto inv_r2 = inv_r * inv_r;
if (r < 1e-8) { inv_r = 0.; inv_r2 = 0.; }
// finally accumulate
auto& normal = source.normal;
auto pot = exp(-Kappa*r)* inv_r;
dx *= pot * (Kappa * r + 1) * inv_r2;
res += gauss_weight[i]*source.Area*(-dx[0]*normal[0]-dx[1]*normal[1]-dx[2]*normal[2]);
}
return res;
}
};
/** Kernel evaluation
* K(t,s)
*
* @param[in] t,s The target and source points to evaluate the kernel
* @result The Laplace potential and force 4-vector on t from s:
* Potential: 1/|s-t| Force: (s-t)/|s-t|^3
*/
kernel_value_type operator()(const source_type& t,
const target_type& s) const {
if (t.BC == Panel::POTENTIAL)
{
// if I know the potential for source panel, need to multiply by dG/dn for RHS, want G for solve
return kernel_value_type(eval_G(s, static_cast<point_type>(t)));
}
else if (t.BC== Panel::NORMAL_DERIV)
{
// I know d(phi)/dn for this panel, need to multiply by G for RHS, want dG/dn for solve
return kernel_value_type(eval_dGdn(s, static_cast<point_type>(t)));
}
else
{
// should never get here
return 0.;
}
}
/** Kernel P2M operation
* M += Op(s) * c where M is the multipole and s is the source
*
* @param[in] source The point source
* @param[in] charge The source's corresponding charge
* @param[in] center The center of the box containing the multipole expansion
* @param[in,out] M The multipole expansion to accumulate into
*/
void P2M(const source_type& source, const charge_type& charge,
const point_type& center, multipole_type& M) const {
auto& gauss_weight = BEMConfig::Instance()->GaussWeights(); // GQ.weights(3);
auto& I = YukawaCartesian::I;
auto& J = YukawaCartesian::J;
auto& K = YukawaCartesian::K;
for (auto j=0u; j<source.quad_points.size(); j++) {
// quad point specific constants
auto& qp = source.quad_points[j];
point_type dX = center - static_cast<point_type>(qp);
auto mult_term = charge * gauss_weight[j] * source.Area;
for (unsigned i=0; i < MTERMS; i++) {
// Multipole term constants
auto C = pow(dX[0],I[i]) * pow(dX[1],J[i]) * pow(dX[2],K[i]);
if (source.BC == Panel::POTENTIAL) {
// influence of G needed
M[0][i] += mult_term * C;
}
else // influence of dG/dn needed
{
auto& normal = source.normal;
M[1][i] -= mult_term * C * I[i] / dX[0] * normal[0];
M[1][i] -= mult_term * C * J[i] / dX[1] * normal[1];
M[1][i] -= mult_term * C * K[i] / dX[2] * normal[2];
}
}
}
}
/** Kernel M2M operator
* M_t += Op(M_s) where M_t is the target and M_s is the source
*
* @param[in] source The multipole source at the child level
* @param[in,out] target The multipole target to accumulate into
* @param[in] translation The vector from source to target
* @pre Msource includes the influence of all points within its box
*/
void M2M(const multipole_type& Msource,
multipole_type& Mtarget,
const point_type& translation) const {
YukawaCartesian::M2M(Msource[0],Mtarget[0],translation);
YukawaCartesian::M2M(Msource[1],Mtarget[1],translation);
}
/** Kernel M2P operation
* r_i += Op(M)
*
* @param[in] M The multpole expansion
* @param[in] center The center of the box with the multipole expansion
* @param[in] t_begin,t_end Iterator pair to the target points
* @param[in] r_begin Iterator to the result accumulator
* @pre M includes the influence of all points within its box
*/
void M2P(const multipole_type& M, const point_type& center,
const target_type& target, result_type& result) const {
std::vector<real> a_aux(MTERMS,0), ax_aux(MTERMS,0), ay_aux(MTERMS,0), az_aux(MTERMS,0);
point_type dX = static_cast<point_type>(target) - center;
// potential, d{x,y,z} coefficients
YukawaCartesian::getCoeff(a_aux,ax_aux,ay_aux,az_aux,dX);
double result_pot = 0.;
double result_dn = 0.;
// loop over tarSize
for (unsigned j=0; j<MTERMS; j++) {
result_pot += a_aux[j]*M[0][j];
result_dn += a_aux[j]*M[1][j];
}
if (target.BC== Panel::POTENTIAL) result += result_pot;
else result -= result_dn;
}
};
<commit_msg>Added Kappa to analytical integral calls<commit_after>#pragma once
#include "YukawaCartesian.hpp"
#include "SemiAnalytical.hpp"
#include "GaussQuadrature.hpp"
#include "BEMConfig.hpp"
class YukawaCartesianBEM : public YukawaCartesian
{
public:
//! # of quadrature points
unsigned K;
// forward declaration
struct Panel;
//! The dimension of the Kernel
static constexpr unsigned dimension = YukawaCartesian::dimension;
//! Point type
typedef YukawaCartesian::point_type point_type;
//! source type
typedef Panel source_type;
//! target type
typedef Panel target_type;
//! Charge type
typedef YukawaCartesian::charge_type charge_type;
//! The return type of a kernel evaluation
typedef double kernel_value_type;
//! The product of the kernel_value_type and the charge_type
typedef double result_type;
//! structure for Boundary elements
struct Panel
{
typedef enum { POTENTIAL, NORMAL_DERIV } BoundaryType;
//! center of the panel
point_type center;
//! panel normal
point_type normal;
//! vertices of the panel
std::vector<point_type> vertices;
//! Stored Quadrature Points
std::vector<point_type> quad_points;
double Area;
//! Boundary condition
BoundaryType BC;
Panel() : center(0), normal(0), Area(0), BC(POTENTIAL) {};
//! copy constructor
Panel(const Panel& p) {
vertices = p.vertices;
center = p.center;
normal = p.normal;
Area = p.Area;
BC = p.BC;
quad_points = p.quad_points;
}
//! main constructor
Panel(point_type p0, point_type p1, point_type p2) : BC(POTENTIAL) {
vertices.resize(3);
vertices[0] = p0;
vertices[1] = p1;
vertices[2] = p2;
// get the center
center = (p0+p1+p2)/3;
// area & normal
auto L0 = p2-p0;
auto L1 = p1-p0;
auto c = point_type(L0[1]*L1[2]-L0[2]*L1[1],
-(L0[0]*L1[2]-L0[2]*L1[0]),
L0[0]*L1[1]-L0[1]*L1[0]);
Area = 0.5*norm(c);
normal = c/2/Area;
// generate the quadrature points
// assume K = 3 for now
auto Config = BEMConfig::Instance();
unsigned k = Config->getK();
auto& points = Config->GaussPoints();
quad_points.resize(k);
// loop over K points performing matvecs
for (unsigned i=0; i<k; i++) {
double x = vertices[0][0]*points[i][0]+vertices[1][0]*points[i][1]+vertices[2][0]*points[i][2];
double y = vertices[0][1]*points[i][0]+vertices[1][1]*points[i][1]+vertices[2][1]*points[i][2];
double z = vertices[0][2]*points[i][0]+vertices[1][2]*points[i][1]+vertices[2][2]*points[i][2];
quad_points[i] = point_type(x,y,z);
}
}
/** cast to point_type */
operator point_type() const { return center; };
/** copy operator */
Panel& operator=(const Panel& p) {
center = p.center;
normal = p.normal;
vertices.resize(3);
for (unsigned i=0; i<3; i++) vertices[i] = p.vertices[i];
Area = p.Area;
quad_points = p.quad_points;
BC = p.BC;
return *this;
}
/** flip the boundary condition flag for calculating RHS */
void switch_BC(void) {
if (this->BC == POTENTIAL) { this->BC = NORMAL_DERIV; }
else { this->BC = POTENTIAL; }
};
};
//! Multipole expansion type
typedef std::vector<YukawaCartesian::multipole_type> multipole_type;
//! Local expansion type
typedef std::vector<YukawaCartesian::local_type> local_type;
//! Panel type (for BEM kernel(s)
typedef Panel panel_type;
//! default constructor - use delegating constructor
YukawaCartesianBEM() : YukawaCartesianBEM(5,0.125,3) {};
//! Constructor
YukawaCartesianBEM(int p, double kappa, unsigned k=3) : YukawaCartesian(p,kappa), K(k) {
BEMConfig::Init();
auto Config = BEMConfig::Instance();
Config->setK(K);
};
/** Initialize a multipole expansion with the size of a box at this level */
void init_multipole(multipole_type& M, point_type extents, unsigned level) const {
M.resize(2);
YukawaCartesian::init_multipole(M[0], extents, level);
YukawaCartesian::init_multipole(M[1], extents, level);
}
/** Initialize a local expansion with the size of a box at this level */
void init_local(local_type& L, point_type& extents, unsigned level) const {
L.resize(2);
YukawaCartesian::init_local(L[0], extents, level);
YukawaCartesian::init_local(L[1], extents, level);
}
/** perform Gaussian integration over panel to evaluate \int G */
double eval_G(const source_type source, const point_type target) const {
auto dist = norm(target-source.center);
// check whether I need Semi-Analytical or Gauss Quadrature
if (sqrt(2*source.Area)/dist >= 0.5) {
// perform semi-analytical integral
namespace AI = AnalyticalIntegral;
double G = 0., dGdn = 0.;
auto& vertices = source.vertices;
AI::SemiAnalytical<AI::YUKAWA>(G,dGdn,vertices[0],vertices[1],vertices[2],target,dist < 1e-10, Kappa);
return G;
}
else
{
// loop over all my quadrature points, accumulating to get \int G
auto& gauss_weight = BEMConfig::Instance()->GaussWeights();
double r = 0.;
for (unsigned i=0; i<K; i++) {
auto dist = norm(target-source.quad_points[i]);
auto inv_dist = 1./dist;
if (dist < 1e-8) inv_dist = 0.;
r += gauss_weight[i]*source.Area*exp(-Kappa*dist)*inv_dist;
}
return r;
}
};
/** Perform gaussian integration from this panel to target */
double eval_dGdn(const source_type source, const point_type target) const {
double dist = norm(target-source.center);
// check for self-interaction
if (dist < 1e-8) return 2*M_PI;
// check for SA / GQ
if (sqrt(2*source.Area)/dist >= 0.5) {
namespace AI = AnalyticalIntegral;
// semi-analytical integral
auto& vertices = source.vertices;
double G = 0., dGdn = 0.;
AI::SemiAnalytical<AI::YUKAWA>(G,dGdn,vertices[0],vertices[1],vertices[2],target,dist < 1e-10, Kappa);
return -dGdn;
} else {
auto& gauss_weight = BEMConfig::Instance()->GaussWeights(); // GQ.weights(K);
double res=0.;
for (unsigned i=0; i<K; i++) {
auto dx = target - source.quad_points[i];
// dG/dn = dx.n / |dx|^3
auto r = norm(dx);
auto inv_r = 1./r;
auto inv_r2 = inv_r * inv_r;
if (r < 1e-8) { inv_r = 0.; inv_r2 = 0.; }
// finally accumulate
auto& normal = source.normal;
auto pot = exp(-Kappa*r)* inv_r;
dx *= pot * (Kappa * r + 1) * inv_r2;
res += gauss_weight[i]*source.Area*(-dx[0]*normal[0]-dx[1]*normal[1]-dx[2]*normal[2]);
}
return res;
}
};
/** Kernel evaluation
* K(t,s)
*
* @param[in] t,s The target and source points to evaluate the kernel
* @result The Laplace potential and force 4-vector on t from s:
* Potential: 1/|s-t| Force: (s-t)/|s-t|^3
*/
kernel_value_type operator()(const source_type& t,
const target_type& s) const {
if (t.BC == Panel::POTENTIAL)
{
// if I know the potential for source panel, need to multiply by dG/dn for RHS, want G for solve
return kernel_value_type(eval_G(s, static_cast<point_type>(t)));
}
else if (t.BC== Panel::NORMAL_DERIV)
{
// I know d(phi)/dn for this panel, need to multiply by G for RHS, want dG/dn for solve
return kernel_value_type(eval_dGdn(s, static_cast<point_type>(t)));
}
else
{
// should never get here
return 0.;
}
}
/** Kernel P2M operation
* M += Op(s) * c where M is the multipole and s is the source
*
* @param[in] source The point source
* @param[in] charge The source's corresponding charge
* @param[in] center The center of the box containing the multipole expansion
* @param[in,out] M The multipole expansion to accumulate into
*/
void P2M(const source_type& source, const charge_type& charge,
const point_type& center, multipole_type& M) const {
auto& gauss_weight = BEMConfig::Instance()->GaussWeights(); // GQ.weights(3);
auto& I = YukawaCartesian::I;
auto& J = YukawaCartesian::J;
auto& K = YukawaCartesian::K;
for (auto j=0u; j<source.quad_points.size(); j++) {
// quad point specific constants
auto& qp = source.quad_points[j];
point_type dX = center - static_cast<point_type>(qp);
auto mult_term = charge * gauss_weight[j] * source.Area;
for (unsigned i=0; i < MTERMS; i++) {
// Multipole term constants
auto C = pow(dX[0],I[i]) * pow(dX[1],J[i]) * pow(dX[2],K[i]);
if (source.BC == Panel::POTENTIAL) {
// influence of G needed
M[0][i] += mult_term * C;
}
else // influence of dG/dn needed
{
auto& normal = source.normal;
M[1][i] -= mult_term * C * I[i] / dX[0] * normal[0];
M[1][i] -= mult_term * C * J[i] / dX[1] * normal[1];
M[1][i] -= mult_term * C * K[i] / dX[2] * normal[2];
}
}
}
}
/** Kernel M2M operator
* M_t += Op(M_s) where M_t is the target and M_s is the source
*
* @param[in] source The multipole source at the child level
* @param[in,out] target The multipole target to accumulate into
* @param[in] translation The vector from source to target
* @pre Msource includes the influence of all points within its box
*/
void M2M(const multipole_type& Msource,
multipole_type& Mtarget,
const point_type& translation) const {
YukawaCartesian::M2M(Msource[0],Mtarget[0],translation);
YukawaCartesian::M2M(Msource[1],Mtarget[1],translation);
}
/** Kernel M2P operation
* r_i += Op(M)
*
* @param[in] M The multpole expansion
* @param[in] center The center of the box with the multipole expansion
* @param[in] t_begin,t_end Iterator pair to the target points
* @param[in] r_begin Iterator to the result accumulator
* @pre M includes the influence of all points within its box
*/
void M2P(const multipole_type& M, const point_type& center,
const target_type& target, result_type& result) const {
std::vector<real> a_aux(MTERMS,0), ax_aux(MTERMS,0), ay_aux(MTERMS,0), az_aux(MTERMS,0);
point_type dX = static_cast<point_type>(target) - center;
// potential, d{x,y,z} coefficients
YukawaCartesian::getCoeff(a_aux,ax_aux,ay_aux,az_aux,dX);
double result_pot = 0.;
double result_dn = 0.;
// loop over tarSize
for (unsigned j=0; j<MTERMS; j++) {
result_pot += a_aux[j]*M[0][j];
result_dn += a_aux[j]*M[1][j];
}
if (target.BC== Panel::POTENTIAL) result += result_pot;
else result -= result_dn;
}
};
<|endoftext|> |
<commit_before>// vim: set sts=2 sw=2 et:
// encoding: utf-8
//
// Copyleft 2011 RIME Developers
// License: GPLv3
//
// 2011-04-24 GONG Chen <chen.sst@gmail.com>
//
#include <cctype>
#include <string>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/key_event.h>
#include <rime/processor.h>
#include <rime/schema.h>
#include <rime/segmentation.h>
#include <rime/segmentor.h>
#include <rime/translation.h>
#include <rime/translator.h>
namespace rime {
Engine::Engine() : schema_(new Schema), context_(new Context) {
EZLOGGERFUNCTRACKER;
// receive context notifications
context_->input_change_notifier().connect(
boost::bind(&Engine::OnInputChange, this, _1));
context_->commit_notifier().connect(
boost::bind(&Engine::OnCommit, this, _1));
}
Engine::~Engine() {
EZLOGGERFUNCTRACKER;
processors_.clear();
segmentors_.clear();
translators_.clear();
}
bool Engine::ProcessKeyEvent(const KeyEvent &key_event) {
EZLOGGERVAR(key_event);
BOOST_FOREACH(shared_ptr<Processor> &p, processors_) {
Processor::Result ret = p->ProcessKeyEvent(key_event);
if (ret == Processor::kRejected) return false;
if (ret == Processor::kAccepted) return true;
}
return false;
}
void Engine::OnInputChange(Context *ctx) {
CalculateSegmentation(ctx);
TranslateSegments(ctx);
}
void Engine::CalculateSegmentation(Context *ctx) {
Segmentation *segmentation = new Segmentation(ctx->input());
int start_pos = 0;
while (!segmentation->HasFinished()) {
// recognize a segment by calling the segmentors in turn
BOOST_FOREACH(shared_ptr<Segmentor> &s, segmentors_) {
if (!s->Proceed(segmentation))
break;
}
// move on to the next segment
if (!segmentation->Forward())
break;
}
ctx->set_segmentation(segmentation);
}
void Engine::TranslateSegments(Context *ctx) {
if (!ctx || !ctx->segmentation())
return;
BOOST_FOREACH(const Segment &segment, ctx->segmentation()->segments()) {
const std::string input = ctx->input().substr(segment.start, segment.end);
std::vector<shared_ptr<Translation> > translations;
BOOST_FOREACH(shared_ptr<Translator> translator, translators_) {
shared_ptr<Translation> translation(translator->Query(input, segment));
if (!translation)
continue;
translations.push_back(translation);
}
// TODO: merge translations
}
}
void Engine::OnCommit(Context *ctx) {
const std::string commit_text = ctx->GetCommitText();
sink_(commit_text);
}
void Engine::set_schema(Schema *schema) {
schema_.reset(schema);
InitializeComponents();
}
void Engine::InitializeComponents() {
if (!schema_)
return;
Config *config = schema_->config();
// create processors
shared_ptr<ConfigList> processor_list(
config->GetList("engine/processors"));
if (processor_list) {
size_t n = processor_list->size();
for (size_t i = 0; i < n; ++i) {
std::string klass;
if (!processor_list->GetAt(i)->GetString(&klass))
continue;
Processor::Component *c = Processor::Require(klass);
if (!c) {
EZLOGGERPRINT("error creating processor: '%s'", klass.c_str());
}
else {
shared_ptr<Processor> p(c->Create(this));
processors_.push_back(p);
}
}
}
// create segmentors
shared_ptr<ConfigList> segmentor_list(
config->GetList("engine/segmentors"));
if (segmentor_list) {
size_t n = segmentor_list->size();
for (size_t i = 0; i < n; ++i) {
std::string klass;
if (!segmentor_list->GetAt(i)->GetString(&klass))
continue;
Segmentor::Component *c = Segmentor::Require(klass);
if (!c) {
EZLOGGERPRINT("error creating segmentor: '%s'", klass.c_str());
}
else {
shared_ptr<Segmentor> s(c->Create(this));
segmentors_.push_back(s);
}
}
}
// create translators
shared_ptr<ConfigList> translator_list(
config->GetList("engine/translators"));
if (translator_list) {
size_t n = translator_list->size();
for (size_t i = 0; i < n; ++i) {
std::string klass;
if (!translator_list->GetAt(i)->GetString(&klass))
continue;
Translator::Component *c = Translator::Require(klass);
if (!c) {
EZLOGGERPRINT("error creating translator: '%s'", klass.c_str());
}
else {
shared_ptr<Translator> d(c->Create(this));
translators_.push_back(d);
}
}
}
}
} // namespace rime
<commit_msg>Should fixed it tommorrow.<commit_after>// vim: set sts=2 sw=2 et:
// encoding: utf-8
//
// Copyleft 2011 RIME Developers
// License: GPLv3
//
// 2011-04-24 GONG Chen <chen.sst@gmail.com>
//
#include <cctype>
#include <string>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/key_event.h>
#include <rime/menu.h>
#include <rime/processor.h>
#include <rime/schema.h>
#include <rime/segmentation.h>
#include <rime/segmentor.h>
#include <rime/translation.h>
#include <rime/translator.h>
namespace rime {
Engine::Engine() : schema_(new Schema), context_(new Context) {
EZLOGGERFUNCTRACKER;
// receive context notifications
context_->input_change_notifier().connect(
boost::bind(&Engine::OnInputChange, this, _1));
context_->commit_notifier().connect(
boost::bind(&Engine::OnCommit, this, _1));
}
Engine::~Engine() {
EZLOGGERFUNCTRACKER;
processors_.clear();
segmentors_.clear();
translators_.clear();
}
bool Engine::ProcessKeyEvent(const KeyEvent &key_event) {
EZLOGGERVAR(key_event);
BOOST_FOREACH(shared_ptr<Processor> &p, processors_) {
Processor::Result ret = p->ProcessKeyEvent(key_event);
if (ret == Processor::kRejected) return false;
if (ret == Processor::kAccepted) return true;
}
return false;
}
void Engine::OnInputChange(Context *ctx) {
CalculateSegmentation(ctx);
TranslateSegments(ctx);
}
void Engine::CalculateSegmentation(Context *ctx) {
Segmentation *segmentation = new Segmentation(ctx->input());
int start_pos = 0;
while (!segmentation->HasFinished()) {
// recognize a segment by calling the segmentors in turn
BOOST_FOREACH(shared_ptr<Segmentor> &s, segmentors_) {
if (!s->Proceed(segmentation))
break;
}
// move on to the next segment
if (!segmentation->Forward())
break;
}
ctx->set_segmentation(segmentation);
}
void Engine::TranslateSegments(Context *ctx) {
if (!ctx || !ctx->segmentation())
return;
BOOST_FOREACH(const Segment &segment, ctx->segmentation()->segments()) {
const std::string input = ctx->input().substr(segment.start, segment.end);
shared_ptr<Menu> menu(new Menu);
BOOST_FOREACH(shared_ptr<Translator> translator, translators_) {
shared_ptr<Translation> translation(translator->Query(input, segment));
if (!translation)
continue;
menu->AddTranslation(translation);
}
// TODO: add menu to current composition
}
}
void Engine::OnCommit(Context *ctx) {
const std::string commit_text = ctx->GetCommitText();
sink_(commit_text);
}
void Engine::set_schema(Schema *schema) {
schema_.reset(schema);
InitializeComponents();
}
void Engine::InitializeComponents() {
if (!schema_)
return;
Config *config = schema_->config();
// create processors
shared_ptr<ConfigList> processor_list(
config->GetList("engine/processors"));
if (processor_list) {
size_t n = processor_list->size();
for (size_t i = 0; i < n; ++i) {
std::string klass;
if (!processor_list->GetAt(i)->GetString(&klass))
continue;
Processor::Component *c = Processor::Require(klass);
if (!c) {
EZLOGGERPRINT("error creating processor: '%s'", klass.c_str());
}
else {
shared_ptr<Processor> p(c->Create(this));
processors_.push_back(p);
}
}
}
// create segmentors
shared_ptr<ConfigList> segmentor_list(
config->GetList("engine/segmentors"));
if (segmentor_list) {
size_t n = segmentor_list->size();
for (size_t i = 0; i < n; ++i) {
std::string klass;
if (!segmentor_list->GetAt(i)->GetString(&klass))
continue;
Segmentor::Component *c = Segmentor::Require(klass);
if (!c) {
EZLOGGERPRINT("error creating segmentor: '%s'", klass.c_str());
}
else {
shared_ptr<Segmentor> s(c->Create(this));
segmentors_.push_back(s);
}
}
}
// create translators
shared_ptr<ConfigList> translator_list(
config->GetList("engine/translators"));
if (translator_list) {
size_t n = translator_list->size();
for (size_t i = 0; i < n; ++i) {
std::string klass;
if (!translator_list->GetAt(i)->GetString(&klass))
continue;
Translator::Component *c = Translator::Require(klass);
if (!c) {
EZLOGGERPRINT("error creating translator: '%s'", klass.c_str());
}
else {
shared_ptr<Translator> d(c->Create(this));
translators_.push_back(d);
}
}
}
}
} // namespace rime
<|endoftext|> |
<commit_before>//
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2013 Project Chrono
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//
#include "ChLcpVariablesShaft.h"
namespace chrono {
ChLcpVariablesShaft& ChLcpVariablesShaft::operator=(const ChLcpVariablesShaft& other)
{
if (&other == this) return *this;
// copy parent class data
ChLcpVariables::operator=(other);
// copy class data
m_shaft = other.m_shaft;
m_inertia = other.m_inertia;
return *this;
}
/// Computes the product of the inverse mass matrix by a
/// vector, and set in result: result = [invMb]*vect
void ChLcpVariablesShaft::Compute_invMb_v(ChMatrix<float>& result, const ChMatrix<float>& vect) const
{
assert(vect.GetRows() == Get_ndof());
assert(result.GetRows() == Get_ndof());
result(0) = (float)m_inv_inertia * vect(0);
};
void ChLcpVariablesShaft::Compute_invMb_v(ChMatrix<double>& result, const ChMatrix<double>& vect) const
{
assert(vect.GetRows() == Get_ndof());
assert(result.GetRows() == Get_ndof());
result(0) = m_inv_inertia * vect(0);
};
/// Computes the product of the inverse mass matrix by a
/// vector, and increment result: result += [invMb]*vect
void ChLcpVariablesShaft::Compute_inc_invMb_v(ChMatrix<float>& result, const ChMatrix<float>& vect) const
{
assert(vect.GetRows() == Get_ndof());
assert(result.GetRows() == Get_ndof());
result(0) += (float)m_inv_inertia * vect(0);
};
void ChLcpVariablesShaft::Compute_inc_invMb_v(ChMatrix<double>& result, const ChMatrix<double>& vect) const
{
assert(vect.GetRows() == Get_ndof());
assert(result.GetRows() == Get_ndof());
result(0) += (float)m_inv_inertia * vect(0);
};
/// Computes the product of the mass matrix by a
/// vector, and set in result: result = [Mb]*vect
void ChLcpVariablesShaft::Compute_inc_Mb_v(ChMatrix<float>& result, const ChMatrix<float>& vect) const
{
assert(result.GetRows() == Get_ndof());
assert(vect.GetRows() == Get_ndof());
result(0) += (float)m_inertia * vect(0);
};
void ChLcpVariablesShaft::Compute_inc_Mb_v(ChMatrix<double>& result, const ChMatrix<double>& vect) const
{
assert(result.GetRows() == vect.GetRows());
assert(vect.GetRows() == Get_ndof());
result(0) += m_inertia * vect(0);
};
/// Computes the product of the corresponding block in the
/// system matrix (ie. the mass matrix) by 'vect', and add to 'result'.
/// NOTE: the 'vect' and 'result' vectors must already have
/// the size of the total variables&constraints in the system; the procedure
/// will use the ChVariable offsets (that must be already updated) to know the
/// indexes in result and vect.
void ChLcpVariablesShaft::MultiplyAndAdd(ChMatrix<double>& result, const ChMatrix<double>& vect) const
{
assert(result.GetColumns() == 1 && vect.GetColumns() == 1);
result(this->offset) += m_inertia * vect(this->offset);
}
/// Add the diagonal of the mass matrix (as a column vector) to 'result'.
/// NOTE: the 'result' vector must already have the size of system unknowns, ie
/// the size of the total variables&constraints in the system; the procedure
/// will use the ChVariable offset (that must be already updated) as index.
void ChLcpVariablesShaft::DiagonalAdd(ChMatrix<double>& result) const
{
assert(result.GetColumns() == 1);
result(this->offset) += m_inertia;
}
/// Build the mass matrix (for these variables) storing
/// it in 'storage' sparse matrix, at given column/row offset.
/// Note, most iterative solvers don't need to know mass matrix explicitly.
/// Optimised: doesn't fill unneeded elements except mass.
void ChLcpVariablesShaft::Build_M(ChSparseMatrix& storage, int insrow, int inscol)
{
storage.SetElement(insrow + 0, inscol + 0, m_inertia);
}
// Register into the object factory, to enable run-time
// dynamic creation and persistence
ChClassRegister<ChLcpVariablesShaft> a_registration_ChLcpVariablesNode;
} // END_OF_NAMESPACE____
<commit_msg>Fix duplicated symbol issue.<commit_after>//
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2013 Project Chrono
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//
#include "ChLcpVariablesShaft.h"
namespace chrono {
ChLcpVariablesShaft& ChLcpVariablesShaft::operator=(const ChLcpVariablesShaft& other)
{
if (&other == this) return *this;
// copy parent class data
ChLcpVariables::operator=(other);
// copy class data
m_shaft = other.m_shaft;
m_inertia = other.m_inertia;
return *this;
}
/// Computes the product of the inverse mass matrix by a
/// vector, and set in result: result = [invMb]*vect
void ChLcpVariablesShaft::Compute_invMb_v(ChMatrix<float>& result, const ChMatrix<float>& vect) const
{
assert(vect.GetRows() == Get_ndof());
assert(result.GetRows() == Get_ndof());
result(0) = (float)m_inv_inertia * vect(0);
};
void ChLcpVariablesShaft::Compute_invMb_v(ChMatrix<double>& result, const ChMatrix<double>& vect) const
{
assert(vect.GetRows() == Get_ndof());
assert(result.GetRows() == Get_ndof());
result(0) = m_inv_inertia * vect(0);
};
/// Computes the product of the inverse mass matrix by a
/// vector, and increment result: result += [invMb]*vect
void ChLcpVariablesShaft::Compute_inc_invMb_v(ChMatrix<float>& result, const ChMatrix<float>& vect) const
{
assert(vect.GetRows() == Get_ndof());
assert(result.GetRows() == Get_ndof());
result(0) += (float)m_inv_inertia * vect(0);
};
void ChLcpVariablesShaft::Compute_inc_invMb_v(ChMatrix<double>& result, const ChMatrix<double>& vect) const
{
assert(vect.GetRows() == Get_ndof());
assert(result.GetRows() == Get_ndof());
result(0) += (float)m_inv_inertia * vect(0);
};
/// Computes the product of the mass matrix by a
/// vector, and set in result: result = [Mb]*vect
void ChLcpVariablesShaft::Compute_inc_Mb_v(ChMatrix<float>& result, const ChMatrix<float>& vect) const
{
assert(result.GetRows() == Get_ndof());
assert(vect.GetRows() == Get_ndof());
result(0) += (float)m_inertia * vect(0);
};
void ChLcpVariablesShaft::Compute_inc_Mb_v(ChMatrix<double>& result, const ChMatrix<double>& vect) const
{
assert(result.GetRows() == vect.GetRows());
assert(vect.GetRows() == Get_ndof());
result(0) += m_inertia * vect(0);
};
/// Computes the product of the corresponding block in the
/// system matrix (ie. the mass matrix) by 'vect', and add to 'result'.
/// NOTE: the 'vect' and 'result' vectors must already have
/// the size of the total variables&constraints in the system; the procedure
/// will use the ChVariable offsets (that must be already updated) to know the
/// indexes in result and vect.
void ChLcpVariablesShaft::MultiplyAndAdd(ChMatrix<double>& result, const ChMatrix<double>& vect) const
{
assert(result.GetColumns() == 1 && vect.GetColumns() == 1);
result(this->offset) += m_inertia * vect(this->offset);
}
/// Add the diagonal of the mass matrix (as a column vector) to 'result'.
/// NOTE: the 'result' vector must already have the size of system unknowns, ie
/// the size of the total variables&constraints in the system; the procedure
/// will use the ChVariable offset (that must be already updated) as index.
void ChLcpVariablesShaft::DiagonalAdd(ChMatrix<double>& result) const
{
assert(result.GetColumns() == 1);
result(this->offset) += m_inertia;
}
/// Build the mass matrix (for these variables) storing
/// it in 'storage' sparse matrix, at given column/row offset.
/// Note, most iterative solvers don't need to know mass matrix explicitly.
/// Optimised: doesn't fill unneeded elements except mass.
void ChLcpVariablesShaft::Build_M(ChSparseMatrix& storage, int insrow, int inscol)
{
storage.SetElement(insrow + 0, inscol + 0, m_inertia);
}
// Register into the object factory, to enable run-time
// dynamic creation and persistence
ChClassRegister<ChLcpVariablesShaft> a_registration_ChLcpVariablesShaft;
} // END_OF_NAMESPACE____
<|endoftext|> |
<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "MemoryStream.h"
#include <algorithm>
#include <memory.h>
using namespace leap;
MemoryStream::MemoryStream(void) {}
bool MemoryStream::Write(const void* pBuf, std::streamsize ncb) {
if (buffer.size() - m_writeOffset < static_cast<size_t>(ncb))
// Exponential growth on the buffer:
buffer.resize(
std::max(
buffer.size() * 2,
m_writeOffset + static_cast<size_t>(ncb)
)
);
memcpy(
buffer.data() + m_writeOffset,
pBuf,
static_cast<size_t>(ncb)
);
m_writeOffset += static_cast<size_t>(ncb);
return true;
}
std::streamsize MemoryStream::Read(void* pBuf, std::streamsize ncb) {
const void* pSrcData = buffer.data() + m_readOffset;
ncb = Skip(ncb);
memcpy(pBuf, pSrcData, static_cast<size_t>(ncb));
return ncb;
}
std::streamsize MemoryStream::Skip(std::streamsize ncb) {
std::streamsize nSkipped = std::min(
ncb,
static_cast<std::streamsize>(m_writeOffset - m_readOffset)
);
m_eof = nSkipped != ncb;
m_readOffset += static_cast<size_t>(nSkipped);
if (m_readOffset == buffer.size()) {
// Reset criteria, no data left in the buffer
m_readOffset = 0;
m_writeOffset = 0;
}
return nSkipped;
}
std::streamsize MemoryStream::Length(void) {
return static_cast<std::streamsize>(m_writeOffset - m_readOffset);
}
<commit_msg>Fix read/write offset comparison<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "MemoryStream.h"
#include <algorithm>
#include <memory.h>
using namespace leap;
MemoryStream::MemoryStream(void) {}
bool MemoryStream::Write(const void* pBuf, std::streamsize ncb) {
if (buffer.size() - m_writeOffset < static_cast<size_t>(ncb))
// Exponential growth on the buffer:
buffer.resize(
std::max(
buffer.size() * 2,
m_writeOffset + static_cast<size_t>(ncb)
)
);
memcpy(
buffer.data() + m_writeOffset,
pBuf,
static_cast<size_t>(ncb)
);
m_writeOffset += static_cast<size_t>(ncb);
return true;
}
std::streamsize MemoryStream::Read(void* pBuf, std::streamsize ncb) {
const void* pSrcData = buffer.data() + m_readOffset;
ncb = Skip(ncb);
memcpy(pBuf, pSrcData, static_cast<size_t>(ncb));
return ncb;
}
std::streamsize MemoryStream::Skip(std::streamsize ncb) {
std::streamsize nSkipped = std::min(
ncb,
static_cast<std::streamsize>(m_writeOffset - m_readOffset)
);
m_eof = nSkipped != ncb;
m_readOffset += static_cast<size_t>(nSkipped);
if (m_readOffset == m_writeOffset) {
// Reset criteria, no data left in the buffer
m_readOffset = 0;
m_writeOffset = 0;
}
return nSkipped;
}
std::streamsize MemoryStream::Length(void) {
return static_cast<std::streamsize>(m_writeOffset - m_readOffset);
}
<|endoftext|> |
<commit_before>#ifndef LEPP2_SPLIT_APPROXIMATOR_H__
#define LEPP2_SPLIT_APPROXIMATOR_H__
#include "lepp2/ObjectApproximator.hpp"
#include "lepp2/models/ObjectModel.h"
#include <deque>
#include <map>
#include <pcl/common/pca.h>
#include <pcl/common/common.h>
namespace lepp {
/**
* An ABC that represents the strategy for splitting a point cloud used by the
* `SplitObjectApproximator`.
*
* Varying the `SplitStrategy` implementation allows us to change how point
* clouds are split (or if they are split at all) without changing the logic of
* the `SplitObjectApproximator` approximator itself.
*/
template<class PointT>
class SplitStrategy {
public:
/**
* Performs the split of the given point cloud according to the particular
* strategy.
*
* This method has a default implementation that is a template method, which
* calls the protected `shouldSplit` method and calls the `doSplit` if it
* indicated that a split should be made. Since all of the methods are
* virtual, concrete implementations can override how the split is made or
* keep the default implementation.
*
* This method can also be overridden by concrete implementations if they
* cannot implement the logic only in terms of the `shouldSplit` and
* `doSplit` method implementations (although that should be rare).
*
* :param split_depth: The current split depth, i.e. the number of times the
* original cloud has already been split
* :param point_cloud: The current point cloud that should be split by the
* `SplitStrategy` implementation.
* :returns: The method should return a vector of point clouds obtained by
* splitting the given cloud into any number of parts. If the given
* point cloud should not be split, an empty vector should be returned.
* Once the empty vector is returned, the `SplitObjectApproximator` will
* stop the splitting process for that branch of the split tree.
*/
virtual std::vector<typename pcl::PointCloud<PointT>::Ptr> split(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud);
protected:
/**
* A pure virtual method that decides whether the given point cloud should be
* split or not.
*
* :param split_depth: The current split depth, i.e. the number of times the
* original cloud has already been split
* :param point_cloud: The current point cloud that should be split by the
* `SplitStrategy` implementation.
* :returns: A boolean indicating whether the cloud should be split or not.
*/
virtual bool shouldSplit(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) = 0;
/**
* A helper method that does the actual split, when needed.
* A default implementation is provided, since that is what most splitters
* will want to use...
*/
virtual std::vector<typename pcl::PointCloud<PointT>::Ptr> doSplit(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud);
};
template<class PointT>
std::vector<typename pcl::PointCloud<PointT>::Ptr> SplitStrategy<PointT>::split(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
if (this->shouldSplit(split_depth, point_cloud)) {
return this->doSplit(point_cloud);
} else {
return std::vector<typename pcl::PointCloud<PointT>::Ptr>();
}
}
template<class PointT>
std::vector<typename pcl::PointCloud<PointT>::Ptr>
SplitStrategy<PointT>::doSplit(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
typedef pcl::PointCloud<PointT> PointCloud;
typedef typename pcl::PointCloud<PointT>::Ptr PointCloudPtr;
// Compute PCA for the input cloud
pcl::PCA<PointT> pca;
pca.setInputCloud(point_cloud);
Eigen::Vector3f eigenvalues = pca.getEigenValues();
Eigen::Matrix3f eigenvectors = pca.getEigenVectors();
Eigen::Vector3d main_pca_axis = eigenvectors.col(0).cast<double>();
// Compute the centroid
Eigen::Vector4d centroid;
pcl::compute3DCentroid(*point_cloud, centroid);
/// The plane equation
double d = (-1) * (
centroid[0] * main_pca_axis[0] +
centroid[1] * main_pca_axis[1] +
centroid[2] * main_pca_axis[2]
);
// Prepare the two parts.
std::vector<PointCloudPtr> ret;
ret.push_back(PointCloudPtr(new pcl::PointCloud<PointT>()));
ret.push_back(PointCloudPtr(new pcl::PointCloud<PointT>()));
PointCloud& first = *ret[0];
PointCloud& second = *ret[1];
// Now divide the input cloud into two clusters based on the splitting plane
size_t const sz = point_cloud->size();
for (size_t i = 0; i < sz; ++i) {
// Boost the precision of the points we are dealing with to make the
// calculation more precise.
PointT const& original_point = (*point_cloud)[i];
Eigen::Vector3f const vector_point = original_point.getVector3fMap();
Eigen::Vector3d const point = vector_point.cast<double>();
// Decide on which side of the plane the current point is and add it to the
// appropriate partition.
if (point.dot(main_pca_axis) + d < 0.) {
first.push_back(original_point);
} else {
second.push_back(original_point);
}
}
// Return the parts in a vector, as expected by the interface...
return ret;
}
/**
* An ABC for classes that provide the functionality of checking whether a
* point cloud should be split or not.
*/
template<class PointT>
class SplitCondition {
public:
/**
* A pure virtual method that decides whether the given point cloud should be
* split or not.
*
* :param split_depth: The current split depth, i.e. the number of times the
* original cloud has already been split
* :param point_cloud: The current point cloud that should be split by the
* `SplitStrategy` implementation.
* :returns: A boolean indicating whether the cloud should be split or not.
*/
virtual bool shouldSplit(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) = 0;
};
/**
* An implementation of the `SplitStrategy` abstract base class that decides
* whether a point cloud should be split by making sure that each condition
* is satisfied (i.e. each `SplitCondition` instance returns `true` from its
* `shouldSplit` method).
*
* If and only if all conditions are satisfied, the strategy performs the split
* by using the default split implementation provided by the `SplitStrategy`
* superclass.
*/
template<class PointT>
class CompositeSplitStrategy : public SplitStrategy<PointT> {
public:
void addSplitCondition(boost::shared_ptr<SplitCondition<PointT> > cond) {
conditions_.push_back(cond);
}
protected:
bool shouldSplit(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
size_t const sz = conditions_.size();
if (sz == 0) {
// If there are no conditions, do not split the object, in order to avoid
// perpetually splitting it, since there's no condition that could
// possibly put an end to it.
return false;
}
for (size_t i = 0; i < sz; ++i) {
if (!conditions_[i]->shouldSplit(split_depth, point_cloud)) {
// No split can happen if any of the conditions disallows it.
return false;
}
}
// Split only if all of the conditions allowed us to split
return true;
}
private:
/**
* A list of conditions that will be checked before any split happens.
*/
std::vector<boost::shared_ptr<SplitCondition<PointT> > > conditions_;
};
/**
* A `SplitStrategy` implementation that initiates the split iff the depth is
* less than the given limit.
*/
template<class PointT>
class DepthLimitSplitStrategy : public SplitStrategy<PointT> {
public:
DepthLimitSplitStrategy(int depth_limit) : limit_(depth_limit) {}
bool shouldSplit(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud);
private:
/**
* The limit at which splits will stop.
*/
int const limit_;
};
template<class PointT>
bool DepthLimitSplitStrategy<PointT>::shouldSplit(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
return split_depth < limit_;
}
/**
* An approximator implementation that will generate an approximation by
* splitting the given object into multiple parts. Each part approximation is
* generated by delegating to a wrapped `ObjectApproximator` instance, allowing
* clients to vary the algorithm used for approximations, while keeping the
* logic of incrementally splitting up the object.
*/
template<class PointT>
class SplitObjectApproximator : public ObjectApproximator<PointT> {
public:
/**
* Create a new `SplitObjectApproximator` that will approximate each part by
* using the given approximator instance and perform splits decided by the
* given `SplitStrategy` instance.
*/
SplitObjectApproximator(
boost::shared_ptr<ObjectApproximator<PointT> > approx,
boost::shared_ptr<SplitStrategy<PointT> > splitter)
: approximator_(approx),
splitter_(splitter) {}
/**
* `ObjectApproximator` interface method.
*/
boost::shared_ptr<CompositeModel> approximate(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud);
private:
/**
* An `ObjectApproximator` used to generate approximations for object parts.
*/
boost::shared_ptr<ObjectApproximator<PointT> > approximator_;
/**
* The strategy to be used for splitting point clouds.
*/
boost::shared_ptr<SplitStrategy<PointT> > splitter_;
};
template<class PointT>
boost::shared_ptr<CompositeModel> SplitObjectApproximator<PointT>::approximate(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
boost::shared_ptr<CompositeModel> approx(new CompositeModel);
typedef typename pcl::PointCloud<PointT>::ConstPtr PointCloudConstPtr;
typedef typename pcl::PointCloud<PointT>::Ptr PointCloudPtr;
std::deque<std::pair<int, PointCloudConstPtr> > queue;
queue.push_back(std::make_pair(0, point_cloud));
while (!queue.empty()) {
int const depth = queue[0].first;
PointCloudConstPtr const current_cloud = queue[0].second;
queue.pop_front();
// Delegates to the wrapped approximator for each part's approximation.
ObjectModelPtr model = approximator_->approximate(current_cloud);
// TODO Decide whether the model fits well enough for the current cloud.
// For now we fix the number of split iterations.
// The approximation should be improved. Try doing it for the split clouds
std::vector<PointCloudPtr> const splits = splitter_->split(depth, current_cloud);
// Add each new split section into the queue as children of the current
// node.
if (splits.size() != 0) {
for (size_t i = 0; i < splits.size(); ++i) {
queue.push_back(std::make_pair(depth + 1, splits[i]));
}
} else {
// Keep the approximation
approx->addModel(model);
}
}
return approx;
}
} // namespace lepp
#endif
<commit_msg>Add a depth-limit split condition<commit_after>#ifndef LEPP2_SPLIT_APPROXIMATOR_H__
#define LEPP2_SPLIT_APPROXIMATOR_H__
#include "lepp2/ObjectApproximator.hpp"
#include "lepp2/models/ObjectModel.h"
#include <deque>
#include <map>
#include <pcl/common/pca.h>
#include <pcl/common/common.h>
namespace lepp {
/**
* An ABC that represents the strategy for splitting a point cloud used by the
* `SplitObjectApproximator`.
*
* Varying the `SplitStrategy` implementation allows us to change how point
* clouds are split (or if they are split at all) without changing the logic of
* the `SplitObjectApproximator` approximator itself.
*/
template<class PointT>
class SplitStrategy {
public:
/**
* Performs the split of the given point cloud according to the particular
* strategy.
*
* This method has a default implementation that is a template method, which
* calls the protected `shouldSplit` method and calls the `doSplit` if it
* indicated that a split should be made. Since all of the methods are
* virtual, concrete implementations can override how the split is made or
* keep the default implementation.
*
* This method can also be overridden by concrete implementations if they
* cannot implement the logic only in terms of the `shouldSplit` and
* `doSplit` method implementations (although that should be rare).
*
* :param split_depth: The current split depth, i.e. the number of times the
* original cloud has already been split
* :param point_cloud: The current point cloud that should be split by the
* `SplitStrategy` implementation.
* :returns: The method should return a vector of point clouds obtained by
* splitting the given cloud into any number of parts. If the given
* point cloud should not be split, an empty vector should be returned.
* Once the empty vector is returned, the `SplitObjectApproximator` will
* stop the splitting process for that branch of the split tree.
*/
virtual std::vector<typename pcl::PointCloud<PointT>::Ptr> split(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud);
protected:
/**
* A pure virtual method that decides whether the given point cloud should be
* split or not.
*
* :param split_depth: The current split depth, i.e. the number of times the
* original cloud has already been split
* :param point_cloud: The current point cloud that should be split by the
* `SplitStrategy` implementation.
* :returns: A boolean indicating whether the cloud should be split or not.
*/
virtual bool shouldSplit(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) = 0;
/**
* A helper method that does the actual split, when needed.
* A default implementation is provided, since that is what most splitters
* will want to use...
*/
virtual std::vector<typename pcl::PointCloud<PointT>::Ptr> doSplit(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud);
};
template<class PointT>
std::vector<typename pcl::PointCloud<PointT>::Ptr> SplitStrategy<PointT>::split(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
if (this->shouldSplit(split_depth, point_cloud)) {
return this->doSplit(point_cloud);
} else {
return std::vector<typename pcl::PointCloud<PointT>::Ptr>();
}
}
template<class PointT>
std::vector<typename pcl::PointCloud<PointT>::Ptr>
SplitStrategy<PointT>::doSplit(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
typedef pcl::PointCloud<PointT> PointCloud;
typedef typename pcl::PointCloud<PointT>::Ptr PointCloudPtr;
// Compute PCA for the input cloud
pcl::PCA<PointT> pca;
pca.setInputCloud(point_cloud);
Eigen::Vector3f eigenvalues = pca.getEigenValues();
Eigen::Matrix3f eigenvectors = pca.getEigenVectors();
Eigen::Vector3d main_pca_axis = eigenvectors.col(0).cast<double>();
// Compute the centroid
Eigen::Vector4d centroid;
pcl::compute3DCentroid(*point_cloud, centroid);
/// The plane equation
double d = (-1) * (
centroid[0] * main_pca_axis[0] +
centroid[1] * main_pca_axis[1] +
centroid[2] * main_pca_axis[2]
);
// Prepare the two parts.
std::vector<PointCloudPtr> ret;
ret.push_back(PointCloudPtr(new pcl::PointCloud<PointT>()));
ret.push_back(PointCloudPtr(new pcl::PointCloud<PointT>()));
PointCloud& first = *ret[0];
PointCloud& second = *ret[1];
// Now divide the input cloud into two clusters based on the splitting plane
size_t const sz = point_cloud->size();
for (size_t i = 0; i < sz; ++i) {
// Boost the precision of the points we are dealing with to make the
// calculation more precise.
PointT const& original_point = (*point_cloud)[i];
Eigen::Vector3f const vector_point = original_point.getVector3fMap();
Eigen::Vector3d const point = vector_point.cast<double>();
// Decide on which side of the plane the current point is and add it to the
// appropriate partition.
if (point.dot(main_pca_axis) + d < 0.) {
first.push_back(original_point);
} else {
second.push_back(original_point);
}
}
// Return the parts in a vector, as expected by the interface...
return ret;
}
/**
* An ABC for classes that provide the functionality of checking whether a
* point cloud should be split or not.
*/
template<class PointT>
class SplitCondition {
public:
/**
* A pure virtual method that decides whether the given point cloud should be
* split or not.
*
* :param split_depth: The current split depth, i.e. the number of times the
* original cloud has already been split
* :param point_cloud: The current point cloud that should be split by the
* `SplitStrategy` implementation.
* :returns: A boolean indicating whether the cloud should be split or not.
*/
virtual bool shouldSplit(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) = 0;
};
/**
* An implementation of the `SplitStrategy` abstract base class that decides
* whether a point cloud should be split by making sure that each condition
* is satisfied (i.e. each `SplitCondition` instance returns `true` from its
* `shouldSplit` method).
*
* If and only if all conditions are satisfied, the strategy performs the split
* by using the default split implementation provided by the `SplitStrategy`
* superclass.
*/
template<class PointT>
class CompositeSplitStrategy : public SplitStrategy<PointT> {
public:
void addSplitCondition(boost::shared_ptr<SplitCondition<PointT> > cond) {
conditions_.push_back(cond);
}
protected:
bool shouldSplit(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
size_t const sz = conditions_.size();
if (sz == 0) {
// If there are no conditions, do not split the object, in order to avoid
// perpetually splitting it, since there's no condition that could
// possibly put an end to it.
return false;
}
for (size_t i = 0; i < sz; ++i) {
if (!conditions_[i]->shouldSplit(split_depth, point_cloud)) {
// No split can happen if any of the conditions disallows it.
return false;
}
}
// Split only if all of the conditions allowed us to split
return true;
}
private:
/**
* A list of conditions that will be checked before any split happens.
*/
std::vector<boost::shared_ptr<SplitCondition<PointT> > > conditions_;
};
/**
* A `SplitCondition` that allows the split to be made only if the split depth
* has not exceeded the given limit.
*/
template<class PointT>
class DepthLimitSplitCondition : public SplitCondition<PointT> {
public:
DepthLimitSplitCondition(int depth_limit) : limit_(depth_limit) {}
bool shouldSplit(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
return split_depth < limit_;
}
private:
int const limit_;
};
/**
* A `SplitStrategy` implementation that initiates the split iff the depth is
* less than the given limit.
*/
template<class PointT>
class DepthLimitSplitStrategy : public SplitStrategy<PointT> {
public:
DepthLimitSplitStrategy(int depth_limit) : limit_(depth_limit) {}
bool shouldSplit(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud);
private:
/**
* The limit at which splits will stop.
*/
int const limit_;
};
template<class PointT>
bool DepthLimitSplitStrategy<PointT>::shouldSplit(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
return split_depth < limit_;
}
/**
* An approximator implementation that will generate an approximation by
* splitting the given object into multiple parts. Each part approximation is
* generated by delegating to a wrapped `ObjectApproximator` instance, allowing
* clients to vary the algorithm used for approximations, while keeping the
* logic of incrementally splitting up the object.
*/
template<class PointT>
class SplitObjectApproximator : public ObjectApproximator<PointT> {
public:
/**
* Create a new `SplitObjectApproximator` that will approximate each part by
* using the given approximator instance and perform splits decided by the
* given `SplitStrategy` instance.
*/
SplitObjectApproximator(
boost::shared_ptr<ObjectApproximator<PointT> > approx,
boost::shared_ptr<SplitStrategy<PointT> > splitter)
: approximator_(approx),
splitter_(splitter) {}
/**
* `ObjectApproximator` interface method.
*/
boost::shared_ptr<CompositeModel> approximate(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud);
private:
/**
* An `ObjectApproximator` used to generate approximations for object parts.
*/
boost::shared_ptr<ObjectApproximator<PointT> > approximator_;
/**
* The strategy to be used for splitting point clouds.
*/
boost::shared_ptr<SplitStrategy<PointT> > splitter_;
};
template<class PointT>
boost::shared_ptr<CompositeModel> SplitObjectApproximator<PointT>::approximate(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
boost::shared_ptr<CompositeModel> approx(new CompositeModel);
typedef typename pcl::PointCloud<PointT>::ConstPtr PointCloudConstPtr;
typedef typename pcl::PointCloud<PointT>::Ptr PointCloudPtr;
std::deque<std::pair<int, PointCloudConstPtr> > queue;
queue.push_back(std::make_pair(0, point_cloud));
while (!queue.empty()) {
int const depth = queue[0].first;
PointCloudConstPtr const current_cloud = queue[0].second;
queue.pop_front();
// Delegates to the wrapped approximator for each part's approximation.
ObjectModelPtr model = approximator_->approximate(current_cloud);
// TODO Decide whether the model fits well enough for the current cloud.
// For now we fix the number of split iterations.
// The approximation should be improved. Try doing it for the split clouds
std::vector<PointCloudPtr> const splits = splitter_->split(depth, current_cloud);
// Add each new split section into the queue as children of the current
// node.
if (splits.size() != 0) {
for (size_t i = 0; i < splits.size(); ++i) {
queue.push_back(std::make_pair(depth + 1, splits[i]));
}
} else {
// Keep the approximation
approx->addModel(model);
}
}
return approx;
}
} // namespace lepp
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <stdio.h>
#include <stdlib.h>
#include "util/random.h"
#include "util/testutil.h"
// Comma-separated list of operations to run in the specified order
// Actual benchmarks:
//
// seq -- output N values in sequential key order
// random -- output N values in random key order
static const char* FLAGS_benchmarks =
"seq,"
"random,"
;
// Number of key/values to place in database
static int FLAGS_num = 1000000;
// Number of read operations to do. If negative, do FLAGS_num reads.
static int FLAGS_reads = -1;
// Size of each key
static int FLAGS_key_size = 16;
// Size of each value
static int FLAGS_value_size = 100;
// Arrange to generate values that shrink to this fraction of
// their original size after compression
static double FLAGS_compression_ratio = 0.5;
// Number of tablets
static int FLAGS_tablet_num = 1;
namespace leveldb {
// Helper for quickly generating random data.
namespace {
class RandomGenerator {
private:
std::string data_;
int pos_;
public:
RandomGenerator() {
// We use a limited amount of data over and over again and ensure
// that it is larger than the compression window (32KB), and also
// large enough to serve all typical value sizes we want to write.
Random rnd(301);
std::string piece;
while (data_.size() < 1048576) {
// Add a short fragment that is as compressible as specified
// by FLAGS_compression_ratio.
test::CompressibleString(&rnd, FLAGS_compression_ratio, 100, &piece);
data_.append(piece);
}
pos_ = 0;
}
Slice Generate(int len) {
if (pos_ + len > static_cast<int>(data_.size())) {
pos_ = 0;
assert(len < static_cast<int>(data_.size()));
}
pos_ += len;
return Slice(data_.data() + pos_ - len, len);
}
};
} // namespace
class Benchmark {
private:
int num_;
int reads_;
double start_;
int64_t bytes_;
std::string message_;
RandomGenerator gen_;
Random rand_;
Random** tablet_rand_vector_;
// State kept for progress messages
int done_;
int next_report_; // When to report next
void Start() {
start_ = Env::Default()->NowMicros() * 1e-6;
bytes_ = 0;
message_.clear();
done_ = 0;
next_report_ = 100;
}
void Stop(const Slice& name) {
double finish = Env::Default()->NowMicros() * 1e-6;
// Pretend at least one op was done in case we are running a benchmark
// that does not call FinishedSingleOp().
if (done_ < 1) done_ = 1;
if (bytes_ > 0) {
char rate[100];
snprintf(rate, sizeof(rate), "%6.1f MB/s",
(bytes_ / 1048576.0) / (finish - start_));
if (!message_.empty()) {
message_ = std::string(rate) + " " + message_;
} else {
message_ = rate;
}
}
fprintf(stderr, "%-12s : %11.3f micros/op;%s%s\n",
name.ToString().c_str(),
(finish - start_) * 1e6 / done_,
(message_.empty() ? "" : " "),
message_.c_str());
fflush(stderr);
}
public:
enum Order {
SEQUENTIAL,
RANDOM
};
Benchmark()
: num_(FLAGS_num),
reads_(FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads),
bytes_(0),
rand_(301) {
tablet_rand_vector_ = new Random*[FLAGS_tablet_num];
for (int i = 0; i < FLAGS_tablet_num; i++) {
tablet_rand_vector_[i] = new Random(301);
}
}
~Benchmark() {
for (int i = 0; i < FLAGS_tablet_num; i++) {
delete tablet_rand_vector_[i];
}
delete[] tablet_rand_vector_;
}
void Run() {
const char* benchmarks = FLAGS_benchmarks;
while (benchmarks != NULL) {
const char* sep = strchr(benchmarks, ',');
Slice name;
if (sep == NULL) {
name = benchmarks;
benchmarks = NULL;
} else {
name = Slice(benchmarks, sep - benchmarks);
benchmarks = sep + 1;
}
Start();
bool known = true;
if (name == Slice("seq")) {
Output(SEQUENTIAL, num_, FLAGS_value_size);
} else if (name == Slice("random")) {
Output(RANDOM, num_, FLAGS_value_size);
} else {
known = false;
if (name != Slice()) { // No error message for empty name
fprintf(stderr, "unknown benchmark '%s'\n", name.ToString().c_str());
}
}
if (known) {
Stop(name);
}
}
}
private:
void Output(Order order, int num_entries, int value_size) {
if (num_entries != num_) {
char msg[100];
snprintf(msg, sizeof(msg), "(%d ops)", num_entries);
message_ = msg;
}
// Write to database
for (int i = 0; i < num_entries; i++)
{
const int t = rand_.Next() % FLAGS_tablet_num;
const int k = (order == SEQUENTIAL) ? i : (tablet_rand_vector_[t]->Next());
char key[10000];
snprintf(key, sizeof(key), "%06d%0*d", t, FLAGS_key_size - 6, k);
bytes_ += value_size + strlen(key);
fprintf(stdout, "%s\t%s\n", key, gen_.Generate(value_size).ToString().c_str());
}
}
};
} // namespace leveldb
int main(int argc, char** argv) {
for (int i = 1; i < argc; i++) {
double d;
int n;
char junk;
if (leveldb::Slice(argv[i]).starts_with("--benchmarks=")) {
FLAGS_benchmarks = argv[i] + strlen("--benchmarks=");
} else if (sscanf(argv[i], "--compression_ratio=%lf%c", &d, &junk) == 1) {
FLAGS_compression_ratio = d;
} else if (sscanf(argv[i], "--num=%d%c", &n, &junk) == 1) {
FLAGS_num = n;
} else if (sscanf(argv[i], "--reads=%d%c", &n, &junk) == 1) {
FLAGS_reads = n;
} else if (sscanf(argv[i], "--key_size=%d%c", &n, &junk) == 1 && n < 10000) {
FLAGS_key_size = n;
} else if (sscanf(argv[i], "--value_size=%d%c", &n, &junk) == 1) {
FLAGS_value_size = n;
} else if (sscanf(argv[i], "--tablet_num=%d%c", &n, &junk) == 1) {
FLAGS_tablet_num = n;
} else {
fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
exit(1);
}
}
leveldb::Benchmark benchmark;
benchmark.Run();
return 0;
}
<commit_msg>add cf and random seed<commit_after>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <stdio.h>
#include <stdlib.h>
#include "util/random.h"
#include "util/testutil.h"
// Comma-separated list of operations to run in the specified order
// Actual benchmarks:
//
// seq -- output N values in sequential key order
// random -- output N values in random key order
static const char* FLAGS_benchmarks =
"seq,"
"random,"
;
// Number of key/values to place in database
static int FLAGS_num = 1000000;
// Number of read operations to do. If negative, do FLAGS_num reads.
static int FLAGS_reads = -1;
// Size of each key
static int FLAGS_key_size = 16;
// Size of each value
static int FLAGS_value_size = 100;
// Arrange to generate values that shrink to this fraction of
// their original size after compression
static double FLAGS_compression_ratio = 0.5;
// Number of tablets
static int FLAGS_tablet_num = 1;
// CF list in format: "cf0:q1,cf1:q2..."
static std::string FLAGS_cf_list = "";
// Seq mode start key
static int FLAGS_start_key = 0;
// Generate different data each time
static char FLAGS_random_seed = 'f';
namespace leveldb {
// Helper for quickly generating random data.
namespace {
class RandomGenerator {
private:
std::string data_;
int pos_;
public:
RandomGenerator() {
// We use a limited amount of data over and over again and ensure
// that it is larger than the compression window (32KB), and also
// large enough to serve all typical value sizes we want to write.
Random rnd(FLAGS_random_seed);
std::string piece;
while (data_.size() < 1048576) {
// Add a short fragment that is as compressible as specified
// by FLAGS_compression_ratio.
test::CompressibleString(&rnd, FLAGS_compression_ratio, 100, &piece);
data_.append(piece);
}
pos_ = 0;
}
Slice Generate(int len) {
if (pos_ + len > static_cast<int>(data_.size())) {
pos_ = 0;
assert(len < static_cast<int>(data_.size()));
}
pos_ += len;
return Slice(data_.data() + pos_ - len, len);
}
};
} // namespace
class Benchmark {
private:
int num_;
int reads_;
double start_;
int64_t bytes_;
std::string message_;
RandomGenerator gen_;
Random rand_;
Random** tablet_rand_vector_;
// State kept for progress messages
int done_;
int next_report_; // When to report next
void Start() {
start_ = Env::Default()->NowMicros() * 1e-6;
bytes_ = 0;
message_.clear();
done_ = 0;
next_report_ = 100;
}
void Stop(const Slice& name) {
double finish = Env::Default()->NowMicros() * 1e-6;
// Pretend at least one op was done in case we are running a benchmark
// that does not call FinishedSingleOp().
if (done_ < 1) done_ = 1;
if (bytes_ > 0) {
char rate[100];
snprintf(rate, sizeof(rate), "%6.1f MB/s",
(bytes_ / 1048576.0) / (finish - start_));
if (!message_.empty()) {
message_ = std::string(rate) + " " + message_;
} else {
message_ = rate;
}
}
fprintf(stderr, "%-12s : %11.3f micros/op;%s%s\n",
name.ToString().c_str(),
(finish - start_) * 1e6 / done_,
(message_.empty() ? "" : " "),
message_.c_str());
fflush(stderr);
}
public:
enum Order {
SEQUENTIAL,
RANDOM
};
Benchmark()
: num_(FLAGS_num),
reads_(FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads),
bytes_(0),
rand_(FLAGS_random_seed) {
tablet_rand_vector_ = new Random*[FLAGS_tablet_num];
for (int i = 0; i < FLAGS_tablet_num; i++) {
tablet_rand_vector_[i] = new Random(FLAGS_random_seed);
}
}
~Benchmark() {
for (int i = 0; i < FLAGS_tablet_num; i++) {
delete tablet_rand_vector_[i];
}
delete[] tablet_rand_vector_;
}
void Run() {
// parse cf list
std::vector<std::string> cfs;
if (FLAGS_cf_list != "") {
std::string buffer = FLAGS_cf_list;
size_t start_index = 0;
size_t end_index = buffer.find(",");
while (end_index != std::string::npos) {
cfs.push_back(buffer.substr(start_index, end_index - start_index));
start_index = end_index + 1;
end_index = buffer.find(",", start_index);
}
cfs.push_back(buffer.substr(start_index));
}
const char* benchmarks = FLAGS_benchmarks;
while (benchmarks != NULL) {
const char* sep = strchr(benchmarks, ',');
Slice name;
if (sep == NULL) {
name = benchmarks;
benchmarks = NULL;
} else {
name = Slice(benchmarks, sep - benchmarks);
benchmarks = sep + 1;
}
Start();
bool known = true;
if (name == Slice("seq")) {
Output(SEQUENTIAL, num_, FLAGS_value_size, cfs);
} else if (name == Slice("random")) {
Output(RANDOM, num_, FLAGS_value_size, cfs);
} else {
known = false;
if (name != Slice()) { // No error message for empty name
fprintf(stderr, "unknown benchmark '%s'\n", name.ToString().c_str());
}
}
if (known) {
Stop(name);
}
}
}
private:
void Output(Order order, int num_entries, int value_size, std::vector<std::string>& cfs) {
if (num_entries != num_) {
char msg[100];
snprintf(msg, sizeof(msg), "(%d ops)", num_entries);
message_ = msg;
}
// Write to database
int i = FLAGS_start_key;
int end_key = i + num_entries;
for (; i < end_key; i++)
{
const int t = rand_.Next() % FLAGS_tablet_num;
const int k = (order == SEQUENTIAL) ? i : (tablet_rand_vector_[t]->Next());
char key[10000];
snprintf(key, sizeof(key), "%06d%0*d", t, FLAGS_key_size - 6, k);
bytes_ += value_size + strlen(key);
if (cfs.empty() == true) {
fprintf(stdout, "%s\t%s\t%s\n", key, gen_.Generate(value_size).ToString().c_str(), "0");
} else {
for (size_t j = 0; j < cfs.size(); ++j) {
fprintf(stdout, "%s\t%s\t%s\t%s\n", key, gen_.Generate(value_size).ToString().c_str(), cfs[j].c_str(), "0");
}
}
}
}
};
} // namespace leveldb
int main(int argc, char** argv) {
for (int i = 1; i < argc; i++) {
double d;
int n;
char junk;
char cf_list[1024];
if (leveldb::Slice(argv[i]).starts_with("--benchmarks=")) {
FLAGS_benchmarks = argv[i] + strlen("--benchmarks=");
} else if (sscanf(argv[i], "--compression_ratio=%lf%c", &d, &junk) == 1) {
FLAGS_compression_ratio = d;
} else if (sscanf(argv[i], "--num=%d%c", &n, &junk) == 1) {
FLAGS_num = n;
} else if (sscanf(argv[i], "--reads=%d%c", &n, &junk) == 1) {
FLAGS_reads = n;
} else if (sscanf(argv[i], "--key_size=%d%c", &n, &junk) == 1 && n < 10000) {
FLAGS_key_size = n;
} else if (sscanf(argv[i], "--value_size=%d%c", &n, &junk) == 1) {
FLAGS_value_size = n;
} else if (sscanf(argv[i], "--tablet_num=%d%c", &n, &junk) == 1) {
FLAGS_tablet_num = n;
} else if (sscanf(argv[i], "--cf=%s", cf_list) == 1) {
FLAGS_cf_list = std::string(cf_list);
} else if (sscanf(argv[i], "--start_key=%d%c", &n, &junk) == 1) {
FLAGS_start_key = n;
} else if (sscanf(argv[i], "--random=%c", &junk) == 1) {
if (junk == 't') {
FLAGS_random_seed = time(NULL);
} else {
FLAGS_random_seed = 301;
}
} else {
fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
exit(1);
}
}
leveldb::Benchmark benchmark;
benchmark.Run();
return 0;
}
<|endoftext|> |
<commit_before>#include "env_p.h"
Qak::AndroidEnv::AndroidEnv(QObject *parent)
: QObject(parent)
{
}
QString Qak::AndroidEnv::obbPath()
{
#if defined(Q_OS_ANDROID)
QAndroidJniObject mediaDir = QAndroidJniObject::callStaticObjectMethod( "android/os/Environment", "getExternalStorageDirectory", "()Ljava/io/File;");
QAndroidJniObject mediaPath = mediaDir.callObjectMethod( "getAbsolutePath", "()Ljava/lang/String;" );
QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod( "org/qtproject/qt5/android/QtNative" , "activity", "()Landroid/app/Activity;");
QAndroidJniObject package = activity.callObjectMethod( "getPackageName", "()Ljava/lang/String;");
// If any exceptions occurred - just clear them and move on
QAndroidJniEnvironment env;
if (env->ExceptionCheck()) { env->ExceptionClear(); }
return mediaPath.toString()+QStringLiteral("/Android/obb/")+package.toString();
#endif
return QStringLiteral("");
}
bool Qak::AndroidEnv::checkPermission(const QString &permission)
{
#if defined(Q_OS_ANDROID)
QtAndroid::PermissionResult r = QtAndroid::checkPermission(permission);
if(r == QtAndroid::PermissionResult::Denied) {
QtAndroid::requestPermissionsSync( QStringList() << permission );
r = QtAndroid::checkPermission(permission);
if(r == QtAndroid::PermissionResult::Denied) {
return false;
}
}
#else
Q_UNUSED(permission);
return false;
#endif
return true;
}
Qak::MouseEnv::MouseEnv(QObject *parent)
: QObject(parent)
{
}
void Qak::MouseEnv::press(QObject *target, const QPointF &point)
{
QMouseEvent *event = new QMouseEvent(QEvent::MouseButtonPress, point,
Qt::LeftButton,
Qt::LeftButton,
Qt::NoModifier );
if(target == nullptr)
target = qApp->focusWindow();
qDebug() << "Env.mouse::press" << target << point;
qApp->postEvent(target, event);
}
void Qak::MouseEnv::release(QObject *target, const QPointF &point)
{
QMouseEvent *event = new QMouseEvent(QEvent::MouseButtonRelease, point,
Qt::LeftButton,
Qt::LeftButton,
Qt::NoModifier );
if(target == nullptr)
target = qApp->focusWindow();
qDebug() << "Env.mouse::release" << target << point;
qApp->postEvent(target, event);
}
void Qak::MouseEnv::move(QObject *target, const QPointF &point)
{
QMouseEvent *event = new QMouseEvent(QEvent::MouseMove, point,
Qt::LeftButton,
Qt::LeftButton,
Qt::NoModifier );
if(target == nullptr)
target = qApp->focusWindow();
qDebug() << "Env.mouse::move" << target << point;
qApp->postEvent(target, event);
}
EnvPrivate::EnvPrivate(QObject *parent)
: QObject(parent)
{
}
QString EnvPrivate::appPath()
{
return QCoreApplication::applicationDirPath();
}
QString EnvPrivate::dataPath()
{
return QStandardPaths::writableLocation(QStandardPaths::DataLocation)+QStringLiteral("/")+subEnvPath();
}
QString EnvPrivate::cachePath()
{
return QStandardPaths::writableLocation(QStandardPaths::CacheLocation)+QStringLiteral("/")+subEnvPath();
}
QString EnvPrivate::configPath()
{
return QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)+QStringLiteral("/")+subEnvPath();
}
QString EnvPrivate::tempPath()
{
return QStandardPaths::writableLocation(QStandardPaths::TempLocation)+QStringLiteral("/")+subEnvPath();
}
bool EnvPrivate::copy(const QString &src, const QString &dst)
{
return copy(src, dst, true);
}
bool EnvPrivate::copy(const QString &src, const QString &dst, bool recursively)
{
if(isFile(src)) {
// File copy
return QFile::copy(src , dst);
}
if(isDir(src)) {
bool success = false;
if(isFile(dst)) {
qWarning() << "Qak" << "Env::copy" << dst << "is a file";
return false;
}
// Directory copy
QDir sourceDir(src);
if(!isDir(dst))
ensure(dst);
QStringList entries = sourceDir.entryList(QDir::Files);
// Copy files first
for(int i = 0; i< entries.count(); i++) {
success = QFile::copy(src + QStringLiteral("/") + entries[i],
dst + QStringLiteral("/") + entries[i]);
if(!success)
return false;
}
if(recursively) {
// Copy directories
entries.clear();
entries = sourceDir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
for(int i = 0; i< entries.count(); i++)
{
success = copy(src + QStringLiteral("/") + entries[i],
dst + QStringLiteral("/") + entries[i],
recursively);
if(!success)
return false;
}
}
return true;
}
return false;
}
bool EnvPrivate::remove(const QString &path)
{
if(isFile(path)) {
QFile file(path);
return file.remove();
}
if(isDir(path)) {
QDir dir(path);
return dir.removeRecursively();
}
return false;
}
QString EnvPrivate::read(const QString &path)
{
if(!isFile(path)){
qWarning() << "Qak" << "Env::read" << "could not read file" << path << "Aborting";
return QString();
}
QString source(path);
source = source.replace("qrc://",":");
source = source.replace("file://","");
QFile file(source);
QString fileContent;
if ( file.open(QFile::ReadOnly) ) {
QString line;
QTextStream t( &file );
do {
line = t.readLine();
fileContent += line;
} while (!line.isNull());
file.close();
} else {
qWarning() << "Qak" << "Env::read" << "unable to open" << path << "Aborting";
return QString();
}
return fileContent;
}
bool EnvPrivate::write(const QString &data, const QString &path)
{
return write(data, path, false);
}
bool EnvPrivate::write(const QString &data, const QString &path, bool overwrite)
{
if(!overwrite && exists(path)) {
qWarning() << "Qak" << "Env::write" << path << "already exist";
return false;
}
if(overwrite && exists(path)) {
if(isFile(path)) {
if(!remove(path)) {
qWarning() << "Qak" << "Env::write" << "could not remove" << path << "for writing. Aborting";
return false;
}
}
if(isDir(path)) {
qWarning() << "Qak" << "Env::write" << path << "is a directory. Not overwriting";
return false;
}
}
QFile file(path);
if(!file.open(QFile::WriteOnly | QFile::Truncate)) {
qWarning() << "Qak" << "Env::write" << path << "could not be opened for writing. Aborting";
return false;
}
QTextStream out(&file);
out << data;
file.close();
return true;
}
QStringList EnvPrivate::list(const QString &dir)
{
return list(dir, false);
}
QStringList EnvPrivate::list(const QString &dir, bool recursively)
{
QStringList entryList;
if(isDir(dir)) {
QDir sourceDir(dir);
QStringList entries = sourceDir.entryList(QDir::AllEntries | QDir::NoDotAndDotDot);
// Files
for(int i = 0; i< entries.count(); i++) {
entryList.append(sourceDir.absolutePath() + QStringLiteral("/") + entries[i]);
}
if(recursively) {
// Decent directories
entries.clear();
entries = sourceDir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
for(int i = 0; i< entries.count(); i++)
{
entryList += list(sourceDir.absolutePath() + QStringLiteral("/") + entries[i], recursively);
}
}
return entryList;
}
qWarning() << "Qak" << "Env::list" << dir << "is not a directory";
return entryList;
}
bool EnvPrivate::ensure(const QString &path)
{
QDir dir(path);
if (!dir.exists())
return dir.mkpath(".");
return false;
}
bool EnvPrivate::exists(const QString &path)
{
QFileInfo check(path);
return check.exists();
}
bool EnvPrivate::isFile(const QString &path)
{
QFileInfo check(path);
return check.exists() && check.isFile();
}
bool EnvPrivate::isDir(const QString &path)
{
QFileInfo check(path);
return check.exists() && check.isDir();
}
qint64 EnvPrivate::size(const QString &path)
{
QFileInfo check(path);
return check.size();
}
bool EnvPrivate::registerResource(const QString &rccFilename, const QString &resourceRoot)
{
return QResource::registerResource(rccFilename,resourceRoot);
}
bool EnvPrivate::unregisterResource(const QString &rccFilename, const QString &resourceRoot)
{
return QResource::unregisterResource(rccFilename,resourceRoot);
}
Qak::AndroidEnv *EnvPrivate::androidEnv()
{
return &_androidEnv;
}
Qak::MouseEnv *EnvPrivate::mouseEnv()
{
return &_mouseEnv;
}
QString EnvPrivate::subEnvPath()
{
QString sub;
if(QGuiApplication::organizationName() != "")
sub += QGuiApplication::organizationName() + QStringLiteral("/");
if(QGuiApplication::organizationDomain() != "")
sub += QGuiApplication::organizationDomain() + QStringLiteral("/");
if(QGuiApplication::applicationName() != "")
sub += QGuiApplication::applicationName() + QStringLiteral("/");
#ifdef QAK_STORE_VERSION_PATH
if(QGuiApplication::applicationVersion() != "")
sub += QGuiApplication::applicationVersion() + QStringLiteral("/") ;
#endif
if(sub == "") {
qWarning() << "Qak" << "Env" << "Couldn't resolve" << sub << "as a valid path. Using generic directory: \"Qak\"";
sub = "Qak";
}
while(sub.endsWith( QStringLiteral("/") )) sub.chop(1);
return sub;
}
<commit_msg>Show any exceptions from Java in obbPath<commit_after>#include "env_p.h"
Qak::AndroidEnv::AndroidEnv(QObject *parent)
: QObject(parent)
{
}
QString Qak::AndroidEnv::obbPath()
{
#if defined(Q_OS_ANDROID)
QAndroidJniObject mediaDir = QAndroidJniObject::callStaticObjectMethod( "android/os/Environment", "getExternalStorageDirectory", "()Ljava/io/File;");
QAndroidJniObject mediaPath = mediaDir.callObjectMethod( "getAbsolutePath", "()Ljava/lang/String;" );
QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod( "org/qtproject/qt5/android/QtNative" , "activity", "()Landroid/app/Activity;");
QAndroidJniObject package = activity.callObjectMethod( "getPackageName", "()Ljava/lang/String;");
// If any exceptions occurred - just clear them and move on
QAndroidJniEnvironment env;
if (env->ExceptionCheck()) {
qWarning() << "Qak" << "Env::obbPath" << "Exception occurred"; // << env->ExceptionDescribe();
env->ExceptionClear();
}
return mediaPath.toString()+QStringLiteral("/Android/obb/")+package.toString();
#endif
return QStringLiteral("");
}
bool Qak::AndroidEnv::checkPermission(const QString &permission)
{
#if defined(Q_OS_ANDROID)
QtAndroid::PermissionResult r = QtAndroid::checkPermission(permission);
if(r == QtAndroid::PermissionResult::Denied) {
QtAndroid::requestPermissionsSync( QStringList() << permission );
r = QtAndroid::checkPermission(permission);
if(r == QtAndroid::PermissionResult::Denied) {
return false;
}
}
#else
Q_UNUSED(permission);
return false;
#endif
return true;
}
Qak::MouseEnv::MouseEnv(QObject *parent)
: QObject(parent)
{
}
void Qak::MouseEnv::press(QObject *target, const QPointF &point)
{
QMouseEvent *event = new QMouseEvent(QEvent::MouseButtonPress, point,
Qt::LeftButton,
Qt::LeftButton,
Qt::NoModifier );
if(target == nullptr)
target = qApp->focusWindow();
qDebug() << "Env.mouse::press" << target << point;
qApp->postEvent(target, event);
}
void Qak::MouseEnv::release(QObject *target, const QPointF &point)
{
QMouseEvent *event = new QMouseEvent(QEvent::MouseButtonRelease, point,
Qt::LeftButton,
Qt::LeftButton,
Qt::NoModifier );
if(target == nullptr)
target = qApp->focusWindow();
qDebug() << "Env.mouse::release" << target << point;
qApp->postEvent(target, event);
}
void Qak::MouseEnv::move(QObject *target, const QPointF &point)
{
QMouseEvent *event = new QMouseEvent(QEvent::MouseMove, point,
Qt::LeftButton,
Qt::LeftButton,
Qt::NoModifier );
if(target == nullptr)
target = qApp->focusWindow();
qDebug() << "Env.mouse::move" << target << point;
qApp->postEvent(target, event);
}
EnvPrivate::EnvPrivate(QObject *parent)
: QObject(parent)
{
}
QString EnvPrivate::appPath()
{
return QCoreApplication::applicationDirPath();
}
QString EnvPrivate::dataPath()
{
return QStandardPaths::writableLocation(QStandardPaths::DataLocation)+QStringLiteral("/")+subEnvPath();
}
QString EnvPrivate::cachePath()
{
return QStandardPaths::writableLocation(QStandardPaths::CacheLocation)+QStringLiteral("/")+subEnvPath();
}
QString EnvPrivate::configPath()
{
return QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)+QStringLiteral("/")+subEnvPath();
}
QString EnvPrivate::tempPath()
{
return QStandardPaths::writableLocation(QStandardPaths::TempLocation)+QStringLiteral("/")+subEnvPath();
}
bool EnvPrivate::copy(const QString &src, const QString &dst)
{
return copy(src, dst, true);
}
bool EnvPrivate::copy(const QString &src, const QString &dst, bool recursively)
{
if(isFile(src)) {
// File copy
return QFile::copy(src , dst);
}
if(isDir(src)) {
bool success = false;
if(isFile(dst)) {
qWarning() << "Qak" << "Env::copy" << dst << "is a file";
return false;
}
// Directory copy
QDir sourceDir(src);
if(!isDir(dst))
ensure(dst);
QStringList entries = sourceDir.entryList(QDir::Files);
// Copy files first
for(int i = 0; i< entries.count(); i++) {
success = QFile::copy(src + QStringLiteral("/") + entries[i],
dst + QStringLiteral("/") + entries[i]);
if(!success)
return false;
}
if(recursively) {
// Copy directories
entries.clear();
entries = sourceDir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
for(int i = 0; i< entries.count(); i++)
{
success = copy(src + QStringLiteral("/") + entries[i],
dst + QStringLiteral("/") + entries[i],
recursively);
if(!success)
return false;
}
}
return true;
}
return false;
}
bool EnvPrivate::remove(const QString &path)
{
if(isFile(path)) {
QFile file(path);
return file.remove();
}
if(isDir(path)) {
QDir dir(path);
return dir.removeRecursively();
}
return false;
}
QString EnvPrivate::read(const QString &path)
{
if(!isFile(path)){
qWarning() << "Qak" << "Env::read" << "could not read file" << path << "Aborting";
return QString();
}
QString source(path);
source = source.replace("qrc://",":");
source = source.replace("file://","");
QFile file(source);
QString fileContent;
if ( file.open(QFile::ReadOnly) ) {
QString line;
QTextStream t( &file );
do {
line = t.readLine();
fileContent += line;
} while (!line.isNull());
file.close();
} else {
qWarning() << "Qak" << "Env::read" << "unable to open" << path << "Aborting";
return QString();
}
return fileContent;
}
bool EnvPrivate::write(const QString &data, const QString &path)
{
return write(data, path, false);
}
bool EnvPrivate::write(const QString &data, const QString &path, bool overwrite)
{
if(!overwrite && exists(path)) {
qWarning() << "Qak" << "Env::write" << path << "already exist";
return false;
}
if(overwrite && exists(path)) {
if(isFile(path)) {
if(!remove(path)) {
qWarning() << "Qak" << "Env::write" << "could not remove" << path << "for writing. Aborting";
return false;
}
}
if(isDir(path)) {
qWarning() << "Qak" << "Env::write" << path << "is a directory. Not overwriting";
return false;
}
}
QFile file(path);
if(!file.open(QFile::WriteOnly | QFile::Truncate)) {
qWarning() << "Qak" << "Env::write" << path << "could not be opened for writing. Aborting";
return false;
}
QTextStream out(&file);
out << data;
file.close();
return true;
}
QStringList EnvPrivate::list(const QString &dir)
{
return list(dir, false);
}
QStringList EnvPrivate::list(const QString &dir, bool recursively)
{
QStringList entryList;
if(isDir(dir)) {
QDir sourceDir(dir);
QStringList entries = sourceDir.entryList(QDir::AllEntries | QDir::NoDotAndDotDot);
// Files
for(int i = 0; i< entries.count(); i++) {
entryList.append(sourceDir.absolutePath() + QStringLiteral("/") + entries[i]);
}
if(recursively) {
// Decent directories
entries.clear();
entries = sourceDir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
for(int i = 0; i< entries.count(); i++)
{
entryList += list(sourceDir.absolutePath() + QStringLiteral("/") + entries[i], recursively);
}
}
return entryList;
}
qWarning() << "Qak" << "Env::list" << dir << "is not a directory";
return entryList;
}
bool EnvPrivate::ensure(const QString &path)
{
QDir dir(path);
if (!dir.exists())
return dir.mkpath(".");
return false;
}
bool EnvPrivate::exists(const QString &path)
{
QFileInfo check(path);
return check.exists();
}
bool EnvPrivate::isFile(const QString &path)
{
QFileInfo check(path);
return check.exists() && check.isFile();
}
bool EnvPrivate::isDir(const QString &path)
{
QFileInfo check(path);
return check.exists() && check.isDir();
}
qint64 EnvPrivate::size(const QString &path)
{
QFileInfo check(path);
return check.size();
}
bool EnvPrivate::registerResource(const QString &rccFilename, const QString &resourceRoot)
{
return QResource::registerResource(rccFilename,resourceRoot);
}
bool EnvPrivate::unregisterResource(const QString &rccFilename, const QString &resourceRoot)
{
return QResource::unregisterResource(rccFilename,resourceRoot);
}
Qak::AndroidEnv *EnvPrivate::androidEnv()
{
return &_androidEnv;
}
Qak::MouseEnv *EnvPrivate::mouseEnv()
{
return &_mouseEnv;
}
QString EnvPrivate::subEnvPath()
{
QString sub;
if(QGuiApplication::organizationName() != "")
sub += QGuiApplication::organizationName() + QStringLiteral("/");
if(QGuiApplication::organizationDomain() != "")
sub += QGuiApplication::organizationDomain() + QStringLiteral("/");
if(QGuiApplication::applicationName() != "")
sub += QGuiApplication::applicationName() + QStringLiteral("/");
#ifdef QAK_STORE_VERSION_PATH
if(QGuiApplication::applicationVersion() != "")
sub += QGuiApplication::applicationVersion() + QStringLiteral("/") ;
#endif
if(sub == "") {
qWarning() << "Qak" << "Env" << "Couldn't resolve" << sub << "as a valid path. Using generic directory: \"Qak\"";
sub = "Qak";
}
while(sub.endsWith( QStringLiteral("/") )) sub.chop(1);
return sub;
}
<|endoftext|> |
<commit_before>/* $Id$ */
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-11 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Common Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin multi_thread.cpp$$
$escape $$
$spell
inv
mega
cpp
num
pthread
pthreads
openmp
bthread
$$
$index multi_thread, example$$
$index multi_thread, speed$$
$index speed, multi_thread$$
$index example, multi_thread$$
$index thread, multi example$$
$section Run Multi-Threading Examples and Speed Tests$$
$head Syntax$$
$codei%./multi_thread a11c
%$$
$codei%./multi_thread simple_ad
%$$
$codei%./multi_thread sum_i_inv %max_threads% %mega_sum%
%$$
$codei%./multi_thread multi_newton \
%max_threads% %num_zero% %num_sub% %num_sum% %use_ad%$$
$head Running Tests$$
You can build this program and run the default version of its test
parameters by executing the following commands:
$codei%
cd multi_thread/%threading%
make test
%$$
If $cref/OpenmpFlags/InstallUnix/OpenmpFlags/$$
are specified during configuration,
you can preform the operation above with
$icode threading$$ equal to $code openmp$$.
If pthreads with barriers are supported by your system,
you can use $icode threading$$ equal to $code pthread$$.
If boost threads have been installed,
you can use $icode threading$$ equal to $code bthread$$.
$head Purpose$$
Runs the CppAD multi-threading examples and speed tests:
$children%
multi_thread/openmp/a11c.cpp%
multi_thread/bthread/a11c.cpp%
multi_thread/pthread/a11c.cpp
%$$
$head a11c$$
The examples
$cref openmp_a11c.cpp$$,
$cref bthread_a11c.cpp$$, and
$cref pthread_a11c.cpp$$
demonstrate simple multi-threading,
without algorithmic differentiation, using
OpenMP, Boost threads, and pthreads respectively
$head simple_ad$$
The $cref simple_ad.cpp$$ routine
demonstrates simple multi-threading with algorithmic differentiation.
$head sum_i_inv$$
The $cref sum_i_inv_time.cpp$$ routine
preforms a timing test for a multi-threading
example without algorithmic differentiation.
$subhead max_threads$$
If the argument $icode max_threads$$ is a non-negative integer specifying
the maximum number of threads to use for the test.
The specified test is run with the following number of threads:
$codei%
%num_threads% = 0 , %...% , %max_threads%
%$$
The value of zero corresponds to not using the multi-threading system.
$subhead mega_sum$$
The command line argument $icode mega_sum$$
is an integer greater than or equal one and has the same meaning as in
$cref/sum_i_inv_time.cpp/sum_i_inv_time.cpp/mega_sum/$$.
$head multi_newton$$
The $cref multi_newton_time.cpp$$ routine
preforms a timing test for a multi-threading
example with algorithmic differentiation.
$subhead max_threads$$
If the argument $icode max_threads$$ is a non-negative integer specifying
the maximum number of threads to use for the test.
The specified test is run with the following number of threads:
$codei%
%num_threads% = 0 , %...% , %max_threads%
%$$
The value of zero corresponds to not using the multi-threading system.
$subhead num_zero$$
The command line argument $icode num_zero$$
is an integer greater than or equal two and has the same meaning as in
$cref/multi_newton_time.cpp/multi_newton_time.cpp/num_zero/$$.
$subhead num_sub$$
The command line argument $icode num_sub$$
is an integer greater than or equal one and has the same meaning as in
$cref/multi_newton_time.cpp/multi_newton_time.cpp/num_sub/$$.
$subhead num_sum$$
The command line argument $icode num_sum$$
is an integer greater than or equal one and has the same meaning as in
$cref/multi_newton_time.cpp/multi_newton_time.cpp/num_sum/$$.
$subhead use_ad$$
The command line argument $icode use_ad$$ is either
$code true$$ or $code false$$ and has the same meaning as in
$cref/multi_newton_time.cpp/multi_newton_time.cpp/use_ad/$$.
$head Threading System Specific Routines$$
The following routines are used to link specific threading
systems through the common interface $cref thread_team.hpp$$:
$table
$rref openmp_team.cpp$$
$rref bthread_team.cpp$$
$rref pthread_team.cpp$$
$tend
$head Source$$
$code
$verbatim%multi_thread/multi_thread.cpp%0%// BEGIN PROGRAM%// END PROGRAM%1%$$
$$
$end
*/
// BEGIN PROGRAM
# include <cppad/cppad.hpp>
# include <cmath>
# include <cstring>
# include "thread_team.hpp"
# include "simple_ad.hpp"
# include "sum_i_inv_time.hpp"
# include "multi_newton_time.hpp"
extern bool a11c(void);
namespace {
size_t arg2size_t(
const char* arg ,
int limit ,
const char* error_msg )
{ int i = std::atoi(arg);
if( i >= limit )
return size_t(i);
std::cerr << "value = " << i << std::endl;
std::cerr << error_msg << std::endl;
exit(1);
}
}
int main(int argc, char *argv[])
{ using CppAD::thread_alloc;
size_t num_fail = 0;
bool ok = true;
using std::cout;
// commnd line usage message
const char *usage =
"./multi_thread a11c\n"
"./multi_thread simple_ad\n"
"./multi_thread sum_i_inv max_threads mega_sum\n"
"./multi_thread multi_newton max_threads num_zero num_sub num_sum use_ad";
// command line argument values (assign values to avoid compiler warnings)
size_t num_zero=0, num_sub=0, num_sum=0;
bool use_ad=true;
ok = false;
const char* test_name = "";
if( argc > 1 )
test_name = *++argv;
bool run_a11c = std::strcmp(test_name, "a11c") == 0;
bool run_simple_ad = std::strcmp(test_name, "simple_ad") == 0;
bool run_sum_i_inv = std::strcmp(test_name, "sum_i_inv") == 0;
bool run_multi_newton = std::strcmp(test_name, "multi_newton") == 0;
if( run_a11c || run_simple_ad )
ok = (argc == 2);
else if( run_sum_i_inv )
ok = (argc == 4);
else if( run_multi_newton )
ok = (argc == 7);
if( ! ok )
{ std::cerr << "test_name = " << test_name << std::endl;
std::cerr << "argc = " << argc << std::endl;
std::cerr << usage << std::endl;
exit(1);
}
if( run_a11c || run_simple_ad )
{ if( run_a11c )
ok = a11c();
else ok = simple_ad();
if( ok )
{ cout << "OK: " << test_name << std::endl;
exit(0);
}
else
{ cout << "Error: " << test_name << std::endl;
exit(1);
}
}
// max_threads
size_t max_threads = arg2size_t( *++argv, 0,
"run: max_threads is less than zero"
);
size_t mega_sum = 0; // assignment to avoid compiler warning
if( run_sum_i_inv )
{ // mega_sum
mega_sum = arg2size_t( *++argv, 1,
"run: mega_sum is less than one"
);
}
else
{ ok &= run_multi_newton;
// num_zero
num_zero = arg2size_t( *++argv, 2,
"run: num_zero is less than two"
);
// num_sub
num_sub = arg2size_t( *++argv, 1,
"run: num_sub is less than one"
);
// num_sum
num_sum = arg2size_t( *++argv, 1,
"run: num_sum is less than one"
);
// use_ad
++argv;
if( std::strcmp(*argv, "true") == 0 )
use_ad = true;
else if( std::strcmp(*argv, "false") == 0 )
use_ad = false;
else
{ std::cerr << "run: use_ad = '" << *argv;
std::cerr << "' is not true or false" << std::endl;
exit(1);
}
}
// run the test for each number of threads
CppAD::vector<size_t> rate_all(max_threads + 1);
size_t num_threads, inuse_this_thread = 0;
for(num_threads = 0; num_threads <= max_threads; num_threads++)
{ // set the number of threads
if( num_threads > 0 )
ok &= start_team(num_threads);
// ammount of memory initialy inuse by thread zero
ok &= 0 == thread_alloc::thread_num();
inuse_this_thread = thread_alloc::inuse(0);
// run the requested test
if( run_sum_i_inv ) ok &=
sum_i_inv_time(rate_all[num_threads], num_threads, mega_sum);
else
{ ok &= run_multi_newton;
ok &= multi_newton_time(
rate_all[num_threads] ,
num_threads ,
num_zero ,
num_sub ,
num_sum ,
use_ad
);
}
// set back to one thread and fee all avaialable memory
if( num_threads > 0 )
ok &= stop_team();
size_t thread;
for(thread = 0; thread < num_threads; thread++)
{ thread_alloc::free_available(thread);
if( thread == 0 )
ok &= thread_alloc::inuse(thread) == inuse_this_thread;
else ok &= thread_alloc::inuse(thread) == 0;
}
if( ok )
cout << "OK: " << test_name << ": ";
else
{ cout << "Error: " << test_name << ": ";
num_fail++;
}
cout << "num_threads = " << num_threads;
cout << ", rate = " << rate_all[num_threads] << std::endl;
}
cout << "rate_all = " << rate_all << std::endl;
if( num_fail == 0 )
{ cout << "All " << max_threads + 1 << " " << test_name;
cout << " tests passed." << std::endl;
}
else
{ cout << num_fail << " " << test_name;
cout << " tests failed." << std::endl;
}
return num_fail;
}
// END PROGRAM
<commit_msg>Make all output octave / matlab commands and include the command line in output.<commit_after>/* $Id$ */
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-11 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Common Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin multi_thread.cpp$$
$escape $$
$spell
inv
mega
cpp
num
pthread
pthreads
openmp
bthread
$$
$index multi_thread, example$$
$index multi_thread, speed$$
$index speed, multi_thread$$
$index example, multi_thread$$
$index thread, multi example$$
$section Run Multi-Threading Examples and Speed Tests$$
$head Syntax$$
$codei%./multi_thread a11c
%$$
$codei%./multi_thread simple_ad
%$$
$codei%./multi_thread sum_i_inv %max_threads% %mega_sum%
%$$
$codei%./multi_thread multi_newton \
%max_threads% %num_zero% %num_sub% %num_sum% %use_ad%$$
$head Running Tests$$
You can build this program and run the default version of its test
parameters by executing the following commands:
$codei%
cd multi_thread/%threading%
make test
%$$
If $cref/OpenmpFlags/InstallUnix/OpenmpFlags/$$
are specified during configuration,
you can preform the operation above with
$icode threading$$ equal to $code openmp$$.
If pthreads with barriers are supported by your system,
you can use $icode threading$$ equal to $code pthread$$.
If boost threads have been installed,
you can use $icode threading$$ equal to $code bthread$$.
$head Purpose$$
Runs the CppAD multi-threading examples and speed tests:
$children%
multi_thread/openmp/a11c.cpp%
multi_thread/bthread/a11c.cpp%
multi_thread/pthread/a11c.cpp
%$$
$head a11c$$
The examples
$cref openmp_a11c.cpp$$,
$cref bthread_a11c.cpp$$, and
$cref pthread_a11c.cpp$$
demonstrate simple multi-threading,
without algorithmic differentiation, using
OpenMP, Boost threads, and pthreads respectively
$head simple_ad$$
The $cref simple_ad.cpp$$ routine
demonstrates simple multi-threading with algorithmic differentiation.
$head sum_i_inv$$
The $cref sum_i_inv_time.cpp$$ routine
preforms a timing test for a multi-threading
example without algorithmic differentiation.
$subhead max_threads$$
If the argument $icode max_threads$$ is a non-negative integer specifying
the maximum number of threads to use for the test.
The specified test is run with the following number of threads:
$codei%
%num_threads% = 0 , %...% , %max_threads%
%$$
The value of zero corresponds to not using the multi-threading system.
$subhead mega_sum$$
The command line argument $icode mega_sum$$
is an integer greater than or equal one and has the same meaning as in
$cref/sum_i_inv_time.cpp/sum_i_inv_time.cpp/mega_sum/$$.
$head multi_newton$$
The $cref multi_newton_time.cpp$$ routine
preforms a timing test for a multi-threading
example with algorithmic differentiation.
$subhead max_threads$$
If the argument $icode max_threads$$ is a non-negative integer specifying
the maximum number of threads to use for the test.
The specified test is run with the following number of threads:
$codei%
%num_threads% = 0 , %...% , %max_threads%
%$$
The value of zero corresponds to not using the multi-threading system.
$subhead num_zero$$
The command line argument $icode num_zero$$
is an integer greater than or equal two and has the same meaning as in
$cref/multi_newton_time.cpp/multi_newton_time.cpp/num_zero/$$.
$subhead num_sub$$
The command line argument $icode num_sub$$
is an integer greater than or equal one and has the same meaning as in
$cref/multi_newton_time.cpp/multi_newton_time.cpp/num_sub/$$.
$subhead num_sum$$
The command line argument $icode num_sum$$
is an integer greater than or equal one and has the same meaning as in
$cref/multi_newton_time.cpp/multi_newton_time.cpp/num_sum/$$.
$subhead use_ad$$
The command line argument $icode use_ad$$ is either
$code true$$ or $code false$$ and has the same meaning as in
$cref/multi_newton_time.cpp/multi_newton_time.cpp/use_ad/$$.
$head Threading System Specific Routines$$
The following routines are used to link specific threading
systems through the common interface $cref thread_team.hpp$$:
$table
$rref openmp_team.cpp$$
$rref bthread_team.cpp$$
$rref pthread_team.cpp$$
$tend
$head Source$$
$code
$verbatim%multi_thread/multi_thread.cpp%0%// BEGIN PROGRAM%// END PROGRAM%1%$$
$$
$end
*/
// BEGIN PROGRAM
# include <cppad/cppad.hpp>
# include <cmath>
# include <cstring>
# include "thread_team.hpp"
# include "simple_ad.hpp"
# include "sum_i_inv_time.hpp"
# include "multi_newton_time.hpp"
extern bool a11c(void);
namespace {
size_t arg2size_t(
const char* arg ,
int limit ,
const char* error_msg )
{ int i = std::atoi(arg);
if( i >= limit )
return size_t(i);
std::cerr << "value = " << i << std::endl;
std::cerr << error_msg << std::endl;
exit(1);
}
}
int main(int argc, char *argv[])
{ using CppAD::thread_alloc;
bool ok = true;
using std::cout;
using std::endl;
// commnd line usage message
const char *usage =
"./multi_thread a11c\n"
"./multi_thread simple_ad\n"
"./multi_thread sum_i_inv max_threads mega_sum\n"
"./multi_thread multi_newton max_threads num_zero num_sub num_sum use_ad";
// command line argument values (assign values to avoid compiler warnings)
size_t num_zero=0, num_sub=0, num_sum=0;
bool use_ad=true;
// print command line as valid matlab/octave
cout << "command = '" << argv[0];
for(int i = 1; i < argc; i++)
cout << " " << argv[i];
cout << "';" << endl;
ok = false;
const char* test_name = "";
if( argc > 1 )
test_name = *++argv;
bool run_a11c = std::strcmp(test_name, "a11c") == 0;
bool run_simple_ad = std::strcmp(test_name, "simple_ad") == 0;
bool run_sum_i_inv = std::strcmp(test_name, "sum_i_inv") == 0;
bool run_multi_newton = std::strcmp(test_name, "multi_newton") == 0;
if( run_a11c || run_simple_ad )
ok = (argc == 2);
else if( run_sum_i_inv )
ok = (argc == 4);
else if( run_multi_newton )
ok = (argc == 7);
if( ! ok )
{ std::cerr << "test_name = " << test_name << endl;
std::cerr << "argc = " << argc << endl;
std::cerr << usage << endl;
exit(1);
}
if( run_a11c || run_simple_ad )
{ if( run_a11c )
ok = a11c();
else ok = simple_ad();
if( ok )
{ cout << "OK = true;" << endl;
exit(0);
}
else
{ cout << "OK = false;" << endl;
exit(1);
}
}
// max_threads
size_t max_threads = arg2size_t( *++argv, 0,
"run: max_threads is less than zero"
);
size_t mega_sum = 0; // assignment to avoid compiler warning
if( run_sum_i_inv )
{ // mega_sum
mega_sum = arg2size_t( *++argv, 1,
"run: mega_sum is less than one"
);
}
else
{ ok &= run_multi_newton;
// num_zero
num_zero = arg2size_t( *++argv, 2,
"run: num_zero is less than two"
);
// num_sub
num_sub = arg2size_t( *++argv, 1,
"run: num_sub is less than one"
);
// num_sum
num_sum = arg2size_t( *++argv, 1,
"run: num_sum is less than one"
);
// use_ad
++argv;
if( std::strcmp(*argv, "true") == 0 )
use_ad = true;
else if( std::strcmp(*argv, "false") == 0 )
use_ad = false;
else
{ std::cerr << "run: use_ad = '" << *argv;
std::cerr << "' is not true or false" << endl;
exit(1);
}
}
// run the test for each number of threads
size_t num_threads, inuse_this_thread = 0;
cout << "rate_all = [" << endl;
for(num_threads = 0; num_threads <= max_threads; num_threads++)
{ size_t rate;
// set the number of threads
if( num_threads > 0 )
ok &= start_team(num_threads);
// ammount of memory initialy inuse by thread zero
ok &= 0 == thread_alloc::thread_num();
inuse_this_thread = thread_alloc::inuse(0);
// run the requested test
if( run_sum_i_inv ) ok &=
sum_i_inv_time(rate, num_threads, mega_sum);
else
{ ok &= run_multi_newton;
ok &= multi_newton_time(
rate ,
num_threads ,
num_zero ,
num_sub ,
num_sum ,
use_ad
);
}
// set back to one thread and fee all avaialable memory
if( num_threads > 0 )
ok &= stop_team();
size_t thread;
for(thread = 0; thread < num_threads; thread++)
{ thread_alloc::free_available(thread);
if( thread == 0 )
ok &= thread_alloc::inuse(thread) == inuse_this_thread;
else ok &= thread_alloc::inuse(thread) == 0;
}
cout << "\t" << rate << " % ";
if( num_threads == 0 )
cout << "no threading" << endl;
else cout << num_threads << " threads" << endl;
}
cout << "]" << endl;
if( ok )
cout << "OK = true;" << endl;
else cout << "OK = false;" << endl;
return ! ok;
}
// END PROGRAM
<|endoftext|> |
<commit_before>/*
* Copyright 2020 nelson85.
*
* 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 "jpype.h"
#include "pyjp.h"
#include "jp_boxedclasses.h"
#ifdef __cplusplus
extern "C"
{
#endif
static PyObject *PyJPNumber_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
JP_PY_TRY("PyJPNumberLong_new", type);
ASSERT_JVM_RUNNING();
JPJavaFrame frame;
JPClass *cls = (JPClass*) PyJPClass_getJPClass((PyObject*) type);
if (cls == NULL)
JP_RAISE(PyExc_TypeError, "Class type incorrect");
PyObject *self;
if (PyObject_IsSubclass((PyObject*) type, (PyObject*) & PyLong_Type))
{
self = PyLong_Type.tp_new(type, args, kwargs);
} else if (PyObject_IsSubclass((PyObject*) type, (PyObject*) & PyFloat_Type))
{
self = PyFloat_Type.tp_new(type, args, kwargs);
} else
{
PyErr_Format(PyExc_TypeError, "Type '%s' is not a number class", type->tp_name);
return NULL;
}
if (!self)
JP_RAISE_PYTHON("type new failed");
jvalue val = cls->convertToJava(self);
PyJPValue_assignJavaSlot(self, JPValue(cls, val));
JP_TRACE("new", self);
return self;
JP_PY_CATCH(NULL);
}
static PyObject *PyJPChar_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
JP_PY_TRY("PyJPValueChar_new", type);
ASSERT_JVM_RUNNING();
JPJavaFrame frame;
PyObject *self;
if (PyTuple_Size(args) == 1 && JPPyString::checkCharUTF16(PyTuple_GetItem(args, 0)))
{
jchar i = JPPyString::asCharUTF16(PyTuple_GetItem(args, 0));
PyObject *args2 = PyTuple_Pack(1, PyLong_FromLong(i));
self = PyLong_Type.tp_new(type, args2, kwargs);
Py_DECREF(args2);
} else
{
self = PyLong_Type.tp_new(type, args, kwargs);
}
if (!self)
JP_RAISE_PYTHON("type new failed");
JPClass *cls = PyJPClass_getJPClass((PyObject*) type);
if (cls == NULL)
JP_RAISE(PyExc_TypeError, "Class type incorrect");
jvalue val = cls->convertToJava(self);
PyJPValue_assignJavaSlot(self, JPValue(cls, val));
JP_TRACE("new", self);
return self;
JP_PY_CATCH(NULL);
}
static PyObject* PyJPChar_str(PyObject* self)
{
JP_PY_TRY("PyJPValueChar_str", self);
JPValue *value = PyJPValue_getJavaSlot(self);
if (value == NULL)
JP_RAISE(PyExc_RuntimeError, "Java slot missing");
return JPPyString::fromCharUTF16(value->getValue().c).keep();
JP_PY_CATCH(NULL);
}
static PyType_Slot numberLongSlots[] = {
{Py_tp_new, (void*) &PyJPNumber_new},
{Py_tp_getattro, (void*) &PyJPValue_getattro},
{Py_tp_setattro, (void*) &PyJPValue_setattro},
{0}
};
PyTypeObject *PyJPNumberLong_Type = NULL;
PyType_Spec numberLongSpec = {
"_jpype._JNumberLong",
0,
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
numberLongSlots
};
static PyType_Slot numberFloatSlots[] = {
{Py_tp_new, (void*) &PyJPNumber_new},
{Py_tp_getattro, (void*) &PyJPValue_getattro},
{Py_tp_setattro, (void*) &PyJPValue_setattro},
{0}
};
PyTypeObject *PyJPNumberFloat_Type = NULL;
PyType_Spec numberFloatSpec = {
"_jpype._JNumberFloat",
0,
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
numberFloatSlots
};
static PyType_Slot numberCharSlots[] = {
{Py_tp_new, (void*) PyJPChar_new},
{Py_tp_getattro, (void*) &PyJPValue_getattro},
{Py_tp_setattro, (void*) &PyJPValue_setattro},
{Py_tp_str, (void*) &PyJPChar_str},
{0}
};
PyTypeObject *PyJPNumberChar_Type = NULL;
PyType_Spec numberCharSpec = {
"_jpype._JNumberChar",
0,
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
numberCharSlots
};
#ifdef __cplusplus
}
#endif
void PyJPNumber_initType(PyObject* module)
{
PyObject *bases;
bases = PyTuple_Pack(2, &PyLong_Type, PyJPObject_Type);
PyJPNumberLong_Type = (PyTypeObject*) PyJPClass_FromSpecWithBases(&numberLongSpec, bases);
Py_DECREF(bases);
JP_PY_CHECK();
PyModule_AddObject(module, "_JNumberLong", (PyObject*) PyJPNumberLong_Type);
JP_PY_CHECK();
bases = PyTuple_Pack(2, &PyFloat_Type, PyJPObject_Type);
PyJPNumberFloat_Type = (PyTypeObject*) PyJPClass_FromSpecWithBases(&numberFloatSpec, bases);
Py_DECREF(bases);
JP_PY_CHECK();
PyModule_AddObject(module, "_JNumberFloat", (PyObject*) PyJPNumberFloat_Type);
JP_PY_CHECK();
bases = PyTuple_Pack(2, &PyFloat_Type, PyJPObject_Type);
PyJPNumberFloat_Type = (PyTypeObject*) PyJPClass_FromSpecWithBases(&numberFloatSpec, bases);
Py_DECREF(bases);
JP_PY_CHECK();
PyModule_AddObject(module, "_JNumberChar", (PyObject*) PyJPNumberFloat_Type);
JP_PY_CHECK();
}
JPPyObject PyJPNumber_create(JPPyObject& wrapper, const JPValue& value)
{
// Bools are not numbers in Java
if (value.getClass() == JPTypeManager::_java_lang_Boolean)
{
jlong l = JPJni::booleanValue(value.getJavaObject());
PyObject *args = PyTuple_Pack(1, PyLong_FromLongLong(l));
return JPPyObject(JPPyRef::_call,
PyLong_Type.tp_new((PyTypeObject*) wrapper.get(), args, NULL));
}
if (PyObject_IsSubclass(wrapper.get(), (PyObject*) & PyLong_Type))
{
jlong l = JPJni::longValue(value.getJavaObject());
PyObject *args = PyTuple_Pack(1, PyLong_FromLongLong(l));
return JPPyObject(JPPyRef::_call,
PyLong_Type.tp_new((PyTypeObject*) wrapper.get(), args, NULL));
}
if (PyObject_IsSubclass(wrapper.get(), (PyObject*) & PyFloat_Type))
{
jdouble l = JPJni::doubleValue(value.getJavaObject());
PyObject *args = PyTuple_Pack(1, PyFloat_FromDouble(l));
return JPPyObject(JPPyRef::_call,
PyFloat_Type.tp_new((PyTypeObject*) wrapper.get(), args, NULL));
}
JP_RAISE(PyExc_TypeError, "unable to convert");
}
<commit_msg>Finished removing dead code.<commit_after>/*
* Copyright 2020 nelson85.
*
* 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 "jpype.h"
#include "pyjp.h"
#include "jp_boxedclasses.h"
#ifdef __cplusplus
extern "C"
{
#endif
static PyObject *PyJPNumber_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
JP_PY_TRY("PyJPNumberLong_new", type);
ASSERT_JVM_RUNNING();
JPJavaFrame frame;
JPClass *cls = (JPClass*) PyJPClass_getJPClass((PyObject*) type);
if (cls == NULL)
JP_RAISE(PyExc_TypeError, "Class type incorrect");
PyObject *self;
if (PyObject_IsSubclass((PyObject*) type, (PyObject*) & PyLong_Type))
{
self = PyLong_Type.tp_new(type, args, kwargs);
} else if (PyObject_IsSubclass((PyObject*) type, (PyObject*) & PyFloat_Type))
{
self = PyFloat_Type.tp_new(type, args, kwargs);
} else
{
PyErr_Format(PyExc_TypeError, "Type '%s' is not a number class", type->tp_name);
return NULL;
}
if (!self)
JP_RAISE_PYTHON("type new failed");
jvalue val = cls->convertToJava(self);
PyJPValue_assignJavaSlot(self, JPValue(cls, val));
JP_TRACE("new", self);
return self;
JP_PY_CATCH(NULL);
}
static PyObject *PyJPChar_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
JP_PY_TRY("PyJPValueChar_new", type);
ASSERT_JVM_RUNNING();
JPJavaFrame frame;
PyObject *self;
if (PyTuple_Size(args) == 1 && JPPyString::checkCharUTF16(PyTuple_GetItem(args, 0)))
{
jchar i = JPPyString::asCharUTF16(PyTuple_GetItem(args, 0));
PyObject *args2 = PyTuple_Pack(1, PyLong_FromLong(i));
self = PyLong_Type.tp_new(type, args2, kwargs);
Py_DECREF(args2);
} else
{
self = PyLong_Type.tp_new(type, args, kwargs);
}
if (!self)
JP_RAISE_PYTHON("type new failed");
JPClass *cls = PyJPClass_getJPClass((PyObject*) type);
if (cls == NULL)
JP_RAISE(PyExc_TypeError, "Class type incorrect");
jvalue val = cls->convertToJava(self);
PyJPValue_assignJavaSlot(self, JPValue(cls, val));
JP_TRACE("new", self);
return self;
JP_PY_CATCH(NULL);
}
static PyObject* PyJPChar_str(PyObject* self)
{
JP_PY_TRY("PyJPValueChar_str", self);
JPValue *value = PyJPValue_getJavaSlot(self);
if (value == NULL)
JP_RAISE(PyExc_RuntimeError, "Java slot missing");
return JPPyString::fromCharUTF16(value->getValue().c).keep();
JP_PY_CATCH(NULL);
}
static PyType_Slot numberLongSlots[] = {
{Py_tp_new, (void*) &PyJPNumber_new},
{Py_tp_getattro, (void*) &PyJPValue_getattro},
{Py_tp_setattro, (void*) &PyJPValue_setattro},
{0}
};
PyTypeObject *PyJPNumberLong_Type = NULL;
PyType_Spec numberLongSpec = {
"_jpype._JNumberLong",
0,
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
numberLongSlots
};
static PyType_Slot numberFloatSlots[] = {
{Py_tp_new, (void*) &PyJPNumber_new},
{Py_tp_getattro, (void*) &PyJPValue_getattro},
{Py_tp_setattro, (void*) &PyJPValue_setattro},
{0}
};
PyTypeObject *PyJPNumberFloat_Type = NULL;
PyType_Spec numberFloatSpec = {
"_jpype._JNumberFloat",
0,
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
numberFloatSlots
};
static PyType_Slot numberCharSlots[] = {
{Py_tp_new, (void*) PyJPChar_new},
{Py_tp_getattro, (void*) &PyJPValue_getattro},
{Py_tp_setattro, (void*) &PyJPValue_setattro},
{Py_tp_str, (void*) &PyJPChar_str},
{0}
};
PyTypeObject *PyJPNumberChar_Type = NULL;
PyType_Spec numberCharSpec = {
"_jpype._JNumberChar",
0,
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
numberCharSlots
};
#ifdef __cplusplus
}
#endif
void PyJPNumber_initType(PyObject* module)
{
PyObject *bases;
bases = PyTuple_Pack(2, &PyLong_Type, PyJPObject_Type);
PyJPNumberLong_Type = (PyTypeObject*) PyJPClass_FromSpecWithBases(&numberLongSpec, bases);
Py_DECREF(bases);
JP_PY_CHECK();
PyModule_AddObject(module, "_JNumberLong", (PyObject*) PyJPNumberLong_Type);
JP_PY_CHECK();
bases = PyTuple_Pack(2, &PyFloat_Type, PyJPObject_Type);
PyJPNumberFloat_Type = (PyTypeObject*) PyJPClass_FromSpecWithBases(&numberFloatSpec, bases);
Py_DECREF(bases);
JP_PY_CHECK();
PyModule_AddObject(module, "_JNumberFloat", (PyObject*) PyJPNumberFloat_Type);
JP_PY_CHECK();
bases = PyTuple_Pack(1, &PyLong_Type, PyJPObject_Type);
PyJPNumberChar_Type = (PyTypeObject*) PyJPClass_FromSpecWithBases(&numberCharSpec, bases);
Py_DECREF(bases);
JP_PY_CHECK();
PyModule_AddObject(module, "_JNumberChar", (PyObject*) PyJPNumberChar_Type);
JP_PY_CHECK();
}
JPPyObject PyJPNumber_create(JPPyObject& wrapper, const JPValue& value)
{
// Bools are not numbers in Java
if (value.getClass() == JPTypeManager::_java_lang_Boolean)
{
jlong l = JPJni::booleanValue(value.getJavaObject());
PyObject *args = PyTuple_Pack(1, PyLong_FromLongLong(l));
return JPPyObject(JPPyRef::_call,
PyLong_Type.tp_new((PyTypeObject*) wrapper.get(), args, NULL));
}
if (PyObject_IsSubclass(wrapper.get(), (PyObject*) & PyLong_Type))
{
jlong l = JPJni::longValue(value.getJavaObject());
PyObject *args = PyTuple_Pack(1, PyLong_FromLongLong(l));
return JPPyObject(JPPyRef::_call,
PyLong_Type.tp_new((PyTypeObject*) wrapper.get(), args, NULL));
}
if (PyObject_IsSubclass(wrapper.get(), (PyObject*) & PyFloat_Type))
{
jdouble l = JPJni::doubleValue(value.getJavaObject());
PyObject *args = PyTuple_Pack(1, PyFloat_FromDouble(l));
return JPPyObject(JPPyRef::_call,
PyFloat_Type.tp_new((PyTypeObject*) wrapper.get(), args, NULL));
}
JP_RAISE(PyExc_TypeError, "unable to convert");
}
<|endoftext|> |
<commit_before>/* This file is part of Ingen.
* Copyright (C) 2007 Dave Robillard <http://drobilla.net>
*
* Ingen 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.
*
* Ingen 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 details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include CONFIG_H_PATH
#include <cstdlib>
#include <pthread.h>
#include <dirent.h>
#include <float.h>
#include <cmath>
#include "module/World.hpp"
#include "NodeFactory.hpp"
#include "ThreadManager.hpp"
#include "MidiNoteNode.hpp"
#include "MidiTriggerNode.hpp"
#include "MidiControlNode.hpp"
#include "TransportNode.hpp"
#include "PluginImpl.hpp"
#include "PatchImpl.hpp"
#ifdef HAVE_SLV2
#include "LV2Node.hpp"
#include <slv2/slv2.h>
#endif
#ifdef HAVE_LADSPA
#include "LADSPANode.hpp"
#endif
using namespace std;
namespace Ingen {
/* I am perfectly aware that the vast majority of this class is a
* vomit inducing nightmare at the moment ;)
*/
NodeFactory::NodeFactory(Ingen::Shared::World* world)
: _world(world)
, _has_loaded(false)
{
}
NodeFactory::~NodeFactory()
{
for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i)
if (i->second->type() != Plugin::Internal)
delete i->second;
_plugins.clear();
}
PluginImpl*
NodeFactory::plugin(const string& uri)
{
Plugins::const_iterator i = _plugins.find(uri);
return ((i != _plugins.end()) ? i->second : NULL);
}
/** DEPRECATED: Find a plugin by type, lib, label.
*
* Slow. Evil. Do not use.
*/
PluginImpl*
NodeFactory::plugin(const string& type, const string& lib, const string& label)
{
if (type == "" || lib == "" || label == "")
return NULL;
for (Plugins::const_iterator i = _plugins.begin(); i != _plugins.end(); ++i)
if (i->second->type_string() == type
&& i->second->lib_name() == lib
&& i->second->plug_label() == label)
return i->second;
cerr << "ERROR: Failed to find " << type << " plugin " << lib << " / " << label << endl;
return NULL;
}
void
NodeFactory::load_plugins()
{
assert(ThreadManager::current_thread_id() == THREAD_PRE_PROCESS);
// Only load if we havn't already, so every client connecting doesn't cause
// this (expensive!) stuff to happen. Not the best solution - would be nice
// if clients could refresh plugins list for whatever reason :/
if (!_has_loaded) {
_plugins.clear(); // FIXME: assert empty?
load_internal_plugins();
#ifdef HAVE_SLV2
load_lv2_plugins();
#endif
#ifdef HAVE_LADSPA
load_ladspa_plugins();
#endif
_has_loaded = true;
}
//cerr << "[NodeFactory] # Plugins: " << _plugins.size() << endl;
}
/** Loads a plugin.
*
* Calls the load_*_plugin functions to actually do things, just a wrapper.
*/
NodeImpl*
NodeFactory::load_plugin(PluginImpl* plugin,
const string& name,
bool polyphonic,
PatchImpl* parent)
{
assert(parent != NULL);
assert(plugin);
NodeImpl* r = NULL;
const SampleRate srate = parent->sample_rate();
const size_t buffer_size = parent->buffer_size();
switch (plugin->type()) {
#ifdef HAVE_SLV2
case Plugin::LV2:
r = load_lv2_plugin(plugin, name, polyphonic, parent, srate, buffer_size);
break;
#endif
#ifdef HAVE_LADSPA
case Plugin::LADSPA:
r = load_ladspa_plugin(plugin, name, polyphonic, parent, srate, buffer_size);
break;
#endif
case Plugin::Internal:
r = load_internal_plugin(plugin, name, polyphonic, parent, srate, buffer_size);
break;
default:
cerr << "[NodeFactory] WARNING: Unknown plugin type." << endl;
}
return r;
}
void
NodeFactory::load_internal_plugins()
{
// This is a touch gross...
PatchImpl* parent = new PatchImpl(*_world->local_engine, "dummy", 1, NULL, 1, 1, 1);
NodeImpl* n = NULL;
n = new MidiNoteNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
n = new MidiTriggerNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
n = new MidiControlNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
n = new TransportNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
delete parent;
}
/** Loads an internal plugin.
*/
NodeImpl*
NodeFactory::load_internal_plugin(PluginImpl* plugin,
const string& name,
bool polyphonic,
PatchImpl* parent,
SampleRate srate,
size_t buffer_size)
{
assert(plugin);
assert(plugin->type() == Plugin::Internal);
assert(parent != NULL);
assert(plugin->uri().length() > 6);
assert(plugin->uri().substr(0, 6) == "ingen:");
return plugin->instantiate(name, polyphonic, parent, srate, buffer_size);
}
#ifdef HAVE_SLV2
/** Loads information about all LV2 plugins into internal plugin database.
*/
void
NodeFactory::load_lv2_plugins()
{
SLV2Plugins plugins = slv2_world_get_all_plugins(_world->slv2_world);
//cerr << "[NodeFactory] Found " << slv2_plugins_size(plugins) << " LV2 plugins:" << endl;
for (unsigned i=0; i < slv2_plugins_size(plugins); ++i) {
SLV2Plugin lv2_plug = slv2_plugins_get_at(plugins, i);
#ifndef NDEBUG
const string uri((const char*)slv2_plugin_get_uri(lv2_plug));
assert(_plugins.find(uri) == _plugins.end());
#endif
PluginImpl* const plugin = new PluginImpl(Plugin::LV2, uri);
plugin->slv2_plugin(lv2_plug);
plugin->lib_path(slv2_uri_to_path(slv2_plugin_get_library_uri(lv2_plug)));
char* const name = slv2_plugin_get_name(lv2_plug);
if (name) {
plugin->name(name);
free(name);
_plugins.insert(make_pair(uri, plugin));
} else {
cerr << "ERROR: LV2 Plugin " << uri << " has no name. Ignoring." << endl;
continue;
}
}
slv2_plugins_free(_world->slv2_world, plugins);
}
/** Loads a LV2 plugin.
* Returns 'poly' independant plugins as a NodeImpl*
*/
NodeImpl*
NodeFactory::load_lv2_plugin(PluginImpl* plugin,
const string& node_name,
bool polyphonic,
PatchImpl* parent,
SampleRate srate,
size_t buffer_size)
{
assert(plugin);
assert(plugin->type() == Plugin::LV2);
NodeImpl* n = NULL;
plugin->load(); // FIXME: unload
n = new LV2Node(plugin, node_name, polyphonic, parent, srate, buffer_size);
Glib::Mutex::Lock lock(_world->rdf_world->mutex());
const bool success = ((LV2Node*)n)->instantiate();
if (!success) {
delete n;
n = NULL;
}
return n;
}
#endif // HAVE_SLV2
#ifdef HAVE_LADSPA
/** Loads information about all LADSPA plugins into internal plugin database.
*/
void
NodeFactory::load_ladspa_plugins()
{
char* env_ladspa_path = getenv("LADSPA_PATH");
string ladspa_path;
if (!env_ladspa_path) {
cerr << "[NodeFactory] LADSPA_PATH is empty. Assuming /usr/lib/ladspa:/usr/local/lib/ladspa:~/.ladspa" << endl;
ladspa_path = string("/usr/lib/ladspa:/usr/local/lib/ladspa:").append(
getenv("HOME")).append("/.ladspa");
} else {
ladspa_path = env_ladspa_path;
}
// Yep, this should use an sstream alright..
while (ladspa_path != "") {
const string dir = ladspa_path.substr(0, ladspa_path.find(':'));
if (ladspa_path.find(':') != string::npos)
ladspa_path = ladspa_path.substr(ladspa_path.find(':')+1);
else
ladspa_path = "";
DIR* pdir = opendir(dir.c_str());
if (pdir == NULL) {
//cerr << "[NodeFactory] Unreadable directory in LADSPA_PATH: " << dir.c_str() << endl;
continue;
}
struct dirent* pfile;
while ((pfile = readdir(pdir))) {
LADSPA_Descriptor_Function df = NULL;
LADSPA_Descriptor* descriptor = NULL;
if (!strcmp(pfile->d_name, ".") || !strcmp(pfile->d_name, ".."))
continue;
const string lib_path = dir +"/"+ pfile->d_name;
// Ignore stupid libtool files. Kludge alert.
if (lib_path.substr(lib_path.length()-3) == ".la") {
//cerr << "WARNING: Skipping stupid libtool file " << pfile->d_name << endl;
continue;
}
Glib::Module* plugin_library = new Glib::Module(lib_path, Glib::MODULE_BIND_LOCAL);
if (!plugin_library || !(*plugin_library)) {
cerr << "WARNING: Failed to load LADSPA library " << lib_path << endl;
continue;
}
bool found = plugin_library->get_symbol("ladspa_descriptor", (void*&)df);
if (!found || !df) {
cerr << "WARNING: Non-LADSPA library found in LADSPA path: " <<
lib_path << endl;
// Not a LADSPA plugin library
delete plugin_library;
continue;
}
for (unsigned long i=0; (descriptor = (LADSPA_Descriptor*)df(i)) != NULL; ++i) {
char id_str[11];
snprintf(id_str, 11, "%lu", descriptor->UniqueID);
const string uri = string("ladspa:").append(id_str);
const Plugins::const_iterator i = _plugins.find(uri);
if (i == _plugins.end()) {
PluginImpl* plugin = new PluginImpl(Plugin::LADSPA, uri);
assert(plugin_library != NULL);
plugin->module(NULL);
plugin->lib_path(lib_path);
plugin->plug_label(descriptor->Label);
plugin->name(descriptor->Name);
plugin->type(Plugin::LADSPA);
plugin->id(descriptor->UniqueID);
_plugins.insert(make_pair(uri, plugin));
} else {
cerr << "Warning: Duplicate LADSPA plugin " << uri << " found." << endl;
cerr << "\tUsing " << i->second->lib_path() << " over " << lib_path << endl;
}
}
delete plugin_library;
}
closedir(pdir);
}
}
/** Loads a LADSPA plugin.
* Returns 'poly' independant plugins as a NodeImpl*
*/
NodeImpl*
NodeFactory::load_ladspa_plugin(PluginImpl* plugin,
const string& name,
bool polyphonic,
PatchImpl* parent,
SampleRate srate,
size_t buffer_size)
{
assert(plugin);
assert(plugin->type() == Plugin::LADSPA);
assert(plugin->id() != 0);
assert(name != "");
LADSPA_Descriptor_Function df = NULL;
NodeImpl* n = NULL;
plugin->load(); // FIXME: unload
assert(plugin->module());
assert(*plugin->module());
if (!plugin->module()->get_symbol("ladspa_descriptor", (void*&)df)) {
cerr << "Looks like this isn't a LADSPA plugin." << endl;
return NULL;
}
// Attempt to find the plugin in lib
LADSPA_Descriptor* descriptor = NULL;
for (unsigned long i=0; (descriptor = (LADSPA_Descriptor*)df(i)) != NULL; ++i) {
if (descriptor->UniqueID == plugin->id()) {
break;
}
}
if (descriptor == NULL) {
cerr << "Could not find plugin \"" << plugin->id() << "\" in " << plugin->lib_path() << endl;
return NULL;
}
n = new LADSPANode(plugin, name, polyphonic, parent, descriptor, srate, buffer_size);
bool success = ((LADSPANode*)n)->instantiate();
if (!success) {
delete n;
n = NULL;
}
return n;
}
#endif // HAVE_LADSPA
} // namespace Ingen
<commit_msg>Fix broken compilation w/o --enable-debug<commit_after>/* This file is part of Ingen.
* Copyright (C) 2007 Dave Robillard <http://drobilla.net>
*
* Ingen 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.
*
* Ingen 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 details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include CONFIG_H_PATH
#include <cstdlib>
#include <pthread.h>
#include <dirent.h>
#include <float.h>
#include <cmath>
#include "module/World.hpp"
#include "NodeFactory.hpp"
#include "ThreadManager.hpp"
#include "MidiNoteNode.hpp"
#include "MidiTriggerNode.hpp"
#include "MidiControlNode.hpp"
#include "TransportNode.hpp"
#include "PluginImpl.hpp"
#include "PatchImpl.hpp"
#ifdef HAVE_SLV2
#include "LV2Node.hpp"
#include <slv2/slv2.h>
#endif
#ifdef HAVE_LADSPA
#include "LADSPANode.hpp"
#endif
using namespace std;
namespace Ingen {
/* I am perfectly aware that the vast majority of this class is a
* vomit inducing nightmare at the moment ;)
*/
NodeFactory::NodeFactory(Ingen::Shared::World* world)
: _world(world)
, _has_loaded(false)
{
}
NodeFactory::~NodeFactory()
{
for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i)
if (i->second->type() != Plugin::Internal)
delete i->second;
_plugins.clear();
}
PluginImpl*
NodeFactory::plugin(const string& uri)
{
Plugins::const_iterator i = _plugins.find(uri);
return ((i != _plugins.end()) ? i->second : NULL);
}
/** DEPRECATED: Find a plugin by type, lib, label.
*
* Slow. Evil. Do not use.
*/
PluginImpl*
NodeFactory::plugin(const string& type, const string& lib, const string& label)
{
if (type == "" || lib == "" || label == "")
return NULL;
for (Plugins::const_iterator i = _plugins.begin(); i != _plugins.end(); ++i)
if (i->second->type_string() == type
&& i->second->lib_name() == lib
&& i->second->plug_label() == label)
return i->second;
cerr << "ERROR: Failed to find " << type << " plugin " << lib << " / " << label << endl;
return NULL;
}
void
NodeFactory::load_plugins()
{
assert(ThreadManager::current_thread_id() == THREAD_PRE_PROCESS);
// Only load if we havn't already, so every client connecting doesn't cause
// this (expensive!) stuff to happen. Not the best solution - would be nice
// if clients could refresh plugins list for whatever reason :/
if (!_has_loaded) {
_plugins.clear(); // FIXME: assert empty?
load_internal_plugins();
#ifdef HAVE_SLV2
load_lv2_plugins();
#endif
#ifdef HAVE_LADSPA
load_ladspa_plugins();
#endif
_has_loaded = true;
}
//cerr << "[NodeFactory] # Plugins: " << _plugins.size() << endl;
}
/** Loads a plugin.
*
* Calls the load_*_plugin functions to actually do things, just a wrapper.
*/
NodeImpl*
NodeFactory::load_plugin(PluginImpl* plugin,
const string& name,
bool polyphonic,
PatchImpl* parent)
{
assert(parent != NULL);
assert(plugin);
NodeImpl* r = NULL;
const SampleRate srate = parent->sample_rate();
const size_t buffer_size = parent->buffer_size();
switch (plugin->type()) {
#ifdef HAVE_SLV2
case Plugin::LV2:
r = load_lv2_plugin(plugin, name, polyphonic, parent, srate, buffer_size);
break;
#endif
#ifdef HAVE_LADSPA
case Plugin::LADSPA:
r = load_ladspa_plugin(plugin, name, polyphonic, parent, srate, buffer_size);
break;
#endif
case Plugin::Internal:
r = load_internal_plugin(plugin, name, polyphonic, parent, srate, buffer_size);
break;
default:
cerr << "[NodeFactory] WARNING: Unknown plugin type." << endl;
}
return r;
}
void
NodeFactory::load_internal_plugins()
{
// This is a touch gross...
PatchImpl* parent = new PatchImpl(*_world->local_engine, "dummy", 1, NULL, 1, 1, 1);
NodeImpl* n = NULL;
n = new MidiNoteNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
n = new MidiTriggerNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
n = new MidiControlNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
n = new TransportNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
delete parent;
}
/** Loads an internal plugin.
*/
NodeImpl*
NodeFactory::load_internal_plugin(PluginImpl* plugin,
const string& name,
bool polyphonic,
PatchImpl* parent,
SampleRate srate,
size_t buffer_size)
{
assert(plugin);
assert(plugin->type() == Plugin::Internal);
assert(parent != NULL);
assert(plugin->uri().length() > 6);
assert(plugin->uri().substr(0, 6) == "ingen:");
return plugin->instantiate(name, polyphonic, parent, srate, buffer_size);
}
#ifdef HAVE_SLV2
/** Loads information about all LV2 plugins into internal plugin database.
*/
void
NodeFactory::load_lv2_plugins()
{
SLV2Plugins plugins = slv2_world_get_all_plugins(_world->slv2_world);
//cerr << "[NodeFactory] Found " << slv2_plugins_size(plugins) << " LV2 plugins:" << endl;
for (unsigned i=0; i < slv2_plugins_size(plugins); ++i) {
SLV2Plugin lv2_plug = slv2_plugins_get_at(plugins, i);
const string uri((const char*)slv2_plugin_get_uri(lv2_plug));
#ifndef NDEBUG
assert(_plugins.find(uri) == _plugins.end());
#endif
PluginImpl* const plugin = new PluginImpl(Plugin::LV2, uri);
plugin->slv2_plugin(lv2_plug);
plugin->lib_path(slv2_uri_to_path(slv2_plugin_get_library_uri(lv2_plug)));
char* const name = slv2_plugin_get_name(lv2_plug);
if (name) {
plugin->name(name);
free(name);
_plugins.insert(make_pair(uri, plugin));
} else {
cerr << "ERROR: LV2 Plugin " << uri << " has no name. Ignoring." << endl;
continue;
}
}
slv2_plugins_free(_world->slv2_world, plugins);
}
/** Loads a LV2 plugin.
* Returns 'poly' independant plugins as a NodeImpl*
*/
NodeImpl*
NodeFactory::load_lv2_plugin(PluginImpl* plugin,
const string& node_name,
bool polyphonic,
PatchImpl* parent,
SampleRate srate,
size_t buffer_size)
{
assert(plugin);
assert(plugin->type() == Plugin::LV2);
NodeImpl* n = NULL;
plugin->load(); // FIXME: unload
n = new LV2Node(plugin, node_name, polyphonic, parent, srate, buffer_size);
Glib::Mutex::Lock lock(_world->rdf_world->mutex());
const bool success = ((LV2Node*)n)->instantiate();
if (!success) {
delete n;
n = NULL;
}
return n;
}
#endif // HAVE_SLV2
#ifdef HAVE_LADSPA
/** Loads information about all LADSPA plugins into internal plugin database.
*/
void
NodeFactory::load_ladspa_plugins()
{
char* env_ladspa_path = getenv("LADSPA_PATH");
string ladspa_path;
if (!env_ladspa_path) {
cerr << "[NodeFactory] LADSPA_PATH is empty. Assuming /usr/lib/ladspa:/usr/local/lib/ladspa:~/.ladspa" << endl;
ladspa_path = string("/usr/lib/ladspa:/usr/local/lib/ladspa:").append(
getenv("HOME")).append("/.ladspa");
} else {
ladspa_path = env_ladspa_path;
}
// Yep, this should use an sstream alright..
while (ladspa_path != "") {
const string dir = ladspa_path.substr(0, ladspa_path.find(':'));
if (ladspa_path.find(':') != string::npos)
ladspa_path = ladspa_path.substr(ladspa_path.find(':')+1);
else
ladspa_path = "";
DIR* pdir = opendir(dir.c_str());
if (pdir == NULL) {
//cerr << "[NodeFactory] Unreadable directory in LADSPA_PATH: " << dir.c_str() << endl;
continue;
}
struct dirent* pfile;
while ((pfile = readdir(pdir))) {
LADSPA_Descriptor_Function df = NULL;
LADSPA_Descriptor* descriptor = NULL;
if (!strcmp(pfile->d_name, ".") || !strcmp(pfile->d_name, ".."))
continue;
const string lib_path = dir +"/"+ pfile->d_name;
// Ignore stupid libtool files. Kludge alert.
if (lib_path.substr(lib_path.length()-3) == ".la") {
//cerr << "WARNING: Skipping stupid libtool file " << pfile->d_name << endl;
continue;
}
Glib::Module* plugin_library = new Glib::Module(lib_path, Glib::MODULE_BIND_LOCAL);
if (!plugin_library || !(*plugin_library)) {
cerr << "WARNING: Failed to load LADSPA library " << lib_path << endl;
continue;
}
bool found = plugin_library->get_symbol("ladspa_descriptor", (void*&)df);
if (!found || !df) {
cerr << "WARNING: Non-LADSPA library found in LADSPA path: " <<
lib_path << endl;
// Not a LADSPA plugin library
delete plugin_library;
continue;
}
for (unsigned long i=0; (descriptor = (LADSPA_Descriptor*)df(i)) != NULL; ++i) {
char id_str[11];
snprintf(id_str, 11, "%lu", descriptor->UniqueID);
const string uri = string("ladspa:").append(id_str);
const Plugins::const_iterator i = _plugins.find(uri);
if (i == _plugins.end()) {
PluginImpl* plugin = new PluginImpl(Plugin::LADSPA, uri);
assert(plugin_library != NULL);
plugin->module(NULL);
plugin->lib_path(lib_path);
plugin->plug_label(descriptor->Label);
plugin->name(descriptor->Name);
plugin->type(Plugin::LADSPA);
plugin->id(descriptor->UniqueID);
_plugins.insert(make_pair(uri, plugin));
} else {
cerr << "Warning: Duplicate LADSPA plugin " << uri << " found." << endl;
cerr << "\tUsing " << i->second->lib_path() << " over " << lib_path << endl;
}
}
delete plugin_library;
}
closedir(pdir);
}
}
/** Loads a LADSPA plugin.
* Returns 'poly' independant plugins as a NodeImpl*
*/
NodeImpl*
NodeFactory::load_ladspa_plugin(PluginImpl* plugin,
const string& name,
bool polyphonic,
PatchImpl* parent,
SampleRate srate,
size_t buffer_size)
{
assert(plugin);
assert(plugin->type() == Plugin::LADSPA);
assert(plugin->id() != 0);
assert(name != "");
LADSPA_Descriptor_Function df = NULL;
NodeImpl* n = NULL;
plugin->load(); // FIXME: unload
assert(plugin->module());
assert(*plugin->module());
if (!plugin->module()->get_symbol("ladspa_descriptor", (void*&)df)) {
cerr << "Looks like this isn't a LADSPA plugin." << endl;
return NULL;
}
// Attempt to find the plugin in lib
LADSPA_Descriptor* descriptor = NULL;
for (unsigned long i=0; (descriptor = (LADSPA_Descriptor*)df(i)) != NULL; ++i) {
if (descriptor->UniqueID == plugin->id()) {
break;
}
}
if (descriptor == NULL) {
cerr << "Could not find plugin \"" << plugin->id() << "\" in " << plugin->lib_path() << endl;
return NULL;
}
n = new LADSPANode(plugin, name, polyphonic, parent, descriptor, srate, buffer_size);
bool success = ((LADSPANode*)n)->instantiate();
if (!success) {
delete n;
n = NULL;
}
return n;
}
#endif // HAVE_LADSPA
} // namespace Ingen
<|endoftext|> |
<commit_before>#ifndef SLA_HOLLOWING_HPP
#define SLA_HOLLOWING_HPP
#include <memory>
#include <libslic3r/SLA/Contour3D.hpp>
#include <libslic3r/SLA/JobController.hpp>
namespace Slic3r {
class TriangleMesh;
namespace sla {
struct HollowingConfig
{
double min_thickness = 2.;
double quality = 0.5;
double closing_distance = 0.5;
bool enabled = true;
};
enum HollowingFlags { hfRemoveInsideTriangles = 0x1 };
// All data related to a generated mesh interior. Includes the 3D grid and mesh
// and various metadata. No need to manipulate from outside.
struct Interior;
struct InteriorDeleter { void operator()(Interior *p); };
using InteriorPtr = std::unique_ptr<Interior, InteriorDeleter>;
TriangleMesh & get_mesh(Interior &interior);
const TriangleMesh &get_mesh(const Interior &interior);
struct DrainHole
{
Vec3f pos;
Vec3f normal;
float radius;
float height;
bool failed = false;
DrainHole()
: pos(Vec3f::Zero()), normal(Vec3f::UnitZ()), radius(5.f), height(10.f)
{}
DrainHole(Vec3f p, Vec3f n, float r, float h)
: pos(p), normal(n), radius(r), height(h)
{}
DrainHole(const DrainHole& rhs) :
DrainHole(rhs.pos, rhs.normal, rhs.radius, rhs.height) {}
bool operator==(const DrainHole &sp) const;
bool operator!=(const DrainHole &sp) const { return !(sp == (*this)); }
bool is_inside(const Vec3f& pt) const;
bool get_intersections(const Vec3f& s, const Vec3f& dir,
std::array<std::pair<float, Vec3d>, 2>& out) const;
Contour3D to_mesh() const;
template<class Archive> inline void serialize(Archive &ar)
{
ar(pos, normal, radius, height);
}
static constexpr size_t steps = 32;
};
using DrainHoles = std::vector<DrainHole>;
constexpr float HoleStickOutLength = 1.f;
InteriorPtr generate_interior(const TriangleMesh &mesh,
const HollowingConfig & = {},
const JobController &ctl = {});
// Will do the hollowing
void hollow_mesh(TriangleMesh &mesh, const HollowingConfig &cfg, int flags = 0);
// Hollowing prepared in "interior", merge with original mesh
void hollow_mesh(TriangleMesh &mesh, const Interior &interior, int flags = 0);
void remove_inside_triangles(TriangleMesh &mesh, const Interior &interior,
const std::vector<bool> &exclude_mask = {});
double get_distance(const Vec3f &p, const Interior &interior);
template<class T>
FloatingOnly<T> get_distance(const Vec<3, T> &p, const Interior &interior)
{
return get_distance(Vec3f(p.template cast<float>()), interior);
}
void cut_drainholes(std::vector<ExPolygons> & obj_slices,
const std::vector<float> &slicegrid,
float closing_radius,
const sla::DrainHoles & holes,
std::function<void(void)> thr);
}
}
#endif // HOLLOWINGFILTER_H
<commit_msg>Fix unmarked failed holes on first gizmo opening<commit_after>#ifndef SLA_HOLLOWING_HPP
#define SLA_HOLLOWING_HPP
#include <memory>
#include <libslic3r/SLA/Contour3D.hpp>
#include <libslic3r/SLA/JobController.hpp>
namespace Slic3r {
class TriangleMesh;
namespace sla {
struct HollowingConfig
{
double min_thickness = 2.;
double quality = 0.5;
double closing_distance = 0.5;
bool enabled = true;
};
enum HollowingFlags { hfRemoveInsideTriangles = 0x1 };
// All data related to a generated mesh interior. Includes the 3D grid and mesh
// and various metadata. No need to manipulate from outside.
struct Interior;
struct InteriorDeleter { void operator()(Interior *p); };
using InteriorPtr = std::unique_ptr<Interior, InteriorDeleter>;
TriangleMesh & get_mesh(Interior &interior);
const TriangleMesh &get_mesh(const Interior &interior);
struct DrainHole
{
Vec3f pos;
Vec3f normal;
float radius;
float height;
bool failed = false;
DrainHole()
: pos(Vec3f::Zero()), normal(Vec3f::UnitZ()), radius(5.f), height(10.f)
{}
DrainHole(Vec3f p, Vec3f n, float r, float h, bool fl = false)
: pos(p), normal(n), radius(r), height(h), failed(fl)
{}
DrainHole(const DrainHole& rhs) :
DrainHole(rhs.pos, rhs.normal, rhs.radius, rhs.height, rhs.failed) {}
bool operator==(const DrainHole &sp) const;
bool operator!=(const DrainHole &sp) const { return !(sp == (*this)); }
bool is_inside(const Vec3f& pt) const;
bool get_intersections(const Vec3f& s, const Vec3f& dir,
std::array<std::pair<float, Vec3d>, 2>& out) const;
Contour3D to_mesh() const;
template<class Archive> inline void serialize(Archive &ar)
{
ar(pos, normal, radius, height, failed);
}
static constexpr size_t steps = 32;
};
using DrainHoles = std::vector<DrainHole>;
constexpr float HoleStickOutLength = 1.f;
InteriorPtr generate_interior(const TriangleMesh &mesh,
const HollowingConfig & = {},
const JobController &ctl = {});
// Will do the hollowing
void hollow_mesh(TriangleMesh &mesh, const HollowingConfig &cfg, int flags = 0);
// Hollowing prepared in "interior", merge with original mesh
void hollow_mesh(TriangleMesh &mesh, const Interior &interior, int flags = 0);
void remove_inside_triangles(TriangleMesh &mesh, const Interior &interior,
const std::vector<bool> &exclude_mask = {});
double get_distance(const Vec3f &p, const Interior &interior);
template<class T>
FloatingOnly<T> get_distance(const Vec<3, T> &p, const Interior &interior)
{
return get_distance(Vec3f(p.template cast<float>()), interior);
}
void cut_drainholes(std::vector<ExPolygons> & obj_slices,
const std::vector<float> &slicegrid,
float closing_radius,
const sla::DrainHoles & holes,
std::function<void(void)> thr);
}
}
#endif // HOLLOWINGFILTER_H
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.