text stringlengths 54 60.6k |
|---|
<commit_before>/**
* @file classifier_test.cpp
* @author Sean Massung
*/
#include <random>
#include "test/classifier_test.h"
#include "classify/loss/all.h"
namespace meta
{
namespace testing
{
template <class Index, class Classifier>
void check_cv(Index& idx, Classifier& c, double min_accuracy)
{
std::vector<doc_id> docs = idx.docs();
classify::confusion_matrix mtx = c.cross_validate(docs, 5);
ASSERT_GREATER(mtx.accuracy(), min_accuracy);
ASSERT_LESS(mtx.accuracy(), 100.0);
}
template <class Index, class Classifier>
void check_split(Index& idx, Classifier& c, double min_accuracy)
{
// create splits
std::vector<doc_id> docs = idx.docs();
std::mt19937 gen(47);
std::shuffle(docs.begin(), docs.end(), gen);
size_t split_idx = docs.size() / 8;
std::vector<doc_id> train_docs{docs.begin() + split_idx, docs.end()};
std::vector<doc_id> test_docs{docs.begin(), docs.begin() + split_idx};
// train and test
c.train(train_docs);
classify::confusion_matrix mtx = c.test(test_docs);
ASSERT_GREATER(mtx.accuracy(), min_accuracy);
ASSERT_LESS(mtx.accuracy(), 100.0);
}
int run_tests(const std::string& type)
{
using namespace classify;
int num_failed = 0;
auto i_idx =
index::make_index<index::inverted_index, caching::no_evict_cache>(
"test-config.toml");
auto f_idx =
index::make_index<index::forward_index, caching::no_evict_cache>(
"test-config.toml");
num_failed += testing::run_test("naive-bayes-cv-" + type, [&]()
{
naive_bayes nb{f_idx};
check_cv(*f_idx, nb, 0.84);
});
num_failed += testing::run_test("naive-bayes-split-" + type, [&]()
{
naive_bayes nb{f_idx};
check_split(*f_idx, nb, 0.83);
});
num_failed += testing::run_test("knn-cv-" + type, [&]()
{
knn kn{i_idx, f_idx, 10, make_unique<index::okapi_bm25>()};
check_cv(*f_idx, kn, 0.90);
});
num_failed += testing::run_test("knn-split-" + type, [&]()
{
knn kn{i_idx, f_idx, 10, make_unique<index::okapi_bm25>()};
check_split(*f_idx, kn, 0.88);
});
num_failed += testing::run_test("sgd-cv-" + type, [&]()
{
one_vs_all hinge_sgd{f_idx, [&](class_label positive)
{
return make_unique<sgd>("sgd-model-test", f_idx, positive,
class_label{"negative"}, make_unique<loss::hinge>());
}};
check_cv(*f_idx, hinge_sgd, 0.93);
one_vs_all perceptron{f_idx, [&](class_label positive)
{
return make_unique<sgd>("sgd-model-test", f_idx, positive,
class_label{"negative"}, make_unique<loss::perceptron>());
}};
check_cv(*f_idx, perceptron, 0.89);
});
num_failed += testing::run_test("sgd-split-" + type, [&]()
{
one_vs_all hinge_sgd{f_idx, [&](class_label positive)
{
return make_unique<sgd>("sgd-model-test", f_idx, positive,
class_label{"negative"}, make_unique<loss::hinge>());
}};
check_split(*f_idx, hinge_sgd, 0.89);
one_vs_all perceptron{f_idx, [&](class_label positive)
{
return make_unique<sgd>("sgd-model-test", f_idx, positive,
class_label{"negative"}, make_unique<loss::perceptron>());
}};
check_split(*f_idx, perceptron, 0.85);
});
num_failed += testing::run_test("log-reg-cv-" + type, [&]()
{
logistic_regression logreg{"logreg-model-test", f_idx};
check_cv(*f_idx, logreg, 0.92);
});
num_failed += testing::run_test("log-reg-split-" + type, [&]()
{
logistic_regression logreg{"logreg-model-test", f_idx};
check_split(*f_idx, logreg, 0.87);
});
num_failed += testing::run_test("winnow-cv-" + type, [&]()
{
winnow win{f_idx};
check_cv(*f_idx, win, 0.80);
});
num_failed += testing::run_test("winnow-split-" + type, [&]()
{
winnow win{f_idx};
// this is *really* low... is winnow broken?
check_split(*f_idx, win, 0.65);
});
num_failed += testing::run_test("svm-wrapper-" + type, [&]()
{
auto config = cpptoml::parse_file("test-config.toml");
auto mod_path = config.get_as<std::string>("libsvm-modules");
if (!mod_path)
throw std::runtime_error{"no path for libsvm-modules"};
svm_wrapper svm{f_idx, *mod_path};
check_cv(*f_idx, svm, .80);
});
system("rm -rf ceeaus-*");
return num_failed;
}
int classifier_tests()
{
int num_failed = 0;
system("rm -rf ceeaus-*");
create_config("file");
num_failed += run_tests("file");
create_config("line");
num_failed += run_tests("line");
return num_failed;
}
}
}
<commit_msg>unit test for nearest_centroid<commit_after>/**
* @file classifier_test.cpp
* @author Sean Massung
*/
#include <random>
#include "test/classifier_test.h"
#include "classify/loss/all.h"
namespace meta
{
namespace testing
{
template <class Index, class Classifier>
void check_cv(Index& idx, Classifier& c, double min_accuracy)
{
std::vector<doc_id> docs = idx.docs();
classify::confusion_matrix mtx = c.cross_validate(docs, 5);
ASSERT_GREATER(mtx.accuracy(), min_accuracy);
ASSERT_LESS(mtx.accuracy(), 100.0);
}
template <class Index, class Classifier>
void check_split(Index& idx, Classifier& c, double min_accuracy)
{
// create splits
std::vector<doc_id> docs = idx.docs();
std::mt19937 gen(47);
std::shuffle(docs.begin(), docs.end(), gen);
size_t split_idx = docs.size() / 8;
std::vector<doc_id> train_docs{docs.begin() + split_idx, docs.end()};
std::vector<doc_id> test_docs{docs.begin(), docs.begin() + split_idx};
// train and test
c.train(train_docs);
classify::confusion_matrix mtx = c.test(test_docs);
ASSERT_GREATER(mtx.accuracy(), min_accuracy);
ASSERT_LESS(mtx.accuracy(), 100.0);
}
int run_tests(const std::string& type)
{
using namespace classify;
int num_failed = 0;
auto i_idx =
index::make_index<index::inverted_index, caching::no_evict_cache>(
"test-config.toml");
auto f_idx =
index::make_index<index::forward_index, caching::no_evict_cache>(
"test-config.toml");
num_failed += testing::run_test("naive-bayes-cv-" + type, [&]()
{
naive_bayes nb{f_idx};
check_cv(*f_idx, nb, 0.84);
});
num_failed += testing::run_test("naive-bayes-split-" + type, [&]()
{
naive_bayes nb{f_idx};
check_split(*f_idx, nb, 0.83);
});
num_failed += testing::run_test("knn-cv-" + type, [&]()
{
knn kn{i_idx, f_idx, 10, make_unique<index::okapi_bm25>()};
check_cv(*f_idx, kn, 0.90);
});
num_failed += testing::run_test("knn-split-" + type, [&]()
{
knn kn{i_idx, f_idx, 10, make_unique<index::okapi_bm25>()};
check_split(*f_idx, kn, 0.88);
});
num_failed += testing::run_test("nearest-centroid-cv-" + type, [&]()
{
nearest_centroid nc{i_idx, f_idx};
check_cv(*f_idx, nc, 0.88);
});
num_failed += testing::run_test("nearest-centroid-split-" + type, [&]()
{
nearest_centroid nc{i_idx, f_idx};
check_split(*f_idx, nc, 0.84);
});
num_failed += testing::run_test("sgd-cv-" + type, [&]()
{
one_vs_all hinge_sgd{f_idx, [&](class_label positive)
{
return make_unique<sgd>("sgd-model-test", f_idx, positive,
class_label{"negative"}, make_unique<loss::hinge>());
}};
check_cv(*f_idx, hinge_sgd, 0.93);
one_vs_all perceptron{f_idx, [&](class_label positive)
{
return make_unique<sgd>("sgd-model-test", f_idx, positive,
class_label{"negative"}, make_unique<loss::perceptron>());
}};
check_cv(*f_idx, perceptron, 0.89);
});
num_failed += testing::run_test("sgd-split-" + type, [&]()
{
one_vs_all hinge_sgd{f_idx, [&](class_label positive)
{
return make_unique<sgd>("sgd-model-test", f_idx, positive,
class_label{"negative"}, make_unique<loss::hinge>());
}};
check_split(*f_idx, hinge_sgd, 0.89);
one_vs_all perceptron{f_idx, [&](class_label positive)
{
return make_unique<sgd>("sgd-model-test", f_idx, positive,
class_label{"negative"}, make_unique<loss::perceptron>());
}};
check_split(*f_idx, perceptron, 0.85);
});
num_failed += testing::run_test("log-reg-cv-" + type, [&]()
{
logistic_regression logreg{"logreg-model-test", f_idx};
check_cv(*f_idx, logreg, 0.92);
});
num_failed += testing::run_test("log-reg-split-" + type, [&]()
{
logistic_regression logreg{"logreg-model-test", f_idx};
check_split(*f_idx, logreg, 0.87);
});
num_failed += testing::run_test("winnow-cv-" + type, [&]()
{
winnow win{f_idx};
check_cv(*f_idx, win, 0.80);
});
num_failed += testing::run_test("winnow-split-" + type, [&]()
{
winnow win{f_idx};
// this is *really* low... is winnow broken?
check_split(*f_idx, win, 0.65);
});
num_failed += testing::run_test("svm-wrapper-" + type, [&]()
{
auto config = cpptoml::parse_file("test-config.toml");
auto mod_path = config.get_as<std::string>("libsvm-modules");
if (!mod_path)
throw std::runtime_error{"no path for libsvm-modules"};
svm_wrapper svm{f_idx, *mod_path};
check_cv(*f_idx, svm, .80);
});
system("rm -rf ceeaus-*");
return num_failed;
}
int classifier_tests()
{
int num_failed = 0;
system("rm -rf ceeaus-*");
create_config("file");
num_failed += run_tests("file");
create_config("line");
num_failed += run_tests("line");
return num_failed;
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/jingle_glue/xmpp_signal_strategy.h"
#include "base/logging.h"
#include "jingle/notifier/base/gaia_token_pre_xmpp_auth.h"
#include "remoting/jingle_glue/jingle_thread.h"
#include "remoting/jingle_glue/xmpp_socket_adapter.h"
#include "third_party/libjingle/source/talk/base/asyncsocket.h"
#include "third_party/libjingle/source/talk/xmpp/prexmppauth.h"
#include "third_party/libjingle/source/talk/xmpp/saslcookiemechanism.h"
namespace {
const char kDefaultResourceName[] = "chromoting";
} // namespace
namespace remoting {
XmppSignalStrategy::XmppSignalStrategy(JingleThread* jingle_thread,
const std::string& username,
const std::string& auth_token,
const std::string& auth_token_service)
: thread_(jingle_thread),
username_(username),
auth_token_(auth_token),
auth_token_service_(auth_token_service),
resource_name_(kDefaultResourceName),
xmpp_client_(NULL),
state_(DISCONNECTED) {
}
XmppSignalStrategy::~XmppSignalStrategy() {
DCHECK_EQ(listeners_.size(), 0U);
Disconnect();
}
void XmppSignalStrategy::Connect() {
DCHECK(CalledOnValidThread());
// Disconnect first if we are currently connected.
Disconnect();
buzz::XmppClientSettings settings;
buzz::Jid login_jid(username_);
settings.set_user(login_jid.node());
settings.set_host(login_jid.domain());
settings.set_resource(resource_name_);
settings.set_use_tls(buzz::TLS_ENABLED);
settings.set_token_service(auth_token_service_);
settings.set_auth_cookie(auth_token_);
settings.set_server(talk_base::SocketAddress("talk.google.com", 5222));
buzz::AsyncSocket* socket = new XmppSocketAdapter(settings, false);
xmpp_client_ = new buzz::XmppClient(thread_->task_pump());
xmpp_client_->Connect(settings, "", socket, CreatePreXmppAuth(settings));
xmpp_client_->SignalStateChange.connect(
this, &XmppSignalStrategy::OnConnectionStateChanged);
xmpp_client_->engine()->AddStanzaHandler(this, buzz::XmppEngine::HL_TYPE);
xmpp_client_->Start();
SetState(CONNECTING);
}
void XmppSignalStrategy::Disconnect() {
DCHECK(CalledOnValidThread());
if (xmpp_client_) {
xmpp_client_->engine()->RemoveStanzaHandler(this);
xmpp_client_->Disconnect();
// |xmpp_client_| should be set to NULL in OnConnectionStateChanged()
// in response to Disconnect() call above.
DCHECK(xmpp_client_ == NULL);
}
}
SignalStrategy::State XmppSignalStrategy::GetState() const {
DCHECK(CalledOnValidThread());
return state_;
}
std::string XmppSignalStrategy::GetLocalJid() const {
DCHECK(CalledOnValidThread());
return xmpp_client_->jid().Str();
}
void XmppSignalStrategy::AddListener(Listener* listener) {
DCHECK(CalledOnValidThread());
listeners_.AddObserver(listener);
}
void XmppSignalStrategy::RemoveListener(Listener* listener) {
DCHECK(CalledOnValidThread());
listeners_.RemoveObserver(listener);
}
bool XmppSignalStrategy::SendStanza(buzz::XmlElement* stanza) {
DCHECK(CalledOnValidThread());
if (!xmpp_client_) {
LOG(INFO) << "Dropping signalling message because XMPP "
"connection has been terminated.";
delete stanza;
return false;
}
buzz::XmppReturnStatus status = xmpp_client_->SendStanza(stanza);
return status == buzz::XMPP_RETURN_OK || status == buzz::XMPP_RETURN_PENDING;
}
std::string XmppSignalStrategy::GetNextId() {
DCHECK(CalledOnValidThread());
if (!xmpp_client_) {
// If the connection has been terminated then it doesn't matter
// what Id we return.
return "";
}
return xmpp_client_->NextId();
}
bool XmppSignalStrategy::HandleStanza(const buzz::XmlElement* stanza) {
DCHECK(CalledOnValidThread());
ObserverListBase<Listener>::Iterator it(listeners_);
Listener* listener;
while ((listener = it.GetNext()) != NULL) {
if (listener->OnSignalStrategyIncomingStanza(stanza))
return true;
}
return false;
}
void XmppSignalStrategy::SetAuthInfo(const std::string& username,
const std::string& auth_token,
const std::string& auth_token_service) {
DCHECK(CalledOnValidThread());
username_ = username;
auth_token_ = auth_token;
auth_token_service_ = auth_token_service;
}
void XmppSignalStrategy::SetResourceName(const std::string &resource_name) {
DCHECK(CalledOnValidThread());
resource_name_ = resource_name;
}
void XmppSignalStrategy::OnConnectionStateChanged(
buzz::XmppEngine::State state) {
DCHECK(CalledOnValidThread());
if (state == buzz::XmppEngine::STATE_OPEN) {
SetState(CONNECTED);
} else if (state == buzz::XmppEngine::STATE_CLOSED) {
// Client is destroyed by the TaskRunner after the client is
// closed. Reset the pointer so we don't try to use it later.
xmpp_client_ = NULL;
SetState(DISCONNECTED);
}
}
void XmppSignalStrategy::SetState(State new_state) {
if (state_ != new_state) {
state_ = new_state;
FOR_EACH_OBSERVER(Listener, listeners_,
OnSignalStrategyStateChange(new_state));
}
}
// static
buzz::PreXmppAuth* XmppSignalStrategy::CreatePreXmppAuth(
const buzz::XmppClientSettings& settings) {
buzz::Jid jid(settings.user(), settings.host(), buzz::STR_EMPTY);
std::string mechanism = notifier::GaiaTokenPreXmppAuth::kDefaultAuthMechanism;
if (settings.token_service() == "oauth2") {
mechanism = "X-OAUTH2";
}
return new notifier::GaiaTokenPreXmppAuth(
jid.Str(), settings.auth_cookie(), settings.token_service(), mechanism);
}
} // namespace remoting
<commit_msg>Dump Xmpp connection error code to the log to facilitate debugging.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/jingle_glue/xmpp_signal_strategy.h"
#include "base/logging.h"
#include "jingle/notifier/base/gaia_token_pre_xmpp_auth.h"
#include "remoting/jingle_glue/jingle_thread.h"
#include "remoting/jingle_glue/xmpp_socket_adapter.h"
#include "third_party/libjingle/source/talk/base/asyncsocket.h"
#include "third_party/libjingle/source/talk/xmpp/prexmppauth.h"
#include "third_party/libjingle/source/talk/xmpp/saslcookiemechanism.h"
namespace {
const char kDefaultResourceName[] = "chromoting";
} // namespace
namespace remoting {
XmppSignalStrategy::XmppSignalStrategy(JingleThread* jingle_thread,
const std::string& username,
const std::string& auth_token,
const std::string& auth_token_service)
: thread_(jingle_thread),
username_(username),
auth_token_(auth_token),
auth_token_service_(auth_token_service),
resource_name_(kDefaultResourceName),
xmpp_client_(NULL),
state_(DISCONNECTED) {
}
XmppSignalStrategy::~XmppSignalStrategy() {
DCHECK_EQ(listeners_.size(), 0U);
Disconnect();
}
void XmppSignalStrategy::Connect() {
DCHECK(CalledOnValidThread());
// Disconnect first if we are currently connected.
Disconnect();
buzz::XmppClientSettings settings;
buzz::Jid login_jid(username_);
settings.set_user(login_jid.node());
settings.set_host(login_jid.domain());
settings.set_resource(resource_name_);
settings.set_use_tls(buzz::TLS_ENABLED);
settings.set_token_service(auth_token_service_);
settings.set_auth_cookie(auth_token_);
settings.set_server(talk_base::SocketAddress("talk.google.com", 5222));
buzz::AsyncSocket* socket = new XmppSocketAdapter(settings, false);
xmpp_client_ = new buzz::XmppClient(thread_->task_pump());
xmpp_client_->Connect(settings, "", socket, CreatePreXmppAuth(settings));
xmpp_client_->SignalStateChange.connect(
this, &XmppSignalStrategy::OnConnectionStateChanged);
xmpp_client_->engine()->AddStanzaHandler(this, buzz::XmppEngine::HL_TYPE);
xmpp_client_->Start();
SetState(CONNECTING);
}
void XmppSignalStrategy::Disconnect() {
DCHECK(CalledOnValidThread());
if (xmpp_client_) {
xmpp_client_->engine()->RemoveStanzaHandler(this);
xmpp_client_->Disconnect();
// |xmpp_client_| should be set to NULL in OnConnectionStateChanged()
// in response to Disconnect() call above.
DCHECK(xmpp_client_ == NULL);
}
}
SignalStrategy::State XmppSignalStrategy::GetState() const {
DCHECK(CalledOnValidThread());
return state_;
}
std::string XmppSignalStrategy::GetLocalJid() const {
DCHECK(CalledOnValidThread());
return xmpp_client_->jid().Str();
}
void XmppSignalStrategy::AddListener(Listener* listener) {
DCHECK(CalledOnValidThread());
listeners_.AddObserver(listener);
}
void XmppSignalStrategy::RemoveListener(Listener* listener) {
DCHECK(CalledOnValidThread());
listeners_.RemoveObserver(listener);
}
bool XmppSignalStrategy::SendStanza(buzz::XmlElement* stanza) {
DCHECK(CalledOnValidThread());
if (!xmpp_client_) {
LOG(INFO) << "Dropping signalling message because XMPP "
"connection has been terminated.";
delete stanza;
return false;
}
buzz::XmppReturnStatus status = xmpp_client_->SendStanza(stanza);
return status == buzz::XMPP_RETURN_OK || status == buzz::XMPP_RETURN_PENDING;
}
std::string XmppSignalStrategy::GetNextId() {
DCHECK(CalledOnValidThread());
if (!xmpp_client_) {
// If the connection has been terminated then it doesn't matter
// what Id we return.
return "";
}
return xmpp_client_->NextId();
}
bool XmppSignalStrategy::HandleStanza(const buzz::XmlElement* stanza) {
DCHECK(CalledOnValidThread());
ObserverListBase<Listener>::Iterator it(listeners_);
Listener* listener;
while ((listener = it.GetNext()) != NULL) {
if (listener->OnSignalStrategyIncomingStanza(stanza))
return true;
}
return false;
}
void XmppSignalStrategy::SetAuthInfo(const std::string& username,
const std::string& auth_token,
const std::string& auth_token_service) {
DCHECK(CalledOnValidThread());
username_ = username;
auth_token_ = auth_token;
auth_token_service_ = auth_token_service;
}
void XmppSignalStrategy::SetResourceName(const std::string &resource_name) {
DCHECK(CalledOnValidThread());
resource_name_ = resource_name;
}
void XmppSignalStrategy::OnConnectionStateChanged(
buzz::XmppEngine::State state) {
DCHECK(CalledOnValidThread());
if (state == buzz::XmppEngine::STATE_OPEN) {
SetState(CONNECTED);
} else if (state == buzz::XmppEngine::STATE_CLOSED) {
// Make sure we dump errors to the log.
int subcode;
buzz::XmppEngine::Error error = xmpp_client_->GetError(&subcode);
LOG(INFO) << "XMPP connection was closed: error=" << error
<< ", subcode=" << subcode;
// Client is destroyed by the TaskRunner after the client is
// closed. Reset the pointer so we don't try to use it later.
xmpp_client_ = NULL;
SetState(DISCONNECTED);
}
}
void XmppSignalStrategy::SetState(State new_state) {
if (state_ != new_state) {
state_ = new_state;
FOR_EACH_OBSERVER(Listener, listeners_,
OnSignalStrategyStateChange(new_state));
}
}
// static
buzz::PreXmppAuth* XmppSignalStrategy::CreatePreXmppAuth(
const buzz::XmppClientSettings& settings) {
buzz::Jid jid(settings.user(), settings.host(), buzz::STR_EMPTY);
std::string mechanism = notifier::GaiaTokenPreXmppAuth::kDefaultAuthMechanism;
if (settings.token_service() == "oauth2") {
mechanism = "X-OAUTH2";
}
return new notifier::GaiaTokenPreXmppAuth(
jid.Str(), settings.auth_cookie(), settings.token_service(), mechanism);
}
} // namespace remoting
<|endoftext|> |
<commit_before>/*
* xmpp_features.cpp - XMPP entity features
* Copyright (C) 2003 Justin Karneges
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <https://www.gnu.org/licenses/>.
*
*/
#include <QCoreApplication>
#include <QString>
#include <QMap>
#include <QStringList>
#include "xmpp_features.h"
#include "jingle.h"
#include "jingle-ft.h"
using namespace XMPP;
Features::Features()
{
}
Features::Features(const QStringList &l)
{
setList(l);
}
Features::Features(const QSet<QString> &s)
{
setList(s);
}
Features::Features(const QString &str)
{
QSet<QString> l;
l << str;
setList(l);
}
Features::~Features()
{
}
QStringList Features::list() const
{
return _list.toList();
}
void Features::setList(const QStringList &l)
{
_list = QSet<QString>::fromList(l);
}
void Features::setList(const QSet<QString> &l)
{
_list = l;
}
void Features::addFeature(const QString& s)
{
_list += s;
}
bool Features::test(const QStringList &ns) const
{
return _list.contains(QSet<QString>::fromList(ns));
}
bool Features::test(const QSet<QString> &ns) const
{
return _list.contains(ns);
}
#define FID_MULTICAST "http://jabber.org/protocol/address"
bool Features::hasMulticast() const
{
QSet<QString> ns;
ns << FID_MULTICAST;
return test(ns);
}
#define FID_AHCOMMAND "http://jabber.org/protocol/commands"
bool Features::hasCommand() const
{
QSet<QString> ns;
ns << FID_AHCOMMAND;
return test(ns);
}
#define FID_REGISTER "jabber:iq:register"
bool Features::hasRegister() const
{
QSet<QString> ns;
ns << FID_REGISTER;
return test(ns);
}
#define FID_SEARCH "jabber:iq:search"
bool Features::hasSearch() const
{
QSet<QString> ns;
ns << FID_SEARCH;
return test(ns);
}
#define FID_GROUPCHAT "http://jabber.org/protocol/muc"
bool Features::hasGroupchat() const
{
QSet<QString> ns;
ns << FID_GROUPCHAT;
return test(ns);
}
#define FID_VOICE "http://www.google.com/xmpp/protocol/voice/v1"
bool Features::hasVoice() const
{
QSet<QString> ns;
ns << FID_VOICE;
return test(ns);
}
#define FID_GATEWAY "jabber:iq:gateway"
bool Features::hasGateway() const
{
QSet<QString> ns;
ns << FID_GATEWAY;
return test(ns);
}
#define FID_QUERYVERSION "jabber:iq:version"
bool Features::hasVersion() const
{
QSet<QString> ns;
ns << FID_QUERYVERSION;
return test(ns);
}
#define FID_DISCO "http://jabber.org/protocol/disco"
bool Features::hasDisco() const
{
QSet<QString> ns;
ns << FID_DISCO;
ns << "http://jabber.org/protocol/disco#info";
ns << "http://jabber.org/protocol/disco#items";
return test(ns);
}
#define FID_CHATSTATE "http://jabber.org/protocol/chatstates"
bool Features::hasChatState() const
{
QSet<QString> ns;
ns << FID_CHATSTATE;
return test(ns);
}
#define FID_VCARD "vcard-temp"
bool Features::hasVCard() const
{
QSet<QString> ns;
ns << FID_VCARD;
return test(ns);
}
#define FID_MESSAGECARBONS "urn:xmpp:carbons:2"
bool Features::hasMessageCarbons() const
{
QStringList ns;
ns << FID_MESSAGECARBONS;
return test(ns);
}
bool Features::hasJingleFT() const
{
QStringList ns;
ns << Jingle::FileTransfer::NS;
return test(ns);
}
// custom Psi actions
#define FID_ADD "psi:add"
class Features::FeatureName : public QObject
{
Q_OBJECT
public:
FeatureName()
: QObject(QCoreApplication::instance())
{
id2s[FID_Invalid] = tr("ERROR: Incorrect usage of Features class");
id2s[FID_None] = tr("None");
id2s[FID_Register] = tr("Register");
id2s[FID_Search] = tr("Search");
id2s[FID_Groupchat] = tr("Groupchat");
id2s[FID_Gateway] = tr("Gateway");
id2s[FID_Disco] = tr("Service Discovery");
id2s[FID_VCard] = tr("VCard");
id2s[FID_AHCommand] = tr("Execute command");
id2s[FID_QueryVersion] = tr("Query version");
id2s[FID_MessageCarbons]= tr("Message Carbons");
// custom Psi actions
id2s[FID_Add] = tr("Add to roster");
// compute reverse map
//QMap<QString, long>::Iterator it = id2s.begin();
//for ( ; it != id2s.end(); ++it)
// s2id[it.data()] = it.key();
id2f[FID_Register] = FID_REGISTER;
id2f[FID_Search] = FID_SEARCH;
id2f[FID_Groupchat] = FID_GROUPCHAT;
id2f[FID_Gateway] = FID_GATEWAY;
id2f[FID_Disco] = FID_DISCO;
id2f[FID_VCard] = FID_VCARD;
id2f[FID_AHCommand] = FID_AHCOMMAND;
id2f[FID_QueryVersion] = FID_QUERYVERSION;
id2f[FID_MessageCarbons]= FID_MESSAGECARBONS;
// custom Psi actions
id2f[FID_Add] = FID_ADD;
}
//QMap<QString, long> s2id;
QMap<long, QString> id2s;
QMap<long, QString> id2f;
};
static Features::FeatureName *featureName = nullptr;
long Features::id() const
{
if ( _list.count() > 1 )
return FID_Invalid;
else if ( hasRegister() )
return FID_Register;
else if ( hasSearch() )
return FID_Search;
else if ( hasGroupchat() )
return FID_Groupchat;
else if ( hasGateway() )
return FID_Gateway;
else if ( hasDisco() )
return FID_Disco;
else if ( hasVCard() )
return FID_VCard;
else if ( hasCommand() )
return FID_AHCommand;
else if ( test(QStringList(FID_ADD)) )
return FID_Add;
else if ( hasVersion() )
return FID_QueryVersion;
return FID_None;
}
long Features::id(const QString &feature)
{
Features f(feature);
return f.id();
}
QString Features::feature(long id)
{
if ( !featureName )
featureName = new FeatureName();
return featureName->id2f[id];
}
Features &Features::operator<<(const QString &feature)
{
_list << feature;
return *this;
}
QString Features::name(long id)
{
if ( !featureName )
featureName = new FeatureName();
return featureName->id2s[id];
}
QString Features::name() const
{
return name(id());
}
QString Features::name(const QString &feature)
{
Features f(feature);
return f.name(f.id());
}
#include "xmpp_features.moc"
<commit_msg>minor formatting fix<commit_after>/*
* xmpp_features.cpp - XMPP entity features
* Copyright (C) 2003 Justin Karneges
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <https://www.gnu.org/licenses/>.
*
*/
#include <QCoreApplication>
#include <QString>
#include <QMap>
#include <QStringList>
#include "xmpp_features.h"
#include "jingle.h"
#include "jingle-ft.h"
using namespace XMPP;
Features::Features()
{
}
Features::Features(const QStringList &l)
{
setList(l);
}
Features::Features(const QSet<QString> &s)
{
setList(s);
}
Features::Features(const QString &str)
{
QSet<QString> l;
l << str;
setList(l);
}
Features::~Features()
{
}
QStringList Features::list() const
{
return _list.toList();
}
void Features::setList(const QStringList &l)
{
_list = QSet<QString>::fromList(l);
}
void Features::setList(const QSet<QString> &l)
{
_list = l;
}
void Features::addFeature(const QString& s)
{
_list += s;
}
bool Features::test(const QStringList &ns) const
{
return _list.contains(QSet<QString>::fromList(ns));
}
bool Features::test(const QSet<QString> &ns) const
{
return _list.contains(ns);
}
#define FID_MULTICAST "http://jabber.org/protocol/address"
bool Features::hasMulticast() const
{
QSet<QString> ns;
ns << FID_MULTICAST;
return test(ns);
}
#define FID_AHCOMMAND "http://jabber.org/protocol/commands"
bool Features::hasCommand() const
{
QSet<QString> ns;
ns << FID_AHCOMMAND;
return test(ns);
}
#define FID_REGISTER "jabber:iq:register"
bool Features::hasRegister() const
{
QSet<QString> ns;
ns << FID_REGISTER;
return test(ns);
}
#define FID_SEARCH "jabber:iq:search"
bool Features::hasSearch() const
{
QSet<QString> ns;
ns << FID_SEARCH;
return test(ns);
}
#define FID_GROUPCHAT "http://jabber.org/protocol/muc"
bool Features::hasGroupchat() const
{
QSet<QString> ns;
ns << FID_GROUPCHAT;
return test(ns);
}
#define FID_VOICE "http://www.google.com/xmpp/protocol/voice/v1"
bool Features::hasVoice() const
{
QSet<QString> ns;
ns << FID_VOICE;
return test(ns);
}
#define FID_GATEWAY "jabber:iq:gateway"
bool Features::hasGateway() const
{
QSet<QString> ns;
ns << FID_GATEWAY;
return test(ns);
}
#define FID_QUERYVERSION "jabber:iq:version"
bool Features::hasVersion() const
{
QSet<QString> ns;
ns << FID_QUERYVERSION;
return test(ns);
}
#define FID_DISCO "http://jabber.org/protocol/disco"
bool Features::hasDisco() const
{
QSet<QString> ns;
ns << FID_DISCO;
ns << "http://jabber.org/protocol/disco#info";
ns << "http://jabber.org/protocol/disco#items";
return test(ns);
}
#define FID_CHATSTATE "http://jabber.org/protocol/chatstates"
bool Features::hasChatState() const
{
QSet<QString> ns;
ns << FID_CHATSTATE;
return test(ns);
}
#define FID_VCARD "vcard-temp"
bool Features::hasVCard() const
{
QSet<QString> ns;
ns << FID_VCARD;
return test(ns);
}
#define FID_MESSAGECARBONS "urn:xmpp:carbons:2"
bool Features::hasMessageCarbons() const
{
QStringList ns;
ns << FID_MESSAGECARBONS;
return test(ns);
}
bool Features::hasJingleFT() const
{
QStringList ns;
ns << Jingle::FileTransfer::NS;
return test(ns);
}
// custom Psi actions
#define FID_ADD "psi:add"
class Features::FeatureName : public QObject
{
Q_OBJECT
public:
FeatureName()
: QObject(QCoreApplication::instance())
{
id2s[FID_Invalid] = tr("ERROR: Incorrect usage of Features class");
id2s[FID_None] = tr("None");
id2s[FID_Register] = tr("Register");
id2s[FID_Search] = tr("Search");
id2s[FID_Groupchat] = tr("Groupchat");
id2s[FID_Gateway] = tr("Gateway");
id2s[FID_Disco] = tr("Service Discovery");
id2s[FID_VCard] = tr("VCard");
id2s[FID_AHCommand] = tr("Execute command");
id2s[FID_QueryVersion] = tr("Query version");
id2s[FID_MessageCarbons]= tr("Message Carbons");
// custom Psi actions
id2s[FID_Add] = tr("Add to roster");
// compute reverse map
//QMap<QString, long>::Iterator it = id2s.begin();
//for ( ; it != id2s.end(); ++it)
// s2id[it.data()] = it.key();
id2f[FID_Register] = FID_REGISTER;
id2f[FID_Search] = FID_SEARCH;
id2f[FID_Groupchat] = FID_GROUPCHAT;
id2f[FID_Gateway] = FID_GATEWAY;
id2f[FID_Disco] = FID_DISCO;
id2f[FID_VCard] = FID_VCARD;
id2f[FID_AHCommand] = FID_AHCOMMAND;
id2f[FID_QueryVersion] = FID_QUERYVERSION;
id2f[FID_MessageCarbons]= FID_MESSAGECARBONS;
// custom Psi actions
id2f[FID_Add] = FID_ADD;
}
//QMap<QString, long> s2id;
QMap<long, QString> id2s;
QMap<long, QString> id2f;
};
static Features::FeatureName *featureName = nullptr;
long Features::id() const
{
if ( _list.count() > 1 )
return FID_Invalid;
else if ( hasRegister() )
return FID_Register;
else if ( hasSearch() )
return FID_Search;
else if ( hasGroupchat() )
return FID_Groupchat;
else if ( hasGateway() )
return FID_Gateway;
else if ( hasDisco() )
return FID_Disco;
else if ( hasVCard() )
return FID_VCard;
else if ( hasCommand() )
return FID_AHCommand;
else if ( test(QStringList(FID_ADD)) )
return FID_Add;
else if ( hasVersion() )
return FID_QueryVersion;
return FID_None;
}
long Features::id(const QString &feature)
{
Features f(feature);
return f.id();
}
QString Features::feature(long id)
{
if ( !featureName )
featureName = new FeatureName();
return featureName->id2f[id];
}
Features &Features::operator<<(const QString &feature)
{
_list << feature;
return *this;
}
QString Features::name(long id)
{
if ( !featureName )
featureName = new FeatureName();
return featureName->id2s[id];
}
QString Features::name() const
{
return name(id());
}
QString Features::name(const QString &feature)
{
Features f(feature);
return f.name(f.id());
}
#include "xmpp_features.moc"
<|endoftext|> |
<commit_before>// This file is part of the "x0" project, http://xzero.io/
// (c) 2009-2014 Christian Parpart <trapni@gmail.com>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <xzero/http/http1/Connection.h>
#include <xzero/http/http1/Channel.h>
#include <xzero/http/HttpDateGenerator.h>
#include <xzero/http/HttpResponseInfo.h>
#include <xzero/http/HttpResponse.h>
#include <xzero/http/HttpRequest.h>
#include <xzero/http/BadMessage.h>
#include <xzero/net/Connection.h>
#include <xzero/net/EndPoint.h>
#include <xzero/net/EndPointWriter.h>
#include <xzero/executor/Executor.h>
#include <xzero/logging.h>
#include <xzero/RuntimeError.h>
#include <xzero/StringUtil.h>
#include <xzero/sysconfig.h>
#include <cassert>
#include <cstdlib>
namespace xzero {
namespace http {
namespace http1 {
#define ERROR(msg...) logError("http.http1.Connection", msg)
#ifndef NDEBUG
#define TRACE(msg...) logTrace("http.http1.Connection", msg)
#else
#define TRACE(msg...) do {} while (0)
#endif
Connection::Connection(EndPoint* endpoint,
Executor* executor,
const HttpHandler& handler,
HttpDateGenerator* dateGenerator,
HttpOutputCompressor* outputCompressor,
size_t maxRequestUriLength,
size_t maxRequestBodyLength,
size_t maxRequestCount,
Duration maxKeepAlive,
bool corkStream)
: ::xzero::Connection(endpoint, executor),
channel_(new Channel(
this, executor, handler,
maxRequestUriLength, maxRequestBodyLength,
dateGenerator, outputCompressor)),
parser_(Parser::REQUEST, channel_.get()),
inputBuffer_(),
inputOffset_(0),
writer_(),
onComplete_(),
generator_(&writer_),
maxKeepAlive_(maxKeepAlive),
requestCount_(0),
requestMax_(maxRequestCount),
corkStream_(corkStream) {
channel_->request()->setRemoteAddress(endpoint->remoteAddress());
channel_->request()->setLocalAddress(endpoint->localAddress());
TRACE("$0 ctor", this);
}
Connection::~Connection() {
TRACE("$0 dtor", this);
}
void Connection::onOpen() {
TRACE("$0 onOpen", this);
::xzero::Connection::onOpen();
// TODO support TCP_DEFER_ACCEPT here
#if 0
if (connector()->deferAccept())
onFillable();
else
wantFill();
#else
wantFill();
#endif
}
void Connection::onClose() {
TRACE("$0 onClose", this);
::xzero::Connection::onClose();
}
void Connection::abort() {
TRACE("$0 abort()", this);
channel_->response()->setBytesTransmitted(generator_.bytesTransmitted());
channel_->responseEnd();
TRACE("$0 abort", this);
endpoint()->close();
}
void Connection::completed() {
TRACE("$0 completed", this);
if (channel_->request()->method() != HttpMethod::HEAD &&
!generator_.isChunked() &&
generator_.pendingContentLength() > 0)
RAISE(IllegalStateError, "Invalid State. Response not fully written but completed() invoked.");
setCompleter(std::bind(&Connection::onResponseComplete, this,
std::placeholders::_1));
generator_.generateTrailer(channel_->response()->trailers());
wantFlush();
}
void Connection::onResponseComplete(bool succeed) {
TRACE("$0 onResponseComplete($1)", this, succeed ? "succeed" : "failure");
channel_->response()->setBytesTransmitted(generator_.bytesTransmitted());
channel_->responseEnd();
if (!succeed) {
// writing trailer failed. do not attempt to do anything on the wire.
return;
}
if (channel_->isPersistent()) {
TRACE("$0 completed.onComplete", this);
// re-use on keep-alive
channel_->reset();
endpoint()->setCorking(false);
if (inputOffset_ < inputBuffer_.size()) {
// have some request pipelined
TRACE("$0 completed.onComplete: pipelined read", this);
executor()->execute(std::bind(&Connection::parseFragment, this));
} else {
// wait for next request
TRACE("$0 completed.onComplete: keep-alive read", this);
wantFill();
}
} else {
endpoint()->close();
}
}
void Connection::send(HttpResponseInfo&& responseInfo,
const BufferRef& chunk,
CompletionHandler onComplete) {
setCompleter(onComplete, responseInfo.status());
TRACE("$0 send(BufferRef, status=$1, persistent=$2, chunkSize=$2)",
this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no",
chunk.size());
patchResponseInfo(responseInfo);
if (corkStream_)
endpoint()->setCorking(true);
generator_.generateResponse(responseInfo, chunk);
wantFlush();
}
void Connection::send(HttpResponseInfo&& responseInfo,
Buffer&& chunk,
CompletionHandler onComplete) {
setCompleter(onComplete, responseInfo.status());
TRACE("$0 send(Buffer, status=$1, persistent=$2, chunkSize=$3)",
this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no",
chunk.size());
patchResponseInfo(responseInfo);
const bool corking_ = true; // TODO(TCP_CORK): part of HttpResponseInfo?
if (corking_)
endpoint()->setCorking(true);
generator_.generateResponse(responseInfo, std::move(chunk));
wantFlush();
}
void Connection::send(HttpResponseInfo&& responseInfo,
FileView&& chunk,
CompletionHandler onComplete) {
setCompleter(onComplete, responseInfo.status());
TRACE("$0 send(FileView, status=$1, persistent=$2, fd=$3, chunkSize=$4)",
this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no",
chunk.handle(), chunk.size());
patchResponseInfo(responseInfo);
const bool corking_ = true; // TODO(TCP_CORK): part of HttpResponseInfo?
if (corking_)
endpoint()->setCorking(true);
generator_.generateResponse(responseInfo, std::move(chunk));
wantFlush();
}
void Connection::setCompleter(CompletionHandler cb) {
if (cb && onComplete_)
RAISE(IllegalStateError, "There is still another completion hook.");
onComplete_ = std::move(cb);
}
void Connection::setCompleter(CompletionHandler onComplete, HttpStatus status) {
// make sure, that on ContinueRequest we do actually continue with
// the prior request
if (status != HttpStatus::ContinueRequest) {
setCompleter(onComplete);
} else {
setCompleter([this, onComplete](bool s) {
wantFill();
if (onComplete) {
onComplete(s);
}
});
}
}
void Connection::invokeCompleter(bool success) {
if (onComplete_) {
TRACE("$0 invoking completion callback", this);
auto callback = std::move(onComplete_);
onComplete_ = nullptr;
callback(success);
}
}
void Connection::patchResponseInfo(HttpResponseInfo& responseInfo) {
if (static_cast<int>(responseInfo.status()) >= 200) {
// patch in HTTP transport-layer headers
if (channel_->isPersistent() && requestCount_ < requestMax_) {
++requestCount_;
char keepAlive[64];
snprintf(keepAlive, sizeof(keepAlive), "timeout=%llu, max=%zu",
(unsigned long long) maxKeepAlive_.seconds(),
requestMax_ - requestCount_);
responseInfo.headers().push_back("Connection", "Keep-Alive");
responseInfo.headers().push_back("Keep-Alive", keepAlive);
} else {
channel_->setPersistent(false);
responseInfo.headers().push_back("Connection", "closed");
}
}
}
void Connection::send(Buffer&& chunk, CompletionHandler onComplete) {
setCompleter(onComplete);
TRACE("$0 send(Buffer, chunkSize=$1)", this, chunk.size());
generator_.generateBody(std::move(chunk));
wantFlush();
}
void Connection::send(const BufferRef& chunk,
CompletionHandler onComplete) {
setCompleter(onComplete);
TRACE("$0 send(BufferRef, chunkSize=$1)", this, chunk.size());
generator_.generateBody(chunk);
wantFlush();
}
void Connection::send(FileView&& chunk, CompletionHandler onComplete) {
setCompleter(onComplete);
TRACE("$0 send(FileView, chunkSize=$1)", this, chunk.size());
generator_.generateBody(std::move(chunk));
wantFlush();
}
void Connection::setInputBufferSize(size_t size) {
TRACE("$0 setInputBufferSize($1)", this, size);
inputBuffer_.reserve(size);
}
void Connection::onFillable() {
TRACE("$0 onFillable", this);
TRACE("$0 onFillable: calling fill()", this);
if (endpoint()->fill(&inputBuffer_) == 0) {
TRACE("$0 onFillable: fill() returned 0", this);
// RAISE("client EOF");
abort();
return;
}
parseFragment();
}
void Connection::parseFragment() {
try {
TRACE("parseFragment: calling parseFragment ($0 into $1)",
inputOffset_, inputBuffer_.size());
size_t n = parser_.parseFragment(inputBuffer_.ref(inputOffset_));
TRACE("parseFragment: called ($0 into $1) => $2 ($3)",
inputOffset_, inputBuffer_.size(), n,
parser_.state());
inputOffset_ += n;
// on a partial read we must make sure that we wait for more input
if (parser_.state() != Parser::MESSAGE_BEGIN) {
wantFill();
}
} catch (const BadMessage& e) {
TRACE("$0 parseFragment: BadMessage caught (while in state $1). $2",
this, to_string(channel_->state()), e.what());
if (channel_->response()->version() == HttpVersion::UNKNOWN)
channel_->response()->setVersion(HttpVersion::VERSION_0_9);
if (channel_->state() == HttpChannelState::READING)
channel_->setState(HttpChannelState::HANDLING);
channel_->response()->sendError(e.httpCode(), e.what());
}
}
void Connection::onFlushable() {
TRACE("$0 onFlushable", this);
if (channel_->state() != HttpChannelState::SENDING)
channel_->setState(HttpChannelState::SENDING);
const bool complete = writer_.flush(endpoint());
if (complete) {
TRACE("$0 onFlushable: completed. ($1)",
this,
(onComplete_ ? "onComplete cb set" : "onComplete cb not set"));
channel_->setState(HttpChannelState::HANDLING);
invokeCompleter(true);
} else {
// continue flushing as we still have data pending
wantFlush();
}
}
void Connection::onInterestFailure(const std::exception& error) {
TRACE("$0 onInterestFailure($1): $2",
this, typeid(error).name(), error.what());
// TODO: improve logging here, as this eats our exception here.
// e.g. via (factory or connector)->error(error);
logError("Connection", error, "Unhandled exception caught in I/O loop");
invokeCompleter(false);
abort();
}
} // namespace http1
} // namespace http
template <>
std::string StringUtil::toString(http::http1::Connection* c) {
return StringUtil::format("$0:$1", c->endpoint()->remoteAddress());
}
} // namespace xzero
<commit_msg>http1::Connection: display-bug fix in StringUtil::toString overload<commit_after>// This file is part of the "x0" project, http://xzero.io/
// (c) 2009-2014 Christian Parpart <trapni@gmail.com>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <xzero/http/http1/Connection.h>
#include <xzero/http/http1/Channel.h>
#include <xzero/http/HttpDateGenerator.h>
#include <xzero/http/HttpResponseInfo.h>
#include <xzero/http/HttpResponse.h>
#include <xzero/http/HttpRequest.h>
#include <xzero/http/BadMessage.h>
#include <xzero/net/Connection.h>
#include <xzero/net/EndPoint.h>
#include <xzero/net/EndPointWriter.h>
#include <xzero/executor/Executor.h>
#include <xzero/logging.h>
#include <xzero/RuntimeError.h>
#include <xzero/StringUtil.h>
#include <xzero/sysconfig.h>
#include <cassert>
#include <cstdlib>
namespace xzero {
namespace http {
namespace http1 {
#define ERROR(msg...) logError("http.http1.Connection", msg)
#ifndef NDEBUG
#define TRACE(msg...) logTrace("http.http1.Connection", msg)
#else
#define TRACE(msg...) do {} while (0)
#endif
Connection::Connection(EndPoint* endpoint,
Executor* executor,
const HttpHandler& handler,
HttpDateGenerator* dateGenerator,
HttpOutputCompressor* outputCompressor,
size_t maxRequestUriLength,
size_t maxRequestBodyLength,
size_t maxRequestCount,
Duration maxKeepAlive,
bool corkStream)
: ::xzero::Connection(endpoint, executor),
channel_(new Channel(
this, executor, handler,
maxRequestUriLength, maxRequestBodyLength,
dateGenerator, outputCompressor)),
parser_(Parser::REQUEST, channel_.get()),
inputBuffer_(),
inputOffset_(0),
writer_(),
onComplete_(),
generator_(&writer_),
maxKeepAlive_(maxKeepAlive),
requestCount_(0),
requestMax_(maxRequestCount),
corkStream_(corkStream) {
channel_->request()->setRemoteAddress(endpoint->remoteAddress());
channel_->request()->setLocalAddress(endpoint->localAddress());
TRACE("$0 ctor", this);
}
Connection::~Connection() {
TRACE("$0 dtor", this);
}
void Connection::onOpen() {
TRACE("$0 onOpen", this);
::xzero::Connection::onOpen();
// TODO support TCP_DEFER_ACCEPT here
#if 0
if (connector()->deferAccept())
onFillable();
else
wantFill();
#else
wantFill();
#endif
}
void Connection::onClose() {
TRACE("$0 onClose", this);
::xzero::Connection::onClose();
}
void Connection::abort() {
TRACE("$0 abort()", this);
channel_->response()->setBytesTransmitted(generator_.bytesTransmitted());
channel_->responseEnd();
TRACE("$0 abort", this);
endpoint()->close();
}
void Connection::completed() {
TRACE("$0 completed", this);
if (channel_->request()->method() != HttpMethod::HEAD &&
!generator_.isChunked() &&
generator_.pendingContentLength() > 0)
RAISE(IllegalStateError, "Invalid State. Response not fully written but completed() invoked.");
setCompleter(std::bind(&Connection::onResponseComplete, this,
std::placeholders::_1));
generator_.generateTrailer(channel_->response()->trailers());
wantFlush();
}
void Connection::onResponseComplete(bool succeed) {
TRACE("$0 onResponseComplete($1)", this, succeed ? "succeed" : "failure");
channel_->response()->setBytesTransmitted(generator_.bytesTransmitted());
channel_->responseEnd();
if (!succeed) {
// writing trailer failed. do not attempt to do anything on the wire.
return;
}
if (channel_->isPersistent()) {
TRACE("$0 completed.onComplete", this);
// re-use on keep-alive
channel_->reset();
endpoint()->setCorking(false);
if (inputOffset_ < inputBuffer_.size()) {
// have some request pipelined
TRACE("$0 completed.onComplete: pipelined read", this);
executor()->execute(std::bind(&Connection::parseFragment, this));
} else {
// wait for next request
TRACE("$0 completed.onComplete: keep-alive read", this);
wantFill();
}
} else {
endpoint()->close();
}
}
void Connection::send(HttpResponseInfo&& responseInfo,
const BufferRef& chunk,
CompletionHandler onComplete) {
setCompleter(onComplete, responseInfo.status());
TRACE("$0 send(BufferRef, status=$1, persistent=$2, chunkSize=$2)",
this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no",
chunk.size());
patchResponseInfo(responseInfo);
if (corkStream_)
endpoint()->setCorking(true);
generator_.generateResponse(responseInfo, chunk);
wantFlush();
}
void Connection::send(HttpResponseInfo&& responseInfo,
Buffer&& chunk,
CompletionHandler onComplete) {
setCompleter(onComplete, responseInfo.status());
TRACE("$0 send(Buffer, status=$1, persistent=$2, chunkSize=$3)",
this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no",
chunk.size());
patchResponseInfo(responseInfo);
const bool corking_ = true; // TODO(TCP_CORK): part of HttpResponseInfo?
if (corking_)
endpoint()->setCorking(true);
generator_.generateResponse(responseInfo, std::move(chunk));
wantFlush();
}
void Connection::send(HttpResponseInfo&& responseInfo,
FileView&& chunk,
CompletionHandler onComplete) {
setCompleter(onComplete, responseInfo.status());
TRACE("$0 send(FileView, status=$1, persistent=$2, fd=$3, chunkSize=$4)",
this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no",
chunk.handle(), chunk.size());
patchResponseInfo(responseInfo);
const bool corking_ = true; // TODO(TCP_CORK): part of HttpResponseInfo?
if (corking_)
endpoint()->setCorking(true);
generator_.generateResponse(responseInfo, std::move(chunk));
wantFlush();
}
void Connection::setCompleter(CompletionHandler cb) {
if (cb && onComplete_)
RAISE(IllegalStateError, "There is still another completion hook.");
onComplete_ = std::move(cb);
}
void Connection::setCompleter(CompletionHandler onComplete, HttpStatus status) {
// make sure, that on ContinueRequest we do actually continue with
// the prior request
if (status != HttpStatus::ContinueRequest) {
setCompleter(onComplete);
} else {
setCompleter([this, onComplete](bool s) {
wantFill();
if (onComplete) {
onComplete(s);
}
});
}
}
void Connection::invokeCompleter(bool success) {
if (onComplete_) {
TRACE("$0 invoking completion callback", this);
auto callback = std::move(onComplete_);
onComplete_ = nullptr;
callback(success);
}
}
void Connection::patchResponseInfo(HttpResponseInfo& responseInfo) {
if (static_cast<int>(responseInfo.status()) >= 200) {
// patch in HTTP transport-layer headers
if (channel_->isPersistent() && requestCount_ < requestMax_) {
++requestCount_;
char keepAlive[64];
snprintf(keepAlive, sizeof(keepAlive), "timeout=%llu, max=%zu",
(unsigned long long) maxKeepAlive_.seconds(),
requestMax_ - requestCount_);
responseInfo.headers().push_back("Connection", "Keep-Alive");
responseInfo.headers().push_back("Keep-Alive", keepAlive);
} else {
channel_->setPersistent(false);
responseInfo.headers().push_back("Connection", "closed");
}
}
}
void Connection::send(Buffer&& chunk, CompletionHandler onComplete) {
setCompleter(onComplete);
TRACE("$0 send(Buffer, chunkSize=$1)", this, chunk.size());
generator_.generateBody(std::move(chunk));
wantFlush();
}
void Connection::send(const BufferRef& chunk,
CompletionHandler onComplete) {
setCompleter(onComplete);
TRACE("$0 send(BufferRef, chunkSize=$1)", this, chunk.size());
generator_.generateBody(chunk);
wantFlush();
}
void Connection::send(FileView&& chunk, CompletionHandler onComplete) {
setCompleter(onComplete);
TRACE("$0 send(FileView, chunkSize=$1)", this, chunk.size());
generator_.generateBody(std::move(chunk));
wantFlush();
}
void Connection::setInputBufferSize(size_t size) {
TRACE("$0 setInputBufferSize($1)", this, size);
inputBuffer_.reserve(size);
}
void Connection::onFillable() {
TRACE("$0 onFillable", this);
TRACE("$0 onFillable: calling fill()", this);
if (endpoint()->fill(&inputBuffer_) == 0) {
TRACE("$0 onFillable: fill() returned 0", this);
// RAISE("client EOF");
abort();
return;
}
parseFragment();
}
void Connection::parseFragment() {
try {
TRACE("parseFragment: calling parseFragment ($0 into $1)",
inputOffset_, inputBuffer_.size());
size_t n = parser_.parseFragment(inputBuffer_.ref(inputOffset_));
TRACE("parseFragment: called ($0 into $1) => $2 ($3)",
inputOffset_, inputBuffer_.size(), n,
parser_.state());
inputOffset_ += n;
// on a partial read we must make sure that we wait for more input
if (parser_.state() != Parser::MESSAGE_BEGIN) {
wantFill();
}
} catch (const BadMessage& e) {
TRACE("$0 parseFragment: BadMessage caught (while in state $1). $2",
this, to_string(channel_->state()), e.what());
if (channel_->response()->version() == HttpVersion::UNKNOWN)
channel_->response()->setVersion(HttpVersion::VERSION_0_9);
if (channel_->state() == HttpChannelState::READING)
channel_->setState(HttpChannelState::HANDLING);
channel_->response()->sendError(e.httpCode(), e.what());
}
}
void Connection::onFlushable() {
TRACE("$0 onFlushable", this);
if (channel_->state() != HttpChannelState::SENDING)
channel_->setState(HttpChannelState::SENDING);
const bool complete = writer_.flush(endpoint());
if (complete) {
TRACE("$0 onFlushable: completed. ($1)",
this,
(onComplete_ ? "onComplete cb set" : "onComplete cb not set"));
channel_->setState(HttpChannelState::HANDLING);
invokeCompleter(true);
} else {
// continue flushing as we still have data pending
wantFlush();
}
}
void Connection::onInterestFailure(const std::exception& error) {
TRACE("$0 onInterestFailure($1): $2",
this, typeid(error).name(), error.what());
// TODO: improve logging here, as this eats our exception here.
// e.g. via (factory or connector)->error(error);
logError("Connection", error, "Unhandled exception caught in I/O loop");
invokeCompleter(false);
abort();
}
} // namespace http1
} // namespace http
template <>
std::string StringUtil::toString(http::http1::Connection* c) {
return StringUtil::format("$0", c->endpoint()->remoteAddress());
}
} // namespace xzero
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/singleton.h"
#include "net/base/ev_root_ca_metadata.h"
namespace net {
// Raw metadata.
struct EVMetadata {
// The SHA-1 fingerprint of the root CA certificate, used as a unique
// identifier for a root CA certificate.
X509Certificate::Fingerprint fingerprint;
// The EV policy OID of the root CA.
// Note: a root CA may have multiple EV policies. When that actually
// happens, we'll need to support that.
const char* policy_oid;
};
static const EVMetadata ev_root_ca_metadata[] = {
// COMODO Certification Authority
// https://secure.comodo.com/
{ { { 0x66, 0x31, 0xbf, 0x9e, 0xf7, 0x4f, 0x9e, 0xb6, 0xc9, 0xd5,
0xa6, 0x0c, 0xba, 0x6a, 0xbe, 0xd1, 0xf7, 0xbd, 0xef, 0x7b } },
"1.3.6.1.4.1.6449.1.2.1.5.1"
},
// DigiCert High Assurance EV Root CA
// https://www.digicert.com
{ { { 0x5f, 0xb7, 0xee, 0x06, 0x33, 0xe2, 0x59, 0xdb, 0xad, 0x0c,
0x4c, 0x9a, 0xe6, 0xd3, 0x8f, 0x1a, 0x61, 0xc7, 0xdc, 0x25 } },
"2.16.840.1.114412.2.1"
},
// Entrust.net Secure Server Certification Authority
// https://www.entrust.net/
{ { { 0x99, 0xa6, 0x9b, 0xe6, 0x1a, 0xfe, 0x88, 0x6b, 0x4d, 0x2b,
0x82, 0x00, 0x7c, 0xb8, 0x54, 0xfc, 0x31, 0x7e, 0x15, 0x39 } },
"2.16.840.1.114028.10.1.2"
},
// Entrust Root Certification Authority
// https://www.entrust.net/
{ { { 0xb3, 0x1e, 0xb1, 0xb7, 0x40, 0xe3, 0x6c, 0x84, 0x02, 0xda,
0xdc, 0x37, 0xd4, 0x4d, 0xf5, 0xd4, 0x67, 0x49, 0x52, 0xf9 } },
"2.16.840.1.114028.10.1.2"
},
// Equifax Secure Certificate Authority (GeoTrust)
// https://www.geotrust.com/
{ { { 0xd2, 0x32, 0x09, 0xad, 0x23, 0xd3, 0x14, 0x23, 0x21, 0x74,
0xe4, 0x0d, 0x7f, 0x9d, 0x62, 0x13, 0x97, 0x86, 0x63, 0x3a } },
"1.3.6.1.4.1.14370.1.6"
},
// GeoTrust Primary Certification Authority
// https://www.geotrust.com/
{ { { 0x32, 0x3c, 0x11, 0x8e, 0x1b, 0xf7, 0xb8, 0xb6, 0x52, 0x54,
0xe2, 0xe2, 0x10, 0x0d, 0xd6, 0x02, 0x90, 0x37, 0xf0, 0x96 } },
"1.3.6.1.4.1.14370.1.6"
},
// Go Daddy Class 2 Certification Authority
// https://www.godaddy.com/
{ { { 0x27, 0x96, 0xba, 0xe6, 0x3f, 0x18, 0x01, 0xe2, 0x77, 0x26,
0x1b, 0xa0, 0xd7, 0x77, 0x70, 0x02, 0x8f, 0x20, 0xee, 0xe4 } },
"2.16.840.1.114413.1.7.23.3"
},
// Network Solutions Certificate Authority
// https://www.networksolutions.com/website-packages/index.jsp
{ { { 0x74, 0xf8, 0xa3, 0xc3, 0xef, 0xe7, 0xb3, 0x90, 0x06, 0x4b,
0x83, 0x90, 0x3c, 0x21, 0x64, 0x60, 0x20, 0xe5, 0xdf, 0xce } },
"1.3.6.1.4.1.782.1.2.1.8.1"
},
// QuoVadis Root CA 2
// https://www.quovadis.bm/
{ { { 0xca, 0x3a, 0xfb, 0xcf, 0x12, 0x40, 0x36, 0x4b, 0x44, 0xb2,
0x16, 0x20, 0x88, 0x80, 0x48, 0x39, 0x19, 0x93, 0x7c, 0xf7 } },
"1.3.6.1.4.1.8024.0.2.100.1.2"
},
// SecureTrust CA, SecureTrust Corporation
// https://www.securetrust.com
// https://www.trustwave.com/
{ { { 0x87, 0x82, 0xc6, 0xc3, 0x04, 0x35, 0x3b, 0xcf, 0xd2, 0x96,
0x92, 0xd2, 0x59, 0x3e, 0x7d, 0x44, 0xd9, 0x34, 0xff, 0x11 } },
"2.16.840.1.114404.1.1.2.4.1"
},
// Secure Global CA, SecureTrust Corporation
{ { { 0x3a, 0x44, 0x73, 0x5a, 0xe5, 0x81, 0x90, 0x1f, 0x24, 0x86,
0x61, 0x46, 0x1e, 0x3b, 0x9c, 0xc4, 0x5f, 0xf5, 0x3a, 0x1b } },
"2.16.840.1.114404.1.1.2.4.1"
},
// Starfield Class 2 Certification Authority
// https://www.starfieldtech.com/
{ { { 0xad, 0x7e, 0x1c, 0x28, 0xb0, 0x64, 0xef, 0x8f, 0x60, 0x03,
0x40, 0x20, 0x14, 0xc3, 0xd0, 0xe3, 0x37, 0x0e, 0xb5, 0x8a } },
"2.16.840.1.114414.1.7.23.3"
},
// Thawte Premium Server CA
// https://www.thawte.com/
{ { { 0x62, 0x7f, 0x8d, 0x78, 0x27, 0x65, 0x63, 0x99, 0xd2, 0x7d,
0x7f, 0x90, 0x44, 0xc9, 0xfe, 0xb3, 0xf3, 0x3e, 0xfa, 0x9a } },
"2.16.840.1.113733.1.7.48.1"
},
// thawte Primary Root CA
// https://www.thawte.com/
{ { { 0x91, 0xc6, 0xd6, 0xee, 0x3e, 0x8a, 0xc8, 0x63, 0x84, 0xe5,
0x48, 0xc2, 0x99, 0x29, 0x5c, 0x75, 0x6c, 0x81, 0x7b, 0x81 } },
"2.16.840.1.113733.1.7.48.1"
},
// UTN - DATACorp SGC
{ { { 0x58, 0x11, 0x9f, 0x0e, 0x12, 0x82, 0x87, 0xea, 0x50, 0xfd,
0xd9, 0x87, 0x45, 0x6f, 0x4f, 0x78, 0xdc, 0xfa, 0xd6, 0xd4 } },
"1.3.6.1.4.1.6449.1.2.1.5.1"
},
// UTN-USERFirst-Hardware
{ { { 0x04, 0x83, 0xed, 0x33, 0x99, 0xac, 0x36, 0x08, 0x05, 0x87,
0x22, 0xed, 0xbc, 0x5e, 0x46, 0x00, 0xe3, 0xbe, 0xf9, 0xd7 } },
"1.3.6.1.4.1.6449.1.2.1.5.1"
},
// ValiCert Class 2 Policy Validation Authority
// TODO(wtc): bug 1165107: this CA has another policy OID
// "2.16.840.1.114414.1.7.23.3".
{ { { 0x31, 0x7a, 0x2a, 0xd0, 0x7f, 0x2b, 0x33, 0x5e, 0xf5, 0xa1,
0xc3, 0x4e, 0x4b, 0x57, 0xe8, 0xb7, 0xd8, 0xf1, 0xfc, 0xa6 } },
"2.16.840.1.114413.1.7.23.3"
},
// VeriSign Class 3 Public Primary Certification Authority
// https://www.verisign.com/
{ { { 0x74, 0x2c, 0x31, 0x92, 0xe6, 0x07, 0xe4, 0x24, 0xeb, 0x45,
0x49, 0x54, 0x2b, 0xe1, 0xbb, 0xc5, 0x3e, 0x61, 0x74, 0xe2 } },
"2.16.840.1.113733.1.7.23.6"
},
// VeriSign Class 3 Public Primary Certification Authority - G5
// https://www.verisign.com/
{ { { 0x4e, 0xb6, 0xd5, 0x78, 0x49, 0x9b, 0x1c, 0xcf, 0x5f, 0x58,
0x1e, 0xad, 0x56, 0xbe, 0x3d, 0x9b, 0x67, 0x44, 0xa5, 0xe5 } },
"2.16.840.1.113733.1.7.23.6"
},
// XRamp Global Certification Authority
{ { { 0xb8, 0x01, 0x86, 0xd1, 0xeb, 0x9c, 0x86, 0xa5, 0x41, 0x04,
0xcf, 0x30, 0x54, 0xf3, 0x4c, 0x52, 0xb7, 0xe5, 0x58, 0xc6 } },
"2.16.840.1.114404.1.1.2.4.1"
}
};
// static
EVRootCAMetadata* EVRootCAMetadata::GetInstance() {
return Singleton<EVRootCAMetadata>::get();
}
bool EVRootCAMetadata::GetPolicyOID(
const X509Certificate::Fingerprint& fingerprint,
std::string* policy_oid) const {
StringMap::const_iterator iter = ev_policy_.find(fingerprint);
if (iter == ev_policy_.end())
return false;
*policy_oid = iter->second;
return true;
}
EVRootCAMetadata::EVRootCAMetadata() {
// Constructs the object from the raw metadata in ev_root_ca_metadata.
num_policy_oids_ = arraysize(ev_root_ca_metadata);
policy_oids_.reset(new const char*[num_policy_oids_]);
for (size_t i = 0; i < arraysize(ev_root_ca_metadata); i++) {
const EVMetadata& metadata = ev_root_ca_metadata[i];
ev_policy_[metadata.fingerprint] = metadata.policy_oid;
// Multiple root CA certs may use the same EV policy OID. Having
// duplicates in the policy_oids_ array does no harm, so we don't
// bother detecting duplicates.
policy_oids_[i] = metadata.policy_oid;
}
}
} // namespace net
<commit_msg>Add the EV metadata for two GlobalSign root CA certificates.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/singleton.h"
#include "net/base/ev_root_ca_metadata.h"
namespace net {
// Raw metadata.
struct EVMetadata {
// The SHA-1 fingerprint of the root CA certificate, used as a unique
// identifier for a root CA certificate.
X509Certificate::Fingerprint fingerprint;
// The EV policy OID of the root CA.
// Note: a root CA may have multiple EV policies. When that actually
// happens, we'll need to support that.
const char* policy_oid;
};
static const EVMetadata ev_root_ca_metadata[] = {
// COMODO Certification Authority
// https://secure.comodo.com/
{ { { 0x66, 0x31, 0xbf, 0x9e, 0xf7, 0x4f, 0x9e, 0xb6, 0xc9, 0xd5,
0xa6, 0x0c, 0xba, 0x6a, 0xbe, 0xd1, 0xf7, 0xbd, 0xef, 0x7b } },
"1.3.6.1.4.1.6449.1.2.1.5.1"
},
// DigiCert High Assurance EV Root CA
// https://www.digicert.com
{ { { 0x5f, 0xb7, 0xee, 0x06, 0x33, 0xe2, 0x59, 0xdb, 0xad, 0x0c,
0x4c, 0x9a, 0xe6, 0xd3, 0x8f, 0x1a, 0x61, 0xc7, 0xdc, 0x25 } },
"2.16.840.1.114412.2.1"
},
// Entrust.net Secure Server Certification Authority
// https://www.entrust.net/
{ { { 0x99, 0xa6, 0x9b, 0xe6, 0x1a, 0xfe, 0x88, 0x6b, 0x4d, 0x2b,
0x82, 0x00, 0x7c, 0xb8, 0x54, 0xfc, 0x31, 0x7e, 0x15, 0x39 } },
"2.16.840.1.114028.10.1.2"
},
// Entrust Root Certification Authority
// https://www.entrust.net/
{ { { 0xb3, 0x1e, 0xb1, 0xb7, 0x40, 0xe3, 0x6c, 0x84, 0x02, 0xda,
0xdc, 0x37, 0xd4, 0x4d, 0xf5, 0xd4, 0x67, 0x49, 0x52, 0xf9 } },
"2.16.840.1.114028.10.1.2"
},
// Equifax Secure Certificate Authority (GeoTrust)
// https://www.geotrust.com/
{ { { 0xd2, 0x32, 0x09, 0xad, 0x23, 0xd3, 0x14, 0x23, 0x21, 0x74,
0xe4, 0x0d, 0x7f, 0x9d, 0x62, 0x13, 0x97, 0x86, 0x63, 0x3a } },
"1.3.6.1.4.1.14370.1.6"
},
// GeoTrust Primary Certification Authority
// https://www.geotrust.com/
{ { { 0x32, 0x3c, 0x11, 0x8e, 0x1b, 0xf7, 0xb8, 0xb6, 0x52, 0x54,
0xe2, 0xe2, 0x10, 0x0d, 0xd6, 0x02, 0x90, 0x37, 0xf0, 0x96 } },
"1.3.6.1.4.1.14370.1.6"
},
// GlobalSign
// https://www.globalsign.com/
{ { { 0x75, 0xe0, 0xab, 0xb6, 0x13, 0x85, 0x12, 0x27, 0x1c, 0x04,
0xf8, 0x5f, 0xdd, 0xde, 0x38, 0xe4, 0xb7, 0x24, 0x2e, 0xfe } },
"1.3.6.1.4.1.4146.1.1"
},
// GlobalSign Root CA
{ { { 0xb1, 0xbc, 0x96, 0x8b, 0xd4, 0xf4, 0x9d, 0x62, 0x2a, 0xa8,
0x9a, 0x81, 0xf2, 0x15, 0x01, 0x52, 0xa4, 0x1d, 0x82, 0x9c } },
"1.3.6.1.4.1.4146.1.1"
},
// Go Daddy Class 2 Certification Authority
// https://www.godaddy.com/
{ { { 0x27, 0x96, 0xba, 0xe6, 0x3f, 0x18, 0x01, 0xe2, 0x77, 0x26,
0x1b, 0xa0, 0xd7, 0x77, 0x70, 0x02, 0x8f, 0x20, 0xee, 0xe4 } },
"2.16.840.1.114413.1.7.23.3"
},
// Network Solutions Certificate Authority
// https://www.networksolutions.com/website-packages/index.jsp
{ { { 0x74, 0xf8, 0xa3, 0xc3, 0xef, 0xe7, 0xb3, 0x90, 0x06, 0x4b,
0x83, 0x90, 0x3c, 0x21, 0x64, 0x60, 0x20, 0xe5, 0xdf, 0xce } },
"1.3.6.1.4.1.782.1.2.1.8.1"
},
// QuoVadis Root CA 2
// https://www.quovadis.bm/
{ { { 0xca, 0x3a, 0xfb, 0xcf, 0x12, 0x40, 0x36, 0x4b, 0x44, 0xb2,
0x16, 0x20, 0x88, 0x80, 0x48, 0x39, 0x19, 0x93, 0x7c, 0xf7 } },
"1.3.6.1.4.1.8024.0.2.100.1.2"
},
// SecureTrust CA, SecureTrust Corporation
// https://www.securetrust.com
// https://www.trustwave.com/
{ { { 0x87, 0x82, 0xc6, 0xc3, 0x04, 0x35, 0x3b, 0xcf, 0xd2, 0x96,
0x92, 0xd2, 0x59, 0x3e, 0x7d, 0x44, 0xd9, 0x34, 0xff, 0x11 } },
"2.16.840.1.114404.1.1.2.4.1"
},
// Secure Global CA, SecureTrust Corporation
{ { { 0x3a, 0x44, 0x73, 0x5a, 0xe5, 0x81, 0x90, 0x1f, 0x24, 0x86,
0x61, 0x46, 0x1e, 0x3b, 0x9c, 0xc4, 0x5f, 0xf5, 0x3a, 0x1b } },
"2.16.840.1.114404.1.1.2.4.1"
},
// Starfield Class 2 Certification Authority
// https://www.starfieldtech.com/
{ { { 0xad, 0x7e, 0x1c, 0x28, 0xb0, 0x64, 0xef, 0x8f, 0x60, 0x03,
0x40, 0x20, 0x14, 0xc3, 0xd0, 0xe3, 0x37, 0x0e, 0xb5, 0x8a } },
"2.16.840.1.114414.1.7.23.3"
},
// Thawte Premium Server CA
// https://www.thawte.com/
{ { { 0x62, 0x7f, 0x8d, 0x78, 0x27, 0x65, 0x63, 0x99, 0xd2, 0x7d,
0x7f, 0x90, 0x44, 0xc9, 0xfe, 0xb3, 0xf3, 0x3e, 0xfa, 0x9a } },
"2.16.840.1.113733.1.7.48.1"
},
// thawte Primary Root CA
// https://www.thawte.com/
{ { { 0x91, 0xc6, 0xd6, 0xee, 0x3e, 0x8a, 0xc8, 0x63, 0x84, 0xe5,
0x48, 0xc2, 0x99, 0x29, 0x5c, 0x75, 0x6c, 0x81, 0x7b, 0x81 } },
"2.16.840.1.113733.1.7.48.1"
},
// UTN - DATACorp SGC
{ { { 0x58, 0x11, 0x9f, 0x0e, 0x12, 0x82, 0x87, 0xea, 0x50, 0xfd,
0xd9, 0x87, 0x45, 0x6f, 0x4f, 0x78, 0xdc, 0xfa, 0xd6, 0xd4 } },
"1.3.6.1.4.1.6449.1.2.1.5.1"
},
// UTN-USERFirst-Hardware
{ { { 0x04, 0x83, 0xed, 0x33, 0x99, 0xac, 0x36, 0x08, 0x05, 0x87,
0x22, 0xed, 0xbc, 0x5e, 0x46, 0x00, 0xe3, 0xbe, 0xf9, 0xd7 } },
"1.3.6.1.4.1.6449.1.2.1.5.1"
},
// ValiCert Class 2 Policy Validation Authority
// TODO(wtc): bug 1165107: this CA has another policy OID
// "2.16.840.1.114414.1.7.23.3".
{ { { 0x31, 0x7a, 0x2a, 0xd0, 0x7f, 0x2b, 0x33, 0x5e, 0xf5, 0xa1,
0xc3, 0x4e, 0x4b, 0x57, 0xe8, 0xb7, 0xd8, 0xf1, 0xfc, 0xa6 } },
"2.16.840.1.114413.1.7.23.3"
},
// VeriSign Class 3 Public Primary Certification Authority
// https://www.verisign.com/
{ { { 0x74, 0x2c, 0x31, 0x92, 0xe6, 0x07, 0xe4, 0x24, 0xeb, 0x45,
0x49, 0x54, 0x2b, 0xe1, 0xbb, 0xc5, 0x3e, 0x61, 0x74, 0xe2 } },
"2.16.840.1.113733.1.7.23.6"
},
// VeriSign Class 3 Public Primary Certification Authority - G5
// https://www.verisign.com/
{ { { 0x4e, 0xb6, 0xd5, 0x78, 0x49, 0x9b, 0x1c, 0xcf, 0x5f, 0x58,
0x1e, 0xad, 0x56, 0xbe, 0x3d, 0x9b, 0x67, 0x44, 0xa5, 0xe5 } },
"2.16.840.1.113733.1.7.23.6"
},
// XRamp Global Certification Authority
{ { { 0xb8, 0x01, 0x86, 0xd1, 0xeb, 0x9c, 0x86, 0xa5, 0x41, 0x04,
0xcf, 0x30, 0x54, 0xf3, 0x4c, 0x52, 0xb7, 0xe5, 0x58, 0xc6 } },
"2.16.840.1.114404.1.1.2.4.1"
}
};
// static
EVRootCAMetadata* EVRootCAMetadata::GetInstance() {
return Singleton<EVRootCAMetadata>::get();
}
bool EVRootCAMetadata::GetPolicyOID(
const X509Certificate::Fingerprint& fingerprint,
std::string* policy_oid) const {
StringMap::const_iterator iter = ev_policy_.find(fingerprint);
if (iter == ev_policy_.end())
return false;
*policy_oid = iter->second;
return true;
}
EVRootCAMetadata::EVRootCAMetadata() {
// Constructs the object from the raw metadata in ev_root_ca_metadata.
num_policy_oids_ = arraysize(ev_root_ca_metadata);
policy_oids_.reset(new const char*[num_policy_oids_]);
for (size_t i = 0; i < arraysize(ev_root_ca_metadata); i++) {
const EVMetadata& metadata = ev_root_ca_metadata[i];
ev_policy_[metadata.fingerprint] = metadata.policy_oid;
// Multiple root CA certs may use the same EV policy OID. Having
// duplicates in the policy_oids_ array does no harm, so we don't
// bother detecting duplicates.
policy_oids_[i] = metadata.policy_oid;
}
}
} // namespace net
<|endoftext|> |
<commit_before><commit_msg>Remove a redefined variable.<commit_after><|endoftext|> |
<commit_before>/*
* NetworkPlan.hpp
*
* Created on: 06.06.2016
* Author: hartung
*/
#ifndef NETWORK_INCLUDE_NETWORKPLAN_HPP_
#define NETWORK_INCLUDE_NETWORKPLAN_HPP_
#include <memory>
#include <VariableList.hpp>
#include <SimulationServer.hpp>
#include "Stdafx.hpp"
#include "fmi/InputMapping.hpp"
namespace Network
{
struct NetworkFmuInformation
{
size_type simPos;
size_type corePos;
size_type solverPos;
FMI::InputMapping inputMap;
FMI::InputMapping outputMap;
};
struct NetworkPlan
{
std::shared_ptr<NetOff::SimulationServer> server;
std::vector<NetworkFmuInformation> fmuNet;
};
}
#endif /* NETWORK_INCLUDE_NETWORKPLAN_HPP_ */
<commit_msg>Review: header includes, remove namespace std<commit_after>/*
* NetworkPlan.hpp
*
* Created on: 06.06.2016
* Author: hartung
*/
#ifndef NETWORK_INCLUDE_NETWORKPLAN_HPP_
#define NETWORK_INCLUDE_NETWORKPLAN_HPP_
#include "Stdafx.hpp"
#include "SimulationServer.hpp"
#include "fmi/InputMapping.hpp"
namespace Network
{
struct NetworkFmuInformation
{
size_type simPos;
size_type corePos;
size_type solverPos;
FMI::InputMapping inputMap;
FMI::InputMapping outputMap;
};
struct NetworkPlan
{
shared_ptr<NetOff::SimulationServer> server;
vector<NetworkFmuInformation> fmuNet;
};
}
#endif /* NETWORK_INCLUDE_NETWORKPLAN_HPP_ */
<|endoftext|> |
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef IOX_POSH_POPO_SAMPLE_HPP
#define IOX_POSH_POPO_SAMPLE_HPP
#include "iceoryx_posh/mepoo/chunk_header.hpp"
#include "iceoryx_utils/cxx/unique_ptr.hpp"
namespace iox
{
namespace popo
{
template <typename T>
class PublisherInterface;
///
/// @brief The Sample class is a mutable abstraction over types which are written to loaned shared memory.
/// These samples are publishable to the iceoryx system.
///
template <typename T>
class Sample
{
public:
Sample(cxx::unique_ptr<T>&& samplePtr, PublisherInterface<T>& publisher);
Sample(const Sample<T>&) = delete;
Sample<T>& operator=(const Sample<T>&) = delete;
Sample<T>& operator=(Sample<T>&& rhs);
Sample(Sample<T>&& rhs);
~Sample();
Sample(std::nullptr_t) noexcept;
///
/// @brief operator -> Transparent access to the encapsulated type.
/// @return
///
T* operator->() noexcept;
///
/// @brief operator -> Transparent read-only access to the encapsulated type.
/// @return
///
const T* operator->() const noexcept;
///
/// @brief operator* Provide a reference to the encapsulated type.
/// @return A T& to the encapsulated type.
/// @details Only available for non void type T.
///
template <typename S = T,
typename = std::enable_if_t<std::is_same<S, T>::value && !std::is_same<S, void>::value, S>>
S& operator*() noexcept;
///
/// @brief operator* Provide a const reference to the encapsulated type.
/// @return A T& to the encapsulated type.
/// @details Only available for non void type T.
///
template <typename S = T,
typename = std::enable_if_t<std::is_same<S, T>::value && !std::is_same<S, void>::value, S>>
const S& operator*() const noexcept;
///
/// @brief operator bool Indciates whether the sample is valid, i.e. refers to allocated memory.
/// @return true if the sample is valid, false otherwise.
///
operator bool() const;
///
/// @brief allocation Access to the memory chunk loaned to the sample.
/// @return
///
T* get() noexcept;
///
/// @brief allocation Read-only access to the memory chunk loaned to the sample.
/// @return
///
const T* get() const noexcept;
///
/// @brief header Retrieve the header of the underlying memory chunk loaned to the sample.
/// @return The ChunkHeader of the underlying memory chunk.
///
mepoo::ChunkHeader* getHeader() noexcept;
///
/// @brief publish Publish the sample via the publisher from which it was loaned and automatically
/// release ownership to it.
///
void publish() noexcept;
///
/// @brief release Manually release ownership of the loaned memory chunk.
/// @details This prevents the sample from automatically releasing ownership on destruction.
///
void release() noexcept;
protected:
cxx::unique_ptr<T> m_samplePtr{[](T* const) {}}; // Placeholder. This is overwritten on sample construction.
std::reference_wrapper<PublisherInterface<T>> m_publisherRef;
};
///
/// @brief The Sample<const T> class is a non-mutable abstraction over types which are written to loaned shared memory.
/// These samples are received from the iceoryx system via subscribers.
///
template <typename T>
class Sample<const T>
{
public:
/// Creates an empty sample.
Sample(cxx::unique_ptr<T>&& samplePtr) noexcept;
Sample(const Sample&) = delete;
Sample& operator=(const Sample&) = delete;
Sample(Sample<const T>&& rhs);
Sample& operator=(Sample<const T>&& rhs);
~Sample();
Sample(std::nullptr_t) noexcept;
const T* operator->() noexcept;
template <typename S = T,
typename = std::enable_if_t<std::is_same<S, T>::value && !std::is_same<S, void>::value, S>>
const S& operator*() noexcept;
const T* get() noexcept;
const mepoo::ChunkHeader* getHeader() noexcept;
template <typename... Args>
void emplace(Args&&... args) noexcept = delete;
private:
cxx::unique_ptr<T> m_samplePtr{[](T* const) {}}; // Placeholder. This is overwritten on sample construction.
};
} // namespace popo
} // namespace iox
#include "iceoryx_posh/internal/popo/sample.inl"
#endif // IOX_POSH_POPO_SAMPLE_HPP
<commit_msg>iox-#408 remove emplace in sample header<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef IOX_POSH_POPO_SAMPLE_HPP
#define IOX_POSH_POPO_SAMPLE_HPP
#include "iceoryx_posh/mepoo/chunk_header.hpp"
#include "iceoryx_utils/cxx/unique_ptr.hpp"
namespace iox
{
namespace popo
{
template <typename T>
class PublisherInterface;
///
/// @brief The Sample class is a mutable abstraction over types which are written to loaned shared memory.
/// These samples are publishable to the iceoryx system.
///
template <typename T>
class Sample
{
public:
Sample(cxx::unique_ptr<T>&& samplePtr, PublisherInterface<T>& publisher);
Sample(const Sample<T>&) = delete;
Sample<T>& operator=(const Sample<T>&) = delete;
Sample<T>& operator=(Sample<T>&& rhs);
Sample(Sample<T>&& rhs);
~Sample();
Sample(std::nullptr_t) noexcept;
///
/// @brief operator -> Transparent access to the encapsulated type.
/// @return
///
T* operator->() noexcept;
///
/// @brief operator -> Transparent read-only access to the encapsulated type.
/// @return
///
const T* operator->() const noexcept;
///
/// @brief operator* Provide a reference to the encapsulated type.
/// @return A T& to the encapsulated type.
/// @details Only available for non void type T.
///
template <typename S = T,
typename = std::enable_if_t<std::is_same<S, T>::value && !std::is_same<S, void>::value, S>>
S& operator*() noexcept;
///
/// @brief operator* Provide a const reference to the encapsulated type.
/// @return A T& to the encapsulated type.
/// @details Only available for non void type T.
///
template <typename S = T,
typename = std::enable_if_t<std::is_same<S, T>::value && !std::is_same<S, void>::value, S>>
const S& operator*() const noexcept;
///
/// @brief operator bool Indciates whether the sample is valid, i.e. refers to allocated memory.
/// @return true if the sample is valid, false otherwise.
///
operator bool() const;
///
/// @brief allocation Access to the memory chunk loaned to the sample.
/// @return
///
T* get() noexcept;
///
/// @brief allocation Read-only access to the memory chunk loaned to the sample.
/// @return
///
const T* get() const noexcept;
///
/// @brief header Retrieve the header of the underlying memory chunk loaned to the sample.
/// @return The ChunkHeader of the underlying memory chunk.
///
mepoo::ChunkHeader* getHeader() noexcept;
///
/// @brief publish Publish the sample via the publisher from which it was loaned and automatically
/// release ownership to it.
///
void publish() noexcept;
///
/// @brief release Manually release ownership of the loaned memory chunk.
/// @details This prevents the sample from automatically releasing ownership on destruction.
///
void release() noexcept;
protected:
cxx::unique_ptr<T> m_samplePtr{[](T* const) {}}; // Placeholder. This is overwritten on sample construction.
std::reference_wrapper<PublisherInterface<T>> m_publisherRef;
};
///
/// @brief The Sample<const T> class is a non-mutable abstraction over types which are written to loaned shared memory.
/// These samples are received from the iceoryx system via subscribers.
///
template <typename T>
class Sample<const T>
{
public:
/// Creates an empty sample.
Sample(cxx::unique_ptr<T>&& samplePtr) noexcept;
Sample(const Sample&) = delete;
Sample& operator=(const Sample&) = delete;
Sample(Sample<const T>&& rhs);
Sample& operator=(Sample<const T>&& rhs);
~Sample();
Sample(std::nullptr_t) noexcept;
const T* operator->() noexcept;
template <typename S = T,
typename = std::enable_if_t<std::is_same<S, T>::value && !std::is_same<S, void>::value, S>>
const S& operator*() noexcept;
const T* get() noexcept;
const mepoo::ChunkHeader* getHeader() noexcept;
private:
cxx::unique_ptr<T> m_samplePtr{[](T* const) {}}; // Placeholder. This is overwritten on sample construction.
};
} // namespace popo
} // namespace iox
#include "iceoryx_posh/internal/popo/sample.inl"
#endif // IOX_POSH_POPO_SAMPLE_HPP
<|endoftext|> |
<commit_before>#include <map>
#include <iostream>
#include <sstream>
#include <fstream>
#include <readline/readline.h>
#include <readline/history.h>
#include "sexpr.hpp"
#include "ast.hpp"
#include "eval.hpp"
#include "parse.hpp"
#include "type.hpp"
#include "package.hpp"
const bool debug = false;
struct history {
const std::string filename;
history(const std::string& filename="/tmp/slap.history")
: filename(filename) {
read_history(filename.c_str());
}
~history() {
write_history(filename.c_str());
}
};
template<class F>
static void read_loop(const F& f) {
const history lock;
while(const char* line = readline("> ")) {
if(!*line) continue;
add_history(line);
std::stringstream ss(line);
f(ss);
}
};
static void print_error(const std::exception& e, std::size_t level=0) {
const std::string prefix(level, ' ');
std::cerr << prefix << e.what() << std::endl;
try {
std::rethrow_if_nested(e);
} catch(std::exception& e) {
print_error(e, level + 1);
}
}
int main(int argc, char** argv) {
// parser::debug::stream = &std::clog;
package pkg = package::core();
static const auto handler =
[&](std::istream& in) {
try {
ast::expr::iter(in, [&](ast::expr e) {
if(debug) std::cout << "ast: " << e << std::endl;
pkg.exec(e, [&](type::poly p, eval::value v) {
// TODO: cleanup variables with depth greater than current in
// substitution
if(auto v = e.get<ast::var>()) {
std::cout << v->name;
}
std::cout << " : " << p << std::flush
<< " = " << v << std::endl;
});
});
return true;
} catch(sexpr::error& e) {
std::cerr << "parse error: " << e.what() << std::endl;
} catch(ast::error& e) {
std::cerr << "syntax error: " << e.what() << std::endl;
} catch(type::error& e) {
print_error(e);
std::cerr << "type error: " << e.what() << std::endl;
} catch(kind::error& e) {
std::cerr << "kind error: " << e.what() << std::endl;
} catch(std::runtime_error& e) {
std::cerr << "runtime error: " << e.what() << std::endl;
}
return false;
};
if(argc > 1) {
const char* filename = argv[1];
if(auto ifs = std::ifstream(filename)) {
return handler(ifs) ? 0 : 1;
} else {
std::cerr << "io error: " << "cannot read " << filename << std::endl;
return 1;
}
} else {
read_loop(handler);
}
return 0;
}
<commit_msg>nested errors<commit_after>#include <map>
#include <iostream>
#include <sstream>
#include <fstream>
#include <readline/readline.h>
#include <readline/history.h>
#include "sexpr.hpp"
#include "ast.hpp"
#include "eval.hpp"
#include "parse.hpp"
#include "type.hpp"
#include "package.hpp"
const bool debug = false;
struct history {
const std::string filename;
history(const std::string& filename="/tmp/slap.history")
: filename(filename) {
read_history(filename.c_str());
}
~history() {
write_history(filename.c_str());
}
};
template<class F>
static void read_loop(const F& f) {
const history lock;
while(const char* line = readline("> ")) {
if(!*line) continue;
add_history(line);
std::stringstream ss(line);
f(ss);
}
};
static void print_error(const std::exception& e, std::size_t level=0) {
const std::string prefix(level, '.');
std::cerr << prefix << e.what() << std::endl;
try {
std::rethrow_if_nested(e);
} catch(std::exception& e) {
print_error(e, level + 1);
}
}
int main(int argc, char** argv) {
// parser::debug::stream = &std::clog;
package pkg = package::core();
static const auto handler =
[&](std::istream& in) {
try {
ast::expr::iter(in, [&](ast::expr e) {
if(debug) std::cout << "ast: " << e << std::endl;
pkg.exec(e, [&](type::poly p, eval::value v) {
// TODO: cleanup variables with depth greater than current in
// substitution
if(auto v = e.get<ast::var>()) {
std::cout << v->name;
}
std::cout << " : " << p << std::flush
<< " = " << v << std::endl;
});
});
return true;
} catch(sexpr::error& e) {
std::cerr << "parse error: " << e.what() << std::endl;
} catch(ast::error& e) {
std::cerr << "syntax error: " << e.what() << std::endl;
} catch(type::error& e) {
std::cerr << "type error: " << std::endl;
print_error(e);
} catch(kind::error& e) {
std::cerr << "kind error: " << e.what() << std::endl;
} catch(std::runtime_error& e) {
std::cerr << "runtime error: " << e.what() << std::endl;
}
return false;
};
if(argc > 1) {
const char* filename = argv[1];
if(auto ifs = std::ifstream(filename)) {
return handler(ifs) ? 0 : 1;
} else {
std::cerr << "io error: " << "cannot read " << filename << std::endl;
return 1;
}
} else {
read_loop(handler);
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef VIGRA_RF_RANDOM_FOREST_HXX
#define VIGRA_RF_RANDOM_FOREST_HXX
#include <type_traits>
#include <thread>
#include "../multi_shape.hxx"
#include "../binary_forest.hxx"
#include "../threadpool.hxx"
namespace vigra
{
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACCTYPE, ContainerTag CTag = MapTag>
class RandomForest
{
public:
typedef FEATURES Features;
typedef typename Features::value_type FeatureType;
typedef LABELS Labels;
typedef typename Labels::value_type LabelType;
typedef SPLITTESTS SplitTests;
typedef ACCTYPE ACC;
typedef typename ACC::input_type AccInputType;
typedef BinaryForest Graph;
typedef Graph::Node Node;
typedef std::vector<size_t> DistributionType;
static ContainerTag const container_tag = CTag;
// Default (empty) constructor.
RandomForest();
// Default constructor (copy all of the given stuff).
RandomForest(
Graph const & graph,
PropertyMap<Node, SplitTests, CTag> const & split_tests,
PropertyMap<Node, AccInputType, CTag> const & node_responses,
std::vector<LabelType> const & distinct_labels,
size_t num_features
);
/// \brief Grow this forest by incorporating the other.
void merge(
RandomForest const & other
);
/// \brief Predict the given data and return the average number of split comparisons.
/// \note labels should have the shape (features.shape()[0],).
double predict(
FEATURES const & features,
LABELS & labels,
int n_threads = -1
) const;
/// \brief Predict the probabilities of the given data and return the average number of split comparisons.
/// \note probs should have the shape (features.shape()[0], num_trees).
template <typename PROBS>
double predict_proba(
FEATURES const & features,
PROBS & probs,
int n_threads = -1
) const;
/// \brief For each data point in features, compute the corresponding leaf ids and return the average number of split comparisons.
/// \note ids should have the shape (features.shape()[0], num_trees).
template <typename IDS>
double leaf_ids(
FEATURES const & features,
IDS & ids,
int n_threads = -1
) const;
/// \brief Return the number of nodes.
size_t num_nodes() const
{
return graph_.numNodes();
}
/// \brief Return the number of trees.
size_t num_trees() const
{
return graph_.numRoots();
}
/// \brief The graph structure.
Graph graph_;
/// \brief Contains a test for each internal node, that is used to determine whether given data goes to the left or the right child.
PropertyMap<Node, SplitTests, CTag> split_tests_;
/// \brief Contains the responses of each node (for example the most frequent label).
PropertyMap<Node, AccInputType, CTag> node_responses_;
/// \brief The distinct labels that were found in training.
std::vector<LabelType> distinct_labels_;
/// \brief The number of features.
size_t num_features_;
private:
/// \brief Compute the leaf ids of the instances in [from, to).
template <typename IDS>
double leaf_ids_impl(
FEATURES const & features,
IDS & ids,
size_t from,
size_t to
) const;
};
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACC, ContainerTag CTag>
RandomForest<FEATURES, LABELS, SPLITTESTS, ACC, CTag>::RandomForest()
:
graph_(),
split_tests_(),
node_responses_(),
distinct_labels_(),
num_features_(0)
{}
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACC, ContainerTag CTag>
RandomForest<FEATURES, LABELS, SPLITTESTS, ACC, CTag>::RandomForest(
Graph const & graph,
PropertyMap<Node, SplitTests, CTag> const & split_tests,
PropertyMap<Node, AccInputType, CTag> const & node_responses,
std::vector<LabelType> const & distinct_labels,
size_t num_features
) :
graph_(graph),
split_tests_(split_tests),
node_responses_(node_responses),
distinct_labels_(distinct_labels),
num_features_(num_features)
{}
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACC, ContainerTag CTag>
void RandomForest<FEATURES, LABELS, SPLITTESTS, ACC, CTag>::merge(
RandomForest const & other
){
vigra_precondition(num_features_ == other.num_features_,
"RandomForest::merge(): Number of features must not be different.");
vigra_precondition(distinct_labels_ == other.distinct_labels_,
"RandomForest::merge(): The distinct labels must not be different.");
size_t const offset = num_nodes();
graph_.merge(other.graph_);
for (auto const & p : other.split_tests_)
{
split_tests_.insert(Node(p.first.id()+offset), p.second);
}
for (auto const & p : other.node_responses_)
{
node_responses_.insert(Node(p.first.id()+offset), p.second);
}
}
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACC, ContainerTag CTag>
double RandomForest<FEATURES, LABELS, SPLITTESTS, ACC, CTag>::predict(
FEATURES const & features,
LABELS & labels,
int n_threads
) const {
vigra_precondition(features.shape()[0] == labels.shape()[0],
"RandomForest::predict(): Shape mismatch between features and labels.");
vigra_precondition(features.shape()[1] == num_features_,
"RandomForest::predict(): Number of features in prediction differs from training.");
MultiArray<2, double> probs(Shape2(features.shape()[0], distinct_labels_.size()));
double const average_split_counts = predict_proba(features, probs, n_threads);
for (size_t i = 0; i < features.shape()[0]; ++i)
{
auto const sub_probs = probs.template bind<0>(i);
auto it = std::max_element(sub_probs.begin(), sub_probs.end());
size_t const label = std::distance(sub_probs.begin(), it);
labels(i) = distinct_labels_[label];
}
return average_split_counts;
}
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACC, ContainerTag CTag>
template <typename PROBS>
double RandomForest<FEATURES, LABELS, SPLITTESTS, ACC, CTag>::predict_proba(
FEATURES const & features,
PROBS & probs,
int n_threads
) const {
vigra_precondition(features.shape()[0] == probs.shape()[0],
"RandomForest::predict_proba(): Shape mismatch between features and probabilities.");
vigra_precondition(features.shape()[1] == num_features_,
"RandomForest::predict_proba(): Number of features in prediction differs from training.");
vigra_precondition(probs.shape()[1] == distinct_labels_.size(),
"RandomForest::predict_proba(): Number of labels in probabilities differs from training.");
size_t const num_roots = graph_.numRoots();
MultiArray<2, size_t> ids(Shape2(features.shape()[0], num_roots));
double const average_split_counts = leaf_ids(features, ids, n_threads);
ACC acc;
for (size_t i = 0; i < features.shape()[0]; ++i)
{
std::vector<AccInputType> tree_results(num_roots);
for (size_t k = 0; k < num_roots; ++k)
{
tree_results[k] = node_responses_.at(Node(ids(i, k)));
}
auto sub_probs = probs.template bind<0>(i);
acc(tree_results.begin(), tree_results.end(), sub_probs.begin());
}
return average_split_counts;
}
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACC, ContainerTag CTag>
template <typename IDS>
double RandomForest<FEATURES, LABELS, SPLITTESTS, ACC, CTag>::leaf_ids(
FEATURES const & features,
IDS & ids,
int n_threads
) const {
vigra_precondition(features.shape()[0] == ids.shape()[0],
"RandomForest::leaf_ids(): Shape mismatch between features and probabilities.");
vigra_precondition(features.shape()[1] == num_features_,
"RandomForest::leaf_ids(): Number of features in prediction differs from training.");
vigra_precondition(ids.shape()[1] == graph_.numRoots(),
"RandomForest::leaf_ids(): Leaf array has wrong shape.");
size_t const num_instances = features.shape()[0];
if (n_threads == -1)
n_threads = std::thread::hardware_concurrency();
if (n_threads < 1)
n_threads = 1;
std::vector<double> split_comparisons(n_threads, 0.0);
std::vector<size_t> indices(num_instances);
std::iota(indices.begin(), indices.end(), 0);
parallel_foreach(
n_threads,
num_instances,
indices.begin(),
indices.end(),
[this, &features, &ids, &split_comparisons](size_t thread_id, size_t i) {
split_comparisons[thread_id] += leaf_ids_impl(features, ids, i, i+1);
}
);
double const sum_split_comparisons = std::accumulate(split_comparisons.begin(), split_comparisons.end(), 0.0);
return sum_split_comparisons / features.shape()[0];
}
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACC, ContainerTag CTag>
template <typename IDS>
double RandomForest<FEATURES, LABELS, SPLITTESTS, ACC, CTag>::leaf_ids_impl(
FEATURES const & features,
IDS & ids,
size_t from,
size_t to
) const {
vigra_precondition(features.shape()[0] == ids.shape()[0],
"RandomForest::leaf_ids_impl(): Shape mismatch between features and labels.");
vigra_precondition(features.shape()[1] == num_features_,
"RandomForest::leaf_ids_impl(): Number of Features in prediction differs from training.");
vigra_precondition(from >= 0 && from <= to && to <= features.shape()[0],
"RandomForest::leaf_ids_impl(): Indices out of range.");
vigra_precondition(ids.shape()[1] == graph_.numRoots(),
"RandomForest::leaf_ids_impl(): Leaf array has wrong shape.");
double split_comparisons = 0.0;
for (size_t i = from; i < to; ++i)
{
auto const sub_features = features.template bind<0>(i);
for (size_t k = 0; k < graph_.numRoots(); ++k)
{
Node node = graph_.getRoot(k);
while (graph_.outDegree(node) > 0)
{
size_t const child_index = split_tests_.at(node)(sub_features);
node = graph_.getChild(node, child_index);
split_comparisons += 1.0;
}
ids(i, k) = node.id();
}
}
return split_comparisons;
}
} // namespace vigra
#endif
<commit_msg>Fixed lambda expression.<commit_after>#ifndef VIGRA_RF_RANDOM_FOREST_HXX
#define VIGRA_RF_RANDOM_FOREST_HXX
#include <type_traits>
#include <thread>
#include "../multi_shape.hxx"
#include "../binary_forest.hxx"
#include "../threadpool.hxx"
namespace vigra
{
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACCTYPE, ContainerTag CTag = MapTag>
class RandomForest
{
public:
typedef FEATURES Features;
typedef typename Features::value_type FeatureType;
typedef LABELS Labels;
typedef typename Labels::value_type LabelType;
typedef SPLITTESTS SplitTests;
typedef ACCTYPE ACC;
typedef typename ACC::input_type AccInputType;
typedef BinaryForest Graph;
typedef Graph::Node Node;
typedef std::vector<size_t> DistributionType;
static ContainerTag const container_tag = CTag;
// Default (empty) constructor.
RandomForest();
// Default constructor (copy all of the given stuff).
RandomForest(
Graph const & graph,
PropertyMap<Node, SplitTests, CTag> const & split_tests,
PropertyMap<Node, AccInputType, CTag> const & node_responses,
std::vector<LabelType> const & distinct_labels,
size_t num_features
);
/// \brief Grow this forest by incorporating the other.
void merge(
RandomForest const & other
);
/// \brief Predict the given data and return the average number of split comparisons.
/// \note labels should have the shape (features.shape()[0],).
double predict(
FEATURES const & features,
LABELS & labels,
int n_threads = -1
) const;
/// \brief Predict the probabilities of the given data and return the average number of split comparisons.
/// \note probs should have the shape (features.shape()[0], num_trees).
template <typename PROBS>
double predict_proba(
FEATURES const & features,
PROBS & probs,
int n_threads = -1
) const;
/// \brief For each data point in features, compute the corresponding leaf ids and return the average number of split comparisons.
/// \note ids should have the shape (features.shape()[0], num_trees).
template <typename IDS>
double leaf_ids(
FEATURES const & features,
IDS & ids,
int n_threads = -1
) const;
/// \brief Return the number of nodes.
size_t num_nodes() const
{
return graph_.numNodes();
}
/// \brief Return the number of trees.
size_t num_trees() const
{
return graph_.numRoots();
}
/// \brief The graph structure.
Graph graph_;
/// \brief Contains a test for each internal node, that is used to determine whether given data goes to the left or the right child.
PropertyMap<Node, SplitTests, CTag> split_tests_;
/// \brief Contains the responses of each node (for example the most frequent label).
PropertyMap<Node, AccInputType, CTag> node_responses_;
/// \brief The distinct labels that were found in training.
std::vector<LabelType> distinct_labels_;
/// \brief The number of features.
size_t num_features_;
private:
/// \brief Compute the leaf ids of the instances in [from, to).
template <typename IDS>
double leaf_ids_impl(
FEATURES const & features,
IDS & ids,
size_t from,
size_t to
) const;
};
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACC, ContainerTag CTag>
RandomForest<FEATURES, LABELS, SPLITTESTS, ACC, CTag>::RandomForest()
:
graph_(),
split_tests_(),
node_responses_(),
distinct_labels_(),
num_features_(0)
{}
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACC, ContainerTag CTag>
RandomForest<FEATURES, LABELS, SPLITTESTS, ACC, CTag>::RandomForest(
Graph const & graph,
PropertyMap<Node, SplitTests, CTag> const & split_tests,
PropertyMap<Node, AccInputType, CTag> const & node_responses,
std::vector<LabelType> const & distinct_labels,
size_t num_features
) :
graph_(graph),
split_tests_(split_tests),
node_responses_(node_responses),
distinct_labels_(distinct_labels),
num_features_(num_features)
{}
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACC, ContainerTag CTag>
void RandomForest<FEATURES, LABELS, SPLITTESTS, ACC, CTag>::merge(
RandomForest const & other
){
vigra_precondition(num_features_ == other.num_features_,
"RandomForest::merge(): Number of features must not be different.");
vigra_precondition(distinct_labels_ == other.distinct_labels_,
"RandomForest::merge(): The distinct labels must not be different.");
size_t const offset = num_nodes();
graph_.merge(other.graph_);
for (auto const & p : other.split_tests_)
{
split_tests_.insert(Node(p.first.id()+offset), p.second);
}
for (auto const & p : other.node_responses_)
{
node_responses_.insert(Node(p.first.id()+offset), p.second);
}
}
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACC, ContainerTag CTag>
double RandomForest<FEATURES, LABELS, SPLITTESTS, ACC, CTag>::predict(
FEATURES const & features,
LABELS & labels,
int n_threads
) const {
vigra_precondition(features.shape()[0] == labels.shape()[0],
"RandomForest::predict(): Shape mismatch between features and labels.");
vigra_precondition(features.shape()[1] == num_features_,
"RandomForest::predict(): Number of features in prediction differs from training.");
MultiArray<2, double> probs(Shape2(features.shape()[0], distinct_labels_.size()));
double const average_split_counts = predict_proba(features, probs, n_threads);
for (size_t i = 0; i < features.shape()[0]; ++i)
{
auto const sub_probs = probs.template bind<0>(i);
auto it = std::max_element(sub_probs.begin(), sub_probs.end());
size_t const label = std::distance(sub_probs.begin(), it);
labels(i) = distinct_labels_[label];
}
return average_split_counts;
}
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACC, ContainerTag CTag>
template <typename PROBS>
double RandomForest<FEATURES, LABELS, SPLITTESTS, ACC, CTag>::predict_proba(
FEATURES const & features,
PROBS & probs,
int n_threads
) const {
vigra_precondition(features.shape()[0] == probs.shape()[0],
"RandomForest::predict_proba(): Shape mismatch between features and probabilities.");
vigra_precondition(features.shape()[1] == num_features_,
"RandomForest::predict_proba(): Number of features in prediction differs from training.");
vigra_precondition(probs.shape()[1] == distinct_labels_.size(),
"RandomForest::predict_proba(): Number of labels in probabilities differs from training.");
size_t const num_roots = graph_.numRoots();
MultiArray<2, size_t> ids(Shape2(features.shape()[0], num_roots));
double const average_split_counts = leaf_ids(features, ids, n_threads);
ACC acc;
for (size_t i = 0; i < features.shape()[0]; ++i)
{
std::vector<AccInputType> tree_results(num_roots);
for (size_t k = 0; k < num_roots; ++k)
{
tree_results[k] = node_responses_.at(Node(ids(i, k)));
}
auto sub_probs = probs.template bind<0>(i);
acc(tree_results.begin(), tree_results.end(), sub_probs.begin());
}
return average_split_counts;
}
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACC, ContainerTag CTag>
template <typename IDS>
double RandomForest<FEATURES, LABELS, SPLITTESTS, ACC, CTag>::leaf_ids(
FEATURES const & features,
IDS & ids,
int n_threads
) const {
vigra_precondition(features.shape()[0] == ids.shape()[0],
"RandomForest::leaf_ids(): Shape mismatch between features and probabilities.");
vigra_precondition(features.shape()[1] == num_features_,
"RandomForest::leaf_ids(): Number of features in prediction differs from training.");
vigra_precondition(ids.shape()[1] == graph_.numRoots(),
"RandomForest::leaf_ids(): Leaf array has wrong shape.");
size_t const num_instances = features.shape()[0];
if (n_threads == -1)
n_threads = std::thread::hardware_concurrency();
if (n_threads < 1)
n_threads = 1;
std::vector<double> split_comparisons(n_threads, 0.0);
std::vector<size_t> indices(num_instances);
std::iota(indices.begin(), indices.end(), 0);
parallel_foreach(
n_threads,
num_instances,
indices.begin(),
indices.end(),
[this, &features, &ids, &split_comparisons](size_t thread_id, size_t i) {
split_comparisons[thread_id] += this->leaf_ids_impl(features, ids, i, i+1);
}
);
double const sum_split_comparisons = std::accumulate(split_comparisons.begin(), split_comparisons.end(), 0.0);
return sum_split_comparisons / features.shape()[0];
}
template <typename FEATURES, typename LABELS, typename SPLITTESTS, typename ACC, ContainerTag CTag>
template <typename IDS>
double RandomForest<FEATURES, LABELS, SPLITTESTS, ACC, CTag>::leaf_ids_impl(
FEATURES const & features,
IDS & ids,
size_t from,
size_t to
) const {
vigra_precondition(features.shape()[0] == ids.shape()[0],
"RandomForest::leaf_ids_impl(): Shape mismatch between features and labels.");
vigra_precondition(features.shape()[1] == num_features_,
"RandomForest::leaf_ids_impl(): Number of Features in prediction differs from training.");
vigra_precondition(from >= 0 && from <= to && to <= features.shape()[0],
"RandomForest::leaf_ids_impl(): Indices out of range.");
vigra_precondition(ids.shape()[1] == graph_.numRoots(),
"RandomForest::leaf_ids_impl(): Leaf array has wrong shape.");
double split_comparisons = 0.0;
for (size_t i = from; i < to; ++i)
{
auto const sub_features = features.template bind<0>(i);
for (size_t k = 0; k < graph_.numRoots(); ++k)
{
Node node = graph_.getRoot(k);
while (graph_.outDegree(node) > 0)
{
size_t const child_index = split_tests_.at(node)(sub_features);
node = graph_.getChild(node, child_index);
split_comparisons += 1.0;
}
ids(i, k) = node.id();
}
}
return split_comparisons;
}
} // namespace vigra
#endif
<|endoftext|> |
<commit_before>/**
* @author Laurent El Shafey <Laurent.El-Shafey@idiap.ch>
* @date Mon Apr 14 20:43:48 CEST 2014
*
* @brief Binds configuration information available from bob
*/
#ifdef NO_IMPORT_ARRAY
#undef NO_IMPORT_ARRAY
#endif
#include <bob.blitz/capi.h>
#include <bob.blitz/cleanup.h>
#include <string>
#include <cstdlib>
#include <blitz/blitz.h>
#include <boost/preprocessor/stringize.hpp>
#include <boost/version.hpp>
#include <boost/format.hpp>
#include <vl/generic.h>
#include <bob.core/config.h>
#include <bob.io.base/config.h>
#include <bob.sp/config.h>
#include <bob.math/config.h>
static int dict_set(PyObject* d, const char* key, const char* value) {
PyObject* v = Py_BuildValue("s", value);
if (!v) return 0;
int retval = PyDict_SetItemString(d, key, v);
Py_DECREF(v);
if (retval == 0) return 1; //all good
return 0; //a problem occurred
}
static int dict_steal(PyObject* d, const char* key, PyObject* value) {
if (!value) return 0;
int retval = PyDict_SetItemString(d, key, value);
Py_DECREF(value);
return retval == 0 ? 1 : 0;
}
/**
* Describes the version of Boost libraries installed
*/
static PyObject* boost_version() {
boost::format f("%d.%d.%d");
f % (BOOST_VERSION / 100000);
f % (BOOST_VERSION / 100 % 1000);
f % (BOOST_VERSION % 100);
return Py_BuildValue("s", f.str().c_str());
}
/**
* Describes the compiler version
*/
static PyObject* compiler_version() {
# if defined(__GNUC__) && !defined(__llvm__)
boost::format f("%s.%s.%s");
f % BOOST_PP_STRINGIZE(__GNUC__);
f % BOOST_PP_STRINGIZE(__GNUC_MINOR__);
f % BOOST_PP_STRINGIZE(__GNUC_PATCHLEVEL__);
return Py_BuildValue("ss", "gcc", f.str().c_str());
# elif defined(__llvm__) && !defined(__clang__)
return Py_BuildValue("ss", "llvm-gcc", __VERSION__);
# elif defined(__clang__)
return Py_BuildValue("ss", "clang", __clang_version__);
# else
return Py_BuildValue("s", "unsupported");
# endif
}
/**
* Python version with which we compiled the extensions
*/
static PyObject* python_version() {
boost::format f("%s.%s.%s");
f % BOOST_PP_STRINGIZE(PY_MAJOR_VERSION);
f % BOOST_PP_STRINGIZE(PY_MINOR_VERSION);
f % BOOST_PP_STRINGIZE(PY_MICRO_VERSION);
return Py_BuildValue("s", f.str().c_str());
}
/**
* VLFeat version
*/
static PyObject* vlfeat_version() {
return Py_BuildValue("s", VL_VERSION_STRING);
}
/**
* Numpy version
*/
static PyObject* numpy_version() {
return Py_BuildValue("{ssss}", "abi", BOOST_PP_STRINGIZE(NPY_VERSION),
"api", BOOST_PP_STRINGIZE(NPY_API_VERSION));
}
/**
* bob.blitz c/c++ api version
*/
static PyObject* bob_blitz_version() {
return Py_BuildValue("{ss}", "api", BOOST_PP_STRINGIZE(BOB_BLITZ_API_VERSION));
}
/**
* bob.core c/c++ api version
*/
static PyObject* bob_core_version() {
return Py_BuildValue("{ss}", "api", BOOST_PP_STRINGIZE(BOB_CORE_API_VERSION));
}
/**
* bob.core c/c++ api version
*/
static PyObject* bob_io_base_version() {
return Py_BuildValue("{ss}", "api", BOOST_PP_STRINGIZE(BOB_IO_BASE_API_VERSION));
}
/**
* bob.core c/c++ api version
*/
static PyObject* bob_sp_version() {
return Py_BuildValue("{ss}", "api", BOOST_PP_STRINGIZE(BOB_SP_API_VERSION));
}
/**
* bob.core c/c++ api version
*/
static PyObject* bob_math_version() {
return Py_BuildValue("{ss}", "api", BOOST_PP_STRINGIZE(BOB_MATH_API_VERSION));
}
static PyObject* build_version_dictionary() {
PyObject* retval = PyDict_New();
if (!retval) return 0;
auto retval_ = make_safe(retval);
if (!dict_steal(retval, "Bob", bob_core_version())) return 0;
if (!dict_set(retval, "Blitz++", BZ_VERSION)) return 0;
if (!dict_steal(retval, "Boost", boost_version())) return 0;
if (!dict_steal(retval, "Compiler", compiler_version())) return 0;
if (!dict_steal(retval, "Python", python_version())) return 0;
if (!dict_steal(retval, "NumPy", numpy_version())) return 0;
if (!dict_steal(retval, "bob.blitz", bob_blitz_version())) return 0;
if (!dict_steal(retval, "bob.core", bob_core_version())) return 0;
if (!dict_steal(retval, "bob.io.base", bob_io_base_version())) return 0;
if (!dict_steal(retval, "bob.sp", bob_sp_version())) return 0;
if (!dict_steal(retval, "bob.math", bob_math_version())) return 0;
if (!dict_steal(retval, "VLFeat", vlfeat_version())) return 0;
Py_INCREF(retval);
return retval;
}
static PyMethodDef module_methods[] = {
{0} /* Sentinel */
};
PyDoc_STRVAR(module_docstr,
"Information about software used to compile the C++ Bob API"
);
#if PY_VERSION_HEX >= 0x03000000
static PyModuleDef module_definition = {
PyModuleDef_HEAD_INIT,
BOB_EXT_MODULE_NAME,
module_docstr,
-1,
module_methods,
0, 0, 0, 0
};
#endif
static PyObject* create_module (void) {
# if PY_VERSION_HEX >= 0x03000000
PyObject* m = PyModule_Create(&module_definition);
# else
PyObject* m = Py_InitModule3(BOB_EXT_MODULE_NAME, module_methods, module_docstr);
# endif
if (!m) return 0;
auto m_ = make_safe(m); ///< protects against early returns
/* register version numbers and constants */
if (PyModule_AddStringConstant(m, "module", BOB_EXT_MODULE_VERSION) < 0) return 0;
PyObject* externals = build_version_dictionary();
if (!externals) return 0;
if (PyModule_AddObject(m, "externals", externals) < 0) return 0;
/* imports dependencies */
if (import_bob_blitz() < 0) {
PyErr_Print();
PyErr_Format(PyExc_ImportError, "cannot import `%s'", BOB_EXT_MODULE_NAME);
return 0;
}
Py_INCREF(m);
return m;
}
PyMODINIT_FUNC BOB_EXT_ENTRY_NAME (void) {
# if PY_VERSION_HEX >= 0x03000000
return
# endif
create_module();
}
<commit_msg>Removed 'Bob' from version.cpp<commit_after>/**
* @author Laurent El Shafey <Laurent.El-Shafey@idiap.ch>
* @date Mon Apr 14 20:43:48 CEST 2014
*
* @brief Binds configuration information available from bob
*/
#ifdef NO_IMPORT_ARRAY
#undef NO_IMPORT_ARRAY
#endif
#include <bob.blitz/capi.h>
#include <bob.blitz/cleanup.h>
#include <string>
#include <cstdlib>
#include <blitz/blitz.h>
#include <boost/preprocessor/stringize.hpp>
#include <boost/version.hpp>
#include <boost/format.hpp>
#include <vl/generic.h>
#include <bob.core/config.h>
#include <bob.io.base/config.h>
#include <bob.sp/config.h>
#include <bob.math/config.h>
static int dict_set(PyObject* d, const char* key, const char* value) {
PyObject* v = Py_BuildValue("s", value);
if (!v) return 0;
int retval = PyDict_SetItemString(d, key, v);
Py_DECREF(v);
if (retval == 0) return 1; //all good
return 0; //a problem occurred
}
static int dict_steal(PyObject* d, const char* key, PyObject* value) {
if (!value) return 0;
int retval = PyDict_SetItemString(d, key, value);
Py_DECREF(value);
return retval == 0 ? 1 : 0;
}
/**
* Describes the version of Boost libraries installed
*/
static PyObject* boost_version() {
boost::format f("%d.%d.%d");
f % (BOOST_VERSION / 100000);
f % (BOOST_VERSION / 100 % 1000);
f % (BOOST_VERSION % 100);
return Py_BuildValue("s", f.str().c_str());
}
/**
* Describes the compiler version
*/
static PyObject* compiler_version() {
# if defined(__GNUC__) && !defined(__llvm__)
boost::format f("%s.%s.%s");
f % BOOST_PP_STRINGIZE(__GNUC__);
f % BOOST_PP_STRINGIZE(__GNUC_MINOR__);
f % BOOST_PP_STRINGIZE(__GNUC_PATCHLEVEL__);
return Py_BuildValue("ss", "gcc", f.str().c_str());
# elif defined(__llvm__) && !defined(__clang__)
return Py_BuildValue("ss", "llvm-gcc", __VERSION__);
# elif defined(__clang__)
return Py_BuildValue("ss", "clang", __clang_version__);
# else
return Py_BuildValue("s", "unsupported");
# endif
}
/**
* Python version with which we compiled the extensions
*/
static PyObject* python_version() {
boost::format f("%s.%s.%s");
f % BOOST_PP_STRINGIZE(PY_MAJOR_VERSION);
f % BOOST_PP_STRINGIZE(PY_MINOR_VERSION);
f % BOOST_PP_STRINGIZE(PY_MICRO_VERSION);
return Py_BuildValue("s", f.str().c_str());
}
/**
* VLFeat version
*/
static PyObject* vlfeat_version() {
return Py_BuildValue("s", VL_VERSION_STRING);
}
/**
* Numpy version
*/
static PyObject* numpy_version() {
return Py_BuildValue("{ssss}", "abi", BOOST_PP_STRINGIZE(NPY_VERSION),
"api", BOOST_PP_STRINGIZE(NPY_API_VERSION));
}
/**
* bob.blitz c/c++ api version
*/
static PyObject* bob_blitz_version() {
return Py_BuildValue("{ss}", "api", BOOST_PP_STRINGIZE(BOB_BLITZ_API_VERSION));
}
/**
* bob.core c/c++ api version
*/
static PyObject* bob_core_version() {
return Py_BuildValue("{ss}", "api", BOOST_PP_STRINGIZE(BOB_CORE_API_VERSION));
}
/**
* bob.core c/c++ api version
*/
static PyObject* bob_io_base_version() {
return Py_BuildValue("{ss}", "api", BOOST_PP_STRINGIZE(BOB_IO_BASE_API_VERSION));
}
/**
* bob.core c/c++ api version
*/
static PyObject* bob_sp_version() {
return Py_BuildValue("{ss}", "api", BOOST_PP_STRINGIZE(BOB_SP_API_VERSION));
}
/**
* bob.core c/c++ api version
*/
static PyObject* bob_math_version() {
return Py_BuildValue("{ss}", "api", BOOST_PP_STRINGIZE(BOB_MATH_API_VERSION));
}
static PyObject* build_version_dictionary() {
PyObject* retval = PyDict_New();
if (!retval) return 0;
auto retval_ = make_safe(retval);
if (!dict_set(retval, "Blitz++", BZ_VERSION)) return 0;
if (!dict_steal(retval, "Boost", boost_version())) return 0;
if (!dict_steal(retval, "Compiler", compiler_version())) return 0;
if (!dict_steal(retval, "Python", python_version())) return 0;
if (!dict_steal(retval, "NumPy", numpy_version())) return 0;
if (!dict_steal(retval, "bob.blitz", bob_blitz_version())) return 0;
if (!dict_steal(retval, "bob.core", bob_core_version())) return 0;
if (!dict_steal(retval, "bob.io.base", bob_io_base_version())) return 0;
if (!dict_steal(retval, "bob.sp", bob_sp_version())) return 0;
if (!dict_steal(retval, "bob.math", bob_math_version())) return 0;
if (!dict_steal(retval, "VLFeat", vlfeat_version())) return 0;
Py_INCREF(retval);
return retval;
}
static PyMethodDef module_methods[] = {
{0} /* Sentinel */
};
PyDoc_STRVAR(module_docstr,
"Information about software used to compile the C++ Bob API"
);
#if PY_VERSION_HEX >= 0x03000000
static PyModuleDef module_definition = {
PyModuleDef_HEAD_INIT,
BOB_EXT_MODULE_NAME,
module_docstr,
-1,
module_methods,
0, 0, 0, 0
};
#endif
static PyObject* create_module (void) {
# if PY_VERSION_HEX >= 0x03000000
PyObject* m = PyModule_Create(&module_definition);
# else
PyObject* m = Py_InitModule3(BOB_EXT_MODULE_NAME, module_methods, module_docstr);
# endif
if (!m) return 0;
auto m_ = make_safe(m); ///< protects against early returns
/* register version numbers and constants */
if (PyModule_AddStringConstant(m, "module", BOB_EXT_MODULE_VERSION) < 0) return 0;
PyObject* externals = build_version_dictionary();
if (!externals) return 0;
if (PyModule_AddObject(m, "externals", externals) < 0) return 0;
/* imports dependencies */
if (import_bob_blitz() < 0) {
PyErr_Print();
PyErr_Format(PyExc_ImportError, "cannot import `%s'", BOB_EXT_MODULE_NAME);
return 0;
}
Py_INCREF(m);
return m;
}
PyMODINIT_FUNC BOB_EXT_ENTRY_NAME (void) {
# if PY_VERSION_HEX >= 0x03000000
return
# endif
create_module();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <ncurses.h>
#include "maze.h"
using namespace std;
int main()
{
const int MAX_SIZE = 71;
bool maze[MAX_SIZE * MAX_SIZE];
int nrows = 19;
int ncols = 31;
int start[2] = {1, 1};
int finish[2] = {1, 1};
char c;
initscr();
while (true) {
// generate a new maze
backtracking_maze_gen(maze, MAX_SIZE, nrows, ncols);
gen_entrances_opposites(start, finish, nrows, ncols);
maze_print(maze, MAX_SIZE, nrows, ncols, start, finish);
// parse user input
c = getch();
if (c == 'q'){
break;
}
// increase the size of the maze (to a limit)
if (ncols < MAX_SIZE) {
ncols += 2;
}
if (nrows < (MAX_SIZE / 2)) {
nrows += 2;
}
}
endwin();
return 0;
}
<commit_msg>cleaning up curses window<commit_after>#include <iostream>
#include <ncurses.h>
#include "maze.h"
using namespace std;
int main()
{
const int MAX_SIZE = 71;
bool maze[MAX_SIZE * MAX_SIZE];
int nrows = 19;
int ncols = 31;
int start[2] = {1, 1};
int finish[2] = {1, 1};
char c;
initscr();
noecho();
curs_set(false);
while (true) {
// generate a new maze
backtracking_maze_gen(maze, MAX_SIZE, nrows, ncols);
gen_entrances_opposites(start, finish, nrows, ncols);
maze_print(maze, MAX_SIZE, nrows, ncols, start, finish);
// parse user input
c = getch();
if (c == 'q'){
break;
}
// increase the size of the maze (to a limit)
if (ncols < MAX_SIZE) {
ncols += 2;
}
if (nrows < (MAX_SIZE / 2)) {
nrows += 2;
}
}
endwin();
return 0;
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2013 Danny Y., Rapptz
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef SOL_STACK_HPP
#define SOL_STACK_HPP
#include "reference.hpp"
#include "tuple.hpp"
#include <utility>
#include <type_traits>
#include <array>
namespace sol {
template<typename T, typename R = void>
using EnableIf = typename std::enable_if<T::value, R>::type;
template<typename T, typename R = void>
using DisableIf = typename std::enable_if<!T::value, R>::type;
namespace stack {
namespace detail {
template<typename T>
inline T get_unsigned(lua_State* L, std::true_type, int index = -1) {
return lua_tounsigned(L, index);
}
template<typename T>
inline T get_unsigned(lua_State* L, std::false_type, int index = -1) {
return lua_tointeger(L, index);
}
template<typename T>
inline T get_arithmetic(lua_State* L, std::false_type, int index = -1) {
// T is a floating point
return lua_tonumber(L, index);
}
template<typename T>
inline T get_arithmetic(lua_State* L, std::true_type, int index = -1) {
// T is an integral
return get_unsigned<T>(L, std::is_unsigned<T>{}, index);
}
template<typename T>
inline T get_helper(lua_State* L, std::true_type, int index = -1) {
// T is a class type
return T(L, index);
}
template<typename T>
inline T get_helper(lua_State* L, std::false_type, int index = -1) {
// T is a fundamental type
return get_arithmetic<T>(L, std::is_integral<T>{}, index);
}
template<typename T>
inline void push_unsigned(lua_State* L, T x, std::true_type) {
lua_pushunsigned(L, x);
}
template<typename T>
inline void push_unsigned(lua_State* L, T x, std::false_type) {
lua_pushinteger(L, x);
}
template<typename T>
inline void push_arithmetic(lua_State* L, T x, std::true_type) {
// T is an integral type
push_unsigned(L, x, std::is_unsigned<T>{});
}
template<typename T>
inline void push_arithmetic(lua_State* L, T x, std::false_type) {
// T is an floating point type
lua_pushnumber(L, x);
}
} // detail
template<typename T>
inline T get(lua_State* L, int index = -1) {
return detail::get_helper<T>(L, std::is_class<T>{}, index);
}
template<>
inline bool get<bool>(lua_State* L, int index) {
return lua_toboolean(L, index) != 0;
}
template<>
inline std::string get<std::string>(lua_State* L, int index) {
std::string::size_type len;
auto str = lua_tolstring(L, index, &len);
return { str, len };
}
template<>
inline const char* get<const char*>(lua_State* L, int index) {
return lua_tostring(L, index);
}
template<typename T>
inline T pop(lua_State* L) {
auto r = get<T>(L);
lua_pop(L, 1);
return r;
}
template<typename T>
inline EnableIf<std::is_arithmetic<T>> push(lua_State* L, T arithmetic) {
detail::push_arithmetic(L, arithmetic, std::is_integral<T>{});
}
inline void push(lua_State*, reference& ref) {
ref.push();
}
inline void push(lua_State* L, bool boolean) {
lua_pushboolean(L, boolean);
}
inline void push(lua_State* L, const nil_t&) {
lua_pushnil(L);
}
inline void push(lua_State* L, lua_CFunction func) {
lua_pushcfunction(L, func);
}
inline void push(lua_State* L, lua_CFunction func, int n) {
lua_pushcclosure(L, func, n);
}
inline void push(lua_State* L, void* userdata) {
lua_pushlightuserdata(L, userdata);
}
template<size_t N>
inline void push(lua_State* L, const char (&str)[N]) {
lua_pushlstring(L, str, N - 1);
}
inline void push(lua_State* L, const char* str) {
lua_pushlstring(L, str, std::char_traits<char>::length(str));
}
inline void push(lua_State* L, const std::string& str) {
lua_pushlstring(L, str.c_str(), str.size());
}
template<typename T, size_t N>
inline void push(lua_State* L, const std::array<T, N>& data) {
for (std::size_t i = 0; i < data.size(); ++i) {
push(L, data[ i ]);
}
}
namespace detail {
template<typename T, std::size_t... I>
inline void push(lua_State* L, indices<I...>, const T& tuplen) {
using swallow = char[];
void(swallow{ '\0', (sol::stack::push(L, std::get<I>(tuplen)), '\0')... });
}
template<typename F, typename... Vs>
auto ltr_pop(lua_State*, F&& f, types<>, Vs&&... vs) -> decltype(f(std::forward<Vs>(vs)...)) {
return f(std::forward<Vs>(vs)...);
}
template<typename F, typename Head, typename... Vs>
auto ltr_pop(lua_State* L, F&& f, types<Head>, Vs&&... vs) -> decltype(ltr_pop(L, std::forward<F>(f), types<>(), std::forward<Vs>(vs)..., pop<Head>(L))) {
return ltr_pop(L, std::forward<F>(f), types<>(), std::forward<Vs>(vs)..., pop<Head>(L));
}
template<typename F, typename Head, typename... Tail, typename... Vs>
auto ltr_pop(lua_State* L, F&& f, types<Head, Tail...>, Vs&&... vs) -> decltype(ltr_pop(L, std::forward<F>(f), types<Tail...>(), std::forward<Vs>(vs)..., pop<Head>(L))) {
return ltr_pop(L, std::forward<F>(f), types<Tail...>(), std::forward<Vs>(vs)..., pop<Head>(L));
}
} // detail
template<typename... Args>
inline void push(lua_State* L, const std::tuple<Args...>& tuplen) {
detail::push(L, build_indices<sizeof...(Args)>(), tuplen);
}
template<typename... Args, typename TFx>
inline auto pop_call(lua_State* L, TFx&& fx, types<Args...>) -> decltype(detail::ltr_pop(L, std::forward<TFx>(fx), types<Args...>())) {
return detail::ltr_pop(L, std::forward<TFx>(fx), types<Args...>());
}
template<typename... Args>
void push_args(lua_State* L, Args&&... args) {
using swallow = char[];
void(swallow{ '\0', (stack::push(L, std::forward<Args>(args)), '\0')... });
}
} // stack
} // sol
#endif // SOL_STACK_HPP<commit_msg>Ranged for loop. Because ~~clean code~~.<commit_after>// The MIT License (MIT)
// Copyright (c) 2013 Danny Y., Rapptz
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef SOL_STACK_HPP
#define SOL_STACK_HPP
#include "reference.hpp"
#include "tuple.hpp"
#include <utility>
#include <type_traits>
#include <array>
namespace sol {
template<typename T, typename R = void>
using EnableIf = typename std::enable_if<T::value, R>::type;
template<typename T, typename R = void>
using DisableIf = typename std::enable_if<!T::value, R>::type;
namespace stack {
namespace detail {
template<typename T>
inline T get_unsigned(lua_State* L, std::true_type, int index = -1) {
return lua_tounsigned(L, index);
}
template<typename T>
inline T get_unsigned(lua_State* L, std::false_type, int index = -1) {
return lua_tointeger(L, index);
}
template<typename T>
inline T get_arithmetic(lua_State* L, std::false_type, int index = -1) {
// T is a floating point
return lua_tonumber(L, index);
}
template<typename T>
inline T get_arithmetic(lua_State* L, std::true_type, int index = -1) {
// T is an integral
return get_unsigned<T>(L, std::is_unsigned<T>{}, index);
}
template<typename T>
inline T get_helper(lua_State* L, std::true_type, int index = -1) {
// T is a class type
return T(L, index);
}
template<typename T>
inline T get_helper(lua_State* L, std::false_type, int index = -1) {
// T is a fundamental type
return get_arithmetic<T>(L, std::is_integral<T>{}, index);
}
template<typename T>
inline void push_unsigned(lua_State* L, T x, std::true_type) {
lua_pushunsigned(L, x);
}
template<typename T>
inline void push_unsigned(lua_State* L, T x, std::false_type) {
lua_pushinteger(L, x);
}
template<typename T>
inline void push_arithmetic(lua_State* L, T x, std::true_type) {
// T is an integral type
push_unsigned(L, x, std::is_unsigned<T>{});
}
template<typename T>
inline void push_arithmetic(lua_State* L, T x, std::false_type) {
// T is an floating point type
lua_pushnumber(L, x);
}
} // detail
template<typename T>
inline T get(lua_State* L, int index = -1) {
return detail::get_helper<T>(L, std::is_class<T>{}, index);
}
template<>
inline bool get<bool>(lua_State* L, int index) {
return lua_toboolean(L, index) != 0;
}
template<>
inline std::string get<std::string>(lua_State* L, int index) {
std::string::size_type len;
auto str = lua_tolstring(L, index, &len);
return { str, len };
}
template<>
inline const char* get<const char*>(lua_State* L, int index) {
return lua_tostring(L, index);
}
template<typename T>
inline T pop(lua_State* L) {
auto r = get<T>(L);
lua_pop(L, 1);
return r;
}
template<typename T>
inline EnableIf<std::is_arithmetic<T>> push(lua_State* L, T arithmetic) {
detail::push_arithmetic(L, arithmetic, std::is_integral<T>{});
}
inline void push(lua_State*, reference& ref) {
ref.push();
}
inline void push(lua_State* L, bool boolean) {
lua_pushboolean(L, boolean);
}
inline void push(lua_State* L, const nil_t&) {
lua_pushnil(L);
}
inline void push(lua_State* L, lua_CFunction func) {
lua_pushcfunction(L, func);
}
inline void push(lua_State* L, lua_CFunction func, int n) {
lua_pushcclosure(L, func, n);
}
inline void push(lua_State* L, void* userdata) {
lua_pushlightuserdata(L, userdata);
}
template<size_t N>
inline void push(lua_State* L, const char (&str)[N]) {
lua_pushlstring(L, str, N - 1);
}
inline void push(lua_State* L, const char* str) {
lua_pushlstring(L, str, std::char_traits<char>::length(str));
}
inline void push(lua_State* L, const std::string& str) {
lua_pushlstring(L, str.c_str(), str.size());
}
template<typename T, size_t N>
inline void push(lua_State* L, const std::array<T, N>& data) {
for (auto&& i : data) {
push(L, i);
}
}
namespace detail {
template<typename T, std::size_t... I>
inline void push(lua_State* L, indices<I...>, const T& tuplen) {
using swallow = char[];
void(swallow{ '\0', (sol::stack::push(L, std::get<I>(tuplen)), '\0')... });
}
template<typename F, typename... Vs>
auto ltr_pop(lua_State*, F&& f, types<>, Vs&&... vs) -> decltype(f(std::forward<Vs>(vs)...)) {
return f(std::forward<Vs>(vs)...);
}
template<typename F, typename Head, typename... Vs>
auto ltr_pop(lua_State* L, F&& f, types<Head>, Vs&&... vs) -> decltype(ltr_pop(L, std::forward<F>(f), types<>(), std::forward<Vs>(vs)..., pop<Head>(L))) {
return ltr_pop(L, std::forward<F>(f), types<>(), std::forward<Vs>(vs)..., pop<Head>(L));
}
template<typename F, typename Head, typename... Tail, typename... Vs>
auto ltr_pop(lua_State* L, F&& f, types<Head, Tail...>, Vs&&... vs) -> decltype(ltr_pop(L, std::forward<F>(f), types<Tail...>(), std::forward<Vs>(vs)..., pop<Head>(L))) {
return ltr_pop(L, std::forward<F>(f), types<Tail...>(), std::forward<Vs>(vs)..., pop<Head>(L));
}
} // detail
template<typename... Args>
inline void push(lua_State* L, const std::tuple<Args...>& tuplen) {
detail::push(L, build_indices<sizeof...(Args)>(), tuplen);
}
template<typename... Args, typename TFx>
inline auto pop_call(lua_State* L, TFx&& fx, types<Args...>) -> decltype(detail::ltr_pop(L, std::forward<TFx>(fx), types<Args...>())) {
return detail::ltr_pop(L, std::forward<TFx>(fx), types<Args...>());
}
template<typename... Args>
void push_args(lua_State* L, Args&&... args) {
using swallow = char[];
void(swallow{ '\0', (stack::push(L, std::forward<Args>(args)), '\0')... });
}
} // stack
} // sol
#endif // SOL_STACK_HPP<|endoftext|> |
<commit_before><commit_msg>Added MPI rank<commit_after><|endoftext|> |
<commit_before>#ifndef ITER_CHAIN_HPP_
#define ITER_CHAIN_HPP_
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <memory>
#include <initializer_list>
#include <type_traits>
namespace iter {
// rather than a chain function, use a callable object to support
// from_iterable
class ChainMaker;
template <typename Container, typename... RestContainers>
class Chained {
static_assert(
are_same<iterator_deref<Container>,
iterator_deref<RestContainers>...>::value,
"All chained iterables must have iterators that "
"dereference to the same type, including cv-qualifiers "
"and references.");
friend class ChainMaker;
template <typename C, typename... RC>
friend class Chained;
using iter_traits_deref =
typename std::remove_reference<iterator_deref<Container>>::type;
private:
Container container;
Chained<RestContainers...> rest_chained;
Chained(Container container, RestContainers&&... rest)
: container(std::forward<Container>(container)),
rest_chained{std::forward<RestContainers>(rest)...}
{ }
public:
class Iterator
: public std::iterator<
std::input_iterator_tag, iter_traits_deref>
{
private:
using RestIter =
typename Chained<RestContainers...>::Iterator;
iterator_type<Container> sub_iter;
const iterator_type<Container> sub_end;
RestIter rest_iter;
bool at_end;
public:
Iterator(const iterator_type<Container>& s_begin,
const iterator_type<Container>& s_end,
RestIter rest_iter)
: sub_iter{s_begin},
sub_end{s_end},
rest_iter{rest_iter},
at_end{!(sub_iter != sub_end)}
{ }
Iterator& operator++() {
if (this->at_end) {
++this->rest_iter;
} else {
++this->sub_iter;
if (!(this->sub_iter != this->sub_end)) {
this->at_end = true;
}
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter ||
this->rest_iter != other.rest_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
iterator_deref<Container> operator*() {
return this->at_end ?
*this->rest_iter : *this->sub_iter;
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
std::begin(this->rest_chained)};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
std::end(this->rest_chained)};
}
};
template <typename Container>
class Chained<Container> {
friend class ChainMaker;
template <typename C, typename... RC>
friend class Chained;
using iter_traits_deref =
typename std::remove_reference<iterator_deref<Container>>::type;
private:
Container container;
Chained(Container container)
: container(std::forward<Container>(container))
{ }
public:
class Iterator
: public std::iterator<
std::input_iterator_tag, iter_traits_deref>
{
private:
iterator_type<Container> sub_iter;
const iterator_type<Container> sub_end;
public:
Iterator(const iterator_type<Container>& s_begin,
const iterator_type<Container>& s_end)
: sub_iter{s_begin},
sub_end{s_end}
{ }
Iterator& operator++() {
++this->sub_iter;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
iterator_deref<Container> operator*() {
return *this->sub_iter;
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container)};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container)};
}
};
template <typename Container>
class ChainedFromIterable {
private:
Container container;
friend class ChainMaker;
ChainedFromIterable(Container container)
: container(std::forward<Container>(container))
{ }
public:
class Iterator {
private:
using SubContainer = iterator_deref<Container>;
using SubIter = iterator_type<SubContainer>;
iterator_type<Container> top_level_iter;
const iterator_type<Container> top_level_end;
std::unique_ptr<SubIter> sub_iter_p;
std::unique_ptr<SubIter> sub_end_p;
public:
Iterator(iterator_type<Container> top_iter,
iterator_type<Container> top_end)
: top_level_iter{top_iter},
top_level_end{top_end},
sub_iter_p{!(top_iter != top_end) ? // iter == end ?
nullptr : new SubIter{std::begin(*top_iter)}},
sub_end_p{!(top_iter != top_end) ? // iter == end ?
nullptr : new SubIter{std::end(*top_iter)}}
{ }
Iterator& operator++() {
++*this->sub_iter_p;
if (!(*this->sub_iter_p != *this->sub_end_p)) {
++this->top_level_iter;
if (this->top_level_iter != this->top_level_end) {
sub_iter_p.reset(
new SubIter{std::begin(*this->top_level_iter)});
sub_end_p.reset(
new SubIter{std::end(*this->top_level_iter)});
} else {
sub_iter_p.reset(nullptr);
sub_end_p.reset(nullptr);
}
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->top_level_iter != other.top_level_iter &&
(this->sub_iter_p != other.sub_iter_p ||
*this->sub_iter_p != *other.sub_iter_p);
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
iterator_deref<iterator_deref<Container>> operator*() {
return **this->sub_iter_p;
}
};
Iterator begin() {
return {std::begin(this->container), std::end(this->container)};
}
Iterator end() {
return {std::end(this->container), std::end(this->container)};
}
};
class ChainMaker {
public:
// expose regular call operator to provide usual chain()
template <typename... Containers>
Chained<Containers...> operator()(Containers&&... cs) const {
return {std::forward<Containers>(cs)...};
}
// chain.from_iterable
template <typename Container>
ChainedFromIterable<Container> from_iterable(
Container&& container) const {
return {std::forward<Container>(container)};
}
};
namespace {
constexpr auto chain = ChainMaker{};
}
}
#endif // #ifndef ITER_CHAIN_HPP_
<commit_msg>Makes chain iterator copy constructible<commit_after>#ifndef ITER_CHAIN_HPP_
#define ITER_CHAIN_HPP_
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <memory>
#include <initializer_list>
#include <type_traits>
namespace iter {
// rather than a chain function, use a callable object to support
// from_iterable
class ChainMaker;
template <typename Container, typename... RestContainers>
class Chained {
static_assert(
are_same<iterator_deref<Container>,
iterator_deref<RestContainers>...>::value,
"All chained iterables must have iterators that "
"dereference to the same type, including cv-qualifiers "
"and references.");
friend class ChainMaker;
template <typename C, typename... RC>
friend class Chained;
private:
Container container;
Chained<RestContainers...> rest_chained;
Chained(Container container, RestContainers&&... rest)
: container(std::forward<Container>(container)),
rest_chained{std::forward<RestContainers>(rest)...}
{ }
public:
class Iterator
: public std::iterator<
std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
using RestIter =
typename Chained<RestContainers...>::Iterator;
iterator_type<Container> sub_iter;
const iterator_type<Container> sub_end;
RestIter rest_iter;
bool at_end;
public:
Iterator(const iterator_type<Container>& s_begin,
const iterator_type<Container>& s_end,
RestIter rest_iter)
: sub_iter{s_begin},
sub_end{s_end},
rest_iter{rest_iter},
at_end{!(sub_iter != sub_end)}
{ }
Iterator& operator++() {
if (this->at_end) {
++this->rest_iter;
} else {
++this->sub_iter;
if (!(this->sub_iter != this->sub_end)) {
this->at_end = true;
}
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter ||
this->rest_iter != other.rest_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
iterator_deref<Container> operator*() {
return this->at_end ?
*this->rest_iter : *this->sub_iter;
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
std::begin(this->rest_chained)};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
std::end(this->rest_chained)};
}
};
template <typename Container>
class Chained<Container> {
friend class ChainMaker;
template <typename C, typename... RC>
friend class Chained;
private:
Container container;
Chained(Container container)
: container(std::forward<Container>(container))
{ }
public:
class Iterator
: public std::iterator<
std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
iterator_type<Container> sub_iter;
const iterator_type<Container> sub_end;
public:
Iterator(const iterator_type<Container>& s_begin,
const iterator_type<Container>& s_end)
: sub_iter{s_begin},
sub_end{s_end}
{ }
Iterator& operator++() {
++this->sub_iter;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
iterator_deref<Container> operator*() {
return *this->sub_iter;
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container)};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container)};
}
};
template <typename Container>
class ChainedFromIterable {
private:
Container container;
friend class ChainMaker;
ChainedFromIterable(Container container)
: container(std::forward<Container>(container))
{ }
public:
class Iterator
:public std::iterator<std::input_iterator_tag,
iterator_traits_deref<iterator_deref<Container>>>
{
private:
using SubContainer = iterator_deref<Container>;
using SubIter = iterator_type<SubContainer>;
iterator_type<Container> top_level_iter;
const iterator_type<Container> top_level_end;
std::unique_ptr<SubIter> sub_iter_p;
std::unique_ptr<SubIter> sub_end_p;
public:
Iterator(iterator_type<Container> top_iter,
iterator_type<Container> top_end)
: top_level_iter{top_iter},
top_level_end{top_end},
sub_iter_p{!(top_iter != top_end) ? // iter == end ?
nullptr : new SubIter{std::begin(*top_iter)}},
sub_end_p{!(top_iter != top_end) ? // iter == end ?
nullptr : new SubIter{std::end(*top_iter)}}
{ }
Iterator(const Iterator& other)
: top_level_iter{other.top_level_iter},
top_level_end{other.top_level_end},
sub_iter_p{other.sub_iter_p ?
new SubIter{*other.sub_iter_p} : nullptr},
sub_end_p{other.sub_end_p ?
new SubIter{*other.sub_end_p} : nullptr}
{ }
Iterator& operator++() {
++*this->sub_iter_p;
if (!(*this->sub_iter_p != *this->sub_end_p)) {
++this->top_level_iter;
if (this->top_level_iter != this->top_level_end) {
sub_iter_p.reset(
new SubIter{std::begin(*this->top_level_iter)});
sub_end_p.reset(
new SubIter{std::end(*this->top_level_iter)});
} else {
sub_iter_p.reset(nullptr);
sub_end_p.reset(nullptr);
}
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->top_level_iter != other.top_level_iter &&
(this->sub_iter_p != other.sub_iter_p ||
*this->sub_iter_p != *other.sub_iter_p);
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
iterator_deref<iterator_deref<Container>> operator*() {
return **this->sub_iter_p;
}
};
Iterator begin() {
return {std::begin(this->container), std::end(this->container)};
}
Iterator end() {
return {std::end(this->container), std::end(this->container)};
}
};
class ChainMaker {
public:
// expose regular call operator to provide usual chain()
template <typename... Containers>
Chained<Containers...> operator()(Containers&&... cs) const {
return {std::forward<Containers>(cs)...};
}
// chain.from_iterable
template <typename Container>
ChainedFromIterable<Container> from_iterable(
Container&& container) const {
return {std::forward<Container>(container)};
}
};
namespace {
constexpr auto chain = ChainMaker{};
}
}
#endif // #ifndef ITER_CHAIN_HPP_
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <fxdiv.h>
TEST(uint32_t, cases) {
EXPECT_EQ(UINT32_C(42) / UINT32_C(7),
fxdiv_quotient_uint32_t(UINT32_C(42),
fxdiv_init_uint32_t(UINT32_C(7))));
EXPECT_EQ(UINT32_C(42) / UINT32_C(6),
fxdiv_quotient_uint32_t(UINT32_C(42),
fxdiv_init_uint32_t(UINT32_C(6))));
EXPECT_EQ(UINT32_C(42) / UINT32_C(5),
fxdiv_quotient_uint32_t(UINT32_C(42),
fxdiv_init_uint32_t(UINT32_C(5))));
EXPECT_EQ(UINT32_C(1) / UINT32_C(1),
fxdiv_quotient_uint32_t(UINT32_C(1),
fxdiv_init_uint32_t(UINT32_C(1))));
EXPECT_EQ(UINT32_MAX / UINT32_C(1),
fxdiv_quotient_uint32_t(UINT32_MAX,
fxdiv_init_uint32_t(UINT32_C(1))));
EXPECT_EQ(UINT32_MAX / UINT32_MAX,
fxdiv_quotient_uint32_t(UINT32_MAX,
fxdiv_init_uint32_t(UINT32_MAX)));
EXPECT_EQ((UINT32_MAX - 1) / UINT32_MAX,
fxdiv_quotient_uint32_t(UINT32_MAX - 1,
fxdiv_init_uint32_t(UINT32_MAX)));
EXPECT_EQ(UINT32_MAX / (UINT32_MAX - 1),
fxdiv_quotient_uint32_t(UINT32_MAX,
fxdiv_init_uint32_t(UINT32_MAX - 1)));
EXPECT_EQ(UINT32_C(0) / UINT32_C(1),
fxdiv_quotient_uint32_t(UINT32_C(0),
fxdiv_init_uint32_t(UINT32_C(1))));
}
TEST(uint32_t, divide_by_1) {
const fxdiv_divisor_uint32_t d = fxdiv_init_uint32_t(UINT32_C(1));
const uint32_t step = UINT32_C(487);
for (uint32_t n = 0; n <= UINT32_MAX - step + 1; n += step) {
EXPECT_EQ(n, fxdiv_quotient_uint32_t(n, d));
}
}
TEST(uint32_t, divide_zero) {
const uint32_t step = UINT32_C(491);
for (uint32_t d = 1; d <= UINT32_MAX - step + 1; d += step) {
EXPECT_EQ(0,
fxdiv_quotient_uint32_t(0,
fxdiv_init_uint32_t(d)));
}
}
TEST(uint32_t, divide_by_n_minus_1) {
const uint32_t step = UINT32_C(523);
for (uint32_t n = 3; n <= UINT32_MAX - step + 1; n += step) {
EXPECT_EQ(UINT32_C(1),
fxdiv_quotient_uint32_t(n,
fxdiv_init_uint32_t(n - 1)));
}
}
TEST(uint32_t, divide_by_power_of_2) {
const uint32_t step = UINT32_C(25183);
for (uint32_t n = 0; n <= UINT32_MAX - step + 1; n += step) {
for (uint32_t p = 0; p < 32; p += 1) {
EXPECT_EQ(n >> p,
fxdiv_quotient_uint32_t(n,
fxdiv_init_uint32_t(UINT32_C(1) << p)));
}
}
}
TEST(uint32_t, match_native) {
const uint32_t stepD = UINT32_C(821603);
const uint32_t stepN = UINT32_C(821641);
for (uint32_t d = UINT32_MAX; d >= stepD; d -= stepD) {
const fxdiv_divisor_uint32_t divisor = fxdiv_init_uint32_t(d);
for (uint32_t n = UINT32_MAX; n >= stepN; n -= stepN) {
EXPECT_EQ(n / d, fxdiv_quotient_uint32_t(n, divisor));
}
}
}
TEST(uint64_t, cases) {
EXPECT_EQ(UINT64_C(42) / UINT64_C(7),
fxdiv_quotient_uint64_t(UINT64_C(42),
fxdiv_init_uint64_t(UINT64_C(7))));
EXPECT_EQ(UINT64_C(42) / UINT64_C(6),
fxdiv_quotient_uint64_t(UINT64_C(42),
fxdiv_init_uint64_t(UINT64_C(6))));
EXPECT_EQ(UINT64_C(42) / UINT64_C(5),
fxdiv_quotient_uint64_t(UINT64_C(42),
fxdiv_init_uint64_t(UINT64_C(5))));
EXPECT_EQ(UINT64_C(1) / UINT64_C(1),
fxdiv_quotient_uint64_t(UINT64_C(1),
fxdiv_init_uint64_t(UINT64_C(1))));
EXPECT_EQ(UINT64_MAX / UINT64_C(1),
fxdiv_quotient_uint64_t(UINT64_MAX,
fxdiv_init_uint64_t(UINT64_C(1))));
EXPECT_EQ(UINT64_MAX / UINT64_MAX,
fxdiv_quotient_uint64_t(UINT64_MAX,
fxdiv_init_uint64_t(UINT64_MAX)));
EXPECT_EQ((UINT64_MAX - 1) / UINT64_MAX,
fxdiv_quotient_uint64_t(UINT64_MAX - 1,
fxdiv_init_uint64_t(UINT64_MAX)));
EXPECT_EQ(UINT64_MAX / (UINT64_MAX - 1),
fxdiv_quotient_uint64_t(UINT64_MAX,
fxdiv_init_uint64_t(UINT64_MAX - 1)));
EXPECT_EQ(UINT64_C(0) / UINT64_C(1),
fxdiv_quotient_uint64_t(UINT64_C(0),
fxdiv_init_uint64_t(UINT64_C(1))));
}
TEST(uint64_t, divide_by_1) {
const fxdiv_divisor_uint64_t d = fxdiv_init_uint64_t(UINT64_C(1));
const uint64_t step = UINT64_C(2048116998241);
for (uint64_t n = 0; n <= UINT64_MAX - step + 1; n += step) {
EXPECT_EQ(n, fxdiv_quotient_uint64_t(n, d));
}
}
TEST(uint64_t, divide_zero) {
const uint64_t step = UINT64_C(8624419641811);
for (uint64_t d = 1; d <= UINT64_MAX - step + 1; d += step) {
EXPECT_EQ(0,
fxdiv_quotient_uint64_t(0,
fxdiv_init_uint64_t(d)));
}
}
TEST(uint64_t, divide_by_n_minus_1) {
const uint64_t step = UINT64_C(8624419641833);
for (uint64_t n = 3; n <= UINT64_MAX - step + 1; n += step) {
EXPECT_EQ(UINT64_C(1),
fxdiv_quotient_uint64_t(n,
fxdiv_init_uint64_t(n - 1)));
}
}
TEST(uint64_t, divide_by_power_of_2) {
const uint64_t step = UINT64_C(93400375993241);
for (uint64_t n = 0; n <= UINT64_MAX - step + 1; n += step) {
for (uint64_t p = 0; p < 32; p += 1) {
EXPECT_EQ(n >> p,
fxdiv_quotient_uint64_t(n,
fxdiv_init_uint64_t(UINT64_C(1) << p)));
}
}
}
TEST(uint64_t, match_native) {
const uint64_t stepD = UINT64_C(7093600525704701);
const uint64_t stepN = UINT64_C(7093600525704677);
for (uint64_t d = UINT64_MAX; d >= stepD; d -= stepD) {
const fxdiv_divisor_uint64_t divisor = fxdiv_init_uint64_t(d);
for (uint64_t n = UINT64_MAX; n >= stepN; n -= stepN) {
EXPECT_EQ(n / d, fxdiv_quotient_uint64_t(n, divisor));
}
}
}
TEST(size_t, cases) {
EXPECT_EQ(42 / 7,
fxdiv_quotient_size_t(42,
fxdiv_init_size_t(7)));
EXPECT_EQ(42 / 6,
fxdiv_quotient_size_t(42,
fxdiv_init_size_t(6)));
EXPECT_EQ(42 / 5,
fxdiv_quotient_size_t(42,
fxdiv_init_size_t(5)));
EXPECT_EQ(1 / 1,
fxdiv_quotient_size_t(1,
fxdiv_init_size_t(1)));
EXPECT_EQ(SIZE_MAX / 1,
fxdiv_quotient_size_t(SIZE_MAX,
fxdiv_init_size_t(1)));
EXPECT_EQ(SIZE_MAX / SIZE_MAX,
fxdiv_quotient_size_t(SIZE_MAX,
fxdiv_init_size_t(SIZE_MAX)));
EXPECT_EQ((SIZE_MAX - 1) / SIZE_MAX,
fxdiv_quotient_size_t(SIZE_MAX - 1,
fxdiv_init_size_t(SIZE_MAX)));
EXPECT_EQ(SIZE_MAX / (SIZE_MAX - 1),
fxdiv_quotient_size_t(SIZE_MAX,
fxdiv_init_size_t(SIZE_MAX - 1)));
EXPECT_EQ(0 / 1,
fxdiv_quotient_size_t(0,
fxdiv_init_size_t(1)));
}
<commit_msg>Test: optimize division by power-of-2 test<commit_after>#include <gtest/gtest.h>
#include <fxdiv.h>
TEST(uint32_t, cases) {
EXPECT_EQ(UINT32_C(42) / UINT32_C(7),
fxdiv_quotient_uint32_t(UINT32_C(42),
fxdiv_init_uint32_t(UINT32_C(7))));
EXPECT_EQ(UINT32_C(42) / UINT32_C(6),
fxdiv_quotient_uint32_t(UINT32_C(42),
fxdiv_init_uint32_t(UINT32_C(6))));
EXPECT_EQ(UINT32_C(42) / UINT32_C(5),
fxdiv_quotient_uint32_t(UINT32_C(42),
fxdiv_init_uint32_t(UINT32_C(5))));
EXPECT_EQ(UINT32_C(1) / UINT32_C(1),
fxdiv_quotient_uint32_t(UINT32_C(1),
fxdiv_init_uint32_t(UINT32_C(1))));
EXPECT_EQ(UINT32_MAX / UINT32_C(1),
fxdiv_quotient_uint32_t(UINT32_MAX,
fxdiv_init_uint32_t(UINT32_C(1))));
EXPECT_EQ(UINT32_MAX / UINT32_MAX,
fxdiv_quotient_uint32_t(UINT32_MAX,
fxdiv_init_uint32_t(UINT32_MAX)));
EXPECT_EQ((UINT32_MAX - 1) / UINT32_MAX,
fxdiv_quotient_uint32_t(UINT32_MAX - 1,
fxdiv_init_uint32_t(UINT32_MAX)));
EXPECT_EQ(UINT32_MAX / (UINT32_MAX - 1),
fxdiv_quotient_uint32_t(UINT32_MAX,
fxdiv_init_uint32_t(UINT32_MAX - 1)));
EXPECT_EQ(UINT32_C(0) / UINT32_C(1),
fxdiv_quotient_uint32_t(UINT32_C(0),
fxdiv_init_uint32_t(UINT32_C(1))));
}
TEST(uint32_t, divide_by_1) {
const fxdiv_divisor_uint32_t d = fxdiv_init_uint32_t(UINT32_C(1));
const uint32_t step = UINT32_C(487);
for (uint32_t n = 0; n <= UINT32_MAX - step + 1; n += step) {
EXPECT_EQ(n, fxdiv_quotient_uint32_t(n, d));
}
}
TEST(uint32_t, divide_zero) {
const uint32_t step = UINT32_C(491);
for (uint32_t d = 1; d <= UINT32_MAX - step + 1; d += step) {
EXPECT_EQ(0,
fxdiv_quotient_uint32_t(0,
fxdiv_init_uint32_t(d)));
}
}
TEST(uint32_t, divide_by_n_minus_1) {
const uint32_t step = UINT32_C(523);
for (uint32_t n = 3; n <= UINT32_MAX - step + 1; n += step) {
EXPECT_EQ(UINT32_C(1),
fxdiv_quotient_uint32_t(n,
fxdiv_init_uint32_t(n - 1)));
}
}
TEST(uint32_t, divide_by_power_of_2) {
const uint32_t step = UINT32_C(25183);
for (uint32_t p = 0; p < 32; p += 1) {
const fxdiv_divisor_uint32_t divisor =
fxdiv_init_uint32_t(UINT32_C(1) << p);
for (uint32_t n = 0; n <= UINT32_MAX - step + 1; n += step) {
EXPECT_EQ(n >> p, fxdiv_quotient_uint32_t(n, divisor));
}
}
}
TEST(uint32_t, match_native) {
const uint32_t stepD = UINT32_C(821603);
const uint32_t stepN = UINT32_C(821641);
for (uint32_t d = UINT32_MAX; d >= stepD; d -= stepD) {
const fxdiv_divisor_uint32_t divisor = fxdiv_init_uint32_t(d);
for (uint32_t n = UINT32_MAX; n >= stepN; n -= stepN) {
EXPECT_EQ(n / d, fxdiv_quotient_uint32_t(n, divisor));
}
}
}
TEST(uint64_t, cases) {
EXPECT_EQ(UINT64_C(42) / UINT64_C(7),
fxdiv_quotient_uint64_t(UINT64_C(42),
fxdiv_init_uint64_t(UINT64_C(7))));
EXPECT_EQ(UINT64_C(42) / UINT64_C(6),
fxdiv_quotient_uint64_t(UINT64_C(42),
fxdiv_init_uint64_t(UINT64_C(6))));
EXPECT_EQ(UINT64_C(42) / UINT64_C(5),
fxdiv_quotient_uint64_t(UINT64_C(42),
fxdiv_init_uint64_t(UINT64_C(5))));
EXPECT_EQ(UINT64_C(1) / UINT64_C(1),
fxdiv_quotient_uint64_t(UINT64_C(1),
fxdiv_init_uint64_t(UINT64_C(1))));
EXPECT_EQ(UINT64_MAX / UINT64_C(1),
fxdiv_quotient_uint64_t(UINT64_MAX,
fxdiv_init_uint64_t(UINT64_C(1))));
EXPECT_EQ(UINT64_MAX / UINT64_MAX,
fxdiv_quotient_uint64_t(UINT64_MAX,
fxdiv_init_uint64_t(UINT64_MAX)));
EXPECT_EQ((UINT64_MAX - 1) / UINT64_MAX,
fxdiv_quotient_uint64_t(UINT64_MAX - 1,
fxdiv_init_uint64_t(UINT64_MAX)));
EXPECT_EQ(UINT64_MAX / (UINT64_MAX - 1),
fxdiv_quotient_uint64_t(UINT64_MAX,
fxdiv_init_uint64_t(UINT64_MAX - 1)));
EXPECT_EQ(UINT64_C(0) / UINT64_C(1),
fxdiv_quotient_uint64_t(UINT64_C(0),
fxdiv_init_uint64_t(UINT64_C(1))));
}
TEST(uint64_t, divide_by_1) {
const fxdiv_divisor_uint64_t d = fxdiv_init_uint64_t(UINT64_C(1));
const uint64_t step = UINT64_C(2048116998241);
for (uint64_t n = 0; n <= UINT64_MAX - step + 1; n += step) {
EXPECT_EQ(n, fxdiv_quotient_uint64_t(n, d));
}
}
TEST(uint64_t, divide_zero) {
const uint64_t step = UINT64_C(8624419641811);
for (uint64_t d = 1; d <= UINT64_MAX - step + 1; d += step) {
EXPECT_EQ(0,
fxdiv_quotient_uint64_t(0,
fxdiv_init_uint64_t(d)));
}
}
TEST(uint64_t, divide_by_n_minus_1) {
const uint64_t step = UINT64_C(8624419641833);
for (uint64_t n = 3; n <= UINT64_MAX - step + 1; n += step) {
EXPECT_EQ(UINT64_C(1),
fxdiv_quotient_uint64_t(n,
fxdiv_init_uint64_t(n - 1)));
}
}
TEST(uint64_t, divide_by_power_of_2) {
const uint64_t step = UINT64_C(93400375993241);
for (uint64_t p = 0; p < 64; p += 1) {
const fxdiv_divisor_uint64_t divisor =
fxdiv_init_uint64_t(UINT64_C(1) << p);
for (uint64_t n = 0; n <= UINT64_MAX - step + 1; n += step) {
EXPECT_EQ(n >> p, fxdiv_quotient_uint64_t(n, divisor));
}
}
}
TEST(uint64_t, match_native) {
const uint64_t stepD = UINT64_C(7093600525704701);
const uint64_t stepN = UINT64_C(7093600525704677);
for (uint64_t d = UINT64_MAX; d >= stepD; d -= stepD) {
const fxdiv_divisor_uint64_t divisor = fxdiv_init_uint64_t(d);
for (uint64_t n = UINT64_MAX; n >= stepN; n -= stepN) {
EXPECT_EQ(n / d, fxdiv_quotient_uint64_t(n, divisor));
}
}
}
TEST(size_t, cases) {
EXPECT_EQ(42 / 7,
fxdiv_quotient_size_t(42,
fxdiv_init_size_t(7)));
EXPECT_EQ(42 / 6,
fxdiv_quotient_size_t(42,
fxdiv_init_size_t(6)));
EXPECT_EQ(42 / 5,
fxdiv_quotient_size_t(42,
fxdiv_init_size_t(5)));
EXPECT_EQ(1 / 1,
fxdiv_quotient_size_t(1,
fxdiv_init_size_t(1)));
EXPECT_EQ(SIZE_MAX / 1,
fxdiv_quotient_size_t(SIZE_MAX,
fxdiv_init_size_t(1)));
EXPECT_EQ(SIZE_MAX / SIZE_MAX,
fxdiv_quotient_size_t(SIZE_MAX,
fxdiv_init_size_t(SIZE_MAX)));
EXPECT_EQ((SIZE_MAX - 1) / SIZE_MAX,
fxdiv_quotient_size_t(SIZE_MAX - 1,
fxdiv_init_size_t(SIZE_MAX)));
EXPECT_EQ(SIZE_MAX / (SIZE_MAX - 1),
fxdiv_quotient_size_t(SIZE_MAX,
fxdiv_init_size_t(SIZE_MAX - 1)));
EXPECT_EQ(0 / 1,
fxdiv_quotient_size_t(0,
fxdiv_init_size_t(1)));
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: htmlnum.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-08-14 17:05:11 $
*
* 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 _HTMLNUM_HXX
#define _HTMLNUM_HXX
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#include <string.h>
#define HTML_NUMBUL_MARGINLEFT (MM50*2 + MM50/2)
#define HTML_NUMBUL_INDENT (-MM50)
class SwTxtNode;
class SwNumRule;
class SwHTMLNumRuleInfo
{
sal_uInt16 aNumStarts[MAXLEVEL];
SwNumRule * pNumRule; // Aktuelle Numerierung
sal_uInt16 nDeep; // aktuelle Num-Tiefe (1, 2, 3, ...)
sal_Bool bRestart : 1; // Export: Numerierung neu starten
sal_Bool bNumbered : 1; // Export: Absatz ist numeriert
public:
inline void Set( const SwHTMLNumRuleInfo& rInf );
void Set( const SwTxtNode& rTxtNd );
SwHTMLNumRuleInfo() :
pNumRule( 0 ), nDeep( 0 ),
bRestart( sal_False ), bNumbered( sal_False )
{
memset( &aNumStarts, 0xff, sizeof( aNumStarts ) );
}
SwHTMLNumRuleInfo( const SwHTMLNumRuleInfo& rInf ) :
pNumRule( rInf.pNumRule ), nDeep( rInf.nDeep ),
bRestart( rInf.bRestart ), bNumbered( rInf.bNumbered )
{
memcpy( &aNumStarts, &rInf.aNumStarts, sizeof( aNumStarts ) );
}
SwHTMLNumRuleInfo( const SwTxtNode& rTxtNd ) { Set( rTxtNd ); }
inline SwHTMLNumRuleInfo& operator=( const SwHTMLNumRuleInfo& rInf );
inline void Clear();
void SetNumRule( const SwNumRule *pRule ) { pNumRule = (SwNumRule *)pRule; }
SwNumRule *GetNumRule() { return pNumRule; }
const SwNumRule *GetNumRule() const { return pNumRule; }
void SetDepth( sal_uInt16 nDepth ) { nDeep = nDepth; }
sal_uInt16 GetDepth() const { return nDeep; }
sal_uInt16 IncDepth() { return ++nDeep; }
sal_uInt16 DecDepth() { return nDeep==0 ? 0 : --nDeep; }
inline sal_uInt8 GetLevel() const;
void SetRestart( sal_Bool bSet ) { bRestart = bSet; }
sal_Bool IsRestart() const { return bRestart; }
void SetNumbered( sal_Bool bSet ) { bNumbered = bSet; }
sal_Bool IsNumbered() const { return bNumbered; }
inline void SetNodeStartValue( sal_uInt8 nLvl, sal_uInt16 nVal=USHRT_MAX );
sal_uInt16 GetNodeStartValue( sal_uInt8 nLvl ) const { return aNumStarts[nLvl]; }
};
inline SwHTMLNumRuleInfo& SwHTMLNumRuleInfo::operator=(
const SwHTMLNumRuleInfo& rInf )
{
Set( rInf );
return *this;
}
inline void SwHTMLNumRuleInfo::Set( const SwHTMLNumRuleInfo& rInf )
{
pNumRule = rInf.pNumRule;
nDeep = rInf.nDeep;
bRestart = rInf.bRestart;
bNumbered = rInf.bNumbered;
memcpy( &aNumStarts, &rInf.aNumStarts, sizeof( aNumStarts ) );
}
inline void SwHTMLNumRuleInfo::Clear()
{
pNumRule = 0;
nDeep = 0;
bRestart = bNumbered = sal_False;
memset( &aNumStarts, 0xff, sizeof( aNumStarts ) );
}
inline sal_uInt8 SwHTMLNumRuleInfo::GetLevel() const
{
return
(sal_uInt8)( pNumRule!=0 && nDeep != 0
? ( nDeep<=MAXLEVEL ? nDeep-1 : MAXLEVEL - 1 )
: 0 );
}
inline void SwHTMLNumRuleInfo::SetNodeStartValue( sal_uInt8 nLvl, sal_uInt16 nVal )
{
aNumStarts[nLvl] = nVal;
}
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.738); FILE MERGED 2008/04/01 12:54:40 thb 1.3.738.2: #i85898# Stripping all external header guards 2008/03/31 16:55:31 rt 1.3.738.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: htmlnum.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _HTMLNUM_HXX
#define _HTMLNUM_HXX
#include <swtypes.hxx>
#include <string.h>
#define HTML_NUMBUL_MARGINLEFT (MM50*2 + MM50/2)
#define HTML_NUMBUL_INDENT (-MM50)
class SwTxtNode;
class SwNumRule;
class SwHTMLNumRuleInfo
{
sal_uInt16 aNumStarts[MAXLEVEL];
SwNumRule * pNumRule; // Aktuelle Numerierung
sal_uInt16 nDeep; // aktuelle Num-Tiefe (1, 2, 3, ...)
sal_Bool bRestart : 1; // Export: Numerierung neu starten
sal_Bool bNumbered : 1; // Export: Absatz ist numeriert
public:
inline void Set( const SwHTMLNumRuleInfo& rInf );
void Set( const SwTxtNode& rTxtNd );
SwHTMLNumRuleInfo() :
pNumRule( 0 ), nDeep( 0 ),
bRestart( sal_False ), bNumbered( sal_False )
{
memset( &aNumStarts, 0xff, sizeof( aNumStarts ) );
}
SwHTMLNumRuleInfo( const SwHTMLNumRuleInfo& rInf ) :
pNumRule( rInf.pNumRule ), nDeep( rInf.nDeep ),
bRestart( rInf.bRestart ), bNumbered( rInf.bNumbered )
{
memcpy( &aNumStarts, &rInf.aNumStarts, sizeof( aNumStarts ) );
}
SwHTMLNumRuleInfo( const SwTxtNode& rTxtNd ) { Set( rTxtNd ); }
inline SwHTMLNumRuleInfo& operator=( const SwHTMLNumRuleInfo& rInf );
inline void Clear();
void SetNumRule( const SwNumRule *pRule ) { pNumRule = (SwNumRule *)pRule; }
SwNumRule *GetNumRule() { return pNumRule; }
const SwNumRule *GetNumRule() const { return pNumRule; }
void SetDepth( sal_uInt16 nDepth ) { nDeep = nDepth; }
sal_uInt16 GetDepth() const { return nDeep; }
sal_uInt16 IncDepth() { return ++nDeep; }
sal_uInt16 DecDepth() { return nDeep==0 ? 0 : --nDeep; }
inline sal_uInt8 GetLevel() const;
void SetRestart( sal_Bool bSet ) { bRestart = bSet; }
sal_Bool IsRestart() const { return bRestart; }
void SetNumbered( sal_Bool bSet ) { bNumbered = bSet; }
sal_Bool IsNumbered() const { return bNumbered; }
inline void SetNodeStartValue( sal_uInt8 nLvl, sal_uInt16 nVal=USHRT_MAX );
sal_uInt16 GetNodeStartValue( sal_uInt8 nLvl ) const { return aNumStarts[nLvl]; }
};
inline SwHTMLNumRuleInfo& SwHTMLNumRuleInfo::operator=(
const SwHTMLNumRuleInfo& rInf )
{
Set( rInf );
return *this;
}
inline void SwHTMLNumRuleInfo::Set( const SwHTMLNumRuleInfo& rInf )
{
pNumRule = rInf.pNumRule;
nDeep = rInf.nDeep;
bRestart = rInf.bRestart;
bNumbered = rInf.bNumbered;
memcpy( &aNumStarts, &rInf.aNumStarts, sizeof( aNumStarts ) );
}
inline void SwHTMLNumRuleInfo::Clear()
{
pNumRule = 0;
nDeep = 0;
bRestart = bNumbered = sal_False;
memset( &aNumStarts, 0xff, sizeof( aNumStarts ) );
}
inline sal_uInt8 SwHTMLNumRuleInfo::GetLevel() const
{
return
(sal_uInt8)( pNumRule!=0 && nDeep != 0
? ( nDeep<=MAXLEVEL ? nDeep-1 : MAXLEVEL - 1 )
: 0 );
}
inline void SwHTMLNumRuleInfo::SetNodeStartValue( sal_uInt8 nLvl, sal_uInt16 nVal )
{
aNumStarts[nLvl] = nVal;
}
#endif
<|endoftext|> |
<commit_before>#include <valhalla/baldr/signinfo.h>
#include "test.h"
#include "mjolnir/graphbuilder.h"
using namespace std;
using namespace valhalla::mjolnir;
using valhalla::mjolnir::GraphBuilder;
namespace {
class test_graph_builder : public GraphBuilder {
public:
using GraphBuilder::CreateExitSignInfoList;
};
void ExitToTest() {
uint64_t osmnodeid = 1;
Node node;
OSMWay way;
std::unordered_map<uint64_t, std::string> map_ref;
std::unordered_map<uint64_t, std::string> map_name;
std::unordered_map<uint64_t, std::string> map_exit_to;
node.set_exit_to(true);
map_exit_to[osmnodeid] = "US 11;To I 81;Carlisle;Harrisburg";
std::vector<SignInfo> exitsigns;
exitsigns = test_graph_builder::CreateExitSignInfoList(osmnodeid, node, way, map_ref, map_name, map_exit_to);
if (exitsigns.size() == 4) {
for (auto& exitsign : exitsigns) {
if (exitsign.type() != Sign::Type::kExitToward)
throw std::runtime_error("US 11;To I 81;Carlisle;Harrisburg types are not all Toward");
}
if (exitsigns[0].text() != "US 11" && exitsigns[1].text() != "I 81" &&
exitsigns[2].text() != "Carlisle" && exitsigns[3].text() != "Harrisburg")
throw std::runtime_error("Exitsign text is bad for US 11;To I 81;Carlisle;Harrisburg.");
}
else throw std::runtime_error("US 11/To I 81/Carlisle/Harrisburg failed to be parsed. " + exitsigns.size() );
exitsigns.clear();
map_exit_to[osmnodeid] = "US 11;Toward I 81;Carlisle;Harrisburg";
exitsigns = test_graph_builder::CreateExitSignInfoList(osmnodeid, node, way, map_ref, map_name, map_exit_to);
if (exitsigns.size() == 4) {
for (auto& exitsign : exitsigns) {
if (exitsign.type() != Sign::Type::kExitToward)
throw std::runtime_error("US 11;Toward I 81;Carlisle;Harrisburg types are not all Toward");
}
if (exitsigns[0].text() != "US 11" && exitsigns[1].text() != "I 81" &&
exitsigns[2].text() != "Carlisle" && exitsigns[3].text() != "Harrisburg")
throw std::runtime_error("Exitsign text is bad for US 11;To I 81;Carlisle;Harrisburg.");
}
else throw std::runtime_error("US 11;Toward I 81;Carlisle;Harrisburg failed to be parsed.");
exitsigns.clear();
map_exit_to[osmnodeid] = "I 95 To I 695";
exitsigns = test_graph_builder::CreateExitSignInfoList(osmnodeid, node, way, map_ref, map_name, map_exit_to);
if (exitsigns.size() == 2) {
if (exitsigns[0].type() != Sign::Type::kExitBranch)
throw std::runtime_error("I 95 should be a branch.");
if (exitsigns[1].type() != Sign::Type::kExitToward)
throw std::runtime_error("I 695 should be a toward.");
if (exitsigns[0].text() != "I 95" && exitsigns[1].text() != "I 695")
throw std::runtime_error("Exitsign text is bad for I 95 To I 695");
}
else throw std::runtime_error("I 95 To I 695 failed to be parsed.");
exitsigns.clear();
map_exit_to[osmnodeid] = "I 495 Toward I 270";
exitsigns = test_graph_builder::CreateExitSignInfoList(osmnodeid, node, way, map_ref, map_name, map_exit_to);
if (exitsigns.size() == 2) {
if (exitsigns[0].type() != Sign::Type::kExitBranch)
throw std::runtime_error("I 495 should be a branch.");
if (exitsigns[1].type() != Sign::Type::kExitToward)
throw std::runtime_error("I 270 should be a toward.");
if (exitsigns[0].text() != "I 495" && exitsigns[1].text() != "I 270")
throw std::runtime_error("Exitsign text is bad for I 495 Toward I 270");
}
else throw std::runtime_error("I 495 Toward I 270 failed to be parsed.");
exitsigns.clear();
map_exit_to[osmnodeid] = "I 495 Toward I 270 To I 95";//default to toward. Punt on parsing.
exitsigns = test_graph_builder::CreateExitSignInfoList(osmnodeid, node, way, map_ref, map_name, map_exit_to);
if (exitsigns.size() == 1) {
if (exitsigns[0].type() != Sign::Type::kExitToward)
throw std::runtime_error("I 495 Toward I 270 To I 95 should be a toward.");
if (exitsigns[0].text() != "I 495 Toward I 270 To I 95")
throw std::runtime_error("Exitsign text is bad for I 495 Toward I 270 To I 95");
}
else throw std::runtime_error("I 495 Toward I 270 To I 95 failed to be parsed.");
}
}
int main() {
test::suite suite("signinfo");
// Test exit to logic.
suite.test(TEST_CASE(ExitToTest));
return suite.tear_down();
}
<commit_msg>fixed the test.<commit_after>#include <valhalla/baldr/signinfo.h>
#include <valhalla/mjolnir/uniquenames.h>
#include "test.h"
#include "mjolnir/graphbuilder.h"
using namespace std;
using namespace valhalla::mjolnir;
using valhalla::mjolnir::GraphBuilder;
namespace {
class test_graph_builder : public GraphBuilder {
public:
using GraphBuilder::CreateExitSignInfoList;
};
void ExitToTest() {
uint64_t osmnodeid = 1;
Node node;
OSMWay way;
std::unordered_map<uint64_t, std::string> map_ref;
std::unordered_map<uint64_t, std::string> map_name;
std::unordered_map<uint64_t, std::string> map_exit_to;
UniqueNames uniquenames;
node.set_exit_to(true);
map_exit_to[osmnodeid] = "US 11;To I 81;Carlisle;Harrisburg";
std::vector<SignInfo> exitsigns;
exitsigns = test_graph_builder::CreateExitSignInfoList(osmnodeid, node, way, map_ref, map_name, map_exit_to, uniquenames, uniquenames);
if (exitsigns.size() == 4) {
for (auto& exitsign : exitsigns) {
if (exitsign.type() != Sign::Type::kExitToward)
throw std::runtime_error("US 11;To I 81;Carlisle;Harrisburg types are not all Toward");
}
if (exitsigns[0].text() != "US 11" && exitsigns[1].text() != "I 81" &&
exitsigns[2].text() != "Carlisle" && exitsigns[3].text() != "Harrisburg")
throw std::runtime_error("Exitsign text is bad for US 11;To I 81;Carlisle;Harrisburg.");
}
else throw std::runtime_error("US 11/To I 81/Carlisle/Harrisburg failed to be parsed. " + exitsigns.size() );
exitsigns.clear();
map_exit_to[osmnodeid] = "US 11;Toward I 81;Carlisle;Harrisburg";
exitsigns = test_graph_builder::CreateExitSignInfoList(osmnodeid, node, way, map_ref, map_name, map_exit_to, uniquenames, uniquenames);
if (exitsigns.size() == 4) {
for (auto& exitsign : exitsigns) {
if (exitsign.type() != Sign::Type::kExitToward)
throw std::runtime_error("US 11;Toward I 81;Carlisle;Harrisburg types are not all Toward");
}
if (exitsigns[0].text() != "US 11" && exitsigns[1].text() != "I 81" &&
exitsigns[2].text() != "Carlisle" && exitsigns[3].text() != "Harrisburg")
throw std::runtime_error("Exitsign text is bad for US 11;To I 81;Carlisle;Harrisburg.");
}
else throw std::runtime_error("US 11;Toward I 81;Carlisle;Harrisburg failed to be parsed.");
exitsigns.clear();
map_exit_to[osmnodeid] = "I 95 To I 695";
exitsigns = test_graph_builder::CreateExitSignInfoList(osmnodeid, node, way, map_ref, map_name, map_exit_to, uniquenames, uniquenames);
if (exitsigns.size() == 2) {
if (exitsigns[0].type() != Sign::Type::kExitBranch)
throw std::runtime_error("I 95 should be a branch.");
if (exitsigns[1].type() != Sign::Type::kExitToward)
throw std::runtime_error("I 695 should be a toward.");
if (exitsigns[0].text() != "I 95" && exitsigns[1].text() != "I 695")
throw std::runtime_error("Exitsign text is bad for I 95 To I 695");
}
else throw std::runtime_error("I 95 To I 695 failed to be parsed.");
exitsigns.clear();
map_exit_to[osmnodeid] = "I 495 Toward I 270";
exitsigns = test_graph_builder::CreateExitSignInfoList(osmnodeid, node, way, map_ref, map_name, map_exit_to, uniquenames, uniquenames);
if (exitsigns.size() == 2) {
if (exitsigns[0].type() != Sign::Type::kExitBranch)
throw std::runtime_error("I 495 should be a branch.");
if (exitsigns[1].type() != Sign::Type::kExitToward)
throw std::runtime_error("I 270 should be a toward.");
if (exitsigns[0].text() != "I 495" && exitsigns[1].text() != "I 270")
throw std::runtime_error("Exitsign text is bad for I 495 Toward I 270");
}
else throw std::runtime_error("I 495 Toward I 270 failed to be parsed.");
exitsigns.clear();
map_exit_to[osmnodeid] = "I 495 Toward I 270 To I 95";//default to toward. Punt on parsing.
exitsigns = test_graph_builder::CreateExitSignInfoList(osmnodeid, node, way, map_ref, map_name, map_exit_to, uniquenames, uniquenames);
if (exitsigns.size() == 1) {
if (exitsigns[0].type() != Sign::Type::kExitToward)
throw std::runtime_error("I 495 Toward I 270 To I 95 should be a toward.");
if (exitsigns[0].text() != "I 495 Toward I 270 To I 95")
throw std::runtime_error("Exitsign text is bad for I 495 Toward I 270 To I 95");
}
else throw std::runtime_error("I 495 Toward I 270 To I 95 failed to be parsed.");
}
}
int main() {
test::suite suite("signinfo");
// Test exit to logic.
suite.test(TEST_CASE(ExitToTest));
return suite.tear_down();
}
<|endoftext|> |
<commit_before>#include "common.th"
#define nop a <- a;
#define SPI_BASE 0x200
b <- 0
b -> [(SPI_BASE + 0x14)] // set divider
// data
b <- [reloff(IDLE_COMMAND, 1)]
b -> [(SPI_BASE + 0x0)] // bits 0 - 31
b <- [reloff(IDLE_COMMAND, 0)]
b -> [(SPI_BASE + 0x4)] // bits 32 - 47
b <- (48 + 8) // message length + response length
//b <- b | (1 << 11) // LSB mode
d <- 1
d <- d << 13
b <- b | d // ASS mode
b -> [(SPI_BASE + 0x10)]
c <- 1
c -> [(SPI_BASE + 0x18)] // set SS to 1
// GO_BSY
b <- b | (1 << 8)
b -> [(SPI_BASE + 0x10)]
d <- 50 # wait count
loop:
d <- d - 1
e <- d <> 0
jnzrel(e,loop)
b <- [(SPI_BASE + 0x0)] // read data
c <- [(SPI_BASE + 0x4)] // read data
illegal
IDLE_COMMAND: // includes response ones
.word 0x400000, 0x000001ff
<commit_msg>Cosmetics using new underscored literals<commit_after>#include "common.th"
#define nop a <- a;
#define SPI_BASE 0x200
b <- 0
b -> [(SPI_BASE + 0x14)] // set divider
// data
b <- [reloff(IDLE_COMMAND, 1)]
b -> [(SPI_BASE + 0x0)] // bits 0 - 31
b <- [reloff(IDLE_COMMAND, 0)]
b -> [(SPI_BASE + 0x4)] // bits 32 - 47
b <- (48 + 8) // message length + response length
//b <- b | (1 << 11) // LSB mode
d <- 1
d <- d << 13
b <- b | d // ASS mode
b -> [(SPI_BASE + 0x10)]
c <- 1
c -> [(SPI_BASE + 0x18)] // set SS to 1
// GO_BSY
b <- b | (1 << 8)
b -> [(SPI_BASE + 0x10)]
d <- 50 # wait count
loop:
d <- d - 1
e <- d <> 0
jnzrel(e,loop)
c <- [(SPI_BASE + 0x0)] // read data
b <- [(SPI_BASE + 0x4)] // read data
illegal
IDLE_COMMAND:
/* 01 |cmd-| |cmd-argument------ ------------------| |CRC--| 1 |rsp ---| */
.word 0b01__000000__0000_0000_0000_0000, 0b0000_0000_0000_0000__0000000_1___1111_1111
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmliteme.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: rt $ $Date: 2005-09-09 06:23:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#include <hintids.hxx>
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _SHL_HXX //autogen wg. SHL_WRITER
#include <tools/shl.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _XMLITMPR_HXX
#include "xmlexpit.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLTABE_HXX
#include <xmloff/xmltabe.hxx>
#endif
#ifndef _XMLBRSHE_HXX
#include "xmlbrshe.hxx"
#endif
#ifndef _SVX_TSPTITEM_HXX
#include <svx/tstpitem.hxx>
#endif
#ifndef _SVX_BRSHITEM_HXX
#include <svx/brshitem.hxx>
#endif
#ifndef _SVX_UNOMID_HXX
#include <svx/unomid.hxx>
#endif
#ifndef _VCL_FLDUNIT_HXX
#include <vcl/fldunit.hxx>
#endif
#ifndef _SWMODULE_HXX //autogen wg. SW_MOD
#include <swmodule.hxx>
#endif
#ifndef _DOC_HXX //autogen wg. SwDoc
#include <doc.hxx>
#endif
#ifndef _FMTORNT_HXX
#include "fmtornt.hxx"
#endif
#ifndef _UNOMID_H
#include <unomid.h>
#endif
#ifndef _FRMFMT_HXX
#include "frmfmt.hxx"
#endif
#ifndef _FMTFSIZE_HXX
#include "fmtfsize.hxx"
#endif
#ifndef _SWRECT_HXX
#include "swrect.hxx"
#endif
#ifndef _XMLEXP_HXX
#include "xmlexp.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::xmloff::token;
extern SvXMLItemMapEntry aXMLTableItemMap[];
extern SvXMLItemMapEntry aXMLTableRowItemMap[];
extern SvXMLItemMapEntry aXMLTableCellItemMap[];
class SwXMLTableItemMapper_Impl: public SvXMLExportItemMapper
{
SwXMLBrushItemExport aBrushItemExport;
protected:
sal_uInt32 nAbsWidth;
void AddAttribute( sal_uInt16 nPrefix, enum XMLTokenEnum eLName,
const OUString& rValue,
const SvXMLNamespaceMap& rNamespaceMap,
SvXMLAttributeList& rAttrList ) const;
public:
SwXMLTableItemMapper_Impl(
SvXMLItemMapEntriesRef rMapEntries,
SwXMLExport& rExp );
virtual ~SwXMLTableItemMapper_Impl();
virtual void handleSpecialItem( SvXMLAttributeList& rAttrList,
const SvXMLItemMapEntry& rEntry,
const SfxPoolItem& rItem,
const SvXMLUnitConverter& rUnitConverter,
const SvXMLNamespaceMap& rNamespaceMap,
const SfxItemSet *pSet = NULL ) const;
virtual void handleElementItem(
SvXMLExport& rExport,
const SvXMLItemMapEntry& rEntry,
const SfxPoolItem& rItem,
const SvXMLUnitConverter& rUnitConverter,
const SfxItemSet& rSet,
sal_uInt16 nFlags ) const;
inline void SetAbsWidth( sal_uInt32 nAbs );
};
SwXMLTableItemMapper_Impl::SwXMLTableItemMapper_Impl(
SvXMLItemMapEntriesRef rMapEntries,
SwXMLExport& rExp ) :
SvXMLExportItemMapper( rMapEntries ),
aBrushItemExport( rExp ),
nAbsWidth( USHRT_MAX )
{
}
SwXMLTableItemMapper_Impl::~SwXMLTableItemMapper_Impl()
{
}
void SwXMLTableItemMapper_Impl::AddAttribute( sal_uInt16 nPrefix,
enum XMLTokenEnum eLName,
const OUString& rValue,
const SvXMLNamespaceMap& rNamespaceMap,
SvXMLAttributeList& rAttrList ) const
{
OUString sName( rNamespaceMap.GetQNameByKey( nPrefix,
GetXMLToken(eLName) ) );
rAttrList.AddAttribute( sName, rValue );
}
void SwXMLTableItemMapper_Impl::handleSpecialItem(
SvXMLAttributeList& rAttrList,
const SvXMLItemMapEntry& rEntry,
const SfxPoolItem& rItem,
const SvXMLUnitConverter& rUnitConverter,
const SvXMLNamespaceMap& rNamespaceMap,
const SfxItemSet *pSet ) const
{
switch( rEntry.nWhichId )
{
case RES_LR_SPACE:
{
const SfxPoolItem *pItem;
if( pSet &&
SFX_ITEM_SET == pSet->GetItemState( RES_HORI_ORIENT, sal_True,
&pItem ) )
{
SwHoriOrient eHoriOrient =
((const SwFmtHoriOrient *)pItem)->GetHoriOrient();
sal_Bool bExport = sal_False;
sal_uInt16 nMemberId =
static_cast<sal_uInt16>( rEntry.nMemberId & MID_SW_FLAG_MASK );
switch( nMemberId )
{
case MID_L_MARGIN:
bExport = HORI_NONE == eHoriOrient ||
HORI_LEFT_AND_WIDTH == eHoriOrient;
break;
case MID_R_MARGIN:
bExport = HORI_NONE == eHoriOrient;
break;
}
OUString sValue;
if( bExport && SvXMLExportItemMapper::QueryXMLValue(
rItem, sValue, nMemberId, rUnitConverter ) )
{
AddAttribute( rEntry.nNameSpace, rEntry.eLocalName, sValue,
rNamespaceMap, rAttrList );
}
}
}
break;
case RES_FRM_SIZE:
{
sal_uInt16 nMemberId =
static_cast<sal_uInt16>( rEntry.nMemberId & MID_SW_FLAG_MASK );
switch( nMemberId )
{
case MID_FRMSIZE_WIDTH:
if( nAbsWidth )
{
OUStringBuffer sBuffer;
rUnitConverter.convertMeasure( sBuffer, nAbsWidth );
AddAttribute( rEntry.nNameSpace, rEntry.eLocalName,
sBuffer.makeStringAndClear(),
rNamespaceMap, rAttrList );
}
break;
case MID_FRMSIZE_REL_WIDTH:
{
OUString sValue;
if( SvXMLExportItemMapper::QueryXMLValue(
rItem, sValue, nMemberId, rUnitConverter ) )
{
AddAttribute( rEntry.nNameSpace, rEntry.eLocalName,
sValue, rNamespaceMap, rAttrList );
}
}
break;
}
}
break;
}
}
/** this method is called for every item that has the
MID_SW_FLAG_ELEMENT_EXPORT flag set */
void SwXMLTableItemMapper_Impl::handleElementItem(
SvXMLExport& rExport,
const SvXMLItemMapEntry& rEntry,
const SfxPoolItem& rItem,
const SvXMLUnitConverter& rUnitConverter,
const SfxItemSet&,
sal_uInt16 ) const
{
switch( rEntry.nWhichId )
{
case RES_BACKGROUND:
{
((SwXMLTableItemMapper_Impl *)this)->aBrushItemExport.exportXML(
(const SvxBrushItem&)rItem );
}
break;
}
}
inline void SwXMLTableItemMapper_Impl::SetAbsWidth( sal_uInt32 nAbs )
{
nAbsWidth = nAbs;
}
// ----------------------------------------------------------------------------
void SwXMLExport::_InitItemExport()
{
// #110680#
pTwipUnitConv = new SvXMLUnitConverter( MAP_TWIP,
GetMM100UnitConverter().getXMLMeasureUnit(), getServiceFactory() );
xTableItemMap = new SvXMLItemMapEntries( aXMLTableItemMap );
xTableRowItemMap = new SvXMLItemMapEntries( aXMLTableRowItemMap );
xTableCellItemMap = new SvXMLItemMapEntries( aXMLTableCellItemMap );
pTableItemMapper = new SwXMLTableItemMapper_Impl( xTableItemMap, *this );
}
void SwXMLExport::_FinitItemExport()
{
delete pTableItemMapper;
delete pTwipUnitConv;
}
void SwXMLExport::ExportTableFmt( const SwFrmFmt& rFmt, sal_uInt32 nAbsWidth )
{
((SwXMLTableItemMapper_Impl *)pTableItemMapper)
->SetAbsWidth( nAbsWidth );
ExportFmt( rFmt, XML_TABLE );
}
<commit_msg>INTEGRATION: CWS writercorehandoff (1.13.140); FILE MERGED 2005/09/13 15:47:39 tra 1.13.140.3: RESYNC: (1.13-1.14); FILE MERGED 2005/06/07 14:15:15 fme 1.13.140.2: #i50348# General cleanup - removed unused header files, functions, members, declarations etc. 2005/06/06 09:29:06 tra 1.13.140.1: Unnecessary includes removed #i50348#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmliteme.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: hr $ $Date: 2006-08-14 17:23:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#include <hintids.hxx>
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _SHL_HXX //autogen wg. SHL_WRITER
#include <tools/shl.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _XMLITMPR_HXX
#include "xmlexpit.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLTABE_HXX
#include <xmloff/xmltabe.hxx>
#endif
#ifndef _XMLBRSHE_HXX
#include "xmlbrshe.hxx"
#endif
#ifndef _SVX_TSPTITEM_HXX
#include <svx/tstpitem.hxx>
#endif
#ifndef _SVX_BRSHITEM_HXX
#include <svx/brshitem.hxx>
#endif
#ifndef _VCL_FLDUNIT_HXX
#include <vcl/fldunit.hxx>
#endif
#ifndef _SWMODULE_HXX //autogen wg. SW_MOD
#include <swmodule.hxx>
#endif
#ifndef _DOC_HXX //autogen wg. SwDoc
#include <doc.hxx>
#endif
#ifndef _FMTORNT_HXX
#include "fmtornt.hxx"
#endif
#ifndef _UNOMID_H
#include <unomid.h>
#endif
#ifndef _FRMFMT_HXX
#include "frmfmt.hxx"
#endif
#ifndef _FMTFSIZE_HXX
#include "fmtfsize.hxx"
#endif
#ifndef _SWRECT_HXX
#include "swrect.hxx"
#endif
#ifndef _XMLEXP_HXX
#include "xmlexp.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::xmloff::token;
extern SvXMLItemMapEntry aXMLTableItemMap[];
extern SvXMLItemMapEntry aXMLTableRowItemMap[];
extern SvXMLItemMapEntry aXMLTableCellItemMap[];
class SwXMLTableItemMapper_Impl: public SvXMLExportItemMapper
{
SwXMLBrushItemExport aBrushItemExport;
protected:
sal_uInt32 nAbsWidth;
void AddAttribute( sal_uInt16 nPrefix, enum XMLTokenEnum eLName,
const OUString& rValue,
const SvXMLNamespaceMap& rNamespaceMap,
SvXMLAttributeList& rAttrList ) const;
public:
SwXMLTableItemMapper_Impl(
SvXMLItemMapEntriesRef rMapEntries,
SwXMLExport& rExp );
virtual ~SwXMLTableItemMapper_Impl();
virtual void handleSpecialItem( SvXMLAttributeList& rAttrList,
const SvXMLItemMapEntry& rEntry,
const SfxPoolItem& rItem,
const SvXMLUnitConverter& rUnitConverter,
const SvXMLNamespaceMap& rNamespaceMap,
const SfxItemSet *pSet = NULL ) const;
virtual void handleElementItem(
SvXMLExport& rExport,
const SvXMLItemMapEntry& rEntry,
const SfxPoolItem& rItem,
const SvXMLUnitConverter& rUnitConverter,
const SfxItemSet& rSet,
sal_uInt16 nFlags ) const;
inline void SetAbsWidth( sal_uInt32 nAbs );
};
SwXMLTableItemMapper_Impl::SwXMLTableItemMapper_Impl(
SvXMLItemMapEntriesRef rMapEntries,
SwXMLExport& rExp ) :
SvXMLExportItemMapper( rMapEntries ),
aBrushItemExport( rExp ),
nAbsWidth( USHRT_MAX )
{
}
SwXMLTableItemMapper_Impl::~SwXMLTableItemMapper_Impl()
{
}
void SwXMLTableItemMapper_Impl::AddAttribute( sal_uInt16 nPrefix,
enum XMLTokenEnum eLName,
const OUString& rValue,
const SvXMLNamespaceMap& rNamespaceMap,
SvXMLAttributeList& rAttrList ) const
{
OUString sName( rNamespaceMap.GetQNameByKey( nPrefix,
GetXMLToken(eLName) ) );
rAttrList.AddAttribute( sName, rValue );
}
void SwXMLTableItemMapper_Impl::handleSpecialItem(
SvXMLAttributeList& rAttrList,
const SvXMLItemMapEntry& rEntry,
const SfxPoolItem& rItem,
const SvXMLUnitConverter& rUnitConverter,
const SvXMLNamespaceMap& rNamespaceMap,
const SfxItemSet *pSet ) const
{
switch( rEntry.nWhichId )
{
case RES_LR_SPACE:
{
const SfxPoolItem *pItem;
if( pSet &&
SFX_ITEM_SET == pSet->GetItemState( RES_HORI_ORIENT, sal_True,
&pItem ) )
{
SwHoriOrient eHoriOrient =
((const SwFmtHoriOrient *)pItem)->GetHoriOrient();
sal_Bool bExport = sal_False;
sal_uInt16 nMemberId =
static_cast<sal_uInt16>( rEntry.nMemberId & MID_SW_FLAG_MASK );
switch( nMemberId )
{
case MID_L_MARGIN:
bExport = HORI_NONE == eHoriOrient ||
HORI_LEFT_AND_WIDTH == eHoriOrient;
break;
case MID_R_MARGIN:
bExport = HORI_NONE == eHoriOrient;
break;
}
OUString sValue;
if( bExport && SvXMLExportItemMapper::QueryXMLValue(
rItem, sValue, nMemberId, rUnitConverter ) )
{
AddAttribute( rEntry.nNameSpace, rEntry.eLocalName, sValue,
rNamespaceMap, rAttrList );
}
}
}
break;
case RES_FRM_SIZE:
{
sal_uInt16 nMemberId =
static_cast<sal_uInt16>( rEntry.nMemberId & MID_SW_FLAG_MASK );
switch( nMemberId )
{
case MID_FRMSIZE_WIDTH:
if( nAbsWidth )
{
OUStringBuffer sBuffer;
rUnitConverter.convertMeasure( sBuffer, nAbsWidth );
AddAttribute( rEntry.nNameSpace, rEntry.eLocalName,
sBuffer.makeStringAndClear(),
rNamespaceMap, rAttrList );
}
break;
case MID_FRMSIZE_REL_WIDTH:
{
OUString sValue;
if( SvXMLExportItemMapper::QueryXMLValue(
rItem, sValue, nMemberId, rUnitConverter ) )
{
AddAttribute( rEntry.nNameSpace, rEntry.eLocalName,
sValue, rNamespaceMap, rAttrList );
}
}
break;
}
}
break;
}
}
/** this method is called for every item that has the
MID_SW_FLAG_ELEMENT_EXPORT flag set */
void SwXMLTableItemMapper_Impl::handleElementItem(
SvXMLExport& rExport,
const SvXMLItemMapEntry& rEntry,
const SfxPoolItem& rItem,
const SvXMLUnitConverter& rUnitConverter,
const SfxItemSet&,
sal_uInt16 ) const
{
switch( rEntry.nWhichId )
{
case RES_BACKGROUND:
{
((SwXMLTableItemMapper_Impl *)this)->aBrushItemExport.exportXML(
(const SvxBrushItem&)rItem );
}
break;
}
}
inline void SwXMLTableItemMapper_Impl::SetAbsWidth( sal_uInt32 nAbs )
{
nAbsWidth = nAbs;
}
// ----------------------------------------------------------------------------
void SwXMLExport::_InitItemExport()
{
// #110680#
pTwipUnitConv = new SvXMLUnitConverter( MAP_TWIP,
GetMM100UnitConverter().getXMLMeasureUnit(), getServiceFactory() );
xTableItemMap = new SvXMLItemMapEntries( aXMLTableItemMap );
xTableRowItemMap = new SvXMLItemMapEntries( aXMLTableRowItemMap );
xTableCellItemMap = new SvXMLItemMapEntries( aXMLTableCellItemMap );
pTableItemMapper = new SwXMLTableItemMapper_Impl( xTableItemMap, *this );
}
void SwXMLExport::_FinitItemExport()
{
delete pTableItemMapper;
delete pTwipUnitConv;
}
void SwXMLExport::ExportTableFmt( const SwFrmFmt& rFmt, sal_uInt32 nAbsWidth )
{
((SwXMLTableItemMapper_Impl *)pTableItemMapper)
->SetAbsWidth( nAbsWidth );
ExportFmt( rFmt, XML_TABLE );
}
<|endoftext|> |
<commit_before>#include "Actor.hpp"
#define LOG_GL
#include "glerr.hpp"
Actor::Actor(std::shared_ptr<RenderModel> model)
: m_orientation(glm::quat(1.0f, 0.0f, 0.0f, 0.0f))
, m_position(glm::vec4(0.0f, 0.0f, 0.0f, 0.0f))
, m_forward(glm::vec4(0.0f, 0.0f, -1.0f, 0.0f))
, m_up(glm::vec4(0.0f, 1.0f, 0.0f, 0.0f))
, m_left(glm::vec4(-1.0f, 0.0f, 0.0f, 0.0f))
, m_renderModel(model) {}
/*Actor::Actor(const Actor& original)
: m_orientation(original.m_orientation)
, m_position(original.m_position)
, m_forward(original.m_forward)
, m_up(original.m_up)
, m_left(original.m_left)
, m_renderModel(original.m_renderModel) {}*/
Actor::~Actor() {}
/**
* Translates the actor along its personal axes
*
* @param [in] longitude Number of units along the actor's forward/backward axis to translate by
* @param [in] latitude Number of units along the actor's left/right axis to translate by
* @param [in] altitude Number of units along the actor's up/down axis to translate by
*/
void Actor::translate(float longitude, float latitude, float altitude) {
glm::vec4 longVec = m_forward * longitude;
glm::vec4 latVec = m_left * latitude;
glm::vec4 altVec = m_up * altitude;
m_position += longVec + latVec + altVec;
}
/**
* Rotates the actor around its personal axes
*
* @param [in] roll Number of degrees around the forward/backward axis to rotate by
* @param [in] pitch Number of degrees around the left/right axis to rotate by
* @param [in] yaw Number of degrees around the up/dawn axis to rotate by
*/
void Actor::rotate(float roll, float pitch, float yaw) {
glm::quat rotationQuat(glm::vec3(pitch, yaw, roll));
m_orientation *= rotationQuat;
glm::vec4 canonicalForward(0.0f, 0.0f, -1.0f, 0.0f);
glm::vec4 canonicalUp(0.0f, 1.0f, 0.0f, 0.0f);
glm::vec4 canonicalLeft(-1.0f, 0.0f, 0.0f, 0.0f);
glm::mat4 orientationMatrix = glm::mat4_cast(m_orientation);
m_forward = orientationMatrix * canonicalForward;
m_up = orientationMatrix * canonicalUp;
m_left = orientationMatrix * canonicalLeft;
}
/**
* Called once per cycle. By default does nothing, but can be overriden to
* progress animations, respond to collisions, etc.
*
* TODO: Needs to take time since last cycle as input
* TODO: Allow user definition via scripting
*/
// void Actor::update() {}
/* Draws the actor's render model to the active frame buffer
*
* @param [in] viewMatrix The matrix used to transform the model respective to a camera's viewpoint
* @param [in] projectionMatrix The matrix used to project the model from 3D/4D world space to 2D screen space
*/
void Actor::draw(Shader& shader) {
if(m_renderModel == nullptr) return;
glm::mat4 rotationMatrix = glm::mat4_cast(m_orientation);
glm::mat4 translationMatrix =
glm::translate(glm::mat4(), glm::vec3(m_position));
glm::mat4 modelMatrix = translationMatrix * rotationMatrix;
shader.setModelMatrix(modelMatrix);
glLogErr("Uploading model matrix");
shader.updateNormalMatrix();
glLogErr("Uploading normal matrix");
m_renderModel->draw(shader);
glLogErr("drawing render model");
}
/*
* Directly sets the actor's orientation, overriding any previous values.
*
* @param [in] deg Number of degrees to rotate about the axis specified by paramaters x, y, and z
* @param [in] x x component of the 3D axis about which the actor will be rotated
* @param [in] y y component of the 3D axis about which the actor will be rotated
* @param [in] z z component of the 3D axis about which the actor will be rotated
*/
void Actor::setOrientation(float deg, float x, float y, float z) {
m_orientation = glm::quat(deg, x, y, z);
}
/*
* Directly sets the actor's position, overriding any previous values.
*
* @param [in] x Absolute x position in world space
* @param [in] y Absolute y position in world space
* @param [in] z Absolute z position in world space
*/
void Actor::setPosition(float x, float y, float z) {
m_position = glm::vec4(x, y, z, 0);
}
<commit_msg>Remove commented-out copy constructor<commit_after>#include "Actor.hpp"
#define LOG_GL
#include "glerr.hpp"
Actor::Actor(std::shared_ptr<RenderModel> model)
: m_orientation(glm::quat(1.0f, 0.0f, 0.0f, 0.0f))
, m_position(glm::vec4(0.0f, 0.0f, 0.0f, 0.0f))
, m_forward(glm::vec4(0.0f, 0.0f, -1.0f, 0.0f))
, m_up(glm::vec4(0.0f, 1.0f, 0.0f, 0.0f))
, m_left(glm::vec4(-1.0f, 0.0f, 0.0f, 0.0f))
, m_renderModel(model) {}
Actor::~Actor() {}
/**
* Translates the actor along its personal axes
*
* @param [in] longitude Number of units along the actor's forward/backward axis to translate by
* @param [in] latitude Number of units along the actor's left/right axis to translate by
* @param [in] altitude Number of units along the actor's up/down axis to translate by
*/
void Actor::translate(float longitude, float latitude, float altitude) {
glm::vec4 longVec = m_forward * longitude;
glm::vec4 latVec = m_left * latitude;
glm::vec4 altVec = m_up * altitude;
m_position += longVec + latVec + altVec;
}
/**
* Rotates the actor around its personal axes
*
* @param [in] roll Number of degrees around the forward/backward axis to rotate by
* @param [in] pitch Number of degrees around the left/right axis to rotate by
* @param [in] yaw Number of degrees around the up/dawn axis to rotate by
*/
void Actor::rotate(float roll, float pitch, float yaw) {
glm::quat rotationQuat(glm::vec3(pitch, yaw, roll));
m_orientation *= rotationQuat;
glm::vec4 canonicalForward(0.0f, 0.0f, -1.0f, 0.0f);
glm::vec4 canonicalUp(0.0f, 1.0f, 0.0f, 0.0f);
glm::vec4 canonicalLeft(-1.0f, 0.0f, 0.0f, 0.0f);
glm::mat4 orientationMatrix = glm::mat4_cast(m_orientation);
m_forward = orientationMatrix * canonicalForward;
m_up = orientationMatrix * canonicalUp;
m_left = orientationMatrix * canonicalLeft;
}
/**
* Called once per cycle. By default does nothing, but can be overriden to
* progress animations, respond to collisions, etc.
*
* TODO: Needs to take time since last cycle as input
* TODO: Allow user definition via scripting
*/
// void Actor::update() {}
/* Draws the actor's render model to the active frame buffer
*
* @param [in] viewMatrix The matrix used to transform the model respective to a camera's viewpoint
* @param [in] projectionMatrix The matrix used to project the model from 3D/4D world space to 2D screen space
*/
void Actor::draw(Shader& shader) {
if(m_renderModel == nullptr) return;
glm::mat4 rotationMatrix = glm::mat4_cast(m_orientation);
glm::mat4 translationMatrix =
glm::translate(glm::mat4(), glm::vec3(m_position));
glm::mat4 modelMatrix = translationMatrix * rotationMatrix;
shader.setModelMatrix(modelMatrix);
glLogErr("Uploading model matrix");
shader.updateNormalMatrix();
glLogErr("Uploading normal matrix");
m_renderModel->draw(shader);
glLogErr("drawing render model");
}
/*
* Directly sets the actor's orientation, overriding any previous values.
*
* @param [in] deg Number of degrees to rotate about the axis specified by paramaters x, y, and z
* @param [in] x x component of the 3D axis about which the actor will be rotated
* @param [in] y y component of the 3D axis about which the actor will be rotated
* @param [in] z z component of the 3D axis about which the actor will be rotated
*/
void Actor::setOrientation(float deg, float x, float y, float z) {
m_orientation = glm::quat(deg, x, y, z);
}
/*
* Directly sets the actor's position, overriding any previous values.
*
* @param [in] x Absolute x position in world space
* @param [in] y Absolute y position in world space
* @param [in] z Absolute z position in world space
*/
void Actor::setPosition(float x, float y, float z) {
m_position = glm::vec4(x, y, z, 0);
}
<|endoftext|> |
<commit_before>#include "Audio.h"
std::recursive_mutex Audio :: m_Mutex;
float Audio :: s_Rolloff = 1.0f;
float Audio :: s_MaxDist = 2048.0f;
float Audio :: s_ReferenceDist = 256.0f;
Audio::Buffer :: Buffer(){
auto l = Audio::lock();
alGenBuffers(1, &id);
}
Audio::Buffer :: Buffer(const std::string& fn, ICache* c) {
auto l = Audio::lock();
Audio::check_errors();
id = alutCreateBufferFromFile(fn.c_str());
Audio::check_errors();
}
Audio::Buffer :: Buffer(const std::tuple<std::string, ICache*>& args):
Buffer(std::get<0>(args), std::get<1>(args))
{}
Audio::Buffer :: ~Buffer() {
if(id){
auto l = Audio::lock();
Audio::check_errors();
alDeleteBuffers(1, &id);
Audio::check_errors();
}
}
float Audio::Buffer :: length() const
{
assert(id > 0);
ALint sz;
ALint channels;
ALint bits;
ALint freq;
alGetBufferi(id, AL_SIZE, &sz);
alGetBufferi(id, AL_CHANNELS, &channels);
alGetBufferi(id, AL_BITS, &bits);
alGetBufferi(id, AL_FREQUENCY, &freq);
unsigned samples = sz * 8 / (channels * bits);
return (float)samples / (float)freq;
}
Audio::Source :: Source(
unsigned int _flags
):
flags(_flags)
{
auto l = Audio::lock();
alGenSources(1, &id);
if(flags & F_AUTOPLAY){
play();
}
}
Audio::Source :: ~Source() {
auto l = Audio::lock();
stop();
Audio::check_errors();
alDeleteSources(1, &id);
Audio::check_errors();
}
bool Audio::Source :: update() {
return false;
//return kit::make_future<bool>(false);
}
void Audio::Source :: bind(Buffer* buf) {
auto l = Audio::lock();
alSourcei(id, AL_BUFFER, buf ? buf->id : 0);
}
void Audio::Source :: refresh() {
if(!buffer_id)
return;
auto l = Audio::lock();
alSourcei(id, AL_BUFFER, buffer_id);
alSourcef(id, AL_PITCH, pitch);
alSourcef(id, AL_GAIN, kit::clamp<float>(gain, 0.0f, 1.0f - K_EPSILON));
alSourcefv(id, AL_POSITION, glm::value_ptr(pos));
alSourcefv(id, AL_VELOCITY, glm::value_ptr(vel));
alSourcef(id, AL_ROLLOFF_FACTOR, 1.0f);
alSourcef(id, AL_MAX_DISTANCE, 2048.0f);
alSourcef(id, AL_REFERENCE_DISTANCE, 256.0f);
alSourcei(id, AL_LOOPING, (flags & F_LOOP) ? AL_TRUE : AL_FALSE);
}
void Audio::Source :: play() {
auto l = Audio::lock();
refresh();
alSourcePlay(id);
}
bool Audio::Source :: playing() const {
auto l = Audio::lock();
ALint state;
alGetSourcei(id, AL_SOURCE_STATE, &state);
//LOGf("state: %s", state)
return state == AL_PLAYING;
}
bool Audio::Source :: stopped() const {
auto l = Audio::lock();
ALint state;
alGetSourcei(id, AL_SOURCE_STATE, &state);
//LOGf("state: %s", state)
return state == AL_STOPPED;
}
//bool initial() const {
// auto l = Audio::lock();
// ALint state;
// alGetSourcei(id, AL_SOURCE_STATE, &state);
// return state == AL_INITIAL;
//}
void Audio::Source :: pause() {
auto l = Audio::lock();
alSourcePause(id);
}
void Audio::Source :: stop() {
auto l = Audio::lock();
if(playing())
alSourceStop(id);
}
Audio::Stream :: ~Stream()
{
auto l = Audio::lock();
stop();
clear();
alDeleteBuffers(2, m_Buffers);
ov_clear(&m_Ogg);
}
bool Audio::Stream :: update()
{
auto l = Audio::lock();
clear_errors();
int processed;
bool active = true;
alGetSourcei(id, AL_BUFFERS_PROCESSED, &processed);
while(processed--)
{
ALuint buffer;
alSourceUnqueueBuffers(id, 1, &buffer);
Audio::check_errors();
active = stream(buffer);
if(active) {
alSourceQueueBuffers(id, 1, &buffer);
Audio::check_errors();
}
}
return active;
}
void Audio::Stream :: clear()
{
auto l = Audio::lock();
Audio::check_errors();
int queued;
alGetSourcei(id, AL_BUFFERS_QUEUED, &queued);
while(queued--)
{
ALuint buffer;
alSourceUnqueueBuffers(id, 1, &buffer);
if(Audio::check_errors())
break;
}
}
void Audio::Stream :: refresh()
{
//if(playing())
//{
auto l = Audio::lock();
clear_errors();
update();
alSourcei(id, AL_BUFFER, buffer_id);
alSourcef(id, AL_PITCH, pitch);
alSourcef(id, AL_GAIN, kit::clamp<float>(gain, 0.0f, 1.0f - K_EPSILON));
alSourcefv(id, AL_POSITION, glm::value_ptr(pos));
alSourcefv(id, AL_VELOCITY, glm::value_ptr(vel));
//alSourcefv(id, AL_DIRECTION, glm::value_ptr(velT));
alSourcef(id, AL_ROLLOFF_FACTOR, m_Rolloff);
alSourcef(id, AL_MAX_DISTANCE, m_MaxDist);
alSourcef(id, AL_REFERENCE_DISTANCE, m_ReferenceDist);
//alSourcei(id, AL_LOOPING, (flags & F_LOOP) ? AL_TRUE : AL_FALSE);
//}
}
void Audio::Stream :: play()
{
auto l = Audio::lock();
if(playing())
return;
if(!stream(m_Buffers[0]))
return;
if(!stream(m_Buffers[1]))
return;
alSourceQueueBuffers(id, 2, m_Buffers);
alSourcePlay(id);
}
bool Audio::Stream :: stream(unsigned int buffer)
{
auto l = Audio::lock();
char data[BUFFER_SIZE];
int size = 0;
int endian = 0;
int section;
int result;
while(size < BUFFER_SIZE)
{
result = ov_read(&m_Ogg, data + size, BUFFER_SIZE - size, endian, 2, 1, §ion);
if((flags & Source::F_LOOP) && !result)
ov_raw_seek(&m_Ogg, 0);
if(result > 0)
size += result;
else
{
if(result < 0)
return false;
else
break;
}
}
if(size == 0)
return false;
alBufferData(buffer, m_Format, data, size, m_VorbisInfo->rate);
return true;
}
Audio::Listener :: Listener()
{
gain = 1.0f;
pos = glm::vec3(0.0f, 0.0f, 0.0f);
vel = glm::vec3(0.0f, 0.0f, 0.0f);
at = glm::vec3(0.0f, 0.0f, -1.0f);
up = glm::vec3(0.0f, -1.0f, 0.0f);
}
Audio::Listener :: ~Listener() {}
void Audio::Listener :: listen()
{
auto l = Audio::lock();
alListenerf(AL_GAIN, kit::clamp<float>(gain, 0.0f, 1.0f - K_EPSILON));
alListenerfv(AL_POSITION, glm::value_ptr(pos));
alListenerfv(AL_VELOCITY, glm::value_ptr(vel));
float ori[6];
ori[0] = at.x; ori[1] = at.y; ori[2] = at.z;
ori[3] = up.x; ori[4] = up.y; ori[5] = up.z;
alListenerfv(AL_ORIENTATION, ori);
}
Audio :: Audio()
{
auto l = lock();
//alutInit(0, NULL);
alutInitWithoutContext(0, NULL);
m_pDevice = alcOpenDevice(NULL);
if(not m_pDevice)
throw std::runtime_error("failed to open OpenAL audio device");
m_pContext = alcCreateContext(m_pDevice, NULL);
if(not m_pContext)
alcCloseDevice(m_pDevice);
try{
set_context();
}catch(...){
alcDestroyContext(m_pContext);
alcCloseDevice(m_pDevice);
throw;
}
}
Audio::Stream :: Stream(std::string fn):
m_Filename(fn)
{
auto l = Audio::lock();
// clear errors
clear_errors();
int r;
if((r = ov_fopen((char*)&fn[0], &m_Ogg)) < 0)
ERROR(READ, Filesystem::getFileName(fn));
if(check_errors())
ERROR(READ, Filesystem::getFileName(fn));
m_VorbisInfo = ov_info(&m_Ogg, -1);
m_VorbisComment = ov_comment(&m_Ogg, -1);
if(check_errors())
ERROR(READ, Filesystem::getFileName(fn));
if(m_VorbisInfo->channels == 1)
m_Format = AL_FORMAT_MONO16;
else
m_Format = AL_FORMAT_STEREO16;
alGenBuffers(2, m_Buffers);
if(check_errors())
ERROR(READ, Filesystem::getFileName(fn));
flags |= Source::F_LOOP;
//std::cout
// << "version " << m_VorbisInfo->version << "\n"
// << "channels " << m_VorbisInfo->channels << "\n"
// << "rate (hz) " << m_VorbisInfo->rate << "\n"
// << "bitrate upper " << m_VorbisInfo->bitrate_upper << "\n"
// << "bitrate nominal " << m_VorbisInfo->bitrate_nominal << "\n"
// << "bitrate lower " << m_VorbisInfo->bitrate_lower << "\n"
// << "bitrate window " << m_VorbisInfo->bitrate_window << "\n"
// << "\n"
// << "vendor " << m_VorbisComment->vendor << "\n";
//for(int i = 0; i < m_VorbisComment->comments; i++)
// std::cout << " " << m_VorbisComment->user_comments[i] << "\n";
//std::cout << std::endl;
m_bOpen = true;
}
Audio :: ~Audio()
{
auto l = lock();
alcDestroyContext(m_pContext);
alcCloseDevice(m_pDevice);
alutExit();
}
void Audio :: set_context()
{
auto l = Audio::lock();
if(not alcMakeContextCurrent(m_pContext))
throw std::runtime_error("failed to set OpenAL Context");
clear_errors();
}
void Audio :: listen(Listener* listener) const
{
if(listener)
listener->listen();
}
bool Audio :: error() const
{
auto l = Audio::lock();
return alGetError();
}
void Audio :: clear_errors()
{
auto l = Audio::lock();
alGetError();
}
bool Audio :: check_errors()
{
int error = alGetError();
if(error != AL_NO_ERROR) {
std::tuple<std::string, std::string> errpair = error_string_al(error);
WARNINGf("OpenAL Error (%s): %s",
std::get<0>(errpair) % std::get<1>(errpair)
);
return true;
}
return false;
}
std::tuple<std::string, std::string> Audio :: error_string_al(int code)
{
switch(code)
{
case AL_INVALID_NAME:
return std::make_tuple("AL_INVALID_NAME", "Invalid name.");
case AL_INVALID_ENUM:
return std::make_tuple("AL_INVALID_ENUM", "Invalid enum.");
case AL_INVALID_VALUE:
return std::make_tuple("AL_INVALID_VALUE", "Invalid value.");
case AL_INVALID_OPERATION:
return std::make_tuple("AL_INVALID_OPERATION", "Invalid operation.");
case AL_OUT_OF_MEMORY:
return std::make_tuple("AL_OUT_OF_MEMORY", "Out of memory.");
}
return (code!=AL_NO_ERROR) ?
std::tuple<std::string,std::string>(std::string(), std::string("No Error.")):
std::tuple<std::string,std::string>(
boost::to_string(code),
std::string("Unknown Error Code")
);
}
std::tuple<std::string,std::string> Audio :: error_string_ov(int code)
{
switch(code)
{
// libvorbis return codes http://www.xiph.org/vorbis/doc/libvorbis/return.html
case OV_EREAD:
return std::make_tuple("OC_EREAD","Read from media.");
case OV_ENOTVORBIS:
return std::make_tuple("OC_ENOTVORBIS","Not Vorbis data.");
case OV_EVERSION:
return std::make_tuple("OV_EVERSION", "Vorbis version mismatch.");
case OV_EBADHEADER:
return std::make_tuple("OV_EBADHEADER", "Invalid Vorbis header.");
case OV_EFAULT:
return std::make_tuple("OV_EFAULT", "Internal logic fault (bug or heap/stack corruption.");
}
return code ?
std::tuple<std::string,std::string>(
boost::to_string(code),
std::string("Unknown Error Code ") + boost::to_string(code)
):
std::tuple<std::string,std::string>("","No Error.");
}
<commit_msg>m_ -> s_<commit_after>#include "Audio.h"
std::recursive_mutex Audio :: m_Mutex;
float Audio :: s_Rolloff = 1.0f;
float Audio :: s_MaxDist = 2048.0f;
float Audio :: s_ReferenceDist = 256.0f;
Audio::Buffer :: Buffer(){
auto l = Audio::lock();
alGenBuffers(1, &id);
}
Audio::Buffer :: Buffer(const std::string& fn, ICache* c) {
auto l = Audio::lock();
Audio::check_errors();
id = alutCreateBufferFromFile(fn.c_str());
Audio::check_errors();
}
Audio::Buffer :: Buffer(const std::tuple<std::string, ICache*>& args):
Buffer(std::get<0>(args), std::get<1>(args))
{}
Audio::Buffer :: ~Buffer() {
if(id){
auto l = Audio::lock();
Audio::check_errors();
alDeleteBuffers(1, &id);
Audio::check_errors();
}
}
float Audio::Buffer :: length() const
{
assert(id > 0);
ALint sz;
ALint channels;
ALint bits;
ALint freq;
alGetBufferi(id, AL_SIZE, &sz);
alGetBufferi(id, AL_CHANNELS, &channels);
alGetBufferi(id, AL_BITS, &bits);
alGetBufferi(id, AL_FREQUENCY, &freq);
unsigned samples = sz * 8 / (channels * bits);
return (float)samples / (float)freq;
}
Audio::Source :: Source(
unsigned int _flags
):
flags(_flags)
{
auto l = Audio::lock();
alGenSources(1, &id);
if(flags & F_AUTOPLAY){
play();
}
}
Audio::Source :: ~Source() {
auto l = Audio::lock();
stop();
Audio::check_errors();
alDeleteSources(1, &id);
Audio::check_errors();
}
bool Audio::Source :: update() {
return false;
//return kit::make_future<bool>(false);
}
void Audio::Source :: bind(Buffer* buf) {
auto l = Audio::lock();
alSourcei(id, AL_BUFFER, buf ? buf->id : 0);
}
void Audio::Source :: refresh() {
if(!buffer_id)
return;
auto l = Audio::lock();
alSourcei(id, AL_BUFFER, buffer_id);
alSourcef(id, AL_PITCH, pitch);
alSourcef(id, AL_GAIN, kit::clamp<float>(gain, 0.0f, 1.0f - K_EPSILON));
alSourcefv(id, AL_POSITION, glm::value_ptr(pos));
alSourcefv(id, AL_VELOCITY, glm::value_ptr(vel));
alSourcef(id, AL_ROLLOFF_FACTOR, 1.0f);
alSourcef(id, AL_MAX_DISTANCE, 2048.0f);
alSourcef(id, AL_REFERENCE_DISTANCE, 256.0f);
alSourcei(id, AL_LOOPING, (flags & F_LOOP) ? AL_TRUE : AL_FALSE);
}
void Audio::Source :: play() {
auto l = Audio::lock();
refresh();
alSourcePlay(id);
}
bool Audio::Source :: playing() const {
auto l = Audio::lock();
ALint state;
alGetSourcei(id, AL_SOURCE_STATE, &state);
//LOGf("state: %s", state)
return state == AL_PLAYING;
}
bool Audio::Source :: stopped() const {
auto l = Audio::lock();
ALint state;
alGetSourcei(id, AL_SOURCE_STATE, &state);
//LOGf("state: %s", state)
return state == AL_STOPPED;
}
//bool initial() const {
// auto l = Audio::lock();
// ALint state;
// alGetSourcei(id, AL_SOURCE_STATE, &state);
// return state == AL_INITIAL;
//}
void Audio::Source :: pause() {
auto l = Audio::lock();
alSourcePause(id);
}
void Audio::Source :: stop() {
auto l = Audio::lock();
if(playing())
alSourceStop(id);
}
Audio::Stream :: ~Stream()
{
auto l = Audio::lock();
stop();
clear();
alDeleteBuffers(2, m_Buffers);
ov_clear(&m_Ogg);
}
bool Audio::Stream :: update()
{
auto l = Audio::lock();
clear_errors();
int processed;
bool active = true;
alGetSourcei(id, AL_BUFFERS_PROCESSED, &processed);
while(processed--)
{
ALuint buffer;
alSourceUnqueueBuffers(id, 1, &buffer);
Audio::check_errors();
active = stream(buffer);
if(active) {
alSourceQueueBuffers(id, 1, &buffer);
Audio::check_errors();
}
}
return active;
}
void Audio::Stream :: clear()
{
auto l = Audio::lock();
Audio::check_errors();
int queued;
alGetSourcei(id, AL_BUFFERS_QUEUED, &queued);
while(queued--)
{
ALuint buffer;
alSourceUnqueueBuffers(id, 1, &buffer);
if(Audio::check_errors())
break;
}
}
void Audio::Stream :: refresh()
{
//if(playing())
//{
auto l = Audio::lock();
clear_errors();
update();
alSourcei(id, AL_BUFFER, buffer_id);
alSourcef(id, AL_PITCH, pitch);
alSourcef(id, AL_GAIN, kit::clamp<float>(gain, 0.0f, 1.0f - K_EPSILON));
alSourcefv(id, AL_POSITION, glm::value_ptr(pos));
alSourcefv(id, AL_VELOCITY, glm::value_ptr(vel));
//alSourcefv(id, AL_DIRECTION, glm::value_ptr(velT));
alSourcef(id, AL_ROLLOFF_FACTOR, s_Rolloff);
alSourcef(id, AL_MAX_DISTANCE, s_MaxDist);
alSourcef(id, AL_REFERENCE_DISTANCE, s_ReferenceDist);
//alSourcei(id, AL_LOOPING, (flags & F_LOOP) ? AL_TRUE : AL_FALSE);
//}
}
void Audio::Stream :: play()
{
auto l = Audio::lock();
if(playing())
return;
if(!stream(m_Buffers[0]))
return;
if(!stream(m_Buffers[1]))
return;
alSourceQueueBuffers(id, 2, m_Buffers);
alSourcePlay(id);
}
bool Audio::Stream :: stream(unsigned int buffer)
{
auto l = Audio::lock();
char data[BUFFER_SIZE];
int size = 0;
int endian = 0;
int section;
int result;
while(size < BUFFER_SIZE)
{
result = ov_read(&m_Ogg, data + size, BUFFER_SIZE - size, endian, 2, 1, §ion);
if((flags & Source::F_LOOP) && !result)
ov_raw_seek(&m_Ogg, 0);
if(result > 0)
size += result;
else
{
if(result < 0)
return false;
else
break;
}
}
if(size == 0)
return false;
alBufferData(buffer, m_Format, data, size, m_VorbisInfo->rate);
return true;
}
Audio::Listener :: Listener()
{
gain = 1.0f;
pos = glm::vec3(0.0f, 0.0f, 0.0f);
vel = glm::vec3(0.0f, 0.0f, 0.0f);
at = glm::vec3(0.0f, 0.0f, -1.0f);
up = glm::vec3(0.0f, -1.0f, 0.0f);
}
Audio::Listener :: ~Listener() {}
void Audio::Listener :: listen()
{
auto l = Audio::lock();
alListenerf(AL_GAIN, kit::clamp<float>(gain, 0.0f, 1.0f - K_EPSILON));
alListenerfv(AL_POSITION, glm::value_ptr(pos));
alListenerfv(AL_VELOCITY, glm::value_ptr(vel));
float ori[6];
ori[0] = at.x; ori[1] = at.y; ori[2] = at.z;
ori[3] = up.x; ori[4] = up.y; ori[5] = up.z;
alListenerfv(AL_ORIENTATION, ori);
}
Audio :: Audio()
{
auto l = lock();
//alutInit(0, NULL);
alutInitWithoutContext(0, NULL);
m_pDevice = alcOpenDevice(NULL);
if(not m_pDevice)
throw std::runtime_error("failed to open OpenAL audio device");
m_pContext = alcCreateContext(m_pDevice, NULL);
if(not m_pContext)
alcCloseDevice(m_pDevice);
try{
set_context();
}catch(...){
alcDestroyContext(m_pContext);
alcCloseDevice(m_pDevice);
throw;
}
}
Audio::Stream :: Stream(std::string fn):
m_Filename(fn)
{
auto l = Audio::lock();
// clear errors
clear_errors();
int r;
if((r = ov_fopen((char*)&fn[0], &m_Ogg)) < 0)
ERROR(READ, Filesystem::getFileName(fn));
if(check_errors())
ERROR(READ, Filesystem::getFileName(fn));
m_VorbisInfo = ov_info(&m_Ogg, -1);
m_VorbisComment = ov_comment(&m_Ogg, -1);
if(check_errors())
ERROR(READ, Filesystem::getFileName(fn));
if(m_VorbisInfo->channels == 1)
m_Format = AL_FORMAT_MONO16;
else
m_Format = AL_FORMAT_STEREO16;
alGenBuffers(2, m_Buffers);
if(check_errors())
ERROR(READ, Filesystem::getFileName(fn));
flags |= Source::F_LOOP;
//std::cout
// << "version " << m_VorbisInfo->version << "\n"
// << "channels " << m_VorbisInfo->channels << "\n"
// << "rate (hz) " << m_VorbisInfo->rate << "\n"
// << "bitrate upper " << m_VorbisInfo->bitrate_upper << "\n"
// << "bitrate nominal " << m_VorbisInfo->bitrate_nominal << "\n"
// << "bitrate lower " << m_VorbisInfo->bitrate_lower << "\n"
// << "bitrate window " << m_VorbisInfo->bitrate_window << "\n"
// << "\n"
// << "vendor " << m_VorbisComment->vendor << "\n";
//for(int i = 0; i < m_VorbisComment->comments; i++)
// std::cout << " " << m_VorbisComment->user_comments[i] << "\n";
//std::cout << std::endl;
m_bOpen = true;
}
Audio :: ~Audio()
{
auto l = lock();
alcDestroyContext(m_pContext);
alcCloseDevice(m_pDevice);
alutExit();
}
void Audio :: set_context()
{
auto l = Audio::lock();
if(not alcMakeContextCurrent(m_pContext))
throw std::runtime_error("failed to set OpenAL Context");
clear_errors();
}
void Audio :: listen(Listener* listener) const
{
if(listener)
listener->listen();
}
bool Audio :: error() const
{
auto l = Audio::lock();
return alGetError();
}
void Audio :: clear_errors()
{
auto l = Audio::lock();
alGetError();
}
bool Audio :: check_errors()
{
int error = alGetError();
if(error != AL_NO_ERROR) {
std::tuple<std::string, std::string> errpair = error_string_al(error);
WARNINGf("OpenAL Error (%s): %s",
std::get<0>(errpair) % std::get<1>(errpair)
);
return true;
}
return false;
}
std::tuple<std::string, std::string> Audio :: error_string_al(int code)
{
switch(code)
{
case AL_INVALID_NAME:
return std::make_tuple("AL_INVALID_NAME", "Invalid name.");
case AL_INVALID_ENUM:
return std::make_tuple("AL_INVALID_ENUM", "Invalid enum.");
case AL_INVALID_VALUE:
return std::make_tuple("AL_INVALID_VALUE", "Invalid value.");
case AL_INVALID_OPERATION:
return std::make_tuple("AL_INVALID_OPERATION", "Invalid operation.");
case AL_OUT_OF_MEMORY:
return std::make_tuple("AL_OUT_OF_MEMORY", "Out of memory.");
}
return (code!=AL_NO_ERROR) ?
std::tuple<std::string,std::string>(std::string(), std::string("No Error.")):
std::tuple<std::string,std::string>(
boost::to_string(code),
std::string("Unknown Error Code")
);
}
std::tuple<std::string,std::string> Audio :: error_string_ov(int code)
{
switch(code)
{
// libvorbis return codes http://www.xiph.org/vorbis/doc/libvorbis/return.html
case OV_EREAD:
return std::make_tuple("OC_EREAD","Read from media.");
case OV_ENOTVORBIS:
return std::make_tuple("OC_ENOTVORBIS","Not Vorbis data.");
case OV_EVERSION:
return std::make_tuple("OV_EVERSION", "Vorbis version mismatch.");
case OV_EBADHEADER:
return std::make_tuple("OV_EBADHEADER", "Invalid Vorbis header.");
case OV_EFAULT:
return std::make_tuple("OV_EFAULT", "Internal logic fault (bug or heap/stack corruption.");
}
return code ?
std::tuple<std::string,std::string>(
boost::to_string(code),
std::string("Unknown Error Code ") + boost::to_string(code)
):
std::tuple<std::string,std::string>("","No Error.");
}
<|endoftext|> |
<commit_before>/******************************************************************************
** Copyright (c) 2015, Intel Corporation **
** All rights reserved. **
** **
** Redistribution and use in source and binary forms, with or without **
** modification, are permitted provided that the following conditions **
** are met: **
** 1. Redistributions of source code must retain the above copyright **
** notice, this list of conditions and the following disclaimer. **
** 2. Redistributions in binary form must reproduce the above copyright **
** notice, this list of conditions and the following disclaimer in the **
** documentation and/or other materials provided with the distribution. **
** 3. Neither the name of the copyright holder nor the names of its **
** contributors may be used to endorse or promote products derived **
** from this software without specific prior written permission. **
** **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ******************************************************************************/
/* Narayanan Sundaram (Intel Corp.)
* ******************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include "catch.hpp"
#include "generator.h"
#include "test_utils.h"
#include "Graph.h"
template<typename T>
void test_read_mtx(int n) {
auto E = generate_dense_edgelist<T>(n);
std::string tempfilenamestr = "GM_tempfileXXXXXX" + std::to_string(GraphMat::get_global_myrank());
int suffixlen = std::to_string(GraphMat::get_global_myrank()).size();
char* tempfilename = new char[tempfilenamestr.size()+1];
int fd;
do {
memcpy(tempfilename, tempfilenamestr.c_str(), tempfilenamestr.size()*sizeof(char));
tempfilename[tempfilenamestr.size()] = '\0';
fd = mkstemps(tempfilename, suffixlen);
} while(fd == -1);
REQUIRE(fd != -1);
char* tempfilenamewithoutsuffix = new char[tempfilenamestr.size() - suffixlen + 1];
memcpy(tempfilenamewithoutsuffix, tempfilename, (tempfilenamestr.size() - suffixlen)*sizeof(char));
tempfilenamewithoutsuffix[ tempfilenamestr.size() - suffixlen] = '\0';
GraphMat::edgelist_t<T> E2;
bool edgeweights;
SECTION("Test text format with header and edgeweights")
{
edgeweights = true;
GraphMat::write_edgelist(tempfilenamewithoutsuffix, E, false, true, edgeweights); //text format with header and edgeweights
GraphMat::load_edgelist<T>(tempfilenamewithoutsuffix, &E2, false, true, edgeweights);
}
SECTION("Test text format with no header and edgeweights")
{
edgeweights = true;
GraphMat::write_edgelist(tempfilenamewithoutsuffix, E, false, false, edgeweights); //text format with header and edgeweights
GraphMat::load_edgelist<T>(tempfilenamewithoutsuffix, &E2, false, false, edgeweights);
}
SECTION("Test text format with no header and no edgeweights")
{
edgeweights = false;
GraphMat::write_edgelist(tempfilenamewithoutsuffix, E, false, false, edgeweights); //text format with header and edgeweights
GraphMat::load_edgelist<T>(tempfilenamewithoutsuffix, &E2, false, false, edgeweights);
}
SECTION("Test text format with header and no edgeweights")
{
edgeweights = false;
GraphMat::write_edgelist<T>(tempfilenamewithoutsuffix, E, false, true, edgeweights); //text format with header and edgeweights
GraphMat::load_edgelist<T>(tempfilenamewithoutsuffix, &E2, false, true, edgeweights);
}
SECTION("Test binary format with header and edgeweights")
{
edgeweights = true;
GraphMat::write_edgelist(tempfilenamewithoutsuffix, E, true, true, edgeweights); //text format with header and edgeweights
GraphMat::load_edgelist<T>(tempfilenamewithoutsuffix, &E2, true, true, edgeweights);
}
SECTION("Test binary format with no header and edgeweights")
{
edgeweights = true;
GraphMat::write_edgelist(tempfilenamewithoutsuffix, E, true, false, edgeweights); //text format with header and edgeweights
GraphMat::load_edgelist<T>(tempfilenamewithoutsuffix, &E2, true, false, edgeweights);
}
SECTION("Test binary format with no header and no edgeweights")
{
edgeweights = false;
GraphMat::write_edgelist(tempfilenamewithoutsuffix, E, true, false, edgeweights); //text format with header and edgeweights
GraphMat::load_edgelist<T>(tempfilenamewithoutsuffix, &E2, true, false, edgeweights);
}
SECTION("Test binary format with header and no edgeweights")
{
edgeweights = false;
GraphMat::write_edgelist<T>(tempfilenamewithoutsuffix, E, true, true, edgeweights); //text format with header and edgeweights
GraphMat::load_edgelist<T>(tempfilenamewithoutsuffix, &E2, true, true, edgeweights);
}
unlink(tempfilename);
GraphMat::edgelist_t<T> E_out;
collect_edges(E, E_out);
std::sort(E_out.edges, E_out.edges + E_out.nnz, edge_compare<T>);
GraphMat::edgelist_t<T> E2_out;
collect_edges(E2, E2_out);
std::sort(E2_out.edges, E2_out.edges + E2_out.nnz, edge_compare<T>);
REQUIRE(E_out.nnz == E2_out.nnz);
for (int i = 0; i < E_out.nnz; i++) {
REQUIRE(E_out.edges[i].src == E2_out.edges[i].src);
REQUIRE(E_out.edges[i].dst == E2_out.edges[i].dst);
if (edgeweights) REQUIRE(E_out.edges[i].val == E2_out.edges[i].val);
}
E.clear();
E_out.clear();
E2.clear();
E2_out.clear();
}
template<typename T>
void test_read_gm_bin(int n) {
auto E = generate_dense_edgelist<T>(n);
GraphMat::edgelist_t<T> E2;
std::string tempfilenamestr = "GM_tempfileXXXXXX" + std::to_string(GraphMat::get_global_myrank());
int suffixlen = std::to_string(GraphMat::get_global_myrank()).size();
char* tempfilename = new char[tempfilenamestr.size()+1];
int fd;
do {
memcpy(tempfilename, tempfilenamestr.c_str(), tempfilenamestr.size()*sizeof(char));
tempfilename[tempfilenamestr.size()] = '\0';
fd = mkstemps(tempfilename, suffixlen);
} while(fd == -1);
REQUIRE(fd != -1);
char* tempfilenamewithoutsuffix = new char[tempfilenamestr.size() - suffixlen + 1];
memcpy(tempfilenamewithoutsuffix, tempfilename, (tempfilenamestr.size() - suffixlen)*sizeof(char));
tempfilenamewithoutsuffix[ tempfilenamestr.size() - suffixlen] = '\0';
{
GraphMat::Graph<int, T> G;
G.MTXFromEdgelist(E);
G.WriteGraphMatBin(tempfilenamewithoutsuffix);
}
{
GraphMat::Graph<double, T> G2;
G2.ReadGraphMatBin(tempfilenamewithoutsuffix);
G2.getEdgelist(E2);
}
unlink(tempfilename);
GraphMat::edgelist_t<T> E_out;
collect_edges(E, E_out);
std::sort(E_out.edges, E_out.edges + E_out.nnz, edge_compare<T>);
GraphMat::edgelist_t<T> E2_out;
collect_edges(E2, E2_out);
std::sort(E2_out.edges, E2_out.edges + E2_out.nnz, edge_compare<T>);
REQUIRE(E_out.nnz == E2_out.nnz);
for (int i = 0; i < E_out.nnz; i++) {
REQUIRE(E_out.edges[i].src == E2_out.edges[i].src);
REQUIRE(E_out.edges[i].dst == E2_out.edges[i].dst);
REQUIRE(E_out.edges[i].val == E2_out.edges[i].val);
}
E.clear();
E_out.clear();
E2.clear();
E2_out.clear();
}
TEST_CASE("IO")
{
SECTION("Test file IO (int mtx)") {
test_read_mtx<int>(10);
}
SECTION("Test file IO (float mtx)") {
test_read_mtx<float>(10);
}
SECTION("Test file IO (GM bin)") {
test_read_gm_bin<int>(10);
test_read_gm_bin<float>(10);
}
}
<commit_msg>refactor test io code<commit_after>/******************************************************************************
** Copyright (c) 2015, Intel Corporation **
** All rights reserved. **
** **
** Redistribution and use in source and binary forms, with or without **
** modification, are permitted provided that the following conditions **
** are met: **
** 1. Redistributions of source code must retain the above copyright **
** notice, this list of conditions and the following disclaimer. **
** 2. Redistributions in binary form must reproduce the above copyright **
** notice, this list of conditions and the following disclaimer in the **
** documentation and/or other materials provided with the distribution. **
** 3. Neither the name of the copyright holder nor the names of its **
** contributors may be used to endorse or promote products derived **
** from this software without specific prior written permission. **
** **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ******************************************************************************/
/* Narayanan Sundaram (Intel Corp.)
* ******************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include "catch.hpp"
#include "generator.h"
#include "test_utils.h"
#include "Graph.h"
template<typename T>
void test_read_mtx(int n, bool binaryformat, bool header, bool edgeweights) {
auto E = generate_dense_edgelist<T>(n);
std::string tempfilenamestr = "GM_tempfileXXXXXX" + std::to_string(GraphMat::get_global_myrank());
int suffixlen = std::to_string(GraphMat::get_global_myrank()).size();
char* tempfilename = new char[tempfilenamestr.size()+1];
int fd;
do {
memcpy(tempfilename, tempfilenamestr.c_str(), tempfilenamestr.size()*sizeof(char));
tempfilename[tempfilenamestr.size()] = '\0';
fd = mkstemps(tempfilename, suffixlen);
} while(fd == -1);
REQUIRE(fd != -1);
char* tempfilenamewithoutsuffix = new char[tempfilenamestr.size() - suffixlen + 1];
memcpy(tempfilenamewithoutsuffix, tempfilename, (tempfilenamestr.size() - suffixlen)*sizeof(char));
tempfilenamewithoutsuffix[ tempfilenamestr.size() - suffixlen] = '\0';
GraphMat::edgelist_t<T> E2;
GraphMat::write_edgelist(tempfilenamewithoutsuffix, E, binaryformat, header, edgeweights); //text format with header and edgeweights
GraphMat::load_edgelist<T>(tempfilenamewithoutsuffix, &E2, binaryformat, header, edgeweights);
unlink(tempfilename);
GraphMat::edgelist_t<T> E_out;
collect_edges(E, E_out);
std::sort(E_out.edges, E_out.edges + E_out.nnz, edge_compare<T>);
GraphMat::edgelist_t<T> E2_out;
collect_edges(E2, E2_out);
std::sort(E2_out.edges, E2_out.edges + E2_out.nnz, edge_compare<T>);
REQUIRE(E_out.nnz == E2_out.nnz);
for (int i = 0; i < E_out.nnz; i++) {
REQUIRE(E_out.edges[i].src == E2_out.edges[i].src);
REQUIRE(E_out.edges[i].dst == E2_out.edges[i].dst);
if (edgeweights) REQUIRE(E_out.edges[i].val == E2_out.edges[i].val);
}
E.clear();
E_out.clear();
E2.clear();
E2_out.clear();
}
template<typename T>
void test_read_gm_bin(int n) {
auto E = generate_dense_edgelist<T>(n);
GraphMat::edgelist_t<T> E2;
std::string tempfilenamestr = "GM_tempfileXXXXXX" + std::to_string(GraphMat::get_global_myrank());
int suffixlen = std::to_string(GraphMat::get_global_myrank()).size();
char* tempfilename = new char[tempfilenamestr.size()+1];
int fd;
do {
memcpy(tempfilename, tempfilenamestr.c_str(), tempfilenamestr.size()*sizeof(char));
tempfilename[tempfilenamestr.size()] = '\0';
fd = mkstemps(tempfilename, suffixlen);
} while(fd == -1);
REQUIRE(fd != -1);
char* tempfilenamewithoutsuffix = new char[tempfilenamestr.size() - suffixlen + 1];
memcpy(tempfilenamewithoutsuffix, tempfilename, (tempfilenamestr.size() - suffixlen)*sizeof(char));
tempfilenamewithoutsuffix[ tempfilenamestr.size() - suffixlen] = '\0';
{
GraphMat::Graph<int, T> G;
G.MTXFromEdgelist(E);
G.WriteGraphMatBin(tempfilenamewithoutsuffix);
}
{
GraphMat::Graph<double, T> G2;
G2.ReadGraphMatBin(tempfilenamewithoutsuffix);
G2.getEdgelist(E2);
}
unlink(tempfilename);
GraphMat::edgelist_t<T> E_out;
collect_edges(E, E_out);
std::sort(E_out.edges, E_out.edges + E_out.nnz, edge_compare<T>);
GraphMat::edgelist_t<T> E2_out;
collect_edges(E2, E2_out);
std::sort(E2_out.edges, E2_out.edges + E2_out.nnz, edge_compare<T>);
REQUIRE(E_out.nnz == E2_out.nnz);
for (int i = 0; i < E_out.nnz; i++) {
REQUIRE(E_out.edges[i].src == E2_out.edges[i].src);
REQUIRE(E_out.edges[i].dst == E2_out.edges[i].dst);
REQUIRE(E_out.edges[i].val == E2_out.edges[i].val);
}
E.clear();
E_out.clear();
E2.clear();
E2_out.clear();
}
TEST_CASE("IO")
{
SECTION("Test file IO (int mtx)") {
test_read_mtx<int>(10, true, true, true);
test_read_mtx<int>(10, true, true, false);
test_read_mtx<int>(10, true, false, true);
test_read_mtx<int>(10, true, false, false);
test_read_mtx<int>(10, false, true, true);
test_read_mtx<int>(10, false, true, false);
test_read_mtx<int>(10, false, false, true);
test_read_mtx<int>(10, false, false, false);
}
SECTION("Test file IO (float mtx)") {
test_read_mtx<float>(10, true, true, true);
test_read_mtx<float>(10, true, true, false);
test_read_mtx<float>(10, true, false, true);
test_read_mtx<float>(10, true, false, false);
test_read_mtx<float>(10, false, true, true);
test_read_mtx<float>(10, false, true, false);
test_read_mtx<float>(10, false, false, true);
test_read_mtx<float>(10, false, false, false);
}
SECTION("Test file IO (GM bin)") {
test_read_gm_bin<int>(10);
test_read_gm_bin<float>(10);
}
}
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Ash Berlin, Aristid Breitkreuz
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 "flusspferd/object.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/evaluate.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/io/io.hpp"
#include "test_environment.hpp"
#include <iostream>
#include <string>
#ifdef FLUSSPFERD_HAVE_IO
BOOST_FIXTURE_TEST_SUITE( io, context_fixture )
BOOST_AUTO_TEST_CASE( test_have_IO ) {
flusspferd::io::load_io();
flusspferd::root_value v;
BOOST_CHECK_NO_THROW( v = flusspferd::evaluate("IO", __FILE__, __LINE__) );
BOOST_CHECK(v.is_object());
BOOST_CHECK(!v.is_null());
flusspferd::gc();
}
BOOST_AUTO_TEST_CASE( test_file_read ) {
flusspferd::io::load_io();
flusspferd::security::create(flusspferd::global());
const char* js = "f = new IO.File('test/fixtures/file1'); f.readWhole()";
flusspferd::root_value v;
BOOST_CHECK_NO_THROW( v = flusspferd::evaluate(js, __FILE__, __LINE__) );
BOOST_CHECK_EQUAL(v.to_string().c_str(), "foobar\nbaz\n");
js = "f = new IO.File('test/fixtures/file1'); f.readWhole()";
BOOST_CHECK_NO_THROW( v = flusspferd::evaluate(js, __FILE__, __LINE__) );
BOOST_CHECK_EQUAL(v.to_string().c_str(), "foobar\nbaz\n");
flusspferd::gc();
}
BOOST_AUTO_TEST_SUITE_END()
#endif
<commit_msg>tests: add new IO test<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Ash Berlin, Aristid Breitkreuz
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 "flusspferd/object.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/evaluate.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/exception.hpp"
#include "flusspferd/io/io.hpp"
#include "test_environment.hpp"
#include <iostream>
#include <string>
#ifdef FLUSSPFERD_HAVE_IO
BOOST_FIXTURE_TEST_SUITE( io, context_fixture )
BOOST_AUTO_TEST_CASE( test_have_IO ) {
flusspferd::io::load_io();
flusspferd::root_value v;
BOOST_CHECK_NO_THROW( v = flusspferd::evaluate("IO", __FILE__, __LINE__) );
BOOST_CHECK(v.is_object());
BOOST_CHECK(!v.is_null());
flusspferd::gc();
}
BOOST_AUTO_TEST_CASE( IO_no_security ) {
flusspferd::io::load_io();
const char* js = "f = new IO.File('test/fixtures/file1'); f.readWhole()";
flusspferd::root_value v;
BOOST_CHECK_THROW(
v = flusspferd::evaluate(js, __FILE__, __LINE__),
flusspferd::exception);
}
BOOST_AUTO_TEST_CASE( test_file_read ) {
flusspferd::io::load_io();
flusspferd::security::create(flusspferd::global());
const char* js = "f = new IO.File('test/fixtures/file1'); f.readWhole()";
flusspferd::root_value v;
BOOST_CHECK_NO_THROW( v = flusspferd::evaluate(js, __FILE__, __LINE__) );
BOOST_CHECK_EQUAL(v.to_string().c_str(), "foobar\nbaz\n");
js = "f = new IO.File('test/fixtures/file1'); f.readWhole()";
BOOST_CHECK_NO_THROW( v = flusspferd::evaluate(js, __FILE__, __LINE__) );
BOOST_CHECK_EQUAL(v.to_string().c_str(), "foobar\nbaz\n");
flusspferd::gc();
}
BOOST_AUTO_TEST_SUITE_END()
#endif
<|endoftext|> |
<commit_before><commit_msg>Fixed tests between distros<commit_after><|endoftext|> |
<commit_before>#include <memory>
#include <stdio.h>
#include "uvpp_udp.hpp"
int main()
{
uvpp::Loop uvloop;
uvpp::Signal usignal(uvloop);
usignal.set_callback([&uvloop](){
uvloop.stop();
});
usignal.start(SIGINT);
struct sockaddr_in saddr;
uvpp::Udp mcast(uvloop);
uv_ip4_addr("0.0.0.0", 5353, &saddr);
mcast.bind(saddr, UV_UDP_REUSEADDR);
mcast.join("224.0.0.251", "0.0.0.0");
mcast.set_callback([](char *buf, int len, const struct sockaddr *addr){
char namebuf[32];
uv_ip4_name((const struct sockaddr_in*)addr, namebuf, sizeof(namebuf));
printf("got %p %d from %s\n", buf, len, namebuf);
});
mcast.start();
uvpp::Udp ucast(uvloop);
uv_ip4_addr("127.0.0.1", 0, &saddr);
ucast.bind(saddr);
ucast.getsockname(saddr);
ucast.set_callback([](char *buf, int len, const struct sockaddr *addr){
int idx = ((int *)buf)[0];
printf("%d %d\n", idx, len);
});
ucast.start();
int buf[4096];
for (int idx=0; idx < 20; idx++) {
buf[0] = idx;
int rc = ucast.try_send((char*)buf, sizeof(buf), saddr);
if (rc==-1)
break;
}
uvloop.run();
printf("first loop break\n");
}
<commit_msg>fix: error return is negative value, not -1<commit_after>#include <memory>
#include <stdio.h>
#include "uvpp_udp.hpp"
int main()
{
uvpp::Loop uvloop;
uvpp::Signal usignal(uvloop);
usignal.set_callback([&uvloop](){
uvloop.stop();
});
usignal.start(SIGINT);
struct sockaddr_in saddr;
uvpp::Udp mcast(uvloop);
uv_ip4_addr("0.0.0.0", 5353, &saddr);
mcast.bind(saddr, UV_UDP_REUSEADDR);
mcast.join("224.0.0.251", "0.0.0.0");
mcast.set_callback([](char *buf, int len, const struct sockaddr *addr){
char namebuf[32];
uv_ip4_name((const struct sockaddr_in*)addr, namebuf, sizeof(namebuf));
printf("got %p %d from %s\n", buf, len, namebuf);
});
mcast.start();
uvpp::Udp ucast(uvloop);
uv_ip4_addr("127.0.0.1", 0, &saddr);
ucast.bind(saddr);
ucast.getsockname(saddr);
ucast.set_callback([](char *buf, int len, const struct sockaddr *addr){
int idx = ((int *)buf)[0];
printf("%d %d\n", idx, len);
});
ucast.start();
int buf[4096];
for (int idx=0; idx < 20; idx++) {
buf[0] = idx;
int rc = ucast.try_send((char*)buf, sizeof(buf), saddr);
if (rc < 0) {
printf("%s at idx %d\n", uv_err_name(rc), idx);
break;
}
}
uvloop.run();
printf("first loop break\n");
}
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LexVB.cxx
** Lexer for Visual Basic and VBScript.
**/
// Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
// Internal state, highlighted as number
#define SCE_B_FILENUMBER SCE_B_DEFAULT+100
static bool IsVBComment(Accessor &styler, int pos, int len) {
return len > 0 && styler[pos] == '\'';
}
static inline bool IsTypeCharacter(int ch) {
return ch == '%' || ch == '&' || ch == '@' || ch == '!' || ch == '#' || ch == '$';
}
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 ||
(isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+');
}
static void ColouriseVBDoc(unsigned int startPos, int length, int initStyle,
WordList *keywordlists[], Accessor &styler, bool vbScriptSyntax) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
styler.StartAt(startPos);
int visibleChars = 0;
int fileNbDigits = 0;
// Do not leak onto next line
if (initStyle == SCE_B_STRINGEOL || initStyle == SCE_B_COMMENT || initStyle == SCE_B_PREPROCESSOR) {
initStyle = SCE_B_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.state == SCE_B_OPERATOR) {
sc.SetState(SCE_B_DEFAULT);
} else if (sc.state == SCE_B_IDENTIFIER) {
if (!IsAWordChar(sc.ch)) {
// In Basic (except VBScript), a variable name or a function name
// can end with a special character indicating the type of the value
// held or returned.
bool skipType = false;
if (!vbScriptSyntax && IsTypeCharacter(sc.ch)) {
sc.Forward(); // Skip it
skipType = true;
}
if (sc.ch == ']') {
sc.Forward();
}
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
if (skipType) {
s[strlen(s) - 1] = '\0';
}
if (strcmp(s, "rem") == 0) {
sc.ChangeState(SCE_B_COMMENT);
} else {
if (keywords.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD4);
} // Else, it is really an identifier...
sc.SetState(SCE_B_DEFAULT);
}
}
} else if (sc.state == SCE_B_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign char
// Also accepts A-F for hex. numbers
if (!IsANumberChar(sc.ch) && !(tolower(sc.ch) >= 'a' && tolower(sc.ch) <= 'f')) {
sc.SetState(SCE_B_DEFAULT);
}
} else if (sc.state == SCE_B_STRING) {
// VB doubles quotes to preserve them, so just end this string
// state now as a following quote will start again
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
if (tolower(sc.chNext) == 'c') {
sc.Forward();
}
sc.ForwardSetState(SCE_B_DEFAULT);
}
} else if (sc.atLineEnd) {
visibleChars = 0;
sc.ChangeState(SCE_B_STRINGEOL);
sc.ForwardSetState(SCE_B_DEFAULT);
}
} else if (sc.state == SCE_B_COMMENT) {
if (sc.atLineEnd) {
visibleChars = 0;
sc.ForwardSetState(SCE_B_DEFAULT);
}
} else if (sc.state == SCE_B_PREPROCESSOR) {
if (sc.atLineEnd) {
visibleChars = 0;
sc.ForwardSetState(SCE_B_DEFAULT);
}
} else if (sc.state == SCE_B_FILENUMBER) {
if (IsADigit(sc.ch)) {
fileNbDigits++;
if (fileNbDigits > 3) {
sc.ChangeState(SCE_B_DATE);
}
} else if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ',') {
// Regular uses: Close #1; Put #1, ...; Get #1, ... etc.
// Too bad if date is format #27, Oct, 2003# or something like that...
// Use regular number state
sc.ChangeState(SCE_B_NUMBER);
sc.SetState(SCE_B_DEFAULT);
} else if (sc.ch == '#') {
sc.ChangeState(SCE_B_DATE);
sc.ForwardSetState(SCE_B_DEFAULT);
} else {
sc.ChangeState(SCE_B_DATE);
}
if (sc.state != SCE_B_FILENUMBER) {
fileNbDigits = 0;
}
} else if (sc.state == SCE_B_DATE) {
if (sc.atLineEnd) {
visibleChars = 0;
sc.ChangeState(SCE_B_STRINGEOL);
sc.ForwardSetState(SCE_B_DEFAULT);
} else if (sc.ch == '#') {
sc.ForwardSetState(SCE_B_DEFAULT);
}
}
if (sc.state == SCE_B_DEFAULT) {
if (sc.ch == '\'') {
sc.SetState(SCE_B_COMMENT);
} else if (sc.ch == '\"') {
sc.SetState(SCE_B_STRING);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_B_PREPROCESSOR);
} else if (sc.ch == '#') {
// It can be a date literal, ending with #, or a file number, from 1 to 511
// The date literal depends on the locale, so anything can go between #'s.
// Can be #January 1, 1993# or #1 Jan 93# or #05/11/2003#, etc.
// So we set the FILENUMBER state, and switch to DATE if it isn't a file number
sc.SetState(SCE_B_FILENUMBER);
} else if (sc.ch == '&' && tolower(sc.chNext) == 'h') {
// Hexadecimal number
sc.SetState(SCE_B_NUMBER);
sc.Forward();
} else if (sc.ch == '&' && tolower(sc.chNext) == 'o') {
// Octal number
sc.SetState(SCE_B_NUMBER);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_B_NUMBER);
} else if (IsAWordStart(sc.ch) || (sc.ch == '[')) {
sc.SetState(SCE_B_IDENTIFIER);
} else if (isoperator(static_cast<char>(sc.ch)) || (sc.ch == '\\')) { // Integer division
sc.SetState(SCE_B_OPERATOR);
}
}
if (sc.atLineEnd) {
visibleChars = 0;
}
if (!IsASpace(sc.ch)) {
visibleChars++;
}
}
sc.Complete();
}
static void FoldVBDoc(unsigned int startPos, int length, int,
WordList *[], Accessor &styler) {
int endPos = startPos + length;
// Backtrack to previous line in case need to fix its fold status
int lineCurrent = styler.GetLine(startPos);
if (startPos > 0) {
if (lineCurrent > 0) {
lineCurrent--;
startPos = styler.LineStart(lineCurrent);
}
}
int spaceFlags = 0;
int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsVBComment);
char chNext = styler[startPos];
for (int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == endPos)) {
int lev = indentCurrent;
int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsVBComment);
if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
// Only non whitespace lines can be headers
if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) {
lev |= SC_FOLDLEVELHEADERFLAG;
} else if (indentNext & SC_FOLDLEVELWHITEFLAG) {
// Line after is blank so check the next - maybe should continue further?
int spaceFlags2 = 0;
int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsVBComment);
if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
}
}
indentCurrent = indentNext;
styler.SetLevel(lineCurrent, lev);
lineCurrent++;
}
}
}
static void ColouriseVBNetDoc(unsigned int startPos, int length, int initStyle,
WordList *keywordlists[], Accessor &styler) {
ColouriseVBDoc(startPos, length, initStyle, keywordlists, styler, false);
}
static void ColouriseVBScriptDoc(unsigned int startPos, int length, int initStyle,
WordList *keywordlists[], Accessor &styler) {
ColouriseVBDoc(startPos, length, initStyle, keywordlists, styler, true);
}
static const char * const vbWordListDesc[] = {
"Keywords",
"user1",
"user2",
"user3",
0
};
LexerModule lmVB(SCLEX_VB, ColouriseVBNetDoc, "vb", FoldVBDoc, vbWordListDesc);
LexerModule lmVBScript(SCLEX_VBSCRIPT, ColouriseVBScriptDoc, "vbscript", FoldVBDoc, vbWordListDesc);
<commit_msg>Bug #2901239 fix. VB: "Module" in last line problem<commit_after>// Scintilla source code edit control
/** @file LexVB.cxx
** Lexer for Visual Basic and VBScript.
**/
// Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
// Internal state, highlighted as number
#define SCE_B_FILENUMBER SCE_B_DEFAULT+100
static bool IsVBComment(Accessor &styler, int pos, int len) {
return len > 0 && styler[pos] == '\'';
}
static inline bool IsTypeCharacter(int ch) {
return ch == '%' || ch == '&' || ch == '@' || ch == '!' || ch == '#' || ch == '$';
}
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 ||
(isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+');
}
static void ColouriseVBDoc(unsigned int startPos, int length, int initStyle,
WordList *keywordlists[], Accessor &styler, bool vbScriptSyntax) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
styler.StartAt(startPos);
int visibleChars = 0;
int fileNbDigits = 0;
// Do not leak onto next line
if (initStyle == SCE_B_STRINGEOL || initStyle == SCE_B_COMMENT || initStyle == SCE_B_PREPROCESSOR) {
initStyle = SCE_B_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.state == SCE_B_OPERATOR) {
sc.SetState(SCE_B_DEFAULT);
} else if (sc.state == SCE_B_IDENTIFIER) {
if (!IsAWordChar(sc.ch)) {
// In Basic (except VBScript), a variable name or a function name
// can end with a special character indicating the type of the value
// held or returned.
bool skipType = false;
if (!vbScriptSyntax && IsTypeCharacter(sc.ch)) {
sc.Forward(); // Skip it
skipType = true;
}
if (sc.ch == ']') {
sc.Forward();
}
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
if (skipType) {
s[strlen(s) - 1] = '\0';
}
if (strcmp(s, "rem") == 0) {
sc.ChangeState(SCE_B_COMMENT);
} else {
if (keywords.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD4);
} // Else, it is really an identifier...
sc.SetState(SCE_B_DEFAULT);
}
}
} else if (sc.state == SCE_B_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign char
// Also accepts A-F for hex. numbers
if (!IsANumberChar(sc.ch) && !(tolower(sc.ch) >= 'a' && tolower(sc.ch) <= 'f')) {
sc.SetState(SCE_B_DEFAULT);
}
} else if (sc.state == SCE_B_STRING) {
// VB doubles quotes to preserve them, so just end this string
// state now as a following quote will start again
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
if (tolower(sc.chNext) == 'c') {
sc.Forward();
}
sc.ForwardSetState(SCE_B_DEFAULT);
}
} else if (sc.atLineEnd) {
visibleChars = 0;
sc.ChangeState(SCE_B_STRINGEOL);
sc.ForwardSetState(SCE_B_DEFAULT);
}
} else if (sc.state == SCE_B_COMMENT) {
if (sc.atLineEnd) {
visibleChars = 0;
sc.ForwardSetState(SCE_B_DEFAULT);
}
} else if (sc.state == SCE_B_PREPROCESSOR) {
if (sc.atLineEnd) {
visibleChars = 0;
sc.ForwardSetState(SCE_B_DEFAULT);
}
} else if (sc.state == SCE_B_FILENUMBER) {
if (IsADigit(sc.ch)) {
fileNbDigits++;
if (fileNbDigits > 3) {
sc.ChangeState(SCE_B_DATE);
}
} else if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ',') {
// Regular uses: Close #1; Put #1, ...; Get #1, ... etc.
// Too bad if date is format #27, Oct, 2003# or something like that...
// Use regular number state
sc.ChangeState(SCE_B_NUMBER);
sc.SetState(SCE_B_DEFAULT);
} else if (sc.ch == '#') {
sc.ChangeState(SCE_B_DATE);
sc.ForwardSetState(SCE_B_DEFAULT);
} else {
sc.ChangeState(SCE_B_DATE);
}
if (sc.state != SCE_B_FILENUMBER) {
fileNbDigits = 0;
}
} else if (sc.state == SCE_B_DATE) {
if (sc.atLineEnd) {
visibleChars = 0;
sc.ChangeState(SCE_B_STRINGEOL);
sc.ForwardSetState(SCE_B_DEFAULT);
} else if (sc.ch == '#') {
sc.ForwardSetState(SCE_B_DEFAULT);
}
}
if (sc.state == SCE_B_DEFAULT) {
if (sc.ch == '\'') {
sc.SetState(SCE_B_COMMENT);
} else if (sc.ch == '\"') {
sc.SetState(SCE_B_STRING);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_B_PREPROCESSOR);
} else if (sc.ch == '#') {
// It can be a date literal, ending with #, or a file number, from 1 to 511
// The date literal depends on the locale, so anything can go between #'s.
// Can be #January 1, 1993# or #1 Jan 93# or #05/11/2003#, etc.
// So we set the FILENUMBER state, and switch to DATE if it isn't a file number
sc.SetState(SCE_B_FILENUMBER);
} else if (sc.ch == '&' && tolower(sc.chNext) == 'h') {
// Hexadecimal number
sc.SetState(SCE_B_NUMBER);
sc.Forward();
} else if (sc.ch == '&' && tolower(sc.chNext) == 'o') {
// Octal number
sc.SetState(SCE_B_NUMBER);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_B_NUMBER);
} else if (IsAWordStart(sc.ch) || (sc.ch == '[')) {
sc.SetState(SCE_B_IDENTIFIER);
} else if (isoperator(static_cast<char>(sc.ch)) || (sc.ch == '\\')) { // Integer division
sc.SetState(SCE_B_OPERATOR);
}
}
if (sc.atLineEnd) {
visibleChars = 0;
}
if (!IsASpace(sc.ch)) {
visibleChars++;
}
}
if (sc.state == SCE_B_IDENTIFIER && !IsAWordChar(sc.ch)) {
// In Basic (except VBScript), a variable name or a function name
// can end with a special character indicating the type of the value
// held or returned.
bool skipType = false;
if (!vbScriptSyntax && IsTypeCharacter(sc.ch)) {
sc.Forward(); // Skip it
skipType = true;
}
if (sc.ch == ']') {
sc.Forward();
}
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
if (skipType) {
s[strlen(s) - 1] = '\0';
}
if (strcmp(s, "rem") == 0) {
sc.ChangeState(SCE_B_COMMENT);
} else {
if (keywords.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_B_KEYWORD4);
} // Else, it is really an identifier...
sc.SetState(SCE_B_DEFAULT);
}
}
sc.Complete();
}
static void FoldVBDoc(unsigned int startPos, int length, int,
WordList *[], Accessor &styler) {
int endPos = startPos + length;
// Backtrack to previous line in case need to fix its fold status
int lineCurrent = styler.GetLine(startPos);
if (startPos > 0) {
if (lineCurrent > 0) {
lineCurrent--;
startPos = styler.LineStart(lineCurrent);
}
}
int spaceFlags = 0;
int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsVBComment);
char chNext = styler[startPos];
for (int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == endPos)) {
int lev = indentCurrent;
int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsVBComment);
if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
// Only non whitespace lines can be headers
if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) {
lev |= SC_FOLDLEVELHEADERFLAG;
} else if (indentNext & SC_FOLDLEVELWHITEFLAG) {
// Line after is blank so check the next - maybe should continue further?
int spaceFlags2 = 0;
int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsVBComment);
if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
}
}
indentCurrent = indentNext;
styler.SetLevel(lineCurrent, lev);
lineCurrent++;
}
}
}
static void ColouriseVBNetDoc(unsigned int startPos, int length, int initStyle,
WordList *keywordlists[], Accessor &styler) {
ColouriseVBDoc(startPos, length, initStyle, keywordlists, styler, false);
}
static void ColouriseVBScriptDoc(unsigned int startPos, int length, int initStyle,
WordList *keywordlists[], Accessor &styler) {
ColouriseVBDoc(startPos, length, initStyle, keywordlists, styler, true);
}
static const char * const vbWordListDesc[] = {
"Keywords",
"user1",
"user2",
"user3",
0
};
LexerModule lmVB(SCLEX_VB, ColouriseVBNetDoc, "vb", FoldVBDoc, vbWordListDesc);
LexerModule lmVBScript(SCLEX_VBSCRIPT, ColouriseVBScriptDoc, "vbscript", FoldVBDoc, vbWordListDesc);
<|endoftext|> |
<commit_before>#include "Model.hpp"
#include <GL/gl.h>
#include <GL/glu.h>
#include <SDL/SDL_image.h>
#include <iostream>
#include <stdexcept>
#include <string>
/*
* Texture
*/
Texture::Texture(const std::string& file) : file_(file), loaded_(false) {
}
Texture::~Texture() {
if (loaded_) {
glDeleteTextures(1, &id_);
SDL_FreeSurface(surface_);
}
}
void Texture::load() {
if (!loaded_) {
surface_ = IMG_Load(file_.c_str());
if (NULL == surface_) {
throw std::runtime_error("Unable to load image " + file_);
}
glGenTextures(1, &id_);
glBindTexture(GL_TEXTURE_2D, id_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface_->w, surface_->h, 0, GL_RGB, GL_UNSIGNED_BYTE, surface_->pixels);
loaded_ = true;
}
}
void Texture::bind() {
if (loaded_)
glBindTexture(GL_TEXTURE_2D, id_);
}
/*
* Material
*/
Material::Material(const std::string& name) : name_(name) {
ka_[0] = ka_[1] = ka_[2] = 0.2f;
kd_[0] = kd_[1] = kd_[2] = 0.8f;
ks_[0] = ks_[1] = ks_[2] = 0.0f;
ke_[0] = ke_[1] = ke_[2] = 0.0f;
ka_[3] = kd_[3] = ks_[3] = ke_[3] = 1.0f;
}
Material::Material(const Material& material) {
*this = material;
}
Material& Material::operator = (const Material& material) {
name_ = material.name_;
for (int i = 0; i < 3; i++) {
ka_[i] = material.ka_[i];
kd_[i] = material.kd_[i];
ks_[i] = material.ks_[i];
ke_[i] = material.ke_[i];
}
texture_ = material.texture_;
return *this;
}
std::string Material::name() {
return name_;
}
void Material::setKa(float a1, float a2, float a3) {
ka_[0] = a1;
ka_[1] = a2;
ka_[2] = a3;
}
void Material::setKd(float d1, float d2, float d3) {
kd_[0] = d1;
kd_[1] = d2;
kd_[2] = d3;
}
void Material::setKs(float s1, float s2, float s3) {
ks_[0] = s1;
ks_[1] = s2;
ks_[2] = s3;
}
void Material::setKe(float e1, float e2, float e3) {
ke_[0] = e1;
ke_[1] = e2;
ke_[2] = e3;
}
void Material::setTexture(const SmartPtr<Texture>& texture) {
this->texture_ = texture;
}
/*
* Face
*/
Face::Face() {
}
void Face::addVertexIndex(unsigned int index) {
vertexIndices_.push_back(index);
}
void Face::addNormalIndex(unsigned int index) {
normalIndices_.push_back(index);
}
void Face::addTexCoordIndex(unsigned int index) {
texCoordIndices_.push_back(index);
}
/*
* Group
*/
Group::Group(unsigned int id, const std::string& name, const MaterialPtr& material) : id_(id), name_(name), material_(material) {
}
void Group::addFace(const FacePtr& face) {
faces_.push_back(face);
}
/*
* Model
*/
Model::Model() {
}
void Model::addVertex(const Point3& vertex) {
vertices_.push_back(vertex);
}
void Model::addNormal(const Point3& normal) {
normals_.push_back(normal);
}
void Model::addTexCoord(const Point2& coord) {
texCoords_.push_back(coord);
}
void Model::addGroup(const GroupPtr& group) {
groups_.push_back(group);
}
void Model::loadTextures() {
for (unsigned int i = 0; i < groups_.size(); i++) {
if (!groups_[i]->material_->texture_.isNull()) {
groups_[i]->material_->texture_->load();
}
}
}
void Model::compileLists() {
GLuint id = glGenLists(groups_.size());
for (unsigned int i = 0; i < groups_.size(); i++) {
GroupPtr group = groups_[i];
group->id_ = id;
glNewList(id, GL_COMPILE);
for (unsigned int j = 0; j < group->faces_.size(); j++) {
FacePtr face = group->faces_[j];
glBegin(GL_POLYGON);
for (unsigned int k = 0; k < face->vertexIndices_.size(); k++) {
unsigned int index;
if (face->texCoordIndices_.size() > 0) {
index = face->texCoordIndices_[k];
glTexCoord2fv(texCoords_[index-1].data());
}
if (face->normalIndices_.size() > 0) {
index = face->normalIndices_[k];
glNormal3fv(normals_[index-1].data());
}
index = face->vertexIndices_[k];
glVertex3fv(vertices_[index-1].data());
}
glEnd();
}
glEndList();
id++;
}
}
void Model::setShaders(ShadersPtr shaders) {
shaders_ = shaders;
}
void Model::render() {
if (!shaders_.isNull())
shaders_->use();
for (unsigned int i = 0; i < groups_.size(); i++) {
GroupPtr group = groups_[i];
MaterialPtr material = group->material_;
if (!material->texture_.isNull()) {
if (!shaders_.isNull() && shaders_->hasSampler())
glActiveTexture(GL_TEXTURE0);
// Disable material parameters until I have a chance to properly test and debug them.
/*if (!shaders_.isNull()) {
glMaterialfv(GL_FRONT, GL_AMBIENT, material->ka_);
glMaterialfv(GL_FRONT, GL_DIFFUSE, material->kd_);
glMaterialfv(GL_FRONT, GL_SPECULAR, material->ks_);
glMaterialfv(GL_FRONT, GL_EMISSION, material->ke_);
}*/
material->texture_->bind();
if (!shaders_.isNull() && shaders_->hasSampler())
glUniform1i(shaders_->samplerId(), 0);
}
glCallList(groups_[i]->id_);
}
}
<commit_msg>Code cleanup.<commit_after>#include "Model.hpp"
#include <GL/gl.h>
#include <GL/glu.h>
#include <SDL/SDL_image.h>
#include <iostream>
#include <stdexcept>
#include <string>
/*
* Texture
*/
Texture::Texture(const std::string& file) : file_(file), loaded_(false) {
}
Texture::~Texture() {
if (loaded_) {
glDeleteTextures(1, &id_);
SDL_FreeSurface(surface_);
}
}
void Texture::load() {
if (!loaded_) {
surface_ = IMG_Load(file_.c_str());
if (NULL == surface_) {
throw std::runtime_error("Unable to load image " + file_);
}
glGenTextures(1, &id_);
glBindTexture(GL_TEXTURE_2D, id_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface_->w, surface_->h, 0, GL_RGB, GL_UNSIGNED_BYTE, surface_->pixels);
loaded_ = true;
}
}
void Texture::bind() {
if (loaded_)
glBindTexture(GL_TEXTURE_2D, id_);
}
/*
* Material
*/
Material::Material(const std::string& name) : name_(name) {
for (int i = 0; i < 3; i++) {
ka_[i] = 0.2f;
kd_[i] = 0.8f;
ks_[i] = 0.0f;
ke_[i] = 0.0f;
}
ka_[3] = kd_[3] = ks_[3] = ke_[3] = 1.0f;
}
Material::Material(const Material& material) {
*this = material;
}
Material& Material::operator = (const Material& material) {
name_ = material.name_;
for (int i = 0; i < 4; i++) {
ka_[i] = material.ka_[i];
kd_[i] = material.kd_[i];
ks_[i] = material.ks_[i];
ke_[i] = material.ke_[i];
}
texture_ = material.texture_;
return *this;
}
std::string Material::name() {
return name_;
}
void Material::setKa(float a1, float a2, float a3) {
ka_[0] = a1;
ka_[1] = a2;
ka_[2] = a3;
}
void Material::setKd(float d1, float d2, float d3) {
kd_[0] = d1;
kd_[1] = d2;
kd_[2] = d3;
}
void Material::setKs(float s1, float s2, float s3) {
ks_[0] = s1;
ks_[1] = s2;
ks_[2] = s3;
}
void Material::setKe(float e1, float e2, float e3) {
ke_[0] = e1;
ke_[1] = e2;
ke_[2] = e3;
}
void Material::setTexture(const SmartPtr<Texture>& texture) {
this->texture_ = texture;
}
/*
* Face
*/
Face::Face() {
}
void Face::addVertexIndex(unsigned int index) {
vertexIndices_.push_back(index);
}
void Face::addNormalIndex(unsigned int index) {
normalIndices_.push_back(index);
}
void Face::addTexCoordIndex(unsigned int index) {
texCoordIndices_.push_back(index);
}
/*
* Group
*/
Group::Group(unsigned int id, const std::string& name, const MaterialPtr& material) : id_(id), name_(name), material_(material) {
}
void Group::addFace(const FacePtr& face) {
faces_.push_back(face);
}
/*
* Model
*/
Model::Model() {
}
void Model::addVertex(const Point3& vertex) {
vertices_.push_back(vertex);
}
void Model::addNormal(const Point3& normal) {
normals_.push_back(normal);
}
void Model::addTexCoord(const Point2& coord) {
texCoords_.push_back(coord);
}
void Model::addGroup(const GroupPtr& group) {
groups_.push_back(group);
}
void Model::loadTextures() {
for (unsigned int i = 0; i < groups_.size(); i++) {
if (!groups_[i]->material_->texture_.isNull()) {
groups_[i]->material_->texture_->load();
}
}
}
void Model::compileLists() {
GLuint id = glGenLists(groups_.size());
for (unsigned int i = 0; i < groups_.size(); i++) {
GroupPtr group = groups_[i];
group->id_ = id;
glNewList(id, GL_COMPILE);
for (unsigned int j = 0; j < group->faces_.size(); j++) {
FacePtr face = group->faces_[j];
glBegin(GL_POLYGON);
for (unsigned int k = 0; k < face->vertexIndices_.size(); k++) {
unsigned int index;
if (face->texCoordIndices_.size() > 0) {
index = face->texCoordIndices_[k];
glTexCoord2fv(texCoords_[index-1].data());
}
if (face->normalIndices_.size() > 0) {
index = face->normalIndices_[k];
glNormal3fv(normals_[index-1].data());
}
index = face->vertexIndices_[k];
glVertex3fv(vertices_[index-1].data());
}
glEnd();
}
glEndList();
id++;
}
}
void Model::setShaders(ShadersPtr shaders) {
shaders_ = shaders;
}
void Model::render() {
if (!shaders_.isNull())
shaders_->use();
for (unsigned int i = 0; i < groups_.size(); i++) {
GroupPtr group = groups_[i];
MaterialPtr material = group->material_;
// Disable material parameters until I have a chance to properly test and debug them.
/*glMaterialfv(GL_FRONT, GL_AMBIENT, material->ka_);
glMaterialfv(GL_FRONT, GL_DIFFUSE, material->kd_);
glMaterialfv(GL_FRONT, GL_SPECULAR, material->ks_);
glMaterialfv(GL_FRONT, GL_EMISSION, material->ke_);*/
if (!material->texture_.isNull()) {
if (!shaders_.isNull() && shaders_->hasSampler())
glActiveTexture(GL_TEXTURE0);
material->texture_->bind();
if (!shaders_.isNull() && shaders_->hasSampler())
glUniform1i(shaders_->samplerId(), 0);
}
glCallList(groups_[i]->id_);
}
}
<|endoftext|> |
<commit_before>/* This file is part of the Vc library.
Copyright (C) 2009 Matthias Kretz <kretz@kde.org>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Vc/Vc>
#include "unittest.h"
using namespace Vc;
template<typename V, unsigned int Size> struct TestEntries {
static inline void run()
{
TestEntries<V, Size/2>::run();
TestEntries<V, Size>::test();
TestEntries<V, Size - 1>::test();
}
static void test();
};
template<typename V> struct TestEntries<V, 0> { static void run() {} static void test() {} };
template<typename V, unsigned int Size> struct TestVectors {
static inline void run()
{
TestVectors<V, Size/2>::run();
TestVectors<V, Size>::test();
TestVectors<V, Size - 1>::test();
}
static void test();
};
template<typename V> struct TestVectors<V, 0> { static void run() {} static void test() {} };
template<typename V, unsigned int Size> struct TestVectorReorganization {
static inline void run()
{
TestVectorReorganization<V, Size/2>::run();
TestVectorReorganization<V, Size>::test();
TestVectorReorganization<V, Size - 1>::test();
}
static void test();
};
template<typename V> struct TestVectorReorganization<V, 0> { static void run() {} static void test() {} };
template<typename V, unsigned int Size> void TestEntries<V, Size>::test()
{
typedef typename V::EntryType T;
const T x = Size;
Memory<V, Size> m;
const Memory<V, Size> &m2 = m;
Memory<V> m3(Size);
for (unsigned int i = 0; i < Size; ++i) {
m[i] = x;
m3[i] = x;
}
for (unsigned int i = 0; i < Size; ++i) {
COMPARE(m[i], x);
COMPARE(m2[i], x);
COMPARE(m3[i], x);
}
for (unsigned int i = 0; i < Size; ++i) {
COMPARE(m.entries()[i], x);
COMPARE(m2.entries()[i], x);
COMPARE(m3.entries()[i], x);
}
const T *ptr = m2;
for (unsigned int i = 0; i < Size; ++i) {
COMPARE(ptr[i], x);
}
ptr = m3;
for (unsigned int i = 0; i < Size; ++i) {
COMPARE(ptr[i], x);
}
}
template<typename V, unsigned int Size> void TestVectors<V, Size>::test()
{
typedef typename V::EntryType T;
const V x = Size;
Memory<V, Size> m;
const Memory<V, Size> &m2 = m;
Memory<V> m3(Size);
for (unsigned int i = 0; i < m.vectorsCount(); ++i) {
m.vector(i) = x;
m3.vector(i) = x;
}
for (unsigned int i = 0; i < m.vectorsCount(); ++i) {
COMPARE(V(m.vector(i)), x);
COMPARE(V(m2.vector(i)), x);
COMPARE(V(m3.vector(i)), x);
}
}
template<typename V, unsigned int Size> void TestVectorReorganization<V, Size>::test()
{
typedef typename V::EntryType T;
typename V::Memory init;
for (unsigned int i = 0; i < V::Size; ++i) {
init[i] = i;
}
V x(init);
Memory<V, Size> m;
Memory<V> m3(Size);
for (unsigned int i = 0; i < m.vectorsCount(); ++i) {
m.vector(i) = x;
m3.vector(i) = x;
x += V::Size;
}
///////////////////////////////////////////////////////////////////////////
x = V(init);
for (unsigned int i = 0; i < m.vectorsCount(); ++i) {
COMPARE(V(m.vector(i)), x);
COMPARE(V(m3.vector(i)), x);
x += V::Size;
}
///////////////////////////////////////////////////////////////////////////
x = V(init);
unsigned int indexes[Size];
for (unsigned int i = 0; i < Size; ++i) {
indexes[i] = i;
}
for (unsigned int i = 0; i + V::Size < Size; ++i) {
COMPARE(m.gather(&indexes[i]), x);
COMPARE(m3.gather(&indexes[i]), x);
x += 1;
}
///////////////////////////////////////////////////////////////////////////
for (unsigned int i = 0; i < V::Size; ++i) {
init[i] = i * 2;
}
x = V(init);
for (unsigned int i = 0; i < Size; ++i) {
indexes[i] = (i * 2) % Size;
}
for (unsigned int i = 0; i + V::Size < Size; ++i) {
COMPARE(m.gather(&indexes[i]), x);
COMPARE(m3.gather(&indexes[i]), x);
x += 2;
x(x >= Size) -= Size;
}
}
template<typename V> void testEntries()
{
TestEntries<V, 128>::run();
}
template<typename V> void testVectors()
{
TestVectors<V, 128>::run();
}
template<typename V> void testVectorReorganization()
{
TestVectorReorganization<V, 128>::run();
}
template<typename V> void memoryOperators()
{
Memory<V, 129> m1, m2;
m1.setZero();
m2.setZero();
VERIFY(m1 == m2);
VERIFY(!(m1 != m2));
VERIFY(!(m1 < m2));
VERIFY(!(m1 > m2));
m1 += m2;
VERIFY(m1 == m2);
VERIFY(m1 <= m2);
VERIFY(m1 >= m2);
m1 += 1;
VERIFY(m1 != m2);
VERIFY(m1 > m2);
VERIFY(m1 >= m2);
VERIFY(m2 < m1);
VERIFY(m2 <= m1);
VERIFY(!(m1 == m2));
VERIFY(!(m1 <= m2));
VERIFY(!(m2 >= m1));
m2 += m1;
VERIFY(m1 == m2);
m2 *= 2;
m1 += 1;
VERIFY(m1 == m2);
m2 /= 2;
m1 -= 1;
VERIFY(m1 == m2);
m1 *= m2;
VERIFY(m1 == m2);
m1 /= m2;
VERIFY(m1 == m2);
m1 -= m2;
m2 -= m2;
VERIFY(m1 == m2);
}
int main()
{
testAllTypes(testEntries);
testAllTypes(testVectors);
testAllTypes(testVectorReorganization);
testAllTypes(memoryOperators);
return 0;
}
<commit_msg>test the new unaligned vector loads<commit_after>/* This file is part of the Vc library.
Copyright (C) 2009 Matthias Kretz <kretz@kde.org>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Vc/Vc>
#include "unittest.h"
using namespace Vc;
template<typename V, unsigned int Size> struct TestEntries {
static inline void run()
{
TestEntries<V, Size/2>::run();
TestEntries<V, Size>::test();
TestEntries<V, Size - 1>::test();
}
static void test();
};
template<typename V> struct TestEntries<V, 0> { static void run() {} static void test() {} };
template<typename V, unsigned int Size> struct TestVectors {
static inline void run()
{
TestVectors<V, Size/2>::run();
TestVectors<V, Size>::test();
TestVectors<V, Size - 1>::test();
}
static void test();
};
template<typename V> struct TestVectors<V, 0> { static void run() {} static void test() {} };
template<typename V, unsigned int Size> struct TestVectorReorganization {
static inline void run()
{
TestVectorReorganization<V, Size/2>::run();
TestVectorReorganization<V, Size>::test();
TestVectorReorganization<V, Size - 1>::test();
}
static void test();
};
template<typename V> struct TestVectorReorganization<V, 0> { static void run() {} static void test() {} };
template<typename V, unsigned int Size> void TestEntries<V, Size>::test()
{
typedef typename V::EntryType T;
const T x = Size;
Memory<V, Size> m;
const Memory<V, Size> &m2 = m;
Memory<V> m3(Size);
for (unsigned int i = 0; i < Size; ++i) {
m[i] = x;
m3[i] = x;
}
for (unsigned int i = 0; i < Size; ++i) {
COMPARE(m[i], x);
COMPARE(m2[i], x);
COMPARE(m3[i], x);
}
for (unsigned int i = 0; i < Size; ++i) {
COMPARE(m.entries()[i], x);
COMPARE(m2.entries()[i], x);
COMPARE(m3.entries()[i], x);
}
const T *ptr = m2;
for (unsigned int i = 0; i < Size; ++i) {
COMPARE(ptr[i], x);
}
ptr = m3;
for (unsigned int i = 0; i < Size; ++i) {
COMPARE(ptr[i], x);
}
}
template<typename V, unsigned int Size> void TestVectors<V, Size>::test()
{
typedef typename V::EntryType T;
const V startX(V::IndexType::IndexesFromZero() + Size);
Memory<V, Size> m;
const Memory<V, Size> &m2 = m;
Memory<V> m3(Size);
V x = startX;
for (unsigned int i = 0; i < m.vectorsCount(); ++i, x += V::Size) {
m.vector(i) = x;
m3.vector(i) = x;
}
x = startX;
unsigned int i;
for (i = 0; i < m.vectorsCount() - 1; ++i) {
COMPARE(V(m.vector(i)), x);
COMPARE(V(m2.vector(i)), x);
COMPARE(V(m3.vector(i)), x);
for (int shift = 0; shift < V::Size; ++shift, ++x) {
COMPARE(V(m.vector(i, shift)), x);
COMPARE(V(m2.vector(i, shift)), x);
COMPARE(V(m3.vector(i, shift)), x);
}
}
COMPARE(V(m.vector(i)), x);
COMPARE(V(m2.vector(i)), x);
COMPARE(V(m3.vector(i)), x);
}
template<typename V, unsigned int Size> void TestVectorReorganization<V, Size>::test()
{
typedef typename V::EntryType T;
typename V::Memory init;
for (unsigned int i = 0; i < V::Size; ++i) {
init[i] = i;
}
V x(init);
Memory<V, Size> m;
Memory<V> m3(Size);
for (unsigned int i = 0; i < m.vectorsCount(); ++i) {
m.vector(i) = x;
m3.vector(i) = x;
x += V::Size;
}
///////////////////////////////////////////////////////////////////////////
x = V(init);
for (unsigned int i = 0; i < m.vectorsCount(); ++i) {
COMPARE(V(m.vector(i)), x);
COMPARE(V(m3.vector(i)), x);
x += V::Size;
}
///////////////////////////////////////////////////////////////////////////
x = V(init);
unsigned int indexes[Size];
for (unsigned int i = 0; i < Size; ++i) {
indexes[i] = i;
}
for (unsigned int i = 0; i + V::Size < Size; ++i) {
COMPARE(m.gather(&indexes[i]), x);
COMPARE(m3.gather(&indexes[i]), x);
x += 1;
}
///////////////////////////////////////////////////////////////////////////
for (unsigned int i = 0; i < V::Size; ++i) {
init[i] = i * 2;
}
x = V(init);
for (unsigned int i = 0; i < Size; ++i) {
indexes[i] = (i * 2) % Size;
}
for (unsigned int i = 0; i + V::Size < Size; ++i) {
COMPARE(m.gather(&indexes[i]), x);
COMPARE(m3.gather(&indexes[i]), x);
x += 2;
x(x >= Size) -= Size;
}
}
template<typename V> void testEntries()
{
TestEntries<V, 128>::run();
}
template<typename V> void testVectors()
{
TestVectors<V, 128>::run();
}
template<typename V> void testVectorReorganization()
{
TestVectorReorganization<V, 128>::run();
}
template<typename V> void memoryOperators()
{
Memory<V, 129> m1, m2;
m1.setZero();
m2.setZero();
VERIFY(m1 == m2);
VERIFY(!(m1 != m2));
VERIFY(!(m1 < m2));
VERIFY(!(m1 > m2));
m1 += m2;
VERIFY(m1 == m2);
VERIFY(m1 <= m2);
VERIFY(m1 >= m2);
m1 += 1;
VERIFY(m1 != m2);
VERIFY(m1 > m2);
VERIFY(m1 >= m2);
VERIFY(m2 < m1);
VERIFY(m2 <= m1);
VERIFY(!(m1 == m2));
VERIFY(!(m1 <= m2));
VERIFY(!(m2 >= m1));
m2 += m1;
VERIFY(m1 == m2);
m2 *= 2;
m1 += 1;
VERIFY(m1 == m2);
m2 /= 2;
m1 -= 1;
VERIFY(m1 == m2);
m1 *= m2;
VERIFY(m1 == m2);
m1 /= m2;
VERIFY(m1 == m2);
m1 -= m2;
m2 -= m2;
VERIFY(m1 == m2);
}
int main()
{
testAllTypes(testEntries);
testAllTypes(testVectors);
testAllTypes(testVectorReorganization);
testAllTypes(memoryOperators);
return 0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Library
Module: Source.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization
Library. No part of this file or its
contents may be copied, reproduced or
altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "Source.hh"
void vlSource::Execute()
{
cerr << "Executing Source\n";
}
void vlSource::Update()
{
// Make sure virtual getMtime method is called since subclasses will overload
if ( this->GetMtime() > this->ExecuteTime )
{
if ( this->StartMethod ) (*this->StartMethod)();
this->Execute();
this->ExecuteTime.Modified();
if ( this->EndMethod ) (*this->EndMethod)();
}
}
void vlSource::SetStartMethod(void (*f)())
{
if ( f != this->StartMethod )
{
this->StartMethod = f;
this->Modified();
}
}
void vlSource::SetEndMethod(void (*f)())
{
if ( f != this->EndMethod )
{
this->EndMethod = f;
this->Modified();
}
}
void vlSource::PrintSelf(ostream& os, vlIndent indent)
{
vlObject::PrintSelf(os,indent);
os << indent << "Execute time: " << this->ExecuteTime.GetMtime() << "\n";
}
<commit_msg>Just fixed the header some<commit_after>/*=========================================================================
Program: Visualization Library
Module: Source.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "Source.hh"
void vlSource::Execute()
{
cerr << "Executing Source\n";
}
void vlSource::Update()
{
// Make sure virtual getMtime method is called since subclasses will overload
if ( this->GetMtime() > this->ExecuteTime )
{
if ( this->StartMethod ) (*this->StartMethod)();
this->Execute();
this->ExecuteTime.Modified();
if ( this->EndMethod ) (*this->EndMethod)();
}
}
void vlSource::SetStartMethod(void (*f)())
{
if ( f != this->StartMethod )
{
this->StartMethod = f;
this->Modified();
}
}
void vlSource::SetEndMethod(void (*f)())
{
if ( f != this->EndMethod )
{
this->EndMethod = f;
this->Modified();
}
}
void vlSource::PrintSelf(ostream& os, vlIndent indent)
{
vlObject::PrintSelf(os,indent);
os << indent << "Execute time: " << this->ExecuteTime.GetMtime() << "\n";
}
<|endoftext|> |
<commit_before>///
/// @file api-c.cpp
/// @brief primesieve C API.
/// Contains the implementations of the functions declared
/// in the primesieve.h header file.
///
/// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve.h>
#include <primesieve.hpp>
#include <primesieve/malloc_vector.hpp>
#include <stdint.h>
#include <cstdlib>
#include <cstddef>
#include <cerrno>
#include <exception>
using namespace std;
using namespace primesieve;
namespace {
template <typename T>
void* store_primes(uint64_t start, uint64_t stop, size_t* size)
{
try
{
malloc_vector<T> primes;
store_primes(start, stop, primes);
if (size)
*size = primes.size();
primes.disable_free();
return primes.data();
}
catch (exception&)
{
if (size)
*size = 0;
errno = EDOM;
return nullptr;
}
}
template <typename T>
void* store_n_primes(uint64_t n, uint64_t start)
{
try
{
malloc_vector<T> primes;
store_n_primes(n, start, primes);
primes.disable_free();
return primes.data();
}
catch (exception&)
{
errno = EDOM;
return nullptr;
}
}
} // namespace
void* primesieve_generate_primes(uint64_t start, uint64_t stop, size_t* size, int type)
{
switch (type)
{
case SHORT_PRIMES: return store_primes<short>(start, stop, size);
case USHORT_PRIMES: return store_primes<unsigned short>(start, stop, size);
case INT_PRIMES: return store_primes<int>(start, stop, size);
case UINT_PRIMES: return store_primes<unsigned int>(start, stop, size);
case LONG_PRIMES: return store_primes<long>(start, stop, size);
case ULONG_PRIMES: return store_primes<unsigned long>(start, stop, size);
case LONGLONG_PRIMES: return store_primes<long long>(start, stop, size);
case ULONGLONG_PRIMES: return store_primes<unsigned long long>(start, stop, size);
case INT16_PRIMES: return store_primes<int16_t>(start, stop, size);
case UINT16_PRIMES: return store_primes<uint16_t>(start, stop, size);
case INT32_PRIMES: return store_primes<int32_t>(start, stop, size);
case UINT32_PRIMES: return store_primes<uint32_t>(start, stop, size);
case INT64_PRIMES: return store_primes<int64_t>(start, stop, size);
case UINT64_PRIMES: return store_primes<uint64_t>(start, stop, size);
}
if (size)
*size = 0;
errno = EDOM;
return nullptr;
}
void* primesieve_generate_n_primes(uint64_t n, uint64_t start, int type)
{
switch (type)
{
case SHORT_PRIMES: return store_n_primes<short>(n, start);
case USHORT_PRIMES: return store_n_primes<unsigned short>(n, start);
case INT_PRIMES: return store_n_primes<int>(n, start);
case UINT_PRIMES: return store_n_primes<unsigned int>(n, start);
case LONG_PRIMES: return store_n_primes<long>(n, start);
case ULONG_PRIMES: return store_n_primes<unsigned long>(n, start);
case LONGLONG_PRIMES: return store_n_primes<long long>(n, start);
case ULONGLONG_PRIMES: return store_n_primes<unsigned long long>(n, start);
case INT16_PRIMES: return store_n_primes<int16_t>(n, start);
case UINT16_PRIMES: return store_n_primes<uint16_t>(n, start);
case INT32_PRIMES: return store_n_primes<int32_t>(n, start);
case UINT32_PRIMES: return store_n_primes<uint32_t>(n, start);
case INT64_PRIMES: return store_n_primes<int64_t>(n, start);
case UINT64_PRIMES: return store_n_primes<uint64_t>(n, start);
}
errno = EDOM;
return nullptr;
}
void primesieve_free(void* primes)
{
free(primes);
}
uint64_t primesieve_nth_prime(int64_t n, uint64_t start)
{
try
{
return nth_prime(n, start);
}
catch (exception&)
{
errno = EDOM;
return PRIMESIEVE_ERROR;
}
}
uint64_t primesieve_count_primes(uint64_t start, uint64_t stop)
{
try
{
return count_primes(start, stop);
}
catch (exception&)
{
errno = EDOM;
return PRIMESIEVE_ERROR;
}
}
uint64_t primesieve_count_twins(uint64_t start, uint64_t stop)
{
try
{
return count_twins(start, stop);
}
catch (exception&)
{
errno = EDOM;
return PRIMESIEVE_ERROR;
}
}
uint64_t primesieve_count_triplets(uint64_t start, uint64_t stop)
{
try
{
return count_triplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
return PRIMESIEVE_ERROR;
}
}
uint64_t primesieve_count_quadruplets(uint64_t start, uint64_t stop)
{
try
{
return count_quadruplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
return PRIMESIEVE_ERROR;
}
}
uint64_t primesieve_count_quintuplets(uint64_t start, uint64_t stop)
{
try
{
return count_quintuplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
return PRIMESIEVE_ERROR;
}
}
uint64_t primesieve_count_sextuplets(uint64_t start, uint64_t stop)
{
try
{
return count_sextuplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
return PRIMESIEVE_ERROR;
}
}
void primesieve_print_primes(uint64_t start, uint64_t stop)
{
try
{
print_primes(start, stop);
}
catch (exception&)
{
errno = EDOM;
}
}
void primesieve_print_twins(uint64_t start, uint64_t stop)
{
try
{
print_twins(start, stop);
}
catch (exception&)
{
errno = EDOM;
}
}
void primesieve_print_triplets(uint64_t start, uint64_t stop)
{
try
{
print_triplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
}
}
void primesieve_print_quadruplets(uint64_t start, uint64_t stop)
{
try
{
print_quadruplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
}
}
void primesieve_print_quintuplets(uint64_t start, uint64_t stop)
{
try
{
print_quintuplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
}
}
void primesieve_print_sextuplets(uint64_t start, uint64_t stop)
{
try
{
print_sextuplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
}
}
int primesieve_get_sieve_size()
{
return get_sieve_size();
}
int primesieve_get_num_threads()
{
return get_num_threads();
}
void primesieve_set_sieve_size(int sieve_size)
{
set_sieve_size(sieve_size);
}
void primesieve_set_num_threads(int num_threads)
{
set_num_threads(num_threads);
}
uint64_t primesieve_get_max_stop()
{
return get_max_stop();
}
const char* primesieve_version()
{
return PRIMESIEVE_VERSION;
}
<commit_msg>Refactor<commit_after>///
/// @file api-c.cpp
/// @brief primesieve C API.
/// Contains the implementations of the functions declared
/// in the primesieve.h header file.
///
/// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve.h>
#include <primesieve.hpp>
#include <primesieve/malloc_vector.hpp>
#include <stdint.h>
#include <cstdlib>
#include <cstddef>
#include <cerrno>
#include <exception>
using namespace std;
using namespace primesieve;
namespace {
template <typename T>
void* get_primes(uint64_t start, uint64_t stop, size_t* size)
{
try
{
malloc_vector<T> primes;
store_primes(start, stop, primes);
if (size)
*size = primes.size();
primes.disable_free();
return primes.data();
}
catch (exception&)
{
if (size)
*size = 0;
errno = EDOM;
return nullptr;
}
}
template <typename T>
void* get_n_primes(uint64_t n, uint64_t start)
{
try
{
malloc_vector<T> primes;
store_n_primes(n, start, primes);
primes.disable_free();
return primes.data();
}
catch (exception&)
{
errno = EDOM;
return nullptr;
}
}
} // namespace
void* primesieve_generate_primes(uint64_t start, uint64_t stop, size_t* size, int type)
{
switch (type)
{
case SHORT_PRIMES: return get_primes<short>(start, stop, size);
case USHORT_PRIMES: return get_primes<unsigned short>(start, stop, size);
case INT_PRIMES: return get_primes<int>(start, stop, size);
case UINT_PRIMES: return get_primes<unsigned int>(start, stop, size);
case LONG_PRIMES: return get_primes<long>(start, stop, size);
case ULONG_PRIMES: return get_primes<unsigned long>(start, stop, size);
case LONGLONG_PRIMES: return get_primes<long long>(start, stop, size);
case ULONGLONG_PRIMES: return get_primes<unsigned long long>(start, stop, size);
case INT16_PRIMES: return get_primes<int16_t>(start, stop, size);
case UINT16_PRIMES: return get_primes<uint16_t>(start, stop, size);
case INT32_PRIMES: return get_primes<int32_t>(start, stop, size);
case UINT32_PRIMES: return get_primes<uint32_t>(start, stop, size);
case INT64_PRIMES: return get_primes<int64_t>(start, stop, size);
case UINT64_PRIMES: return get_primes<uint64_t>(start, stop, size);
}
if (size)
*size = 0;
errno = EDOM;
return nullptr;
}
void* primesieve_generate_n_primes(uint64_t n, uint64_t start, int type)
{
switch (type)
{
case SHORT_PRIMES: return get_n_primes<short>(n, start);
case USHORT_PRIMES: return get_n_primes<unsigned short>(n, start);
case INT_PRIMES: return get_n_primes<int>(n, start);
case UINT_PRIMES: return get_n_primes<unsigned int>(n, start);
case LONG_PRIMES: return get_n_primes<long>(n, start);
case ULONG_PRIMES: return get_n_primes<unsigned long>(n, start);
case LONGLONG_PRIMES: return get_n_primes<long long>(n, start);
case ULONGLONG_PRIMES: return get_n_primes<unsigned long long>(n, start);
case INT16_PRIMES: return get_n_primes<int16_t>(n, start);
case UINT16_PRIMES: return get_n_primes<uint16_t>(n, start);
case INT32_PRIMES: return get_n_primes<int32_t>(n, start);
case UINT32_PRIMES: return get_n_primes<uint32_t>(n, start);
case INT64_PRIMES: return get_n_primes<int64_t>(n, start);
case UINT64_PRIMES: return get_n_primes<uint64_t>(n, start);
}
errno = EDOM;
return nullptr;
}
void primesieve_free(void* primes)
{
free(primes);
}
uint64_t primesieve_nth_prime(int64_t n, uint64_t start)
{
try
{
return nth_prime(n, start);
}
catch (exception&)
{
errno = EDOM;
return PRIMESIEVE_ERROR;
}
}
uint64_t primesieve_count_primes(uint64_t start, uint64_t stop)
{
try
{
return count_primes(start, stop);
}
catch (exception&)
{
errno = EDOM;
return PRIMESIEVE_ERROR;
}
}
uint64_t primesieve_count_twins(uint64_t start, uint64_t stop)
{
try
{
return count_twins(start, stop);
}
catch (exception&)
{
errno = EDOM;
return PRIMESIEVE_ERROR;
}
}
uint64_t primesieve_count_triplets(uint64_t start, uint64_t stop)
{
try
{
return count_triplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
return PRIMESIEVE_ERROR;
}
}
uint64_t primesieve_count_quadruplets(uint64_t start, uint64_t stop)
{
try
{
return count_quadruplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
return PRIMESIEVE_ERROR;
}
}
uint64_t primesieve_count_quintuplets(uint64_t start, uint64_t stop)
{
try
{
return count_quintuplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
return PRIMESIEVE_ERROR;
}
}
uint64_t primesieve_count_sextuplets(uint64_t start, uint64_t stop)
{
try
{
return count_sextuplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
return PRIMESIEVE_ERROR;
}
}
void primesieve_print_primes(uint64_t start, uint64_t stop)
{
try
{
print_primes(start, stop);
}
catch (exception&)
{
errno = EDOM;
}
}
void primesieve_print_twins(uint64_t start, uint64_t stop)
{
try
{
print_twins(start, stop);
}
catch (exception&)
{
errno = EDOM;
}
}
void primesieve_print_triplets(uint64_t start, uint64_t stop)
{
try
{
print_triplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
}
}
void primesieve_print_quadruplets(uint64_t start, uint64_t stop)
{
try
{
print_quadruplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
}
}
void primesieve_print_quintuplets(uint64_t start, uint64_t stop)
{
try
{
print_quintuplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
}
}
void primesieve_print_sextuplets(uint64_t start, uint64_t stop)
{
try
{
print_sextuplets(start, stop);
}
catch (exception&)
{
errno = EDOM;
}
}
int primesieve_get_sieve_size()
{
return get_sieve_size();
}
int primesieve_get_num_threads()
{
return get_num_threads();
}
void primesieve_set_sieve_size(int sieve_size)
{
set_sieve_size(sieve_size);
}
void primesieve_set_num_threads(int num_threads)
{
set_num_threads(num_threads);
}
uint64_t primesieve_get_max_stop()
{
return get_max_stop();
}
const char* primesieve_version()
{
return PRIMESIEVE_VERSION;
}
<|endoftext|> |
<commit_before>/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012
This file is part of Lasercake.
Lasercake 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.
Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LASERCAKE_TILE_PHYSICS_HPP__
#define LASERCAKE_TILE_PHYSICS_HPP__
#include "world.hpp"
namespace tile_physics_impl {
typedef lasercake_int<int64_t>::type water_tile_count;
typedef lasercake_int<int64_t>::type water_group_identifier;
const water_group_identifier NO_WATER_GROUP = 0;
struct state_t;
// "progress" is measured in the smaller, velocity units.
inline sub_tile_distance progress_necessary(cardinal_direction dir) {
return tile_size[which_dimension_is_cardinal_direction(dir)] * velocity_scale_factor;
}
struct active_fluid_tile_info {
// Constructing one of these in the default way yields the natural inactive state
active_fluid_tile_info();
bool is_in_inactive_state()const;
vector3<sub_tile_distance> velocity;
value_for_each_cardinal_direction<sub_tile_distance> progress;
value_for_each_cardinal_direction<sub_tile_distance> blockage_amount_this_frame;
//int frames_until_can_become_groupable = 0;
};
typedef unordered_map<tile_location, active_fluid_tile_info> active_fluids_t;
struct persistent_water_group_info {
literally_random_access_removable_tiles_by_height suckable_tiles_by_height;
literally_random_access_removable_tiles_by_height pushable_tiles_by_height;
map<tile_coordinate, water_tile_count> num_tiles_by_height;
unordered_set<tile_location> surface_tiles;
mutable map<tile_coordinate, fine_scalar> pressure_caches;
mutable map<tile_coordinate, water_tile_count> width_of_widest_level_so_far_caches;
//bool is_infinite;
//tile_coordinate infinite_ocean_height;
void recompute_num_tiles_by_height_from_surface_tiles(state_t const& w);
fine_scalar get_pressure_at_height(tile_coordinate height)const;
tile_location get_and_erase_random_pushable_tile_below_weighted_by_pressure(tile_coordinate height);
bool mark_tile_as_suckable_and_return_true_if_it_is_immediately_sucked_away(state_t& state, tile_location const& loc, active_fluids_t& active_fluids);
bool mark_tile_as_pushable_and_return_true_if_it_is_immediately_pushed_into(state_t& state, tile_location const& loc, active_fluids_t& active_fluids);
};
typedef unordered_map<water_group_identifier, persistent_water_group_info> persistent_water_groups_t;
typedef unordered_map<tile_location, water_group_identifier> water_groups_by_location_t;
template<cardinal_direction Dir> struct volume_calipers_tile_compare_for_dir;
template<> struct volume_calipers_tile_compare_for_dir<xplus > { typedef tile_compare_yzx type; };
template<> struct volume_calipers_tile_compare_for_dir<xminus> { typedef tile_compare_yzx type; };
template<> struct volume_calipers_tile_compare_for_dir<yplus > { typedef tile_compare_zxy type; };
template<> struct volume_calipers_tile_compare_for_dir<yminus> { typedef tile_compare_zxy type; };
template<> struct volume_calipers_tile_compare_for_dir<zplus > { typedef tile_compare_xyz type; };
template<> struct volume_calipers_tile_compare_for_dir<zminus> { typedef tile_compare_xyz type; };
// TileLocationIsPartOfVolume is a predicate (functor returning bool)
// with a member: static const level_of_tile_realization_needed realineeded = ...;
template<cardinal_direction Dir, typename TileLocationIsPartOfVolume>
struct volume_calipers {
typedef typename volume_calipers_tile_compare_for_dir<Dir>::type tile_compare;
static const level_of_tile_realization_needed realineeded = TileLocationIsPartOfVolume::realineeded;
static const cardinal_direction forward = Dir;
static const cardinal_direction backward = cdir_info<Dir>::opposite;
// This set contains the boundary tiles that are part of the volume,
// but not the boundary tiles that are non-volume.
set<tile_location, tile_compare> boundary_tiles_in_dimension;
TileLocationIsPartOfVolume predicate;
// These functions must be called whenever a relevant tile
// changes its TileLocationIsPartOfVolume status.
// ("inserted" = predicate is true, "removed" = predicate is false)
void handle_tile_insertion(tile_location const& loc) {
// We *may* have removed boundaries in either direction, and we *may* now be a boundary tile ourselves.
const tile_location further_in_positive_direction_loc = loc.get_neighbor<forward >(realineeded);
const tile_location further_in_negative_direction_loc = loc.get_neighbor<backward>(realineeded);
bool we_are_boundary_tile = false;
if (predicate(further_in_positive_direction_loc)) {
if (predicate(further_in_positive_direction_loc.get_neighbor<forward >(realineeded))) {
boundary_tiles_in_dimension.erase(further_in_positive_direction_loc);
}
}
else we_are_boundary_tile = true;
if (predicate(further_in_negative_direction_loc)) {
if (predicate(further_in_negative_direction_loc.get_neighbor<backward>(realineeded))) {
boundary_tiles_in_dimension.erase(further_in_negative_direction_loc);
}
}
else we_are_boundary_tile = true;
if (we_are_boundary_tile) boundary_tiles_in_dimension.insert(loc);
}
void handle_tile_removal(tile_location const& loc) {
// This tile is no longer groupable at all, so it can't be a boundary tile
boundary_tiles_in_dimension.erase(loc);
// If there are groupable tiles next to us, they must now be boundary tiles,
// because our deletion exposed them
const tile_location further_in_positive_direction_loc = loc.get_neighbor<forward >(realineeded);
const tile_location further_in_negative_direction_loc = loc.get_neighbor<backward>(realineeded);
if (predicate(further_in_positive_direction_loc)) {
boundary_tiles_in_dimension.insert(further_in_positive_direction_loc);
}
if (predicate(further_in_negative_direction_loc)) {
boundary_tiles_in_dimension.insert(further_in_negative_direction_loc);
}
}
};
struct is_groupable_water {
static const level_of_tile_realization_needed realineeded = CONTENTS_ONLY;
bool operator()(tile_location const& loc)const {
return loc.stuff_at().contents() == GROUPABLE_WATER;
}
};
// We could easily keep lists of boundary tiles in all three dimensions.
// The only reason we don't is because there's no need for any of the others right now.
// (And it would take that much extra space (proportional to the that-dimension surface area)
// and time (proportional to how much the groupable-water landscape changes)).
typedef volume_calipers<xplus, is_groupable_water> groupable_water_volume_calipers_t;
struct state_t {
//state_t(world_collision_detector& d):next_water_group_identifier(1), things_exposed_to_collision(d){}
state_t(world& w):next_water_group_identifier(1), access_the_world(w), rng(w.get_rng()){}
water_group_identifier next_water_group_identifier;
water_groups_by_location_t water_groups_by_surface_tile;
persistent_water_groups_t persistent_water_groups;
groupable_water_volume_calipers_t groupable_water_volume_calipers;
active_fluids_t active_fluids;
//only used in replace_substance(), to get world_collision_detector& things_exposed_to_collision:
world& access_the_world;
large_fast_noncrypto_rng& rng;
};
} // end namespace tile_physics_impl
#endif
<commit_msg>fix tile_physics.hpp for units<commit_after>/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012
This file is part of Lasercake.
Lasercake 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.
Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LASERCAKE_TILE_PHYSICS_HPP__
#define LASERCAKE_TILE_PHYSICS_HPP__
#include "world.hpp"
namespace tile_physics_impl {
typedef lasercake_int<int64_t>::type water_tile_count;
typedef lasercake_int<int64_t>::type water_group_identifier;
const water_group_identifier NO_WATER_GROUP = 0;
struct state_t;
// "progress" is measured in the smaller, velocity units.
inline sub_tile_distance progress_necessary(cardinal_direction dir) {
return sub_tile_distance(
tile_size[which_dimension_is_cardinal_direction(dir)]
* identity(tile_physics_sub_tile_units / fine_units));
}
struct active_fluid_tile_info {
// Constructing one of these in the default way yields the natural inactive state
active_fluid_tile_info();
bool is_in_inactive_state()const;
vector3<sub_tile_distance> velocity;
value_for_each_cardinal_direction<sub_tile_distance> progress;
value_for_each_cardinal_direction<sub_tile_distance> blockage_amount_this_frame;
//int frames_until_can_become_groupable = 0;
};
typedef unordered_map<tile_location, active_fluid_tile_info> active_fluids_t;
struct persistent_water_group_info {
literally_random_access_removable_tiles_by_height suckable_tiles_by_height;
literally_random_access_removable_tiles_by_height pushable_tiles_by_height;
map<tile_coordinate, water_tile_count> num_tiles_by_height;
unordered_set<tile_location> surface_tiles;
mutable map<tile_coordinate, fine_scalar> pressure_caches;
mutable map<tile_coordinate, water_tile_count> width_of_widest_level_so_far_caches;
//bool is_infinite;
//tile_coordinate infinite_ocean_height;
void recompute_num_tiles_by_height_from_surface_tiles(state_t const& w);
fine_scalar get_pressure_at_height(tile_coordinate height)const;
tile_location get_and_erase_random_pushable_tile_below_weighted_by_pressure(tile_coordinate height);
bool mark_tile_as_suckable_and_return_true_if_it_is_immediately_sucked_away(state_t& state, tile_location const& loc, active_fluids_t& active_fluids);
bool mark_tile_as_pushable_and_return_true_if_it_is_immediately_pushed_into(state_t& state, tile_location const& loc, active_fluids_t& active_fluids);
};
typedef unordered_map<water_group_identifier, persistent_water_group_info> persistent_water_groups_t;
typedef unordered_map<tile_location, water_group_identifier> water_groups_by_location_t;
template<cardinal_direction Dir> struct volume_calipers_tile_compare_for_dir;
template<> struct volume_calipers_tile_compare_for_dir<xplus > { typedef tile_compare_yzx type; };
template<> struct volume_calipers_tile_compare_for_dir<xminus> { typedef tile_compare_yzx type; };
template<> struct volume_calipers_tile_compare_for_dir<yplus > { typedef tile_compare_zxy type; };
template<> struct volume_calipers_tile_compare_for_dir<yminus> { typedef tile_compare_zxy type; };
template<> struct volume_calipers_tile_compare_for_dir<zplus > { typedef tile_compare_xyz type; };
template<> struct volume_calipers_tile_compare_for_dir<zminus> { typedef tile_compare_xyz type; };
// TileLocationIsPartOfVolume is a predicate (functor returning bool)
// with a member: static const level_of_tile_realization_needed realineeded = ...;
template<cardinal_direction Dir, typename TileLocationIsPartOfVolume>
struct volume_calipers {
typedef typename volume_calipers_tile_compare_for_dir<Dir>::type tile_compare;
static const level_of_tile_realization_needed realineeded = TileLocationIsPartOfVolume::realineeded;
static const cardinal_direction forward = Dir;
static const cardinal_direction backward = cdir_info<Dir>::opposite;
// This set contains the boundary tiles that are part of the volume,
// but not the boundary tiles that are non-volume.
set<tile_location, tile_compare> boundary_tiles_in_dimension;
TileLocationIsPartOfVolume predicate;
// These functions must be called whenever a relevant tile
// changes its TileLocationIsPartOfVolume status.
// ("inserted" = predicate is true, "removed" = predicate is false)
void handle_tile_insertion(tile_location const& loc) {
// We *may* have removed boundaries in either direction, and we *may* now be a boundary tile ourselves.
const tile_location further_in_positive_direction_loc = loc.get_neighbor<forward >(realineeded);
const tile_location further_in_negative_direction_loc = loc.get_neighbor<backward>(realineeded);
bool we_are_boundary_tile = false;
if (predicate(further_in_positive_direction_loc)) {
if (predicate(further_in_positive_direction_loc.get_neighbor<forward >(realineeded))) {
boundary_tiles_in_dimension.erase(further_in_positive_direction_loc);
}
}
else we_are_boundary_tile = true;
if (predicate(further_in_negative_direction_loc)) {
if (predicate(further_in_negative_direction_loc.get_neighbor<backward>(realineeded))) {
boundary_tiles_in_dimension.erase(further_in_negative_direction_loc);
}
}
else we_are_boundary_tile = true;
if (we_are_boundary_tile) boundary_tiles_in_dimension.insert(loc);
}
void handle_tile_removal(tile_location const& loc) {
// This tile is no longer groupable at all, so it can't be a boundary tile
boundary_tiles_in_dimension.erase(loc);
// If there are groupable tiles next to us, they must now be boundary tiles,
// because our deletion exposed them
const tile_location further_in_positive_direction_loc = loc.get_neighbor<forward >(realineeded);
const tile_location further_in_negative_direction_loc = loc.get_neighbor<backward>(realineeded);
if (predicate(further_in_positive_direction_loc)) {
boundary_tiles_in_dimension.insert(further_in_positive_direction_loc);
}
if (predicate(further_in_negative_direction_loc)) {
boundary_tiles_in_dimension.insert(further_in_negative_direction_loc);
}
}
};
struct is_groupable_water {
static const level_of_tile_realization_needed realineeded = CONTENTS_ONLY;
bool operator()(tile_location const& loc)const {
return loc.stuff_at().contents() == GROUPABLE_WATER;
}
};
// We could easily keep lists of boundary tiles in all three dimensions.
// The only reason we don't is because there's no need for any of the others right now.
// (And it would take that much extra space (proportional to the that-dimension surface area)
// and time (proportional to how much the groupable-water landscape changes)).
typedef volume_calipers<xplus, is_groupable_water> groupable_water_volume_calipers_t;
struct state_t {
//state_t(world_collision_detector& d):next_water_group_identifier(1), things_exposed_to_collision(d){}
state_t(world& w):next_water_group_identifier(1), access_the_world(w), rng(w.get_rng()){}
water_group_identifier next_water_group_identifier;
water_groups_by_location_t water_groups_by_surface_tile;
persistent_water_groups_t persistent_water_groups;
groupable_water_volume_calipers_t groupable_water_volume_calipers;
active_fluids_t active_fluids;
//only used in replace_substance(), to get world_collision_detector& things_exposed_to_collision:
world& access_the_world;
large_fast_noncrypto_rng& rng;
};
} // end namespace tile_physics_impl
#endif
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#define EIGEN_NO_STATIC_ASSERT
#include "main.h"
template<typename MatrixType> void basicStuff(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;
Index rows = m.rows();
Index cols = m.cols();
// this test relies a lot on Random.h, and there's not much more that we can do
// to test it, hence I consider that we will have tested Random.h
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols),
m3(rows, cols),
mzero = MatrixType::Zero(rows, cols),
square = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>::Random(rows, rows);
VectorType v1 = VectorType::Random(rows),
vzero = VectorType::Zero(rows);
SquareMatrixType sm1 = SquareMatrixType::Random(rows,rows), sm2(rows,rows);
Scalar x = 0;
while(x == Scalar(0)) x = internal::random<Scalar>();
Index r = internal::random<Index>(0, rows-1),
c = internal::random<Index>(0, cols-1);
m1.coeffRef(r,c) = x;
VERIFY_IS_APPROX(x, m1.coeff(r,c));
m1(r,c) = x;
VERIFY_IS_APPROX(x, m1(r,c));
v1.coeffRef(r) = x;
VERIFY_IS_APPROX(x, v1.coeff(r));
v1(r) = x;
VERIFY_IS_APPROX(x, v1(r));
v1[r] = x;
VERIFY_IS_APPROX(x, v1[r]);
VERIFY_IS_APPROX( v1, v1);
VERIFY_IS_NOT_APPROX( v1, 2*v1);
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1);
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1.squaredNorm());
VERIFY_IS_NOT_MUCH_SMALLER_THAN(v1, v1);
VERIFY_IS_APPROX( vzero, v1-v1);
VERIFY_IS_APPROX( m1, m1);
VERIFY_IS_NOT_APPROX( m1, 2*m1);
VERIFY_IS_MUCH_SMALLER_THAN( mzero, m1);
VERIFY_IS_NOT_MUCH_SMALLER_THAN(m1, m1);
VERIFY_IS_APPROX( mzero, m1-m1);
// always test operator() on each read-only expression class,
// in order to check const-qualifiers.
// indeed, if an expression class (here Zero) is meant to be read-only,
// hence has no _write() method, the corresponding MatrixBase method (here zero())
// should return a const-qualified object so that it is the const-qualified
// operator() that gets called, which in turn calls _read().
VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows,cols)(r,c), static_cast<Scalar>(1));
// now test copying a row-vector into a (column-)vector and conversely.
square.col(r) = square.row(r).eval();
Matrix<Scalar, 1, MatrixType::RowsAtCompileTime> rv(rows);
Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> cv(rows);
rv = square.row(r);
cv = square.col(r);
VERIFY_IS_APPROX(rv, cv.transpose());
if(cols!=1 && rows!=1 && MatrixType::SizeAtCompileTime!=Dynamic)
{
VERIFY_RAISES_ASSERT(m1 = (m2.block(0,0, rows-1, cols-1)));
}
if(cols!=1 && rows!=1)
{
VERIFY_RAISES_ASSERT(m1[0]);
VERIFY_RAISES_ASSERT((m1+m1)[0]);
}
VERIFY_IS_APPROX(m3 = m1,m1);
MatrixType m4;
VERIFY_IS_APPROX(m4 = m1,m1);
m3.real() = m1.real();
VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), static_cast<const MatrixType&>(m1).real());
VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), m1.real());
// check == / != operators
VERIFY(m1==m1);
VERIFY(m1!=m2);
VERIFY(!(m1==m2));
VERIFY(!(m1!=m1));
m1 = m2;
VERIFY(m1==m2);
VERIFY(!(m1!=m2));
// check automatic transposition
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i) = sm1.row(i);
VERIFY_IS_APPROX(sm2,sm1.transpose());
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i).noalias() = sm1.row(i);
VERIFY_IS_APPROX(sm2,sm1.transpose());
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i).noalias() += sm1.row(i);
VERIFY_IS_APPROX(sm2,sm1.transpose());
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i).noalias() -= sm1.row(i);
VERIFY_IS_APPROX(sm2,-sm1.transpose());
}
template<typename MatrixType> void basicStuffComplex(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, MatrixType::ColsAtCompileTime> RealMatrixType;
Index rows = m.rows();
Index cols = m.cols();
Scalar s1 = internal::random<Scalar>(),
s2 = internal::random<Scalar>();
VERIFY(numext::real(s1)==numext::real_ref(s1));
VERIFY(numext::imag(s1)==numext::imag_ref(s1));
numext::real_ref(s1) = numext::real(s2);
numext::imag_ref(s1) = numext::imag(s2);
VERIFY(internal::isApprox(s1, s2, NumTraits<RealScalar>::epsilon()));
// extended precision in Intel FPUs means that s1 == s2 in the line above is not guaranteed.
RealMatrixType rm1 = RealMatrixType::Random(rows,cols),
rm2 = RealMatrixType::Random(rows,cols);
MatrixType cm(rows,cols);
cm.real() = rm1;
cm.imag() = rm2;
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).real(), rm1);
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).imag(), rm2);
rm1.setZero();
rm2.setZero();
rm1 = cm.real();
rm2 = cm.imag();
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).real(), rm1);
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).imag(), rm2);
cm.real().setZero();
VERIFY(static_cast<const MatrixType&>(cm).real().isZero());
VERIFY(!static_cast<const MatrixType&>(cm).imag().isZero());
}
#ifdef EIGEN_TEST_PART_2
void casting()
{
Matrix4f m = Matrix4f::Random(), m2;
Matrix4d n = m.cast<double>();
VERIFY(m.isApprox(n.cast<float>()));
m2 = m.cast<float>(); // check the specialization when NewType == Type
VERIFY(m.isApprox(m2));
}
#endif
template <typename Scalar>
void fixedSizeMatrixConstruction()
{
const Scalar raw[3] = {1,2,3};
Matrix<Scalar,3,1> m(raw);
Array<Scalar,3,1> a(raw);
VERIFY(m(0) == 1);
VERIFY(m(1) == 2);
VERIFY(m(2) == 3);
VERIFY(a(0) == 1);
VERIFY(a(1) == 2);
VERIFY(a(2) == 3);
}
void test_basicstuff()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( basicStuff(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( basicStuff(Matrix4d()) );
CALL_SUBTEST_3( basicStuff(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_4( basicStuff(MatrixXi(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_5( basicStuff(MatrixXcd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_6( basicStuff(Matrix<float, 100, 100>()) );
CALL_SUBTEST_7( basicStuff(Matrix<long double,Dynamic,Dynamic>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE),internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_3( basicStuffComplex(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_5( basicStuffComplex(MatrixXcd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
}
CALL_SUBTEST_1(fixedSizeMatrixConstruction<unsigned char>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<double>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<double>());
CALL_SUBTEST_2(casting());
}
<commit_msg>Additional unit tests for bug 826 by Gael<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#define EIGEN_NO_STATIC_ASSERT
#include "main.h"
template<typename MatrixType> void basicStuff(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;
Index rows = m.rows();
Index cols = m.cols();
// this test relies a lot on Random.h, and there's not much more that we can do
// to test it, hence I consider that we will have tested Random.h
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols),
m3(rows, cols),
mzero = MatrixType::Zero(rows, cols),
square = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>::Random(rows, rows);
VectorType v1 = VectorType::Random(rows),
vzero = VectorType::Zero(rows);
SquareMatrixType sm1 = SquareMatrixType::Random(rows,rows), sm2(rows,rows);
Scalar x = 0;
while(x == Scalar(0)) x = internal::random<Scalar>();
Index r = internal::random<Index>(0, rows-1),
c = internal::random<Index>(0, cols-1);
m1.coeffRef(r,c) = x;
VERIFY_IS_APPROX(x, m1.coeff(r,c));
m1(r,c) = x;
VERIFY_IS_APPROX(x, m1(r,c));
v1.coeffRef(r) = x;
VERIFY_IS_APPROX(x, v1.coeff(r));
v1(r) = x;
VERIFY_IS_APPROX(x, v1(r));
v1[r] = x;
VERIFY_IS_APPROX(x, v1[r]);
VERIFY_IS_APPROX( v1, v1);
VERIFY_IS_NOT_APPROX( v1, 2*v1);
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1);
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1.squaredNorm());
VERIFY_IS_NOT_MUCH_SMALLER_THAN(v1, v1);
VERIFY_IS_APPROX( vzero, v1-v1);
VERIFY_IS_APPROX( m1, m1);
VERIFY_IS_NOT_APPROX( m1, 2*m1);
VERIFY_IS_MUCH_SMALLER_THAN( mzero, m1);
VERIFY_IS_NOT_MUCH_SMALLER_THAN(m1, m1);
VERIFY_IS_APPROX( mzero, m1-m1);
// always test operator() on each read-only expression class,
// in order to check const-qualifiers.
// indeed, if an expression class (here Zero) is meant to be read-only,
// hence has no _write() method, the corresponding MatrixBase method (here zero())
// should return a const-qualified object so that it is the const-qualified
// operator() that gets called, which in turn calls _read().
VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows,cols)(r,c), static_cast<Scalar>(1));
// now test copying a row-vector into a (column-)vector and conversely.
square.col(r) = square.row(r).eval();
Matrix<Scalar, 1, MatrixType::RowsAtCompileTime> rv(rows);
Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> cv(rows);
rv = square.row(r);
cv = square.col(r);
VERIFY_IS_APPROX(rv, cv.transpose());
if(cols!=1 && rows!=1 && MatrixType::SizeAtCompileTime!=Dynamic)
{
VERIFY_RAISES_ASSERT(m1 = (m2.block(0,0, rows-1, cols-1)));
}
if(cols!=1 && rows!=1)
{
VERIFY_RAISES_ASSERT(m1[0]);
VERIFY_RAISES_ASSERT((m1+m1)[0]);
}
VERIFY_IS_APPROX(m3 = m1,m1);
MatrixType m4;
VERIFY_IS_APPROX(m4 = m1,m1);
m3.real() = m1.real();
VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), static_cast<const MatrixType&>(m1).real());
VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), m1.real());
// check == / != operators
VERIFY(m1==m1);
VERIFY(m1!=m2);
VERIFY(!(m1==m2));
VERIFY(!(m1!=m1));
m1 = m2;
VERIFY(m1==m2);
VERIFY(!(m1!=m2));
// check automatic transposition
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i) = sm1.row(i);
VERIFY_IS_APPROX(sm2,sm1.transpose());
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i).noalias() = sm1.row(i);
VERIFY_IS_APPROX(sm2,sm1.transpose());
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i).noalias() += sm1.row(i);
VERIFY_IS_APPROX(sm2,sm1.transpose());
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i).noalias() -= sm1.row(i);
VERIFY_IS_APPROX(sm2,-sm1.transpose());
}
template<typename MatrixType> void basicStuffComplex(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, MatrixType::ColsAtCompileTime> RealMatrixType;
Index rows = m.rows();
Index cols = m.cols();
Scalar s1 = internal::random<Scalar>(),
s2 = internal::random<Scalar>();
VERIFY(numext::real(s1)==numext::real_ref(s1));
VERIFY(numext::imag(s1)==numext::imag_ref(s1));
numext::real_ref(s1) = numext::real(s2);
numext::imag_ref(s1) = numext::imag(s2);
VERIFY(internal::isApprox(s1, s2, NumTraits<RealScalar>::epsilon()));
// extended precision in Intel FPUs means that s1 == s2 in the line above is not guaranteed.
RealMatrixType rm1 = RealMatrixType::Random(rows,cols),
rm2 = RealMatrixType::Random(rows,cols);
MatrixType cm(rows,cols);
cm.real() = rm1;
cm.imag() = rm2;
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).real(), rm1);
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).imag(), rm2);
rm1.setZero();
rm2.setZero();
rm1 = cm.real();
rm2 = cm.imag();
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).real(), rm1);
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).imag(), rm2);
cm.real().setZero();
VERIFY(static_cast<const MatrixType&>(cm).real().isZero());
VERIFY(!static_cast<const MatrixType&>(cm).imag().isZero());
}
#ifdef EIGEN_TEST_PART_2
void casting()
{
Matrix4f m = Matrix4f::Random(), m2;
Matrix4d n = m.cast<double>();
VERIFY(m.isApprox(n.cast<float>()));
m2 = m.cast<float>(); // check the specialization when NewType == Type
VERIFY(m.isApprox(m2));
}
#endif
template <typename Scalar>
void fixedSizeMatrixConstruction()
{
Scalar raw[4];
for(int k=0; k<4; ++k)
raw[k] = internal::random<Scalar>();
{
Matrix<Scalar,4,1> m(raw);
Array<Scalar,4,1> a(raw);
for(int k=0; k<4; ++k) VERIFY(m(k) == raw[k]);
for(int k=0; k<4; ++k) VERIFY(a(k) == raw[k]);
VERIFY_IS_EQUAL(m,(Matrix<Scalar,4,1>(raw[0],raw[1],raw[2],raw[3])));
VERIFY((a==(Array<Scalar,4,1>(raw[0],raw[1],raw[2],raw[3]))).all());
}
{
Matrix<Scalar,3,1> m(raw);
Array<Scalar,3,1> a(raw);
for(int k=0; k<3; ++k) VERIFY(m(k) == raw[k]);
for(int k=0; k<3; ++k) VERIFY(a(k) == raw[k]);
VERIFY_IS_EQUAL(m,(Matrix<Scalar,3,1>(raw[0],raw[1],raw[2])));
VERIFY((a==Array<Scalar,3,1>(raw[0],raw[1],raw[2])).all());
}
{
Matrix<Scalar,2,1> m(raw);
Array<Scalar,2,1> a(raw);
for(int k=0; k<2; ++k) VERIFY(m(k) == raw[k]);
for(int k=0; k<2; ++k) VERIFY(a(k) == raw[k]);
VERIFY_IS_EQUAL(m,(Matrix<Scalar,2,1>(raw[0],raw[1])));
VERIFY((a==Array<Scalar,2,1>(raw[0],raw[1])).all());
}
{
Matrix<Scalar,1,1> m(raw);
Array<Scalar,1,1> a(raw);
VERIFY(m(0) == raw[0]);
VERIFY(a(0) == raw[0]);
VERIFY_IS_EQUAL(m,(Matrix<Scalar,1,1>(raw[0])));
VERIFY((a==Array<Scalar,1,1>(raw[0])).all());
}
}
void test_basicstuff()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( basicStuff(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( basicStuff(Matrix4d()) );
CALL_SUBTEST_3( basicStuff(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_4( basicStuff(MatrixXi(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_5( basicStuff(MatrixXcd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_6( basicStuff(Matrix<float, 100, 100>()) );
CALL_SUBTEST_7( basicStuff(Matrix<long double,Dynamic,Dynamic>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE),internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_3( basicStuffComplex(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_5( basicStuffComplex(MatrixXcd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
}
CALL_SUBTEST_1(fixedSizeMatrixConstruction<unsigned char>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<double>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<double>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<int>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<std::ptrdiff_t>());
CALL_SUBTEST_2(casting());
}
<|endoftext|> |
<commit_before>
#include <vector>
#include <algorithm>
#include <retest.hpp>
#include "config/args.hpp"
#include "alloc/malloc.hpp"
#include "alloc/object_static.hpp"
#include "btree/array_node.hpp"
#include "btree/get_fsm.hpp"
#include "btree/set_fsm.hpp"
#include "buffer_cache/volatile.hpp"
#include "event.hpp"
using namespace std;
// Forward declarations
struct mock_config_t;
// Mock definitions
template <class config_t>
struct mock_fsm_t {};
// TODO: we're only testing the case where cache reads return
// immediately. We should also test the case where the reads come back
// via AIO.
template <class config_t>
struct recording_cache_t : public volatile_cache_t<config_t> {
public:
typedef volatile_cache_t<config_t> vcache_t;
typedef typename vcache_t::block_id_t block_id_t;
typedef typename vcache_t::fsm_t fsm_t;
typedef typename config_t::btree_fsm_t btree_fsm_t;
public:
recording_cache_t(size_t _block_size) : vcache_t(_block_size) {}
block_id_t release(block_id_t block_id, void *block, bool dirty, fsm_t *state) {
if(dirty) {
// Record the write
event_t e;
e.event_type = et_disk;
e.result = BTREE_BLOCK_SIZE;
e.op = eo_write;
e.offset = (off64_t)block_id;
e.buf = block;
record.push_back(e);
}
return vcache_t::release(block_id, block, dirty, state);
}
typename btree_fsm_t::transition_result_t writes_notify(btree_fsm_t *btree) {
typename btree_fsm_t::transition_result_t res;
for(vector<event_t>::iterator i = record.begin(); i != record.end(); i++) {
res = btree->do_transition(&(*i));
}
record.clear();
return res;
}
public:
vector<event_t> record;
};
// Mock config
struct mock_config_t {
typedef buffer_t<IO_BUFFER_SIZE> iobuf_t;
typedef object_static_alloc_t<malloc_alloc_t, iobuf_t> alloc_t;
// Connection fsm
typedef mock_fsm_t<mock_config_t> fsm_t;
// Btree base
typedef btree_fsm<mock_config_t> btree_fsm_t;
// TODO: add cache_stats_t to make sure we acquire/release right
typedef recording_cache_t<mock_config_t> cache_t;
// BTree rest
typedef array_node_t<cache_t::block_id_t> node_t;
typedef btree_get_fsm<mock_config_t> btree_get_fsm_t;
typedef btree_set_fsm<mock_config_t> btree_set_fsm_t;
};
typedef mock_config_t::cache_t cache_t;
typedef mock_config_t::btree_fsm_t btree_fsm_t;
typedef mock_config_t::btree_get_fsm_t get_fsm_t;
typedef mock_config_t::btree_set_fsm_t set_fsm_t;
// Helpers
get_fsm_t::op_result_t lookup(cache_t *cache, int k, int expected = -1) {
// Initialize get operation state machine
get_fsm_t tree(cache, NULL);
// Perform lookup
tree.init_lookup(k);
btree_fsm_t::transition_result_t res = tree.do_transition(NULL);
// Ensure transaction is complete
assert_eq(res, btree_fsm_t::transition_complete);
if(tree.op_result == get_fsm_t::btree_found)
assert_eq(tree.value, expected);
return tree.op_result;
}
bool insert(cache_t *cache, int k, int v) {
// Initialize set operation state machine
set_fsm_t tree(cache, NULL);
// Perform update
tree.init_update(k, v);
btree_fsm_t::transition_result_t res = tree.do_transition(NULL);
// Ensure we inserted the item successfully
assert_eq(res, btree_fsm_t::transition_ok);
// Notify the btree fsm of writes
res = cache->writes_notify(&tree);
return res == btree_fsm_t::transition_complete;
}
// Tests
void test_lookup_api() {
// Initialize underlying cache
cache_t cache(BTREE_BLOCK_SIZE);
get_fsm_t::op_result_t res = lookup(&cache, 1);
assert_eq(res, get_fsm_t::btree_not_found);
}
void test_insert_api() {
// Initialize underlying cache
cache_t cache(BTREE_BLOCK_SIZE);
bool complete = insert(&cache, 1, 1);
assert(complete);
}
void test_small_insert() {
// Initialize underlying cache
cache_t cache(BTREE_BLOCK_SIZE);
// Insert a node full of items
for(int i = 0; i < NODE_ORDER; i++) {
bool complete = insert(&cache, i, i);
assert(complete);
}
// Make sure the items are there
int value;
for(int i = 0; i < NODE_ORDER; i++) {
get_fsm_t::op_result_t res = lookup(&cache, i, i);
assert_eq(res, get_fsm_t::btree_found);
}
// Make sure missing items aren't there
get_fsm_t::op_result_t res = lookup(&cache, NODE_ORDER);
assert_eq(res, get_fsm_t::btree_not_found);
}
void test_multinode_insert() {
// Initialize underlying cache
cache_t cache(BTREE_BLOCK_SIZE);
// Insert a node full of items
for(int i = 0; i < NODE_ORDER + 1; i++) {
bool complete = insert(&cache, i, i);
assert(complete);
}
// Make sure the items are there
int value;
for(int i = 0; i < NODE_ORDER + 1; i++) {
get_fsm_t::op_result_t res = lookup(&cache, i, i);
assert_eq(res, get_fsm_t::btree_found);
}
// Make sure missing items aren't there
get_fsm_t::op_result_t res = lookup(&cache, NODE_ORDER + 1);
assert_eq(res, get_fsm_t::btree_not_found);
}
void test_large_insert() {
const int lots_of_items = 1000000;
// Initialize underlying cache
cache_t cache(BTREE_BLOCK_SIZE);
// Insert a node full of items
for(int i = 0; i < lots_of_items; i++) {
bool complete = insert(&cache, i, i);
assert(complete);
}
// Make sure the items are there
int value;
for(int i = 0; i < lots_of_items; i++) {
get_fsm_t::op_result_t res = lookup(&cache, i, i);
assert_eq(res, get_fsm_t::btree_found);
}
// Make sure missing items aren't there
get_fsm_t::op_result_t res = lookup(&cache, lots_of_items + 1);
assert_eq(res, get_fsm_t::btree_not_found);
}
void test_large_insert_permuted() {
const int lots_of_items = 1000000;
// Permute an array of numbers
std::vector<int> numbers(lots_of_items);
for(int i = 0; i < lots_of_items; i++) {
numbers[i] = i;
}
std::random_shuffle(numbers.begin(), numbers.end());
// Initialize underlying cache
cache_t cache(BTREE_BLOCK_SIZE);
// Insert a node full of items
for(int i = 0; i < lots_of_items; i++) {
bool complete = insert(&cache, numbers[i], numbers[i]);
assert(complete);
}
// Make sure the items are there
int value;
for(int i = 0; i < lots_of_items; i++) {
get_fsm_t::op_result_t res = lookup(&cache, numbers[i], numbers[i]);
assert_eq(res, get_fsm_t::btree_found);
}
// Make sure missing items aren't there
get_fsm_t::op_result_t res = lookup(&cache, lots_of_items + 1);
assert_eq(res, get_fsm_t::btree_not_found);
}
<commit_msg>Introducing cache_stats to btree testing<commit_after>
#include <vector>
#include <algorithm>
#include <retest.hpp>
#include "config/args.hpp"
#include "alloc/malloc.hpp"
#include "alloc/object_static.hpp"
#include "btree/array_node.hpp"
#include "btree/get_fsm.hpp"
#include "btree/set_fsm.hpp"
#include "buffer_cache/volatile.hpp"
#include "buffer_cache/stats.hpp"
#include "event.hpp"
using namespace std;
// Forward declarations
struct mock_config_t;
// Mock definitions
template <class config_t>
struct mock_fsm_t {};
// TODO: we're only testing the case where cache reads return
// immediately. We should also test the case where the reads come back
// via AIO. (Note, since we're doing it this way, cache_stats is
// unlikely to fail, though it might fail with AIO)
template <class config_t>
struct recording_cache_t : public volatile_cache_t<config_t> {
public:
typedef volatile_cache_t<config_t> vcache_t;
typedef typename vcache_t::block_id_t block_id_t;
typedef typename vcache_t::fsm_t fsm_t;
public:
recording_cache_t(size_t _block_size) : vcache_t(_block_size) {}
block_id_t release(block_id_t block_id, void *block, bool dirty, fsm_t *state) {
if(dirty) {
// Record the write
event_t e;
e.event_type = et_disk;
e.result = BTREE_BLOCK_SIZE;
e.op = eo_write;
e.offset = (off64_t)block_id;
e.buf = block;
record.push_back(e);
}
return vcache_t::release(block_id, block, dirty, state);
}
public:
vector<event_t> record;
};
// Mock config
struct mock_config_t {
typedef buffer_t<IO_BUFFER_SIZE> iobuf_t;
typedef object_static_alloc_t<malloc_alloc_t, iobuf_t> alloc_t;
// Connection fsm
typedef mock_fsm_t<mock_config_t> fsm_t;
// Caching
typedef cache_stats_t<recording_cache_t<mock_config_t> > cache_t;
// BTree
typedef array_node_t<cache_t::block_id_t> node_t;
typedef btree_fsm<mock_config_t> btree_fsm_t;
typedef btree_get_fsm<mock_config_t> btree_get_fsm_t;
typedef btree_set_fsm<mock_config_t> btree_set_fsm_t;
};
typedef mock_config_t::cache_t cache_t;
typedef mock_config_t::btree_fsm_t btree_fsm_t;
typedef mock_config_t::btree_get_fsm_t get_fsm_t;
typedef mock_config_t::btree_set_fsm_t set_fsm_t;
// Helpers
get_fsm_t::op_result_t lookup(cache_t *cache, int k, int expected = -1) {
// Initialize get operation state machine
get_fsm_t tree(cache, NULL);
// Perform lookup
tree.init_lookup(k);
btree_fsm_t::transition_result_t res = tree.do_transition(NULL);
// Ensure transaction is complete
assert_eq(res, btree_fsm_t::transition_complete);
if(tree.op_result == get_fsm_t::btree_found)
assert_eq(tree.value, expected);
return tree.op_result;
}
btree_fsm_t::transition_result_t writes_notify(btree_fsm_t *btree, cache_t *cache) {
btree_fsm_t::transition_result_t res;
for(vector<event_t>::iterator i = cache->record.begin(); i != cache->record.end(); i++) {
res = btree->do_transition(&(*i));
}
cache->record.clear();
return res;
}
bool insert(cache_t *cache, int k, int v) {
// Initialize set operation state machine
set_fsm_t tree(cache, NULL);
// Perform update
tree.init_update(k, v);
btree_fsm_t::transition_result_t res = tree.do_transition(NULL);
// Ensure we inserted the item successfully
assert_eq(res, btree_fsm_t::transition_ok);
// Notify the btree fsm of writes
res = writes_notify(&tree, cache);
return res == btree_fsm_t::transition_complete;
}
// Tests
void test_lookup_api() {
// Initialize underlying cache
cache_t cache(BTREE_BLOCK_SIZE);
get_fsm_t::op_result_t res = lookup(&cache, 1);
assert_eq(res, get_fsm_t::btree_not_found);
}
void test_insert_api() {
// Initialize underlying cache
cache_t cache(BTREE_BLOCK_SIZE);
bool complete = insert(&cache, 1, 1);
assert(complete);
}
void test_small_insert() {
// Initialize underlying cache
cache_t cache(BTREE_BLOCK_SIZE);
// Insert a node full of items
for(int i = 0; i < NODE_ORDER; i++) {
bool complete = insert(&cache, i, i);
assert(complete);
}
// Make sure the items are there
int value;
for(int i = 0; i < NODE_ORDER; i++) {
get_fsm_t::op_result_t res = lookup(&cache, i, i);
assert_eq(res, get_fsm_t::btree_found);
}
// Make sure missing items aren't there
get_fsm_t::op_result_t res = lookup(&cache, NODE_ORDER);
assert_eq(res, get_fsm_t::btree_not_found);
}
void test_multinode_insert() {
// Initialize underlying cache
cache_t cache(BTREE_BLOCK_SIZE);
// Insert a node full of items
for(int i = 0; i < NODE_ORDER + 1; i++) {
bool complete = insert(&cache, i, i);
assert(complete);
}
// Make sure the items are there
int value;
for(int i = 0; i < NODE_ORDER + 1; i++) {
get_fsm_t::op_result_t res = lookup(&cache, i, i);
assert_eq(res, get_fsm_t::btree_found);
}
// Make sure missing items aren't there
get_fsm_t::op_result_t res = lookup(&cache, NODE_ORDER + 1);
assert_eq(res, get_fsm_t::btree_not_found);
}
void test_large_insert() {
const int lots_of_items = 1000000;
// Initialize underlying cache
cache_t cache(BTREE_BLOCK_SIZE);
// Insert a node full of items
for(int i = 0; i < lots_of_items; i++) {
bool complete = insert(&cache, i, i);
assert(complete);
}
// Make sure the items are there
int value;
for(int i = 0; i < lots_of_items; i++) {
get_fsm_t::op_result_t res = lookup(&cache, i, i);
assert_eq(res, get_fsm_t::btree_found);
}
// Make sure missing items aren't there
get_fsm_t::op_result_t res = lookup(&cache, lots_of_items + 1);
assert_eq(res, get_fsm_t::btree_not_found);
}
void test_large_insert_permuted() {
const int lots_of_items = 1000000;
// Permute an array of numbers
std::vector<int> numbers(lots_of_items);
for(int i = 0; i < lots_of_items; i++) {
numbers[i] = i;
}
std::random_shuffle(numbers.begin(), numbers.end());
// Initialize underlying cache
cache_t cache(BTREE_BLOCK_SIZE);
// Insert a node full of items
for(int i = 0; i < lots_of_items; i++) {
bool complete = insert(&cache, numbers[i], numbers[i]);
assert(complete);
}
// Make sure the items are there
int value;
for(int i = 0; i < lots_of_items; i++) {
get_fsm_t::op_result_t res = lookup(&cache, numbers[i], numbers[i]);
assert_eq(res, get_fsm_t::btree_found);
}
// Make sure missing items aren't there
get_fsm_t::op_result_t res = lookup(&cache, lots_of_items + 1);
assert_eq(res, get_fsm_t::btree_not_found);
}
<|endoftext|> |
<commit_before>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/model/CEvent.cpp,v $
// $Revision: 1.21 $
// $Name: $
// $Author: shoops $
// $Date: 2009/05/07 13:31:19 $
// End CVS Header
// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include "copasi.h"
#include <stdio.h>
#include "CopasiDataModel/CCopasiDataModel.h"
#include "CModel.h"
#include "CEvent.h"
#include "utilities/CCopasiMessage.h"
#include "utilities/CCopasiException.h"
#include "utilities/utility.h"
#include "report/CCopasiObjectReference.h"
#include "report/CKeyFactory.h"
#include "copasi/report/CCopasiRootContainer.h"
#include "function/CExpression.h"
// The default constructor is intentionally not implemented.
// CEventAssignment::CEventAssignment() {}
CEventAssignment::CEventAssignment(const std::string & targetKey,
const CCopasiContainer * pParent) :
CCopasiContainer(targetKey, pParent, "EventAssignment"),
mKey(CCopasiRootContainer::getKeyFactory()->add("EventAssignment", this)),
mpExpression(NULL)
{}
CEventAssignment::CEventAssignment(const CEventAssignment & src,
const CCopasiContainer * pParent):
CCopasiContainer(src, pParent),
mKey(CCopasiRootContainer::getKeyFactory()->add("EventAssignment", this)),
mpExpression(NULL)
{
setExpression(src.getExpression());
}
CEventAssignment::~CEventAssignment()
{
pdelete(mpExpression);
}
const std::string & CEventAssignment::getKey() const
{
return mKey;
}
const std::string & CEventAssignment::getTargetKey() const
{
return getObjectName();
}
bool CEventAssignment::setExpression(const std::string & expression)
{
if (mpExpression == NULL)
mpExpression = new CExpression("Expression", this);
return mpExpression->setInfix(expression);
}
void CEventAssignment::setExpressionPtr(CExpression * pExpression)
{
pdelete(mpExpression);
if (pExpression != NULL)
{
mpExpression = pExpression;
mpExpression->setObjectParent(this);
mpExpression->setObjectName("Expression");
mpExpression->compile();
}
}
std::string CEventAssignment::getExpression() const
{
if (mpExpression == NULL)
return "";
mpExpression->updateInfix();
return mpExpression->getInfix();
}
const CExpression* CEventAssignment::getExpressionPtr() const
{
return mpExpression;
}
CExpression* CEventAssignment::getExpressionPtr()
{
return mpExpression;
}
CEvent::CEvent(const std::string & name,
const CCopasiContainer * pParent):
CCopasiContainer(name, pParent, "Event"),
mKey(CCopasiRootContainer::getKeyFactory()->add("Event", this)),
mAssignments("ListOfAssignments", this),
mDelayAssignment(true),
mpTriggerExpression(NULL),
mpDelayExpression(NULL)
{
initObjects();
}
CEvent::CEvent(const CEvent & src,
const CCopasiContainer * pParent):
CCopasiContainer(src, pParent),
mKey(CCopasiRootContainer::getKeyFactory()->add("Event", this)),
mAssignments(src.mAssignments, this),
mDelayAssignment(src.mDelayAssignment),
mpTriggerExpression(src.mpTriggerExpression == NULL ? NULL : new CExpression(*src.mpTriggerExpression)),
mpDelayExpression(src.mpDelayExpression == NULL ? NULL : new CExpression(*src.mpDelayExpression))
{
initObjects();
}
CEvent::~CEvent()
{
CCopasiRootContainer::getKeyFactory()->remove(mKey);
pdelete(mpTriggerExpression);
pdelete(mpDelayExpression);
}
const std::string & CEvent::getKey() const
{
return mKey;
}
bool CEvent::compile()
{
bool success = true;
// TODO We need build the list of direct dependencies to assure the events are deleted
// whenever an object used in an expression or assignment is deleted.
return success;
}
void CEvent::initObjects()
{}
std::ostream & operator<<(std::ostream &os, const CEvent & d)
{
os << "CEvent: " << d.getObjectName() << std::endl;
os << " SBML id: " << d.mSBMLId << std::endl;
os << "----CEvent" << std::endl;
return os;
}
void CEvent::setSBMLId(const std::string& id)
{
this->mSBMLId = id;
}
const std::string& CEvent::getSBMLId() const
{
return this->mSBMLId;
}
void CEvent::setDelayAssignment(const bool & delayAssignment)
{
mDelayAssignment = delayAssignment;
}
const bool & CEvent::getDelayAssignment() const
{
return mDelayAssignment;
}
std::string CEvent::getObjectDisplayName(bool regular, bool richtext) const
{
CModel* tmp = dynamic_cast<CModel*>(this->getObjectAncestor("Model"));
if (tmp)
return "((" + getObjectName() + "))";
return CCopasiObject::getObjectDisplayName(regular, richtext);
}
bool CEvent::setTriggerExpression(const std::string & expression)
{
if (mpTriggerExpression == NULL)
{
mpTriggerExpression = new CExpression("TriggerExpression", this);
mpTriggerExpression->setBoolean(true);
}
return mpTriggerExpression->setInfix(expression);
}
void CEvent::setTriggerExpressionPtr(CExpression * pExpression)
{
pdelete(mpTriggerExpression);
if (pExpression)
{
mpTriggerExpression = pExpression;
mpTriggerExpression->compile();
}
}
std::string CEvent::getTriggerExpression() const
{
if (mpTriggerExpression == NULL)
return "";
mpTriggerExpression->updateInfix();
return mpTriggerExpression->getInfix();
}
const CExpression* CEvent::getTriggerExpressionPtr() const
{
return mpTriggerExpression;
}
CExpression* CEvent::getTriggerExpressionPtr()
{
return mpTriggerExpression;
}
bool CEvent::setDelayExpression(const std::string & expression)
{
if (mpDelayExpression == NULL)
mpDelayExpression = new CExpression("DelayExpression");
return mpDelayExpression->setInfix(expression);
}
void CEvent::setDelayExpressionPtr(CExpression * pExpression)
{
pdelete(mpDelayExpression);
if (pExpression)
{
mpDelayExpression = pExpression;
mpDelayExpression->compile();
}
}
std::string CEvent::getDelayExpression() const
{
if (mpDelayExpression == NULL)
return "";
mpDelayExpression->updateInfix();
return mpDelayExpression->getInfix();
}
const CExpression* CEvent::getDelayExpressionPtr() const
{
return mpDelayExpression;
}
CExpression* CEvent::getDelayExpressionPtr()
{
return mpDelayExpression;
}
const CCopasiVectorN< CEventAssignment > & CEvent::getAssignments() const
{
return mAssignments;
}
CCopasiVectorN< CEventAssignment > & CEvent::getAssignments()
{
return mAssignments;
}
void CEvent::deleteAssignment(const std::string & key)
{
CEventAssignment * pAssignment =
dynamic_cast<CEventAssignment *>(CCopasiRootContainer::getKeyFactory()->get(key));
if (pAssignment != NULL)
{
mAssignments.CCopasiVector< CEventAssignment >::remove(pAssignment);
}
}
<commit_msg>Corrected parents of expression, which had been accidantally removed during merge prior to my last commit.<commit_after>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/model/CEvent.cpp,v $
// $Revision: 1.22 $
// $Name: $
// $Author: shoops $
// $Date: 2009/05/07 17:24:25 $
// End CVS Header
// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include "copasi.h"
#include <stdio.h>
#include "CopasiDataModel/CCopasiDataModel.h"
#include "CModel.h"
#include "CEvent.h"
#include "utilities/CCopasiMessage.h"
#include "utilities/CCopasiException.h"
#include "utilities/utility.h"
#include "report/CCopasiObjectReference.h"
#include "report/CKeyFactory.h"
#include "copasi/report/CCopasiRootContainer.h"
#include "function/CExpression.h"
// The default constructor is intentionally not implemented.
// CEventAssignment::CEventAssignment() {}
CEventAssignment::CEventAssignment(const std::string & targetKey,
const CCopasiContainer * pParent) :
CCopasiContainer(targetKey, pParent, "EventAssignment"),
mKey(CCopasiRootContainer::getKeyFactory()->add("EventAssignment", this)),
mpExpression(NULL)
{}
CEventAssignment::CEventAssignment(const CEventAssignment & src,
const CCopasiContainer * pParent):
CCopasiContainer(src, pParent),
mKey(CCopasiRootContainer::getKeyFactory()->add("EventAssignment", this)),
mpExpression(NULL)
{
setExpression(src.getExpression());
}
CEventAssignment::~CEventAssignment()
{
pdelete(mpExpression);
}
const std::string & CEventAssignment::getKey() const
{
return mKey;
}
const std::string & CEventAssignment::getTargetKey() const
{
return getObjectName();
}
bool CEventAssignment::setExpression(const std::string & expression)
{
if (mpExpression == NULL)
mpExpression = new CExpression("Expression", this);
return mpExpression->setInfix(expression);
}
void CEventAssignment::setExpressionPtr(CExpression * pExpression)
{
pdelete(mpExpression);
if (pExpression != NULL)
{
mpExpression = pExpression;
mpExpression->setObjectParent(this);
mpExpression->setObjectName("Expression");
mpExpression->compile();
}
}
std::string CEventAssignment::getExpression() const
{
if (mpExpression == NULL)
return "";
mpExpression->updateInfix();
return mpExpression->getInfix();
}
const CExpression* CEventAssignment::getExpressionPtr() const
{
return mpExpression;
}
CExpression* CEventAssignment::getExpressionPtr()
{
return mpExpression;
}
CEvent::CEvent(const std::string & name,
const CCopasiContainer * pParent):
CCopasiContainer(name, pParent, "Event"),
mKey(CCopasiRootContainer::getKeyFactory()->add("Event", this)),
mAssignments("ListOfAssignments", this),
mDelayAssignment(true),
mpTriggerExpression(NULL),
mpDelayExpression(NULL)
{
initObjects();
}
CEvent::CEvent(const CEvent & src,
const CCopasiContainer * pParent):
CCopasiContainer(src, pParent),
mKey(CCopasiRootContainer::getKeyFactory()->add("Event", this)),
mAssignments(src.mAssignments, this),
mDelayAssignment(src.mDelayAssignment),
mpTriggerExpression(src.mpTriggerExpression == NULL ? NULL : new CExpression(*src.mpTriggerExpression)),
mpDelayExpression(src.mpDelayExpression == NULL ? NULL : new CExpression(*src.mpDelayExpression))
{
initObjects();
}
CEvent::~CEvent()
{
CCopasiRootContainer::getKeyFactory()->remove(mKey);
pdelete(mpTriggerExpression);
pdelete(mpDelayExpression);
}
const std::string & CEvent::getKey() const
{
return mKey;
}
bool CEvent::compile()
{
bool success = true;
// TODO We need build the list of direct dependencies to assure the events are deleted
// whenever an object used in an expression or assignment is deleted.
return success;
}
void CEvent::initObjects()
{}
std::ostream & operator<<(std::ostream &os, const CEvent & d)
{
os << "CEvent: " << d.getObjectName() << std::endl;
os << " SBML id: " << d.mSBMLId << std::endl;
os << "----CEvent" << std::endl;
return os;
}
void CEvent::setSBMLId(const std::string& id)
{
this->mSBMLId = id;
}
const std::string& CEvent::getSBMLId() const
{
return this->mSBMLId;
}
void CEvent::setDelayAssignment(const bool & delayAssignment)
{
mDelayAssignment = delayAssignment;
}
const bool & CEvent::getDelayAssignment() const
{
return mDelayAssignment;
}
std::string CEvent::getObjectDisplayName(bool regular, bool richtext) const
{
CModel* tmp = dynamic_cast<CModel*>(this->getObjectAncestor("Model"));
if (tmp)
return "((" + getObjectName() + "))";
return CCopasiObject::getObjectDisplayName(regular, richtext);
}
bool CEvent::setTriggerExpression(const std::string & expression)
{
if (mpTriggerExpression == NULL)
{
mpTriggerExpression = new CExpression("TriggerExpression", this);
mpTriggerExpression->setBoolean(true);
}
return mpTriggerExpression->setInfix(expression);
}
void CEvent::setTriggerExpressionPtr(CExpression * pExpression)
{
pdelete(mpTriggerExpression);
if (pExpression)
{
mpTriggerExpression = pExpression;
pExpression->setObjectParent(this);
mpTriggerExpression->compile();
}
}
std::string CEvent::getTriggerExpression() const
{
if (mpTriggerExpression == NULL)
return "";
mpTriggerExpression->updateInfix();
return mpTriggerExpression->getInfix();
}
const CExpression* CEvent::getTriggerExpressionPtr() const
{
return mpTriggerExpression;
}
CExpression* CEvent::getTriggerExpressionPtr()
{
return mpTriggerExpression;
}
bool CEvent::setDelayExpression(const std::string & expression)
{
if (mpDelayExpression == NULL)
mpDelayExpression = new CExpression("DelayExpression", this);
return mpDelayExpression->setInfix(expression);
}
void CEvent::setDelayExpressionPtr(CExpression * pExpression)
{
pdelete(mpDelayExpression);
if (pExpression)
{
mpDelayExpression = pExpression;
this->mpDelayExpression->setObjectParent(this);
mpDelayExpression->compile();
}
}
std::string CEvent::getDelayExpression() const
{
if (mpDelayExpression == NULL)
return "";
mpDelayExpression->updateInfix();
return mpDelayExpression->getInfix();
}
const CExpression* CEvent::getDelayExpressionPtr() const
{
return mpDelayExpression;
}
CExpression* CEvent::getDelayExpressionPtr()
{
return mpDelayExpression;
}
const CCopasiVectorN< CEventAssignment > & CEvent::getAssignments() const
{
return mAssignments;
}
CCopasiVectorN< CEventAssignment > & CEvent::getAssignments()
{
return mAssignments;
}
void CEvent::deleteAssignment(const std::string & key)
{
CEventAssignment * pAssignment =
dynamic_cast<CEventAssignment *>(CCopasiRootContainer::getKeyFactory()->get(key));
if (pAssignment != NULL)
{
mAssignments.CCopasiVector< CEventAssignment >::remove(pAssignment);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "random.h"
#include "scheduler.h"
#include "test/test_bitcoin.h"
#include <boost/bind.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/thread.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(scheduler_tests)
static void microTask(CScheduler& s, boost::mutex& mutex, int& counter, int delta, boost::chrono::system_clock::time_point rescheduleTime)
{
{
boost::unique_lock<boost::mutex> lock(mutex);
counter += delta;
}
boost::chrono::system_clock::time_point noTime = boost::chrono::system_clock::time_point::min();
if (rescheduleTime != noTime) {
CScheduler::Function f = boost::bind(µTask, boost::ref(s), boost::ref(mutex), boost::ref(counter), -delta + 1, noTime);
s.schedule(f, rescheduleTime);
}
}
static void MicroSleep(uint64_t n)
{
#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
boost::this_thread::sleep_for(boost::chrono::microseconds(n));
#elif defined(HAVE_WORKING_BOOST_SLEEP)
boost::this_thread::sleep(boost::posix_time::microseconds(n));
#else
//should never get here
#error missing boost sleep implementation
#endif
}
BOOST_AUTO_TEST_CASE(manythreads)
{
// Stress test: hundreds of microsecond-scheduled tasks,
// serviced by 10 threads.
//
// So... ten shared counters, which if all the tasks execute
// properly will sum to the number of tasks done.
// Each task adds or subtracts a random amount from one of the
// counters, and then schedules another task 0-1000
// microseconds in the future to subtract or add from
// the counter -random_amount+1, so in the end the shared
// counters should sum to the number of initial tasks performed.
CScheduler microTasks;
boost::mutex counterMutex[10];
int counter[10] = { 0 };
boost::random::mt19937 rng(42);
boost::random::uniform_int_distribution<> zeroToNine(0, 9);
boost::random::uniform_int_distribution<> randomMsec(-11, 1000);
boost::random::uniform_int_distribution<> randomDelta(-1000, 1000);
boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now();
boost::chrono::system_clock::time_point now = start;
boost::chrono::system_clock::time_point first, last;
size_t nTasks = microTasks.getQueueInfo(first, last);
BOOST_CHECK(nTasks == 0);
for (int i = 0; i < 100; i++) {
boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng));
boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng));
int whichCounter = zeroToNine(rng);
CScheduler::Function f = boost::bind(µTask, boost::ref(microTasks),
boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]),
randomDelta(rng), tReschedule);
microTasks.schedule(f, t);
}
nTasks = microTasks.getQueueInfo(first, last);
BOOST_CHECK(nTasks == 100);
BOOST_CHECK(first < last);
BOOST_CHECK(last > now);
// As soon as these are created they will start running and servicing the queue
boost::thread_group microThreads;
for (int i = 0; i < 5; i++)
microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, µTasks));
MicroSleep(600);
now = boost::chrono::system_clock::now();
// More threads and more tasks:
for (int i = 0; i < 5; i++)
microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, µTasks));
for (int i = 0; i < 100; i++) {
boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng));
boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng));
int whichCounter = zeroToNine(rng);
CScheduler::Function f = boost::bind(µTask, boost::ref(microTasks),
boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]),
randomDelta(rng), tReschedule);
microTasks.schedule(f, t);
}
// Drain the task queue then exit threads
microTasks.stop(true);
microThreads.join_all(); // ... wait until all the threads are done
int counterSum = 0;
for (int i = 0; i < 10; i++) {
BOOST_CHECK(counter[i] != 0);
counterSum += counter[i];
}
BOOST_CHECK_EQUAL(counterSum, 200);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>[tests] Use FastRandomContext instead of boost::random::{mt19937,uniform_int_distribution}<commit_after>// Copyright (c) 2012-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "random.h"
#include "scheduler.h"
#include "test/test_bitcoin.h"
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(scheduler_tests)
static void microTask(CScheduler& s, boost::mutex& mutex, int& counter, int delta, boost::chrono::system_clock::time_point rescheduleTime)
{
{
boost::unique_lock<boost::mutex> lock(mutex);
counter += delta;
}
boost::chrono::system_clock::time_point noTime = boost::chrono::system_clock::time_point::min();
if (rescheduleTime != noTime) {
CScheduler::Function f = boost::bind(µTask, boost::ref(s), boost::ref(mutex), boost::ref(counter), -delta + 1, noTime);
s.schedule(f, rescheduleTime);
}
}
static void MicroSleep(uint64_t n)
{
#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
boost::this_thread::sleep_for(boost::chrono::microseconds(n));
#elif defined(HAVE_WORKING_BOOST_SLEEP)
boost::this_thread::sleep(boost::posix_time::microseconds(n));
#else
//should never get here
#error missing boost sleep implementation
#endif
}
BOOST_AUTO_TEST_CASE(manythreads)
{
// Stress test: hundreds of microsecond-scheduled tasks,
// serviced by 10 threads.
//
// So... ten shared counters, which if all the tasks execute
// properly will sum to the number of tasks done.
// Each task adds or subtracts a random amount from one of the
// counters, and then schedules another task 0-1000
// microseconds in the future to subtract or add from
// the counter -random_amount+1, so in the end the shared
// counters should sum to the number of initial tasks performed.
CScheduler microTasks;
boost::mutex counterMutex[10];
int counter[10] = { 0 };
FastRandomContext rng(42);
auto zeroToNine = [](FastRandomContext& rc) -> int { return rc.randrange(10); }; // [0, 9]
auto randomMsec = [](FastRandomContext& rc) -> int { return -11 + rc.randrange(1012); }; // [-11, 1000]
auto randomDelta = [](FastRandomContext& rc) -> int { return -1000 + rc.randrange(2001); }; // [-1000, 1000]
boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now();
boost::chrono::system_clock::time_point now = start;
boost::chrono::system_clock::time_point first, last;
size_t nTasks = microTasks.getQueueInfo(first, last);
BOOST_CHECK(nTasks == 0);
for (int i = 0; i < 100; i++) {
boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng));
boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng));
int whichCounter = zeroToNine(rng);
CScheduler::Function f = boost::bind(µTask, boost::ref(microTasks),
boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]),
randomDelta(rng), tReschedule);
microTasks.schedule(f, t);
}
nTasks = microTasks.getQueueInfo(first, last);
BOOST_CHECK(nTasks == 100);
BOOST_CHECK(first < last);
BOOST_CHECK(last > now);
// As soon as these are created they will start running and servicing the queue
boost::thread_group microThreads;
for (int i = 0; i < 5; i++)
microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, µTasks));
MicroSleep(600);
now = boost::chrono::system_clock::now();
// More threads and more tasks:
for (int i = 0; i < 5; i++)
microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, µTasks));
for (int i = 0; i < 100; i++) {
boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng));
boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng));
int whichCounter = zeroToNine(rng);
CScheduler::Function f = boost::bind(µTask, boost::ref(microTasks),
boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]),
randomDelta(rng), tReschedule);
microTasks.schedule(f, t);
}
// Drain the task queue then exit threads
microTasks.stop(true);
microThreads.join_all(); // ... wait until all the threads are done
int counterSum = 0;
for (int i = 0; i < 10; i++) {
BOOST_CHECK(counter[i] != 0);
counterSum += counter[i];
}
BOOST_CHECK_EQUAL(counterSum, 200);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#pragma once
#include "test.hpp"
#include <array>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <miopen/convolution.hpp>
#include <miopen/batch_norm.hpp>
#include <miopen/activ.hpp>
#include <miopen/miopen.h>
#include <miopen/tensor.hpp>
#include <utility>
// #include "network_data.hpp"
#include "driver.hpp"
#include "get_handle.hpp"
#include "tensor_holder.hpp"
#include "verify.hpp"
#include <miopen/direct_conv_ocl.hpp>
template <class T>
void convHostForward(const tensor<T>& input,
tensor<T>& output,
const tensor<T>& weights,
const int bias_mode,
const tensor<T>& bias,
const miopenConvolutionDescriptor_t convDesc)
{
int in_n, in_c, in_h, in_w;
int in_nstride, in_cstride, in_hstride, in_wstride;
std::tie(in_n, in_c, in_h, in_w) = miopen::tien<4>(input.desc.GetLengths());
std::tie(in_nstride, in_cstride, in_hstride, in_wstride) =
miopen::tien<4>(input.desc.GetStrides());
int wei_n, wei_c, wei_h, wei_w;
int wei_nstride, wei_cstride, wei_hstride, wei_wstride;
std::tie(wei_n, wei_c, wei_h, wei_w) = miopen::tien<4>(weights.desc.GetLengths());
std::tie(wei_nstride, wei_cstride, wei_hstride, wei_wstride) =
miopen::tien<4>(weights.desc.GetStrides());
int out_n, out_c, out_h, out_w;
int out_nstride, out_cstride, out_hstride, out_wstride;
std::tie(out_n, out_c, out_h, out_w) = miopen::tien<4>(output.desc.GetLengths());
std::tie(out_nstride, out_cstride, out_hstride, out_wstride) =
miopen::tien<4>(output.desc.GetStrides());
int u, v, pad_h, pad_w, dilation_h, dilation_w;
miopenConvolutionMode_t mode;
miopenPaddingMode_t pmode = miopen::deref(convDesc).paddingMode;
miopenGetConvolutionDescriptor(
convDesc, &mode, &pad_h, &pad_w, &u, &v, &dilation_h, &dilation_w);
if(pmode == miopenPaddingSame)
{
pad_h = (in_h % u == 0) ? (std::max((wei_h - u), 0)) : (std::max((wei_h - (in_h % u)), 0));
pad_w = (in_w % v == 0) ? (std::max((wei_w - v), 0)) : (std::max((wei_w - (in_w % v)), 0));
pad_h /= 2;
pad_w /= 2;
}
else if(pmode == miopenPaddingValid)
{
pad_h = 0;
pad_w = 0;
}
if(out_h <= 0 || out_w <= 0)
MIOPEN_THROW("Invalid Test Case: Check Output Dimension.");
for(int o = 0; o < out_n; o++)
{ // mini-batch size
for(int w = 0; w < out_c; w++)
{ // out_channels (num filters)
for(int i = 0; i < out_h; i++)
{ // output_height (from getforwardoutputdim())
int in_off_h = i * u;
for(int j = 0; j < out_w; j++)
{ // output_width (from getforwardoutputdim())
/*auto acc = static_cast<T>(0.);*/
auto acc = static_cast<double>(0.);
int in_off_w = j * v;
for(int k = 0; k < in_c; k++)
{ // in_channels (RGB)
for(int x = 0; x < wei_h; x++)
{
int in_x = in_off_h - pad_h + x * dilation_h;
if(in_x >= 0 && in_x < in_h)
{
for(int y = 0; y < wei_w; y++)
{
int in_y = in_off_w - pad_w + y * dilation_w;
if(in_y >= 0 && in_y < in_w)
{
acc += double(
static_cast<T>(input[o * in_nstride + k * in_cstride +
in_x * in_w + in_y]) *
static_cast<T>(weights(w, k, x, y)));
}
}
}
}
}
acc = bias_mode != 0 ? acc + static_cast<double>(bias[w]) : acc;
output[o * out_nstride + w * out_cstride + i * out_hstride + j] =
static_cast<T>(acc);
}
}
}
}
}
template <class T>
void batchNormSpatialHostInference(const tensor<T>& input,
tensor<T>& output,
const tensor<T>& scale,
const tensor<T>& bias,
double epsilon,
const tensor<T>& estimatedMean,
const tensor<T>& estimatedVariance)
{
int n_batches, channels, height, width;
std::tie(n_batches, channels, height, width) = miopen::tien<4>(input.desc.GetLengths());
par_for(channels, 1, [&](int cidx) { // via channel
double mean = estimatedMean(0, cidx, 0, 0);
double variance = estimatedVariance(0, cidx, 0, 0);
double invertVar = 1.0 / sqrt(variance + epsilon);
// process the batch per channel
for(int row = 0; row < height; row++)
{ // via rows
for(int column = 0; column < width; column++)
{ // via columns
for(int bidx = 0; bidx < n_batches; bidx++)
{ // via mini_batch
double elemStd = input(bidx, cidx, row, column) - mean;
double inhat = elemStd * invertVar;
output(bidx, cidx, row, column) =
scale(0, cidx, 0, 0) * inhat + bias(0, cidx, 0, 0);
}
}
}
});
}
template <class T>
void batchNormPerActivHostInference(const tensor<T>& input,
tensor<T>& output,
const tensor<T>& scale,
const tensor<T>& bias,
double epsilon,
const tensor<T>& estimatedMean,
const tensor<T>& estimatedVariance)
{
int n_batches, channels, height, width;
std::tie(n_batches, channels, height, width) = miopen::tien<4>(input.desc.GetLengths());
par_for(channels, 1, [&](int cidx) { // via channel
for(int row = 0; row < height; row++)
{ // via rows
for(int column = 0; column < width; column++)
{ // via columns
// apply down the n_batch dimension
double mean = estimatedMean(0, cidx, row, column);
double variance = estimatedVariance(0, cidx, row, column);
double elemInvVar = 1.0 / sqrt(variance + epsilon);
for(int bidx = 0; bidx < n_batches; bidx++)
{ // via mini_batch
// per (x-dims) channel load a block of data into LDS
double elemStd = input(bidx, cidx, row, column) - mean;
double inhat = elemStd * elemInvVar;
output(bidx, cidx, row, column) =
scale(0, cidx, row, column) * inhat + bias(0, cidx, row, column);
}
}
}
});
}
template <class F>
void visitActivationHostInfer(miopenActivationMode_t activMode,
double gamma,
double beta,
double alpha,
F f)
{
switch(activMode)
{
case miopenActivationPASTHRU: // x
f([=](double x) { return x; });
break;
case miopenActivationLOGISTIC: // 1 / (1 + e^-x) //Sigmoid
f([=](double x) { return (1. / (1. + std::exp(-x))); });
break;
case miopenActivationTANH: // beta * tanh(alpha * x)
f([=](double x) { return (beta * std::tanh(alpha * x)); });
break;
case miopenActivationRELU: // max(0, x)
f([=](double x) { return ((x > 0.) ? x : 0.); });
break;
case miopenActivationSOFTRELU: // log(1 + e^x) // bonomial normal log likelihood
f([=](double x) {
return (x > 0.) ? (x + std::log1p(std::exp(-x))) : (std::log1p(std::exp(x)));
});
break;
case miopenActivationABS: // abs(x)
f([=](double x) { return (std::fabs(x)); });
break;
case miopenActivationPOWER: // (alpha + beta * x) ^ gamma
f([=](double x){
auto v = (alpha + beta * x);
return (v <= std::numeric_limits<double>::epsilon()) ? 0. : pow(v, gamma);
});
break;
case miopenActivationCLIPPEDRELU: // min(alpha, max(0, x))
f([=](double x) { return (std::min(alpha, std::max(double(0.), x))); });
break;
case miopenActivationLEAKYRELU: // alpha * x | x<=0; x | x>0
f([=](double x) { return ((x > 0.) ? x : x * alpha); });
break;
case miopenActivationELU: // alpah * (exp(x)-1) | x<=0; x | x>0
f([=](double x) { return ((x > 0.) ? x : alpha * std::expm1(x)); });
break;
// default: printf("ERROR: unknown neuron type: %d\n", activMode); break;
}
}
template <class T>
void activationHostInfer(miopenActivationMode_t activMode,
double gamma,
double beta,
double alpha,
const std::vector<T> input,
std::vector<T>& output)
{
visitActivationHostInfer(activMode, gamma, beta, alpha, [&](auto f) {
par_for(input.size(), 1, [&](int index) {
output[index] = static_cast<T>(f(static_cast<double>(input[index])));
});
});
}
template <class T>
tensor<T> get_output_tensor(const miopen::ConvolutionDescriptor& filter,
const tensor<T>& input,
const tensor<T>& weights)
{
return tensor<T>{filter.GetForwardOutputTensor(input.desc, weights.desc)};
}
<commit_msg>Formatting.<commit_after>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#pragma once
#include "test.hpp"
#include <array>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <miopen/convolution.hpp>
#include <miopen/batch_norm.hpp>
#include <miopen/activ.hpp>
#include <miopen/miopen.h>
#include <miopen/tensor.hpp>
#include <utility>
// #include "network_data.hpp"
#include "driver.hpp"
#include "get_handle.hpp"
#include "tensor_holder.hpp"
#include "verify.hpp"
#include <miopen/direct_conv_ocl.hpp>
template <class T>
void convHostForward(const tensor<T>& input,
tensor<T>& output,
const tensor<T>& weights,
const int bias_mode,
const tensor<T>& bias,
const miopenConvolutionDescriptor_t convDesc)
{
int in_n, in_c, in_h, in_w;
int in_nstride, in_cstride, in_hstride, in_wstride;
std::tie(in_n, in_c, in_h, in_w) = miopen::tien<4>(input.desc.GetLengths());
std::tie(in_nstride, in_cstride, in_hstride, in_wstride) =
miopen::tien<4>(input.desc.GetStrides());
int wei_n, wei_c, wei_h, wei_w;
int wei_nstride, wei_cstride, wei_hstride, wei_wstride;
std::tie(wei_n, wei_c, wei_h, wei_w) = miopen::tien<4>(weights.desc.GetLengths());
std::tie(wei_nstride, wei_cstride, wei_hstride, wei_wstride) =
miopen::tien<4>(weights.desc.GetStrides());
int out_n, out_c, out_h, out_w;
int out_nstride, out_cstride, out_hstride, out_wstride;
std::tie(out_n, out_c, out_h, out_w) = miopen::tien<4>(output.desc.GetLengths());
std::tie(out_nstride, out_cstride, out_hstride, out_wstride) =
miopen::tien<4>(output.desc.GetStrides());
int u, v, pad_h, pad_w, dilation_h, dilation_w;
miopenConvolutionMode_t mode;
miopenPaddingMode_t pmode = miopen::deref(convDesc).paddingMode;
miopenGetConvolutionDescriptor(
convDesc, &mode, &pad_h, &pad_w, &u, &v, &dilation_h, &dilation_w);
if(pmode == miopenPaddingSame)
{
pad_h = (in_h % u == 0) ? (std::max((wei_h - u), 0)) : (std::max((wei_h - (in_h % u)), 0));
pad_w = (in_w % v == 0) ? (std::max((wei_w - v), 0)) : (std::max((wei_w - (in_w % v)), 0));
pad_h /= 2;
pad_w /= 2;
}
else if(pmode == miopenPaddingValid)
{
pad_h = 0;
pad_w = 0;
}
if(out_h <= 0 || out_w <= 0)
MIOPEN_THROW("Invalid Test Case: Check Output Dimension.");
for(int o = 0; o < out_n; o++)
{ // mini-batch size
for(int w = 0; w < out_c; w++)
{ // out_channels (num filters)
for(int i = 0; i < out_h; i++)
{ // output_height (from getforwardoutputdim())
int in_off_h = i * u;
for(int j = 0; j < out_w; j++)
{ // output_width (from getforwardoutputdim())
/*auto acc = static_cast<T>(0.);*/
auto acc = static_cast<double>(0.);
int in_off_w = j * v;
for(int k = 0; k < in_c; k++)
{ // in_channels (RGB)
for(int x = 0; x < wei_h; x++)
{
int in_x = in_off_h - pad_h + x * dilation_h;
if(in_x >= 0 && in_x < in_h)
{
for(int y = 0; y < wei_w; y++)
{
int in_y = in_off_w - pad_w + y * dilation_w;
if(in_y >= 0 && in_y < in_w)
{
acc += double(
static_cast<T>(input[o * in_nstride + k * in_cstride +
in_x * in_w + in_y]) *
static_cast<T>(weights(w, k, x, y)));
}
}
}
}
}
acc = bias_mode != 0 ? acc + static_cast<double>(bias[w]) : acc;
output[o * out_nstride + w * out_cstride + i * out_hstride + j] =
static_cast<T>(acc);
}
}
}
}
}
template <class T>
void batchNormSpatialHostInference(const tensor<T>& input,
tensor<T>& output,
const tensor<T>& scale,
const tensor<T>& bias,
double epsilon,
const tensor<T>& estimatedMean,
const tensor<T>& estimatedVariance)
{
int n_batches, channels, height, width;
std::tie(n_batches, channels, height, width) = miopen::tien<4>(input.desc.GetLengths());
par_for(channels, 1, [&](int cidx) { // via channel
double mean = estimatedMean(0, cidx, 0, 0);
double variance = estimatedVariance(0, cidx, 0, 0);
double invertVar = 1.0 / sqrt(variance + epsilon);
// process the batch per channel
for(int row = 0; row < height; row++)
{ // via rows
for(int column = 0; column < width; column++)
{ // via columns
for(int bidx = 0; bidx < n_batches; bidx++)
{ // via mini_batch
double elemStd = input(bidx, cidx, row, column) - mean;
double inhat = elemStd * invertVar;
output(bidx, cidx, row, column) =
scale(0, cidx, 0, 0) * inhat + bias(0, cidx, 0, 0);
}
}
}
});
}
template <class T>
void batchNormPerActivHostInference(const tensor<T>& input,
tensor<T>& output,
const tensor<T>& scale,
const tensor<T>& bias,
double epsilon,
const tensor<T>& estimatedMean,
const tensor<T>& estimatedVariance)
{
int n_batches, channels, height, width;
std::tie(n_batches, channels, height, width) = miopen::tien<4>(input.desc.GetLengths());
par_for(channels, 1, [&](int cidx) { // via channel
for(int row = 0; row < height; row++)
{ // via rows
for(int column = 0; column < width; column++)
{ // via columns
// apply down the n_batch dimension
double mean = estimatedMean(0, cidx, row, column);
double variance = estimatedVariance(0, cidx, row, column);
double elemInvVar = 1.0 / sqrt(variance + epsilon);
for(int bidx = 0; bidx < n_batches; bidx++)
{ // via mini_batch
// per (x-dims) channel load a block of data into LDS
double elemStd = input(bidx, cidx, row, column) - mean;
double inhat = elemStd * elemInvVar;
output(bidx, cidx, row, column) =
scale(0, cidx, row, column) * inhat + bias(0, cidx, row, column);
}
}
}
});
}
template <class F>
void visitActivationHostInfer(
miopenActivationMode_t activMode, double gamma, double beta, double alpha, F f)
{
switch(activMode)
{
case miopenActivationPASTHRU: // x
f([=](double x) { return x; });
break;
case miopenActivationLOGISTIC: // 1 / (1 + e^-x) //Sigmoid
f([=](double x) { return (1. / (1. + std::exp(-x))); });
break;
case miopenActivationTANH: // beta * tanh(alpha * x)
f([=](double x) { return (beta * std::tanh(alpha * x)); });
break;
case miopenActivationRELU: // max(0, x)
f([=](double x) { return ((x > 0.) ? x : 0.); });
break;
case miopenActivationSOFTRELU: // log(1 + e^x) // bonomial normal log likelihood
f([=](double x) {
return (x > 0.) ? (x + std::log1p(std::exp(-x))) : (std::log1p(std::exp(x)));
});
break;
case miopenActivationABS: // abs(x)
f([=](double x) { return (std::fabs(x)); });
break;
case miopenActivationPOWER: // (alpha + beta * x) ^ gamma
f([=](double x) {
auto v = (alpha + beta * x);
return (v <= std::numeric_limits<double>::epsilon()) ? 0. : pow(v, gamma);
});
break;
case miopenActivationCLIPPEDRELU: // min(alpha, max(0, x))
f([=](double x) { return (std::min(alpha, std::max(double(0.), x))); });
break;
case miopenActivationLEAKYRELU: // alpha * x | x<=0; x | x>0
f([=](double x) { return ((x > 0.) ? x : x * alpha); });
break;
case miopenActivationELU: // alpah * (exp(x)-1) | x<=0; x | x>0
f([=](double x) { return ((x > 0.) ? x : alpha * std::expm1(x)); });
break;
// default: printf("ERROR: unknown neuron type: %d\n", activMode); break;
}
}
template <class T>
void activationHostInfer(miopenActivationMode_t activMode,
double gamma,
double beta,
double alpha,
const std::vector<T> input,
std::vector<T>& output)
{
visitActivationHostInfer(activMode, gamma, beta, alpha, [&](auto f) {
par_for(input.size(), 1, [&](int index) {
output[index] = static_cast<T>(f(static_cast<double>(input[index])));
});
});
}
template <class T>
tensor<T> get_output_tensor(const miopen::ConvolutionDescriptor& filter,
const tensor<T>& input,
const tensor<T>& weights)
{
return tensor<T>{filter.GetForwardOutputTensor(input.desc, weights.desc)};
}
<|endoftext|> |
<commit_before><commit_msg>planning: add TRAFFIC_LIGHT tag to learning data<commit_after><|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_FUN_LOG_SOFTMAX_HPP
#define STAN_MATH_PRIM_FUN_LOG_SOFTMAX_HPP
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/log_sum_exp.hpp>
#include <stan/math/prim/vectorize/apply_vector_unary.hpp>
namespace stan {
namespace math {
/**
* Return the natural logarithm of the softmax of the specified
* vector.
*
* \f$
* \log \mbox{softmax}(y)
* \ = \ y - \log \sum_{k=1}^K \exp(y_k)
* \ = \ y - \mbox{log\_sum\_exp}(y).
* \f$
*
* For the log softmax function, the entries in the Jacobian are
* \f$
* \frac{\partial}{\partial y_m} \mbox{softmax}(y)[k]
* = \left\{
* \begin{array}{ll}
* 1 - \mbox{softmax}(y)[m]
* & \mbox{ if } m = k, \mbox{ and}
* \\[6pt]
* \mbox{softmax}(y)[m]
* & \mbox{ if } m \neq k.
* \end{array}
* \right.
* \f$
*
* @tparam T Type of input vector to transform.
* @param[in] x Vector to transform.
* @return log unit simplex result of the softmax transform of the vector.
*/
template <typename T, require_t<std::is_arithmetic<scalar_type_t<T>>>...>
inline auto log_softmax(const T& x) {
return apply_vector_unary<T>::apply(x, [&](const auto& v) {
check_nonzero_size("log_softmax", "v", v);
return (v.array() - log_sum_exp(v)).matrix();
});
}
} // namespace math
} // namespace stan
#endif
<commit_msg>another case<commit_after>#ifndef STAN_MATH_PRIM_FUN_LOG_SOFTMAX_HPP
#define STAN_MATH_PRIM_FUN_LOG_SOFTMAX_HPP
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/log_sum_exp.hpp>
#include <stan/math/prim/vectorize/apply_vector_unary.hpp>
namespace stan {
namespace math {
/**
* Return the natural logarithm of the softmax of the specified
* vector.
*
* \f$
* \log \mbox{softmax}(y)
* \ = \ y - \log \sum_{k=1}^K \exp(y_k)
* \ = \ y - \mbox{log\_sum\_exp}(y).
* \f$
*
* For the log softmax function, the entries in the Jacobian are
* \f$
* \frac{\partial}{\partial y_m} \mbox{softmax}(y)[k]
* = \left\{
* \begin{array}{ll}
* 1 - \mbox{softmax}(y)[m]
* & \mbox{ if } m = k, \mbox{ and}
* \\[6pt]
* \mbox{softmax}(y)[m]
* & \mbox{ if } m \neq k.
* \end{array}
* \right.
* \f$
*
* @tparam T Type of input vector to transform.
* @param[in] x Vector to transform.
* @return log unit simplex result of the softmax transform of the vector.
*/
template <typename T, require_t<std::is_arithmetic<scalar_type_t<T>>>...>
inline auto log_softmax(const T& x) {
return apply_vector_unary<T>::apply(x, [&](const auto& v) {
check_nonzero_size("log_softmax", "v", v);
return (v.array() - log_sum_exp(v)).matrix().eval();
});
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by the Free *
* Software Foundation; either version 2 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *
* more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., 51 *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/gui/qt/QMouseOperations.h>
#ifdef SOFA_QT4
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QLabel>
/*#include <QRadioButton>
#include <QPushButton>*/
#else
#include <qlayout.h>
#include <qlabel.h>
/*#include <qradiobutton.h>
#include <qpushbutton.h>*/
#endif
namespace sofa
{
namespace gui
{
namespace qt
{
QAttachOperation::QAttachOperation()
{
//Building the GUI for the Attach Operation
QHBoxLayout *layout=new QHBoxLayout(this);
QLabel *label=new QLabel(QString("Stiffness"), this);
value=new QLineEdit(QString("1000.0"), this);
layout->addWidget(label);
layout->addWidget(value);
}
double QAttachOperation::getStiffness() const
{
return atof(value->displayText().ascii());
}
QInciseOperation::QInciseOperation()
{
//Building the GUI for the Injection Operation
QHBoxLayout *layout=new QHBoxLayout(this);
incisionMethodChoiceGroup = new QGroupBox(tr("Incision method choice"));
method1 = new QRadioButton(tr("&Throw segment: Incise from click to click."));
method2 = new QRadioButton(tr("&Continually: Incise continually from first click localization."));
method1->setChecked (true);
QVBoxLayout *vbox = new QVBoxLayout;
vbox->addWidget(method1);
vbox->addWidget(method2);
// vbox->addStretch(1);
incisionMethodChoiceGroup->setLayout(vbox);
layout->addWidget(incisionMethodChoiceGroup);
}
int QInciseOperation::getIncisionMethod() const
{
if (method2->isChecked())
return 1;
else
return 0;
}
QFixOperation::QFixOperation()
{
//Building the GUI for the Fix Operation
QHBoxLayout *layout=new QHBoxLayout(this);
QLabel *label=new QLabel(QString("Fixation"), this);
value=new QLineEdit(QString("10000.0"), this);
layout->addWidget(label);
layout->addWidget(value);
}
double QFixOperation::getStiffness() const
{
return atof(value->displayText().ascii());
}
QInjectOperation::QInjectOperation()
{
//Building the GUI for the Injection Operation
QHBoxLayout *layout=new QHBoxLayout(this);
QLabel *label1=new QLabel(QString("Potential Value"), this);
value=new QLineEdit(QString("100.0"), this);
QLabel *label2=new QLabel(QString("State Tag"), this);
tag=new QLineEdit(QString("elec"), this);
layout->addWidget(label1);
layout->addWidget(value);
layout->addWidget(label2);
layout->addWidget(tag);
}
double QInjectOperation::getPotentialValue() const
{
return atof(value->displayText().ascii());
}
std::string QInjectOperation::getStateTag() const
{
return (std::string)(tag->displayText()).ascii();
}
}
}
}
<commit_msg>r5825/sofa-dev : FIX: maybe this time, fix Qt3 compilation<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by the Free *
* Software Foundation; either version 2 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *
* more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., 51 *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/gui/qt/QMouseOperations.h>
#ifdef SOFA_QT4
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QLabel>
/*#include <QRadioButton>
#include <QPushButton>*/
#else
#include <qlayout.h>
#include <qlabel.h>
#include <qgroupbox.h>
/*#include <qradiobutton.h>
#include <qpushbutton.h>*/
#endif
namespace sofa
{
namespace gui
{
namespace qt
{
QAttachOperation::QAttachOperation()
{
//Building the GUI for the Attach Operation
QHBoxLayout *layout=new QHBoxLayout(this);
QLabel *label=new QLabel(QString("Stiffness"), this);
value=new QLineEdit(QString("1000.0"), this);
layout->addWidget(label);
layout->addWidget(value);
}
double QAttachOperation::getStiffness() const
{
return atof(value->displayText().ascii());
}
QInciseOperation::QInciseOperation()
{
//Building the GUI for the Injection Operation
QHBoxLayout *layout=new QHBoxLayout(this);
incisionMethodChoiceGroup = new QGroupBox(tr("Incision method choice"),this);
method1 = new QRadioButton(tr("&Throw segment: Incise from click to click."), incisionMethodChoiceGroup);
method2 = new QRadioButton(tr("&Continually: Incise continually from first click localization."), incisionMethodChoiceGroup);
method1->setChecked (true);
QVBoxLayout *vbox = new QVBoxLayout;
vbox->addWidget(method1);
vbox->addWidget(method2);
// vbox->addStretch(1);
incisionMethodChoiceGroup->setLayout(vbox);
layout->addWidget(incisionMethodChoiceGroup);
}
int QInciseOperation::getIncisionMethod() const
{
if (method2->isChecked())
return 1;
else
return 0;
}
QFixOperation::QFixOperation()
{
//Building the GUI for the Fix Operation
QHBoxLayout *layout=new QHBoxLayout(this);
QLabel *label=new QLabel(QString("Fixation"), this);
value=new QLineEdit(QString("10000.0"), this);
layout->addWidget(label);
layout->addWidget(value);
}
double QFixOperation::getStiffness() const
{
return atof(value->displayText().ascii());
}
QInjectOperation::QInjectOperation()
{
//Building the GUI for the Injection Operation
QHBoxLayout *layout=new QHBoxLayout(this);
QLabel *label1=new QLabel(QString("Potential Value"), this);
value=new QLineEdit(QString("100.0"), this);
QLabel *label2=new QLabel(QString("State Tag"), this);
tag=new QLineEdit(QString("elec"), this);
layout->addWidget(label1);
layout->addWidget(value);
layout->addWidget(label2);
layout->addWidget(tag);
}
double QInjectOperation::getPotentialValue() const
{
return atof(value->displayText().ascii());
}
std::string QInjectOperation::getStateTag() const
{
return (std::string)(tag->displayText()).ascii();
}
}
}
}
<|endoftext|> |
<commit_before>#include <vtkPLYReader.h>
#include <vtkSmartPointer.h>
#include <iostream>
#include "ply2json.h"
using namespace std;
static string inputFilename;
static string outputFilename;
int main( int argc, char ** argv )
{
if (argc != 3)
{
cout << "Usage: " << argv[0] << " filename.ply outputName" << endl;
return EXIT_FAILURE;
}
inputFilename = argv[1];
outputFilename = argv[2];
loadFile();
return EXIT_SUCCESS;
}
void loadFile()
{
vtkSmartPointer<vtkPLYReader> reader =
vtkSmartPointer<vtkPLYReader>::New();
reader->SetFileName ( inputFilename.c_str() );
reader->Update();
//reader->GetOutput()->Register(reader);
vtkPolyData * output = reader->GetOutput();
vtkIdType vert = output->GetNumberOfVerts();
cout << "verts: " << vert << endl;
vtkIdType poly = output->GetNumberOfPolys();
cout << "polys: " << poly << endl;
}
<commit_msg>reimplemented reading, now can read vertices as well<commit_after>#include <vtkPLYReader.h>
#include <vtkSmartPointer.h>
#include <iostream>
#include "ply2json.h"
using namespace std;
static string inputFilename;
static string outputFilename;
int main( int argc, char ** argv )
{
if (argc != 3)
{
cout << "Usage: " << argv[0] << " filename.ply outputName" << endl;
return EXIT_FAILURE;
}
inputFilename = argv[1];
outputFilename = argv[2];
loadFile();
return EXIT_SUCCESS;
}
void loadFile()
{
vtkSmartPointer<vtkPLYReader> reader =
vtkSmartPointer<vtkPLYReader>::New();
reader->SetFileName ( inputFilename.c_str() );
reader->Update();
vtkDataSet * data = reader->GetOutput();
vtkIdType vert = data->GetNumberOfPoints();
cout << "Vertices: " << vert << endl;
vtkIdType poly = data->GetNumberOfCells();
cout << "Polygons: " << poly << endl;
}
<|endoftext|> |
<commit_before>/*
########## Copyright (C) 2015 Vincenzo Pacella
## ## Distributed under MIT license, see file LICENSE
## ## or <http://opensource.org/licenses/MIT>
## ##
########## ############################################################# shaduzlabs.com #####*/
#include <catch.hpp>
#include <lodepng.h>
#include <gfx/Canvas.h>
#include <iostream>
#include "gfx/CanvasTestFunctions.h"
#include "gfx/CanvasTestHelpers.h"
//--------------------------------------------------------------------------------------------------
namespace sl
{
namespace cabl
{
namespace test
{
//--------------------------------------------------------------------------------------------------
namespace
{
std::string pngFileName(const std::string& test_)
{
return "test-data/gfx/Canvas-" + test_ + ".png";
}
} // namespace
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: constructor", "[gfx/Canvas]")
{
Canvas c(16, 5);
CHECK(c.width() == 16);
CHECK(c.height() == 5);
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: lines", "[gfx/Canvas]")
{
Canvas display(128, 128), displayFromPng(128, 128);
lines(&display);
REQUIRE(pngRead(&displayFromPng, pngFileName("lines")));
CHECK(compare(&display, &displayFromPng));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: circles", "[gfx/Canvas]")
{
Canvas display(128, 128), displayFromPng(128, 128);
circles(&display);
REQUIRE(pngRead(&displayFromPng, pngFileName("circles")));
CHECK(compare(&display, &displayFromPng));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: triangles", "[gfx/Canvas]")
{
Canvas display(128, 128), displayFromPng(128, 128);
triangles(&display);
REQUIRE(pngRead(&displayFromPng, pngFileName("triangles")));
CHECK(compare(&display,&displayFromPng));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: rectangles", "[gfx/Canvas]")
{
Canvas display(128, 128), displayFromPng(128, 128);
rectangles(&display);
REQUIRE(pngRead(&displayFromPng, pngFileName("rectangles")));
CHECK(compare(&display,&displayFromPng));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: text", "[gfx/Canvas]")
{
Canvas display(128, 128), displayFromPng(128, 128);
text(&display);
REQUIRE(pngWrite(&display, pngFileName("text")));
CHECK(compare(&display,&displayFromPng));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: canvas", "[gfx/Canvas]")
{
Canvas display(128, 128), displayFromPng(128, 128);
canvas(&display);
REQUIRE(pngRead(&displayFromPng, pngFileName("canvas")));
CHECK(compare(&display, &displayFromPng));
}
//--------------------------------------------------------------------------------------------------
} // namespace test
} // namespace cabl
} // namespace sl
<commit_msg>fixed failing test<commit_after>/*
########## Copyright (C) 2015 Vincenzo Pacella
## ## Distributed under MIT license, see file LICENSE
## ## or <http://opensource.org/licenses/MIT>
## ##
########## ############################################################# shaduzlabs.com #####*/
#include <catch.hpp>
#include <lodepng.h>
#include <gfx/Canvas.h>
#include <iostream>
#include "gfx/CanvasTestFunctions.h"
#include "gfx/CanvasTestHelpers.h"
//--------------------------------------------------------------------------------------------------
namespace sl
{
namespace cabl
{
namespace test
{
//--------------------------------------------------------------------------------------------------
namespace
{
std::string pngFileName(const std::string& test_)
{
return "test-data/gfx/Canvas-" + test_ + ".png";
}
} // namespace
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: constructor", "[gfx/Canvas]")
{
Canvas c(16, 5);
CHECK(c.width() == 16);
CHECK(c.height() == 5);
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: lines", "[gfx/Canvas]")
{
Canvas display(128, 128), displayFromPng(128, 128);
lines(&display);
REQUIRE(pngRead(&displayFromPng, pngFileName("lines")));
CHECK(compare(&display, &displayFromPng));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: circles", "[gfx/Canvas]")
{
Canvas display(128, 128), displayFromPng(128, 128);
circles(&display);
REQUIRE(pngRead(&displayFromPng, pngFileName("circles")));
CHECK(compare(&display, &displayFromPng));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: triangles", "[gfx/Canvas]")
{
Canvas display(128, 128), displayFromPng(128, 128);
triangles(&display);
REQUIRE(pngRead(&displayFromPng, pngFileName("triangles")));
CHECK(compare(&display,&displayFromPng));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: rectangles", "[gfx/Canvas]")
{
Canvas display(128, 128), displayFromPng(128, 128);
rectangles(&display);
REQUIRE(pngRead(&displayFromPng, pngFileName("rectangles")));
CHECK(compare(&display,&displayFromPng));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: text", "[gfx/Canvas]")
{
Canvas display(128, 128), displayFromPng(128, 128);
text(&display);
REQUIRE(pngRead(&displayFromPng, pngFileName("text")));
CHECK(compare(&display,&displayFromPng));
}
//--------------------------------------------------------------------------------------------------
TEST_CASE("Canvas: canvas", "[gfx/Canvas]")
{
Canvas display(128, 128), displayFromPng(128, 128);
canvas(&display);
REQUIRE(pngRead(&displayFromPng, pngFileName("canvas")));
CHECK(compare(&display, &displayFromPng));
}
//--------------------------------------------------------------------------------------------------
} // namespace test
} // namespace cabl
} // namespace sl
<|endoftext|> |
<commit_before>
#include "numerics/elliptic_functions.hpp"
#include <tuple>
#include "glog/logging.h"
#include "numerics/combinatorics.hpp"
#include "numerics/elliptic_integrals.hpp"
#include "numerics/polynomial.hpp"
#include "numerics/polynomial_evaluators.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/numbers.hpp"
namespace principia {
using quantities::Abs;
using quantities::Sqrt;
namespace numerics {
namespace {
void JacobiSNCNDNReduced(double u, double mc, double& s, double& c, double& d);
// Maclaurin series for Fukushima b₀. These are polynomials in m that are used
// as coefficients of a polynomial in u₀². The index gives the corresponding
// power of u₀².
PolynomialInMonomialBasis<double, double, 0, HornerEvaluator>
fukushima_b₀_maclaurin_m_1(std::make_tuple(1.0 / 2.0));
PolynomialInMonomialBasis<double, double, 1, HornerEvaluator>
fukushima_b₀_maclaurin_m_2(std::make_tuple(-1.0 / 24.0, -1.0 / 6.0));
PolynomialInMonomialBasis<double, double, 2, HornerEvaluator>
fukushima_b₀_maclaurin_m_3(std::make_tuple(1.0 / 720.0,
11.0 / 180.0,
1.0 / 45.0));
// Double precision subroutine to compute three Jacobian elliptic functions
// simultaneously
//
// For limited argument: 0 <= u < K/2
//
// Reference: T. Fukushima, (2012) Numer. Math.
// DOI 10.1007/s00211-012-0498-0
// "Precise and Fast Computation of Jacobian Elliptic Functions by
// Conditional Duplication"
//
// Author: T. Fukushima Toshio.Fukushima@nao.ac.jp
//
// Inputs: u = argument, mc = 1-m, 0 < mc <= 1
//
// Output: s = sn(u|m), c=cn(u|m), d=dn(u|m)
//
void JacobiSNCNDNReduced(double const u,
double const mc,
double& s,
double& c,
double& d) {
constexpr int max_reductions = 20;
double const m = 1.0 - mc;
double const uT = 5.217e-3 - 2.143e-3 * m;
double u₀ = u;
int n = 0; // Note that this variable is used after the loop.
for (; u₀ >= uT; ++n) {
DCHECK_LE(n, max_reductions)
<< "u₀ = " << u₀ << " u = " << u << " mc = " << mc;
u₀ = 0.5 * u₀;
}
double const b₀1 = fukushima_b₀_maclaurin_m_1.Evaluate(m);
double const b₀2 = fukushima_b₀_maclaurin_m_2.Evaluate(m);
double const b₀3 = fukushima_b₀_maclaurin_m_3.Evaluate(m);
PolynomialInMonomialBasis<double, double, 3, HornerEvaluator>
fukushima_b₀_maclaurin_u₀²_3(std::make_tuple(0.0, b₀1, b₀2, b₀3));
double const u₀² = u₀ * u₀;
// We use the subscript i to indicate variables that are computed as part of
// the iteration (Fukushima uses subscripts n and N). This avoids confusion
// between c (the result) and cᵢ (the intermediate numerator of c).
double bᵢ = fukushima_b₀_maclaurin_u₀²_3.Evaluate(u₀²);
double const uA = 1.76269 + 1.16357 * mc;
bool const may_have_cancellation = u > uA;
double aᵢ = 1.0;
for (int i = 0; i < n; ++i) {
double const yᵢ = bᵢ * (2.0 * aᵢ - bᵢ);
double const zᵢ = aᵢ * aᵢ;
double const myᵢ = m * yᵢ;
if (may_have_cancellation && zᵢ < 2.0 * myᵢ) {
double cᵢ = aᵢ - bᵢ;
double const two_mc = 2.0 * mc;
double const two_m = 2.0 * m;
for (; i < n; ++i) {
double const xᵢ = cᵢ * cᵢ;
double const zᵢ = aᵢ * aᵢ;
double const wᵢ = m * xᵢ * xᵢ - mc * zᵢ * zᵢ;
double const xᵢzᵢ = xᵢ * zᵢ;
cᵢ = two_mc * xᵢzᵢ + wᵢ;
aᵢ = two_m * xᵢzᵢ - wᵢ;
}
c = cᵢ / aᵢ;
double const c² = c * c;
s = Sqrt(1.0 - c²);
d = Sqrt(mc + m * c²);
return;
}
bᵢ = 2.0 * yᵢ * (zᵢ - myᵢ);
aᵢ = zᵢ * zᵢ - myᵢ * yᵢ;
}
bᵢ = bᵢ / aᵢ;
double const yᵢ = bᵢ * (2.0 - bᵢ);
c = 1.0 - bᵢ;
s = Sqrt(yᵢ);
d = Sqrt(1.0 - m * yᵢ);
}
} // namespace
// Double precision subroutine to compute three Jacobian elliptic functions
// simultaneously
//
// For general argument: -infty < u < infty
//
// Reference: T. Fukushima, (2012) Numer. Math.
// DOI 10.1007/s00211-012-0498-0
// "Precise and Fast Computation of Jacobian Elliptic Functions by
// Conditional Duplication"
//
// Author: T. Fukushima Toshio.Fukushima@nao.ac.jp
//
// Inputs: u = argument, mc = 1-m, 0 < mc <= 1
//
// Output: s = sn(u|m), c=cn(u|m), d=dn(u|m)
//
void JacobiSNCNDN(double const u,
double const mc,
double& s,
double& c,
double& d) {
constexpr double k_over_2_lower_bound = π / 4.0;
// The argument reduction follows Fukushima (2009), Fast computation of
// Jacobian elliptic function and incomplete elliptic integrals for constant
// values of elliptic parameter and elliptic characteristic, sections 2.4 and
// 3.5.2.
double const m = 1.0 - mc;
double const kʹ = Sqrt(mc);
double abs_u = Abs(u);
if (abs_u < k_over_2_lower_bound) {
JacobiSNCNDNReduced(abs_u, mc, s, c, d);
} else {
double const k = EllipticK(mc);
double const k_over_2 = 0.5 * k;
double const three_k_over_2 = 1.5 * k;
double const two_k = 2.0 * k;
double const five_k_over_2 = 2.5 * k;
double const three_k = 3.0 * k;
double const seven_k_over_2 = 3.5 * k;
double const four_k = 4.0 * k;
abs_u =
abs_u - four_k * static_cast<double>(static_cast<int>(abs_u / four_k));
if (abs_u < k_over_2) {
JacobiSNCNDNReduced(abs_u, mc, s, c, d);
} else if (abs_u < k) {
abs_u = k - abs_u;
JacobiSNCNDNReduced(abs_u, mc, s, c, d);
double const sx = c / d;
c = kʹ * s / d;
s = sx;
d = kʹ / d;
} else if (abs_u < three_k_over_2) {
abs_u = abs_u - k;
JacobiSNCNDNReduced(abs_u, mc, s, c, d);
double const sx = c / d;
c = -kʹ * s / d;
s = sx;
d = kʹ / d;
} else if (abs_u < two_k) {
abs_u = two_k - abs_u;
JacobiSNCNDNReduced(abs_u, mc, s, c, d);
c = -c;
} else if (abs_u < five_k_over_2) {
abs_u = abs_u - two_k;
JacobiSNCNDNReduced(abs_u, mc, s, c, d);
s = -s;
c = -c;
} else if (abs_u < three_k) {
abs_u = three_k - abs_u;
JacobiSNCNDNReduced(abs_u, mc, s, c, d);
double const sx = -c / d;
c = -kʹ * s / d;
s = sx;
d = kʹ / d;
} else if (abs_u < seven_k_over_2) {
abs_u = abs_u - three_k;
JacobiSNCNDNReduced(abs_u, mc, s, c, d);
double const sx = -c / d;
c = kʹ * s / d;
s = sx;
d = kʹ / d;
} else {
abs_u = four_k - abs_u;
JacobiSNCNDNReduced(abs_u, mc, s, c, d);
s = -s;
}
}
if (u < 0.0) {
s = -s;
}
}
} // namespace numerics
} // namespace principia
<commit_msg>Some simplification.<commit_after>
#include "numerics/elliptic_functions.hpp"
#include <tuple>
#include "glog/logging.h"
#include "numerics/combinatorics.hpp"
#include "numerics/elliptic_integrals.hpp"
#include "numerics/polynomial.hpp"
#include "numerics/polynomial_evaluators.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/numbers.hpp"
namespace principia {
using quantities::Abs;
using quantities::Sqrt;
namespace numerics {
namespace {
void JacobiSNCNDNReduced(double u, double mc, double& s, double& c, double& d);
// Maclaurin series for Fukushima b₀. These are polynomials in m that are used
// as coefficients of a polynomial in u₀². The index gives the corresponding
// power of u₀².
PolynomialInMonomialBasis<double, double, 0, HornerEvaluator>
fukushima_b₀_maclaurin_m_1(std::make_tuple(1.0 / 2.0));
PolynomialInMonomialBasis<double, double, 1, HornerEvaluator>
fukushima_b₀_maclaurin_m_2(std::make_tuple(-1.0 / 24.0, -1.0 / 6.0));
PolynomialInMonomialBasis<double, double, 2, HornerEvaluator>
fukushima_b₀_maclaurin_m_3(std::make_tuple(1.0 / 720.0,
11.0 / 180.0,
1.0 / 45.0));
// Double precision subroutine to compute three Jacobian elliptic functions
// simultaneously
//
// For limited argument: 0 <= u < K/2
//
// Reference: T. Fukushima, (2012) Numer. Math.
// DOI 10.1007/s00211-012-0498-0
// "Precise and Fast Computation of Jacobian Elliptic Functions by
// Conditional Duplication"
//
// Author: T. Fukushima Toshio.Fukushima@nao.ac.jp
//
// Inputs: u = argument, mc = 1-m, 0 < mc <= 1
//
// Output: s = sn(u|m), c=cn(u|m), d=dn(u|m)
//
void JacobiSNCNDNReduced(double const u,
double const mc,
double& s,
double& c,
double& d) {
constexpr int max_reductions = 20;
double const m = 1.0 - mc;
double const uT = 5.217e-3 - 2.143e-3 * m;
double u₀ = u;
int n = 0; // Note that this variable is used after the loop.
for (; u₀ >= uT; ++n) {
DCHECK_LE(n, max_reductions)
<< "u₀ = " << u₀ << " u = " << u << " mc = " << mc;
u₀ = 0.5 * u₀;
}
double const b₀1 = fukushima_b₀_maclaurin_m_1.Evaluate(m);
double const b₀2 = fukushima_b₀_maclaurin_m_2.Evaluate(m);
double const b₀3 = fukushima_b₀_maclaurin_m_3.Evaluate(m);
PolynomialInMonomialBasis<double, double, 3, HornerEvaluator>
fukushima_b₀_maclaurin_u₀²_3(std::make_tuple(0.0, b₀1, b₀2, b₀3));
double const u₀² = u₀ * u₀;
// We use the subscript i to indicate variables that are computed as part of
// the iteration (Fukushima uses subscripts n and N). This avoids confusion
// between c (the result) and cᵢ (the intermediate numerator of c).
double bᵢ = fukushima_b₀_maclaurin_u₀²_3.Evaluate(u₀²);
double const uA = 1.76269 + 1.16357 * mc;
bool const may_have_cancellation = u > uA;
double aᵢ = 1.0;
for (int i = 0; i < n; ++i) {
double const yᵢ = bᵢ * (2.0 * aᵢ - bᵢ);
double const zᵢ = aᵢ * aᵢ;
double const myᵢ = m * yᵢ;
if (may_have_cancellation && zᵢ < 2.0 * myᵢ) {
double cᵢ = aᵢ - bᵢ;
double const two_mc = 2.0 * mc;
double const two_m = 2.0 * m;
for (; i < n; ++i) {
double const xᵢ = cᵢ * cᵢ;
double const zᵢ = aᵢ * aᵢ;
double const wᵢ = m * xᵢ * xᵢ - mc * zᵢ * zᵢ;
double const xᵢzᵢ = xᵢ * zᵢ;
cᵢ = two_mc * xᵢzᵢ + wᵢ;
aᵢ = two_m * xᵢzᵢ - wᵢ;
}
c = cᵢ / aᵢ;
double const c² = c * c;
s = Sqrt(1.0 - c²);
d = Sqrt(mc + m * c²);
return;
}
bᵢ = 2.0 * yᵢ * (zᵢ - myᵢ);
aᵢ = zᵢ * zᵢ - myᵢ * yᵢ;
}
bᵢ = bᵢ / aᵢ;
double const yᵢ = bᵢ * (2.0 - bᵢ);
c = 1.0 - bᵢ;
s = Sqrt(yᵢ);
d = Sqrt(1.0 - m * yᵢ);
}
} // namespace
// Double precision subroutine to compute three Jacobian elliptic functions
// simultaneously
//
// For general argument: -infty < u < infty
//
// Reference: T. Fukushima, (2012) Numer. Math.
// DOI 10.1007/s00211-012-0498-0
// "Precise and Fast Computation of Jacobian Elliptic Functions by
// Conditional Duplication"
//
// Author: T. Fukushima Toshio.Fukushima@nao.ac.jp
//
// Inputs: u = argument, mc = 1-m, 0 < mc <= 1
//
// Output: s = sn(u|m), c=cn(u|m), d=dn(u|m)
//
void JacobiSNCNDN(double const u,
double const mc,
double& s,
double& c,
double& d) {
constexpr double k_over_2_lower_bound = π / 4.0;
// The argument reduction follows Fukushima (2009), Fast computation of
// Jacobian elliptic function and incomplete elliptic integrals for constant
// values of elliptic parameter and elliptic characteristic, sections 2.4 and
// 3.5.2.
double const m = 1.0 - mc;
double const kʹ = Sqrt(mc);
double abs_u = Abs(u);
if (abs_u < k_over_2_lower_bound) {
JacobiSNCNDNReduced(abs_u, mc, s, c, d);
} else {
double const k = EllipticK(mc);
double const k_over_2 = 0.5 * k;
double const three_k_over_2 = 1.5 * k;
double const two_k = 2.0 * k;
double const five_k_over_2 = 2.5 * k;
double const three_k = 3.0 * k;
double const seven_k_over_2 = 3.5 * k;
double const four_k = 4.0 * k;
abs_u =
abs_u - four_k * static_cast<double>(static_cast<int>(abs_u / four_k));
if (abs_u < k_over_2) {
JacobiSNCNDNReduced(abs_u, mc, s, c, d);
} else if (abs_u < k) {
JacobiSNCNDNReduced(k - abs_u, mc, s, c, d);
double const sx = c / d;
c = kʹ * s / d;
s = sx;
d = kʹ / d;
} else if (abs_u < three_k_over_2) {
JacobiSNCNDNReduced(abs_u - k, mc, s, c, d);
double const sx = c / d;
c = -kʹ * s / d;
s = sx;
d = kʹ / d;
} else if (abs_u < two_k) {
JacobiSNCNDNReduced(two_k - abs_u, mc, s, c, d);
c = -c;
} else if (abs_u < five_k_over_2) {
JacobiSNCNDNReduced(abs_u - two_k, mc, s, c, d);
s = -s;
c = -c;
} else if (abs_u < three_k) {
JacobiSNCNDNReduced(three_k - abs_u, mc, s, c, d);
double const sx = -c / d;
c = -kʹ * s / d;
s = sx;
d = kʹ / d;
} else if (abs_u < seven_k_over_2) {
JacobiSNCNDNReduced(abs_u - three_k, mc, s, c, d);
double const sx = -c / d;
c = kʹ * s / d;
s = sx;
d = kʹ / d;
} else {
JacobiSNCNDNReduced(four_k - abs_u, mc, s, c, d);
s = -s;
}
}
if (u < 0.0) {
s = -s;
}
}
} // namespace numerics
} // namespace principia
<|endoftext|> |
<commit_before>#include <string.h>
#include "bigid.h"
#include "utils.h"
#include "sha1.h"
namespace dht {
BigId::BigId() {
memset(sha1_, 0, arraysize(sha1_));
}
BigId::BigId(const std::string& s) {
sha1::calc(&s[0], s.size(), sha1_);
}
BigId::BigId(const char* p, int n) {
sha1::calc(p, n, sha1_);
}
int BigId::cmp(const BigId& o) const {
return memcmp(sha1_, o.sha1_, BigId::M);
}
} // namespace dht
<commit_msg>fix bigid comparison<commit_after>#include <string.h>
#include "bigid.h"
#include "utils.h"
#include "sha1.h"
namespace dht {
BigId::BigId() {
memset(sha1_, 0, arraysize(sha1_));
}
BigId::BigId(const std::string& s) {
sha1::calc(&s[0], s.size(), sha1_);
}
BigId::BigId(const char* p, int n) {
sha1::calc(p, n, sha1_);
}
int BigId::cmp(const BigId& o) const {
int full_bytes = BigId::M / 8;
int r = memcmp(sha1_, o.sha1_, full_bytes);
if (r != 0) {
return r;
}
int residual = BigId::M % 8;
if (residual == 0) {
return r;
}
int mask = (1 << residual) - 1;
int a = sha1_[full_bytes] & mask;
int b = o.sha1_[full_bytes] & mask;
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
}
} // namespace dht
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: expander.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 09:25:35 $
*
* 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 _SV_EXPANDER_HXX
#define _SV_EXPANDER_HXX
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_IMAGE_HXX
#include <vcl/image.hxx>
#endif
enum SvExpanderStateType
{
EST_MIN=1,
EST_PLUS=2,
EST_MIN_DOWN=3,
EST_PLUS_DOWN=4,
EST_NONE=5,
EST_MIN_DIS=6,
EST_PLUS_DIS=7,
EST_MIN_DOWN_DIS=8,
EST_PLUS_DOWN_DIS=9
};
class SvExpander: public Control
{
private:
Point aImagePos;
Point aTextPos;
Image aActiveImage;
Rectangle maFocusRect;
ImageList maExpanderImages;
BOOL mbIsExpanded;
BOOL mbHasFocusRect;
BOOL mbIsInMouseDown;
Link maToggleHdl;
SvExpanderStateType eType;
protected:
virtual long PreNotify( NotifyEvent& rNEvt );
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseMove( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual void Paint( const Rectangle& rRect );
virtual void KeyInput( const KeyEvent& rKEvt );
virtual void KeyUp( const KeyEvent& rKEvt );
virtual void Click();
virtual void Resize();
public:
SvExpander( Window* pParent, WinBits nStyle = 0 );
SvExpander( Window* pParent, const ResId& rResId );
BOOL IsExpanded() {return mbIsExpanded;}
void SetToExpanded(BOOL bFlag=TRUE);
void SetExpanderImage( SvExpanderStateType eType);
Image GetExpanderImage(SvExpanderStateType eType);
Size GetMinSize() const;
void SetToggleHdl( const Link& rLink ) { maToggleHdl = rLink; }
const Link& GetToggleHdl() const { return maToggleHdl; }
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.774); FILE MERGED 2008/04/01 15:44:19 thb 1.2.774.2: #i85898# Stripping all external header guards 2008/03/31 13:00:48 rt 1.2.774.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: expander.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SV_EXPANDER_HXX
#define _SV_EXPANDER_HXX
#include <vcl/ctrl.hxx>
#include <vcl/image.hxx>
enum SvExpanderStateType
{
EST_MIN=1,
EST_PLUS=2,
EST_MIN_DOWN=3,
EST_PLUS_DOWN=4,
EST_NONE=5,
EST_MIN_DIS=6,
EST_PLUS_DIS=7,
EST_MIN_DOWN_DIS=8,
EST_PLUS_DOWN_DIS=9
};
class SvExpander: public Control
{
private:
Point aImagePos;
Point aTextPos;
Image aActiveImage;
Rectangle maFocusRect;
ImageList maExpanderImages;
BOOL mbIsExpanded;
BOOL mbHasFocusRect;
BOOL mbIsInMouseDown;
Link maToggleHdl;
SvExpanderStateType eType;
protected:
virtual long PreNotify( NotifyEvent& rNEvt );
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseMove( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual void Paint( const Rectangle& rRect );
virtual void KeyInput( const KeyEvent& rKEvt );
virtual void KeyUp( const KeyEvent& rKEvt );
virtual void Click();
virtual void Resize();
public:
SvExpander( Window* pParent, WinBits nStyle = 0 );
SvExpander( Window* pParent, const ResId& rResId );
BOOL IsExpanded() {return mbIsExpanded;}
void SetToExpanded(BOOL bFlag=TRUE);
void SetExpanderImage( SvExpanderStateType eType);
Image GetExpanderImage(SvExpanderStateType eType);
Size GetMinSize() const;
void SetToggleHdl( const Link& rLink ) { maToggleHdl = rLink; }
const Link& GetToggleHdl() const { return maToggleHdl; }
};
#endif
<|endoftext|> |
<commit_before>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2016 LiteIDE Team. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** In addition, as a special exception, that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: quickopenfiles.cpp
// Creator: visualfc <visualfc@gmail.com>
#include "quickopenfiles.h"
#include "quickopen_global.h"
#include <QStandardItemModel>
#include <QStandardItem>
#include <QSortFilterProxyModel>
#include <QDir>
#include <QFileInfo>
#include <QTimer>
#include <QApplication>
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif
//lite_memory_check_end
QuickOpenFiles::QuickOpenFiles(LiteApi::IApplication *app, QObject *parent)
: LiteApi::IQuickOpen(parent), m_liteApp(app)
{
m_model = new QStandardItemModel(this);
m_proxyModel = new QSortFilterProxyModel(this);
m_proxyModel->setSourceModel(m_model);
m_matchCase = Qt::CaseInsensitive;
m_maxCount = 100000;
}
QString QuickOpenFiles::id() const
{
return "quickopen/files";
}
QString QuickOpenFiles::info() const
{
return tr("Open Files by Name");
}
void QuickOpenFiles::activate()
{
}
QAbstractItemModel *QuickOpenFiles::model() const
{
return m_proxyModel;
}
void updateFolder(QString folder, QStandardItemModel *model, int maxcount, QSet<QString> *extSet, QSet<QString> *folderSet, QSet<QString> *editorSet)
{
if (model->rowCount() >= maxcount) {
return;
}
if (folderSet->contains(folder)) {
return;
}
folderSet->insert(folder);
qApp->processEvents();
QDir dir(folder);
foreach (QFileInfo info, dir.entryInfoList(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot)) {
if (info.isDir()) {
updateFolder(info.filePath(),model,maxcount,extSet,folderSet,editorSet);
} else if (info.isFile()) {
if (extSet->contains(info.suffix()) && !editorSet->contains(info.filePath()) ) {
model->appendRow(QList<QStandardItem*>() << new QStandardItem("f") << new QStandardItem(info.fileName()) << new QStandardItem(info.filePath()));
}
}
}
}
void QuickOpenFiles::updateModel()
{
m_maxCount = m_liteApp->settings()->value(QUICKOPEN_FILES_MAXCOUNT,100000).toInt();
m_matchCase = m_liteApp->settings()->value(QUICKOPNE_FILES_MATCHCASE,false).toBool() ? Qt::CaseSensitive : Qt::CaseInsensitive;
m_model->clear();
m_proxyModel->setFilterFixedString("");
m_proxyModel->setFilterKeyColumn(2);
m_proxyModel->setFilterCaseSensitivity(m_matchCase);
m_editors.clear();
QStringList names;
foreach(LiteApi::IEditor *editor, m_liteApp->editorManager()->editorList()) {
if (editor->filePath().isEmpty()) {
continue;
}
names.push_back(editor->name()+";"+editor->filePath());
m_editors.push_back(editor->filePath());
}
qSort(names);
foreach (QString text, names) {
QStringList ar = text.split(";");
m_model->appendRow(QList<QStandardItem*>() << new QStandardItem("*") << new QStandardItem(ar[0]) << new QStandardItem(ar[1]) );
}
QTimer::singleShot(1,this,SLOT(updateFiles()));
}
void QuickOpenFiles::updateFiles()
{
QSet<QString> extSet;
foreach(LiteApi::IMimeType* type, m_liteApp->mimeTypeManager()->mimeTypeList()) {
foreach (QString ext, type->globPatterns()) {
if (ext.startsWith(".")) {
extSet << ext.mid(1);
} else if (ext.startsWith("*.")) {
extSet << ext.mid(2);
}
}
}
int count = m_model->rowCount();
int maxcount = count+m_liteApp->settings()->value(QUICKOPEN_FILES_MAXCOUNT,100000).toInt();
QSet<QString> folderSet;
QSet<QString> editorSet = m_editors.toSet();
foreach(QString folder, m_liteApp->fileManager()->folderList()) {
updateFolder(folder,m_model,maxcount, &extSet, &folderSet, &editorSet);
}
}
QModelIndex QuickOpenFiles::filterChanged(const QString &text)
{
m_proxyModel->setFilterFixedString(text);
for(int i = 0; i < m_proxyModel->rowCount(); i++) {
QModelIndex index = m_proxyModel->index(i,1);
QString name = index.data().toString();
if (name.startsWith(text,m_matchCase)) {
return index;
}
}
if (m_proxyModel->rowCount() > 0)
return m_proxyModel->index(0,0);
return QModelIndex();
}
void QuickOpenFiles::indexChanged(const QModelIndex &/*index*/)
{
}
bool QuickOpenFiles::selected(const QString &text, const QModelIndex &index)
{
if (!index.isValid()) {
return false;
}
QString filePath = m_proxyModel->index(index.row(),2).data().toString();
if (!m_liteApp->fileManager()->openFile(filePath)) {
return false;
}
return true;
}
<commit_msg>quickopen add editor local files<commit_after>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2016 LiteIDE Team. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** In addition, as a special exception, that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: quickopenfiles.cpp
// Creator: visualfc <visualfc@gmail.com>
#include "quickopenfiles.h"
#include "quickopen_global.h"
#include <QStandardItemModel>
#include <QStandardItem>
#include <QSortFilterProxyModel>
#include <QDir>
#include <QFileInfo>
#include <QTimer>
#include <QApplication>
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif
//lite_memory_check_end
QuickOpenFiles::QuickOpenFiles(LiteApi::IApplication *app, QObject *parent)
: LiteApi::IQuickOpen(parent), m_liteApp(app)
{
m_model = new QStandardItemModel(this);
m_proxyModel = new QSortFilterProxyModel(this);
m_proxyModel->setSourceModel(m_model);
m_matchCase = Qt::CaseInsensitive;
m_maxCount = 100000;
}
QString QuickOpenFiles::id() const
{
return "quickopen/files";
}
QString QuickOpenFiles::info() const
{
return tr("Open Files by Name");
}
void QuickOpenFiles::activate()
{
}
QAbstractItemModel *QuickOpenFiles::model() const
{
return m_proxyModel;
}
void updateFolder(QString folder, QStandardItemModel *model, int maxcount, QSet<QString> *extSet, QSet<QString> *folderSet, QSet<QString> *editorSet)
{
if (model->rowCount() >= maxcount) {
return;
}
if (folderSet->contains(folder)) {
return;
}
folderSet->insert(folder);
qApp->processEvents();
QDir dir(folder);
foreach (QFileInfo info, dir.entryInfoList(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot)) {
if (info.isDir()) {
updateFolder(info.filePath(),model,maxcount,extSet,folderSet,editorSet);
} else if (info.isFile()) {
if (extSet->contains(info.suffix()) && !editorSet->contains(info.filePath()) ) {
model->appendRow(QList<QStandardItem*>() << new QStandardItem("f") << new QStandardItem(info.fileName()) << new QStandardItem(info.filePath()));
}
}
}
}
void QuickOpenFiles::updateModel()
{
m_maxCount = m_liteApp->settings()->value(QUICKOPEN_FILES_MAXCOUNT,100000).toInt();
m_matchCase = m_liteApp->settings()->value(QUICKOPNE_FILES_MATCHCASE,false).toBool() ? Qt::CaseSensitive : Qt::CaseInsensitive;
m_model->clear();
m_proxyModel->setFilterFixedString("");
m_proxyModel->setFilterKeyColumn(2);
m_proxyModel->setFilterCaseSensitivity(m_matchCase);
m_editors.clear();
QStringList names;
foreach(LiteApi::IEditor *editor, m_liteApp->editorManager()->editorList()) {
if (editor->filePath().isEmpty()) {
continue;
}
names.push_back(editor->name()+";"+editor->filePath());
m_editors.push_back(editor->filePath());
}
qSort(names);
foreach (QString text, names) {
QStringList ar = text.split(";");
m_model->appendRow(QList<QStandardItem*>() << new QStandardItem("*") << new QStandardItem(ar[0]) << new QStandardItem(ar[1]) );
}
QTimer::singleShot(1,this,SLOT(updateFiles()));
}
void QuickOpenFiles::updateFiles()
{
QSet<QString> extSet;
foreach(LiteApi::IMimeType* type, m_liteApp->mimeTypeManager()->mimeTypeList()) {
foreach (QString ext, type->globPatterns()) {
if (ext.startsWith(".")) {
extSet << ext.mid(1);
} else if (ext.startsWith("*.")) {
extSet << ext.mid(2);
}
}
}
int count = m_model->rowCount();
int maxcount = count+m_liteApp->settings()->value(QUICKOPEN_FILES_MAXCOUNT,100000).toInt();
QSet<QString> folderSet;
QSet<QString> editorSet = m_editors.toSet();
LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor();
if (editor && !editor->filePath().isEmpty()) {
QString folder = QFileInfo(editor->filePath()).path();
updateFolder(folder,m_model,maxcount, &extSet, &folderSet, &editorSet);
}
foreach(QString folder, m_liteApp->fileManager()->folderList()) {
updateFolder(folder,m_model,maxcount, &extSet, &folderSet, &editorSet);
}
}
QModelIndex QuickOpenFiles::filterChanged(const QString &text)
{
m_proxyModel->setFilterFixedString(text);
for(int i = 0; i < m_proxyModel->rowCount(); i++) {
QModelIndex index = m_proxyModel->index(i,1);
QString name = index.data().toString();
if (name.startsWith(text,m_matchCase)) {
return index;
}
}
if (m_proxyModel->rowCount() > 0)
return m_proxyModel->index(0,0);
return QModelIndex();
}
void QuickOpenFiles::indexChanged(const QModelIndex &/*index*/)
{
}
bool QuickOpenFiles::selected(const QString &text, const QModelIndex &index)
{
if (!index.isValid()) {
return false;
}
QString filePath = m_proxyModel->index(index.row(),2).data().toString();
if (!m_liteApp->fileManager()->openFile(filePath)) {
return false;
}
return true;
}
<|endoftext|> |
<commit_before>#include "polyfrag.h"
#ifdef POLYFRAG_USE_OPENGL
#ifdef __APPLE_CC__
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
#endif
#include <float.h>
#include <stdlib.h>
#include <algorithm>
inline float min(float a, float b) { return a < b ? a : b; }
inline float max(float a, float b) { return a < b ? a : b; }
inline float frand() { return (float)rand() / (float)RAND_MAX; }
// Append newVertex to vertices if it isn't already there, and return the index of newVertex in vertices
static int addVertex(const Vector3D &newVertex, std::vector<Vector3D> &vertices)
{
unsigned int i;
for (i = 0; i < vertices.size(); i++)
if (vertices[i] == newVertex)
return i;
vertices.push_back(newVertex);
return i;
}
////////////////////////////////////////////////////////////////////////////////
// class Plane
////////////////////////////////////////////////////////////////////////////////
int Plane::classify(const Vector3D &v) const
{
float compare = normal.dot(v) - w;
return (compare > EPSILON) ? FRONT : (compare < -EPSILON) ? BACK : COINCIDENT;
}
Vector3D Plane::lineIntersection(const Vector3D &start, const Vector3D &end) const
{
Vector3D alongLine = end - start;
float t = (w - start.dot(normal)) / alongLine.dot(normal);
return start + alongLine * t;
}
////////////////////////////////////////////////////////////////////////////////
// class Polygon
////////////////////////////////////////////////////////////////////////////////
Polygon::Polygon()
{
}
Polygon::Polygon(int a, int b, int c)
{
m_indices.push_back(a);
m_indices.push_back(b);
m_indices.push_back(c);
}
Polygon::Polygon(int a, int b, int c, int d)
{
m_indices.push_back(a);
m_indices.push_back(b);
m_indices.push_back(c);
m_indices.push_back(d);
}
Polygon::~Polygon()
{
}
#ifdef POLYFRAG_USE_OPENGL
void Polygon::draw(const std::vector<Vector3D> &vertices) const
{
Vector3D a = vertices[m_indices[0]];
Vector3D b = vertices[m_indices[1]];
Vector3D c = vertices[m_indices[2]];
Vector3D normal = (b - a).cross(c - a).unit();
glNormal3f(normal.x, normal.y, normal.z);
glBegin(GL_POLYGON);
for (unsigned int i = 0; i < m_indices.size(); i++)
{
const Vector3D &v = vertices[m_indices[i]];
glVertex3d(v.x, v.y, v.z);
}
glEnd();
}
#endif
int Polygon::classifyAndSlice(const std::vector<Vector3D> &vertices, const Plane &plane,
std::vector<Vector3D> &frontVertices, Polygon &front,
std::vector<Vector3D> &backVertices, Polygon &back,
std::vector<Vector3D> &pointsOnPlane) const
{
bool frontUsed = false, backUsed = false;
front.m_indices.clear();
back.m_indices.clear();
// Simplified algorithm for convex polygons only
for (unsigned int i = 0; i < m_indices.size(); i++)
{
// Place the current vertex in either the front or back polygon (or both)
int index = m_indices[i];
int classification = plane.classify(vertices[index]);
switch (classification)
{
case FRONT:
front.m_indices.push_back(addVertex(vertices[index], frontVertices));
frontUsed = true;
break;
case COINCIDENT:
front.m_indices.push_back(addVertex(vertices[index], frontVertices));
back.m_indices.push_back(addVertex(vertices[index], backVertices));
addVertex(vertices[index], pointsOnPlane);
break;
case BACK:
back.m_indices.push_back(addVertex(vertices[index], backVertices));
backUsed = true;
break;
}
// Add a vertex to both polygons where edges intersect the plane
unsigned int nextIndex = m_indices[(i + 1) % m_indices.size()];
int nextClassification = plane.classify(vertices[nextIndex]);
if ((classification == FRONT && nextClassification == BACK) ||
(classification == BACK && nextClassification == FRONT))
{
Vector3D edgeIntersection = plane.lineIntersection(vertices[index], vertices[nextIndex]);
front.m_indices.push_back(addVertex(edgeIntersection, frontVertices));
back.m_indices.push_back(addVertex(edgeIntersection, backVertices));
addVertex(edgeIntersection, pointsOnPlane);
}
}
if (frontUsed) return backUsed ? SPLIT : FRONT;
else return backUsed ? BACK : COINCIDENT;
}
// Helper class to order vectors by their angle in an arbitrary coordinate system
class WindingOrdering
{
public:
Vector3D origin;
Vector3D xAxis;
Vector3D yAxis;
bool operator () (const Vector3D &a, const Vector3D &b) const
{
float angleA = atan2f(yAxis.dot(a - origin), xAxis.dot(a - origin));
float angleB = atan2f(yAxis.dot(b - origin), xAxis.dot(b - origin));
return angleA < angleB;
}
};
Polygon Polygon::fromPoints(const std::vector<Vector3D> &pointsOnPlane, const Vector3D &planeNormal, std::vector<Vector3D> &vertices)
{
// Construct a coordinate system on the polygon with the origin at the polygon center,
// the x-axis from the center to the first point, and the y-axis perpendicular to the
// x-axis and the plane normal
Vector3D center;
for (unsigned int i = 0; i < pointsOnPlane.size(); i++)
center += pointsOnPlane[i];
center /= pointsOnPlane.size();
// Sort polygons by their angles with respect to this coordinate system
WindingOrdering ordering;
ordering.origin = center;
ordering.xAxis = (pointsOnPlane[0] - center).unit();
ordering.yAxis = ordering.xAxis.cross(planeNormal);
std::vector<Vector3D> copy = pointsOnPlane;
std::sort(copy.begin(), copy.end(), ordering);
// Create a polygon with those points in that order
Polygon polygon;
for (unsigned int i = 0; i < copy.size(); i++)
polygon.m_indices.push_back(addVertex(copy[i], vertices));
return polygon;
}
////////////////////////////////////////////////////////////////////////////////
// class Polyhedron
////////////////////////////////////////////////////////////////////////////////
Polyhedron::Polyhedron()
{
}
Polyhedron::~Polyhedron()
{
}
#ifdef POLYFRAG_USE_OPENGL
void Polyhedron::draw() const
{
for (unsigned int i = 0; i < m_polygons.size(); i++)
m_polygons[i].draw(m_vertices);
}
#endif
Vector3D Polyhedron::getCentroid() const
{
Vector3D center;
for (unsigned int i = 0; i < m_vertices.size(); i++)
center += m_vertices[i];
return center / m_vertices.size();
}
void Polyhedron::getAABB(Vector3D &minCoord, Vector3D &maxCoord) const
{
minCoord.x = FLT_MAX;
minCoord.y = FLT_MAX;
minCoord.z = FLT_MAX;
maxCoord.x = -FLT_MAX;
maxCoord.y = -FLT_MAX;
maxCoord.z = -FLT_MAX;
for (unsigned int i = 0; i < m_vertices.size(); i++)
{
const Vector3D &vertex = m_vertices[i];
minCoord.x = min(minCoord.x, vertex.x);
minCoord.y = min(minCoord.y, vertex.y);
minCoord.z = min(minCoord.z, vertex.z);
maxCoord.x = max(maxCoord.x, vertex.x);
maxCoord.y = max(maxCoord.y, vertex.y);
maxCoord.z = max(maxCoord.z, vertex.z);
}
}
bool Polyhedron::slice(const Plane &plane, std::vector<Polyhedron *> &result) const
{
std::vector<Vector3D> pointsOnPlane;
Polyhedron *frontPolyhedron = new Polyhedron();
Polyhedron *backPolyhedron = new Polyhedron();
bool frontUsed = false, backUsed = false;
for (unsigned int i = 0; i < m_polygons.size(); i++)
{
Polygon front, back;
switch (m_polygons[i].classifyAndSlice(m_vertices, plane, frontPolyhedron->m_vertices, front, backPolyhedron->m_vertices, back, pointsOnPlane))
{
case FRONT:
frontPolyhedron->m_polygons.push_back(front);
frontUsed = true;
break;
case COINCIDENT:
case SPLIT:
frontPolyhedron->m_polygons.push_back(front);
backPolyhedron->m_polygons.push_back(back);
break;
case BACK:
backPolyhedron->m_polygons.push_back(back);
backUsed = true;
break;
}
}
result.clear();
if (frontUsed == backUsed)
{
// Create polygons to fill in the holes inside the new polyhedra
frontPolyhedron->m_polygons.push_back(Polygon::fromPoints(pointsOnPlane, plane.normal, frontPolyhedron->m_vertices));
backPolyhedron->m_polygons.push_back(Polygon::fromPoints(pointsOnPlane, -plane.normal, backPolyhedron->m_vertices));
result.push_back(frontPolyhedron);
result.push_back(backPolyhedron);
return true;
}
else
{
delete frontPolyhedron;
delete backPolyhedron;
return false;
}
}
Polyhedron *Polyhedron::box(const Vector3D &min, const Vector3D &max)
{
Polyhedron *cube = new Polyhedron();
cube->m_vertices.push_back(Vector3D(min.x, min.y, min.z));
cube->m_vertices.push_back(Vector3D(min.x, min.y, max.z));
cube->m_vertices.push_back(Vector3D(min.x, max.y, min.z));
cube->m_vertices.push_back(Vector3D(min.x, max.y, max.z));
cube->m_vertices.push_back(Vector3D(max.x, min.y, min.z));
cube->m_vertices.push_back(Vector3D(max.x, min.y, max.z));
cube->m_vertices.push_back(Vector3D(max.x, max.y, min.z));
cube->m_vertices.push_back(Vector3D(max.x, max.y, max.z));
cube->m_polygons.push_back(Polygon(0, 1, 3, 2));
cube->m_polygons.push_back(Polygon(4, 6, 7, 5));
cube->m_polygons.push_back(Polygon(0, 4, 5, 1));
cube->m_polygons.push_back(Polygon(2, 3, 7, 6));
cube->m_polygons.push_back(Polygon(0, 2, 6, 4));
cube->m_polygons.push_back(Polygon(1, 5, 7, 3));
return cube;
}
void recursiveGeodesicSphere(Polyhedron *polyhedron, const Vector3D &a, const Vector3D &b, const Vector3D &c, const Vector3D ¢er, float radius, int depth)
{
if (depth)
{
// Generate the midpoints
Vector3D ab = (a + b) / 2;
Vector3D bc = (b + c) / 2;
Vector3D ca = (c + a) / 2;
// Place the midpoints on the surface of the sphere
ab = center + (ab - center).unit() * radius;
bc = center + (bc - center).unit() * radius;
ca = center + (ca - center).unit() * radius;
// Recursively generate triangles
recursiveGeodesicSphere(polyhedron, a, ab, ca, center, radius, depth - 1);
recursiveGeodesicSphere(polyhedron, ab, b, bc, center, radius, depth - 1);
recursiveGeodesicSphere(polyhedron, ca, bc, c, center, radius, depth - 1);
recursiveGeodesicSphere(polyhedron, ab, bc, ca, center, radius, depth - 1);
}
else
{
// Generate one triangle in the base case
Polygon polygon;
polygon.m_indices.push_back(addVertex(a, polyhedron->m_vertices));
polygon.m_indices.push_back(addVertex(b, polyhedron->m_vertices));
polygon.m_indices.push_back(addVertex(c, polyhedron->m_vertices));
polyhedron->m_polygons.push_back(polygon);
}
}
Polyhedron *Polyhedron::sphere(const Vector3D ¢er, float radius, int depth)
{
const Vector3D &xneg = Vector3D(-1, 0, 0);
const Vector3D &xpos = Vector3D(+1, 0, 0);
const Vector3D &yneg = Vector3D(0, -1, 0);
const Vector3D &ypos = Vector3D(0, +1, 0);
const Vector3D &zneg = Vector3D(0, 0, -1);
const Vector3D &zpos = Vector3D(0, 0, +1);
Polyhedron *polyhedron = new Polyhedron();
recursiveGeodesicSphere(polyhedron, xneg, yneg, zpos, center, radius, depth);
recursiveGeodesicSphere(polyhedron, xneg, zpos, ypos, center, radius, depth);
recursiveGeodesicSphere(polyhedron, xpos, zpos, yneg, center, radius, depth);
recursiveGeodesicSphere(polyhedron, xpos, ypos, zpos, center, radius, depth);
recursiveGeodesicSphere(polyhedron, xneg, zneg, yneg, center, radius, depth);
recursiveGeodesicSphere(polyhedron, xneg, ypos, zneg, center, radius, depth);
recursiveGeodesicSphere(polyhedron, xpos, yneg, zneg, center, radius, depth);
recursiveGeodesicSphere(polyhedron, xpos, zneg, ypos, center, radius, depth);
return polyhedron;
}
void Polyhedron::recursiveSlice(Polyhedron *polyhedron, std::vector<Polyhedron *> &polyhedra, int depth)
{
for (int i = 0; i < 10; i++)
{
// Generate a random plane about the centroid of polyhedron
Vector3D normal = Vector3D(frand() * 2 - 1, frand() * 2 - 1, frand() * 2 - 1).unit();
Plane plane(normal, polyhedron->getCentroid().dot(normal));
// Attempt to split polyhedron by the random plane
std::vector<Polyhedron *> result;
if (polyhedron->slice(plane, result))
{
if (depth)
{
recursiveSlice(result[0], polyhedra, depth - 1);
recursiveSlice(result[1], polyhedra, depth - 1);
}
else
{
polyhedra.push_back(result[0]);
polyhedra.push_back(result[1]);
}
delete polyhedron;
return;
}
}
// Couldn't slice polyhedron, just append it to the output
polyhedra.push_back(polyhedron);
}
<commit_msg>geodesic sphere code wasn't right at all<commit_after>#include "polyfrag.h"
#ifdef POLYFRAG_USE_OPENGL
#ifdef __APPLE_CC__
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
#endif
#include <float.h>
#include <stdlib.h>
#include <algorithm>
inline float min(float a, float b) { return a < b ? a : b; }
inline float max(float a, float b) { return a < b ? a : b; }
inline float frand() { return (float)rand() / (float)RAND_MAX; }
// Append newVertex to vertices if it isn't already there, and return the index of newVertex in vertices
static int addVertex(const Vector3D &newVertex, std::vector<Vector3D> &vertices)
{
unsigned int i;
for (i = 0; i < vertices.size(); i++)
if (vertices[i] == newVertex)
return i;
vertices.push_back(newVertex);
return i;
}
////////////////////////////////////////////////////////////////////////////////
// class Plane
////////////////////////////////////////////////////////////////////////////////
int Plane::classify(const Vector3D &v) const
{
float compare = normal.dot(v) - w;
return (compare > EPSILON) ? FRONT : (compare < -EPSILON) ? BACK : COINCIDENT;
}
Vector3D Plane::lineIntersection(const Vector3D &start, const Vector3D &end) const
{
Vector3D alongLine = end - start;
float t = (w - start.dot(normal)) / alongLine.dot(normal);
return start + alongLine * t;
}
////////////////////////////////////////////////////////////////////////////////
// class Polygon
////////////////////////////////////////////////////////////////////////////////
Polygon::Polygon()
{
}
Polygon::Polygon(int a, int b, int c)
{
m_indices.push_back(a);
m_indices.push_back(b);
m_indices.push_back(c);
}
Polygon::Polygon(int a, int b, int c, int d)
{
m_indices.push_back(a);
m_indices.push_back(b);
m_indices.push_back(c);
m_indices.push_back(d);
}
Polygon::~Polygon()
{
}
#ifdef POLYFRAG_USE_OPENGL
void Polygon::draw(const std::vector<Vector3D> &vertices) const
{
Vector3D a = vertices[m_indices[0]];
Vector3D b = vertices[m_indices[1]];
Vector3D c = vertices[m_indices[2]];
Vector3D normal = (b - a).cross(c - a).unit();
glNormal3f(normal.x, normal.y, normal.z);
glBegin(GL_POLYGON);
for (unsigned int i = 0; i < m_indices.size(); i++)
{
const Vector3D &v = vertices[m_indices[i]];
glVertex3d(v.x, v.y, v.z);
}
glEnd();
}
#endif
int Polygon::classifyAndSlice(const std::vector<Vector3D> &vertices, const Plane &plane,
std::vector<Vector3D> &frontVertices, Polygon &front,
std::vector<Vector3D> &backVertices, Polygon &back,
std::vector<Vector3D> &pointsOnPlane) const
{
bool frontUsed = false, backUsed = false;
front.m_indices.clear();
back.m_indices.clear();
// Simplified algorithm for convex polygons only
for (unsigned int i = 0; i < m_indices.size(); i++)
{
// Place the current vertex in either the front or back polygon (or both)
int index = m_indices[i];
int classification = plane.classify(vertices[index]);
switch (classification)
{
case FRONT:
front.m_indices.push_back(addVertex(vertices[index], frontVertices));
frontUsed = true;
break;
case COINCIDENT:
front.m_indices.push_back(addVertex(vertices[index], frontVertices));
back.m_indices.push_back(addVertex(vertices[index], backVertices));
addVertex(vertices[index], pointsOnPlane);
break;
case BACK:
back.m_indices.push_back(addVertex(vertices[index], backVertices));
backUsed = true;
break;
}
// Add a vertex to both polygons where edges intersect the plane
unsigned int nextIndex = m_indices[(i + 1) % m_indices.size()];
int nextClassification = plane.classify(vertices[nextIndex]);
if ((classification == FRONT && nextClassification == BACK) ||
(classification == BACK && nextClassification == FRONT))
{
Vector3D edgeIntersection = plane.lineIntersection(vertices[index], vertices[nextIndex]);
front.m_indices.push_back(addVertex(edgeIntersection, frontVertices));
back.m_indices.push_back(addVertex(edgeIntersection, backVertices));
addVertex(edgeIntersection, pointsOnPlane);
}
}
if (frontUsed) return backUsed ? SPLIT : FRONT;
else return backUsed ? BACK : COINCIDENT;
}
// Helper class to order vectors by their angle in an arbitrary coordinate system
class WindingOrdering
{
public:
Vector3D origin;
Vector3D xAxis;
Vector3D yAxis;
bool operator () (const Vector3D &a, const Vector3D &b) const
{
float angleA = atan2f(yAxis.dot(a - origin), xAxis.dot(a - origin));
float angleB = atan2f(yAxis.dot(b - origin), xAxis.dot(b - origin));
return angleA < angleB;
}
};
Polygon Polygon::fromPoints(const std::vector<Vector3D> &pointsOnPlane, const Vector3D &planeNormal, std::vector<Vector3D> &vertices)
{
// Construct a coordinate system on the polygon with the origin at the polygon center,
// the x-axis from the center to the first point, and the y-axis perpendicular to the
// x-axis and the plane normal
Vector3D center;
for (unsigned int i = 0; i < pointsOnPlane.size(); i++)
center += pointsOnPlane[i];
center /= pointsOnPlane.size();
// Sort polygons by their angles with respect to this coordinate system
WindingOrdering ordering;
ordering.origin = center;
ordering.xAxis = (pointsOnPlane[0] - center).unit();
ordering.yAxis = ordering.xAxis.cross(planeNormal);
std::vector<Vector3D> copy = pointsOnPlane;
std::sort(copy.begin(), copy.end(), ordering);
// Create a polygon with those points in that order
Polygon polygon;
for (unsigned int i = 0; i < copy.size(); i++)
polygon.m_indices.push_back(addVertex(copy[i], vertices));
return polygon;
}
////////////////////////////////////////////////////////////////////////////////
// class Polyhedron
////////////////////////////////////////////////////////////////////////////////
Polyhedron::Polyhedron()
{
}
Polyhedron::~Polyhedron()
{
}
#ifdef POLYFRAG_USE_OPENGL
void Polyhedron::draw() const
{
for (unsigned int i = 0; i < m_polygons.size(); i++)
m_polygons[i].draw(m_vertices);
}
#endif
Vector3D Polyhedron::getCentroid() const
{
Vector3D center;
for (unsigned int i = 0; i < m_vertices.size(); i++)
center += m_vertices[i];
return center / m_vertices.size();
}
void Polyhedron::getAABB(Vector3D &minCoord, Vector3D &maxCoord) const
{
minCoord.x = FLT_MAX;
minCoord.y = FLT_MAX;
minCoord.z = FLT_MAX;
maxCoord.x = -FLT_MAX;
maxCoord.y = -FLT_MAX;
maxCoord.z = -FLT_MAX;
for (unsigned int i = 0; i < m_vertices.size(); i++)
{
const Vector3D &vertex = m_vertices[i];
minCoord.x = min(minCoord.x, vertex.x);
minCoord.y = min(minCoord.y, vertex.y);
minCoord.z = min(minCoord.z, vertex.z);
maxCoord.x = max(maxCoord.x, vertex.x);
maxCoord.y = max(maxCoord.y, vertex.y);
maxCoord.z = max(maxCoord.z, vertex.z);
}
}
bool Polyhedron::slice(const Plane &plane, std::vector<Polyhedron *> &result) const
{
std::vector<Vector3D> pointsOnPlane;
Polyhedron *frontPolyhedron = new Polyhedron();
Polyhedron *backPolyhedron = new Polyhedron();
bool frontUsed = false, backUsed = false;
for (unsigned int i = 0; i < m_polygons.size(); i++)
{
Polygon front, back;
switch (m_polygons[i].classifyAndSlice(m_vertices, plane, frontPolyhedron->m_vertices, front, backPolyhedron->m_vertices, back, pointsOnPlane))
{
case FRONT:
frontPolyhedron->m_polygons.push_back(front);
frontUsed = true;
break;
case COINCIDENT:
case SPLIT:
frontPolyhedron->m_polygons.push_back(front);
backPolyhedron->m_polygons.push_back(back);
break;
case BACK:
backPolyhedron->m_polygons.push_back(back);
backUsed = true;
break;
}
}
result.clear();
if (frontUsed == backUsed)
{
// Create polygons to fill in the holes inside the new polyhedra
frontPolyhedron->m_polygons.push_back(Polygon::fromPoints(pointsOnPlane, plane.normal, frontPolyhedron->m_vertices));
backPolyhedron->m_polygons.push_back(Polygon::fromPoints(pointsOnPlane, -plane.normal, backPolyhedron->m_vertices));
result.push_back(frontPolyhedron);
result.push_back(backPolyhedron);
return true;
}
else
{
delete frontPolyhedron;
delete backPolyhedron;
return false;
}
}
Polyhedron *Polyhedron::box(const Vector3D &min, const Vector3D &max)
{
Polyhedron *cube = new Polyhedron();
cube->m_vertices.push_back(Vector3D(min.x, min.y, min.z));
cube->m_vertices.push_back(Vector3D(min.x, min.y, max.z));
cube->m_vertices.push_back(Vector3D(min.x, max.y, min.z));
cube->m_vertices.push_back(Vector3D(min.x, max.y, max.z));
cube->m_vertices.push_back(Vector3D(max.x, min.y, min.z));
cube->m_vertices.push_back(Vector3D(max.x, min.y, max.z));
cube->m_vertices.push_back(Vector3D(max.x, max.y, min.z));
cube->m_vertices.push_back(Vector3D(max.x, max.y, max.z));
cube->m_polygons.push_back(Polygon(0, 1, 3, 2));
cube->m_polygons.push_back(Polygon(4, 6, 7, 5));
cube->m_polygons.push_back(Polygon(0, 4, 5, 1));
cube->m_polygons.push_back(Polygon(2, 3, 7, 6));
cube->m_polygons.push_back(Polygon(0, 2, 6, 4));
cube->m_polygons.push_back(Polygon(1, 5, 7, 3));
return cube;
}
void recursiveGeodesicSphere(Polyhedron *polyhedron, const Vector3D &a, const Vector3D &b, const Vector3D &c, const Vector3D ¢er, float radius, int depth)
{
if (depth)
{
// Generate the midpoints
Vector3D ab = (a + b).unit();
Vector3D bc = (b + c).unit();
Vector3D ca = (c + a).unit();
// Recursively generate triangles
recursiveGeodesicSphere(polyhedron, a, ab, ca, center, radius, depth - 1);
recursiveGeodesicSphere(polyhedron, ab, b, bc, center, radius, depth - 1);
recursiveGeodesicSphere(polyhedron, ca, bc, c, center, radius, depth - 1);
recursiveGeodesicSphere(polyhedron, ab, bc, ca, center, radius, depth - 1);
}
else
{
// Generate one triangle in the base case
Polygon polygon;
polygon.m_indices.push_back(addVertex(center + a * radius, polyhedron->m_vertices));
polygon.m_indices.push_back(addVertex(center + b * radius, polyhedron->m_vertices));
polygon.m_indices.push_back(addVertex(center + c * radius, polyhedron->m_vertices));
polyhedron->m_polygons.push_back(polygon);
}
}
Polyhedron *Polyhedron::sphere(const Vector3D ¢er, float radius, int depth)
{
const Vector3D &xneg = Vector3D(-1, 0, 0);
const Vector3D &xpos = Vector3D(+1, 0, 0);
const Vector3D &yneg = Vector3D(0, -1, 0);
const Vector3D &ypos = Vector3D(0, +1, 0);
const Vector3D &zneg = Vector3D(0, 0, -1);
const Vector3D &zpos = Vector3D(0, 0, +1);
Polyhedron *polyhedron = new Polyhedron();
recursiveGeodesicSphere(polyhedron, xneg, yneg, zpos, center, radius, depth);
recursiveGeodesicSphere(polyhedron, xneg, zpos, ypos, center, radius, depth);
recursiveGeodesicSphere(polyhedron, xpos, zpos, yneg, center, radius, depth);
recursiveGeodesicSphere(polyhedron, xpos, ypos, zpos, center, radius, depth);
recursiveGeodesicSphere(polyhedron, xneg, zneg, yneg, center, radius, depth);
recursiveGeodesicSphere(polyhedron, xneg, ypos, zneg, center, radius, depth);
recursiveGeodesicSphere(polyhedron, xpos, yneg, zneg, center, radius, depth);
recursiveGeodesicSphere(polyhedron, xpos, zneg, ypos, center, radius, depth);
return polyhedron;
}
void Polyhedron::recursiveSlice(Polyhedron *polyhedron, std::vector<Polyhedron *> &polyhedra, int depth)
{
for (int i = 0; i < 10; i++)
{
// Generate a random plane about the centroid of polyhedron
Vector3D normal = Vector3D(frand() * 2 - 1, frand() * 2 - 1, frand() * 2 - 1).unit();
Plane plane(normal, polyhedron->getCentroid().dot(normal));
// Attempt to split polyhedron by the random plane
std::vector<Polyhedron *> result;
if (polyhedron->slice(plane, result))
{
if (depth)
{
recursiveSlice(result[0], polyhedra, depth - 1);
recursiveSlice(result[1], polyhedra, depth - 1);
}
else
{
polyhedra.push_back(result[0]);
polyhedra.push_back(result[1]);
}
delete polyhedron;
return;
}
}
// Couldn't slice polyhedron, just append it to the output
polyhedra.push_back(polyhedron);
}
<|endoftext|> |
<commit_before>// Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// A IACA-like simulator (main).
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <iomanip>
#include <iostream>
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm_sim/analysis/inverse_throughput.h"
#include "llvm_sim/analysis/port_pressure.h"
#include "llvm_sim/x86/faucon_lib.h"
#include "llvm_sim/x86/haswell.h"
static llvm::cl::opt<std::string> LogFile(
"log", llvm::cl::desc("Write simulation log to file"),
llvm::cl::value_desc("log_file"), llvm::cl::init(""), llvm::cl::NotHidden);
static llvm::cl::opt<std::string> TraceFile(
"trace", llvm::cl::desc("Write simulation trace to file"),
llvm::cl::value_desc("trace_file"), llvm::cl::init(""),
llvm::cl::NotHidden);
static llvm::cl::opt<std::string> InputFile(llvm::cl::Positional,
llvm::cl::desc("<input file>"),
llvm::cl::Required);
static llvm::cl::opt<int> MaxIters(
"max_iters", llvm::cl::desc("Maximum number of iterations"),
llvm::cl::value_desc("num"), llvm::cl::init(20), llvm::cl::NotHidden);
static llvm::cl::opt<int> MaxCycles("max_cycles",
llvm::cl::desc("Maximum number of cycles"),
llvm::cl::value_desc("num"),
llvm::cl::init(100000),
llvm::cl::NotHidden);
enum class InputFileTypeE { Bin, AsmIntel, AsmATT };
static llvm::cl::opt<InputFileTypeE> InputFileType(
"input_type", llvm::cl::desc("input file type"),
llvm::cl::values(
clEnumValN(InputFileTypeE::Bin, "bin", "IACA-marked binary"),
clEnumValN(InputFileTypeE::AsmIntel, "intel_asm", "Intel assembly"),
clEnumValN(InputFileTypeE::AsmATT, "att_asm", "AT&T assembly")));
namespace exegesis {
namespace simulator {
namespace {
void PrintPortPressures(const GlobalContext& Context,
const BlockContext& BlockContext,
const SimulationLog& Log,
llvm::MCInstPrinter& AsmPrinter) {
// Compute port pressures.
const auto PortPressures = ComputePortPressure(BlockContext, Log);
// Display global port pressure.
{
std::cout << "\nPort Pressure (cycles per iteration):\n";
TextTable Table(2, PortPressures.Pressures.size() + 1, true);
Table.SetValue(0, 0, "Port");
Table.SetValue(1, 0, "Cycles");
for (int I = 0; I < PortPressures.Pressures.size(); ++I) {
Table.SetValue(
0, I + 1,
Log.BufferDescriptions[PortPressures.Pressures[I].BufferIndex]
.DisplayName);
const auto Pressure = PortPressures.Pressures[I].CyclesPerIteration;
if (Pressure == 0.0f) {
continue; // Do not print the 0 for unused ports.
}
char buf[32];
snprintf(buf, sizeof(buf), "%0.2f", Pressure);
Table.SetValue(1, I + 1, buf);
}
Table.Render(llvm::outs());
}
std::cout << "\n";
std::cout << "* - some instruction uops do not use a resource\n";
// Display port pressure per instruction.
{
constexpr const int UopsCol = 0;
TextTable Table(BlockContext.GetNumBasicBlockInstructions() + 1,
PortPressures.Pressures.size() + 1, true);
// Write header.
Table.SetValue(0, UopsCol, "#Uops");
for (int I = 0; I < PortPressures.Pressures.size(); ++I) {
Table.SetValue(
0, I + 1,
Log.BufferDescriptions[PortPressures.Pressures[I].BufferIndex]
.DisplayName);
}
// Write instruction port pressures.
for (unsigned InstrIdx = 0;
InstrIdx < BlockContext.GetNumBasicBlockInstructions(); ++InstrIdx) {
const int CurTableRow = InstrIdx + 1;
const auto Uops =
Context
.GetInstructionDecomposition(
BlockContext.GetInstruction(InstrIdx).getOpcode())
.Uops;
std::string UopString;
if (std::any_of(Uops.begin(), Uops.end(),
[](const InstrUopDecomposition::Uop& Uop) {
return Uop.ProcResIdx == 0;
})) {
UopString.push_back('*');
}
UopString.append(std::to_string(Uops.size()));
Table.SetValue(CurTableRow, UopsCol, UopString);
for (int I = 0; I < PortPressures.Pressures.size(); ++I) {
const auto Pressure =
PortPressures.Pressures[I].CyclesPerIterationByMCInst[InstrIdx];
if (Pressure == 0.0f) {
continue; // Do not print the 0 for unused ports.
}
char buf[32];
snprintf(buf, sizeof(buf), "%0.2f", Pressure);
Table.SetValue(CurTableRow, I + 1, buf);
}
std::string InstrString;
llvm::raw_string_ostream OS(InstrString);
AsmPrinter.printInst(&BlockContext.GetInstruction(InstrIdx), OS, "",
*Context.SubtargetInfo);
OS.flush();
Table.SetTrailingValue(CurTableRow, InstrString);
}
Table.Render(llvm::outs());
}
}
int Simulate() {
const auto Context = GlobalContext::Create("x86_64", "haswell");
if (!Context) {
return EXIT_FAILURE;
}
const auto Simulator = CreateHaswellSimulator(*Context);
std::cout << "analyzing '" << InputFile << "'\n";
std::vector<llvm::MCInst> Instructions;
switch (InputFileType) {
case InputFileTypeE::Bin:
Instructions = ParseIACAMarkedCodeFromFile(*Context, InputFile);
break;
case InputFileTypeE::AsmIntel:
Instructions =
ParseAsmCodeFromFile(*Context, InputFile, llvm::InlineAsm::AD_Intel);
break;
case InputFileTypeE::AsmATT:
Instructions =
ParseAsmCodeFromFile(*Context, InputFile, llvm::InlineAsm::AD_ATT);
break;
}
std::cout << "analyzing " << Instructions.size() << " instructions\n";
const BlockContext BlockContext(Instructions, true);
const auto Log = Simulator->Run(BlockContext, MaxIters, MaxCycles);
std::cout << "ran " << Log->Iterations.size() << " iterations in "
<< Log->NumCycles << " cycles\n";
// Optionally write log to file.
if (!LogFile.empty()) {
std::ofstream OFS(LogFile);
OFS << Log->DebugString();
}
constexpr const unsigned kIntelSyntax = 1;
const std::unique_ptr<llvm::MCInstPrinter> AsmPrinter(
Context->Target->createMCInstPrinter(
Context->Triple, kIntelSyntax, *Context->AsmInfo, *Context->InstrInfo,
*Context->RegisterInfo));
AsmPrinter->setPrintImmHex(true);
// Optionally write trace to file.
if (!TraceFile.empty()) {
std::error_code ErrorCode;
llvm::raw_fd_ostream OFS(
TraceFile, ErrorCode,
llvm::sys::fs::OpenFlags::F_Text | llvm::sys::fs::OpenFlags::F_RW);
if (ErrorCode) {
std::cerr << "Cannot write trace file: " << ErrorCode << "\n";
} else {
PrintTrace(*Context, BlockContext, *Log, *AsmPrinter, OFS);
}
}
if (Log->Iterations.empty()) {
return 0;
}
const auto InvThrougput = ComputeInverseThroughput(BlockContext, *Log);
std::cout << "Block Inverse Throughput (last " << InvThrougput.NumIterations
<< " iterations): [" << InvThrougput.Min << "-" << InvThrougput.Max
<< "] cycles per iteration\n";
PrintPortPressures(*Context, BlockContext, *Log, *AsmPrinter);
return 0;
}
} // namespace
} // namespace simulator
} // namespace exegesis
int main(int argc, char** argv) {
if (!llvm::cl::ParseCommandLineOptions(argc, argv, "", &llvm::errs())) {
return EXIT_FAILURE;
}
LLVMInitializeX86Target();
LLVMInitializeX86TargetInfo();
LLVMInitializeX86TargetMC();
LLVMInitializeX86Disassembler();
LLVMInitializeX86AsmParser();
return exegesis::simulator::Simulate();
}
<commit_msg>Added a command-line flag to trigger the loop body simulation behavior.<commit_after>// Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// A IACA-like simulator (main).
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <iomanip>
#include <iostream>
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm_sim/analysis/inverse_throughput.h"
#include "llvm_sim/analysis/port_pressure.h"
#include "llvm_sim/x86/faucon_lib.h"
#include "llvm_sim/x86/haswell.h"
static llvm::cl::opt<std::string> LogFile(
"log", llvm::cl::desc("Write simulation log to file"),
llvm::cl::value_desc("log_file"), llvm::cl::init(""), llvm::cl::NotHidden);
static llvm::cl::opt<std::string> TraceFile(
"trace", llvm::cl::desc("Write simulation trace to file"),
llvm::cl::value_desc("trace_file"), llvm::cl::init(""),
llvm::cl::NotHidden);
static llvm::cl::opt<std::string> InputFile(llvm::cl::Positional,
llvm::cl::desc("<input file>"),
llvm::cl::Required);
static llvm::cl::opt<int> MaxIters(
"max_iters", llvm::cl::desc("Maximum number of iterations"),
llvm::cl::value_desc("num"), llvm::cl::init(20), llvm::cl::NotHidden);
static llvm::cl::opt<int> MaxCycles("max_cycles",
llvm::cl::desc("Maximum number of cycles"),
llvm::cl::value_desc("num"),
llvm::cl::init(100000),
llvm::cl::NotHidden);
static llvm::cl::opt<bool> IsLoopBody(
"loop_body", llvm::cl::desc("Whether the code is in a loop body"),
llvm::cl::init(true), llvm::cl::NotHidden);
enum class InputFileTypeE { Bin, AsmIntel, AsmATT };
static llvm::cl::opt<InputFileTypeE> InputFileType(
"input_type", llvm::cl::desc("input file type"),
llvm::cl::values(
clEnumValN(InputFileTypeE::Bin, "bin", "IACA-marked binary"),
clEnumValN(InputFileTypeE::AsmIntel, "intel_asm", "Intel assembly"),
clEnumValN(InputFileTypeE::AsmATT, "att_asm", "AT&T assembly")));
namespace exegesis {
namespace simulator {
namespace {
void PrintPortPressures(const GlobalContext& Context,
const BlockContext& BlockContext,
const SimulationLog& Log,
llvm::MCInstPrinter& AsmPrinter) {
// Compute port pressures.
const auto PortPressures = ComputePortPressure(BlockContext, Log);
// Display global port pressure.
{
std::cout << "\nPort Pressure (cycles per iteration):\n";
TextTable Table(2, PortPressures.Pressures.size() + 1, true);
Table.SetValue(0, 0, "Port");
Table.SetValue(1, 0, "Cycles");
for (int I = 0; I < PortPressures.Pressures.size(); ++I) {
Table.SetValue(
0, I + 1,
Log.BufferDescriptions[PortPressures.Pressures[I].BufferIndex]
.DisplayName);
const auto Pressure = PortPressures.Pressures[I].CyclesPerIteration;
if (Pressure == 0.0f) {
continue; // Do not print the 0 for unused ports.
}
char buf[32];
snprintf(buf, sizeof(buf), "%0.2f", Pressure);
Table.SetValue(1, I + 1, buf);
}
Table.Render(llvm::outs());
}
std::cout << "\n";
std::cout << "* - some instruction uops do not use a resource\n";
// Display port pressure per instruction.
{
constexpr const int UopsCol = 0;
TextTable Table(BlockContext.GetNumBasicBlockInstructions() + 1,
PortPressures.Pressures.size() + 1, true);
// Write header.
Table.SetValue(0, UopsCol, "#Uops");
for (int I = 0; I < PortPressures.Pressures.size(); ++I) {
Table.SetValue(
0, I + 1,
Log.BufferDescriptions[PortPressures.Pressures[I].BufferIndex]
.DisplayName);
}
// Write instruction port pressures.
for (unsigned InstrIdx = 0;
InstrIdx < BlockContext.GetNumBasicBlockInstructions(); ++InstrIdx) {
const int CurTableRow = InstrIdx + 1;
const auto Uops =
Context
.GetInstructionDecomposition(
BlockContext.GetInstruction(InstrIdx).getOpcode())
.Uops;
std::string UopString;
if (std::any_of(Uops.begin(), Uops.end(),
[](const InstrUopDecomposition::Uop& Uop) {
return Uop.ProcResIdx == 0;
})) {
UopString.push_back('*');
}
UopString.append(std::to_string(Uops.size()));
Table.SetValue(CurTableRow, UopsCol, UopString);
for (int I = 0; I < PortPressures.Pressures.size(); ++I) {
const auto Pressure =
PortPressures.Pressures[I].CyclesPerIterationByMCInst[InstrIdx];
if (Pressure == 0.0f) {
continue; // Do not print the 0 for unused ports.
}
char buf[32];
snprintf(buf, sizeof(buf), "%0.2f", Pressure);
Table.SetValue(CurTableRow, I + 1, buf);
}
std::string InstrString;
llvm::raw_string_ostream OS(InstrString);
AsmPrinter.printInst(&BlockContext.GetInstruction(InstrIdx), OS, "",
*Context.SubtargetInfo);
OS.flush();
Table.SetTrailingValue(CurTableRow, InstrString);
}
Table.Render(llvm::outs());
}
}
int Simulate() {
const auto Context = GlobalContext::Create("x86_64", "haswell");
if (!Context) {
return EXIT_FAILURE;
}
const auto Simulator = CreateHaswellSimulator(*Context);
std::cout << "analyzing '" << InputFile << "'\n";
std::vector<llvm::MCInst> Instructions;
switch (InputFileType) {
case InputFileTypeE::Bin:
Instructions = ParseIACAMarkedCodeFromFile(*Context, InputFile);
break;
case InputFileTypeE::AsmIntel:
Instructions =
ParseAsmCodeFromFile(*Context, InputFile, llvm::InlineAsm::AD_Intel);
break;
case InputFileTypeE::AsmATT:
Instructions =
ParseAsmCodeFromFile(*Context, InputFile, llvm::InlineAsm::AD_ATT);
break;
}
std::cout << "analyzing " << Instructions.size() << " instructions\n";
const BlockContext BlockContext(Instructions, IsLoopBody);
const auto Log = Simulator->Run(BlockContext, MaxIters, MaxCycles);
std::cout << "ran " << Log->Iterations.size() << " iterations in "
<< Log->NumCycles << " cycles\n";
// Optionally write log to file.
if (!LogFile.empty()) {
std::ofstream OFS(LogFile);
OFS << Log->DebugString();
}
constexpr const unsigned kIntelSyntax = 1;
const std::unique_ptr<llvm::MCInstPrinter> AsmPrinter(
Context->Target->createMCInstPrinter(
Context->Triple, kIntelSyntax, *Context->AsmInfo, *Context->InstrInfo,
*Context->RegisterInfo));
AsmPrinter->setPrintImmHex(true);
// Optionally write trace to file.
if (!TraceFile.empty()) {
std::error_code ErrorCode;
llvm::raw_fd_ostream OFS(
TraceFile, ErrorCode,
llvm::sys::fs::OpenFlags::F_Text | llvm::sys::fs::OpenFlags::F_RW);
if (ErrorCode) {
std::cerr << "Cannot write trace file: " << ErrorCode << "\n";
} else {
PrintTrace(*Context, BlockContext, *Log, *AsmPrinter, OFS);
}
}
if (Log->Iterations.empty()) {
return 0;
}
const auto InvThrougput = ComputeInverseThroughput(BlockContext, *Log);
std::cout << "Block Inverse Throughput (last " << InvThrougput.NumIterations
<< " iterations): [" << InvThrougput.Min << "-" << InvThrougput.Max
<< "] cycles per iteration\n";
PrintPortPressures(*Context, BlockContext, *Log, *AsmPrinter);
return 0;
}
} // namespace
} // namespace simulator
} // namespace exegesis
int main(int argc, char** argv) {
if (!llvm::cl::ParseCommandLineOptions(argc, argv, "", &llvm::errs())) {
return EXIT_FAILURE;
}
LLVMInitializeX86Target();
LLVMInitializeX86TargetInfo();
LLVMInitializeX86TargetMC();
LLVMInitializeX86Disassembler();
LLVMInitializeX86AsmParser();
return exegesis::simulator::Simulate();
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "WpsContext.hxx"
#include <oox/drawingml/shapepropertiescontext.hxx>
#include <oox/drawingml/shapestylecontext.hxx>
#include <com/sun/star/beans/XPropertyState.hpp>
#include <oox/drawingml/drawingmltypes.hxx>
using namespace com::sun::star;
namespace oox
{
namespace shape
{
WpsContext::WpsContext(ContextHandler2Helper& rParent, uno::Reference<drawing::XShape> xShape)
: ContextHandler2(rParent),
mxShape(xShape)
{
mpShape.reset(new oox::drawingml::Shape("com.sun.star.drawing.CustomShape"));
mpShape->setWps(true);
}
WpsContext::~WpsContext()
{
}
oox::drawingml::ShapePtr WpsContext::getShape()
{
return mpShape;
}
oox::core::ContextHandlerRef WpsContext::onCreateContext(sal_Int32 nElementToken, const oox::AttributeList& rAttribs)
{
switch (getBaseToken(nElementToken))
{
case XML_wsp:
break;
case XML_cNvCnPr:
break;
case XML_cNvSpPr:
break;
case XML_spPr:
return new oox::drawingml::ShapePropertiesContext(*this, *mpShape);
break;
case XML_style:
return new oox::drawingml::ShapeStyleContext(*this, *mpShape);
break;
case XML_bodyPr:
if (mxShape.is())
{
OptValue<OUString> oVert = rAttribs.getString(XML_vert);
if (oVert.has() && oVert.get() == "vert270")
{
// No support for this in core, work around by char rotation, as we do so for table cells already.
uno::Reference<text::XText> xText(mxShape, uno::UNO_QUERY);
uno::Reference<text::XTextCursor> xTextCursor = xText->createTextCursor();
xTextCursor->gotoStart(false);
xTextCursor->gotoEnd(true);
uno::Reference<beans::XPropertyState> xPropertyState(xTextCursor, uno::UNO_QUERY);
beans::PropertyState aState = xPropertyState->getPropertyState("CharRotation");
if (aState == beans::PropertyState_DEFAULT_VALUE)
{
uno::Reference<beans::XPropertySet> xPropertySet(xTextCursor, uno::UNO_QUERY);
xPropertySet->setPropertyValue("CharRotation", uno::makeAny(sal_Int16(900)));
}
}
// Handle inset attributes for Writer textframes.
sal_Int32 aInsets[] = { XML_lIns, XML_tIns, XML_rIns, XML_bIns };
boost::optional<sal_Int32> oInsets[4];
for (size_t i = 0; i < SAL_N_ELEMENTS(aInsets); ++i)
{
OptValue<OUString> oValue = rAttribs.getString(aInsets[i]);
if (oValue.has())
oInsets[i] = oox::drawingml::GetCoordinate(oValue.get());
}
OUString aProps[] = { OUString("LeftBorderDistance"), OUString("TopBorderDistance"), OUString("RightBorderDistance"), OUString("BottomBorderDistance") };
uno::Reference<beans::XPropertySet> xPropertySet(mxShape, uno::UNO_QUERY);
for (size_t i = 0; i < SAL_N_ELEMENTS(aProps); ++i)
if (oInsets[i])
xPropertySet->setPropertyValue(aProps[i], uno::makeAny(*oInsets[i]));
// Handle text vertical adjustment inside a text frame
if( rAttribs.hasAttribute( XML_anchor ) )
{
drawing::TextVerticalAdjust eAdjust = drawingml::GetTextVerticalAdjust( rAttribs.getToken( XML_anchor, XML_t ) );
xPropertySet->setPropertyValue("TextVerticalAdjust", uno::makeAny(eAdjust));
}
return this;
}
break;
case XML_noAutofit:
case XML_spAutoFit:
{
// We can't use oox::drawingml::TextBodyPropertiesContext here, as this
// is a child context of bodyPr, so the shape is already sent: we need
// to alter the XShape directly.
uno::Reference<beans::XPropertySet> xPropertySet(mxShape, uno::UNO_QUERY);
if (xPropertySet.is())
xPropertySet->setPropertyValue("FrameIsAutomaticHeight", uno::makeAny(getBaseToken(nElementToken) == XML_spAutoFit));
}
break;
case XML_txbx:
mpShape->getCustomShapeProperties()->setShapeTypeOverride(true);
mpShape->setServiceName("com.sun.star.text.TextFrame");
break;
default:
SAL_WARN("oox", "WpsContext::createFastChildContext: unhandled element: " << getBaseToken(nElementToken));
break;
}
return 0;
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>oox: whitespace fix in WpsContext<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "WpsContext.hxx"
#include <oox/drawingml/shapepropertiescontext.hxx>
#include <oox/drawingml/shapestylecontext.hxx>
#include <com/sun/star/beans/XPropertyState.hpp>
#include <oox/drawingml/drawingmltypes.hxx>
using namespace com::sun::star;
namespace oox
{
namespace shape
{
WpsContext::WpsContext(ContextHandler2Helper& rParent, uno::Reference<drawing::XShape> xShape)
: ContextHandler2(rParent),
mxShape(xShape)
{
mpShape.reset(new oox::drawingml::Shape("com.sun.star.drawing.CustomShape"));
mpShape->setWps(true);
}
WpsContext::~WpsContext()
{
}
oox::drawingml::ShapePtr WpsContext::getShape()
{
return mpShape;
}
oox::core::ContextHandlerRef WpsContext::onCreateContext(sal_Int32 nElementToken, const oox::AttributeList& rAttribs)
{
switch (getBaseToken(nElementToken))
{
case XML_wsp:
break;
case XML_cNvCnPr:
break;
case XML_cNvSpPr:
break;
case XML_spPr:
return new oox::drawingml::ShapePropertiesContext(*this, *mpShape);
break;
case XML_style:
return new oox::drawingml::ShapeStyleContext(*this, *mpShape);
break;
case XML_bodyPr:
if (mxShape.is())
{
OptValue<OUString> oVert = rAttribs.getString(XML_vert);
if (oVert.has() && oVert.get() == "vert270")
{
// No support for this in core, work around by char rotation, as we do so for table cells already.
uno::Reference<text::XText> xText(mxShape, uno::UNO_QUERY);
uno::Reference<text::XTextCursor> xTextCursor = xText->createTextCursor();
xTextCursor->gotoStart(false);
xTextCursor->gotoEnd(true);
uno::Reference<beans::XPropertyState> xPropertyState(xTextCursor, uno::UNO_QUERY);
beans::PropertyState aState = xPropertyState->getPropertyState("CharRotation");
if (aState == beans::PropertyState_DEFAULT_VALUE)
{
uno::Reference<beans::XPropertySet> xPropertySet(xTextCursor, uno::UNO_QUERY);
xPropertySet->setPropertyValue("CharRotation", uno::makeAny(sal_Int16(900)));
}
}
// Handle inset attributes for Writer textframes.
sal_Int32 aInsets[] = { XML_lIns, XML_tIns, XML_rIns, XML_bIns };
boost::optional<sal_Int32> oInsets[4];
for (size_t i = 0; i < SAL_N_ELEMENTS(aInsets); ++i)
{
OptValue<OUString> oValue = rAttribs.getString(aInsets[i]);
if (oValue.has())
oInsets[i] = oox::drawingml::GetCoordinate(oValue.get());
}
OUString aProps[] = { OUString("LeftBorderDistance"), OUString("TopBorderDistance"), OUString("RightBorderDistance"), OUString("BottomBorderDistance") };
uno::Reference<beans::XPropertySet> xPropertySet(mxShape, uno::UNO_QUERY);
for (size_t i = 0; i < SAL_N_ELEMENTS(aProps); ++i)
if (oInsets[i])
xPropertySet->setPropertyValue(aProps[i], uno::makeAny(*oInsets[i]));
// Handle text vertical adjustment inside a text frame
if (rAttribs.hasAttribute(XML_anchor))
{
drawing::TextVerticalAdjust eAdjust = drawingml::GetTextVerticalAdjust(rAttribs.getToken(XML_anchor, XML_t));
xPropertySet->setPropertyValue("TextVerticalAdjust", uno::makeAny(eAdjust));
}
return this;
}
break;
case XML_noAutofit:
case XML_spAutoFit:
{
// We can't use oox::drawingml::TextBodyPropertiesContext here, as this
// is a child context of bodyPr, so the shape is already sent: we need
// to alter the XShape directly.
uno::Reference<beans::XPropertySet> xPropertySet(mxShape, uno::UNO_QUERY);
if (xPropertySet.is())
xPropertySet->setPropertyValue("FrameIsAutomaticHeight", uno::makeAny(getBaseToken(nElementToken) == XML_spAutoFit));
}
break;
case XML_txbx:
mpShape->getCustomShapeProperties()->setShapeTypeOverride(true);
mpShape->setServiceName("com.sun.star.text.TextFrame");
break;
default:
SAL_WARN("oox", "WpsContext::createFastChildContext: unhandled element: " << getBaseToken(nElementToken));
break;
}
return 0;
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "open_spiel/abseil-cpp/absl/flags/flag.h"
#include "open_spiel/abseil-cpp/absl/flags/usage.h"
#include "open_spiel/abseil-cpp/absl/flags/parse.h"
#include "open_spiel/higc/referee.h"
ABSL_FLAG(std::string, bots_dir, "higc/bots",
"Directory containing the competition bots.");
namespace open_spiel {
namespace higc {
namespace {
void PlaySingleMatchIIGS() {
std::string bot_first_action = absl::StrCat(absl::GetFlag(FLAGS_bots_dir),
"/test_bot_first_action.sh");
open_spiel::higc::Referee
ref("goofspiel(imp_info=True,points_order=descending)",
{bot_first_action, bot_first_action}, /*seed=*/42,
// Increase times for Python scripts.
TournamentSettings{
.timeout_ready = 2000,
.timeout_start = 500,
});
std::unique_ptr<TournamentResults> results = ref.PlayTournament(1);
SPIEL_CHECK_EQ(results->num_matches(), 1);
SPIEL_CHECK_TRUE(results->matches[0].terminal->IsTerminal());
SPIEL_CHECK_EQ(results->matches[0].terminal->HistoryString(),
"0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, "
"6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11");
}
void TestInvalidBots() {
std::string bot_first_action = absl::StrCat(absl::GetFlag(FLAGS_bots_dir),
"/test_bot_first_action.sh");
std::vector<std::string> failing_cases = {
"/non_existing_bot",
"/test_bot_with_non_exec_flag"
};
for (const std::string& failing_case : failing_cases) {
std::cout << "Invalid bot: " << failing_case << std::endl;
std::string invalid_bot = absl::StrCat(absl::GetFlag(FLAGS_bots_dir),
failing_case);
bool thrown = false;
try {
open_spiel::higc::Referee ref("tic_tac_toe",
{invalid_bot, bot_first_action});
} catch (std::runtime_error& e) {
std::cout << e.what() << std::endl;
thrown = true;
}
SPIEL_CHECK_TRUE(thrown);
}
}
void PlayWithFailingBots() {
std::vector<std::string> failing_cases = {
"/test_bot_break_pipe.sh",
"/test_bot_sleep.sh",
"/test_bot_ready.sh",
"/test_bot_start.sh",
"/test_bot_illegal_action.sh",
"/test_bot_buffer_overflow.sh",
"/test_bot_fail_after_few_actions.sh",
};
for (int i = 0; i < failing_cases.size(); ++i) {
const std::string& failing_case = failing_cases[i];
std::string failing_bot = absl::StrCat(absl::GetFlag(FLAGS_bots_dir),
failing_case);
std::cout << "\n\nFailing bot: " << failing_bot << std::endl;
// Use a single-player game.
open_spiel::higc::Referee ref("cliff_walking", {failing_bot}, /*seed=*/42,
/*settings=*/TournamentSettings{
// Disqualify after the 2nd failing match.
.disqualification_rate = 0.5
});
std::unique_ptr<TournamentResults> results = ref.PlayTournament(2);
SPIEL_CHECK_EQ(results->disqualified[0], true);
if (i < 2) {
// No matches are played, if the bot can't even start properly.
SPIEL_CHECK_EQ(results->num_matches(), 0);
} else {
SPIEL_CHECK_EQ(results->num_matches(), 2);
}
}
}
void PonderActTimeout() {
open_spiel::higc::Referee ref(
"leduc_poker",
{absl::StrCat(absl::GetFlag(FLAGS_bots_dir), "/random_bot_py.sh"),
absl::StrCat(absl::GetFlag(FLAGS_bots_dir), "/test_bot_start.sh")},
/*seed=*/42,
// Increase times for Python scripts.
TournamentSettings{
.timeout_ready = 2000,
.timeout_start = 500,
});
std::unique_ptr<TournamentResults> results = ref.PlayTournament(1);
SPIEL_CHECK_EQ(results->num_matches(), 1);
}
void PlayManyRandomMatches(int num_matches = 5) {
open_spiel::higc::Referee ref(
"leduc_poker",
{absl::StrCat(absl::GetFlag(FLAGS_bots_dir), "/random_bot_py.sh"),
absl::StrCat(absl::GetFlag(FLAGS_bots_dir), "/random_bot_cpp.sh")},
/*seed=*/42,
// Increase times for Python scripts.
TournamentSettings{
.timeout_ready = 2000,
.timeout_start = 500,
});
std::unique_ptr<TournamentResults> results = ref.PlayTournament(num_matches);
SPIEL_CHECK_EQ(results->num_matches(), num_matches);
results->PrintCsv(std::cout, /*print_header=*/true);
}
void PlayWithManyPlayers() {
constexpr const int num_bots = 8;
std::vector<std::string> bots;
for (int i = 0; i < num_bots; ++i) {
bots.push_back(absl::StrCat(absl::GetFlag(FLAGS_bots_dir),
"/random_bot_cpp.sh"));
}
open_spiel::higc::Referee ref(
absl::StrCat("goofspiel(players=",num_bots,
",imp_info=True,points_order=descending)"),
bots,
/*seed=*/42,
// Increase times for Python scripts.
TournamentSettings{
.timeout_ready = 2000,
.timeout_start = 500,
});
std::unique_ptr<TournamentResults> results = ref.PlayTournament(1);
SPIEL_CHECK_EQ(results->num_matches(), 1);
}
} // namespace
} // namespace higc
} // namespace open_spiel
// Reroute the SIGPIPE signall here, so the test pass ok.
void signal_callback_handler(int signum) {
std::cout << "Caught signal SIGPIPE " << signum << std::endl;
}
int main(int argc, char** argv) {
absl::ParseCommandLine(argc, argv);
signal(SIGPIPE, signal_callback_handler);
open_spiel::higc::TestInvalidBots();
open_spiel::higc::PlayWithFailingBots();
open_spiel::higc::PonderActTimeout();
open_spiel::higc::PlayWithManyPlayers();
open_spiel::higc::PlaySingleMatchIIGS();
open_spiel::higc::PlayManyRandomMatches();
}
<commit_msg>Disable the buffer overflow test again -- somehow it can't be found?<commit_after>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "open_spiel/abseil-cpp/absl/flags/flag.h"
#include "open_spiel/abseil-cpp/absl/flags/usage.h"
#include "open_spiel/abseil-cpp/absl/flags/parse.h"
#include "open_spiel/higc/referee.h"
ABSL_FLAG(std::string, bots_dir, "higc/bots",
"Directory containing the competition bots.");
namespace open_spiel {
namespace higc {
namespace {
void PlaySingleMatchIIGS() {
std::string bot_first_action = absl::StrCat(absl::GetFlag(FLAGS_bots_dir),
"/test_bot_first_action.sh");
open_spiel::higc::Referee
ref("goofspiel(imp_info=True,points_order=descending)",
{bot_first_action, bot_first_action}, /*seed=*/42,
// Increase times for Python scripts.
TournamentSettings{
.timeout_ready = 2000,
.timeout_start = 500,
});
std::unique_ptr<TournamentResults> results = ref.PlayTournament(1);
SPIEL_CHECK_EQ(results->num_matches(), 1);
SPIEL_CHECK_TRUE(results->matches[0].terminal->IsTerminal());
SPIEL_CHECK_EQ(results->matches[0].terminal->HistoryString(),
"0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, "
"6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11");
}
void TestInvalidBots() {
std::string bot_first_action = absl::StrCat(absl::GetFlag(FLAGS_bots_dir),
"/test_bot_first_action.sh");
std::vector<std::string> failing_cases = {
"/non_existing_bot",
"/test_bot_with_non_exec_flag"
};
for (const std::string& failing_case : failing_cases) {
std::cout << "Invalid bot: " << failing_case << std::endl;
std::string invalid_bot = absl::StrCat(absl::GetFlag(FLAGS_bots_dir),
failing_case);
bool thrown = false;
try {
open_spiel::higc::Referee ref("tic_tac_toe",
{invalid_bot, bot_first_action});
} catch (std::runtime_error& e) {
std::cout << e.what() << std::endl;
thrown = true;
}
SPIEL_CHECK_TRUE(thrown);
}
}
void PlayWithFailingBots() {
std::vector<std::string> failing_cases = {
"/test_bot_break_pipe.sh",
"/test_bot_sleep.sh",
"/test_bot_ready.sh",
"/test_bot_start.sh",
"/test_bot_illegal_action.sh",
// "/test_bot_buffer_overflow.sh",
"/test_bot_fail_after_few_actions.sh",
};
for (int i = 0; i < failing_cases.size(); ++i) {
const std::string& failing_case = failing_cases[i];
std::string failing_bot = absl::StrCat(absl::GetFlag(FLAGS_bots_dir),
failing_case);
std::cout << "\n\nFailing bot: " << failing_bot << std::endl;
// Use a single-player game.
open_spiel::higc::Referee ref("cliff_walking", {failing_bot}, /*seed=*/42,
/*settings=*/TournamentSettings{
// Disqualify after the 2nd failing match.
.disqualification_rate = 0.5
});
std::unique_ptr<TournamentResults> results = ref.PlayTournament(2);
SPIEL_CHECK_EQ(results->disqualified[0], true);
if (i < 2) {
// No matches are played, if the bot can't even start properly.
SPIEL_CHECK_EQ(results->num_matches(), 0);
} else {
SPIEL_CHECK_EQ(results->num_matches(), 2);
}
}
}
void PonderActTimeout() {
open_spiel::higc::Referee ref(
"leduc_poker",
{absl::StrCat(absl::GetFlag(FLAGS_bots_dir), "/random_bot_py.sh"),
absl::StrCat(absl::GetFlag(FLAGS_bots_dir), "/test_bot_start.sh")},
/*seed=*/42,
// Increase times for Python scripts.
TournamentSettings{
.timeout_ready = 2000,
.timeout_start = 500,
});
std::unique_ptr<TournamentResults> results = ref.PlayTournament(1);
SPIEL_CHECK_EQ(results->num_matches(), 1);
}
void PlayManyRandomMatches(int num_matches = 5) {
open_spiel::higc::Referee ref(
"leduc_poker",
{absl::StrCat(absl::GetFlag(FLAGS_bots_dir), "/random_bot_py.sh"),
absl::StrCat(absl::GetFlag(FLAGS_bots_dir), "/random_bot_cpp.sh")},
/*seed=*/42,
// Increase times for Python scripts.
TournamentSettings{
.timeout_ready = 2000,
.timeout_start = 500,
});
std::unique_ptr<TournamentResults> results = ref.PlayTournament(num_matches);
SPIEL_CHECK_EQ(results->num_matches(), num_matches);
results->PrintCsv(std::cout, /*print_header=*/true);
}
void PlayWithManyPlayers() {
constexpr const int num_bots = 8;
std::vector<std::string> bots;
for (int i = 0; i < num_bots; ++i) {
bots.push_back(absl::StrCat(absl::GetFlag(FLAGS_bots_dir),
"/random_bot_cpp.sh"));
}
open_spiel::higc::Referee ref(
absl::StrCat("goofspiel(players=",num_bots,
",imp_info=True,points_order=descending)"),
bots,
/*seed=*/42,
// Increase times for Python scripts.
TournamentSettings{
.timeout_ready = 2000,
.timeout_start = 500,
});
std::unique_ptr<TournamentResults> results = ref.PlayTournament(1);
SPIEL_CHECK_EQ(results->num_matches(), 1);
}
} // namespace
} // namespace higc
} // namespace open_spiel
// Reroute the SIGPIPE signall here, so the test pass ok.
void signal_callback_handler(int signum) {
std::cout << "Caught signal SIGPIPE " << signum << std::endl;
}
int main(int argc, char** argv) {
absl::ParseCommandLine(argc, argv);
signal(SIGPIPE, signal_callback_handler);
open_spiel::higc::TestInvalidBots();
open_spiel::higc::PlayWithFailingBots();
open_spiel::higc::PonderActTimeout();
open_spiel::higc::PlayWithManyPlayers();
open_spiel::higc::PlaySingleMatchIIGS();
open_spiel::higc::PlayManyRandomMatches();
}
<|endoftext|> |
<commit_before>/*
* SchemeSmobAtom.c
*
* Scheme small objects (SMOBS) for opencog atom properties
*
* Copyright (c) 2008,2009 Linas Vepstas <linas@linas.org>
*/
#ifdef HAVE_GUILE
#include <vector>
#include <cstddef>
#include <libguile.h>
#include <opencog/atomspace/ClassServer.h>
#include <opencog/atomspace/TruthValue.h>
#include <opencog/guile/SchemeSmob.h>
using namespace opencog;
/* ============================================================== */
/**
* Verify that SCM arg is an actual opencog Handle; returning Handle
*
* This routine is meant for validating arguments passed into
* guile-wrapped C++ code.
*
* This routine takes an SCM arg and a string subroutine name. It
* verifies that the arg is actually a handle (and not, for example,
* an int, string, etc.) If its not a handle, it throws an SCM error,
* using the subroutine name in the error message. (Such an error is
* caught by the shell, and printed as a stack trace at the shell
* prompt). If the arg is a handle, then the actual opencog handle
* is returned.
*/
Handle SchemeSmob::verify_handle (SCM satom, const char * subrname, int pos)
{
Handle h(scm_to_handle(satom));
if (Handle::UNDEFINED == h)
scm_wrong_type_arg_msg(subrname, pos, satom, "opencog atom");
return h;
}
/* ============================================================== */
/**
* Return the string name of the atom
*/
SCM SchemeSmob::ss_name (SCM satom)
{
std::string name;
Handle h = verify_handle(satom, "cog-name");
NodePtr nnn(NodeCast(h));
if (nnn) name = nnn->getName();
SCM str = scm_from_utf8_string(name.c_str());
return str;
}
SCM SchemeSmob::ss_type (SCM satom)
{
Handle h = verify_handle(satom, "cog-type");
Type t = h->getType();
const std::string &tname = classserver().getTypeName(t);
SCM str = scm_from_utf8_string(tname.c_str());
SCM sym = scm_string_to_symbol(str);
return sym;
}
SCM SchemeSmob::ss_arity (SCM satom)
{
Handle h = verify_handle(satom, "cog-arity");
Arity ari = 0;
LinkPtr lll(LinkCast(h));
if (lll) ari = lll->getArity();
/* Arity is currently an unsigned short */
SCM sari = scm_from_ushort(ari);
return sari;
}
SCM SchemeSmob::ss_tv (SCM satom)
{
Handle h = verify_handle(satom, "cog-tv");
TruthValuePtr tv(h->getTruthValue());
TruthValue *stv = tv->rawclone();
return take_tv(stv);
}
SCM SchemeSmob::ss_set_tv (SCM satom, SCM stv)
{
Handle h = verify_handle(satom, "cog-set-tv!");
TruthValue *tv = verify_tv(stv, "cog-set-tv!", 2);
h->setTruthValue(tv->clone());
scm_remember_upto_here_1(stv);
return satom;
}
SCM SchemeSmob::ss_av (SCM satom)
{
Handle h = verify_handle(satom, "cog-av");
AttentionValue *sav = h->getAttentionValue()->rawclone();
return take_av(sav);
}
SCM SchemeSmob::ss_set_av (SCM satom, SCM sav)
{
Handle h = verify_handle(satom, "cog-set-av!");
AttentionValue *av = verify_av(sav, "cog-set-av!", 2);
h->setAttentionValue(av->clone());
return satom;
}
SCM SchemeSmob::ss_inc_vlti (SCM satom)
{
Handle h = verify_handle(satom, "cog-inc-vlti!");
h->incVLTI();
return satom;
}
SCM SchemeSmob::ss_dec_vlti (SCM satom)
{
Handle h = verify_handle(satom, "cog-dec-vlti!");
h->decVLTI();
return satom;
}
/* ============================================================== */
/**
* Convert the outgoing set of an atom into a list; return the list.
*/
SCM SchemeSmob::ss_outgoing_set (SCM satom)
{
Handle h = verify_handle(satom, "cog-outgoing-set");
LinkPtr lll(LinkCast(h));
if (NULL == lll) return SCM_EOL;
const HandleSeq& oset = lll->getOutgoingSet();
SCM list = SCM_EOL;
for (int i = oset.size()-1; i >= 0; i--)
{
Handle h = oset[i];
SCM smob = handle_to_scm(h);
list = scm_cons (smob, list);
}
return list;
}
/* ============================================================== */
/**
* Convert the incoming set of an atom into a list; return the list.
*/
SCM SchemeSmob::ss_incoming_set (SCM satom)
{
Handle h = verify_handle(satom, "cog-incoming-set");
// This reverses the order of the incoming set, but so what ...
SCM head = SCM_EOL;
IncomingSet iset = h->getIncomingSet();
for (const LinkPtr& l : iset)
{
SCM smob = handle_to_scm(l->getHandle());
head = scm_cons(smob, head);
}
return head;
}
/* ============================================================== */
/**
* Apply proceedure proc to all atoms of type stype
* If the proceedure returns something other than #f,
* terminate the loop.
*/
SCM SchemeSmob::ss_map_type (SCM proc, SCM stype)
{
Type t = verify_atom_type (stype, "cog-map-type");
AtomSpace* atomspace = ss_get_env_as("cog-map-type");
// Get all of the handles of the indicated type
std::list<Handle> handle_set;
atomspace->get_handles_by_type(back_inserter(handle_set), t, false);
// Loop over all handles in the handle set.
// Call proc on each handle, in turn.
// Break out of the loop if proc returns anything other than #f
std::list<Handle>::iterator i;
for (i = handle_set.begin(); i != handle_set.end(); ++i) {
Handle h = *i;
SCM smob = handle_to_scm(h);
SCM rc = scm_call_1(proc, smob);
if (!scm_is_false(rc)) return rc;
}
return SCM_BOOL_F;
}
/* ============================================================== */
/**
* Return a list of all of the atom types in the system.
*/
SCM SchemeSmob::ss_get_types (void)
{
SCM list = SCM_EOL;
Type t = classserver().getNumberOfClasses();
while (1) {
t--;
const std::string &tname = classserver().getTypeName(t);
SCM str = scm_from_utf8_string(tname.c_str());
SCM sym = scm_string_to_symbol(str);
list = scm_cons(sym, list);
if (0 == t) break;
}
return list;
}
/**
* Return a list of the subtypes of the indicated type
*/
SCM SchemeSmob::ss_get_subtypes (SCM stype)
{
SCM list = SCM_EOL;
Type t = verify_atom_type(stype, "cog-get-subtypes");
std::vector<Type> subl;
unsigned int ns = classserver().getChildren(t, std::back_inserter(subl));
for (unsigned int i=0; i<ns; i++) {
t = subl[i];
const std::string &tname = classserver().getTypeName(t);
SCM str = scm_from_utf8_string(tname.c_str());
SCM sym = scm_string_to_symbol(str);
list = scm_cons(sym, list);
}
return list;
}
/**
* Return integer value corresponding to the string type name.
*/
SCM SchemeSmob::ss_get_type (SCM stype)
{
if (scm_is_true(scm_symbol_p(stype)))
stype = scm_symbol_to_string(stype);
static_assert(2 == sizeof(Type),
"*** Code currently assumes types are shorts! ***");
if (scm_is_false(scm_string_p(stype)))
return scm_from_ushort(NOTYPE);
const char * ct = scm_i_string_chars(stype);
Type t = classserver().getType(ct);
return scm_from_ushort(t);
}
/**
* Return true if stype is an atom type
*/
SCM SchemeSmob::ss_type_p (SCM stype)
{
if (scm_is_integer(stype)) {
Type t = scm_to_ushort(stype);
if (classserver().isValid(t))
return SCM_BOOL_T;
return SCM_BOOL_F;
}
if (scm_is_true(scm_symbol_p(stype)))
stype = scm_symbol_to_string(stype);
if (scm_is_false(scm_string_p(stype)))
return SCM_BOOL_F;
const char * ct = scm_i_string_chars(stype);
Type t = classserver().getType(ct);
if (NOTYPE == t) return SCM_BOOL_F;
return SCM_BOOL_T;
}
/**
* Return true if stype is a node type
*/
SCM SchemeSmob::ss_node_type_p (SCM stype)
{
if (scm_is_integer(stype)) {
Type t = scm_to_ushort(stype);
if (classserver().isNode(t))
return SCM_BOOL_T;
return SCM_BOOL_F;
}
if (scm_is_true(scm_symbol_p(stype)))
stype = scm_symbol_to_string(stype);
if (scm_is_false(scm_string_p(stype)))
return SCM_BOOL_F;
const char * ct = scm_i_string_chars(stype);
Type t = classserver().getType(ct);
if (NOTYPE == t) return SCM_BOOL_F;
if (false == classserver().isA(t, NODE)) return SCM_BOOL_F;
return SCM_BOOL_T;
}
/**
* Return true if stype is a link type
*/
SCM SchemeSmob::ss_link_type_p (SCM stype)
{
if (scm_is_integer(stype)) {
Type t = scm_to_ushort(stype);
if (classserver().isLink(t))
return SCM_BOOL_T;
return SCM_BOOL_F;
}
if (scm_is_true(scm_symbol_p(stype)))
stype = scm_symbol_to_string(stype);
if (scm_is_false(scm_string_p(stype)))
return SCM_BOOL_F;
const char * ct = scm_i_string_chars(stype);
Type t = classserver().getType(ct);
if (NOTYPE == t) return SCM_BOOL_F;
if (false == classserver().isA(t, LINK)) return SCM_BOOL_F;
return SCM_BOOL_T;
}
/**
* Return true if a subtype
*/
SCM SchemeSmob::ss_subtype_p (SCM stype, SCM schild)
{
if (scm_is_true(scm_symbol_p(stype)))
stype = scm_symbol_to_string(stype);
if (scm_is_false(scm_string_p(stype)))
return SCM_BOOL_F;
const char * ct = scm_i_string_chars(stype);
Type parent = classserver().getType(ct);
if (NOTYPE == parent) return SCM_BOOL_F;
// Now investigate the child ...
if (scm_is_true(scm_symbol_p(schild)))
schild = scm_symbol_to_string(schild);
if (scm_is_false(scm_string_p(schild)))
return SCM_BOOL_F;
const char * cht = scm_i_string_chars(schild);
Type child = classserver().getType(cht);
if (NOTYPE == child) return SCM_BOOL_F;
if (classserver().isA(child, parent)) return SCM_BOOL_T;
return SCM_BOOL_F;
}
#endif
/* ===================== END OF FILE ============================ */
<commit_msg>Throw error if bad atom type.<commit_after>/*
* SchemeSmobAtom.c
*
* Scheme small objects (SMOBS) for opencog atom properties
*
* Copyright (c) 2008,2009 Linas Vepstas <linas@linas.org>
*/
#ifdef HAVE_GUILE
#include <vector>
#include <cstddef>
#include <libguile.h>
#include <opencog/atomspace/ClassServer.h>
#include <opencog/atomspace/TruthValue.h>
#include <opencog/guile/SchemeSmob.h>
using namespace opencog;
/* ============================================================== */
/**
* Verify that SCM arg is an actual opencog Handle; returning Handle
*
* This routine is meant for validating arguments passed into
* guile-wrapped C++ code.
*
* This routine takes an SCM arg and a string subroutine name. It
* verifies that the arg is actually a handle (and not, for example,
* an int, string, etc.) If its not a handle, it throws an SCM error,
* using the subroutine name in the error message. (Such an error is
* caught by the shell, and printed as a stack trace at the shell
* prompt). If the arg is a handle, then the actual opencog handle
* is returned.
*/
Handle SchemeSmob::verify_handle (SCM satom, const char * subrname, int pos)
{
Handle h(scm_to_handle(satom));
if (Handle::UNDEFINED == h)
scm_wrong_type_arg_msg(subrname, pos, satom, "opencog atom");
return h;
}
/* ============================================================== */
/**
* Return the string name of the atom
*/
SCM SchemeSmob::ss_name (SCM satom)
{
std::string name;
Handle h = verify_handle(satom, "cog-name");
NodePtr nnn(NodeCast(h));
if (nnn) name = nnn->getName();
SCM str = scm_from_utf8_string(name.c_str());
return str;
}
SCM SchemeSmob::ss_type (SCM satom)
{
Handle h = verify_handle(satom, "cog-type");
Type t = h->getType();
const std::string &tname = classserver().getTypeName(t);
SCM str = scm_from_utf8_string(tname.c_str());
SCM sym = scm_string_to_symbol(str);
return sym;
}
SCM SchemeSmob::ss_arity (SCM satom)
{
Handle h = verify_handle(satom, "cog-arity");
Arity ari = 0;
LinkPtr lll(LinkCast(h));
if (lll) ari = lll->getArity();
/* Arity is currently an unsigned short */
SCM sari = scm_from_ushort(ari);
return sari;
}
SCM SchemeSmob::ss_tv (SCM satom)
{
Handle h = verify_handle(satom, "cog-tv");
TruthValuePtr tv(h->getTruthValue());
TruthValue *stv = tv->rawclone();
return take_tv(stv);
}
SCM SchemeSmob::ss_set_tv (SCM satom, SCM stv)
{
Handle h = verify_handle(satom, "cog-set-tv!");
TruthValue *tv = verify_tv(stv, "cog-set-tv!", 2);
h->setTruthValue(tv->clone());
scm_remember_upto_here_1(stv);
return satom;
}
SCM SchemeSmob::ss_av (SCM satom)
{
Handle h = verify_handle(satom, "cog-av");
AttentionValue *sav = h->getAttentionValue()->rawclone();
return take_av(sav);
}
SCM SchemeSmob::ss_set_av (SCM satom, SCM sav)
{
Handle h = verify_handle(satom, "cog-set-av!");
AttentionValue *av = verify_av(sav, "cog-set-av!", 2);
h->setAttentionValue(av->clone());
return satom;
}
SCM SchemeSmob::ss_inc_vlti (SCM satom)
{
Handle h = verify_handle(satom, "cog-inc-vlti!");
h->incVLTI();
return satom;
}
SCM SchemeSmob::ss_dec_vlti (SCM satom)
{
Handle h = verify_handle(satom, "cog-dec-vlti!");
h->decVLTI();
return satom;
}
/* ============================================================== */
/**
* Convert the outgoing set of an atom into a list; return the list.
*/
SCM SchemeSmob::ss_outgoing_set (SCM satom)
{
Handle h = verify_handle(satom, "cog-outgoing-set");
LinkPtr lll(LinkCast(h));
if (NULL == lll) return SCM_EOL;
const HandleSeq& oset = lll->getOutgoingSet();
SCM list = SCM_EOL;
for (int i = oset.size()-1; i >= 0; i--)
{
Handle h = oset[i];
SCM smob = handle_to_scm(h);
list = scm_cons (smob, list);
}
return list;
}
/* ============================================================== */
/**
* Convert the incoming set of an atom into a list; return the list.
*/
SCM SchemeSmob::ss_incoming_set (SCM satom)
{
Handle h = verify_handle(satom, "cog-incoming-set");
// This reverses the order of the incoming set, but so what ...
SCM head = SCM_EOL;
IncomingSet iset = h->getIncomingSet();
for (const LinkPtr& l : iset)
{
SCM smob = handle_to_scm(l->getHandle());
head = scm_cons(smob, head);
}
return head;
}
/* ============================================================== */
/**
* Apply proceedure proc to all atoms of type stype
* If the proceedure returns something other than #f,
* terminate the loop.
*/
SCM SchemeSmob::ss_map_type (SCM proc, SCM stype)
{
Type t = verify_atom_type (stype, "cog-map-type");
AtomSpace* atomspace = ss_get_env_as("cog-map-type");
// Get all of the handles of the indicated type
std::list<Handle> handle_set;
atomspace->get_handles_by_type(back_inserter(handle_set), t, false);
// Loop over all handles in the handle set.
// Call proc on each handle, in turn.
// Break out of the loop if proc returns anything other than #f
std::list<Handle>::iterator i;
for (i = handle_set.begin(); i != handle_set.end(); ++i) {
Handle h = *i;
SCM smob = handle_to_scm(h);
SCM rc = scm_call_1(proc, smob);
if (!scm_is_false(rc)) return rc;
}
return SCM_BOOL_F;
}
/* ============================================================== */
/**
* Return a list of all of the atom types in the system.
*/
SCM SchemeSmob::ss_get_types (void)
{
SCM list = SCM_EOL;
Type t = classserver().getNumberOfClasses();
while (1) {
t--;
const std::string &tname = classserver().getTypeName(t);
SCM str = scm_from_utf8_string(tname.c_str());
SCM sym = scm_string_to_symbol(str);
list = scm_cons(sym, list);
if (0 == t) break;
}
return list;
}
/**
* Return a list of the subtypes of the indicated type
*/
SCM SchemeSmob::ss_get_subtypes (SCM stype)
{
SCM list = SCM_EOL;
Type t = verify_atom_type(stype, "cog-get-subtypes");
std::vector<Type> subl;
unsigned int ns = classserver().getChildren(t, std::back_inserter(subl));
for (unsigned int i=0; i<ns; i++) {
t = subl[i];
const std::string &tname = classserver().getTypeName(t);
SCM str = scm_from_utf8_string(tname.c_str());
SCM sym = scm_string_to_symbol(str);
list = scm_cons(sym, list);
}
return list;
}
/**
* Return integer value corresponding to the string type name.
*/
SCM SchemeSmob::ss_get_type (SCM stype)
{
if (scm_is_true(scm_symbol_p(stype)))
stype = scm_symbol_to_string(stype);
static_assert(2 == sizeof(Type),
"*** Code currently assumes types are shorts! ***");
if (scm_is_false(scm_string_p(stype)))
scm_wrong_type_arg_msg("cog-type->int", 0, stype, "opencog atom type");
const char * ct = scm_i_string_chars(stype);
Type t = classserver().getType(ct);
if (NOTYPE == t and strcmp(ct, "Notype"))
scm_wrong_type_arg_msg("cog-type->int", 0, stype, "opencog atom type");
return scm_from_ushort(t);
}
/**
* Return true if stype is an atom type
*/
SCM SchemeSmob::ss_type_p (SCM stype)
{
if (scm_is_integer(stype)) {
Type t = scm_to_ushort(stype);
if (classserver().isValid(t))
return SCM_BOOL_T;
return SCM_BOOL_F;
}
if (scm_is_true(scm_symbol_p(stype)))
stype = scm_symbol_to_string(stype);
if (scm_is_false(scm_string_p(stype)))
return SCM_BOOL_F;
const char * ct = scm_i_string_chars(stype);
Type t = classserver().getType(ct);
if (NOTYPE == t) return SCM_BOOL_F;
return SCM_BOOL_T;
}
/**
* Return true if stype is a node type
*/
SCM SchemeSmob::ss_node_type_p (SCM stype)
{
if (scm_is_integer(stype)) {
Type t = scm_to_ushort(stype);
if (classserver().isNode(t))
return SCM_BOOL_T;
return SCM_BOOL_F;
}
if (scm_is_true(scm_symbol_p(stype)))
stype = scm_symbol_to_string(stype);
if (scm_is_false(scm_string_p(stype)))
return SCM_BOOL_F;
const char * ct = scm_i_string_chars(stype);
Type t = classserver().getType(ct);
if (NOTYPE == t) return SCM_BOOL_F;
if (false == classserver().isA(t, NODE)) return SCM_BOOL_F;
return SCM_BOOL_T;
}
/**
* Return true if stype is a link type
*/
SCM SchemeSmob::ss_link_type_p (SCM stype)
{
if (scm_is_integer(stype)) {
Type t = scm_to_ushort(stype);
if (classserver().isLink(t))
return SCM_BOOL_T;
return SCM_BOOL_F;
}
if (scm_is_true(scm_symbol_p(stype)))
stype = scm_symbol_to_string(stype);
if (scm_is_false(scm_string_p(stype)))
return SCM_BOOL_F;
const char * ct = scm_i_string_chars(stype);
Type t = classserver().getType(ct);
if (NOTYPE == t) return SCM_BOOL_F;
if (false == classserver().isA(t, LINK)) return SCM_BOOL_F;
return SCM_BOOL_T;
}
/**
* Return true if a subtype
*/
SCM SchemeSmob::ss_subtype_p (SCM stype, SCM schild)
{
if (scm_is_true(scm_symbol_p(stype)))
stype = scm_symbol_to_string(stype);
if (scm_is_false(scm_string_p(stype)))
return SCM_BOOL_F;
const char * ct = scm_i_string_chars(stype);
Type parent = classserver().getType(ct);
if (NOTYPE == parent) return SCM_BOOL_F;
// Now investigate the child ...
if (scm_is_true(scm_symbol_p(schild)))
schild = scm_symbol_to_string(schild);
if (scm_is_false(scm_string_p(schild)))
return SCM_BOOL_F;
const char * cht = scm_i_string_chars(schild);
Type child = classserver().getType(cht);
if (NOTYPE == child) return SCM_BOOL_F;
if (classserver().isA(child, parent)) return SCM_BOOL_T;
return SCM_BOOL_F;
}
#endif
/* ===================== END OF FILE ============================ */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: commonlingui.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 20:43:11 $
*
* 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 SVX_COMMON_LINGUI_HXX
#define SVX_COMMON_LINGUI_HXX
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SV_EDIT_HXX
#include <vcl/edit.hxx>
#endif
#ifndef _SVX_BOX_HXX
#include "svxbox.hxx"
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SV_GROUP_HXX
#include <vcl/group.hxx>
#endif
#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
//=============================================================================
// SvxClickInfoCtr
//=============================================================================
class SVX_DLLPUBLIC SvxClickInfoCtr: public Control
{
private:
FixedInfo aFixedInfo;
Link aActivateLink;
public:
SvxClickInfoCtr( Window* pParent, const ResId& rResId );
~SvxClickInfoCtr();
virtual void SetText( const XubString& rStr );
virtual XubString GetText() const;
void SetActivateHdl( const Link& rLink ) { aActivateLink = rLink; }
const Link& GetActivateHdl() const { return aActivateLink; }
protected:
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual long PreNotify( NotifyEvent& rNEvt );
};
//=============================================================================
// SvxCommonLinguisticControl
//=============================================================================
class SVX_DLLPUBLIC SvxCommonLinguisticControl : public Window
{
public:
enum ButtonType
{
eClose,
eIgnore,
eIgnoreAll,
eChange,
eChangeAll,
eOptions
};
protected:
FixedText aWordText;
SvxClickInfoCtr aAktWord;
FixedText aNewWord;
Edit aNewWordED;
FixedText aSuggestionFT;
PushButton aIgnoreBtn;
PushButton aIgnoreAllBtn;
PushButton aChangeBtn;
PushButton aChangeAllBtn;
PushButton aOptionsBtn;
FixedInfo aStatusText;
HelpButton aHelpBtn;
CancelButton aCancelBtn;
GroupBox aAuditBox;
protected:
virtual void Paint( const Rectangle& rRect );
private:
PushButton* implGetButton( ButtonType _eType ) const;
public:
SvxCommonLinguisticControl( ModalDialog* _pParent );
// handlers
inline void SetResetWordHdl( const Link& _rLink ) { aAktWord.SetActivateHdl( _rLink ); }
inline const Link& GetResetWordHdl() const { return aAktWord.GetActivateHdl(); }
void SetButtonHandler( ButtonType _eType, const Link& _rHandler );
void EnableButton( ButtonType _eType, sal_Bool _bEnable );
inline PushButton* GetButton( ButtonType _eType ) { return implGetButton( _eType ); }
inline const PushButton* GetButton( ButtonType _eType ) const { return implGetButton( _eType ); }
// users of this class may want to insert own controls in some places, where the ordinary
// Z-Order determined by construction time is not sufficient
// Use the following methods for this
enum ControlGroup // control groups in this window which cannot be devided (e.g. are adjacent in the Z order)
{
eLeftRightWords, // the controls for the two words (original and suggestion), including the labels
eSuggestionLabel, // the label for the suggestion
eActionButtons, // the group of "ignore(all)" / "change(all)" buttons
eDialogButtons // the group of dialog control buttons (help and close)
};
void InsertControlGroup( Window& _rFirstGroupWindow, Window& _rLastGroupWindow, ControlGroup _eInsertAfter );
/** enlarges the window
Some controls "stick" to the borders: The group of change/ignore buttons, for instance, sticks
to the right, the dictionary list as well as the close/help buttons stick to the bottom of the
window.
*/
void Enlarge( sal_Int32 _nX, sal_Int32 _nY );
// control access methods
inline void SetCurrentText( const String& _rText ) { aAktWord.SetText( _rText ); }
inline String GetCurrentText( ) const { return aAktWord.GetText(); }
inline void SetStatusText( const String& _rText ) { aStatusText.SetText( _rText ); }
inline String GetStatusText( ) const { return aStatusText.GetText(); }
inline Edit& GetWordInputControl() { return aNewWordED; }
inline const Edit& GetWordInputControl() const { return aNewWordED; }
// returns the location (upper-left corner) of the group of action buttons
inline Point GetActionButtonsLocation( ) const { return aIgnoreBtn.GetPosPixel(); }
// updates the help texts for the "change" and "change all" buttons according to the currently
// entered texts
void UpdateChangesHelp( const String& _rNewText );
inline void UpdateChangesHelp( ) { UpdateChangesHelp( GetWordInputControl().GetText() ); }
// updates the help texts for the "ignore" and "always ignore" buttons according to the currently
// entered texts
void UpdateIgnoreHelp( );
String GetNewEditWord();
void SetNewEditWord( const String& _rNew );
};
#endif // SVX_COMMON_LINGUI_HXX
<commit_msg>INTEGRATION: CWS vgbugs07 (1.5.878); FILE MERGED 2007/06/04 13:26:13 vg 1.5.878.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: commonlingui.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-06-27 16:53:40 $
*
* 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 SVX_COMMON_LINGUI_HXX
#define SVX_COMMON_LINGUI_HXX
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SV_EDIT_HXX
#include <vcl/edit.hxx>
#endif
#ifndef _SVX_BOX_HXX
#include <svx/svxbox.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SV_GROUP_HXX
#include <vcl/group.hxx>
#endif
#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
//=============================================================================
// SvxClickInfoCtr
//=============================================================================
class SVX_DLLPUBLIC SvxClickInfoCtr: public Control
{
private:
FixedInfo aFixedInfo;
Link aActivateLink;
public:
SvxClickInfoCtr( Window* pParent, const ResId& rResId );
~SvxClickInfoCtr();
virtual void SetText( const XubString& rStr );
virtual XubString GetText() const;
void SetActivateHdl( const Link& rLink ) { aActivateLink = rLink; }
const Link& GetActivateHdl() const { return aActivateLink; }
protected:
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual long PreNotify( NotifyEvent& rNEvt );
};
//=============================================================================
// SvxCommonLinguisticControl
//=============================================================================
class SVX_DLLPUBLIC SvxCommonLinguisticControl : public Window
{
public:
enum ButtonType
{
eClose,
eIgnore,
eIgnoreAll,
eChange,
eChangeAll,
eOptions
};
protected:
FixedText aWordText;
SvxClickInfoCtr aAktWord;
FixedText aNewWord;
Edit aNewWordED;
FixedText aSuggestionFT;
PushButton aIgnoreBtn;
PushButton aIgnoreAllBtn;
PushButton aChangeBtn;
PushButton aChangeAllBtn;
PushButton aOptionsBtn;
FixedInfo aStatusText;
HelpButton aHelpBtn;
CancelButton aCancelBtn;
GroupBox aAuditBox;
protected:
virtual void Paint( const Rectangle& rRect );
private:
PushButton* implGetButton( ButtonType _eType ) const;
public:
SvxCommonLinguisticControl( ModalDialog* _pParent );
// handlers
inline void SetResetWordHdl( const Link& _rLink ) { aAktWord.SetActivateHdl( _rLink ); }
inline const Link& GetResetWordHdl() const { return aAktWord.GetActivateHdl(); }
void SetButtonHandler( ButtonType _eType, const Link& _rHandler );
void EnableButton( ButtonType _eType, sal_Bool _bEnable );
inline PushButton* GetButton( ButtonType _eType ) { return implGetButton( _eType ); }
inline const PushButton* GetButton( ButtonType _eType ) const { return implGetButton( _eType ); }
// users of this class may want to insert own controls in some places, where the ordinary
// Z-Order determined by construction time is not sufficient
// Use the following methods for this
enum ControlGroup // control groups in this window which cannot be devided (e.g. are adjacent in the Z order)
{
eLeftRightWords, // the controls for the two words (original and suggestion), including the labels
eSuggestionLabel, // the label for the suggestion
eActionButtons, // the group of "ignore(all)" / "change(all)" buttons
eDialogButtons // the group of dialog control buttons (help and close)
};
void InsertControlGroup( Window& _rFirstGroupWindow, Window& _rLastGroupWindow, ControlGroup _eInsertAfter );
/** enlarges the window
Some controls "stick" to the borders: The group of change/ignore buttons, for instance, sticks
to the right, the dictionary list as well as the close/help buttons stick to the bottom of the
window.
*/
void Enlarge( sal_Int32 _nX, sal_Int32 _nY );
// control access methods
inline void SetCurrentText( const String& _rText ) { aAktWord.SetText( _rText ); }
inline String GetCurrentText( ) const { return aAktWord.GetText(); }
inline void SetStatusText( const String& _rText ) { aStatusText.SetText( _rText ); }
inline String GetStatusText( ) const { return aStatusText.GetText(); }
inline Edit& GetWordInputControl() { return aNewWordED; }
inline const Edit& GetWordInputControl() const { return aNewWordED; }
// returns the location (upper-left corner) of the group of action buttons
inline Point GetActionButtonsLocation( ) const { return aIgnoreBtn.GetPosPixel(); }
// updates the help texts for the "change" and "change all" buttons according to the currently
// entered texts
void UpdateChangesHelp( const String& _rNewText );
inline void UpdateChangesHelp( ) { UpdateChangesHelp( GetWordInputControl().GetText() ); }
// updates the help texts for the "ignore" and "always ignore" buttons according to the currently
// entered texts
void UpdateIgnoreHelp( );
String GetNewEditWord();
void SetNewEditWord( const String& _rNew );
};
#endif // SVX_COMMON_LINGUI_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: flyincnt.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: ama $ $Date: 2001-12-13 12:59:48 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "core_pch.hxx"
#endif
#pragma hdrstop
#include "cntfrm.hxx"
#include "doc.hxx"
#include "flyfrm.hxx"
#include "frmtool.hxx"
#include "frmfmt.hxx"
#include "hints.hxx"
#ifndef _FMTORNT_HXX //autogen
#include <fmtornt.hxx>
#endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#include "txtfrm.hxx" //fuer IsLocked()
#include "flyfrms.hxx"
//aus FlyCnt.cxx
void DeepCalc( const SwFrm *pFrm );
/*************************************************************************
|*
|* SwFlyInCntFrm::SwFlyInCntFrm(), ~SwFlyInCntFrm()
|*
|* Ersterstellung MA 01. Dec. 92
|* Letzte Aenderung MA 09. Apr. 99
|*
|*************************************************************************/
SwFlyInCntFrm::SwFlyInCntFrm( SwFlyFrmFmt *pFmt, SwFrm *pAnch ) :
SwFlyFrm( pFmt, pAnch )
{
bInCnt = bInvalidLayout = bInvalidCntnt = TRUE;
SwTwips nRel = pFmt->GetVertOrient().GetPos();
#ifdef VERTICAL_LAYOUT
if( pAnch && pAnch->IsVertical() )
aRelPos.X() = pAnch->IsReverse() ? nRel : -nRel;
else
#endif
aRelPos.Y() = nRel;
}
SwFlyInCntFrm::~SwFlyInCntFrm()
{
//und Tschuess.
if ( !GetFmt()->GetDoc()->IsInDtor() && GetAnchor() )
{
SwRect aTmp( AddSpacesToFrm() );
SwFlyInCntFrm::NotifyBackground( FindPageFrm(), aTmp, PREP_FLY_LEAVE );
}
}
/*************************************************************************
|*
|* SwFlyInCntFrm::SetRefPoint(),
|*
|* Ersterstellung MA 01. Dec. 92
|* Letzte Aenderung MA 06. Aug. 95
|*
|*************************************************************************/
void SwFlyInCntFrm::SetRefPoint( const Point& rPoint, const Point& rRelAttr,
const Point& rRelPos )
{
ASSERT( rPoint != aRef || rRelAttr != aRelPos, "SetRefPoint: no change" );
const SwFlyNotify aNotify( this );
aRef = rPoint;
aRelPos = rRelAttr;
#ifdef VERTICAL_LAYOUT
SWRECTFN( GetAnchor() )
(Frm().*fnRect->fnSetPos)( rPoint + rRelPos );
#else
Frm().Pos( rPoint + rRelPos );
#endif
/*
//Kein InvalidatePos hier, denn das wuerde dem Cntnt ein Prepare
//senden - dieser hat uns aber gerade gerufen.
//Da der Frm aber durchaus sein Position wechseln kann, muss hier
//der von ihm abdeckte Window-Bereich invalidiert werden damit keine
//Reste stehenbleiben.
//Fix: Nicht fuer PreView-Shells, dort ist es nicht notwendig und
//fuehrt zu fiesen Problemen (Der Absatz wird nur formatiert weil
//er gepaintet wird und der Cache uebergelaufen ist, beim Paint durch
//das Invalidate wird der Absatz formatiert weil...)
if ( Frm().HasArea() && GetShell()->ISA(SwCrsrShell) )
GetShell()->InvalidateWindows( Frm() );
*/
InvalidatePage();
bValidPos = FALSE;
bInvalid = TRUE;
Calc();
}
/*************************************************************************
|*
|* SwFlyInCntFrm::Modify()
|*
|* Ersterstellung MA 16. Dec. 92
|* Letzte Aenderung MA 02. Sep. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew )
{
BOOL bCallPrepare = FALSE;
USHORT nWhich = pOld ? pOld->Which() : pNew ? pNew->Which() : 0;
if( RES_ATTRSET_CHG == nWhich )
{
if( SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->
GetItemState( RES_SURROUND, FALSE ) ||
SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->
GetItemState( RES_FRMMACRO, FALSE ) )
{
SwAttrSetChg aOld( *(SwAttrSetChg*)pOld );
SwAttrSetChg aNew( *(SwAttrSetChg*)pNew );
aOld.ClearItem( RES_SURROUND );
aNew.ClearItem( RES_SURROUND );
aOld.ClearItem( RES_FRMMACRO );
aNew.ClearItem( RES_FRMMACRO );
if( aNew.Count() )
{
SwFlyFrm::Modify( &aOld, &aNew );
bCallPrepare = TRUE;
}
}
else if( ((SwAttrSetChg*)pNew)->GetChgSet()->Count())
{
SwFlyFrm::Modify( pOld, pNew );
bCallPrepare = TRUE;
}
}
else if( nWhich != RES_SURROUND && RES_FRMMACRO != nWhich )
{
SwFlyFrm::Modify( pOld, pNew );
bCallPrepare = TRUE;
}
if ( bCallPrepare && GetAnchor() )
GetAnchor()->Prepare( PREP_FLY_ATTR_CHG, GetFmt() );
}
/*************************************************************************
|*
|* SwFlyInCntFrm::Format()
|*
|* Beschreibung: Hier wird der Inhalt initial mit Formatiert.
|* Ersterstellung MA 16. Dec. 92
|* Letzte Aenderung MA 19. May. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::Format( const SwBorderAttrs *pAttrs )
{
if ( !Frm().Height() )
{
Lock(); //nicht hintenherum den Anker formatieren.
SwCntntFrm *pCntnt = ContainsCntnt();
while ( pCntnt )
{ pCntnt->Calc();
pCntnt = pCntnt->GetNextCntntFrm();
}
Unlock();
}
SwFlyFrm::Format( pAttrs );
}
/*************************************************************************
|*
|* SwFlyInCntFrm::MakeFlyPos()
|*
|* Beschreibung Im Unterschied zu anderen Frms wird hier nur die
|* die RelPos berechnet. Die absolute Position wird ausschliesslich
|* per SetAbsPos errechnet.
|* Ersterstellung MA 03. Dec. 92
|* Letzte Aenderung MA 12. Apr. 96
|*
|*************************************************************************/
void SwFlyInCntFrm::MakeFlyPos()
{
if ( !bValidPos )
{
if ( !GetAnchor()->IsTxtFrm() || !((SwTxtFrm*)GetAnchor())->IsLocked() )
::DeepCalc( GetAnchor() );
if( GetAnchor()->IsTxtFrm() )
((SwTxtFrm*)GetAnchor())->GetFormatted();
bValidPos = TRUE;
SwFlyFrmFmt *pFmt = (SwFlyFrmFmt*)GetFmt();
const SwFmtVertOrient &rVert = pFmt->GetVertOrient();
//Und ggf. noch die aktuellen Werte im Format updaten, dabei darf
//zu diesem Zeitpunkt natuerlich kein Modify verschickt werden.
#ifdef VERTICAL_LAYOUT
SWRECTFN( GetAnchor() )
SwTwips nOld = rVert.GetPos();
SwTwips nAct = bVert ? -aRelPos.X() : aRelPos.Y();
if( bRev )
nAct = -nAct;
if( nAct != nOld )
{
SwFmtVertOrient aVert( rVert );
aVert.SetPos( nAct );
#else
if ( rVert.GetPos() != aRelPos.Y() )
{
SwFmtVertOrient aVert( rVert );
aVert.SetPos( aRelPos.Y() );
#endif
pFmt->LockModify();
pFmt->SetAttr( aVert );
pFmt->UnlockModify();
}
}
}
/*************************************************************************
|*
|* SwFlyInCntFrm::NotifyBackground()
|*
|* Ersterstellung MA 03. Dec. 92
|* Letzte Aenderung MA 26. Aug. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::NotifyBackground( SwPageFrm *, const SwRect& rRect,
PrepareHint eHint)
{
if ( eHint == PREP_FLY_ATTR_CHG )
GetAnchor()->Prepare( PREP_FLY_ATTR_CHG );
else
GetAnchor()->Prepare( eHint, (void*)&rRect );
}
/*************************************************************************
|*
|* SwFlyInCntFrm::GetRelPos()
|*
|* Ersterstellung MA 04. Dec. 92
|* Letzte Aenderung MA 04. Dec. 92
|*
|*************************************************************************/
const Point &SwFlyInCntFrm::GetRelPos() const
{
Calc();
return GetCurRelPos();
}
/*************************************************************************
|*
|* SwFlyInCntFrm::RegistFlys()
|*
|* Ersterstellung MA 26. Nov. 93
|* Letzte Aenderung MA 26. Nov. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::RegistFlys()
{
// vgl. SwRowFrm::RegistFlys()
SwPageFrm *pPage = FindPageFrm();
ASSERT( pPage, "Flys ohne Seite anmelden?" );
::RegistFlys( pPage, this );
}
/*************************************************************************
|*
|* SwFlyInCntFrm::MakeAll()
|*
|* Ersterstellung MA 18. Feb. 94
|* Letzte Aenderung MA 13. Jun. 96
|*
|*************************************************************************/
void SwFlyInCntFrm::MakeAll()
{
if ( !GetAnchor() || IsLocked() || IsColLocked() || !FindPageFrm() )
return;
Lock(); //Der Vorhang faellt
//uebernimmt im DTor die Benachrichtigung
const SwFlyNotify aNotify( this );
SwBorderAttrAccess aAccess( SwFrm::GetCache(), this );
const SwBorderAttrs &rAttrs = *aAccess.Get();
const Size &rSz = rAttrs.GetSize();
const SwFmtFrmSize &rFrmSz = GetFmt()->GetFrmSize();
if ( IsClipped() )
bValidSize = bHeightClipped = bWidthClipped = FALSE;
while ( !bValidPos || !bValidSize || !bValidPrtArea )
{
//Nur einstellen wenn das Flag gesetzt ist!!
if ( !bValidSize )
{
bValidPrtArea = FALSE;
long nOldWidth = aFrm.Width();
aFrm.Width( CalcRel( rFrmSz ).Width() );
if ( aFrm.Width() > nOldWidth )
//Damit sich der Inhalt anpasst
aFrm.Height( CalcRel( rFrmSz ).Height() );
}
if ( !bValidPrtArea )
MakePrtArea( rAttrs );
if ( !bValidSize )
Format( &rAttrs );
if ( !bValidPos )
MakeFlyPos();
if ( bValidPos && bValidSize )
{
SwFrm *pFrm = GetAnchor();
if (
//MA 03. Apr. 96 fix(26652), Das trifft uns bestimmt nocheinmal
// !pFrm->IsMoveable() &&
Frm().Left() == (pFrm->Frm().Left()+pFrm->Prt().Left()) &&
Frm().Width() > pFrm->Prt().Width() )
{
Frm().Width( pFrm->Prt().Width() );
bValidPrtArea = FALSE;
bWidthClipped = TRUE;
}
}
}
Unlock();
}
<commit_msg>Fix #102044#: Double moving of fly content<commit_after>/*************************************************************************
*
* $RCSfile: flyincnt.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: ama $ $Date: 2002-08-12 07:56:34 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "core_pch.hxx"
#endif
#pragma hdrstop
#include "cntfrm.hxx"
#include "doc.hxx"
#include "flyfrm.hxx"
#include "frmtool.hxx"
#include "frmfmt.hxx"
#include "hints.hxx"
#ifndef _FMTORNT_HXX //autogen
#include <fmtornt.hxx>
#endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#include "txtfrm.hxx" //fuer IsLocked()
#include "flyfrms.hxx"
//aus FlyCnt.cxx
void DeepCalc( const SwFrm *pFrm );
/*************************************************************************
|*
|* SwFlyInCntFrm::SwFlyInCntFrm(), ~SwFlyInCntFrm()
|*
|* Ersterstellung MA 01. Dec. 92
|* Letzte Aenderung MA 09. Apr. 99
|*
|*************************************************************************/
SwFlyInCntFrm::SwFlyInCntFrm( SwFlyFrmFmt *pFmt, SwFrm *pAnch ) :
SwFlyFrm( pFmt, pAnch )
{
bInCnt = bInvalidLayout = bInvalidCntnt = TRUE;
SwTwips nRel = pFmt->GetVertOrient().GetPos();
#ifdef VERTICAL_LAYOUT
if( pAnch && pAnch->IsVertical() )
aRelPos.X() = pAnch->IsReverse() ? nRel : -nRel;
else
#endif
aRelPos.Y() = nRel;
}
SwFlyInCntFrm::~SwFlyInCntFrm()
{
//und Tschuess.
if ( !GetFmt()->GetDoc()->IsInDtor() && GetAnchor() )
{
SwRect aTmp( AddSpacesToFrm() );
SwFlyInCntFrm::NotifyBackground( FindPageFrm(), aTmp, PREP_FLY_LEAVE );
}
}
/*************************************************************************
|*
|* SwFlyInCntFrm::SetRefPoint(),
|*
|* Ersterstellung MA 01. Dec. 92
|* Letzte Aenderung MA 06. Aug. 95
|*
|*************************************************************************/
void SwFlyInCntFrm::SetRefPoint( const Point& rPoint, const Point& rRelAttr,
const Point& rRelPos )
{
ASSERT( rPoint != aRef || rRelAttr != aRelPos, "SetRefPoint: no change" );
SwFlyNotify *pNotify = NULL;
// No notify at a locked fly frame, if a fly frame is locked, there's
// already a SwFlyNotify object on the stack (MakeAll).
if( !IsLocked() )
pNotify = new SwFlyNotify( this );
aRef = rPoint;
aRelPos = rRelAttr;
#ifdef VERTICAL_LAYOUT
SWRECTFN( GetAnchor() )
(Frm().*fnRect->fnSetPos)( rPoint + rRelPos );
#else
Frm().Pos( rPoint + rRelPos );
#endif
/*
//Kein InvalidatePos hier, denn das wuerde dem Cntnt ein Prepare
//senden - dieser hat uns aber gerade gerufen.
//Da der Frm aber durchaus sein Position wechseln kann, muss hier
//der von ihm abdeckte Window-Bereich invalidiert werden damit keine
//Reste stehenbleiben.
//Fix: Nicht fuer PreView-Shells, dort ist es nicht notwendig und
//fuehrt zu fiesen Problemen (Der Absatz wird nur formatiert weil
//er gepaintet wird und der Cache uebergelaufen ist, beim Paint durch
//das Invalidate wird der Absatz formatiert weil...)
if ( Frm().HasArea() && GetShell()->ISA(SwCrsrShell) )
GetShell()->InvalidateWindows( Frm() );
*/
if( pNotify )
{
InvalidatePage();
bValidPos = FALSE;
bInvalid = TRUE;
Calc();
delete pNotify;
}
}
/*************************************************************************
|*
|* SwFlyInCntFrm::Modify()
|*
|* Ersterstellung MA 16. Dec. 92
|* Letzte Aenderung MA 02. Sep. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew )
{
BOOL bCallPrepare = FALSE;
USHORT nWhich = pOld ? pOld->Which() : pNew ? pNew->Which() : 0;
if( RES_ATTRSET_CHG == nWhich )
{
if( SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->
GetItemState( RES_SURROUND, FALSE ) ||
SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->
GetItemState( RES_FRMMACRO, FALSE ) )
{
SwAttrSetChg aOld( *(SwAttrSetChg*)pOld );
SwAttrSetChg aNew( *(SwAttrSetChg*)pNew );
aOld.ClearItem( RES_SURROUND );
aNew.ClearItem( RES_SURROUND );
aOld.ClearItem( RES_FRMMACRO );
aNew.ClearItem( RES_FRMMACRO );
if( aNew.Count() )
{
SwFlyFrm::Modify( &aOld, &aNew );
bCallPrepare = TRUE;
}
}
else if( ((SwAttrSetChg*)pNew)->GetChgSet()->Count())
{
SwFlyFrm::Modify( pOld, pNew );
bCallPrepare = TRUE;
}
}
else if( nWhich != RES_SURROUND && RES_FRMMACRO != nWhich )
{
SwFlyFrm::Modify( pOld, pNew );
bCallPrepare = TRUE;
}
if ( bCallPrepare && GetAnchor() )
GetAnchor()->Prepare( PREP_FLY_ATTR_CHG, GetFmt() );
}
/*************************************************************************
|*
|* SwFlyInCntFrm::Format()
|*
|* Beschreibung: Hier wird der Inhalt initial mit Formatiert.
|* Ersterstellung MA 16. Dec. 92
|* Letzte Aenderung MA 19. May. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::Format( const SwBorderAttrs *pAttrs )
{
if ( !Frm().Height() )
{
Lock(); //nicht hintenherum den Anker formatieren.
SwCntntFrm *pCntnt = ContainsCntnt();
while ( pCntnt )
{ pCntnt->Calc();
pCntnt = pCntnt->GetNextCntntFrm();
}
Unlock();
}
SwFlyFrm::Format( pAttrs );
}
/*************************************************************************
|*
|* SwFlyInCntFrm::MakeFlyPos()
|*
|* Beschreibung Im Unterschied zu anderen Frms wird hier nur die
|* die RelPos berechnet. Die absolute Position wird ausschliesslich
|* per SetAbsPos errechnet.
|* Ersterstellung MA 03. Dec. 92
|* Letzte Aenderung MA 12. Apr. 96
|*
|*************************************************************************/
void SwFlyInCntFrm::MakeFlyPos()
{
if ( !bValidPos )
{
if ( !GetAnchor()->IsTxtFrm() || !((SwTxtFrm*)GetAnchor())->IsLocked() )
::DeepCalc( GetAnchor() );
if( GetAnchor()->IsTxtFrm() )
((SwTxtFrm*)GetAnchor())->GetFormatted();
bValidPos = TRUE;
SwFlyFrmFmt *pFmt = (SwFlyFrmFmt*)GetFmt();
const SwFmtVertOrient &rVert = pFmt->GetVertOrient();
//Und ggf. noch die aktuellen Werte im Format updaten, dabei darf
//zu diesem Zeitpunkt natuerlich kein Modify verschickt werden.
#ifdef VERTICAL_LAYOUT
SWRECTFN( GetAnchor() )
SwTwips nOld = rVert.GetPos();
SwTwips nAct = bVert ? -aRelPos.X() : aRelPos.Y();
if( bRev )
nAct = -nAct;
if( nAct != nOld )
{
SwFmtVertOrient aVert( rVert );
aVert.SetPos( nAct );
#else
if ( rVert.GetPos() != aRelPos.Y() )
{
SwFmtVertOrient aVert( rVert );
aVert.SetPos( aRelPos.Y() );
#endif
pFmt->LockModify();
pFmt->SetAttr( aVert );
pFmt->UnlockModify();
}
}
}
/*************************************************************************
|*
|* SwFlyInCntFrm::NotifyBackground()
|*
|* Ersterstellung MA 03. Dec. 92
|* Letzte Aenderung MA 26. Aug. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::NotifyBackground( SwPageFrm *, const SwRect& rRect,
PrepareHint eHint)
{
if ( eHint == PREP_FLY_ATTR_CHG )
GetAnchor()->Prepare( PREP_FLY_ATTR_CHG );
else
GetAnchor()->Prepare( eHint, (void*)&rRect );
}
/*************************************************************************
|*
|* SwFlyInCntFrm::GetRelPos()
|*
|* Ersterstellung MA 04. Dec. 92
|* Letzte Aenderung MA 04. Dec. 92
|*
|*************************************************************************/
const Point &SwFlyInCntFrm::GetRelPos() const
{
Calc();
return GetCurRelPos();
}
/*************************************************************************
|*
|* SwFlyInCntFrm::RegistFlys()
|*
|* Ersterstellung MA 26. Nov. 93
|* Letzte Aenderung MA 26. Nov. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::RegistFlys()
{
// vgl. SwRowFrm::RegistFlys()
SwPageFrm *pPage = FindPageFrm();
ASSERT( pPage, "Flys ohne Seite anmelden?" );
::RegistFlys( pPage, this );
}
/*************************************************************************
|*
|* SwFlyInCntFrm::MakeAll()
|*
|* Ersterstellung MA 18. Feb. 94
|* Letzte Aenderung MA 13. Jun. 96
|*
|*************************************************************************/
void SwFlyInCntFrm::MakeAll()
{
if ( !GetAnchor() || IsLocked() || IsColLocked() || !FindPageFrm() )
return;
Lock(); //Der Vorhang faellt
//uebernimmt im DTor die Benachrichtigung
const SwFlyNotify aNotify( this );
SwBorderAttrAccess aAccess( SwFrm::GetCache(), this );
const SwBorderAttrs &rAttrs = *aAccess.Get();
const Size &rSz = rAttrs.GetSize();
const SwFmtFrmSize &rFrmSz = GetFmt()->GetFrmSize();
if ( IsClipped() )
bValidSize = bHeightClipped = bWidthClipped = FALSE;
while ( !bValidPos || !bValidSize || !bValidPrtArea )
{
//Nur einstellen wenn das Flag gesetzt ist!!
if ( !bValidSize )
{
bValidPrtArea = FALSE;
long nOldWidth = aFrm.Width();
aFrm.Width( CalcRel( rFrmSz ).Width() );
if ( aFrm.Width() > nOldWidth )
//Damit sich der Inhalt anpasst
aFrm.Height( CalcRel( rFrmSz ).Height() );
}
if ( !bValidPrtArea )
MakePrtArea( rAttrs );
if ( !bValidSize )
Format( &rAttrs );
if ( !bValidPos )
MakeFlyPos();
if ( bValidPos && bValidSize )
{
SwFrm *pFrm = GetAnchor();
if (
//MA 03. Apr. 96 fix(26652), Das trifft uns bestimmt nocheinmal
// !pFrm->IsMoveable() &&
Frm().Left() == (pFrm->Frm().Left()+pFrm->Prt().Left()) &&
Frm().Width() > pFrm->Prt().Width() )
{
Frm().Width( pFrm->Prt().Width() );
bValidPrtArea = FALSE;
bWidthClipped = TRUE;
}
}
}
Unlock();
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2017 Michael W Powell <mwpowellhtx@gmail.com>
// Copyright 2017 Garrett D'Amore <garrett@damore.org>
// Copyright 2017 Capitar IT Group BV <info@capitar.com>
//
// This software is supplied under the terms of the MIT License, a
// copy of which should be located in the distribution where this
// file was obtained (LICENSE.txt). A copy of the license may also be
// found online at https://opensource.org/licenses/MIT.
//
#include "../catch/catch_nng_exception_matcher.hpp"
#include "../catch/catch_exception_translations.hpp"
#include "../catch/catch_macros.hpp"
#include "../helpers/basic_fixture.h"
#include "../helpers/constants.h"
#include "../helpers/chrono.hpp"
#include <nngcpp.h>
namespace nng {
namespace protocol {
namespace v0 {
class pub_socket_fixture : public pub_socket {
public:
pub_socket_fixture() : pub_socket() {}
virtual ~pub_socket_fixture() {}
std::unique_ptr<binary_message_type> receive(flag_type flags = flag_none) {
return pub_socket::receive(flags);
}
int try_receive(binary_message_type* const bmp, flag_type flags = flag_none) {
return pub_socket::try_receive(bmp, flags);
}
buffer_vector_type receive(size_type& sz, flag_type flags = flag_none) {
return pub_socket::receive(sz, flags);
}
int try_receive(buffer_vector_type* const bufp, size_type& sz, flag_type flags = flag_none) {
return pub_socket::try_receive(bufp, sz, flags);
}
};
class sub_socket_fixture : public sub_socket {
public:
sub_socket_fixture() : sub_socket() {}
virtual ~sub_socket_fixture() {}
void send(binary_message_type* const bmp, flag_type flags = flag_none) {
sub_socket::send(bmp, flags);
}
int send(const buffer_vector_type* const bufp, flag_type flags = flag_none) {
return sub_socket::send(bufp, flags);
}
int send(const buffer_vector_type* const bufp, size_type sz, flag_type flags = flag_none) {
return sub_socket::send(bufp, sz, flags);
}
};
}
typedef v0::pub_socket_fixture latest_pub_socket_fixture;
typedef v0::sub_socket_fixture latest_sub_socket_fixture;
}
}
namespace constants {
const std::string test_addr = "inproc://test";
const std::string __empty = "";
const std::string abc = "abc";
const std::string hello = "hello";
namespace topics {
const std::string some = "/some/";
const std::string some_like_it_hot = "/some/like/it/hot";
const std::string some_day_some_how = "/some/day/some/how";
const std::string some_do_not_like_it = "some/do/not/like/it";
const std::string some_like_it_raw = "/some/like/it/raw";
const TO_BUFFER_RETVAL some_buf = to_buffer(some);
const TO_BUFFER_RETVAL some_like_it_hot_buf = to_buffer(some_like_it_hot);
const TO_BUFFER_RETVAL some_day_some_how_buf = to_buffer(some_day_some_how);
const TO_BUFFER_RETVAL some_do_not_like_it_buf = to_buffer(some_do_not_like_it);
const TO_BUFFER_RETVAL some_like_it_raw_buf = to_buffer(some_like_it_raw);
// Yes, this is intentionally different from /some/path/to/topic...
const std::string somewhere_over_the_rainbow = "/somewhere/over/the/rainbow";
const TO_BUFFER_RETVAL somewhere_over_the_rainbow_buf = to_buffer(somewhere_over_the_rainbow);
}
}
TEST_CASE("Publisher/subscriber pattern using C++ wrapper", "[pubsub][v0][protocol][sockets][cxx]") {
using namespace std;
using namespace constants;
using namespace nng;
using namespace nng::protocol;
using namespace nng::messaging;
using namespace trx;
using namespace Catch::Matchers;
using O = option_names;
basic_fixture fixture;
// Some of these need to be initialized to avoid garbage results, crash situations, etc.
socket::size_type sz = 0;
protocol_type actual_proto, actual_peer;
unique_ptr<binary_message> bmp;
binary_message::buffer_vector_type buf;
unique_ptr<latest_pub_socket_fixture> pubp;
unique_ptr<latest_sub_socket_fixture> subp;
SECTION("We can create a publisher socket") {
REQUIRE_NOTHROW(pubp = make_unique<latest_pub_socket_fixture>());
SECTION("Protocols match") {
REQUIRE_NOTHROW(actual_proto = pubp->get_protocol());
REQUIRE(actual_proto == proto_publisher);
REQUIRE(actual_proto == proto_publisher_v0);
REQUIRE_NOTHROW(actual_peer = pubp->get_peer());
REQUIRE(actual_peer == proto_subscriber);
REQUIRE(actual_peer == proto_subscriber_v0);
}
SECTION("Receive throws invalid operation exception") {
REQUIRE_THROWS_AS(pubp->receive(), invalid_operation);
REQUIRE_THROWS_AS(pubp->receive(sz), invalid_operation);
REQUIRE_THROWS_AS(pubp->try_receive(bmp.get()), invalid_operation);
REQUIRE_THROWS_AS(pubp->try_receive(&buf, sz), invalid_operation);
}
SECTION("Socket can close") {
/* This is better than a raw "Close", at least in this scope. Destroying the resource also Closes. */
REQUIRE_NOTHROW(pubp.reset());
}
}
SECTION("We can create a subscriber socket") {
REQUIRE_NOTHROW(subp = make_unique<latest_sub_socket_fixture>());
SECTION("Protocols match") {
REQUIRE_NOTHROW(actual_proto = subp->get_protocol());
REQUIRE(actual_proto == proto_subscriber);
REQUIRE(actual_proto == proto_subscriber_v0);
REQUIRE_NOTHROW(actual_peer = subp->get_peer());
REQUIRE(actual_peer == proto_publisher);
REQUIRE(actual_peer == proto_publisher_v0);
}
SECTION("Send throws invalid operation exception") {
REQUIRE_THROWS_AS(subp->send(bmp.get()), invalid_operation);
REQUIRE_THROWS_AS(subp->send(&buf), invalid_operation);
REQUIRE_THROWS_AS(subp->send(&buf, sz), invalid_operation);
}
SECTION("Socket can close") {
// Ditto reset versus raw Close.
REQUIRE_NOTHROW(subp.reset());
}
}
SECTION("We can create a linked pub/sub pair") {
REQUIRE_NOTHROW(pubp = make_unique<latest_pub_socket_fixture>());
REQUIRE_NOTHROW(subp = make_unique<latest_sub_socket_fixture>());
/* Most applications will usually have the pub listen and sub dial. However, this
creates a problem for our tests, since we can wind up trying to push data before
the pipe is fully registered due to the accept running asynchronously. */
REQUIRE_NOTHROW(subp->listen(test_addr));
REQUIRE_NOTHROW(pubp->dial(test_addr));
SLEEP_FOR(20ms); // Time for connecting threads.
SECTION("Subscriber can subscribe") {
REQUIRE_NOTHROW(subp->set_option(O::sub_subscribe, abc));
REQUIRE_NOTHROW(subp->set_option(O::sub_subscribe, __empty));
SECTION("Unsubscribe works") {
REQUIRE_NOTHROW(subp->set_option(O::sub_unsubscribe, abc));
REQUIRE_NOTHROW(subp->set_option(O::sub_unsubscribe, __empty));
REQUIRE_THROWS_AS_MATCHING(subp->set_option(O::sub_unsubscribe, __empty), nng_exception, ThrowsNngException(ec_enoent));
REQUIRE_THROWS_AS_MATCHING(subp->set_option(O::sub_unsubscribe, hello), nng_exception, ThrowsNngException(ec_enoent));
}
}
SECTION("Publisher cannot subscribe") {
REQUIRE_THROWS_AS_MATCHING(pubp->set_option(O::sub_subscribe, __empty), nng_exception, ThrowsNngException(ec_enotsup));
}
SECTION("Subscriber can receive from publisher") {
REQUIRE_NOTHROW(subp->set_option(O::sub_subscribe, topics::some));
REQUIRE_NOTHROW(subp->set_option_usec(O::receive_timeout_usec, CAST_DURATION_TO_USEC(90ms).count()));
REQUIRE_NOTHROW(bmp = make_unique<binary_message>());
REQUIRE_NOTHROW(*bmp << topics::some_like_it_hot);
REQUIRE_NOTHROW(pubp->send(bmp.get()));
REQUIRE_NOTHROW(subp->try_receive(bmp.get()));
REQUIRE_THAT(bmp->body()->get(), Equals(topics::some_like_it_hot_buf));
REQUIRE_NOTHROW(bmp = make_unique<binary_message>());
REQUIRE_NOTHROW(*bmp << topics::somewhere_over_the_rainbow);
REQUIRE_THAT(bmp->body()->get(), Equals(topics::somewhere_over_the_rainbow_buf));
REQUIRE_NOTHROW(pubp->send(bmp.get()));
REQUIRE_THROWS_AS_MATCHING(subp->try_receive(bmp.get()), nng_exception, ThrowsNngException(ec_etimedout));
REQUIRE_NOTHROW(bmp = make_unique<binary_message>());
REQUIRE_NOTHROW(*bmp << topics::some_day_some_how);
REQUIRE_NOTHROW(pubp->send(bmp.get()));
REQUIRE_NOTHROW(subp->try_receive(bmp.get()));
REQUIRE_THAT(bmp->body()->get(), Equals(topics::some_day_some_how_buf));
}
SECTION("Subscribers without subsciptions do not receive") {
REQUIRE_NOTHROW(subp->set_option_usec(O::receive_timeout_usec, CAST_DURATION_TO_USEC(90ms).count()));
REQUIRE_NOTHROW(bmp = make_unique<binary_message>());
REQUIRE_NOTHROW(*bmp << topics::some_do_not_like_it);
REQUIRE_NOTHROW(pubp->send(bmp.get()));
REQUIRE_THROWS_AS_MATCHING(subp->try_receive(bmp.get()), nng_exception, ThrowsNngException(ec_etimedout));
}
SECTION("Subscribers in raw receive") {
REQUIRE_NOTHROW(subp->set_option_usec(O::receive_timeout_usec, CAST_DURATION_TO_USEC(90ms).count()));
REQUIRE_NOTHROW(subp->set_option_int(O::raw, 1));
REQUIRE_NOTHROW(bmp = make_unique<binary_message>());
REQUIRE_NOTHROW(*bmp << topics::some_like_it_raw);
REQUIRE_NOTHROW(pubp->send(bmp.get()));
REQUIRE_NOTHROW(subp->try_receive(bmp.get()));
REQUIRE_THAT(bmp->body()->get(), Equals(topics::some_like_it_raw_buf));
}
}
}<commit_msg>added tags to the pub sub test case<commit_after>//
// Copyright (c) 2017 Michael W Powell <mwpowellhtx@gmail.com>
// Copyright 2017 Garrett D'Amore <garrett@damore.org>
// Copyright 2017 Capitar IT Group BV <info@capitar.com>
//
// This software is supplied under the terms of the MIT License, a
// copy of which should be located in the distribution where this
// file was obtained (LICENSE.txt). A copy of the license may also be
// found online at https://opensource.org/licenses/MIT.
//
#include "../catch/catch_nng_exception_matcher.hpp"
#include "../catch/catch_exception_translations.hpp"
#include "../catch/catch_macros.hpp"
#include "../helpers/basic_fixture.h"
#include "../helpers/constants.h"
#include "../helpers/chrono.hpp"
#include <nngcpp.h>
namespace nng {
namespace protocol {
namespace v0 {
class pub_socket_fixture : public pub_socket {
public:
pub_socket_fixture() : pub_socket() {}
virtual ~pub_socket_fixture() {}
std::unique_ptr<binary_message_type> receive(flag_type flags = flag_none) {
return pub_socket::receive(flags);
}
int try_receive(binary_message_type* const bmp, flag_type flags = flag_none) {
return pub_socket::try_receive(bmp, flags);
}
buffer_vector_type receive(size_type& sz, flag_type flags = flag_none) {
return pub_socket::receive(sz, flags);
}
int try_receive(buffer_vector_type* const bufp, size_type& sz, flag_type flags = flag_none) {
return pub_socket::try_receive(bufp, sz, flags);
}
};
class sub_socket_fixture : public sub_socket {
public:
sub_socket_fixture() : sub_socket() {}
virtual ~sub_socket_fixture() {}
void send(binary_message_type* const bmp, flag_type flags = flag_none) {
sub_socket::send(bmp, flags);
}
int send(const buffer_vector_type* const bufp, flag_type flags = flag_none) {
return sub_socket::send(bufp, flags);
}
int send(const buffer_vector_type* const bufp, size_type sz, flag_type flags = flag_none) {
return sub_socket::send(bufp, sz, flags);
}
};
}
typedef v0::pub_socket_fixture latest_pub_socket_fixture;
typedef v0::sub_socket_fixture latest_sub_socket_fixture;
}
}
namespace constants {
const std::string test_addr = "inproc://test";
const std::string __empty = "";
const std::string abc = "abc";
const std::string hello = "hello";
namespace topics {
const std::string some = "/some/";
const std::string some_like_it_hot = "/some/like/it/hot";
const std::string some_day_some_how = "/some/day/some/how";
const std::string some_do_not_like_it = "some/do/not/like/it";
const std::string some_like_it_raw = "/some/like/it/raw";
const TO_BUFFER_RETVAL some_buf = to_buffer(some);
const TO_BUFFER_RETVAL some_like_it_hot_buf = to_buffer(some_like_it_hot);
const TO_BUFFER_RETVAL some_day_some_how_buf = to_buffer(some_day_some_how);
const TO_BUFFER_RETVAL some_do_not_like_it_buf = to_buffer(some_do_not_like_it);
const TO_BUFFER_RETVAL some_like_it_raw_buf = to_buffer(some_like_it_raw);
// Yes, this is intentionally different from /some/path/to/topic...
const std::string somewhere_over_the_rainbow = "/somewhere/over/the/rainbow";
const TO_BUFFER_RETVAL somewhere_over_the_rainbow_buf = to_buffer(somewhere_over_the_rainbow);
}
}
TEST_CASE("Publisher/subscriber pattern using C++ wrapper", "[pub][sub][v0][protocol][sockets][nng][cxx]") {
using namespace std;
using namespace constants;
using namespace nng;
using namespace nng::protocol;
using namespace nng::messaging;
using namespace trx;
using namespace Catch::Matchers;
using O = option_names;
basic_fixture fixture;
// Some of these need to be initialized to avoid garbage results, crash situations, etc.
socket::size_type sz = 0;
protocol_type actual_proto, actual_peer;
unique_ptr<binary_message> bmp;
binary_message::buffer_vector_type buf;
unique_ptr<latest_pub_socket_fixture> pubp;
unique_ptr<latest_sub_socket_fixture> subp;
SECTION("We can create a publisher socket") {
REQUIRE_NOTHROW(pubp = make_unique<latest_pub_socket_fixture>());
SECTION("Protocols match") {
REQUIRE_NOTHROW(actual_proto = pubp->get_protocol());
REQUIRE(actual_proto == proto_publisher);
REQUIRE(actual_proto == proto_publisher_v0);
REQUIRE_NOTHROW(actual_peer = pubp->get_peer());
REQUIRE(actual_peer == proto_subscriber);
REQUIRE(actual_peer == proto_subscriber_v0);
}
SECTION("Receive throws invalid operation exception") {
REQUIRE_THROWS_AS(pubp->receive(), invalid_operation);
REQUIRE_THROWS_AS(pubp->receive(sz), invalid_operation);
REQUIRE_THROWS_AS(pubp->try_receive(bmp.get()), invalid_operation);
REQUIRE_THROWS_AS(pubp->try_receive(&buf, sz), invalid_operation);
}
SECTION("Socket can close") {
/* This is better than a raw "Close", at least in this scope. Destroying the resource also Closes. */
REQUIRE_NOTHROW(pubp.reset());
}
}
SECTION("We can create a subscriber socket") {
REQUIRE_NOTHROW(subp = make_unique<latest_sub_socket_fixture>());
SECTION("Protocols match") {
REQUIRE_NOTHROW(actual_proto = subp->get_protocol());
REQUIRE(actual_proto == proto_subscriber);
REQUIRE(actual_proto == proto_subscriber_v0);
REQUIRE_NOTHROW(actual_peer = subp->get_peer());
REQUIRE(actual_peer == proto_publisher);
REQUIRE(actual_peer == proto_publisher_v0);
}
SECTION("Send throws invalid operation exception") {
REQUIRE_THROWS_AS(subp->send(bmp.get()), invalid_operation);
REQUIRE_THROWS_AS(subp->send(&buf), invalid_operation);
REQUIRE_THROWS_AS(subp->send(&buf, sz), invalid_operation);
}
SECTION("Socket can close") {
// Ditto reset versus raw Close.
REQUIRE_NOTHROW(subp.reset());
}
}
SECTION("We can create a linked pub/sub pair") {
REQUIRE_NOTHROW(pubp = make_unique<latest_pub_socket_fixture>());
REQUIRE_NOTHROW(subp = make_unique<latest_sub_socket_fixture>());
/* Most applications will usually have the pub listen and sub dial. However, this
creates a problem for our tests, since we can wind up trying to push data before
the pipe is fully registered due to the accept running asynchronously. */
REQUIRE_NOTHROW(subp->listen(test_addr));
REQUIRE_NOTHROW(pubp->dial(test_addr));
SLEEP_FOR(20ms); // Time for connecting threads.
SECTION("Subscriber can subscribe") {
REQUIRE_NOTHROW(subp->set_option(O::sub_subscribe, abc));
REQUIRE_NOTHROW(subp->set_option(O::sub_subscribe, __empty));
SECTION("Unsubscribe works") {
REQUIRE_NOTHROW(subp->set_option(O::sub_unsubscribe, abc));
REQUIRE_NOTHROW(subp->set_option(O::sub_unsubscribe, __empty));
REQUIRE_THROWS_AS_MATCHING(subp->set_option(O::sub_unsubscribe, __empty), nng_exception, ThrowsNngException(ec_enoent));
REQUIRE_THROWS_AS_MATCHING(subp->set_option(O::sub_unsubscribe, hello), nng_exception, ThrowsNngException(ec_enoent));
}
}
SECTION("Publisher cannot subscribe") {
REQUIRE_THROWS_AS_MATCHING(pubp->set_option(O::sub_subscribe, __empty), nng_exception, ThrowsNngException(ec_enotsup));
}
SECTION("Subscriber can receive from publisher") {
REQUIRE_NOTHROW(subp->set_option(O::sub_subscribe, topics::some));
REQUIRE_NOTHROW(subp->set_option_usec(O::receive_timeout_usec, CAST_DURATION_TO_USEC(90ms).count()));
REQUIRE_NOTHROW(bmp = make_unique<binary_message>());
REQUIRE_NOTHROW(*bmp << topics::some_like_it_hot);
REQUIRE_NOTHROW(pubp->send(bmp.get()));
REQUIRE_NOTHROW(subp->try_receive(bmp.get()));
REQUIRE_THAT(bmp->body()->get(), Equals(topics::some_like_it_hot_buf));
REQUIRE_NOTHROW(bmp = make_unique<binary_message>());
REQUIRE_NOTHROW(*bmp << topics::somewhere_over_the_rainbow);
REQUIRE_THAT(bmp->body()->get(), Equals(topics::somewhere_over_the_rainbow_buf));
REQUIRE_NOTHROW(pubp->send(bmp.get()));
REQUIRE_THROWS_AS_MATCHING(subp->try_receive(bmp.get()), nng_exception, ThrowsNngException(ec_etimedout));
REQUIRE_NOTHROW(bmp = make_unique<binary_message>());
REQUIRE_NOTHROW(*bmp << topics::some_day_some_how);
REQUIRE_NOTHROW(pubp->send(bmp.get()));
REQUIRE_NOTHROW(subp->try_receive(bmp.get()));
REQUIRE_THAT(bmp->body()->get(), Equals(topics::some_day_some_how_buf));
}
SECTION("Subscribers without subsciptions do not receive") {
REQUIRE_NOTHROW(subp->set_option_usec(O::receive_timeout_usec, CAST_DURATION_TO_USEC(90ms).count()));
REQUIRE_NOTHROW(bmp = make_unique<binary_message>());
REQUIRE_NOTHROW(*bmp << topics::some_do_not_like_it);
REQUIRE_NOTHROW(pubp->send(bmp.get()));
REQUIRE_THROWS_AS_MATCHING(subp->try_receive(bmp.get()), nng_exception, ThrowsNngException(ec_etimedout));
}
SECTION("Subscribers in raw receive") {
REQUIRE_NOTHROW(subp->set_option_usec(O::receive_timeout_usec, CAST_DURATION_TO_USEC(90ms).count()));
REQUIRE_NOTHROW(subp->set_option_int(O::raw, 1));
REQUIRE_NOTHROW(bmp = make_unique<binary_message>());
REQUIRE_NOTHROW(*bmp << topics::some_like_it_raw);
REQUIRE_NOTHROW(pubp->send(bmp.get()));
REQUIRE_NOTHROW(subp->try_receive(bmp.get()));
REQUIRE_THAT(bmp->body()->get(), Equals(topics::some_like_it_raw_buf));
}
}
}<|endoftext|> |
<commit_before>//! Copyright (c) 2013 ASMlover. 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 ofconditions 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 materialsprovided with the
//! distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include "logging.h"
#include "thread.h"
#include "select_poll.h"
#include "select_worker.h"
SelectWorker::SelectWorker(void)
: running_(false)
, thread_(NULL)
, poll_(NULL)
{
}
SelectWorker::~SelectWorker(void)
{
Stop();
}
bool
SelectWorker::Start(void)
{
if (NULL == poll_)
return false;
thread_ = new Thread(&SelectWorker::Routine, this);
if (NULL == thread_) {
LOG_FAILX("new Thread failed\n");
return false;
}
running_ = true;
thread_->Start();
return true;
}
void
SelectWorker::Stop(void)
{
running_ = false;
if (NULL != thread_) {
thread_->Join();
delete thread_;
thread_ = NULL;
}
}
void
SelectWorker::Routine(void* argument)
{
SelectWorker* self = static_cast<SelectWorker*>(argument);
if (NULL == self)
return;
while (self->running_) {
if (!self->poll_->Polling()) {
Sleep(1);
continue;
}
}
}
<commit_msg>fixed bug of select worker module<commit_after>//! Copyright (c) 2013 ASMlover. 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 ofconditions 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 materialsprovided with the
//! distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include "logging.h"
#include "thread.h"
#include "select_poll.h"
#include "select_worker.h"
SelectWorker::SelectWorker(void)
: running_(false)
, thread_(NULL)
, poll_(NULL)
{
}
SelectWorker::~SelectWorker(void)
{
Stop();
}
bool
SelectWorker::Start(void)
{
if (NULL == poll_)
return false;
thread_ = new Thread(&SelectWorker::Routine, this);
if (NULL == thread_) {
LOG_FAIL("new Thread failed\n");
return false;
}
running_ = true;
thread_->Start();
return true;
}
void
SelectWorker::Stop(void)
{
running_ = false;
if (NULL != thread_) {
thread_->Join();
delete thread_;
thread_ = NULL;
}
}
void
SelectWorker::Routine(void* argument)
{
SelectWorker* self = static_cast<SelectWorker*>(argument);
if (NULL == self)
return;
while (self->running_) {
if (!self->poll_->Polling()) {
Sleep(1);
continue;
}
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 <cstring>
#include <inttypes.h>
#include "Allocator.h"
#include "Filesystem.h"
#include "StringUtils.h"
#include "SpriteCompiler.h"
#include "Hash.h"
namespace crown
{
//-----------------------------------------------------------------------------
SpriteCompiler::SpriteCompiler()
: m_anim_data(default_allocator())
{
}
//-----------------------------------------------------------------------------
SpriteCompiler::~SpriteCompiler()
{
}
//-----------------------------------------------------------------------------
size_t SpriteCompiler::compile_impl(Filesystem& fs, const char* resource_path)
{
File* file = fs.open(resource_path, FOM_READ);
char* buf = (char*)default_allocator().allocate(file->size());
file->read(buf, file->size());
JSONParser json(buf);
JSONElement root = json.root();
string::strncpy(m_anim_header.name, root.key("name").string_value(), 128);
DynamicString texture(root.key("texture").string_value());
texture += ".texture";
m_anim_header.texture.id = hash::murmur2_64(texture.c_str(), string::strlen(texture.c_str()), 0);
m_anim_header.num_frames = root.key("num_frames").int_value();
m_anim_header.frame_rate = root.key("frame_rate").int_value();
m_anim_header.playback_mode = root.key("playback_mode").int_value();
List<float> t_positions(default_allocator());
JSONElement anim_vertices = root.key("positions");
anim_vertices.array_value(t_positions);
List<float> t_texcoords(default_allocator());
JSONElement anim_texcoords = root.key("texcoords");
anim_texcoords.array_value(t_texcoords);
for (uint32_t i = 0; i < t_texcoords.size(); i+=8)
{
for (uint32_t j = 0; j < t_positions.size(); j+=2)
{
SpriteAnimationData t_animation_data;
t_animation_data.position.x = t_positions[j];
t_animation_data.position.y = t_positions[j+1];
t_animation_data.texcoords.x = t_texcoords[j+i];
t_animation_data.texcoords.y = t_texcoords[j+i+1];
m_anim_data.push_back(t_animation_data);
}
}
fs.close(file);
default_allocator().deallocate(buf);
return 1;
}
//-----------------------------------------------------------------------------
void SpriteCompiler::write_impl(File* out_file)
{
out_file->write((char*)&m_anim_header, sizeof(SpriteHeader));
out_file->write((char*)m_anim_data.begin(), sizeof(SpriteAnimationData) * m_anim_data.size());
m_anim_data.clear();
}
} // namespace crown<commit_msg>Add missing include<commit_after>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 <cstring>
#include <inttypes.h>
#include "Allocator.h"
#include "Filesystem.h"
#include "StringUtils.h"
#include "SpriteCompiler.h"
#include "Hash.h"
#include "JSONParser.h"
namespace crown
{
//-----------------------------------------------------------------------------
SpriteCompiler::SpriteCompiler()
: m_anim_data(default_allocator())
{
}
//-----------------------------------------------------------------------------
SpriteCompiler::~SpriteCompiler()
{
}
//-----------------------------------------------------------------------------
size_t SpriteCompiler::compile_impl(Filesystem& fs, const char* resource_path)
{
File* file = fs.open(resource_path, FOM_READ);
char* buf = (char*)default_allocator().allocate(file->size());
file->read(buf, file->size());
JSONParser json(buf);
JSONElement root = json.root();
string::strncpy(m_anim_header.name, root.key("name").string_value(), 128);
DynamicString texture(root.key("texture").string_value());
texture += ".texture";
m_anim_header.texture.id = hash::murmur2_64(texture.c_str(), string::strlen(texture.c_str()), 0);
m_anim_header.num_frames = root.key("num_frames").int_value();
m_anim_header.frame_rate = root.key("frame_rate").int_value();
m_anim_header.playback_mode = root.key("playback_mode").int_value();
List<float> t_positions(default_allocator());
JSONElement anim_vertices = root.key("positions");
anim_vertices.array_value(t_positions);
List<float> t_texcoords(default_allocator());
JSONElement anim_texcoords = root.key("texcoords");
anim_texcoords.array_value(t_texcoords);
for (uint32_t i = 0; i < t_texcoords.size(); i+=8)
{
for (uint32_t j = 0; j < t_positions.size(); j+=2)
{
SpriteAnimationData t_animation_data;
t_animation_data.position.x = t_positions[j];
t_animation_data.position.y = t_positions[j+1];
t_animation_data.texcoords.x = t_texcoords[j+i];
t_animation_data.texcoords.y = t_texcoords[j+i+1];
m_anim_data.push_back(t_animation_data);
}
}
fs.close(file);
default_allocator().deallocate(buf);
return 1;
}
//-----------------------------------------------------------------------------
void SpriteCompiler::write_impl(File* out_file)
{
out_file->write((char*)&m_anim_header, sizeof(SpriteHeader));
out_file->write((char*)m_anim_data.begin(), sizeof(SpriteAnimationData) * m_anim_data.size());
m_anim_data.clear();
}
} // namespace crown<|endoftext|> |
<commit_before>
#include "QmitkSegmentationPostProcessing.h"
#include "QmitkNodeDescriptorManager.h"
#include "QmitkToolGUI.h"
#include "mitkAutoCropImageFilter.h"
#include "mitkBinaryThresholdTool.h"
#include "mitkRenderingManager.h"
#include "mitkShowSegmentationAsSurface.h"
#include "mitkProgressBar.h"
#include "mitkStatusBar.h"
#include "mitkImageCast.h"
#include "mitkDataNodeObject.h"
#include <QtGui>
#include <berryIWorkbenchPage.h>
#include <itkConstantPadImageFilter.h>
QmitkSegmentationPostProcessing::QmitkSegmentationPostProcessing(mitk::DataStorage* storage, QmitkFunctionality* functionality, QObject* parent)
:QObject(parent)
,m_BlueBerryView(functionality)
,m_DataStorage(storage)
{
// register a couple of additional actions for DataManager's context menu
QmitkNodeDescriptor* imageDataNodeDescriptor =
QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("Image");
if (imageDataNodeDescriptor)
{
m_ThresholdAction = new QAction("Threshold..", parent);
imageDataNodeDescriptor->AddAction(m_ThresholdAction);
connect( m_ThresholdAction, SIGNAL( triggered(bool) ) , this, SLOT( ThresholdImage(bool) ) );
}
else
{
MITK_WARN << "Could not get datamanager's node descriptor for 'Image'";
}
// register a couple of additional actions for DataManager's context menu
QmitkNodeDescriptor* binaryImageDataNodeDescriptor =
QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("ImageMask");
if (binaryImageDataNodeDescriptor)
{
m_CreateSurfaceAction = new QAction("Create polygon model", parent);
binaryImageDataNodeDescriptor->AddAction(m_CreateSurfaceAction);
connect( m_CreateSurfaceAction, SIGNAL( triggered(bool) ) , this, SLOT( CreateSurface(bool) ) );
m_CreateSmoothSurfaceAction = new QAction("Create smoothed polygon model", parent);
binaryImageDataNodeDescriptor->AddAction(m_CreateSmoothSurfaceAction);
connect( m_CreateSmoothSurfaceAction, SIGNAL( triggered(bool) ) , this, SLOT( CreateSmoothedSurface(bool) ) );
m_StatisticsAction = new QAction("Statistics", parent);
binaryImageDataNodeDescriptor->AddAction(m_StatisticsAction);
connect( m_StatisticsAction, SIGNAL( triggered(bool) ) , this, SLOT( ImageStatistics(bool) ) );
m_AutocropAction = new QAction("Autocrop", parent);
binaryImageDataNodeDescriptor->AddAction(m_AutocropAction);
connect( m_AutocropAction, SIGNAL( triggered(bool) ) , this, SLOT( AutocropSelected(bool) ) );
}
else
{
MITK_WARN << "Could not get datamanager's node descriptor for 'ImageMask'";
}
// register for blueberry selection events
m_SelectionListener = berry::ISelectionListener::Pointer(new berry::SelectionChangedAdapter<QmitkSegmentationPostProcessing>(this, &QmitkSegmentationPostProcessing::SelectionChanged));
m_BlueBerryView->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelectionListener);
}
QmitkSegmentationPostProcessing::~QmitkSegmentationPostProcessing()
{
berry::ISelectionService* s = m_BlueBerryView->GetSite()->GetWorkbenchWindow()->GetSelectionService();
if(s)
{
s->RemovePostSelectionListener(m_SelectionListener);
}
// unregister a couple of additional actions for DataManager's context menu
QmitkNodeDescriptor* imageDataNodeDescriptor =
QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("Image");
if (imageDataNodeDescriptor)
{
imageDataNodeDescriptor->RemoveAction( m_ThresholdAction );
}
else
{
MITK_WARN << "Could not get datamanager's node descriptor for 'Image'";
}
// unregister a couple of additional actions for DataManager's context menu
QmitkNodeDescriptor* binaryImageDataNodeDescriptor =
QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("ImageMask");
if (binaryImageDataNodeDescriptor)
{
binaryImageDataNodeDescriptor->RemoveAction( m_CreateSurfaceAction );
binaryImageDataNodeDescriptor->RemoveAction( m_CreateSmoothSurfaceAction );
binaryImageDataNodeDescriptor->RemoveAction( m_StatisticsAction );
binaryImageDataNodeDescriptor->RemoveAction( m_AutocropAction );
}
else
{
MITK_WARN << "Could not get datamanager's node descriptor for 'ImageMask'";
}
}
void QmitkSegmentationPostProcessing::SelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, berry::ISelection::ConstPointer selection)
{
if ( selection.IsNull() )
{
return;
}
// save current selection in member variable
m_CurrentSelection = selection.Cast<const mitk::DataNodeSelection>();
}
QmitkSegmentationPostProcessing::NodeList QmitkSegmentationPostProcessing::GetSelectedNodes() const
{
NodeList result;
if (m_CurrentSelection)
{
// iterate selection
for (mitk::DataNodeSelection::iterator i = m_CurrentSelection->Begin(); i != m_CurrentSelection->End(); ++i)
{
// extract datatree node
if (mitk::DataNodeObject::Pointer nodeObj = i->Cast<mitk::DataNodeObject>())
{
mitk::DataNode::Pointer node = nodeObj->GetDataNode();
result.push_back( node );
}
}
}
return result;
}
void QmitkSegmentationPostProcessing::ThresholdImage(bool)
{
NodeList selection = this->GetSelectedNodes();
m_ThresholdingToolManager = mitk::ToolManager::New( m_DataStorage );
m_ThresholdingToolManager->RegisterClient();
m_ThresholdingToolManager->ActiveToolChanged +=
mitk::MessageDelegate<QmitkSegmentationPostProcessing>( this, &QmitkSegmentationPostProcessing::OnThresholdingToolManagerToolModified );
m_ThresholdingDialog = new QDialog(NULL);
connect( m_ThresholdingDialog, SIGNAL(finished(int)), this, SLOT(ThresholdingDone(int)) );
QVBoxLayout* layout = new QVBoxLayout;
layout->setContentsMargins(0, 0, 0, 0);
mitk::Tool* tool = m_ThresholdingToolManager->GetToolById( m_ThresholdingToolManager->GetToolIdByToolType<mitk::BinaryThresholdTool>() );
if (tool)
{
itk::Object::Pointer possibleGUI = tool->GetGUI("Qmitk", "GUI");
QmitkToolGUI* gui = dynamic_cast<QmitkToolGUI*>( possibleGUI.GetPointer() );
if (gui)
{
gui->SetTool(tool);
gui->setParent(m_ThresholdingDialog);
layout->addWidget(gui);
m_ThresholdingDialog->setLayout(layout);
layout->activate();
m_ThresholdingDialog->setFixedSize(300,50);
m_ThresholdingDialog->open();
}
}
for ( NodeList::iterator iter = selection.begin(); iter != selection.end(); ++iter )
{
mitk::DataNode* node = *iter;
if (node)
{
m_ThresholdingToolManager->SetReferenceData( node );
m_ThresholdingToolManager->ActivateTool( m_ThresholdingToolManager->GetToolIdByToolType<mitk::BinaryThresholdTool>() );
}
}
}
void QmitkSegmentationPostProcessing::ThresholdingDone(int)
{
MITK_INFO << "Thresholding done, cleaning up";
m_ThresholdingDialog->deleteLater();
m_ThresholdingDialog = NULL;
m_ThresholdingToolManager->SetReferenceData( NULL );
m_ThresholdingToolManager->SetWorkingData( NULL );
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkSegmentationPostProcessing::OnThresholdingToolManagerToolModified()
{
if ( m_ThresholdingToolManager.IsNull() ) return;
//MITK_INFO << "Now got tool " << m_ThresholdingToolManager->GetActiveToolID();
if ( m_ThresholdingToolManager->GetActiveToolID() < 0)
{
if (m_ThresholdingDialog)
m_ThresholdingDialog->accept();
}
}
void QmitkSegmentationPostProcessing::CreateSmoothedSurface(bool)
{
InternalCreateSurface(true);
}
void QmitkSegmentationPostProcessing::CreateSurface(bool)
{
InternalCreateSurface(false);
}
void QmitkSegmentationPostProcessing::InternalCreateSurface(bool smoothed)
{
NodeList selection = this->GetSelectedNodes();
for ( NodeList::iterator iter = selection.begin(); iter != selection.end(); ++iter )
{
mitk::DataNode* node = *iter;
if (node)
{
mitk::Image::Pointer image = dynamic_cast<mitk::Image*>( node->GetData() );
if (image.IsNull()) return;
try
{
mitk::ShowSegmentationAsSurface::Pointer surfaceFilter = mitk::ShowSegmentationAsSurface::New();
// attach observer to get notified about result
itk::SimpleMemberCommand<QmitkSegmentationPostProcessing>::Pointer goodCommand = itk::SimpleMemberCommand<QmitkSegmentationPostProcessing>::New();
goodCommand->SetCallbackFunction(this, &QmitkSegmentationPostProcessing::OnSurfaceCalculationDone);
surfaceFilter->AddObserver(mitk::ResultAvailable(), goodCommand);
itk::SimpleMemberCommand<QmitkSegmentationPostProcessing>::Pointer badCommand = itk::SimpleMemberCommand<QmitkSegmentationPostProcessing>::New();
badCommand->SetCallbackFunction(this, &QmitkSegmentationPostProcessing::OnSurfaceCalculationDone);
surfaceFilter->AddObserver(mitk::ProcessingError(), badCommand);
mitk::DataNode::Pointer nodepointer = node;
surfaceFilter->SetPointerParameter("Input", image);
surfaceFilter->SetPointerParameter("Group node", nodepointer);
surfaceFilter->SetParameter("Show result", true );
surfaceFilter->SetParameter("Sync visibility", false );
surfaceFilter->SetDataStorage( *m_DataStorage );
if (smoothed)
{
surfaceFilter->SetParameter("Smooth", true );
//surfaceFilter->SetParameter("Apply median", true );
surfaceFilter->SetParameter("Apply median", false ); // median makes the resulting surfaces look like lego models
surfaceFilter->SetParameter("Median kernel size", 3u );
surfaceFilter->SetParameter("Gaussian SD", 2.5f );
surfaceFilter->SetParameter("Decimate mesh", true );
surfaceFilter->SetParameter("Decimation rate", 0.80f );
}
else
{
surfaceFilter->SetParameter("Smooth", false );
surfaceFilter->SetParameter("Apply median", false );
surfaceFilter->SetParameter("Median kernel size", 3u );
surfaceFilter->SetParameter("Gaussian SD", 1.5f );
surfaceFilter->SetParameter("Decimate mesh", true );
surfaceFilter->SetParameter("Decimation rate", 0.8f );
}
mitk::ProgressBar::GetInstance()->AddStepsToDo(10);
mitk::ProgressBar::GetInstance()->Progress(2);
mitk::StatusBar::GetInstance()->DisplayText("Surface creation started in background...");
surfaceFilter->StartAlgorithm();
}
catch(...)
{
MITK_ERROR << "surface creation filter had an error";
}
}
else
{
MITK_INFO << " a NULL node selected";
}
}
}
void QmitkSegmentationPostProcessing::OnSurfaceCalculationDone()
{
mitk::ProgressBar::GetInstance()->Progress(8);
}
void QmitkSegmentationPostProcessing::ImageStatistics(bool)
{
if (m_BlueBerryView)
{
m_BlueBerryView->GetSite()->GetWorkbenchWindow()->GetActivePage()->ShowView("org.mitk.views.imagestatistics");
}
}
void QmitkSegmentationPostProcessing::AutocropSelected(bool)
{
NodeList selection = this->GetSelectedNodes();
for ( NodeList::iterator iter = selection.begin(); iter != selection.end(); ++iter )
{
mitk::DataNode* node = *iter;
if (node)
{
mitk::Image::Pointer image = dynamic_cast<mitk::Image*>( node->GetData() );
if (image.IsNull()) return;
mitk::ProgressBar::GetInstance()->AddStepsToDo(10);
mitk::ProgressBar::GetInstance()->Progress(2);
qApp->processEvents();
mitk::AutoCropImageFilter::Pointer cropFilter = mitk::AutoCropImageFilter::New();
cropFilter->SetInput( image );
cropFilter->SetBackgroundValue( 0 );
try
{
cropFilter->Update();
image = cropFilter->GetOutput();
if (image.IsNotNull())
{
node->SetData( this->IncreaseCroppedImageSize(image) ); // bug fix 3145
}
}
catch(...)
{
MITK_ERROR << "Cropping image failed...";
}
mitk::ProgressBar::GetInstance()->Progress(8);
}
else
{
MITK_INFO << " a NULL node selected";
}
}
}
mitk::Image::Pointer QmitkSegmentationPostProcessing::IncreaseCroppedImageSize( mitk::Image::Pointer image )
{
typedef itk::Image< short, 3 > ImageType;
typedef itk::Image< unsigned char, 3 > PADOutputImageType;
ImageType::Pointer itkTransformImage = ImageType::New();
mitk::CastToItkImage( image, itkTransformImage );
typedef itk::ConstantPadImageFilter< ImageType, PADOutputImageType > PadFilterType;
PadFilterType::Pointer padFilter = PadFilterType::New();
unsigned long upperPad[3];
unsigned long lowerPad[3];
int borderLiner = 6;
mitk::Point3D mitkOriginPoint;
double origin[3];
origin[0]=0;
origin[1]=0;
origin[2]=0;
itkTransformImage->SetOrigin(origin);
lowerPad[0]=borderLiner/2;
lowerPad[1]=borderLiner/2;
lowerPad[2]=borderLiner/2;
upperPad[0]=borderLiner/2;
upperPad[1]=borderLiner/2;
upperPad[2]=borderLiner/2;
padFilter->SetInput(itkTransformImage);
padFilter->SetConstant(0);
padFilter->SetPadUpperBound(upperPad);
padFilter->SetPadLowerBound(lowerPad);
padFilter->UpdateLargestPossibleRegion();
mitk::Image::Pointer segmentationImage = mitk::Image::New();
mitk::CastToMitkImage(padFilter->GetOutput(), segmentationImage);
segmentationImage->SetGeometry(image->GetGeometry());
return segmentationImage;
}
<commit_msg>FIX (#3263): fixed offset problem due to padding, geometry is now also translated<commit_after>
#include "QmitkSegmentationPostProcessing.h"
#include "QmitkNodeDescriptorManager.h"
#include "QmitkToolGUI.h"
#include "mitkAutoCropImageFilter.h"
#include "mitkBinaryThresholdTool.h"
#include "mitkRenderingManager.h"
#include "mitkShowSegmentationAsSurface.h"
#include "mitkProgressBar.h"
#include "mitkStatusBar.h"
#include "mitkImageCast.h"
#include "mitkDataNodeObject.h"
#include <QtGui>
#include <berryIWorkbenchPage.h>
#include <itkConstantPadImageFilter.h>
QmitkSegmentationPostProcessing::QmitkSegmentationPostProcessing(mitk::DataStorage* storage, QmitkFunctionality* functionality, QObject* parent)
:QObject(parent)
,m_BlueBerryView(functionality)
,m_DataStorage(storage)
{
// register a couple of additional actions for DataManager's context menu
QmitkNodeDescriptor* imageDataNodeDescriptor =
QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("Image");
if (imageDataNodeDescriptor)
{
m_ThresholdAction = new QAction("Threshold..", parent);
imageDataNodeDescriptor->AddAction(m_ThresholdAction);
connect( m_ThresholdAction, SIGNAL( triggered(bool) ) , this, SLOT( ThresholdImage(bool) ) );
}
else
{
MITK_WARN << "Could not get datamanager's node descriptor for 'Image'";
}
// register a couple of additional actions for DataManager's context menu
QmitkNodeDescriptor* binaryImageDataNodeDescriptor =
QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("ImageMask");
if (binaryImageDataNodeDescriptor)
{
m_CreateSurfaceAction = new QAction("Create polygon model", parent);
binaryImageDataNodeDescriptor->AddAction(m_CreateSurfaceAction);
connect( m_CreateSurfaceAction, SIGNAL( triggered(bool) ) , this, SLOT( CreateSurface(bool) ) );
m_CreateSmoothSurfaceAction = new QAction("Create smoothed polygon model", parent);
binaryImageDataNodeDescriptor->AddAction(m_CreateSmoothSurfaceAction);
connect( m_CreateSmoothSurfaceAction, SIGNAL( triggered(bool) ) , this, SLOT( CreateSmoothedSurface(bool) ) );
m_StatisticsAction = new QAction("Statistics", parent);
binaryImageDataNodeDescriptor->AddAction(m_StatisticsAction);
connect( m_StatisticsAction, SIGNAL( triggered(bool) ) , this, SLOT( ImageStatistics(bool) ) );
m_AutocropAction = new QAction("Autocrop", parent);
binaryImageDataNodeDescriptor->AddAction(m_AutocropAction);
connect( m_AutocropAction, SIGNAL( triggered(bool) ) , this, SLOT( AutocropSelected(bool) ) );
}
else
{
MITK_WARN << "Could not get datamanager's node descriptor for 'ImageMask'";
}
// register for blueberry selection events
m_SelectionListener = berry::ISelectionListener::Pointer(new berry::SelectionChangedAdapter<QmitkSegmentationPostProcessing>(this, &QmitkSegmentationPostProcessing::SelectionChanged));
m_BlueBerryView->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelectionListener);
}
QmitkSegmentationPostProcessing::~QmitkSegmentationPostProcessing()
{
berry::ISelectionService* s = m_BlueBerryView->GetSite()->GetWorkbenchWindow()->GetSelectionService();
if(s)
{
s->RemovePostSelectionListener(m_SelectionListener);
}
// unregister a couple of additional actions for DataManager's context menu
QmitkNodeDescriptor* imageDataNodeDescriptor =
QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("Image");
if (imageDataNodeDescriptor)
{
imageDataNodeDescriptor->RemoveAction( m_ThresholdAction );
}
else
{
MITK_WARN << "Could not get datamanager's node descriptor for 'Image'";
}
// unregister a couple of additional actions for DataManager's context menu
QmitkNodeDescriptor* binaryImageDataNodeDescriptor =
QmitkNodeDescriptorManager::GetInstance()->GetDescriptor("ImageMask");
if (binaryImageDataNodeDescriptor)
{
binaryImageDataNodeDescriptor->RemoveAction( m_CreateSurfaceAction );
binaryImageDataNodeDescriptor->RemoveAction( m_CreateSmoothSurfaceAction );
binaryImageDataNodeDescriptor->RemoveAction( m_StatisticsAction );
binaryImageDataNodeDescriptor->RemoveAction( m_AutocropAction );
}
else
{
MITK_WARN << "Could not get datamanager's node descriptor for 'ImageMask'";
}
}
void QmitkSegmentationPostProcessing::SelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, berry::ISelection::ConstPointer selection)
{
if ( selection.IsNull() )
{
return;
}
// save current selection in member variable
m_CurrentSelection = selection.Cast<const mitk::DataNodeSelection>();
}
QmitkSegmentationPostProcessing::NodeList QmitkSegmentationPostProcessing::GetSelectedNodes() const
{
NodeList result;
if (m_CurrentSelection)
{
// iterate selection
for (mitk::DataNodeSelection::iterator i = m_CurrentSelection->Begin(); i != m_CurrentSelection->End(); ++i)
{
// extract datatree node
if (mitk::DataNodeObject::Pointer nodeObj = i->Cast<mitk::DataNodeObject>())
{
mitk::DataNode::Pointer node = nodeObj->GetDataNode();
result.push_back( node );
}
}
}
return result;
}
void QmitkSegmentationPostProcessing::ThresholdImage(bool)
{
NodeList selection = this->GetSelectedNodes();
m_ThresholdingToolManager = mitk::ToolManager::New( m_DataStorage );
m_ThresholdingToolManager->RegisterClient();
m_ThresholdingToolManager->ActiveToolChanged +=
mitk::MessageDelegate<QmitkSegmentationPostProcessing>( this, &QmitkSegmentationPostProcessing::OnThresholdingToolManagerToolModified );
m_ThresholdingDialog = new QDialog(NULL);
connect( m_ThresholdingDialog, SIGNAL(finished(int)), this, SLOT(ThresholdingDone(int)) );
QVBoxLayout* layout = new QVBoxLayout;
layout->setContentsMargins(0, 0, 0, 0);
mitk::Tool* tool = m_ThresholdingToolManager->GetToolById( m_ThresholdingToolManager->GetToolIdByToolType<mitk::BinaryThresholdTool>() );
if (tool)
{
itk::Object::Pointer possibleGUI = tool->GetGUI("Qmitk", "GUI");
QmitkToolGUI* gui = dynamic_cast<QmitkToolGUI*>( possibleGUI.GetPointer() );
if (gui)
{
gui->SetTool(tool);
gui->setParent(m_ThresholdingDialog);
layout->addWidget(gui);
m_ThresholdingDialog->setLayout(layout);
layout->activate();
m_ThresholdingDialog->setFixedSize(300,50);
m_ThresholdingDialog->open();
}
}
for ( NodeList::iterator iter = selection.begin(); iter != selection.end(); ++iter )
{
mitk::DataNode* node = *iter;
if (node)
{
m_ThresholdingToolManager->SetReferenceData( node );
m_ThresholdingToolManager->ActivateTool( m_ThresholdingToolManager->GetToolIdByToolType<mitk::BinaryThresholdTool>() );
}
}
}
void QmitkSegmentationPostProcessing::ThresholdingDone(int)
{
MITK_INFO << "Thresholding done, cleaning up";
m_ThresholdingDialog->deleteLater();
m_ThresholdingDialog = NULL;
m_ThresholdingToolManager->SetReferenceData( NULL );
m_ThresholdingToolManager->SetWorkingData( NULL );
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkSegmentationPostProcessing::OnThresholdingToolManagerToolModified()
{
if ( m_ThresholdingToolManager.IsNull() ) return;
//MITK_INFO << "Now got tool " << m_ThresholdingToolManager->GetActiveToolID();
if ( m_ThresholdingToolManager->GetActiveToolID() < 0)
{
if (m_ThresholdingDialog)
m_ThresholdingDialog->accept();
}
}
void QmitkSegmentationPostProcessing::CreateSmoothedSurface(bool)
{
InternalCreateSurface(true);
}
void QmitkSegmentationPostProcessing::CreateSurface(bool)
{
InternalCreateSurface(false);
}
void QmitkSegmentationPostProcessing::InternalCreateSurface(bool smoothed)
{
NodeList selection = this->GetSelectedNodes();
for ( NodeList::iterator iter = selection.begin(); iter != selection.end(); ++iter )
{
mitk::DataNode* node = *iter;
if (node)
{
mitk::Image::Pointer image = dynamic_cast<mitk::Image*>( node->GetData() );
if (image.IsNull()) return;
try
{
mitk::ShowSegmentationAsSurface::Pointer surfaceFilter = mitk::ShowSegmentationAsSurface::New();
// attach observer to get notified about result
itk::SimpleMemberCommand<QmitkSegmentationPostProcessing>::Pointer goodCommand = itk::SimpleMemberCommand<QmitkSegmentationPostProcessing>::New();
goodCommand->SetCallbackFunction(this, &QmitkSegmentationPostProcessing::OnSurfaceCalculationDone);
surfaceFilter->AddObserver(mitk::ResultAvailable(), goodCommand);
itk::SimpleMemberCommand<QmitkSegmentationPostProcessing>::Pointer badCommand = itk::SimpleMemberCommand<QmitkSegmentationPostProcessing>::New();
badCommand->SetCallbackFunction(this, &QmitkSegmentationPostProcessing::OnSurfaceCalculationDone);
surfaceFilter->AddObserver(mitk::ProcessingError(), badCommand);
mitk::DataNode::Pointer nodepointer = node;
surfaceFilter->SetPointerParameter("Input", image);
surfaceFilter->SetPointerParameter("Group node", nodepointer);
surfaceFilter->SetParameter("Show result", true );
surfaceFilter->SetParameter("Sync visibility", false );
surfaceFilter->SetDataStorage( *m_DataStorage );
if (smoothed)
{
surfaceFilter->SetParameter("Smooth", true );
//surfaceFilter->SetParameter("Apply median", true );
surfaceFilter->SetParameter("Apply median", false ); // median makes the resulting surfaces look like lego models
surfaceFilter->SetParameter("Median kernel size", 3u );
surfaceFilter->SetParameter("Gaussian SD", 2.5f );
surfaceFilter->SetParameter("Decimate mesh", true );
surfaceFilter->SetParameter("Decimation rate", 0.80f );
}
else
{
surfaceFilter->SetParameter("Smooth", false );
surfaceFilter->SetParameter("Apply median", false );
surfaceFilter->SetParameter("Median kernel size", 3u );
surfaceFilter->SetParameter("Gaussian SD", 1.5f );
surfaceFilter->SetParameter("Decimate mesh", true );
surfaceFilter->SetParameter("Decimation rate", 0.8f );
}
mitk::ProgressBar::GetInstance()->AddStepsToDo(10);
mitk::ProgressBar::GetInstance()->Progress(2);
mitk::StatusBar::GetInstance()->DisplayText("Surface creation started in background...");
surfaceFilter->StartAlgorithm();
}
catch(...)
{
MITK_ERROR << "surface creation filter had an error";
}
}
else
{
MITK_INFO << " a NULL node selected";
}
}
}
void QmitkSegmentationPostProcessing::OnSurfaceCalculationDone()
{
mitk::ProgressBar::GetInstance()->Progress(8);
}
void QmitkSegmentationPostProcessing::ImageStatistics(bool)
{
if (m_BlueBerryView)
{
m_BlueBerryView->GetSite()->GetWorkbenchWindow()->GetActivePage()->ShowView("org.mitk.views.imagestatistics");
}
}
void QmitkSegmentationPostProcessing::AutocropSelected(bool)
{
NodeList selection = this->GetSelectedNodes();
for ( NodeList::iterator iter = selection.begin(); iter != selection.end(); ++iter )
{
mitk::DataNode* node = *iter;
if (node)
{
mitk::Image::Pointer image = dynamic_cast<mitk::Image*>( node->GetData() );
if (image.IsNull()) return;
mitk::ProgressBar::GetInstance()->AddStepsToDo(10);
mitk::ProgressBar::GetInstance()->Progress(2);
qApp->processEvents();
mitk::AutoCropImageFilter::Pointer cropFilter = mitk::AutoCropImageFilter::New();
cropFilter->SetInput( image );
cropFilter->SetBackgroundValue( 0 );
try
{
cropFilter->Update();
image = cropFilter->GetOutput();
if (image.IsNotNull())
{
node->SetData( this->IncreaseCroppedImageSize(image) ); // bug fix 3145
}
}
catch(...)
{
MITK_ERROR << "Cropping image failed...";
}
mitk::ProgressBar::GetInstance()->Progress(8);
}
else
{
MITK_INFO << " a NULL node selected";
}
}
}
mitk::Image::Pointer QmitkSegmentationPostProcessing::IncreaseCroppedImageSize( mitk::Image::Pointer image )
{
typedef itk::Image< short, 3 > ImageType;
typedef itk::Image< unsigned char, 3 > PADOutputImageType;
ImageType::Pointer itkTransformImage = ImageType::New();
mitk::CastToItkImage( image, itkTransformImage );
typedef itk::ConstantPadImageFilter< ImageType, PADOutputImageType > PadFilterType;
PadFilterType::Pointer padFilter = PadFilterType::New();
unsigned long upperPad[3];
unsigned long lowerPad[3];
int borderLiner = 6;
mitk::Point3D mitkOriginPoint;
double origin[3];
origin[0]=0;
origin[1]=0;
origin[2]=0;
itkTransformImage->SetOrigin(origin);
lowerPad[0]=borderLiner/2;
lowerPad[1]=borderLiner/2;
lowerPad[2]=borderLiner/2;
upperPad[0]=borderLiner/2;
upperPad[1]=borderLiner/2;
upperPad[2]=borderLiner/2;
padFilter->SetInput(itkTransformImage);
padFilter->SetConstant(0);
padFilter->SetPadUpperBound(upperPad);
padFilter->SetPadLowerBound(lowerPad);
padFilter->UpdateLargestPossibleRegion();
mitk::Image::Pointer paddedImage = mitk::Image::New();
mitk::CastToMitkImage(padFilter->GetOutput(), paddedImage);
paddedImage->SetGeometry(image->GetGeometry());
//calculate translation vector according to padding to get the new origin
mitk::Vector3D transVector = image->GetGeometry()->GetSpacing();
transVector[0] = -(borderLiner/2);
transVector[1] = -(borderLiner/2);
transVector[2] = -(borderLiner/2);
mitk::Vector3D newTransVectorInmm = image->GetGeometry()->GetSpacing();
image->GetGeometry()->IndexToWorld(mitkOriginPoint, transVector, newTransVectorInmm);
paddedImage->GetGeometry()->Translate(newTransVectorInmm);
//paddedImage->SetRequestedRegionToLargestPossibleRegion();
return paddedImage;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#include "test.hpp"
#include <array>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <miopen/convolution.hpp>
#include <miopen/miopen.h>
#include <miopen/tensor.hpp>
#include <miopen/tensor_ops.hpp>
#include <utility>
#include "driver.hpp"
#include "get_handle.hpp"
#include "tensor_holder.hpp"
#include "verify.hpp"
#define MIO_OPS_DEBUG 0
template <class T>
struct tensor_ops_base
{
tensor<T> a;
tensor<T> b;
tensor<T> c;
void fail(float = 0)
{
std::cout << "A tensor: " << a.desc.ToString() << std::endl;
std::cout << "B tensor: " << b.desc.ToString() << std::endl;
std::cout << "C tensor: " << a.desc.ToString() << std::endl;
}
};
template <class T>
struct verify_tensor_ops : tensor_ops_base<T>
{
using tensor_ops_base<T>::a;
using tensor_ops_base<T>::b;
using tensor_ops_base<T>::c;
int Aoffset;
int Boffset;
int Coffset;
float alpha;
float beta;
verify_tensor_ops(const tensor<T>& pa,
const tensor<T>& pb,
const tensor<T>& pc,
std::vector<size_t>& offsets,
float palpha = 1,
float pbeta = 1)
{
a = pa;
b = pb;
c = pc;
Aoffset = offsets[0];
Boffset = offsets[1];
Coffset = offsets[2];
alpha = palpha;
beta = pbeta;
}
// verify_tensor_ops(const tensor<T>& pa, const tensor<T>& pb, const tensor<T>& pc, const
// std::vector<T>& dims)
//{
// a = pa(dims);
// b = pb(dims);
// c = pc(dims);
//}
T add_elem(T aelem, T belem) { return aelem + belem; }
T mul_elem(T aelem, T belem) { return aelem * belem; }
void tensor_for_loop(const tensor<T>& aten,
const tensor<T>& bten,
tensor<T>& cten,
const std::vector<size_t>& a_dims,
const std::vector<size_t>& b_dims,
float palpha,
float pbeta,
int recurr_aoffset,
int recurr_boffset,
int recurr_coffset,
int dim,
int AtenOffset,
int BtenOffset,
int CtenOffset)
{
int astride = aten.desc.GetStrides()[dim];
int bstride = bten.desc.GetStrides()[dim];
int cstride = cten.desc.GetStrides()[dim];
// printf("cstride: %d\n", cstride);
for(int idx = 0; idx < a_dims[dim]; idx++)
{
size_t aindex = recurr_aoffset + astride * idx;
size_t cindex = recurr_coffset + cstride * idx;
size_t bindex =
(b_dims[dim] == a_dims[dim]) ? recurr_boffset + bstride * idx : recurr_boffset;
// if((bindex < bten.desc.GetElementSize()) && (dim == a_dims.size() - 1))
if(dim == (a_dims.size() - 1))
{
#if(MIO_OPS_DEBUG)
printf("c[%lu](%f) = a[%lu](%f) + b[%lu](%f)\n",
cindex + CtenOffset,
cten[cindex + CtenOffset],
aindex + AtenOffset,
aten[aindex + AtenOffset],
bindex + Boffset,
bten[bindex + Boffset]);
#endif
cten[cindex + CtenOffset] =
add_elem(aten[aindex + AtenOffset], bten[bindex + BtenOffset]) * palpha +
pbeta * cten[cindex + Coffset];
}
if(dim < (a_dims.size() - 1))
{
tensor_for_loop(aten,
bten,
cten,
a_dims,
b_dims,
palpha,
pbeta,
aindex,
bindex,
cindex,
dim + 1,
AtenOffset,
BtenOffset,
CtenOffset);
}
}
return;
}
tensor<T> cpu()
{
std::fill(c.begin(), c.end(), 1);
auto clens = c.desc.GetLengths();
auto blens = b.desc.GetLengths();
auto bstrides = b.desc.GetStrides();
auto cstrides = c.desc.GetStrides();
// float alpha = -1, beta = 1;
tensor_for_loop(a, b, c, clens, blens, alpha, beta, 0, 0, 0, 0, Aoffset, Boffset, Coffset);
#if(MIO_OPS_DEBUG)
for(int i = 0; i < c.desc.GetElementSize(); i++)
printf("CPU_C[%d]: %f\n", i, c.data[i]);
#endif
return c;
}
tensor<T> gpu()
{
auto&& handle = get_handle();
// return c;
std::fill(c.begin(), c.end(), 1);
auto c_dev = handle.Write(c.data);
auto a_dev = handle.Write(a.data);
auto b_dev = handle.Write(b.data);
// float alpha1 = -1, alpha2 = 1, beta = 1;
miopen::OpTensor(handle,
miopenTensorOpAdd,
// miopenTensorOpMul,
&alpha,
a.desc,
a_dev.get(),
NULL,
b.desc,
b_dev.get(),
&beta,
c.desc,
c_dev.get(),
Aoffset,
Boffset,
Coffset);
c.data = handle.Read<T>(c_dev, c.data.size());
#if(MIO_OPS_DEBUG)
handle.Finish();
auto clens = c.desc.GetLengths();
auto cstrides = c.desc.GetStrides();
for(int i = 0; i < c.desc.GetElementSize(); i++)
printf("GPU_C[%d]: %f\n", i, c.data[i]);
#endif
return c;
}
void fail(float = 0)
{
std::cout << "TensorOp: " << std::endl;
this->tensor_ops_base<T>::fail();
}
};
template <class T>
struct tensor_ops_driver : test_driver
{
tensor<T> super_a;
tensor<T> super_b;
tensor<T> super_c;
// tensor<T> a;
// tensor<T> b;
// tensor<T> c;
tensor_ops_driver()
{
add(super_a, "super_a", generate_tensor(get_super_tensor(), {40, 10, 8, 20, 4}));
add(super_b, "super_b", generate_tensor(get_super_tensor(), {40, 10, 8, 20, 4}));
add(super_c, "super_c", generate_tensor(get_super_tensor(), {40, 10, 8, 20, 4}));
}
std::set<std::vector<int>> get_super_tensor()
{
std::vector<std::vector<int>> a_dims{
{40, 10, 8, 20, 4},
};
return (std::set<std::vector<int>>(a_dims.begin(), a_dims.end()));
}
std::vector<tensor<T>> get_subtensors()
{
std::vector<tensor<T>> tensorList;
unsigned int num_tensor_per_dims_size = 8;
std::vector<std::vector<int>> lens{
{32, 8, 8, 16, 4},
{32, 4, 4, 8, 2},
{16, 8, 4, 16, 2},
{16, 2, 8, 4, 4},
{8, 2, 8, 4, 4},
{8, 8, 8, 4, 4},
{4, 2, 4, 8, 2},
{1, 8, 4, 8, 2}, // 5d
{8, 1, 16, 4},
{4, 2, 8, 2},
{8, 4, 16, 2},
{2, 8, 4, 4},
{2, 2, 8, 4},
{8, 8, 4, 4},
{1, 4, 8, 2},
{1, 1, 8, 2}, // 4d
{8, 16, 4},
{4, 8, 2},
{4, 16, 2},
{8, 1, 4},
{8, 2, 4},
{8, 4, 4},
{4, 8, 2},
{1, 8, 2}, // 3d
{16, 4},
{8, 2},
{16, 2},
{4, 4},
{2, 4},
{4, 1},
{8, 2},
{1, 4}, // 2d
};
std::vector<std::vector<int>> strides{
{6400, 640, 80, 4, 1}, {640, 80, 4, 1}, {80, 4, 1}, {4, 1},
};
for(int i = 0; i < lens.size(); i++)
{
tensorList.push_back(
make_tensor<T, int>(super_a, lens[i], strides[i / num_tensor_per_dims_size]));
}
return tensorList;
}
void run()
{
std::vector<tensor<T>> aTensorList = get_subtensors();
std::vector<tensor<T>> bTensorList = get_subtensors();
std::vector<tensor<T>> cTensorList = get_subtensors();
std::vector<std::vector<size_t>> offsetList = {{32, 16, 1}, {16, 32, 1}};
std::vector<std::vector<float>> alphaBetaList = {{1, 1}, {-1, 1}, {0, 0}, {-1.5, 0.5}};
for(int i = 0; i < aTensorList.size(); i++)
if(aTensorList[i].desc.GetSize() == bTensorList[i].desc.GetSize())
{
for(int j = 0; j < offsetList.size(); j++)
{
for(int k = 0; k < alphaBetaList.size(); k++)
verify(verify_tensor_ops<T>{aTensorList[i],
bTensorList[i],
cTensorList[i],
offsetList[j],
alphaBetaList[k][0],
alphaBetaList[k][1]});
}
}
}
};
int main(int argc, const char* argv[]) { test_drive<tensor_ops_driver<float>>(argc, argv); }
<commit_msg>tidy fix<commit_after>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#include "test.hpp"
#include <array>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <miopen/convolution.hpp>
#include <miopen/miopen.h>
#include <miopen/tensor.hpp>
#include <miopen/tensor_ops.hpp>
#include <utility>
#include "driver.hpp"
#include "get_handle.hpp"
#include "tensor_holder.hpp"
#include "verify.hpp"
#define MIO_OPS_DEBUG 0
template <class T>
struct tensor_ops_base
{
tensor<T> a;
tensor<T> b;
tensor<T> c;
void fail(float = 0)
{
std::cout << "A tensor: " << a.desc.ToString() << std::endl;
std::cout << "B tensor: " << b.desc.ToString() << std::endl;
std::cout << "C tensor: " << a.desc.ToString() << std::endl;
}
};
template <class T>
struct verify_tensor_ops : tensor_ops_base<T>
{
using tensor_ops_base<T>::a;
using tensor_ops_base<T>::b;
using tensor_ops_base<T>::c;
int Aoffset;
int Boffset;
int Coffset;
float alpha;
float beta;
verify_tensor_ops(const tensor<T>& pa,
const tensor<T>& pb,
const tensor<T>& pc,
std::vector<size_t>& offsets,
float palpha = 1,
float pbeta = 1)
{
a = pa;
b = pb;
c = pc;
Aoffset = offsets[0];
Boffset = offsets[1];
Coffset = offsets[2];
alpha = palpha;
beta = pbeta;
}
// verify_tensor_ops(const tensor<T>& pa, const tensor<T>& pb, const tensor<T>& pc, const
// std::vector<T>& dims)
//{
// a = pa(dims);
// b = pb(dims);
// c = pc(dims);
//}
T add_elem(T aelem, T belem) { return aelem + belem; }
T mul_elem(T aelem, T belem) { return aelem * belem; }
void tensor_for_loop(const tensor<T>& aten,
const tensor<T>& bten,
tensor<T>& cten,
const std::vector<size_t>& a_dims,
const std::vector<size_t>& b_dims,
float palpha,
float pbeta,
int recurr_aoffset,
int recurr_boffset,
int recurr_coffset,
int dim,
int AtenOffset,
int BtenOffset,
int CtenOffset)
{
int astride = aten.desc.GetStrides()[dim];
int bstride = bten.desc.GetStrides()[dim];
int cstride = cten.desc.GetStrides()[dim];
// printf("cstride: %d\n", cstride);
for(int idx = 0; idx < a_dims[dim]; idx++)
{
size_t aindex = recurr_aoffset + astride * idx;
size_t cindex = recurr_coffset + cstride * idx;
size_t bindex =
(b_dims[dim] == a_dims[dim]) ? recurr_boffset + bstride * idx : recurr_boffset;
// if((bindex < bten.desc.GetElementSize()) && (dim == a_dims.size() - 1))
if(dim == (a_dims.size() - 1))
{
#if(MIO_OPS_DEBUG)
printf("c[%lu](%f) = a[%lu](%f) + b[%lu](%f)\n",
cindex + CtenOffset,
cten[cindex + CtenOffset],
aindex + AtenOffset,
aten[aindex + AtenOffset],
bindex + Boffset,
bten[bindex + Boffset]);
#endif
cten[cindex + CtenOffset] =
add_elem(aten[aindex + AtenOffset], bten[bindex + BtenOffset]) * palpha +
pbeta * cten[cindex + Coffset];
}
if(dim < (a_dims.size() - 1))
{
tensor_for_loop(aten,
bten,
cten,
a_dims,
b_dims,
palpha,
pbeta,
aindex,
bindex,
cindex,
dim + 1,
AtenOffset,
BtenOffset,
CtenOffset);
}
}
return;
}
tensor<T> cpu()
{
std::fill(c.begin(), c.end(), 1);
auto clens = c.desc.GetLengths();
auto blens = b.desc.GetLengths();
auto bstrides = b.desc.GetStrides();
auto cstrides = c.desc.GetStrides();
// float alpha = -1, beta = 1;
tensor_for_loop(a, b, c, clens, blens, alpha, beta, 0, 0, 0, 0, Aoffset, Boffset, Coffset);
#if(MIO_OPS_DEBUG)
for(int i = 0; i < c.desc.GetElementSize(); i++)
printf("CPU_C[%d]: %f\n", i, c.data[i]);
#endif
return c;
}
tensor<T> gpu()
{
auto&& handle = get_handle();
// return c;
std::fill(c.begin(), c.end(), 1);
auto c_dev = handle.Write(c.data);
auto a_dev = handle.Write(a.data);
auto b_dev = handle.Write(b.data);
float alpha2 = 1;
miopen::OpTensor(handle,
miopenTensorOpAdd,
// miopenTensorOpMul,
&alpha,
a.desc,
a_dev.get(),
&alpha2,
b.desc,
b_dev.get(),
&beta,
c.desc,
c_dev.get(),
Aoffset,
Boffset,
Coffset);
c.data = handle.Read<T>(c_dev, c.data.size());
#if(MIO_OPS_DEBUG)
handle.Finish();
auto clens = c.desc.GetLengths();
auto cstrides = c.desc.GetStrides();
for(int i = 0; i < c.desc.GetElementSize(); i++)
printf("GPU_C[%d]: %f\n", i, c.data[i]);
#endif
return c;
}
void fail(float = 0)
{
std::cout << "TensorOp: " << std::endl;
this->tensor_ops_base<T>::fail();
}
};
template <class T>
struct tensor_ops_driver : test_driver
{
tensor<T> super_a;
tensor<T> super_b;
tensor<T> super_c;
// tensor<T> a;
// tensor<T> b;
// tensor<T> c;
tensor_ops_driver()
{
add(super_a, "super_a", generate_tensor(get_super_tensor(), {40, 10, 8, 20, 4}));
add(super_b, "super_b", generate_tensor(get_super_tensor(), {40, 10, 8, 20, 4}));
add(super_c, "super_c", generate_tensor(get_super_tensor(), {40, 10, 8, 20, 4}));
}
std::set<std::vector<int>> get_super_tensor()
{
std::vector<std::vector<int>> a_dims{
{40, 10, 8, 20, 4},
};
return (std::set<std::vector<int>>(a_dims.begin(), a_dims.end()));
}
std::vector<tensor<T>> get_subtensors()
{
std::vector<tensor<T>> tensorList;
unsigned int num_tensor_per_dims_size = 8;
std::vector<std::vector<int>> lens{
{32, 8, 8, 16, 4},
{32, 4, 4, 8, 2},
{16, 8, 4, 16, 2},
{16, 2, 8, 4, 4},
{8, 2, 8, 4, 4},
{8, 8, 8, 4, 4},
{4, 2, 4, 8, 2},
{1, 8, 4, 8, 2}, // 5d
{8, 1, 16, 4},
{4, 2, 8, 2},
{8, 4, 16, 2},
{2, 8, 4, 4},
{2, 2, 8, 4},
{8, 8, 4, 4},
{1, 4, 8, 2},
{1, 1, 8, 2}, // 4d
{8, 16, 4},
{4, 8, 2},
{4, 16, 2},
{8, 1, 4},
{8, 2, 4},
{8, 4, 4},
{4, 8, 2},
{1, 8, 2}, // 3d
{16, 4},
{8, 2},
{16, 2},
{4, 4},
{2, 4},
{4, 1},
{8, 2},
{1, 4}, // 2d
};
std::vector<std::vector<int>> strides{
{6400, 640, 80, 4, 1}, {640, 80, 4, 1}, {80, 4, 1}, {4, 1},
};
for(int i = 0; i < lens.size(); i++)
{
tensorList.push_back(
make_tensor<T, int>(super_a, lens[i], strides[i / num_tensor_per_dims_size]));
}
return tensorList;
}
void run()
{
std::vector<tensor<T>> aTensorList = get_subtensors();
std::vector<tensor<T>> bTensorList = get_subtensors();
std::vector<tensor<T>> cTensorList = get_subtensors();
std::vector<std::vector<size_t>> offsetList = {{32, 16, 1}, {16, 32, 1}};
std::vector<std::vector<float>> alphaBetaList = {{1, 1}, {-1, 1}, {0, 0}, {-1.5, 0.5}};
for(int i = 0; i < aTensorList.size(); i++)
if(aTensorList[i].desc.GetSize() == bTensorList[i].desc.GetSize())
{
for(int j = 0; j < offsetList.size(); j++)
{
for(int k = 0; k < alphaBetaList.size(); k++)
verify(verify_tensor_ops<T>{aTensorList[i],
bTensorList[i],
cTensorList[i],
offsetList[j],
alphaBetaList[k][0],
alphaBetaList[k][1]});
}
}
}
};
int main(int argc, const char* argv[]) { test_drive<tensor_ops_driver<float>>(argc, argv); }
<|endoftext|> |
<commit_before>/*
* test-lexer.cpp
*
* Created on: Jun 16, 2019
* Author: iconmaster
*/
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include "ccl/lexer.hpp"
using namespace std;
using namespace ccl;
static string location = "TEST LOCATION";
namespace std {
ostream& operator<<(ostream& os, const Token::Type t) {
os << (void*) t;
return os;
}
}
BOOST_AUTO_TEST_SUITE(lexer);
BOOST_AUTO_TEST_CASE(oneWord) {
Lexer lexer{location, "hello"};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "hello");
BOOST_CHECK_EQUAL(*t.source.location, location);
BOOST_CHECK_EQUAL(t.source.line, 1);
BOOST_CHECK_EQUAL(t.source.col, 1);
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(twoWords) {
Lexer lexer{location, "hello world"};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "hello");
BOOST_CHECK_EQUAL(*t.source.location, location);
BOOST_CHECK_EQUAL(t.source.line, 1);
BOOST_CHECK_EQUAL(t.source.col, 1);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "world");
BOOST_CHECK_EQUAL(*t.source.location, location);
BOOST_CHECK_EQUAL(t.source.line, 1);
BOOST_CHECK_EQUAL(t.source.col, 7);
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(locationsMultiline) {
Lexer lexer{location, "a\nb c\nd"};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.source.line, 1);
BOOST_CHECK_EQUAL(t.source.col, 1);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.source.line, 2);
BOOST_CHECK_EQUAL(t.source.col, 1);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.source.line, 2);
BOOST_CHECK_EQUAL(t.source.col, 3);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.source.line, 3);
BOOST_CHECK_EQUAL(t.source.col, 1);
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(leadingWhitespace) {
Lexer lexer{location, " hello"};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "hello");
BOOST_CHECK_EQUAL(*t.source.location, location);
BOOST_CHECK_EQUAL(t.source.line, 1);
BOOST_CHECK_EQUAL(t.source.col, 4);
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(trailingWhitespace) {
Lexer lexer{location, "hello "};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "hello");
BOOST_CHECK_EQUAL(*t.source.location, location);
BOOST_CHECK_EQUAL(t.source.line, 1);
BOOST_CHECK_EQUAL(t.source.col, 1);
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(flagEdgeCases) {
Lexer lexer{location, "--a -a-b -a- -1 - -. -.1 -1.a -a.1 a- a-b"};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::FLAG);
BOOST_CHECK_EQUAL(t.value, "-a");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::FLAG);
BOOST_CHECK_EQUAL(t.value, "a-b");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::FLAG);
BOOST_CHECK_EQUAL(t.value, "a-");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "-1");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "-");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::FLAG);
BOOST_CHECK_EQUAL(t.value, ".");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "-.1");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::FLAG);
BOOST_CHECK_EQUAL(t.value, "1.a");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::FLAG);
BOOST_CHECK_EQUAL(t.value, "a.1");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "a-");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "a-b");
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(varEdgeCase) {
Lexer lexer{location, "$ $-a $a- $$a $a$ a$ a$b"};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "$");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::VAR);
BOOST_CHECK_EQUAL(t.value, "-a");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::VAR);
BOOST_CHECK_EQUAL(t.value, "a-");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::VAR);
BOOST_CHECK_EQUAL(t.value, "$a");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::VAR);
BOOST_CHECK_EQUAL(t.value, "a$");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "a$");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "a$b");
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(everyToken) {
Lexer lexer{location, "a -f 'x' | $g \"y\" & [(...)]{};"};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "a");
BOOST_CHECK_EQUAL(t.source.col, 1);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::FLAG);
BOOST_CHECK_EQUAL(t.value, "f");
BOOST_CHECK_EQUAL(t.source.col, 3);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::STRING);
BOOST_CHECK_EQUAL(t.value, "x");
BOOST_CHECK_EQUAL(t.source.col, 6);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::PIPE);
BOOST_CHECK_EQUAL(t.value, "|");
BOOST_CHECK_EQUAL(t.source.col, 10);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::VAR);
BOOST_CHECK_EQUAL(t.value, "g");
BOOST_CHECK_EQUAL(t.source.col, 12);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::EX_STRING);
BOOST_CHECK_EQUAL(t.value, "y");
BOOST_CHECK_EQUAL(t.source.col, 15);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::AND);
BOOST_CHECK_EQUAL(t.value, "&");
BOOST_CHECK_EQUAL(t.source.col, 19);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::LBRACKET);
BOOST_CHECK_EQUAL(t.value, "[");
BOOST_CHECK_EQUAL(t.source.col, 21);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::LPAREN);
BOOST_CHECK_EQUAL(t.value, "(");
BOOST_CHECK_EQUAL(t.source.col, 22);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::ELLIPSES);
BOOST_CHECK_EQUAL(t.value, "...");
BOOST_CHECK_EQUAL(t.source.col, 23);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::RPAREN);
BOOST_CHECK_EQUAL(t.value, ")");
BOOST_CHECK_EQUAL(t.source.col, 26);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::RBRACKET);
BOOST_CHECK_EQUAL(t.value, "]");
BOOST_CHECK_EQUAL(t.source.col, 27);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::LBRACE);
BOOST_CHECK_EQUAL(t.value, "{");
BOOST_CHECK_EQUAL(t.source.col, 28);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::RBRACE);
BOOST_CHECK_EQUAL(t.value, "}");
BOOST_CHECK_EQUAL(t.source.col, 29);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::SEMICOLON);
BOOST_CHECK_EQUAL(t.value, ";");
BOOST_CHECK_EQUAL(t.source.col, 30);
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Added more lexer tests<commit_after>/*
* test-lexer.cpp
*
* Created on: Jun 16, 2019
* Author: iconmaster
*/
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include <vector>
#include "ccl/lexer.hpp"
using namespace std;
using namespace ccl;
static string location = "TEST LOCATION";
namespace std {
ostream& operator<<(ostream& os, const Token::Type t) {
os << (void*) t;
return os;
}
}
BOOST_AUTO_TEST_SUITE(lexer);
BOOST_AUTO_TEST_CASE(oneWord) {
Lexer lexer{location, "hello"};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "hello");
BOOST_CHECK_EQUAL(*t.source.location, location);
BOOST_CHECK_EQUAL(t.source.line, 1);
BOOST_CHECK_EQUAL(t.source.col, 1);
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(twoWords) {
Lexer lexer{location, "hello world"};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "hello");
BOOST_CHECK_EQUAL(*t.source.location, location);
BOOST_CHECK_EQUAL(t.source.line, 1);
BOOST_CHECK_EQUAL(t.source.col, 1);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "world");
BOOST_CHECK_EQUAL(*t.source.location, location);
BOOST_CHECK_EQUAL(t.source.line, 1);
BOOST_CHECK_EQUAL(t.source.col, 7);
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(locationsMultiline) {
Lexer lexer{location, "a\nb c\nd"};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.source.line, 1);
BOOST_CHECK_EQUAL(t.source.col, 1);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.source.line, 2);
BOOST_CHECK_EQUAL(t.source.col, 1);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.source.line, 2);
BOOST_CHECK_EQUAL(t.source.col, 3);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.source.line, 3);
BOOST_CHECK_EQUAL(t.source.col, 1);
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(leadingWhitespace) {
Lexer lexer{location, " hello"};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "hello");
BOOST_CHECK_EQUAL(*t.source.location, location);
BOOST_CHECK_EQUAL(t.source.line, 1);
BOOST_CHECK_EQUAL(t.source.col, 4);
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(trailingWhitespace) {
Lexer lexer{location, "hello "};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "hello");
BOOST_CHECK_EQUAL(*t.source.location, location);
BOOST_CHECK_EQUAL(t.source.line, 1);
BOOST_CHECK_EQUAL(t.source.col, 1);
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(flagEdgeCases) {
Lexer lexer{location, "--a -a-b -a- -1 - -. -.1 -1.a -a.1 a- a-b"};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::FLAG);
BOOST_CHECK_EQUAL(t.value, "-a");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::FLAG);
BOOST_CHECK_EQUAL(t.value, "a-b");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::FLAG);
BOOST_CHECK_EQUAL(t.value, "a-");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "-1");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "-");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::FLAG);
BOOST_CHECK_EQUAL(t.value, ".");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "-.1");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::FLAG);
BOOST_CHECK_EQUAL(t.value, "1.a");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::FLAG);
BOOST_CHECK_EQUAL(t.value, "a.1");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "a-");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "a-b");
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(varEdgeCase) {
Lexer lexer{location, "$ $-a $a- $$a $a$ a$ a$b"};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "$");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::VAR);
BOOST_CHECK_EQUAL(t.value, "-a");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::VAR);
BOOST_CHECK_EQUAL(t.value, "a-");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::VAR);
BOOST_CHECK_EQUAL(t.value, "$a");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::VAR);
BOOST_CHECK_EQUAL(t.value, "a$");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "a$");
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "a$b");
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(strings) {
Lexer lexer{location, "'' 'a' 'a b' ' ' '\\'' '\"' '\\n' 'a\\nb' '\\\\' '\\$' '\n' 'a\nb'"};
Token t;
vector<string> values{"", "a", "a b", " ", "'", "\"", "\n", "a\nb", "\\", "$", "\n", "a\nb"};
for (const string& s : values) {
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::STRING);
BOOST_CHECK_EQUAL(t.value, s);
}
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(exStrings) {
Lexer lexer{location, "\"\" \"a\" \"a b\" \" \" \"'\" \"\\\"\" \"\\n\" \"a\\nb\" \"\\\\\" \"\\$\" \"\n\" \"a\nb\""};
Token t;
vector<string> values{"", "a", "a b", " ", "'", "\"", "\n", "a\nb", "\\", "$", "\n", "a\nb"};
for (const string& s : values) {
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::EX_STRING);
BOOST_CHECK_EQUAL(t.value, s);
}
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_CASE(everyToken) {
Lexer lexer{location, "a -f 'x' | $g \"y\" & [(...)]{};"};
Token t;
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::WORD);
BOOST_CHECK_EQUAL(t.value, "a");
BOOST_CHECK_EQUAL(t.source.col, 1);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::FLAG);
BOOST_CHECK_EQUAL(t.value, "f");
BOOST_CHECK_EQUAL(t.source.col, 3);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::STRING);
BOOST_CHECK_EQUAL(t.value, "x");
BOOST_CHECK_EQUAL(t.source.col, 6);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::PIPE);
BOOST_CHECK_EQUAL(t.value, "|");
BOOST_CHECK_EQUAL(t.source.col, 10);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::VAR);
BOOST_CHECK_EQUAL(t.value, "g");
BOOST_CHECK_EQUAL(t.source.col, 12);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::EX_STRING);
BOOST_CHECK_EQUAL(t.value, "y");
BOOST_CHECK_EQUAL(t.source.col, 15);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::AND);
BOOST_CHECK_EQUAL(t.value, "&");
BOOST_CHECK_EQUAL(t.source.col, 19);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::LBRACKET);
BOOST_CHECK_EQUAL(t.value, "[");
BOOST_CHECK_EQUAL(t.source.col, 21);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::LPAREN);
BOOST_CHECK_EQUAL(t.value, "(");
BOOST_CHECK_EQUAL(t.source.col, 22);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::ELLIPSES);
BOOST_CHECK_EQUAL(t.value, "...");
BOOST_CHECK_EQUAL(t.source.col, 23);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::RPAREN);
BOOST_CHECK_EQUAL(t.value, ")");
BOOST_CHECK_EQUAL(t.source.col, 26);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::RBRACKET);
BOOST_CHECK_EQUAL(t.value, "]");
BOOST_CHECK_EQUAL(t.source.col, 27);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::LBRACE);
BOOST_CHECK_EQUAL(t.value, "{");
BOOST_CHECK_EQUAL(t.source.col, 28);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::RBRACE);
BOOST_CHECK_EQUAL(t.value, "}");
BOOST_CHECK_EQUAL(t.source.col, 29);
BOOST_CHECK_NO_THROW({
t = lexer.next();
});
BOOST_CHECK_EQUAL(t.type, Token::Type::SEMICOLON);
BOOST_CHECK_EQUAL(t.value, ";");
BOOST_CHECK_EQUAL(t.source.col, 30);
BOOST_CHECK(lexer.done());
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>#include "unittest.hpp"
#include "rice/Class.hpp"
#include "rice/Constructor.hpp"
#include "rice/protect.hpp"
#include "rice/Exception.hpp"
#include "rice/Array.hpp"
#include "rice/String.hpp"
#include "rice/Symbol.hpp"
#include <iostream>
using namespace Rice;
using namespace std;
TESTSUITE(Class);
SETUP(Class)
{
ruby_init();
}
TESTCASE(construct)
{
Class c(rb_cObject);
ASSERT_EQUAL(rb_cObject, c.value());
}
TESTCASE(undef_creation_funcs)
{
Class c(anonymous_class());
Class & c2(c.undef_creation_funcs());
ASSERT_EQUAL(&c, &c2);
ASSERT_EXCEPTION_CHECK(
Exception,
c.call("new"),
ASSERT_EQUAL(
Object(rb_eTypeError), // TODO: 1.6.x?
Object(CLASS_OF(ex.value()))
)
);
}
TESTCASE(include_module)
{
Class c(anonymous_class());
Class & c2(c.include_module(rb_mEnumerable));
ASSERT_EQUAL(&c, &c2);
Array ancestors(c.ancestors());
Array expected_ancestors;
expected_ancestors.push(c);
expected_ancestors.push(Module(rb_mEnumerable));
expected_ancestors.push(Module(rb_cObject));
expected_ancestors.push(Module(rb_mKernel));
#ifdef RUBY_VM
expected_ancestors.push(Module(rb_cBasicObject));
#endif
ASSERT_EQUAL(expected_ancestors, ancestors);
}
TESTCASE(const_set_get_by_id)
{
Class c(anonymous_class());
Object v = to_ruby(42);
Class & c2(c.const_set(rb_intern("FOO"), v));
ASSERT_EQUAL(&c, &c2);
ASSERT_EQUAL(v, c.const_get(rb_intern("FOO")));
}
TESTCASE(const_set_get_by_identifier)
{
Class c(anonymous_class());
Object v = to_ruby(42);
Class & c2(c.const_set(Identifier("FOO"), v));
ASSERT_EQUAL(&c, &c2);
ASSERT_EQUAL(v, c.const_get(Identifier("FOO")));
}
TESTCASE(const_set_get_by_string)
{
Class c(anonymous_class());
Object v = to_ruby(42);
Class & c2(c.const_set("FOO", v));
ASSERT_EQUAL(&c, &c2);
ASSERT_EQUAL(v, c.const_get("FOO"));
}
namespace
{
bool define_method_simple_ok;
void define_method_simple_helper(Object o)
{
define_method_simple_ok = true;
}
} // namespace
TESTCASE(define_method_simple)
{
Class c(anonymous_class());
c.define_method("foo", &define_method_simple_helper);
Object o = c.call("new");
define_method_simple_ok = false;
o.call("foo");
ASSERT(define_method_simple_ok);
}
TESTCASE(define_singleton_method_simple)
{
Class c(anonymous_class());
c.define_singleton_method("foo", &define_method_simple_helper);
define_method_simple_ok = false;
Object o = c.call("foo");
ASSERT(define_method_simple_ok);
}
TESTCASE(define_module_function_simple)
{
// module_function only works with Module, not Class
Class c(anonymous_class());
ASSERT_EXCEPTION_CHECK(
Exception,
c.define_module_function("foo", &define_method_simple_helper),
ASSERT_EQUAL(
Object(rb_eTypeError),
Object(CLASS_OF(ex.value()))
)
);
}
namespace
{
int define_method_int_result;
class IntHelper {
public:
IntHelper() { }
void define_method_int_helper(int i)
{
define_method_int_result = i;
}
};
} // namespace
TESTCASE(define_method_int)
{
Class c =
define_class<IntHelper>("IntHelper")
.define_constructor(Constructor<IntHelper>())
.define_method("foo", &IntHelper::define_method_int_helper);
Object o = c.call("new");
define_method_int_result = 0;
o.call("foo", 42);
ASSERT_EQUAL(42, define_method_int_result);
}
TESTCASE(define_method_int_passed_two_args)
{
Class c =
define_class<IntHelper>("IntHelper")
.define_constructor(Constructor<IntHelper>())
.define_method("foo", &IntHelper::define_method_int_helper);
Object o = c.call("new");
ASSERT_EXCEPTION_CHECK(
Exception,
o.call("foo", 1, 2),
ASSERT_EQUAL(
Object(rb_eArgError),
Object(CLASS_OF(ex.value()))
)
);
}
TESTCASE(define_method_int_passed_no_args)
{
Class c =
define_class<IntHelper>("IntHelper")
.define_constructor(Constructor<IntHelper>())
.define_method("foo", &IntHelper::define_method_int_helper);
Object o = c.call("new");
ASSERT_EXCEPTION_CHECK(
Exception,
o.call("foo"),
ASSERT_EQUAL(
Object(rb_eArgError),
Object(CLASS_OF(ex.value()))
)
);
}
namespace
{
struct Foo
{
int x;
};
int define_method_int_foo_result_i;
Foo * define_method_int_foo_result_x;
void define_method_int_foo_helper(Object o, int i, Foo * x)
{
define_method_int_foo_result_i = i;
define_method_int_foo_result_x = x;
}
} // namespace
template<>
Foo * from_ruby<Foo *>(Object x)
{
Foo * retval;
Data_Get_Struct(x.value(), Foo, retval);
return retval;
}
TESTCASE(define_method_int_foo)
{
Class c(anonymous_class());
c.define_method("foo", &define_method_int_foo_helper);
Object o = c.call("new");
define_method_int_result = 0;
Foo * foo = new Foo;
foo->x = 1024;
VALUE f = Data_Wrap_Struct(rb_cObject, 0, Default_Allocation_Strategy<Foo>::free, foo);
o.call("foo", 42, Object(f));
ASSERT_EQUAL(42, define_method_int_foo_result_i);
ASSERT_EQUAL(foo, define_method_int_foo_result_x);
}
namespace
{
class Silly_Exception
: public std::exception
{
};
void handle_silly_exception(Silly_Exception const & ex)
{
throw Exception(rb_eRuntimeError, "SILLY");
}
void throw_silly_exception(Object self)
{
throw Silly_Exception();
}
}
TESTCASE(add_handler)
{
Class c(rb_cObject);
c.add_handler<Silly_Exception>(handle_silly_exception);
c.define_method("foo", throw_silly_exception);
Object exc = protect(rb_eval_string, "begin; foo; rescue Exception; $!; end");
ASSERT_EQUAL(rb_eRuntimeError, CLASS_OF(exc));
Exception ex(exc);
ASSERT_EQUAL(String("SILLY"), String(ex.message()));
}
namespace
{
class Container
{
public:
Container(int * array, size_t length)
: array_(array)
, length_(length)
{
}
int * begin() { return array_; }
int * end() { return array_ + length_; }
private:
int * array_;
size_t length_;
};
} // namespace
template<>
Container * from_ruby<Container *>(Object x)
{
Container * retval;
Data_Get_Struct(x.value(), Container, retval);
return retval;
}
TESTCASE(define_iterator)
{
int array[] = { 1, 2, 3 };
Class c(anonymous_class());
c.define_iterator(&Container::begin, &Container::end);
Container * container = new Container(array, 3);
Object wrapped_container = Data_Wrap_Struct(
c, 0, Default_Allocation_Strategy<Container>::free, container);
Array a = wrapped_container.instance_eval("a = []; each() { |x| a << x }; a");
ASSERT_EQUAL(3u, a.size());
ASSERT_EQUAL(to_ruby(1), Object(a[0]));
ASSERT_EQUAL(to_ruby(2), Object(a[1]));
ASSERT_EQUAL(to_ruby(3), Object(a[2]));
}
TESTCASE(define_class)
{
Class object(rb_cObject);
if(object.const_defined("Foo"))
{
object.remove_const("Foo");
}
Class c = define_class("Foo");
ASSERT(c.is_a(rb_cClass));
ASSERT_EQUAL(c, object.const_get("Foo"));
}
TESTCASE(define_class_under)
{
Class object(rb_cObject);
if(object.const_defined("Foo"))
{
object.remove_const("Foo");
}
Module math(rb_mMath);
if(math.const_defined("Foo"))
{
math.remove_const("Foo");
}
Class c = define_class_under(math, "Foo");
ASSERT(c.is_a(rb_cClass));
ASSERT_EQUAL(c, math.const_get("Foo"));
ASSERT(!object.const_defined("Foo"));
}
TESTCASE(module_define_class)
{
Class object(rb_cObject);
if(object.const_defined("Foo"))
{
object.remove_const("Foo");
}
Module math(rb_mMath);
if(math.const_defined("Foo"))
{
math.remove_const("Foo");
}
Class c = math.define_class("Foo");
ASSERT(c.is_a(rb_cClass));
ASSERT_EQUAL(c, math.const_get("Foo"));
ASSERT(!object.const_defined("Foo"));
}
namespace {
class BaseClass {
public:
BaseClass() { }
};
}
TESTCASE(subclassing)
{
Module m = define_module("Testing");
define_class_under<BaseClass>(m, "BaseClass").
define_constructor(Constructor<BaseClass>());
// Not sure how to make this a true failure case. If the subclassing
// doesn't work, Ruby will throw an error:
//
// in `new': wrong instance allocation
//
m.instance_eval("class NewClass < Testing::BaseClass; end;");
m.instance_eval("n = NewClass.new");
}
<commit_msg>Don't need the 'self' argument anymore<commit_after>#include "unittest.hpp"
#include "rice/Class.hpp"
#include "rice/Constructor.hpp"
#include "rice/protect.hpp"
#include "rice/Exception.hpp"
#include "rice/Array.hpp"
#include "rice/String.hpp"
#include "rice/Symbol.hpp"
#include <iostream>
using namespace Rice;
using namespace std;
TESTSUITE(Class);
SETUP(Class)
{
ruby_init();
}
TESTCASE(construct)
{
Class c(rb_cObject);
ASSERT_EQUAL(rb_cObject, c.value());
}
TESTCASE(undef_creation_funcs)
{
Class c(anonymous_class());
Class & c2(c.undef_creation_funcs());
ASSERT_EQUAL(&c, &c2);
ASSERT_EXCEPTION_CHECK(
Exception,
c.call("new"),
ASSERT_EQUAL(
Object(rb_eTypeError), // TODO: 1.6.x?
Object(CLASS_OF(ex.value()))
)
);
}
TESTCASE(include_module)
{
Class c(anonymous_class());
Class & c2(c.include_module(rb_mEnumerable));
ASSERT_EQUAL(&c, &c2);
Array ancestors(c.ancestors());
Array expected_ancestors;
expected_ancestors.push(c);
expected_ancestors.push(Module(rb_mEnumerable));
expected_ancestors.push(Module(rb_cObject));
expected_ancestors.push(Module(rb_mKernel));
#ifdef RUBY_VM
expected_ancestors.push(Module(rb_cBasicObject));
#endif
ASSERT_EQUAL(expected_ancestors, ancestors);
}
TESTCASE(const_set_get_by_id)
{
Class c(anonymous_class());
Object v = to_ruby(42);
Class & c2(c.const_set(rb_intern("FOO"), v));
ASSERT_EQUAL(&c, &c2);
ASSERT_EQUAL(v, c.const_get(rb_intern("FOO")));
}
TESTCASE(const_set_get_by_identifier)
{
Class c(anonymous_class());
Object v = to_ruby(42);
Class & c2(c.const_set(Identifier("FOO"), v));
ASSERT_EQUAL(&c, &c2);
ASSERT_EQUAL(v, c.const_get(Identifier("FOO")));
}
TESTCASE(const_set_get_by_string)
{
Class c(anonymous_class());
Object v = to_ruby(42);
Class & c2(c.const_set("FOO", v));
ASSERT_EQUAL(&c, &c2);
ASSERT_EQUAL(v, c.const_get("FOO"));
}
namespace
{
bool define_method_simple_ok;
void define_method_simple_helper()
{
define_method_simple_ok = true;
}
} // namespace
TESTCASE(define_method_simple)
{
Class c(anonymous_class());
c.define_method("foo", &define_method_simple_helper);
Object o = c.call("new");
define_method_simple_ok = false;
o.call("foo");
ASSERT(define_method_simple_ok);
}
TESTCASE(define_singleton_method_simple)
{
Class c(anonymous_class());
c.define_singleton_method("foo", &define_method_simple_helper);
define_method_simple_ok = false;
Object o = c.call("foo");
ASSERT(define_method_simple_ok);
}
TESTCASE(define_module_function_simple)
{
// module_function only works with Module, not Class
Class c(anonymous_class());
ASSERT_EXCEPTION_CHECK(
Exception,
c.define_module_function("foo", &define_method_simple_helper),
ASSERT_EQUAL(
Object(rb_eTypeError),
Object(CLASS_OF(ex.value()))
)
);
}
namespace
{
int define_method_int_result;
class IntHelper {
public:
IntHelper() { }
void define_method_int_helper(int i)
{
define_method_int_result = i;
}
};
} // namespace
TESTCASE(define_method_int)
{
Class c =
define_class<IntHelper>("IntHelper")
.define_constructor(Constructor<IntHelper>())
.define_method("foo", &IntHelper::define_method_int_helper);
Object o = c.call("new");
define_method_int_result = 0;
o.call("foo", 42);
ASSERT_EQUAL(42, define_method_int_result);
}
TESTCASE(define_method_int_passed_two_args)
{
Class c =
define_class<IntHelper>("IntHelper")
.define_constructor(Constructor<IntHelper>())
.define_method("foo", &IntHelper::define_method_int_helper);
Object o = c.call("new");
ASSERT_EXCEPTION_CHECK(
Exception,
o.call("foo", 1, 2),
ASSERT_EQUAL(
Object(rb_eArgError),
Object(CLASS_OF(ex.value()))
)
);
}
TESTCASE(define_method_int_passed_no_args)
{
Class c =
define_class<IntHelper>("IntHelper")
.define_constructor(Constructor<IntHelper>())
.define_method("foo", &IntHelper::define_method_int_helper);
Object o = c.call("new");
ASSERT_EXCEPTION_CHECK(
Exception,
o.call("foo"),
ASSERT_EQUAL(
Object(rb_eArgError),
Object(CLASS_OF(ex.value()))
)
);
}
namespace
{
struct Foo
{
int x;
};
int define_method_int_foo_result_i;
Foo * define_method_int_foo_result_x;
void define_method_int_foo_helper(int i, Foo * x)
{
define_method_int_foo_result_i = i;
define_method_int_foo_result_x = x;
}
} // namespace
template<>
Foo * from_ruby<Foo *>(Object x)
{
Foo * retval;
Data_Get_Struct(x.value(), Foo, retval);
return retval;
}
TESTCASE(define_method_int_foo)
{
Class c(anonymous_class());
c.define_method("foo", &define_method_int_foo_helper);
Object o = c.call("new");
define_method_int_result = 0;
Foo * foo = new Foo;
foo->x = 1024;
VALUE f = Data_Wrap_Struct(rb_cObject, 0, Default_Allocation_Strategy<Foo>::free, foo);
o.call("foo", 42, Object(f));
ASSERT_EQUAL(42, define_method_int_foo_result_i);
ASSERT_EQUAL(foo, define_method_int_foo_result_x);
}
namespace
{
class Silly_Exception
: public std::exception
{
};
void handle_silly_exception(Silly_Exception const & ex)
{
throw Exception(rb_eRuntimeError, "SILLY");
}
void throw_silly_exception()
{
throw Silly_Exception();
}
}
TESTCASE(add_handler)
{
Class c(rb_cObject);
c.add_handler<Silly_Exception>(handle_silly_exception);
c.define_method("foo", throw_silly_exception);
Object exc = protect(rb_eval_string, "begin; foo; rescue Exception; $!; end");
ASSERT_EQUAL(rb_eRuntimeError, CLASS_OF(exc));
Exception ex(exc);
ASSERT_EQUAL(String("SILLY"), String(ex.message()));
}
namespace
{
class Container
{
public:
Container(int * array, size_t length)
: array_(array)
, length_(length)
{
}
int * begin() { return array_; }
int * end() { return array_ + length_; }
private:
int * array_;
size_t length_;
};
} // namespace
template<>
Container * from_ruby<Container *>(Object x)
{
Container * retval;
Data_Get_Struct(x.value(), Container, retval);
return retval;
}
TESTCASE(define_iterator)
{
int array[] = { 1, 2, 3 };
Class c(anonymous_class());
c.define_iterator(&Container::begin, &Container::end);
Container * container = new Container(array, 3);
Object wrapped_container = Data_Wrap_Struct(
c, 0, Default_Allocation_Strategy<Container>::free, container);
Array a = wrapped_container.instance_eval("a = []; each() { |x| a << x }; a");
ASSERT_EQUAL(3u, a.size());
ASSERT_EQUAL(to_ruby(1), Object(a[0]));
ASSERT_EQUAL(to_ruby(2), Object(a[1]));
ASSERT_EQUAL(to_ruby(3), Object(a[2]));
}
TESTCASE(define_class)
{
Class object(rb_cObject);
if(object.const_defined("Foo"))
{
object.remove_const("Foo");
}
Class c = define_class("Foo");
ASSERT(c.is_a(rb_cClass));
ASSERT_EQUAL(c, object.const_get("Foo"));
}
TESTCASE(define_class_under)
{
Class object(rb_cObject);
if(object.const_defined("Foo"))
{
object.remove_const("Foo");
}
Module math(rb_mMath);
if(math.const_defined("Foo"))
{
math.remove_const("Foo");
}
Class c = define_class_under(math, "Foo");
ASSERT(c.is_a(rb_cClass));
ASSERT_EQUAL(c, math.const_get("Foo"));
ASSERT(!object.const_defined("Foo"));
}
TESTCASE(module_define_class)
{
Class object(rb_cObject);
if(object.const_defined("Foo"))
{
object.remove_const("Foo");
}
Module math(rb_mMath);
if(math.const_defined("Foo"))
{
math.remove_const("Foo");
}
Class c = math.define_class("Foo");
ASSERT(c.is_a(rb_cClass));
ASSERT_EQUAL(c, math.const_get("Foo"));
ASSERT(!object.const_defined("Foo"));
}
namespace {
class BaseClass {
public:
BaseClass() { }
};
}
TESTCASE(subclassing)
{
Module m = define_module("Testing");
define_class_under<BaseClass>(m, "BaseClass").
define_constructor(Constructor<BaseClass>());
// Not sure how to make this a true failure case. If the subclassing
// doesn't work, Ruby will throw an error:
//
// in `new': wrong instance allocation
//
m.instance_eval("class NewClass < Testing::BaseClass; end;");
m.instance_eval("n = NewClass.new");
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "SharedInt.h"
struct Data { int value = 77; };
GTEST_TEST(BasicTest, PlainCOW)
{
COW<Data> d;
// Access should work on a default constructed object.
EXPECT_EQ(77, d->value);
}
GTEST_TEST(BasicTest, DefaultConstructed)
{
SharedInt::AllowAllocations(false);
EXPECT_EQ(0, SharedInt::ReferenceCount());
SharedInt a, b, c;
EXPECT_EQ(0, a.value());
EXPECT_EQ(0, b.value());
EXPECT_EQ(0, c.value());
EXPECT_EQ(1, SharedInt::ReferenceCount());
// No heap memory has been allocated so far.
EXPECT_EQ(0, SharedInt::AllocatedCount());
//All three variables point to the shared null
EXPECT_EQ(a.d.pointer, b.d.pointer);
EXPECT_EQ(b.d.pointer, c.d.pointer);
}
GTEST_TEST(BasicTest, StandardUsage)
{
{
EXPECT_EQ(0, SharedInt::AllocatedCount());
// ReferenceCount will include the "shared null" object,
// so it will always be 1 larger than expected.
EXPECT_EQ(1, SharedInt::ReferenceCount());
SharedInt x(1), y(2), z(3);
// No variables have been allocated on the heap.
EXPECT_EQ(0, SharedInt::AllocatedCount());
EXPECT_EQ(3+1, SharedInt::ReferenceCount());
// Check their values
EXPECT_EQ(1, x.value());
EXPECT_EQ(2, y.value());
EXPECT_EQ(3, z.value());
y = x;
EXPECT_EQ(2+1, SharedInt::ReferenceCount());
z = y;
EXPECT_EQ(1+1, SharedInt::ReferenceCount());
// Now two have been freed, and all three point to the same value(1).
EXPECT_EQ(1, x.value());
EXPECT_EQ(1, y.value());
EXPECT_EQ(1, z.value());
// The following line changes x, but leaves y and z unchanged.
x.setValue(4);
EXPECT_EQ(2+1, SharedInt::ReferenceCount());
EXPECT_EQ(4, x.value());
EXPECT_EQ(1, y.value());
EXPECT_EQ(1, z.value());
}
// Check that all memory has been freed
EXPECT_EQ(1, SharedInt::ReferenceCount());
}
GTEST_TEST(BasicTest, Arrays)
{
SharedInt::AllowAllocations(false);
static const int Size = 256;
// The following line triggers no heap allocation:
SharedInt array[Size];
EXPECT_EQ(1, SharedInt::ReferenceCount());
// Check that a single element has the size of two pointers:
// Unfortunately shared_ptr, which the current implementation
// is based on, has the size of two pointers.
EXPECT_EQ(2*sizeof(void*), sizeof(array)/Size);
std::vector<SharedInt> vector(100);
EXPECT_EQ(1, SharedInt::ReferenceCount());
}
GTEST_TEST(BasicTest, Count)
{
COW<int> a(2);
EXPECT_EQ(2, a.constData());
EXPECT_EQ(1, a.count());
COW<int> b = COW<int>(4);
EXPECT_EQ(4, b.constData());
EXPECT_EQ(1, b.count());
COW<int> c = a;
EXPECT_EQ(2, a.count());
EXPECT_EQ(2, c.count());
EXPECT_EQ(c.constData(), a.constData());
a.data() = a.constData();
EXPECT_EQ(1, a.count());
EXPECT_EQ(1, c.count());
EXPECT_EQ(2, a.constData());
EXPECT_EQ(4, b.constData());
EXPECT_EQ(2, c.constData());
c.data() = a.constData();
EXPECT_EQ(1, a.count());
EXPECT_EQ(1, c.count());
}
static int ctor_count = 0;
static int copy_count = 0;
static int forwarding_count = 0;
static int assignment_count = 0;
GTEST_TEST(BasicTest, perfectForwarding)
{
struct ConstructorTester
{
ConstructorTester()
{
ctor_count++;
}
ConstructorTester(const ConstructorTester&)
{
copy_count++;
}
ConstructorTester(ConstructorTester&&)
{
forwarding_count++;
}
ConstructorTester& operator=(const ConstructorTester&)
{
assignment_count++;
return *this;
}
static ConstructorTester get()
{
ConstructorTester tmp;
return std::move(tmp);
}
};
EXPECT_EQ(0, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_EQ(0, forwarding_count);
EXPECT_EQ(0, assignment_count);
COW<ConstructorTester> a, b, c;
EXPECT_EQ(1, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_EQ(0, forwarding_count);
EXPECT_EQ(0, assignment_count);
COW<ConstructorTester> d(ConstructorTester::get());
EXPECT_EQ(2, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_NE(0, forwarding_count);
EXPECT_EQ(0, assignment_count);
a = c;
EXPECT_EQ(2, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_EQ(0, assignment_count);
b.data() = d.constData();
EXPECT_EQ(2, ctor_count);
EXPECT_EQ(1, copy_count);
EXPECT_EQ(1, assignment_count);
}
#ifdef HAVE_CXX_REFERENCE_QUALIFIED_FUNCTIONS
class CopyChecker
{
public:
CopyChecker()
: d(0)
{
}
void modify()&
{
d.detach();
}
CopyChecker modified()const&
{
return CopyChecker(*this).modified();
}
CopyChecker modified()&&
{
modify();
return std::move(*this);
}
private:
struct ThrowsIfCopied
{
ThrowsIfCopied()=default;
ThrowsIfCopied(int){}
ThrowsIfCopied(const ThrowsIfCopied&){throw 1;}
void operator=(const ThrowsIfCopied&){throw 1;}
ThrowsIfCopied(ThrowsIfCopied&&)=delete;
void operator=(ThrowsIfCopied&&)=delete;
};
COW<ThrowsIfCopied> d;
};
GTEST_TEST(BasicTest, NoNeedLessCopies)
{
CopyChecker a;
// modify() works in place and does not trigger a copy:
a.modify();
// modified() doesn't throw, when called on an rvalue.
CopyChecker().modified().modified().modified();
// Calling modified() on an lvalue will trigger a copy.
EXPECT_THROW( auto b = a.modified(), int);
}
#endif
<commit_msg>Codacy fix.<commit_after>#include "gtest/gtest.h"
#include "SharedInt.h"
struct Data { int value = 77; };
GTEST_TEST(BasicTest, PlainCOW)
{
COW<Data> d;
// Access should work on a default constructed object.
EXPECT_EQ(77, d->value);
}
GTEST_TEST(BasicTest, DefaultConstructed)
{
SharedInt::AllowAllocations(false);
EXPECT_EQ(0, SharedInt::ReferenceCount());
SharedInt a, b, c;
EXPECT_EQ(0, a.value());
EXPECT_EQ(0, b.value());
EXPECT_EQ(0, c.value());
EXPECT_EQ(1, SharedInt::ReferenceCount());
// No heap memory has been allocated so far.
EXPECT_EQ(0, SharedInt::AllocatedCount());
//All three variables point to the shared null
EXPECT_EQ(a.d.pointer, b.d.pointer);
EXPECT_EQ(b.d.pointer, c.d.pointer);
}
GTEST_TEST(BasicTest, StandardUsage)
{
{
EXPECT_EQ(0, SharedInt::AllocatedCount());
// ReferenceCount will include the "shared null" object,
// so it will always be 1 larger than expected.
EXPECT_EQ(1, SharedInt::ReferenceCount());
SharedInt x(1), y(2), z(3);
// No variables have been allocated on the heap.
EXPECT_EQ(0, SharedInt::AllocatedCount());
EXPECT_EQ(3+1, SharedInt::ReferenceCount());
// Check their values
EXPECT_EQ(1, x.value());
EXPECT_EQ(2, y.value());
EXPECT_EQ(3, z.value());
y = x;
EXPECT_EQ(2+1, SharedInt::ReferenceCount());
z = y;
EXPECT_EQ(1+1, SharedInt::ReferenceCount());
// Now two have been freed, and all three point to the same value(1).
EXPECT_EQ(1, x.value());
EXPECT_EQ(1, y.value());
EXPECT_EQ(1, z.value());
// The following line changes x, but leaves y and z unchanged.
x.setValue(4);
EXPECT_EQ(2+1, SharedInt::ReferenceCount());
EXPECT_EQ(4, x.value());
EXPECT_EQ(1, y.value());
EXPECT_EQ(1, z.value());
}
// Check that all memory has been freed
EXPECT_EQ(1, SharedInt::ReferenceCount());
}
GTEST_TEST(BasicTest, Arrays)
{
SharedInt::AllowAllocations(false);
static const int Size = 256;
// The following line triggers no heap allocation:
SharedInt array[Size];
EXPECT_EQ(1, SharedInt::ReferenceCount());
// Check that a single element has the size of two pointers:
// Unfortunately shared_ptr, which the current implementation
// is based on, has the size of two pointers.
EXPECT_EQ(2*sizeof(void*), sizeof(array)/Size);
std::vector<SharedInt> vector(100);
EXPECT_EQ(1, SharedInt::ReferenceCount());
}
GTEST_TEST(BasicTest, Count)
{
COW<int> a(2);
EXPECT_EQ(2, a.constData());
EXPECT_EQ(1, a.count());
COW<int> b = COW<int>(4);
EXPECT_EQ(4, b.constData());
EXPECT_EQ(1, b.count());
COW<int> c = a;
EXPECT_EQ(2, a.count());
EXPECT_EQ(2, c.count());
EXPECT_EQ(c.constData(), a.constData());
a.data() = a.constData();
EXPECT_EQ(1, a.count());
EXPECT_EQ(1, c.count());
EXPECT_EQ(2, a.constData());
EXPECT_EQ(4, b.constData());
EXPECT_EQ(2, c.constData());
c.data() = a.constData();
EXPECT_EQ(1, a.count());
EXPECT_EQ(1, c.count());
}
static int ctor_count = 0;
static int copy_count = 0;
static int forwarding_count = 0;
static int assignment_count = 0;
GTEST_TEST(BasicTest, perfectForwarding)
{
struct ConstructorTester
{
ConstructorTester()
{
ctor_count++;
}
ConstructorTester(const ConstructorTester&)
{
copy_count++;
}
ConstructorTester(ConstructorTester&&)
{
forwarding_count++;
}
ConstructorTester& operator=(const ConstructorTester&)
{
assignment_count++;
return *this;
}
static ConstructorTester get()
{
ConstructorTester tmp;
return std::move(tmp);
}
};
EXPECT_EQ(0, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_EQ(0, forwarding_count);
EXPECT_EQ(0, assignment_count);
COW<ConstructorTester> a, b, c;
EXPECT_EQ(1, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_EQ(0, forwarding_count);
EXPECT_EQ(0, assignment_count);
COW<ConstructorTester> d(ConstructorTester::get());
EXPECT_EQ(2, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_NE(0, forwarding_count);
EXPECT_EQ(0, assignment_count);
a = c;
EXPECT_EQ(2, ctor_count);
EXPECT_EQ(0, copy_count);
EXPECT_EQ(0, assignment_count);
b.data() = d.constData();
EXPECT_EQ(2, ctor_count);
EXPECT_EQ(1, copy_count);
EXPECT_EQ(1, assignment_count);
}
#ifdef HAVE_CXX_REFERENCE_QUALIFIED_FUNCTIONS
class CopyChecker
{
public:
CopyChecker()
: d(0)
{
}
void modify()&
{
d.detach();
}
CopyChecker modified()const&
{
return CopyChecker(*this).modified();
}
CopyChecker modified()&&
{
modify();
return std::move(*this);
}
private:
struct ThrowsIfCopied
{
ThrowsIfCopied()=default;
explicit ThrowsIfCopied(int){}
ThrowsIfCopied(const ThrowsIfCopied&){throw 1;}
ThrowsIfCopied& operator=(const ThrowsIfCopied&){throw 1;}
ThrowsIfCopied(ThrowsIfCopied&&)=delete;
ThrowsIfCopied& operator=(ThrowsIfCopied&&)=delete;
};
COW<ThrowsIfCopied> d;
};
GTEST_TEST(BasicTest, NoNeedLessCopies)
{
CopyChecker a;
// modify() works in place and does not trigger a copy:
a.modify();
// modified() doesn't throw, when called on an rvalue.
CopyChecker().modified().modified().modified();
// Calling modified() on an lvalue will trigger a copy.
EXPECT_THROW( auto b = a.modified(), int);
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2013, 2014, Huang-Ming Huang, Object Computing, Inc.
// All rights reserved.
//
// This file is part of mFAST.
//
// mFAST is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// mFAST 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 Lesser General Public License
// along with mFast. If not, see <http://www.gnu.org/licenses/>.
//
#include "test3.h"
#include <mfast/json/json.h>
#include <sstream>
#define BOOST_TEST_DYN_LINK
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
#include "debug_allocator.h"
namespace mfast {
namespace json {
bool get_quoted_string(std::istream& strm,
std::string* pstr,
const mfast::byte_vector_mref* pref,
bool first_quote_extracted=false);
bool get_decimal_string(std::istream& strm, std::string& str);
bool skip_value (std::istream& strm);
}
}
BOOST_AUTO_TEST_SUITE( json_test_suite )
BOOST_AUTO_TEST_CASE(json_encode_product_test)
{
using namespace test3;
Product product_holder;
Product_mref product_ref = product_holder.mref();
// product_ref.set_id().as(1);
product_ref.set_price().as(12356, -2);
product_ref.set_name().as("Foo");
Product_mref::tags_mref tags = product_ref.set_tags();
BOOST_CHECK_EQUAL(tags.instruction()->field_type(), mfast::field_type_sequence);
BOOST_CHECK_EQUAL(tags.instruction()->subinstructions().size(), 1U);
tags.resize(2);
BOOST_CHECK_EQUAL(tags.size(), 2U);
mfast::ascii_string_mref tag0 = tags[0];
BOOST_CHECK_EQUAL(tag0.instruction()->field_type(), mfast::field_type_ascii_string);
tags[0].as("Bar with \"quote\"");
BOOST_CHECK_EQUAL(strcmp(tags[0].c_str(), "Bar with \"quote\""),0);
tags[1].as("Eek with \\");
BOOST_CHECK_EQUAL(strcmp(tags[1].c_str(), "Eek with \\"), 0);
Product_mref::stock_mref stock = product_ref.set_stock();
stock.set_warehouse().as(300);
stock.set_retail().as(20);
const unsigned char ext_data[] = "{\"test1\":1}";
// product_ref.set_ext().assign(ext_data, ext_data+sizeof(ext_data)-1);
product_ref.set_ext().refers_to(ext_data, sizeof(ext_data)-1);
std::ostringstream ostrm;
mfast::json::encode(ostrm,
product_ref,
mfast_tag::JSON_UNKNOWN);
const char* result = "{\"name\":\"Foo\",\"price\":123.56,\"tags\":[\"Bar with \\\"quote\\\"\",\"Eek with \\\\\"],\"stock\":{\"warehouse\":300,\"retail\":20},\"ext\":{\"test1\":1}}";
// std::cout << strm.str() << "\n";
// std::cout << result << "\n";
BOOST_CHECK_EQUAL(ostrm.str(),
std::string(result));
debug_allocator alloc;
Product product2_holder(product_ref, &alloc);
Product product3_holder;
std::istringstream istrm(result);
mfast::json::decode(istrm,
product3_holder.mref(),
mfast_tag::JSON_UNKNOWN);
//
BOOST_CHECK(product3_holder.cref() == product_ref);
product_ref.omit_stock();
BOOST_CHECK(product_ref.get_stock().absent());
}
BOOST_AUTO_TEST_CASE(json_encode_person_test)
{
using namespace test3;
Person person_holder;
Person_mref person_ref = person_holder.mref();
person_ref.set_firstName().as("John");
person_ref.set_lastName().as("Smith");
person_ref.set_age().as(25);
Person_mref::phoneNumbers_mref phones = person_ref.set_phoneNumbers();
phones.resize(2);
phones[0].set_type().as("home");
phones[0].set_number().as("212 555-1234");
phones[1].set_type().as("fax");
phones[1].set_number().as("646 555-4567");
LoginAccount_mref login = person_ref.set_login().as<LoginAccount>();
login.set_userName().as("John");
login.set_password().as("J0hnsm1th");
BOOST_CHECK(person_ref.get_login().present());
person_ref.set_bankAccounts().grow_by(1);
BOOST_CHECK_EQUAL(person_ref.get_bankAccounts().size(), 1U);
BankAccount_mref acct0 = person_ref.set_bankAccounts()[0].as<BankAccount>();
acct0.set_number().as(12345678);
acct0.set_routingNumber().as(87654321);
BOOST_CHECK_EQUAL(person_ref.get_bankAccounts().size(), 1U);
mfast::nested_message_cref n0 = person_ref.get_bankAccounts()[0];
BankAccount_cref acct0_read = static_cast<BankAccount_cref>(n0.target());
BOOST_CHECK_EQUAL(acct0_read.get_number().value(), 12345678U);
BOOST_CHECK_EQUAL(acct0_read.get_routingNumber().value(), 87654321U);
std::stringstream strm;
mfast::json::encode(strm, person_ref);
const char* result = "{\"firstName\":\"John\",\"lastName\":\"Smith\",\"age\":25,"
"\"phoneNumbers\":[{\"type\":\"home\",\"number\":\"212 555-1234\"},{\"type\":\"fax\",\"number\":\"646 555-4567\"}],"
"\"emails\":[],\"login\":{\"userName\":\"John\",\"password\":\"J0hnsm1th\"},\"bankAccounts\":[{\"number\":12345678,\"routingNumber\":87654321}]}";
BOOST_CHECK_EQUAL(strm.str(),
std::string(result));
debug_allocator alloc;
Person person_holder2(person_ref, &alloc);
}
BOOST_AUTO_TEST_CASE(json_decode_null_test)
{
using namespace test3;
try {
LoginAccount account_holder;
const char result[] = "{\"userName\":\"test\",\"password\": null}";
std::stringstream strm(result);
mfast::json::decode(strm, account_holder.mref());
BOOST_CHECK_EQUAL(account_holder.cref().get_userName().value(), "test");
BOOST_CHECK( account_holder.cref().get_password().absent() );
}
catch (boost::exception& ex)
{
std::cerr << diagnostic_information(ex);
}
}
BOOST_AUTO_TEST_CASE(test_get_quoted_string)
{
using namespace mfast;
using namespace mfast::json;
debug_allocator alloc;
std::string str;
const byte_vector_field_instruction byte_vector_field_instruction_prototype(operator_none,presence_mandatory,0,0,"",0, string_value_storage(), 0, "", "");
value_storage storage;
byte_vector_field_instruction_prototype.construct_value(storage, &alloc);
byte_vector_mref bv_ref(&alloc,
&storage,
&byte_vector_field_instruction_prototype);
{
const char data[] = "\"abcd\",";
std::stringstream strm(data);
BOOST_CHECK(get_quoted_string(strm, &str, &bv_ref, false));
BOOST_CHECK_EQUAL(str, std::string("abcd"));
BOOST_CHECK_EQUAL(bv_ref.size(), sizeof(data)-2 );
BOOST_CHECK(memcmp(data, bv_ref.data(), sizeof(data)-2 ) ==0);
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
bv_ref.clear();
const char data[] = "\"abc\\\"d\",";
std::stringstream strm(data);
BOOST_CHECK(get_quoted_string(strm, &str, &bv_ref, false));
BOOST_CHECK_EQUAL(str, std::string("abc\"d"));
BOOST_CHECK_EQUAL(bv_ref.size(), sizeof(data)-2 );
BOOST_CHECK(memcmp(data, bv_ref.data(), sizeof(data)-2) == 0);
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
bv_ref.clear();
const char data[] = "\"abc\\nd\",";
std::stringstream strm(data);
BOOST_CHECK(get_quoted_string(strm, &str, &bv_ref, false));
BOOST_CHECK_EQUAL(str, std::string("abc\nd"));
BOOST_CHECK_EQUAL(bv_ref.size(), sizeof(data)-2);
BOOST_CHECK(memcmp(data, bv_ref.data(), sizeof(data)-2) ==0);
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
byte_vector_field_instruction_prototype.destruct_value(storage, &alloc);
}
BOOST_AUTO_TEST_CASE(test_get_decimal_string)
{
using namespace mfast::json;
std::string str;
{
std::stringstream strm(" 123.45,");
BOOST_CHECK(get_decimal_string(strm, str));
BOOST_CHECK_EQUAL(str, std::string("123.45"));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" -123.45,");
BOOST_CHECK(get_decimal_string(strm, str));
BOOST_CHECK_EQUAL(str, std::string("-123.45"));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" 123.45E+12,");
BOOST_CHECK(get_decimal_string(strm, str));
BOOST_CHECK_EQUAL(str, std::string("123.45E+12"));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" 123.45E-12,");
BOOST_CHECK(get_decimal_string(strm, str));
BOOST_CHECK_EQUAL(str, std::string("123.45E-12"));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" 0.123,");
BOOST_CHECK(get_decimal_string(strm, str));
BOOST_CHECK_EQUAL(str, std::string("0.123"));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
}
BOOST_AUTO_TEST_CASE(test_skip_value)
{
using namespace mfast::json;
std::string str;
{
std::stringstream strm(" 123.45,");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" \"ab\\ncd\",");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" null,");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" true,");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" false,");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" [1, 2, 3],");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
BOOST_CHECK(strm.eof());
}
{
std::stringstream strm(" [1, [ \"abc\" ], 3],");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
BOOST_CHECK(strm.eof());
}
{
std::stringstream strm(" [1, { \"f1\":\"abc\" }, 3],");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
BOOST_CHECK(strm.eof());
}
{
std::stringstream strm(" {\"id\":1,\"name\":\"Foo\"},");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
BOOST_CHECK(strm.eof());
}
}
BOOST_AUTO_TEST_CASE(test_seq_codegen)
{
using namespace test3;
const UsingSeqTemplates::instruction_type* top_inst = UsingSeqTemplates::instruction();
BOOST_CHECK_EQUAL(top_inst->subinstructions().size(), 3U);
const mfast::sequence_field_instruction* seq1_inst = dynamic_cast<const mfast::sequence_field_instruction*>(top_inst->subinstruction(1));
BOOST_REQUIRE(seq1_inst);
BOOST_CHECK(strcmp(seq1_inst->name(), "seq1")==0);
BOOST_CHECK_EQUAL(seq1_inst->subinstructions().size(), 2U);
BOOST_CHECK_EQUAL(seq1_inst->ref_instruction(), SeqTemplate1::instruction());
BOOST_CHECK_EQUAL(seq1_inst->element_instruction(), (const mfast::group_field_instruction*) 0);
const mfast::sequence_field_instruction* seq2_inst = dynamic_cast<const mfast::sequence_field_instruction*>(top_inst->subinstruction(2));
BOOST_REQUIRE(seq2_inst);
BOOST_CHECK(strcmp(seq2_inst->name(), "seq2")==0);
BOOST_CHECK_EQUAL(seq2_inst->subinstructions().size(), 4U);
BOOST_CHECK_EQUAL(seq2_inst->ref_instruction(), SeqTemplate2::instruction());
BOOST_CHECK_EQUAL(seq2_inst->element_instruction(), BankAccount::instruction());
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fixed a type mismatch problem when using BOOST_CHECK_EQUAL<commit_after>// Copyright (c) 2013, 2014, Huang-Ming Huang, Object Computing, Inc.
// All rights reserved.
//
// This file is part of mFAST.
//
// mFAST is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// mFAST 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 Lesser General Public License
// along with mFast. If not, see <http://www.gnu.org/licenses/>.
//
#include "test3.h"
#include <mfast/json/json.h>
#include <sstream>
#define BOOST_TEST_DYN_LINK
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
#include "debug_allocator.h"
namespace mfast {
namespace json {
bool get_quoted_string(std::istream& strm,
std::string* pstr,
const mfast::byte_vector_mref* pref,
bool first_quote_extracted=false);
bool get_decimal_string(std::istream& strm, std::string& str);
bool skip_value (std::istream& strm);
}
}
BOOST_AUTO_TEST_SUITE( json_test_suite )
BOOST_AUTO_TEST_CASE(json_encode_product_test)
{
using namespace test3;
Product product_holder;
Product_mref product_ref = product_holder.mref();
// product_ref.set_id().as(1);
product_ref.set_price().as(12356, -2);
product_ref.set_name().as("Foo");
Product_mref::tags_mref tags = product_ref.set_tags();
BOOST_CHECK_EQUAL(tags.instruction()->field_type(), mfast::field_type_sequence);
BOOST_CHECK_EQUAL(tags.instruction()->subinstructions().size(), 1U);
tags.resize(2);
BOOST_CHECK_EQUAL(tags.size(), 2U);
mfast::ascii_string_mref tag0 = tags[0];
BOOST_CHECK_EQUAL(tag0.instruction()->field_type(), mfast::field_type_ascii_string);
tags[0].as("Bar with \"quote\"");
BOOST_CHECK_EQUAL(strcmp(tags[0].c_str(), "Bar with \"quote\""),0);
tags[1].as("Eek with \\");
BOOST_CHECK_EQUAL(strcmp(tags[1].c_str(), "Eek with \\"), 0);
Product_mref::stock_mref stock = product_ref.set_stock();
stock.set_warehouse().as(300);
stock.set_retail().as(20);
const unsigned char ext_data[] = "{\"test1\":1}";
// product_ref.set_ext().assign(ext_data, ext_data+sizeof(ext_data)-1);
product_ref.set_ext().refers_to(ext_data, sizeof(ext_data)-1);
std::ostringstream ostrm;
mfast::json::encode(ostrm,
product_ref,
mfast_tag::JSON_UNKNOWN);
const char* result = "{\"name\":\"Foo\",\"price\":123.56,\"tags\":[\"Bar with \\\"quote\\\"\",\"Eek with \\\\\"],\"stock\":{\"warehouse\":300,\"retail\":20},\"ext\":{\"test1\":1}}";
// std::cout << strm.str() << "\n";
// std::cout << result << "\n";
BOOST_CHECK_EQUAL(ostrm.str(),
std::string(result));
debug_allocator alloc;
Product product2_holder(product_ref, &alloc);
Product product3_holder;
std::istringstream istrm(result);
mfast::json::decode(istrm,
product3_holder.mref(),
mfast_tag::JSON_UNKNOWN);
//
BOOST_CHECK(product3_holder.cref() == product_ref);
product_ref.omit_stock();
BOOST_CHECK(product_ref.get_stock().absent());
}
BOOST_AUTO_TEST_CASE(json_encode_person_test)
{
using namespace test3;
Person person_holder;
Person_mref person_ref = person_holder.mref();
person_ref.set_firstName().as("John");
person_ref.set_lastName().as("Smith");
person_ref.set_age().as(25);
Person_mref::phoneNumbers_mref phones = person_ref.set_phoneNumbers();
phones.resize(2);
phones[0].set_type().as("home");
phones[0].set_number().as("212 555-1234");
phones[1].set_type().as("fax");
phones[1].set_number().as("646 555-4567");
LoginAccount_mref login = person_ref.set_login().as<LoginAccount>();
login.set_userName().as("John");
login.set_password().as("J0hnsm1th");
BOOST_CHECK(person_ref.get_login().present());
person_ref.set_bankAccounts().grow_by(1);
BOOST_CHECK_EQUAL(person_ref.get_bankAccounts().size(), 1U);
BankAccount_mref acct0 = person_ref.set_bankAccounts()[0].as<BankAccount>();
acct0.set_number().as(12345678);
acct0.set_routingNumber().as(87654321);
BOOST_CHECK_EQUAL(person_ref.get_bankAccounts().size(), 1U);
mfast::nested_message_cref n0 = person_ref.get_bankAccounts()[0];
BankAccount_cref acct0_read = static_cast<BankAccount_cref>(n0.target());
BOOST_CHECK_EQUAL(acct0_read.get_number().value(), 12345678U);
BOOST_CHECK_EQUAL(acct0_read.get_routingNumber().value(), 87654321U);
std::stringstream strm;
mfast::json::encode(strm, person_ref);
const char* result = "{\"firstName\":\"John\",\"lastName\":\"Smith\",\"age\":25,"
"\"phoneNumbers\":[{\"type\":\"home\",\"number\":\"212 555-1234\"},{\"type\":\"fax\",\"number\":\"646 555-4567\"}],"
"\"emails\":[],\"login\":{\"userName\":\"John\",\"password\":\"J0hnsm1th\"},\"bankAccounts\":[{\"number\":12345678,\"routingNumber\":87654321}]}";
BOOST_CHECK_EQUAL(strm.str(),
std::string(result));
debug_allocator alloc;
Person person_holder2(person_ref, &alloc);
}
BOOST_AUTO_TEST_CASE(json_decode_null_test)
{
using namespace test3;
try {
LoginAccount account_holder;
const char result[] = "{\"userName\":\"test\",\"password\": null}";
std::stringstream strm(result);
mfast::json::decode(strm, account_holder.mref());
BOOST_CHECK_EQUAL(account_holder.cref().get_userName().value(), boost::string_ref("test"));
BOOST_CHECK( account_holder.cref().get_password().absent() );
}
catch (boost::exception& ex)
{
std::cerr << diagnostic_information(ex);
}
}
BOOST_AUTO_TEST_CASE(test_get_quoted_string)
{
using namespace mfast;
using namespace mfast::json;
debug_allocator alloc;
std::string str;
const byte_vector_field_instruction byte_vector_field_instruction_prototype(operator_none,presence_mandatory,0,0,"",0, string_value_storage(), 0, "", "");
value_storage storage;
byte_vector_field_instruction_prototype.construct_value(storage, &alloc);
byte_vector_mref bv_ref(&alloc,
&storage,
&byte_vector_field_instruction_prototype);
{
const char data[] = "\"abcd\",";
std::stringstream strm(data);
BOOST_CHECK(get_quoted_string(strm, &str, &bv_ref, false));
BOOST_CHECK_EQUAL(str, std::string("abcd"));
BOOST_CHECK_EQUAL(bv_ref.size(), sizeof(data)-2 );
BOOST_CHECK(memcmp(data, bv_ref.data(), sizeof(data)-2 ) ==0);
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
bv_ref.clear();
const char data[] = "\"abc\\\"d\",";
std::stringstream strm(data);
BOOST_CHECK(get_quoted_string(strm, &str, &bv_ref, false));
BOOST_CHECK_EQUAL(str, std::string("abc\"d"));
BOOST_CHECK_EQUAL(bv_ref.size(), sizeof(data)-2 );
BOOST_CHECK(memcmp(data, bv_ref.data(), sizeof(data)-2) == 0);
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
bv_ref.clear();
const char data[] = "\"abc\\nd\",";
std::stringstream strm(data);
BOOST_CHECK(get_quoted_string(strm, &str, &bv_ref, false));
BOOST_CHECK_EQUAL(str, std::string("abc\nd"));
BOOST_CHECK_EQUAL(bv_ref.size(), sizeof(data)-2);
BOOST_CHECK(memcmp(data, bv_ref.data(), sizeof(data)-2) ==0);
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
byte_vector_field_instruction_prototype.destruct_value(storage, &alloc);
}
BOOST_AUTO_TEST_CASE(test_get_decimal_string)
{
using namespace mfast::json;
std::string str;
{
std::stringstream strm(" 123.45,");
BOOST_CHECK(get_decimal_string(strm, str));
BOOST_CHECK_EQUAL(str, std::string("123.45"));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" -123.45,");
BOOST_CHECK(get_decimal_string(strm, str));
BOOST_CHECK_EQUAL(str, std::string("-123.45"));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" 123.45E+12,");
BOOST_CHECK(get_decimal_string(strm, str));
BOOST_CHECK_EQUAL(str, std::string("123.45E+12"));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" 123.45E-12,");
BOOST_CHECK(get_decimal_string(strm, str));
BOOST_CHECK_EQUAL(str, std::string("123.45E-12"));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" 0.123,");
BOOST_CHECK(get_decimal_string(strm, str));
BOOST_CHECK_EQUAL(str, std::string("0.123"));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
}
BOOST_AUTO_TEST_CASE(test_skip_value)
{
using namespace mfast::json;
std::string str;
{
std::stringstream strm(" 123.45,");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" \"ab\\ncd\",");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" null,");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" true,");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" false,");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
}
{
std::stringstream strm(" [1, 2, 3],");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
BOOST_CHECK(strm.eof());
}
{
std::stringstream strm(" [1, [ \"abc\" ], 3],");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
BOOST_CHECK(strm.eof());
}
{
std::stringstream strm(" [1, { \"f1\":\"abc\" }, 3],");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
BOOST_CHECK(strm.eof());
}
{
std::stringstream strm(" {\"id\":1,\"name\":\"Foo\"},");
BOOST_CHECK(skip_value(strm));
strm >> str;
BOOST_CHECK_EQUAL(str, std::string(","));
BOOST_CHECK(strm.eof());
}
}
BOOST_AUTO_TEST_CASE(test_seq_codegen)
{
using namespace test3;
const UsingSeqTemplates::instruction_type* top_inst = UsingSeqTemplates::instruction();
BOOST_CHECK_EQUAL(top_inst->subinstructions().size(), 3U);
const mfast::sequence_field_instruction* seq1_inst = dynamic_cast<const mfast::sequence_field_instruction*>(top_inst->subinstruction(1));
BOOST_REQUIRE(seq1_inst);
BOOST_CHECK(strcmp(seq1_inst->name(), "seq1")==0);
BOOST_CHECK_EQUAL(seq1_inst->subinstructions().size(), 2U);
BOOST_CHECK_EQUAL(seq1_inst->ref_instruction(), SeqTemplate1::instruction());
BOOST_CHECK_EQUAL(seq1_inst->element_instruction(), (const mfast::group_field_instruction*) 0);
const mfast::sequence_field_instruction* seq2_inst = dynamic_cast<const mfast::sequence_field_instruction*>(top_inst->subinstruction(2));
BOOST_REQUIRE(seq2_inst);
BOOST_CHECK(strcmp(seq2_inst->name(), "seq2")==0);
BOOST_CHECK_EQUAL(seq2_inst->subinstructions().size(), 4U);
BOOST_CHECK_EQUAL(seq2_inst->ref_instruction(), SeqTemplate2::instruction());
BOOST_CHECK_EQUAL(seq2_inst->element_instruction(), BankAccount::instruction());
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include <chrono>
#include "cproc.h"
Cproc::Cproc()
: _running(false)
{
}
Cproc::~Cproc()
{
stop();
}
void Cproc::run(Cimage & image)
{
_running = true;
_thread = std::thread(&Cproc::mt_run, this, std::ref(image));
}
void Cproc::stop()
{
_running = false;
_thread.join();
}
void Cproc::mt_run(Cimage & image)
{
size_t count = 0;
while (_running)
{
printf("%lu. iteration: ", ++count);
image.info();
std::this_thread::sleep_for(
std::chrono::milliseconds(500));
}
}
<commit_msg>Issue #1: added fflush to printf<commit_after>#include <chrono>
#include "cproc.h"
Cproc::Cproc()
: _running(false)
{
}
Cproc::~Cproc()
{
stop();
}
void Cproc::run(Cimage & image)
{
_running = true;
_thread = std::thread(&Cproc::mt_run, this, std::ref(image));
}
void Cproc::stop()
{
_running = false;
_thread.join();
}
void Cproc::mt_run(Cimage & image)
{
size_t count = 0;
while (_running)
{
printf("%lu. iteration: ", ++count);
fflush(stdout);
image.info();
std::this_thread::sleep_for(
std::chrono::milliseconds(500));
}
}
<|endoftext|> |
<commit_before>/*
* MRustC - Mutabah's Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* debug.cpp
* - Debug printing (with indenting)
*/
#include <debug_inner.hpp>
#include <debug.hpp>
#include <set>
#include <iostream>
#include <iomanip>
#include <common.hpp> // FmtEscaped
int g_debug_indent_level = 0;
bool g_debug_enabled = true;
::std::string g_cur_phase;
::std::set< ::std::string> g_debug_disable_map;
TraceLog::TraceLog(const char* tag, ::std::function<void(::std::ostream&)> info_cb, ::std::function<void(::std::ostream&)> ret):
m_tag(tag),
m_ret(ret)
{
if(debug_enabled() && m_tag) {
auto& os = debug_output(g_debug_indent_level, m_tag);
os << ">> (";
info_cb(os);
os << ")" << ::std::endl;
}
INDENT();
}
TraceLog::TraceLog(const char* tag, ::std::function<void(::std::ostream&)> info_cb):
m_tag(tag),
m_ret([](const auto&){})
{
if(debug_enabled() && m_tag) {
auto& os = debug_output(g_debug_indent_level, m_tag);
os << ">> (";
info_cb(os);
os << ")" << ::std::endl;
}
INDENT();
}
TraceLog::TraceLog(const char* tag):
m_tag(tag),
m_ret([](const auto&){})
{
if(debug_enabled() && m_tag) {
auto& os = debug_output(g_debug_indent_level, m_tag);
os << ">>" << ::std::endl;
}
INDENT();
}
TraceLog::~TraceLog() {
UNINDENT();
if(debug_enabled() && m_tag) {
auto& os = debug_output(g_debug_indent_level, m_tag);
os << "<< (";
m_ret(os);
os << ")" << ::std::endl;
}
}
bool debug_enabled_update() {
if( g_debug_disable_map.count(g_cur_phase) != 0 ) {
return false;
}
else {
return true;
}
}
bool debug_enabled()
{
return g_debug_enabled;
}
::std::ostream& debug_output(int indent, const char* function)
{
return ::std::cout << g_cur_phase << "- " << RepeatLitStr { " ", indent } << function << ": ";
}
DebugTimedPhase::DebugTimedPhase(const char* name):
m_name(name)
{
::std::cout << m_name << ": V V V" << ::std::endl;
g_cur_phase = m_name;
g_debug_enabled = debug_enabled_update();
m_start = clock();
}
DebugTimedPhase::~DebugTimedPhase()
{
auto end = clock();
g_cur_phase = "";
g_debug_enabled = debug_enabled_update();
// TODO: Show wall time too?
::std::cout << "(" << ::std::fixed << ::std::setprecision(2) << static_cast<double>(end - m_start) / static_cast<double>(CLOCKS_PER_SEC) << " s) ";
::std::cout << m_name << ": DONE";
::std::cout << ::std::endl;
}
extern void debug_init_phases(const char* env_var_name, std::initializer_list<const char*> il)
{
for(const char* e : il)
{
g_debug_disable_map.insert(e);
}
// Mutate this map using an environment variable
const char* debug_string = ::std::getenv(env_var_name);
if( debug_string )
{
while( debug_string[0] )
{
const char* end = strchr(debug_string, ':');
::std::string s;
if( end )
{
s = ::std::string { debug_string, end };
debug_string = end + 1;
}
else
{
s = debug_string;
}
if( g_debug_disable_map.erase(s) == 0 )
{
::std::cerr << "WARN: Unknown compiler phase '" << s << "' in $" << env_var_name << ::std::endl;
}
if( !end ) {
break;
}
}
}
}
::std::ostream& operator<<(::std::ostream& os, const FmtEscaped& x)
{
os << ::std::hex;
for(auto s = x.s; *s != '\0'; s ++)
{
switch(*s)
{
case '\0': os << "\\0"; break;
case '\n': os << "\\n"; break;
case '\\': os << "\\\\"; break;
case '"': os << "\\\""; break;
default:
uint8_t v = *s;
if( v < 0x80 )
{
if( v < ' ' || v > 0x7F )
os << "\\u{" << ::std::hex << (unsigned int)v << "}";
else
os << v;
}
else if( v < 0xC0 )
;
else if( v < 0xE0 )
{
uint32_t val = (uint32_t)(v & 0x1F) << 6;
v = (uint8_t)*++s; if( (v & 0xC0) != 0x80 ) { s--; continue ; } val |= (uint32_t)v << 6;
os << "\\u{" << ::std::hex << val << "}";
}
else if( v < 0xF0 )
{
uint32_t val = (uint32_t)(v & 0x0F) << 12;
v = (uint8_t)*++s; if( (v & 0xC0) != 0x80 ) { s--; continue ; } val |= (uint32_t)v << 12;
v = (uint8_t)*++s; if( (v & 0xC0) != 0x80 ) { s--; continue ; } val |= (uint32_t)v << 6;
os << "\\u{" << ::std::hex << val << "}";
}
else if( v < 0xF8 )
{
uint32_t val = (uint32_t)(v & 0x07) << 18;
v = (uint8_t)*++s; if( (v & 0xC0) != 0x80 ) { s--; continue ; } val |= (uint32_t)v << 18;
v = (uint8_t)*++s; if( (v & 0xC0) != 0x80 ) { s--; continue ; } val |= (uint32_t)v << 12;
v = (uint8_t)*++s; if( (v & 0xC0) != 0x80 ) { s--; continue ; } val |= (uint32_t)v << 6;
os << "\\u{" << ::std::hex << val << "}";
}
break;
}
}
os << ::std::dec;
return os;
}
<commit_msg>debug - Fix compilation failure on linux<commit_after>/*
* MRustC - Mutabah's Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* debug.cpp
* - Debug printing (with indenting)
*/
#include <debug_inner.hpp>
#include <debug.hpp>
#include <set>
#include <iostream>
#include <iomanip>
#include <common.hpp> // FmtEscaped
#include <cstring> // strchr
int g_debug_indent_level = 0;
bool g_debug_enabled = true;
::std::string g_cur_phase;
::std::set< ::std::string> g_debug_disable_map;
TraceLog::TraceLog(const char* tag, ::std::function<void(::std::ostream&)> info_cb, ::std::function<void(::std::ostream&)> ret):
m_tag(tag),
m_ret(ret)
{
if(debug_enabled() && m_tag) {
auto& os = debug_output(g_debug_indent_level, m_tag);
os << ">> (";
info_cb(os);
os << ")" << ::std::endl;
}
INDENT();
}
TraceLog::TraceLog(const char* tag, ::std::function<void(::std::ostream&)> info_cb):
m_tag(tag),
m_ret([](const auto&){})
{
if(debug_enabled() && m_tag) {
auto& os = debug_output(g_debug_indent_level, m_tag);
os << ">> (";
info_cb(os);
os << ")" << ::std::endl;
}
INDENT();
}
TraceLog::TraceLog(const char* tag):
m_tag(tag),
m_ret([](const auto&){})
{
if(debug_enabled() && m_tag) {
auto& os = debug_output(g_debug_indent_level, m_tag);
os << ">>" << ::std::endl;
}
INDENT();
}
TraceLog::~TraceLog() {
UNINDENT();
if(debug_enabled() && m_tag) {
auto& os = debug_output(g_debug_indent_level, m_tag);
os << "<< (";
m_ret(os);
os << ")" << ::std::endl;
}
}
bool debug_enabled_update() {
if( g_debug_disable_map.count(g_cur_phase) != 0 ) {
return false;
}
else {
return true;
}
}
bool debug_enabled()
{
return g_debug_enabled;
}
::std::ostream& debug_output(int indent, const char* function)
{
return ::std::cout << g_cur_phase << "- " << RepeatLitStr { " ", indent } << function << ": ";
}
DebugTimedPhase::DebugTimedPhase(const char* name):
m_name(name)
{
::std::cout << m_name << ": V V V" << ::std::endl;
g_cur_phase = m_name;
g_debug_enabled = debug_enabled_update();
m_start = clock();
}
DebugTimedPhase::~DebugTimedPhase()
{
auto end = clock();
g_cur_phase = "";
g_debug_enabled = debug_enabled_update();
// TODO: Show wall time too?
::std::cout << "(" << ::std::fixed << ::std::setprecision(2) << static_cast<double>(end - m_start) / static_cast<double>(CLOCKS_PER_SEC) << " s) ";
::std::cout << m_name << ": DONE";
::std::cout << ::std::endl;
}
extern void debug_init_phases(const char* env_var_name, std::initializer_list<const char*> il)
{
for(const char* e : il)
{
g_debug_disable_map.insert(e);
}
// Mutate this map using an environment variable
const char* debug_string = ::std::getenv(env_var_name);
if( debug_string )
{
while( debug_string[0] )
{
const char* end = strchr(debug_string, ':');
::std::string s;
if( end )
{
s = ::std::string { debug_string, end };
debug_string = end + 1;
}
else
{
s = debug_string;
}
if( g_debug_disable_map.erase(s) == 0 )
{
::std::cerr << "WARN: Unknown compiler phase '" << s << "' in $" << env_var_name << ::std::endl;
}
if( !end ) {
break;
}
}
}
}
::std::ostream& operator<<(::std::ostream& os, const FmtEscaped& x)
{
os << ::std::hex;
for(auto s = x.s; *s != '\0'; s ++)
{
switch(*s)
{
case '\0': os << "\\0"; break;
case '\n': os << "\\n"; break;
case '\\': os << "\\\\"; break;
case '"': os << "\\\""; break;
default:
uint8_t v = *s;
if( v < 0x80 )
{
if( v < ' ' || v > 0x7F )
os << "\\u{" << ::std::hex << (unsigned int)v << "}";
else
os << v;
}
else if( v < 0xC0 )
;
else if( v < 0xE0 )
{
uint32_t val = (uint32_t)(v & 0x1F) << 6;
v = (uint8_t)*++s; if( (v & 0xC0) != 0x80 ) { s--; continue ; } val |= (uint32_t)v << 6;
os << "\\u{" << ::std::hex << val << "}";
}
else if( v < 0xF0 )
{
uint32_t val = (uint32_t)(v & 0x0F) << 12;
v = (uint8_t)*++s; if( (v & 0xC0) != 0x80 ) { s--; continue ; } val |= (uint32_t)v << 12;
v = (uint8_t)*++s; if( (v & 0xC0) != 0x80 ) { s--; continue ; } val |= (uint32_t)v << 6;
os << "\\u{" << ::std::hex << val << "}";
}
else if( v < 0xF8 )
{
uint32_t val = (uint32_t)(v & 0x07) << 18;
v = (uint8_t)*++s; if( (v & 0xC0) != 0x80 ) { s--; continue ; } val |= (uint32_t)v << 18;
v = (uint8_t)*++s; if( (v & 0xC0) != 0x80 ) { s--; continue ; } val |= (uint32_t)v << 12;
v = (uint8_t)*++s; if( (v & 0xC0) != 0x80 ) { s--; continue ; } val |= (uint32_t)v << 6;
os << "\\u{" << ::std::hex << val << "}";
}
break;
}
}
os << ::std::dec;
return os;
}
<|endoftext|> |
<commit_before>#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <asyncply/parallel.h>
#include <asyncply/pipeline.h>
#include <asyncply/cmd.h>
int main()
{
using namespace asyncply;
std::cout.sync_with_stdio(false);
std::vector<std::string> lines;
cmd(find("../tests"), grep("test_"), out(lines));
for (auto& line : lines)
std::cout << line << std::endl;
/*
cmd({
find(".."),
grep(".*\\.cpp$|.*\\.h$"),
cat(),
grep("class|struct|typedef|using|void|int|double|float"),
grep_v("enable_if|;|\"|\'"),
trim(),
split(" "),
uniq(),
join(" "),
out()
});
*/
// ssh_session my_ssh_session;
// int rc;
// char* password;
// // Open session and set options
// my_ssh_session = ssh_new();
// if (my_ssh_session == NULL)
// exit(-1);
// ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "localhost");
// // Connect to server
// rc = ssh_connect(my_ssh_session);
// if (rc != SSH_OK)
// {
// fprintf(stderr, "Error connecting to localhost: %s\n", ssh_get_error(my_ssh_session));
// ssh_free(my_ssh_session);
// exit(-1);
// }
// // Verify the server's identity
// // For the source code of verify_knowhost(), check previous example
// if (verify_knownhost(my_ssh_session) < 0)
// {
// ssh_disconnect(my_ssh_session);
// ssh_free(my_ssh_session);
// exit(-1);
// }
// // Authenticate ourselves
// password = getpass("Password: ");
// rc = ssh_userauth_password(my_ssh_session, NULL, password);
// if (rc != SSH_AUTH_SUCCESS)
// {
// fprintf(stderr, "Error authenticating with password: %s\n", ssh_get_error(my_ssh_session));
// ssh_disconnect(my_ssh_session);
// ssh_free(my_ssh_session);
// exit(-1);
// }
//
// std::cout << "connected!" << std::endl;
// show_remote_processes(my_ssh_session);
//
// ssh_disconnect(my_ssh_session);
// ssh_free(my_ssh_session);
//
// fes::async_fast< std::shared_ptr<asyncply::coro<int> > > _channel;
// std::atomic<bool> _exit;
// _exit = false;
// asyncply::parallel(
// [&](){
// while(!_exit)
// {
// _channel.connect([&](const std::shared_ptr<asyncply::coro<int> >& coro) {
// while(*coro)
// {
// int x = coro->get();
// _exit = (x == 1);
// (*coro)();
// }
// });
// _channel.update();
// }
// },
// [&](){
// asyncply::run(
// [&](){
// for(int i=0; i<1000; ++i)
// {
// _channel(asyncply::corun<int>(
// [](asyncply::yield_type<int>& yield)
// {
// std::cout << "create " << std::endl;
// yield(0);
// std::cout << "download " << std::endl;
// yield(0);
// std::cout << "patching " << std::endl;
// yield(0);
// std::cout << "compile " << std::endl;
// yield(0);
// std::cout << "tests " << std::endl;
// yield(0);
// std::cout << "packing " << std::endl;
// yield(0);
// }
// ));
// }
// }
// ,
// [&](){
// _channel(asyncply::corun<int>(
// [](asyncply::yield_type<int>& yield)
// {
// std::cout << "request exit" << std::endl;
// yield(1);
// }
// ));
// }
// );
// },
// [&](){
// _channel(asyncply::corun<int>(
// [](asyncply::yield_type<int>& yield)
// {
// std::cout << "step1 - thread3 " << std::endl;
// yield(0);
// std::cout << "step2 - thread3 " << std::endl;
// yield(0);
// std::cout << "step3 - thread3 " << std::endl;
// yield(0);
// }
// ));
// }
// );
// pipelines in parallel
// try
// {
// auto result = asyncply::parallel(
// [](){
// return "one";
// },
// [](){
// cmd({
// find(".."),
// grep(".*\\.cpp$|.*\\.h$"),
// cat(),
// grep("class|struct|typedef|using|void|int|double|float"),
// grep_v("enable_if|;|\"|\'"),
// trim(),
// split(" "),
// uniq(),
// join(" "),
// out()
// });
// return "two";
// }
// );
// std::cout << result.size() << std::endl;
// for(auto& r : result)
// {
// std::cout << r << std::endl;
// }
// }
// catch(boost::filesystem::filesystem_error& e)
// {
// std::cout << "exception: " << e.what() << std::endl;
// }
}
<commit_msg>Update test_coro.cpp<commit_after>#include <asyncply/cmd.h>
using namespace asyncply;
int main()
{
std::vector<std::string> lines;
cmd(find("../tests"), grep("test_"), out(lines));
for (auto& line : lines)
std::cout << line << std::endl;
/*
cmd({
find(".."),
grep(".*\\.cpp$|.*\\.h$"),
cat(),
grep("class|struct|typedef|using|void|int|double|float"),
grep_v("enable_if|;|\"|\'"),
trim(),
split(" "),
uniq(),
join(" "),
out()
});
*/
// ssh_session my_ssh_session;
// int rc;
// char* password;
// // Open session and set options
// my_ssh_session = ssh_new();
// if (my_ssh_session == NULL)
// exit(-1);
// ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "localhost");
// // Connect to server
// rc = ssh_connect(my_ssh_session);
// if (rc != SSH_OK)
// {
// fprintf(stderr, "Error connecting to localhost: %s\n", ssh_get_error(my_ssh_session));
// ssh_free(my_ssh_session);
// exit(-1);
// }
// // Verify the server's identity
// // For the source code of verify_knowhost(), check previous example
// if (verify_knownhost(my_ssh_session) < 0)
// {
// ssh_disconnect(my_ssh_session);
// ssh_free(my_ssh_session);
// exit(-1);
// }
// // Authenticate ourselves
// password = getpass("Password: ");
// rc = ssh_userauth_password(my_ssh_session, NULL, password);
// if (rc != SSH_AUTH_SUCCESS)
// {
// fprintf(stderr, "Error authenticating with password: %s\n", ssh_get_error(my_ssh_session));
// ssh_disconnect(my_ssh_session);
// ssh_free(my_ssh_session);
// exit(-1);
// }
//
// std::cout << "connected!" << std::endl;
// show_remote_processes(my_ssh_session);
//
// ssh_disconnect(my_ssh_session);
// ssh_free(my_ssh_session);
//
// fes::async_fast< std::shared_ptr<asyncply::coro<int> > > _channel;
// std::atomic<bool> _exit;
// _exit = false;
// asyncply::parallel(
// [&](){
// while(!_exit)
// {
// _channel.connect([&](const std::shared_ptr<asyncply::coro<int> >& coro) {
// while(*coro)
// {
// int x = coro->get();
// _exit = (x == 1);
// (*coro)();
// }
// });
// _channel.update();
// }
// },
// [&](){
// asyncply::run(
// [&](){
// for(int i=0; i<1000; ++i)
// {
// _channel(asyncply::corun<int>(
// [](asyncply::yield_type<int>& yield)
// {
// std::cout << "create " << std::endl;
// yield(0);
// std::cout << "download " << std::endl;
// yield(0);
// std::cout << "patching " << std::endl;
// yield(0);
// std::cout << "compile " << std::endl;
// yield(0);
// std::cout << "tests " << std::endl;
// yield(0);
// std::cout << "packing " << std::endl;
// yield(0);
// }
// ));
// }
// }
// ,
// [&](){
// _channel(asyncply::corun<int>(
// [](asyncply::yield_type<int>& yield)
// {
// std::cout << "request exit" << std::endl;
// yield(1);
// }
// ));
// }
// );
// },
// [&](){
// _channel(asyncply::corun<int>(
// [](asyncply::yield_type<int>& yield)
// {
// std::cout << "step1 - thread3 " << std::endl;
// yield(0);
// std::cout << "step2 - thread3 " << std::endl;
// yield(0);
// std::cout << "step3 - thread3 " << std::endl;
// yield(0);
// }
// ));
// }
// );
// pipelines in parallel
// try
// {
// auto result = asyncply::parallel(
// [](){
// return "one";
// },
// [](){
// cmd({
// find(".."),
// grep(".*\\.cpp$|.*\\.h$"),
// cat(),
// grep("class|struct|typedef|using|void|int|double|float"),
// grep_v("enable_if|;|\"|\'"),
// trim(),
// split(" "),
// uniq(),
// join(" "),
// out()
// });
// return "two";
// }
// );
// std::cout << result.size() << std::endl;
// for(auto& r : result)
// {
// std::cout << r << std::endl;
// }
// }
// catch(boost::filesystem::filesystem_error& e)
// {
// std::cout << "exception: " << e.what() << std::endl;
// }
}
<|endoftext|> |
<commit_before>#include <tests/Base.hh>
#include <aleph/containers/PointCloud.hh>
#include <aleph/geometry/BruteForce.hh>
#include <aleph/geometry/VietorisRipsComplex.hh>
#include <aleph/geometry/distances/Euclidean.hh>
#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/persistentHomology/PhiPersistence.hh>
#include <aleph/topology/BarycentricSubdivision.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <aleph/topology/Skeleton.hh>
#include <aleph/topology/Spine.hh>
#include <aleph/topology/io/LinesAndPoints.hh>
#include <random>
#include <vector>
#include <cmath>
template <class T> void testDisk()
{
ALEPH_TEST_BEGIN( "Spine: disk" );
using DataType = bool;
using VertexType = T;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
std::vector<Simplex> simplices;
unsigned n = 7;
for( unsigned i = 0; i < n; i++ )
{
if( i+1 < n )
simplices.push_back( Simplex( {T(0),T(i+1),T(i+2)} ) );
else
simplices.push_back( Simplex( {T(0),T(i+1),T( 1)} ) );
}
SimplicialComplex K( simplices.begin(), simplices.end() );
K.createMissingFaces();
K.sort();
auto L = aleph::topology::spine( K );
ALEPH_ASSERT_THROW( L.size() < K.size() );
ALEPH_ASSERT_EQUAL( L.size(), 1 );
ALEPH_TEST_END();
}
template <class T> void testPinchedTorus()
{
using DataType = T;
using PointCloud = aleph::containers::PointCloud<DataType>;
ALEPH_TEST_BEGIN( "Spine: pinched torus" );
unsigned n = 40;
unsigned m = 20;
PointCloud pc( n*m, 3 );
auto g = [] ( T x, T y )
{
return T(2) + std::sin(x/2) * std::cos(y);
};
std::random_device rd;
std::mt19937 rng( rd() );
std::normal_distribution<DataType> noise( T(0), T(0.05) );
unsigned k = 0;
for( unsigned i = 0; i < n; i++ )
{
auto x = T( 2*M_PI / n * i );
for( unsigned j = 0; j < m; j++ )
{
auto y = T( 2*M_PI / m * j );
auto x0 = g(x,y) * std::cos(x) + noise( rng );
auto x1 = g(x,y) * std::sin(x) + noise( rng );
auto x2 = std::sin(x/2) * std::sin(y) + noise( rng );
pc.set(k++, {x0,x1,x2} );
}
}
using Distance = aleph::geometry::distances::Euclidean<DataType>;
using NearestNeighbours = aleph::geometry::BruteForce<PointCloud, Distance>;
auto K
= aleph::geometry::buildVietorisRipsComplex(
NearestNeighbours( pc ),
DataType( 0.700 ),
2
);
std::ofstream out( "/tmp/Pinched_torus.txt" );
aleph::topology::io::LinesAndPoints lap;
lap( out, K, pc );
auto D1 = aleph::calculatePersistenceDiagrams( K );
ALEPH_ASSERT_EQUAL( D1.size(), 2 );
ALEPH_ASSERT_EQUAL( D1[0].dimension(), 0 );
ALEPH_ASSERT_EQUAL( D1[1].dimension(), 1 );
ALEPH_ASSERT_EQUAL( D1[1].betti(), 1 );
#if 0
// FIXME: this is still too large to be easily processed by the
// algorithm...
auto L = aleph::topology::spine( K );
ALEPH_ASSERT_THROW( L.size() < K.size() );
auto K0 = aleph::topology::Skeleton()(0, K);
auto K1 = K0;
auto K2 = K;
auto D2 = aleph::calculateIntersectionHomology( L, {K0,K1,K2}, aleph::PerversityGM( {0} ) );
ALEPH_ASSERT_EQUAL( D2.size(), 3 );
#endif
ALEPH_TEST_END();
}
template <class T> void testS1vS1()
{
using DataType = T;
using PointCloud = aleph::containers::PointCloud<DataType>;
ALEPH_TEST_BEGIN( "Spine: S^1 v S^1" );
unsigned n = 50;
PointCloud pc( 2*n - 1, 2 );
unsigned k = 0;
for( unsigned i = 0; i < n; i++ )
{
auto x0 = DataType( std::cos( 2*M_PI / n * i ) );
auto y0 = DataType( std::sin( 2*M_PI / n * i ) );
if( x0 > -1 )
{
auto x1 = x0 + 2;
auto y1 = y0;
pc.set(k++, {x0, y0});
pc.set(k++, {x1, y1});
}
// prevent duplication of singular point
else
pc.set(k++, {x0, y0} );
}
using Distance = aleph::geometry::distances::Euclidean<DataType>;
using NearestNeighbours = aleph::geometry::BruteForce<PointCloud, Distance>;
auto K
= aleph::geometry::buildVietorisRipsComplex(
NearestNeighbours( pc ),
DataType( 0.30 ),
2
);
auto D1 = aleph::calculatePersistenceDiagrams( K );
// Persistent homology -----------------------------------------------
//
// This should not be surprising: it is possible to extract the two
// circles from the data set. They form one connected component.
ALEPH_ASSERT_EQUAL( D1.size(), 2 );
ALEPH_ASSERT_EQUAL( D1[0].betti(), 1 );
ALEPH_ASSERT_EQUAL( D1[1].betti(), 2 );
// Persistent intersection homology ----------------------------------
//
// Regardless of the stratification, it is impossible to detect the
// singularity in dimension 0.
auto L = aleph::topology::BarycentricSubdivision()( K, [] ( std::size_t dimension ) { return dimension == 0 ? 0 : 0.5; } );
auto K0 = aleph::topology::Skeleton()( 0, K );
auto D2 = aleph::calculateIntersectionHomology( L, {K0,K}, aleph::Perversity( {-1} ) );
ALEPH_ASSERT_EQUAL( D2.size(), 3 );
ALEPH_ASSERT_EQUAL( D2[0].dimension(), 0 );
ALEPH_ASSERT_EQUAL( D2[0].betti(), 1 );
// Spine calculation -------------------------------------------------
auto M = aleph::topology::spine( K );
{
auto D = aleph::calculatePersistenceDiagrams( M );
ALEPH_ASSERT_EQUAL( D.size() , 2 );
ALEPH_ASSERT_EQUAL( D[0].dimension(), 0 );
ALEPH_ASSERT_EQUAL( D[1].dimension(), 1 );
ALEPH_ASSERT_EQUAL( D[0].betti(), 1 );
ALEPH_ASSERT_EQUAL( D[1].betti(), 2 );
}
ALEPH_ASSERT_THROW( M.size() < K .size() );
ALEPH_TEST_END();
{
std::ofstream out( "/tmp/M.txt" );
aleph::topology::io::LinesAndPoints lap;
lap( out, M, pc );
}
L = aleph::topology::BarycentricSubdivision()( M, [] ( std::size_t dimension ) { return dimension == 0 ? 0 : 0.5; } );
K0 = { {0} };
auto K1 = aleph::topology::Skeleton()( 2, M );
auto D3 = aleph::calculateIntersectionHomology( L, {K0,M}, aleph::Perversity( {-1,0} ) );
ALEPH_ASSERT_EQUAL( D3.size(), 3 );
ALEPH_ASSERT_EQUAL( D3[0].dimension(), 0 );
ALEPH_ASSERT_EQUAL( D3[0].betti(), 43 );
}
template <class T> void testTriangle()
{
using DataType = bool;
using VertexType = T;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
SimplicialComplex K = {
{0,1,2},
{0,1}, {0,2}, {1,2},
{0}, {1}, {2}
};
auto L = aleph::topology::spine( K );
ALEPH_ASSERT_THROW( L.size() < K.size() );
ALEPH_ASSERT_EQUAL( L.size(), 1 );
}
int main( int, char** )
{
testDisk<short> ();
testDisk<unsigned>();
#if 0
testPinchedTorus<float> ();
testPinchedTorus<double>();
#endif
testS1vS1<float> ();
testS1vS1<double>();
testTriangle<short> ();
testTriangle<unsigned>();
}
<commit_msg>Updated test case<commit_after>#include <tests/Base.hh>
#include <aleph/containers/PointCloud.hh>
#include <aleph/geometry/BruteForce.hh>
#include <aleph/geometry/VietorisRipsComplex.hh>
#include <aleph/geometry/distances/Euclidean.hh>
#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/persistentHomology/PhiPersistence.hh>
#include <aleph/topology/BarycentricSubdivision.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <aleph/topology/Skeleton.hh>
#include <aleph/topology/Spine.hh>
#include <aleph/topology/io/LinesAndPoints.hh>
#include <random>
#include <vector>
#include <cmath>
template <class T> void testDisk()
{
ALEPH_TEST_BEGIN( "Spine: disk" );
using DataType = bool;
using VertexType = T;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
std::vector<Simplex> simplices;
unsigned n = 7;
for( unsigned i = 0; i < n; i++ )
{
if( i+1 < n )
simplices.push_back( Simplex( {T(0),T(i+1),T(i+2)} ) );
else
simplices.push_back( Simplex( {T(0),T(i+1),T( 1)} ) );
}
SimplicialComplex K( simplices.begin(), simplices.end() );
K.createMissingFaces();
K.sort();
auto L = aleph::topology::spine( K );
ALEPH_ASSERT_THROW( L.size() < K.size() );
ALEPH_ASSERT_EQUAL( L.size(), 1 );
ALEPH_TEST_END();
}
template <class T> void testPinchedTorus()
{
using DataType = T;
using PointCloud = aleph::containers::PointCloud<DataType>;
ALEPH_TEST_BEGIN( "Spine: pinched torus" );
unsigned n = 40;
unsigned m = 20;
PointCloud pc( n*m, 3 );
auto g = [] ( T x, T y )
{
return T(2) + std::sin(x/2) * std::cos(y);
};
std::random_device rd;
std::mt19937 rng( rd() );
std::normal_distribution<DataType> noise( T(0), T(0.05) );
unsigned k = 0;
for( unsigned i = 0; i < n; i++ )
{
auto x = T( 2*M_PI / n * i );
for( unsigned j = 0; j < m; j++ )
{
auto y = T( 2*M_PI / m * j );
auto x0 = g(x,y) * std::cos(x) + noise( rng );
auto x1 = g(x,y) * std::sin(x) + noise( rng );
auto x2 = std::sin(x/2) * std::sin(y) + noise( rng );
pc.set(k++, {x0,x1,x2} );
}
}
using Distance = aleph::geometry::distances::Euclidean<DataType>;
using NearestNeighbours = aleph::geometry::BruteForce<PointCloud, Distance>;
auto K
= aleph::geometry::buildVietorisRipsComplex(
NearestNeighbours( pc ),
DataType( 0.700 ),
2
);
std::ofstream out( "/tmp/Pinched_torus.txt" );
aleph::topology::io::LinesAndPoints lap;
lap( out, K, pc );
auto D1 = aleph::calculatePersistenceDiagrams( K );
ALEPH_ASSERT_EQUAL( D1.size(), 2 );
ALEPH_ASSERT_EQUAL( D1[0].dimension(), 0 );
ALEPH_ASSERT_EQUAL( D1[1].dimension(), 1 );
ALEPH_ASSERT_EQUAL( D1[1].betti(), 1 );
#if 0
// FIXME: this is still too large to be easily processed by the
// algorithm...
auto L = aleph::topology::spine( K );
ALEPH_ASSERT_THROW( L.size() < K.size() );
auto K0 = aleph::topology::Skeleton()(0, K);
auto K1 = K0;
auto K2 = K;
auto D2 = aleph::calculateIntersectionHomology( L, {K0,K1,K2}, aleph::PerversityGM( {0} ) );
ALEPH_ASSERT_EQUAL( D2.size(), 3 );
#endif
ALEPH_TEST_END();
}
template <class T> void testS1vS1()
{
using DataType = T;
using PointCloud = aleph::containers::PointCloud<DataType>;
ALEPH_TEST_BEGIN( "Spine: S^1 v S^1" );
unsigned n = 50;
PointCloud pc( 2*n - 1, 2 );
unsigned k = 0;
for( unsigned i = 0; i < n; i++ )
{
auto x0 = DataType( std::cos( 2*M_PI / n * i ) );
auto y0 = DataType( std::sin( 2*M_PI / n * i ) );
if( x0 > -1 )
{
auto x1 = x0 + 2;
auto y1 = y0;
pc.set(k++, {x0, y0});
pc.set(k++, {x1, y1});
}
// prevent duplication of singular point
else
pc.set(k++, {x0, y0} );
}
using Distance = aleph::geometry::distances::Euclidean<DataType>;
using NearestNeighbours = aleph::geometry::BruteForce<PointCloud, Distance>;
auto K
= aleph::geometry::buildVietorisRipsComplex(
NearestNeighbours( pc ),
DataType( 0.30 ),
2
);
auto D1 = aleph::calculatePersistenceDiagrams( K );
// Persistent homology -----------------------------------------------
//
// This should not be surprising: it is possible to extract the two
// circles from the data set. They form one connected component.
ALEPH_ASSERT_EQUAL( D1.size(), 2 );
ALEPH_ASSERT_EQUAL( D1[0].betti(), 1 );
ALEPH_ASSERT_EQUAL( D1[1].betti(), 2 );
// Persistent intersection homology ----------------------------------
//
// Regardless of the stratification, it is impossible to detect the
// singularity in dimension 0.
auto L = aleph::topology::BarycentricSubdivision()( K, [] ( std::size_t dimension ) { return dimension == 0 ? 0 : 0.5; } );
auto K0 = aleph::topology::Skeleton()( 0, K );
auto D2 = aleph::calculateIntersectionHomology( L, {K0,K}, aleph::Perversity( {-1} ) );
ALEPH_ASSERT_EQUAL( D2.size(), 3 );
ALEPH_ASSERT_EQUAL( D2[0].dimension(), 0 );
ALEPH_ASSERT_EQUAL( D2[0].betti(), 1 );
// Spine calculation -------------------------------------------------
auto M = aleph::topology::spine( K );
{
auto D = aleph::calculatePersistenceDiagrams( M );
ALEPH_ASSERT_EQUAL( D.size() , 2 );
ALEPH_ASSERT_EQUAL( D[0].dimension(), 0 );
ALEPH_ASSERT_EQUAL( D[1].dimension(), 1 );
ALEPH_ASSERT_EQUAL( D[0].betti(), 1 );
ALEPH_ASSERT_EQUAL( D[1].betti(), 2 );
}
ALEPH_ASSERT_THROW( M.size() < K .size() );
ALEPH_TEST_END();
{
std::ofstream out( "/tmp/M.txt" );
aleph::topology::io::LinesAndPoints lap;
lap( out, M, pc );
}
L = aleph::topology::BarycentricSubdivision()( M, [] ( std::size_t dimension ) { return dimension == 0 ? 0 : 0.5; } );
L.sort();
K0 = { {0} };
auto D3 = aleph::calculateIntersectionHomology( L, {K0,M}, aleph::Perversity( {0,0} ) );
ALEPH_ASSERT_EQUAL( D3.size(), 3 );
ALEPH_ASSERT_EQUAL( D3[0].dimension(), 0 );
ALEPH_ASSERT_EQUAL( D3[0].betti(), 43 );
}
template <class T> void testTriangle()
{
using DataType = bool;
using VertexType = T;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
SimplicialComplex K = {
{0,1,2},
{0,1}, {0,2}, {1,2},
{0}, {1}, {2}
};
auto L = aleph::topology::spine( K );
ALEPH_ASSERT_THROW( L.size() < K.size() );
ALEPH_ASSERT_EQUAL( L.size(), 1 );
}
int main( int, char** )
{
testDisk<short> ();
testDisk<unsigned>();
#if 0
testPinchedTorus<float> ();
testPinchedTorus<double>();
#endif
testS1vS1<float> ();
testS1vS1<double>();
testTriangle<short> ();
testTriangle<unsigned>();
}
<|endoftext|> |
<commit_before>/**
* @class PMT
* Data Structure: PMT in triggered event
*
* This represents a PMT in a detector event.
*/
#ifndef __RAT_DS_PMT__
#define __RAT_DS_PMT__
namespace RAT {
namespace DS {
class PMT : public TObject {
public:
PMT() : TObject() {}
virtual ~PMT() {}
/** ID number of PMT */
virtual void SetID(Int_t _id) { this->id = _id; }
virtual Int_t GetID() { return id; }
/** Total charge in waveform (pC) */
virtual void SetCharge(Float_t _charge) { this->charge = _charge; }
virtual Float_t GetCharge() { return charge; }
/** Hit time in ns */
virtual void SetTime(Float_t _time) { this->time = _time; }
virtual Float_t GetTime() { return time; }
ClassDef(PMT, 1);
protected:
Int_t id;
Float_t charge;
Float_t time;
};
} // namespace DS
} // namespace RAT
#endif
<commit_msg>Case fix<commit_after>/**
* @class PMT
* Data Structure: PMT in triggered event
*
* This represents a PMT in a detector event.
*/
#ifndef __RAT_DS_PMT__
#define __RAT_DS_PMT__
#include <Rtypes.h>
namespace RAT {
namespace DS {
class PMT : public TObject {
public:
PMT() : TObject() {}
virtual ~PMT() {}
/** ID number of PMT */
virtual void SetID(Int_t _id) { this->id = _id; }
virtual Int_t GetID() { return id; }
/** Total charge in waveform (pC) */
virtual void SetCharge(Float_t _charge) { this->charge = _charge; }
virtual Float_t GetCharge() { return charge; }
/** Hit time in ns */
virtual void SetTime(Float_t _time) { this->time = _time; }
virtual Float_t GetTime() { return time; }
ClassDef(PMT, 1);
protected:
Int_t id;
Float_t charge;
Float_t time;
};
} // namespace DS
} // namespace RAT
#endif
<|endoftext|> |
<commit_before>#include <catch.hpp>
#include <luwra.hpp>
#include <memory>
struct A {
int a;
A(int x = 1338): a(x) {}
};
TEST_CASE("UserTypeRegistration") {
luwra::StateWrapper state;
luwra::registerUserType<A>(state);
}
TEST_CASE("UserTypeConstruction") {
luwra::StateWrapper state;
luwra::registerUserType<A>(state);
luwra::setGlobal(state, "A", LUWRA_WRAP_CONSTRUCTOR(A, int));
// Construction
REQUIRE(luaL_dostring(state, "return A(73)") == 0);
// Check
A* instance = luwra::read<A*>(state, -1);
REQUIRE(instance != nullptr);
REQUIRE(instance->a == 73);
}
struct B {
int n;
const int cn;
volatile int vn;
const volatile int cvn;
B(int val):
n(val),
cn(val),
vn(val),
cvn(val)
{}
};
TEST_CASE("UserTypeFields") {
luwra::StateWrapper state;
// Registration
luwra::registerUserType<B>(
state,
{
LUWRA_MEMBER(B, n),
LUWRA_MEMBER(B, cn),
LUWRA_MEMBER(B, vn),
LUWRA_MEMBER(B, cvn)
}
);
// Instantiation
luwra::Value<B&>::push(state, 1338);
lua_setglobal(state, "value");
B& value = luwra::getGlobal<B&>(state, "value");
// Unqualified get
REQUIRE(luaL_dostring(state, "return value:n()") == 0);
puts(lua_tostring(state, -1));
REQUIRE(luwra::read<int>(state, -1) == value.n);
// Unqualified set
REQUIRE(luaL_dostring(state, "value:n(42)") == 0);
REQUIRE(value.n == 42);
// 'const'-qualified get
REQUIRE(luaL_dostring(state, "return value:cn()") == 0);
REQUIRE(luwra::read<int>(state, -1) == value.cn);
// 'const'-qualified set
REQUIRE(luaL_dostring(state, "value:cn(42)") == 0);
REQUIRE(value.cn == 1338);
// 'volatile' get
REQUIRE(luaL_dostring(state, "return value:vn()") == 0);
REQUIRE(luwra::read<int>(state, -1) == value.vn);
// 'volatile' set
REQUIRE(luaL_dostring(state, "value:vn(42)") == 0);
REQUIRE(value.vn == 42);
// 'const volatile'-qualified get
REQUIRE(luaL_dostring(state, "return value:cvn()") == 0);
REQUIRE(luwra::read<int>(state, -1) == value.cvn);
// 'const volatile'-qualified set
REQUIRE(luaL_dostring(state, "value:cvn(42)") == 0);
REQUIRE(value.cvn == 1338);
}
struct C {
int prop;
C(int val):
prop(val)
{}
int foo1(int x) {
return prop += x;
}
int foo2(int x) const {
return prop + x;
}
int foo3(int x) volatile {
return prop -= x;
}
int foo4(int x) const volatile {
return prop - x;
}
};
TEST_CASE("UserTypeMethods") {
luwra::StateWrapper state;
// Registration
luwra::registerUserType<C>(
state,
{
LUWRA_MEMBER(C, foo1),
LUWRA_MEMBER(C, foo2),
LUWRA_MEMBER(C, foo3),
LUWRA_MEMBER(C, foo4)
}
);
// Instantiation
luwra::Value<C&>::push(state, 1337);
lua_setglobal(state, "value");
C& value = luwra::getGlobal<C&>(state, "value");
// Unqualified method
REQUIRE(luaL_dostring(state, "return value:foo1(63)") == 0);
REQUIRE(value.prop == 1400);
REQUIRE(luwra::read<int>(state, -1) == value.prop);
// 'const'-qualified method
REQUIRE(luaL_dostring(state, "return value:foo2(44)") == 0);
REQUIRE(value.prop == 1400);
REQUIRE(luwra::read<int>(state, -1) == 1444);
// 'volatile'-qualified method
REQUIRE(luaL_dostring(state, "return value:foo3(400)") == 0);
REQUIRE(value.prop == 1000);
REQUIRE(luwra::read<int>(state, -1) == value.prop);
// 'const volatile'-qualified method
REQUIRE(luaL_dostring(state, "return value:foo4(334)") == 0);
REQUIRE(value.prop == 1000);
REQUIRE(luwra::read<int>(state, -1) == 666);
}
TEST_CASE("UserTypeGarbageCollectionRef") {
lua_State* state = luaL_newstate();
// Registration
luwra::registerUserType<std::shared_ptr<int>>(state);
// Instantiation
std::shared_ptr<int> shared_var = std::make_shared<int>(1337);
REQUIRE(shared_var.use_count() == 1);
// Copy construction
luwra::push<std::shared_ptr<int>&>(state, shared_var);
REQUIRE(shared_var.use_count() == 2);
// Garbage collection
lua_close(state);
REQUIRE(shared_var.use_count() == 1);
}
<commit_msg>tests: Use 'registerUserType' which registers the constructor automatically<commit_after>#include <catch.hpp>
#include <luwra.hpp>
#include <memory>
struct A {
int a;
A(int x = 1338): a(x) {}
};
TEST_CASE("UserTypeRegistration") {
luwra::StateWrapper state;
luwra::registerUserType<A>(state);
}
TEST_CASE("UserTypeConstruction") {
luwra::StateWrapper state;
luwra::registerUserType<A(int)>(state, "A");
// Construction
REQUIRE(luaL_dostring(state, "return A(73)") == 0);
// Check
A* instance = luwra::read<A*>(state, -1);
REQUIRE(instance != nullptr);
REQUIRE(instance->a == 73);
}
struct B {
int n;
const int cn;
volatile int vn;
const volatile int cvn;
B(int val):
n(val),
cn(val),
vn(val),
cvn(val)
{}
};
TEST_CASE("UserTypeFields") {
luwra::StateWrapper state;
// Registration
luwra::registerUserType<B>(
state,
{
LUWRA_MEMBER(B, n),
LUWRA_MEMBER(B, cn),
LUWRA_MEMBER(B, vn),
LUWRA_MEMBER(B, cvn)
}
);
// Instantiation
luwra::Value<B&>::push(state, 1338);
lua_setglobal(state, "value");
B& value = luwra::getGlobal<B&>(state, "value");
// Unqualified get
REQUIRE(luaL_dostring(state, "return value:n()") == 0);
puts(lua_tostring(state, -1));
REQUIRE(luwra::read<int>(state, -1) == value.n);
// Unqualified set
REQUIRE(luaL_dostring(state, "value:n(42)") == 0);
REQUIRE(value.n == 42);
// 'const'-qualified get
REQUIRE(luaL_dostring(state, "return value:cn()") == 0);
REQUIRE(luwra::read<int>(state, -1) == value.cn);
// 'const'-qualified set
REQUIRE(luaL_dostring(state, "value:cn(42)") == 0);
REQUIRE(value.cn == 1338);
// 'volatile' get
REQUIRE(luaL_dostring(state, "return value:vn()") == 0);
REQUIRE(luwra::read<int>(state, -1) == value.vn);
// 'volatile' set
REQUIRE(luaL_dostring(state, "value:vn(42)") == 0);
REQUIRE(value.vn == 42);
// 'const volatile'-qualified get
REQUIRE(luaL_dostring(state, "return value:cvn()") == 0);
REQUIRE(luwra::read<int>(state, -1) == value.cvn);
// 'const volatile'-qualified set
REQUIRE(luaL_dostring(state, "value:cvn(42)") == 0);
REQUIRE(value.cvn == 1338);
}
struct C {
int prop;
C(int val):
prop(val)
{}
int foo1(int x) {
return prop += x;
}
int foo2(int x) const {
return prop + x;
}
int foo3(int x) volatile {
return prop -= x;
}
int foo4(int x) const volatile {
return prop - x;
}
};
TEST_CASE("UserTypeMethods") {
luwra::StateWrapper state;
// Registration
luwra::registerUserType<C>(
state,
{
LUWRA_MEMBER(C, foo1),
LUWRA_MEMBER(C, foo2),
LUWRA_MEMBER(C, foo3),
LUWRA_MEMBER(C, foo4)
}
);
// Instantiation
luwra::Value<C&>::push(state, 1337);
lua_setglobal(state, "value");
C& value = luwra::getGlobal<C&>(state, "value");
// Unqualified method
REQUIRE(luaL_dostring(state, "return value:foo1(63)") == 0);
REQUIRE(value.prop == 1400);
REQUIRE(luwra::read<int>(state, -1) == value.prop);
// 'const'-qualified method
REQUIRE(luaL_dostring(state, "return value:foo2(44)") == 0);
REQUIRE(value.prop == 1400);
REQUIRE(luwra::read<int>(state, -1) == 1444);
// 'volatile'-qualified method
REQUIRE(luaL_dostring(state, "return value:foo3(400)") == 0);
REQUIRE(value.prop == 1000);
REQUIRE(luwra::read<int>(state, -1) == value.prop);
// 'const volatile'-qualified method
REQUIRE(luaL_dostring(state, "return value:foo4(334)") == 0);
REQUIRE(value.prop == 1000);
REQUIRE(luwra::read<int>(state, -1) == 666);
}
TEST_CASE("UserTypeGarbageCollectionRef") {
lua_State* state = luaL_newstate();
// Registration
luwra::registerUserType<std::shared_ptr<int>>(state);
// Instantiation
std::shared_ptr<int> shared_var = std::make_shared<int>(1337);
REQUIRE(shared_var.use_count() == 1);
// Copy construction
luwra::push<std::shared_ptr<int>&>(state, shared_var);
REQUIRE(shared_var.use_count() == 2);
// Garbage collection
lua_close(state);
REQUIRE(shared_var.use_count() == 1);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <algorithm>
#include <iostream>
#include <iomanip>
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"
#if defined(_MSC_VER)
namespace std
{
using ::isprint;
}
#define for if (false) {} else for
#endif
namespace
{
template <class T>
void call_destructor(T* o)
{
TORRENT_ASSERT(o);
o->~T();
}
struct compare_string
{
compare_string(char const* s): m_str(s) {}
bool operator()(
std::pair<std::string
, libtorrent::entry> const& e) const
{
return m_str && e.first == m_str;
}
char const* m_str;
};
}
namespace libtorrent
{
namespace detail
{
TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)
{
int sign = 0;
if (val < 0)
{
sign = 1;
val = -val;
}
buf[--size] = '\0';
if (val == 0) buf[--size] = '0';
for (; size > sign && val != 0;)
{
buf[--size] = '0' + char(val % 10);
val /= 10;
}
if (sign) buf[--size] = '-';
return buf + size;
}
}
entry& entry::operator[](char const* key)
{
dictionary_type::iterator i = dict().find(key);
if (i != dict().end()) return i->second;
dictionary_type::iterator ret = dict().insert(
dict().begin()
, std::make_pair(std::string(key), entry()));
return ret->second;
}
entry& entry::operator[](std::string const& key)
{
return (*this)[key.c_str()];
}
entry* entry::find_key(char const* key)
{
dictionary_type::iterator i = std::find_if(
dict().begin()
, dict().end()
, compare_string(key));
if (i == dict().end()) return 0;
return &i->second;
}
entry const* entry::find_key(char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) return 0;
return &i->second;
}
#ifndef BOOST_NO_EXCEPTIONS
const entry& entry::operator[](char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) throw type_error(
(std::string("key not found: ") + key).c_str());
return i->second;
}
const entry& entry::operator[](std::string const& key) const
{
return (*this)[key.c_str()];
}
#endif
entry::entry()
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
}
entry::entry(data_type t)
: m_type(undefined_t)
{
construct(t);
#ifndef NDEBUG
m_type_queried = true;
#endif
}
entry::entry(const entry& e)
: m_type(undefined_t)
{
copy(e);
#ifndef NDEBUG
m_type_queried = e.m_type_queried;
#endif
}
entry::entry(dictionary_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) dictionary_type(v);
m_type = dictionary_t;
}
entry::entry(string_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) string_type(v);
m_type = string_t;
}
entry::entry(list_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) list_type(v);
m_type = list_t;
}
entry::entry(integer_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) integer_type(v);
m_type = int_t;
}
void entry::operator=(dictionary_type const& v)
{
destruct();
new(data) dictionary_type(v);
m_type = dictionary_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(string_type const& v)
{
destruct();
new(data) string_type(v);
m_type = string_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(list_type const& v)
{
destruct();
new(data) list_type(v);
m_type = list_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(integer_type const& v)
{
destruct();
new(data) integer_type(v);
m_type = int_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
bool entry::operator==(entry const& e) const
{
if (m_type != e.m_type) return false;
switch(m_type)
{
case int_t:
return integer() == e.integer();
case string_t:
return string() == e.string();
case list_t:
return list() == e.list();
case dictionary_t:
return dict() == e.dict();
default:
TORRENT_ASSERT(m_type == undefined_t);
return true;
}
}
void entry::construct(data_type t)
{
switch(t)
{
case int_t:
new(data) integer_type;
break;
case string_t:
new(data) string_type;
break;
case list_t:
new(data) list_type;
break;
case dictionary_t:
new (data) dictionary_type;
break;
default:
TORRENT_ASSERT(t == undefined_t);
}
m_type = t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::copy(entry const& e)
{
switch (e.type())
{
case int_t:
new(data) integer_type(e.integer());
break;
case string_t:
new(data) string_type(e.string());
break;
case list_t:
new(data) list_type(e.list());
break;
case dictionary_t:
new (data) dictionary_type(e.dict());
break;
default:
TORRENT_ASSERT(e.type() == undefined_t);
}
m_type = e.type();
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::destruct()
{
switch(m_type)
{
case int_t:
call_destructor(reinterpret_cast<integer_type*>(data));
break;
case string_t:
call_destructor(reinterpret_cast<string_type*>(data));
break;
case list_t:
call_destructor(reinterpret_cast<list_type*>(data));
break;
case dictionary_t:
call_destructor(reinterpret_cast<dictionary_type*>(data));
break;
default:
TORRENT_ASSERT(m_type == undefined_t);
break;
}
m_type = undefined_t;
#ifndef NDEBUG
m_type_queried = false;
#endif
}
void entry::swap(entry& e)
{
// not implemented
TORRENT_ASSERT(false);
}
void entry::print(std::ostream& os, int indent) const
{
TORRENT_ASSERT(indent >= 0);
for (int i = 0; i < indent; ++i) os << " ";
switch (m_type)
{
case int_t:
os << integer() << "\n";
break;
case string_t:
{
bool binary_string = false;
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
{
if (!std::isprint(static_cast<unsigned char>(*i)))
{
binary_string = true;
break;
}
}
if (binary_string)
{
os.unsetf(std::ios_base::dec);
os.setf(std::ios_base::hex);
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
os << std::setfill('0') << std::setw(2)
<< static_cast<unsigned int>((unsigned char)*i);
os.unsetf(std::ios_base::hex);
os.setf(std::ios_base::dec);
os << "\n";
}
else
{
os << string() << "\n";
}
} break;
case list_t:
{
os << "list\n";
for (list_type::const_iterator i = list().begin(); i != list().end(); ++i)
{
i->print(os, indent+1);
}
} break;
case dictionary_t:
{
os << "dictionary\n";
for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)
{
for (int j = 0; j < indent+1; ++j) os << " ";
os << "[" << i->first << "]";
if (i->second.type() != entry::string_t
&& i->second.type() != entry::int_t)
os << "\n";
else os << " ";
i->second.print(os, indent+2);
}
} break;
default:
os << "<uninitialized>\n";
}
}
}
<commit_msg>fixed include issue in entry.cpp<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <iostream>
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"
#if defined(_MSC_VER)
namespace std
{
using ::isprint;
}
#define for if (false) {} else for
#endif
namespace
{
template <class T>
void call_destructor(T* o)
{
TORRENT_ASSERT(o);
o->~T();
}
struct compare_string
{
compare_string(char const* s): m_str(s) {}
bool operator()(
std::pair<std::string
, libtorrent::entry> const& e) const
{
return m_str && e.first == m_str;
}
char const* m_str;
};
}
namespace libtorrent
{
namespace detail
{
TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)
{
int sign = 0;
if (val < 0)
{
sign = 1;
val = -val;
}
buf[--size] = '\0';
if (val == 0) buf[--size] = '0';
for (; size > sign && val != 0;)
{
buf[--size] = '0' + char(val % 10);
val /= 10;
}
if (sign) buf[--size] = '-';
return buf + size;
}
}
entry& entry::operator[](char const* key)
{
dictionary_type::iterator i = dict().find(key);
if (i != dict().end()) return i->second;
dictionary_type::iterator ret = dict().insert(
dict().begin()
, std::make_pair(std::string(key), entry()));
return ret->second;
}
entry& entry::operator[](std::string const& key)
{
return (*this)[key.c_str()];
}
entry* entry::find_key(char const* key)
{
dictionary_type::iterator i = std::find_if(
dict().begin()
, dict().end()
, compare_string(key));
if (i == dict().end()) return 0;
return &i->second;
}
entry const* entry::find_key(char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) return 0;
return &i->second;
}
#ifndef BOOST_NO_EXCEPTIONS
const entry& entry::operator[](char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) throw type_error(
(std::string("key not found: ") + key).c_str());
return i->second;
}
const entry& entry::operator[](std::string const& key) const
{
return (*this)[key.c_str()];
}
#endif
entry::entry()
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
}
entry::entry(data_type t)
: m_type(undefined_t)
{
construct(t);
#ifndef NDEBUG
m_type_queried = true;
#endif
}
entry::entry(const entry& e)
: m_type(undefined_t)
{
copy(e);
#ifndef NDEBUG
m_type_queried = e.m_type_queried;
#endif
}
entry::entry(dictionary_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) dictionary_type(v);
m_type = dictionary_t;
}
entry::entry(string_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) string_type(v);
m_type = string_t;
}
entry::entry(list_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) list_type(v);
m_type = list_t;
}
entry::entry(integer_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) integer_type(v);
m_type = int_t;
}
void entry::operator=(dictionary_type const& v)
{
destruct();
new(data) dictionary_type(v);
m_type = dictionary_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(string_type const& v)
{
destruct();
new(data) string_type(v);
m_type = string_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(list_type const& v)
{
destruct();
new(data) list_type(v);
m_type = list_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(integer_type const& v)
{
destruct();
new(data) integer_type(v);
m_type = int_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
bool entry::operator==(entry const& e) const
{
if (m_type != e.m_type) return false;
switch(m_type)
{
case int_t:
return integer() == e.integer();
case string_t:
return string() == e.string();
case list_t:
return list() == e.list();
case dictionary_t:
return dict() == e.dict();
default:
TORRENT_ASSERT(m_type == undefined_t);
return true;
}
}
void entry::construct(data_type t)
{
switch(t)
{
case int_t:
new(data) integer_type;
break;
case string_t:
new(data) string_type;
break;
case list_t:
new(data) list_type;
break;
case dictionary_t:
new (data) dictionary_type;
break;
default:
TORRENT_ASSERT(t == undefined_t);
}
m_type = t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::copy(entry const& e)
{
switch (e.type())
{
case int_t:
new(data) integer_type(e.integer());
break;
case string_t:
new(data) string_type(e.string());
break;
case list_t:
new(data) list_type(e.list());
break;
case dictionary_t:
new (data) dictionary_type(e.dict());
break;
default:
TORRENT_ASSERT(e.type() == undefined_t);
}
m_type = e.type();
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::destruct()
{
switch(m_type)
{
case int_t:
call_destructor(reinterpret_cast<integer_type*>(data));
break;
case string_t:
call_destructor(reinterpret_cast<string_type*>(data));
break;
case list_t:
call_destructor(reinterpret_cast<list_type*>(data));
break;
case dictionary_t:
call_destructor(reinterpret_cast<dictionary_type*>(data));
break;
default:
TORRENT_ASSERT(m_type == undefined_t);
break;
}
m_type = undefined_t;
#ifndef NDEBUG
m_type_queried = false;
#endif
}
void entry::swap(entry& e)
{
// not implemented
TORRENT_ASSERT(false);
}
void entry::print(std::ostream& os, int indent) const
{
TORRENT_ASSERT(indent >= 0);
for (int i = 0; i < indent; ++i) os << " ";
switch (m_type)
{
case int_t:
os << integer() << "\n";
break;
case string_t:
{
bool binary_string = false;
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
{
if (!std::isprint(static_cast<unsigned char>(*i)))
{
binary_string = true;
break;
}
}
if (binary_string)
{
os.unsetf(std::ios_base::dec);
os.setf(std::ios_base::hex);
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
os << std::setfill('0') << std::setw(2)
<< static_cast<unsigned int>((unsigned char)*i);
os.unsetf(std::ios_base::hex);
os.setf(std::ios_base::dec);
os << "\n";
}
else
{
os << string() << "\n";
}
} break;
case list_t:
{
os << "list\n";
for (list_type::const_iterator i = list().begin(); i != list().end(); ++i)
{
i->print(os, indent+1);
}
} break;
case dictionary_t:
{
os << "dictionary\n";
for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)
{
for (int j = 0; j < indent+1; ++j) os << " ";
os << "[" << i->first << "]";
if (i->second.type() != entry::string_t
&& i->second.type() != entry::int_t)
os << "\n";
else os << " ";
i->second.print(os, indent+2);
}
} break;
default:
os << "<uninitialized>\n";
}
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <iostream>
#include <vector>
#include <set>
#include <sys/socket.h>
#include <net/ethernet.h>
#include <net/if_dl.h>
#include <ifaddrs.h>
// Get Destination Address
#define ETH_GDA(eth) \
(struct ether_addr*)((struct eth_header*)eth->ether_dhost)
// Get Source Address
#define ETH_GSA(eth) \
(struct ether_addr*)((struct eth_header*)eth->ether_shost)
// Set Destination Address
#define ETH_SDA(eth, addr) \
*((struct ether_addr*)((struct eth_header*)eth->ether_dhost)) = *((struct ether_addr*)addr)
// Set Source Address
#define ETH_SSA(eth, addr) \
*((struct ether_addr*)((struct eth_header*)eth->ether_shost)) = *((struct ether_addr*)addr)
void
swap_mac(struct ether_addr* mac1, struct ether_addr* mac2)
{
struct ether_addr tmp;
tmp = *mac1;
*mac1 = *mac2;
*mac2 = tmp;
return;
}
void
printmac(const char* prefix, struct ether_addr* mac, const char* suffix)
{
//struct ether_addr {
// u_char octet[ETHER_ADDR_LEN];
//} __packed;
printf("%s" , prefix);
printf("%02x:", mac->octet[0]);
printf("%02x:" , mac->octet[1]);
printf("%02x:" , mac->octet[2]);
printf("%02x:" , mac->octet[3]);
printf("%02x:" , mac->octet[4]);
printf("%02x " , mac->octet[5]);
printf("%s" , suffix);
return;
}
bool is_exist_if(std::vector<std::string>& v, std::string& s)
{
std::vector<std::string>::iterator it;
bool retval = false;
for (it = v.begin(); it != v.end(); it++) {
if (*it == s) {
retval = true;
}
}
return retval;
}
bool get_mac_addr(const char* ifname, struct ether_addr* retval)
{
struct ifaddrs *ifs;
struct ifaddrs *ifp;
struct sockaddr_dl* dl;
if (getifaddrs(&ifs) != 0) {
PERROR("getifaddrs");
MESG("unabe to get interface info for %s", ifname);
return false;
}
for (ifp=ifs; ifp; ifp=ifp->ifa_next) {
int ifp_family = ifp->ifa_addr->sa_family;
if (ifp->ifa_addr == NULL) {
continue;
} else if (ifp_family != AF_LINK) {
continue;
}
dl = (struct sockaddr_dl*)ifp->ifa_addr;
if (strncmp(ifname, dl->sdl_data, dl->sdl_nlen) == 0) {
memcpy(retval, LLADDR(dl), ETHER_ADDR_LEN);
break;
}
}
freeifaddrs(ifs);
return true;
}
std::vector<std::string>
get_ifname_list()
{
//getmac
struct ifaddrs *ifs;
struct ifaddrs *ifp;
//struct sockaddr_dl* dl;
std::set<std::string> s;
std::vector<std::string> v;
if (getifaddrs(&ifs) != 0) {
PERROR("getifaddrs");
exit(EXIT_FAILURE);
}
for (ifp=ifs; ifp; ifp=ifp->ifa_next) {
int ifp_family = ifp->ifa_addr->sa_family;
if (ifp->ifa_addr == NULL) {
continue;
} else if (ifp_family != AF_LINK) {
continue;
}
s.insert(std::string(ifp->ifa_name));
}
freeifaddrs(ifs);
std::set<std::string>::iterator it;
for (it = s.begin(); it != s.end(); it++) {
v.push_back(*it);
}
return v;
}
<commit_msg>update<commit_after>#pragma once
#include <iostream>
#include <vector>
#include <set>
#include <sys/socket.h>
#include <net/ethernet.h>
#ifndef __linux__
#include <net/if_dl.h>
#endif
#include <ifaddrs.h>
// Get Destination Address
#define ETH_GDA(eth) \
(struct ether_addr*)((struct eth_header*)eth->ether_dhost)
// Get Source Address
#define ETH_GSA(eth) \
(struct ether_addr*)((struct eth_header*)eth->ether_shost)
// Set Destination Address
#define ETH_SDA(eth, addr) \
*((struct ether_addr*)((struct eth_header*)eth->ether_dhost)) = *((struct ether_addr*)addr)
// Set Source Address
#define ETH_SSA(eth, addr) \
*((struct ether_addr*)((struct eth_header*)eth->ether_shost)) = *((struct ether_addr*)addr)
void
swap_mac(struct ether_addr* mac1, struct ether_addr* mac2)
{
struct ether_addr tmp;
tmp = *mac1;
*mac1 = *mac2;
*mac2 = tmp;
return;
}
void
printmac(const char* prefix, struct ether_addr* mac, const char* suffix)
{
//struct ether_addr {
// u_char octet[ETHER_ADDR_LEN];
//} __packed;
printf("%s" , prefix);
printf("%02x:", mac->octet[0]);
printf("%02x:" , mac->octet[1]);
printf("%02x:" , mac->octet[2]);
printf("%02x:" , mac->octet[3]);
printf("%02x:" , mac->octet[4]);
printf("%02x " , mac->octet[5]);
printf("%s" , suffix);
return;
}
bool is_exist_if(std::vector<std::string>& v, std::string& s)
{
std::vector<std::string>::iterator it;
bool retval = false;
for (it = v.begin(); it != v.end(); it++) {
if (*it == s) {
retval = true;
}
}
return retval;
}
bool get_mac_addr(const char* ifname, struct ether_addr* retval)
{
#ifndef __linux
struct ifaddrs *ifs;
struct ifaddrs *ifp;
struct sockaddr_dl* dl;
if (getifaddrs(&ifs) != 0) {
PERROR("getifaddrs");
MESG("unabe to get interface info for %s", ifname);
return false;
}
for (ifp=ifs; ifp; ifp=ifp->ifa_next) {
int ifp_family = ifp->ifa_addr->sa_family;
if (ifp->ifa_addr == NULL) {
continue;
} else if (ifp_family != AF_LINK) {
continue;
}
dl = (struct sockaddr_dl*)ifp->ifa_addr;
if (strncmp(ifname, dl->sdl_data, dl->sdl_nlen) == 0) {
memcpy(retval, LLADDR(dl), ETHER_ADDR_LEN);
break;
}
}
freeifaddrs(ifs);
return true;
#else
{
int fd = 0;
int retval = 0;
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
return false;
}
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name, ifname, strlen(ifname));
if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
close(fd);
return false;
}
close(fd);
memcpy(&nm_mac, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
return true
}
#endif
}
std::vector<std::string>
get_ifname_list()
{
//getmac
struct ifaddrs *ifs;
struct ifaddrs *ifp;
//struct sockaddr_dl* dl;
std::set<std::string> s;
std::vector<std::string> v;
if (getifaddrs(&ifs) != 0) {
PERROR("getifaddrs");
exit(EXIT_FAILURE);
}
for (ifp=ifs; ifp; ifp=ifp->ifa_next) {
int ifp_family = ifp->ifa_addr->sa_family;
if (ifp->ifa_addr == NULL) {
continue;
} else if (ifp_family != AF_LINK) {
continue;
}
s.insert(std::string(ifp->ifa_name));
}
freeifaddrs(ifs);
std::set<std::string>::iterator it;
for (it = s.begin(); it != s.end(); it++) {
v.push_back(*it);
}
return v;
}
<|endoftext|> |
<commit_before>#include "field.hpp"
#include <algorithm>
#include <utility>
#include <cassert>
Field::Field( Cells&& cells, const Dimension width )
: _cells( std::move( cells ) )
, _size( { width, static_cast< Dimension >( _cells.size() / width ) } )
{
assert( static_cast< unsigned int >( _size.x ) * _size.y == _cells.size() );
}
// FloodFills with empty (0)
// TODO: use scanline fill for better speed
static Score floodFill( Field::Cells& cells, const Coordinate size, const Coordinate coord, const Color color )
{
const Field::Cells::size_type index = static_cast< Field::Cells::size_type >( coord.y ) * size.x + coord.x;
if( cells[ index ] != color )
{
return 0;
}
cells[ index ] = 0;
Score count = 1;
if( coord.x > 0 )
{
count += floodFill( cells, size, { static_cast< unsigned int >( coord.x - 1u ), coord.y }, color );
}
if( coord.x + 1 < size.x )
{
count += floodFill( cells, size, { static_cast< unsigned int >( coord.x + 1u ), coord.y }, color );
}
if( coord.y > 0 )
{
count += floodFill( cells, size, { coord.x, static_cast< unsigned int >( coord.y - 1u ) }, color );
}
if( coord.y + 1 < size.y )
{
count += floodFill( cells, size, { coord.x, static_cast< unsigned int >( coord.y + 1u ) }, color );
}
return count;
}
void Field::calculateMoves( PossibleMoves& out_moves ) const
{
thread_local std::vector< Color > cells;
cells = _cells;
Coordinate coord{ 0, 0 };
out_moves.clear();
// stop on first empty column
for( coord.x = 0; coord.x < _size.x && get( { coord.x, 0 } ) != 0; ++coord.x )
{
Color col;
// stop ascent at first empty cell
for( coord.y = 0; coord.y < _size.y && (col = get( coord ) ) != 0; ++coord.y )
{
assert( col != 0 );
Score tiles = floodFill( cells, _size, coord, col );
if( tiles > 1 )
{
out_moves.push_back( { coord, ( tiles - 1 ) * ( tiles - 1 ) } );
}
}
}
}
Score Field::remove( Coordinate coord )
{
Color color = get( coord );
if( color == 0 )
{
return 0;
}
Score tiles = floodFill( _cells, _size, coord, color );
Coordinate pos{ 0, 0 };
// move tiles down
for( pos.x = 0; pos.x < _size.x; ++pos.x )
{
Dimension yOut = 0;
for( pos.y = 0; pos.y < _size.y; ++pos.y )
{
const Color color = get( pos );
if( color == 0 )
{
continue;
}
if( yOut != pos.y )
{
set( Coordinate{ pos.x, yOut }, color );
set( pos, 0 );
}
++yOut;
}
}
// move rows left (empty rows have an empty bottom tile)
Dimension xOut = 0;
for( pos.x = 0; pos.x < _size.x; ++pos.x )
{
pos.y = 0;
if( get( pos ) == 0 )
{
continue;
}
for( pos.y = 0; pos.y < _size.y; ++pos.y )
{
const Color color = get( pos );
if( color == 0 )
{
break;
}
if( pos.x != xOut )
{
set( Coordinate{ xOut, pos.y }, color );
set( pos, 0 );
}
}
++xOut;
}
return ( tiles - 1 ) * ( tiles - 1 );
}
Score Field::calculatePenalty()
{
// sorting in-place, i.e. Field is unusable now
std::sort( _cells.begin(), _cells.end() );
auto it = _cells.begin();
// ignore 0s
while( it != _cells.end() && *it == 0 )
{
++it;
}
if( it == _cells.end() )
{
return 0;
}
Score penalty = 0;
Score curCountMinusOne = 0;
Color curColor = *it;
++it;
while( it != _cells.end() )
{
if( *it != curColor )
{
curColor = *it;
penalty += curCountMinusOne * curCountMinusOne;
curCountMinusOne = 0;
}
else
{
++curCountMinusOne;
}
++it;
}
return penalty + curCountMinusOne * curCountMinusOne;
}
std::ostream& operator<<( std::ostream& os, const Field& field )
{
const Coordinate size = field.getSize();
for( Coordinate pos{ 0, size.y - 1u }; ; --pos.y )
{
for( pos.x = 0; pos.x < size.x; ++pos.x )
{
os << static_cast< unsigned int >( field.get( pos ) );
if( pos.x + 1 < size.x )
{
os << '\t';
}
}
if( pos.y > 0 )
{
os << '\n';
}
else
{
break;
}
}
return os;
}
<commit_msg>reverting casts<commit_after>#include "field.hpp"
#include <algorithm>
#include <utility>
#include <cassert>
Field::Field( Cells&& cells, const Dimension width )
: _cells( std::move( cells ) )
, _size( { width, static_cast< Dimension >( _cells.size() / width ) } )
{
assert( static_cast< unsigned int >( _size.x ) * _size.y == _cells.size() );
}
// FloodFills with empty (0)
// TODO: use scanline fill for better speed
static Score floodFill( Field::Cells& cells, const Coordinate size, const Coordinate coord, const Color color )
{
const Field::Cells::size_type index = static_cast< Field::Cells::size_type >( coord.y ) * size.x + coord.x;
if( cells[ index ] != color )
{
return 0;
}
cells[ index ] = 0;
Score count = 1;
if( coord.x > 0 )
{
count += floodFill( cells, size, { coord.x - 1u, coord.y }, color );
}
if( coord.x + 1 < size.x )
{
count += floodFill( cells, size, { coord.x + 1u, coord.y }, color );
}
if( coord.y > 0 )
{
count += floodFill( cells, size, { coord.x, coord.y - 1u }, color );
}
if( coord.y + 1 < size.y )
{
count += floodFill( cells, size, { coord.x, coord.y + 1u }, color );
}
return count;
}
void Field::calculateMoves( PossibleMoves& out_moves ) const
{
thread_local std::vector< Color > cells;
cells = _cells;
Coordinate coord{ 0, 0 };
out_moves.clear();
// stop on first empty column
for( coord.x = 0; coord.x < _size.x && get( { coord.x, 0 } ) != 0; ++coord.x )
{
Color col;
// stop ascent at first empty cell
for( coord.y = 0; coord.y < _size.y && (col = get( coord ) ) != 0; ++coord.y )
{
assert( col != 0 );
Score tiles = floodFill( cells, _size, coord, col );
if( tiles > 1 )
{
out_moves.push_back( { coord, ( tiles - 1 ) * ( tiles - 1 ) } );
}
}
}
}
Score Field::remove( Coordinate coord )
{
Color color = get( coord );
if( color == 0 )
{
return 0;
}
Score tiles = floodFill( _cells, _size, coord, color );
Coordinate pos{ 0, 0 };
// move tiles down
for( pos.x = 0; pos.x < _size.x; ++pos.x )
{
Dimension yOut = 0;
for( pos.y = 0; pos.y < _size.y; ++pos.y )
{
const Color color = get( pos );
if( color == 0 )
{
continue;
}
if( yOut != pos.y )
{
set( Coordinate{ pos.x, yOut }, color );
set( pos, 0 );
}
++yOut;
}
}
// move rows left (empty rows have an empty bottom tile)
Dimension xOut = 0;
for( pos.x = 0; pos.x < _size.x; ++pos.x )
{
pos.y = 0;
if( get( pos ) == 0 )
{
continue;
}
for( pos.y = 0; pos.y < _size.y; ++pos.y )
{
const Color color = get( pos );
if( color == 0 )
{
break;
}
if( pos.x != xOut )
{
set( Coordinate{ xOut, pos.y }, color );
set( pos, 0 );
}
}
++xOut;
}
return ( tiles - 1 ) * ( tiles - 1 );
}
Score Field::calculatePenalty()
{
// sorting in-place, i.e. Field is unusable now
std::sort( _cells.begin(), _cells.end() );
auto it = _cells.begin();
// ignore 0s
while( it != _cells.end() && *it == 0 )
{
++it;
}
if( it == _cells.end() )
{
return 0;
}
Score penalty = 0;
Score curCountMinusOne = 0;
Color curColor = *it;
++it;
while( it != _cells.end() )
{
if( *it != curColor )
{
curColor = *it;
penalty += curCountMinusOne * curCountMinusOne;
curCountMinusOne = 0;
}
else
{
++curCountMinusOne;
}
++it;
}
return penalty + curCountMinusOne * curCountMinusOne;
}
std::ostream& operator<<( std::ostream& os, const Field& field )
{
const Coordinate size = field.getSize();
for( Coordinate pos{ 0, size.y - 1u }; ; --pos.y )
{
for( pos.x = 0; pos.x < size.x; ++pos.x )
{
os << static_cast< unsigned int >( field.get( pos ) );
if( pos.x + 1 < size.x )
{
os << '\t';
}
}
if( pos.y > 0 )
{
os << '\n';
}
else
{
break;
}
}
return os;
}
<|endoftext|> |
<commit_before>// Copyright Toru Niina 2019.
// Distributed under the MIT License.
#ifndef TOML11_SERIALIZER_HPP
#define TOML11_SERIALIZER_HPP
#include "value.hpp"
#include "lexer.hpp"
#include <limits>
#include <cstdio>
namespace toml
{
struct serializer
{
serializer(const std::size_t w = 80,
const int float_prec = std::numeric_limits<toml::floating>::max_digits10,
const bool can_be_inlined = false,
std::vector<toml::key> ks = {})
: can_be_inlined_(can_be_inlined), float_prec_(float_prec), width_(w),
keys_(std::move(ks))
{}
~serializer() = default;
std::string operator()(const toml::boolean& b) const
{
return b ? "true" : "false";
}
std::string operator()(const integer i) const
{
return std::to_string(i);
}
std::string operator()(const toml::floating f) const
{
const auto fmt = "%.*g";
const auto bsz = std::snprintf(nullptr, 0, fmt, int(this->float_prec_), f);
std::vector<char> buf(bsz + 1, '\0'); // +1 for null character(\0)
std::snprintf(buf.data(), buf.size(), fmt, int(this->float_prec_), f);
std::string token(buf.begin(), buf.end());
if(token.back() == '.') // 1. => 1.0
{
token += '0';
}
const auto e = std::find_if(token.cbegin(), token.cend(),
[](const char c) -> bool {
return c == 'E' || c == 'e';
});
if(e == token.cend())
{
return token; // there is no exponent part. just return it.
}
// zero-prefix in an exponent is not allowed in TOML.
// remove it if it exists.
bool sign_exists = false;
std::size_t zero_prefix = 0;
for(auto iter = std::next(e), iend = token.cend(); iter != iend; ++iter)
{
if(*iter == '+' || *iter == '-'){sign_exists = true; continue;}
if(*iter == '0'){zero_prefix += 1;}
else {break;}
}
if(zero_prefix != 0)
{
const auto offset = std::distance(token.cbegin(), e) +
(sign_exists ? 2 : 1);
token.erase(offset, zero_prefix);
}
return token;
}
std::string operator()(const string& s) const
{
if(s.kind == string_t::basic)
{
if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend())
{
// if linefeed is contained, make it multiline-string.
const std::string open("\"\"\"\n");
const std::string close("\\\n\"\"\"");
return open + this->escape_ml_basic_string(s.str) + close;
}
// no linefeed. try to make it oneline-string.
std::string oneline = this->escape_basic_string(s.str);
if(oneline.size() + 2 < width_ || width_ < 2)
{
const std::string quote("\"");
return quote + oneline + quote;
}
// the line is too long compared to the specified width.
// split it into multiple lines.
std::string token("\"\"\"\n");
while(!oneline.empty())
{
if(oneline.size() < width_)
{
token += oneline;
oneline.clear();
}
else if(oneline.at(width_-2) == '\\')
{
token += oneline.substr(0, width_-2);
token += "\\\n";
oneline.erase(0, width_-2);
}
else
{
token += oneline.substr(0, width_-1);
token += "\\\n";
oneline.erase(0, width_-1);
}
}
return token + std::string("\\\n\"\"\"");
}
else // the string `s` is literal-string.
{
if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend() ||
std::find(s.str.cbegin(), s.str.cend(), '\'') != s.str.cend() )
{
const std::string open("'''\n");
const std::string close("'''");
return open + s.str + close;
}
else
{
const std::string quote("'");
return quote + s.str + quote;
}
}
}
std::string operator()(const local_date& d) const
{
std::ostringstream oss;
oss << d;
return oss.str();
}
std::string operator()(const local_time& t) const
{
std::ostringstream oss;
oss << t;
return oss.str();
}
std::string operator()(const local_datetime& dt) const
{
std::ostringstream oss;
oss << dt;
return oss.str();
}
std::string operator()(const offset_datetime& odt) const
{
std::ostringstream oss;
oss << odt;
return oss.str();
}
std::string operator()(const array& v) const
{
if(!v.empty() && v.front().is(value_t::Table))// v is an array of tables
{
// if it's not inlined, we need to add `[[table.key]]`.
// but if it can be inlined, we need `table.key = [...]`.
if(this->can_be_inlined_)
{
std::string token;
if(!keys_.empty())
{
token += this->serialize_key(keys_.back());
token += " = ";
}
bool width_exceeds = false;
token += "[\n";
for(const auto& item : v)
{
const auto t =
this->make_inline_table(item.cast<value_t::Table>());
if(t.size() + 1 > width_ || // +1 for the last comma {...},
std::find(t.cbegin(), t.cend(), '\n') != t.cend())
{
width_exceeds = true;
break;
}
token += t;
token += ",\n";
}
if(!width_exceeds)
{
token += "]\n";
return token;
}
// if width_exceeds, serialize it as [[array.of.tables]].
}
std::string token;
for(const auto& item : v)
{
token += "[[";
token += this->serialize_dotted_key(keys_);
token += "]]\n";
token += this->make_multiline_table(item.cast<value_t::Table>());
}
return token;
}
if(v.empty())
{
return std::string("[]");
}
// not an array of tables. normal array. first, try to make it inline.
{
const auto inl = this->make_inline_array(v);
if(inl.size() < this->width_ &&
std::find(inl.cbegin(), inl.cend(), '\n') == inl.cend())
{
return inl;
}
}
// if the length exceeds this->width_, print multiline array
std::string token;
std::string current_line;
token += "[\n";
for(const auto& item : v)
{
auto next_elem = toml::visit(*this, item);
// newline between array-value and comma is not allowed
if(next_elem.back() == '\n'){next_elem.pop_back();}
if(current_line.size() + next_elem.size() + 1 < this->width_)
{
current_line += next_elem;
current_line += ',';
}
else if(current_line.empty())
{
// the next elem cannot be within the width.
token += next_elem;
token += ",\n";
// keep current line empty
}
else // current_line has some tokens and it exceeds width
{
assert(current_line.back() == ',');
token += current_line;
token += '\n';
current_line = next_elem;
current_line += ',';
}
}
if(!current_line.empty())
{
if(current_line.back() != '\n') {current_line += '\n';}
token += current_line;
}
token += "]\n";
return token;
}
std::string operator()(const table& v) const
{
if(this->can_be_inlined_)
{
std::string token;
if(!this->keys_.empty())
{
token += this->serialize_key(this->keys_.back());
token += " = ";
}
token += this->make_inline_table(v);
if(token.size() < this->width_)
{
return token;
}
}
std::string token;
if(!keys_.empty())
{
token += '[';
token += this->serialize_dotted_key(keys_);
token += "]\n";
}
token += this->make_multiline_table(v);
return token;
}
private:
std::string serialize_key(const toml::key& key) const
{
detail::location<toml::key> loc(key, key);
detail::lex_unquoted_key::invoke(loc);
if(loc.iter() == loc.end())
{
return key; // all the tokens are consumed. the key is unquoted-key.
}
std::string token("\"");
token += this->escape_basic_string(key);
token += "\"";
return token;
}
std::string serialize_dotted_key(const std::vector<toml::key>& keys) const
{
std::string token;
if(keys.empty()){return token;}
for(const auto& k : keys)
{
token += this->serialize_key(k);
token += '.';
}
token.erase(token.size() - 1, 1); // remove trailing `.`
return token;
}
std::string escape_basic_string(const std::string& s) const
{
//XXX assuming `s` is a valid utf-8 sequence.
std::string retval;
for(const char c : s)
{
switch(c)
{
case '\\': {retval += "\\\\"; break;}
case '\"': {retval += "\\\""; break;}
case '\b': {retval += "\\b"; break;}
case '\t': {retval += "\\t"; break;}
case '\f': {retval += "\\f"; break;}
case '\n': {retval += "\\n"; break;}
case '\r': {retval += "\\r"; break;}
default : {retval += c; break;}
}
}
return retval;
}
std::string escape_ml_basic_string(const std::string& s) const
{
std::string retval;
for(auto i=s.cbegin(), e=s.cend(); i!=e; ++i)
{
switch(*i)
{
case '\\': {retval += "\\\\"; break;}
case '\"': {retval += "\\\""; break;}
case '\b': {retval += "\\b"; break;}
case '\t': {retval += "\\t"; break;}
case '\f': {retval += "\\f"; break;}
case '\n': {retval += "\n"; break;}
case '\r':
{
if(std::next(i) != e && *std::next(i) == '\n')
{
retval += "\r\n";
++i;
}
else
{
retval += "\\r";
}
break;
}
default: {retval += *i; break;}
}
}
return retval;
}
std::string make_inline_array(const array& v) const
{
std::string token;
token += '[';
bool is_first = true;
for(const auto& item : v)
{
if(is_first) {is_first = false;} else {token += ',';}
token += visit(serializer(std::numeric_limits<std::size_t>::max(),
this->float_prec_, true), item);
}
token += ']';
return token;
}
std::string make_inline_table(const table& v) const
{
assert(this->can_be_inlined_);
std::string token;
token += '{';
bool is_first = true;
for(const auto& kv : v)
{
// in inline tables, trailing comma is not allowed (toml-lang #569).
if(is_first) {is_first = false;} else {token += ',';}
token += this->serialize_key(kv.first);
token += '=';
token += visit(serializer(std::numeric_limits<std::size_t>::max(),
this->float_prec_, true), kv.second);
}
token += '}';
return token;
}
std::string make_multiline_table(const table& v) const
{
std::string token;
// print non-table stuff first. because after printing [foo.bar], the
// remaining non-table values will be assigned into [foo.bar], not [foo]
for(const auto kv : v)
{
if(kv.second.is(value_t::Table) || is_array_of_tables(kv.second))
{
continue;
}
const auto key_and_sep = this->serialize_key(kv.first) + " = ";
const auto residual_width = (this->width_ > key_and_sep.size()) ?
this->width_ - key_and_sep.size() : 0;
token += key_and_sep;
token += visit(serializer(residual_width, this->float_prec_, true),
kv.second);
if(token.back() != '\n')
{
token += '\n';
}
}
// normal tables / array of tables
// after multiline table appeared, the other tables cannot be inline
// because the table would be assigned into the table.
// [foo]
// ...
// bar = {...} # <- bar will be a member of [foo].
bool multiline_table_printed = false;
for(const auto& kv : v)
{
if(!kv.second.is(value_t::Table) && !is_array_of_tables(kv.second))
{
continue; // other stuff are already serialized. skip them.
}
std::vector<toml::key> ks(this->keys_);
ks.push_back(kv.first);
auto tmp = visit(serializer(
this->width_, this->float_prec_, !multiline_table_printed, ks),
kv.second);
if((!multiline_table_printed) &&
std::find(tmp.cbegin(), tmp.cend(), '\n') != tmp.cend())
{
multiline_table_printed = true;
}
else
{
// still inline tables only.
tmp += '\n';
}
token += tmp;
}
return token;
}
bool is_array_of_tables(const value& v) const
{
if(!v.is(value_t::Array)) {return false;}
const auto& a = v.cast<value_t::Array>();
return !a.empty() && a.front().is(value_t::Table);
}
private:
bool can_be_inlined_;
int float_prec_;
std::size_t width_;
std::vector<toml::key> keys_;
};
inline std::string
format(const value& v, std::size_t w = 80,
int fprec = std::numeric_limits<toml::floating>::max_digits10)
{
return visit(serializer(w, fprec, true), v);
}
inline std::string
format(const table& t, std::size_t w = 80,
int fprec = std::numeric_limits<toml::floating>::max_digits10)
{
return serializer(w, fprec, true)(t);
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const value& v)
{
// get status of std::setw().
const std::size_t w = os.width();
const int fprec = os.precision();
os.width(0);
// the root object can't be an inline table. so pass `false`.
os << visit(serializer(w, fprec, false), v);
return os;
}
} // toml
#endif// TOML11_SERIALIZER_HPP
<commit_msg>style: remove needless type casting<commit_after>// Copyright Toru Niina 2019.
// Distributed under the MIT License.
#ifndef TOML11_SERIALIZER_HPP
#define TOML11_SERIALIZER_HPP
#include "value.hpp"
#include "lexer.hpp"
#include <limits>
#include <cstdio>
namespace toml
{
struct serializer
{
serializer(const std::size_t w = 80,
const int float_prec = std::numeric_limits<toml::floating>::max_digits10,
const bool can_be_inlined = false,
std::vector<toml::key> ks = {})
: can_be_inlined_(can_be_inlined), float_prec_(float_prec), width_(w),
keys_(std::move(ks))
{}
~serializer() = default;
std::string operator()(const toml::boolean& b) const
{
return b ? "true" : "false";
}
std::string operator()(const integer i) const
{
return std::to_string(i);
}
std::string operator()(const toml::floating f) const
{
const auto fmt = "%.*g";
const auto bsz = std::snprintf(nullptr, 0, fmt, this->float_prec_, f);
std::vector<char> buf(bsz + 1, '\0'); // +1 for null character(\0)
std::snprintf(buf.data(), buf.size(), fmt, this->float_prec_, f);
std::string token(buf.begin(), buf.end());
if(token.back() == '.') // 1. => 1.0
{
token += '0';
}
const auto e = std::find_if(token.cbegin(), token.cend(),
[](const char c) -> bool {
return c == 'E' || c == 'e';
});
if(e == token.cend())
{
return token; // there is no exponent part. just return it.
}
// zero-prefix in an exponent is not allowed in TOML.
// remove it if it exists.
bool sign_exists = false;
std::size_t zero_prefix = 0;
for(auto iter = std::next(e), iend = token.cend(); iter != iend; ++iter)
{
if(*iter == '+' || *iter == '-'){sign_exists = true; continue;}
if(*iter == '0'){zero_prefix += 1;}
else {break;}
}
if(zero_prefix != 0)
{
const auto offset = std::distance(token.cbegin(), e) +
(sign_exists ? 2 : 1);
token.erase(offset, zero_prefix);
}
return token;
}
std::string operator()(const string& s) const
{
if(s.kind == string_t::basic)
{
if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend())
{
// if linefeed is contained, make it multiline-string.
const std::string open("\"\"\"\n");
const std::string close("\\\n\"\"\"");
return open + this->escape_ml_basic_string(s.str) + close;
}
// no linefeed. try to make it oneline-string.
std::string oneline = this->escape_basic_string(s.str);
if(oneline.size() + 2 < width_ || width_ < 2)
{
const std::string quote("\"");
return quote + oneline + quote;
}
// the line is too long compared to the specified width.
// split it into multiple lines.
std::string token("\"\"\"\n");
while(!oneline.empty())
{
if(oneline.size() < width_)
{
token += oneline;
oneline.clear();
}
else if(oneline.at(width_-2) == '\\')
{
token += oneline.substr(0, width_-2);
token += "\\\n";
oneline.erase(0, width_-2);
}
else
{
token += oneline.substr(0, width_-1);
token += "\\\n";
oneline.erase(0, width_-1);
}
}
return token + std::string("\\\n\"\"\"");
}
else // the string `s` is literal-string.
{
if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend() ||
std::find(s.str.cbegin(), s.str.cend(), '\'') != s.str.cend() )
{
const std::string open("'''\n");
const std::string close("'''");
return open + s.str + close;
}
else
{
const std::string quote("'");
return quote + s.str + quote;
}
}
}
std::string operator()(const local_date& d) const
{
std::ostringstream oss;
oss << d;
return oss.str();
}
std::string operator()(const local_time& t) const
{
std::ostringstream oss;
oss << t;
return oss.str();
}
std::string operator()(const local_datetime& dt) const
{
std::ostringstream oss;
oss << dt;
return oss.str();
}
std::string operator()(const offset_datetime& odt) const
{
std::ostringstream oss;
oss << odt;
return oss.str();
}
std::string operator()(const array& v) const
{
if(!v.empty() && v.front().is(value_t::Table))// v is an array of tables
{
// if it's not inlined, we need to add `[[table.key]]`.
// but if it can be inlined, we need `table.key = [...]`.
if(this->can_be_inlined_)
{
std::string token;
if(!keys_.empty())
{
token += this->serialize_key(keys_.back());
token += " = ";
}
bool width_exceeds = false;
token += "[\n";
for(const auto& item : v)
{
const auto t =
this->make_inline_table(item.cast<value_t::Table>());
if(t.size() + 1 > width_ || // +1 for the last comma {...},
std::find(t.cbegin(), t.cend(), '\n') != t.cend())
{
width_exceeds = true;
break;
}
token += t;
token += ",\n";
}
if(!width_exceeds)
{
token += "]\n";
return token;
}
// if width_exceeds, serialize it as [[array.of.tables]].
}
std::string token;
for(const auto& item : v)
{
token += "[[";
token += this->serialize_dotted_key(keys_);
token += "]]\n";
token += this->make_multiline_table(item.cast<value_t::Table>());
}
return token;
}
if(v.empty())
{
return std::string("[]");
}
// not an array of tables. normal array. first, try to make it inline.
{
const auto inl = this->make_inline_array(v);
if(inl.size() < this->width_ &&
std::find(inl.cbegin(), inl.cend(), '\n') == inl.cend())
{
return inl;
}
}
// if the length exceeds this->width_, print multiline array
std::string token;
std::string current_line;
token += "[\n";
for(const auto& item : v)
{
auto next_elem = toml::visit(*this, item);
// newline between array-value and comma is not allowed
if(next_elem.back() == '\n'){next_elem.pop_back();}
if(current_line.size() + next_elem.size() + 1 < this->width_)
{
current_line += next_elem;
current_line += ',';
}
else if(current_line.empty())
{
// the next elem cannot be within the width.
token += next_elem;
token += ",\n";
// keep current line empty
}
else // current_line has some tokens and it exceeds width
{
assert(current_line.back() == ',');
token += current_line;
token += '\n';
current_line = next_elem;
current_line += ',';
}
}
if(!current_line.empty())
{
if(current_line.back() != '\n') {current_line += '\n';}
token += current_line;
}
token += "]\n";
return token;
}
std::string operator()(const table& v) const
{
if(this->can_be_inlined_)
{
std::string token;
if(!this->keys_.empty())
{
token += this->serialize_key(this->keys_.back());
token += " = ";
}
token += this->make_inline_table(v);
if(token.size() < this->width_)
{
return token;
}
}
std::string token;
if(!keys_.empty())
{
token += '[';
token += this->serialize_dotted_key(keys_);
token += "]\n";
}
token += this->make_multiline_table(v);
return token;
}
private:
std::string serialize_key(const toml::key& key) const
{
detail::location<toml::key> loc(key, key);
detail::lex_unquoted_key::invoke(loc);
if(loc.iter() == loc.end())
{
return key; // all the tokens are consumed. the key is unquoted-key.
}
std::string token("\"");
token += this->escape_basic_string(key);
token += "\"";
return token;
}
std::string serialize_dotted_key(const std::vector<toml::key>& keys) const
{
std::string token;
if(keys.empty()){return token;}
for(const auto& k : keys)
{
token += this->serialize_key(k);
token += '.';
}
token.erase(token.size() - 1, 1); // remove trailing `.`
return token;
}
std::string escape_basic_string(const std::string& s) const
{
//XXX assuming `s` is a valid utf-8 sequence.
std::string retval;
for(const char c : s)
{
switch(c)
{
case '\\': {retval += "\\\\"; break;}
case '\"': {retval += "\\\""; break;}
case '\b': {retval += "\\b"; break;}
case '\t': {retval += "\\t"; break;}
case '\f': {retval += "\\f"; break;}
case '\n': {retval += "\\n"; break;}
case '\r': {retval += "\\r"; break;}
default : {retval += c; break;}
}
}
return retval;
}
std::string escape_ml_basic_string(const std::string& s) const
{
std::string retval;
for(auto i=s.cbegin(), e=s.cend(); i!=e; ++i)
{
switch(*i)
{
case '\\': {retval += "\\\\"; break;}
case '\"': {retval += "\\\""; break;}
case '\b': {retval += "\\b"; break;}
case '\t': {retval += "\\t"; break;}
case '\f': {retval += "\\f"; break;}
case '\n': {retval += "\n"; break;}
case '\r':
{
if(std::next(i) != e && *std::next(i) == '\n')
{
retval += "\r\n";
++i;
}
else
{
retval += "\\r";
}
break;
}
default: {retval += *i; break;}
}
}
return retval;
}
std::string make_inline_array(const array& v) const
{
std::string token;
token += '[';
bool is_first = true;
for(const auto& item : v)
{
if(is_first) {is_first = false;} else {token += ',';}
token += visit(serializer(std::numeric_limits<std::size_t>::max(),
this->float_prec_, true), item);
}
token += ']';
return token;
}
std::string make_inline_table(const table& v) const
{
assert(this->can_be_inlined_);
std::string token;
token += '{';
bool is_first = true;
for(const auto& kv : v)
{
// in inline tables, trailing comma is not allowed (toml-lang #569).
if(is_first) {is_first = false;} else {token += ',';}
token += this->serialize_key(kv.first);
token += '=';
token += visit(serializer(std::numeric_limits<std::size_t>::max(),
this->float_prec_, true), kv.second);
}
token += '}';
return token;
}
std::string make_multiline_table(const table& v) const
{
std::string token;
// print non-table stuff first. because after printing [foo.bar], the
// remaining non-table values will be assigned into [foo.bar], not [foo]
for(const auto kv : v)
{
if(kv.second.is(value_t::Table) || is_array_of_tables(kv.second))
{
continue;
}
const auto key_and_sep = this->serialize_key(kv.first) + " = ";
const auto residual_width = (this->width_ > key_and_sep.size()) ?
this->width_ - key_and_sep.size() : 0;
token += key_and_sep;
token += visit(serializer(residual_width, this->float_prec_, true),
kv.second);
if(token.back() != '\n')
{
token += '\n';
}
}
// normal tables / array of tables
// after multiline table appeared, the other tables cannot be inline
// because the table would be assigned into the table.
// [foo]
// ...
// bar = {...} # <- bar will be a member of [foo].
bool multiline_table_printed = false;
for(const auto& kv : v)
{
if(!kv.second.is(value_t::Table) && !is_array_of_tables(kv.second))
{
continue; // other stuff are already serialized. skip them.
}
std::vector<toml::key> ks(this->keys_);
ks.push_back(kv.first);
auto tmp = visit(serializer(
this->width_, this->float_prec_, !multiline_table_printed, ks),
kv.second);
if((!multiline_table_printed) &&
std::find(tmp.cbegin(), tmp.cend(), '\n') != tmp.cend())
{
multiline_table_printed = true;
}
else
{
// still inline tables only.
tmp += '\n';
}
token += tmp;
}
return token;
}
bool is_array_of_tables(const value& v) const
{
if(!v.is(value_t::Array)) {return false;}
const auto& a = v.cast<value_t::Array>();
return !a.empty() && a.front().is(value_t::Table);
}
private:
bool can_be_inlined_;
int float_prec_;
std::size_t width_;
std::vector<toml::key> keys_;
};
inline std::string
format(const value& v, std::size_t w = 80,
int fprec = std::numeric_limits<toml::floating>::max_digits10)
{
return visit(serializer(w, fprec, true), v);
}
inline std::string
format(const table& t, std::size_t w = 80,
int fprec = std::numeric_limits<toml::floating>::max_digits10)
{
return serializer(w, fprec, true)(t);
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const value& v)
{
// get status of std::setw().
const std::size_t w = os.width();
const int fprec = os.precision();
os.width(0);
// the root object can't be an inline table. so pass `false`.
os << visit(serializer(w, fprec, false), v);
return os;
}
} // toml
#endif// TOML11_SERIALIZER_HPP
<|endoftext|> |
<commit_before>#include "input.h"
#include "engine.h"
P<WindowManager> InputHandler::windowManager;
bool InputHandler::touch_screen = false;
glm::mat3x3 InputHandler::mouse_transform;
PVector<InputEventHandler> InputHandler::input_event_handlers;
PVector<JoystickEventHandler> InputHandler::joystick_event_handlers;
#warning TODO SDL2 this no longer works, SDLK_Keycode will be out of range. Port SP2 keybindings.
bool InputHandler::keyboard_button_down[256];
bool InputHandler::keyboard_button_pressed[256];
bool InputHandler::keyboard_button_released[256];
SDL_KeyboardEvent InputHandler::last_key_press;
glm::vec2 InputHandler::mouse_position;
float InputHandler::mouse_wheel_delta;
bool InputHandler::mouse_button_down[5];
bool InputHandler::mouse_button_pressed[5];
bool InputHandler::mouse_button_released[5];
float InputHandler::joystick_axis_pos[4][4];
float InputHandler::joystick_axis_changed[4][4];
bool InputHandler::joystick_button_down[4][4];
bool InputHandler::joystick_button_changed[4][4];
InputEventHandler::InputEventHandler()
{
InputHandler::input_event_handlers.push_back(this);
}
InputEventHandler::~InputEventHandler()
{
}
JoystickEventHandler::JoystickEventHandler()
{
InputHandler::joystick_event_handlers.push_back(this);
}
JoystickEventHandler::~JoystickEventHandler()
{
}
void InputHandler::initialize()
{
memset(mouse_button_down, 0, sizeof(mouse_button_down));
memset(keyboard_button_down, 0, sizeof(keyboard_button_down));
memset(joystick_axis_pos, 0, sizeof(joystick_axis_pos));
#ifdef __ANDROID__
touch_screen = true;
#endif
last_key_press.keysym.sym = SDLK_UNKNOWN;
}
void InputHandler::preEventsUpdate()
{
if (!windowManager)
windowManager = engine->getObject("windowManager");
for(unsigned int n=0; n<256; n++)
{
if (keyboard_button_pressed[n])
keyboard_button_pressed[n] = false;
else
keyboard_button_released[n] = false;
}
for(unsigned int n=0; n<256; n++)
{
if (mouse_button_pressed[n])
mouse_button_pressed[n] = false;
else
mouse_button_released[n] = false;
}
for(unsigned int i=0; i<4; i++)
{
for(unsigned int n=0; n<4; n++)
{
joystick_axis_changed[i][n] = false;
}
for(unsigned int n=0; n<4; n++)
{
joystick_button_changed[i][n] = false;
}
}
mouse_wheel_delta = 0;
}
void InputHandler::handleEvent(const SDL_Event& event)
{
if (event.type == SDL_KEYDOWN)
{
if (event.key.keysym.sym > -1 && event.key.keysym.sym < 256)
{
keyboard_button_down[event.key.keysym.sym] = true;
keyboard_button_pressed[event.key.keysym.sym] = true;
}
last_key_press = event.key;
}
else if (event.type == SDL_KEYUP)
{
if (event.key.keysym.sym > -1 && event.key.keysym.sym < 256)
{
keyboard_button_down[event.key.keysym.sym] = false;
keyboard_button_released[event.key.keysym.sym] = true;
}
}
else if (event.type == SDL_TEXTINPUT && event.text.text[0] > 31 && event.text.text[0] < 128)
{
if (last_key_press.keysym.sym != SDLK_UNKNOWN)
{
fireKeyEvent(last_key_press, event.text.text[0]);
last_key_press.keysym.sym = SDLK_UNKNOWN;
}
}
else if (event.type == SDL_MOUSEWHEEL)
mouse_wheel_delta += event.wheel.y;
if (event.type == SDL_MOUSEBUTTONDOWN)
{
mouse_button_down[event.button.button] = true;
mouse_button_pressed[event.button.button] = true;
}
else if (event.type == SDL_MOUSEBUTTONUP)
{
mouse_button_down[event.button.button] = false;
mouse_button_released[event.button.button] = true;
}
/*
else if (event.type == SDL_JOYAXISMOTION)
{
static constexpr float scale_factor = 100.f / (100.f - joystick_axis_snap_to_0_range);
float axis_pos = 0.f;
if (event.jaxis.value > joystick_axis_snap_to_0_range) {
axis_pos = (event.jaxis.value - joystick_axis_snap_to_0_range) * scale_factor;
} else if (event.jaxis.value < -joystick_axis_snap_to_0_range) {
axis_pos = (event.jaxis.value + joystick_axis_snap_to_0_range) * scale_factor;
}
// Clamp axis_pos within SFML range.
axis_pos = std::min(std::max(-100.f, axis_pos), 100.f);
if (joystick_axis_pos[event.jaxis.which][event.jaxis.axis] != axis_pos){
joystick_axis_changed[event.jaxis.which][event.jaxis.axis] = true;
}
joystick_axis_pos[event.joystickMove.joystickId][event.joystickMove.axis] = axis_pos;
}
else if (event.type == sf::Event::JoystickButtonPressed)
{
joystick_button_down[event.joystickMove.joystickId][event.joystickButton.button] = true;
joystick_button_changed[event.joystickMove.joystickId][event.joystickButton.button] = true;
}
else if (event.type == sf::Event::JoystickButtonReleased)
{
joystick_button_down[event.joystickMove.joystickId][event.joystickButton.button] = false;
joystick_button_changed[event.joystickMove.joystickId][event.joystickButton.button] = true;
}
else if (event.type == sf::Event::LostFocus)
{
for(unsigned int n=0; n<sf::Keyboard::KeyCount; n++)
{
keyboard_button_down[n] = false;
}
}
*/
}
void InputHandler::postEventsUpdate()
{
input_event_handlers.update();
joystick_event_handlers.update();
if (last_key_press.keysym.sym != SDLK_UNKNOWN)
{
InputHandler::fireKeyEvent(last_key_press, -1);
last_key_press.keysym.sym = SDLK_UNKNOWN;
}
#ifdef __ANDROID__
if (sf::Touch::isDown(0))
{
mouse_position = realWindowPosToVirtual(sf::Touch::getPosition(0));
if (!mouse_button_down[sf::Mouse::Left])
mouse_button_pressed[sf::Mouse::Left] = true;
mouse_button_down[sf::Mouse::Left] = true;
}else{
if (mouse_button_down[sf::Mouse::Left])
mouse_button_released[sf::Mouse::Left] = true;
mouse_button_down[sf::Mouse::Left] = false;
}
#else
int x, y;
SDL_GetMouseState(&x, &y);
mouse_position = realWindowPosToVirtual({x, y});
#endif
#warning SDL2 TODO
//mouse_position = mouse_transform * mouse_position;
if (touch_screen)
{
bool any_button_down = false;
for(unsigned int n=0; n<5; n++)
if (mouse_button_down[n] || mouse_button_released[n])
any_button_down = true;
if (!any_button_down)
{
mouse_position = {-1, -1};
}
}
for(unsigned int i=0; i<4; i++)
{
for(unsigned int n=0; n<4; n++)
{
if(joystick_axis_changed[i][n])
{
foreach(JoystickEventHandler, e, joystick_event_handlers)
{
e->handleJoystickAxis(i, n, joystick_axis_pos[i][n]);
}
}
}
for(unsigned int n=0; n<4; n++)
{
if(joystick_button_changed[i][n])
{
foreach(JoystickEventHandler, e, joystick_event_handlers)
{
e->handleJoystickButton(i, n, joystick_button_down[i][n]);
}
}
}
}
}
void InputHandler::setMousePos(glm::vec2 position)
{
if (!windowManager)
windowManager = engine->getObject("windowManager");
//sf::Mouse::setPosition(virtualWindowPosToReal(position), windowManager->window);
//mouse_position = realWindowPosToVirtual(sf::Mouse::getPosition(windowManager->window));
}
void InputHandler::fireKeyEvent(const SDL_KeyboardEvent& key, int unicode)
{
foreach(InputEventHandler, e, input_event_handlers)
{
e->handleKeyPress(key, unicode);
}
}
glm::vec2 InputHandler::realWindowPosToVirtual(glm::ivec2 position)
{
return windowManager->mapPixelToCoords(position);
}
glm::ivec2 InputHandler::virtualWindowPosToReal(glm::vec2 position)
{
return windowManager->mapCoordsToPixel(position);
}
<commit_msg>Ooops<commit_after>#include "input.h"
#include "engine.h"
P<WindowManager> InputHandler::windowManager;
bool InputHandler::touch_screen = false;
glm::mat3x3 InputHandler::mouse_transform;
PVector<InputEventHandler> InputHandler::input_event_handlers;
PVector<JoystickEventHandler> InputHandler::joystick_event_handlers;
#warning TODO SDL2 this no longer works, SDLK_Keycode will be out of range. Port SP2 keybindings.
bool InputHandler::keyboard_button_down[256];
bool InputHandler::keyboard_button_pressed[256];
bool InputHandler::keyboard_button_released[256];
SDL_KeyboardEvent InputHandler::last_key_press;
glm::vec2 InputHandler::mouse_position;
float InputHandler::mouse_wheel_delta;
bool InputHandler::mouse_button_down[5];
bool InputHandler::mouse_button_pressed[5];
bool InputHandler::mouse_button_released[5];
float InputHandler::joystick_axis_pos[4][4];
float InputHandler::joystick_axis_changed[4][4];
bool InputHandler::joystick_button_down[4][4];
bool InputHandler::joystick_button_changed[4][4];
InputEventHandler::InputEventHandler()
{
InputHandler::input_event_handlers.push_back(this);
}
InputEventHandler::~InputEventHandler()
{
}
JoystickEventHandler::JoystickEventHandler()
{
InputHandler::joystick_event_handlers.push_back(this);
}
JoystickEventHandler::~JoystickEventHandler()
{
}
void InputHandler::initialize()
{
memset(mouse_button_down, 0, sizeof(mouse_button_down));
memset(keyboard_button_down, 0, sizeof(keyboard_button_down));
memset(joystick_axis_pos, 0, sizeof(joystick_axis_pos));
#ifdef __ANDROID__
touch_screen = true;
#endif
last_key_press.keysym.sym = SDLK_UNKNOWN;
}
void InputHandler::preEventsUpdate()
{
if (!windowManager)
windowManager = engine->getObject("windowManager");
for(unsigned int n=0; n<256; n++)
{
if (keyboard_button_pressed[n])
keyboard_button_pressed[n] = false;
else
keyboard_button_released[n] = false;
}
for(unsigned int n=0; n<5; n++)
{
if (mouse_button_pressed[n])
mouse_button_pressed[n] = false;
else
mouse_button_released[n] = false;
}
for(unsigned int i=0; i<4; i++)
{
for(unsigned int n=0; n<4; n++)
{
joystick_axis_changed[i][n] = false;
}
for(unsigned int n=0; n<4; n++)
{
joystick_button_changed[i][n] = false;
}
}
mouse_wheel_delta = 0;
}
void InputHandler::handleEvent(const SDL_Event& event)
{
if (event.type == SDL_KEYDOWN)
{
if (event.key.keysym.sym > -1 && event.key.keysym.sym < 256)
{
keyboard_button_down[event.key.keysym.sym] = true;
keyboard_button_pressed[event.key.keysym.sym] = true;
}
last_key_press = event.key;
}
else if (event.type == SDL_KEYUP)
{
if (event.key.keysym.sym > -1 && event.key.keysym.sym < 256)
{
keyboard_button_down[event.key.keysym.sym] = false;
keyboard_button_released[event.key.keysym.sym] = true;
}
}
else if (event.type == SDL_TEXTINPUT && event.text.text[0] > 31 && event.text.text[0] < 128)
{
if (last_key_press.keysym.sym != SDLK_UNKNOWN)
{
fireKeyEvent(last_key_press, event.text.text[0]);
last_key_press.keysym.sym = SDLK_UNKNOWN;
}
}
else if (event.type == SDL_MOUSEWHEEL)
mouse_wheel_delta += event.wheel.y;
if (event.type == SDL_MOUSEBUTTONDOWN)
{
mouse_button_down[event.button.button] = true;
mouse_button_pressed[event.button.button] = true;
}
else if (event.type == SDL_MOUSEBUTTONUP)
{
mouse_button_down[event.button.button] = false;
mouse_button_released[event.button.button] = true;
}
/*
else if (event.type == SDL_JOYAXISMOTION)
{
static constexpr float scale_factor = 100.f / (100.f - joystick_axis_snap_to_0_range);
float axis_pos = 0.f;
if (event.jaxis.value > joystick_axis_snap_to_0_range) {
axis_pos = (event.jaxis.value - joystick_axis_snap_to_0_range) * scale_factor;
} else if (event.jaxis.value < -joystick_axis_snap_to_0_range) {
axis_pos = (event.jaxis.value + joystick_axis_snap_to_0_range) * scale_factor;
}
// Clamp axis_pos within SFML range.
axis_pos = std::min(std::max(-100.f, axis_pos), 100.f);
if (joystick_axis_pos[event.jaxis.which][event.jaxis.axis] != axis_pos){
joystick_axis_changed[event.jaxis.which][event.jaxis.axis] = true;
}
joystick_axis_pos[event.joystickMove.joystickId][event.joystickMove.axis] = axis_pos;
}
else if (event.type == sf::Event::JoystickButtonPressed)
{
joystick_button_down[event.joystickMove.joystickId][event.joystickButton.button] = true;
joystick_button_changed[event.joystickMove.joystickId][event.joystickButton.button] = true;
}
else if (event.type == sf::Event::JoystickButtonReleased)
{
joystick_button_down[event.joystickMove.joystickId][event.joystickButton.button] = false;
joystick_button_changed[event.joystickMove.joystickId][event.joystickButton.button] = true;
}
else if (event.type == sf::Event::LostFocus)
{
for(unsigned int n=0; n<sf::Keyboard::KeyCount; n++)
{
keyboard_button_down[n] = false;
}
}
*/
}
void InputHandler::postEventsUpdate()
{
input_event_handlers.update();
joystick_event_handlers.update();
if (last_key_press.keysym.sym != SDLK_UNKNOWN)
{
InputHandler::fireKeyEvent(last_key_press, -1);
last_key_press.keysym.sym = SDLK_UNKNOWN;
}
#ifdef __ANDROID__
if (sf::Touch::isDown(0))
{
mouse_position = realWindowPosToVirtual(sf::Touch::getPosition(0));
if (!mouse_button_down[sf::Mouse::Left])
mouse_button_pressed[sf::Mouse::Left] = true;
mouse_button_down[sf::Mouse::Left] = true;
}else{
if (mouse_button_down[sf::Mouse::Left])
mouse_button_released[sf::Mouse::Left] = true;
mouse_button_down[sf::Mouse::Left] = false;
}
#else
int x, y;
SDL_GetMouseState(&x, &y);
mouse_position = realWindowPosToVirtual({x, y});
#endif
#warning SDL2 TODO
//mouse_position = mouse_transform * mouse_position;
if (touch_screen)
{
bool any_button_down = false;
for(unsigned int n=0; n<5; n++)
if (mouse_button_down[n] || mouse_button_released[n])
any_button_down = true;
if (!any_button_down)
{
mouse_position = {-1, -1};
}
}
for(unsigned int i=0; i<4; i++)
{
for(unsigned int n=0; n<4; n++)
{
if(joystick_axis_changed[i][n])
{
foreach(JoystickEventHandler, e, joystick_event_handlers)
{
e->handleJoystickAxis(i, n, joystick_axis_pos[i][n]);
}
}
}
for(unsigned int n=0; n<4; n++)
{
if(joystick_button_changed[i][n])
{
foreach(JoystickEventHandler, e, joystick_event_handlers)
{
e->handleJoystickButton(i, n, joystick_button_down[i][n]);
}
}
}
}
}
void InputHandler::setMousePos(glm::vec2 position)
{
if (!windowManager)
windowManager = engine->getObject("windowManager");
//sf::Mouse::setPosition(virtualWindowPosToReal(position), windowManager->window);
//mouse_position = realWindowPosToVirtual(sf::Mouse::getPosition(windowManager->window));
}
void InputHandler::fireKeyEvent(const SDL_KeyboardEvent& key, int unicode)
{
foreach(InputEventHandler, e, input_event_handlers)
{
e->handleKeyPress(key, unicode);
}
}
glm::vec2 InputHandler::realWindowPosToVirtual(glm::ivec2 position)
{
return windowManager->mapPixelToCoords(position);
}
glm::ivec2 InputHandler::virtualWindowPosToReal(glm::vec2 position)
{
return windowManager->mapCoordsToPixel(position);
}
<|endoftext|> |
<commit_before>#include "kafka.h"
#include <iostream>
#include <librdkafka/rdkafkacpp.h>
#include <boost/asio/ip/host_name.hpp>
// XXX require the unused fields to be present but blank?
void set_single_config_field(RdKafka::Conf& rd_conf, YAML::Node& yaml_conf, std::string field) {
if (!yaml_conf[field]) {
print::debug("KafkaProducer: no config for ", field);
throw;
}
if (yaml_conf[field].IsNull()) {
return;
}
auto value = yaml_conf[field].as<std::string>();
std::string errstr;
if (rd_conf.set(field, value, errstr) !=
RdKafka::Conf::CONF_OK) {
print::debug("KafkaProducer: bad config for ", field, value, errstr);
throw;
}
}
KafkaProducer::KafkaProducer(BanjaxInterface* banjax, YAML::Node &config)
: banjax(banjax) {
print::debug("KafkaProducer default constructor");
if (config.Type() != YAML::NodeType::Map) {
print::debug("KafkaProducer::load_config requires a YAML::Map");
throw;
}
auto conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
// auto brokers = config["metadata.broker.list"].as<std::string>();
// std::string errstr;
// if (conf->set("metadata.broker.list", brokers, errstr) !=
// RdKafka::Conf::CONF_OK) {
// print::debug("KafkaProducer: bad 'brokers' config: ", errstr);
// throw;
// }
set_single_config_field(*conf, config, "metadata.broker.list");
set_single_config_field(*conf, config, "security.protocol");
set_single_config_field(*conf, config, "ssl.ca.location");
set_single_config_field(*conf, config, "ssl.certificate.location");
set_single_config_field(*conf, config, "ssl.key.location");
set_single_config_field(*conf, config, "ssl.key.password");
report_topic = config["report_topic"].as<std::string>();
std::string errstr;
rdk_producer.reset(RdKafka::Producer::create(conf, errstr));
if (!rdk_producer) {
print::debug("KafkaProducer: failed to create Producer (for failed challenges): ", errstr);
throw;
}
print::debug("KafkaProducer load_config done");
}
int KafkaProducer::send_message(const json& message) {
const std::string& serialized_message = message.dump();
size_t serialized_message_size = message.dump().size();
RdKafka::ErrorCode err = rdk_producer->produce(
/* Topic name */
report_topic,
/* Any Partition: the builtin partitioner will be
* used to assign the message to a topic based
* on the message key, or random partition if
* the key is not set. */
(int)RdKafka::Topic::PARTITION_UA,
/* Make a copy of the value */
(int)RdKafka::Producer::RK_MSG_COPY /* Copy payload */,
/* Value */
(void*)serialized_message.c_str(), serialized_message_size,
/* Key */
nullptr, 0,
/* Timestamp (defaults to current time) */
0,
/* Message headers, if any */
NULL);
if (err == RdKafka::ERR_NO_ERROR) {
print::debug("sent message: ", serialized_message);
return 0;
} else {
print::debug("Failed to send kafka message! ");
return -1;
}
}
void
KafkaConsumer::reload_config(YAML::Node& config, BanjaxInterface* new_banjax) {
{
print::debug("-!-! reload_config() before lock");
TSMutexLock(stored_config_lock);
auto on_scope_exit = defer([&] { TSMutexUnlock(stored_config_lock); });
print::debug("-!-! reload_config() after lock");
stored_config = config;
banjax = new_banjax;
config_valid = false;
}
print::debug("-!-! reload_config() after lock released");
}
KafkaConsumer::KafkaConsumer(YAML::Node &new_config, BanjaxInterface* new_banjax)
: stored_config_lock(TSMutexCreate()),
stored_config(new_config),
banjax(new_banjax)
{
// XXX this (or at least the `while (config_valid && !shutting_down)` loop ~50 lines down)
// should probably be a TS continuation scheduled with TSContScheduleEvery(),
// but i think this thing below works and i'm afraid of breaking it.
thread_handle = std::thread([=] {
print::debug("hello from lambda");
while (!shutting_down) {
print::debug("(RE)LOADING CONFIG");
auto conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
auto tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);
std::vector<std::string> topics; // annoyingly a vector when we really just need one
std::string errstr;
{
TSMutexLock(stored_config_lock);
auto on_scope_exit = defer([&] { TSMutexUnlock(stored_config_lock); });
if (stored_config.Type() != YAML::NodeType::Map) {
print::debug("KafkaConsumer::load_config requires a YAML::Map");
throw;
}
auto topic = stored_config["command_topic"].as<std::string>();
topics.push_back(topic);
set_single_config_field(*conf, stored_config, "metadata.broker.list");
set_single_config_field(*conf, stored_config, "security.protocol");
set_single_config_field(*conf, stored_config, "ssl.ca.location");
set_single_config_field(*conf, stored_config, "ssl.certificate.location");
set_single_config_field(*conf, stored_config, "ssl.key.location");
set_single_config_field(*conf, stored_config, "ssl.key.password");
// we want every banjax instance to see every message. this means every banjax instance
// needs its own group id. so i'm using the hostname.
if (conf->set("group.id", boost::asio::ip::host_name(), errstr) != RdKafka::Conf::CONF_OK) {
print::debug("KafkaConsumer: bad group.id config: ", errstr);
throw;
}
config_valid = true;
}
RdKafka::KafkaConsumer *consumer = RdKafka::KafkaConsumer::create(conf, errstr);
if (!consumer) {
print::debug("Failed to create consumer: ", errstr);
throw;
}
print::debug("% Created consumer ", consumer->name());
RdKafka::ErrorCode resp = consumer->subscribe(topics);
if (resp != RdKafka::ERR_NO_ERROR) {
print::debug("Failed to start consumer: ", RdKafka::err2str(resp));
throw; // XXX inside this thread?...
}
while (config_valid && !shutting_down) {
std::cerr << "BLOCKING" << std::endl;
auto msg = std::unique_ptr<RdKafka::Message>(consumer->consume(2000));
msg_consume(std::move(msg), NULL);
}
print::debug("BEFORE CLOSE");
consumer->close();
print::debug("AFTER CLOSE");
}
print::debug("THREAD EXITING");
});
print::debug("hello from OUTSIDE lambda");
}
void KafkaConsumer::shutdown() {
shutting_down = true;
print::debug("KafkaConsumer::shutdown() BEFORE thread join()");
thread_handle.join();
print::debug("KafkaConsumer::shutdown() AFTER thread join()");
}
void KafkaConsumer::msg_consume(std::unique_ptr<RdKafka::Message> message, void *opaque) {
if (TSMutexLockTry(stored_config_lock) != TS_SUCCESS) {
print::debug("KafkaConsumer::msg_consume() failed to get lock; skipping.");
return;
}
print::debug("KafkaConsumer::msg_consume() acquired lock");
{
auto on_scope_exit = defer([&] { TSMutexUnlock(stored_config_lock); });
print::debug("MSG_CONSUME()");
switch (message->err()) {
case RdKafka::ERR__TIMED_OUT:
print::debug("timed out");
break;
case RdKafka::ERR_NO_ERROR: {
/* Real message */
print::debug("Read msg at offset ", message->offset());
print::debug("msg json: ", (char*)message->payload());
json message_dict;
try {
message_dict = json::parse((char*)message->payload());
} catch (json::exception& e) {
print::debug("kafka message not json: ", (char*)message->payload());
return;
}
banjax->kafka_message_consume(message_dict);
} break;
case RdKafka::ERR__PARTITION_EOF: {
print::debug("%% EOF reached for all partition(s)");
}
break;
case RdKafka::ERR__UNKNOWN_TOPIC: {
}
case RdKafka::ERR__UNKNOWN_PARTITION: {
print::debug("Consume failed: ", message->errstr());
} break;
default: {
/* Errors */
print::debug("Consume failed: ", message->errstr());
}
}
}
print::debug("KafkaConsumer::msg_consume() released lock");
}
<commit_msg>fix some comments and debug messages<commit_after>#include "kafka.h"
#include <iostream>
#include <librdkafka/rdkafkacpp.h>
#include <boost/asio/ip/host_name.hpp>
// XXX require the unused fields to be present but blank?
void set_single_config_field(RdKafka::Conf& rd_conf, YAML::Node& yaml_conf, std::string field) {
if (!yaml_conf[field]) {
print::debug("KafkaProducer: no config for ", field);
throw;
}
if (yaml_conf[field].IsNull()) {
return;
}
auto value = yaml_conf[field].as<std::string>();
std::string errstr;
if (rd_conf.set(field, value, errstr) !=
RdKafka::Conf::CONF_OK) {
print::debug("KafkaProducer: bad config for ", field, value, errstr);
throw;
}
}
KafkaProducer::KafkaProducer(BanjaxInterface* banjax, YAML::Node &config)
: banjax(banjax) {
print::debug("KafkaProducer default constructor");
if (config.Type() != YAML::NodeType::Map) {
print::debug("KafkaProducer::load_config requires a YAML::Map");
throw;
}
auto conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
set_single_config_field(*conf, config, "metadata.broker.list");
set_single_config_field(*conf, config, "security.protocol");
set_single_config_field(*conf, config, "ssl.ca.location");
set_single_config_field(*conf, config, "ssl.certificate.location");
set_single_config_field(*conf, config, "ssl.key.location");
set_single_config_field(*conf, config, "ssl.key.password");
report_topic = config["report_topic"].as<std::string>();
std::string errstr;
rdk_producer.reset(RdKafka::Producer::create(conf, errstr));
if (!rdk_producer) {
print::debug("KafkaProducer: failed to create Producer (for failed challenges): ", errstr);
throw;
}
print::debug("KafkaProducer load_config done");
}
int KafkaProducer::send_message(const json& message) {
const std::string& serialized_message = message.dump();
size_t serialized_message_size = message.dump().size();
RdKafka::ErrorCode err = rdk_producer->produce(
/* Topic name */
report_topic,
/* Any Partition */
(int)RdKafka::Topic::PARTITION_UA,
/* Make a copy of the value */
(int)RdKafka::Producer::RK_MSG_COPY /* Copy payload */,
/* Value */
(void*)serialized_message.c_str(), serialized_message_size,
/* Key */
nullptr, 0,
/* Timestamp (defaults to current time) */
0,
/* Message headers, if any */
NULL);
if (err == RdKafka::ERR_NO_ERROR) {
print::debug("sent message: ", serialized_message);
return 0;
} else {
print::debug("Failed to send kafka message! ");
return -1;
}
}
void
KafkaConsumer::reload_config(YAML::Node& config, BanjaxInterface* new_banjax) {
{
TSMutexLock(stored_config_lock);
auto on_scope_exit = defer([&] { TSMutexUnlock(stored_config_lock); });
stored_config = config;
banjax = new_banjax;
config_valid = false;
}
}
KafkaConsumer::KafkaConsumer(YAML::Node &new_config, BanjaxInterface* new_banjax)
: stored_config_lock(TSMutexCreate()),
stored_config(new_config),
banjax(new_banjax)
{
// XXX this (or at least the `while (config_valid && !shutting_down)` loop ~50 lines down)
// should probably be a TS continuation scheduled with TSContScheduleEvery(),
// but i think this thing below works and i'm afraid of breaking it.
thread_handle = std::thread([=] {
while (!shutting_down) {
print::debug("kafka consumer is (re)loading configuration");
auto conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
auto tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);
std::vector<std::string> topics; // annoyingly a vector when we really just need one
std::string errstr;
{
TSMutexLock(stored_config_lock);
auto on_scope_exit = defer([&] { TSMutexUnlock(stored_config_lock); });
if (stored_config.Type() != YAML::NodeType::Map) {
print::debug("KafkaConsumer::load_config requires a YAML::Map");
throw;
}
auto topic = stored_config["command_topic"].as<std::string>();
topics.push_back(topic);
set_single_config_field(*conf, stored_config, "metadata.broker.list");
set_single_config_field(*conf, stored_config, "security.protocol");
set_single_config_field(*conf, stored_config, "ssl.ca.location");
set_single_config_field(*conf, stored_config, "ssl.certificate.location");
set_single_config_field(*conf, stored_config, "ssl.key.location");
set_single_config_field(*conf, stored_config, "ssl.key.password");
// we want every banjax instance to see every message. this means every banjax instance
// needs its own group id. so i'm using the hostname.
if (conf->set("group.id", boost::asio::ip::host_name(), errstr) != RdKafka::Conf::CONF_OK) {
print::debug("KafkaConsumer: bad group.id config: ", errstr);
throw;
}
config_valid = true;
}
RdKafka::KafkaConsumer *consumer = RdKafka::KafkaConsumer::create(conf, errstr);
if (!consumer) {
print::debug("Failed to create consumer: ", errstr);
throw;
}
print::debug("% Created consumer ", consumer->name());
RdKafka::ErrorCode resp = consumer->subscribe(topics);
if (resp != RdKafka::ERR_NO_ERROR) {
print::debug("Failed to start consumer: ", RdKafka::err2str(resp));
throw; // XXX inside this thread?...
}
while (config_valid && !shutting_down) {
print::debug("kafka consumer is blocking...");
auto msg = std::unique_ptr<RdKafka::Message>(consumer->consume(2000));
msg_consume(std::move(msg), NULL);
}
consumer->close();
}
});
}
void KafkaConsumer::shutdown() {
shutting_down = true;
thread_handle.join();
print::debug("KafkaConsumer::shutdown() after thread join");
}
void KafkaConsumer::msg_consume(std::unique_ptr<RdKafka::Message> message, void *opaque) {
if (TSMutexLockTry(stored_config_lock) != TS_SUCCESS) {
print::debug("KafkaConsumer::msg_consume() failed to get lock; skipping.");
return;
}
print::debug("KafkaConsumer::msg_consume() acquired lock");
{
auto on_scope_exit = defer([&] { TSMutexUnlock(stored_config_lock); });
print::debug("KafkaConsumer::msg_consume()");
switch (message->err()) {
case RdKafka::ERR__TIMED_OUT:
print::debug("no message, just a timeout");
break;
case RdKafka::ERR_NO_ERROR: {
/* Real message */
print::debug("Read msg at offset ", message->offset());
print::debug("msg json: ", (char*)message->payload());
json message_dict;
try {
message_dict = json::parse((char*)message->payload());
} catch (json::exception& e) {
print::debug("kafka message not json: ", (char*)message->payload());
return;
}
banjax->kafka_message_consume(message_dict);
} break;
case RdKafka::ERR__PARTITION_EOF: {
print::debug("%% EOF reached for all partition(s)");
}
break;
case RdKafka::ERR__UNKNOWN_TOPIC: {
}
case RdKafka::ERR__UNKNOWN_PARTITION: {
print::debug("Consume failed: ", message->errstr());
} break;
default: {
/* Errors */
print::debug("Consume failed: ", message->errstr());
}
}
}
print::debug("KafkaConsumer::msg_consume() released lock");
}
<|endoftext|> |
<commit_before>#include "test_common.h"
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
TEST_UNIT(lambda_test1)
{
std::vector<int> c{ 1, 2, 3, 4, 5, 6, 7 };
int x = 5;
c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; }), c.end());
std::cout << "c: ";
for (auto i : c) {
std::cout << i << ' ';
}
std::cout << '\n';
// the type of a closure cannot be named, but can be inferred with auto
auto func1 = [](int i) { return i + 4; };
std::cout << "func1: " << func1(6) << '\n';
// like all callable objects, closures can be captured in std::function
// (this may incur unnecessary overhead)
std::function<int(int)> func2 = [](int i) { return i + 4; };
std::cout << "func2: " << func2(6) << '\n';
}
TEST_UNIT(lambda_test2)
{
using namespace std;
// Create a vector object that contains 10 elements.
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
// Count the number of even numbers in the vector by
// using the for_each function and a lambda. ൱ڴһ캯IJΪ&evenCount
int evenCount = 0;
for_each(v.begin(), v.end(), [&evenCount](int n) {
cout << n;
if (n % 2 == 0) {
cout << " is even " << endl;
++evenCount;
}
else {
cout << " is odd " << endl;
}
});
// Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
}
<commit_msg>Add more lambda test code<commit_after>#include "test_common.h"
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
TEST_UNIT(lambda_test1)
{
std::vector<int> c{ 1, 2, 3, 4, 5, 6, 7 };
int x = 5;
c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; }), c.end());
std::cout << "c: ";
for (auto i : c) {
std::cout << i << ' ';
}
std::cout << '\n';
// the type of a closure cannot be named, but can be inferred with auto
auto func1 = [](int i) { return i + 4; };
std::cout << "func1: " << func1(6) << '\n';
// like all callable objects, closures can be captured in std::function
// (this may incur unnecessary overhead)
std::function<int(int)> func2 = [](int i) { return i + 4; };
std::cout << "func2: " << func2(6) << '\n';
}
using namespace std;
TEST_UNIT(lambda_test2)
{
// Create a vector object that contains 10 elements.
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
// Count the number of even numbers in the vector by
// using the for_each function and a lambda. ൱ڴһ캯IJΪ&evenCount
int evenCount = 0;
for_each(v.begin(), v.end(), [&evenCount](int n) {
cout << n;
if (n % 2 == 0) {
cout << " is even " << endl;
++evenCount;
}
else {
cout << " is odd " << endl;
}
});
// Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
}
TEST_UNIT(lambda_test3)
{
int x = 10;
int y = 3;
int z = 0;
//Ϊֵݵķʽx,yx,yֵûзı
z = [=]()mutable throw() -> int { int n = x + y; x = y; y = n; return n; }();
cout << "z:" << z << "\tx:" << x << "\t" << "y:" << y << endl;
H_TEST_ASSERT(x == 10);
H_TEST_ASSERT(y == 3);
H_TEST_ASSERT(z == 13);
//Ϊôݵķʽx,yx,yֵѾı
z = [&]()mutable throw() -> int { int n = x + y; x = y; y = n; return n; }();
cout << "z:" << z << "\tx:" << x << "\t" << "y:" << y << endl;
H_TEST_ASSERT(y == 13);
H_TEST_ASSERT(x == 3);
H_TEST_ASSERT(z == 13);
}<|endoftext|> |
<commit_before>/*
* Copyright (C) 2006,2007,2008,2009,2010,2011,2012 Olly Betts
*
* 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 "length.h"
std::string
encode_length(size_t len)
{
std::string result;
if (len < 255) {
result += static_cast<unsigned char>(len);
} else {
result += '\xff';
len -= 255;
while (true) {
unsigned char b = static_cast<unsigned char>(len & 0x7f);
len >>= 7;
if (!len) {
result += (b | static_cast<unsigned char>(0x80));
break;
}
result += b;
}
}
return result;
}
size_t
decode_length(const char ** p, const char *end, bool check_remaining)
{
const char *pos = *p;
if (pos == end) {
return -1;
}
size_t len = static_cast<unsigned char>(*pos++);
if (len == 0xff) {
len = 0;
unsigned char ch;
int shift = 0;
do {
if (pos == end || shift > 28)
return -1;
ch = *pos++;
len |= size_t(ch & 0x7f) << shift;
shift += 7;
} while ((ch & 0x80) == 0);
len += 255;
}
if (check_remaining && len > size_t(end - pos)) {
return -1;
}
*p = pos;
return len;
}
<commit_msg>Serializers/unserializers of length and strings<commit_after>/*
* Copyright (C) 2006,2007,2008,2009,2010,2011,2012 Olly Betts
*
* 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 "length.h"
std::string
serialise_length(size_t len)
{
std::string result;
if (len < 255) {
result += static_cast<unsigned char>(len);
} else {
result += '\xff';
len -= 255;
while (true) {
unsigned char b = static_cast<unsigned char>(len & 0x7f);
len >>= 7;
if (!len) {
result += (b | static_cast<unsigned char>(0x80));
break;
}
result += b;
}
}
return result;
}
size_t
unserialise_length(const char **p, const char *end, bool check_remaining)
{
const char *pos = *p;
if (pos == end) {
return -1;
}
size_t len = static_cast<unsigned char>(*pos++);
if (len == 0xff) {
len = 0;
unsigned char ch;
int shift = 0;
do {
if (pos == end || shift > 28)
return -1;
ch = *pos++;
len |= size_t(ch & 0x7f) << shift;
shift += 7;
} while ((ch & 0x80) == 0);
len += 255;
}
if (check_remaining && len > size_t(end - pos)) {
return -1;
}
*p = pos;
return len;
}
std::string
serialise_string(std::string &input) {
std::string output;
output.append(encode_length(input.size()));
output.append(input);
return output;
}
size_t
unserialise_string(std::string &output, const char **p, const char *end) {
size_t length = decode_length(p, end, true);
if (length != -1) {
output.append(std::string(*p, length));
*p += length;
}
return length;
}
<|endoftext|> |
<commit_before>#include "taichi_grid.h"
#include <taichi/visual/texture.h>
#include <taichi/system/threading.h>
#include <taichi/util.h>
#include <taichi/math/svd.h>
TC_NAMESPACE_BEGIN
struct NodeFlags : public bit::Bits<32> {
using Base = bit::Bits<32>;
TC_BIT_FIELD(uint8, num_effective_neighbours, 0);
TC_BIT_FIELD(bool, effective, 8);
};
struct Node {
real channels[16];
real &operator[](int i) {
return channels[i];
}
NodeFlags &flags() {
return bit::reinterpret_bits<NodeFlags>(channels[15]);
}
};
using Block = TBlock<Node, char, TSize3D<8>, 0>;
class MGPCGTest {
public:
static constexpr auto dim = Block::dim;
using Vector = TVector<real, dim>;
using VectorP = TVector<real, dim + 1>;
using Matrix = TMatrix<real, dim>;
using Grid = TaichiGrid<Block>;
std::vector<std::unique_ptr<Grid>> grids;
int mg_lv = 2;
using VectorI = Vector3i;
using Vectori = VectorI;
using GridScratchPad = TGridScratchPad<Block>;
enum { CH_R, CH_Z, CH_X, CH_B, CH_TMP, CH_P, CH_MG_U, CH_MG_B, CH_MG_R };
MGPCGTest() {
// Span a region in
grids.resize(mg_lv);
for (int i = 0; i < mg_lv; i++) {
grids[i] = std::make_unique<Grid>();
}
TC_ASSERT(mg_lv >= 1);
constexpr int n = 32;
TC_ASSERT_INFO(bit::is_power_of_two(n), "Only POT grid sizes supported");
Region3D active_region(VectorI(-n, -n, -n * 2), VectorI(n, n, n * 2));
for (auto &ind : active_region) {
grids[0]->touch(ind.get_ipos());
grids[0]->node(ind.get_ipos()).flags().set_effective(true);
if (ind.get_ipos() == VectorI(0)) {
grids[0]->node(ind.get_ipos())[CH_B] = 1;
}
}
set_up_hierechy();
}
void set_up_hierechy() {
int total_blocks = grids[0]->num_active_blocks();
for (int i = 0; i < mg_lv - 1; i++) {
grids[i]->coarsen(
*grids[i + 1], [&](Block &b, Grid::PyramidAncestors &an) {
for (auto ind : b.get_local_region()) {
b.node_local(ind.get_ipos()).flags().set_effective(true);
}
});
total_blocks /= 8;
TC_ASSERT(grids[i + 1]->num_active_blocks() == total_blocks);
}
}
void residual(int level, int U, int B, int R) {
grids[level]->advance(
[&](Block &b, Grid::Ancestors &an) {
GridScratchPad scratch(an);
std::memcpy(&b.nodes[0], &an[VectorI(0)]->nodes[0], sizeof(b.nodes));
// 6 neighbours
for (int i = 0; i < Block::size[0]; i++) {
for (int j = 0; j < Block::size[1]; j++) {
for (int k = 0; k < Block::size[2]; k++) {
auto rhs = b.get_node_volume()[i][j][k][B];
auto c = b.get_node_volume()[i][j][k][U];
auto &o = b.get_node_volume()[i][j][k][R];
auto fetch = [&](int ii, int jj, int kk) {
if (scratch.data[i + ii][j + jj][k + kk]
.flags()
.get_effective()) {
rhs -= (scratch.data[i + ii][j + jj][k + kk][U] - c);
}
};
fetch(0, 0, 1);
fetch(0, 0, -1);
fetch(0, 1, 0);
fetch(0, -1, 0);
fetch(1, 0, 0);
fetch(-1, 0, 0);
b.get_node_volume()[i][j][k][R] = rhs;
}
}
}
},
false);
}
void multiply(int channel_out, int channel_in) {
grids[0]->advance(
[&](Block &b, Grid::Ancestors &an) {
GridScratchPad scratch(an);
std::memcpy(&b.nodes[0], &an[VectorI(0)]->nodes[0], sizeof(b.nodes));
// 6 neighbours
for (int i = 0; i < Block::size[0]; i++) {
for (int j = 0; j < Block::size[1]; j++) {
for (int k = 0; k < Block::size[2]; k++) {
#define V(ii, jj, kk) scratch.data[i + (ii)][j + (jj)][k + (kk)][channel_in]
auto &o = b.get_node_volume()[i][j][k][channel_out];
o = 6 * V(0, 0, 0) - V(0, 0, 1) - V(0, 0, -1) - V(0, 1, 0) -
V(0, -1, 0) - V(1, 0, 0) - V(-1, 0, 0);
if (o != o) {
TC_P(b.base_coord);
TC_P(V(0, 0, 0));
TC_P(V(0, 0, 1));
TC_P(V(0, 1, 0));
TC_P(V(1, 0, 0));
TC_P(V(0, 0, -1));
TC_P(V(0, -1, 0));
TC_P(V(-1, 0, 0));
TC_P(o);
TC_P(i);
TC_P(j);
TC_P(k);
Time::sleep(0.01);
}
#undef V
}
}
}
},
false);
}
// out += a + scale * b
void saxpy(int channel_out, int channel_a, int channel_b, real scale) {
TC_ASSERT(!with_mpi());
grids[0]->map([&](Block &b) {
for (auto &n : b.nodes) {
n[channel_out] = n[channel_a] + scale * n[channel_b];
}
});
}
// out += a + scale * b
void copy(int channel_out, int channel_a) {
grids[0]->map([&](Block &b) {
for (auto &n : b.nodes) {
n[channel_out] = n[channel_a];
}
});
}
float64 dot_product(int channel_a, int channel_b) {
return grids[0]->reduce([&](Block &b) -> float64 {
float64 sum = 0;
for (auto &n : b.nodes) {
sum += n[channel_a] * n[channel_b];
}
return sum;
});
}
void smooth(int level, int U, int B) {
grids[level]->advance(
[&](Grid::Block &b, Grid::Ancestors &an) {
GridScratchPad scratch(an);
std::memcpy(&b.nodes[0], &an[VectorI(0)]->nodes[0], sizeof(b.nodes));
// 6 neighbours
for (int i = 0; i < Block::size[0]; i++) {
for (int j = 0; j < Block::size[1]; j++) {
for (int k = 0; k < Block::size[2]; k++) {
if (!scratch.data[i][j][k].flags().get_effective()) {
continue;
}
int count = 0;
real tmp = scratch.data[i][j][k][B];
auto fetch = [&](int ii, int jj, int kk) {
if (scratch.data[i + ii][j + jj][k + kk]
.flags()
.get_effective()) {
count += 1;
tmp += scratch.data[i + ii][j + jj][k + kk][U];
}
};
fetch(0, 0, 1);
fetch(0, 0, -1);
fetch(0, 1, 0);
fetch(0, -1, 0);
fetch(1, 0, 0);
fetch(-1, 0, 0);
auto &o = b.get_node_volume()[i][j][k][U];
o = tmp / count;
}
}
}
},
false);
}
void clear(int level, int channel) {
grids[level]->for_each_node([&](Block::Node &n) { n[channel] = 0; });
}
// B[level + 1] = coarsened(R[level])
void restrict(int level, int R_in, int B_out) {
// average residual
grids[level]->coarsen(
*grids[level + 1], [&](Block &block, Grid::PyramidAncestors &an) {
for (auto ind : Region3D(Vector3i(0), Vector3i(2))) {
if (!an[ind.get_ipos()]) {
continue;
}
Block &ab = *an[ind.get_ipos()];
for (auto j : ab.get_local_region()) {
auto coarse_coord = div_floor(
ind.get_ipos() * Vector3i(Block::size) + j.get_ipos(),
Vector3i(2));
block.node_local(coarse_coord).channels[B_out] +=
ab.node_local(j.get_ipos())[R_in];
}
}
});
}
// U[level] += refined(U]level + 1]);
void prolongate(int level, int U) {
real scale = 0.5_f;
// upsample and apply correction
grids[level - 1]->refine(*grids[level], [&](Block &block, Block &ancestor) {
for (auto ind : block.get_global_region()) {
block.node_global(ind.get_ipos())[U] +=
scale *
ancestor.node_global(div_floor(ind.get_ipos(), Vector3i(2)))[U];
}
});
}
real norm(int channel) {
return (real)std::sqrt(dot_product(channel, channel));
}
void V_cycle(int channel_in, int channel_out, bool use_as_preconditioner=true) {
copy(CH_MG_B, channel_in);
constexpr int U = CH_MG_U, B = CH_MG_B, R = CH_MG_R;
constexpr int smoothing_iters = 1, bottom_smoothing_iter = 10;
for (int i = 0; i < mg_lv - 1; i++) {
if (use_as_preconditioner || i != 0) {
clear(i, U);
}
// pre-smoothing
for (int j = 0; j < smoothing_iters; j++) {
smooth(i, U, B);
}
residual(i, U, B, R);
restrict(i, R, B);
}
// Bottom solve
for (int j = 0; j < bottom_smoothing_iter; j++) {
smooth(mg_lv - 1, U, B);
}
for (int i = mg_lv - 1; i > 0; i--) {
prolongate(i, U);
// post-smoothing
for (int j = 0; j < smoothing_iters; j++) {
smooth(i, U, B);
}
}
copy(channel_out, CH_MG_U);
}
void run() {
while (1) {
V_cycle(CH_B, CH_X, false);
multiply(CH_TMP, CH_X);
saxpy(CH_R, CH_B, CH_TMP, -1);
TC_P(norm(CH_TMP));
}
}
// https://en.wikipedia.org/wiki/Conjugate_gradient_method
void run_pcg() {
TC_P(norm(CH_B));
// r = b - Ax
multiply(CH_TMP, CH_X);
TC_P(norm(CH_TMP));
saxpy(CH_R, CH_B, CH_TMP, -1);
// z = M^-1 r
saxpy(CH_Z, CH_R, CH_R, 0);
// p = z
copy(CH_P, CH_Z);
while (1) {
multiply(CH_TMP, CH_P);
real alpha = dot_product(CH_R, CH_Z) / dot_product(CH_P, CH_TMP);
auto old_zr = dot_product(CH_Z, CH_R);
saxpy(CH_X, CH_X, CH_P, alpha);
saxpy(CH_R, CH_R, CH_TMP, -alpha);
auto l2 = norm(CH_R);
TC_P(l2);
if (l2 < 1e-7) {
break;
}
copy(CH_Z, CH_R);
auto beta = dot_product(CH_Z, CH_R) / old_zr;
saxpy(CH_P, CH_Z, CH_P, beta);
}
}
};
auto mgpcg = [](const std::vector<std::string> ¶ms) {
// ThreadedTaskManager::TbbParallelismControl _(1);
std::unique_ptr<MGPCGTest> mgpcg;
mgpcg = std::make_unique<MGPCGTest>();
mgpcg->run();
};
TC_REGISTER_TASK(mgpcg);
TC_NAMESPACE_END
<commit_msg>Jacobi iteration works<commit_after>#include "taichi_grid.h"
#include <taichi/visual/texture.h>
#include <taichi/system/threading.h>
#include <taichi/util.h>
#include <taichi/math/svd.h>
TC_NAMESPACE_BEGIN
struct NodeFlags : public bit::Bits<32> {
using Base = bit::Bits<32>;
TC_BIT_FIELD(uint8, num_effective_neighbours, 0);
TC_BIT_FIELD(bool, effective, 8);
};
struct Node {
real channels[16];
real &operator[](int i) {
return channels[i];
}
NodeFlags &flags() {
return bit::reinterpret_bits<NodeFlags>(channels[15]);
}
};
using Block = TBlock<Node, char, TSize3D<8>, 0>;
class MGPCGTest {
public:
static constexpr auto dim = Block::dim;
using Vector = TVector<real, dim>;
using VectorP = TVector<real, dim + 1>;
using Matrix = TMatrix<real, dim>;
using Grid = TaichiGrid<Block>;
std::vector<std::unique_ptr<Grid>> grids;
int mg_lv = 1;
using VectorI = Vector3i;
using Vectori = VectorI;
using GridScratchPad = TGridScratchPad<Block>;
enum { CH_R, CH_Z, CH_X, CH_B, CH_TMP, CH_P, CH_MG_U, CH_MG_B, CH_MG_R };
MGPCGTest() {
// Span a region in
grids.resize(mg_lv);
for (int i = 0; i < mg_lv; i++) {
grids[i] = std::make_unique<Grid>();
}
TC_ASSERT(mg_lv >= 1);
constexpr int n = 32;
TC_ASSERT_INFO(bit::is_power_of_two(n), "Only POT grid sizes supported");
Region3D active_region(VectorI(-n, -n, -n * 2), VectorI(n, n, n * 2));
for (auto &ind : active_region) {
grids[0]->touch(ind.get_ipos());
grids[0]->node(ind.get_ipos()).flags().set_effective(true);
if (ind.get_ipos() == VectorI(0)) {
grids[0]->node(ind.get_ipos())[CH_B] = 1;
}
}
set_up_hierechy();
}
void set_up_hierechy() {
int total_blocks = grids[0]->num_active_blocks();
for (int i = 0; i < mg_lv - 1; i++) {
grids[i]->coarsen(
*grids[i + 1], [&](Block &b, Grid::PyramidAncestors &an) {
for (auto ind : b.get_local_region()) {
b.node_local(ind.get_ipos()).flags().set_effective(true);
}
});
total_blocks /= 8;
TC_ASSERT(grids[i + 1]->num_active_blocks() == total_blocks);
}
}
void residual(int level, int U, int B, int R) {
grids[level]->advance(
[&](Block &b, Grid::Ancestors &an) {
GridScratchPad scratch(an);
std::memcpy(&b.nodes[0], &an[VectorI(0)]->nodes[0], sizeof(b.nodes));
// 6 neighbours
for (int i = 0; i < Block::size[0]; i++) {
for (int j = 0; j < Block::size[1]; j++) {
for (int k = 0; k < Block::size[2]; k++) {
auto rhs = b.get_node_volume()[i][j][k][B];
auto c = b.get_node_volume()[i][j][k][U];
auto &o = b.get_node_volume()[i][j][k][R];
auto fetch = [&](int ii, int jj, int kk) {
if (scratch.data[i + ii][j + jj][k + kk]
.flags()
.get_effective()) {
rhs -= (scratch.data[i + ii][j + jj][k + kk][U] - c);
}
};
fetch(0, 0, 1);
fetch(0, 0, -1);
fetch(0, 1, 0);
fetch(0, -1, 0);
fetch(1, 0, 0);
fetch(-1, 0, 0);
b.get_node_volume()[i][j][k][R] = rhs;
}
}
}
},
false);
}
void multiply(int channel_out, int channel_in) {
// TODO: this supports zero-Dirichlet BC only!
grids[0]->advance(
[&](Block &b, Grid::Ancestors &an) {
GridScratchPad scratch(an);
std::memcpy(&b.nodes[0], &an[VectorI(0)]->nodes[0], sizeof(b.nodes));
// 6 neighbours
for (int i = 0; i < Block::size[0]; i++) {
for (int j = 0; j < Block::size[1]; j++) {
for (int k = 0; k < Block::size[2]; k++) {
int count = 0;
real tmp = 0;
auto &o = b.get_node_volume()[i][j][k][channel_out];
auto fetch = [&](int ii, int jj, int kk) {
auto &n = scratch.data[i + (ii)][j + (jj)][k + (kk)];
count++;
tmp += n[channel_in];
};
fetch(0, 0, 1);
fetch(0, 0, -1);
fetch(0, 1, 0);
fetch(0, -1, 0);
fetch(1, 0, 0);
fetch(-1, 0, 0);
o = count * scratch.data[i][j][k][channel_in] - tmp;
if (o != o) {
TC_P(b.base_coord);
TC_P(o);
TC_P(i);
TC_P(j);
TC_P(k);
Time::sleep(0.01);
}
}
}
}
},
false);
}
// out += a + scale * b
void saxpy(int channel_out, int channel_a, int channel_b, real scale) {
TC_ASSERT(!with_mpi());
grids[0]->map([&](Block &b) {
for (auto &n : b.nodes) {
n[channel_out] = n[channel_a] + scale * n[channel_b];
}
});
}
// out += a + scale * b
void copy(int channel_out, int channel_a) {
grids[0]->map([&](Block &b) {
for (auto &n : b.nodes) {
n[channel_out] = n[channel_a];
}
});
}
float64 dot_product(int channel_a, int channel_b) {
return grids[0]->reduce([&](Block &b) -> float64 {
float64 sum = 0;
for (auto &n : b.nodes) {
sum += n[channel_a] * n[channel_b];
}
return sum;
});
}
void smooth(int level, int U, int B) {
// TODO: this supports zero-Dirichlet BC only!
grids[level]->advance(
[&](Grid::Block &b, Grid::Ancestors &an) {
GridScratchPad scratch(an);
std::memcpy(&b.nodes[0], &an[VectorI(0)]->nodes[0], sizeof(b.nodes));
// 6 neighbours
for (int i = 0; i < Block::size[0]; i++) {
for (int j = 0; j < Block::size[1]; j++) {
for (int k = 0; k < Block::size[2]; k++) {
TC_ASSERT(scratch.data[i][j][k].flags().get_effective());
int count = 0;
// (B - Lu) / Diag
real tmp = scratch.data[i][j][k][B];
auto fetch = [&](int ii, int jj, int kk) {
count += 1;
tmp += scratch.data[i + ii][j + jj][k + kk][U];
};
fetch(0, 0, 1);
fetch(0, 0, -1);
fetch(0, 1, 0);
fetch(0, -1, 0);
fetch(1, 0, 0);
fetch(-1, 0, 0);
auto original = scratch.data[i][j][k][U];
TC_ASSERT(count != 0);
auto &o = b.get_node_volume()[i][j][k][U];
o = original + (tmp / count - original) * 1; // 0.666667_f;
/*
if (tmp != 0) {
TC_P(b.base_coord + Vector3i(i, j, k));
TC_P(o);
TC_P(tmp);
TC_P(count);
}
*/
}
}
}
},
false);
}
void clear(int level, int channel) {
grids[level]->for_each_node([&](Block::Node &n) { n[channel] = 0; });
}
// B[level + 1] = coarsened(R[level])
void restrict(int level, int R_in, int B_out) {
// average residual
grids[level]->coarsen(
*grids[level + 1], [&](Block &block, Grid::PyramidAncestors &an) {
for (auto ind : Region3D(Vector3i(0), Vector3i(2))) {
if (!an[ind.get_ipos()]) {
continue;
}
Block &ab = *an[ind.get_ipos()];
for (auto j : ab.get_local_region()) {
auto coarse_coord = div_floor(
ind.get_ipos() * Vector3i(Block::size) + j.get_ipos(),
Vector3i(2));
block.node_local(coarse_coord).channels[B_out] +=
ab.node_local(j.get_ipos())[R_in];
}
}
});
}
// U[level] += refined(U]level + 1]);
void prolongate(int level, int U) {
real scale = 0.5_f;
// upsample and apply correction
grids[level - 1]->refine(*grids[level], [&](Block &block, Block &ancestor) {
for (auto ind : block.get_global_region()) {
block.node_global(ind.get_ipos())[U] +=
scale *
ancestor.node_global(div_floor(ind.get_ipos(), Vector3i(2)))[U];
}
});
}
real norm(int channel) {
return (real)std::sqrt(dot_product(channel, channel));
}
void V_cycle(int channel_in,
int channel_out,
bool use_as_preconditioner = true) {
copy(CH_MG_B, channel_in);
constexpr int U = CH_MG_U, B = CH_MG_B, R = CH_MG_R;
constexpr int smoothing_iters = 1, bottom_smoothing_iter = 1;
for (int i = 0; i < mg_lv - 1; i++) {
if (use_as_preconditioner || i != 0) {
clear(i, U);
}
// pre-smoothing
for (int j = 0; j < smoothing_iters; j++) {
smooth(i, U, B);
}
residual(i, U, B, R);
restrict(i, R, B);
}
// Bottom solve
for (int j = 0; j < bottom_smoothing_iter; j++) {
smooth(mg_lv - 1, U, B);
}
for (int i = mg_lv - 1; i > 0; i--) {
prolongate(i, U);
// post-smoothing
for (int j = 0; j < smoothing_iters; j++) {
smooth(i, U, B);
}
}
copy(channel_out, CH_MG_U);
}
void run() {
for (int i = 0; i < 10; i++) {
V_cycle(CH_B, CH_X, false);
multiply(CH_TMP, CH_X);
/*
grids[0]->for_each_block([&](Block &b) {
for (auto ind : b.get_global_region()) {
auto val = b.node_global(ind.get_ipos())[CH_B];
if ()
}
});
*/
saxpy(CH_R, CH_B, CH_TMP, -1);
TC_P(norm(CH_R));
}
}
// https://en.wikipedia.org/wiki/Conjugate_gradient_method
void run_pcg() {
TC_P(norm(CH_B));
// r = b - Ax
multiply(CH_TMP, CH_X);
TC_P(norm(CH_TMP));
saxpy(CH_R, CH_B, CH_TMP, -1);
// z = M^-1 r
saxpy(CH_Z, CH_R, CH_R, 0);
// p = z
copy(CH_P, CH_Z);
while (1) {
multiply(CH_TMP, CH_P);
real alpha = dot_product(CH_R, CH_Z) / dot_product(CH_P, CH_TMP);
auto old_zr = dot_product(CH_Z, CH_R);
saxpy(CH_X, CH_X, CH_P, alpha);
saxpy(CH_R, CH_R, CH_TMP, -alpha);
auto l2 = norm(CH_R);
TC_P(l2);
if (l2 < 1e-7) {
break;
}
copy(CH_Z, CH_R);
auto beta = dot_product(CH_Z, CH_R) / old_zr;
saxpy(CH_P, CH_Z, CH_P, beta);
}
}
};
auto mgpcg = [](const std::vector<std::string> ¶ms) {
ThreadedTaskManager::TbbParallelismControl _(1);
std::unique_ptr<MGPCGTest> mgpcg;
mgpcg = std::make_unique<MGPCGTest>();
mgpcg->run();
};
TC_REGISTER_TASK(mgpcg);
TC_NAMESPACE_END
<|endoftext|> |
<commit_before>// Original: https://github.com/fcanas/node-native-boilerplate/blob/master/NativeExtension.cc
#include "functions.h"
using v8::FunctionTemplate;
// NativeExtension.cc represents the top level of the module.
// C++ constructs that are exposed to javascript are exported here
NAN_MODULE_INIT(InitAll) {
Nan::Set(target, Nan::New("nothing").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(nothing)).ToLocalChecked());
Nan::Set(target, Nan::New("aString").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(aString)).ToLocalChecked());
Nan::Set(target, Nan::New("aBoolean").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(aBoolean)).ToLocalChecked());
Nan::Set(target, Nan::New("aNumber").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(aNumber)).ToLocalChecked());
Nan::Set(target, Nan::New("anObject").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(anObject)).ToLocalChecked());
Nan::Set(target, Nan::New("anArray").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(anArray)).ToLocalChecked());
Nan::Set(target, Nan::New("callback").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(callback)).ToLocalChecked());
// Passing target down to the next NAN_MODULE_INIT
MyObject::Init(target);
}
NODE_MODULE(NativeExtension, InitAll)<commit_msg>reindent for easier consumption<commit_after>// Original: https://github.com/fcanas/node-native-boilerplate/blob/master/NativeExtension.cc
#include "functions.h"
using v8::FunctionTemplate;
// NativeExtension.cc represents the top level of the module.
// C++ constructs that are exposed to javascript are exported here
NAN_MODULE_INIT(InitAll) {
Nan::Set(
target,
Nan::New("nothing").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(nothing)).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("aString").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(aString)).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("aBoolean").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(aBoolean)).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("aNumber").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(aNumber)).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("anObject").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(anObject)).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("anArray").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(anArray)).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("callback").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(callback)).ToLocalChecked()
);
// Passing target down to the next NAN_MODULE_INIT
MyObject::Init(target);
}
NODE_MODULE(NativeExtension, InitAll)<|endoftext|> |
<commit_before>#include "myers.h"
#include <stdint.h>
using namespace std;
typedef uint64_t Word;
static const int WORD_SIZE = sizeof(Word) * 8; // Size of Word in bits
static const Word HIGH_BIT_MASK = ((Word)1) << (WORD_SIZE-1);
static int myersCalcEditDistanceSemiGlobal(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks,
const unsigned char* query, int queryLength,
const unsigned char* target, int targetLength,
int alphabetLength, int k, int mode, int* bestScore, int* position);
static int myersCalcEditDistanceNW(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks,
const unsigned char* query, int queryLength,
const unsigned char* target, int targetLength,
int alphabetLength, int k, int* bestScore, int* position);
static inline int ceilDiv(int x, int y);
int myersCalcEditDistance(const unsigned char* query, int queryLength,
const unsigned char* target, int targetLength,
int alphabetLength, int k, int mode, int* bestScore, int* position) {
/*--------------------- INITIALIZATION ------------------*/
int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE); // bmax in Myers
Word* P = new Word[maxNumBlocks]; // Contains Pvin for each block (column is divided into blocks)
Word* M = new Word[maxNumBlocks]; // Contains Mvin for each block
int* score = new int[maxNumBlocks]; // Contains score for each block
Word** Peq = new Word*[alphabetLength+1]; // [alphabetLength+1][maxNumBlocks]. Last symbol is wildcard.
int W = maxNumBlocks * WORD_SIZE - queryLength; // number of redundant cells in last level blocks
// Build Peq (1 is match, 0 is mismatch). NOTE: last column is wildcard(symbol that matches anything) with just 1s
for (int symbol = 0; symbol <= alphabetLength; symbol++) {
Peq[symbol] = new Word[maxNumBlocks];
for (int b = 0; b < maxNumBlocks; b++) {
if (symbol < alphabetLength) {
Peq[symbol][b] = 0;
for (int r = (b+1) * WORD_SIZE - 1; r >= b * WORD_SIZE; r--) {
Peq[symbol][b] <<= 1;
// NOTE: We pretend like query is padded at the end with W wildcard symbols
if (r >= queryLength || query[r] == symbol)
Peq[symbol][b] += 1;
}
} else { // Last symbol is wildcard, so it is all 1s
Peq[symbol][b] = (Word)-1;
}
}
}
/*-------------------------------------------------------*/
/*------------------ MAIN CALCULATION -------------------*/
*bestScore = -1;
*position = -1;
if (k < 0) { // If valid k is not given, auto-adjust k until solution is found.
k = WORD_SIZE; // Gives better results then smaller k
while (*bestScore == -1) {
if (mode == MYERS_MODE_HW || mode == MYERS_MODE_SHW)
myersCalcEditDistanceSemiGlobal(P, M, score, Peq, W, maxNumBlocks,
query, queryLength, target, targetLength,
alphabetLength, k, mode, bestScore, position);
else // mode == MYERS_MODE_NW
myersCalcEditDistanceNW(P, M, score, Peq, W, maxNumBlocks,
query, queryLength, target, targetLength,
alphabetLength, k, bestScore, position);
k *= 2;
}
} else {
if (mode == MYERS_MODE_HW || mode == MYERS_MODE_SHW)
myersCalcEditDistanceSemiGlobal(P, M, score, Peq, W, maxNumBlocks,
query, queryLength, target, targetLength,
alphabetLength, k, mode, bestScore, position);
else // mode == MYERS_MODE_NW
myersCalcEditDistanceNW(P, M, score, Peq, W, maxNumBlocks,
query, queryLength, target, targetLength,
alphabetLength, k, bestScore, position);
}
/*-------------------------------------------------------*/
//--- Free memory ---//
delete[] P;
delete[] M;
delete[] score;
for (int i = 0; i < alphabetLength+1; i++)
delete[] Peq[i];
delete[] Peq;
//-------------------//
return MYERS_STATUS_OK;
}
/**
* Corresponds to Advance_Block function from Myers.
* Calculates one word(block), which is part of a column.
* Highest bit of word is most bottom cell of block from column.
* @param [in] Pv Bitset, Pv[i] == 1 if vin is +1, otherwise Pv[i] == 0.
* @param [in] Mv Bitset, Mv[i] == 1 if vin is -1, otherwise Mv[i] == 0.
* @param [in] Eq Bitset, Eq[i] == 1 if match, 0 if mismatch.
* @param [in] hin Will be +1, 0 or -1.
* @param [out] PvOut Bitset, PvOut[i] == 1 if vout is +1, otherwise PvOut[i] == 0.
* @param [out] MvOut Bitset, MvOut[i] == 1 if vout is -1, otherwise MvOut[i] == 0.
* @param [out] hout Will be +1, 0 or -1.
*/
static inline int calculateBlock(Word Pv, Word Mv, Word Eq, const int hin,
Word &PvOut, Word &MvOut) {
Word Xv = Eq | Mv;
if (hin < 0)
Eq |= (Word)1;
Word Xh = (((Eq & Pv) + Pv) ^ Pv) | Eq;
Word Ph = Mv | ~(Xh | Pv);
Word Mh = Pv & Xh;
int hout = 0;
if (Ph & HIGH_BIT_MASK)
hout = 1;
else if (Mh & HIGH_BIT_MASK)
hout = -1;
Ph <<= 1;
Mh <<= 1;
if (hin < 0)
Mh |= (Word)1;
else if (hin > 0)
Ph |= (Word)1;
PvOut = Mh | ~(Xv | Ph);
MvOut = Ph & Xv;
return hout;
}
/**
* Does ceiling division x / y.
* Note: x and y must be non-negative and x + y must not overflow.
*/
static inline int ceilDiv(int x, int y) {
return x % y ? x / y + 1 : x / y;
}
static inline int min(int x, int y) {
return x < y ? x : y;
}
static inline int max(int x, int y) {
return x > y ? x : y;
}
static inline int abs(int x) {
return x < 0 ? -1 * x : x;
}
/**
* @param [in] mode MYERS_MODE_HW or MYERS_MODE_SHW
*/
static int myersCalcEditDistanceSemiGlobal(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks,
const unsigned char* query, int queryLength,
const unsigned char* target, int targetLength,
int alphabetLength, int k, int mode, int* bestScore_, int* position_) {
// firstBlock is 0-based index of first block in Ukkonen band.
// lastBlock is 0-based index of block AFTER last block in Ukkonen band. <- WATCH OUT!
int firstBlock = 0;
int lastBlock = min(ceilDiv(k + 1, WORD_SIZE), maxNumBlocks); // y in Myers
// Initialize P, M and score
for (int b = 0; b < lastBlock; b++) {
score[b] = (b+1) * WORD_SIZE;
P[b] = (Word)-1; // All 1s
M[b] = (Word)0;
}
int bestScore = -1;
int position = -1;
for (int c = 0; c < targetLength + W; c++) { // for each column
// We pretend like target is padded at end with W wildcard symbols
Word* Peq_c = c < targetLength ? Peq[target[c]] : Peq[alphabetLength];
//----------------------- Calculate column -------------------------//
int hout = mode == MYERS_MODE_HW ? 0 : 1; // If 0 then gap before query is not penalized
for (int b = firstBlock; b < lastBlock; b++) {
hout = calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]);
score[b] += hout;
}
//------------------------------------------------------------------//
//---------- Adjust number of blocks according to Ukkonen ----------//
if (mode != MYERS_MODE_HW)
if (score[firstBlock] >= k + WORD_SIZE) {
firstBlock++;
}
if ((score[lastBlock-1] - hout <= k) && (lastBlock < maxNumBlocks)
&& ((Peq_c[lastBlock] & (Word)1) || hout < 0)) {
// If score of left block is not too big, calculate one more block
lastBlock++;
int b = lastBlock-1; // index of last block (one we just added)
P[b] = (Word)-1; // All 1s
M[b] = (Word)0;
score[b] = score[b-1] - hout + WORD_SIZE + calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]);
} else {
while (lastBlock > 0 && score[lastBlock-1] >= k + WORD_SIZE)
lastBlock--;
}
// If band stops to exist finish
if (lastBlock <= firstBlock) {
*bestScore_ = bestScore;
*position_ = position;
return MYERS_STATUS_OK;
}
//------------------------------------------------------------------//
//------------------------- Update best score ----------------------//
if (c >= W && lastBlock == maxNumBlocks) { // We ignore scores from first W columns, they are not relevant.
int colScore = score[maxNumBlocks-1];
if (colScore <= k) { // Scores > k dont have correct values (so we cannot use them), but are certainly > k.
// NOTE: Score that I find in column c is actually score from column c-W
if (bestScore == -1 || colScore < bestScore) {
bestScore = colScore;
position = c - W;
k = bestScore - 1; // Change k so we will look only for better scores then the best found so far.
}
}
}
//------------------------------------------------------------------//
}
*bestScore_ = bestScore;
*position_ = position;
return MYERS_STATUS_OK;
}
static int myersCalcEditDistanceNW(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks,
const unsigned char* query, int queryLength,
const unsigned char* target, int targetLength,
int alphabetLength, int k, int* bestScore_, int* position_) {
targetLength += W;
queryLength += W;
if (k < abs(targetLength - queryLength)) {
*bestScore_ = *position_ = -1;
return MYERS_STATUS_OK;
}
k = min(k, max(queryLength, targetLength)); // Upper bound for k
// firstBlock is 0-based index of first block in Ukkonen band.
// lastBlock is 0-based index of block AFTER last block in Ukkonen band. <- WATCH OUT!
int firstBlock = 0;
// This is optimal now, by my formula.
int lastBlock = min(maxNumBlocks, ceilDiv(min(k, (k + queryLength - targetLength) / 2) + 1, WORD_SIZE)); // y in Myers
// Initialize P, M and score
for (int b = 0; b < lastBlock; b++) {
score[b] = (b+1) * WORD_SIZE;
P[b] = (Word)-1; // All 1s
M[b] = (Word)0;
}
for (int c = 0; c < targetLength; c++) { // for each column
Word* Peq_c = c < targetLength - W ? Peq[target[c]] : Peq[alphabetLength];
//----------------------- Calculate column -------------------------//
int hout = 1;
for (int b = firstBlock; b < lastBlock; b++) {
hout = calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]);
score[b] += hout;
}
//------------------------------------------------------------------//
//---------- Adjust number of blocks according to Ukkonen ----------//
// Adjust first block - this is optimal now, by my formula.
// While outside of band, advance block
while (score[firstBlock] >= k + WORD_SIZE
|| (firstBlock + 1) * WORD_SIZE - 1 < score[firstBlock] - k - targetLength + queryLength + c) {
firstBlock++;
}
// if (firstBlock == lastBlock)
// printf("Ohohoho\n");
//--- Adjust last block ---//
// While block is not beneath band, calculate next block
while (lastBlock < maxNumBlocks
&& (firstBlock == lastBlock // If above band
|| !(score[lastBlock - 1] >= k + WORD_SIZE
|| (lastBlock * WORD_SIZE - 1 > k - score[lastBlock - 1] + 2 * WORD_SIZE - 2 - targetLength + c + queryLength)))
) {
lastBlock++;
int b = lastBlock-1; // index of last block (one we just added)
P[b] = (Word)-1; // All 1s
M[b] = (Word)0;
int newHout = calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]);
score[b] = score[b-1] - hout + WORD_SIZE + newHout;
hout = newHout;
}
// While block is out of band, move one block up. - This is optimal now, by my formula.
// NOT WORKING!
/*while (lastBlock > 0
&& (score[lastBlock - 1] >= k + WORD_SIZE
|| (lastBlock * WORD_SIZE - 1 > k - score[lastBlock - 1] + 2 * WORD_SIZE - 2 - targetLength + c + queryLength))) {
lastBlock--; // PROBLEM: Cini se da cesto/uvijek smanji za 1 previse!
}*/
while (lastBlock > 0 && score[lastBlock-1] >= k + WORD_SIZE) { // TODO: put some stronger constraint
lastBlock--;
}
//-------------------------//
// If band stops to exist finish
if (lastBlock <= firstBlock) {
//printf("Stopped to exist\n");
*bestScore_ = *position_ = -1;
return MYERS_STATUS_OK;
}
//------------------------------------------------------------------//
}
if (lastBlock == maxNumBlocks) { // If last block of last column was calculated
int bestScore = score[maxNumBlocks-1];
/*
for (int i = 0; i < W; i++) {
if (P[maxNumBlocks-1] & HIGH_BIT_MASK)
bestScore--;
if (M[maxNumBlocks-1] & HIGH_BIT_MASK)
bestScore++;
P[maxNumBlocks-1] <<= 1;
M[maxNumBlocks-1] <<= 1;
}
*/
if (bestScore <= k) {
*bestScore_ = bestScore;
*position_ = targetLength - 1 - W;
return MYERS_STATUS_OK;
}
}
*bestScore_ = *position_ = -1;
return MYERS_STATUS_OK;
}
<commit_msg>Changed lastBlock semantic<commit_after>#include "myers.h"
#include <stdint.h>
using namespace std;
typedef uint64_t Word;
static const int WORD_SIZE = sizeof(Word) * 8; // Size of Word in bits
static const Word HIGH_BIT_MASK = ((Word)1) << (WORD_SIZE-1);
static int myersCalcEditDistanceSemiGlobal(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks,
const unsigned char* query, int queryLength,
const unsigned char* target, int targetLength,
int alphabetLength, int k, int mode, int* bestScore, int* position);
static int myersCalcEditDistanceNW(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks,
const unsigned char* query, int queryLength,
const unsigned char* target, int targetLength,
int alphabetLength, int k, int* bestScore, int* position);
static inline int ceilDiv(int x, int y);
int myersCalcEditDistance(const unsigned char* query, int queryLength,
const unsigned char* target, int targetLength,
int alphabetLength, int k, int mode, int* bestScore, int* position) {
/*--------------------- INITIALIZATION ------------------*/
int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE); // bmax in Myers
Word* P = new Word[maxNumBlocks]; // Contains Pvin for each block (column is divided into blocks)
Word* M = new Word[maxNumBlocks]; // Contains Mvin for each block
int* score = new int[maxNumBlocks]; // Contains score for each block
Word** Peq = new Word*[alphabetLength+1]; // [alphabetLength+1][maxNumBlocks]. Last symbol is wildcard.
int W = maxNumBlocks * WORD_SIZE - queryLength; // number of redundant cells in last level blocks
// Build Peq (1 is match, 0 is mismatch). NOTE: last column is wildcard(symbol that matches anything) with just 1s
for (int symbol = 0; symbol <= alphabetLength; symbol++) {
Peq[symbol] = new Word[maxNumBlocks];
for (int b = 0; b < maxNumBlocks; b++) {
if (symbol < alphabetLength) {
Peq[symbol][b] = 0;
for (int r = (b+1) * WORD_SIZE - 1; r >= b * WORD_SIZE; r--) {
Peq[symbol][b] <<= 1;
// NOTE: We pretend like query is padded at the end with W wildcard symbols
if (r >= queryLength || query[r] == symbol)
Peq[symbol][b] += 1;
}
} else { // Last symbol is wildcard, so it is all 1s
Peq[symbol][b] = (Word)-1;
}
}
}
/*-------------------------------------------------------*/
/*------------------ MAIN CALCULATION -------------------*/
*bestScore = -1;
*position = -1;
if (k < 0) { // If valid k is not given, auto-adjust k until solution is found.
k = WORD_SIZE; // Gives better results then smaller k
while (*bestScore == -1) {
if (mode == MYERS_MODE_HW || mode == MYERS_MODE_SHW)
myersCalcEditDistanceSemiGlobal(P, M, score, Peq, W, maxNumBlocks,
query, queryLength, target, targetLength,
alphabetLength, k, mode, bestScore, position);
else // mode == MYERS_MODE_NW
myersCalcEditDistanceNW(P, M, score, Peq, W, maxNumBlocks,
query, queryLength, target, targetLength,
alphabetLength, k, bestScore, position);
k *= 2;
}
} else {
if (mode == MYERS_MODE_HW || mode == MYERS_MODE_SHW)
myersCalcEditDistanceSemiGlobal(P, M, score, Peq, W, maxNumBlocks,
query, queryLength, target, targetLength,
alphabetLength, k, mode, bestScore, position);
else // mode == MYERS_MODE_NW
myersCalcEditDistanceNW(P, M, score, Peq, W, maxNumBlocks,
query, queryLength, target, targetLength,
alphabetLength, k, bestScore, position);
}
/*-------------------------------------------------------*/
//--- Free memory ---//
delete[] P;
delete[] M;
delete[] score;
for (int i = 0; i < alphabetLength+1; i++)
delete[] Peq[i];
delete[] Peq;
//-------------------//
return MYERS_STATUS_OK;
}
/**
* Corresponds to Advance_Block function from Myers.
* Calculates one word(block), which is part of a column.
* Highest bit of word is most bottom cell of block from column.
* @param [in] Pv Bitset, Pv[i] == 1 if vin is +1, otherwise Pv[i] == 0.
* @param [in] Mv Bitset, Mv[i] == 1 if vin is -1, otherwise Mv[i] == 0.
* @param [in] Eq Bitset, Eq[i] == 1 if match, 0 if mismatch.
* @param [in] hin Will be +1, 0 or -1.
* @param [out] PvOut Bitset, PvOut[i] == 1 if vout is +1, otherwise PvOut[i] == 0.
* @param [out] MvOut Bitset, MvOut[i] == 1 if vout is -1, otherwise MvOut[i] == 0.
* @param [out] hout Will be +1, 0 or -1.
*/
static inline int calculateBlock(Word Pv, Word Mv, Word Eq, const int hin,
Word &PvOut, Word &MvOut) {
Word Xv = Eq | Mv;
if (hin < 0)
Eq |= (Word)1;
Word Xh = (((Eq & Pv) + Pv) ^ Pv) | Eq;
Word Ph = Mv | ~(Xh | Pv);
Word Mh = Pv & Xh;
int hout = 0;
if (Ph & HIGH_BIT_MASK)
hout = 1;
else if (Mh & HIGH_BIT_MASK)
hout = -1;
Ph <<= 1;
Mh <<= 1;
if (hin < 0)
Mh |= (Word)1;
else if (hin > 0)
Ph |= (Word)1;
PvOut = Mh | ~(Xv | Ph);
MvOut = Ph & Xv;
return hout;
}
/**
* Does ceiling division x / y.
* Note: x and y must be non-negative and x + y must not overflow.
*/
static inline int ceilDiv(int x, int y) {
return x % y ? x / y + 1 : x / y;
}
static inline int min(int x, int y) {
return x < y ? x : y;
}
static inline int max(int x, int y) {
return x > y ? x : y;
}
static inline int abs(int x) {
return x < 0 ? -1 * x : x;
}
/**
* @param [in] mode MYERS_MODE_HW or MYERS_MODE_SHW
*/
static int myersCalcEditDistanceSemiGlobal(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks,
const unsigned char* query, int queryLength,
const unsigned char* target, int targetLength,
int alphabetLength, int k, int mode, int* bestScore_, int* position_) {
// firstBlock is 0-based index of first block in Ukkonen band.
// lastBlock is 0-based index of last block in Ukkonen band.
int firstBlock = 0;
int lastBlock = min(ceilDiv(k + 1, WORD_SIZE), maxNumBlocks) - 1; // y in Myers
// Initialize P, M and score
for (int b = 0; b <= lastBlock; b++) {
score[b] = (b+1) * WORD_SIZE;
P[b] = (Word)-1; // All 1s
M[b] = (Word)0;
}
int bestScore = -1;
int position = -1;
for (int c = 0; c < targetLength + W; c++) { // for each column
// We pretend like target is padded at end with W wildcard symbols
Word* Peq_c = c < targetLength ? Peq[target[c]] : Peq[alphabetLength];
//----------------------- Calculate column -------------------------//
int hout = mode == MYERS_MODE_HW ? 0 : 1; // If 0 then gap before query is not penalized
for (int b = firstBlock; b <= lastBlock; b++) {
hout = calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]);
score[b] += hout;
}
//------------------------------------------------------------------//
//---------- Adjust number of blocks according to Ukkonen ----------//
if (mode != MYERS_MODE_HW)
if (score[firstBlock] >= k + WORD_SIZE) {
firstBlock++;
}
if ((score[lastBlock] - hout <= k) && (lastBlock < maxNumBlocks - 1)
&& ((Peq_c[lastBlock + 1] & (Word)1) || hout < 0)) {
// If score of left block is not too big, calculate one more block
lastBlock++;
int b = lastBlock; // index of last block (one we just added)
P[b] = (Word)-1; // All 1s
M[b] = (Word)0;
score[b] = score[b-1] - hout + WORD_SIZE + calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]);
} else {
while (lastBlock >= 0 && score[lastBlock] >= k + WORD_SIZE)
lastBlock--;
}
// If band stops to exist finish
if (lastBlock < firstBlock) {
*bestScore_ = bestScore;
*position_ = position;
return MYERS_STATUS_OK;
}
//------------------------------------------------------------------//
//------------------------- Update best score ----------------------//
if (c >= W && lastBlock == maxNumBlocks - 1) { // We ignore scores from first W columns, they are not relevant.
int colScore = score[maxNumBlocks-1];
if (colScore <= k) { // Scores > k dont have correct values (so we cannot use them), but are certainly > k.
// NOTE: Score that I find in column c is actually score from column c-W
if (bestScore == -1 || colScore < bestScore) {
bestScore = colScore;
position = c - W;
k = bestScore - 1; // Change k so we will look only for better scores then the best found so far.
}
}
}
//------------------------------------------------------------------//
}
*bestScore_ = bestScore;
*position_ = position;
return MYERS_STATUS_OK;
}
static int myersCalcEditDistanceNW(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks,
const unsigned char* query, int queryLength,
const unsigned char* target, int targetLength,
int alphabetLength, int k, int* bestScore_, int* position_) {
targetLength += W;
queryLength += W;
if (k < abs(targetLength - queryLength)) {
*bestScore_ = *position_ = -1;
return MYERS_STATUS_OK;
}
k = min(k, max(queryLength, targetLength)); // Upper bound for k
// firstBlock is 0-based index of first block in Ukkonen band.
// lastBlock is 0-based index of last block in Ukkonen band.
int firstBlock = 0;
// This is optimal now, by my formula.
int lastBlock = min(maxNumBlocks, ceilDiv(min(k, (k + queryLength - targetLength) / 2) + 1, WORD_SIZE)) - 1;
// Initialize P, M and score
for (int b = 0; b <= lastBlock; b++) {
score[b] = (b+1) * WORD_SIZE;
P[b] = (Word)-1; // All 1s
M[b] = (Word)0;
}
for (int c = 0; c < targetLength; c++) { // for each column
Word* Peq_c = c < targetLength - W ? Peq[target[c]] : Peq[alphabetLength];
//----------------------- Calculate column -------------------------//
int hout = 1;
for (int b = firstBlock; b <= lastBlock; b++) {
hout = calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]);
score[b] += hout;
}
//------------------------------------------------------------------//
//---------- Adjust number of blocks according to Ukkonen ----------//
// Adjust first block - this is optimal now, by my formula.
// While outside of band, advance block
while (score[firstBlock] >= k + WORD_SIZE
|| (firstBlock + 1) * WORD_SIZE - 1 < score[firstBlock] - k - targetLength + queryLength + c) {
firstBlock++;
}
// if (firstBlock == lastBlock)
// printf("Ohohoho\n");
//--- Adjust last block ---//
// While block is not beneath band, calculate next block
while (lastBlock + 1 < maxNumBlocks
&& (firstBlock == lastBlock + 1 // If above band
|| !(score[lastBlock] >= k + WORD_SIZE
|| ((lastBlock + 1) * WORD_SIZE - 1 > k - score[lastBlock] + 2 * WORD_SIZE - 2 - targetLength + c + queryLength)))
) {
lastBlock++;
int b = lastBlock; // index of last block (one we just added)
P[b] = (Word)-1; // All 1s
M[b] = (Word)0;
int newHout = calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]);
score[b] = score[b-1] - hout + WORD_SIZE + newHout;
hout = newHout;
}
// While block is out of band, move one block up. - This is optimal now, by my formula.
// NOT WORKING!
/*while (lastBlock >= 0
&& (score[lastBlock] >= k + WORD_SIZE
|| ((lastBlock + 1) * WORD_SIZE - 1 > k - score[lastBlock] + 2 * WORD_SIZE - 2 - targetLength + c + queryLength))) {
lastBlock--; // PROBLEM: Cini se da cesto/uvijek smanji za 1 previse!
}*/
while (lastBlock >= 0 && score[lastBlock] >= k + WORD_SIZE) { // TODO: put some stronger constraint
lastBlock--;
}
//-------------------------//
// If band stops to exist finish
if (lastBlock < firstBlock) {
//printf("Stopped to exist\n");
*bestScore_ = *position_ = -1;
return MYERS_STATUS_OK;
}
//------------------------------------------------------------------//
}
if (lastBlock == maxNumBlocks - 1) { // If last block of last column was calculated
int bestScore = score[maxNumBlocks-1];
/*
for (int i = 0; i < W; i++) {
if (P[maxNumBlocks-1] & HIGH_BIT_MASK)
bestScore--;
if (M[maxNumBlocks-1] & HIGH_BIT_MASK)
bestScore++;
P[maxNumBlocks-1] <<= 1;
M[maxNumBlocks-1] <<= 1;
}
*/
if (bestScore <= k) {
*bestScore_ = bestScore;
*position_ = targetLength - 1 - W;
return MYERS_STATUS_OK;
}
}
*bestScore_ = *position_ = -1;
return MYERS_STATUS_OK;
}
<|endoftext|> |
<commit_before>#include "ofApp.h"
using namespace ofxCv;
using namespace cv;
//--------------------------------------------------------------
void ofApp::setup(){
cout << "Hello World!";
ofSetVerticalSync(true);
cam.initGrabber(640, 480);
tracker.setup();
tracker.setRescale(.5);
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch (key){
case 'f':
case 'F':
ofToggleFullscreen();
break;
default:
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<commit_msg>update() from ofxFaceTracker example-expression<commit_after>#include "ofApp.h"
using namespace ofxCv;
using namespace cv;
//--------------------------------------------------------------
void ofApp::setup(){
cout << "Hello World!";
ofSetVerticalSync(true);
cam.initGrabber(640, 480);
tracker.setup();
tracker.setRescale(.5);
}
//--------------------------------------------------------------
void ofApp::update(){
cam.update();
if(cam.isFrameNew()) {
if(tracker.update(toCv(cam))) {
classifier.classify(tracker);
}
}
}
//--------------------------------------------------------------
void ofApp::draw(){
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch (key){
case 'f':
case 'F':
ofToggleFullscreen();
break;
default:
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<|endoftext|> |
<commit_before>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
// Screen
ofBackground(255);
// Font
font.loadFont("font/Courier New Bold.ttf", 9);
// Misc
verbose = true;
// Pd
int ticksPerBuffer = 8;
ofSoundStreamSetup(2, 1, 44100, ofxPd::blockSize()*ticksPerBuffer, 3);
core.setup(2, 1, 44100, ticksPerBuffer);
// Camera
camWidth = 640;
camHeight = 480;
lineCounter = 0;
tmpR = 0;
tmpG = 0;
tmpB = 0;
tmpC = 0;
vector<ofVideoDevice> devices = camera.listDevices();
if(verbose) {
for(int i = 0; i < devices.size(); i++){
cout << devices[i].id << ": " << devices[i].deviceName;
if( devices[i].bAvailable ){
cout << endl;
}else{
cout << " - unavailable " << endl;
}
}
}
camera.setDeviceID(4);
camera.setDesiredFrameRate(60);
camera.setVerbose(true);
camera.initGrabber(camWidth, camHeight);
// FBOs
averageColours.allocate(camWidth, camHeight);
blockColours.allocate(camWidth, camHeight);
cout << " -- END OF SETUP -- " << endl;
}
//--------------------------------------------------------------
void ofApp::update(){
// Camera
camera.update();
if (camera.isFrameNew()){
pixels = camera.getPixels();
int totalPixels = camWidth * camHeight;
lineCounter = 0;
int tempCounter = 0;
for (int i = 0; i < totalPixels; i++) {
// Adding Colors
tmpR += pixels[i*3];
tmpG += pixels[i*3+1];
tmpB += pixels[i*3+2];
//tmpC += pixels[i];
tempCounter++;
// Store Color
if(i % camWidth == 0) {
// get the average value
tmpR = tmpR/camWidth;
tmpG = tmpG/camWidth;
tmpB = tmpB/camWidth;
// Set Avg Colours To Color Array
lineColors[lineCounter].r = int(tmpR);
lineColors[lineCounter].g = int(tmpG);
lineColors[lineCounter].b = int(tmpB);
// Reset Temp Colors
tmpR = 0;
tmpG = 0;
tmpB = 0;
// Iterate
lineCounter++;
}
}
}
}
//--------------------------------------------------------------
void ofApp::draw(){
// Raw Camera
ofSetColor(255);
camera.draw(0, 0, camWidth, camHeight);
// Lines
for (int i = 0; i < camHeight; i++) {
ofSetColor(lineColors[i]);
ofLine(camWidth + 0, 0 + i, camWidth * 2 + 0, 0 + i);
}
// Debug
ofSetColor(0);
char fpsStr[255];
sprintf(fpsStr, "frame rate: %f", ofGetFrameRate());
ofDrawBitmapString(fpsStr, 50, ofGetWindowHeight() - 50);
}
//--------------------------------------------------------------
void ofApp::exit() {
ofLogNotice("Exiting App");
// Close Pd
core.exit();
// Close Camera
camera.close();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
// Camera Settings
if (key == 's' || key == 'S'){
camera.videoSettings();
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<commit_msg>GL_RGBA THEM FBOs YO<commit_after>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
// Screen
ofBackground(255);
// Font
font.loadFont("font/Courier New Bold.ttf", 9);
// Misc
verbose = true;
// Pd
int ticksPerBuffer = 8;
ofSoundStreamSetup(2, 1, 44100, ofxPd::blockSize()*ticksPerBuffer, 3);
core.setup(2, 1, 44100, ticksPerBuffer);
// Camera
camWidth = 640;
camHeight = 480;
lineCounter = 0;
tmpR = 0;
tmpG = 0;
tmpB = 0;
tmpC = 0;
vector<ofVideoDevice> devices = camera.listDevices();
if(verbose) {
for(int i = 0; i < devices.size(); i++){
cout << devices[i].id << ": " << devices[i].deviceName;
if( devices[i].bAvailable ){
cout << endl;
}else{
cout << " - unavailable " << endl;
}
}
}
camera.setDeviceID(4);
camera.setDesiredFrameRate(60);
camera.setVerbose(true);
camera.initGrabber(camWidth, camHeight);
// FBOs
averageColours.allocate(camWidth, camHeight, GL_RGBA);
blockColours.allocate(camWidth, camHeight, GL_RGBA);
cout << " -- END OF SETUP -- " << endl;
}
//--------------------------------------------------------------
void ofApp::update(){
// Camera
camera.update();
if (camera.isFrameNew()){
pixels = camera.getPixels();
int totalPixels = camWidth * camHeight;
lineCounter = 0;
int tempCounter = 0;
for (int i = 0; i < totalPixels; i++) {
// Adding Colors
tmpR += pixels[i*3];
tmpG += pixels[i*3+1];
tmpB += pixels[i*3+2];
//tmpC += pixels[i];
tempCounter++;
// Store Color
if(i % camWidth == 0) {
// get the average value
tmpR = tmpR/camWidth;
tmpG = tmpG/camWidth;
tmpB = tmpB/camWidth;
// Set Avg Colours To Color Array
lineColors[lineCounter].r = int(tmpR);
lineColors[lineCounter].g = int(tmpG);
lineColors[lineCounter].b = int(tmpB);
// Reset Temp Colors
tmpR = 0;
tmpG = 0;
tmpB = 0;
// Iterate
lineCounter++;
}
}
}
}
//--------------------------------------------------------------
void ofApp::draw(){
// Raw Camera
ofSetColor(255);
camera.draw(0, 0, camWidth, camHeight);
// Lines
for (int i = 0; i < camHeight; i++) {
ofSetColor(lineColors[i]);
ofLine(camWidth + 0, 0 + i, camWidth * 2 + 0, 0 + i);
}
// Debug
ofSetColor(0);
char fpsStr[255];
sprintf(fpsStr, "frame rate: %f", ofGetFrameRate());
ofDrawBitmapString(fpsStr, 50, ofGetWindowHeight() - 50);
}
//--------------------------------------------------------------
void ofApp::exit() {
ofLogNotice("Exiting App");
// Close Pd
core.exit();
// Close Camera
camera.close();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
// Camera Settings
if (key == 's' || key == 'S'){
camera.videoSettings();
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<|endoftext|> |
<commit_before>#include "ofApp.h"
#include "Terrain.h"
#include "MusicAnalysis.h"
//--------------------------------------------------------------
void ofApp::setup()
{
songNames.push_back("song_1.wav");
musicAnalysis.loadSongs(songNames);
terrain.setMusicAnalysis(&musicAnalysis);
terrain.initializeTerrain();
cam.setDistance(50);
ofSetVerticalSync(true);
ofEnableDepthTest();
}
//--------------------------------------------------------------
void ofApp::update()
{
terrain.changeHeight();
}
//--------------------------------------------------------------
void ofApp::draw()
{
cam.begin();
terrain.draw();
cam.end();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key) {
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key) {
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ) {
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y) {
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y) {
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h) {
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg) {
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo) {
}
<commit_msg>Keyboard Input<commit_after>#include "ofApp.h"
#include "Terrain.h"
#include "MusicAnalysis.h"
//--------------------------------------------------------------
void ofApp::setup()
{
songNames.push_back("song_1.wav");
musicAnalysis.loadSongs(songNames);
terrain.setMusicAnalysis(&musicAnalysis);
terrain.initializeTerrain();
cam.setDistance(50);
ofSetVerticalSync(true);
ofEnableDepthTest();
}
//--------------------------------------------------------------
void ofApp::update()
{
terrain.changeHeight();
}
//--------------------------------------------------------------
void ofApp::draw()
{
cam.begin();
terrain.draw();
cam.end();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key)
{
if (key == 'p')
{
musicAnalysis.togglePlay();
}
else if ('0' <= key <= '9')
{
musicAnalysis.changeSong((int)key);
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key) {
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ) {
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y) {
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y) {
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h) {
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg) {
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo) {
}
<|endoftext|> |
<commit_before>#include <cstring>
#define BUILDING_NODE_EXTENSION
#include <node.h>
#include <node_buffer.h>
#include <mcnet.h>
#include "parser.h"
using namespace v8;
using namespace node;
mcnet::Parser::Parser() {
settings.on_packet = mcnet::Parser::on_packet;
settings.on_error = mcnet::Parser::on_error;
}
mcnet::Parser::~Parser() {
}
void mcnet::Parser::Init(Handle< Object > target) {
Local< FunctionTemplate > tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("Parser"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->PrototypeTemplate()->Set(String::NewSymbol("execute"), FunctionTemplate::New(Execute)->GetFunction());
tpl->PrototypeTemplate()->Set(String::NewSymbol("EAGAIN"), Number::New(MCNET_EAGAIN));
tpl->PrototypeTemplate()->Set(String::NewSymbol("EINVALID"), Number::New(MCNET_EINVALID));
Persistent< Function > constructor = Persistent< Function >::New(tpl->GetFunction());
target->Set(String::NewSymbol("Parser"), constructor);
}
Handle< Value > mcnet::Parser::New(const Arguments& args) {
HandleScope scope;
Parser* obj = new Parser();
obj->Wrap(args.This());
return args.This();
}
Handle< Value > mcnet::Parser::Execute(const Arguments& args) {
HandleScope scope;
mcnet::Parser* parser = ObjectWrap::Unwrap< mcnet::Parser >(args.This());
Local< Object > buffer = Local< Object >::Cast(args[0]);
Handle< Object > obj = args.This();
parser->parser.data = (void*)&obj;
size_t nparsed = mcnet_parser_execute(&(parser->parser), &(parser->settings), reinterpret_cast< uint8_t* >(Buffer::Data(buffer)), Buffer::Length(buffer));
parser->parser.data = NULL;
return scope.Close(Number::New(nparsed));
}
void mcnet::Parser::on_packet(mcnet_parser_t* parser, mcnet_packet_t* packet) {
Handle< Object >* obj = (Handle< Object >*)(parser->data);
Local< Object > object = Object::New();
Local< Object > global = Context::GetCurrent()->Global();
Local< Function > buffer_constructor = Local< Function >::Cast(global->Get(String::New("Buffer")));
#define PACKET(id, code) case 0x##id: { \
mcnet_packet_##id##_t* pkt = reinterpret_cast< mcnet_packet_##id##_t* >(packet); \
BYTE(pid) \
code \
break; \
}
#define CODE(data)
#define BOOL(name) object->Set(String::New(#name), Boolean::New(pkt->name ? true : false));
#define NUMBER(name) object->Set(String::New(#name), Number::New(pkt->name));
#define BYTE(name) NUMBER(name)
#define UBYTE(name) NUMBER(name)
#define SHORT(name) NUMBER(name)
#define USHORT(name) NUMBER(name)
#define INT(name) NUMBER(name)
#define LONG(name) NUMBER(name)
#define FLOAT(name) NUMBER(name)
#define DOUBLE(name) NUMBER(name)
#define STRING8(name) BLOB(name, name##_len)
#define STRING16(name) BLOB(name, name##_len * 2)
#define BLOB(name, length) \
Buffer* name##_buffer = Buffer::New(pkt->length); \
memcpy(Buffer::Data(name##_buffer), pkt->name, pkt->length); \
Handle< Value > name##_args[3] = { name##_buffer->handle_, Integer::New(pkt->length), Integer::New(0) }; \
object->Set(String::New(#name), buffer_constructor->NewInstance(3, name##_args));
#define METADATA(name) \
Local< Object > name##_metadata = Object::New(); \
mcnet_metadata_parser_t name##_parser; \
name##_parser.on_error = NULL; \
name##_parser.on_complete = NULL; \
name##_parser.on_entry = mcnet::Parser::on_metadata_entry; \
name##_parser.data = &name##_metadata; \
mcnet_metadata_parser_parse(&name##_parser, pkt->name, pkt->name##_len); \
object->Set(String::New(#name), name##_metadata);
#define SLOT(name) \
Local< Object > name##_slot = Object::New(); \
mcnet_slot_parser_t name##_parser; \
name##_parser.on_error = NULL; \
name##_parser.on_complete = mcnet::Parser::on_slot; \
name##_parser.data = &name##_slot; \
mcnet_slot_parser_parse(&name##_parser, pkt->name, pkt->name##_len); \
name##_parser.data = NULL; \
object->Set(String::New(#name), name##_slot);
#define SLOTS(name, count) \
Local< Array > name##_slots = Array::New(pkt->count); \
mcnet_slot_parser_t name##_parser; \
name##_parser.on_error = NULL; \
name##_parser.on_complete = mcnet::Parser::on_slot; \
int name##_nparsed = 0, name##_i = 0; \
while (name##_nparsed < pkt->name##_len) { \
Local< Object > name##_slot = Object::New(); \
name##_parser.data = &name##_slot; \
name##_nparsed += mcnet_slot_parser_parse(&name##_parser, pkt->name + name##_nparsed, pkt->name##_len - name##_nparsed); \
name##_parser.data = NULL; \
name##_slots->Set(name##_i++, name##_slot); \
} \
object->Set(String::New(#name), name##_slots);
switch (packet->pid) {
PACKETS
}
#undef CODE
#undef BOOL
#undef NUMBER
#undef BYTE
#undef UBYTE
#undef SHORT
#undef USHORT
#undef INT
#undef LONG
#undef FLOAT
#undef DOUBLE
#undef STRING8
#undef STRING16
#undef BLOB
#undef METADATA
#undef SLOT
#undef SLOTS
#undef PACKET
Handle< Value > argv[2] = {
String::New("packet"),
object
};
MakeCallback(*obj, "emit", 2, argv);
}
void mcnet::Parser::on_error(mcnet_parser_t* parser, int err) {
if (err == MCNET_EAGAIN) {
return;
}
Handle< Object >* obj = (Handle< Object >*)(parser->data);
Handle< Value > argv[2] = {
String::New("error"),
Number::New(err)
};
MakeCallback(*obj, "emit", 2, argv);
}
void mcnet::Parser::on_metadata_entry(mcnet_metadata_parser_t* parser, mcnet_metadata_entry_t* entry) {
Local< Object >* obj = reinterpret_cast< Local< Object >* >(parser->data);
switch (entry->type) {
case MCNET_METADATA_TYPE_BYTE: {
mcnet_metadata_entry_byte_t* ent = reinterpret_cast< mcnet_metadata_entry_byte_t* >(entry);
(*obj)->Set(ent->index, Number::New(ent->data));
break;
}
case MCNET_METADATA_TYPE_SHORT: {
mcnet_metadata_entry_short_t* ent = reinterpret_cast< mcnet_metadata_entry_short_t* >(entry);
(*obj)->Set(ent->index, Number::New(ent->data));
break;
}
case MCNET_METADATA_TYPE_INT: {
mcnet_metadata_entry_int_t* ent = reinterpret_cast< mcnet_metadata_entry_int_t* >(entry);
(*obj)->Set(ent->index, Number::New(ent->data));
break;
}
case MCNET_METADATA_TYPE_FLOAT: {
mcnet_metadata_entry_float_t* ent = reinterpret_cast< mcnet_metadata_entry_float_t* >(entry);
(*obj)->Set(ent->index, Number::New(ent->data));
break;
}
case MCNET_METADATA_TYPE_STRING16: {
mcnet_metadata_entry_string16_t* ent = reinterpret_cast< mcnet_metadata_entry_string16_t* >(entry);
Buffer* buffer = Buffer::New(ent->data_length);
memcpy(Buffer::Data(buffer), ent->data, ent->data_length);
Handle< Value > args[3] = { buffer->handle_, Integer::New(ent->data_length), Integer::New(0) };
Local< Object > global = Context::GetCurrent()->Global();
Local< Function > buffer_constructor = Local< Function >::Cast(global->Get(String::New("Buffer")));
(*obj)->Set(ent->index, buffer_constructor->NewInstance(3, args));
break;
}
case MCNET_METADATA_TYPE_SLOT: {
mcnet_metadata_entry_sbs_t* ent = reinterpret_cast< mcnet_metadata_entry_sbs_t* >(entry);
Local< Object > object = Object::New();
object->Set(String::New("id"), Number::New(ent->id));
object->Set(String::New("count"), Number::New(ent->count));
object->Set(String::New("damage"), Number::New(ent->damage));
(*obj)->Set(ent->index, object);
break;
}
case MCNET_METADATA_TYPE_INTS: {
mcnet_metadata_entry_iii_t* ent = reinterpret_cast< mcnet_metadata_entry_iii_t* >(entry);
Local< Array > array = Array::New(3);
array->Set(0, Number::New(ent->data[0]));
array->Set(1, Number::New(ent->data[1]));
array->Set(2, Number::New(ent->data[2]));
(*obj)->Set(ent->index, array);
break;
}
}
}
void mcnet::Parser::on_slot(mcnet_slot_parser_t* parser, mcnet_slot_t* slot) {
Local< Object >* obj = reinterpret_cast< Local< Object >* >(parser->data);
(*obj)->Set(String::New("item"), Number::New(slot->item));
(*obj)->Set(String::New("count"), Number::New(slot->count));
(*obj)->Set(String::New("meta"), Number::New(slot->meta));
Buffer* buffer = Buffer::New(slot->data_len);
memcpy(Buffer::Data(buffer), slot->data, slot->data_len);
Handle< Value > args[3] = { buffer->handle_, Integer::New(slot->data_len), Integer::New(0) };
Local< Object > global = Context::GetCurrent()->Global();
Local< Function > buffer_constructor = Local< Function >::Cast(global->Get(String::New("Buffer")));
(*obj)->Set(String::New("data"), buffer_constructor->NewInstance(3, args));
}
<commit_msg>fixed string metadata length<commit_after>#include <cstring>
#define BUILDING_NODE_EXTENSION
#include <node.h>
#include <node_buffer.h>
#include <mcnet.h>
#include "parser.h"
using namespace v8;
using namespace node;
mcnet::Parser::Parser() {
settings.on_packet = mcnet::Parser::on_packet;
settings.on_error = mcnet::Parser::on_error;
}
mcnet::Parser::~Parser() {
}
void mcnet::Parser::Init(Handle< Object > target) {
Local< FunctionTemplate > tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("Parser"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->PrototypeTemplate()->Set(String::NewSymbol("execute"), FunctionTemplate::New(Execute)->GetFunction());
tpl->PrototypeTemplate()->Set(String::NewSymbol("EAGAIN"), Number::New(MCNET_EAGAIN));
tpl->PrototypeTemplate()->Set(String::NewSymbol("EINVALID"), Number::New(MCNET_EINVALID));
Persistent< Function > constructor = Persistent< Function >::New(tpl->GetFunction());
target->Set(String::NewSymbol("Parser"), constructor);
}
Handle< Value > mcnet::Parser::New(const Arguments& args) {
HandleScope scope;
Parser* obj = new Parser();
obj->Wrap(args.This());
return args.This();
}
Handle< Value > mcnet::Parser::Execute(const Arguments& args) {
HandleScope scope;
mcnet::Parser* parser = ObjectWrap::Unwrap< mcnet::Parser >(args.This());
Local< Object > buffer = Local< Object >::Cast(args[0]);
Handle< Object > obj = args.This();
parser->parser.data = (void*)&obj;
size_t nparsed = mcnet_parser_execute(&(parser->parser), &(parser->settings), reinterpret_cast< uint8_t* >(Buffer::Data(buffer)), Buffer::Length(buffer));
parser->parser.data = NULL;
return scope.Close(Number::New(nparsed));
}
void mcnet::Parser::on_packet(mcnet_parser_t* parser, mcnet_packet_t* packet) {
Handle< Object >* obj = (Handle< Object >*)(parser->data);
Local< Object > object = Object::New();
Local< Object > global = Context::GetCurrent()->Global();
Local< Function > buffer_constructor = Local< Function >::Cast(global->Get(String::New("Buffer")));
#define PACKET(id, code) case 0x##id: { \
mcnet_packet_##id##_t* pkt = reinterpret_cast< mcnet_packet_##id##_t* >(packet); \
BYTE(pid) \
code \
break; \
}
#define CODE(data)
#define BOOL(name) object->Set(String::New(#name), Boolean::New(pkt->name ? true : false));
#define NUMBER(name) object->Set(String::New(#name), Number::New(pkt->name));
#define BYTE(name) NUMBER(name)
#define UBYTE(name) NUMBER(name)
#define SHORT(name) NUMBER(name)
#define USHORT(name) NUMBER(name)
#define INT(name) NUMBER(name)
#define LONG(name) NUMBER(name)
#define FLOAT(name) NUMBER(name)
#define DOUBLE(name) NUMBER(name)
#define STRING8(name) BLOB(name, name##_len)
#define STRING16(name) BLOB(name, name##_len * 2)
#define BLOB(name, length) \
Buffer* name##_buffer = Buffer::New(pkt->length); \
memcpy(Buffer::Data(name##_buffer), pkt->name, pkt->length); \
Handle< Value > name##_args[3] = { name##_buffer->handle_, Integer::New(pkt->length), Integer::New(0) }; \
object->Set(String::New(#name), buffer_constructor->NewInstance(3, name##_args));
#define METADATA(name) \
Local< Object > name##_metadata = Object::New(); \
mcnet_metadata_parser_t name##_parser; \
name##_parser.on_error = NULL; \
name##_parser.on_complete = NULL; \
name##_parser.on_entry = mcnet::Parser::on_metadata_entry; \
name##_parser.data = &name##_metadata; \
mcnet_metadata_parser_parse(&name##_parser, pkt->name, pkt->name##_len); \
object->Set(String::New(#name), name##_metadata);
#define SLOT(name) \
Local< Object > name##_slot = Object::New(); \
mcnet_slot_parser_t name##_parser; \
name##_parser.on_error = NULL; \
name##_parser.on_complete = mcnet::Parser::on_slot; \
name##_parser.data = &name##_slot; \
mcnet_slot_parser_parse(&name##_parser, pkt->name, pkt->name##_len); \
name##_parser.data = NULL; \
object->Set(String::New(#name), name##_slot);
#define SLOTS(name, count) \
Local< Array > name##_slots = Array::New(pkt->count); \
mcnet_slot_parser_t name##_parser; \
name##_parser.on_error = NULL; \
name##_parser.on_complete = mcnet::Parser::on_slot; \
int name##_nparsed = 0, name##_i = 0; \
while (name##_nparsed < pkt->name##_len) { \
Local< Object > name##_slot = Object::New(); \
name##_parser.data = &name##_slot; \
name##_nparsed += mcnet_slot_parser_parse(&name##_parser, pkt->name + name##_nparsed, pkt->name##_len - name##_nparsed); \
name##_parser.data = NULL; \
name##_slots->Set(name##_i++, name##_slot); \
} \
object->Set(String::New(#name), name##_slots);
switch (packet->pid) {
PACKETS
}
#undef CODE
#undef BOOL
#undef NUMBER
#undef BYTE
#undef UBYTE
#undef SHORT
#undef USHORT
#undef INT
#undef LONG
#undef FLOAT
#undef DOUBLE
#undef STRING8
#undef STRING16
#undef BLOB
#undef METADATA
#undef SLOT
#undef SLOTS
#undef PACKET
Handle< Value > argv[2] = {
String::New("packet"),
object
};
MakeCallback(*obj, "emit", 2, argv);
}
void mcnet::Parser::on_error(mcnet_parser_t* parser, int err) {
if (err == MCNET_EAGAIN) {
return;
}
Handle< Object >* obj = (Handle< Object >*)(parser->data);
Handle< Value > argv[2] = {
String::New("error"),
Number::New(err)
};
MakeCallback(*obj, "emit", 2, argv);
}
void mcnet::Parser::on_metadata_entry(mcnet_metadata_parser_t* parser, mcnet_metadata_entry_t* entry) {
Local< Object >* obj = reinterpret_cast< Local< Object >* >(parser->data);
switch (entry->type) {
case MCNET_METADATA_TYPE_BYTE: {
mcnet_metadata_entry_byte_t* ent = reinterpret_cast< mcnet_metadata_entry_byte_t* >(entry);
(*obj)->Set(ent->index, Number::New(ent->data));
break;
}
case MCNET_METADATA_TYPE_SHORT: {
mcnet_metadata_entry_short_t* ent = reinterpret_cast< mcnet_metadata_entry_short_t* >(entry);
(*obj)->Set(ent->index, Number::New(ent->data));
break;
}
case MCNET_METADATA_TYPE_INT: {
mcnet_metadata_entry_int_t* ent = reinterpret_cast< mcnet_metadata_entry_int_t* >(entry);
(*obj)->Set(ent->index, Number::New(ent->data));
break;
}
case MCNET_METADATA_TYPE_FLOAT: {
mcnet_metadata_entry_float_t* ent = reinterpret_cast< mcnet_metadata_entry_float_t* >(entry);
(*obj)->Set(ent->index, Number::New(ent->data));
break;
}
case MCNET_METADATA_TYPE_STRING16: {
mcnet_metadata_entry_string16_t* ent = reinterpret_cast< mcnet_metadata_entry_string16_t* >(entry);
Buffer* buffer = Buffer::New(ent->data_length * 2);
memcpy(Buffer::Data(buffer), ent->data, ent->data_length * 2);
Handle< Value > args[3] = { buffer->handle_, Integer::New(ent->data_length * 2), Integer::New(0) };
Local< Object > global = Context::GetCurrent()->Global();
Local< Function > buffer_constructor = Local< Function >::Cast(global->Get(String::New("Buffer")));
(*obj)->Set(ent->index, buffer_constructor->NewInstance(3, args));
break;
}
case MCNET_METADATA_TYPE_SLOT: {
mcnet_metadata_entry_sbs_t* ent = reinterpret_cast< mcnet_metadata_entry_sbs_t* >(entry);
Local< Object > object = Object::New();
object->Set(String::New("id"), Number::New(ent->id));
object->Set(String::New("count"), Number::New(ent->count));
object->Set(String::New("damage"), Number::New(ent->damage));
(*obj)->Set(ent->index, object);
break;
}
case MCNET_METADATA_TYPE_INTS: {
mcnet_metadata_entry_iii_t* ent = reinterpret_cast< mcnet_metadata_entry_iii_t* >(entry);
Local< Array > array = Array::New(3);
array->Set(0, Number::New(ent->data[0]));
array->Set(1, Number::New(ent->data[1]));
array->Set(2, Number::New(ent->data[2]));
(*obj)->Set(ent->index, array);
break;
}
}
}
void mcnet::Parser::on_slot(mcnet_slot_parser_t* parser, mcnet_slot_t* slot) {
Local< Object >* obj = reinterpret_cast< Local< Object >* >(parser->data);
(*obj)->Set(String::New("item"), Number::New(slot->item));
(*obj)->Set(String::New("count"), Number::New(slot->count));
(*obj)->Set(String::New("meta"), Number::New(slot->meta));
Buffer* buffer = Buffer::New(slot->data_len);
memcpy(Buffer::Data(buffer), slot->data, slot->data_len);
Handle< Value > args[3] = { buffer->handle_, Integer::New(slot->data_len), Integer::New(0) };
Local< Object > global = Context::GetCurrent()->Global();
Local< Function > buffer_constructor = Local< Function >::Cast(global->Get(String::New("Buffer")));
(*obj)->Set(String::New("data"), buffer_constructor->NewInstance(3, args));
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2015 Jamis Hoo
* Distributed under the MIT license
* (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
*
* Project: UDP-Echo
* Filename: parser.cc
* Version: 1.0
* Author: Jamis Hoo
* E-mail: hjm211324@gmail.com
* Date: May 1, 2015
* Time: 20:02:34
* Description:
*****************************************************************************/
#include "parser.h"
#include <iostream>
#include <fstream>
#include <limits>
void OptionParser::initialize() {
using namespace std;
namespace po = boost::program_options;
po::options_description server_options("Server options");
server_options.add_options()
("inputfile,i", po::value<string>(), "Path of file fo all clients. This options is mandatory for server. ")
("count,c", po::value<int32_t>(), "Stop after sending count packets. The default value is 5. ")
("timeout,t", po::value<int32_t>(), "Specify a timeout, in seconds. The default value is 3. "
"If this is set to zero, it will never timeout. ")
("packetsize,s", po::value<int32_t>(), "Specify the number of data bytes to be sent."
"The default is 28, which is size of UDP header and IP header, "
"value less than this will be ignored. "
"Don't set this value too large which exceeds the limit for "
"the data length imposed by the underlying IPv4 protocol. ");
po::options_description client_options("Client options");
client_options.add_options()
("listen,l", "Listen for incoming messages. This option is mandatory for client. ");
po::options_description generic_options("Generic options");
generic_options.add_options()
("help,h", "Display this help message. ")
("version,v", "Display version number of this program. ")
("port,p", po::value<uint16_t>(), "Specify listen/send port for client/server. "
"This option is mandatory for client. "
"If you don't specify a port for a server, "
"the system will automatically allocate a free port. ");
all_options.add(generic_options).add(server_options).add(client_options);
}
void OptionParser::parse(int argc, char** argv) {
using namespace std;
namespace po = boost::program_options;
_is_server = _is_client = 0;
_filename.clear();
try {
po::store(parse_command_line(argc, argv, all_options), vm);
po::notify(vm);
// print version message
if (vm.size() == 1 && vm.count("version")) {
cout << "Version: 1.0" << "\n";
cout << "Copyright (c) 2015 Jamis Hoo" << "\n";
cout << "Distributed under the MIT license" << "\n";
return;
}
// print help message
if (vm.size() == 1 && vm.count("help")) {
cout << all_options << "\n";
return;
}
// client
if (vm.size() == 2 && vm.count("listen") && vm.count("port")) {
_is_client = 1;
_port = vm["port"].as<uint16_t>();
return;
}
// server
if (vm.count("inputfile") && !vm.count("help") && !vm.count("version") && !vm.count("listen")) {
_is_server = 1;
_filename = vm["inputfile"].as<string>();
if (vm.count("port"))
_port = vm["port"].as<uint16_t>();
else
_port = 0;
if (vm.count("timeout"))
_timeout = vm["timeout"].as<int32_t>();
else
_timeout = 3;
if (vm.count("count"))
_packet_count = vm["count"].as<int32_t>();
else
_packet_count = 5;
if (vm.count("packetsize"))
_packet_size = vm["packetsize"].as<int32_t>();
else
_packet_size = PACKET_HEADER_SIZE;
loadClientAddrs();
return;
}
// else invalid options
if (argc - 1)
cout << "Invalid option(s)." << "\n\n";
cout << all_options << "\n";
} catch (exception& e) {
cerr << e.what() << "\n";
}
}
void OptionParser::loadClientAddrs() {
std::ifstream fin(_filename);
std::string ip_s;
std::string port_s;
std::array<uint8_t, 4> ip;
uint16_t port;
while (fin >> ip_s >> port_s) {
try {
ip = text2ip(ip_s);
int port_tmp = std::stoi(port_s);
if (port_tmp > std::numeric_limits<uint16_t>::max() ||
port_tmp < std::numeric_limits<uint16_t>::min())
throw std::out_of_range(port_s);
port = port_tmp;
_client_addrs.emplace_back(ip, port);
} catch (std::exception& error) {
std::cerr << error.what() << std::endl;
}
}
}
<commit_msg>fix typo<commit_after>/******************************************************************************
* Copyright (c) 2015 Jamis Hoo
* Distributed under the MIT license
* (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
*
* Project: UDP-Echo
* Filename: parser.cc
* Version: 1.0
* Author: Jamis Hoo
* E-mail: hjm211324@gmail.com
* Date: May 1, 2015
* Time: 20:02:34
* Description:
*****************************************************************************/
#include "parser.h"
#include <iostream>
#include <fstream>
#include <limits>
void OptionParser::initialize() {
using namespace std;
namespace po = boost::program_options;
po::options_description server_options("Server options");
server_options.add_options()
("inputfile,i", po::value<string>(), "Path of file for all clients. This options is mandatory for server. ")
("count,c", po::value<int32_t>(), "Stop after sending count packets. The default value is 5. ")
("timeout,t", po::value<int32_t>(), "Specify a timeout, in seconds. The default value is 3. "
"If this is set to zero, it will never timeout. ")
("packetsize,s", po::value<int32_t>(), "Specify the number of data bytes to be sent."
"The default is 28, which is size of UDP header and IP header, "
"value less than this will be ignored. "
"Don't set this value too large which exceeds the limit for "
"the data length imposed by the underlying IPv4 protocol. ");
po::options_description client_options("Client options");
client_options.add_options()
("listen,l", "Listen for incoming messages. This option is mandatory for client. ");
po::options_description generic_options("Generic options");
generic_options.add_options()
("help,h", "Display this help message. ")
("version,v", "Display version number of this program. ")
("port,p", po::value<uint16_t>(), "Specify listen/send port for client/server. "
"This option is mandatory for client. "
"If you don't specify a port for a server, "
"the system will automatically allocate a free port. ");
all_options.add(generic_options).add(server_options).add(client_options);
}
void OptionParser::parse(int argc, char** argv) {
using namespace std;
namespace po = boost::program_options;
_is_server = _is_client = 0;
_filename.clear();
try {
po::store(parse_command_line(argc, argv, all_options), vm);
po::notify(vm);
// print version message
if (vm.size() == 1 && vm.count("version")) {
cout << "Version: 1.0" << "\n";
cout << "Copyright (c) 2015 Jamis Hoo" << "\n";
cout << "Distributed under the MIT license" << "\n";
return;
}
// print help message
if (vm.size() == 1 && vm.count("help")) {
cout << all_options << "\n";
return;
}
// client
if (vm.size() == 2 && vm.count("listen") && vm.count("port")) {
_is_client = 1;
_port = vm["port"].as<uint16_t>();
return;
}
// server
if (vm.count("inputfile") && !vm.count("help") && !vm.count("version") && !vm.count("listen")) {
_is_server = 1;
_filename = vm["inputfile"].as<string>();
if (vm.count("port"))
_port = vm["port"].as<uint16_t>();
else
_port = 0;
if (vm.count("timeout"))
_timeout = vm["timeout"].as<int32_t>();
else
_timeout = 3;
if (vm.count("count"))
_packet_count = vm["count"].as<int32_t>();
else
_packet_count = 5;
if (vm.count("packetsize"))
_packet_size = vm["packetsize"].as<int32_t>();
else
_packet_size = PACKET_HEADER_SIZE;
loadClientAddrs();
return;
}
// else invalid options
if (argc - 1)
cout << "Invalid option(s)." << "\n\n";
cout << all_options << "\n";
} catch (exception& e) {
cerr << e.what() << "\n";
}
}
void OptionParser::loadClientAddrs() {
std::ifstream fin(_filename);
std::string ip_s;
std::string port_s;
std::array<uint8_t, 4> ip;
uint16_t port;
while (fin >> ip_s >> port_s) {
try {
ip = text2ip(ip_s);
int port_tmp = std::stoi(port_s);
if (port_tmp > std::numeric_limits<uint16_t>::max() ||
port_tmp < std::numeric_limits<uint16_t>::min())
throw std::out_of_range(port_s);
port = port_tmp;
_client_addrs.emplace_back(ip, port);
} catch (std::exception& error) {
std::cerr << error.what() << std::endl;
}
}
}
<|endoftext|> |
<commit_before>// Nikita Kouevda
// 2013/11/02
#include <cmath>
#include "prime.hpp"
using namespace std;
bool isPrime(long int n) {
if (n == 2 || n == 3) {
return 1;
} else if (n < 2 || n % 2 == 0 || n % 3 == 0) {
return 0;
}
for (long int i = 5, max = sqrt(n) + 1; i < max; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return 0;
}
}
return 1;
}
<commit_msg>Use true and false instead of 1 and 0.<commit_after>// Nikita Kouevda
// 2013/11/02
#include <cmath>
#include "prime.hpp"
using namespace std;
bool isPrime(long int n) {
if (n == 2 || n == 3) {
return true;
} else if (n < 2 || n % 2 == 0 || n % 3 == 0) {
return false;
}
for (long int i = 5, max = sqrt(n) + 1; i < max; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
<|endoftext|> |
<commit_before>/*
* redsea - RDS decoder
* Copyright (c) Oona Räisänen OH2EIQ (windyoona@gmail.com)
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include <iostream>
#include "config.h"
#include "src/channel.h"
#include "src/common.h"
#include "src/groups.h"
#include "src/options.h"
#include "src/subcarrier.h"
namespace redsea {
void PrintUsage() {
std::cout <<
"radio_command | redsea [OPTIONS]\n"
"\n"
"By default, a 171 kHz single-channel 16-bit MPX signal is expected via\n"
"stdin.\n"
"\n"
"-b, --input-bits Input is an unsynchronized ASCII bit stream\n"
" (011010110...). All characters but '0' and '1'\n"
" are ignored.\n"
"\n"
"-c, --channels CHANS Number of channels in the raw input signal. Each\n"
" channel is demodulated independently.\n"
"\n"
"-e, --feed-through Echo the input signal to stdout and print\n"
" decoded groups to stderr.\n"
"\n"
"-E, --bler Display the average block error rate, or the\n"
" percentage of blocks that had errors before\n"
" error correction. Averaged over the last 12\n"
" groups. For hex input, this is the percentage\n"
" of missing blocks.\n"
"\n"
"-f, --file FILENAME Use an audio file as MPX input. All formats\n"
" readable by libsndfile should work.\n"
"\n"
"-h, --input-hex The input is in the RDS Spy hex format.\n"
"\n"
"-l, --loctable DIR Load TMC location table from a directory in TMC\n"
" Exchange format. This option can be specified\n"
" multiple times to load several location tables.\n"
"\n"
"-p, --show-partial Under noisy conditions, redsea may not be able to\n"
" fully receive all information. Multi-group data\n"
" such as PS names, RadioText, and alternative\n"
" frequencies are especially vulnerable. This option\n"
" makes it display them even if not fully received,\n"
" as partial_{ps,radiotext,alt_kilohertz}.\n"
"\n"
"-r, --samplerate RATE Set stdin sample frequency in Hz. Will resample\n"
" (slow) if this differs from 171000 Hz.\n"
"\n"
"-t, --timestamp FORMAT Add time of decoding to JSON groups; see\n"
" man strftime for formatting options (or\n"
" try \"%c\").\n"
"\n"
"-u, --rbds RBDS mode; use North American program type names\n"
" and \"back-calculate\" the station's call sign from\n"
" its PI code. Note that this calculation gives an\n"
" incorrect call sign for most stations that transmit\n"
" TMC.\n"
"\n"
"-v, --version Print version string and exit.\n"
"\n"
"-x, --output-hex Output hex groups in the RDS Spy format,\n"
" suppressing JSON output.\n";
}
void PrintVersion() {
#ifdef DEBUG
std::cout << PACKAGE_STRING << "-debug by OH2EIQ" << '\n';
#else
std::cout << PACKAGE_STRING << " by OH2EIQ" << '\n';
#endif
}
int ProcessMPXInput(Options options) {
#ifndef HAVE_LIQUID
std::cerr << "error: redsea was compiled without liquid-dsp"
<< '\n';
return EXIT_FAILURE;
#endif
MPXReader mpx;
try {
mpx.init(options);
} catch (BeyondEofError& e) {
PrintUsage();
return EXIT_FAILURE;
}
options.samplerate = mpx.samplerate();
options.num_channels = mpx.num_channels();
if (mpx.error())
return EXIT_FAILURE;
std::vector<Channel> channels;
std::vector<std::unique_ptr<Subcarrier>> subcarriers;
for (int i = 0; i < options.num_channels; i++) {
channels.emplace_back(options, i);
subcarriers.push_back(std::make_unique<Subcarrier>(options));
}
while (!mpx.eof()) {
mpx.FillBuffer();
for (int i = 0; i < options.num_channels; i++) {
channels[i].ProcessBits(
subcarriers[i]->ProcessChunk(
mpx.ReadChunk(i)
)
);
}
}
for (int i = 0; i < options.num_channels; i++)
channels[i].Flush();
return EXIT_SUCCESS;
}
int ProcessASCIIBitsInput(Options options) {
Channel channel(options, 0);
AsciiBitReader ascii_reader(options);
while (!ascii_reader.eof()) {
channel.ProcessBit(ascii_reader.ReadBit());
}
channel.Flush();
return EXIT_SUCCESS;
}
int ProcessHexInput(Options options) {
Channel channel(options, 0);
while (!std::cin.eof()) {
channel.ProcessGroup(ReadHexGroup(options));
}
return EXIT_SUCCESS;
}
} // namespace redsea
int main(int argc, char** argv) {
redsea::Options options = redsea::GetOptions(argc, argv);
if (options.print_usage)
redsea::PrintUsage();
if (options.print_version)
redsea::PrintVersion();
if (options.exit_failure)
return EXIT_FAILURE;
if (options.exit_success)
return EXIT_SUCCESS;
switch (options.input_type) {
case redsea::InputType::MPX_stdin:
case redsea::InputType::MPX_sndfile:
return ProcessMPXInput(options);
break;
case redsea::InputType::ASCIIbits:
return ProcessASCIIBitsInput(options);
break;
case redsea::InputType::Hex:
return ProcessHexInput(options);
break;
}
}
<commit_msg>stdin usage<commit_after>/*
* redsea - RDS decoder
* Copyright (c) Oona Räisänen OH2EIQ (windyoona@gmail.com)
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include <iostream>
#include "config.h"
#include "src/channel.h"
#include "src/common.h"
#include "src/groups.h"
#include "src/options.h"
#include "src/subcarrier.h"
namespace redsea {
void PrintUsage() {
std::cout <<
"radio_command | redsea [OPTIONS]\n"
"redsea [OPTIONS] < raw_signal_file.s16\n"
"\n"
"By default, a 171 kHz single-channel 16-bit MPX signal is expected via\n"
"stdin.\n"
"\n"
"-b, --input-bits Input is an unsynchronized ASCII bit stream\n"
" (011010110...). All characters but '0' and '1'\n"
" are ignored.\n"
"\n"
"-c, --channels CHANS Number of channels in the raw input signal. Each\n"
" channel is demodulated independently.\n"
"\n"
"-e, --feed-through Echo the input signal to stdout and print\n"
" decoded groups to stderr.\n"
"\n"
"-E, --bler Display the average block error rate, or the\n"
" percentage of blocks that had errors before\n"
" error correction. Averaged over the last 12\n"
" groups. For hex input, this is the percentage\n"
" of missing blocks.\n"
"\n"
"-f, --file FILENAME Use an audio file as MPX input. All formats\n"
" readable by libsndfile should work.\n"
"\n"
"-h, --input-hex The input is in the RDS Spy hex format.\n"
"\n"
"-l, --loctable DIR Load TMC location table from a directory in TMC\n"
" Exchange format. This option can be specified\n"
" multiple times to load several location tables.\n"
"\n"
"-p, --show-partial Under noisy conditions, redsea may not be able to\n"
" fully receive all information. Multi-group data\n"
" such as PS names, RadioText, and alternative\n"
" frequencies are especially vulnerable. This option\n"
" makes it display them even if not fully received,\n"
" as partial_{ps,radiotext,alt_kilohertz}.\n"
"\n"
"-r, --samplerate RATE Set stdin sample frequency in Hz. Will resample\n"
" (slow) if this differs from 171000 Hz.\n"
"\n"
"-t, --timestamp FORMAT Add time of decoding to JSON groups; see\n"
" man strftime for formatting options (or\n"
" try \"%c\").\n"
"\n"
"-u, --rbds RBDS mode; use North American program type names\n"
" and \"back-calculate\" the station's call sign from\n"
" its PI code. Note that this calculation gives an\n"
" incorrect call sign for most stations that transmit\n"
" TMC.\n"
"\n"
"-v, --version Print version string and exit.\n"
"\n"
"-x, --output-hex Output hex groups in the RDS Spy format,\n"
" suppressing JSON output.\n";
}
void PrintVersion() {
#ifdef DEBUG
std::cout << PACKAGE_STRING << "-debug by OH2EIQ" << '\n';
#else
std::cout << PACKAGE_STRING << " by OH2EIQ" << '\n';
#endif
}
int ProcessMPXInput(Options options) {
#ifndef HAVE_LIQUID
std::cerr << "error: redsea was compiled without liquid-dsp"
<< '\n';
return EXIT_FAILURE;
#endif
MPXReader mpx;
try {
mpx.init(options);
} catch (BeyondEofError& e) {
PrintUsage();
return EXIT_FAILURE;
}
options.samplerate = mpx.samplerate();
options.num_channels = mpx.num_channels();
if (mpx.error())
return EXIT_FAILURE;
std::vector<Channel> channels;
std::vector<std::unique_ptr<Subcarrier>> subcarriers;
for (int i = 0; i < options.num_channels; i++) {
channels.emplace_back(options, i);
subcarriers.push_back(std::make_unique<Subcarrier>(options));
}
while (!mpx.eof()) {
mpx.FillBuffer();
for (int i = 0; i < options.num_channels; i++) {
channels[i].ProcessBits(
subcarriers[i]->ProcessChunk(
mpx.ReadChunk(i)
)
);
}
}
for (int i = 0; i < options.num_channels; i++)
channels[i].Flush();
return EXIT_SUCCESS;
}
int ProcessASCIIBitsInput(Options options) {
Channel channel(options, 0);
AsciiBitReader ascii_reader(options);
while (!ascii_reader.eof()) {
channel.ProcessBit(ascii_reader.ReadBit());
}
channel.Flush();
return EXIT_SUCCESS;
}
int ProcessHexInput(Options options) {
Channel channel(options, 0);
while (!std::cin.eof()) {
channel.ProcessGroup(ReadHexGroup(options));
}
return EXIT_SUCCESS;
}
} // namespace redsea
int main(int argc, char** argv) {
redsea::Options options = redsea::GetOptions(argc, argv);
if (options.print_usage)
redsea::PrintUsage();
if (options.print_version)
redsea::PrintVersion();
if (options.exit_failure)
return EXIT_FAILURE;
if (options.exit_success)
return EXIT_SUCCESS;
switch (options.input_type) {
case redsea::InputType::MPX_stdin:
case redsea::InputType::MPX_sndfile:
return ProcessMPXInput(options);
break;
case redsea::InputType::ASCIIbits:
return ProcessASCIIBitsInput(options);
break;
case redsea::InputType::Hex:
return ProcessHexInput(options);
break;
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006 - 2010, Paul Beckingham.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
// Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA
// 02110-1301
// USA
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <stdlib.h>
#include "Context.h"
#include "Table.h"
#include "Date.h"
#include "text.h"
#include "util.h"
#include "main.h"
extern Context context;
static std::map <std::string, Color> gsColor;
static std::vector <std::string> gsPrecedence;
////////////////////////////////////////////////////////////////////////////////
void initializeColorRules ()
{
gsColor.clear ();
gsPrecedence.clear ();
// Load all the configuration values, filter to only the ones that begin with
// "color.", then store name/value in gsColor, and name in rules.
std::vector <std::string> rules;
std::vector <std::string> variables;
context.config.all (variables);
foreach (it, variables)
{
if (it->substr (0, 6) == "color.")
{
Color c (context.config.get (*it));
gsColor[*it] = c;
rules.push_back (*it);
}
}
// Load the rule.precedence.color list, split it, then autocomplete against
// the 'rules' vector loaded above.
std::vector <std::string> results;
std::vector <std::string> precedence;
split (precedence, context.config.get ("rule.precedence.color"), ',');
foreach (it, precedence)
{
// Add the leading "color." string.
std::string rule = "color." + *it;
autoComplete (rule, rules, results);
foreach (r, results)
gsPrecedence.push_back (*r);
}
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeBlocked (Task& task, const std::string& rule, Color& c)
{
if (gsColor[rule].nontrivial ())
if (task.get ("depends") != "")
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeTagged (Task& task, const std::string& rule, Color& c)
{
if (gsColor[rule].nontrivial ())
if (task.getTagCount ())
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityL (Task& task, const std::string& rule, Color& c)
{
if (gsColor[rule].nontrivial ())
if (task.get ("priority") == "L")
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityM (Task& task, const std::string& rule, Color& c)
{
if (gsColor[rule].nontrivial ())
if (task.get ("priority") == "M")
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityH (Task& task, const std::string& rule, Color& c)
{
if (gsColor[rule].nontrivial ())
if (task.get ("priority") == "H")
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityNone (Task& task, const std::string& rule, Color& c)
{
if (gsColor[rule].nontrivial ())
if (task.get ("priority") == "")
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeActive (Task& task, const std::string& rule, Color& c)
{
Task::status status = task.getStatus ();
if (gsColor[rule].nontrivial () &&
status != Task::completed &&
status != Task::deleted &&
task.has ("start"))
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeTag (Task& task, const std::string& rule, Color& c)
{
if (task.hasTag (rule.substr (10)))
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeProject (Task& task, const std::string& rule, Color& c)
{
// Observe the case sensitivity setting.
bool sensitive = context.config.getBoolean ("search.case.sensitive");
if (compare (task.get ("project"), rule.substr (14), sensitive))
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeProjectNone (Task& task, const std::string& rule, Color& c)
{
if (task.get ("project") == "")
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeTagNone (Task& task, const std::string& rule, Color& c)
{
if (task.getTagCount () == 0)
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeKeyword (Task& task, const std::string& rule, Color& c)
{
// Observe the case sensitivity setting.
bool sensitive = context.config.getBoolean ("search.case.sensitive");
// The easiest thing to check is the description, because it is just one
// attribute.
if (find (task.get ("description"), rule.substr (14), sensitive) != std::string::npos)
c.blend (gsColor[rule]);
// Failing the description check, look at all annotations, returning on the
// first match.
else
{
Task::iterator it;
for (it = task.begin (); it != task.end (); ++it)
{
if (it->first.substr (0, 11) == "annotation_" &&
find (it->second.value (), rule.substr (14), sensitive) != std::string::npos)
{
c.blend (gsColor[rule]);
return;
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeDue (Task& task, const std::string& rule, Color& c)
{
Task::status status = task.getStatus ();
if (task.has ("due") &&
status != Task::completed &&
status != Task::deleted)
{
if (getDueState (task.get ("due")) == 1)
c.blend (gsColor[rule]);
}
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeDueToday (Task& task, const std::string& rule, Color& c)
{
Task::status status = task.getStatus ();
if (task.has ("due") &&
status != Task::completed &&
status != Task::deleted)
{
if (getDueState (task.get ("due")) == 2)
c.blend (gsColor[rule]);
}
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeOverdue (Task& task, const std::string& rule, Color& c)
{
Task::status status = task.getStatus ();
if (task.has ("due") &&
status != Task::completed &&
status != Task::deleted)
{
if (getDueState (task.get ("due")) == 3)
c.blend (gsColor[rule]);
}
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeRecurring (Task& task, const std::string& rule, Color& c)
{
if (gsColor[rule].nontrivial ())
if (task.has ("recur"))
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
void autoColorize (Task& task, Color& c)
{
// The special tag 'nocolor' overrides all auto and specific colorization.
if (task.hasTag ("nocolor"))
{
c = Color ();
return;
}
// Note: c already contains colors specifically assigned via command.
// Note: These rules form a hierarchy - the last rule is King, hence the
// reverse iterator.
std::vector <std::string>::reverse_iterator r;
for (r = gsPrecedence.rbegin (); r != gsPrecedence.rend (); ++r)
{
if (*r == "color.blocked") colorizeBlocked (task, *r, c);
else if (*r == "color.tagged") colorizeTagged (task, *r, c);
else if (*r == "color.pri.L") colorizePriorityL (task, *r, c);
else if (*r == "color.pri.M") colorizePriorityM (task, *r, c);
else if (*r == "color.pri.H") colorizePriorityH (task, *r, c);
else if (*r == "color.pri.none") colorizePriorityNone (task, *r, c);
else if (*r == "color.active") colorizeActive (task, *r, c);
else if (*r == "color.project.none") colorizeProjectNone (task, *r, c);
else if (*r == "color.tag.none") colorizeTagNone (task, *r, c);
else if (*r == "color.due") colorizeDue (task, *r, c);
else if (*r == "color.due.today") colorizeDueToday (task, *r, c);
else if (*r == "color.overdue") colorizeOverdue (task, *r, c);
else if (*r == "color.recurring") colorizeRecurring (task, *r, c);
// Wildcards
else if (r->substr (0, 9) == "color.tag") colorizeTag (task, *r, c);
else if (r->substr (0, 13) == "color.project") colorizeProject (task, *r, c);
else if (r->substr (0, 13) == "color.keyword") colorizeKeyword (task, *r, c);
}
}
////////////////////////////////////////////////////////////////////////////////
std::string colorizeHeader (const std::string& input)
{
if (gsColor["color.header"].nontrivial ())
return gsColor["color.header"].colorize (input);
return input;
}
////////////////////////////////////////////////////////////////////////////////
std::string colorizeFootnote (const std::string& input)
{
if (gsColor["color.footnote"].nontrivial ())
return gsColor["color.footnote"].colorize (input);
return input;
}
////////////////////////////////////////////////////////////////////////////////
std::string colorizeDebug (const std::string& input)
{
if (gsColor["color.debug"].nontrivial ())
return gsColor["color.debug"].colorize (input);
return input;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Dependencies<commit_after>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006 - 2010, Paul Beckingham.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
// Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA
// 02110-1301
// USA
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <stdlib.h>
#include "Context.h"
#include "Table.h"
#include "Date.h"
#include "text.h"
#include "util.h"
#include "main.h"
extern Context context;
static std::map <std::string, Color> gsColor;
static std::vector <std::string> gsPrecedence;
////////////////////////////////////////////////////////////////////////////////
void initializeColorRules ()
{
gsColor.clear ();
gsPrecedence.clear ();
// Load all the configuration values, filter to only the ones that begin with
// "color.", then store name/value in gsColor, and name in rules.
std::vector <std::string> rules;
std::vector <std::string> variables;
context.config.all (variables);
foreach (it, variables)
{
if (it->substr (0, 6) == "color.")
{
Color c (context.config.get (*it));
gsColor[*it] = c;
rules.push_back (*it);
}
}
// Load the rule.precedence.color list, split it, then autocomplete against
// the 'rules' vector loaded above.
std::vector <std::string> results;
std::vector <std::string> precedence;
split (precedence, context.config.get ("rule.precedence.color"), ',');
foreach (it, precedence)
{
// Add the leading "color." string.
std::string rule = "color." + *it;
autoComplete (rule, rules, results);
foreach (r, results)
gsPrecedence.push_back (*r);
}
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeBlocked (Task& task, const std::string& rule, Color& c)
{
if (gsColor[rule].nontrivial ())
if (dependencyIsBlocked (task))
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeTagged (Task& task, const std::string& rule, Color& c)
{
if (gsColor[rule].nontrivial ())
if (task.getTagCount ())
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityL (Task& task, const std::string& rule, Color& c)
{
if (gsColor[rule].nontrivial ())
if (task.get ("priority") == "L")
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityM (Task& task, const std::string& rule, Color& c)
{
if (gsColor[rule].nontrivial ())
if (task.get ("priority") == "M")
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityH (Task& task, const std::string& rule, Color& c)
{
if (gsColor[rule].nontrivial ())
if (task.get ("priority") == "H")
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityNone (Task& task, const std::string& rule, Color& c)
{
if (gsColor[rule].nontrivial ())
if (task.get ("priority") == "")
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeActive (Task& task, const std::string& rule, Color& c)
{
Task::status status = task.getStatus ();
if (gsColor[rule].nontrivial () &&
status != Task::completed &&
status != Task::deleted &&
task.has ("start"))
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeTag (Task& task, const std::string& rule, Color& c)
{
if (task.hasTag (rule.substr (10)))
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeProject (Task& task, const std::string& rule, Color& c)
{
// Observe the case sensitivity setting.
bool sensitive = context.config.getBoolean ("search.case.sensitive");
if (compare (task.get ("project"), rule.substr (14), sensitive))
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeProjectNone (Task& task, const std::string& rule, Color& c)
{
if (task.get ("project") == "")
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeTagNone (Task& task, const std::string& rule, Color& c)
{
if (task.getTagCount () == 0)
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeKeyword (Task& task, const std::string& rule, Color& c)
{
// Observe the case sensitivity setting.
bool sensitive = context.config.getBoolean ("search.case.sensitive");
// The easiest thing to check is the description, because it is just one
// attribute.
if (find (task.get ("description"), rule.substr (14), sensitive) != std::string::npos)
c.blend (gsColor[rule]);
// Failing the description check, look at all annotations, returning on the
// first match.
else
{
Task::iterator it;
for (it = task.begin (); it != task.end (); ++it)
{
if (it->first.substr (0, 11) == "annotation_" &&
find (it->second.value (), rule.substr (14), sensitive) != std::string::npos)
{
c.blend (gsColor[rule]);
return;
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeDue (Task& task, const std::string& rule, Color& c)
{
Task::status status = task.getStatus ();
if (task.has ("due") &&
status != Task::completed &&
status != Task::deleted)
{
if (getDueState (task.get ("due")) == 1)
c.blend (gsColor[rule]);
}
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeDueToday (Task& task, const std::string& rule, Color& c)
{
Task::status status = task.getStatus ();
if (task.has ("due") &&
status != Task::completed &&
status != Task::deleted)
{
if (getDueState (task.get ("due")) == 2)
c.blend (gsColor[rule]);
}
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeOverdue (Task& task, const std::string& rule, Color& c)
{
Task::status status = task.getStatus ();
if (task.has ("due") &&
status != Task::completed &&
status != Task::deleted)
{
if (getDueState (task.get ("due")) == 3)
c.blend (gsColor[rule]);
}
}
////////////////////////////////////////////////////////////////////////////////
static void colorizeRecurring (Task& task, const std::string& rule, Color& c)
{
if (gsColor[rule].nontrivial ())
if (task.has ("recur"))
c.blend (gsColor[rule]);
}
////////////////////////////////////////////////////////////////////////////////
void autoColorize (Task& task, Color& c)
{
// The special tag 'nocolor' overrides all auto and specific colorization.
if (task.hasTag ("nocolor"))
{
c = Color ();
return;
}
// Note: c already contains colors specifically assigned via command.
// Note: These rules form a hierarchy - the last rule is King, hence the
// reverse iterator.
std::vector <std::string>::reverse_iterator r;
for (r = gsPrecedence.rbegin (); r != gsPrecedence.rend (); ++r)
{
if (*r == "color.blocked") colorizeBlocked (task, *r, c);
else if (*r == "color.tagged") colorizeTagged (task, *r, c);
else if (*r == "color.pri.L") colorizePriorityL (task, *r, c);
else if (*r == "color.pri.M") colorizePriorityM (task, *r, c);
else if (*r == "color.pri.H") colorizePriorityH (task, *r, c);
else if (*r == "color.pri.none") colorizePriorityNone (task, *r, c);
else if (*r == "color.active") colorizeActive (task, *r, c);
else if (*r == "color.project.none") colorizeProjectNone (task, *r, c);
else if (*r == "color.tag.none") colorizeTagNone (task, *r, c);
else if (*r == "color.due") colorizeDue (task, *r, c);
else if (*r == "color.due.today") colorizeDueToday (task, *r, c);
else if (*r == "color.overdue") colorizeOverdue (task, *r, c);
else if (*r == "color.recurring") colorizeRecurring (task, *r, c);
// Wildcards
else if (r->substr (0, 9) == "color.tag") colorizeTag (task, *r, c);
else if (r->substr (0, 13) == "color.project") colorizeProject (task, *r, c);
else if (r->substr (0, 13) == "color.keyword") colorizeKeyword (task, *r, c);
}
}
////////////////////////////////////////////////////////////////////////////////
std::string colorizeHeader (const std::string& input)
{
if (gsColor["color.header"].nontrivial ())
return gsColor["color.header"].colorize (input);
return input;
}
////////////////////////////////////////////////////////////////////////////////
std::string colorizeFootnote (const std::string& input)
{
if (gsColor["color.footnote"].nontrivial ())
return gsColor["color.footnote"].colorize (input);
return input;
}
////////////////////////////////////////////////////////////////////////////////
std::string colorizeDebug (const std::string& input)
{
if (gsColor["color.debug"].nontrivial ())
return gsColor["color.debug"].colorize (input);
return input;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#include "../include/scene.hpp"
////////////////////////////////////////////////////////////////////////////////
scene::scene(const uint screen_w, const uint screen_h, const uint map_size, const double tiles_separation, const double map_separation):
tile_map_(map_size, tiles_separation),
map_separation_(map_separation),
screen_w_(screen_w),
screen_h_(screen_h),
map_size_(map_size),
inc_x_(0),
inc_y_(0)
{}
////////////////////////////////////////////////////////////////////////////////
scene::~scene()
{}
////////////////////////////////////////////////////////////////////////////////
void scene::generate(const uint rivers, const uint min_size_river, const bool accumulative_rivers)
{
tile_map_.generate(rivers,min_size_river,accumulative_rivers);
}
////////////////////////////////////////////////////////////////////////////////
void scene::draw() const
{
std::vector<ALLEGRO_VERTEX> vertices;
double cx = screen_w_/2 + inc_x_;
double cy = screen_h_/2 + inc_y_;
// GET VERTICES
tile_map_.appendVertices(vertices, cx, cy, (screen_w_>screen_h_ ? screen_h_ : screen_w_)*(1.0-map_separation_), screen_w_, screen_h_);
// CLEAR & LOCK
al_clear_to_color(BACKGROUND_COLOR);
al_lock_bitmap(al_get_target_bitmap(), ALLEGRO_PIXEL_FORMAT_ANY, ALLEGRO_LOCK_READWRITE );
// DRAW
al_draw_prim(vertices.data(), nullptr, nullptr, 0, vertices.size(), ALLEGRO_PRIM_TRIANGLE_LIST);
// UNLOCK
al_unlock_bitmap(al_get_target_bitmap());
// TEXT & DEBG
al_draw_text(caviar_font_16, BLACK, 10, 40,ALLEGRO_ALIGN_LEFT, ("Triangles: "+std::to_string(vertices.size()/3)).c_str());
displayFPS(caviar_font_16);
}
////////////////////////////////////////////////////////////////////////////////
void scene::moveX(const double x)
{
inc_x_ += x;
}
////////////////////////////////////////////////////////////////////////////////
void scene::moveY(const double y)
{
inc_y_ += y;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Testing<commit_after>#include "../include/scene.hpp"
////////////////////////////////////////////////////////////////////////////////
scene::scene(const uint screen_w, const uint screen_h, const uint map_size, const double tiles_separation, const double map_separation):
tile_map_(map_size, tiles_separation),
map_separation_(map_separation),
screen_w_(screen_w),
screen_h_(screen_h),
map_size_(map_size),
inc_x_(0),
inc_y_(0)
{}
////////////////////////////////////////////////////////////////////////////////
scene::~scene()
{}
////////////////////////////////////////////////////////////////////////////////
void scene::generate(const uint rivers, const uint min_size_river, const bool accumulative_rivers)
{
tile_map_.generate(rivers,min_size_river,accumulative_rivers);
}
////////////////////////////////////////////////////////////////////////////////
void scene::draw() const
{
std::vector<ALLEGRO_VERTEX> vertices;
double cx = screen_w_/2 + inc_x_;
double cy = screen_h_/2 + inc_y_;
// GET VERTICES
tile_map_.appendVertices(vertices, cx, cy, (screen_w_>screen_h_ ? screen_h_ : screen_w_)*(1.0-map_separation_), screen_w_, screen_h_);
// CLEAR & LOCK
al_clear_to_color(BACKGROUND_COLOR);
al_lock_bitmap(al_get_target_bitmap(), ALLEGRO_PIXEL_FORMAT_ANY, ALLEGRO_LOCK_READWRITE );
// DRAW
al_draw_prim(vertices.data(), nullptr, nullptr, 0, vertices.size(), ALLEGRO_PRIM_TRIANGLE_LIST);
// UNLOCK
al_unlock_bitmap(al_get_target_bitmap());
// TEXT & DEBG
al_draw_text(caviar_font_16, BLACK, 10, 40,ALLEGRO_ALIGN_LEFT, ("Triangles: "+std::to_string(vertices.size()/3)).c_str());
displayFPS(caviar_font_16);
// THIS IS A TEST
}
////////////////////////////////////////////////////////////////////////////////
void scene::moveX(const double x)
{
inc_x_ += x;
}
////////////////////////////////////////////////////////////////////////////////
void scene::moveY(const double y)
{
inc_y_ += y;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#include <algorithm>
#include "timer.h"
double NS_TO_SEC = 1e9;
#ifdef __COMPILE_AS_LINUX__
#define CLOCK_TYPE CLOCK_MONOTONIC //CLOCK_PROCESS_CPUTIME_ID
#endif // ifdef __COMPILE_AS_LINUX__
Timer::Timer() {
reset();
#ifdef __COMPILE_AS_WINDOWS__
get_clock_frequency();
#endif
}
double Timer::now() {
double ret = 0.0;
#ifdef __COMPILE_AS_WINDOWS__
LARGE_INTEGER freq;
LARGE_INTEGER now;
if (!freq.QuadPart) {
QueryPerformanceFrequency(&freq);
}
QueryPerformanceCounter(&now);
ret = (now.QuadPart * NS_TO_SEC) / (double)freq.QuadPart;
#elif defined (__COMPILE_AS_LINUX__)
timespec now;
clock_gettime(CLOCK_TYPE, &now);
ret = (NS_TO_SEC * now.tv_sec) + now.tv_nsec;
#endif
return ret;
}
void Timer::start() {
#ifdef __COMPILE_AS_WINDOWS__
get_clock_frequency();
QueryPerformanceCounter(&start_);
#elif defined (__COMPILE_AS_LINUX__)
clock_gettime(CLOCK_TYPE, &start_);
#endif
}
void Timer::stop() {
#ifdef __COMPILE_AS_WINDOWS__
QueryPerformanceCounter(&end_);
#elif defined (__COMPILE_AS_LINUX__)
clock_gettime(CLOCK_TYPE, &end_);
#endif
}
double Timer::get_elapsed_ns() {
#ifdef __COMPILE_AS_WINDOWS__
return ((end_.QuadPart - start_.QuadPart) * NS_TO_SEC) / (double)freq_.QuadPart;
#elif defined (__COMPILE_AS_LINUX__)
timespec tmp = diff(start_, end_);
return (NS_TO_SEC * tmp.tv_sec) + tmp.tv_nsec;
#endif
}
#ifdef __COMPILE_AS_LINUX__
timespec Timer::diff(timespec start, timespec end) {
timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0) {
temp.tv_sec = end.tv_sec - start.tv_sec - 1;
temp.tv_nsec = NS_TO_SEC + end.tv_nsec - start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec - start.tv_sec;
temp.tv_nsec = end.tv_nsec - start.tv_nsec;
}
return temp;
}
#endif
#ifdef __COMPILE_AS_WINDOWS__
int64_t Timer::get_clock_frequency() {
if (!freq_.QuadPart) {
QueryPerformanceFrequency(&freq_);
}
return freq_.QuadPart;
}
#endif
void Timer::reset() {
#ifdef __COMPILE_AS_WINDOWS__
freq_ = start_ = end_ = LARGE_INTEGER();
#elif defined (__COMPILE_AS_LINUX__)
start_.tv_sec = end_.tv_sec = 0;
start_.tv_nsec = end_.tv_nsec = 0;
#endif
}
WindowTimer::WindowTimer(uint8_t window_size) : iterator_(0) {
window_size_ = std::max(window_size, (uint8_t)1);
window_.reserve(window_size_);
for (uint8_t i = 0; i < window_size_; ++i) {
window_.push_back(0);
}
reset();
}
// Starts the timer.
void WindowTimer::start() {
timer_.start();
}
// Starts the timer.
void WindowTimer::step() {
window_[iterator_++] = get_elapsed_ns();
iterator_ = iterator_ % window_size_;
}
// Stops the timer.
void WindowTimer::stop() {
timer_.stop();
}
// Stops and resets the timer.
void WindowTimer::reset() {
timer_.reset();
for (uint8_t i = 0; i < window_size_; ++i) {
window_[i] = 0;
}
}
// Gets the average elapsed time in [ns] since start.
double WindowTimer::get_elapsed_ns() {
return timer_.get_elapsed_ns();
}
// Gets the average elapsed time in [ns] since start.
double WindowTimer::get_avg_elapsed_ns() {
double accum = 0;
for (auto& n : window_) {
accum += n;
}
return accum / window_size_;
}
<commit_msg>Updated Timer to be Windows compatible<commit_after>#include <algorithm>
#include "timer.h"
double NS_TO_SEC = 1e9;
#ifdef __COMPILE_AS_LINUX__
#define CLOCK_TYPE CLOCK_MONOTONIC //CLOCK_PROCESS_CPUTIME_ID
#endif // ifdef __COMPILE_AS_LINUX__
Timer::Timer() {
reset();
#ifdef __COMPILE_AS_WINDOWS__
get_clock_frequency();
#endif
}
double Timer::now() {
double ret = 0.0;
#ifdef __COMPILE_AS_WINDOWS__
static LARGE_INTEGER freq = { 0, 0 };
LARGE_INTEGER now;
if (!freq.QuadPart) {
QueryPerformanceFrequency(&freq);
}
QueryPerformanceCounter(&now);
ret = (now.QuadPart * NS_TO_SEC) / (double)freq.QuadPart;
#elif defined (__COMPILE_AS_LINUX__)
timespec now;
clock_gettime(CLOCK_TYPE, &now);
ret = (NS_TO_SEC * now.tv_sec) + now.tv_nsec;
#endif
return ret;
}
void Timer::start() {
#ifdef __COMPILE_AS_WINDOWS__
get_clock_frequency();
QueryPerformanceCounter(&start_);
#elif defined (__COMPILE_AS_LINUX__)
clock_gettime(CLOCK_TYPE, &start_);
#endif
}
void Timer::stop() {
#ifdef __COMPILE_AS_WINDOWS__
QueryPerformanceCounter(&end_);
#elif defined (__COMPILE_AS_LINUX__)
clock_gettime(CLOCK_TYPE, &end_);
#endif
}
double Timer::get_elapsed_ns() {
#ifdef __COMPILE_AS_WINDOWS__
return ((end_.QuadPart - start_.QuadPart) * NS_TO_SEC) / (double)freq_.QuadPart;
#elif defined (__COMPILE_AS_LINUX__)
timespec tmp = diff(start_, end_);
return (NS_TO_SEC * tmp.tv_sec) + tmp.tv_nsec;
#endif
}
#ifdef __COMPILE_AS_LINUX__
timespec Timer::diff(timespec start, timespec end) {
timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0) {
temp.tv_sec = end.tv_sec - start.tv_sec - 1;
temp.tv_nsec = NS_TO_SEC + end.tv_nsec - start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec - start.tv_sec;
temp.tv_nsec = end.tv_nsec - start.tv_nsec;
}
return temp;
}
#endif
#ifdef __COMPILE_AS_WINDOWS__
int64_t Timer::get_clock_frequency() {
if (!freq_.QuadPart) {
QueryPerformanceFrequency(&freq_);
}
return freq_.QuadPart;
}
#endif
void Timer::reset() {
#ifdef __COMPILE_AS_WINDOWS__
freq_ = start_ = end_ = LARGE_INTEGER();
#elif defined (__COMPILE_AS_LINUX__)
start_.tv_sec = end_.tv_sec = 0;
start_.tv_nsec = end_.tv_nsec = 0;
#endif
}
WindowTimer::WindowTimer(uint8_t window_size) : iterator_(0) {
window_size_ = std::max(window_size, (uint8_t)1);
window_.reserve(window_size_);
for (uint8_t i = 0; i < window_size_; ++i) {
window_.push_back(0);
}
reset();
}
// Starts the timer.
void WindowTimer::start() {
timer_.start();
}
// Starts the timer.
void WindowTimer::step() {
window_[iterator_++] = (int64_t)get_elapsed_ns();
iterator_ = iterator_ % window_size_;
}
// Stops the timer.
void WindowTimer::stop() {
timer_.stop();
}
// Stops and resets the timer.
void WindowTimer::reset() {
timer_.reset();
for (uint8_t i = 0; i < window_size_; ++i) {
window_[i] = 0;
}
}
// Gets the average elapsed time in [ns] since start.
double WindowTimer::get_elapsed_ns() {
return timer_.get_elapsed_ns();
}
// Gets the average elapsed time in [ns] since start.
double WindowTimer::get_avg_elapsed_ns() {
double accum = 0;
for (auto& n : window_) {
accum += n;
}
return accum / window_size_;
}
<|endoftext|> |
<commit_before>#pragma once
enum TokenType {
// Symbols //////
NUL, // Reserved
WHITESPACE, // Spaces or tabs
INDENT, // Spaces or tabs
DEDENT, // Spaces or tabs
NEWLINE, // /n
LEFT_BRACKET, // {
RIGHT_BRACKET, // }
LEFT_SQUARE, // [
RIGHT_SQUARE, // ]
LEFT_PAREN, // (
RIGHT_PAREN, // )
ARROW, // ->
COMMA, // ,
DOT, // .
TRIPLE_DOT // ...
COLON, // :
DOUBLE_COLON, // ::
LEFT_CARROT, // <
RIGHT_CARROT, // >
SINGLE_QUOTE, // '
DOUBLE_QUOTE, // "
TD_QUOTE, // """
// User defined stuff //
IDENTIFIER, // foo in foo(->):
LIT_INT, // 3
LIT_FLOAT, // 3.14159
LIT_STRING, // "FOO BAR!"
// Keywords
KEY_ABOUT, // about
KEY_CALL, // call
KEY_CASE, // case
KEY_DEFINE, // define
KEY_DO, // do
KEY_DOCS, // docs
KEY_ELIF, // elif
KEY_ELSE, // else
KEY_IF, // if
KEY_INSTANCE, // instance
KEY_INTRIN, // intrinsic
KEY_JUMP, // jump
KEY_LEFT, // left
KEY_MATCH, // match
KEY_OP, // operator
KEY_PERM, // permission
KEY_RET, // return
KEY_RIGHT // right
KEY_SYNONYM // synonym
KEY_TRAIT, // trait
KEY_TYPE, // type
KEY_VOCAB, // vocab
KEY_WITH // with
};
<commit_msg>More tokens fixed<commit_after>#pragma once
enum TokenType {
// Symbols //
NUL, // Reserved
WHITESPACE, // Spaces or tabs
INDENT, // Spaces or tabs
DEDENT, // Spaces or tabs
NEWLINE, // /n
LEFT_BRACKET, // {
RIGHT_BRACKET, // }
LEFT_SQUARE, // [
RIGHT_SQUARE, // ]
LEFT_PAREN, // (
RIGHT_PAREN, // )
ARROW, // ->
COMMA, // ,
DOT, // .
TRIPLE_DOT, // ...
COLON, // :
DOUBLE_COLON, // ::
LEFT_CARROT, // <
RIGHT_CARROT, // >
SINGLE_QUOTE, // '
DOUBLE_QUOTE, // "
TD_QUOTE, // """
// User defined stuff //
IDENTIFIER, // foo in foo(->):
LIT_INT, // 3
LIT_FLOAT, // 3.14159
LIT_STRING, // "FOO BAR!"
// Keywords //
KEY_ABOUT, // about
KEY_CALL, // call
KEY_CASE, // case
KEY_DEFINE, // define
KEY_DO, // do
KEY_DOCS, // docs
KEY_ELIF, // elif
KEY_ELSE, // else
KEY_IF, // if
KEY_INSTANCE, // instance
KEY_INTRIN, // intrinsic
KEY_JUMP, // jump
KEY_LEFT, // left
KEY_MATCH, // match
KEY_OP, // operator
KEY_PERM, // permission
KEY_RET, // return
KEY_RIGHT // right
KEY_SYNONYM // synonym
KEY_TRAIT, // trait
KEY_TYPE, // type
KEY_VOCAB, // vocab
KEY_WITH // with
};
<|endoftext|> |
<commit_before>// This file is part of the pd::ssl library.
// Copyright (C) 2011-2014, Eugene Mamchits <mamchits@yandex-team.ru>.
// Copyright (C) 2011-2014, YANDEX LLC.
// This library may be distributed under the terms of the GNU LGPL 2.1.
// See the file ‘COPYING’ or ‘http://www.gnu.org/licenses/lgpl-2.1.html’.
#include "ssl.H"
#include "log.I"
#include <pd/bq/bq_cont.H>
#include <pd/base/exception.H>
#include <pd/base/string_file.H>
#include <pthread.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/engine.h>
namespace pd {
namespace {
struct mgr_t {
static unsigned types;
static pthread_rwlock_t *locks;
static void lock_func(int mode, int type, const char *, int) {
if((unsigned)type > types)
return;
pthread_rwlock_t *lock = &locks[type];
if(mode & CRYPTO_LOCK) {
if(mode & CRYPTO_READ)
pthread_rwlock_rdlock(lock);
else
pthread_rwlock_wrlock(lock);
}
else
pthread_rwlock_unlock(lock);
}
static unsigned long id_func(void) {
return (unsigned long)bq_cont_current ?: (unsigned long)pthread_self();
}
inline mgr_t() throw() {
SSL_library_init();
SSL_load_error_strings();
ENGINE_load_builtin_engines();
OpenSSL_add_all_algorithms();
types = CRYPTO_num_locks();
locks = (pthread_rwlock_t *)malloc(types * sizeof(pthread_rwlock_t));
for(unsigned i = 0; i < types; ++i)
pthread_rwlock_init(&locks[i], NULL);
CRYPTO_set_locking_callback(&lock_func);
CRYPTO_set_id_callback(&id_func);
}
inline ~mgr_t() throw() {
CRYPTO_set_id_callback(NULL);
CRYPTO_set_locking_callback(NULL);
for(unsigned i = 0; i < types; ++i)
pthread_rwlock_destroy(&locks[i]);
free(locks);
locks = NULL;
types = 0;
}
};
unsigned mgr_t::types = 0;
pthread_rwlock_t *mgr_t::locks = NULL;
static mgr_t const mgr;
class bio_t {
BIO *val;
public:
inline bio_t(string_t const &buf) :
val(BIO_new_mem_buf((void *)buf.ptr(), buf.size())) {
if(!val) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "BIO_new_mem_buf");
}
}
inline ~bio_t() throw() {
BIO_free(val);
}
inline operator BIO *() { return val; }
};
} // namespace
ssl_auth_t::ssl_auth_t(
string_t const &key_fname, string_t const &cert_fname
) : key(), cert() {
if(key_fname)
key = string_file(key_fname.str());
if(cert_fname)
cert = string_file(cert_fname.str());
}
ssl_auth_t::~ssl_auth_t() throw() { }
ssl_ctx_t::ssl_ctx_t(
mode_t _mode, ssl_auth_t const *auth, string_t const &ciphers
) : internal(NULL) {
SSL_CTX *ctx = SSL_CTX_new(
_mode == client ? SSLv23_client_method() : SSLv23_server_method()
);
if(!ctx) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "SSL_CTX_new");
}
if(auth) {
try {
if(auth->cert) {
bio_t cert_bio(auth->cert);
X509 *x = PEM_read_bio_X509_AUX(cert_bio, NULL, NULL, NULL);
if(!x) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "cert, PEM_read_bio_X509");
}
if(SSL_CTX_use_certificate(ctx, x) <= 0) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "SSL_CTX_use_certificate");
}
X509_free(x);
while(!BIO_eof(cert_bio)) {
x = PEM_read_bio_X509(cert_bio, NULL, NULL, NULL);
if(!x) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "cert_chain, PEM_read_bio_X509");
}
if(SSL_CTX_add_extra_chain_cert(ctx, x) <= 0) {
X509_free(x);
log_openssl_error(log::error);
throw exception_log_t(log::error, "SSL_CTX_add_extra_chain_cert");
}
// X509_free(x); // ????
}
}
if(auth->key) {
bio_t key_bio(auth->key);
EVP_PKEY *pkey = PEM_read_bio_PrivateKey(key_bio, NULL, NULL, NULL);
if(!pkey) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "PEM_read_bio_PrivateKey");
}
if(SSL_CTX_use_PrivateKey(ctx, pkey) <= 0) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "SSL_CTX_use_PrivateKey");
}
EVP_PKEY_free(pkey);
}
if(_mode == server) {
SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
SSL_CTX_set_options(ctx, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
SSL_CTX_set_options(ctx, SSL_OP_TLS_ROLLBACK_BUG);
SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
/*
SSL_CTX_set_session_cache_mode(ctx, ...);
SSL_CTX_set_timeout(ctx, ...);
*/
}
/*
SSL_CTX_set_default_verify_paths(ctx);
SSL_CTX_load_verify_locations(ctx, NULL, "/etc/ssl/certs");
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
*/
}
catch(...) {
SSL_CTX_free(ctx);
throw;
}
}
if(ciphers) {
MKCSTR(_ciphers, ciphers);
if(SSL_CTX_set_cipher_list(ctx, _ciphers) <= 0) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "SSL_CTX_set_cipher_list");
}
}
internal = ctx;
}
ssl_ctx_t::~ssl_ctx_t() throw() {
SSL_CTX_free((SSL_CTX *)internal);
}
} // namespace pd
<commit_msg>Initialize OpenSSL library in a way to read config-file.<commit_after>// This file is part of the pd::ssl library.
// Copyright (C) 2011-2014, Eugene Mamchits <mamchits@yandex-team.ru>.
// Copyright (C) 2011-2014, YANDEX LLC.
// This library may be distributed under the terms of the GNU LGPL 2.1.
// See the file ‘COPYING’ or ‘http://www.gnu.org/licenses/lgpl-2.1.html’.
#include "ssl.H"
#include "log.I"
#include <pd/bq/bq_cont.H>
#include <pd/base/exception.H>
#include <pd/base/string_file.H>
#include <pthread.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/engine.h>
#include <openssl/conf.h>
namespace pd {
namespace {
struct mgr_t {
static unsigned types;
static pthread_rwlock_t *locks;
static void lock_func(int mode, int type, const char *, int) {
if((unsigned)type > types)
return;
pthread_rwlock_t *lock = &locks[type];
if(mode & CRYPTO_LOCK) {
if(mode & CRYPTO_READ)
pthread_rwlock_rdlock(lock);
else
pthread_rwlock_wrlock(lock);
}
else
pthread_rwlock_unlock(lock);
}
static unsigned long id_func(void) {
return (unsigned long)bq_cont_current ?: (unsigned long)pthread_self();
}
inline mgr_t() throw() {
OPENSSL_load_builtin_modules();
ENGINE_load_builtin_engines();
ERR_clear_error();
if (CONF_modules_load_file(NULL, NULL, CONF_MFLAGS_DEFAULT_SECTION |
CONF_MFLAGS_IGNORE_MISSING_FILE) <= 0) {
fprintf(stderr, "FATAL: error loading configuration file\n");
ERR_print_errors_fp(stderr);
exit(1);
}
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
types = CRYPTO_num_locks();
locks = (pthread_rwlock_t *)malloc(types * sizeof(pthread_rwlock_t));
for(unsigned i = 0; i < types; ++i)
pthread_rwlock_init(&locks[i], NULL);
CRYPTO_set_locking_callback(&lock_func);
CRYPTO_set_id_callback(&id_func);
}
inline ~mgr_t() throw() {
CRYPTO_set_id_callback(NULL);
CRYPTO_set_locking_callback(NULL);
for(unsigned i = 0; i < types; ++i)
pthread_rwlock_destroy(&locks[i]);
free(locks);
locks = NULL;
types = 0;
}
};
unsigned mgr_t::types = 0;
pthread_rwlock_t *mgr_t::locks = NULL;
static mgr_t const mgr;
class bio_t {
BIO *val;
public:
inline bio_t(string_t const &buf) :
val(BIO_new_mem_buf((void *)buf.ptr(), buf.size())) {
if(!val) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "BIO_new_mem_buf");
}
}
inline ~bio_t() throw() {
BIO_free(val);
}
inline operator BIO *() { return val; }
};
} // namespace
ssl_auth_t::ssl_auth_t(
string_t const &key_fname, string_t const &cert_fname
) : key(), cert() {
if(key_fname)
key = string_file(key_fname.str());
if(cert_fname)
cert = string_file(cert_fname.str());
}
ssl_auth_t::~ssl_auth_t() throw() { }
ssl_ctx_t::ssl_ctx_t(
mode_t _mode, ssl_auth_t const *auth, string_t const &ciphers
) : internal(NULL) {
SSL_CTX *ctx = SSL_CTX_new(
_mode == client ? SSLv23_client_method() : SSLv23_server_method()
);
if(!ctx) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "SSL_CTX_new");
}
if(auth) {
try {
if(auth->cert) {
bio_t cert_bio(auth->cert);
X509 *x = PEM_read_bio_X509_AUX(cert_bio, NULL, NULL, NULL);
if(!x) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "cert, PEM_read_bio_X509");
}
if(SSL_CTX_use_certificate(ctx, x) <= 0) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "SSL_CTX_use_certificate");
}
X509_free(x);
while(!BIO_eof(cert_bio)) {
x = PEM_read_bio_X509(cert_bio, NULL, NULL, NULL);
if(!x) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "cert_chain, PEM_read_bio_X509");
}
if(SSL_CTX_add_extra_chain_cert(ctx, x) <= 0) {
X509_free(x);
log_openssl_error(log::error);
throw exception_log_t(log::error, "SSL_CTX_add_extra_chain_cert");
}
// X509_free(x); // ????
}
}
if(auth->key) {
bio_t key_bio(auth->key);
EVP_PKEY *pkey = PEM_read_bio_PrivateKey(key_bio, NULL, NULL, NULL);
if(!pkey) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "PEM_read_bio_PrivateKey");
}
if(SSL_CTX_use_PrivateKey(ctx, pkey) <= 0) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "SSL_CTX_use_PrivateKey");
}
EVP_PKEY_free(pkey);
}
if(_mode == server) {
SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
SSL_CTX_set_options(ctx, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
SSL_CTX_set_options(ctx, SSL_OP_TLS_ROLLBACK_BUG);
SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
/*
SSL_CTX_set_session_cache_mode(ctx, ...);
SSL_CTX_set_timeout(ctx, ...);
*/
}
/*
SSL_CTX_set_default_verify_paths(ctx);
SSL_CTX_load_verify_locations(ctx, NULL, "/etc/ssl/certs");
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
*/
}
catch(...) {
SSL_CTX_free(ctx);
throw;
}
}
if(ciphers) {
MKCSTR(_ciphers, ciphers);
if(SSL_CTX_set_cipher_list(ctx, _ciphers) <= 0) {
log_openssl_error(log::error);
throw exception_log_t(log::error, "SSL_CTX_set_cipher_list");
}
}
internal = ctx;
}
ssl_ctx_t::~ssl_ctx_t() throw() {
SSL_CTX_free((SSL_CTX *)internal);
}
} // namespace pd
<|endoftext|> |
<commit_before>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
// Disable "'this': used in base member initializer list"
#ifdef _MSC_VER
# pragma warning( push )
# pragma warning(disable: 4355)
#endif
#include <vector>
#include <map>
#include <boost/make_shared.hpp>
#include <qi/anyobject.hpp>
#include <qi/future.hpp>
#include "transportserver.hpp"
#include "messagesocket.hpp"
#include "servicedirectory.hpp"
#include <qi/session.hpp>
#include <qi/messaging/serviceinfo.hpp>
#include <qi/type/objecttypebuilder.hpp>
#include "session_p.hpp"
#include <qi/os.hpp>
#include <qi/log.hpp>
#include <qi/url.hpp>
#include "servicedirectory_p.hpp"
#include "server.hpp"
#include <boost/algorithm/string.hpp>
qiLogCategory("qimessaging.servicedirectory");
namespace qi
{
qi::AnyObject createSDP(ServiceDirectory* self) {
static qi::ObjectTypeBuilder<ServiceDirectory>* ob = nullptr;
static boost::mutex* mutex = nullptr;
QI_THREADSAFE_NEW(mutex);
boost::mutex::scoped_lock lock(*mutex);
if (!ob)
{
ob = new qi::ObjectTypeBuilder<ServiceDirectory>();
ob->setThreadingModel(ObjectThreadingModel_MultiThread);
unsigned int id = 0;
id = ob->advertiseMethod("service", &ServiceDirectory::service);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_Service);
id = ob->advertiseMethod("services", &ServiceDirectory::services);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_Services);
id = ob->advertiseMethod("registerService", &ServiceDirectory::registerService);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_RegisterService);
id = ob->advertiseMethod("unregisterService", &ServiceDirectory::unregisterService);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_UnregisterService);
id = ob->advertiseMethod("serviceReady", &ServiceDirectory::serviceReady);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_ServiceReady);
id = ob->advertiseMethod("updateServiceInfo", &ServiceDirectory::updateServiceInfo);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_UpdateServiceInfo);
id = ob->advertiseSignal("serviceAdded", &ServiceDirectory::serviceAdded);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_ServiceAdded);
id = ob->advertiseSignal("serviceRemoved", &ServiceDirectory::serviceRemoved);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_ServiceRemoved);
id = ob->advertiseMethod("machineId", &ServiceDirectory::machineId);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_MachineId);
ob->advertiseMethod("_socketOfService", &ServiceDirectory::_socketOfService);
// used locally only, we do not export its id
// Silence compile warning unused id
(void)id;
}
return ob->object(self);
}
ServiceDirectory::ServiceDirectory()
: servicesCount(0)
{
}
ServiceDirectory::~ServiceDirectory()
{
if (!connectedServices.empty())
qiLogWarning() << "Destroying while connected services remain";
}
void ServiceDirectory::onSocketDisconnected(MessageSocketPtr socket, std::string error)
{
boost::recursive_mutex::scoped_lock lock(mutex);
// clean from idxToSocket
for (std::map<unsigned int, MessageSocketPtr>::iterator it = idxToSocket.begin(), iend = idxToSocket.end(); it != iend;)
{
std::map<unsigned int, MessageSocketPtr>::iterator next = it;
++next;
if (it->second == socket)
idxToSocket.erase(it);
it = next;
}
// if services were connected behind the socket
std::map<MessageSocketPtr, std::vector<unsigned int> >::iterator it;
it = socketToIdx.find(socket);
if (it == socketToIdx.end()) {
return;
}
// Copy the vector, iterators will be invalidated.
std::vector<unsigned int> ids = it->second;
// Always start at the beginning since we erase elements on unregisterService
// and mess up the iterator
for (std::vector<unsigned int>::iterator it2 = ids.begin();
it2 != ids.end();
++it2)
{
qiLogInfo() << "Service #" << *it2 << " disconnected";
try {
unregisterService(*it2);
} catch (std::runtime_error &) {
qiLogWarning() << "Cannot unregister service #" << *it2;
}
}
socketToIdx.erase(it);
}
std::vector<ServiceInfo> ServiceDirectory::services()
{
boost::recursive_mutex::scoped_lock lock(mutex);
std::vector<ServiceInfo> result;
std::map<unsigned int, ServiceInfo>::const_iterator it;
for (it = connectedServices.begin(); it != connectedServices.end(); ++it)
result.push_back(it->second);
return result;
}
ServiceInfo ServiceDirectory::service(const std::string &name)
{
boost::recursive_mutex::scoped_lock lock(mutex);
std::map<unsigned int, ServiceInfo>::const_iterator servicesIt;
std::map<std::string, unsigned int>::const_iterator it;
it = nameToIdx.find(name);
if (it == nameToIdx.end()) {
std::stringstream ss;
ss << "Cannot find service '" << name << "' in index";
throw std::runtime_error(ss.str());
}
unsigned int idx = it->second;
servicesIt = connectedServices.find(idx);
if (servicesIt == connectedServices.end()) {
std::stringstream ss;
ss << "Cannot find ServiceInfo for service '" << name << "'";
throw std::runtime_error(ss.str());
}
return servicesIt->second;
}
unsigned int ServiceDirectory::registerService(const ServiceInfo &svcinfo)
{
boost::shared_ptr<ServiceBoundObject> sbo = serviceBoundObject.lock();
if (!sbo)
throw std::runtime_error("ServiceBoundObject has expired.");
MessageSocketPtr socket = sbo->currentSocket();
boost::recursive_mutex::scoped_lock lock(mutex);
std::map<std::string, unsigned int>::iterator it;
it = nameToIdx.find(svcinfo.name());
if (it != nameToIdx.end())
{
std::stringstream ss;
ss << "Service \"" <<
svcinfo.name() <<
"\" (#" << it->second << ") is already registered. " <<
"Rejecting conflicting registration attempt.";
qiLogWarning() << ss.str();
throw std::runtime_error(ss.str());
}
unsigned int idx = ++servicesCount;
nameToIdx[svcinfo.name()] = idx;
// Do not add serviceDirectory on the map (socket() == null)
if (idx != qi::Message::Service_ServiceDirectory)
socketToIdx[socket].push_back(idx);
pendingServices[idx] = svcinfo;
pendingServices[idx].setServiceId(idx);
idxToSocket[idx] = socket;
std::stringstream ss;
ss << "Registered Service \"" << svcinfo.name() << "\" (#" << idx << ")";
if (! svcinfo.name().empty() && svcinfo.name()[0] == '_') {
// Hide services whose name starts with an underscore
qiLogDebug() << ss.str();
}
else
{
qiLogInfo() << ss.str();
}
qi::UrlVector::const_iterator jt;
for (jt = svcinfo.endpoints().begin(); jt != svcinfo.endpoints().end(); ++jt)
{
qiLogDebug() << "Service \"" << svcinfo.name() << "\" is now on " << jt->str();
}
return idx;
}
void ServiceDirectory::unregisterService(const unsigned int &idx)
{
boost::recursive_mutex::scoped_lock lock(mutex);
bool pending = false;
// search the id before accessing it
// otherwise operator[] create a empty entry
std::map<unsigned int, ServiceInfo>::iterator it2;
it2 = connectedServices.find(idx);
if (it2 == connectedServices.end()) {
qiLogVerbose() << "Unregister Service: service #" << idx << " not found in the"
<< " connected list. Looking in the pending list.";
it2 = pendingServices.find(idx);
pending = true;
if (it2 == pendingServices.end())
{
std::stringstream ss;
ss << "Unregister Service: Can't find service #" << idx;
qiLogVerbose() << ss.str();
throw std::runtime_error(ss.str());
}
}
std::string serviceName = it2->second.name();
std::map<std::string, unsigned int>::iterator it;
it = nameToIdx.find(serviceName);
if (it == nameToIdx.end())
{
std::stringstream ss;
ss << "Unregister Service: Mapping error, service #" << idx << " (" << serviceName << ") not in nameToIdx";
qiLogError() << ss.str();
throw std::runtime_error(ss.str());
}
std::stringstream ss;
ss << "Unregistered Service \""
<< serviceName
<< "\" (#" << idx << ")";
if (! serviceName.empty() && serviceName[0] == '_') {
// Hide services whose name starts with underscore
qiLogDebug() << ss.str();
}
else
{
qiLogInfo() << ss.str();
}
nameToIdx.erase(it);
if (pending)
pendingServices.erase(it2);
else
connectedServices.erase(it2);
// Find and remove serviceId into socketToIdx map
{
std::map<MessageSocketPtr , std::vector<unsigned int> >::iterator it;
for (it = socketToIdx.begin(); it != socketToIdx.end(); ++it) {
std::vector<unsigned int>::iterator jt;
for (jt = it->second.begin(); jt != it->second.end(); ++jt) {
if (*jt == idx) {
it->second.erase(jt);
//socketToIdx is erased by onSocketDisconnected
break;
}
}
}
}
serviceRemoved(idx, serviceName);
}
void ServiceDirectory::updateServiceInfo(const ServiceInfo &svcinfo)
{
boost::recursive_mutex::scoped_lock lock(mutex);
std::map<unsigned int, ServiceInfo>::iterator itService;
for (itService = connectedServices.begin();
itService != connectedServices.end();
++itService)
{
if (svcinfo.sessionId() == itService->second.sessionId())
{
itService->second.setEndpoints(svcinfo.endpoints());
}
}
itService = connectedServices.find(svcinfo.serviceId());
if (itService != connectedServices.end())
{
connectedServices[svcinfo.serviceId()] = svcinfo;
return;
}
// maybe the service registration was pending...
itService = pendingServices.find(svcinfo.serviceId());
if (itService != pendingServices.end())
{
pendingServices[svcinfo.serviceId()] = svcinfo;
return;
}
std::stringstream ss;
ss << "updateServiceInfo: Can't find service #" << svcinfo.serviceId();
qiLogVerbose() << ss.str();
throw std::runtime_error(ss.str());
}
void ServiceDirectory::serviceReady(const unsigned int &idx)
{
boost::recursive_mutex::scoped_lock lock(mutex);
// search the id before accessing it
// otherwise operator[] create a empty entry
std::map<unsigned int, ServiceInfo>::iterator itService;
itService = pendingServices.find(idx);
if (itService == pendingServices.end())
{
std::stringstream ss;
ss << "Can't find pending service #" << idx;
qiLogError() << ss.str();
throw std::runtime_error(ss.str());
}
std::string serviceName = itService->second.name();
connectedServices[idx] = itService->second;
pendingServices.erase(itService);
serviceAdded(idx, serviceName);
}
Session_SD::Session_SD(ObjectRegistrar* server)
: _server(server)
, _init(false)
{
ServiceDirectory *sdObject = new ServiceDirectory();
boost::shared_ptr<ServiceBoundObject> sbo = boost::make_shared<ServiceBoundObject>(1, Message::GenericObject_Main, createSDP(sdObject), qi::MetaCallType_Direct);
_serviceBoundObject = sbo;
sdObject->_setServiceBoundObject(sbo);
_sdObject = sdObject;
}
Session_SD::~Session_SD()
{
}
void Session_SD::updateServiceInfo()
{
ServiceInfo si;
si.setName("ServiceDirectory");
si.setServiceId(qi::Message::Service_ServiceDirectory);
si.setMachineId(qi::os::getMachineId());
si.setEndpoints(_server->endpoints());
_sdObject->updateServiceInfo(si);
}
qi::Future<void> Session_SD::listenStandalone(const std::vector<qi::Url> &listenAddresses)
{
if (_init)
throw std::runtime_error("Already initialised");
_init = true;
_server->addObject(1, _serviceBoundObject);
std::ostringstream messInfo;
messInfo << "ServiceDirectory listener created on";
qi::FutureBarrier<void> barrier;
for (const qi::Url& url : listenAddresses)
{
messInfo << " " << url.str();
barrier.addFuture(_server->listen(url));
}
qiLogInfo() << messInfo.str();
auto f = barrier.future().andThen([&](const std::vector<Future<void>>& futures)
{
std::string error = [&]
{
std::stringstream ss;
for (const auto& future: futures)
{
if (future.hasError())
{
if (error.empty())
ss << "an error occurred when listening to one of the requested endpoints:";
ss << std::endl << future.error();
}
}
return ss.str();
}();
if (!error.empty())
throw std::runtime_error(error);
auto it = _sdObject->connectedServices.find(qi::Message::Service_ServiceDirectory);
if (it != _sdObject->connectedServices.end())
{
it->second.setEndpoints(_server->endpoints());
return;
}
ServiceInfo si;
si.setName("ServiceDirectory");
si.setServiceId(qi::Message::Service_ServiceDirectory);
si.setMachineId(qi::os::getMachineId());
si.setProcessId(qi::os::getpid());
si.setSessionId("0");
si.setEndpoints(_server->endpoints());
unsigned int regid = _sdObject->registerService(si);
(void)regid;
_sdObject->serviceReady(qi::Message::Service_ServiceDirectory);
//serviceDirectory must have id '1'
QI_ASSERT(regid == qi::Message::Service_ServiceDirectory);
_server->_server.endpointsChanged.connect(boost::bind(&Session_SD::updateServiceInfo, this));
});
return f;
}
std::string ServiceDirectory::machineId()
{
return qi::os::getMachineId();
}
qi::MessageSocketPtr ServiceDirectory::_socketOfService(unsigned int id)
{
boost::recursive_mutex::scoped_lock lock(mutex);
std::map<unsigned int, MessageSocketPtr>::iterator it = idxToSocket.find(id);
if (it == idxToSocket.end())
return MessageSocketPtr();
else
return it->second;
}
void ServiceDirectory::_setServiceBoundObject(boost::shared_ptr<ServiceBoundObject> sbo)
{
serviceBoundObject = sbo;
sbo->_onSocketDisconnectedCallback = boost::bind(&ServiceDirectory::onSocketDisconnected, this, _1, _2);
}
} // !qi
#ifdef _MSC_VER
# pragma warning( pop )
#endif
<commit_msg>messaging: fix an undefined behavior which may lead to a segfault<commit_after>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
// Disable "'this': used in base member initializer list"
#ifdef _MSC_VER
# pragma warning( push )
# pragma warning(disable: 4355)
#endif
#include <vector>
#include <map>
#include <boost/make_shared.hpp>
#include <qi/anyobject.hpp>
#include <qi/future.hpp>
#include "transportserver.hpp"
#include "messagesocket.hpp"
#include "servicedirectory.hpp"
#include <qi/session.hpp>
#include <qi/messaging/serviceinfo.hpp>
#include <qi/type/objecttypebuilder.hpp>
#include "session_p.hpp"
#include <qi/os.hpp>
#include <qi/log.hpp>
#include <qi/url.hpp>
#include "servicedirectory_p.hpp"
#include "server.hpp"
#include <boost/algorithm/string.hpp>
qiLogCategory("qimessaging.servicedirectory");
namespace qi
{
qi::AnyObject createSDP(ServiceDirectory* self) {
static qi::ObjectTypeBuilder<ServiceDirectory>* ob = nullptr;
static boost::mutex* mutex = nullptr;
QI_THREADSAFE_NEW(mutex);
boost::mutex::scoped_lock lock(*mutex);
if (!ob)
{
ob = new qi::ObjectTypeBuilder<ServiceDirectory>();
ob->setThreadingModel(ObjectThreadingModel_MultiThread);
unsigned int id = 0;
id = ob->advertiseMethod("service", &ServiceDirectory::service);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_Service);
id = ob->advertiseMethod("services", &ServiceDirectory::services);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_Services);
id = ob->advertiseMethod("registerService", &ServiceDirectory::registerService);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_RegisterService);
id = ob->advertiseMethod("unregisterService", &ServiceDirectory::unregisterService);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_UnregisterService);
id = ob->advertiseMethod("serviceReady", &ServiceDirectory::serviceReady);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_ServiceReady);
id = ob->advertiseMethod("updateServiceInfo", &ServiceDirectory::updateServiceInfo);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_UpdateServiceInfo);
id = ob->advertiseSignal("serviceAdded", &ServiceDirectory::serviceAdded);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_ServiceAdded);
id = ob->advertiseSignal("serviceRemoved", &ServiceDirectory::serviceRemoved);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_ServiceRemoved);
id = ob->advertiseMethod("machineId", &ServiceDirectory::machineId);
QI_ASSERT(id == qi::Message::ServiceDirectoryAction_MachineId);
ob->advertiseMethod("_socketOfService", &ServiceDirectory::_socketOfService);
// used locally only, we do not export its id
// Silence compile warning unused id
(void)id;
}
return ob->object(self);
}
ServiceDirectory::ServiceDirectory()
: servicesCount(0)
{
}
ServiceDirectory::~ServiceDirectory()
{
if (!connectedServices.empty())
qiLogWarning() << "Destroying while connected services remain";
}
void ServiceDirectory::onSocketDisconnected(MessageSocketPtr socket, std::string error)
{
boost::recursive_mutex::scoped_lock lock(mutex);
// clean from idxToSocket
for (std::map<unsigned int, MessageSocketPtr>::iterator it = idxToSocket.begin(), iend = idxToSocket.end(); it != iend;)
{
std::map<unsigned int, MessageSocketPtr>::iterator next = it;
++next;
if (it->second == socket)
idxToSocket.erase(it);
it = next;
}
// if services were connected behind the socket
std::map<MessageSocketPtr, std::vector<unsigned int> >::iterator it;
it = socketToIdx.find(socket);
if (it == socketToIdx.end()) {
return;
}
// Copy the vector, iterators will be invalidated.
std::vector<unsigned int> ids = it->second;
// Always start at the beginning since we erase elements on unregisterService
// and mess up the iterator
for (std::vector<unsigned int>::iterator it2 = ids.begin();
it2 != ids.end();
++it2)
{
qiLogInfo() << "Service #" << *it2 << " disconnected";
try {
unregisterService(*it2);
} catch (std::runtime_error &) {
qiLogWarning() << "Cannot unregister service #" << *it2;
}
}
socketToIdx.erase(it);
}
std::vector<ServiceInfo> ServiceDirectory::services()
{
boost::recursive_mutex::scoped_lock lock(mutex);
std::vector<ServiceInfo> result;
std::map<unsigned int, ServiceInfo>::const_iterator it;
for (it = connectedServices.begin(); it != connectedServices.end(); ++it)
result.push_back(it->second);
return result;
}
ServiceInfo ServiceDirectory::service(const std::string &name)
{
boost::recursive_mutex::scoped_lock lock(mutex);
std::map<unsigned int, ServiceInfo>::const_iterator servicesIt;
std::map<std::string, unsigned int>::const_iterator it;
it = nameToIdx.find(name);
if (it == nameToIdx.end()) {
std::stringstream ss;
ss << "Cannot find service '" << name << "' in index";
throw std::runtime_error(ss.str());
}
unsigned int idx = it->second;
servicesIt = connectedServices.find(idx);
if (servicesIt == connectedServices.end()) {
std::stringstream ss;
ss << "Cannot find ServiceInfo for service '" << name << "'";
throw std::runtime_error(ss.str());
}
return servicesIt->second;
}
unsigned int ServiceDirectory::registerService(const ServiceInfo &svcinfo)
{
boost::shared_ptr<ServiceBoundObject> sbo = serviceBoundObject.lock();
if (!sbo)
throw std::runtime_error("ServiceBoundObject has expired.");
MessageSocketPtr socket = sbo->currentSocket();
boost::recursive_mutex::scoped_lock lock(mutex);
std::map<std::string, unsigned int>::iterator it;
it = nameToIdx.find(svcinfo.name());
if (it != nameToIdx.end())
{
std::stringstream ss;
ss << "Service \"" <<
svcinfo.name() <<
"\" (#" << it->second << ") is already registered. " <<
"Rejecting conflicting registration attempt.";
qiLogWarning() << ss.str();
throw std::runtime_error(ss.str());
}
unsigned int idx = ++servicesCount;
nameToIdx[svcinfo.name()] = idx;
// Do not add serviceDirectory on the map (socket() == null)
if (idx != qi::Message::Service_ServiceDirectory)
socketToIdx[socket].push_back(idx);
pendingServices[idx] = svcinfo;
pendingServices[idx].setServiceId(idx);
idxToSocket[idx] = socket;
std::stringstream ss;
ss << "Registered Service \"" << svcinfo.name() << "\" (#" << idx << ")";
if (! svcinfo.name().empty() && svcinfo.name()[0] == '_') {
// Hide services whose name starts with an underscore
qiLogDebug() << ss.str();
}
else
{
qiLogInfo() << ss.str();
}
qi::UrlVector::const_iterator jt;
for (jt = svcinfo.endpoints().begin(); jt != svcinfo.endpoints().end(); ++jt)
{
qiLogDebug() << "Service \"" << svcinfo.name() << "\" is now on " << jt->str();
}
return idx;
}
void ServiceDirectory::unregisterService(const unsigned int &idx)
{
boost::recursive_mutex::scoped_lock lock(mutex);
bool pending = false;
// search the id before accessing it
// otherwise operator[] create a empty entry
std::map<unsigned int, ServiceInfo>::iterator it2;
it2 = connectedServices.find(idx);
if (it2 == connectedServices.end()) {
qiLogVerbose() << "Unregister Service: service #" << idx << " not found in the"
<< " connected list. Looking in the pending list.";
it2 = pendingServices.find(idx);
pending = true;
if (it2 == pendingServices.end())
{
std::stringstream ss;
ss << "Unregister Service: Can't find service #" << idx;
qiLogVerbose() << ss.str();
throw std::runtime_error(ss.str());
}
}
std::string serviceName = it2->second.name();
std::map<std::string, unsigned int>::iterator it;
it = nameToIdx.find(serviceName);
if (it == nameToIdx.end())
{
std::stringstream ss;
ss << "Unregister Service: Mapping error, service #" << idx << " (" << serviceName << ") not in nameToIdx";
qiLogError() << ss.str();
throw std::runtime_error(ss.str());
}
std::stringstream ss;
ss << "Unregistered Service \""
<< serviceName
<< "\" (#" << idx << ")";
if (! serviceName.empty() && serviceName[0] == '_') {
// Hide services whose name starts with underscore
qiLogDebug() << ss.str();
}
else
{
qiLogInfo() << ss.str();
}
nameToIdx.erase(it);
if (pending)
pendingServices.erase(it2);
else
connectedServices.erase(it2);
// Find and remove serviceId into socketToIdx map
{
std::map<MessageSocketPtr , std::vector<unsigned int> >::iterator it;
for (it = socketToIdx.begin(); it != socketToIdx.end(); ++it) {
std::vector<unsigned int>::iterator jt;
for (jt = it->second.begin(); jt != it->second.end(); ++jt) {
if (*jt == idx) {
it->second.erase(jt);
//socketToIdx is erased by onSocketDisconnected
break;
}
}
}
}
serviceRemoved(idx, serviceName);
}
void ServiceDirectory::updateServiceInfo(const ServiceInfo &svcinfo)
{
boost::recursive_mutex::scoped_lock lock(mutex);
std::map<unsigned int, ServiceInfo>::iterator itService;
for (itService = connectedServices.begin();
itService != connectedServices.end();
++itService)
{
if (svcinfo.sessionId() == itService->second.sessionId())
{
itService->second.setEndpoints(svcinfo.endpoints());
}
}
itService = connectedServices.find(svcinfo.serviceId());
if (itService != connectedServices.end())
{
connectedServices[svcinfo.serviceId()] = svcinfo;
return;
}
// maybe the service registration was pending...
itService = pendingServices.find(svcinfo.serviceId());
if (itService != pendingServices.end())
{
pendingServices[svcinfo.serviceId()] = svcinfo;
return;
}
std::stringstream ss;
ss << "updateServiceInfo: Can't find service #" << svcinfo.serviceId();
qiLogVerbose() << ss.str();
throw std::runtime_error(ss.str());
}
void ServiceDirectory::serviceReady(const unsigned int &idx)
{
boost::recursive_mutex::scoped_lock lock(mutex);
// search the id before accessing it
// otherwise operator[] create a empty entry
std::map<unsigned int, ServiceInfo>::iterator itService;
itService = pendingServices.find(idx);
if (itService == pendingServices.end())
{
std::stringstream ss;
ss << "Can't find pending service #" << idx;
qiLogError() << ss.str();
throw std::runtime_error(ss.str());
}
std::string serviceName = itService->second.name();
connectedServices[idx] = itService->second;
pendingServices.erase(itService);
serviceAdded(idx, serviceName);
}
Session_SD::Session_SD(ObjectRegistrar* server)
: _server(server)
, _init(false)
{
ServiceDirectory *sdObject = new ServiceDirectory();
boost::shared_ptr<ServiceBoundObject> sbo = boost::make_shared<ServiceBoundObject>(1, Message::GenericObject_Main, createSDP(sdObject), qi::MetaCallType_Direct);
_serviceBoundObject = sbo;
sdObject->_setServiceBoundObject(sbo);
_sdObject = sdObject;
}
Session_SD::~Session_SD()
{
}
void Session_SD::updateServiceInfo()
{
ServiceInfo si;
si.setName("ServiceDirectory");
si.setServiceId(qi::Message::Service_ServiceDirectory);
si.setMachineId(qi::os::getMachineId());
si.setEndpoints(_server->endpoints());
_sdObject->updateServiceInfo(si);
}
qi::Future<void> Session_SD::listenStandalone(const std::vector<qi::Url> &listenAddresses)
{
if (_init)
throw std::runtime_error("Already initialised");
_init = true;
_server->addObject(1, _serviceBoundObject);
std::ostringstream messInfo;
messInfo << "ServiceDirectory listener created on";
qi::FutureBarrier<void> barrier;
for (const qi::Url& url : listenAddresses)
{
messInfo << " " << url.str();
barrier.addFuture(_server->listen(url));
}
qiLogInfo() << messInfo.str();
auto f = barrier.future().andThen([&](const std::vector<Future<void>>& futures)
{
const auto error = [&]
{
std::stringstream ss;
bool prefixed = false;
for (const auto& future: futures)
{
if (future.hasError())
{
if (!prefixed)
{
ss << "an error occurred when listening to one of the requested endpoints:";
prefixed = true;
}
ss << std::endl << future.error();
}
}
return ss.str();
}();
if (!error.empty())
throw std::runtime_error(error);
auto it = _sdObject->connectedServices.find(qi::Message::Service_ServiceDirectory);
if (it != _sdObject->connectedServices.end())
{
it->second.setEndpoints(_server->endpoints());
return;
}
ServiceInfo si;
si.setName("ServiceDirectory");
si.setServiceId(qi::Message::Service_ServiceDirectory);
si.setMachineId(qi::os::getMachineId());
si.setProcessId(qi::os::getpid());
si.setSessionId("0");
si.setEndpoints(_server->endpoints());
unsigned int regid = _sdObject->registerService(si);
(void)regid;
_sdObject->serviceReady(qi::Message::Service_ServiceDirectory);
//serviceDirectory must have id '1'
QI_ASSERT(regid == qi::Message::Service_ServiceDirectory);
_server->_server.endpointsChanged.connect(boost::bind(&Session_SD::updateServiceInfo, this));
});
return f;
}
std::string ServiceDirectory::machineId()
{
return qi::os::getMachineId();
}
qi::MessageSocketPtr ServiceDirectory::_socketOfService(unsigned int id)
{
boost::recursive_mutex::scoped_lock lock(mutex);
std::map<unsigned int, MessageSocketPtr>::iterator it = idxToSocket.find(id);
if (it == idxToSocket.end())
return MessageSocketPtr();
else
return it->second;
}
void ServiceDirectory::_setServiceBoundObject(boost::shared_ptr<ServiceBoundObject> sbo)
{
serviceBoundObject = sbo;
sbo->_onSocketDisconnectedCallback = boost::bind(&ServiceDirectory::onSocketDisconnected, this, _1, _2);
}
} // !qi
#ifdef _MSC_VER
# pragma warning( pop )
#endif
<|endoftext|> |
<commit_before>/*________________________________
| |
| INCLUDES |
|_________________________________| */
#include "good.cpp"
#include <pcl/io/pcd_io.h>
#include <pcl/io/ply_io.h>
#include <pcl/visualization/cloud_viewer.h>
#include <boost/filesystem.hpp>
#include <pcl/visualization/histogram_visualizer.h>
typedef pcl::PointXYZRGBA PointT;
void
visualizationPointCloud(boost::shared_ptr<pcl::PointCloud<PointT> > point_cloud, std::string name_of_window)
{
// visualization point cloud
pcl::visualization::PCLVisualizer viewer1 (name_of_window.c_str());
viewer1.addPointCloud (point_cloud, "original");
viewer1.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "original");
viewer1.addCoordinateSystem (0.12);
viewer1.setBackgroundColor (255, 255, 255);
while (!viewer1.wasStopped ())
{ viewer1.spinOnce (100);}
}
int
readPointCloud(std::string object_path, boost::shared_ptr<pcl::PointCloud<PointT> > point_cloud)
{
std::string extension = boost::filesystem::extension(object_path);
if (extension == ".pcd" || extension == ".PCD")
{
if (pcl::io::loadPCDFile(object_path.c_str() , *point_cloud) == -1)
{
std::cout << "\n Cloud reading failed." << std::endl;
return (-1);
}
}
else if (extension == ".ply" || extension == ".PLY")
{
if (pcl::io::loadPLYFile(object_path , *point_cloud) == -1)
{
std::cout << "\n Cloud reading failed." << std::endl;
return (-1);
}
}
else
{
std::cout << "\n file extension is not correct. Syntax is: test_GOOD_descriptor <path/file_name.pcd> [--nogui] or test_GOOD_descriptor <path/file_name.ply> [--nogui]" << std::endl;
return -1;
}
return 1;
}
int main(int argc, char* argv[])
{
bool gui_flag = true;
if (argc < 2 ||argc > 3)
{
std::cout << "\n Syntax is: test_GOOD_descriptor <path/file_name.pcd> [--nogui] or test_GOOD_descriptor <path/file_name.ply> [--nogui]" << std::endl;
return 0;
}
if (argc ==3 && strcmp(argv[2],"--nogui") != 0 )
{
std::cout << "\n Syntax is: test_GOOD_descriptor <path/file_name.pcd> [--nogui] or test_GOOD_descriptor <path/file_name.ply> [--nogui]" << std::endl;
return 0;
}
else if (argc ==3)
{
gui_flag = false;
}
std::string object_path = argv[1];
pcl::PointCloud<PointT>::Ptr object (new pcl::PointCloud<PointT>);
if (readPointCloud( object_path, object)==-1)
return -1;
if (gui_flag)
visualizationPointCloud(object, "Original point cloud and camera reference frame");
std::vector< float > object_description;
std::vector < boost::shared_ptr<pcl::PointCloud<PointT> > > vector_of_projected_views;
boost::shared_ptr<pcl::PointCloud<PointT> > transformed_object (new pcl::PointCloud<PointT>);
Eigen::Matrix4f transformation;
pcl::PointCloud<PointT>::Ptr transformed_object_and_projected_views (new pcl::PointCloud<PointT>);
pcl::PointXYZ center_of_bounding_box;
pcl::PointXYZ bounding_box_dimensions;
std::string order_of_projected_planes;
// Setup the GOOD descriptor
// GOOD can also be setup in a line: GOODEstimation test_GOOD_descriptor (5, 0.0015);
GOODEstimation<PointT> test_GOOD_descriptor;
test_GOOD_descriptor.setNumberOfBins(5);
test_GOOD_descriptor.setThreshold(0.0015);
// Provide the original point cloud
test_GOOD_descriptor.setInputCloud(object);
// Compute GOOD discriptor for the given object
test_GOOD_descriptor.compute(object_description);
std::cout <<"\n GOOD = [";
for (size_t i =0; i< object_description.size()-1; i ++)
std::cout << object_description.at(i)<<",";
std::cout << object_description.back() <<"]"<<std::endl;
/*_________________________________________
| |
| Functionalities for Object Manipulation |
|__________________________________________| */
// The following functinalities of GOOD are usefull for manipulation tasks:
// Get objec point cloud in local reference frame
test_GOOD_descriptor.getTransformedObject (transformed_object);
// Get three orthographic projects and transformation matrix
test_GOOD_descriptor.getOrthographicProjections (vector_of_projected_views);
test_GOOD_descriptor.getTransformationMatrix (transformation);
std::cout << "\n transofrmation matrix =\n"<<transformation << std::endl;
// Get object bounding box information
test_GOOD_descriptor.getCenterOfObjectBoundingBox (center_of_bounding_box);
test_GOOD_descriptor.getObjectBoundingBoxDimensions(bounding_box_dimensions);
std::cout<<"\n center_of_bounding_box = " << center_of_bounding_box<<std::endl;
std::cout<<"\n bounding_box_dimensions = " << bounding_box_dimensions <<std::endl;
// Get the order of the three projected planes
test_GOOD_descriptor.getOrderOfProjectedPlanes(order_of_projected_planes);
std::cout << "\n order of projected planes = "<<order_of_projected_planes << std::endl;
if (gui_flag)
{
// Visualizing the transformed object, local reference fram and three orthographic projections
*transformed_object_and_projected_views += *vector_of_projected_views.at(0);
*transformed_object_and_projected_views += *vector_of_projected_views.at(1);
*transformed_object_and_projected_views += *vector_of_projected_views.at(2);
*transformed_object_and_projected_views += *transformed_object;
visualizationPointCloud(transformed_object_and_projected_views, "Transformed object and projected views");
}
return 0;
}
<commit_msg>Update test_GOOD_descriptor.cpp<commit_after>/*________________________________
| |
| INCLUDES |
|_________________________________| */
#include "good.cpp"
#include <pcl/io/pcd_io.h>
#include <pcl/io/ply_io.h>
#include <pcl/visualization/cloud_viewer.h>
#include <boost/filesystem.hpp>
#include <pcl/visualization/histogram_visualizer.h>
typedef pcl::PointXYZRGB PointT;
void
visualizationPointCloud(boost::shared_ptr<pcl::PointCloud<PointT> > point_cloud, std::string name_of_window)
{
// visualization point cloud
pcl::visualization::PCLVisualizer viewer1 (name_of_window.c_str());
viewer1.addPointCloud (point_cloud, "original");
viewer1.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "original");
viewer1.addCoordinateSystem (0.12);
viewer1.setBackgroundColor (255, 255, 255);
while (!viewer1.wasStopped ())
{ viewer1.spinOnce (100);}
}
int
readPointCloud(std::string object_path, boost::shared_ptr<pcl::PointCloud<PointT> > point_cloud)
{
std::string extension = boost::filesystem::extension(object_path);
if (extension == ".pcd" || extension == ".PCD")
{
if (pcl::io::loadPCDFile(object_path.c_str() , *point_cloud) == -1)
{
std::cout << "\n Cloud reading failed." << std::endl;
return (-1);
}
}
else if (extension == ".ply" || extension == ".PLY")
{
if (pcl::io::loadPLYFile(object_path , *point_cloud) == -1)
{
std::cout << "\n Cloud reading failed." << std::endl;
return (-1);
}
}
else
{
std::cout << "\n file extension is not correct. Syntax is: test_GOOD_descriptor <path/file_name.pcd> [--nogui] or test_GOOD_descriptor <path/file_name.ply> [--nogui]" << std::endl;
return -1;
}
return 1;
}
int main(int argc, char* argv[])
{
bool gui_flag = true;
if (argc < 2 ||argc > 3)
{
std::cout << "\n Syntax is: test_GOOD_descriptor <path/file_name.pcd> [--nogui] or test_GOOD_descriptor <path/file_name.ply> [--nogui]" << std::endl;
return 0;
}
if (argc ==3 && strcmp(argv[2],"--nogui") != 0 )
{
std::cout << "\n Syntax is: test_GOOD_descriptor <path/file_name.pcd> [--nogui] or test_GOOD_descriptor <path/file_name.ply> [--nogui]" << std::endl;
return 0;
}
else if (argc ==3)
{
gui_flag = false;
}
std::string object_path = argv[1];
pcl::PointCloud<PointT>::Ptr object (new pcl::PointCloud<PointT>);
if (readPointCloud( object_path, object)==-1)
return -1;
if (gui_flag)
visualizationPointCloud(object, "Original point cloud and camera reference frame");
std::vector< float > object_description;
std::vector < boost::shared_ptr<pcl::PointCloud<PointT> > > vector_of_projected_views;
boost::shared_ptr<pcl::PointCloud<PointT> > transformed_object (new pcl::PointCloud<PointT>);
Eigen::Matrix4f transformation;
pcl::PointCloud<PointT>::Ptr transformed_object_and_projected_views (new pcl::PointCloud<PointT>);
pcl::PointXYZ center_of_bounding_box;
pcl::PointXYZ bounding_box_dimensions;
std::string order_of_projected_planes;
// Setup the GOOD descriptor
// GOOD can also be setup in a line: GOODEstimation test_GOOD_descriptor (5, 0.0015);
GOODEstimation<PointT> test_GOOD_descriptor;
test_GOOD_descriptor.setNumberOfBins(5);
test_GOOD_descriptor.setThreshold(0.0015);
// Provide the original point cloud
test_GOOD_descriptor.setInputCloud(object);
// Compute GOOD discriptor for the given object
test_GOOD_descriptor.compute(object_description);
std::cout <<"\n GOOD = [";
for (size_t i =0; i< object_description.size()-1; i ++)
std::cout << object_description.at(i)<<",";
std::cout << object_description.back() <<"]"<<std::endl;
/*_________________________________________
| |
| Functionalities for Object Manipulation |
|__________________________________________| */
// The following functinalities of GOOD are usefull for manipulation tasks:
// Get objec point cloud in local reference frame
test_GOOD_descriptor.getTransformedObject (transformed_object);
// Get three orthographic projects and transformation matrix
test_GOOD_descriptor.getOrthographicProjections (vector_of_projected_views);
test_GOOD_descriptor.getTransformationMatrix (transformation);
std::cout << "\n transofrmation matrix =\n"<<transformation << std::endl;
// Get object bounding box information
test_GOOD_descriptor.getCenterOfObjectBoundingBox (center_of_bounding_box);
test_GOOD_descriptor.getObjectBoundingBoxDimensions(bounding_box_dimensions);
std::cout<<"\n center_of_bounding_box = " << center_of_bounding_box<<std::endl;
std::cout<<"\n bounding_box_dimensions = " << bounding_box_dimensions <<std::endl;
// Get the order of the three projected planes
test_GOOD_descriptor.getOrderOfProjectedPlanes(order_of_projected_planes);
std::cout << "\n order of projected planes = "<<order_of_projected_planes << std::endl;
if (gui_flag)
{
// Visualizing the transformed object, local reference fram and three orthographic projections
*transformed_object_and_projected_views += *vector_of_projected_views.at(0);
*transformed_object_and_projected_views += *vector_of_projected_views.at(1);
*transformed_object_and_projected_views += *vector_of_projected_views.at(2);
*transformed_object_and_projected_views += *transformed_object;
visualizationPointCloud(transformed_object_and_projected_views, "Transformed object and projected views");
}
return 0;
}
<|endoftext|> |
<commit_before>#include "ylikuutio_string.hpp"
// Include standard headers
#include <cstdio> // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.
#include <cstring> // std::memcmp, std::strcmp, std::strlen, std::strncmp
#include <iostream> // std::cout, std::cin, std::cerr
#include <list> // std::list
#include <sstream> // std::stringstream
#include <string> // std::string
#include <vector> // std::vector
namespace string
{
bool check_and_report_if_some_string_matches(const char* file_base_pointer, char* file_data_pointer, std::vector<std::string> identifier_strings_vector)
{
for (std::string identifier_string : identifier_strings_vector)
{
const char* identifier_string_char = identifier_string.c_str();
if (std::strncmp(file_data_pointer, identifier_string_char, std::strlen(identifier_string_char)) == 0)
{
const char* identifier_string_char = identifier_string.c_str();
uint64_t offset = (uint64_t) file_data_pointer - (uint64_t) file_base_pointer;
// std::printf("%s found at file offset 0x%llu (memory address 0x%llu).\n", identifier_string_char, offset, (uint64_t) file_data_pointer);
return true;
}
}
return false;
}
void extract_string(char* dest_mem_pointer, char* &src_mem_pointer, char* char_end_string)
{
while (std::strncmp(src_mem_pointer, char_end_string, std::strlen(char_end_string)) != 0)
{
strncpy(dest_mem_pointer++, src_mem_pointer++, 1);
}
*dest_mem_pointer = '\0';
}
void extract_string_with_several_endings(char* dest_mem_pointer, char*& src_mem_pointer, char* char_end_string)
{
// This function copies characters from `src_mem_pointer` until a character matches.
while (true)
{
uint32_t n_of_ending_characters = std::strlen(char_end_string);
char* end_char_pointer;
end_char_pointer = char_end_string;
// Check if current character is any of the ending characters.
while (*end_char_pointer != '\0')
{
if (std::strncmp(src_mem_pointer, end_char_pointer, 1) == 0)
{
*dest_mem_pointer = '\0';
return;
}
end_char_pointer++;
}
// OK, current character is not any of the ending characters.
// Copy it and advance the pointers accordingly.
strncpy(dest_mem_pointer++, src_mem_pointer++, 1);
}
}
int32_t extract_int32_t_value_from_string(char*& data_pointer, char* char_end_string, const char* description)
{
char char_number_buffer[1024]; // FIXME: risk of buffer overflow.
char* dest_mem_pointer;
dest_mem_pointer = char_number_buffer;
string::extract_string_with_several_endings(dest_mem_pointer, ++data_pointer, char_end_string);
uint32_t value = std::atoi(dest_mem_pointer);
if (description != nullptr)
{
std::printf("%s: %d\n", description, value);
}
return value;
}
float extract_float_value_from_string(char*& data_pointer, char* char_end_string, const char* description)
{
char char_number_buffer[1024]; // FIXME: risk of buffer overflow.
char* dest_mem_pointer;
dest_mem_pointer = char_number_buffer;
string::extract_string_with_several_endings(dest_mem_pointer, ++data_pointer, char_end_string);
float value = std::atof(dest_mem_pointer);
if (description != nullptr)
{
std::printf("%s: %f\n", description, value);
}
return value;
}
int32_t extract_unicode_value_from_string(const char*& unicode_char_pointer)
{
if (*unicode_char_pointer == '\0')
{
unicode_char_pointer++;
std::cerr << "Error: Unicode can not begin with \\0!\n";
return 0xdfff; // invalid unicode!
}
if (*unicode_char_pointer != '&')
{
// it's just a character, so return its value,
// and advance to the next character.
return (int32_t) *unicode_char_pointer++;
}
if (*++unicode_char_pointer != '#')
{
// not valid format, must begin `"&#x"`.
unicode_char_pointer++;
std::cerr << "Error: Unicode string format not supported!\n";
return 0xdfff; // invalid unicode!
}
if (*++unicode_char_pointer != 'x')
{
// not valid format, must begin `"&#x"`.
unicode_char_pointer++;
std::cerr << "Error: Unicode string format not supported!\n";
return 0xdfff; // invalid unicode!
}
// valid format.
std::string hex_string;
// unicode string beginning with '&'
while (*++unicode_char_pointer != ';')
{
if (*unicode_char_pointer == '\0')
{
std::cerr << "Error: Null character \\0 reached before end of Unicode string!\n";
return 0xdfff; // invalid unicode!
}
char current_char = *unicode_char_pointer;
hex_string.append(unicode_char_pointer);
}
// Advance to the next character.
unicode_char_pointer++;
// convert hexadecimal string to signed integer.
// http://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer/1070499#1070499
uint32_t unicode_value;
std::stringstream unicode_stringstream;
unicode_stringstream << std::hex << hex_string;
unicode_stringstream >> unicode_value;
return unicode_value;
}
std::string convert_std_list_char_to_std_string(const std::list<char>& std_list_char)
{
std::string my_string;
for (std::list<char>::const_iterator it = std_list_char.begin(); it != std_list_char.end(); it++)
{
my_string.push_back(*it);
}
return my_string;
}
std::string convert_std_list_char_to_std_string(const std::list<char>& std_list_char, uint32_t first_line_length, uint32_t line_length)
{
std::string my_string;
uint32_t remaining_characters_on_this_line = first_line_length;
for (std::list<char>::const_iterator it = std_list_char.begin(); it != std_list_char.end(); it++)
{
if (remaining_characters_on_this_line == 0)
{
my_string.push_back('\\');
my_string.push_back('n');
remaining_characters_on_this_line = line_length;
}
my_string.push_back(*it);
remaining_characters_on_this_line--;
}
return my_string;
}
}
<commit_msg>Removed commented out code.<commit_after>#include "ylikuutio_string.hpp"
// Include standard headers
#include <cstdio> // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.
#include <cstring> // std::memcmp, std::strcmp, std::strlen, std::strncmp
#include <iostream> // std::cout, std::cin, std::cerr
#include <list> // std::list
#include <sstream> // std::stringstream
#include <string> // std::string
#include <vector> // std::vector
namespace string
{
bool check_and_report_if_some_string_matches(const char* file_base_pointer, char* file_data_pointer, std::vector<std::string> identifier_strings_vector)
{
for (std::string identifier_string : identifier_strings_vector)
{
const char* identifier_string_char = identifier_string.c_str();
if (std::strncmp(file_data_pointer, identifier_string_char, std::strlen(identifier_string_char)) == 0)
{
const char* identifier_string_char = identifier_string.c_str();
uint64_t offset = (uint64_t) file_data_pointer - (uint64_t) file_base_pointer;
return true;
}
}
return false;
}
void extract_string(char* dest_mem_pointer, char* &src_mem_pointer, char* char_end_string)
{
while (std::strncmp(src_mem_pointer, char_end_string, std::strlen(char_end_string)) != 0)
{
strncpy(dest_mem_pointer++, src_mem_pointer++, 1);
}
*dest_mem_pointer = '\0';
}
void extract_string_with_several_endings(char* dest_mem_pointer, char*& src_mem_pointer, char* char_end_string)
{
// This function copies characters from `src_mem_pointer` until a character matches.
while (true)
{
uint32_t n_of_ending_characters = std::strlen(char_end_string);
char* end_char_pointer;
end_char_pointer = char_end_string;
// Check if current character is any of the ending characters.
while (*end_char_pointer != '\0')
{
if (std::strncmp(src_mem_pointer, end_char_pointer, 1) == 0)
{
*dest_mem_pointer = '\0';
return;
}
end_char_pointer++;
}
// OK, current character is not any of the ending characters.
// Copy it and advance the pointers accordingly.
strncpy(dest_mem_pointer++, src_mem_pointer++, 1);
}
}
int32_t extract_int32_t_value_from_string(char*& data_pointer, char* char_end_string, const char* description)
{
char char_number_buffer[1024]; // FIXME: risk of buffer overflow.
char* dest_mem_pointer;
dest_mem_pointer = char_number_buffer;
string::extract_string_with_several_endings(dest_mem_pointer, ++data_pointer, char_end_string);
uint32_t value = std::atoi(dest_mem_pointer);
if (description != nullptr)
{
std::printf("%s: %d\n", description, value);
}
return value;
}
float extract_float_value_from_string(char*& data_pointer, char* char_end_string, const char* description)
{
char char_number_buffer[1024]; // FIXME: risk of buffer overflow.
char* dest_mem_pointer;
dest_mem_pointer = char_number_buffer;
string::extract_string_with_several_endings(dest_mem_pointer, ++data_pointer, char_end_string);
float value = std::atof(dest_mem_pointer);
if (description != nullptr)
{
std::printf("%s: %f\n", description, value);
}
return value;
}
int32_t extract_unicode_value_from_string(const char*& unicode_char_pointer)
{
if (*unicode_char_pointer == '\0')
{
unicode_char_pointer++;
std::cerr << "Error: Unicode can not begin with \\0!\n";
return 0xdfff; // invalid unicode!
}
if (*unicode_char_pointer != '&')
{
// it's just a character, so return its value,
// and advance to the next character.
return (int32_t) *unicode_char_pointer++;
}
if (*++unicode_char_pointer != '#')
{
// not valid format, must begin `"&#x"`.
unicode_char_pointer++;
std::cerr << "Error: Unicode string format not supported!\n";
return 0xdfff; // invalid unicode!
}
if (*++unicode_char_pointer != 'x')
{
// not valid format, must begin `"&#x"`.
unicode_char_pointer++;
std::cerr << "Error: Unicode string format not supported!\n";
return 0xdfff; // invalid unicode!
}
// valid format.
std::string hex_string;
// unicode string beginning with '&'
while (*++unicode_char_pointer != ';')
{
if (*unicode_char_pointer == '\0')
{
std::cerr << "Error: Null character \\0 reached before end of Unicode string!\n";
return 0xdfff; // invalid unicode!
}
char current_char = *unicode_char_pointer;
hex_string.append(unicode_char_pointer);
}
// Advance to the next character.
unicode_char_pointer++;
// convert hexadecimal string to signed integer.
// http://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer/1070499#1070499
uint32_t unicode_value;
std::stringstream unicode_stringstream;
unicode_stringstream << std::hex << hex_string;
unicode_stringstream >> unicode_value;
return unicode_value;
}
std::string convert_std_list_char_to_std_string(const std::list<char>& std_list_char)
{
std::string my_string;
for (std::list<char>::const_iterator it = std_list_char.begin(); it != std_list_char.end(); it++)
{
my_string.push_back(*it);
}
return my_string;
}
std::string convert_std_list_char_to_std_string(const std::list<char>& std_list_char, uint32_t first_line_length, uint32_t line_length)
{
std::string my_string;
uint32_t remaining_characters_on_this_line = first_line_length;
for (std::list<char>::const_iterator it = std_list_char.begin(); it != std_list_char.end(); it++)
{
if (remaining_characters_on_this_line == 0)
{
my_string.push_back('\\');
my_string.push_back('n');
remaining_characters_on_this_line = line_length;
}
my_string.push_back(*it);
remaining_characters_on_this_line--;
}
return my_string;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cunooptions.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 03:37:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_codemaker.hxx"
#include <stdio.h>
#include "cunooptions.hxx"
using namespace rtl;
sal_Bool CunoOptions::initOptions(int ac, char* av[], sal_Bool bCmdFile)
throw( IllegalArgument )
{
sal_Bool ret = sal_True;
sal_uInt16 i=0;
if (!bCmdFile)
{
bCmdFile = sal_True;
m_program = av[0];
if (ac < 2)
{
fprintf(stderr, "%s", prepareHelp().getStr());
ret = sal_False;
}
i = 1;
} else
{
i = 0;
}
char *s=NULL;
for (i; i < ac; i++)
{
if (av[i][0] == '-')
{
switch (av[i][1])
{
case 'O':
if (av[i][2] == 'C')
{
if (av[i][3] == '\0')
{
if (i < ac - 1 && av[i+1][0] != '-')
{
i++;
s = av[i];
} else
{
OString tmp("'-OC', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i+1]) + "'";
}
throw IllegalArgument(tmp);
}
} else
{
s = av[i] + 3;
}
m_options["-OC"] = OString(s);
break;
} else
if (av[i][2] == '\0')
{
if (i < ac - 1 && av[i+1][0] != '-')
{
i++;
s = av[i];
} else
{
OString tmp("'-O', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i+1]) + "'";
}
throw IllegalArgument(tmp);
}
} else
{
s = av[i] + 2;
}
m_options["-O"] = OString(s);
break;
case 'B':
if (av[i][2] == '\0')
{
if (i < ac - 1 && av[i+1][0] != '-')
{
i++;
s = av[i];
} else
{
OString tmp("'-B', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i+1]) + "'";
}
throw IllegalArgument(tmp);
}
} else
{
s = av[i] + 2;
}
m_options["-B"] = OString(s);
break;
case 'T':
if (av[i][2] == '\0')
{
if (i < ac - 1 && av[i+1][0] != '-')
{
i++;
s = av[i];
} else
{
OString tmp("'-T', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i+1]) + "'";
}
throw IllegalArgument(tmp);
}
} else
{
s = av[i] + 2;
}
if (m_options.count("-T") > 0)
{
OString tmp(m_options["-T"]);
tmp = tmp + ";" + s;
m_options["-T"] = tmp;
} else
{
m_options["-T"] = OString(s);
}
break;
case 'U':
if (av[i][2] != '\0')
{
OString tmp("'-U', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i]) + "'";
}
throw IllegalArgument(tmp);
}
m_options["-U"] = OString("");
break;
/*
case 'L':
if (av[i][2] != '\0')
{
OString tmp("'-L', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i]) + "'";
}
throw IllegalArgument(tmp);
}
if (isValid("-C") || isValid("-CS"))
{
OString tmp("'-L' could not be combined with '-C' or '-CS' option");
throw IllegalArgument(tmp);
}
m_options["-L"] = OString("");
break;
*/
case 'C':
if (av[i][2] != '\0')
{
OString tmp("'-C', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i]) + "'";
}
throw IllegalArgument(tmp);
}
if (isValid("-L") || isValid("-CS"))
{
OString tmp("'-C' could not be combined with '-L' or '-CS' option");
throw IllegalArgument(tmp);
}
m_options["-C"] = OString("");
break;
case 'G':
if (av[i][2] == 'c')
{
if (av[i][3] != '\0')
{
OString tmp("'-Gc', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i]) + "'";
}
throw IllegalArgument(tmp);
}
m_options["-Gc"] = OString("");
break;
} else
if (av[i][2] != '\0')
{
OString tmp("'-G', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i]) + "'";
}
throw IllegalArgument(tmp);
}
m_options["-G"] = OString("");
break;
default:
throw IllegalArgument("the option is unknown" + OString(av[i]));
break;
}
} else
{
if (av[i][0] == '@')
{
FILE* cmdFile = fopen(av[i]+1, "r");
if( cmdFile == NULL )
{
fprintf(stderr, "%s", prepareHelp().getStr());
ret = sal_False;
} else
{
int rargc=0;
char* rargv[512];
char buffer[512];
while ( fscanf(cmdFile, "%s", buffer) != EOF )
{
rargv[rargc]= strdup(buffer);
rargc++;
}
fclose(cmdFile);
ret = initOptions(rargc, rargv, bCmdFile);
for (long i=0; i < rargc; i++)
{
free(rargv[i]);
}
}
} else
{
m_inputFiles.push_back(av[i]);
}
}
}
return ret;
}
OString CunoOptions::prepareHelp()
{
OString help("\nusing: ");
help += m_program + " [-options] file_1 ... file_n\nOptions:\n";
help += " -O<path> = path describes the root directory for the generated output.\n";
help += " The output directory tree is generated under this directory.\n";
help += " -T<name> = name specifies a type or a list of types. The output for this\n";
help += " [t1;...] type is generated. If no '-T' option is specified,\n";
help += " then output for all types is generated.\n";
help += " Example: 'com.sun.star.uno.XInterface' is a valid type.\n";
help += " -B<name> = name specifies the base node. All types are searched under this\n";
help += " node. Default is the root '/' of the registry files.\n";
help += " -U = activate the generating of a getCppuType_<name> function.\n";
// help += " -L = getCppuType function with a known leak.\n";
help += " -C = getCppuType_<name> function keeps comprehensive type information.\n";
help += " -G = generate only target files which does not exists.\n";
help += " -Gc = generate only target files which content will be changed.\n";
help += prepareVersion();
return help;
}
OString CunoOptions::prepareVersion()
{
OString version("\nSun Microsystems (R) ");
version += m_program + " Version 1.0\n\n";
return version;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.4.38); FILE MERGED 2008/03/31 07:22:54 rt 1.4.38.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: cunooptions.cxx,v $
* $Revision: 1.5 $
*
* 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_codemaker.hxx"
#include <stdio.h>
#include "cunooptions.hxx"
using namespace rtl;
sal_Bool CunoOptions::initOptions(int ac, char* av[], sal_Bool bCmdFile)
throw( IllegalArgument )
{
sal_Bool ret = sal_True;
sal_uInt16 i=0;
if (!bCmdFile)
{
bCmdFile = sal_True;
m_program = av[0];
if (ac < 2)
{
fprintf(stderr, "%s", prepareHelp().getStr());
ret = sal_False;
}
i = 1;
} else
{
i = 0;
}
char *s=NULL;
for (i; i < ac; i++)
{
if (av[i][0] == '-')
{
switch (av[i][1])
{
case 'O':
if (av[i][2] == 'C')
{
if (av[i][3] == '\0')
{
if (i < ac - 1 && av[i+1][0] != '-')
{
i++;
s = av[i];
} else
{
OString tmp("'-OC', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i+1]) + "'";
}
throw IllegalArgument(tmp);
}
} else
{
s = av[i] + 3;
}
m_options["-OC"] = OString(s);
break;
} else
if (av[i][2] == '\0')
{
if (i < ac - 1 && av[i+1][0] != '-')
{
i++;
s = av[i];
} else
{
OString tmp("'-O', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i+1]) + "'";
}
throw IllegalArgument(tmp);
}
} else
{
s = av[i] + 2;
}
m_options["-O"] = OString(s);
break;
case 'B':
if (av[i][2] == '\0')
{
if (i < ac - 1 && av[i+1][0] != '-')
{
i++;
s = av[i];
} else
{
OString tmp("'-B', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i+1]) + "'";
}
throw IllegalArgument(tmp);
}
} else
{
s = av[i] + 2;
}
m_options["-B"] = OString(s);
break;
case 'T':
if (av[i][2] == '\0')
{
if (i < ac - 1 && av[i+1][0] != '-')
{
i++;
s = av[i];
} else
{
OString tmp("'-T', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i+1]) + "'";
}
throw IllegalArgument(tmp);
}
} else
{
s = av[i] + 2;
}
if (m_options.count("-T") > 0)
{
OString tmp(m_options["-T"]);
tmp = tmp + ";" + s;
m_options["-T"] = tmp;
} else
{
m_options["-T"] = OString(s);
}
break;
case 'U':
if (av[i][2] != '\0')
{
OString tmp("'-U', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i]) + "'";
}
throw IllegalArgument(tmp);
}
m_options["-U"] = OString("");
break;
/*
case 'L':
if (av[i][2] != '\0')
{
OString tmp("'-L', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i]) + "'";
}
throw IllegalArgument(tmp);
}
if (isValid("-C") || isValid("-CS"))
{
OString tmp("'-L' could not be combined with '-C' or '-CS' option");
throw IllegalArgument(tmp);
}
m_options["-L"] = OString("");
break;
*/
case 'C':
if (av[i][2] != '\0')
{
OString tmp("'-C', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i]) + "'";
}
throw IllegalArgument(tmp);
}
if (isValid("-L") || isValid("-CS"))
{
OString tmp("'-C' could not be combined with '-L' or '-CS' option");
throw IllegalArgument(tmp);
}
m_options["-C"] = OString("");
break;
case 'G':
if (av[i][2] == 'c')
{
if (av[i][3] != '\0')
{
OString tmp("'-Gc', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i]) + "'";
}
throw IllegalArgument(tmp);
}
m_options["-Gc"] = OString("");
break;
} else
if (av[i][2] != '\0')
{
OString tmp("'-G', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i]) + "'";
}
throw IllegalArgument(tmp);
}
m_options["-G"] = OString("");
break;
default:
throw IllegalArgument("the option is unknown" + OString(av[i]));
break;
}
} else
{
if (av[i][0] == '@')
{
FILE* cmdFile = fopen(av[i]+1, "r");
if( cmdFile == NULL )
{
fprintf(stderr, "%s", prepareHelp().getStr());
ret = sal_False;
} else
{
int rargc=0;
char* rargv[512];
char buffer[512];
while ( fscanf(cmdFile, "%s", buffer) != EOF )
{
rargv[rargc]= strdup(buffer);
rargc++;
}
fclose(cmdFile);
ret = initOptions(rargc, rargv, bCmdFile);
for (long i=0; i < rargc; i++)
{
free(rargv[i]);
}
}
} else
{
m_inputFiles.push_back(av[i]);
}
}
}
return ret;
}
OString CunoOptions::prepareHelp()
{
OString help("\nusing: ");
help += m_program + " [-options] file_1 ... file_n\nOptions:\n";
help += " -O<path> = path describes the root directory for the generated output.\n";
help += " The output directory tree is generated under this directory.\n";
help += " -T<name> = name specifies a type or a list of types. The output for this\n";
help += " [t1;...] type is generated. If no '-T' option is specified,\n";
help += " then output for all types is generated.\n";
help += " Example: 'com.sun.star.uno.XInterface' is a valid type.\n";
help += " -B<name> = name specifies the base node. All types are searched under this\n";
help += " node. Default is the root '/' of the registry files.\n";
help += " -U = activate the generating of a getCppuType_<name> function.\n";
// help += " -L = getCppuType function with a known leak.\n";
help += " -C = getCppuType_<name> function keeps comprehensive type information.\n";
help += " -G = generate only target files which does not exists.\n";
help += " -Gc = generate only target files which content will be changed.\n";
help += prepareVersion();
return help;
}
OString CunoOptions::prepareVersion()
{
OString version("\nSun Microsystems (R) ");
version += m_program + " Version 1.0\n\n";
return version;
}
<|endoftext|> |
<commit_before>// test.m.cpp
#include "gtest/gtest.h"
int main( int argc, char* argv[] )
{
::testing::InitGoogleTest( &argc, argv );
return RUN_ALL_TESTS();
}<commit_msg>Correct styling issue<commit_after>// test.m.cpp
#include <gtest/gtest.h>
int main( int argc, char* argv[] )
{
::testing::InitGoogleTest( &argc, argv );
return RUN_ALL_TESTS();
}<|endoftext|> |
<commit_before>/*
* File: main.cpp
* Author: ruehle
*
* Created on July 6, 2010, 12:15 PM
*/
#include <stdlib.h>
#include <votca/csg/csgapplication.h>
#include <votca/tools/histogramnew.h>
#include <votca/csg/beadlist.h>
#include <votca/csg/nblist.h>
#include <votca/csg/nblistgrid.h>
//using namespace votca::tools;
using namespace std;
using namespace votca::csg;
class CsgTestApp
: public CsgApplication {
string ProgramName() {
return "template_nblist";
}
void HelpText(ostream &out) {
out << "rough template for rdf calculations";
}
/* why not setting a member variable? */
bool DoThreaded() {
return true;
}
void Initialize();
bool DoTrajectory() {
return true;
}
void BeginEvaluate(Topology *top, Topology *top_ref);
void EndEvaluate();
CsgApplication::Worker *ForkWorker(void);
void MergeWorker(Worker *worker);
protected:
Mutex rdfMutex;
HistogramNew _rdf;
double _cut_off;
};
class RDFWorker
: public CsgApplication::Worker {
public:
/*TODO do we need con/destructor?*/
//RDFWorker();
~RDFWorker();
void EvalConfiguration(Topology *top, Topology *top_ref);
// funktionen implementieren, unter anerem initialize
HistogramNew _rdf;
double _cut_off;
};
int main(int argc, char** argv) {
CsgTestApp app;
return app.Exec(argc, argv);
}
void CsgTestApp::Initialize() {
CsgApplication::Initialize();
AddProgramOptions("RDF options")
("c", boost::program_options::value<double>()->default_value(1.0), "the cutoff");
}
void CsgTestApp::BeginEvaluate(Topology *top, Topology *top_ref) {
_cut_off = OptionsMap()["c"].as<double>();
_rdf.Initialize(0, _cut_off, 50);
}
void CsgTestApp::EndEvaluate() {
_rdf.data().y() = //_avg_vol.getAvg() * iter->second->_norm *
element_div(_rdf.data().y(),
element_prod(_rdf.data().x(), _rdf.data().x())
);
_rdf.data().Save("rdf.dat");
}
CsgApplication::Worker * CsgTestApp::ForkWorker() {
//std::cout << "i am so forking a worker right now" << std::endl;
RDFWorker *worker;
worker = new RDFWorker();
// initializiseren here?
worker->_cut_off = OptionsMap()["c"].as<double>();
worker->_rdf.Initialize(0, worker->_cut_off, 50);
return worker; // evtl cast
//i->_norm = 1. / (4. * M_PI * i->_step * beads1.size()*(beads2.size() - 1.) / 2.);
}
void CsgTestApp::MergeWorker(Worker *worker) {
RDFWorker * myRDFWorker;
myRDFWorker = dynamic_cast<RDFWorker*> (worker);
rdfMutex.Lock();
_rdf.data().y() = _rdf.data().y() + myRDFWorker->_rdf.data().y();
// for (int i=0; i<myRDFWorker->_rdf.data().size(); i++)
// std::cout << myRDFWorker->_rdf.data().x(i) << std::endl;
rdfMutex.Unlock();
}
RDFWorker::~RDFWorker(void) {
}
void RDFWorker::EvalConfiguration(Topology *top, Topology *top_ref) {
//std::cout << "I am so hard working! worker id: " << getId() << ", frame nr: " << top->getStep() << std::endl;
// << ", topology copy addr: " << top << std::endl;
// sleep(rand()%3);
BeadList b;
b.Generate(*top, "*");
NBListGrid nb;
nb.setCutoff(_cut_off);
nb.Generate(b);
NBList::iterator i;
for (i = nb.begin(); i != nb.end(); ++i) {
_rdf.Process((*i)->dist());
}
//std::cout << " " << _rdf. << std::endl;
// _rdf.y() = _rdf.y() + worker.rdf.data().y() // so ungefaehr
}<commit_msg>this commit is less than useless but it might help checking out the review tools here we go...<commit_after>/*
* File: main.cpp
* Author: ruehle
*
* Created on July 6, 2010, 12:15 PM
*/
#include <stdlib.h>
#include <votca/csg/csgapplication.h>
#include <votca/tools/histogramnew.h>
#include <votca/csg/beadlist.h>
#include <votca/csg/nblist.h>
#include <votca/csg/nblistgrid.h>
//using namespace votca::tools;
using namespace std;
using namespace votca::csg;
class CsgTestApp
: public CsgApplication {
string ProgramName() {
return "template_nblist";
}
void HelpText(ostream &out) {
out << "rough template for rdf calculations";
}
/* why not setting a member variable? */
bool DoThreaded() {
return true;
}
void Initialize();
bool DoTrajectory() {
return true;
}
void BeginEvaluate(Topology *top, Topology *top_ref);
void EndEvaluate();
CsgApplication::Worker *ForkWorker(void);
void MergeWorker(Worker *worker);
protected:
Mutex rdfMutex;
HistogramNew _rdf;
double _cut_off;
};
class RDFWorker
: public CsgApplication::Worker {
public:
/*TODO do we need con/destructor?*/
//RDFWorker();
~RDFWorker();
void EvalConfiguration(Topology *top, Topology *top_ref);
// funktionen implementieren, unter anerem initialize
HistogramNew _rdf;
double _cut_off;
};
int main(int argc, char** argv) {
CsgTestApp app;
return app.Exec(argc, argv);
}
void CsgTestApp::Initialize() {
CsgApplication::Initialize();
AddProgramOptions("RDF options")
("c", boost::program_options::value<double>()->default_value(1.0), "the cutoff");
}
void CsgTestApp::BeginEvaluate(Topology *top, Topology *top_ref) {
_cut_off = OptionsMap()["c"].as<double>();
_rdf.Initialize(0, _cut_off, 50);
}
void CsgTestApp::EndEvaluate() {
_rdf.data().y() = //_avg_vol.getAvg() * iter->second->_norm *
element_div(_rdf.data().y(),
element_prod(_rdf.data().x(), _rdf.data().x())
);
_rdf.data().Save("rdf.dat");
}
CsgApplication::Worker * CsgTestApp::ForkWorker() {
//std::cout << "i am so forking a worker right now" << std::endl;
RDFWorker *worker;
worker = new RDFWorker();
// initializiseren here?
worker->_cut_off = OptionsMap()["c"].as<double>();
worker->_rdf.Initialize(0, worker->_cut_off, 50);
return worker; // evtl cast
//i->_norm = 1. / (4. * M_PI * i->_step * beads1.size()*(beads2.size() - 1.) / 2.);
}
void CsgTestApp::MergeWorker(Worker *worker) {
RDFWorker * myRDFWorker;
myRDFWorker = dynamic_cast<RDFWorker*> (worker);
rdfMutex.Lock();
_rdf.data().y() = _rdf.data().y() + myRDFWorker->_rdf.data().y();
// for (int i=0; i<myRDFWorker->_rdf.data().size(); i++)
// std::cout << myRDFWorker->_rdf.data().x(i) << std::endl;
rdfMutex.Unlock();
}
RDFWorker::~RDFWorker(void) {
//review me!
}
void RDFWorker::EvalConfiguration(Topology *top, Topology *top_ref) {
//std::cout << "I am so hard working! worker id: " << getId() << ", frame nr: " << top->getStep() << std::endl;
// << ", topology copy addr: " << top << std::endl;
// sleep(rand()%3);
BeadList b;
b.Generate(*top, "*");
NBListGrid nb;
nb.setCutoff(_cut_off);
nb.Generate(b);
NBList::iterator i;
for (i = nb.begin(); i != nb.end(); ++i) {
_rdf.Process((*i)->dist());
}
//std::cout << " " << _rdf. << std::endl;
// _rdf.y() = _rdf.y() + worker.rdf.data().y() // so ungefaehr
}<|endoftext|> |
<commit_before>/**
* @file
*
* @brief
*
* @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*/
#include "ansicolors.hpp"
#ifdef _WIN32
#include <stdio.h>
#undef STDERR_FILENO
#undef STDOUT_FILENO
#define STDERR_FILENO _fileno (stderr)
#define STDOUT_FILENO _fileno (stdout)
#else
#include <unistd.h>
#endif
std::string & colors ()
{
static std::string nocolors = "auto";
return nocolors;
}
std::string getColorEscape (ANSI_COLOR color, ANSI_COLOR_LAYER layer)
{
if (color == ANSI_COLOR::RESET) return "\x1b[0m";
if (color == ANSI_COLOR::BOLD) return "\x1b[1m";
if (color == ANSI_COLOR::UNDERSCORE) return "\x1b[4m";
if (layer == ANSI_COLOR_LAYER::FG)
{
switch (color)
{
case ANSI_COLOR::BLACK:
return "\x1b[30m";
break;
case ANSI_COLOR::RED:
return "\x1b[31m";
break;
case ANSI_COLOR::GREEN:
return "\x1b[32m";
break;
case ANSI_COLOR::YELLOW:
return "\x1b[33m";
break;
case ANSI_COLOR::BLUE:
return "\x1b[34m";
break;
case ANSI_COLOR::MAGENTA:
return "\x1b[35m";
break;
case ANSI_COLOR::CYAN:
return "\x1b[36m";
break;
case ANSI_COLOR::WHITE:
return "\x1b[37m";
break;
default:
return "";
}
}
else
{
switch (color)
{
case ANSI_COLOR::BLACK:
return "\x1b[40m";
break;
case ANSI_COLOR::RED:
return "\x1b[41m";
break;
case ANSI_COLOR::GREEN:
return "\x1b[42m";
break;
case ANSI_COLOR::YELLOW:
return "\x1b[43m";
break;
case ANSI_COLOR::BLUE:
return "\x1b[44m";
break;
case ANSI_COLOR::MAGENTA:
return "\x1b[45m";
break;
case ANSI_COLOR::CYAN:
return "\x1b[46m";
break;
case ANSI_COLOR::WHITE:
return "\x1b[47m";
break;
default:
return "";
}
}
}
std::string getErrorColor (ANSI_COLOR color, ANSI_COLOR_LAYER layer)
{
if (colors ().compare ("never") == 0 || (colors ().compare ("auto") == 0 && !isatty (STDERR_FILENO))) return "";
return getColorEscape (color, layer);
}
std::string getStdColor (ANSI_COLOR color, ANSI_COLOR_LAYER layer)
{
if (colors ().compare ("never") == 0 || (colors ().compare ("auto") == 0 && !isatty (STDOUT_FILENO))) return "";
return getColorEscape (color, layer);
}
#ifdef _WIN32
#undef STDERR_FILENO
#undef STDOUT_FILENO
#endif
<commit_msg>include io.h in ansicolors.hpp for WIN32<commit_after>/**
* @file
*
* @brief
*
* @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*/
#include "ansicolors.hpp"
#ifdef _WIN32
#include <stdio.h>
#include <io.h>
#undef STDERR_FILENO
#undef STDOUT_FILENO
#define STDERR_FILENO _fileno (stderr)
#define STDOUT_FILENO _fileno (stdout)
#define isatty _isatty
#else
#include <unistd.h>
#endif
std::string & colors ()
{
static std::string nocolors = "auto";
return nocolors;
}
std::string getColorEscape (ANSI_COLOR color, ANSI_COLOR_LAYER layer)
{
if (color == ANSI_COLOR::RESET) return "\x1b[0m";
if (color == ANSI_COLOR::BOLD) return "\x1b[1m";
if (color == ANSI_COLOR::UNDERSCORE) return "\x1b[4m";
if (layer == ANSI_COLOR_LAYER::FG)
{
switch (color)
{
case ANSI_COLOR::BLACK:
return "\x1b[30m";
break;
case ANSI_COLOR::RED:
return "\x1b[31m";
break;
case ANSI_COLOR::GREEN:
return "\x1b[32m";
break;
case ANSI_COLOR::YELLOW:
return "\x1b[33m";
break;
case ANSI_COLOR::BLUE:
return "\x1b[34m";
break;
case ANSI_COLOR::MAGENTA:
return "\x1b[35m";
break;
case ANSI_COLOR::CYAN:
return "\x1b[36m";
break;
case ANSI_COLOR::WHITE:
return "\x1b[37m";
break;
default:
return "";
}
}
else
{
switch (color)
{
case ANSI_COLOR::BLACK:
return "\x1b[40m";
break;
case ANSI_COLOR::RED:
return "\x1b[41m";
break;
case ANSI_COLOR::GREEN:
return "\x1b[42m";
break;
case ANSI_COLOR::YELLOW:
return "\x1b[43m";
break;
case ANSI_COLOR::BLUE:
return "\x1b[44m";
break;
case ANSI_COLOR::MAGENTA:
return "\x1b[45m";
break;
case ANSI_COLOR::CYAN:
return "\x1b[46m";
break;
case ANSI_COLOR::WHITE:
return "\x1b[47m";
break;
default:
return "";
}
}
}
std::string getErrorColor (ANSI_COLOR color, ANSI_COLOR_LAYER layer)
{
if (colors ().compare ("never") == 0 || (colors ().compare ("auto") == 0 && !isatty (STDERR_FILENO))) return "";
return getColorEscape (color, layer);
}
std::string getStdColor (ANSI_COLOR color, ANSI_COLOR_LAYER layer)
{
if (colors ().compare ("never") == 0 || (colors ().compare ("auto") == 0 && !isatty (STDOUT_FILENO))) return "";
return getColorEscape (color, layer);
}
#ifdef _WIN32
#undef isatty
#undef STDERR_FILENO
#undef STDOUT_FILENO
#endif
<|endoftext|> |
<commit_before>// Author: Guilherme Amadio, Enrico Guiraud, Danilo Piparo CERN 2/2018
/*************************************************************************
* Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_RSNAPSHOTOPTIONS
#define ROOT_RSNAPSHOTOPTIONS
#include <Compression.h>
#include <ROOT/RStringView.hxx>
#include <string>
namespace ROOT {
namespace RDF {
/// A collection of options to steer the creation of the dataset on file
struct RSnapshotOptions {
using ECAlgo = ::ROOT::ECompressionAlgorithm;
RSnapshotOptions() = default;
RSnapshotOptions(const RSnapshotOptions &) = default;
RSnapshotOptions(RSnapshotOptions &&) = default;
RSnapshotOptions(std::string_view mode, ECAlgo comprAlgo, int comprLevel, int autoFlush, int splitLevel, bool lazy)
: fMode(mode), fCompressionAlgorithm(comprAlgo), fCompressionLevel{comprLevel}, fAutoFlush(autoFlush),
fSplitLevel(splitLevel), fLazy(lazy)
{
}
std::string fMode = "RECREATE"; //< Mode of creation of output file
ECAlgo fCompressionAlgorithm = ROOT::kZLIB; //< Compression algorithm of output file
int fCompressionLevel = 1; //< Compression level of output file
int fAutoFlush = 0; //< AutoFlush value for output tree
int fSplitLevel = 99; //< Split level of output tree
bool fLazy = false; //< Delay the snapshot of the dataset
};
} // ns RDF
} // ns ROOT
#endif
<commit_msg>Fix doxygen syntax for RSnapshotOptions<commit_after>// Author: Guilherme Amadio, Enrico Guiraud, Danilo Piparo CERN 2/2018
/*************************************************************************
* Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_RSNAPSHOTOPTIONS
#define ROOT_RSNAPSHOTOPTIONS
#include <Compression.h>
#include <ROOT/RStringView.hxx>
#include <string>
namespace ROOT {
namespace RDF {
/// A collection of options to steer the creation of the dataset on file
struct RSnapshotOptions {
using ECAlgo = ::ROOT::ECompressionAlgorithm;
RSnapshotOptions() = default;
RSnapshotOptions(const RSnapshotOptions &) = default;
RSnapshotOptions(RSnapshotOptions &&) = default;
RSnapshotOptions(std::string_view mode, ECAlgo comprAlgo, int comprLevel, int autoFlush, int splitLevel, bool lazy)
: fMode(mode), fCompressionAlgorithm(comprAlgo), fCompressionLevel{comprLevel}, fAutoFlush(autoFlush),
fSplitLevel(splitLevel), fLazy(lazy)
{
}
std::string fMode = "RECREATE"; ///< Mode of creation of output file
ECAlgo fCompressionAlgorithm = ROOT::kZLIB; ///< Compression algorithm of output file
int fCompressionLevel = 1; ///< Compression level of output file
int fAutoFlush = 0; ///< AutoFlush value for output tree
int fSplitLevel = 99; ///< Split level of output tree
bool fLazy = false; ///< Delay the snapshot of the dataset
};
} // ns RDF
} // ns ROOT
#endif
<|endoftext|> |
<commit_before>#include "world_rc1.h"
#include "galaxy_gen.h"
#include "player_controller.h"
#include "lightning_effect.h"
#include "badger/math/random.h"
#include "pathos/render/sky_ansel.h"
#include "pathos/loader/imageloader.h"
#include "pathos/render/irradiance_baker.h"
#include "pathos/mesh/static_mesh_actor.h"
#include "pathos/mesh/mesh.h"
#include "pathos/mesh/geometry_primitive.h"
#include "pathos/mesh/geometry_procedural.h"
#include "pathos/light/directional_light_actor.h"
#include "pathos/input/input_manager.h"
const vector3 SUN_DIRECTION = glm::normalize(vector3(0.0f, -1.0f, 0.0f));
const vector3 SUN_RADIANCE = 20.0f * vector3(1.0f, 1.0f, 1.0f);
void World_RC1::onInitialize()
{
playerController = spawnActor<PlayerController>();
setupSky();
setupScene();
ButtonBinding updateSky;
updateSky.addInput(InputConstants::KEYBOARD_R);
InputManager* inputManager = gEngine->getInputSystem()->getDefaultInputManager();
inputManager->bindButtonPressed("updateSky", updateSky, [this]()
{
updateStarfield();
}
);
}
void World_RC1::onTick(float deltaSeconds)
{
vector3 ringRotations[6] = {
vector3(25.0f, 12.0f, 25.0f),
vector3(20.0f, -10.0f, 20.0f),
vector3(-17.0f, 12.0f, 15.0f),
vector3(14.0f, 17.0f, 7.0f),
vector3(-5.0f, -8.0f, 4.0f),
vector3(-3.0f, -2.5f, 2.0f),
};
for (uint32 i = 0; i < (uint32)rings.size(); ++i) {
RingActor* ring = rings[i];
Rotator rot = ring->getActorRotation();
rot.pitch += ringRotations[i].x * deltaSeconds;
rot.yaw += ringRotations[i].y * deltaSeconds;
rot.roll += ringRotations[i].z * deltaSeconds;
ring->setActorRotation(rot);
}
auto& components = lightningSphere->getParticleComponents();
for (uint32 i = 0; i < (uint32)components.size(); ++i) {
components[i]->setRotation(rings[ringIndicesForParticleRotation[i]]->getActorRotation());
}
}
void World_RC1::setupSky()
{
GalaxyGenerator::createStarField(starfield, 2048, 1024);
glObjectLabel(GL_TEXTURE, starfield, -1, "Texture: Starfield");
GLuint cubemapForIBL = IrradianceBaker::bakeCubemap(starfield, 512);
glObjectLabel(GL_TEXTURE, cubemapForIBL, -1, "Texture IBL: cubemapForIBL");
// diffuse irradiance
GLuint irradianceMap = IrradianceBaker::bakeIrradianceMap(cubemapForIBL, 32, false);
glObjectLabel(GL_TEXTURE, irradianceMap, -1, "Texture IBL: diffuse irradiance");
scene.irradianceMap = irradianceMap;
// specular IBL
GLuint prefilteredEnvMap;
uint32 mipLevels;
IrradianceBaker::bakePrefilteredEnvMap(cubemapForIBL, 128, prefilteredEnvMap, mipLevels);
glObjectLabel(GL_TEXTURE, prefilteredEnvMap, -1, "Texture IBL: specular IBL (prefiltered env map)");
scene.prefilterEnvMap = prefilteredEnvMap;
scene.prefilterEnvMapMipLevels = mipLevels;
scene.sky = new AnselSkyRendering(starfield);
}
void World_RC1::setupScene()
{
//////////////////////////////////////////////////////////////////////////
// Light
DirectionalLightActor* dirLight = spawnActor<DirectionalLightActor>();
dirLight->setLightParameters(SUN_DIRECTION, SUN_RADIANCE);
//////////////////////////////////////////////////////////////////////////
auto geom_sphere = new SphereGeometry(5.0f, 30);
geom_sphere->calculateTangentBasis();
auto material_color = new ColorMaterial;
{
auto color = static_cast<ColorMaterial*>(material_color);
color->setAlbedo(2.0f, 0.2f, 0.2f);
color->setMetallic(0.2f);
color->setRoughness(0.1f);
}
PBRTextureMaterial* material_pbr;
{
constexpr bool genMipmap = true;
constexpr bool sRGB = true;
GLuint albedo = pathos::createTextureFromBitmap(loadImage("resources/render_challenge_1/T_Brick.png"), genMipmap, sRGB);
GLuint normal = pathos::createTextureFromBitmap(loadImage("resources/render_challenge_1/N_Brick.png"), genMipmap, !sRGB);
GLuint metallic = pathos::createTextureFromBitmap(loadImage("resources/render_challenge_1/M_Brick.png"), genMipmap, !sRGB);
GLuint roughness = pathos::createTextureFromBitmap(loadImage("resources/render_challenge_1/R_Brick.png"), genMipmap, !sRGB);
GLuint ao = pathos::createTextureFromBitmap(loadImage("resources/render_challenge_1/A_Brick.png"), genMipmap, !sRGB);
material_pbr = new PBRTextureMaterial(albedo, normal, metallic, roughness, ao);
}
//////////////////////////////////////////////////////////////////////////
// Objects
lightningSphere = spawnActor<LightningActor>();
lightningSphere->setActorScale(40.0f);
constexpr uint32 numRings = 6;
const float ring_gap = 40.0f;
const float ring_width = 100.0f;
const float ring_thickness = 50.0f;
float innerRadius = 150.0f;
float outerRadius = innerRadius + ring_width;
std::vector<std::vector<float>> ringSegRanges = {
{0.0f, 280.0f},
{30.0f, 120.0f, 140.0f, 310.0f},
{150.0f, 260.0f},
{50.0f, 180.0f, 250.0f, 300.0f},
{0.0f, 100.0f, 120.0f, 200.0f, 220.0f, 320.0f},
{0.0f, 70.0f, 90.0f, 260.0f},
};
for (uint32 i = 0; i < numRings; ++i) {
auto ring = spawnActor<RingActor>();
ring->buildRing(innerRadius, outerRadius, ring_thickness + (i * 20.0f), ringSegRanges[i]);
innerRadius = outerRadius + ring_gap;
outerRadius = innerRadius + (ring_width + i * 50.0f);
rings.push_back(ring);
ring->getStaticMesh()->setMaterial(0, material_pbr);
}
const uint32 numParticles = 10;
for (uint32 i = 0; i < numParticles; ++i) {
uint32 ringIx = (uint32)(numRings * Random());
RingActor* ring = rings[ringIx];
lightningSphere->generateParticle(vector3(0.0f), ring->getRandomInnerPosition());
ringIndicesForParticleRotation.push_back(ringIx);
}
//StaticMeshActor* godRaySource = spawnActor<StaticMeshActor>();
//godRaySource->setStaticMesh(new Mesh(geom_sphere, material_color));
//godRaySource->setActorScale(20.0f);
//godRaySource->setActorLocation(vector3(0.0f, 300.0f, -5500.0f));
//godRaySource->getStaticMeshComponent()->castsShadow = false;
//getScene().godRaySource = godRaySource->getStaticMeshComponent();
}
void World_RC1::updateStarfield()
{
gEngine->execute("recompile_shaders");
GalaxyGenerator::createStarField(starfield, 2048, 1024);
}
//////////////////////////////////////////////////////////////////////////
RingActor::RingActor()
{
G = new ProceduralGeometry;
M = new ColorMaterial;
M->setAlbedo(1.8f, 1.8f, 1.8f);
M->setRoughness(1.0f);
M->setMetallic(0.0f);
setStaticMesh(new Mesh(G, M));
}
void RingActor::buildRing(float innerRadius, float outerRadius, float thickness, const std::vector<float>& segmentRanges)
{
G->clear();
innerVertexIndices.clear();
static const float defaultRange[] = { 0.0f, 360.0f };
const float* segRanges = segmentRanges.size() == 0 ? defaultRange : segmentRanges.data();
const uint32 numSegments = segmentRanges.size() == 0 ? 1 : (uint32)segmentRanges.size() / 2;
constexpr uint32 numSubdivisions = 60;
constexpr auto n = numSubdivisions;
std::vector<vector3> positions(numSegments * n * 4);
std::vector<vector2> uvs(numSegments * n * 4);
std::vector<uint32> indices;
indices.reserve(numSegments * n * 24);
innerVertexIndices.reserve(positions.size() / 2);
uint32 i0 = 0;
for(uint32 segmentIndex = 0; segmentIndex < numSegments; ++segmentIndex) {
const float dz = thickness * 0.5f;
const float startAngle = glm::radians(segRanges[segmentIndex * 2]);
const float endAngle = glm::radians(segRanges[segmentIndex * 2 + 1]);
// clockwise
auto makeQuad = [&indices](uint32 a, uint32 b, uint32 c, uint32 d) {
indices.push_back(a); indices.push_back(b); indices.push_back(d);
indices.push_back(b); indices.push_back(c); indices.push_back(d);
};
for (uint32 i = i0; i < i0 + n; ++i)
{
const float ratio = (float)(i - i0) / (n - 1);
float angle = startAngle + (endAngle - startAngle) * ratio;
float cosAngle = cosf(angle);
float sinAngle = sinf(angle);
innerVertexIndices.push_back(i);
innerVertexIndices.push_back(i + 2 * n);
positions[i] = vector3(innerRadius * cosAngle, innerRadius * sinAngle, +dz);
positions[i + n] = vector3(outerRadius * cosAngle, outerRadius * sinAngle, +dz);
positions[i + 2 * n] = vector3(innerRadius * cosAngle, innerRadius * sinAngle, -dz);
positions[i + 3 * n] = vector3(outerRadius * cosAngle, outerRadius * sinAngle, -dz);
uvs[i] = vector2(ratio, 0.0f);
uvs[i + n] = vector2(ratio, 0.25f);
uvs[i + 2 * n] = vector2(ratio, 0.5f);
uvs[i + 3 * n] = vector2(ratio, 1.0f);
if (i - i0 != n - 1) {
makeQuad(i, i + n, i + n + 1, i + 1); // front
makeQuad(2 * n + i, 2 * n + i + 1, 2 * n + i + n + 1, 2 * n + i + n); // back
makeQuad(i, i + 1, i + 2 * n + 1, i + 2 * n); // inner
makeQuad(i + n, 2 * n + i + n, 2 * n + i + n + 1, i + n + 1); // outer
} else {
//makeQuad(i, i + n, i + 1, i + 1 - n);
//makeQuad(2 * n + i, 2 * n + i + 1 - n, 2 * n + i + 1, 2 * n + i + n);
//makeQuad(i, i + 1 - n, i + 1 + n, i + 2 * n);
//makeQuad(i + n, i + 3 * n, i + 2 * n + 1, i + 1);
}
}
makeQuad(i0, i0 + 2 * n, i0 + 3 * n, i0 + n);
makeQuad(n - 1 + i0, n - 1 + i0 + n, n - 1 + i0 + 3 * n, n - 1 + i0 + 2 * n);
i0 += n * 4;
}
G->updatePositionData((float*)positions.data(), (uint32)(positions.size() * 3));
G->updateUVData((float*)uvs.data(), (uint32)(uvs.size() * 2));
G->updateIndexData(indices.data(), (uint32)indices.size());
G->calculateNormals();
G->calculateTangentBasis();
}
vector3 RingActor::getRandomInnerPosition() const
{
uint32 ix = (uint32)(innerVertexIndices.size() * Random());
return G->getPosition(innerVertexIndices[ix]);
}
<commit_msg>Add a point light for the lightball and reduce sun radiance<commit_after>#include "world_rc1.h"
#include "galaxy_gen.h"
#include "player_controller.h"
#include "lightning_effect.h"
#include "badger/math/random.h"
#include "pathos/render/sky_ansel.h"
#include "pathos/loader/imageloader.h"
#include "pathos/render/irradiance_baker.h"
#include "pathos/mesh/static_mesh_actor.h"
#include "pathos/mesh/mesh.h"
#include "pathos/mesh/geometry_primitive.h"
#include "pathos/mesh/geometry_procedural.h"
#include "pathos/light/directional_light_actor.h"
#include "pathos/light/point_light_actor.h"
#include "pathos/input/input_manager.h"
const vector3 SUN_DIRECTION = glm::normalize(vector3(0.0f, -1.0f, 0.0f));
const vector3 SUN_RADIANCE = 1.0f * vector3(1.0f, 1.0f, 1.0f);
void World_RC1::onInitialize()
{
playerController = spawnActor<PlayerController>();
setupSky();
setupScene();
ButtonBinding updateSky;
updateSky.addInput(InputConstants::KEYBOARD_R);
InputManager* inputManager = gEngine->getInputSystem()->getDefaultInputManager();
inputManager->bindButtonPressed("updateSky", updateSky, [this]()
{
updateStarfield();
}
);
}
void World_RC1::onTick(float deltaSeconds)
{
vector3 ringRotations[6] = {
vector3(25.0f, 12.0f, 25.0f),
vector3(20.0f, -10.0f, 20.0f),
vector3(-17.0f, 12.0f, 15.0f),
vector3(14.0f, 17.0f, 7.0f),
vector3(-5.0f, -8.0f, 4.0f),
vector3(-3.0f, -2.5f, 2.0f),
};
for (uint32 i = 0; i < (uint32)rings.size(); ++i) {
RingActor* ring = rings[i];
Rotator rot = ring->getActorRotation();
rot.pitch += ringRotations[i].x * deltaSeconds;
rot.yaw += ringRotations[i].y * deltaSeconds;
rot.roll += ringRotations[i].z * deltaSeconds;
ring->setActorRotation(rot);
}
auto& components = lightningSphere->getParticleComponents();
for (uint32 i = 0; i < (uint32)components.size(); ++i) {
components[i]->setRotation(rings[ringIndicesForParticleRotation[i]]->getActorRotation());
}
}
void World_RC1::setupSky()
{
GalaxyGenerator::createStarField(starfield, 2048, 1024);
glObjectLabel(GL_TEXTURE, starfield, -1, "Texture: Starfield");
GLuint cubemapForIBL = IrradianceBaker::bakeCubemap(starfield, 512);
glObjectLabel(GL_TEXTURE, cubemapForIBL, -1, "Texture IBL: cubemapForIBL");
// diffuse irradiance
GLuint irradianceMap = IrradianceBaker::bakeIrradianceMap(cubemapForIBL, 32, false);
glObjectLabel(GL_TEXTURE, irradianceMap, -1, "Texture IBL: diffuse irradiance");
scene.irradianceMap = irradianceMap;
// specular IBL
GLuint prefilteredEnvMap;
uint32 mipLevels;
IrradianceBaker::bakePrefilteredEnvMap(cubemapForIBL, 128, prefilteredEnvMap, mipLevels);
glObjectLabel(GL_TEXTURE, prefilteredEnvMap, -1, "Texture IBL: specular IBL (prefiltered env map)");
scene.prefilterEnvMap = prefilteredEnvMap;
scene.prefilterEnvMapMipLevels = mipLevels;
scene.sky = new AnselSkyRendering(starfield);
}
void World_RC1::setupScene()
{
//////////////////////////////////////////////////////////////////////////
// Light
DirectionalLightActor* dirLight = spawnActor<DirectionalLightActor>();
dirLight->setLightParameters(SUN_DIRECTION, SUN_RADIANCE);
PointLightActor* pLight = spawnActor<PointLightActor>();
pLight->setLightParameters(5000.0f * vector3(1.0f, 1.0f, 1.0f), 10000.0f);
//////////////////////////////////////////////////////////////////////////
auto geom_sphere = new SphereGeometry(5.0f, 30);
geom_sphere->calculateTangentBasis();
auto material_color = new ColorMaterial;
{
auto color = static_cast<ColorMaterial*>(material_color);
color->setAlbedo(2.0f, 0.2f, 0.2f);
color->setMetallic(0.2f);
color->setRoughness(0.1f);
}
PBRTextureMaterial* material_pbr;
{
constexpr bool genMipmap = true;
constexpr bool sRGB = true;
GLuint albedo = pathos::createTextureFromBitmap(loadImage("resources/render_challenge_1/T_Brick.png"), genMipmap, sRGB);
GLuint normal = pathos::createTextureFromBitmap(loadImage("resources/render_challenge_1/N_Brick.png"), genMipmap, !sRGB);
GLuint metallic = pathos::createTextureFromBitmap(loadImage("resources/render_challenge_1/M_Brick.png"), genMipmap, !sRGB);
GLuint roughness = pathos::createTextureFromBitmap(loadImage("resources/render_challenge_1/R_Brick.png"), genMipmap, !sRGB);
GLuint ao = pathos::createTextureFromBitmap(loadImage("resources/render_challenge_1/A_Brick.png"), genMipmap, !sRGB);
material_pbr = new PBRTextureMaterial(albedo, normal, metallic, roughness, ao);
}
//////////////////////////////////////////////////////////////////////////
// Objects
lightningSphere = spawnActor<LightningActor>();
lightningSphere->setActorScale(40.0f);
constexpr uint32 numRings = 6;
const float ring_gap = 40.0f;
const float ring_width = 100.0f;
const float ring_thickness = 50.0f;
float innerRadius = 150.0f;
float outerRadius = innerRadius + ring_width;
std::vector<std::vector<float>> ringSegRanges = {
{0.0f, 280.0f},
{30.0f, 120.0f, 140.0f, 310.0f},
{150.0f, 260.0f},
{50.0f, 180.0f, 250.0f, 300.0f},
{0.0f, 100.0f, 120.0f, 200.0f, 220.0f, 320.0f},
{0.0f, 70.0f, 90.0f, 260.0f},
};
for (uint32 i = 0; i < numRings; ++i) {
auto ring = spawnActor<RingActor>();
ring->buildRing(innerRadius, outerRadius, ring_thickness + (i * 20.0f), ringSegRanges[i]);
innerRadius = outerRadius + ring_gap;
outerRadius = innerRadius + (ring_width + i * 50.0f);
rings.push_back(ring);
ring->getStaticMesh()->setMaterial(0, material_pbr);
}
const uint32 numParticles = 10;
for (uint32 i = 0; i < numParticles; ++i) {
uint32 ringIx = (uint32)(numRings * Random());
RingActor* ring = rings[ringIx];
lightningSphere->generateParticle(vector3(0.0f), ring->getRandomInnerPosition());
ringIndicesForParticleRotation.push_back(ringIx);
}
//StaticMeshActor* godRaySource = spawnActor<StaticMeshActor>();
//godRaySource->setStaticMesh(new Mesh(geom_sphere, material_color));
//godRaySource->setActorScale(20.0f);
//godRaySource->setActorLocation(vector3(0.0f, 300.0f, -5500.0f));
//godRaySource->getStaticMeshComponent()->castsShadow = false;
//getScene().godRaySource = godRaySource->getStaticMeshComponent();
}
void World_RC1::updateStarfield()
{
gEngine->execute("recompile_shaders");
GalaxyGenerator::createStarField(starfield, 2048, 1024);
}
//////////////////////////////////////////////////////////////////////////
RingActor::RingActor()
{
G = new ProceduralGeometry;
M = new ColorMaterial;
M->setAlbedo(1.8f, 1.8f, 1.8f);
M->setRoughness(1.0f);
M->setMetallic(0.0f);
setStaticMesh(new Mesh(G, M));
}
void RingActor::buildRing(float innerRadius, float outerRadius, float thickness, const std::vector<float>& segmentRanges)
{
G->clear();
innerVertexIndices.clear();
static const float defaultRange[] = { 0.0f, 360.0f };
const float* segRanges = segmentRanges.size() == 0 ? defaultRange : segmentRanges.data();
const uint32 numSegments = segmentRanges.size() == 0 ? 1 : (uint32)segmentRanges.size() / 2;
constexpr uint32 numSubdivisions = 60;
constexpr auto n = numSubdivisions;
std::vector<vector3> positions(numSegments * n * 4);
std::vector<vector2> uvs(numSegments * n * 4);
std::vector<uint32> indices;
indices.reserve(numSegments * n * 24);
innerVertexIndices.reserve(positions.size() / 2);
uint32 i0 = 0;
for(uint32 segmentIndex = 0; segmentIndex < numSegments; ++segmentIndex) {
const float dz = thickness * 0.5f;
const float startAngle = glm::radians(segRanges[segmentIndex * 2]);
const float endAngle = glm::radians(segRanges[segmentIndex * 2 + 1]);
// clockwise
auto makeQuad = [&indices](uint32 a, uint32 b, uint32 c, uint32 d) {
indices.push_back(a); indices.push_back(b); indices.push_back(d);
indices.push_back(b); indices.push_back(c); indices.push_back(d);
};
for (uint32 i = i0; i < i0 + n; ++i)
{
const float ratio = (float)(i - i0) / (n - 1);
float angle = startAngle + (endAngle - startAngle) * ratio;
float cosAngle = cosf(angle);
float sinAngle = sinf(angle);
innerVertexIndices.push_back(i);
innerVertexIndices.push_back(i + 2 * n);
positions[i] = vector3(innerRadius * cosAngle, innerRadius * sinAngle, +dz);
positions[i + n] = vector3(outerRadius * cosAngle, outerRadius * sinAngle, +dz);
positions[i + 2 * n] = vector3(innerRadius * cosAngle, innerRadius * sinAngle, -dz);
positions[i + 3 * n] = vector3(outerRadius * cosAngle, outerRadius * sinAngle, -dz);
uvs[i] = vector2(ratio, 0.0f);
uvs[i + n] = vector2(ratio, 0.25f);
uvs[i + 2 * n] = vector2(ratio, 0.5f);
uvs[i + 3 * n] = vector2(ratio, 1.0f);
if (i - i0 != n - 1) {
makeQuad(i, i + n, i + n + 1, i + 1); // front
makeQuad(2 * n + i, 2 * n + i + 1, 2 * n + i + n + 1, 2 * n + i + n); // back
makeQuad(i, i + 1, i + 2 * n + 1, i + 2 * n); // inner
makeQuad(i + n, 2 * n + i + n, 2 * n + i + n + 1, i + n + 1); // outer
} else {
//makeQuad(i, i + n, i + 1, i + 1 - n);
//makeQuad(2 * n + i, 2 * n + i + 1 - n, 2 * n + i + 1, 2 * n + i + n);
//makeQuad(i, i + 1 - n, i + 1 + n, i + 2 * n);
//makeQuad(i + n, i + 3 * n, i + 2 * n + 1, i + 1);
}
}
makeQuad(i0, i0 + 2 * n, i0 + 3 * n, i0 + n);
makeQuad(n - 1 + i0, n - 1 + i0 + n, n - 1 + i0 + 3 * n, n - 1 + i0 + 2 * n);
i0 += n * 4;
}
G->updatePositionData((float*)positions.data(), (uint32)(positions.size() * 3));
G->updateUVData((float*)uvs.data(), (uint32)(uvs.size() * 2));
G->updateIndexData(indices.data(), (uint32)indices.size());
G->calculateNormals();
G->calculateTangentBasis();
}
vector3 RingActor::getRandomInnerPosition() const
{
uint32 ix = (uint32)(innerVertexIndices.size() * Random());
return G->getPosition(innerVertexIndices[ix]);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.