text stringlengths 54 60.6k |
|---|
<commit_before><commit_msg>Report status message when stats export fails. (#83)<commit_after><|endoftext|> |
<commit_before>#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
ui->payTo->setPlaceholderText(tr("Enter a Blakecoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
ui->addAsLabel->setText(associatedLabel);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));
clear();
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
// update the display unit, to not use the default ("BLC")
updateDisplayUnit();
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
<commit_msg>slight cosmetic correction<commit_after>#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
ui->payTo->setPlaceholderText(tr("Enter a Blakecoin address (e.g. BjUDfqowhrCzmNQfQLHHB6S2FFccGTA1ur)"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
ui->addAsLabel->setText(associatedLabel);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));
clear();
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
// update the display unit, to not use the default ("BLC")
updateDisplayUnit();
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
<|endoftext|> |
<commit_before>#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_WS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
ui->payTo->setPlaceholderText(tr("Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)"));
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if no label is filled in yet
if(ui->addAsLabel->text().isEmpty())
ui->addAsLabel->setText(model->getAddressTableModel()->labelForAddress(address));}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
if(model && model->getOptionsModel())
{
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
<commit_msg>Make the sendcoins dialog use the configured unit type, even on the first attempt.<commit_after>#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_WS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
ui->payTo->setPlaceholderText(tr("Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)"));
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if no label is filled in yet
if(ui->addAsLabel->text().isEmpty())
ui->addAsLabel->setText(model->getAddressTableModel()->labelForAddress(address));}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
clear();
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
if(model && model->getOptionsModel())
{
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
<|endoftext|> |
<commit_before>#include <QTest>
#include <QObject>
#include "uritests.h"
// This is all you need to run all the tests
int main(int argc, char *argv[])
{
URITests test1;
QTest::qExec(&test1);
}
<commit_msg>Return !0 when qt tests fail.<commit_after>#include <QTest>
#include <QObject>
#include "uritests.h"
// This is all you need to run all the tests
int main(int argc, char *argv[])
{
bool fInvalid = false;
URITests test1;
if (QTest::qExec(&test1) != 0)
fInvalid = true;
return fInvalid;
}
<|endoftext|> |
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "rdb_protocol/error.hpp"
#include "backtrace.hpp"
#include "containers/archive/stl_types.hpp"
#include "rdb_protocol/datum.hpp"
#include "rdb_protocol/term_walker.hpp"
#include "rdb_protocol/val.hpp"
namespace ql {
#ifdef RQL_ERROR_BT
#define RQL_ERROR_VAR
#else
#define RQL_ERROR_VAR UNUSED
#endif
void runtime_fail(base_exc_t::type_t type,
RQL_ERROR_VAR const char *test, RQL_ERROR_VAR const char *file,
RQL_ERROR_VAR int line,
std::string msg, const Backtrace *bt_src) {
#ifdef RQL_ERROR_BT
msg = strprintf("%s\nFailed assertion: %s\nAt: %s:%d",
msg.c_str(), test, file, line);
#endif
throw exc_t(type, msg, bt_src);
}
void runtime_fail(base_exc_t::type_t type,
RQL_ERROR_VAR const char *test, RQL_ERROR_VAR const char *file,
RQL_ERROR_VAR int line, std::string msg) {
#ifdef RQL_ERROR_BT
msg = strprintf("%s\nFailed assertion: %s\nAt: %s:%d",
msg.c_str(), test, file, line);
#endif
throw datum_exc_t(type, msg);
}
void runtime_sanity_check_failed() {
lazy_backtrace_formatter_t bt;
throw exc_t(base_exc_t::GENERIC,
"SANITY CHECK FAILED (server is buggy). Backtrace:\n" + bt.addrs(),
backtrace_t());
}
base_exc_t::type_t exc_type(const datum_t *d) {
r_sanity_check(d);
return d->get_type() == datum_t::R_NULL
? base_exc_t::NON_EXISTENCE
: base_exc_t::GENERIC;
}
base_exc_t::type_t exc_type(const counted_t<const datum_t> &d) {
r_sanity_check(d.has());
return exc_type(d.get());
}
base_exc_t::type_t exc_type(const val_t *v) {
r_sanity_check(v);
if (v->get_type().is_convertible(val_t::type_t::DATUM)) {
return exc_type(v->as_datum());
} else {
return base_exc_t::GENERIC;
}
}
base_exc_t::type_t exc_type(const counted_t<val_t> &v) {
r_sanity_check(v.has());
return exc_type(v.get());
}
void backtrace_t::fill_bt(Backtrace *bt) const {
for (std::list<backtrace_t::frame_t>::const_iterator
it = frames.begin(); it != frames.end(); ++it) {
if (it->is_skip()) continue;
if (it->is_head()) {
rassert(it == frames.begin());
continue;
}
*bt->add_frames() = it->toproto();
}
}
void backtrace_t::fill_error(Response *res, Response_ResponseType type,
std::string msg) const {
guarantee(type == Response::CLIENT_ERROR ||
type == Response::COMPILE_ERROR ||
type == Response::RUNTIME_ERROR);
Datum error_msg;
error_msg.set_type(Datum::R_STR);
error_msg.set_r_str(msg);
res->set_type(type);
*res->add_response() = error_msg;
fill_bt(res->mutable_backtrace());
}
void fill_error(Response *res, Response_ResponseType type, std::string msg,
const backtrace_t &bt) {
bt.fill_error(res, type, msg);
}
Frame backtrace_t::frame_t::toproto() const {
Frame f;
switch(type) {
case POS: {
f.set_type(Frame_FrameType_POS);
f.set_pos(pos);
} break;
case OPT: {
f.set_type(Frame_FrameType_OPT);
f.set_opt(opt);
} break;
default: unreachable();
}
return f;
}
backtrace_t::frame_t::frame_t(const Frame &f) {
switch(f.type()) {
case Frame::POS: {
type = POS;
pos = f.pos();
} break;
case Frame::OPT: {
type = OPT;
opt = f.opt();
} break;
default: unreachable();
}
}
protob_t<const Backtrace> get_backtrace(const protob_t<const Term> &t) {
return t.make_child(&t->GetExtension(ql2::extension::backtrace));
}
void pb_rcheckable_t::propagate(Term *t) const {
propagate_backtrace(t, bt_src.get());
}
RDB_IMPL_ME_SERIALIZABLE_1_SINCE_v1_13(backtrace_t, frames);
RDB_IMPL_ME_SERIALIZABLE_3_SINCE_v1_13(backtrace_t::frame_t, type, pos, opt);
RDB_IMPL_ME_SERIALIZABLE_3_SINCE_v1_13(exc_t, type_, backtrace_, exc_msg_);
RDB_IMPL_ME_SERIALIZABLE_2_SINCE_v1_13(datum_exc_t, type_, exc_msg);
} // namespace ql
<commit_msg>fixing error responses not living up to expectations<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "rdb_protocol/error.hpp"
#include "backtrace.hpp"
#include "containers/archive/stl_types.hpp"
#include "rdb_protocol/datum.hpp"
#include "rdb_protocol/term_walker.hpp"
#include "rdb_protocol/val.hpp"
namespace ql {
#ifdef RQL_ERROR_BT
#define RQL_ERROR_VAR
#else
#define RQL_ERROR_VAR UNUSED
#endif
void runtime_fail(base_exc_t::type_t type,
RQL_ERROR_VAR const char *test, RQL_ERROR_VAR const char *file,
RQL_ERROR_VAR int line,
std::string msg, const Backtrace *bt_src) {
#ifdef RQL_ERROR_BT
msg = strprintf("%s\nFailed assertion: %s\nAt: %s:%d",
msg.c_str(), test, file, line);
#endif
throw exc_t(type, msg, bt_src);
}
void runtime_fail(base_exc_t::type_t type,
RQL_ERROR_VAR const char *test, RQL_ERROR_VAR const char *file,
RQL_ERROR_VAR int line, std::string msg) {
#ifdef RQL_ERROR_BT
msg = strprintf("%s\nFailed assertion: %s\nAt: %s:%d",
msg.c_str(), test, file, line);
#endif
throw datum_exc_t(type, msg);
}
void runtime_sanity_check_failed() {
lazy_backtrace_formatter_t bt;
throw exc_t(base_exc_t::GENERIC,
"SANITY CHECK FAILED (server is buggy). Backtrace:\n" + bt.addrs(),
backtrace_t());
}
base_exc_t::type_t exc_type(const datum_t *d) {
r_sanity_check(d);
return d->get_type() == datum_t::R_NULL
? base_exc_t::NON_EXISTENCE
: base_exc_t::GENERIC;
}
base_exc_t::type_t exc_type(const counted_t<const datum_t> &d) {
r_sanity_check(d.has());
return exc_type(d.get());
}
base_exc_t::type_t exc_type(const val_t *v) {
r_sanity_check(v);
if (v->get_type().is_convertible(val_t::type_t::DATUM)) {
return exc_type(v->as_datum());
} else {
return base_exc_t::GENERIC;
}
}
base_exc_t::type_t exc_type(const counted_t<val_t> &v) {
r_sanity_check(v.has());
return exc_type(v.get());
}
void backtrace_t::fill_bt(Backtrace *bt) const {
for (std::list<backtrace_t::frame_t>::const_iterator
it = frames.begin(); it != frames.end(); ++it) {
if (it->is_skip()) continue;
if (it->is_head()) {
rassert(it == frames.begin());
continue;
}
*bt->add_frames() = it->toproto();
}
}
void backtrace_t::fill_error(Response *res, Response_ResponseType type,
std::string msg) const {
guarantee(type == Response::CLIENT_ERROR ||
type == Response::COMPILE_ERROR ||
type == Response::RUNTIME_ERROR);
Datum error_msg;
error_msg.set_type(Datum::R_STR);
error_msg.set_r_str(msg);
res->set_type(type);
res->clear_response();
res->clear_profile();
*res->add_response() = error_msg;
fill_bt(res->mutable_backtrace());
}
void fill_error(Response *res, Response_ResponseType type, std::string msg,
const backtrace_t &bt) {
bt.fill_error(res, type, msg);
}
Frame backtrace_t::frame_t::toproto() const {
Frame f;
switch(type) {
case POS: {
f.set_type(Frame_FrameType_POS);
f.set_pos(pos);
} break;
case OPT: {
f.set_type(Frame_FrameType_OPT);
f.set_opt(opt);
} break;
default: unreachable();
}
return f;
}
backtrace_t::frame_t::frame_t(const Frame &f) {
switch(f.type()) {
case Frame::POS: {
type = POS;
pos = f.pos();
} break;
case Frame::OPT: {
type = OPT;
opt = f.opt();
} break;
default: unreachable();
}
}
protob_t<const Backtrace> get_backtrace(const protob_t<const Term> &t) {
return t.make_child(&t->GetExtension(ql2::extension::backtrace));
}
void pb_rcheckable_t::propagate(Term *t) const {
propagate_backtrace(t, bt_src.get());
}
RDB_IMPL_ME_SERIALIZABLE_1_SINCE_v1_13(backtrace_t, frames);
RDB_IMPL_ME_SERIALIZABLE_3_SINCE_v1_13(backtrace_t::frame_t, type, pos, opt);
RDB_IMPL_ME_SERIALIZABLE_3_SINCE_v1_13(exc_t, type_, backtrace_, exc_msg_);
RDB_IMPL_ME_SERIALIZABLE_2_SINCE_v1_13(datum_exc_t, type_, exc_msg);
} // namespace ql
<|endoftext|> |
<commit_before>/*
This file is part of Ingen.
Copyright 2007-2015 David Robillard <http://drobilla.net/>
Ingen is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU Affero General Public License for details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ingen/URIs.hpp"
#include "Buffer.hpp"
#include "Driver.hpp"
#include "DuplexPort.hpp"
#include "Engine.hpp"
#include "GraphImpl.hpp"
#include "OutputPort.hpp"
using namespace std;
namespace Ingen {
namespace Server {
DuplexPort::DuplexPort(BufferFactory& bufs,
BlockImpl* parent,
const Raul::Symbol& symbol,
uint32_t index,
bool polyphonic,
uint32_t poly,
PortType type,
LV2_URID buffer_type,
const Atom& value,
size_t buffer_size,
bool is_output)
: PortImpl(bufs, parent, symbol, index, poly, type, buffer_type, value, buffer_size)
, InputPort(bufs, parent, symbol, index, poly, type, buffer_type, value, buffer_size)
, OutputPort(bufs, parent, symbol, index, poly, type, buffer_type, value, buffer_size)
, _is_output(is_output)
{
if (polyphonic) {
set_property(bufs.uris().ingen_polyphonic, bufs.forge().make(true));
}
if (!parent->parent() ||
_poly != parent->parent_graph()->internal_poly()) {
_poly = 1;
}
// Set default control range
if (!is_output && value.type() == bufs.uris().atom_Float) {
set_property(bufs.uris().lv2_minimum, bufs.forge().make(0.0f));
set_property(bufs.uris().lv2_maximum, bufs.forge().make(1.0f));
}
}
DuplexPort::~DuplexPort()
{
if (is_linked()) {
parent_graph()->remove_port(*this);
}
}
DuplexPort*
DuplexPort::duplicate(Engine& engine,
const Raul::Symbol& symbol,
GraphImpl* parent)
{
BufferFactory& bufs = *engine.buffer_factory();
const Atom polyphonic = get_property(bufs.uris().ingen_polyphonic);
DuplexPort* dup = new DuplexPort(
bufs, parent, symbol, _index,
polyphonic.type() == bufs.uris().atom_Bool && polyphonic.get<int32_t>(),
_poly, _type, _buffer_type,
_value, _buffer_size, _is_output);
dup->set_properties(properties());
return dup;
}
void
DuplexPort::inherit_neighbour(const PortImpl* port,
Resource::Properties& remove,
Resource::Properties& add)
{
const URIs& uris = _bufs.uris();
/* TODO: This needs to become more sophisticated, and correct the situation
if the port is disconnected. */
if (_type == PortType::CONTROL || _type == PortType::CV) {
if (port->minimum().get<float>() < _min.get<float>()) {
_min = port->minimum();
remove.emplace(uris.lv2_minimum, uris.patch_wildcard);
add.emplace(uris.lv2_minimum, port->minimum());
}
if (port->maximum().get<float>() > _max.get<float>()) {
_max = port->maximum();
remove.emplace(uris.lv2_maximum, uris.patch_wildcard);
add.emplace(uris.lv2_maximum, port->maximum());
}
} else if (_type == PortType::ATOM) {
for (Resource::Properties::const_iterator i = port->properties().find(
uris.atom_supports);
i != port->properties().end() && i->first == uris.atom_supports;
++i) {
set_property(i->first, i->second);
add.insert(*i);
}
}
}
void
DuplexPort::on_property(const Raul::URI& uri, const Atom& value)
{
_bufs.engine().driver()->port_property(_path, uri, value);
}
bool
DuplexPort::get_buffers(BufferFactory& bufs,
Raul::Array<Voice>* voices,
uint32_t poly,
bool real_time) const
{
if (_is_output) {
return InputPort::get_buffers(bufs, voices, poly, real_time);
} else {
return OutputPort::get_buffers(bufs, voices, poly, real_time);
}
}
uint32_t
DuplexPort::max_tail_poly(Context& context) const
{
return std::max(_poly, parent_graph()->internal_poly_process());
}
bool
DuplexPort::prepare_poly(BufferFactory& bufs, uint32_t poly)
{
if (!parent()->parent() ||
poly != parent()->parent_graph()->internal_poly()) {
return false;
}
return PortImpl::prepare_poly(bufs, poly);
}
bool
DuplexPort::apply_poly(ProcessContext& context, Raul::Maid& maid, uint32_t poly)
{
if (!parent()->parent() ||
poly != parent()->parent_graph()->internal_poly()) {
return false;
}
return PortImpl::apply_poly(context, maid, poly);
}
void
DuplexPort::pre_process(Context& context)
{
if (_is_output) {
/* This is a graph output, which is an input from the internal
perspective. Prepare buffers for write so plugins can deliver to
them */
for (uint32_t v = 0; v < _poly; ++v) {
_voices->at(v).buffer->prepare_write(context);
}
} else {
/* This is a a graph input, which is an output from the internal
perspective. Do whatever a normal block's input port does to
prepare input for reading. */
InputPort::pre_process(context);
InputPort::pre_run(context);
}
}
void
DuplexPort::post_process(Context& context)
{
if (_is_output) {
/* This is a graph output, which is an input from the internal
perspective. Mix down input delivered by plugins so output
(external perspective) is ready. */
InputPort::pre_process(context);
InputPort::pre_run(context);
} else {
monitor(context);
}
}
SampleCount
DuplexPort::next_value_offset(SampleCount offset, SampleCount end) const
{
return OutputPort::next_value_offset(offset, end);
}
void
DuplexPort::update_values(SampleCount offset, uint32_t voice)
{
return OutputPort::update_values(offset, voice);
}
} // namespace Server
} // namespace Ingen
<commit_msg>Remove last use of map::emplace.<commit_after>/*
This file is part of Ingen.
Copyright 2007-2015 David Robillard <http://drobilla.net/>
Ingen is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU Affero General Public License for details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ingen/URIs.hpp"
#include "Buffer.hpp"
#include "Driver.hpp"
#include "DuplexPort.hpp"
#include "Engine.hpp"
#include "GraphImpl.hpp"
#include "OutputPort.hpp"
using namespace std;
namespace Ingen {
namespace Server {
DuplexPort::DuplexPort(BufferFactory& bufs,
BlockImpl* parent,
const Raul::Symbol& symbol,
uint32_t index,
bool polyphonic,
uint32_t poly,
PortType type,
LV2_URID buffer_type,
const Atom& value,
size_t buffer_size,
bool is_output)
: PortImpl(bufs, parent, symbol, index, poly, type, buffer_type, value, buffer_size)
, InputPort(bufs, parent, symbol, index, poly, type, buffer_type, value, buffer_size)
, OutputPort(bufs, parent, symbol, index, poly, type, buffer_type, value, buffer_size)
, _is_output(is_output)
{
if (polyphonic) {
set_property(bufs.uris().ingen_polyphonic, bufs.forge().make(true));
}
if (!parent->parent() ||
_poly != parent->parent_graph()->internal_poly()) {
_poly = 1;
}
// Set default control range
if (!is_output && value.type() == bufs.uris().atom_Float) {
set_property(bufs.uris().lv2_minimum, bufs.forge().make(0.0f));
set_property(bufs.uris().lv2_maximum, bufs.forge().make(1.0f));
}
}
DuplexPort::~DuplexPort()
{
if (is_linked()) {
parent_graph()->remove_port(*this);
}
}
DuplexPort*
DuplexPort::duplicate(Engine& engine,
const Raul::Symbol& symbol,
GraphImpl* parent)
{
BufferFactory& bufs = *engine.buffer_factory();
const Atom polyphonic = get_property(bufs.uris().ingen_polyphonic);
DuplexPort* dup = new DuplexPort(
bufs, parent, symbol, _index,
polyphonic.type() == bufs.uris().atom_Bool && polyphonic.get<int32_t>(),
_poly, _type, _buffer_type,
_value, _buffer_size, _is_output);
dup->set_properties(properties());
return dup;
}
void
DuplexPort::inherit_neighbour(const PortImpl* port,
Resource::Properties& remove,
Resource::Properties& add)
{
const URIs& uris = _bufs.uris();
/* TODO: This needs to become more sophisticated, and correct the situation
if the port is disconnected. */
if (_type == PortType::CONTROL || _type == PortType::CV) {
if (port->minimum().get<float>() < _min.get<float>()) {
_min = port->minimum();
remove.insert(std::make_pair(uris.lv2_minimum, uris.patch_wildcard));
add.insert(std::make_pair(uris.lv2_minimum, port->minimum()));
}
if (port->maximum().get<float>() > _max.get<float>()) {
_max = port->maximum();
remove.insert(std::make_pair(uris.lv2_maximum, uris.patch_wildcard));
add.insert(std::make_pair(uris.lv2_maximum, port->maximum()));
}
} else if (_type == PortType::ATOM) {
for (Resource::Properties::const_iterator i = port->properties().find(
uris.atom_supports);
i != port->properties().end() && i->first == uris.atom_supports;
++i) {
set_property(i->first, i->second);
add.insert(*i);
}
}
}
void
DuplexPort::on_property(const Raul::URI& uri, const Atom& value)
{
_bufs.engine().driver()->port_property(_path, uri, value);
}
bool
DuplexPort::get_buffers(BufferFactory& bufs,
Raul::Array<Voice>* voices,
uint32_t poly,
bool real_time) const
{
if (_is_output) {
return InputPort::get_buffers(bufs, voices, poly, real_time);
} else {
return OutputPort::get_buffers(bufs, voices, poly, real_time);
}
}
uint32_t
DuplexPort::max_tail_poly(Context& context) const
{
return std::max(_poly, parent_graph()->internal_poly_process());
}
bool
DuplexPort::prepare_poly(BufferFactory& bufs, uint32_t poly)
{
if (!parent()->parent() ||
poly != parent()->parent_graph()->internal_poly()) {
return false;
}
return PortImpl::prepare_poly(bufs, poly);
}
bool
DuplexPort::apply_poly(ProcessContext& context, Raul::Maid& maid, uint32_t poly)
{
if (!parent()->parent() ||
poly != parent()->parent_graph()->internal_poly()) {
return false;
}
return PortImpl::apply_poly(context, maid, poly);
}
void
DuplexPort::pre_process(Context& context)
{
if (_is_output) {
/* This is a graph output, which is an input from the internal
perspective. Prepare buffers for write so plugins can deliver to
them */
for (uint32_t v = 0; v < _poly; ++v) {
_voices->at(v).buffer->prepare_write(context);
}
} else {
/* This is a a graph input, which is an output from the internal
perspective. Do whatever a normal block's input port does to
prepare input for reading. */
InputPort::pre_process(context);
InputPort::pre_run(context);
}
}
void
DuplexPort::post_process(Context& context)
{
if (_is_output) {
/* This is a graph output, which is an input from the internal
perspective. Mix down input delivered by plugins so output
(external perspective) is ready. */
InputPort::pre_process(context);
InputPort::pre_run(context);
} else {
monitor(context);
}
}
SampleCount
DuplexPort::next_value_offset(SampleCount offset, SampleCount end) const
{
return OutputPort::next_value_offset(offset, end);
}
void
DuplexPort::update_values(SampleCount offset, uint32_t voice)
{
return OutputPort::update_values(offset, voice);
}
} // namespace Server
} // namespace Ingen
<|endoftext|> |
<commit_before>#pragma once
#include <cstring>
namespace iod
{
struct stringview
{
stringview() {}
stringview(const std::string& _str) : str(&_str[0]), len(_str.size()) {}
stringview(const char* _str, int _len) : str(_str), len(_len) {}
stringview(const char* _str) : str(_str), len(strlen(_str)) {}
bool operator==(const stringview& o) const { return len == o.len and !strncmp(o.str, str, len); }
bool operator==(const std::string& o) const { return len == int(o.size()) and !strncmp(&o[0], str, len); }
bool operator==(const char* o) const { return len == int(strlen(o)) and !strncmp(o, str, len); }
bool operator<(const stringview& o) const { return strncmp(o.str, str, std::min(len, o.len)); }
explicit operator std::string() const { return std::string(str, len); }
auto& operator[](int p) { return str[p]; }
const auto& operator[](int p) const { return str[p]; }
int size() const { return len; }
const char* data() const { return str; }
auto to_std_string() const { return std::string(str, len); }
const char* str;
int len;
};
}
<commit_msg>Fix stringview headers.<commit_after>#pragma once
#include <cstring>
#include <string>
namespace iod
{
struct stringview
{
stringview() {}
stringview(const std::string& _str) : str(&_str[0]), len(_str.size()) {}
stringview(const char* _str, int _len) : str(_str), len(_len) {}
stringview(const char* _str) : str(_str), len(strlen(_str)) {}
bool operator==(const stringview& o) const { return len == o.len and !strncmp(o.str, str, len); }
bool operator==(const std::string& o) const { return len == int(o.size()) and !strncmp(&o[0], str, len); }
bool operator==(const char* o) const { return len == int(strlen(o)) and !strncmp(o, str, len); }
bool operator<(const stringview& o) const { return strncmp(o.str, str, std::min(len, o.len)); }
explicit operator std::string() const { return std::string(str, len); }
auto& operator[](int p) { return str[p]; }
const auto& operator[](int p) const { return str[p]; }
int size() const { return len; }
const char* data() const { return str; }
auto to_std_string() const { return std::string(str, len); }
const char* str;
int len;
};
}
<|endoftext|> |
<commit_before>/*
Copyright 2013-present Barefoot Networks, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ir.h"
#include "dbprint.h"
#include "lib/hex.h"
#include "lib/map.h"
using namespace DBPrint;
using namespace IndentCtl;
void IR::HeaderStackItemRef::dbprint(std::ostream &out) const {
int prec = getprec(out);
out << setprec(Prec_Postfix) << *base_ << "[" << setprec(Prec_Low) << *index_
<< "]" << setprec(prec);
if (prec == 0) out << ';';
}
void IR::FieldList::dbprint(std::ostream &out) const {
out << "field_list " << name << " {" << indent;
for (auto f : fields)
out << endl << f;
if (payload)
out << endl << "payload;";
out << unindent << " }";
}
void IR::FieldListCalculation::dbprint(std::ostream &out) const {
out << "field_list_calcualtion " << name << '(' << algorithm << ", " << output_width << ')';
}
void IR::CalculatedField::dbprint(std::ostream &out) const {
out << "calcualted_field " << *field << indent;
for (auto &spec : specs) {
out << endl << (spec.update ? "update " : "verify ") << spec.name;
if (spec.cond) out << " if " << spec.cond; }
out << unindent;
}
void IR::CaseEntry::dbprint(std::ostream &out) const {
const char *sep = "";
int prec = getprec(out);
out << setprec(Prec_Low);
for (auto &val : values) {
if (val.second->asLong() == -1)
out << sep << *val.first;
else if (val.second->asLong() == 0)
out << sep << "default";
else
out << sep << *val.first << " &&& " << *val.second;
sep = ", "; }
out << ':' << setprec(prec) << " " << action;
}
void IR::V1Parser::dbprint(std::ostream &out) const {
out << "parser " << name << " {" << indent;
for (auto &stmt : stmts)
out << endl << *stmt;
if (select) {
int prec = getprec(out);
const char *sep = "";
out << endl << "select (" << setprec(Prec_Low);
for (auto e : *select) {
out << sep << *e;
sep = ", "; }
out << ") {" << indent << setprec(prec); }
if (cases)
for (auto c : *cases)
out << endl << *c;
if (select)
out << " }" << unindent;
if (default_return)
out << endl << "return " << default_return << ";";
if (parse_error)
out << endl << "error " << parse_error << ";";
if (drop)
out << endl << "drop;";
out << " }" << unindent;
}
void IR::ParserException::dbprint(std::ostream &out) const { out << "IR::ParserException"; }
void IR::ParserState::dbprint(std::ostream &out) const {
out << "state " << name << " " << annotations << "{" << indent;
for (auto s : components)
out << endl << s;
if (selectExpression)
out << endl << selectExpression;
out << " }" << unindent;
}
void IR::P4Parser::dbprint(std::ostream &out) const {
out << "parser " << name;
if (type->typeParameters && !type->typeParameters->empty())
out << type->typeParameters;
if (constructorParams)
out << '(' << constructorParams << ')';
out << " " << type->annotations << "{" << indent;
for (auto d : parserLocals)
out << endl << d;
for (auto s : states)
out << endl << s;
out << " }" << unindent;
}
void IR::Counter::dbprint(std::ostream &out) const { IR::Attached::dbprint(out); }
void IR::Meter::dbprint(std::ostream &out) const { IR::Attached::dbprint(out); }
void IR::Register::dbprint(std::ostream &out) const { IR::Attached::dbprint(out); }
void IR::PrimitiveAction::dbprint(std::ostream &out) const { out << "IR::PrimitiveAction"; }
void IR::NameList::dbprint(std::ostream &out) const { out << "IR::NameList"; }
void IR::ActionFunction::dbprint(std::ostream &out) const {
out << "action " << name << "(";
const char *sep = "";
for (auto &arg : args) {
out << sep << *arg->type << ' ' << arg->name;
sep = ", "; }
out << ") {" << indent;
for (auto &p : action)
out << endl << p;
out << unindent << " }";
}
void IR::P4Action::dbprint(std::ostream &out) const {
out << "action " << name << "(";
const char *sep = "";
for (auto arg : parameters->parameters) {
out << sep << arg->direction << ' ' << arg->type << ' ' << arg->name;
sep = ", "; }
out << ") {" << indent;
if (body)
for (auto p : body->components)
out << endl << p;
out << unindent << " }";
}
void IR::BlockStatement::dbprint(std::ostream &out) const {
out << "{" << indent;
bool first = true;
for (auto p : components) {
if (first) {
out << ' ' << p;
first = false;
} else {
out << endl << p; } }
out << unindent << " }";
}
void IR::ActionProfile::dbprint(std::ostream &out) const { out << "IR::ActionProfile"; }
void IR::ActionSelector::dbprint(std::ostream &out) const { out << "IR::ActionSelector"; }
void IR::V1Table::dbprint(std::ostream &out) const { out << "IR::V1Table " << name; }
void IR::ActionList::dbprint(std::ostream &out) const {
out << "{" << indent;
bool first = true;
for (auto el : actionList) {
if (first)
out << ' ' << el;
else
out << endl << el;
first = false; }
out << unindent << " }";
}
void IR::KeyElement::dbprint(std::ostream &out) const {
int prec = getprec(out);
out << annotations << Prec_Low << expression << ": " << matchType << setprec(prec);
if (!prec) out << ';';
}
void IR::Key::dbprint(std::ostream &out) const {
out << "{" << indent;
bool first = true;
for (auto el : keyElements) {
if (first)
out << ' ' << el;
else
out << endl << el;
first = false; }
out << unindent << " }";
}
void IR::P4Table::dbprint(std::ostream &out) const {
out << "table " << name;
out << " " << annotations << "{" << indent;
for (auto p : properties->properties)
out << endl << p;
out << " }" << unindent;
}
void IR::V1Control::dbprint(std::ostream &out) const {
out << "control " << name << " {" << indent << code << unindent << " }";
}
void IR::P4Control::dbprint(std::ostream &out) const {
out << "control " << name;
if (type->typeParameters && !type->typeParameters->empty())
out << type->typeParameters;
if (constructorParams)
out << '(' << constructorParams << ')';
out << " " << type->annotations << "{" << indent;
for (auto d : controlLocals)
out << endl << d;
for (auto s : body->components)
out << endl << s;
out << " }" << unindent;
}
void IR::V1Program::dbprint(std::ostream &out) const {
for (auto &obj : Values(scope))
out << obj << endl;
}
void IR::P4Program::dbprint(std::ostream &out) const {
for (auto obj : declarations)
out << obj << endl;
}
void IR::Type_Error::dbprint(std::ostream &out) const {
out << "error {";
const char *sep = " ";
for (auto id : members) {
out << sep << id->name;
sep = ", "; }
out << (sep+1) << "}";
}
void IR::Declaration_MatchKind::dbprint(std::ostream &out) const {
out << "match_kind {";
const char *sep = " ";
for (auto id : members) {
out << sep << id->name;
sep = ", "; }
out << (sep+1) << "}";
}
void IR::Declaration_Instance::dbprint(std::ostream &out) const {
int prec = getprec(out);
out << annotations << type << ' ' << name << '(' << Prec_Low;
const char *sep = "";
for (auto e : *arguments) {
out << sep << e;
sep = ", "; }
out << ')' << setprec(prec);
if (initializer)
out << " {" << indent << initializer << " }" << unindent;
if (!properties.empty()) {
out << " {" << indent;
for (auto &obj : properties)
out << endl << obj.second;
out << " }" << unindent; }
}
<commit_msg>(Part 3) - Fix spelling and null-handling in dbprint() for CalculatedField and FieldListCalculation<commit_after>/*
Copyright 2013-present Barefoot Networks, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ir.h"
#include "dbprint.h"
#include "lib/hex.h"
#include "lib/map.h"
using namespace DBPrint;
using namespace IndentCtl;
void IR::HeaderStackItemRef::dbprint(std::ostream &out) const {
int prec = getprec(out);
out << setprec(Prec_Postfix) << *base_ << "[" << setprec(Prec_Low) << *index_
<< "]" << setprec(prec);
if (prec == 0) out << ';';
}
void IR::FieldList::dbprint(std::ostream &out) const {
out << "field_list " << name << " {" << indent;
for (auto f : fields)
out << endl << f;
if (payload)
out << endl << "payload;";
out << unindent << " }";
}
void IR::FieldListCalculation::dbprint(std::ostream &out) const {
out << "field_list_calculation" << name << '(' << algorithm << ", " << output_width << ')';
}
void IR::CalculatedField::dbprint(std::ostream &out) const {
out << "calculated_field ";
if (field) {
out << *field;
} else {
out << "(null)";
}
out << indent;
for (auto &spec : specs) {
out << endl << (spec.update ? "update " : "verify ") << spec.name;
if (spec.cond) out << " if " << spec.cond; }
out << unindent;
}
void IR::CaseEntry::dbprint(std::ostream &out) const {
const char *sep = "";
int prec = getprec(out);
out << setprec(Prec_Low);
for (auto &val : values) {
if (val.second->asLong() == -1)
out << sep << *val.first;
else if (val.second->asLong() == 0)
out << sep << "default";
else
out << sep << *val.first << " &&& " << *val.second;
sep = ", "; }
out << ':' << setprec(prec) << " " << action;
}
void IR::V1Parser::dbprint(std::ostream &out) const {
out << "parser " << name << " {" << indent;
for (auto &stmt : stmts)
out << endl << *stmt;
if (select) {
int prec = getprec(out);
const char *sep = "";
out << endl << "select (" << setprec(Prec_Low);
for (auto e : *select) {
out << sep << *e;
sep = ", "; }
out << ") {" << indent << setprec(prec); }
if (cases)
for (auto c : *cases)
out << endl << *c;
if (select)
out << " }" << unindent;
if (default_return)
out << endl << "return " << default_return << ";";
if (parse_error)
out << endl << "error " << parse_error << ";";
if (drop)
out << endl << "drop;";
out << " }" << unindent;
}
void IR::ParserException::dbprint(std::ostream &out) const { out << "IR::ParserException"; }
void IR::ParserState::dbprint(std::ostream &out) const {
out << "state " << name << " " << annotations << "{" << indent;
for (auto s : components)
out << endl << s;
if (selectExpression)
out << endl << selectExpression;
out << " }" << unindent;
}
void IR::P4Parser::dbprint(std::ostream &out) const {
out << "parser " << name;
if (type->typeParameters && !type->typeParameters->empty())
out << type->typeParameters;
if (constructorParams)
out << '(' << constructorParams << ')';
out << " " << type->annotations << "{" << indent;
for (auto d : parserLocals)
out << endl << d;
for (auto s : states)
out << endl << s;
out << " }" << unindent;
}
void IR::Counter::dbprint(std::ostream &out) const { IR::Attached::dbprint(out); }
void IR::Meter::dbprint(std::ostream &out) const { IR::Attached::dbprint(out); }
void IR::Register::dbprint(std::ostream &out) const { IR::Attached::dbprint(out); }
void IR::PrimitiveAction::dbprint(std::ostream &out) const { out << "IR::PrimitiveAction"; }
void IR::NameList::dbprint(std::ostream &out) const { out << "IR::NameList"; }
void IR::ActionFunction::dbprint(std::ostream &out) const {
out << "action " << name << "(";
const char *sep = "";
for (auto &arg : args) {
out << sep << *arg->type << ' ' << arg->name;
sep = ", "; }
out << ") {" << indent;
for (auto &p : action)
out << endl << p;
out << unindent << " }";
}
void IR::P4Action::dbprint(std::ostream &out) const {
out << "action " << name << "(";
const char *sep = "";
for (auto arg : parameters->parameters) {
out << sep << arg->direction << ' ' << arg->type << ' ' << arg->name;
sep = ", "; }
out << ") {" << indent;
if (body)
for (auto p : body->components)
out << endl << p;
out << unindent << " }";
}
void IR::BlockStatement::dbprint(std::ostream &out) const {
out << "{" << indent;
bool first = true;
for (auto p : components) {
if (first) {
out << ' ' << p;
first = false;
} else {
out << endl << p; } }
out << unindent << " }";
}
void IR::ActionProfile::dbprint(std::ostream &out) const { out << "IR::ActionProfile"; }
void IR::ActionSelector::dbprint(std::ostream &out) const { out << "IR::ActionSelector"; }
void IR::V1Table::dbprint(std::ostream &out) const { out << "IR::V1Table " << name; }
void IR::ActionList::dbprint(std::ostream &out) const {
out << "{" << indent;
bool first = true;
for (auto el : actionList) {
if (first)
out << ' ' << el;
else
out << endl << el;
first = false; }
out << unindent << " }";
}
void IR::KeyElement::dbprint(std::ostream &out) const {
int prec = getprec(out);
out << annotations << Prec_Low << expression << ": " << matchType << setprec(prec);
if (!prec) out << ';';
}
void IR::Key::dbprint(std::ostream &out) const {
out << "{" << indent;
bool first = true;
for (auto el : keyElements) {
if (first)
out << ' ' << el;
else
out << endl << el;
first = false; }
out << unindent << " }";
}
void IR::P4Table::dbprint(std::ostream &out) const {
out << "table " << name;
out << " " << annotations << "{" << indent;
for (auto p : properties->properties)
out << endl << p;
out << " }" << unindent;
}
void IR::V1Control::dbprint(std::ostream &out) const {
out << "control " << name << " {" << indent << code << unindent << " }";
}
void IR::P4Control::dbprint(std::ostream &out) const {
out << "control " << name;
if (type->typeParameters && !type->typeParameters->empty())
out << type->typeParameters;
if (constructorParams)
out << '(' << constructorParams << ')';
out << " " << type->annotations << "{" << indent;
for (auto d : controlLocals)
out << endl << d;
for (auto s : body->components)
out << endl << s;
out << " }" << unindent;
}
void IR::V1Program::dbprint(std::ostream &out) const {
for (auto &obj : Values(scope))
out << obj << endl;
}
void IR::P4Program::dbprint(std::ostream &out) const {
for (auto obj : declarations)
out << obj << endl;
}
void IR::Type_Error::dbprint(std::ostream &out) const {
out << "error {";
const char *sep = " ";
for (auto id : members) {
out << sep << id->name;
sep = ", "; }
out << (sep+1) << "}";
}
void IR::Declaration_MatchKind::dbprint(std::ostream &out) const {
out << "match_kind {";
const char *sep = " ";
for (auto id : members) {
out << sep << id->name;
sep = ", "; }
out << (sep+1) << "}";
}
void IR::Declaration_Instance::dbprint(std::ostream &out) const {
int prec = getprec(out);
out << annotations << type << ' ' << name << '(' << Prec_Low;
const char *sep = "";
for (auto e : *arguments) {
out << sep << e;
sep = ", "; }
out << ')' << setprec(prec);
if (initializer)
out << " {" << indent << initializer << " }" << unindent;
if (!properties.empty()) {
out << " {" << indent;
for (auto &obj : properties)
out << endl << obj.second;
out << " }" << unindent; }
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2017, EPL-Vizards
* 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 EPL-Vizards 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 EPL-Vizards BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
* \file EPLVizDefines.hpp
* \note This file is automatically generated.
* Please edit only defines.in.hpp in the project root
*/
#pragma once
#define EPL_VIZ_ENABLE_MOCKING @CM_ENABLE_MOCKING@
#ifndef mockable
#if EPL_VIZ_ENABLE_MOCKING
#define mockable virtual
#else
#define mockable
#endif
#endif
namespace EPL_Viz {
namespace constants {
const int EPL_VIZ_VERSION_MAJOR = @CM_VERSION_MAJOR@;
const int EPL_VIZ_VERSION_MINOR = @CM_VERSION_MINOR@;
const int EPL_VIZ_VERSION_SUBMINOR = @CM_VERSION_SUBMINOR@;
const int EPL_VIZ_GIT_LAST_TAG_DIFF = @CM_TAG_DIFF@;
const char * const EPL_VIZ_VERSION_GIT = "@CM_VERSION_GIT@";
const char * const EPL_VIZ_INSTALL_PREFIX = "@CMAKE_INSTALL_PREFIX@";
}
}
<commit_msg>Fixed mockable<commit_after>/* Copyright (c) 2017, EPL-Vizards
* 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 EPL-Vizards 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 EPL-Vizards BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
* \file EPLVizDefines.hpp
* \note This file is automatically generated.
* Please edit only defines.in.hpp in the project root
*/
#pragma once
#define EPL_VIZ_ENABLE_MOCKING @CM_ENABLE_MOCKING@
namespace EPL_Viz {
namespace constants {
const int EPL_VIZ_VERSION_MAJOR = @CM_VERSION_MAJOR@;
const int EPL_VIZ_VERSION_MINOR = @CM_VERSION_MINOR@;
const int EPL_VIZ_VERSION_SUBMINOR = @CM_VERSION_SUBMINOR@;
const int EPL_VIZ_GIT_LAST_TAG_DIFF = @CM_TAG_DIFF@;
const char * const EPL_VIZ_VERSION_GIT = "@CM_VERSION_GIT@";
const char * const EPL_VIZ_INSTALL_PREFIX = "@CMAKE_INSTALL_PREFIX@";
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup
// 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 <stingraykit/log/Logger.h>
#include <stingraykit/log/SystemLogger.h>
#include <stingraykit/string/StringFormat.h>
#include <stingraykit/time/TimeEngine.h>
#include <stingraykit/FunctionToken.h>
#include <stingraykit/SafeSingleton.h>
#include <stingraykit/lazy.h>
#include <string.h>
namespace stingray
{
namespace Detail {
namespace LoggerDetail
{
NullPtrType s_logger; // Static logger fallback
}}
struct NamedLoggerSettings
{
private:
optional<LogLevel> _logLevel;
bool _backtrace;
bool _highlight;
public:
NamedLoggerSettings()
: _backtrace(false), _highlight(false)
{ }
optional<LogLevel> GetLogLevel() const { return _logLevel; }
void SetLogLevel(optional<LogLevel> logLevel) { _logLevel = logLevel; }
bool BacktraceEnabled() const { return _backtrace; }
void EnableBacktrace(bool enable) { _backtrace = enable; }
bool HighlightEnabled() const { return _highlight; }
void EnableHighlight(bool enable) { _highlight = enable; }
bool IsEmpty() const { return !_logLevel && !_backtrace && !_highlight; }
};
class NamedLoggerRegistry
{
struct StrLess
{
bool operator() (const char* l, const char* r) const { return strcmp(l, r) < 0; }
};
typedef std::map<std::string, NamedLoggerSettings> SettingsRegistry;
typedef std::multimap<const char*, NamedLogger*, StrLess> ObjectsRegistry;
private:
Mutex _mutex;
SettingsRegistry _settings;
ObjectsRegistry _objects;
public:
NamedLoggerRegistry()
{ }
ObjectsRegistry::const_iterator Register(const char* loggerName, NamedLogger* logger)
{
MutexLock l(_mutex);
const SettingsRegistry::const_iterator it = _settings.find(loggerName);
if (it != _settings.end())
{
logger->SetLogLevel(it->second.GetLogLevel());
logger->EnableBacktrace(it->second.BacktraceEnabled());
logger->EnableHighlight(it->second.HighlightEnabled());
}
return _objects.emplace(loggerName, logger);
}
void Unregister(ObjectsRegistry::const_iterator it)
{
MutexLock l(_mutex);
_objects.erase(it);
}
std::set<std::string> GetLoggerNames() const
{
MutexLock l(_mutex);
return std::set<std::string>(keys_iterator(_objects.begin()), keys_iterator(_objects.end()));
}
void SetLogLevel(const std::string& loggerName, optional<LogLevel> logLevel)
{
MutexLock l(_mutex);
const std::pair<ObjectsRegistry::iterator, ObjectsRegistry::iterator> range = _objects.equal_range(loggerName.c_str());
for (ObjectsRegistry::iterator it = range.first; it != range.second; ++it)
it->second->SetLogLevel(logLevel);
const SettingsRegistry::iterator it = _settings.emplace(loggerName, NamedLoggerSettings()).first;
it->second.SetLogLevel(logLevel);
if (it->second.IsEmpty())
_settings.erase(it);
}
void EnableBacktrace(const std::string& loggerName, bool enable)
{
MutexLock l(_mutex);
const std::pair<ObjectsRegistry::iterator, ObjectsRegistry::iterator> range = _objects.equal_range(loggerName.c_str());
for (ObjectsRegistry::iterator it = range.first; it != range.second; ++it)
it->second->EnableBacktrace(enable);
const SettingsRegistry::iterator it = _settings.emplace(loggerName, NamedLoggerSettings()).first;
it->second.EnableBacktrace(enable);
if (it->second.IsEmpty())
_settings.erase(it);
}
void EnableHighlight(const std::string& loggerName, bool enable)
{
MutexLock l(_mutex);
const std::pair<ObjectsRegistry::iterator, ObjectsRegistry::iterator> range = _objects.equal_range(loggerName.c_str());
for (ObjectsRegistry::iterator it = range.first; it != range.second; ++it)
it->second->EnableHighlight(enable);
const SettingsRegistry::iterator it = _settings.emplace(loggerName, NamedLoggerSettings()).first;
it->second.EnableHighlight(enable);
if (it->second.IsEmpty())
_settings.erase(it);
}
};
STINGRAYKIT_DECLARE_PTR(NamedLoggerRegistry);
class LoggerImpl
{
typedef std::vector<ILoggerSinkPtr> SinksBundle;
private:
SinksBundle _sinks;
Mutex _logMutex;
NamedLoggerRegistry _registry;
public:
LoggerImpl()
{ }
~LoggerImpl()
{ }
void AddSink(const ILoggerSinkPtr& sink)
{
MutexLock l(_logMutex);
_sinks.push_back(sink);
}
void RemoveSink(const ILoggerSinkPtr& sink)
{
MutexLock l(_logMutex);
SinksBundle::iterator it = std::find(_sinks.begin(), _sinks.end(), sink);
if (it != _sinks.end())
_sinks.erase(it);
}
void Log(const LoggerMessage& message) noexcept
{
try
{
EnableInterruptionPoints eip(false);
SinksBundle sinks;
{
MutexLock l(_logMutex);
sinks = _sinks;
}
if (sinks.empty())
SystemLogger::Log(message);
else
PutMessageToSinks(sinks, message);
}
catch (const std::exception&)
{ }
}
NamedLoggerRegistry& GetRegistry()
{ return _registry; }
private:
static void PutMessageToSinks(const SinksBundle& sinks, const LoggerMessage& message)
{
for (SinksBundle::const_iterator it = sinks.begin(); it != sinks.end(); ++it)
{
try
{ (*it)->Log(message); }
catch (const std::exception&)
{ }
}
}
};
STINGRAYKIT_DECLARE_PTR(LoggerImpl);
typedef SafeSingleton<LoggerImpl> LoggerSingleton;
/////////////////////////////////////////////////////////////////
struct LogLevelHolder
{
static u32 s_logLevel;
};
u32 LogLevelHolder::s_logLevel = (u32)LogLevel::Info;
void Logger::SetLogLevel(LogLevel logLevel)
{
AtomicU32::Store(LogLevelHolder::s_logLevel, (u32)logLevel.val(), MemoryOrderRelaxed);
Stream(logLevel) << "Log level is " << logLevel;
}
LogLevel Logger::GetLogLevel()
{ return (LogLevel::Enum)AtomicU32::Load(LogLevelHolder::s_logLevel, MemoryOrderRelaxed); }
LoggerStream Logger::Stream(LogLevel logLevel, DuplicatingLogsFilter* duplicatingLogsFilter)
{ return LoggerStream(null, GetLogLevel(), logLevel, duplicatingLogsFilter, &Logger::DoLog); }
void Logger::SetLogLevel(const std::string& loggerName, optional<LogLevel> logLevel)
{
LoggerImplPtr logger = LoggerSingleton::Instance();
if (logger)
logger->GetRegistry().SetLogLevel(loggerName, logLevel);
}
void Logger::EnableBacktrace(const std::string& loggerName, bool enable)
{
LoggerImplPtr logger = LoggerSingleton::Instance();
if (logger)
logger->GetRegistry().EnableBacktrace(loggerName, enable);
}
void Logger::EnableHighlight(const std::string& loggerName, bool enable)
{
LoggerImplPtr logger = LoggerSingleton::Instance();
if (logger)
logger->GetRegistry().EnableHighlight(loggerName, enable);
}
std::set<std::string> Logger::GetLoggerNames()
{
LoggerImplPtr logger = LoggerSingleton::Instance();
if (logger)
return logger->GetRegistry().GetLoggerNames();
else
return std::set<std::string>();
}
Token Logger::AddSink(const ILoggerSinkPtr& sink)
{
LoggerImplPtr logger = LoggerSingleton::Instance();
if (!logger)
return null;
logger->AddSink(sink);
return MakeFunctionToken(Bind(&LoggerImpl::RemoveSink, logger, sink));
}
void Logger::DoLog(const NamedLoggerParams* loggerParams, LogLevel logLevel, const std::string& text)
{
LoggerImplPtr logger = LoggerSingleton::Instance();
LogLevel ll = logger ? GetLogLevel() : LogLevel(LogLevel::Debug);
if (!loggerParams && logLevel < ll) // NamedLogger LoggerStream checks the log level in its destructor
return;
optional<LoggerMessage> msg;
if (loggerParams)
msg.emplace(loggerParams->GetName(), logLevel, text + (loggerParams->BacktraceEnabled() ? ": " + Backtrace().Get() : std::string()), loggerParams->HighlightEnabled());
else
msg.emplace(logLevel, text, false);
if (logger)
logger->Log(*msg);
else
SystemLogger::Log(*msg);
}
/////////////////////////////////////////////////////////////////
NamedLogger::NamedLogger(const char* name)
: _params(name),
_logLevel(OptionalLogLevel::Null)
{
if (const LoggerImplPtr logger = LoggerSingleton::Instance())
{
const NamedLoggerRegistryPtr r(logger, &(logger->GetRegistry()));
_token = MakeFunctionToken(Bind(&NamedLoggerRegistry::Unregister, r, r->Register(_params.GetName(), this)));
}
}
LogLevel NamedLogger::GetLogLevel() const
{ return OptionalLogLevel::ToLogLevel(_logLevel.load(MemoryOrderRelaxed)).get_value_or(lazy(&Logger::GetLogLevel)); }
void NamedLogger::SetLogLevel(optional<LogLevel> logLevel)
{
_logLevel.store(OptionalLogLevel::FromLogLevel(logLevel), MemoryOrderRelaxed);
Stream(GetLogLevel()) << "Log level is " << logLevel;
}
bool NamedLogger::BacktraceEnabled() const
{ return _params.BacktraceEnabled(); }
void NamedLogger::EnableBacktrace(bool enable)
{
_params.EnableBacktrace(enable);
Stream(GetLogLevel()) << "Backtrace " << (enable ? "enabled" : "disabled");
}
bool NamedLogger::HighlightEnabled() const
{ return _params.HighlightEnabled(); }
void NamedLogger::EnableHighlight(bool enable)
{ _params.EnableHighlight(enable); }
LoggerStream NamedLogger::Stream(LogLevel logLevel) const
{ return LoggerStream(&_params, GetLogLevel(), logLevel, &_duplicatingLogsFilter, &Logger::DoLog); }
void NamedLogger::Log(LogLevel logLevel, const std::string& message) const
{ Stream(logLevel) << message; }
/////////////////////////////////////////////////////////////////
namespace
{
class ElapsedMillisecondsToString
{
private:
const ElapsedTime& _elapsed;
public:
explicit ElapsedMillisecondsToString(const ElapsedTime& elapsed) : _elapsed(elapsed) { }
std::string ToString() const
{
s64 ms = 0;
int mms = 0;
try { s64 e = _elapsed.ElapsedMicroseconds(); ms = e / 1000; mms = e % 1000; }
catch (const std::exception&) { }
return StringBuilder() % ms % "." % mms;
}
};
}
ActionLogger::ActionLogger(const std::string& action)
: _namedLogger(NULL), _logLevel(LogLevel::Info), _action(action)
{ Logger::Info() << _action << "..."; }
ActionLogger::ActionLogger(LogLevel logLevel, const std::string& action)
: _namedLogger(NULL), _logLevel(logLevel), _action(action)
{ Logger::Stream(logLevel) << _action << "..."; }
ActionLogger::ActionLogger(const NamedLogger& namedLogger, const std::string& action)
: _namedLogger(&namedLogger), _logLevel(LogLevel::Info), _action(action)
{ _namedLogger->Info() << _action << "..."; }
ActionLogger::ActionLogger(const NamedLogger& namedLogger, LogLevel logLevel, const std::string& action)
: _namedLogger(&namedLogger), _logLevel(logLevel), _action(action)
{ _namedLogger->Stream(logLevel) << _action << "..."; }
ActionLogger::~ActionLogger()
{
if (std::uncaught_exception())
{
try
{
if (_namedLogger)
_namedLogger->Stream(_logLevel) << _action << " completed with exception in " << ElapsedMillisecondsToString(_elapsedTime) << " ms";
else
Logger::Stream(_logLevel) << _action << " completed with exception in " << ElapsedMillisecondsToString(_elapsedTime) << " ms";
}
catch (const std::exception&)
{ return; }
}
else
{
if (_namedLogger)
_namedLogger->Stream(_logLevel) << _action << " completed in " << ElapsedMillisecondsToString(_elapsedTime) << " ms";
else
Logger::Stream(_logLevel) << _action << " completed in " << ElapsedMillisecondsToString(_elapsedTime) << " ms";
}
}
/////////////////////////////////////////////////////////////////
Tracer::Tracer(const Detail::NamedLoggerAccessor& logger, const char* funcName)
: _logger(logger), _logLevel(logger.GetLogLevel()), _funcName(funcName)
{
if (_logLevel > LogLevel::Trace)
return;
_startTime = TimeEngine::GetMonotonicMicroseconds();
_logger.Trace() << "TRACER: entering function '" << _funcName << "'";
}
Tracer::~Tracer()
{
if (_logLevel > LogLevel::Trace)
return;
try
{
s64 e = TimeEngine::GetMonotonicMicroseconds() - _startTime;
s64 ms = e / 1000;
int mms = e % 1000;
if (std::uncaught_exception())
_logger.Trace() << "TRACER: leaving function '" << _funcName << "' due to an exception (" << StringFormat("%1%.%2$3%", ms, mms) << " ms)";
else
_logger.Trace() << "TRACER: leaving function '" << _funcName << "' (" << StringFormat("%1%.%2$3%", ms, mms) << " ms)";
}
catch (const std::exception&)
{ }
}
}
<commit_msg>Logger: use string builder for string concatenation<commit_after>// Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup
// 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 <stingraykit/log/Logger.h>
#include <stingraykit/log/SystemLogger.h>
#include <stingraykit/string/StringFormat.h>
#include <stingraykit/time/TimeEngine.h>
#include <stingraykit/FunctionToken.h>
#include <stingraykit/SafeSingleton.h>
#include <stingraykit/lazy.h>
#include <string.h>
namespace stingray
{
namespace Detail {
namespace LoggerDetail
{
NullPtrType s_logger; // Static logger fallback
}}
struct NamedLoggerSettings
{
private:
optional<LogLevel> _logLevel;
bool _backtrace;
bool _highlight;
public:
NamedLoggerSettings()
: _backtrace(false), _highlight(false)
{ }
optional<LogLevel> GetLogLevel() const { return _logLevel; }
void SetLogLevel(optional<LogLevel> logLevel) { _logLevel = logLevel; }
bool BacktraceEnabled() const { return _backtrace; }
void EnableBacktrace(bool enable) { _backtrace = enable; }
bool HighlightEnabled() const { return _highlight; }
void EnableHighlight(bool enable) { _highlight = enable; }
bool IsEmpty() const { return !_logLevel && !_backtrace && !_highlight; }
};
class NamedLoggerRegistry
{
struct StrLess
{
bool operator() (const char* l, const char* r) const { return strcmp(l, r) < 0; }
};
typedef std::map<std::string, NamedLoggerSettings> SettingsRegistry;
typedef std::multimap<const char*, NamedLogger*, StrLess> ObjectsRegistry;
private:
Mutex _mutex;
SettingsRegistry _settings;
ObjectsRegistry _objects;
public:
NamedLoggerRegistry()
{ }
ObjectsRegistry::const_iterator Register(const char* loggerName, NamedLogger* logger)
{
MutexLock l(_mutex);
const SettingsRegistry::const_iterator it = _settings.find(loggerName);
if (it != _settings.end())
{
logger->SetLogLevel(it->second.GetLogLevel());
logger->EnableBacktrace(it->second.BacktraceEnabled());
logger->EnableHighlight(it->second.HighlightEnabled());
}
return _objects.emplace(loggerName, logger);
}
void Unregister(ObjectsRegistry::const_iterator it)
{
MutexLock l(_mutex);
_objects.erase(it);
}
std::set<std::string> GetLoggerNames() const
{
MutexLock l(_mutex);
return std::set<std::string>(keys_iterator(_objects.begin()), keys_iterator(_objects.end()));
}
void SetLogLevel(const std::string& loggerName, optional<LogLevel> logLevel)
{
MutexLock l(_mutex);
const std::pair<ObjectsRegistry::iterator, ObjectsRegistry::iterator> range = _objects.equal_range(loggerName.c_str());
for (ObjectsRegistry::iterator it = range.first; it != range.second; ++it)
it->second->SetLogLevel(logLevel);
const SettingsRegistry::iterator it = _settings.emplace(loggerName, NamedLoggerSettings()).first;
it->second.SetLogLevel(logLevel);
if (it->second.IsEmpty())
_settings.erase(it);
}
void EnableBacktrace(const std::string& loggerName, bool enable)
{
MutexLock l(_mutex);
const std::pair<ObjectsRegistry::iterator, ObjectsRegistry::iterator> range = _objects.equal_range(loggerName.c_str());
for (ObjectsRegistry::iterator it = range.first; it != range.second; ++it)
it->second->EnableBacktrace(enable);
const SettingsRegistry::iterator it = _settings.emplace(loggerName, NamedLoggerSettings()).first;
it->second.EnableBacktrace(enable);
if (it->second.IsEmpty())
_settings.erase(it);
}
void EnableHighlight(const std::string& loggerName, bool enable)
{
MutexLock l(_mutex);
const std::pair<ObjectsRegistry::iterator, ObjectsRegistry::iterator> range = _objects.equal_range(loggerName.c_str());
for (ObjectsRegistry::iterator it = range.first; it != range.second; ++it)
it->second->EnableHighlight(enable);
const SettingsRegistry::iterator it = _settings.emplace(loggerName, NamedLoggerSettings()).first;
it->second.EnableHighlight(enable);
if (it->second.IsEmpty())
_settings.erase(it);
}
};
STINGRAYKIT_DECLARE_PTR(NamedLoggerRegistry);
class LoggerImpl
{
typedef std::vector<ILoggerSinkPtr> SinksBundle;
private:
SinksBundle _sinks;
Mutex _logMutex;
NamedLoggerRegistry _registry;
public:
LoggerImpl()
{ }
~LoggerImpl()
{ }
void AddSink(const ILoggerSinkPtr& sink)
{
MutexLock l(_logMutex);
_sinks.push_back(sink);
}
void RemoveSink(const ILoggerSinkPtr& sink)
{
MutexLock l(_logMutex);
SinksBundle::iterator it = std::find(_sinks.begin(), _sinks.end(), sink);
if (it != _sinks.end())
_sinks.erase(it);
}
void Log(const LoggerMessage& message) noexcept
{
try
{
EnableInterruptionPoints eip(false);
SinksBundle sinks;
{
MutexLock l(_logMutex);
sinks = _sinks;
}
if (sinks.empty())
SystemLogger::Log(message);
else
PutMessageToSinks(sinks, message);
}
catch (const std::exception&)
{ }
}
NamedLoggerRegistry& GetRegistry()
{ return _registry; }
private:
static void PutMessageToSinks(const SinksBundle& sinks, const LoggerMessage& message)
{
for (SinksBundle::const_iterator it = sinks.begin(); it != sinks.end(); ++it)
{
try
{ (*it)->Log(message); }
catch (const std::exception&)
{ }
}
}
};
STINGRAYKIT_DECLARE_PTR(LoggerImpl);
typedef SafeSingleton<LoggerImpl> LoggerSingleton;
/////////////////////////////////////////////////////////////////
struct LogLevelHolder
{
static u32 s_logLevel;
};
u32 LogLevelHolder::s_logLevel = (u32)LogLevel::Info;
void Logger::SetLogLevel(LogLevel logLevel)
{
AtomicU32::Store(LogLevelHolder::s_logLevel, (u32)logLevel.val(), MemoryOrderRelaxed);
Stream(logLevel) << "Log level is " << logLevel;
}
LogLevel Logger::GetLogLevel()
{ return (LogLevel::Enum)AtomicU32::Load(LogLevelHolder::s_logLevel, MemoryOrderRelaxed); }
LoggerStream Logger::Stream(LogLevel logLevel, DuplicatingLogsFilter* duplicatingLogsFilter)
{ return LoggerStream(null, GetLogLevel(), logLevel, duplicatingLogsFilter, &Logger::DoLog); }
void Logger::SetLogLevel(const std::string& loggerName, optional<LogLevel> logLevel)
{
LoggerImplPtr logger = LoggerSingleton::Instance();
if (logger)
logger->GetRegistry().SetLogLevel(loggerName, logLevel);
}
void Logger::EnableBacktrace(const std::string& loggerName, bool enable)
{
LoggerImplPtr logger = LoggerSingleton::Instance();
if (logger)
logger->GetRegistry().EnableBacktrace(loggerName, enable);
}
void Logger::EnableHighlight(const std::string& loggerName, bool enable)
{
LoggerImplPtr logger = LoggerSingleton::Instance();
if (logger)
logger->GetRegistry().EnableHighlight(loggerName, enable);
}
std::set<std::string> Logger::GetLoggerNames()
{
LoggerImplPtr logger = LoggerSingleton::Instance();
if (logger)
return logger->GetRegistry().GetLoggerNames();
else
return std::set<std::string>();
}
Token Logger::AddSink(const ILoggerSinkPtr& sink)
{
LoggerImplPtr logger = LoggerSingleton::Instance();
if (!logger)
return null;
logger->AddSink(sink);
return MakeFunctionToken(Bind(&LoggerImpl::RemoveSink, logger, sink));
}
void Logger::DoLog(const NamedLoggerParams* loggerParams, LogLevel logLevel, const std::string& text)
{
LoggerImplPtr logger = LoggerSingleton::Instance();
LogLevel ll = logger ? GetLogLevel() : LogLevel(LogLevel::Debug);
if (!loggerParams && logLevel < ll) // NamedLogger LoggerStream checks the log level in its destructor
return;
optional<LoggerMessage> msg;
if (loggerParams)
msg.emplace(loggerParams->GetName(), logLevel, loggerParams->BacktraceEnabled() ? StringBuilder() % text % ": " % Backtrace() : text, loggerParams->HighlightEnabled());
else
msg.emplace(logLevel, text, false);
if (logger)
logger->Log(*msg);
else
SystemLogger::Log(*msg);
}
/////////////////////////////////////////////////////////////////
NamedLogger::NamedLogger(const char* name)
: _params(name),
_logLevel(OptionalLogLevel::Null)
{
if (const LoggerImplPtr logger = LoggerSingleton::Instance())
{
const NamedLoggerRegistryPtr r(logger, &(logger->GetRegistry()));
_token = MakeFunctionToken(Bind(&NamedLoggerRegistry::Unregister, r, r->Register(_params.GetName(), this)));
}
}
LogLevel NamedLogger::GetLogLevel() const
{ return OptionalLogLevel::ToLogLevel(_logLevel.load(MemoryOrderRelaxed)).get_value_or(lazy(&Logger::GetLogLevel)); }
void NamedLogger::SetLogLevel(optional<LogLevel> logLevel)
{
_logLevel.store(OptionalLogLevel::FromLogLevel(logLevel), MemoryOrderRelaxed);
Stream(GetLogLevel()) << "Log level is " << logLevel;
}
bool NamedLogger::BacktraceEnabled() const
{ return _params.BacktraceEnabled(); }
void NamedLogger::EnableBacktrace(bool enable)
{
_params.EnableBacktrace(enable);
Stream(GetLogLevel()) << "Backtrace " << (enable ? "enabled" : "disabled");
}
bool NamedLogger::HighlightEnabled() const
{ return _params.HighlightEnabled(); }
void NamedLogger::EnableHighlight(bool enable)
{ _params.EnableHighlight(enable); }
LoggerStream NamedLogger::Stream(LogLevel logLevel) const
{ return LoggerStream(&_params, GetLogLevel(), logLevel, &_duplicatingLogsFilter, &Logger::DoLog); }
void NamedLogger::Log(LogLevel logLevel, const std::string& message) const
{ Stream(logLevel) << message; }
/////////////////////////////////////////////////////////////////
namespace
{
class ElapsedMillisecondsToString
{
private:
const ElapsedTime& _elapsed;
public:
explicit ElapsedMillisecondsToString(const ElapsedTime& elapsed) : _elapsed(elapsed) { }
std::string ToString() const
{
s64 ms = 0;
int mms = 0;
try { s64 e = _elapsed.ElapsedMicroseconds(); ms = e / 1000; mms = e % 1000; }
catch (const std::exception&) { }
return StringBuilder() % ms % "." % mms;
}
};
}
ActionLogger::ActionLogger(const std::string& action)
: _namedLogger(NULL), _logLevel(LogLevel::Info), _action(action)
{ Logger::Info() << _action << "..."; }
ActionLogger::ActionLogger(LogLevel logLevel, const std::string& action)
: _namedLogger(NULL), _logLevel(logLevel), _action(action)
{ Logger::Stream(logLevel) << _action << "..."; }
ActionLogger::ActionLogger(const NamedLogger& namedLogger, const std::string& action)
: _namedLogger(&namedLogger), _logLevel(LogLevel::Info), _action(action)
{ _namedLogger->Info() << _action << "..."; }
ActionLogger::ActionLogger(const NamedLogger& namedLogger, LogLevel logLevel, const std::string& action)
: _namedLogger(&namedLogger), _logLevel(logLevel), _action(action)
{ _namedLogger->Stream(logLevel) << _action << "..."; }
ActionLogger::~ActionLogger()
{
if (std::uncaught_exception())
{
try
{
if (_namedLogger)
_namedLogger->Stream(_logLevel) << _action << " completed with exception in " << ElapsedMillisecondsToString(_elapsedTime) << " ms";
else
Logger::Stream(_logLevel) << _action << " completed with exception in " << ElapsedMillisecondsToString(_elapsedTime) << " ms";
}
catch (const std::exception&)
{ return; }
}
else
{
if (_namedLogger)
_namedLogger->Stream(_logLevel) << _action << " completed in " << ElapsedMillisecondsToString(_elapsedTime) << " ms";
else
Logger::Stream(_logLevel) << _action << " completed in " << ElapsedMillisecondsToString(_elapsedTime) << " ms";
}
}
/////////////////////////////////////////////////////////////////
Tracer::Tracer(const Detail::NamedLoggerAccessor& logger, const char* funcName)
: _logger(logger), _logLevel(logger.GetLogLevel()), _funcName(funcName)
{
if (_logLevel > LogLevel::Trace)
return;
_startTime = TimeEngine::GetMonotonicMicroseconds();
_logger.Trace() << "TRACER: entering function '" << _funcName << "'";
}
Tracer::~Tracer()
{
if (_logLevel > LogLevel::Trace)
return;
try
{
s64 e = TimeEngine::GetMonotonicMicroseconds() - _startTime;
s64 ms = e / 1000;
int mms = e % 1000;
if (std::uncaught_exception())
_logger.Trace() << "TRACER: leaving function '" << _funcName << "' due to an exception (" << StringFormat("%1%.%2$3%", ms, mms) << " ms)";
else
_logger.Trace() << "TRACER: leaving function '" << _funcName << "' (" << StringFormat("%1%.%2$3%", ms, mms) << " ms)";
}
catch (const std::exception&)
{ }
}
}
<|endoftext|> |
<commit_before>// SampSharp
// Copyright 2018 Tim Potze
//
// 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 "remote_server.h"
#include "platforms.h"
#include "version.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "logging.h"
#include "pathutil.h"
#define DEBUG_PAUSE_TIMEOUT (5)
#define DEBUG_PAUSE_TICK_INTERVAL (7)
#define DEBUG_PAUSE_TICK_MIN_SKIP (50)
/* receive */
#define CMD_PING (0x01) /* request a pong */
#define CMD_PRINT (0x02) /* print data */
#define CMD_RESPONSE (0x03) /* response to public call */
#define CMD_RECONNECT (0x04) /* expect client to reconnect */
#define CMD_REGISTER_CALL (0x05) /* register a public call */
#define CMD_FIND_NATIVE (0x06) /* return native id */
#define CMD_INVOKE_NATIVE (0x07) /* invoke a native */
#define CMD_START (0x08) /* start sending messages*/
#define CMD_DISCONNECT (0x09) /* expect client to disconnect */
#define CMD_ALIVE (0x10) /* sign of live */
/* send */
#define CMD_TICK (0x11) /* server tick */
#define CMD_PONG (0x12) /* ping reply */
#define CMD_PUBLIC_CALL (0x13) /* public call */
#define CMD_REPLY (0x14) /* reply to find native or native invoke */
#define CMD_ANNOUNCE (0x15) /* announce with version */
/* status marcos */
#define STATUS_SET(v) status_ = (status)(status_ | (v))
#define STATUS_UNSET(v) status_ = (status)(status_ & ~(v))
#define STATUS_ISSET(v) ((status_ & (v)) == (v))
#pragma region Constructors and loading
/** initializes and allocates required memory for the server instance */
remote_server::remote_server(plugin *plg, commsvr *communication, const bool debug_check) :
status_(status_none),
communication_(communication),
intermission_(plg),
debug_check_(debug_check) {
intermission_.signal_starting();
communication_->setup(this);
}
/** frees memory allocated by this instance */
remote_server::~remote_server() {
if (communication_) {
communication_->disconnect();
}
}
#pragma endregion
#pragma region Commands
CMD_DEFINE(cmd_ping) {
log_debug("Sending pong");
communication_->send(CMD_PONG, 0, NULL);
}
CMD_DEFINE(cmd_print) {
log_print("%s", buf);
}
CMD_DEFINE(cmd_alive) {
}
CMD_DEFINE(cmd_register_call) {
log_debug("Register call %s", buf);
callbacks_.register_buffer(buf);
}
CMD_DEFINE(cmd_find_native) {
// copy callerid to output buffer
*(uint16_t *)buftx_ = *(uint16_t *)buf;
log_debug("Find native w/%d data", buflen - sizeof(uint16_t));
*(int32_t *)(buftx_ + sizeof(uint16_t)) = natives_.get_handle((char *)(buf + sizeof(uint16_t)));
communication_->send(CMD_RESPONSE, sizeof(int32_t) + sizeof(uint16_t), buftx_);
}
CMD_DEFINE(cmd_invoke_native) {
uint32_t txlen = LEN_NETBUF;
uint8_t *buftx = buftx_;
uint16_t callerid = *(uint16_t *)buf;
uint16_t* calleridptr = (uint16_t *)buftx;
buf += sizeof(uint16_t);
buftx += sizeof(uint16_t); // reserve callerid space
buflen -= sizeof(uint16_t);
txlen -= sizeof(uint16_t);
natives_.invoke(buf, buflen, buftx, &txlen);
log_debug("Native invoked with %d buflen, response has %d buflen", buflen, txlen);
txlen += sizeof(uint16_t);
// copy callerid to output buffer after the native was executed because the
// native might invoke callbacks which in turn may cause this function
// to be executed again, causing the value to be overwritten.
*calleridptr = callerid;
communication_->send(CMD_RESPONSE, txlen, buftx_);
}
CMD_DEFINE(cmd_reconnect) {
log_info("The gamemode is reconnecting.");
STATUS_SET(status_client_reconnecting);
disconnect(NULL, true);
}
CMD_DEFINE(cmd_disconnect) {
log_info("The gamemode is disconnecting.");
STATUS_SET(status_client_disconnecting);
}
CMD_DEFINE(cmd_start) {
log_info("The gamemode has started.");
STATUS_SET(status_client_started);
uint8_t type = buflen == 0 ? 0 : buf[0];
switch (type) {
case 0:
log_debug("Using 'none' start method");
break;
case 1:
log_debug("Using 'gmx' start method");
if (STATUS_ISSET(status_server_received_init)) {
log_debug("Sending gmx to attach game mode.");
sampgdk_SendRconCommand("gmx");
}
break;
case 2:
log_debug("Using 'fake gmx' start method");
if (STATUS_ISSET(status_server_received_init)) {
STATUS_SET(status_client_received_init);
cell params = 0;
uint32_t len = LEN_NETBUF;
uint8_t *response = NULL;
if(!callbacks_.fill_call_buffer(NULL, "OnGameModeInit", ¶ms,
buf_, &len, true)) {
break;
}
/* send */
communication_->send(CMD_PUBLIC_CALL, len, buf_);
/* receive */
if (!cmd_receive_unhandled(&response, &len) || !response ||
len == 0) {
log_error("Received no response to callback OnGameModeInit.");
break;
}
delete[] response;
}
break;
default:
log_error("Invalid game mode start mode");
break;
}
}
#pragma endregion
#pragma region Communication
/** store current time as last interaction time */
void remote_server::store_time() {
sol_ = time(NULL);
}
/** a guessed value whether the client is paused by a debugger */
bool remote_server::is_debugging(bool is_tick) {
if(!debug_check_) {
return false;
}
const bool new_debug = tick_ - sol_ >= DEBUG_PAUSE_TIMEOUT;
if(new_debug && !is_debug_) {
log_info("Debugger pause detected.");
}
else if (!new_debug && is_debug_) {
log_info("Debugger resume detected.");
}
if (is_tick) {
if (new_debug && is_debug_) {
if (time(NULL) - tick_ >= DEBUG_PAUSE_TICK_INTERVAL && ticks_skipped_ > DEBUG_PAUSE_TICK_MIN_SKIP) {
log_debug("Keepalive tick.");
ticks_skipped_ = 0;
return false;
}
ticks_skipped_++;
}
else if (!new_debug && ticks_skipped_) {
ticks_skipped_ = 0;
}
}
return is_debug_ = new_debug;
}
/** a value indicating whether the client is connected */
bool remote_server::is_client_connected() {
return communication_->is_connected() && STATUS_ISSET(status_client_connected);
}
/* try to let a client connect */
bool remote_server::connect() {
if (communication_->is_connected()) {
return true;
}
if (!communication_->is_ready() && !communication_->setup(this)) {
return false;
}
if (!communication_->connect()) {
return false;
}
intermission_.set_on(false);
STATUS_SET(status_client_connected);
if (STATUS_ISSET(status_client_reconnecting)) {
log_info("Client reconnected.");
}
else {
log_info("Connected to client.");
}
STATUS_UNSET(status_client_reconnecting);
cmd_send_announce();
return true;
}
/** sends the server announcement to the client */
void remote_server::cmd_send_announce() {
/* send version */
uint8_t buf[sizeof(uint32_t) * 2 + 260];
((uint32_t *)buf)[0] = PLUGIN_PROTOCOL_VERSION;
((uint32_t *)buf)[1] = PLUGIN_VERSION;
std::string cwd;
get_cwd(cwd);
memcpy(buf + sizeof(uint32_t) * 2, cwd.c_str(), cwd.length());
communication_->send(CMD_ANNOUNCE, sizeof(uint32_t) * 2 + cwd.length(),
buf);
log_info("Server announcement sent.");
}
/** disconnects from client */
void remote_server::disconnect(const char *context, bool expected) {
if (!is_client_connected()) {
return;
}
if (expected) {
log_info("Client disconnected.");
intermission_.signal_disconnect();
}
else if (STATUS_ISSET(status_client_disconnecting)) {
log_info("Client disconnected.");
STATUS_UNSET(status_client_started | status_client_disconnecting);
intermission_.signal_disconnect();
natives_.clear();
callbacks_.clear();
}
else {
if (!context) {
context = "";
}
log_error("Unexpected disconnect of client. %s", context);
STATUS_UNSET(status_client_started);
intermission_.signal_error();
natives_.clear();
callbacks_.clear();
}
/* disconnect and close */
communication_->disconnect();
/* re-setup */
communication_->setup(this);
STATUS_UNSET(status_client_connected);
}
/** receives a single command if available */
cmd_status remote_server::cmd_receive_one(uint8_t **response, uint32_t *len) {
uint8_t command;
uint32_t command_len = LEN_NETBUF;
assert(response);
assert(len);
assert(sizeof(unsigned long) == sizeof(uint32_t));
if (!connect()) {
return conn_dead;
}
cmd_status stat = communication_->receive(&command, buf_, &command_len);
if (stat == conn_dead || stat == no_cmd) {
return stat;
}
store_time();
return cmd_process(command, buf_, command_len, response, len);
}
/** receives commands until an unhandled command appears */
bool remote_server::cmd_receive_unhandled(uint8_t **response, uint32_t *len) {
assert(response);
assert(len);
cmd_status stat;
do {
*response = NULL;
*len = 0;
stat = cmd_receive_one(response, len);
} while (stat == handled ||
stat == no_cmd);
return stat == unhandled;
}
/** processes a command */
cmd_status remote_server::cmd_process(uint8_t cmd, uint8_t *buf,
uint32_t buflen, uint8_t **resp, uint32_t *resplen) {
#define MAP_COMMAND(a,b) case a:b(buf, buflen);return handled
switch (cmd) {
/* mapped commands */
MAP_COMMAND(CMD_PING, cmd_ping);
MAP_COMMAND(CMD_PRINT, cmd_print);
MAP_COMMAND(CMD_REGISTER_CALL, cmd_register_call);
MAP_COMMAND(CMD_FIND_NATIVE, cmd_find_native);
MAP_COMMAND(CMD_INVOKE_NATIVE, cmd_invoke_native);
MAP_COMMAND(CMD_RECONNECT, cmd_reconnect);
MAP_COMMAND(CMD_DISCONNECT, cmd_disconnect);
MAP_COMMAND(CMD_START, cmd_start);
MAP_COMMAND(CMD_ALIVE, cmd_alive);
/* unmapped commands (unhandled) */
case CMD_RESPONSE:
default:
if (buflen > 0) {
*resp = new uint8_t[buflen];
memcpy(*resp, buf, buflen);
*resplen = buflen;
}
return unhandled;
}
#undef MAP_COMMAND
}
#pragma endregion
void remote_server::terminate(const char *context) {
disconnect(context, false);
}
/** called when a public call is send from the server */
void remote_server::public_call(AMX *amx, const char *name, cell *params, cell *retval) {
bool is_gmi = !strcmp(name, "OnGameModeInit");
bool is_gme = !is_gmi && !strcmp(name, "OnGameModeExit");
if (is_gmi) {
STATUS_SET(status_server_received_init);
}
else if (is_gme) {
STATUS_UNSET(status_server_received_init);
}
if (!is_client_connected() ||
!STATUS_ISSET(status_client_started) ||
STATUS_ISSET(status_client_reconnecting) ||
STATUS_ISSET(status_client_disconnecting)) {
return;
}
intermission_.set_on(false);
if (is_gmi) {
STATUS_SET(status_client_received_init);
}
else if (!STATUS_ISSET(status_client_received_init)) {
return;
}
/* skip call if debugger pause is detected */
if (is_debugging(false)) {
return;
}
/* prep network buffer */
uint32_t len = LEN_NETBUF;
uint8_t *response = NULL;
if(!callbacks_.fill_call_buffer(amx, name, params, buf_, &len, true)) {
return;
}
mutex_.lock();
/* send */
communication_->send(CMD_PUBLIC_CALL, len, buf_);
/* receive */
if(!cmd_receive_unhandled(&response, &len) || !response || len == 0) {
log_error("Received no response to callback %s.", name);
mutex_.unlock();
return;
}
mutex_.unlock();
if (len >= 5 && response[0] && retval) {
/* get return value */
*retval = *((uint32_t *)(response + 1));
}
delete[] response;
}
/** called when a server tick occurs */
void remote_server::tick() {
mutex_.lock();
if (is_client_connected() &&
STATUS_ISSET(status_client_started | status_client_received_init) &&
!STATUS_ISSET(status_client_reconnecting) &&
!STATUS_ISSET(status_client_disconnecting)) {
intermission_.set_on(false);
/* only send tick if no paused debugger is detected */
if (!is_debugging(true)) {
tick_ = time(NULL);
communication_->send(CMD_TICK, 0, NULL);
}
}
uint8_t *response = NULL;
uint32_t len;
cmd_status stat;
/* receive calls from the game mode client */
do {
stat = cmd_receive_one(&response, &len);
if (response) {
log_error("Unhandled response in tick.");
delete[] response;
}
} while (stat != no_cmd && stat != conn_dead);
mutex_.unlock();
}
<commit_msg>[plugin] Removed some debug logging<commit_after>// SampSharp
// Copyright 2018 Tim Potze
//
// 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 "remote_server.h"
#include "platforms.h"
#include "version.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "logging.h"
#include "pathutil.h"
#define DEBUG_PAUSE_TIMEOUT (5)
#define DEBUG_PAUSE_TICK_INTERVAL (7)
#define DEBUG_PAUSE_TICK_MIN_SKIP (50)
/* receive */
#define CMD_PING (0x01) /* request a pong */
#define CMD_PRINT (0x02) /* print data */
#define CMD_RESPONSE (0x03) /* response to public call */
#define CMD_RECONNECT (0x04) /* expect client to reconnect */
#define CMD_REGISTER_CALL (0x05) /* register a public call */
#define CMD_FIND_NATIVE (0x06) /* return native id */
#define CMD_INVOKE_NATIVE (0x07) /* invoke a native */
#define CMD_START (0x08) /* start sending messages*/
#define CMD_DISCONNECT (0x09) /* expect client to disconnect */
#define CMD_ALIVE (0x10) /* sign of live */
/* send */
#define CMD_TICK (0x11) /* server tick */
#define CMD_PONG (0x12) /* ping reply */
#define CMD_PUBLIC_CALL (0x13) /* public call */
#define CMD_REPLY (0x14) /* reply to find native or native invoke */
#define CMD_ANNOUNCE (0x15) /* announce with version */
/* status marcos */
#define STATUS_SET(v) status_ = (status)(status_ | (v))
#define STATUS_UNSET(v) status_ = (status)(status_ & ~(v))
#define STATUS_ISSET(v) ((status_ & (v)) == (v))
#pragma region Constructors and loading
/** initializes and allocates required memory for the server instance */
remote_server::remote_server(plugin *plg, commsvr *communication, const bool debug_check) :
status_(status_none),
communication_(communication),
intermission_(plg),
debug_check_(debug_check) {
intermission_.signal_starting();
communication_->setup(this);
}
/** frees memory allocated by this instance */
remote_server::~remote_server() {
if (communication_) {
communication_->disconnect();
}
}
#pragma endregion
#pragma region Commands
CMD_DEFINE(cmd_ping) {
log_debug("Sending pong");
communication_->send(CMD_PONG, 0, NULL);
}
CMD_DEFINE(cmd_print) {
log_print("%s", buf);
}
CMD_DEFINE(cmd_alive) {
}
CMD_DEFINE(cmd_register_call) {
log_debug("Register call %s", buf);
callbacks_.register_buffer(buf);
}
CMD_DEFINE(cmd_find_native) {
// copy callerid to output buffer
*(uint16_t *)buftx_ = *(uint16_t *)buf;
*(int32_t *)(buftx_ + sizeof(uint16_t)) = natives_.get_handle((char *)(buf + sizeof(uint16_t)));
communication_->send(CMD_RESPONSE, sizeof(int32_t) + sizeof(uint16_t), buftx_);
}
CMD_DEFINE(cmd_invoke_native) {
uint32_t txlen = LEN_NETBUF;
uint8_t *buftx = buftx_;
uint16_t callerid = *(uint16_t *)buf;
uint16_t* calleridptr = (uint16_t *)buftx;
buf += sizeof(uint16_t);
buftx += sizeof(uint16_t); // reserve callerid space
buflen -= sizeof(uint16_t);
txlen -= sizeof(uint16_t);
natives_.invoke(buf, buflen, buftx, &txlen);
txlen += sizeof(uint16_t);
// copy callerid to output buffer after the native was executed because the
// native might invoke callbacks which in turn may cause this function
// to be executed again, causing the value to be overwritten.
*calleridptr = callerid;
communication_->send(CMD_RESPONSE, txlen, buftx_);
}
CMD_DEFINE(cmd_reconnect) {
log_info("The gamemode is reconnecting.");
STATUS_SET(status_client_reconnecting);
disconnect(NULL, true);
}
CMD_DEFINE(cmd_disconnect) {
log_info("The gamemode is disconnecting.");
STATUS_SET(status_client_disconnecting);
}
CMD_DEFINE(cmd_start) {
log_info("The gamemode has started.");
STATUS_SET(status_client_started);
uint8_t type = buflen == 0 ? 0 : buf[0];
switch (type) {
case 0:
log_debug("Using 'none' start method");
break;
case 1:
log_debug("Using 'gmx' start method");
if (STATUS_ISSET(status_server_received_init)) {
log_debug("Sending gmx to attach game mode.");
sampgdk_SendRconCommand("gmx");
}
break;
case 2:
log_debug("Using 'fake gmx' start method");
if (STATUS_ISSET(status_server_received_init)) {
STATUS_SET(status_client_received_init);
cell params = 0;
uint32_t len = LEN_NETBUF;
uint8_t *response = NULL;
if(!callbacks_.fill_call_buffer(NULL, "OnGameModeInit", ¶ms,
buf_, &len, true)) {
break;
}
/* send */
communication_->send(CMD_PUBLIC_CALL, len, buf_);
/* receive */
if (!cmd_receive_unhandled(&response, &len) || !response ||
len == 0) {
log_error("Received no response to callback OnGameModeInit.");
break;
}
delete[] response;
}
break;
default:
log_error("Invalid game mode start mode");
break;
}
}
#pragma endregion
#pragma region Communication
/** store current time as last interaction time */
void remote_server::store_time() {
sol_ = time(NULL);
}
/** a guessed value whether the client is paused by a debugger */
bool remote_server::is_debugging(bool is_tick) {
if(!debug_check_) {
return false;
}
const bool new_debug = tick_ - sol_ >= DEBUG_PAUSE_TIMEOUT;
if(new_debug && !is_debug_) {
log_info("Debugger pause detected.");
}
else if (!new_debug && is_debug_) {
log_info("Debugger resume detected.");
}
if (is_tick) {
if (new_debug && is_debug_) {
if (time(NULL) - tick_ >= DEBUG_PAUSE_TICK_INTERVAL && ticks_skipped_ > DEBUG_PAUSE_TICK_MIN_SKIP) {
log_debug("Keepalive tick.");
ticks_skipped_ = 0;
return false;
}
ticks_skipped_++;
}
else if (!new_debug && ticks_skipped_) {
ticks_skipped_ = 0;
}
}
return is_debug_ = new_debug;
}
/** a value indicating whether the client is connected */
bool remote_server::is_client_connected() {
return communication_->is_connected() && STATUS_ISSET(status_client_connected);
}
/* try to let a client connect */
bool remote_server::connect() {
if (communication_->is_connected()) {
return true;
}
if (!communication_->is_ready() && !communication_->setup(this)) {
return false;
}
if (!communication_->connect()) {
return false;
}
intermission_.set_on(false);
STATUS_SET(status_client_connected);
if (STATUS_ISSET(status_client_reconnecting)) {
log_info("Client reconnected.");
}
else {
log_info("Connected to client.");
}
STATUS_UNSET(status_client_reconnecting);
cmd_send_announce();
return true;
}
/** sends the server announcement to the client */
void remote_server::cmd_send_announce() {
/* send version */
uint8_t buf[sizeof(uint32_t) * 2 + 260];
((uint32_t *)buf)[0] = PLUGIN_PROTOCOL_VERSION;
((uint32_t *)buf)[1] = PLUGIN_VERSION;
std::string cwd;
get_cwd(cwd);
memcpy(buf + sizeof(uint32_t) * 2, cwd.c_str(), cwd.length());
communication_->send(CMD_ANNOUNCE, sizeof(uint32_t) * 2 + cwd.length(),
buf);
log_info("Server announcement sent.");
}
/** disconnects from client */
void remote_server::disconnect(const char *context, bool expected) {
if (!is_client_connected()) {
return;
}
if (expected) {
log_info("Client disconnected.");
intermission_.signal_disconnect();
}
else if (STATUS_ISSET(status_client_disconnecting)) {
log_info("Client disconnected.");
STATUS_UNSET(status_client_started | status_client_disconnecting);
intermission_.signal_disconnect();
natives_.clear();
callbacks_.clear();
}
else {
if (!context) {
context = "";
}
log_error("Unexpected disconnect of client. %s", context);
STATUS_UNSET(status_client_started);
intermission_.signal_error();
natives_.clear();
callbacks_.clear();
}
/* disconnect and close */
communication_->disconnect();
/* re-setup */
communication_->setup(this);
STATUS_UNSET(status_client_connected);
}
/** receives a single command if available */
cmd_status remote_server::cmd_receive_one(uint8_t **response, uint32_t *len) {
uint8_t command;
uint32_t command_len = LEN_NETBUF;
assert(response);
assert(len);
assert(sizeof(unsigned long) == sizeof(uint32_t));
if (!connect()) {
return conn_dead;
}
cmd_status stat = communication_->receive(&command, buf_, &command_len);
if (stat == conn_dead || stat == no_cmd) {
return stat;
}
store_time();
return cmd_process(command, buf_, command_len, response, len);
}
/** receives commands until an unhandled command appears */
bool remote_server::cmd_receive_unhandled(uint8_t **response, uint32_t *len) {
assert(response);
assert(len);
cmd_status stat;
do {
*response = NULL;
*len = 0;
stat = cmd_receive_one(response, len);
} while (stat == handled ||
stat == no_cmd);
return stat == unhandled;
}
/** processes a command */
cmd_status remote_server::cmd_process(uint8_t cmd, uint8_t *buf,
uint32_t buflen, uint8_t **resp, uint32_t *resplen) {
#define MAP_COMMAND(a,b) case a:b(buf, buflen);return handled
switch (cmd) {
/* mapped commands */
MAP_COMMAND(CMD_PING, cmd_ping);
MAP_COMMAND(CMD_PRINT, cmd_print);
MAP_COMMAND(CMD_REGISTER_CALL, cmd_register_call);
MAP_COMMAND(CMD_FIND_NATIVE, cmd_find_native);
MAP_COMMAND(CMD_INVOKE_NATIVE, cmd_invoke_native);
MAP_COMMAND(CMD_RECONNECT, cmd_reconnect);
MAP_COMMAND(CMD_DISCONNECT, cmd_disconnect);
MAP_COMMAND(CMD_START, cmd_start);
MAP_COMMAND(CMD_ALIVE, cmd_alive);
/* unmapped commands (unhandled) */
case CMD_RESPONSE:
default:
if (buflen > 0) {
*resp = new uint8_t[buflen];
memcpy(*resp, buf, buflen);
*resplen = buflen;
}
return unhandled;
}
#undef MAP_COMMAND
}
#pragma endregion
void remote_server::terminate(const char *context) {
disconnect(context, false);
}
/** called when a public call is send from the server */
void remote_server::public_call(AMX *amx, const char *name, cell *params, cell *retval) {
bool is_gmi = !strcmp(name, "OnGameModeInit");
bool is_gme = !is_gmi && !strcmp(name, "OnGameModeExit");
if (is_gmi) {
STATUS_SET(status_server_received_init);
}
else if (is_gme) {
STATUS_UNSET(status_server_received_init);
}
if (!is_client_connected() ||
!STATUS_ISSET(status_client_started) ||
STATUS_ISSET(status_client_reconnecting) ||
STATUS_ISSET(status_client_disconnecting)) {
return;
}
intermission_.set_on(false);
if (is_gmi) {
STATUS_SET(status_client_received_init);
}
else if (!STATUS_ISSET(status_client_received_init)) {
return;
}
/* skip call if debugger pause is detected */
if (is_debugging(false)) {
return;
}
/* prep network buffer */
uint32_t len = LEN_NETBUF;
uint8_t *response = NULL;
if(!callbacks_.fill_call_buffer(amx, name, params, buf_, &len, true)) {
return;
}
mutex_.lock();
/* send */
communication_->send(CMD_PUBLIC_CALL, len, buf_);
/* receive */
if(!cmd_receive_unhandled(&response, &len) || !response || len == 0) {
log_error("Received no response to callback %s.", name);
mutex_.unlock();
return;
}
mutex_.unlock();
if (len >= 5 && response[0] && retval) {
/* get return value */
*retval = *((uint32_t *)(response + 1));
}
delete[] response;
}
/** called when a server tick occurs */
void remote_server::tick() {
mutex_.lock();
if (is_client_connected() &&
STATUS_ISSET(status_client_started | status_client_received_init) &&
!STATUS_ISSET(status_client_reconnecting) &&
!STATUS_ISSET(status_client_disconnecting)) {
intermission_.set_on(false);
/* only send tick if no paused debugger is detected */
if (!is_debugging(true)) {
tick_ = time(NULL);
communication_->send(CMD_TICK, 0, NULL);
}
}
uint8_t *response = NULL;
uint32_t len;
cmd_status stat;
/* receive calls from the game mode client */
do {
stat = cmd_receive_one(&response, &len);
if (response) {
log_error("Unhandled response in tick.");
delete[] response;
}
} while (stat != no_cmd && stat != conn_dead);
mutex_.unlock();
}
<|endoftext|> |
<commit_before>#include <sys/time.h>
#include "thread_private.h"
#include "parameters.h"
#include "exception.h"
#define NUM_PAGES (4096 * config.get_nthreads())
bool align_req = false;
int align_size = PAGE_SIZE;
extern struct timeval global_start;
void check_read_content(char *buf, int size, off_t off)
{
// I assume the space in the buffer is larger than 8 bytes.
off_t aligned_off = off & (~(sizeof(off_t) - 1));
long data[2];
data[0] = aligned_off / sizeof(off_t);
data[1] = aligned_off / sizeof(off_t) + 1;
long expected = 0;
int copy_size = size < (int) sizeof(off_t) ? size : (int) sizeof(off_t);
memcpy(&expected, ((char *) data) + (off - aligned_off), copy_size);
long read_value = 0;
memcpy(&read_value, buf, copy_size);
if(read_value != expected)
printf("%ld %ld\n", read_value, expected);
assert(read_value == expected);
}
void create_write_data(char *buf, int size, off_t off)
{
off_t aligned_start = off & (~(sizeof(off_t) - 1));
off_t aligned_end = (off + size) & (~(sizeof(off_t) - 1));
long start_data = aligned_start / sizeof(off_t);
long end_data = aligned_end / sizeof(off_t);
/* If all data is in one 8-byte word. */
if (aligned_start == aligned_end) {
memcpy(buf, ((char *) &start_data) + (off - aligned_start), size);
return;
}
int first_size = (int)(sizeof(off_t) - (off - aligned_start));
int last_size = (int) (off + size - aligned_end);
if (first_size == sizeof(off_t))
first_size = 0;
if (first_size)
memcpy(buf, ((char *) &start_data) + (off - aligned_start),
first_size);
// Make each buffer written to SSDs different, so it's hard for SSDs
// to do some tricks on it.
struct timeval zero = {0, 0};
long diff = time_diff_us(zero, global_start);
for (int i = first_size; i < aligned_end - off; i += sizeof(off_t)) {
*((long *) (buf + i)) = (off + i) / sizeof(off_t) + diff;
}
if (aligned_end > aligned_start
|| (aligned_end == aligned_start && first_size == 0)) {
if (last_size)
memcpy(buf + (aligned_end - off), (char *) &end_data, last_size);
}
check_read_content(buf, size, off);
}
class cleanup_callback: public callback
{
rand_buf *buf;
ssize_t read_bytes;
int thread_id;
thread_private *thread;
public:
cleanup_callback(rand_buf *buf, int idx, thread_private *thread) {
this->buf = buf;
read_bytes = 0;
this->thread_id = idx;
this->thread = thread;
}
int invoke(io_request *rqs[], int num) {
for (int i = 0; i < num; i++) {
io_request *rq = rqs[i];
if (rq->get_access_method() == READ && config.is_verify_read()) {
off_t off = rq->get_offset();
for (int i = 0; i < rq->get_num_bufs(); i++) {
check_read_content(rq->get_buf(i), rq->get_buf_size(i), off);
off += rq->get_buf_size(i);
}
}
for (int i = 0; i < rq->get_num_bufs(); i++)
buf->free_entry(rq->get_buf(i));
read_bytes += rq->get_size();
}
#ifdef STATISTICS
thread->num_completes.inc(num);
thread->num_pending.dec(num);
#endif
return 0;
}
ssize_t get_size() {
return read_bytes;
}
};
ssize_t thread_private::get_read_bytes() {
if (cb)
return cb->get_size();
else
return read_bytes;
}
void thread_private::init() {
io = factory->create_io(this);
io->set_max_num_pending_ios(sys_params.get_aio_depth_per_file());
io->init();
rand_buf *buf = new rand_buf(NUM_PAGES / config.get_nthreads() * PAGE_SIZE,
config.get_buf_size(), node_id);
this->buf = buf;
if (io->support_aio()) {
cb = new cleanup_callback(buf, idx, this);
io->set_callback(cb);
}
}
class work2req_converter
{
workload_t workload;
int align_size;
rand_buf *buf;
io_interface *io;
public:
work2req_converter(io_interface *io, rand_buf * buf, int align_size) {
workload.off = -1;
workload.size = -1;
workload.read = 0;
this->align_size = align_size;
this->buf = buf;
this->io = io;
}
void init(const workload_t &workload) {
this->workload = workload;
if (align_size > 0) {
this->workload.off = ROUND(workload.off, align_size);
this->workload.size = ROUNDUP(workload.off
+ workload.size, align_size)
- ROUND(workload.off, align_size);
}
}
bool has_complete() const {
return workload.size <= 0;
}
int to_reqs(int buf_type, int num, io_request reqs[]);
};
int work2req_converter::to_reqs(int buf_type, int num, io_request reqs[])
{
int node_id = io->get_node_id();
int access_method = workload.read ? READ : WRITE;
off_t off = workload.off;
int size = workload.size;
if (buf_type == MULTI_BUF) {
throw unsupported_exception();
#if 0
assert(off % PAGE_SIZE == 0);
int num_vecs = size / PAGE_SIZE;
reqs[i].init(off, io, access_method, node_id);
assert(buf->get_entry_size() >= PAGE_SIZE);
for (int k = 0; k < num_vecs; k++) {
reqs[i].add_buf(buf->next_entry(PAGE_SIZE), PAGE_SIZE);
}
workload.off += size;
workload.size = 0;
#endif
}
else if (buf_type == SINGLE_SMALL_BUF) {
int i = 0;
while (size > 0 && i < num) {
off_t next_off = ROUNDUP_PAGE(off + 1);
if (next_off > off + size)
next_off = off + size;
char *p = buf->next_entry(next_off - off);
if (p == NULL)
break;
if (access_method == WRITE && config.is_verify_read())
create_write_data(p, next_off - off, off);
reqs[i].init(p, off, next_off - off, access_method,
io, node_id);
size -= next_off - off;
off = next_off;
i++;
}
workload.off = off;
workload.size = size;
return i;
}
else {
char *p = buf->next_entry(size);
if (p == NULL)
return 0;
if (access_method == WRITE && config.is_verify_read())
create_write_data(p, size, off);
reqs[0].init(p, off, size, access_method, io, node_id);
return 1;
}
}
void thread_private::run()
{
gettimeofday(&start_time, NULL);
io_request reqs[NUM_REQS_BY_USER];
char *entry = NULL;
if (config.is_use_aio())
assert(io->support_aio());
if (!config.is_use_aio()) {
entry = (char *) valloc(config.get_buf_size());
}
work2req_converter converter(io, buf, align_size);
while (gen->has_next()) {
if (config.is_use_aio()) {
int i;
int num_reqs_by_user = min(io->get_remaining_io_slots(), NUM_REQS_BY_USER);
for (i = 0; i < num_reqs_by_user; ) {
if (converter.has_complete() && gen->has_next()) {
converter.init(gen->next());
}
int ret = converter.to_reqs(config.get_buf_type(),
num_reqs_by_user - i, reqs + i);
if (ret == 0)
break;
i += ret;
}
io->access(reqs, i);
while (io->get_remaining_io_slots() <= 0) {
int num_ios = io->get_max_num_pending_ios() / 10;
if (num_ios == 0)
num_ios = 1;
io->wait4complete(num_ios);
}
num_accesses += i;
#ifdef STATISTICS
int curr = num_pending.inc(i);
if (max_num_pending < curr)
max_num_pending = curr;
if (num_accesses % 100 == 0) {
num_sampling++;
tot_num_pending += curr;
}
#endif
}
else {
int ret = 0;
workload_t workload = gen->next();
off_t off = workload.off;
int access_method = workload.read ? READ : WRITE;
int entry_size = workload.size;
if (align_req) {
off = ROUND(off, align_size);
entry_size = ROUNDUP(off + entry_size, align_size)
- ROUND(off, align_size);
}
if (config.get_buf_type() == SINGLE_SMALL_BUF) {
while (entry_size > 0) {
/*
* generate the data for writing the file,
* so the data in the file isn't changed.
*/
if (access_method == WRITE && config.is_verify_read()) {
create_write_data(entry, entry_size, off);
}
// There is at least one byte we need to access in the page.
// By adding 1 and rounding up the offset, we'll get the next page
// behind the current offset.
off_t next_off = ROUNDUP_PAGE(off + 1);
if (next_off > off + entry_size)
next_off = off + entry_size;
io_status status = io->access(entry, off, next_off - off,
access_method);
assert(!(status == IO_UNSUPPORTED));
if (status == IO_OK) {
num_accesses++;
if (access_method == READ && config.is_verify_read()) {
check_read_content(entry, next_off - off, off);
}
read_bytes += ret;
}
if (status == IO_FAIL) {
perror("access");
::exit(1);
}
entry_size -= next_off - off;
off = next_off;
}
}
else {
if (access_method == WRITE && config.is_verify_read()) {
create_write_data(entry, entry_size, off);
}
io_status status = io->access(entry, off, entry_size,
access_method);
assert(!(status == IO_UNSUPPORTED));
if (status == IO_OK) {
num_accesses++;
if (access_method == READ && config.is_verify_read()) {
check_read_content(entry, entry_size, off);
}
read_bytes += ret;
}
if (status == IO_FAIL) {
perror("access");
::exit(1);
}
}
}
}
printf("thread %d has issued all requests\n", idx);
io->cleanup();
gettimeofday(&end_time, NULL);
// Stop itself.
stop();
}
int thread_private::attach2cpu()
{
#if 0
cpu_set_t cpuset;
pthread_t thread = pthread_self();
CPU_ZERO(&cpuset);
int cpu_num = idx % NCPUS;
CPU_SET(cpu_num, &cpuset);
int ret = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
if (ret != 0) {
perror("pthread_setaffinity_np");
exit(1);
}
return ret;
#endif
return 0;
}
#ifdef USE_PROCESS
static int process_create(pid_t *pid, void (*func)(void *), void *priv)
{
pid_t id = fork();
if (id < 0)
return -1;
if (id == 0) { // child
func(priv);
exit(0);
}
if (id > 0)
*pid = id;
return 0;
}
static int process_join(pid_t pid)
{
int status;
pid_t ret = waitpid(pid, &status, 0);
return ret < 0 ? ret : 0;
}
#endif
<commit_msg>Redefine the semantics of the option buf_size.<commit_after>#include <sys/time.h>
#include "thread_private.h"
#include "parameters.h"
#include "exception.h"
bool align_req = false;
int align_size = PAGE_SIZE;
extern struct timeval global_start;
void check_read_content(char *buf, int size, off_t off)
{
// I assume the space in the buffer is larger than 8 bytes.
off_t aligned_off = off & (~(sizeof(off_t) - 1));
long data[2];
data[0] = aligned_off / sizeof(off_t);
data[1] = aligned_off / sizeof(off_t) + 1;
long expected = 0;
int copy_size = size < (int) sizeof(off_t) ? size : (int) sizeof(off_t);
memcpy(&expected, ((char *) data) + (off - aligned_off), copy_size);
long read_value = 0;
memcpy(&read_value, buf, copy_size);
if(read_value != expected)
printf("%ld %ld\n", read_value, expected);
assert(read_value == expected);
}
void create_write_data(char *buf, int size, off_t off)
{
off_t aligned_start = off & (~(sizeof(off_t) - 1));
off_t aligned_end = (off + size) & (~(sizeof(off_t) - 1));
long start_data = aligned_start / sizeof(off_t);
long end_data = aligned_end / sizeof(off_t);
/* If all data is in one 8-byte word. */
if (aligned_start == aligned_end) {
memcpy(buf, ((char *) &start_data) + (off - aligned_start), size);
return;
}
int first_size = (int)(sizeof(off_t) - (off - aligned_start));
int last_size = (int) (off + size - aligned_end);
if (first_size == sizeof(off_t))
first_size = 0;
if (first_size)
memcpy(buf, ((char *) &start_data) + (off - aligned_start),
first_size);
// Make each buffer written to SSDs different, so it's hard for SSDs
// to do some tricks on it.
struct timeval zero = {0, 0};
long diff = time_diff_us(zero, global_start);
for (int i = first_size; i < aligned_end - off; i += sizeof(off_t)) {
*((long *) (buf + i)) = (off + i) / sizeof(off_t) + diff;
}
if (aligned_end > aligned_start
|| (aligned_end == aligned_start && first_size == 0)) {
if (last_size)
memcpy(buf + (aligned_end - off), (char *) &end_data, last_size);
}
check_read_content(buf, size, off);
}
class cleanup_callback: public callback
{
rand_buf *buf;
ssize_t read_bytes;
int thread_id;
thread_private *thread;
public:
cleanup_callback(rand_buf *buf, int idx, thread_private *thread) {
this->buf = buf;
read_bytes = 0;
this->thread_id = idx;
this->thread = thread;
}
int invoke(io_request *rqs[], int num) {
for (int i = 0; i < num; i++) {
io_request *rq = rqs[i];
if (rq->get_access_method() == READ && config.is_verify_read()) {
off_t off = rq->get_offset();
for (int i = 0; i < rq->get_num_bufs(); i++) {
check_read_content(rq->get_buf(i), rq->get_buf_size(i), off);
off += rq->get_buf_size(i);
}
}
for (int i = 0; i < rq->get_num_bufs(); i++)
buf->free_entry(rq->get_buf(i));
read_bytes += rq->get_size();
}
#ifdef STATISTICS
thread->num_completes.inc(num);
thread->num_pending.dec(num);
#endif
return 0;
}
ssize_t get_size() {
return read_bytes;
}
};
ssize_t thread_private::get_read_bytes() {
if (cb)
return cb->get_size();
else
return read_bytes;
}
void thread_private::init() {
io = factory->create_io(this);
io->set_max_num_pending_ios(sys_params.get_aio_depth_per_file());
io->init();
rand_buf *buf = new rand_buf(config.get_buf_size(),
config.get_entry_size(), node_id);
this->buf = buf;
if (io->support_aio()) {
cb = new cleanup_callback(buf, idx, this);
io->set_callback(cb);
}
}
class work2req_converter
{
workload_t workload;
int align_size;
rand_buf *buf;
io_interface *io;
public:
work2req_converter(io_interface *io, rand_buf * buf, int align_size) {
workload.off = -1;
workload.size = -1;
workload.read = 0;
this->align_size = align_size;
this->buf = buf;
this->io = io;
}
void init(const workload_t &workload) {
this->workload = workload;
if (align_size > 0) {
this->workload.off = ROUND(workload.off, align_size);
this->workload.size = ROUNDUP(workload.off
+ workload.size, align_size)
- ROUND(workload.off, align_size);
}
}
bool has_complete() const {
return workload.size <= 0;
}
int to_reqs(int buf_type, int num, io_request reqs[]);
};
int work2req_converter::to_reqs(int buf_type, int num, io_request reqs[])
{
int node_id = io->get_node_id();
int access_method = workload.read ? READ : WRITE;
off_t off = workload.off;
int size = workload.size;
if (buf_type == MULTI_BUF) {
throw unsupported_exception();
#if 0
assert(off % PAGE_SIZE == 0);
int num_vecs = size / PAGE_SIZE;
reqs[i].init(off, io, access_method, node_id);
assert(buf->get_entry_size() >= PAGE_SIZE);
for (int k = 0; k < num_vecs; k++) {
reqs[i].add_buf(buf->next_entry(PAGE_SIZE), PAGE_SIZE);
}
workload.off += size;
workload.size = 0;
#endif
}
else if (buf_type == SINGLE_SMALL_BUF) {
int i = 0;
while (size > 0 && i < num) {
off_t next_off = ROUNDUP_PAGE(off + 1);
if (next_off > off + size)
next_off = off + size;
char *p = buf->next_entry(next_off - off);
if (p == NULL)
break;
if (access_method == WRITE && config.is_verify_read())
create_write_data(p, next_off - off, off);
reqs[i].init(p, off, next_off - off, access_method,
io, node_id);
size -= next_off - off;
off = next_off;
i++;
}
workload.off = off;
workload.size = size;
return i;
}
else {
char *p = buf->next_entry(size);
if (p == NULL)
return 0;
if (access_method == WRITE && config.is_verify_read())
create_write_data(p, size, off);
reqs[0].init(p, off, size, access_method, io, node_id);
return 1;
}
}
void thread_private::run()
{
gettimeofday(&start_time, NULL);
io_request reqs[NUM_REQS_BY_USER];
char *entry = NULL;
if (config.is_use_aio())
assert(io->support_aio());
if (!config.is_use_aio()) {
entry = (char *) valloc(config.get_entry_size());
}
work2req_converter converter(io, buf, align_size);
while (gen->has_next()) {
if (config.is_use_aio()) {
int i;
int num_reqs_by_user = min(io->get_remaining_io_slots(), NUM_REQS_BY_USER);
for (i = 0; i < num_reqs_by_user; ) {
if (converter.has_complete() && gen->has_next()) {
converter.init(gen->next());
}
int ret = converter.to_reqs(config.get_buf_type(),
num_reqs_by_user - i, reqs + i);
if (ret == 0)
break;
i += ret;
}
io->access(reqs, i);
while (io->get_remaining_io_slots() <= 0) {
int num_ios = io->get_max_num_pending_ios() / 10;
if (num_ios == 0)
num_ios = 1;
io->wait4complete(num_ios);
}
num_accesses += i;
#ifdef STATISTICS
int curr = num_pending.inc(i);
if (max_num_pending < curr)
max_num_pending = curr;
if (num_accesses % 100 == 0) {
num_sampling++;
tot_num_pending += curr;
}
#endif
}
else {
int ret = 0;
workload_t workload = gen->next();
off_t off = workload.off;
int access_method = workload.read ? READ : WRITE;
int entry_size = workload.size;
if (align_req) {
off = ROUND(off, align_size);
entry_size = ROUNDUP(off + entry_size, align_size)
- ROUND(off, align_size);
}
if (config.get_buf_type() == SINGLE_SMALL_BUF) {
while (entry_size > 0) {
/*
* generate the data for writing the file,
* so the data in the file isn't changed.
*/
if (access_method == WRITE && config.is_verify_read()) {
create_write_data(entry, entry_size, off);
}
// There is at least one byte we need to access in the page.
// By adding 1 and rounding up the offset, we'll get the next page
// behind the current offset.
off_t next_off = ROUNDUP_PAGE(off + 1);
if (next_off > off + entry_size)
next_off = off + entry_size;
io_status status = io->access(entry, off, next_off - off,
access_method);
assert(!(status == IO_UNSUPPORTED));
if (status == IO_OK) {
num_accesses++;
if (access_method == READ && config.is_verify_read()) {
check_read_content(entry, next_off - off, off);
}
read_bytes += ret;
}
if (status == IO_FAIL) {
perror("access");
::exit(1);
}
entry_size -= next_off - off;
off = next_off;
}
}
else {
if (access_method == WRITE && config.is_verify_read()) {
create_write_data(entry, entry_size, off);
}
io_status status = io->access(entry, off, entry_size,
access_method);
assert(!(status == IO_UNSUPPORTED));
if (status == IO_OK) {
num_accesses++;
if (access_method == READ && config.is_verify_read()) {
check_read_content(entry, entry_size, off);
}
read_bytes += ret;
}
if (status == IO_FAIL) {
perror("access");
::exit(1);
}
}
}
}
printf("thread %d has issued all requests\n", idx);
io->cleanup();
gettimeofday(&end_time, NULL);
// Stop itself.
stop();
}
int thread_private::attach2cpu()
{
#if 0
cpu_set_t cpuset;
pthread_t thread = pthread_self();
CPU_ZERO(&cpuset);
int cpu_num = idx % NCPUS;
CPU_SET(cpu_num, &cpuset);
int ret = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
if (ret != 0) {
perror("pthread_setaffinity_np");
exit(1);
}
return ret;
#endif
return 0;
}
#ifdef USE_PROCESS
static int process_create(pid_t *pid, void (*func)(void *), void *priv)
{
pid_t id = fork();
if (id < 0)
return -1;
if (id == 0) { // child
func(priv);
exit(0);
}
if (id > 0)
*pid = id;
return 0;
}
static int process_join(pid_t pid)
{
int status;
pid_t ret = waitpid(pid, &status, 0);
return ret < 0 ? ret : 0;
}
#endif
<|endoftext|> |
<commit_before>#include "AnnSpace.hpp"
namespace Elysia{
AnnSpace::AnnSpace(){
child[0] = NULL;
child[1] = NULL;
parent = NULL;
}
AnnSpace::~AnnSpace(){
if(child[0] != NULL){
delete child[0];
}
if(child[1] != NULL){
delete child[1];
}
}
bool AnnSpace::isLeaf(){
if (child[0] == NULL && child[1] == NULL){
return true;
}
else{
return false;
}
}
int AnnSpace::chooseChild(float x, float y){
if(whichAxis == XAXIS){
if(x > partitionPoint){
return 1;
}
else{
return 0;
}
}
else{
if(y > partitionPoint){return 1;}
else{return 0;}
}
}
class ComparePlaceablebyY {
public:
bool operator() (const Placeable*a, const Placeable*b) const {
return a->getLocation().y<b->getLocation().y;
}
};
class ComparePlaceablebyX {
public:
bool operator() (const Placeable*a, const Placeable*b) const {
return a->getLocation().x<b->getLocation().x;
}
};
void AnnSpace::partitionSpace(TreeNNSpatialSearch* treenn){
std::vector<float> XArray;
std::vector<float> YArray;
for(std::vector<Placeable*>::iterator i=placeableList.begin();i!=placeableList.end();++i){
Placeable* current=*i;
Vector3f location = current->getLocation();
XArray.push_back(location.x);
YArray.push_back(location.y);
}
child[0] = new AnnSpace();
child[1] = new AnnSpace();
child[0]->setParent(this);
child[1]->setParent(this);
//This algorithm is a super primitive way of partitioning the space. Something like k-means might be better
//As the number of points becomes large, I expect the exactness of this for ANN improves and it's not that
//bad to begin with. If someone wants to put k-means in here (or some other thing for calling partitions), cool.
sort(XArray.begin(), XArray.end());
sort(YArray.begin(), YArray.end());
float Xdist = XArray[int(XArray.size()/2) + 1] - XArray[int(XArray.size()/2)];
float Ydist = YArray[int(YArray.size()/2) + 1] - YArray[int(YArray.size()/2)];
if(Xdist > Ydist){
whichAxis = XAXIS;
std::sort(placeableList.begin(),placeableList.end(),ComparePlaceablebyX());
Placeable* midpoint = placeableList[int(placeableList.size()/2)];
partitionPoint = (XArray[int(XArray.size()/2) + 1] + XArray[int(XArray.size()/2)])/2;
for(std::vector<Placeable*>::iterator i=placeableList.begin();i!=placeableList.end();++i){
this->addPoint(*i, treenn);
}
}
else{
float test = FLT_MAX;
whichAxis = YAXIS;
std::sort(placeableList.begin(),placeableList.end(),ComparePlaceablebyY());
Placeable* midpoint = placeableList[int(placeableList.size()/2)];
partitionPoint = (YArray[int(YArray.size()/2) + 1] + YArray[int(YArray.size()/2)])/2;
for(std::vector<Placeable*>::iterator i=placeableList.begin();i!=placeableList.end();++i){
this->addPoint(*i, treenn);
}
}
placeableList.clear();
}
void AnnSpace::deletePoint(Placeable* placeable, TreeNNSpatialSearch* treenn){
if(this->isLeaf()){
std::vector<Placeable*>::iterator result = std::find(placeableList.begin(), placeableList.end(), placeable);
placeableList.erase(result);
if(placeableList.size() < treenn->pointLowerThreshold){
if(parent != NULL){
parent -> mergeSpace(treenn);
}
}
}
else{
Vector3f location = placeable->getLocation();
child[chooseChild(location.x, location.y)] -> deletePoint(placeable, treenn);
}
}
void AnnSpace::addPoint(Placeable* placeable, TreeNNSpatialSearch* treenn){
if(this->isLeaf()){
placeableList.push_back(placeable);
if(placeableList.size() + 1 > treenn->pointUpperThreshold){
this->partitionSpace(treenn);
}
}
else{
Vector3f location = placeable->getLocation();
child[chooseChild(location.x, location.y)] -> addPoint(placeable, treenn);
}
}
Placeable* AnnSpace::findNN(float x, float y, Placeable* exclude){
if(this->isLeaf()){
Vector3f queryPoint;
queryPoint.x = x;
queryPoint.y = y;
queryPoint.z = 0;
float maxDistance;
Placeable * maxDistanceItem=NULL;
for(std::vector<Placeable*>::iterator i=placeableList.begin();i!=placeableList.end();++i) {
Placeable * current=*i;//find out what's "inside" i
float currentDistance=(current->getLocation()-queryPoint).length();
if ((maxDistanceItem==NULL || currentDistance<maxDistance) && current != exclude){
maxDistance=currentDistance;
maxDistanceItem=current;
}
}
return maxDistanceItem;
}
else{
return child[chooseChild(x, y)] -> findNN(x, y, exclude);
}
}
void AnnSpace::mergeSpace(TreeNNSpatialSearch* treenn){
//First find whether both children are leaves
if(child[0]->isLeaf() && child[1]->isLeaf()){
partitionPoint = 0.0f;
std::vector<Placeable*> newPlaceableList;
newPlaceableList = child[0]->getChildList();
for(std::vector<Placeable*>::iterator i=newPlaceableList.begin();i!=newPlaceableList.end();++i) {
Placeable* current=*i;
this->placeableList.push_back(current);
}
newPlaceableList = child[1]->getChildList();
for(std::vector<Placeable*>::iterator i=newPlaceableList.begin();i!=newPlaceableList.end();++i) {
Placeable* current=*i;
this->placeableList.push_back(current);
}
delete child[0];
delete child[1];
child[0] = NULL;
child[1] = NULL;
}
//If one child is not a leaf,
else{
AnnSpace* departingChild;
AnnSpace* remainingChild;
float newPartition;
if(child[0]->isLeaf()){
newPartition = FLT_MAX;
departingChild = child[0];
remainingChild = child[1];
child[0] = NULL;
}
else{
float newPartition = FLT_MIN;
departingChild = child[1];
remainingChild = child[0];
child[1] = NULL;
}
remainingChild->setPartition(newPartition);
std::vector<Placeable*> newPlaceableList;
newPlaceableList = departingChild->getChildList();
for(std::vector<Placeable*>::iterator i=newPlaceableList.begin();i!=newPlaceableList.end();++i) {
Placeable* current=*i;
remainingChild->placeableList.push_back(current);
}
delete departingChild;
}
}
std::vector<Placeable*> AnnSpace::getChildList(){
return placeableList;
}
}
<commit_msg>Ok, added additional controls to ANN. Still failing<commit_after>#include "AnnSpace.hpp"
namespace Elysia{
AnnSpace::AnnSpace(){
child[0] = NULL;
child[1] = NULL;
parent = NULL;
}
AnnSpace::~AnnSpace(){
if(child[0] != NULL){
delete child[0];
}
if(child[1] != NULL){
delete child[1];
}
}
bool AnnSpace::isLeaf(){
if (child[0] == NULL && child[1] == NULL){
return true;
}
else{
return false;
}
}
int AnnSpace::chooseChild(float x, float y){
if(whichAxis == XAXIS){
if(x > partitionPoint){
return 1;
}
else{
return 0;
}
}
else{
if(y > partitionPoint){return 1;}
else{return 0;}
}
}
class ComparePlaceablebyY {
public:
bool operator() (const Placeable*a, const Placeable*b) const {
return a->getLocation().y<b->getLocation().y;
}
};
class ComparePlaceablebyX {
public:
bool operator() (const Placeable*a, const Placeable*b) const {
return a->getLocation().x<b->getLocation().x;
}
};
void AnnSpace::partitionSpace(TreeNNSpatialSearch* treenn){
std::vector<float> XArray;
std::vector<float> YArray;
for(std::vector<Placeable*>::iterator i=placeableList.begin();i!=placeableList.end();++i){
Placeable* current=*i;
Vector3f location = current->getLocation();
XArray.push_back(location.x);
YArray.push_back(location.y);
}
child[0] = new AnnSpace();
child[1] = new AnnSpace();
child[0]->setParent(this);
child[1]->setParent(this);
//This algorithm is a super primitive way of partitioning the space. Something like k-means might be better
//As the number of points becomes large, I expect the exactness of this for ANN improves and it's not that
//bad to begin with. If someone wants to put k-means in here (or some other thing for calling partitions), cool.
sort(XArray.begin(), XArray.end());
sort(YArray.begin(), YArray.end());
float Xdist = XArray[int(XArray.size()/2) + 1] - XArray[int(XArray.size()/2)];
float Ydist = YArray[int(YArray.size()/2) + 1] - YArray[int(YArray.size()/2)];
if(Xdist > Ydist){
whichAxis = XAXIS;
std::sort(placeableList.begin(),placeableList.end(),ComparePlaceablebyX());
Placeable* midpoint = placeableList[int(placeableList.size()/2)];
partitionPoint = (XArray[int(XArray.size()/2) + 1] + XArray[int(XArray.size()/2)])/2;
for(std::vector<Placeable*>::iterator i=placeableList.begin();i!=placeableList.end();++i){
this->addPoint(*i, treenn);
}
}
else{
float test = FLT_MAX;
whichAxis = YAXIS;
std::sort(placeableList.begin(),placeableList.end(),ComparePlaceablebyY());
Placeable* midpoint = placeableList[int(placeableList.size()/2)];
partitionPoint = (YArray[int(YArray.size()/2) + 1] + YArray[int(YArray.size()/2)])/2;
for(std::vector<Placeable*>::iterator i=placeableList.begin();i!=placeableList.end();++i){
this->addPoint(*i, treenn);
}
}
placeableList.clear();
}
void AnnSpace::deletePoint(Placeable* placeable, TreeNNSpatialSearch* treenn){
if(this->isLeaf()){
std::vector<Placeable*>::iterator result = std::find(placeableList.begin(), placeableList.end(), placeable);
placeableList.erase(result);
if(placeableList.size() < treenn->pointLowerThreshold){
if(parent != NULL){
parent -> mergeSpace(treenn);
}
}
}
else{
Vector3f location = placeable->getLocation();
child[chooseChild(location.x, location.y)] -> deletePoint(placeable, treenn);
}
}
void AnnSpace::addPoint(Placeable* placeable, TreeNNSpatialSearch* treenn){
if(this->isLeaf()){
placeableList.push_back(placeable);
if(placeableList.size() + 1 > treenn->pointUpperThreshold){
this->partitionSpace(treenn);
}
}
else{
Vector3f location = placeable->getLocation();
child[chooseChild(location.x, location.y)] -> addPoint(placeable, treenn);
}
}
Placeable* AnnSpace::findNN(float x, float y, Placeable* exclude){
if(this->isLeaf()){
Vector3f queryPoint;
queryPoint.x = x;
queryPoint.y = y;
queryPoint.z = 0;
float maxDistance;
Placeable * maxDistanceItem=NULL;
for(std::vector<Placeable*>::iterator i=placeableList.begin();i!=placeableList.end();++i) {
Placeable * current=*i;//find out what's "inside" i
float currentDistance=(current->getLocation()-queryPoint).length();
if ((maxDistanceItem==NULL || currentDistance<maxDistance) && current != exclude){
maxDistance=currentDistance;
maxDistanceItem=current;
}
}
return maxDistanceItem;
}
else{
return child[chooseChild(x, y)] -> findNN(x, y, exclude);
}
}
void AnnSpace::mergeSpace(TreeNNSpatialSearch* treenn){
if(child[0] != NULL && child[1] != NULL){
//First find whether both children are leaves
if(child[0]->isLeaf() && child[1]->isLeaf()){
partitionPoint = 0.0f;
std::vector<Placeable*> newPlaceableList;
newPlaceableList = child[0]->getChildList();
for(std::vector<Placeable*>::iterator i=newPlaceableList.begin();i!=newPlaceableList.end();++i) {
Placeable* current=*i;
this->placeableList.push_back(current);
}
newPlaceableList = child[1]->getChildList();
for(std::vector<Placeable*>::iterator i=newPlaceableList.begin();i!=newPlaceableList.end();++i) {
Placeable* current=*i;
this->placeableList.push_back(current);
}
delete child[0];
delete child[1];
child[0] = NULL;
child[1] = NULL;
}
//If one child is not a leaf,
else{
AnnSpace* departingChild;
AnnSpace* remainingChild;
float newPartition;
if(child[0]->isLeaf()){
newPartition = FLT_MAX;
departingChild = child[0];
remainingChild = child[1];
child[0] = NULL;
}
else{
float newPartition = FLT_MIN;
departingChild = child[1];
remainingChild = child[0];
child[1] = NULL;
}
remainingChild->setPartition(newPartition);
std::vector<Placeable*> newPlaceableList;
newPlaceableList = departingChild->getChildList();
for(std::vector<Placeable*>::iterator i=newPlaceableList.begin();i!=newPlaceableList.end();++i) {
Placeable* current=*i;
remainingChild->placeableList.push_back(current);
}
delete departingChild;
}
}
else{
for(int i=0; i<2; i++){
if(child[i] != NULL){
std::vector<Placeable*> newPlaceableList;
newPlaceableList = child[i]->getChildList();
for(std::vector<Placeable*>::iterator j=newPlaceableList.begin();j!=newPlaceableList.end();++j) {
Placeable* current=*j;
this->placeableList.push_back(current);
}
delete child[i];
child[i] = NULL;
}
}
parent->mergeSpace(treenn);
}
}
std::vector<Placeable*> AnnSpace::getChildList(){
return placeableList;
}
}
<|endoftext|> |
<commit_before>#include "Parser.h"
namespace EpisodesParser {
EpisodeNameIDHash Parser::episodeNameIDHash;
DomainNameIDHash Parser::domainNameIDHash;
#ifdef DEBUG
EpisodeIDNameHash Parser::episodeIDNameHash;
DomainIDNameHash Parser::domainIDNameHash;
#endif
bool Parser::staticsInitialized = false;
QBrowsCap Parser::browsCap;
QGeoIP Parser::geoIP;
QMutex Parser::staticsInitializationMutex;
QMutex Parser::episodeHashMutex;
QMutex Parser::domainHashMutex;
QMutex Parser::regExpMutex;
QMutex Parser::dateTimeMutex;
Parser::Parser() {
// Only initialize some static members the first time an instance of
// this class is created.
this->staticsInitializationMutex.lock();
if (!this->staticsInitialized) {
this->browsCap.setCsvFile("/Users/wimleers/Desktop/browscap.csv");
this->browsCap.setIndexFile("/Users/wimleers/Desktop/browscap-index.db");
this->browsCap.buildIndex();
this->geoIP.openDatabases("./data/GeoIPCity.dat", "./data/GeoIPASNum.dat");
}
this->staticsInitializationMutex.unlock();
connect(this, SIGNAL(parsedChunk(QStringList)), SLOT(processParsedChunk(QStringList)));
}
/**
* Parse the given Episodes log file.
*
* Emits a signal for every chunk (with CHUNK_SIZE lines). This signal can
* then be used to process that chunk. This allows multiple chunks to be
* processed in parallel (by using QtConcurrent), if that is desired.
*
* @param fileName
* The full path to an Episodes log file.
* @return
* -1 if the log file could not be read. Otherwise: the number of lines
* parsed.
*/
int Parser::parse(const QString & fileName) {
QFile file;
QStringList chunk;
int numLines = 0;
file.setFileName(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return -1;
else {
QTextStream in(&file);
while (!in.atEnd()) {
chunk.append(in.readLine());
numLines++;
if (chunk.size() == CHUNK_SIZE) {
emit parsedChunk(chunk);
chunk.clear();
}
}
// Check if we have another chunk (with size < CHUNK_SIZE).
if (chunk.size() > 0) {
emit parsedChunk(chunk);
}
return numLines;
}
}
//---------------------------------------------------------------------------
// Protected methods.
/**
* Map an episode name to an episode ID. Generate a new ID when necessary.
*
* @param name
* Episode name.
* @return
* The corresponding episode ID.
*
* Modifies a class variable upon some calls (i.e. when a new key must be
* inserted in the QHash), hence we need to use a mutex to ensure thread
* safety.
*/
EpisodeID Parser::mapEpisodeNameToID(EpisodeName name) {
if (!Parser::episodeNameIDHash.contains(name)) {
Parser::episodeHashMutex.lock();
EpisodeID id = Parser::episodeNameIDHash.size();
Parser::episodeNameIDHash.insert(name, id);
#ifdef DEBUG
Parser::episodeIDNameHash.insert(id, name);
#endif
Parser::episodeHashMutex.unlock();
}
return Parser::episodeNameIDHash[name];
}
/**
* Map a domain name to a domain ID. Generate a new ID when necessary.
*
* @param name
* Domain name.
* @return
* The corresponding domain ID.
*
* Modifies a class variable upon some calls (i.e. when a new key must be
* inserted in the QHash), hence we need to use a mutex to ensure thread
* safety.
*/
DomainID Parser::mapDomainNameToID(DomainName name) {
if (!Parser::domainNameIDHash.contains(name)) {
Parser::domainHashMutex.lock();
DomainID id = Parser::domainNameIDHash.size();
Parser::domainNameIDHash.insert(name, id);
#ifdef DEBUG
Parser::domainIDNameHash.insert(id, name);
#endif
Parser::domainHashMutex.unlock();
}
return Parser::domainNameIDHash[name];
}
/**
* Map a line (raw string) to an EpisodesLogLine data structure.
*
* @param line
* Raw line, as read from the episodes log file.
* @return
* Corresponding EpisodesLogLine data structure.
*/
EpisodesLogLine Parser::mapLineToEpisodesLogLine(const QString & line) {
static QDateTime timeConvertor;
QStringList list, episodesRaw, episodeParts;
QString dateTime;
int timezoneOffset;
Episode episode;
EpisodesLogLine parsedLine;
Parser::regExpMutex.lock();
QRegExp rx("((?:\\d{1,3}\\.){3}\\d{1,3}) \\[\\w+, ([^\\]]+)\\] \\\"\\?ets=([^\\\"]+)\\\" (\\d{3}) \\\"([^\\\"]+)\\\" \\\"([^\\\"]+)\\\" \\\"([^\\\"]+)\\\"");
rx.indexIn(line);
list = rx.capturedTexts();
Parser::regExpMutex.unlock();
// IP address.
parsedLine.ip.setAddress(list[1]);
// Time.
dateTime = list[2].left(20);
timezoneOffset = list[2].right(5).left(3).toInt();
Parser::dateTimeMutex.lock();
timeConvertor = QDateTime::fromString(dateTime, "dd-MMM-yyyy HH:mm:ss");
// Mark this QDateTime as one with a certain offset from UTC, and
// set that offset.
timeConvertor.setTimeSpec(Qt::OffsetFromUTC);
timeConvertor.setUtcOffset(timezoneOffset * 3600);
// Convert this QDateTime to UTC.
timeConvertor = timeConvertor.toUTC();
// Store the UTC timestamp.
parsedLine.time = timeConvertor.toTime_t();
Parser::dateTimeMutex.unlock();
// Episode names and durations.
episodesRaw = list[3].split(',');
foreach (QString episodeRaw, episodesRaw) {
episodeParts = episodeRaw.split(':');
episode.id = Parser::mapEpisodeNameToID(episodeParts[0]);
episode.duration = episodeParts[1].toInt();
#ifdef DEBUG
episode.IDNameHash = &Parser::episodeIDNameHash;
#endif
parsedLine.episodes.append(episode);
}
// HTTP status code.
parsedLine.status = list[4].toShort();
// URL.
parsedLine.url = list[5];
// User-Agent.
parsedLine.ua = list[6];
// Domain name.
parsedLine.domain.id = Parser::mapDomainNameToID(list[7]);
#ifdef DEBUG
parsedLine.domain.IDNameHash = &domainIDNameHash;
#endif
#ifdef DEBUG
/*
parsedLine.episodeIDNameHash = &Parser::episodeIDNameHash;
parsedLine.domainIDNameHash = &Parser::domainIDNameHash;
qDebug() << parsedLine;
*/
#endif
return parsedLine;
}
/**
* Expand an EpisodesLogLine data structure to an ExpandedEpisodesLogLine
* data structure, which contains the expanded (hierarchical) versions
* of the ip and User Agent values. I.e. these expanded versions provide
* a concept hierarchy.
*
* @param line
* EpisodesLogLine data structure.
* return
* Corresponding ExpandedEpisodesLogLine data structure.
*/
ExpandedEpisodesLogLine Parser::expandEpisodesLogLine(const EpisodesLogLine & line) {
ExpandedEpisodesLogLine expandedLine;
QGeoIPRecord geoIPRecord;
QPair<bool, QBrowsCapRecord> BCResult;
QBrowsCapRecord & BCRecord = BCResult.second;
// IP address hierarchy.
geoIPRecord = Parser::geoIP.recordByAddr(line.ip);
expandedLine.ip.ip = line.ip;
expandedLine.ip.continent = geoIPRecord.continentCode;
expandedLine.ip.country = geoIPRecord.country;
expandedLine.ip.city = geoIPRecord.city;
expandedLine.ip.region = geoIPRecord.region;
expandedLine.ip.isp = geoIPRecord.isp;
// Time.
expandedLine.time = line.time;
// Episode name and durations.
// @TODO: discretize to fast/acceptable/slow.
expandedLine.episodes = line.episodes;
// URL.
expandedLine.url = line.url;
// User-Agent hierarchy.
BCResult = Parser::browsCap.matchUserAgent(line.ua);
BCRecord = BCResult.second;
expandedLine.ua.ua = line.ua;
expandedLine.ua.platform = BCRecord.platform;
expandedLine.ua.browser_name = BCRecord.browser_name;
expandedLine.ua.browser_version = BCRecord.browser_version;
expandedLine.ua.browser_version_major = BCRecord.browser_version_major;
expandedLine.ua.browser_version_minor = BCRecord.browser_version_minor;
expandedLine.ua.is_mobile = BCRecord.is_mobile;
return expandedLine;
}
ExpandedEpisodesLogLine Parser::mapAndExpandToEpisodesLogLine(const QString & line) {
return Parser::expandEpisodesLogLine(Parser::mapLineToEpisodesLogLine(line));
}
//---------------------------------------------------------------------------
// Protected slots.
void Parser::processParsedChunk(const QStringList & chunk) {
// QList<EpisodesLogLine> processedChunk = QtConcurrent::blockingMapped(chunk, Parser::mapLineToEpisodesLogLine);
// QtConcurrent::blockingMapped(processedChunk, Parser::expandEpisodesLogLine);
QString line;
foreach (line, chunk) {
Parser::mapAndExpandToEpisodesLogLine(line);
}
// QtConcurrent::blockingMapped(chunk, Parser::mapAndExpandToEpisodesLogLine);
}
}
<commit_msg>Since a 100% concurrent approach is not possible due to thread-safety issues in QGeoIP, go with a partially concurrent approach that still provides a significant speed-up.<commit_after>#include "Parser.h"
namespace EpisodesParser {
EpisodeNameIDHash Parser::episodeNameIDHash;
DomainNameIDHash Parser::domainNameIDHash;
#ifdef DEBUG
EpisodeIDNameHash Parser::episodeIDNameHash;
DomainIDNameHash Parser::domainIDNameHash;
#endif
bool Parser::staticsInitialized = false;
QBrowsCap Parser::browsCap;
QGeoIP Parser::geoIP;
QMutex Parser::staticsInitializationMutex;
QMutex Parser::episodeHashMutex;
QMutex Parser::domainHashMutex;
QMutex Parser::regExpMutex;
QMutex Parser::dateTimeMutex;
Parser::Parser() {
// Only initialize some static members the first time an instance of
// this class is created.
this->staticsInitializationMutex.lock();
if (!this->staticsInitialized) {
this->browsCap.setCsvFile("/Users/wimleers/Desktop/browscap.csv");
this->browsCap.setIndexFile("/Users/wimleers/Desktop/browscap-index.db");
this->browsCap.buildIndex();
this->geoIP.openDatabases("./data/GeoIPCity.dat", "./data/GeoIPASNum.dat");
}
this->staticsInitializationMutex.unlock();
connect(this, SIGNAL(parsedChunk(QStringList)), SLOT(processParsedChunk(QStringList)));
}
/**
* Parse the given Episodes log file.
*
* Emits a signal for every chunk (with CHUNK_SIZE lines). This signal can
* then be used to process that chunk. This allows multiple chunks to be
* processed in parallel (by using QtConcurrent), if that is desired.
*
* @param fileName
* The full path to an Episodes log file.
* @return
* -1 if the log file could not be read. Otherwise: the number of lines
* parsed.
*/
int Parser::parse(const QString & fileName) {
QFile file;
QStringList chunk;
int numLines = 0;
file.setFileName(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return -1;
else {
QTextStream in(&file);
while (!in.atEnd()) {
chunk.append(in.readLine());
numLines++;
if (chunk.size() == CHUNK_SIZE) {
emit parsedChunk(chunk);
chunk.clear();
}
}
// Check if we have another chunk (with size < CHUNK_SIZE).
if (chunk.size() > 0) {
emit parsedChunk(chunk);
}
return numLines;
}
}
//---------------------------------------------------------------------------
// Protected methods.
/**
* Map an episode name to an episode ID. Generate a new ID when necessary.
*
* @param name
* Episode name.
* @return
* The corresponding episode ID.
*
* Modifies a class variable upon some calls (i.e. when a new key must be
* inserted in the QHash), hence we need to use a mutex to ensure thread
* safety.
*/
EpisodeID Parser::mapEpisodeNameToID(EpisodeName name) {
if (!Parser::episodeNameIDHash.contains(name)) {
Parser::episodeHashMutex.lock();
EpisodeID id = Parser::episodeNameIDHash.size();
Parser::episodeNameIDHash.insert(name, id);
#ifdef DEBUG
Parser::episodeIDNameHash.insert(id, name);
#endif
Parser::episodeHashMutex.unlock();
}
return Parser::episodeNameIDHash[name];
}
/**
* Map a domain name to a domain ID. Generate a new ID when necessary.
*
* @param name
* Domain name.
* @return
* The corresponding domain ID.
*
* Modifies a class variable upon some calls (i.e. when a new key must be
* inserted in the QHash), hence we need to use a mutex to ensure thread
* safety.
*/
DomainID Parser::mapDomainNameToID(DomainName name) {
if (!Parser::domainNameIDHash.contains(name)) {
Parser::domainHashMutex.lock();
DomainID id = Parser::domainNameIDHash.size();
Parser::domainNameIDHash.insert(name, id);
#ifdef DEBUG
Parser::domainIDNameHash.insert(id, name);
#endif
Parser::domainHashMutex.unlock();
}
return Parser::domainNameIDHash[name];
}
/**
* Map a line (raw string) to an EpisodesLogLine data structure.
*
* @param line
* Raw line, as read from the episodes log file.
* @return
* Corresponding EpisodesLogLine data structure.
*/
EpisodesLogLine Parser::mapLineToEpisodesLogLine(const QString & line) {
static QDateTime timeConvertor;
QStringList list, episodesRaw, episodeParts;
QString dateTime;
int timezoneOffset;
Episode episode;
EpisodesLogLine parsedLine;
Parser::regExpMutex.lock();
QRegExp rx("((?:\\d{1,3}\\.){3}\\d{1,3}) \\[\\w+, ([^\\]]+)\\] \\\"\\?ets=([^\\\"]+)\\\" (\\d{3}) \\\"([^\\\"]+)\\\" \\\"([^\\\"]+)\\\" \\\"([^\\\"]+)\\\"");
rx.indexIn(line);
list = rx.capturedTexts();
Parser::regExpMutex.unlock();
// IP address.
parsedLine.ip.setAddress(list[1]);
// Time.
dateTime = list[2].left(20);
timezoneOffset = list[2].right(5).left(3).toInt();
Parser::dateTimeMutex.lock();
timeConvertor = QDateTime::fromString(dateTime, "dd-MMM-yyyy HH:mm:ss");
// Mark this QDateTime as one with a certain offset from UTC, and
// set that offset.
timeConvertor.setTimeSpec(Qt::OffsetFromUTC);
timeConvertor.setUtcOffset(timezoneOffset * 3600);
// Convert this QDateTime to UTC.
timeConvertor = timeConvertor.toUTC();
// Store the UTC timestamp.
parsedLine.time = timeConvertor.toTime_t();
Parser::dateTimeMutex.unlock();
// Episode names and durations.
episodesRaw = list[3].split(',');
foreach (QString episodeRaw, episodesRaw) {
episodeParts = episodeRaw.split(':');
episode.id = Parser::mapEpisodeNameToID(episodeParts[0]);
episode.duration = episodeParts[1].toInt();
#ifdef DEBUG
episode.IDNameHash = &Parser::episodeIDNameHash;
#endif
parsedLine.episodes.append(episode);
}
// HTTP status code.
parsedLine.status = list[4].toShort();
// URL.
parsedLine.url = list[5];
// User-Agent.
parsedLine.ua = list[6];
// Domain name.
parsedLine.domain.id = Parser::mapDomainNameToID(list[7]);
#ifdef DEBUG
parsedLine.domain.IDNameHash = &domainIDNameHash;
#endif
#ifdef DEBUG
/*
parsedLine.episodeIDNameHash = &Parser::episodeIDNameHash;
parsedLine.domainIDNameHash = &Parser::domainIDNameHash;
qDebug() << parsedLine;
*/
#endif
return parsedLine;
}
/**
* Expand an EpisodesLogLine data structure to an ExpandedEpisodesLogLine
* data structure, which contains the expanded (hierarchical) versions
* of the ip and User Agent values. I.e. these expanded versions provide
* a concept hierarchy.
*
* @param line
* EpisodesLogLine data structure.
* return
* Corresponding ExpandedEpisodesLogLine data structure.
*/
ExpandedEpisodesLogLine Parser::expandEpisodesLogLine(const EpisodesLogLine & line) {
ExpandedEpisodesLogLine expandedLine;
QGeoIPRecord geoIPRecord;
QPair<bool, QBrowsCapRecord> BCResult;
QBrowsCapRecord & BCRecord = BCResult.second;
// IP address hierarchy.
geoIPRecord = Parser::geoIP.recordByAddr(line.ip);
expandedLine.ip.ip = line.ip;
expandedLine.ip.continent = geoIPRecord.continentCode;
expandedLine.ip.country = geoIPRecord.country;
expandedLine.ip.city = geoIPRecord.city;
expandedLine.ip.region = geoIPRecord.region;
expandedLine.ip.isp = geoIPRecord.isp;
// Time.
expandedLine.time = line.time;
// Episode name and durations.
// @TODO: discretize to fast/acceptable/slow.
expandedLine.episodes = line.episodes;
// URL.
expandedLine.url = line.url;
// User-Agent hierarchy.
BCResult = Parser::browsCap.matchUserAgent(line.ua);
BCRecord = BCResult.second;
expandedLine.ua.ua = line.ua;
expandedLine.ua.platform = BCRecord.platform;
expandedLine.ua.browser_name = BCRecord.browser_name;
expandedLine.ua.browser_version = BCRecord.browser_version;
expandedLine.ua.browser_version_major = BCRecord.browser_version_major;
expandedLine.ua.browser_version_minor = BCRecord.browser_version_minor;
expandedLine.ua.is_mobile = BCRecord.is_mobile;
return expandedLine;
}
ExpandedEpisodesLogLine Parser::mapAndExpandToEpisodesLogLine(const QString & line) {
return Parser::expandEpisodesLogLine(Parser::mapLineToEpisodesLogLine(line));
}
//---------------------------------------------------------------------------
// Protected slots.
void Parser::processParsedChunk(const QStringList & chunk) {
// This 100% concurrent approach fails, because QGeoIP still has
// thread-safety issues. Hence, we only do the mapping from a QString
// to an EpisodesLogLine concurrently for now.
// QtConcurrent::blockingMapped(chunk, Parser::mapAndExpandToEpisodesLogLine);
QList<EpisodesLogLine> mappedChunk = QtConcurrent::blockingMapped(chunk, Parser::mapLineToEpisodesLogLine);
QList<ExpandedEpisodesLogLine> expandedChunk;
EpisodesLogLine line;
foreach (line, mappedChunk) {
expandedChunk << Parser::expandEpisodesLogLine(line);
}
qDebug() << "Processed chunk! Size:" << expandedChunk.size();
}
}
<|endoftext|> |
<commit_before>#include "tinfra/io/stream.h"
#include "tinfra/io/socket.h"
#include "tinfra/fmt.h"
#include "tinfra/string.h" // debug only
#include <iostream> // debug only
#ifdef _WIN32
#include <winsock.h>
#define TS_WINSOCK
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#define TS_BSD
#endif
using namespace std;
namespace tinfra {
namespace io {
namespace socket {
/*
class stream {
virtual ~stream() {}
enum {
start,
end,
current
} seek_origin;
void close() = 0;
int seek(int pos, seek_origin origin = start) = 0;
int read(char* dest, int size) = 0;
int write(const char* data, int size) = 0;
};
*/
#ifdef TS_WINSOCK
typedef SOCKET socket_type;
#else
typedef int socket_type;
#endif
static const socket_type invalid_socket = static_cast<socket_type>(-1);
static void close_socket(socket_type socket);
static void throw_socket_error(const char* message);
// TODO this log facility should be tinfra-wide
#ifdef _DEBUG
static void L(const std::string& msg)
{
//std::cerr << "socket: " << escape_c(msg) << std::endl;
}
#else
#define L(a) (void)0
#endif
class socketstream: public stream {
socket_type socket_;
public:
socketstream(socket_type socket): socket_(socket) {}
~socketstream() {
if( socket_ != invalid_socket )
close();
}
void close() {
close_socket(socket_);
socket_ = invalid_socket;
}
int seek(int pos, stream::seek_origin origin)
{
throw io_exception("sockets don't support seek()");
}
int read(char* data, int size)
{
L(fmt("%i: reading ...") % socket_);
int result = ::recv(socket_, data ,size, 0);
L(fmt("%i: readed %i '%s'") % socket_ % result % std::string(data,result));
if( result == -1 ) {
throw_socket_error("unable to read from socket");
}
return result;
}
int write(const char* data, int size)
{
L(fmt("%i: send '%s'") % socket_ % std::string(data,size));
int result = ::send(socket_, data, size, 0);
L(fmt("%i: sent %i") % socket_ % result);
if( result == -1 ) {
throw_socket_error("unable to write to socket");
}
return result;
}
void sync()
{
}
socket_type get_socket() const { return socket_; }
};
#ifdef _WIN32
std::string win32_strerror(DWORD error_code)
{
LPVOID lpMsgBuf;
if( ::FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
) < 0 || lpMsgBuf == NULL) {
return fmt("unknown error: %i") % error_code;
}
std::string result((char*)lpMsgBuf);
::LocalFree(lpMsgBuf);
return result;
}
#endif
static void ensure_socket_initialized()
{
#ifdef TS_WINSOCK
static bool winsock_initialized = false;
if( winsock_initialized ) return;
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(1, 1);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0)
throw io_exception(fmt("unable to initialize WinSock system: %s") % win32_strerror(err));
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup();
errno = ENODEV;
throw io_exception("bad winsock version");
}
winsock_initialized = true;
#endif
}
static void throw_socket_error(const char* message)
{
#ifdef TS_WINSOCK
int error_code = WSAGetLastError();
throw io_exception(fmt("%s: %s") % message % win32_strerror(error_code));
#else
throw io_exception(fmt("%s: %s") % message % strerror(errno));
#endif
}
static void close_socket(socket_type socket)
{
#ifdef TS_WINSOCK
int rc = ::closesocket(socket);
#else
int rc = ::close(socket);
#endif
if( rc == -1 ) throw_socket_error("unable to close socket");
}
static socket_type create_socket()
{
ensure_socket_initialized();
int result = ::socket(AF_INET,SOCK_STREAM,0);
if( result == invalid_socket )
throw_socket_error("socket creation failed");
return result;
}
#ifndef INADDR_NONE
#define INADDR_NONE -1
#endif
static void get_inet_address(const char* address,int rport, struct sockaddr_in* sa)
{
ensure_socket_initialized();
std::memset(sa,0,sizeof(*sa));
sa->sin_family = AF_INET;
sa->sin_port = htons((short)rport);
::in_addr ia;
unsigned long ian = ::inet_addr(address);
ia.s_addr = ian;
if( ian == INADDR_NONE ) {
::hostent* ha;
ha = ::gethostbyname(address);
if( ha == NULL )
throw io_exception(fmt("unable to resolve: %s") % address);
std::memcpy(&sa->sin_addr, ha->h_addr, ha->h_length);
} else {
/* found with inet_addr or inet_aton */
std::memcpy(&sa->sin_addr,&ia,sizeof(ia));
}
}
stream* open_client_socket(char const* address, int port)
{
::sockaddr_in sock_addr;
get_inet_address(address, port, &sock_addr);
socket_type s = create_socket();
if( ::connect(s, (struct sockaddr*)&sock_addr,sizeof(sock_addr)) < 0 ) {
close_socket(s);
throw_socket_error(fmt("unable to connect %s:%i") % address % port);
}
return new socketstream(s);
}
stream* open_server_socket(char const* listening_host, int port)
{
::sockaddr_in sock_addr;
std::memset(&sock_addr,0,sizeof(sock_addr));
sock_addr.sin_family = AF_INET;
if( listening_host ) {
get_inet_address(listening_host, port, &sock_addr);
} else {
sock_addr.sin_port = htons((short) port);
}
socket_type s = create_socket();
if( ::bind(s,(struct sockaddr*)&sock_addr,sizeof(sock_addr)) < 0 ) {
close_socket(s);
throw_socket_error("bind failed");
}
if( ::listen(s,5) < 0 ) {
close_socket(s);
throw_socket_error("listen failed");
}
return new socketstream(s);
}
stream* accept_client_connection(stream* server_socket)
{
socketstream* socket = dynamic_cast<socketstream*>(server_socket);
if( !socket ) throw_socket_error("accept: not a socketstream");
socket_type accept_sock = ::accept(socket->get_socket(), NULL, NULL );
if( accept_sock == invalid_socket ) throw_socket_error("accept failed");
return new socketstream(accept_sock);
}
//
// Server implementation
//
Server::Server()
: stopped_(false)
{
}
Server::Server(const char* address, int port)
: stopped_(false)
{
bind(address, port);
}
void Server::bind(const char* address, int port)
{
server_socket_ = std::auto_ptr<stream>(open_server_socket(address,port));
bound_address_ = address;
bound_port_ = port;
}
void Server::run()
{
while( !stopped_ ) {
stream* client_socket = accept_client_connection(server_socket_.get());
if( !stopped_ )
onAccept(std::auto_ptr<stream>(client_socket));
}
server_socket_->close();
}
void Server::stop()
{
stopped_ = true;
try {
stream* f = open_client_socket(bound_address_.c_str(), bound_port_);
if( f )
delete f;
} catch( io_exception& wtf) {
}
}
} } } //end namespace tinfra::io::socket
<commit_msg>socket::Server: fix mem leak when deailing with stop() socket::create_socket(): fix types<commit_after>#include "tinfra/io/stream.h"
#include "tinfra/io/socket.h"
#include "tinfra/fmt.h"
#include "tinfra/string.h" // debug only
#include <iostream> // debug only
#ifdef _WIN32
#include <winsock.h>
#define TS_WINSOCK
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#define TS_BSD
#endif
using namespace std;
namespace tinfra {
namespace io {
namespace socket {
/*
class stream {
virtual ~stream() {}
enum {
start,
end,
current
} seek_origin;
void close() = 0;
int seek(int pos, seek_origin origin = start) = 0;
int read(char* dest, int size) = 0;
int write(const char* data, int size) = 0;
};
*/
#ifdef TS_WINSOCK
typedef SOCKET socket_type;
#else
typedef int socket_type;
#endif
static const socket_type invalid_socket = static_cast<socket_type>(-1);
static void close_socket(socket_type socket);
static void throw_socket_error(const char* message);
// TODO this log facility should be tinfra-wide
#ifdef _DEBUG
static void L(const std::string& msg)
{
//std::cerr << "socket: " << escape_c(msg) << std::endl;
}
#else
#define L(a) (void)0
#endif
class socketstream: public stream {
socket_type socket_;
public:
socketstream(socket_type socket): socket_(socket) {}
~socketstream() {
if( socket_ != invalid_socket )
close();
}
void close() {
close_socket(socket_);
socket_ = invalid_socket;
}
int seek(int pos, stream::seek_origin origin)
{
throw io_exception("sockets don't support seek()");
}
int read(char* data, int size)
{
L(fmt("%i: reading ...") % socket_);
int result = ::recv(socket_, data ,size, 0);
L(fmt("%i: readed %i '%s'") % socket_ % result % std::string(data,result));
if( result == -1 ) {
throw_socket_error("unable to read from socket");
}
return result;
}
int write(const char* data, int size)
{
L(fmt("%i: send '%s'") % socket_ % std::string(data,size));
int result = ::send(socket_, data, size, 0);
L(fmt("%i: sent %i") % socket_ % result);
if( result == -1 ) {
throw_socket_error("unable to write to socket");
}
return result;
}
void sync()
{
}
socket_type get_socket() const { return socket_; }
};
#ifdef _WIN32
std::string win32_strerror(DWORD error_code)
{
LPVOID lpMsgBuf;
if( ::FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
) < 0 || lpMsgBuf == NULL) {
return fmt("unknown error: %i") % error_code;
}
std::string result((char*)lpMsgBuf);
::LocalFree(lpMsgBuf);
return result;
}
#endif
static void ensure_socket_initialized()
{
#ifdef TS_WINSOCK
static bool winsock_initialized = false;
if( winsock_initialized ) return;
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(1, 1);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0)
throw io_exception(fmt("unable to initialize WinSock system: %s") % win32_strerror(err));
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup();
errno = ENODEV;
throw io_exception("bad winsock version");
}
winsock_initialized = true;
#endif
}
static void throw_socket_error(const char* message)
{
#ifdef TS_WINSOCK
int error_code = WSAGetLastError();
throw io_exception(fmt("%s: %s") % message % win32_strerror(error_code));
#else
throw io_exception(fmt("%s: %s") % message % strerror(errno));
#endif
}
static void close_socket(socket_type socket)
{
#ifdef TS_WINSOCK
int rc = ::closesocket(socket);
#else
int rc = ::close(socket);
#endif
if( rc == -1 ) throw_socket_error("unable to close socket");
}
static socket_type create_socket()
{
ensure_socket_initialized();
socket_type result = ::socket(AF_INET,SOCK_STREAM,0);
if( result == invalid_socket )
throw_socket_error("socket creation failed");
return result;
}
#ifndef INADDR_NONE
#define INADDR_NONE -1
#endif
static void get_inet_address(const char* address,int rport, struct sockaddr_in* sa)
{
ensure_socket_initialized();
std::memset(sa,0,sizeof(*sa));
sa->sin_family = AF_INET;
sa->sin_port = htons((short)rport);
::in_addr ia;
unsigned long ian = ::inet_addr(address);
ia.s_addr = ian;
if( ian == INADDR_NONE ) {
::hostent* ha;
ha = ::gethostbyname(address);
if( ha == NULL )
throw io_exception(fmt("unable to resolve: %s") % address);
std::memcpy(&sa->sin_addr, ha->h_addr, ha->h_length);
} else {
/* found with inet_addr or inet_aton */
std::memcpy(&sa->sin_addr,&ia,sizeof(ia));
}
}
stream* open_client_socket(char const* address, int port)
{
::sockaddr_in sock_addr;
get_inet_address(address, port, &sock_addr);
socket_type s = create_socket();
if( ::connect(s, (struct sockaddr*)&sock_addr,sizeof(sock_addr)) < 0 ) {
close_socket(s);
throw_socket_error(fmt("unable to connect %s:%i") % address % port);
}
return new socketstream(s);
}
stream* open_server_socket(char const* listening_host, int port)
{
::sockaddr_in sock_addr;
std::memset(&sock_addr,0,sizeof(sock_addr));
sock_addr.sin_family = AF_INET;
if( listening_host ) {
get_inet_address(listening_host, port, &sock_addr);
} else {
sock_addr.sin_port = htons((short) port);
}
socket_type s = create_socket();
if( ::bind(s,(struct sockaddr*)&sock_addr,sizeof(sock_addr)) < 0 ) {
close_socket(s);
throw_socket_error("bind failed");
}
if( ::listen(s,5) < 0 ) {
close_socket(s);
throw_socket_error("listen failed");
}
return new socketstream(s);
}
stream* accept_client_connection(stream* server_socket)
{
socketstream* socket = dynamic_cast<socketstream*>(server_socket);
if( !socket ) throw_socket_error("accept: not a socketstream");
socket_type accept_sock = ::accept(socket->get_socket(), NULL, NULL );
if( accept_sock == invalid_socket ) throw_socket_error("accept failed");
return new socketstream(accept_sock);
}
//
// Server implementation
//
Server::Server()
: stopped_(false)
{
}
Server::Server(const char* address, int port)
: stopped_(false)
{
bind(address, port);
}
void Server::bind(const char* address, int port)
{
server_socket_ = std::auto_ptr<stream>(open_server_socket(address,port));
bound_address_ = address;
bound_port_ = port;
}
void Server::run()
{
while( !stopped_ ) {
std::auto_ptr<stream> client_socket = std::auto_ptr<stream>(accept_client_connection(server_socket_.get()));
if( !stopped_ )
onAccept(client_socket);
}
server_socket_->close();
}
void Server::stop()
{
stopped_ = true;
try {
stream* f = open_client_socket(bound_address_.c_str(), bound_port_);
if( f )
delete f;
} catch( io_exception& wtf) {
}
}
} } } //end namespace tinfra::io::socket
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2014 Sonora Games
*
*/
#include <Windows.h>
#include "D3D11Renderer.h"
#include "D3D11VertexBuffer.h"
using namespace Monsoon;
using namespace Monsoon::Renderer;
D3D11Renderer::D3D11Renderer(RendererSettings& settings, Scene::SpatialSystem* spatialSystem)
: Renderer(settings, spatialSystem),
mSpatialSystem(spatialSystem),
mWindow(settings.windowName, settings.screenWidth, settings.screenHeight, settings.fullscreen)
{
mVertexBuffers.reserve(MONSOON_MAX_ENTITIES);
}
D3D11Renderer::~D3D11Renderer() {
}
bool D3D11Renderer::Initialize() {
if (!mWindow.Initialize())
return false;
if(!mD3d.Initialize(mWindow))
return false;
if (!mColorMaterial.Load(mD3d.GetDevice(), mWindow.getHandle()))
return false;
}
void D3D11Renderer::Shutdown() {
for (std::vector<D3D11VertexBuffer>::iterator i = mVertexBuffers.begin(); i < mVertexBuffers.end(); i++)
i->Free();
mVertexBuffers.empty();
mColorMaterial.Release();
mD3d.Shutdown();
mWindow.Shutdown();
}
bool D3D11Renderer::Update() {
D3DXMATRIX viewMatrix, projectionMatrix, worldMatrix;
float fieldOfView = (float)D3DX_PI / 4.0f;
float screenAspect = (float)mWindow.getWidth() / (float)mWindow.getHeight();
if (defaultCamera.mode == Camera::PERSPECTIVE)
D3DXMatrixPerspectiveFovLH(&projectionMatrix, fieldOfView, screenAspect, defaultCamera.nearClip, defaultCamera.farClip);
else if (defaultCamera.mode == Camera::ORTHOGRAPHIC)
D3DXMatrixOrthoLH(&projectionMatrix, defaultCamera.orthoWidth, defaultCamera.orthoHeight, defaultCamera.nearClip, defaultCamera.farClip);
D3DXVECTOR3 up, position, lookAt;
D3DXMATRIX rotationMatrix;
up.x = 0.0f;
up.y = 1.0f;
up.z = 0.0f;
position.x = defaultCamera.x;
position.y = defaultCamera.y;
position.z = defaultCamera.z;
lookAt.x = 0.0f;
lookAt.y = 0.0f;
lookAt.z = 0.0f;
D3DXMatrixRotationYawPitchRoll(&rotationMatrix, defaultCamera.yaw, defaultCamera.pitch, defaultCamera.roll);
D3DXVec3TransformCoord(&lookAt, &lookAt, &rotationMatrix);
D3DXVec3TransformCoord(&up, &up, &rotationMatrix);
D3DXMatrixLookAtLH(&viewMatrix, &position, &lookAt, &up);
if (!mWindow.Update())
return false;
mD3d.BeginScene();
D3DXMATRIX translation, rotation;
for (int x = 0; x < mMeshComponents.Size(); x++) {
auto& spatialComponent = mSpatialSystem->GetSpatialComponent(mMeshComponents.IndexToId(x)).first;
D3DXMatrixIdentity(&worldMatrix);
D3DXMatrixIdentity(&translation);
D3DXMatrixIdentity(&rotation);
D3DXMatrixTranslation(&translation, spatialComponent.x, spatialComponent.y, spatialComponent.z);
D3DXMatrixRotationYawPitchRoll(&rotation, spatialComponent.yaw, spatialComponent.pitch, spatialComponent.roll);
D3DXMatrixMultiply(&worldMatrix, &rotation, &translation);
mColorMaterial.Render(mD3d.GetContext(), worldMatrix, viewMatrix, projectionMatrix);
mVertexBuffers[mMeshComponents.At(x).VertexBuffer].Render(mD3d.GetContext());
}
mD3d.EndScene();
return true;
}
int nextFreeId = 0;
VertexBufferHandle D3D11Renderer::CreateVertexBuffer(ColorVertex* vertices, int vertexCount, unsigned int* indicies, int indexCount)
{
int vbHandle = 0;
if (mFreeIndexList.size()) {
vbHandle = mFreeIndexList.back();
mFreeIndexList.pop_back();
}
else
{
vbHandle = mVertexBuffers.size();
mVertexBuffers.push_back(D3D11VertexBuffer());
}
mVertexBuffers[vbHandle].Allocate(mD3d.GetDevice(), vertices, vertexCount, indicies, indexCount);
return vbHandle;
}
void D3D11Renderer::DestroyVertexBuffer(VertexBufferHandle vbHandle)
{
mVertexBuffers[vbHandle].Free();
mFreeIndexList.push_back(vbHandle);
}
void D3D11Renderer::AttachMeshComponent(Monsoon::Entity entity, MeshComponent& component)
{
mMeshComponents.Add(entity, component);
}
void D3D11Renderer::DetachMeshComponent(Monsoon::Entity entity)
{
mMeshComponents.Remove(entity);
}
MeshComponent& D3D11Renderer::GetMeshComponent(Monsoon::Entity entity) {
return mMeshComponents[entity];
}
VertexBufferHandle D3D11Renderer::CreatePlane(float width, float height) {
ColorVertex vertices[4];
vertices[0].SetPosition((width / 2.0f) * -1.0f, (height / 2.0f) * -1.0f, 0.0f);
vertices[0].SetColor(1.0f, 1.0f, 0.0f, 1.0f);
vertices[1].SetPosition((width / 2.0f) * -1.0f, (height / 2.0f), 0.0f);
vertices[1].SetColor(1.0f, 0.0f, 1.0f, 1.0f);
vertices[2].SetPosition((width / 2.0f), (height / 2.0f), 0.0f);
vertices[2].SetColor(0.0f, 1.0f, 1.0f, 1.0f);
vertices[3].SetPosition((width / 2.0f), (height / 2.0f) * -1.0f, 0.0f);
vertices[3].SetColor(1.0f, 1.0f, 1.0f, 1.0f);
unsigned int indices[6] = {
0, 1, 2,
0, 2, 3
};
return CreateVertexBuffer(vertices, 4, indices, 6);
}
VertexBufferHandle D3D11Renderer::CreateCube(float length) {
ColorVertex vertices[8];
float halfLength = length / 2.0f;
vertices[0].SetPosition(-1.0f * halfLength, -1.0f * halfLength, -1.0f * halfLength);
vertices[0].SetColor(1.0f, 1.0f, 0.0f, 1.0f);
vertices[1].SetPosition(-1.0f * halfLength, 1.0f * halfLength, -1 * halfLength);
vertices[1].SetColor(1.0f, 0.5f, 1.0f, 1.0f);
vertices[2].SetPosition(1.0f * halfLength, 1.0f * halfLength, -1.0f * halfLength);
vertices[2].SetColor(1.0f, 0.5f, 0.5f, 1.0f);
vertices[3].SetPosition(1.0f * halfLength, -1.0f * halfLength, -1.0f * halfLength);
vertices[3].SetColor(1.0f, 0.5f, 0.0f, 1.0f);
vertices[4].SetPosition(-1.0f * halfLength, -1.0f * halfLength, 1.0f * halfLength);
vertices[4].SetColor(1.0f, 1.0f, 0.0f, 1.0f);
vertices[5].SetPosition(-1.0f * halfLength, 1.0f * halfLength, 1.0f * halfLength);
vertices[5].SetColor(1.0f, 0.5f, 1.0f, 1.0f);
vertices[6].SetPosition(1.0f * halfLength, 1.0f * halfLength, 1.0f * halfLength);
vertices[6].SetColor(1.0f, 0.5f, 0.5f, 1.0f);
vertices[7].SetPosition(1.0f * halfLength, -1.0f * halfLength, 1.0f * halfLength);
vertices[7].SetColor(1.0f, 0.5f, 0.0f, 1.0f);
unsigned int indices[36] =
{
0, 1, 2,
0, 2, 3,
4, 6, 5,
4, 7, 6,
4, 5, 1,
4, 1, 0,
3, 2, 6,
3, 6, 7,
1, 5, 6,
1, 6, 2,
4, 0, 3,
4, 3, 7
};
return CreateVertexBuffer(vertices, 8, indices, 36);
}
VertexBufferHandle D3D11Renderer::CreatePyramid(float base, float height)
{
ColorVertex vertices[5];
float halfHeight = height / 2.0f;
float halfBase = base / 2.0f;
vertices[0].SetPosition(-1.0f * halfBase, -1.0f * halfHeight, -1.0f * halfBase);
vertices[0].SetColor(1.0f, 0.0f, 1.0f, 1.0f);
vertices[1].SetPosition(-1.0f * halfBase, -1.0f * halfHeight, 1.0f * halfBase);
vertices[1].SetColor(1.0f, 0.0f, 1.0f, 1.0f);
vertices[2].SetPosition(1.0f * halfBase, -1.0f * halfHeight, 1.0f * halfBase);
vertices[2].SetColor(1.0f, 0.5f, 1.0f, 1.0f);
vertices[3].SetPosition(1.0f * halfBase, -1.0f * halfHeight, -1.0f * halfBase);
vertices[3].SetColor(1.0f, 0.0f, 1.0f, 1.0f);
vertices[4].SetPosition(0.0f, 1.0f * halfHeight, 0.0f);
vertices[4].SetColor(1.0f, 0.0f, 1.0f, 1.0f);
unsigned int indices[18] =
{
// Bottom
0, 1, 2,
0, 2, 3,
0, 4, 1,
1, 4, 2,
2, 4, 3,
3, 4, 0
};
return CreateVertexBuffer(vertices, 5, indices, 18);
}<commit_msg>[D3D11Renderer] Renderer now take scaling into account.<commit_after>/**
* Copyright (c) 2014 Sonora Games
*
*/
#include <Windows.h>
#include "D3D11Renderer.h"
#include "D3D11VertexBuffer.h"
using namespace Monsoon;
using namespace Monsoon::Renderer;
D3D11Renderer::D3D11Renderer(RendererSettings& settings, Scene::SpatialSystem* spatialSystem)
: Renderer(settings, spatialSystem),
mSpatialSystem(spatialSystem),
mWindow(settings.windowName, settings.screenWidth, settings.screenHeight, settings.fullscreen)
{
mVertexBuffers.reserve(MONSOON_MAX_ENTITIES);
}
D3D11Renderer::~D3D11Renderer() {
}
bool D3D11Renderer::Initialize() {
if (!mWindow.Initialize())
return false;
if(!mD3d.Initialize(mWindow))
return false;
if (!mColorMaterial.Load(mD3d.GetDevice(), mWindow.getHandle()))
return false;
}
void D3D11Renderer::Shutdown() {
for (std::vector<D3D11VertexBuffer>::iterator i = mVertexBuffers.begin(); i < mVertexBuffers.end(); i++)
i->Free();
mVertexBuffers.empty();
mColorMaterial.Release();
mD3d.Shutdown();
mWindow.Shutdown();
}
bool D3D11Renderer::Update() {
D3DXMATRIX viewMatrix, projectionMatrix, worldMatrix;
float fieldOfView = (float)D3DX_PI / 4.0f;
float screenAspect = (float)mWindow.getWidth() / (float)mWindow.getHeight();
if (defaultCamera.mode == Camera::PERSPECTIVE)
D3DXMatrixPerspectiveFovLH(&projectionMatrix, fieldOfView, screenAspect, defaultCamera.nearClip, defaultCamera.farClip);
else if (defaultCamera.mode == Camera::ORTHOGRAPHIC)
D3DXMatrixOrthoLH(&projectionMatrix, defaultCamera.orthoWidth, defaultCamera.orthoHeight, defaultCamera.nearClip, defaultCamera.farClip);
D3DXVECTOR3 up, position, lookAt;
D3DXMATRIX rotationMatrix;
up.x = 0.0f;
up.y = 1.0f;
up.z = 0.0f;
position.x = defaultCamera.x;
position.y = defaultCamera.y;
position.z = defaultCamera.z;
lookAt.x = 0.0f;
lookAt.y = 0.0f;
lookAt.z = 0.0f;
D3DXMatrixRotationYawPitchRoll(&rotationMatrix, defaultCamera.yaw, defaultCamera.pitch, defaultCamera.roll);
D3DXVec3TransformCoord(&lookAt, &lookAt, &rotationMatrix);
D3DXVec3TransformCoord(&up, &up, &rotationMatrix);
D3DXMatrixLookAtLH(&viewMatrix, &position, &lookAt, &up);
if (!mWindow.Update())
return false;
mD3d.BeginScene();
D3DXMATRIX translation, rotation, scale;
for (int x = 0; x < mMeshComponents.Size(); x++) {
auto& spatialComponent = mSpatialSystem->GetSpatialComponent(mMeshComponents.IndexToId(x)).first;
D3DXMatrixIdentity(&worldMatrix);
D3DXMatrixIdentity(&translation);
D3DXMatrixIdentity(&rotation);
D3DXMatrixIdentity(&scale);
D3DXMatrixTranslation(&translation, spatialComponent.x, spatialComponent.y, spatialComponent.z);
D3DXMatrixRotationYawPitchRoll(&rotation, spatialComponent.yaw, spatialComponent.pitch, spatialComponent.roll);
D3DXMatrixScaling(&scale, spatialComponent.scaleX, spatialComponent.scaleY, spatialComponent.scaleZ);
D3DXMatrixMultiply(&worldMatrix, &rotation, &scale);
D3DXMatrixMultiply(&worldMatrix, &worldMatrix, &translation);
mColorMaterial.Render(mD3d.GetContext(), worldMatrix, viewMatrix, projectionMatrix);
mVertexBuffers[mMeshComponents.At(x).VertexBuffer].Render(mD3d.GetContext());
}
mD3d.EndScene();
return true;
}
int nextFreeId = 0;
VertexBufferHandle D3D11Renderer::CreateVertexBuffer(ColorVertex* vertices, int vertexCount, unsigned int* indicies, int indexCount)
{
int vbHandle = 0;
if (mFreeIndexList.size()) {
vbHandle = mFreeIndexList.back();
mFreeIndexList.pop_back();
}
else
{
vbHandle = mVertexBuffers.size();
mVertexBuffers.push_back(D3D11VertexBuffer());
}
mVertexBuffers[vbHandle].Allocate(mD3d.GetDevice(), vertices, vertexCount, indicies, indexCount);
return vbHandle;
}
void D3D11Renderer::DestroyVertexBuffer(VertexBufferHandle vbHandle)
{
mVertexBuffers[vbHandle].Free();
mFreeIndexList.push_back(vbHandle);
}
void D3D11Renderer::AttachMeshComponent(Monsoon::Entity entity, MeshComponent& component)
{
mMeshComponents.Add(entity, component);
}
void D3D11Renderer::DetachMeshComponent(Monsoon::Entity entity)
{
mMeshComponents.Remove(entity);
}
MeshComponent& D3D11Renderer::GetMeshComponent(Monsoon::Entity entity) {
return mMeshComponents[entity];
}
VertexBufferHandle D3D11Renderer::CreatePlane(float width, float height) {
ColorVertex vertices[4];
vertices[0].SetPosition((width / 2.0f) * -1.0f, (height / 2.0f) * -1.0f, 0.0f);
vertices[0].SetColor(1.0f, 1.0f, 0.0f, 1.0f);
vertices[1].SetPosition((width / 2.0f) * -1.0f, (height / 2.0f), 0.0f);
vertices[1].SetColor(1.0f, 0.0f, 1.0f, 1.0f);
vertices[2].SetPosition((width / 2.0f), (height / 2.0f), 0.0f);
vertices[2].SetColor(0.0f, 1.0f, 1.0f, 1.0f);
vertices[3].SetPosition((width / 2.0f), (height / 2.0f) * -1.0f, 0.0f);
vertices[3].SetColor(1.0f, 1.0f, 1.0f, 1.0f);
unsigned int indices[6] = {
0, 1, 2,
0, 2, 3
};
return CreateVertexBuffer(vertices, 4, indices, 6);
}
VertexBufferHandle D3D11Renderer::CreateCube(float length) {
ColorVertex vertices[8];
float halfLength = length / 2.0f;
vertices[0].SetPosition(-1.0f * halfLength, -1.0f * halfLength, -1.0f * halfLength);
vertices[0].SetColor(1.0f, 1.0f, 0.0f, 1.0f);
vertices[1].SetPosition(-1.0f * halfLength, 1.0f * halfLength, -1 * halfLength);
vertices[1].SetColor(1.0f, 0.5f, 1.0f, 1.0f);
vertices[2].SetPosition(1.0f * halfLength, 1.0f * halfLength, -1.0f * halfLength);
vertices[2].SetColor(1.0f, 0.5f, 0.5f, 1.0f);
vertices[3].SetPosition(1.0f * halfLength, -1.0f * halfLength, -1.0f * halfLength);
vertices[3].SetColor(1.0f, 0.5f, 0.0f, 1.0f);
vertices[4].SetPosition(-1.0f * halfLength, -1.0f * halfLength, 1.0f * halfLength);
vertices[4].SetColor(1.0f, 1.0f, 0.0f, 1.0f);
vertices[5].SetPosition(-1.0f * halfLength, 1.0f * halfLength, 1.0f * halfLength);
vertices[5].SetColor(1.0f, 0.5f, 1.0f, 1.0f);
vertices[6].SetPosition(1.0f * halfLength, 1.0f * halfLength, 1.0f * halfLength);
vertices[6].SetColor(1.0f, 0.5f, 0.5f, 1.0f);
vertices[7].SetPosition(1.0f * halfLength, -1.0f * halfLength, 1.0f * halfLength);
vertices[7].SetColor(1.0f, 0.5f, 0.0f, 1.0f);
unsigned int indices[36] =
{
0, 1, 2,
0, 2, 3,
4, 6, 5,
4, 7, 6,
4, 5, 1,
4, 1, 0,
3, 2, 6,
3, 6, 7,
1, 5, 6,
1, 6, 2,
4, 0, 3,
4, 3, 7
};
return CreateVertexBuffer(vertices, 8, indices, 36);
}
VertexBufferHandle D3D11Renderer::CreatePyramid(float base, float height)
{
ColorVertex vertices[5];
float halfHeight = height / 2.0f;
float halfBase = base / 2.0f;
vertices[0].SetPosition(-1.0f * halfBase, -1.0f * halfHeight, -1.0f * halfBase);
vertices[0].SetColor(1.0f, 0.0f, 1.0f, 1.0f);
vertices[1].SetPosition(-1.0f * halfBase, -1.0f * halfHeight, 1.0f * halfBase);
vertices[1].SetColor(1.0f, 0.0f, 1.0f, 1.0f);
vertices[2].SetPosition(1.0f * halfBase, -1.0f * halfHeight, 1.0f * halfBase);
vertices[2].SetColor(1.0f, 0.5f, 1.0f, 1.0f);
vertices[3].SetPosition(1.0f * halfBase, -1.0f * halfHeight, -1.0f * halfBase);
vertices[3].SetColor(1.0f, 0.0f, 1.0f, 1.0f);
vertices[4].SetPosition(0.0f, 1.0f * halfHeight, 0.0f);
vertices[4].SetColor(1.0f, 0.0f, 1.0f, 1.0f);
unsigned int indices[18] =
{
// Bottom
0, 1, 2,
0, 2, 3,
0, 4, 1,
1, 4, 2,
2, 4, 3,
3, 4, 0
};
return CreateVertexBuffer(vertices, 5, indices, 18);
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tabdlg.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 12:30:59 $
*
* 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_FIXED_HXX
#include <fixed.hxx>
#endif
#ifndef _SV_TABCTRL_HXX
#include <tabctrl.hxx>
#endif
#ifndef _SV_TABDLG_HXX
#include <tabdlg.hxx>
#endif
#ifndef _SV_RC_H
#include <tools/rc.h>
#endif
// =======================================================================
void TabDialog::ImplInitData()
{
mpFixedLine = NULL;
mpViewWindow = NULL;
meViewAlign = WINDOWALIGN_LEFT;
mbPosControls = TRUE;
}
// -----------------------------------------------------------------------
void TabDialog::ImplPosControls()
{
Size aCtrlSize( IMPL_MINSIZE_BUTTON_WIDTH, IMPL_MINSIZE_BUTTON_HEIGHT );
long nDownCtrl = 0;
long nOffY = 0;
TabControl* pTabControl = NULL;
Window* pChild = GetWindow( WINDOW_FIRSTCHILD );
while ( pChild )
{
if ( pChild->IsVisible() && (pChild != mpViewWindow) )
{
if ( pChild->GetType() == WINDOW_TABCONTROL )
pTabControl = (TabControl*)pChild;
else if ( pTabControl )
{
long nTxtWidth = pChild->GetCtrlTextWidth( pChild->GetText() );
nTxtWidth += IMPL_EXTRA_BUTTON_WIDTH;
if ( nTxtWidth > aCtrlSize.Width() )
aCtrlSize.Width() = nTxtWidth;
long nTxtHeight = pChild->GetTextHeight();
nTxtHeight += IMPL_EXTRA_BUTTON_HEIGHT;
if ( nTxtHeight > aCtrlSize.Height() )
aCtrlSize.Height() = nTxtHeight;
nDownCtrl++;
}
else
{
long nHeight = pChild->GetSizePixel().Height();
if ( nHeight > nOffY )
nOffY = nHeight;
}
}
pChild = pChild->GetWindow( WINDOW_NEXT );
}
// Haben wir ueberhaupt ein TabControl
if ( pTabControl )
{
// Offset bei weiteren Controls um einen weiteren Abstand anpassen
if ( nOffY )
nOffY += IMPL_DIALOG_BAR_OFFSET*2 + 2;
Point aTabOffset( IMPL_DIALOG_OFFSET, IMPL_DIALOG_OFFSET+nOffY );
Size aTabSize = pTabControl->GetSizePixel();
Size aDlgSize( aTabSize.Width() + IMPL_DIALOG_OFFSET*2,
aTabSize.Height() + IMPL_DIALOG_OFFSET*2 + nOffY );
long nBtnEx = 0;
// Preview-Fenster beruecksichtigen und die Groessen/Offsets anpassen
if ( mpViewWindow && mpViewWindow->IsVisible() )
{
long nViewOffX = 0;
long nViewOffY = 0;
long nViewWidth = 0;
long nViewHeight = 0;
USHORT nViewPosFlags = WINDOW_POSSIZE_POS;
Size aViewSize = mpViewWindow->GetSizePixel();
if ( meViewAlign == WINDOWALIGN_TOP )
{
nViewOffX = aTabOffset.X();
nViewOffY = nOffY+IMPL_DIALOG_OFFSET;
nViewWidth = aTabSize.Width();
nViewPosFlags |= WINDOW_POSSIZE_WIDTH;
aTabOffset.Y() += aViewSize.Height()+IMPL_DIALOG_OFFSET;
aDlgSize.Height() += aViewSize.Height()+IMPL_DIALOG_OFFSET;
}
else if ( meViewAlign == WINDOWALIGN_BOTTOM )
{
nViewOffX = aTabOffset.X();
nViewOffY = aTabOffset.Y()+aTabSize.Height()+IMPL_DIALOG_OFFSET;
nViewWidth = aTabSize.Width();
nViewPosFlags |= WINDOW_POSSIZE_WIDTH;
aDlgSize.Height() += aViewSize.Height()+IMPL_DIALOG_OFFSET;
}
else if ( meViewAlign == WINDOWALIGN_RIGHT )
{
nViewOffX = aTabOffset.X()+aTabSize.Width()+IMPL_DIALOG_OFFSET;
nViewOffY = aTabOffset.Y();
nViewHeight = aTabSize.Height();
nViewPosFlags |= WINDOW_POSSIZE_HEIGHT;
aDlgSize.Width() += aViewSize.Width()+IMPL_DIALOG_OFFSET;
nBtnEx = aViewSize.Width()+IMPL_DIALOG_OFFSET;
}
else // meViewAlign == WINDOWALIGN_LEFT
{
nViewOffX = IMPL_DIALOG_OFFSET;
nViewOffY = aTabOffset.Y();
nViewHeight = aTabSize.Height();
nViewPosFlags |= WINDOW_POSSIZE_HEIGHT;
aTabOffset.X() += aViewSize.Width()+IMPL_DIALOG_OFFSET;
aDlgSize.Width() += aViewSize.Width()+IMPL_DIALOG_OFFSET;
nBtnEx = aViewSize.Width()+IMPL_DIALOG_OFFSET;
}
mpViewWindow->SetPosSizePixel( nViewOffX, nViewOffY,
nViewWidth, nViewHeight,
nViewPosFlags );
}
// Positionierung vornehmen
pTabControl->SetPosPixel( aTabOffset );
// Alle anderen Childs positionieren
BOOL bTabCtrl = FALSE;
int nLines = 0;
long nX;
long nY = aDlgSize.Height();
long nTopX = IMPL_DIALOG_OFFSET;
// Unter Windows 95 werden die Buttons rechtsbuendig angeordnet
nX = IMPL_DIALOG_OFFSET;
long nCtrlBarWidth = ((aCtrlSize.Width()+IMPL_DIALOG_OFFSET)*nDownCtrl)-IMPL_DIALOG_OFFSET;
if ( nCtrlBarWidth <= (aTabSize.Width()+nBtnEx) )
nX = (aTabSize.Width()+nBtnEx) - nCtrlBarWidth + IMPL_DIALOG_OFFSET;
pChild = pChild = GetWindow( WINDOW_FIRSTCHILD );
while ( pChild )
{
if ( pChild->IsVisible() && (pChild != mpViewWindow) )
{
if ( pChild == pTabControl )
bTabCtrl = TRUE;
else if ( bTabCtrl )
{
if ( !nLines )
nLines = 1;
if ( nX+aCtrlSize.Width()-IMPL_DIALOG_OFFSET > (aTabSize.Width()+nBtnEx) )
{
nY += aCtrlSize.Height()+IMPL_DIALOG_OFFSET;
nX = IMPL_DIALOG_OFFSET;
nLines++;
}
pChild->SetPosSizePixel( Point( nX, nY ), aCtrlSize );
nX += aCtrlSize.Width()+IMPL_DIALOG_OFFSET;
}
else
{
Size aChildSize = pChild->GetSizePixel();
pChild->SetPosPixel( Point( nTopX, (nOffY-aChildSize.Height())/2 ) );
nTopX += aChildSize.Width()+2;
}
}
pChild = pChild->GetWindow( WINDOW_NEXT );
}
aDlgSize.Height() += nLines * (aCtrlSize.Height()+IMPL_DIALOG_OFFSET);
SetOutputSizePixel( aDlgSize );
}
// Offset merken
if ( nOffY )
{
Size aDlgSize = GetOutputSizePixel();
if ( !mpFixedLine )
mpFixedLine = new FixedLine( this );
mpFixedLine->SetPosSizePixel( Point( 0, nOffY ),
Size( aDlgSize.Width(), 2 ) );
mpFixedLine->Show();
}
mbPosControls = FALSE;
}
// -----------------------------------------------------------------------
TabDialog::TabDialog( Window* pParent, WinBits nStyle ) :
Dialog( WINDOW_TABDIALOG )
{
ImplInitData();
ImplInit( pParent, nStyle );
}
// -----------------------------------------------------------------------
TabDialog::TabDialog( Window* pParent, const ResId& rResId ) :
Dialog( WINDOW_TABDIALOG )
{
ImplInitData();
rResId.SetRT( RSC_TABDIALOG );
ImplInit( pParent, ImplInitRes( rResId ) );
ImplLoadRes( rResId );
}
// -----------------------------------------------------------------------
TabDialog::~TabDialog()
{
if ( mpFixedLine )
delete mpFixedLine;
}
// -----------------------------------------------------------------------
void TabDialog::Resize()
{
// !!! In the future the controls should be automaticly rearrange
// !!! if the window is resized
// !!! if ( !IsRollUp() )
// !!! ImplPosControls();
}
// -----------------------------------------------------------------------
void TabDialog::StateChanged( StateChangedType nType )
{
if ( nType == STATE_CHANGE_INITSHOW )
{
// Calculate the Layout only for the initialized state
if ( mbPosControls )
ImplPosControls();
}
Dialog::StateChanged( nType );
}
// -----------------------------------------------------------------------
void TabDialog::AdjustLayout()
{
ImplPosControls();
}
<commit_msg>INTEGRATION: CWS warnings01 (1.4.70); FILE MERGED 2005/11/02 12:19:06 pl 1.4.70.1: #i55991# removed warnings for solaris platform<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tabdlg.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 19:41:09 $
*
* 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_FIXED_HXX
#include <fixed.hxx>
#endif
#ifndef _SV_TABCTRL_HXX
#include <tabctrl.hxx>
#endif
#ifndef _SV_TABDLG_HXX
#include <tabdlg.hxx>
#endif
#ifndef _SV_RC_H
#include <tools/rc.h>
#endif
// =======================================================================
void TabDialog::ImplInitTabDialogData()
{
mpFixedLine = NULL;
mpViewWindow = NULL;
meViewAlign = WINDOWALIGN_LEFT;
mbPosControls = TRUE;
}
// -----------------------------------------------------------------------
void TabDialog::ImplPosControls()
{
Size aCtrlSize( IMPL_MINSIZE_BUTTON_WIDTH, IMPL_MINSIZE_BUTTON_HEIGHT );
long nDownCtrl = 0;
long nOffY = 0;
TabControl* pTabControl = NULL;
Window* pChild = GetWindow( WINDOW_FIRSTCHILD );
while ( pChild )
{
if ( pChild->IsVisible() && (pChild != mpViewWindow) )
{
if ( pChild->GetType() == WINDOW_TABCONTROL )
pTabControl = (TabControl*)pChild;
else if ( pTabControl )
{
long nTxtWidth = pChild->GetCtrlTextWidth( pChild->GetText() );
nTxtWidth += IMPL_EXTRA_BUTTON_WIDTH;
if ( nTxtWidth > aCtrlSize.Width() )
aCtrlSize.Width() = nTxtWidth;
long nTxtHeight = pChild->GetTextHeight();
nTxtHeight += IMPL_EXTRA_BUTTON_HEIGHT;
if ( nTxtHeight > aCtrlSize.Height() )
aCtrlSize.Height() = nTxtHeight;
nDownCtrl++;
}
else
{
long nHeight = pChild->GetSizePixel().Height();
if ( nHeight > nOffY )
nOffY = nHeight;
}
}
pChild = pChild->GetWindow( WINDOW_NEXT );
}
// Haben wir ueberhaupt ein TabControl
if ( pTabControl )
{
// Offset bei weiteren Controls um einen weiteren Abstand anpassen
if ( nOffY )
nOffY += IMPL_DIALOG_BAR_OFFSET*2 + 2;
Point aTabOffset( IMPL_DIALOG_OFFSET, IMPL_DIALOG_OFFSET+nOffY );
Size aTabSize = pTabControl->GetSizePixel();
Size aDlgSize( aTabSize.Width() + IMPL_DIALOG_OFFSET*2,
aTabSize.Height() + IMPL_DIALOG_OFFSET*2 + nOffY );
long nBtnEx = 0;
// Preview-Fenster beruecksichtigen und die Groessen/Offsets anpassen
if ( mpViewWindow && mpViewWindow->IsVisible() )
{
long nViewOffX = 0;
long nViewOffY = 0;
long nViewWidth = 0;
long nViewHeight = 0;
USHORT nViewPosFlags = WINDOW_POSSIZE_POS;
Size aViewSize = mpViewWindow->GetSizePixel();
if ( meViewAlign == WINDOWALIGN_TOP )
{
nViewOffX = aTabOffset.X();
nViewOffY = nOffY+IMPL_DIALOG_OFFSET;
nViewWidth = aTabSize.Width();
nViewPosFlags |= WINDOW_POSSIZE_WIDTH;
aTabOffset.Y() += aViewSize.Height()+IMPL_DIALOG_OFFSET;
aDlgSize.Height() += aViewSize.Height()+IMPL_DIALOG_OFFSET;
}
else if ( meViewAlign == WINDOWALIGN_BOTTOM )
{
nViewOffX = aTabOffset.X();
nViewOffY = aTabOffset.Y()+aTabSize.Height()+IMPL_DIALOG_OFFSET;
nViewWidth = aTabSize.Width();
nViewPosFlags |= WINDOW_POSSIZE_WIDTH;
aDlgSize.Height() += aViewSize.Height()+IMPL_DIALOG_OFFSET;
}
else if ( meViewAlign == WINDOWALIGN_RIGHT )
{
nViewOffX = aTabOffset.X()+aTabSize.Width()+IMPL_DIALOG_OFFSET;
nViewOffY = aTabOffset.Y();
nViewHeight = aTabSize.Height();
nViewPosFlags |= WINDOW_POSSIZE_HEIGHT;
aDlgSize.Width() += aViewSize.Width()+IMPL_DIALOG_OFFSET;
nBtnEx = aViewSize.Width()+IMPL_DIALOG_OFFSET;
}
else // meViewAlign == WINDOWALIGN_LEFT
{
nViewOffX = IMPL_DIALOG_OFFSET;
nViewOffY = aTabOffset.Y();
nViewHeight = aTabSize.Height();
nViewPosFlags |= WINDOW_POSSIZE_HEIGHT;
aTabOffset.X() += aViewSize.Width()+IMPL_DIALOG_OFFSET;
aDlgSize.Width() += aViewSize.Width()+IMPL_DIALOG_OFFSET;
nBtnEx = aViewSize.Width()+IMPL_DIALOG_OFFSET;
}
mpViewWindow->SetPosSizePixel( nViewOffX, nViewOffY,
nViewWidth, nViewHeight,
nViewPosFlags );
}
// Positionierung vornehmen
pTabControl->SetPosPixel( aTabOffset );
// Alle anderen Childs positionieren
BOOL bTabCtrl = FALSE;
int nLines = 0;
long nX;
long nY = aDlgSize.Height();
long nTopX = IMPL_DIALOG_OFFSET;
// Unter Windows 95 werden die Buttons rechtsbuendig angeordnet
nX = IMPL_DIALOG_OFFSET;
long nCtrlBarWidth = ((aCtrlSize.Width()+IMPL_DIALOG_OFFSET)*nDownCtrl)-IMPL_DIALOG_OFFSET;
if ( nCtrlBarWidth <= (aTabSize.Width()+nBtnEx) )
nX = (aTabSize.Width()+nBtnEx) - nCtrlBarWidth + IMPL_DIALOG_OFFSET;
pChild = pChild = GetWindow( WINDOW_FIRSTCHILD );
while ( pChild )
{
if ( pChild->IsVisible() && (pChild != mpViewWindow) )
{
if ( pChild == pTabControl )
bTabCtrl = TRUE;
else if ( bTabCtrl )
{
if ( !nLines )
nLines = 1;
if ( nX+aCtrlSize.Width()-IMPL_DIALOG_OFFSET > (aTabSize.Width()+nBtnEx) )
{
nY += aCtrlSize.Height()+IMPL_DIALOG_OFFSET;
nX = IMPL_DIALOG_OFFSET;
nLines++;
}
pChild->SetPosSizePixel( Point( nX, nY ), aCtrlSize );
nX += aCtrlSize.Width()+IMPL_DIALOG_OFFSET;
}
else
{
Size aChildSize = pChild->GetSizePixel();
pChild->SetPosPixel( Point( nTopX, (nOffY-aChildSize.Height())/2 ) );
nTopX += aChildSize.Width()+2;
}
}
pChild = pChild->GetWindow( WINDOW_NEXT );
}
aDlgSize.Height() += nLines * (aCtrlSize.Height()+IMPL_DIALOG_OFFSET);
SetOutputSizePixel( aDlgSize );
}
// Offset merken
if ( nOffY )
{
Size aDlgSize = GetOutputSizePixel();
if ( !mpFixedLine )
mpFixedLine = new FixedLine( this );
mpFixedLine->SetPosSizePixel( Point( 0, nOffY ),
Size( aDlgSize.Width(), 2 ) );
mpFixedLine->Show();
}
mbPosControls = FALSE;
}
// -----------------------------------------------------------------------
TabDialog::TabDialog( Window* pParent, WinBits nStyle ) :
Dialog( WINDOW_TABDIALOG )
{
ImplInitTabDialogData();
ImplInit( pParent, nStyle );
}
// -----------------------------------------------------------------------
TabDialog::TabDialog( Window* pParent, const ResId& rResId ) :
Dialog( WINDOW_TABDIALOG )
{
ImplInitTabDialogData();
rResId.SetRT( RSC_TABDIALOG );
ImplInit( pParent, ImplInitRes( rResId ) );
ImplLoadRes( rResId );
}
// -----------------------------------------------------------------------
TabDialog::~TabDialog()
{
if ( mpFixedLine )
delete mpFixedLine;
}
// -----------------------------------------------------------------------
void TabDialog::Resize()
{
// !!! In the future the controls should be automaticly rearrange
// !!! if the window is resized
// !!! if ( !IsRollUp() )
// !!! ImplPosControls();
}
// -----------------------------------------------------------------------
void TabDialog::StateChanged( StateChangedType nType )
{
if ( nType == STATE_CHANGE_INITSHOW )
{
// Calculate the Layout only for the initialized state
if ( mbPosControls )
ImplPosControls();
}
Dialog::StateChanged( nType );
}
// -----------------------------------------------------------------------
void TabDialog::AdjustLayout()
{
ImplPosControls();
}
<|endoftext|> |
<commit_before>/**
* L I N E A R A L G E B R A O P C O D E S F O R C S O U N D
* Michael Gogins
*
* These opcodes implement many linear algebra operations
* from BLAS and LAPACK, up to and including eigenvalue decompositions.
* They are designed to facilitate signal processing,
* and of course other mathematical operations,
* in the Csound orchestra language.
*
* The opcodes work with the following data types (and data type codes):
* 1. Real scalars, which are Csound i-rate (ir) or k-rate scalars (kr),
* where x stands for either i or k (xr).
* 2. Complex scalars, which are ordered pairs of Csound scalars (xcr, xci).
* 3. Allocated real vectors (xvr).
* 4. Allocated complex vectors (xvc).
* 5. Allocated real matrices (xmr).
* 6. Allocated complex matrices (xmc).
* 7. Storage for each allocated array is created using AUXCH,
* but it is used as a regular Csound variable,
* which is always a pointer to a floating-point number.
* The size and type code of the array are found
* in the first 8 bytes of storage:
* bytes 0 through 4: number of elements in the array.
* bytes 5 through 7: type code (e.g. 'imc'), encoding rate, rank, type.
* byte 8: first byte of the first element of the array.
*
* The BLAS vector-vector copy functions are overloaded,
* and can also be used for copying BLAS arrays
* to and from other Csound data types:
* 1. Csound a-rate scalars (which are already vectors)
* and function tables (i-rate scalars as function table numbers)
* can copied to and from real vectors (xvr)
* of the same size.
* 2. Csound fsigs (PVS signals, PVSDAT)
* and wsigs (spectral signals, SPECDAT)
* can be copied to and from complex vectors (xvc)
* of the same size.
*
* Opcode names and signatures are determined as follows:
* 1. All opcode names in this library are prefixed "la_" for "linear algebra".
* 2. The opcode name is then additionally prefixed with a data type code.
* Because Csound variables have a fixed precision
* (always single or always double),
* Csound data types (r for real, c for complex) are used instead of
* BLAS data types (S, D, C, Z).
* 3. The body of the opcode name is the same as
* the body of the BLAS or LAPACK name.
* 4. The return values and parameters are prefixed
* first with the Csound rate, then with v for vector or m for matrix,
* then with the data type code, then (if a variable) with an underscore;
* as previously noted complex scalars are pairs of real scalars.
* Thus, the i-rate BLAS complex scalar a is icr_a, ici_a;
* the k-rate BLAS complex vector x is kvc_x; and
* the i-rate or k-rate BLAS real matrix A is xvr_A.
* 5. Because all Csound data types and allocated arrays
* know their own size, BLAS and LAPACK size arguments are omitted,
* except from creator functions; this is similar to the FORTRAN 95
* interface to the BLAS routines.
* 6. Operations that return scalars usually return i-rate or k-rate values
* on the left-hand side of the opcode.
* 7. Operations that return vectors or matrices always copy the return value
* into a preallocated argument on the right-hand side of the opcode.
* 8. The rate (i-rate versus k-rate or a-rate) of either the return value,
* or the first argument if there is no return value, determines
* the rate of the operation. The exact same function is called
* for i-rate, k-rate, and a-rate opcodes;
* the only difference is that an i-rate opcode is evaluated only in the init pass,
* while a k-rate or a-rate opcode is evaluated in each kperiod pass.
* 9. All arrays are 0-based.
*10. All matrices are considered to be row-major
* (x or i goes along rows, y or j goes along columns).
*11. All arrays are considered to be general and dense; therefore, the BLAS
* banded, Hermitian, symmetric, and sparse routines are not implemented.
*12. At this time, only the general-purpose 'driver' routines
* for LAPACK are implemented.
*
* For more complete information on how to use the opcodes,
* what the arguments are, which arguments are inputs, which arguments are outputs,
* and so on, consult BLAS and LAPACK documentation,
* e.g. http://www.intel.com/software/products/mkl/docs/WebHelp/mkl.htm.
*
* The operations are:
*
* ALLOCATORS
*
* Allocate real vector.
* xvr la_rv ir_size
*
* Allocate complex vector.
* xvc la_cv ir_size
*
* Allocate real matrix, with optional diagonal.
* xmr la_rm ir_rows, ir_columns [, or_diagonal]
*
* Allocate complex matrix, with optional diagonal.
* xmc la_cm irows, icolumns [, or_diagonal, oi_diagonal]
*
* LEVEL 1 BLAS -- VECTOR-VECTOR OPERATIONS
*
* Vector-vector dot product:
* Return x * y.
* xr la_rdot xvr_x, xvr_y
* xcr, xci la_cdotu xvc_x, xvc_y
*
* Conjugate vector-vector dot product:
* Return conjg(x) * y.
* xcr, xci la_cdotc xvc_x, xvc_y
*
* Compute y := a * x + y.
* la_raxpy xr_a, xvr_x, xvr_y
* la_caxpy xr_a, xcr_x, xcr_y
*
* Givens rotation:
* Given a point in a, b,
* compute the Givens plane rotation in a, b, c, s
* that zeros the y-coordinate of the point.
* la_rrotg xr_a, xr_b, xr_c, xr_s
* la_crotg xcr_a, xci_a, xcr_b, xci_b, xcr_c, xci_c, xcr_s, xci_s
*
* Rotate a vector x by a vector y:
* For all i, x[i] = c * x[i] + s * y[i];
* For all i, y[i] = c * y[i] - s * x[i].
* la_rrot xvr_x, xvr_y, xr_c, xr_s
* la_crot xvc_x, xvc_y, xr_c, xr_s
*
* Vector copy:
* Compute y := x.
* Note that x or y can be a-rate, function table number,
*
* la_rcopy xvr_x, xvr_y
* la_ccopy xcr_x, xvc_y
*
* Vector swap:
* Swap vector x with vector y.
* la_rswap xvr_x, xvr_y
* la_cswap xcr_x, xvc_y
*
* Vector norm:
* Return the Euclidean norm of vector x.
* xr rnrm2 xvr_x
* xcr, xci cnrm2 xcr_x
*
* Vector absolute value:
* Return the real sum of the absolute values of the vector elements.
* xr asum xvr_x
* xr axum xcr_x
*
* Vector scale:
* Compute x := alpha * x.
* la_rscal xr_alpha, xvr_x
* la_cscal xcr_alpha, xci_alpha, xcr_x
*
* Vector absolute maximum:
* Return the index of the maximum absolute value in vector x.
* xr la_ramax xvr_x
* xr la_camax xvc_x
*
* Vector absolute minimum:
* Return the index of the minimum absolute value in vector x.
* xr la_ramin xvr_x
* xr la_camin xvc_x
*
* LEVEL 2 BLAS -- MATRIX-VECTOR OPERATIONS
*
* Matrix-vector dot product:
* Compute y := alpha * A * x + beta * y, if trans is 0.
* Compute y := alpha * A' * x + beta * y, if trans is 1.
* Compute y := alpha * conjg(A') * x + beta * y, if trans is 2.
* la_rgemv xmr_A, xvr_x, xvr_ay [, Pr_alpha][, or_beta][, or_trans]
* la_cgemv xmc_A, xvc_x, xvc_ay [, Pcr_alpha, oci_alpha][, ocr_beta, oci_beta][, or_trans]
*
* Rank-1 update of a matrix:
* Compute A := alpha * x * y' + A.
* la_rger xr_alpha, xvr_x, xvr_y, xmr_A
* la_cger xcr_alpha, xci_alpha, xvc_x, xvc_y, xmc_A
*
* Rank-1 update of a conjugated matrix:
* Compute A := alpha * x * conjg(y') + A
* la_rgerc xmr_A, xvr_x, xvr_y, [, Pr_alpha]
* la_cgerc xmc_A, xvc_x, xvc_y, [, Pcr_alpha, oci_alpha]
*
* Solve a system of linear equations:
* Coefficients are in a packed triangular matrix,
* upper triangular if uplo = 0, lower triangular if uplo = 1.
* Solve A * x = b for x, if trans = 0.
* Solve A' * x = b for x, if trans = 1.
* Solve conjg(A') * x = b for x, if trans = 2.
* la_rtpsv xmr_A, xvr_x, xvr_b [, or_uplo][, or_trans]
* la_ctpsv xmc_A, xvc_x, xvc_b [, or_uplo][, or_trans]
*
* LEVEL 3 BLAS -- MATRIX-MATRIX OPERATIONS
*
* Matrix-matrix dot product:
* Compute C := alpha * op(A) * op(B) + beta * C,
* where transa or transb is 0 if op(X) is X, 1 if op(X) is X', or 2 if op(X) is conjg(X);
* alpha and beta are 1 by default (set beta to 0 if you don't want to zero C first).
* la_rgemm xmr_A, xmr_B, xmr_C [, or_transa][, or_transb][, Pr_alpha][, Pr_beta]
* la_cgemm xmc_A, xmc_B, xmc_C [, or_transa][, or_transb][, Pcr_alpha, oci_alpha][, Pcr_beta, oci_beta]
*
* Solve a matrix equation:
* Solve op(A) * X = alpha * B or X * op(A) = alpha * B for X,
* where transa is 0 if op(X) is X, 1 if op(X) is X', or 2 if op(X) is conjg(X);
* side is 0 for op(A) on the left, or 1 for op(A) on the right;
* uplo is 0 for upper triangular A, or 1 for lower triangular A;
* and diag is 0 for unit triangular A, or 1 for non-unit triangular A.
* la_rtrsm xmr_A, xmr_B [, or_side][, or_uplo][, or_transa][, or_diag] [, Pr_alpha]
* la_ctrsm xmc_A, cmc_B [, or_side][, or_uplo][, or_transa][, or_diag] [, Pcr_alpha, oci_alpha]
*
* LAPACK -- LINEAR SOLUTIONS
*
* Solve a system of linear equations:
* Solve A * X = B,
* where A is a square matrix of coefficients,
* the columns of B are individual right-hand sides,
* ipiv is a vector for pivot elements,
* the columns of B are replaced with the corresponding solutions,
* and info is replaced with 0 for success, -i for a bad value in the ith parameter,
* or i if U(i, i) is 0, i.e. U is singular.
* la_rgesv xmr_A, xmr_B [, ovr_ipiv][, or_info]
* la_cgesv xmc_A, xmc_B [, ovc_ipiv][, or_info]
*
* LAPACK -- LINEAR LEAST SQUARES PROBLEMS
*
* QR or LQ factorization:
* Uses QR or LQ factorization to solve an overdetermined or underdetermined
* linear system with full rank matrix,
* where A is the m x n matrix to factor;
* B is an m x number of right-hand sides,
* containing B as input and solution X as result;
* if trans = 0, A is normal;
* if trans = 1, A is transposed (real matrices only);
* if trans = 2, A is conjugate-transposed (complex matrices only);
* and info is replaced with 0 for success, -i for a bad value in the ith parameter,
* or i if U(i, i) is 0, the i-th diagonal element of the triangular factor
* of A is zero, so that A does not have full rank; the least squares solution could not be computed.
* la_rgels xmr_A, xmr_B [, or_trans] [, or_info]
*
* LAPACK -- SINGULAR VALUE DECOMPOSITION
*
* Singular value decomposition of a general rectangular matrix:
* Singular value decomposition of a general rectangular matrix by divide and conquer:
*
* LAPACK -- NONSYMMETRIX EIGENPROBLEMS
*
* Computes the eigenvalues and Schur factorization of a general matrix,
* and orders the factorization so that selected eigenvalues are at the top left of the Schur form:
* Computes the eigenvalues and left and right eigenvectors of a general matrix:
*
* LAPACK -- GENERALIZED NONSYMMETRIC EIGENPROBLEMS
*
* Compute the generalized eigenvalues, Schur form,
* and the left and/or right Schur vectors for a pair of nonsymmetric matrices:
* Computes the generalized eigenvalues, and the left and/or right generalized eigenvectors
* for a pair of nonsymmetric matrices:
*
*/
extern "C"
{
// a-rate, k-rate, FUNC, SPECDAT
#include <csoundCore.h>
// PVSDAT
#include <pstream.h>
}
/**
* Used for all types of arrays
* (vectors and matrices, real and complex).
*/
struct BLASArray
{
size_t elements;
char[4] typecode;
MYFLT *data;
};
#include <OpcodeBase.hpp>
<commit_msg>Renamed to linear_algebra.cpp.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2016. Imed Eddine Nezzar <imad.eddine.nezzar[at]gmail.com>
#include <iostream>
#include <algorithm> // swap()
#include <vector> // vector<double>
#define MAX_SIZE 10
using namespace std;
vector<double> sum(const vector<double>& pli, const vector<double>& plii) {
/*
Return the sum to two polynomial equations.
Example:
a x^n + b x^(n-1)...
+ a'x^n + b'x^(n-1)...
-----------------------------------
(a + a')x^n + (b + b')x^(n-1)...
*/
vector<double> r(MAX_SIZE);
for (int power = 0; power < MAX_SIZE; ++power) {
r[power] = pli[power] + plii[power];
}
return r;
}
vector<double> multiply (const vector<double>& pli, const vector<double>& plii) {
/*
Return the multiplication to two polynomial equations.
TODO: implement this correclly
*/
vector<double> r(MAX_SIZE * 2);
for (int power = 0; power < MAX_SIZE; ++ power) {
r[power * 2] = pli[power] * plii[power];
}
return r;
}
vector<double> derive(const vector<double>& pl) {
vector<double> r(MAX_SIZE);
for (int power = 1; power < MAX_SIZE; ++power) {
r[power - 1] = pl[power] * power;
}
return r;
}
vector<double> integral(const vector<double>& pl) {
vector<double> r(MAX_SIZE);
for (int power = MAX_SIZE - 1; power >= 0; --power) {
r[power + 1] = pl[power] / power;
}
return r;
}
int comp(const vector<double>& pli, const vector<double>& plii) {
for (int power = MAX_SIZE; power >= 0; --power) {
if (pli[power] < plii[power]) return -1;
else if (pli[power] > plii[power]) return 1;
}
return 0;
}
int min(const vector<vector<double> >& stack) {
int m = 0;
for (int i = 1; i < MAX_SIZE; ++i) {
if (comp(stack[m], stack[i]) == 1)
m = i;
}
return m;
}
int max(const vector<vector<double> >& stack) {
int m = 0;
for (int i = 1; i < MAX_SIZE; ++i) {
if (comp(stack[m], stack[i]) == -1)
m = i;
}
return m;
}
void sort(vector<vector<double> >& stack) {
bool swapped;
int k = 0;
do {
swapped = false;
for (int i = 1; i < MAX_SIZE - k; ++i) {
if (comp(stack[i], stack[i - 1]) == -1) {
swap(stack[i], stack[i - 1]);
swapped = true;
}
}
++k;
} while (swapped);
}
int main(void) {
// FIXME: complete this.
return 0;
}
<commit_msg>Worked on Polynomial_equations.cpp<commit_after>// Copyright (c) 2016. Imed Eddine Nezzar <imad.eddine.nezzar[at]gmail.com>
#include <iostream>
#include <algorithm> // swap()
#include <vector> // vector<double>
#define LIMIT 10
using namespace std;
vector<double> sum(const vector<double>& p, const vector<double>& pi) {
/*
Return the sum to two polynomial equations.
Example:
a x^n + b x^(n-1)...
+ a'x^n + b'x^(n-1)...
-----------------------------------
(a + a')x^n + (b + b')x^(n-1)...
*/
vector<double> r(LIMIT, 0);
for (int power = 0; power < LIMIT; ++power)
r[power] = p[power] + pi[power];
return r;
}
vector<double> multiply (const vector<double>& p, const vector<double>& pi) {
/*
Return the multipcation to two polynomial equations.
Example:
(a x^n + b x^(n-1)...) * (a' x^(n) + b' x^(n-1))
(aa'x^(n+n) + ab'x^(n+n-1) + ... + ba'x(n+n-1) + bb'x(n-1+n-1) + ...
*/
vector<double> r(LIMIT * 2, 0);
for (int outer = 0; outer < LIMIT; ++outer) {
for (int inner = 0; inner < LIMIT; ++inner) {
r[outer + inner] += (p[outer] * pi[inner]);
}
}
return r;
}
vector<double> derive(const vector<double>& pl) {
/*
* TODO: write documentation
*/
vector<double> r(LIMIT, 0);
for (int power = 1; power < LIMIT; ++power)
r[power - 1] = pl[power] * power;
return r;
}
vector<double> integral(const vector<double>& pl) {
/*
* TODO: write documentation
* FIXME: correct this implementation
*/
vector<double> r(LIMIT, 0);
for (int power = 0; power <LIMIT; ++power)
r[power + 1] = pl[power] / power + 1;
return r;
}
int comp(const vector<double>& p, const vector<double>& pi) {
/*
* TODO: write documentation
*/
for (int power = LIMIT; power >= 0; --power) {
if (p[power] < pi[power]) return -1;
else if (p[power] > pi[power]) return 1;
}
return 0;
}
int min(const vector<vector<double> >& stack) {
/*
* TODO: write documentation
*/
int m = 0;
for (int i = 1; i < LIMIT; ++i) {
if (comp(stack[m], stack[i]) == 1)
m = i;
}
return m;
}
int max(const vector<vector<double> >& stack) {
/*
* TODO: write documentation
*/
int m = 0;
for (int i = 1; i < LIMIT; ++i) {
if (comp(stack[m], stack[i]) == -1)
m = i;
}
return m;
}
void sort(vector<vector<double> >& stack) {
/*
* TODO: write documentation
*/
bool swapped;
int k = 0;
do {
swapped = false;
for (int i = 1; i < LIMIT - k; ++i) {
if (comp(stack[i], stack[i - 1]) == -1) {
swap(stack[i], stack[i - 1]);
swapped = true;
}
}
++k;
} while (swapped);
}
void printPolynomial(const vector<double>& p) {
/*
* TODO: write documentation
*/
for (int i = 0; i < p.size(); ++i) {
cout << p[i] << "(" << i << ") ";
}
cout << endl;
}
int main(void) {
// FIXME: write tests
int n;
vector<double> p1(10, 0), p2(10, 0);
cout << "poli 1: ";
for (int i = 0; i < 10; ++i) cin >> p1[i];
cout << "poli 2: ";
for (int i = 0; i < 10; ++i) cin >> p2[i];
cout << "sum: " << endl;
printPolynomial(sum(p1, p2));
cout << "multi: " << endl;
printPolynomial(multiply(p1, p2));
cout << "integral: "<< endl;
printPolynomial(integral(p1));
cout << "derive: " << endl;
printPolynomial(derive(p1));
return 0;
}
<|endoftext|> |
<commit_before>/*
pvsops.c: pvs and other spectral-based opcodes
Copyright (C) 2017 Victor Lazzarini
This file is part of Csound.
The Csound 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.
Csound 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 Csound; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
*/
#include <algorithm>
#include <plugin.h>
struct PVTrace : csnd::FPlugin<1, 2> {
csnd::AuxMem<float> amps;
static constexpr char const *otypes = "f";
static constexpr char const *itypes = "fk";
int init() {
if (inargs.fsig_data(0).isSliding())
return csound->init_error(Str("sliding not supported"));
if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs &&
inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar)
return csound->init_error(Str("fsig format not supported"));
amps.allocate(csound, inargs.fsig_data(0).nbins());
csnd::Fsig &fout = outargs.fsig_data(0);
fout.init(csound, inargs.fsig_data(0));
framecount = 0;
return OK;
}
int kperf() {
csnd::pv_frame &fin = inargs.fsig_data(0);
csnd::pv_frame &fout = outargs.fsig_data(0);
if (framecount < fin.count()) {
int n = fin.len() - (int)inargs[1];
float thrsh;
std::transform(fin.begin(), fin.end(), amps.begin(),
[](csnd::pv_bin f) { return f.amp(); });
std::nth_element(amps.begin(), amps.begin() + n, amps.end());
thrsh = amps[n];
std::transform(fin.begin(), fin.end(), fout.begin(),
[thrsh](csnd::pv_bin f) {
return f.amp() >= thrsh ? f : csnd::pv_bin();
});
framecount = fout.count(fin.count());
}
return OK;
}
};
struct TVConv : csnd::Plugin<1, 6> {
csnd::AuxMem<MYFLT> ir;
csnd::AuxMem<MYFLT> in;
csnd::AuxMem<MYFLT> insp;
csnd::AuxMem<MYFLT> irsp;
csnd::AuxMem<MYFLT> out;
csnd::AuxMem<MYFLT> saved;
uint32_t n;
uint32_t fils;
uint32_t pars;
uint32_t ffts;
uint32_t nparts;
uint32_t pp;
csnd::fftp fwd, inv;
typedef std::complex<MYFLT> cmplx;
uint32_t rpow2(uint32_t n) {
uint32_t v = 2;
while (v <= n)
v <<= 1;
if ((n - (v >> 1)) < (v - n))
return v >> 1;
else
return v;
}
cmplx *to_cmplx(MYFLT *f) { return reinterpret_cast<cmplx *>(f); }
cmplx real_prod(cmplx &a, cmplx &b) {
return cmplx(a.real() * b.real(), a.imag() * b.imag());
}
int init() {
pars = inargs[4];
fils = inargs[5];
if (pars > fils)
std::swap(pars, fils);
if (pars > 1) {
pars = rpow2(pars);
fils = rpow2(fils);
ffts = pars * 2;
fwd = csound->fft_setup(ffts, FFT_FWD);
inv = csound->fft_setup(ffts, FFT_INV);
out.allocate(csound, 2 * pars);
insp.allocate(csound, 2 * fils);
irsp.allocate(csound, 2 * fils);
saved.allocate(csound, pars);
ir.allocate(csound, 2 * fils);
in.allocate(csound, 2 * fils);
nparts = fils / pars;
fils *= 2;
} else {
ir.allocate(csound, fils);
in.allocate(csound, fils);
}
n = 0;
pp = 0;
return OK;
}
int pconv() {
csnd::AudioSig insig(this, inargs(0));
csnd::AudioSig irsig(this, inargs(1));
csnd::AudioSig outsig(this, outargs(0));
auto irp = irsig.begin();
auto inp = insig.begin();
MYFLT *frz1 = inargs(2);
MYFLT *frz2 = inargs(3);
bool inc1 = csound->is_asig(frz1);
bool inc2 = csound->is_asig(frz2);
for (auto &s : outsig) {
*frz1 > 0 ? in[n + pp] = *inp++ : *inp++;
*frz2 > 0 ? ir[n + pp] = *irp++ : *irp++;
s = out[n] + saved[n];
saved[n] = out[n + pars];
if (++n == pars) {
cmplx *ins, *irs, *ous = to_cmplx(out.data());
std::copy(in.begin() + pp, in.begin() + pp + ffts, insp.begin() + pp);
std::copy(ir.begin() + pp, ir.begin() + pp + ffts, irsp.begin() + pp);
std::fill(out.begin(), out.end(), 0.);
// FFT
csound->rfft(fwd, insp.data() + pp);
csound->rfft(fwd, irsp.data() + pp);
pp += ffts;
if (pp == fils)
pp = 0;
// spectral delay line
for (uint32_t k = 0, kp = pp; k < nparts; k++, kp += ffts) {
if (kp == fils)
kp = 0;
ins = to_cmplx(insp.data() + kp);
irs = to_cmplx(irsp.data() + (nparts - k - 1) * ffts);
// spectral product
for (uint32_t i = 1; i < pars; i++)
ous[i] += ins[i] * irs[i];
ous[0] += real_prod(ins[0], irs[0]);
}
// IFFT
csound->rfft(inv, out.data());
n = 0;
}
frz1 += inc1;
frz2 += inc2;
}
return OK;
}
int dconv() {
csnd::AudioSig insig(this, inargs(0));
csnd::AudioSig irsig(this, inargs(1));
csnd::AudioSig outsig(this, outargs(0));
auto irp = irsig.begin();
auto inp = insig.begin();
MYFLT *frz1 = inargs(2);
MYFLT *frz2 = inargs(3);
bool inc1 = csound->is_asig(frz1);
bool inc2 = csound->is_asig(frz2);
for (auto &s : outsig) {
*frz1 > 0 ? in[pp] = *inp++ : *inp++;
*frz2 > 0 ? ir[pp] = *irp++ : *irp++;
pp = pp != fils - 1 ? pp + 1 : 0;
s = 0.;
for (uint32_t k = 0, kp = pp; k < fils; k++, kp++) {
if (kp == fils)
kp = 0;
s += in[kp] * ir[fils - k - 1];
}
frz1 += inc1;
frz2 += inc2;
}
return OK;
}
int aperf() {
if (pars > 1)
return pconv();
else
return dconv();
}
};
#include <modload.h>
void csnd::on_load(Csound *csound) {
csnd::plugin<PVTrace>(csound, "pvstrace", csnd::thread::ik);
csnd::plugin<TVConv>(csound, "tvconv", "a", "aakkii", csnd::thread::ia);
csnd::plugin<TVConv>(csound, "tvconv", "a", "aaakii", csnd::thread::ia);
csnd::plugin<TVConv>(csound, "tvconv", "a", "aakaii", csnd::thread::ia);
csnd::plugin<TVConv>(csound, "tvconv", "a", "aaaaii", csnd::thread::ia);
}
<commit_msg>making tvconv code more readable<commit_after>/*
pvsops.c: pvs and other spectral-based opcodes
Copyright (C) 2017 Victor Lazzarini
This file is part of Csound.
The Csound 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.
Csound 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 Csound; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
*/
#include <algorithm>
#include <plugin.h>
struct PVTrace : csnd::FPlugin<1, 2> {
csnd::AuxMem<float> amps;
static constexpr char const *otypes = "f";
static constexpr char const *itypes = "fk";
int init() {
if (inargs.fsig_data(0).isSliding())
return csound->init_error(Str("sliding not supported"));
if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs &&
inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar)
return csound->init_error(Str("fsig format not supported"));
amps.allocate(csound, inargs.fsig_data(0).nbins());
csnd::Fsig &fout = outargs.fsig_data(0);
fout.init(csound, inargs.fsig_data(0));
framecount = 0;
return OK;
}
int kperf() {
csnd::pv_frame &fin = inargs.fsig_data(0);
csnd::pv_frame &fout = outargs.fsig_data(0);
if (framecount < fin.count()) {
int n = fin.len() - (int)inargs[1];
float thrsh;
std::transform(fin.begin(), fin.end(), amps.begin(),
[](csnd::pv_bin f) { return f.amp(); });
std::nth_element(amps.begin(), amps.begin() + n, amps.end());
thrsh = amps[n];
std::transform(fin.begin(), fin.end(), fout.begin(),
[thrsh](csnd::pv_bin f) {
return f.amp() >= thrsh ? f : csnd::pv_bin();
});
framecount = fout.count(fin.count());
}
return OK;
}
};
struct TVConv : csnd::Plugin<1, 6> {
csnd::AuxMem<MYFLT> ir;
csnd::AuxMem<MYFLT> in;
csnd::AuxMem<MYFLT> insp;
csnd::AuxMem<MYFLT> irsp;
csnd::AuxMem<MYFLT> out;
csnd::AuxMem<MYFLT> saved;
uint32_t n;
uint32_t fils;
uint32_t pars;
uint32_t ffts;
uint32_t nparts;
uint32_t pp;
csnd::fftp fwd, inv;
typedef std::complex<MYFLT> cmplx;
uint32_t rpow2(uint32_t n) {
uint32_t v = 2;
while (v <= n)
v <<= 1;
if ((n - (v >> 1)) < (v - n))
return v >> 1;
else
return v;
}
cmplx *to_cmplx(MYFLT *f) { return reinterpret_cast<cmplx *>(f); }
cmplx real_prod(cmplx &a, cmplx &b) {
return cmplx(a.real() * b.real(), a.imag() * b.imag());
}
int init() {
pars = inargs[4];
fils = inargs[5];
if (pars > fils)
std::swap(pars, fils);
if (pars > 1) {
pars = rpow2(pars);
fils = rpow2(fils);
ffts = pars * 2;
fwd = csound->fft_setup(ffts, FFT_FWD);
inv = csound->fft_setup(ffts, FFT_INV);
out.allocate(csound, 2 * pars);
insp.allocate(csound, 2 * fils);
irsp.allocate(csound, 2 * fils);
saved.allocate(csound, pars);
ir.allocate(csound, 2 * fils);
in.allocate(csound, 2 * fils);
nparts = fils / pars;
fils *= 2;
} else {
ir.allocate(csound, fils);
in.allocate(csound, fils);
}
n = 0;
pp = 0;
return OK;
}
int pconv() {
csnd::AudioSig insig(this, inargs(0));
csnd::AudioSig irsig(this, inargs(1));
csnd::AudioSig outsig(this, outargs(0));
auto irp = irsig.begin();
auto inp = insig.begin();
MYFLT *frz1 = inargs(2);
MYFLT *frz2 = inargs(3);
bool inc1 = csound->is_asig(frz1);
bool inc2 = csound->is_asig(frz2);
for (auto &s : outsig) {
if(*frz1 > 0) in[pp] = *inp;
if(*frz2 > 0) ir[pp] = *irp;
s = out[n] + saved[n];
saved[n] = out[n + pars];
if (++n == pars) {
cmplx *ins, *irs, *ous = to_cmplx(out.data());
std::copy(in.begin() + pp, in.begin() + pp + ffts, insp.begin() + pp);
std::copy(ir.begin() + pp, ir.begin() + pp + ffts, irsp.begin() + pp);
std::fill(out.begin(), out.end(), 0.);
// FFT
csound->rfft(fwd, insp.data() + pp);
csound->rfft(fwd, irsp.data() + pp);
pp += ffts;
if (pp == fils)
pp = 0;
// spectral delay line
for (uint32_t k = 0, kp = pp; k < nparts; k++, kp += ffts) {
if (kp == fils)
kp = 0;
ins = to_cmplx(insp.data() + kp);
irs = to_cmplx(irsp.data() + (nparts - k - 1) * ffts);
// spectral product
for (uint32_t i = 1; i < pars; i++)
ous[i] += ins[i] * irs[i];
ous[0] += real_prod(ins[0], irs[0]);
}
// IFFT
csound->rfft(inv, out.data());
n = 0;
}
frz1 += inc1;
frz2 += inc2;
irp++;
inp++;
}
return OK;
}
int dconv() {
csnd::AudioSig insig(this, inargs(0));
csnd::AudioSig irsig(this, inargs(1));
csnd::AudioSig outsig(this, outargs(0));
auto irp = irsig.begin();
auto inp = insig.begin();
MYFLT *frz1 = inargs(2);
MYFLT *frz2 = inargs(3);
bool inc1 = csound->is_asig(frz1);
bool inc2 = csound->is_asig(frz2);
for (auto &s : outsig) {
if(*frz1 > 0) in[pp] = *inp;
if(*frz2 > 0) ir[pp] = *irp;
pp = pp != fils - 1 ? pp + 1 : 0;
s = 0.;
for (uint32_t k = 0, kp = pp; k < fils; k++, kp++) {
if (kp == fils)
kp = 0;
s += in[kp] * ir[fils - k - 1];
}
frz1 += inc1;
frz2 += inc2;
inp++;
irp++;
}
return OK;
}
int aperf() {
if (pars > 1)
return pconv();
else
return dconv();
}
};
#include <modload.h>
void csnd::on_load(Csound *csound) {
csnd::plugin<PVTrace>(csound, "pvstrace", csnd::thread::ik);
csnd::plugin<TVConv>(csound, "tvconv", "a", "aakkii", csnd::thread::ia);
csnd::plugin<TVConv>(csound, "tvconv", "a", "aaakii", csnd::thread::ia);
csnd::plugin<TVConv>(csound, "tvconv", "a", "aakaii", csnd::thread::ia);
csnd::plugin<TVConv>(csound, "tvconv", "a", "aaaaii", csnd::thread::ia);
}
<|endoftext|> |
<commit_before>#include <QtNetwork/QTcpSocket>
#include <QFileInfo>
#include <QFile>
#include <QStringList>
#include <QDir>
#include <QThread>
#include "httpconnection.h"
HTTPConnection::HTTPConnection(int socketDescriptor, const QString &docRoot,
QObject *parent) : QObject(parent), socket(this),
isParsedHeader(false), eventLoop(this), docRoot(docRoot),
responseStatusLine("HTTP/1.0 %1\r\n")
{
if(!socket.setSocketDescriptor(socketDescriptor)){
qDebug() << socket.errorString() << "Cannot set sd: " << socketDescriptor;
emit closed();
}
}
void HTTPConnection::start()
{
qDebug() << "start() in: " << QThread::currentThread();
connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this,
SLOT(onError(QAbstractSocket::SocketError)));
connect(&socket, SIGNAL(readyRead()), this, SLOT(read()));
connect(this, SIGNAL(requestParsed(RequestData)), this,
SLOT(onRequestParsed(RequestData)));
connect(this, SIGNAL(closed()), &eventLoop, SLOT(quit()));
eventLoop.exec();
}
void HTTPConnection::read(){
qDebug() << "reead() in: " << QThread::currentThread();
request.append(QString(socket.readAll()));
QString lf = "\n\n";
int crlfPos = request.indexOf("\r\n\r\n");
int lfPos = request.indexOf("\n\n");
if(!isParsedHeader && (-1 != crlfPos || -1 != lfPos)){
isParsedHeader = true;
requestData = parser.parseRequestHeader(request);
if(-1 != crlfPos){
lf = "\r\n\r\n";
lfPos = crlfPos;
}
bytesToParse = requestData.contentLength;
//discard the header from the request
request = request.replace(lf, "").right(request.size()-lfPos-lf.size());
}
if(isParsedHeader && "POST" == requestData.method && !request.isEmpty()){
if(0 >= bytesToParse){
//a POST request with no Content-Length is bogus as per standard
requestData.valid = false;
emit requestParsed(requestData);
}
bytesToParse -= request.size();
QHash<QString, QString> postData = parser.parsePostBody(request);
if(!postData.isEmpty()){
QHash<QString, QString>::const_iterator i;
for(i = postData.constBegin(); i != postData.constEnd(); ++i){
requestData.postData.insert(i.key(), i.value());
}
request = "";
}
}
if(isParsedHeader &&
(0 == bytesToParse || "GET" == requestData.method)){
emit requestParsed(requestData);
}
}
QByteArray HTTPConnection::processRequestData(const RequestData &requestData)
{
//TODO: add support for different Host values?
//TODO: URL rewriting?
//TODO: integrate PHP
QByteArray response = responseStatusLine.arg("200 OK").toUtf8();
if(!requestData.valid){
return responseStatusLine.arg("400 Bad request\r\n").toAscii();
}
if("GET" == requestData.method || "POST" == requestData.method){
//serve static files
/* TODO:
* Metoda de servire a fisierelor statice e cam ineficienta.
* Practic incarci tot fisierul in memorie si tot concatenezi array-uri,
* cand ai putea sa trimiti direct pe tava pe masura ce citesti.
*/
QString fullPath = docRoot + requestData.url.path();
QFileInfo f(fullPath);
qDebug() << requestData.method << " " << fullPath;
if(f.exists() && f.isReadable()){
if(f.isDir()){
response = serveStaticDir(response, f.absoluteFilePath());
}
else{
response = serveStaticFile(response, f.absoluteFilePath());
if(response.isEmpty()){
response = responseStatusLine.arg(
"500 Internal Server Error\r\n").toAscii();
}
}
}
/* TODO: load things via a common interface from .so and .dll files?
* -> evolve this into FastCGI? read more
*
* or at least create a mapping of path -> method
*
* What's below isn't good because I have to modify the daemon every
* time I want new functionality and the "login", "check", etc.
* methods are not a semantic part of HTTPThread
*/
else if("/patrat" == requestData.url.path()){
response = square(response, requestData);
}
else if("/login" == requestData.url.path()){
response = login(response, requestData);
}
else if("/verifica" == requestData.url.path()){
response = check(response, requestData);
}
else if(!f.exists()){
response = responseStatusLine.arg("404 Not Found\r\n").toAscii();
}
else if(!f.isReadable()){
qDebug() << "Not readable!";
response = responseStatusLine.arg("403 Forbidden\r\n").toAscii() +
"Permission denied\n";
}
}
else{
response = responseStatusLine.arg("501 Not Implemented\r\n").toAscii();
qDebug() << "Unsupported HTTP method!";
}
return response;
}
QByteArray HTTPConnection::serveStaticFile(const QByteArray &partialResponse,
const QString &filePath)
{
//TODO: set the mime type
QFile file(filePath);
if(!file.open( QIODevice::ReadOnly)){
qDebug() << "Cannot open";
return "";
}
return partialResponse + "\r\n" + file.readAll();
}
QByteArray HTTPConnection::serveStaticDir(const QByteArray &partialResponse,
const QString &dirPath)
{
QDir dir(dirPath);
QStringList dirList = dir.entryList();
if(dirList.isEmpty()){
return responseStatusLine.arg("404 Not Found\r\n").toAscii();
}
//TODO: format as HTML
return partialResponse + "Content-Type: text/plain\r\n\r\n" +
dirList.join("\n").toUtf8();
}
QByteArray HTTPConnection::square(const QByteArray &partialResponse,
const RequestData &requestData)
{
if("GET" != requestData.method || !requestData.url.hasQueryItem("a")){
return responseStatusLine.arg("400 Bad Request\r\n").toAscii();
}
QString numToSquare = requestData.url.queryItemValue("a");
QString body;
bool ok;
double n = numToSquare.toDouble(&ok);
if(!ok){
body = "a-ul trebuie sa fie numar!\n";
}
else{
body = numToSquare + "^2 = " + QString::number(n*n) + "\n";
}
return partialResponse + "\r\n" + body.toAscii();
}
QByteArray HTTPConnection::login(const QByteArray &partialResponse,
const RequestData &requestData)
{
QString page = "\r\n<html><body>"
"<form method=\"POST\">"
"%1"
"Username: <input type=\"text\" name=\"username\">"
"Password: <input type=\"password\" name=\"pass\">"
"<INPUT type=\"submit\" value=\"Auth\">"
"</form></body></html>";
if("GET" == requestData.method){
return partialResponse + page.arg("").toAscii();
}
if("POST" == requestData.method && !requestData.postData.isEmpty()){
if(requestData.postData.contains("username") &&
"Ion" == requestData.postData["username"] &&
requestData.postData.contains("pass") &&
"1234" == requestData.postData["pass"]){
return partialResponse + "Set-Cookie: loggedin=1\r\n\r\nYou're logged in!";
}
return partialResponse +
page.arg("Login failed, try again!<br>").toAscii();
}
return responseStatusLine.arg("400 Bad request\r\n").toAscii();
}
QByteArray HTTPConnection::check(const QByteArray &partialResponse,
const RequestData &requestData)
{
if("GET" != requestData.method){
return responseStatusLine.arg("400 Bad request\r\n").toAscii();
}
if(requestData.fields.contains("Cookie") &&
"loggedin=1" == requestData.fields["Cookie"][0]){
return partialResponse + "\r\nYou're logged in!";
}
return partialResponse + "\r\nYou're not logged in!";;
}
void HTTPConnection::onError(QAbstractSocket::SocketError socketError)
{
qDebug() << socketError << ": " << socket.errorString();
socket.disconnectFromHost();
socket.waitForDisconnected(1000);
emit closed();
}
void HTTPConnection::onRequestParsed(const RequestData &requestData)
{
qDebug() << "Request data:\n\tMethod: "
<< requestData.method << "\n\tUrl: "
<< requestData.url << "\n\tProtocol: "
<< requestData.protocol << "\n\tVer: "
<<requestData.protocolVersion
<< "\n\tFields: " << requestData.fields
<< "\n\tContent-Length: " << requestData.contentLength
<< "\n\tpost: " << requestData.postData;
QByteArray response = processRequestData(requestData);
socket.write(response, response.size());
socket.disconnectFromHost();
socket.waitForDisconnected(1000);
emit closed();
}
<commit_msg>updated TODOs<commit_after>#include <QtNetwork/QTcpSocket>
#include <QFileInfo>
#include <QFile>
#include <QStringList>
#include <QDir>
#include <QThread>
#include "httpconnection.h"
/*TODO: refactor
Creezi doua clase model, HTTPRequest, HTTPResponse ce contin informatiile
primite/de trimis catre client. De exemplu metoda, versiunea, content length,
cookie-uri, etc. Query-ul, de exemplu ar fi stocat frumos sub forma de perechi
cheie-valoare. Cele doua clase ar contine si cate un stream pentru citire
respectiv scriere. Creezi o clasa HTTPRequestParser ce ar avea rolul de a citi
informatiile primite prin socket si de a crea o clasa HTTPRequest
corespunzatoare. Stream-ul la care va face referire aceasta clase va permite
citirea ulterioara a informatiilor in cazul unui POST de exemplu.
Dupa ce ai obtinut un HTTPRequest, il dai mai departe catre o instanta a unei
noi clase, sa-i zicem Dispatcher, ce verifica ce este cerut defapt si, pe baza
unor reguli, returneaza o referinta spre un HTTPRequestHandler.
HTTPRequestHandler-ul ales va primi apoi cererea si va returna un raspuns,
HTTPResponse. Din stream-ul mentionat in acesta, se vor citi datele pe care
serverul le va trimite inapoi, spre client. Exemple de HTTPRequestHandler ar fi
FileHTTPRequestHandler ce serveste static un fisier aflat pe disc, sau diverse
clase ce ar reprezenta aplicatii custom gen cea necesara pentru /patrat. Astfel
de aplicatii ar putea fi stocate si in DLL-uri, ele fiind destul de
independente. Treaba lor ar fi astfel doar de a returna un raspuns la o cerere,
neinteresandu-le cum citesti tu din socket, sau cum gestionezi 1000 de conexiuni
simultane.
*/
HTTPConnection::HTTPConnection(int socketDescriptor, const QString &docRoot,
QObject *parent) : QObject(parent), socket(this),
isParsedHeader(false), eventLoop(this), docRoot(docRoot),
responseStatusLine("HTTP/1.0 %1\r\n")
{
if(!socket.setSocketDescriptor(socketDescriptor)){
qDebug() << socket.errorString() << "Cannot set sd: " << socketDescriptor;
emit closed();
}
}
void HTTPConnection::start()
{
qDebug() << "start() in: " << QThread::currentThread();
connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this,
SLOT(onError(QAbstractSocket::SocketError)));
connect(&socket, SIGNAL(readyRead()), this, SLOT(read()));
connect(this, SIGNAL(requestParsed(RequestData)), this,
SLOT(onRequestParsed(RequestData)));
connect(this, SIGNAL(closed()), &eventLoop, SLOT(quit()));
eventLoop.exec();
}
void HTTPConnection::read(){
qDebug() << "reead() in: " << QThread::currentThread();
request.append(QString(socket.readAll()));
QString lf = "\n\n";
int crlfPos = request.indexOf("\r\n\r\n");
int lfPos = request.indexOf("\n\n");
if(!isParsedHeader && (-1 != crlfPos || -1 != lfPos)){
isParsedHeader = true;
requestData = parser.parseRequestHeader(request);
if(-1 != crlfPos){
lf = "\r\n\r\n";
lfPos = crlfPos;
}
bytesToParse = requestData.contentLength;
//discard the header from the request
request = request.replace(lf, "").right(request.size()-lfPos-lf.size());
}
if(isParsedHeader && "POST" == requestData.method && !request.isEmpty()){
if(0 >= bytesToParse){
//a POST request with no Content-Length is bogus as per standard
requestData.valid = false;
emit requestParsed(requestData);
}
bytesToParse -= request.size();
QHash<QString, QString> postData = parser.parsePostBody(request);
if(!postData.isEmpty()){
QHash<QString, QString>::const_iterator i;
for(i = postData.constBegin(); i != postData.constEnd(); ++i){
requestData.postData.insert(i.key(), i.value());
}
request = "";
}
}
if(isParsedHeader &&
(0 == bytesToParse || "GET" == requestData.method)){
emit requestParsed(requestData);
}
}
QByteArray HTTPConnection::processRequestData(const RequestData &requestData)
{
//TODO: add support for different Host values?
//TODO: URL rewriting?
//TODO: integrate FastCGI
QByteArray response = responseStatusLine.arg("200 OK").toUtf8();
if(!requestData.valid){
return responseStatusLine.arg("400 Bad request\r\n").toAscii();
}
if("GET" == requestData.method || "POST" == requestData.method){
//serve static files
/* TODO: optimize the sending of static files (don't load the whole
* thing in memory)
*/
QString fullPath = docRoot + requestData.url.path();
QFileInfo f(fullPath);
qDebug() << requestData.method << " " << fullPath;
if(f.exists() && f.isReadable()){
if(f.isDir()){
response = serveStaticDir(response, f.absoluteFilePath());
}
else{
response = serveStaticFile(response, f.absoluteFilePath());
if(response.isEmpty()){
response = responseStatusLine.arg(
"500 Internal Server Error\r\n").toAscii();
}
}
}
else if("/patrat" == requestData.url.path()){
response = square(response, requestData);
}
else if("/login" == requestData.url.path()){
response = login(response, requestData);
}
else if("/verifica" == requestData.url.path()){
response = check(response, requestData);
}
else if(!f.exists()){
response = responseStatusLine.arg("404 Not Found\r\n").toAscii();
}
else if(!f.isReadable()){
qDebug() << "Not readable!";
response = responseStatusLine.arg("403 Forbidden\r\n").toAscii() +
"Permission denied\n";
}
}
else{
response = responseStatusLine.arg("501 Not Implemented\r\n").toAscii();
qDebug() << "Unsupported HTTP method!";
}
return response;
}
QByteArray HTTPConnection::serveStaticFile(const QByteArray &partialResponse,
const QString &filePath)
{
//TODO: set the mime type
QFile file(filePath);
if(!file.open( QIODevice::ReadOnly)){
qDebug() << "Cannot open";
return "";
}
return partialResponse + "\r\n" + file.readAll();
}
QByteArray HTTPConnection::serveStaticDir(const QByteArray &partialResponse,
const QString &dirPath)
{
QDir dir(dirPath);
QStringList dirList = dir.entryList();
if(dirList.isEmpty()){
return responseStatusLine.arg("404 Not Found\r\n").toAscii();
}
//TODO: format as HTML
return partialResponse + "Content-Type: text/plain\r\n\r\n" +
dirList.join("\n").toUtf8();
}
QByteArray HTTPConnection::square(const QByteArray &partialResponse,
const RequestData &requestData)
{
if("GET" != requestData.method || !requestData.url.hasQueryItem("a")){
return responseStatusLine.arg("400 Bad Request\r\n").toAscii();
}
QString numToSquare = requestData.url.queryItemValue("a");
QString body;
bool ok;
double n = numToSquare.toDouble(&ok);
if(!ok){
body = "a-ul trebuie sa fie numar!\n";
}
else{
body = numToSquare + "^2 = " + QString::number(n*n) + "\n";
}
return partialResponse + "\r\n" + body.toAscii();
}
QByteArray HTTPConnection::login(const QByteArray &partialResponse,
const RequestData &requestData)
{
QString page = "\r\n<html><body>"
"<form method=\"POST\">"
"%1"
"Username: <input type=\"text\" name=\"username\">"
"Password: <input type=\"password\" name=\"pass\">"
"<INPUT type=\"submit\" value=\"Auth\">"
"</form></body></html>";
if("GET" == requestData.method){
return partialResponse + page.arg("").toAscii();
}
if("POST" == requestData.method && !requestData.postData.isEmpty()){
if(requestData.postData.contains("username") &&
"Ion" == requestData.postData["username"] &&
requestData.postData.contains("pass") &&
"1234" == requestData.postData["pass"]){
return partialResponse + "Set-Cookie: loggedin=1\r\n\r\nYou're logged in!";
}
return partialResponse +
page.arg("Login failed, try again!<br>").toAscii();
}
return responseStatusLine.arg("400 Bad request\r\n").toAscii();
}
QByteArray HTTPConnection::check(const QByteArray &partialResponse,
const RequestData &requestData)
{
if("GET" != requestData.method){
return responseStatusLine.arg("400 Bad request\r\n").toAscii();
}
if(requestData.fields.contains("Cookie") &&
"loggedin=1" == requestData.fields["Cookie"][0]){
return partialResponse + "\r\nYou're logged in!";
}
return partialResponse + "\r\nYou're not logged in!";;
}
void HTTPConnection::onError(QAbstractSocket::SocketError socketError)
{
qDebug() << socketError << ": " << socket.errorString();
socket.disconnectFromHost();
socket.waitForDisconnected(1000);
emit closed();
}
void HTTPConnection::onRequestParsed(const RequestData &requestData)
{
qDebug() << "Request data:\n\tMethod: "
<< requestData.method << "\n\tUrl: "
<< requestData.url << "\n\tProtocol: "
<< requestData.protocol << "\n\tVer: "
<<requestData.protocolVersion
<< "\n\tFields: " << requestData.fields
<< "\n\tContent-Length: " << requestData.contentLength
<< "\n\tpost: " << requestData.postData;
QByteArray response = processRequestData(requestData);
socket.write(response, response.size());
socket.disconnectFromHost();
socket.waitForDisconnected(1000);
emit closed();
}
<|endoftext|> |
<commit_before>#include "urtupdater.h"
#include "ui_urtupdater.h"
UrTUpdater::UrTUpdater(QWidget *parent) : QMainWindow(parent), ui(new Ui::UrTUpdater)
{
ui->setupUi(this);
updaterVersion = "4.0.1";
downloadServer = 0;
gameEngine = 0;
configFileExists = false;
QMenu *menuFile = menuBar()->addMenu("&File");
QMenu *menuHelp = menuBar()->addMenu("&Help");
QAction *actionEngine = menuFile->addAction("&Engine Selection");
connect(actionEngine, SIGNAL(triggered()), this, SLOT(engineSelection()));
QAction *actionDlServer = menuFile->addAction("&Download Server Selection");
connect(actionDlServer, SIGNAL(triggered()), this, SLOT(serverSelection()));
QAction *actionChangelog = menuFile->addAction("&Changelog");
//connect(actionChangelog, SIGNAL(triggered()), this, SLOT(openChangelogPage()));
QAction *actionAbout = menuHelp->addAction("&About");
//connect(actionAbout, SIGNAL(triggered()), this, SLOT(openAboutPage()));
QAction *actionHelp = menuHelp->addAction("&Get help");
//connect(actionHelp, SIGNAL(triggered()), this, SLOT(openHelpPage()));
actionHelp->setShortcut(QKeySequence("Ctrl+H"));
QAction *actionQuitter = menuFile->addAction("&Quit");
connect(actionQuitter, SIGNAL(triggered()), this, SLOT(quit()));
actionQuitter->setShortcut(QKeySequence("Ctrl+Q"));
connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(quit()));
init();
}
UrTUpdater::~UrTUpdater()
{
delete ui;
}
void UrTUpdater::init(){
updaterPath = getCurrentPath();
// Check if this is the first launch of the updater
if(!QFile::exists(updaterPath + URT_GAME_SUBDIR)){
QMessageBox msg;
int result;
msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
msg.setIcon(QMessageBox::Information);
msg.setText("The game " URT_GAME_NAME " will be installed in this path:\n" + updaterPath + "\n"
+ "To change the installation path, please click on \"Cancel\" and copy this Updater to where you want it to be installed.");
result = msg.exec();
// If we want to quit
if(result == QMessageBox::Cancel){
quit();
}
// Create the game folder
else {
if(!QDir().mkdir(updaterPath + URT_GAME_SUBDIR)){
QMessageBox::critical(this, QString(URT_GAME_SUBDIR) + " folder", "Could not create the game folder (" + updaterPath + URT_GAME_SUBDIR + ").\n"
+ "Please move the updater to a folder where it has sufficient permissions.");
quit();
}
}
}
parseLocalConfig();
getManifest("versionInfo");
}
QString UrTUpdater::getPlatform()
{
#ifdef Q_OS_MAC
return "Mac";
#endif
#ifdef Q_OS_LINUX
return "Linux";
#endif
#ifdef Q_OS_WIN32
return "Windows";
#endif
return "Linux";
}
QString UrTUpdater::getCurrentPath(){
QDir dir = QDir(QCoreApplication::applicationDirPath());
// If we're on Mac, 'dir' will contain the path to the executable
// inside of the Updater's bundle which isn't what we want.
// We need to cd ../../..
if(getPlatform() == "Mac"){
dir.cdUp();
dir.cdUp();
dir.cdUp();
}
return dir.absolutePath() + "/";
}
void UrTUpdater::parseLocalConfig(){
QDomDocument *dom = new QDomDocument();
QFile *f = new QFile(updaterPath + URT_UPDATER_CFG);
if(!f->open(QFile::ReadOnly)){
delete f;
configFileExists = false;
return;
}
dom->setContent(f);
QDomNode node = dom->firstChild();
while(!node.isNull()){
if(node.toElement().nodeName() == "UpdaterConfig"){
QDomNode conf = node.firstChild();
while(!conf.isNull()){
if(conf.toElement().nodeName() == "DownloadServer"){
downloadServer = conf.toElement().text().toInt();
}
if(conf.toElement().nodeName() == "GameEngine"){
gameEngine = conf.toElement().text().toInt();
}
conf = conf.nextSibling();
}
}
node = node.nextSibling();
}
configFileExists = true;
f->close();
delete f;
delete dom;
}
void UrTUpdater::saveLocalConfig(){
QFile *f = new QFile(updaterPath + URT_UPDATER_CFG);
QXmlStreamWriter *xml = new QXmlStreamWriter();
if(!f->open(QFile::WriteOnly)){
QMessageBox::critical(0, "Could not write the config file", "Could not write the Updater config file inside of the game folder. Your updater preferences won't be saved.");
delete f;
return;
}
xml->setDevice(f);
xml->writeStartDocument();
xml->writeStartElement("UpdaterConfig");
xml->writeStartElement("DownloadServer");
xml->writeCharacters(QString::number(downloadServer));
xml->writeEndElement();
xml->writeStartElement("GameEngine");
xml->writeCharacters(QString::number(gameEngine));
xml->writeEndElement();
xml->writeEndElement();
xml->writeEndDocument();
f->close();
qDebug() << "Local config saved." << endl;
delete f;
delete xml;
}
void UrTUpdater::getManifest(QString query){
QUrl APIUrl(URT_API_LINK);
QUrlQuery url;
QNetworkRequest apiRequest(APIUrl);
QNetworkAccessManager *apiManager = new QNetworkAccessManager(this);
qDebug() << "query: " << query << endl;
apiRequest.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded;charset=utf-8");
url.addQueryItem("platform", getPlatform());
url.addQueryItem("query", query);
apiAnswer = apiManager->post(apiRequest, url.query(QUrl::FullyEncoded).toUtf8());
connect(apiAnswer, SIGNAL(finished()), this, SLOT(parseAPIAnswer()));
connect(apiAnswer, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkError(QNetworkReply::NetworkError)));
}
void UrTUpdater::parseAPIAnswer(){
QByteArray apiByteAnswer = apiAnswer->readAll();
QString apiData = QString(apiByteAnswer);
qDebug() << "apiData: " << apiData << endl;
parseManifest(apiData);
}
void UrTUpdater::parseManifest(QString data){
QDomDocument* dom = new QDomDocument();
dom->setContent(data);
QDomNode node = dom->firstChild();
while(!node.isNull()){
if(node.toElement().nodeName() == "Updater"){
QDomNode updater = node.firstChild();
while(!updater.isNull()){
if(updater.toElement().nodeName() == "VersionInfo"){
QDomNode versionInfo = updater.firstChild();
while(!versionInfo.isNull()){
if(versionInfo.nodeName() == "VersionNumber"){
versionNumber = versionInfo.toElement().text();
}
if(versionInfo.nodeName() == "ReleaseDate"){
releaseDate = versionInfo.toElement().text();
}
versionInfo = versionInfo.nextSibling();
}
}
else if(updater.toElement().nodeName() == "ServerList"){
QDomNode serverListNode = updater.firstChild();
while(!serverListNode.isNull()){
if(serverListNode.nodeName() == "Server"){
QDomNode serverNode = serverListNode.firstChild();
int serverId;
QString serverURL;
QString serverName;
QString serverLocation;
serverInfo_s si;
while(!serverNode.isNull()){
if(serverNode.nodeName() == "ServerName"){
serverName = serverNode.toElement().text();
}
if(serverNode.nodeName() == "ServerURL"){
serverURL = serverNode.toElement().text();
}
if(serverNode.nodeName() == "ServerLocation"){
serverLocation = serverNode.toElement().text();
}
if(serverNode.nodeName() == "ServerId"){
serverId = serverNode.toElement().text().toInt();
}
serverNode = serverNode.nextSibling();
}
si.serverId = serverId;
si.serverName = serverName;
si.serverURL = serverURL;
si.serverLocation = serverLocation;
downloadServers.append(si);
}
serverListNode = serverListNode.nextSibling();
}
}
else if(updater.toElement().nodeName() == "EngineList"){
QDomNode engineListNode = updater.firstChild();
while(!engineListNode.isNull()){
if(engineListNode.nodeName() == "Engine"){
QDomNode engineNode = engineListNode.firstChild();
int engineId;
QString engineDir;
QString engineName;
engineInfo_s ei;
while(!engineNode.isNull()){
if(engineNode.nodeName() == "EngineName"){
engineName = engineNode.toElement().text();
}
if(engineNode.nodeName() == "EngineDir"){
engineDir = engineNode.toElement().text();
}
if(engineNode.nodeName() == "EngineId"){
engineId = engineNode.toElement().text().toInt();
}
engineNode = engineNode.nextSibling();
}
ei.engineId = engineId;
ei.engineName = engineName;
ei.engineDir = engineDir;
enginesList.append(ei);
}
engineListNode = engineListNode.nextSibling();
}
}
else if(updater.toElement().nodeName() == "Files"){
QDomNode files = updater.firstChild();
while(!files.isNull()){
if(files.nodeName() == "File"){
QDomNode fileInfo = files.firstChild();
QString fileDir;
QString fileName;
QString fileMd5;
QString fileSize;
bool mustDownload = false;
while(!fileInfo.isNull()){
if(fileInfo.nodeName() == "FileDir"){
fileDir = fileInfo.toElement().text();
}
if(fileInfo.nodeName() == "FileName"){
fileName = fileInfo.toElement().text();
}
if(fileInfo.nodeName() == "FileMD5"){
fileMd5 = fileInfo.toElement().text();
}
if(fileInfo.nodeName() == "FileSize"){
fileSize = fileInfo.toElement().text();
}
fileInfo = fileInfo.nextSibling();
}
QString filePath(updaterPath + fileDir + fileName);
QFile* f = new QFile(filePath);
// If the file does not exist, it must be downloaded.
if(!f->exists()){
mustDownload = true;
}
// If the md5 string is empty, it means that the API wants
// us to delete this file if needed
else if(!fileName.isEmpty() && fileMd5.isEmpty()){
QFile::remove(filePath);
}
// Check the file's md5sum to see if it needs to be updated.
else if(!fileName.isEmpty() && !fileMd5.isEmpty()){
if(getMd5Sum(f) != fileMd5){
mustDownload = true;
qDebug() << "md5 file: " << getMd5Sum(f) << ", " << fileMd5 << endl;
}
}
qDebug() << "fileDir:" << fileDir << endl;
qDebug() << "fileName: " << fileName << endl;
qDebug() << "fileMd5: " << fileMd5 << endl;
if(mustDownload){
fileInfo_s fi;
fi.fileName = fileName;
fi.filePath = fileDir;
fi.fileMd5 = fileMd5;
fi.fileSize = fileSize;
filesToDownload.append(fi);
}
delete f;
}
files = files.nextSibling();
}
}
updater = updater.nextSibling();
}
}
node = node.nextSibling();
}
checkDownloadServer();
checkGameEngine();
delete dom;
}
void UrTUpdater::checkDownloadServer(){
QList<serverInfo_s>::iterator li;
bool found = false;
// Check if the download server that is stored in the config file still exists
for(li = downloadServers.begin(); li != downloadServers.end(); ++li){
if(li->serverId == downloadServer){
found = true;
}
}
// If the engine isn't available anymore, pick the first one in the list
if(!found){
downloadServer = downloadServers.takeFirst().serverId;
}
}
void UrTUpdater::checkGameEngine(){
QList<engineInfo_s>::iterator li;
bool found = false;
// Check if the engine that is stored in the config file still exists
for(li = enginesList.begin(); li != enginesList.end(); ++li){
if(li->engineId == gameEngine){
found = true;
}
}
// If the server isn't a mirror anymore, pick the first one in the list
if(!found){
gameEngine = enginesList.takeFirst().engineId;
}
}
QString UrTUpdater::getMd5Sum(QFile* file)
{
if (file->exists() && file->open(QIODevice::ReadOnly))
{
QByteArray content = file->readAll();
QByteArray hashed = QCryptographicHash::hash(content, QCryptographicHash::Md5);
file->close();
return hashed.toHex().data();
}
return "";
}
void UrTUpdater::networkError(QNetworkReply::NetworkError code){
QString error = "";
bool critical = false;
switch(code){
case QNetworkReply::ConnectionRefusedError:
error = "Error: the remote server refused the connection. Please try again later.";
critical = true;
break;
case QNetworkReply::RemoteHostClosedError:
error = "Error: the remote server closed the connection prematurely. Please try again later.";
break;
case QNetworkReply::HostNotFoundError:
error = "Error: the remote server could not be found. Please check your internet connection!";
critical = true;
break;
case QNetworkReply::TimeoutError:
error = "Error: the connection to the remote server timed out. Please try again.";
break;
case QNetworkReply::TemporaryNetworkFailureError:
error = "Error: the connection to the remote server was broken due to disconnection from the network. Please try again.";
break;
case QNetworkReply::ContentNotFoundError:
error = "Error: the remote content could not be found. Please report this issue on our website: http://www.urbanterror.info";
break;
case QNetworkReply::UnknownNetworkError:
error = "Error: an unknown network-related error was encountered. Please try again";
break;
case QNetworkReply::UnknownContentError:
error = "Error: an unknown content-related error was encountered. Please try again";
break;
default:
case QNetworkReply::NoError:
break;
}
if(!error.isEmpty()){
if(critical == true){
QMessageBox::critical(0, "Download error", error);
quit();
}
else {
QMessageBox::information(0, "Download error", error);
}
}
}
void UrTUpdater::serverSelection(){
ServerSelection *serverSel = new ServerSelection(this);
connect(serverSel, SIGNAL(serverSelected(int)), this, SLOT(setDownloadServer(int)));
serverSel->currentServer = downloadServer;
serverSel->downloadServers = downloadServers;
serverSel->init();
serverSel->exec();
}
void UrTUpdater::engineSelection(){
EngineSelection* engineSel = new EngineSelection(this);
connect(engineSel, SIGNAL(engineSelected(int)), this, SLOT(setEngine(int)));
engineSel->currentEngine = gameEngine;
engineSel->enginesList = enginesList;
engineSel->init();
engineSel->exec();
}
void UrTUpdater::setDownloadServer(int server){
downloadServer = server;
saveLocalConfig();
}
void UrTUpdater::setEngine(int engine){
gameEngine = engine;
saveLocalConfig();
}
void UrTUpdater::quit(){
saveLocalConfig();
exit(0);
}
<commit_msg>The takeFirst() function removes the first element in the list... we don't want this to happen!<commit_after>#include "urtupdater.h"
#include "ui_urtupdater.h"
UrTUpdater::UrTUpdater(QWidget *parent) : QMainWindow(parent), ui(new Ui::UrTUpdater)
{
ui->setupUi(this);
updaterVersion = "4.0.1";
downloadServer = -1;
gameEngine = -1;
configFileExists = false;
QMenu *menuFile = menuBar()->addMenu("&File");
QMenu *menuHelp = menuBar()->addMenu("&Help");
QAction *actionEngine = menuFile->addAction("&Engine Selection");
connect(actionEngine, SIGNAL(triggered()), this, SLOT(engineSelection()));
QAction *actionDlServer = menuFile->addAction("&Download Server Selection");
connect(actionDlServer, SIGNAL(triggered()), this, SLOT(serverSelection()));
QAction *actionChangelog = menuFile->addAction("&Changelog");
//connect(actionChangelog, SIGNAL(triggered()), this, SLOT(openChangelogPage()));
QAction *actionAbout = menuHelp->addAction("&About");
//connect(actionAbout, SIGNAL(triggered()), this, SLOT(openAboutPage()));
QAction *actionHelp = menuHelp->addAction("&Get help");
//connect(actionHelp, SIGNAL(triggered()), this, SLOT(openHelpPage()));
actionHelp->setShortcut(QKeySequence("Ctrl+H"));
QAction *actionQuitter = menuFile->addAction("&Quit");
connect(actionQuitter, SIGNAL(triggered()), this, SLOT(quit()));
actionQuitter->setShortcut(QKeySequence("Ctrl+Q"));
connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(quit()));
init();
}
UrTUpdater::~UrTUpdater()
{
delete ui;
}
void UrTUpdater::init(){
updaterPath = getCurrentPath();
// Check if this is the first launch of the updater
if(!QFile::exists(updaterPath + URT_GAME_SUBDIR)){
QMessageBox msg;
int result;
msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
msg.setIcon(QMessageBox::Information);
msg.setText("The game " URT_GAME_NAME " will be installed in this path:\n" + updaterPath + "\n"
+ "To change the installation path, please click on \"Cancel\" and copy this Updater to where you want it to be installed.");
result = msg.exec();
// If we want to quit
if(result == QMessageBox::Cancel){
quit();
}
// Create the game folder
else {
if(!QDir().mkdir(updaterPath + URT_GAME_SUBDIR)){
QMessageBox::critical(this, QString(URT_GAME_SUBDIR) + " folder", "Could not create the game folder (" + updaterPath + URT_GAME_SUBDIR + ").\n"
+ "Please move the updater to a folder where it has sufficient permissions.");
quit();
}
}
}
parseLocalConfig();
getManifest("versionInfo");
}
QString UrTUpdater::getPlatform()
{
#ifdef Q_OS_MAC
return "Mac";
#endif
#ifdef Q_OS_LINUX
return "Linux";
#endif
#ifdef Q_OS_WIN32
return "Windows";
#endif
return "Linux";
}
QString UrTUpdater::getCurrentPath(){
QDir dir = QDir(QCoreApplication::applicationDirPath());
// If we're on Mac, 'dir' will contain the path to the executable
// inside of the Updater's bundle which isn't what we want.
// We need to cd ../../..
if(getPlatform() == "Mac"){
dir.cdUp();
dir.cdUp();
dir.cdUp();
}
return dir.absolutePath() + "/";
}
void UrTUpdater::parseLocalConfig(){
QDomDocument *dom = new QDomDocument();
QFile *f = new QFile(updaterPath + URT_UPDATER_CFG);
if(!f->open(QFile::ReadOnly)){
delete f;
configFileExists = false;
return;
}
dom->setContent(f);
QDomNode node = dom->firstChild();
while(!node.isNull()){
if(node.toElement().nodeName() == "UpdaterConfig"){
QDomNode conf = node.firstChild();
while(!conf.isNull()){
if(conf.toElement().nodeName() == "DownloadServer"){
downloadServer = conf.toElement().text().toInt();
}
if(conf.toElement().nodeName() == "GameEngine"){
gameEngine = conf.toElement().text().toInt();
}
conf = conf.nextSibling();
}
}
node = node.nextSibling();
}
configFileExists = true;
f->close();
delete f;
delete dom;
}
void UrTUpdater::saveLocalConfig(){
QFile *f = new QFile(updaterPath + URT_UPDATER_CFG);
QXmlStreamWriter *xml = new QXmlStreamWriter();
if(!f->open(QFile::WriteOnly)){
QMessageBox::critical(0, "Could not write the config file", "Could not write the Updater config file inside of the game folder. Your updater preferences won't be saved.");
delete f;
return;
}
xml->setDevice(f);
xml->writeStartDocument();
xml->writeStartElement("UpdaterConfig");
xml->writeStartElement("DownloadServer");
xml->writeCharacters(QString::number(downloadServer));
xml->writeEndElement();
xml->writeStartElement("GameEngine");
xml->writeCharacters(QString::number(gameEngine));
xml->writeEndElement();
xml->writeEndElement();
xml->writeEndDocument();
f->close();
qDebug() << "Local config saved." << endl;
delete f;
delete xml;
}
void UrTUpdater::getManifest(QString query){
QUrl APIUrl(URT_API_LINK);
QUrlQuery url;
QNetworkRequest apiRequest(APIUrl);
QNetworkAccessManager *apiManager = new QNetworkAccessManager(this);
qDebug() << "query: " << query << endl;
apiRequest.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded;charset=utf-8");
url.addQueryItem("platform", getPlatform());
url.addQueryItem("query", query);
apiAnswer = apiManager->post(apiRequest, url.query(QUrl::FullyEncoded).toUtf8());
connect(apiAnswer, SIGNAL(finished()), this, SLOT(parseAPIAnswer()));
connect(apiAnswer, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkError(QNetworkReply::NetworkError)));
}
void UrTUpdater::parseAPIAnswer(){
QByteArray apiByteAnswer = apiAnswer->readAll();
QString apiData = QString(apiByteAnswer);
qDebug() << "apiData: " << apiData << endl;
parseManifest(apiData);
}
void UrTUpdater::parseManifest(QString data){
QDomDocument* dom = new QDomDocument();
dom->setContent(data);
QDomNode node = dom->firstChild();
while(!node.isNull()){
if(node.toElement().nodeName() == "Updater"){
QDomNode updater = node.firstChild();
while(!updater.isNull()){
if(updater.toElement().nodeName() == "VersionInfo"){
QDomNode versionInfo = updater.firstChild();
while(!versionInfo.isNull()){
if(versionInfo.nodeName() == "VersionNumber"){
versionNumber = versionInfo.toElement().text();
}
if(versionInfo.nodeName() == "ReleaseDate"){
releaseDate = versionInfo.toElement().text();
}
versionInfo = versionInfo.nextSibling();
}
}
else if(updater.toElement().nodeName() == "ServerList"){
QDomNode serverListNode = updater.firstChild();
while(!serverListNode.isNull()){
if(serverListNode.nodeName() == "Server"){
QDomNode serverNode = serverListNode.firstChild();
int serverId;
QString serverURL;
QString serverName;
QString serverLocation;
serverInfo_s si;
while(!serverNode.isNull()){
if(serverNode.nodeName() == "ServerName"){
serverName = serverNode.toElement().text();
}
if(serverNode.nodeName() == "ServerURL"){
serverURL = serverNode.toElement().text();
}
if(serverNode.nodeName() == "ServerLocation"){
serverLocation = serverNode.toElement().text();
}
if(serverNode.nodeName() == "ServerId"){
serverId = serverNode.toElement().text().toInt();
}
serverNode = serverNode.nextSibling();
}
si.serverId = serverId;
si.serverName = serverName;
si.serverURL = serverURL;
si.serverLocation = serverLocation;
downloadServers.append(si);
}
serverListNode = serverListNode.nextSibling();
}
}
else if(updater.toElement().nodeName() == "EngineList"){
QDomNode engineListNode = updater.firstChild();
while(!engineListNode.isNull()){
if(engineListNode.nodeName() == "Engine"){
QDomNode engineNode = engineListNode.firstChild();
int engineId;
QString engineDir;
QString engineName;
engineInfo_s ei;
while(!engineNode.isNull()){
if(engineNode.nodeName() == "EngineName"){
engineName = engineNode.toElement().text();
}
if(engineNode.nodeName() == "EngineDir"){
engineDir = engineNode.toElement().text();
}
if(engineNode.nodeName() == "EngineId"){
engineId = engineNode.toElement().text().toInt();
}
engineNode = engineNode.nextSibling();
}
ei.engineId = engineId;
ei.engineName = engineName;
ei.engineDir = engineDir;
enginesList.append(ei);
}
engineListNode = engineListNode.nextSibling();
}
}
else if(updater.toElement().nodeName() == "Files"){
QDomNode files = updater.firstChild();
while(!files.isNull()){
if(files.nodeName() == "File"){
QDomNode fileInfo = files.firstChild();
QString fileDir;
QString fileName;
QString fileMd5;
QString fileSize;
bool mustDownload = false;
while(!fileInfo.isNull()){
if(fileInfo.nodeName() == "FileDir"){
fileDir = fileInfo.toElement().text();
}
if(fileInfo.nodeName() == "FileName"){
fileName = fileInfo.toElement().text();
}
if(fileInfo.nodeName() == "FileMD5"){
fileMd5 = fileInfo.toElement().text();
}
if(fileInfo.nodeName() == "FileSize"){
fileSize = fileInfo.toElement().text();
}
fileInfo = fileInfo.nextSibling();
}
QString filePath(updaterPath + fileDir + fileName);
QFile* f = new QFile(filePath);
// If the file does not exist, it must be downloaded.
if(!f->exists()){
mustDownload = true;
}
// If the md5 string is empty, it means that the API wants
// us to delete this file if needed
else if(!fileName.isEmpty() && fileMd5.isEmpty()){
QFile::remove(filePath);
}
// Check the file's md5sum to see if it needs to be updated.
else if(!fileName.isEmpty() && !fileMd5.isEmpty()){
if(getMd5Sum(f) != fileMd5){
mustDownload = true;
qDebug() << "md5 file: " << getMd5Sum(f) << ", " << fileMd5 << endl;
}
}
qDebug() << "fileDir:" << fileDir << endl;
qDebug() << "fileName: " << fileName << endl;
qDebug() << "fileMd5: " << fileMd5 << endl;
if(mustDownload){
fileInfo_s fi;
fi.fileName = fileName;
fi.filePath = fileDir;
fi.fileMd5 = fileMd5;
fi.fileSize = fileSize;
filesToDownload.append(fi);
}
delete f;
}
files = files.nextSibling();
}
}
updater = updater.nextSibling();
}
}
node = node.nextSibling();
}
checkDownloadServer();
checkGameEngine();
delete dom;
}
void UrTUpdater::checkDownloadServer(){
QList<serverInfo_s>::iterator li;
bool found = false;
// Check if the download server that is stored in the config file still exists
for(li = downloadServers.begin(); li != downloadServers.end(); ++li){
if(li->serverId == downloadServer){
found = true;
}
}
// If the engine isn't available anymore, pick the first one in the list
if(!found){
downloadServer = downloadServers.at(0).serverId;
}
}
void UrTUpdater::checkGameEngine(){
QList<engineInfo_s>::iterator li;
bool found = false;
// Check if the engine that is stored in the config file still exists
for(li = enginesList.begin(); li != enginesList.end(); ++li){
if(li->engineId == gameEngine){
found = true;
}
}
// If the server isn't a mirror anymore, pick the first one in the list
if(!found){
gameEngine = enginesList.at(0).engineId;
}
}
QString UrTUpdater::getMd5Sum(QFile* file)
{
if (file->exists() && file->open(QIODevice::ReadOnly))
{
QByteArray content = file->readAll();
QByteArray hashed = QCryptographicHash::hash(content, QCryptographicHash::Md5);
file->close();
return hashed.toHex().data();
}
return "";
}
void UrTUpdater::networkError(QNetworkReply::NetworkError code){
QString error = "";
bool critical = false;
switch(code){
case QNetworkReply::ConnectionRefusedError:
error = "Error: the remote server refused the connection. Please try again later.";
critical = true;
break;
case QNetworkReply::RemoteHostClosedError:
error = "Error: the remote server closed the connection prematurely. Please try again later.";
break;
case QNetworkReply::HostNotFoundError:
error = "Error: the remote server could not be found. Please check your internet connection!";
critical = true;
break;
case QNetworkReply::TimeoutError:
error = "Error: the connection to the remote server timed out. Please try again.";
break;
case QNetworkReply::TemporaryNetworkFailureError:
error = "Error: the connection to the remote server was broken due to disconnection from the network. Please try again.";
break;
case QNetworkReply::ContentNotFoundError:
error = "Error: the remote content could not be found. Please report this issue on our website: http://www.urbanterror.info";
break;
case QNetworkReply::UnknownNetworkError:
error = "Error: an unknown network-related error was encountered. Please try again";
break;
case QNetworkReply::UnknownContentError:
error = "Error: an unknown content-related error was encountered. Please try again";
break;
default:
case QNetworkReply::NoError:
break;
}
if(!error.isEmpty()){
if(critical == true){
QMessageBox::critical(0, "Download error", error);
quit();
}
else {
QMessageBox::information(0, "Download error", error);
}
}
}
void UrTUpdater::serverSelection(){
ServerSelection *serverSel = new ServerSelection(this);
connect(serverSel, SIGNAL(serverSelected(int)), this, SLOT(setDownloadServer(int)));
serverSel->currentServer = downloadServer;
serverSel->downloadServers = downloadServers;
serverSel->init();
serverSel->exec();
}
void UrTUpdater::engineSelection(){
EngineSelection* engineSel = new EngineSelection(this);
connect(engineSel, SIGNAL(engineSelected(int)), this, SLOT(setEngine(int)));
engineSel->currentEngine = gameEngine;
engineSel->enginesList = enginesList;
engineSel->init();
engineSel->exec();
}
void UrTUpdater::setDownloadServer(int server){
downloadServer = server;
saveLocalConfig();
}
void UrTUpdater::setEngine(int engine){
gameEngine = engine;
saveLocalConfig();
}
void UrTUpdater::quit(){
saveLocalConfig();
exit(0);
}
<|endoftext|> |
<commit_before><commit_msg>silence hlt message when event is finished<commit_after><|endoftext|> |
<commit_before>#include "VideodrommLiveCodingApp.h"
void VideodrommLiveCodingApp::prepare(Settings *settings)
{
settings->setWindowSize(1280, 720);
//settings->setBorderless();
settings->setWindowPos(0, 0);
#ifdef _DEBUG
settings->setConsoleWindowEnabled();
#else
#endif // _DEBUG
}
VideodrommLiveCodingApp::VideodrommLiveCodingApp()
: mSpoutOut("VDLiveCoding", app::getWindowSize())
{
// Settings
mVDSettings = VDSettings::create();
// Session
mVDSession = VDSession::create(mVDSettings);
mVDSession->getWindowsResolution();
// TODO render window size must be < main window size or else it overlaps
setWindowSize(mVDSettings->mMainWindowWidth - 300, mVDSettings->mMainWindowHeight - 100);
// UI
mVDUI = VDUI::create(mVDSettings, mVDSession);
mouseGlobal = false;
mFadeInDelay = true;
// mouse cursor and UI
setUIVisibility(mVDSettings->mCursorVisible);
// windows
mIsShutDown = false;
isWindowReady = false;
mMainWindow = getWindow();
mMainWindow->getSignalDraw().connect(std::bind(&VideodrommLiveCodingApp::drawMain, this));
mMainWindow->getSignalResize().connect(std::bind(&VideodrommLiveCodingApp::resizeWindow, this));
if (mVDSettings->mStandalone) {
createRenderWindow();
setWindowSize(mVDSettings->mRenderWidth, mVDSettings->mRenderHeight);
}
else {
}
setFrameRate(mVDSession->getTargetFps());
//CI_LOG_V("setup");
}
void VideodrommLiveCodingApp::createRenderWindow()
{
isWindowReady = false;
mVDUI->resize();
deleteRenderWindows();
mVDSession->getWindowsResolution();
//CI_LOG_V("createRenderWindow, resolution:" + toString(mVDSettings->mRenderWidth) + "x" + toString(mVDSettings->mRenderHeight));
string windowName = "render";
mRenderWindow = createWindow(Window::Format().size(mVDSettings->mRenderWidth, mVDSettings->mRenderHeight));
// create instance of the window and store in vector
allRenderWindows.push_back(mRenderWindow);
mRenderWindow->setBorderless();
mRenderWindow->getSignalDraw().connect(std::bind(&VideodrommLiveCodingApp::drawRender, this));
mVDSettings->mRenderPosXY = ivec2(mVDSettings->mRenderX, mVDSettings->mRenderY);
mRenderWindow->setPos(50, 50);
mRenderWindowTimer = 0.0f;
timeline().apply(&mRenderWindowTimer, 1.0f, 2.0f).finishFn([&] { positionRenderWindow(); });
}
void VideodrommLiveCodingApp::positionRenderWindow()
{
mRenderWindow->setPos(mVDSettings->mRenderX, mVDSettings->mRenderY);
isWindowReady = true;
}
void VideodrommLiveCodingApp::deleteRenderWindows()
{
#if defined( CINDER_MSW )
for (auto wRef : allRenderWindows) DestroyWindow((HWND)mRenderWindow->getNative());
#endif
allRenderWindows.clear();
}
void VideodrommLiveCodingApp::setUIVisibility(bool visible)
{
if (visible)
{
showCursor();
}
else
{
hideCursor();
}
}
void VideodrommLiveCodingApp::update()
{
switch (mVDSession->getCmd()) {
case 0:
createRenderWindow();
break;
case 1:
deleteRenderWindows();
break;
}
mVDSession->setFloatUniformValueByIndex(mVDSettings->IFPS, getAverageFps());
mVDSession->update();
}
void VideodrommLiveCodingApp::cleanup()
{
if (!mIsShutDown)
{
mIsShutDown = true;
//CI_LOG_V("shutdown");
ui::disconnectWindow(getWindow());
ui::Shutdown();
// save settings
mVDSettings->save();
mVDSession->save();
deleteRenderWindows();
quit();
}
}
void VideodrommLiveCodingApp::mouseMove(MouseEvent event)
{
if (!mVDSession->handleMouseMove(event)) {
// let your application perform its mouseMove handling here
}
}
void VideodrommLiveCodingApp::mouseDown(MouseEvent event)
{
if (!mVDSession->handleMouseDown(event)) {
// let your application perform its mouseDown handling here
}
}
void VideodrommLiveCodingApp::mouseDrag(MouseEvent event)
{
if (!mVDSession->handleMouseDrag(event)) {
// let your application perform its mouseDrag handling here
}
}
void VideodrommLiveCodingApp::mouseUp(MouseEvent event)
{
if (!mVDSession->handleMouseUp(event)) {
// let your application perform its mouseUp handling here
}
}
void VideodrommLiveCodingApp::keyDown(KeyEvent event)
{
if (!mVDSession->handleKeyDown(event)) {
switch (event.getCode()) {
case KeyEvent::KEY_KP_PLUS:
createRenderWindow();
break;
case KeyEvent::KEY_KP_MINUS:
deleteRenderWindows();
break;
case KeyEvent::KEY_ESCAPE:
// quit the application
quit();
break;
case KeyEvent::KEY_h:
// mouse cursor and ui visibility
mVDSettings->mCursorVisible = !mVDSettings->mCursorVisible;
setUIVisibility(mVDSettings->mCursorVisible);
break;
}
}
}
void VideodrommLiveCodingApp::keyUp(KeyEvent event)
{
if (!mVDSession->handleKeyUp(event)) {
}
}
void VideodrommLiveCodingApp::resizeWindow()
{
mVDUI->resize();
//mVDSession->resize();
}
void VideodrommLiveCodingApp::fileDrop(FileDropEvent event)
{
mVDSession->fileDrop(event);
}
void VideodrommLiveCodingApp::drawRender()
{
gl::clear(Color::black());
//gl::setMatricesWindow(toPixels(getWindowSize()));
if (mFadeInDelay) {
mVDSettings->iAlpha = 0.0f;
if (getElapsedFrames() > mVDSession->getFadeInDelay()) {
mFadeInDelay = false;
// warps resize at the end
mVDSession->resize();
timeline().apply(&mVDSettings->iAlpha, 0.0f, 1.0f, 1.5f, EaseInCubic());
}
}
gl::setMatricesWindow(mVDSettings->mRenderWidth, mVDSettings->mRenderHeight);// , false);
if (isWindowReady) {
gl::draw(mVDSession->getRenderTexture(), Area(0, 0, mVDSettings->mRenderWidth, mVDSettings->mRenderHeight));//getWindowBounds()
}
}
void VideodrommLiveCodingApp::drawMain()
{
mMainWindow->setTitle(mVDSettings->sFps + " fps videodromm");
gl::clear(Color::black());
//gl::setMatricesWindow(toPixels(getWindowSize()));
gl::enableAlphaBlending(mVDSession->isEnabledAlphaBlending());
gl::setMatricesWindow(mVDSettings->mRenderWidth, mVDSettings->mRenderHeight, false);
gl::draw(mVDSession->getMixTexture(mVDSession->getCurrentEditIndex()), Area(0, 0, mVDSettings->mRenderWidth, mVDSettings->mRenderHeight));//getWindowBounds()
// spout sender
if (mVDSettings->mSpoutSender) mSpoutOut.sendViewport();
// imgui
if (!mVDSettings->mCursorVisible) return;
mVDUI->Run("UI", (int)getAverageFps());
if (mVDUI->isReady()) {
}
}
CINDER_APP(VideodrommLiveCodingApp, RendererGl, &VideodrommLiveCodingApp::prepare)
<commit_msg>no console<commit_after>#include "VideodrommLiveCodingApp.h"
void VideodrommLiveCodingApp::prepare(Settings *settings)
{
settings->setWindowSize(1280, 720);
//settings->setBorderless();
settings->setWindowPos(0, 0);
#ifdef _DEBUG
//settings->setConsoleWindowEnabled();
#else
#endif // _DEBUG
}
VideodrommLiveCodingApp::VideodrommLiveCodingApp()
: mSpoutOut("VDLiveCoding", app::getWindowSize())
{
// Settings
mVDSettings = VDSettings::create();
// Session
mVDSession = VDSession::create(mVDSettings);
mVDSession->getWindowsResolution();
// TODO render window size must be < main window size or else it overlaps
setWindowSize(mVDSettings->mMainWindowWidth - 300, mVDSettings->mMainWindowHeight - 100);
// UI
mVDUI = VDUI::create(mVDSettings, mVDSession);
mouseGlobal = false;
mFadeInDelay = true;
// mouse cursor and UI
setUIVisibility(mVDSettings->mCursorVisible);
// windows
mIsShutDown = false;
isWindowReady = false;
mMainWindow = getWindow();
mMainWindow->getSignalDraw().connect(std::bind(&VideodrommLiveCodingApp::drawMain, this));
mMainWindow->getSignalResize().connect(std::bind(&VideodrommLiveCodingApp::resizeWindow, this));
if (mVDSettings->mStandalone) {
createRenderWindow();
setWindowSize(mVDSettings->mRenderWidth, mVDSettings->mRenderHeight);
}
else {
}
setFrameRate(mVDSession->getTargetFps());
//CI_LOG_V("setup");
}
void VideodrommLiveCodingApp::createRenderWindow()
{
isWindowReady = false;
mVDUI->resize();
deleteRenderWindows();
mVDSession->getWindowsResolution();
//CI_LOG_V("createRenderWindow, resolution:" + toString(mVDSettings->mRenderWidth) + "x" + toString(mVDSettings->mRenderHeight));
string windowName = "render";
mRenderWindow = createWindow(Window::Format().size(mVDSettings->mRenderWidth, mVDSettings->mRenderHeight));
// create instance of the window and store in vector
allRenderWindows.push_back(mRenderWindow);
mRenderWindow->setBorderless();
mRenderWindow->getSignalDraw().connect(std::bind(&VideodrommLiveCodingApp::drawRender, this));
mVDSettings->mRenderPosXY = ivec2(mVDSettings->mRenderX, mVDSettings->mRenderY);
mRenderWindow->setPos(50, 50);
mRenderWindowTimer = 0.0f;
timeline().apply(&mRenderWindowTimer, 1.0f, 2.0f).finishFn([&] { positionRenderWindow(); });
}
void VideodrommLiveCodingApp::positionRenderWindow()
{
mRenderWindow->setPos(mVDSettings->mRenderX, mVDSettings->mRenderY);
isWindowReady = true;
}
void VideodrommLiveCodingApp::deleteRenderWindows()
{
#if defined( CINDER_MSW )
for (auto wRef : allRenderWindows) DestroyWindow((HWND)mRenderWindow->getNative());
#endif
allRenderWindows.clear();
}
void VideodrommLiveCodingApp::setUIVisibility(bool visible)
{
if (visible)
{
showCursor();
}
else
{
hideCursor();
}
}
void VideodrommLiveCodingApp::update()
{
switch (mVDSession->getCmd()) {
case 0:
createRenderWindow();
break;
case 1:
deleteRenderWindows();
break;
}
mVDSession->setFloatUniformValueByIndex(mVDSettings->IFPS, getAverageFps());
mVDSession->update();
}
void VideodrommLiveCodingApp::cleanup()
{
if (!mIsShutDown)
{
mIsShutDown = true;
//CI_LOG_V("shutdown");
ui::disconnectWindow(getWindow());
ui::Shutdown();
// save settings
mVDSettings->save();
mVDSession->save();
deleteRenderWindows();
quit();
}
}
void VideodrommLiveCodingApp::mouseMove(MouseEvent event)
{
if (!mVDSession->handleMouseMove(event)) {
// let your application perform its mouseMove handling here
}
}
void VideodrommLiveCodingApp::mouseDown(MouseEvent event)
{
if (!mVDSession->handleMouseDown(event)) {
// let your application perform its mouseDown handling here
}
}
void VideodrommLiveCodingApp::mouseDrag(MouseEvent event)
{
if (!mVDSession->handleMouseDrag(event)) {
// let your application perform its mouseDrag handling here
}
}
void VideodrommLiveCodingApp::mouseUp(MouseEvent event)
{
if (!mVDSession->handleMouseUp(event)) {
// let your application perform its mouseUp handling here
}
}
void VideodrommLiveCodingApp::keyDown(KeyEvent event)
{
if (!mVDSession->handleKeyDown(event)) {
switch (event.getCode()) {
case KeyEvent::KEY_KP_PLUS:
createRenderWindow();
break;
case KeyEvent::KEY_KP_MINUS:
deleteRenderWindows();
break;
case KeyEvent::KEY_ESCAPE:
// quit the application
quit();
break;
case KeyEvent::KEY_h:
// mouse cursor and ui visibility
mVDSettings->mCursorVisible = !mVDSettings->mCursorVisible;
setUIVisibility(mVDSettings->mCursorVisible);
break;
}
}
}
void VideodrommLiveCodingApp::keyUp(KeyEvent event)
{
if (!mVDSession->handleKeyUp(event)) {
}
}
void VideodrommLiveCodingApp::resizeWindow()
{
mVDUI->resize();
//mVDSession->resize();
}
void VideodrommLiveCodingApp::fileDrop(FileDropEvent event)
{
mVDSession->fileDrop(event);
}
void VideodrommLiveCodingApp::drawRender()
{
gl::clear(Color::black());
if (mFadeInDelay) {
mVDSettings->iAlpha = 0.0f;
if (getElapsedFrames() > mVDSession->getFadeInDelay()) {
mFadeInDelay = false;
// warps resize at the end
mVDSession->resize();
timeline().apply(&mVDSettings->iAlpha, 0.0f, 1.0f, 1.5f, EaseInCubic());
}
}
gl::setMatricesWindow(mVDSettings->mRenderWidth, mVDSettings->mRenderHeight);// , false);
if (isWindowReady) {
//gl::draw(mVDSession->getRenderTexture(), getWindowBounds());
gl::draw(mVDSession->getRenderTexture(), Area(0, 0, mVDSettings->mRenderWidth, mVDSettings->mRenderHeight));//getWindowBounds()
}
}
void VideodrommLiveCodingApp::drawMain()
{
mMainWindow->setTitle(mVDSettings->sFps + " fps videodromm");
gl::clear(Color::black());
gl::enableAlphaBlending(mVDSession->isEnabledAlphaBlending());
gl::setMatricesWindow(mVDSettings->mRenderWidth, mVDSettings->mRenderHeight, false);
gl::draw(mVDSession->getMixTexture(mVDSession->getCurrentEditIndex()), Area(0, 0, mVDSettings->mRenderWidth, mVDSettings->mRenderHeight));//getWindowBounds()
// spout sender
if (mVDSettings->mSpoutSender) mSpoutOut.sendViewport();
// imgui
if (!mVDSettings->mCursorVisible) return;
mVDUI->Run("UI", (int)getAverageFps());
if (mVDUI->isReady()) {
}
}
CINDER_APP(VideodrommLiveCodingApp, RendererGl, &VideodrommLiveCodingApp::prepare)
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPCAAnalysisFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkPCAAnalysisFilter.h"
#include "vtkObjectFactory.h"
#include "vtkTransformPolyDataFilter.h"
#include "vtkPolyData.h"
#include "vtkMath.h"
#include "vtkFloatArray.h"
vtkCxxRevisionMacro(vtkPCAAnalysisFilter, "1.1");
vtkStandardNewMacro(vtkPCAAnalysisFilter);
//------------------------------------------------------------------------
// Matrix ops. Some taken from vtkThinPlateSplineTransform.cxx
static inline double** NewMatrix(int rows, int cols)
{
double *matrix = new double[rows*cols];
double **m = new double *[rows];
for(int i = 0; i < rows; i++) {
m[i] = &matrix[i*cols];
}
return m;
}
//------------------------------------------------------------------------
static inline void DeleteMatrix(double **m)
{
delete [] *m;
delete [] m;
}
//------------------------------------------------------------------------
static inline void MatrixMultiply(double **a, double **b, double **c,
int arows, int acols,
int brows, int bcols)
{
if(acols != brows) {
return; // acols must equal br otherwise we can't proceed
}
// c must have size arows*bcols (we assume this)
for(int i = 0; i < arows; i++) {
for(int j = 0; j < bcols; j++) {
c[i][j] = 0.0;
for(int k = 0; k < acols; k++) {
c[i][j] += a[i][k]*b[k][j];
}
}
}
}
//------------------------------------------------------------------------
// Subtracting the mean column from the observation matrix is equal
// to subtracting the mean shape from all shapes.
// The mean column is equal to the Procrustes mean (it is also returned)
static inline void SubtractMeanColumn(double **m, double *mean, int rows, int cols)
{
for (int r = 0; r < rows; r++) {
double csum = 0.0F;
for (int c = 0; c < cols; c++) {
csum += m[r][c];
}
// calculate average value of row
csum /= cols;
// Mean shape vector is updated
mean[r] = csum;
// average value is subtracted from all elements in the row
for (c = 0; c < cols; c++) {
m[r][c] -= csum;
}
}
}
//------------------------------------------------------------------------
// Normalise all columns to have length 1
// meaning that all eigenvectors are normalised
static inline void NormaliseColumns(double **m, int rows, int cols)
{
for (int c = 0; c < cols; c++) {
double cl = 0;
for (int r = 0; r < rows; r++) {
cl += m[r][c] * m[r][c];
}
cl = sqrt(cl);
// If cl == 0 something is rotten, dont do anything now
if (cl != 0) {
for (int r = 0; r < rows; r++) {
m[r][c] /= cl;
}
}
}
}
//------------------------------------------------------------------------
// Here it is assumed that a rows >> a cols
// Output matrix is [a cols X a cols]
static inline void SmallCovarianceMatrix(double **a, double **c,
int arows, int acols)
{
const int s = acols;
// c must have size acols*acols (we assume this)
for(int i = 0; i < acols; i++) {
for(int j = 0; j < acols; j++) {
// Use symmetry
if (i <= j) {
c[i][j] = 0.0;
for(int k = 0; k < arows; k++) {
c[i][j] += a[k][i]*a[k][j];
}
c[i][j] /= (s-1);
c[j][i] = c[i][j];
}
}
}
}
//------------------------------------------------------------------------
static inline void MatrixTranspose(double **a, double **b, int rows, int cols)
{
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
double tmp = a[i][j];
b[i][j] = a[j][i];
b[j][i] = tmp;
}
}
}
//------------------------------------------------------------------------
static inline double* NewVector(int length)
{
double *vec = new double[length];
return vec;
}
//------------------------------------------------------------------------
static inline void DeleteVector(double *v)
{
delete [] v;
}
//----------------------------------------------------------------------------
// protected
vtkPCAAnalysisFilter::vtkPCAAnalysisFilter()
{
this->Evals = vtkFloatArray::New();
this->evecMat2 = NULL;
this->meanshape = NULL;
}
//----------------------------------------------------------------------------
// protected
vtkPCAAnalysisFilter::~vtkPCAAnalysisFilter()
{
if (this->Evals) {
this->Evals->Delete();
}
if (this->evecMat2) {
DeleteMatrix(this->evecMat2);
this->evecMat2 = NULL;
}
if (this->meanshape) {
DeleteVector(this->meanshape);
this->meanshape = NULL;
}
}
//----------------------------------------------------------------------------
// protected
void vtkPCAAnalysisFilter::Execute()
{
vtkDebugMacro(<<"Execute()");
if(!this->vtkProcessObject::Inputs) {
vtkErrorMacro(<<"No input!");
return;
}
int i;
// Clean up from previous computation
if (this->evecMat2) {
DeleteMatrix(this->evecMat2);
this->evecMat2 = NULL;
}
if (this->meanshape) {
DeleteVector(this->meanshape);
this->meanshape = NULL;
}
const int N_SETS = this->vtkProcessObject::GetNumberOfInputs();
// copy the inputs across
for(i=0;i<N_SETS;i++) {
this->GetOutput(i)->DeepCopy(this->GetInput(i));
}
// the number of points is determined by the first input (they must all be the same)
const int N_POINTS = this->GetInput(0)->GetNumberOfPoints();
vtkDebugMacro(<<"N_POINTS is " <<N_POINTS);
if(N_POINTS == 0) {
vtkErrorMacro(<<"No points!");
return;
}
// all the inputs must have the same number of points to consider executing
for(i=1;i<N_SETS;i++) {
if(this->GetInput(i)->GetNumberOfPoints() != N_POINTS) {
vtkErrorMacro(<<"The inputs have different numbers of points!");
return;
}
}
// Number of shapes
const int s = N_SETS;
// Number of points in a shape
const int n = N_POINTS;
// Observation Matrix [number of points * 3 X number of shapes]
double **D = NewMatrix(3*n, s);
for (i = 0; i < n; i++) {
for (int j = 0; j < s; j++) {
float *p = this->GetInput(j)->GetPoint(i);
D[i*3 ][j] = p[0];
D[i*3+1][j] = p[1];
D[i*3+2][j] = p[2];
}
}
// The mean shape is also calculated
meanshape = NewVector(3*n);
SubtractMeanColumn(D, meanshape, 3*n, s);
// Covariance matrix of dim [s x s]
double **T = NewMatrix(s, s);
SmallCovarianceMatrix(D, T, 3*n, s);
double *ev = NewVector(s);
double **evecMat = NewMatrix(s, s);
vtkMath::JacobiN(T, s, ev, evecMat);
// Compute eigenvecs of DD' instead of T which is D'D
// evecMat2 of dim [3*n x s]
evecMat2 = NewMatrix(3*n, s);
MatrixMultiply(D, evecMat, evecMat2, 3*n, s, s, s);
// Normalise eigenvectors
NormaliseColumns(evecMat2, 3*n, s);
this->Evals->SetNumberOfValues(s);
// Copy data to output structures
for (int j = 0; j < s; j++) {
this->Evals->SetValue(j, ev[j]);
for (int i = 0; i < n; i++) {
double x = evecMat2[i*3 ][j];
double y = evecMat2[i*3+1][j];
double z = evecMat2[i*3+2][j];
this->GetOutput(j)->GetPoints()->SetPoint(i, x, y, z);
}
}
DeleteMatrix(evecMat);
DeleteVector(ev);
DeleteMatrix(T);
DeleteMatrix(D);
}
//----------------------------------------------------------------------------
// public
void vtkPCAAnalysisFilter::GetParameterisedShape(vtkFloatArray *b, vtkPointSet* shape)
{
const int bsize = b->GetNumberOfTuples();
const int n = this->GetOutput(0)->GetNumberOfPoints();
if(shape->GetNumberOfPoints() != n) {
vtkErrorMacro(<<"Input shape does not have the correct number of points");
return;
}
double *shapevec = NewVector(n*3);
int i,j;
// b is weighted by the eigenvals
// make weigth vector for speed reasons
double *w = NewVector(bsize);
for (i = 0; i < bsize; i++) {
w[i] =sqrt(this->Evals->GetValue(i)) * b->GetValue(i);
}
for (j = 0; j < n*3; j++) {
shapevec[j] = meanshape[j];
for (i = 0; i < bsize; i++) {
shapevec[j] += w[i] * evecMat2[j][i];
}
}
// Copy shape
for (i = 0; i < n; i++) {
shape->GetPoints()->SetPoint(i,shapevec[i*3 ], shapevec[i*3+1], shapevec[i*3+2]);
}
DeleteVector(w);
}
//----------------------------------------------------------------------------
// public
void vtkPCAAnalysisFilter::GetShapeParameters(vtkPointSet *shape, vtkFloatArray *b, int bsize)
{
// Local variant of b for fast access.
double *bloc = NewVector(bsize);
const int n = this->GetOutput(0)->GetNumberOfPoints();
if(shape->GetNumberOfPoints() != n) {
vtkErrorMacro(<<"Input shape does not have the correct number of points");
return;
}
double *shapevec = NewVector(n*3);
// Copy shape and subtract mean shape
for (int i = 0; i < n; i++) {
float *p = shape->GetPoint(i);
shapevec[i*3 ] = p[0] - meanshape[i*3];
shapevec[i*3+1] = p[1] - meanshape[i*3+1];
shapevec[i*3+2] = p[2] - meanshape[i*3+2];
}
for (i = 0; i < bsize; i++) {
bloc[i] = 0;
// Project the shape onto eigenvector i
for (int j = 0; j < n*3; j++) {
bloc[i] += shapevec[j] * evecMat2[j][i];
}
}
// Return b in number of standard deviations
b->SetNumberOfValues(bsize);
for (i = 0; i < bsize; i++) {
if (this->Evals->GetValue(i))
b->SetValue(i, bloc[i]/sqrt(this->Evals->GetValue(i)));
else
b->SetValue(i, 0);
}
DeleteVector(shapevec);
DeleteVector(bloc);
}
//----------------------------------------------------------------------------
// public
void vtkPCAAnalysisFilter::SetNumberOfInputs(int n)
{
this->vtkProcessObject::SetNumberOfInputs(n);
this->vtkSource::SetNumberOfOutputs(n);
// initialise the outputs
for(int i=0;i<n;i++) {
vtkPoints *points = vtkPoints::New();
vtkPolyData *ps = vtkPolyData::New();
ps->SetPoints(points);
points->Delete();
this->vtkSource::SetNthOutput(i,ps);
ps->Delete();
}
// is this the right thing to be doing here? if we don't initialise the outputs here
// then the filter crashes but vtkPolyData may not be the type of the inputs
}
//----------------------------------------------------------------------------
// public
void vtkPCAAnalysisFilter::SetInput(int idx,vtkPointSet* p)
{
if(idx<0 || idx>=this->vtkProcessObject::GetNumberOfInputs()) {
vtkErrorMacro(<<"Index out of bounds in SetInput!");
return;
}
this->vtkProcessObject::SetNthInput(idx,p);
}
//----------------------------------------------------------------------------
// protected
vtkPointSet* vtkPCAAnalysisFilter::GetInput(int idx)
{
if(idx<0 || idx>=this->vtkProcessObject::GetNumberOfInputs()) {
vtkErrorMacro(<<"Index out of bounds in GetInput!");
return NULL;
}
return static_cast<vtkPointSet*>(this->vtkProcessObject::Inputs[idx]);
}
//----------------------------------------------------------------------------
// public
vtkPointSet* vtkPCAAnalysisFilter::GetOutput(int idx)
{
if(idx<0 || idx>=this->vtkSource::GetNumberOfOutputs()) {
vtkErrorMacro(<<"Index out of bounds in GetOutput!");
return NULL;
}
return static_cast<vtkPointSet*>(this->vtkSource::GetOutput(idx));
}
//----------------------------------------------------------------------------
// public
void vtkPCAAnalysisFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
this->Evals->PrintSelf(os,indent);
}
<commit_msg>ERR: moved variable declarations for i,j out of for loops (gave errors on some compilers)<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPCAAnalysisFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkPCAAnalysisFilter.h"
#include "vtkObjectFactory.h"
#include "vtkTransformPolyDataFilter.h"
#include "vtkPolyData.h"
#include "vtkMath.h"
#include "vtkFloatArray.h"
vtkCxxRevisionMacro(vtkPCAAnalysisFilter, "1.2");
vtkStandardNewMacro(vtkPCAAnalysisFilter);
//------------------------------------------------------------------------
// Matrix ops. Some taken from vtkThinPlateSplineTransform.cxx
static inline double** NewMatrix(int rows, int cols)
{
double *matrix = new double[rows*cols];
double **m = new double *[rows];
for(int i = 0; i < rows; i++) {
m[i] = &matrix[i*cols];
}
return m;
}
//------------------------------------------------------------------------
static inline void DeleteMatrix(double **m)
{
delete [] *m;
delete [] m;
}
//------------------------------------------------------------------------
static inline void MatrixMultiply(double **a, double **b, double **c,
int arows, int acols,
int brows, int bcols)
{
if(acols != brows) {
return; // acols must equal br otherwise we can't proceed
}
// c must have size arows*bcols (we assume this)
for(int i = 0; i < arows; i++) {
for(int j = 0; j < bcols; j++) {
c[i][j] = 0.0;
for(int k = 0; k < acols; k++) {
c[i][j] += a[i][k]*b[k][j];
}
}
}
}
//------------------------------------------------------------------------
// Subtracting the mean column from the observation matrix is equal
// to subtracting the mean shape from all shapes.
// The mean column is equal to the Procrustes mean (it is also returned)
static inline void SubtractMeanColumn(double **m, double *mean, int rows, int cols)
{
int r,c;
double csum;
for (r = 0; r < rows; r++) {
csum = 0.0F;
for (c = 0; c < cols; c++) {
csum += m[r][c];
}
// calculate average value of row
csum /= cols;
// Mean shape vector is updated
mean[r] = csum;
// average value is subtracted from all elements in the row
for (c = 0; c < cols; c++) {
m[r][c] -= csum;
}
}
}
//------------------------------------------------------------------------
// Normalise all columns to have length 1
// meaning that all eigenvectors are normalised
static inline void NormaliseColumns(double **m, int rows, int cols)
{
for (int c = 0; c < cols; c++) {
double cl = 0;
for (int r = 0; r < rows; r++) {
cl += m[r][c] * m[r][c];
}
cl = sqrt(cl);
// If cl == 0 something is rotten, dont do anything now
if (cl != 0) {
for (int r = 0; r < rows; r++) {
m[r][c] /= cl;
}
}
}
}
//------------------------------------------------------------------------
// Here it is assumed that a rows >> a cols
// Output matrix is [a cols X a cols]
static inline void SmallCovarianceMatrix(double **a, double **c,
int arows, int acols)
{
const int s = acols;
// c must have size acols*acols (we assume this)
for(int i = 0; i < acols; i++) {
for(int j = 0; j < acols; j++) {
// Use symmetry
if (i <= j) {
c[i][j] = 0.0;
for(int k = 0; k < arows; k++) {
c[i][j] += a[k][i]*a[k][j];
}
c[i][j] /= (s-1);
c[j][i] = c[i][j];
}
}
}
}
//------------------------------------------------------------------------
static inline void MatrixTranspose(double **a, double **b, int rows, int cols)
{
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
double tmp = a[i][j];
b[i][j] = a[j][i];
b[j][i] = tmp;
}
}
}
//------------------------------------------------------------------------
static inline double* NewVector(int length)
{
double *vec = new double[length];
return vec;
}
//------------------------------------------------------------------------
static inline void DeleteVector(double *v)
{
delete [] v;
}
//----------------------------------------------------------------------------
// protected
vtkPCAAnalysisFilter::vtkPCAAnalysisFilter()
{
this->Evals = vtkFloatArray::New();
this->evecMat2 = NULL;
this->meanshape = NULL;
}
//----------------------------------------------------------------------------
// protected
vtkPCAAnalysisFilter::~vtkPCAAnalysisFilter()
{
if (this->Evals) {
this->Evals->Delete();
}
if (this->evecMat2) {
DeleteMatrix(this->evecMat2);
this->evecMat2 = NULL;
}
if (this->meanshape) {
DeleteVector(this->meanshape);
this->meanshape = NULL;
}
}
//----------------------------------------------------------------------------
// protected
void vtkPCAAnalysisFilter::Execute()
{
vtkDebugMacro(<<"Execute()");
if(!this->vtkProcessObject::Inputs) {
vtkErrorMacro(<<"No input!");
return;
}
int i;
// Clean up from previous computation
if (this->evecMat2) {
DeleteMatrix(this->evecMat2);
this->evecMat2 = NULL;
}
if (this->meanshape) {
DeleteVector(this->meanshape);
this->meanshape = NULL;
}
const int N_SETS = this->vtkProcessObject::GetNumberOfInputs();
// copy the inputs across
for(i=0;i<N_SETS;i++) {
this->GetOutput(i)->DeepCopy(this->GetInput(i));
}
// the number of points is determined by the first input (they must all be the same)
const int N_POINTS = this->GetInput(0)->GetNumberOfPoints();
vtkDebugMacro(<<"N_POINTS is " <<N_POINTS);
if(N_POINTS == 0) {
vtkErrorMacro(<<"No points!");
return;
}
// all the inputs must have the same number of points to consider executing
for(i=1;i<N_SETS;i++) {
if(this->GetInput(i)->GetNumberOfPoints() != N_POINTS) {
vtkErrorMacro(<<"The inputs have different numbers of points!");
return;
}
}
// Number of shapes
const int s = N_SETS;
// Number of points in a shape
const int n = N_POINTS;
// Observation Matrix [number of points * 3 X number of shapes]
double **D = NewMatrix(3*n, s);
for (i = 0; i < n; i++) {
for (int j = 0; j < s; j++) {
float *p = this->GetInput(j)->GetPoint(i);
D[i*3 ][j] = p[0];
D[i*3+1][j] = p[1];
D[i*3+2][j] = p[2];
}
}
// The mean shape is also calculated
meanshape = NewVector(3*n);
SubtractMeanColumn(D, meanshape, 3*n, s);
// Covariance matrix of dim [s x s]
double **T = NewMatrix(s, s);
SmallCovarianceMatrix(D, T, 3*n, s);
double *ev = NewVector(s);
double **evecMat = NewMatrix(s, s);
vtkMath::JacobiN(T, s, ev, evecMat);
// Compute eigenvecs of DD' instead of T which is D'D
// evecMat2 of dim [3*n x s]
evecMat2 = NewMatrix(3*n, s);
MatrixMultiply(D, evecMat, evecMat2, 3*n, s, s, s);
// Normalise eigenvectors
NormaliseColumns(evecMat2, 3*n, s);
this->Evals->SetNumberOfValues(s);
// Copy data to output structures
for (int j = 0; j < s; j++) {
this->Evals->SetValue(j, ev[j]);
for (int i = 0; i < n; i++) {
double x = evecMat2[i*3 ][j];
double y = evecMat2[i*3+1][j];
double z = evecMat2[i*3+2][j];
this->GetOutput(j)->GetPoints()->SetPoint(i, x, y, z);
}
}
DeleteMatrix(evecMat);
DeleteVector(ev);
DeleteMatrix(T);
DeleteMatrix(D);
}
//----------------------------------------------------------------------------
// public
void vtkPCAAnalysisFilter::GetParameterisedShape(vtkFloatArray *b, vtkPointSet* shape)
{
const int bsize = b->GetNumberOfTuples();
const int n = this->GetOutput(0)->GetNumberOfPoints();
if(shape->GetNumberOfPoints() != n) {
vtkErrorMacro(<<"Input shape does not have the correct number of points");
return;
}
double *shapevec = NewVector(n*3);
int i,j;
// b is weighted by the eigenvals
// make weigth vector for speed reasons
double *w = NewVector(bsize);
for (i = 0; i < bsize; i++) {
w[i] =sqrt(this->Evals->GetValue(i)) * b->GetValue(i);
}
for (j = 0; j < n*3; j++) {
shapevec[j] = meanshape[j];
for (i = 0; i < bsize; i++) {
shapevec[j] += w[i] * evecMat2[j][i];
}
}
// Copy shape
for (i = 0; i < n; i++) {
shape->GetPoints()->SetPoint(i,shapevec[i*3 ], shapevec[i*3+1], shapevec[i*3+2]);
}
DeleteVector(w);
}
//----------------------------------------------------------------------------
// public
void vtkPCAAnalysisFilter::GetShapeParameters(vtkPointSet *shape, vtkFloatArray *b, int bsize)
{
// Local variant of b for fast access.
double *bloc = NewVector(bsize);
const int n = this->GetOutput(0)->GetNumberOfPoints();
int i,j;
if(shape->GetNumberOfPoints() != n) {
vtkErrorMacro(<<"Input shape does not have the correct number of points");
return;
}
double *shapevec = NewVector(n*3);
// Copy shape and subtract mean shape
for (i = 0; i < n; i++) {
float *p = shape->GetPoint(i);
shapevec[i*3 ] = p[0] - meanshape[i*3];
shapevec[i*3+1] = p[1] - meanshape[i*3+1];
shapevec[i*3+2] = p[2] - meanshape[i*3+2];
}
for (i = 0; i < bsize; i++) {
bloc[i] = 0;
// Project the shape onto eigenvector i
for (j = 0; j < n*3; j++) {
bloc[i] += shapevec[j] * evecMat2[j][i];
}
}
// Return b in number of standard deviations
b->SetNumberOfValues(bsize);
for (i = 0; i < bsize; i++) {
if (this->Evals->GetValue(i))
b->SetValue(i, bloc[i]/sqrt(this->Evals->GetValue(i)));
else
b->SetValue(i, 0);
}
DeleteVector(shapevec);
DeleteVector(bloc);
}
//----------------------------------------------------------------------------
// public
void vtkPCAAnalysisFilter::SetNumberOfInputs(int n)
{
this->vtkProcessObject::SetNumberOfInputs(n);
this->vtkSource::SetNumberOfOutputs(n);
// initialise the outputs
for(int i=0;i<n;i++) {
vtkPoints *points = vtkPoints::New();
vtkPolyData *ps = vtkPolyData::New();
ps->SetPoints(points);
points->Delete();
this->vtkSource::SetNthOutput(i,ps);
ps->Delete();
}
// is this the right thing to be doing here? if we don't initialise the outputs here
// then the filter crashes but vtkPolyData may not be the type of the inputs
}
//----------------------------------------------------------------------------
// public
void vtkPCAAnalysisFilter::SetInput(int idx,vtkPointSet* p)
{
if(idx<0 || idx>=this->vtkProcessObject::GetNumberOfInputs()) {
vtkErrorMacro(<<"Index out of bounds in SetInput!");
return;
}
this->vtkProcessObject::SetNthInput(idx,p);
}
//----------------------------------------------------------------------------
// protected
vtkPointSet* vtkPCAAnalysisFilter::GetInput(int idx)
{
if(idx<0 || idx>=this->vtkProcessObject::GetNumberOfInputs()) {
vtkErrorMacro(<<"Index out of bounds in GetInput!");
return NULL;
}
return static_cast<vtkPointSet*>(this->vtkProcessObject::Inputs[idx]);
}
//----------------------------------------------------------------------------
// public
vtkPointSet* vtkPCAAnalysisFilter::GetOutput(int idx)
{
if(idx<0 || idx>=this->vtkSource::GetNumberOfOutputs()) {
vtkErrorMacro(<<"Index out of bounds in GetOutput!");
return NULL;
}
return static_cast<vtkPointSet*>(this->vtkSource::GetOutput(idx));
}
//----------------------------------------------------------------------------
// public
void vtkPCAAnalysisFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
this->Evals->PrintSelf(os,indent);
}
<|endoftext|> |
<commit_before>/*
* observation.cpp
*
* Created on: Apr 29, 2013
* Author: F. Bellagamba
*/
#include "slsimlib.h"
#ifdef ENABLE_FITS
#include <CCfits/CCfits>
//#include <CCfits>
#endif
#ifdef ENABLE_FFTW
#include "fftw3.h"
#endif
#include <fstream>
#include <limits>
/*\brief Creates an observation setup that mimics a known instrument
*
*/
Observation::Observation(Telescope tel_name)
{
if (tel_name == Euclid_VIS)
{
diameter = 119.;
transmission = 0.30;
exp_time = 1800.;
exp_num = 3;
back_mag = 22.8;
ron = 5.;
seeing = 0.18;
pix_size = .1/60./60./180.*pi;
}
if (tel_name == Euclid_Y)
{
diameter = 119.;
transmission = 0.0961;
exp_time = 264.;
exp_num = 3;
back_mag = 22.57;
ron = 5.;
seeing = 0.3;
pix_size = .3/60./60./180.*pi;
}
if (tel_name == Euclid_J)
{
diameter = 119.;
transmission = 0.0814;
exp_time = 270.;
exp_num = 3;
back_mag = 22.53;
ron = 5.;
seeing = 0.3;
pix_size = .3/60./60./180.*pi;
}
if (tel_name == Euclid_H)
{
diameter = 119.;
transmission = 0.1692;
exp_time = 162.;
exp_num = 3;
back_mag = 22.59;
ron = 5.;
seeing = 0.3;
pix_size = .3/60./60./180.*pi;
}
if (tel_name == KiDS_u)
{
diameter = 265.;
transmission = 0.032;
exp_time = 1000.;
exp_num = 5;
back_mag = 22.93;
ron = 5.;
seeing = 1.0;
pix_size = .21/60./60./180.*pi;
}
if (tel_name == KiDS_g)
{
diameter = 265.;
transmission = 0.1220;
exp_time = 900.;
exp_num = 5;
back_mag = 22.29;
ron = 5.;
seeing = 0.8;
pix_size = .21/60./60./180.*pi;
}
if (tel_name == KiDS_r)
{
diameter = 265.;
transmission = 0.089;
exp_time = 1800.;
exp_num = 5;
back_mag = 21.40;
ron = 5.;
seeing = 0.7;
pix_size = .21/60./60./180.*pi;
}
if (tel_name == KiDS_i)
{
diameter = 265.;
transmission = 0.062;
exp_time = 1200.;
exp_num = 5;
back_mag = 20.64;
ron = 5.;
seeing = 1.1;
pix_size = .21/60./60./180.*pi;
}
mag_zeropoint = 2.5*log10(diameter*diameter*transmission*pi/4./hplanck) - 48.6;
telescope = true;
}
/* Creates a custom observation setup with parameters decided by the user.
*
* \param diameter Diameter of telescope (in cm) (Collecting area is pi/4.*diameter^2)
* \param transmission Total transmission of the telescope (/int T(\lambda)/\lambda d\lambda)
* \param exp_time Total exposure time
* \param exp_num Number of exposures
* \param back_mag Flux due to background and/or sky in mag/arcsec^2
* \param ron Read-out noise in electrons/pixel
* \param seeing FWHM in arcsecs of the image
*/
Observation::Observation(float diameter, float transmission, float exp_time, int exp_num, float back_mag, float ron, float seeing):
diameter(diameter), transmission(transmission), exp_time(exp_time), exp_num(exp_num), back_mag(back_mag), ron(ron), seeing(seeing)
{
mag_zeropoint = 2.5*log10(diameter*diameter*transmission*pi/4./hplanck) - 48.6;
telescope = false;
}
/* Creates a custom observation setup with parameters decided by the user. Allows for the use of a psf fits image.
*
* \param diameter Diameter of telescope (in cm) (Collecting area is pi/4.*diameter^2)
* \param transmission Total transmission of the telescope (/int T(\lambda)/\lambda d\lambda)
* \param exp_time Total exposure time
* \param exp_num Number of exposures
* \param back_mag Flux due to background and/or sky in mag/arcsec^2
* \param ron Read-out noise in electrons/pixel
* \param psf_file Input PSF image
* \param oversample Oversampling rate of the PSF image
*/
Observation::Observation(float diameter, float transmission, float exp_time, int exp_num, float back_mag, float ron, std::string psf_file, float oversample):
diameter(diameter), transmission(transmission), exp_time(exp_time), exp_num(exp_num), back_mag(back_mag), ron(ron), oversample(oversample)
{
mag_zeropoint = 2.5*log10(diameter*diameter*transmission*pi/4./hplanck) - 48.6;
#ifdef ENABLE_FITS
std::auto_ptr<CCfits::FITS> fp (new CCfits::FITS (psf_file.c_str(), CCfits::Read));
CCfits::PHDU *h0=&fp->pHDU();
int side_psf = h0->axis(0);
int N_psf = side_psf*side_psf;
map_psf.resize(N_psf);
h0->read(map_psf);
#else
std::cout << "Please enable the preprocessor flag ENABLE_FITS !" << std::endl;
exit(1);
#endif
telescope = false;
}
/* \brief Converts the input map to a realistic image
*
* \param map Input map in photons/(cm^2*Hz)
* \param psf Decides if the psf smoothing is applied
* \param noise Decides if noise is added
*/
PixelMap Observation::Convert (PixelMap &map, bool psf, bool noise, long *seed)
{
if (telescope == true && fabs(map.getResolution()-pix_size) > std::numeric_limits<double>::epsilon())
{
std::cout << "The resolution of the input map is different from the one of the simulated instrument!" << std::endl;
exit(1);
}
PixelMap outmap = PhotonToCounts(map);
if (psf == true) outmap = ApplyPSF(outmap);
if (noise == true) outmap = AddNoise(outmap,seed);
return outmap;
}
/// Converts an observed image to the units of the lensing simulation
PixelMap Observation::Convert_back (PixelMap &map)
{
PixelMap outmap(map);
double Q = pow(10,0.4*(mag_zeropoint+48.6))*hplanck;
outmap.Renormalize(1./Q);
return outmap;
}
/** \brief Smooths the image with a PSF map.
*
*/
PixelMap Observation::ApplyPSF(PixelMap &pmap)
{
if (map_psf.size() == 0)
{
if (seeing > 0.)
{
PixelMap outmap(pmap);
outmap.smooth(seeing/2.355);
return outmap;
}
else
{
return pmap;
}
}
else
{
#ifdef ENABLE_FITS
#ifdef ENABLE_FFTW
PixelMap outmap(pmap);
// creates plane for fft of map, sets properly input and output data, then performs fft
fftw_plan p;
long Npix = outmap.getNpixels();
double* in = new double[Npix*Npix];
std::complex<double>* out=new std::complex<double> [Npix*(Npix/2+1)];
for (unsigned long i = 0; i < Npix*Npix; i++)
{
in[i] = outmap[i];
}
p = fftw_plan_dft_r2c_2d(Npix,Npix,in, reinterpret_cast<fftw_complex*>(out), FFTW_ESTIMATE);
fftw_execute(p);
// creates plane for perform backward fft after convolution, sets output data
fftw_plan p2;
double* out2 = new double[Npix*Npix];
p2 = fftw_plan_dft_c2r_2d(Npix,Npix,reinterpret_cast<fftw_complex*>(out), out2, FFTW_ESTIMATE);
// calculates normalisation of psf
int N_psf = map_psf.size();
int side_psf = sqrt(N_psf);
double map_norm = 0.;
for (int i = 0; i < N_psf; i++)
{
map_norm += map_psf[i];
}
fftw_plan p_psf;
// arrange psf data for fft, creates plane, then performs fft
int psf_big_Npixels = static_cast<int>(Npix*oversample);
double* psf_big = new double[psf_big_Npixels*psf_big_Npixels];
std::complex<double>* out_psf=new std::complex<double> [psf_big_Npixels*(psf_big_Npixels/2+1)];
p_psf = fftw_plan_dft_r2c_2d(psf_big_Npixels,psf_big_Npixels,psf_big, reinterpret_cast<fftw_complex*>(out_psf), FFTW_ESTIMATE);
long ix, iy;
for (int i = 0; i < psf_big_Npixels*psf_big_Npixels; i++)
{
ix = i/psf_big_Npixels;
iy = i%psf_big_Npixels;
if(ix<side_psf/2 && iy<side_psf/2)
psf_big[i] = map_psf[(ix+side_psf/2)*side_psf+(iy+side_psf/2)]/map_norm;
else if(ix<side_psf/2 && iy>=psf_big_Npixels-side_psf/2)
psf_big[i] = map_psf[(ix+side_psf/2)*side_psf+(iy-(psf_big_Npixels-side_psf/2))]/map_norm;
else if(ix>=psf_big_Npixels-side_psf/2 && iy<side_psf/2)
psf_big[i] = map_psf[(ix-(psf_big_Npixels-side_psf/2))*side_psf+(iy+side_psf/2)]/map_norm;
else if(ix>=psf_big_Npixels-side_psf/2 && iy>=psf_big_Npixels-side_psf/2)
psf_big[i] = map_psf[(ix-(psf_big_Npixels-side_psf/2))*side_psf+(iy-(psf_big_Npixels-side_psf/2))]/map_norm;
else
psf_big[i] = 0.;
}
fftw_execute(p_psf);
// performs convolution in Fourier space, and transforms back to real space
for (unsigned long i = 0; i < Npix*(Npix/2+1); i++)
{
ix = i/(Npix/2+1);
iy = i%(Npix/2+1);
if (ix>Npix/2)
out[i] *= out_psf[(psf_big_Npixels-(Npix-ix))*(psf_big_Npixels/2+1)+iy];
else
out[i] *= out_psf[ix*(psf_big_Npixels/2+1)+iy];
}
fftw_execute(p2);
// translates array of data in (normalised) counts map
for (unsigned long i = 0; i < Npix*Npix; i++)
{
//ix = i/Npix;
//iy = i%Npix;
outmap.AssignValue(i,out2[i]/double(Npix*Npix));
}
return outmap;
#else
std::cout << "Please enable the preprocessor flag ENABLE_FFTW !" << std::endl;
exit(1);
#endif
#else
std::cout << "Please enable the preprocessor flag ENABLE_FITS !" << std::endl;
exit(1);
#endif
}
}
/// Applies realistic noise (read-out + Poisson) on an image
PixelMap Observation::AddNoise(PixelMap &pmap,long *seed)
{
PixelMap outmap(pmap);
double Q = pow(10,0.4*(mag_zeropoint+48.6));
double res_in_arcsec = outmap.getResolution()*180.*60.*60/pi;
double back_mean = pow(10,-0.4*(48.6+back_mag))*res_in_arcsec*res_in_arcsec*Q*exp_time;
double rms, noise;
double norm_map;
for (unsigned long i = 0; i < outmap.getNpixels()*outmap.getNpixels(); i++)
{
norm_map = outmap[i]*exp_time;
if (norm_map+back_mean > 500.)
{
rms = sqrt(pow(exp_num*ron,2)+norm_map+back_mean);
noise = gasdev(seed)*rms;
outmap.AssignValue(i,double(norm_map+noise)/exp_time);
}
else
{
int k = 0;
double p = 1.;
double L = exp(-(norm_map+back_mean));
while (p > L)
{
k++;
p *= ran2(seed);
}
outmap.AssignValue(i,double(k-1-back_mean)/exp_time);
}
}
return outmap;
}
/// Translates photon flux (in photons/(cm^2*Hz)) into telescope pixel counts
PixelMap Observation::PhotonToCounts(PixelMap &pmap)
{
PixelMap outmap(pmap);
double Q = pow(10,0.4*(mag_zeropoint+48.6))*hplanck;
outmap.Renormalize(Q);
return outmap;
}
<commit_msg>Changes to comments.<commit_after>/*
* observation.cpp
*
* Created on: Apr 29, 2013
* Author: F. Bellagamba
*/
#include "slsimlib.h"
#ifdef ENABLE_FITS
#include <CCfits/CCfits>
//#include <CCfits>
#endif
#ifdef ENABLE_FFTW
#include "fftw3.h"
#endif
#include <fstream>
#include <limits>
/** * \brief Creates an observation setup that mimics a known instrument
*
*/
Observation::Observation(Telescope tel_name)
{
if (tel_name == Euclid_VIS)
{
diameter = 119.;
transmission = 0.30;
exp_time = 1800.;
exp_num = 3;
back_mag = 22.8;
ron = 5.;
seeing = 0.18;
pix_size = .1/60./60./180.*pi;
}
if (tel_name == Euclid_Y)
{
diameter = 119.;
transmission = 0.0961;
exp_time = 264.;
exp_num = 3;
back_mag = 22.57;
ron = 5.;
seeing = 0.3;
pix_size = .3/60./60./180.*pi;
}
if (tel_name == Euclid_J)
{
diameter = 119.;
transmission = 0.0814;
exp_time = 270.;
exp_num = 3;
back_mag = 22.53;
ron = 5.;
seeing = 0.3;
pix_size = .3/60./60./180.*pi;
}
if (tel_name == Euclid_H)
{
diameter = 119.;
transmission = 0.1692;
exp_time = 162.;
exp_num = 3;
back_mag = 22.59;
ron = 5.;
seeing = 0.3;
pix_size = .3/60./60./180.*pi;
}
if (tel_name == KiDS_u)
{
diameter = 265.;
transmission = 0.032;
exp_time = 1000.;
exp_num = 5;
back_mag = 22.93;
ron = 5.;
seeing = 1.0;
pix_size = .21/60./60./180.*pi;
}
if (tel_name == KiDS_g)
{
diameter = 265.;
transmission = 0.1220;
exp_time = 900.;
exp_num = 5;
back_mag = 22.29;
ron = 5.;
seeing = 0.8;
pix_size = .21/60./60./180.*pi;
}
if (tel_name == KiDS_r)
{
diameter = 265.;
transmission = 0.089;
exp_time = 1800.;
exp_num = 5;
back_mag = 21.40;
ron = 5.;
seeing = 0.7;
pix_size = .21/60./60./180.*pi;
}
if (tel_name == KiDS_i)
{
diameter = 265.;
transmission = 0.062;
exp_time = 1200.;
exp_num = 5;
back_mag = 20.64;
ron = 5.;
seeing = 1.1;
pix_size = .21/60./60./180.*pi;
}
mag_zeropoint = 2.5*log10(diameter*diameter*transmission*pi/4./hplanck) - 48.6;
telescope = true;
}
/** * Creates a custom observation setup with parameters decided by the user.
*
* \param diameter Diameter of telescope (in cm) (Collecting area is pi/4.*diameter^2)
* \param transmission Total transmission of the telescope (/int T(\lambda)/\lambda d\lambda)
* \param exp_time Total exposure time
* \param exp_num Number of exposures
* \param back_mag Flux due to background and/or sky in mag/arcsec^2
* \param ron Read-out noise in electrons/pixel
* \param seeing FWHM in arcsecs of the image
*/
Observation::Observation(float diameter, float transmission, float exp_time, int exp_num, float back_mag, float ron, float seeing):
diameter(diameter), transmission(transmission), exp_time(exp_time), exp_num(exp_num), back_mag(back_mag), ron(ron), seeing(seeing)
{
mag_zeropoint = 2.5*log10(diameter*diameter*transmission*pi/4./hplanck) - 48.6;
telescope = false;
}
/** Creates a custom observation setup with parameters decided by the user. Allows for the use of a psf fits image.
*
* \param diameter Diameter of telescope (in cm) (Collecting area is pi/4.*diameter^2)
* \param transmission Total transmission of the telescope (/int T(\lambda)/\lambda d\lambda)
* \param exp_time Total exposure time
* \param exp_num Number of exposures
* \param back_mag Flux due to background and/or sky in mag/arcsec^2
* \param ron Read-out noise in electrons/pixel
* \param psf_file Input PSF image
* \param oversample Oversampling rate of the PSF image
*/
Observation::Observation(float diameter, float transmission, float exp_time, int exp_num, float back_mag, float ron, std::string psf_file, float oversample):
diameter(diameter), transmission(transmission), exp_time(exp_time), exp_num(exp_num), back_mag(back_mag), ron(ron), oversample(oversample)
{
mag_zeropoint = 2.5*log10(diameter*diameter*transmission*pi/4./hplanck) - 48.6;
#ifdef ENABLE_FITS
std::auto_ptr<CCfits::FITS> fp (new CCfits::FITS (psf_file.c_str(), CCfits::Read));
CCfits::PHDU *h0=&fp->pHDU();
int side_psf = h0->axis(0);
int N_psf = side_psf*side_psf;
map_psf.resize(N_psf);
h0->read(map_psf);
#else
std::cout << "Please enable the preprocessor flag ENABLE_FITS !" << std::endl;
exit(1);
#endif
telescope = false;
}
/** \brief Converts the input map to a realistic image
*
* \param map Input map in photons/(cm^2*Hz)
* \param psf Decides if the psf smoothing is applied
* \param noise Decides if noise is added
*/
PixelMap Observation::Convert (PixelMap &map, bool psf, bool noise, long *seed)
{
if (telescope == true && fabs(map.getResolution()-pix_size) > std::numeric_limits<double>::epsilon())
{
std::cout << "The resolution of the input map is different from the one of the simulated instrument!" << std::endl;
exit(1);
}
PixelMap outmap = PhotonToCounts(map);
if (psf == true) outmap = ApplyPSF(outmap);
if (noise == true) outmap = AddNoise(outmap,seed);
return outmap;
}
/// Converts an observed image to the units of the lensing simulation
PixelMap Observation::Convert_back (PixelMap &map)
{
PixelMap outmap(map);
double Q = pow(10,0.4*(mag_zeropoint+48.6))*hplanck;
outmap.Renormalize(1./Q);
return outmap;
}
/** * \brief Smooths the image with a PSF map.
*
*/
PixelMap Observation::ApplyPSF(PixelMap &pmap)
{
if (map_psf.size() == 0)
{
if (seeing > 0.)
{
PixelMap outmap(pmap);
outmap.smooth(seeing/2.355);
return outmap;
}
else
{
return pmap;
}
}
else
{
#ifdef ENABLE_FITS
#ifdef ENABLE_FFTW
PixelMap outmap(pmap);
// creates plane for fft of map, sets properly input and output data, then performs fft
fftw_plan p;
long Npix = outmap.getNpixels();
double* in = new double[Npix*Npix];
std::complex<double>* out=new std::complex<double> [Npix*(Npix/2+1)];
for (unsigned long i = 0; i < Npix*Npix; i++)
{
in[i] = outmap[i];
}
p = fftw_plan_dft_r2c_2d(Npix,Npix,in, reinterpret_cast<fftw_complex*>(out), FFTW_ESTIMATE);
fftw_execute(p);
// creates plane for perform backward fft after convolution, sets output data
fftw_plan p2;
double* out2 = new double[Npix*Npix];
p2 = fftw_plan_dft_c2r_2d(Npix,Npix,reinterpret_cast<fftw_complex*>(out), out2, FFTW_ESTIMATE);
// calculates normalisation of psf
int N_psf = map_psf.size();
int side_psf = sqrt(N_psf);
double map_norm = 0.;
for (int i = 0; i < N_psf; i++)
{
map_norm += map_psf[i];
}
fftw_plan p_psf;
// arrange psf data for fft, creates plane, then performs fft
int psf_big_Npixels = static_cast<int>(Npix*oversample);
double* psf_big = new double[psf_big_Npixels*psf_big_Npixels];
std::complex<double>* out_psf=new std::complex<double> [psf_big_Npixels*(psf_big_Npixels/2+1)];
p_psf = fftw_plan_dft_r2c_2d(psf_big_Npixels,psf_big_Npixels,psf_big, reinterpret_cast<fftw_complex*>(out_psf), FFTW_ESTIMATE);
long ix, iy;
for (int i = 0; i < psf_big_Npixels*psf_big_Npixels; i++)
{
ix = i/psf_big_Npixels;
iy = i%psf_big_Npixels;
if(ix<side_psf/2 && iy<side_psf/2)
psf_big[i] = map_psf[(ix+side_psf/2)*side_psf+(iy+side_psf/2)]/map_norm;
else if(ix<side_psf/2 && iy>=psf_big_Npixels-side_psf/2)
psf_big[i] = map_psf[(ix+side_psf/2)*side_psf+(iy-(psf_big_Npixels-side_psf/2))]/map_norm;
else if(ix>=psf_big_Npixels-side_psf/2 && iy<side_psf/2)
psf_big[i] = map_psf[(ix-(psf_big_Npixels-side_psf/2))*side_psf+(iy+side_psf/2)]/map_norm;
else if(ix>=psf_big_Npixels-side_psf/2 && iy>=psf_big_Npixels-side_psf/2)
psf_big[i] = map_psf[(ix-(psf_big_Npixels-side_psf/2))*side_psf+(iy-(psf_big_Npixels-side_psf/2))]/map_norm;
else
psf_big[i] = 0.;
}
fftw_execute(p_psf);
// performs convolution in Fourier space, and transforms back to real space
for (unsigned long i = 0; i < Npix*(Npix/2+1); i++)
{
ix = i/(Npix/2+1);
iy = i%(Npix/2+1);
if (ix>Npix/2)
out[i] *= out_psf[(psf_big_Npixels-(Npix-ix))*(psf_big_Npixels/2+1)+iy];
else
out[i] *= out_psf[ix*(psf_big_Npixels/2+1)+iy];
}
fftw_execute(p2);
// translates array of data in (normalised) counts map
for (unsigned long i = 0; i < Npix*Npix; i++)
{
//ix = i/Npix;
//iy = i%Npix;
outmap.AssignValue(i,out2[i]/double(Npix*Npix));
}
return outmap;
#else
std::cout << "Please enable the preprocessor flag ENABLE_FFTW !" << std::endl;
exit(1);
#endif
#else
std::cout << "Please enable the preprocessor flag ENABLE_FITS !" << std::endl;
exit(1);
#endif
}
}
/// Applies realistic noise (read-out + Poisson) on an image
PixelMap Observation::AddNoise(PixelMap &pmap,long *seed)
{
PixelMap outmap(pmap);
double Q = pow(10,0.4*(mag_zeropoint+48.6));
double res_in_arcsec = outmap.getResolution()*180.*60.*60/pi;
double back_mean = pow(10,-0.4*(48.6+back_mag))*res_in_arcsec*res_in_arcsec*Q*exp_time;
double rms, noise;
double norm_map;
for (unsigned long i = 0; i < outmap.getNpixels()*outmap.getNpixels(); i++)
{
norm_map = outmap[i]*exp_time;
if (norm_map+back_mean > 500.)
{
rms = sqrt(pow(exp_num*ron,2)+norm_map+back_mean);
noise = gasdev(seed)*rms;
outmap.AssignValue(i,double(norm_map+noise)/exp_time);
}
else
{
int k = 0;
double p = 1.;
double L = exp(-(norm_map+back_mean));
while (p > L)
{
k++;
p *= ran2(seed);
}
outmap.AssignValue(i,double(k-1-back_mean)/exp_time);
}
}
return outmap;
}
/// Translates photon flux (in photons/(cm^2*Hz)) into telescope pixel counts
PixelMap Observation::PhotonToCounts(PixelMap &pmap)
{
PixelMap outmap(pmap);
double Q = pow(10,0.4*(mag_zeropoint+48.6))*hplanck;
outmap.Renormalize(Q);
return outmap;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageMapToColors.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageMapToColors.h"
#include "vtkImageData.h"
#include "vtkObjectFactory.h"
#include "vtkScalarsToColors.h"
#include "vtkPointData.h"
vtkCxxRevisionMacro(vtkImageMapToColors, "1.21");
vtkStandardNewMacro(vtkImageMapToColors);
vtkCxxSetObjectMacro(vtkImageMapToColors,LookupTable,vtkScalarsToColors);
//----------------------------------------------------------------------------
// Constructor sets default values
vtkImageMapToColors::vtkImageMapToColors()
{
this->OutputFormat = 4;
this->ActiveComponent = 0;
this->PassAlphaToOutput = 0;
this->LookupTable = NULL;
this->DataWasPassed = 0;
}
vtkImageMapToColors::~vtkImageMapToColors()
{
if (this->LookupTable != NULL)
{
this->LookupTable->UnRegister(this);
}
}
//----------------------------------------------------------------------------
unsigned long vtkImageMapToColors::GetMTime()
{
unsigned long t1, t2;
t1 = this->vtkImageToImageFilter::GetMTime();
if (this->LookupTable)
{
t2 = this->LookupTable->GetMTime();
if (t2 > t1)
{
t1 = t2;
}
}
return t1;
}
//----------------------------------------------------------------------------
// This method checks to see if we can simply reference the input data
void vtkImageMapToColors::ExecuteData(vtkDataObject *output)
{
vtkImageData *outData = (vtkImageData *)(output);
vtkImageData *inData = this->GetInput();
// If LookupTable is null, just pass the data
if (this->LookupTable == NULL)
{
vtkDebugMacro("ExecuteData: LookupTable not set, "\
"passing input to output.");
outData->SetExtent(inData->GetExtent());
outData->GetPointData()->PassData(inData->GetPointData());
this->DataWasPassed = 1;
}
else // normal behaviour
{
if (this->DataWasPassed)
{
outData->GetPointData()->SetScalars(NULL);
this->DataWasPassed = 0;
}
this->vtkImageToImageFilter::ExecuteData(output);
}
}
//----------------------------------------------------------------------------
void vtkImageMapToColors::ExecuteInformation(vtkImageData *inData,
vtkImageData *outData)
{
int numComponents = 4;
switch (this->OutputFormat)
{
case VTK_RGBA:
numComponents = 4;
break;
case VTK_RGB:
numComponents = 3;
break;
case VTK_LUMINANCE_ALPHA:
numComponents = 2;
break;
case VTK_LUMINANCE:
numComponents = 1;
break;
default:
vtkErrorMacro("ExecuteInformation: Unrecognized color format.");
break;
}
if (this->LookupTable == NULL)
{
if (inData->GetScalarType() != VTK_UNSIGNED_CHAR)
{
vtkErrorMacro("ExecuteInformation: No LookupTable was set but input data is not VTK_UNSIGNED_CHAR, therefore input can't be passed through!");
return;
}
else if (numComponents != inData->GetNumberOfScalarComponents())
{
vtkErrorMacro("ExecuteInformation: No LookupTable was set but number of components in input doesn't match OutputFormat, therefore input can't be passed through!");
return;
}
}
outData->SetScalarType(VTK_UNSIGNED_CHAR);
outData->SetNumberOfScalarComponents(numComponents);
}
//----------------------------------------------------------------------------
// This non-templated function executes the filter for any type of data.
void vtkImageMapToColorsExecute(vtkImageMapToColors *self,
vtkImageData *inData, void *inPtr,
vtkImageData *outData,
unsigned char *outPtr,
int outExt[6], int id)
{
int idxY, idxZ;
int extX, extY, extZ;
int inIncX, inIncY, inIncZ;
int outIncX, outIncY, outIncZ;
unsigned long count = 0;
unsigned long target;
int dataType = inData->GetScalarType();
int scalarSize = inData->GetScalarSize();
int numberOfComponents,numberOfOutputComponents,outputFormat;
int rowLength;
vtkScalarsToColors *lookupTable = self->GetLookupTable();
unsigned char *outPtr1;
void *inPtr1;
// find the region to loop over
extX = outExt[1] - outExt[0] + 1;
extY = outExt[3] - outExt[2] + 1;
extZ = outExt[5] - outExt[4] + 1;
target = (unsigned long)(extZ*extY/50.0);
target++;
// Get increments to march through data
inData->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ);
// because we are using void * and char * we must take care
// of the scalar size in the increments
inIncY *= scalarSize;
inIncZ *= scalarSize;
outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);
numberOfComponents = inData->GetNumberOfScalarComponents();
numberOfOutputComponents = outData->GetNumberOfScalarComponents();
outputFormat = self->GetOutputFormat();
rowLength = extX*scalarSize*numberOfComponents;
// Loop through output pixels
outPtr1 = outPtr;
inPtr1 = (void *) ((char *) inPtr + self->GetActiveComponent()*scalarSize);
for (idxZ = 0; idxZ < extZ; idxZ++)
{
for (idxY = 0; !self->AbortExecute && idxY < extY; idxY++)
{
if (!id)
{
if (!(count%target))
{
self->UpdateProgress(count/(50.0*target));
}
count++;
}
lookupTable->MapScalarsThroughTable2(inPtr1,outPtr1,
dataType,extX,numberOfComponents,
outputFormat);
if (self->GetPassAlphaToOutput() &&
dataType == VTK_UNSIGNED_CHAR && numberOfComponents > 1 &&
(outputFormat == VTK_RGBA || outputFormat == VTK_LUMINANCE_ALPHA))
{
unsigned char *outPtr2 = outPtr1 + numberOfOutputComponents - 1;
unsigned char *inPtr2 = (unsigned char *)inPtr1
- self->GetActiveComponent()*scalarSize
+ numberOfComponents - 1;
for (int i = 0; i < extX; i++)
{
*outPtr2 = (*outPtr2 * *inPtr2)/255;
outPtr2 += numberOfOutputComponents;
inPtr2 += numberOfComponents;
}
}
outPtr1 += outIncY + extX*numberOfOutputComponents;
inPtr1 = (void *) ((char *) inPtr1 + inIncY + rowLength);
}
outPtr1 += outIncZ;
inPtr1 = (void *) ((char *) inPtr1 + inIncZ);
}
}
//----------------------------------------------------------------------------
// This method is passed a input and output data, and executes the filter
// algorithm to fill the output from the input.
void vtkImageMapToColors::ThreadedExecute(vtkImageData *inData,
vtkImageData *outData,
int outExt[6], int id)
{
void *inPtr = inData->GetScalarPointerForExtent(outExt);
void *outPtr = outData->GetScalarPointerForExtent(outExt);
vtkImageMapToColorsExecute(this, inData, inPtr,
outData, (unsigned char *)outPtr, outExt, id);
}
void vtkImageMapToColors::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "OutputFormat: " <<
(this->OutputFormat == VTK_RGBA ? "RGBA" :
(this->OutputFormat == VTK_RGB ? "RGB" :
(this->OutputFormat == VTK_LUMINANCE_ALPHA ? "LuminanceAlpha" :
(this->OutputFormat == VTK_LUMINANCE ? "Luminance" : "Unknown"))))
<< "\n";
os << indent << "ActiveComponent: " << this->ActiveComponent << "\n";
os << indent << "PassAlphaToOutput: " << this->PassAlphaToOutput << "\n";
os << indent << "LookupTable: " << this->LookupTable << "\n";
if (this->LookupTable)
{
this->LookupTable->PrintSelf(os,indent.GetNextIndent());
}
}
<commit_msg>ERR:Make syre lookup table is built<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageMapToColors.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageMapToColors.h"
#include "vtkImageData.h"
#include "vtkObjectFactory.h"
#include "vtkScalarsToColors.h"
#include "vtkPointData.h"
vtkCxxRevisionMacro(vtkImageMapToColors, "1.22");
vtkStandardNewMacro(vtkImageMapToColors);
vtkCxxSetObjectMacro(vtkImageMapToColors,LookupTable,vtkScalarsToColors);
//----------------------------------------------------------------------------
// Constructor sets default values
vtkImageMapToColors::vtkImageMapToColors()
{
this->OutputFormat = 4;
this->ActiveComponent = 0;
this->PassAlphaToOutput = 0;
this->LookupTable = NULL;
this->DataWasPassed = 0;
}
vtkImageMapToColors::~vtkImageMapToColors()
{
if (this->LookupTable != NULL)
{
this->LookupTable->UnRegister(this);
}
}
//----------------------------------------------------------------------------
unsigned long vtkImageMapToColors::GetMTime()
{
unsigned long t1, t2;
t1 = this->vtkImageToImageFilter::GetMTime();
if (this->LookupTable)
{
t2 = this->LookupTable->GetMTime();
if (t2 > t1)
{
t1 = t2;
}
}
return t1;
}
//----------------------------------------------------------------------------
// This method checks to see if we can simply reference the input data
void vtkImageMapToColors::ExecuteData(vtkDataObject *output)
{
vtkImageData *outData = (vtkImageData *)(output);
vtkImageData *inData = this->GetInput();
// If LookupTable is null, just pass the data
if (this->LookupTable == NULL)
{
vtkDebugMacro("ExecuteData: LookupTable not set, "\
"passing input to output.");
outData->SetExtent(inData->GetExtent());
outData->GetPointData()->PassData(inData->GetPointData());
this->DataWasPassed = 1;
}
else // normal behaviour
{
this->LookupTable->Build(); //make sure table is built
if (this->DataWasPassed)
{
outData->GetPointData()->SetScalars(NULL);
this->DataWasPassed = 0;
}
this->vtkImageToImageFilter::ExecuteData(output);
}
}
//----------------------------------------------------------------------------
void vtkImageMapToColors::ExecuteInformation(vtkImageData *inData,
vtkImageData *outData)
{
int numComponents = 4;
switch (this->OutputFormat)
{
case VTK_RGBA:
numComponents = 4;
break;
case VTK_RGB:
numComponents = 3;
break;
case VTK_LUMINANCE_ALPHA:
numComponents = 2;
break;
case VTK_LUMINANCE:
numComponents = 1;
break;
default:
vtkErrorMacro("ExecuteInformation: Unrecognized color format.");
break;
}
if (this->LookupTable == NULL)
{
if (inData->GetScalarType() != VTK_UNSIGNED_CHAR)
{
vtkErrorMacro("ExecuteInformation: No LookupTable was set but input data is not VTK_UNSIGNED_CHAR, therefore input can't be passed through!");
return;
}
else if (numComponents != inData->GetNumberOfScalarComponents())
{
vtkErrorMacro("ExecuteInformation: No LookupTable was set but number of components in input doesn't match OutputFormat, therefore input can't be passed through!");
return;
}
}
outData->SetScalarType(VTK_UNSIGNED_CHAR);
outData->SetNumberOfScalarComponents(numComponents);
}
//----------------------------------------------------------------------------
// This non-templated function executes the filter for any type of data.
void vtkImageMapToColorsExecute(vtkImageMapToColors *self,
vtkImageData *inData, void *inPtr,
vtkImageData *outData,
unsigned char *outPtr,
int outExt[6], int id)
{
int idxY, idxZ;
int extX, extY, extZ;
int inIncX, inIncY, inIncZ;
int outIncX, outIncY, outIncZ;
unsigned long count = 0;
unsigned long target;
int dataType = inData->GetScalarType();
int scalarSize = inData->GetScalarSize();
int numberOfComponents,numberOfOutputComponents,outputFormat;
int rowLength;
vtkScalarsToColors *lookupTable = self->GetLookupTable();
unsigned char *outPtr1;
void *inPtr1;
// find the region to loop over
extX = outExt[1] - outExt[0] + 1;
extY = outExt[3] - outExt[2] + 1;
extZ = outExt[5] - outExt[4] + 1;
target = (unsigned long)(extZ*extY/50.0);
target++;
// Get increments to march through data
inData->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ);
// because we are using void * and char * we must take care
// of the scalar size in the increments
inIncY *= scalarSize;
inIncZ *= scalarSize;
outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);
numberOfComponents = inData->GetNumberOfScalarComponents();
numberOfOutputComponents = outData->GetNumberOfScalarComponents();
outputFormat = self->GetOutputFormat();
rowLength = extX*scalarSize*numberOfComponents;
// Loop through output pixels
outPtr1 = outPtr;
inPtr1 = (void *) ((char *) inPtr + self->GetActiveComponent()*scalarSize);
for (idxZ = 0; idxZ < extZ; idxZ++)
{
for (idxY = 0; !self->AbortExecute && idxY < extY; idxY++)
{
if (!id)
{
if (!(count%target))
{
self->UpdateProgress(count/(50.0*target));
}
count++;
}
lookupTable->MapScalarsThroughTable2(inPtr1,outPtr1,
dataType,extX,numberOfComponents,
outputFormat);
if (self->GetPassAlphaToOutput() &&
dataType == VTK_UNSIGNED_CHAR && numberOfComponents > 1 &&
(outputFormat == VTK_RGBA || outputFormat == VTK_LUMINANCE_ALPHA))
{
unsigned char *outPtr2 = outPtr1 + numberOfOutputComponents - 1;
unsigned char *inPtr2 = (unsigned char *)inPtr1
- self->GetActiveComponent()*scalarSize
+ numberOfComponents - 1;
for (int i = 0; i < extX; i++)
{
*outPtr2 = (*outPtr2 * *inPtr2)/255;
outPtr2 += numberOfOutputComponents;
inPtr2 += numberOfComponents;
}
}
outPtr1 += outIncY + extX*numberOfOutputComponents;
inPtr1 = (void *) ((char *) inPtr1 + inIncY + rowLength);
}
outPtr1 += outIncZ;
inPtr1 = (void *) ((char *) inPtr1 + inIncZ);
}
}
//----------------------------------------------------------------------------
// This method is passed a input and output data, and executes the filter
// algorithm to fill the output from the input.
void vtkImageMapToColors::ThreadedExecute(vtkImageData *inData,
vtkImageData *outData,
int outExt[6], int id)
{
void *inPtr = inData->GetScalarPointerForExtent(outExt);
void *outPtr = outData->GetScalarPointerForExtent(outExt);
vtkImageMapToColorsExecute(this, inData, inPtr,
outData, (unsigned char *)outPtr, outExt, id);
}
void vtkImageMapToColors::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "OutputFormat: " <<
(this->OutputFormat == VTK_RGBA ? "RGBA" :
(this->OutputFormat == VTK_RGB ? "RGB" :
(this->OutputFormat == VTK_LUMINANCE_ALPHA ? "LuminanceAlpha" :
(this->OutputFormat == VTK_LUMINANCE ? "Luminance" : "Unknown"))))
<< "\n";
os << indent << "ActiveComponent: " << this->ActiveComponent << "\n";
os << indent << "PassAlphaToOutput: " << this->PassAlphaToOutput << "\n";
os << indent << "LookupTable: " << this->LookupTable << "\n";
if (this->LookupTable)
{
this->LookupTable->PrintSelf(os,indent.GetNextIndent());
}
}
<|endoftext|> |
<commit_before>#ifndef VIENNAGRID_STORAGE_RANGE_HPP
#define VIENNAGRID_STORAGE_RANGE_HPP
/* =======================================================================
Copyright (c) 2011-2013, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include "viennagrid/forwards.hpp"
namespace viennagrid
{
namespace storage
{
template<typename container_type>
class container_range_wrapper
{
friend class container_range_wrapper<const container_type>;
public:
typedef container_type base_container_type;
typedef typename container_type::size_type size_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::pointer pointer;
typedef typename container_type::const_pointer const_pointer;
typedef typename container_type::iterator iterator;
typedef typename container_type::const_iterator const_iterator;
typedef typename container_type::reverse_iterator reverse_iterator;
typedef typename container_type::const_reverse_iterator const_reverse_iterator;
container_range_wrapper(container_type & container_) : container(&container_) {}
template<typename element_domain_segment_config_or_something_like_that>
container_range_wrapper( viennagrid::element_range_proxy<element_domain_segment_config_or_something_like_that> range_proxy )
{ *this = elements< value_type >( range_proxy() ); }
template<typename element_domain_segment_config_or_something_like_that>
container_range_wrapper operator=( viennagrid::element_range_proxy<element_domain_segment_config_or_something_like_that> range_proxy )
{
*this = elements< value_type >( range_proxy() );
return *this;
}
iterator begin() { return container->begin(); }
const_iterator begin() const { return container->begin(); }
iterator end() { return container->end(); }
const_iterator end() const { return container->end(); }
reverse_iterator rbegin() { return container->rbegin(); }
const_reverse_iterator rbegin() const { return container->rbegin(); }
reverse_iterator rend() { return container->rend(); }
const_reverse_iterator rend() const { return container->rend(); }
reference front() { return container->front(); }
const_reference front() const { return container->front(); }
reference back() { return container->back(); }
const_reference back() const { return container->back(); }
reference operator[] (size_type index) { return (*container)[index]; }
const_reference operator[] (size_type index) const { return (*container)[index]; }
bool empty() const { return container->empty(); }
size_type size() const { return container->size(); }
typedef typename container_type::handle_type handle_type;
typedef typename container_type::const_handle_type const_handle_type;
iterator erase( iterator pos ) { return container->erase( pos ); }
handle_type handle_at(std::size_t pos)
{ return viennagrid::advance(begin(), pos).handle(); }
const_handle_type handle_at(std::size_t pos) const
{ return viennagrid::advance(begin(), pos).handle(); }
void erase_handle(handle_type handle)
{ container->erase_handle(handle); }
void insert_unique_handle(handle_type handle)
{ container->insert_unique_handle(handle); }
void insert_handle(handle_type handle)
{ container->insert_handle(handle); }
void set_handle_at(handle_type handle, std::size_t pos)
{ container->set_handle(handle, pos); }
container_type * get_base_container() { return container; }
const container_type * get_base_container() const { return container; }
private:
container_type * container;
};
template<typename container_type>
class container_range_wrapper<const container_type>
{
public:
typedef const container_type base_container_type;
typedef typename container_type::size_type size_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::const_reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::const_pointer pointer;
typedef typename container_type::const_pointer const_pointer;
typedef typename container_type::const_iterator iterator;
typedef typename container_type::const_iterator const_iterator;
typedef typename container_type::const_reverse_iterator reverse_iterator;
typedef typename container_type::const_reverse_iterator const_reverse_iterator;
container_range_wrapper(const container_type & _container) : container(&_container) {}
container_range_wrapper(const container_range_wrapper<container_type> & rhs) : container(rhs.container) {}
template<typename element_domain_segment_config_or_something_like_that>
container_range_wrapper( const viennagrid::element_range_proxy<element_domain_segment_config_or_something_like_that> range_proxy )
{ *this = elements< value_type >( range_proxy() ); }
template<typename element_domain_segment_config_or_something_like_that>
container_range_wrapper( const viennagrid::element_range_proxy<const element_domain_segment_config_or_something_like_that> range_proxy )
{ *this = elements< value_type >( range_proxy() ); }
template<typename element_domain_segment_config_or_something_like_that>
container_range_wrapper operator=( viennagrid::element_range_proxy<element_domain_segment_config_or_something_like_that> range_proxy )
{
*this = elements< value_type >( range_proxy() );
return *this;
}
template<typename element_domain_segment_config_or_something_like_that>
container_range_wrapper operator=( viennagrid::element_range_proxy<const element_domain_segment_config_or_something_like_that> range_proxy )
{
*this = elements< value_type >( range_proxy() );
return *this;
}
iterator begin() { return container->begin(); }
const_iterator begin() const { return container->begin(); }
iterator end() { return container->end(); }
const_iterator end() const { return container->end(); }
reverse_iterator rbegin() { return container->rbegin(); }
const_reverse_iterator rbegin() const { return container->rbegin(); }
reverse_iterator rend() { return container->rend(); }
const_reverse_iterator rend() const { return container->rend(); }
reference front() { return container->front(); }
const_reference front() const { return container->front(); }
reference back() { return container->back(); }
const_reference back() const { return container->back(); }
reference operator[] (size_type index) { return (*container)[index]; }
const_reference operator[] (size_type index) const { return (*container)[index]; }
bool empty() const { return container->empty(); }
size_type size() const { return container->size(); }
typedef typename container_type::const_handle_type handle_type;
typedef typename container_type::const_handle_type const_handle_type;
handle_type handle_at(std::size_t pos)
{ return viennagrid::advance(begin(), pos).handle(); }
const_handle_type handle_at(std::size_t pos) const
{ return viennagrid::advance(begin(), pos).handle(); }
const container_type * get_base_container() const { return container; }
private:
const container_type * container;
};
template<typename iterator_type>
class forward_iterator_range
{
public:
forward_iterator_range(iterator_type _first, iterator_type _last) : first(_first), last(_last) {}
typedef typename iterator_type::T value_type;
typedef typename iterator_type::Reference reference;
typedef const typename iterator_type::Reference const_reference;
typedef typename iterator_type::Pointer pointer;
typedef const typename iterator_type::Pointer const_pointer;
typedef iterator_type iterator;
typedef const iterator_type const_iterator;
iterator begin() { return first; }
const_iterator begin() const { return first; }
iterator end() { return last; }
const_iterator end() const { return last; }
reference front() { return *first; }
const_reference front() const { return *first; }
reference back() { iterator_type tmp = last; return *(--tmp); }
const_reference back() const { iterator_type tmp = last; return *(--tmp); }
bool empty() const { return first == last; }
private:
iterator_type first;
iterator_type last;
};
}
}
#endif
<commit_msg>Tempalte argument names changed<commit_after>#ifndef VIENNAGRID_STORAGE_RANGE_HPP
#define VIENNAGRID_STORAGE_RANGE_HPP
/* =======================================================================
Copyright (c) 2011-2013, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include "viennagrid/forwards.hpp"
namespace viennagrid
{
namespace storage
{
template<typename container_type>
class container_range_wrapper
{
friend class container_range_wrapper<const container_type>;
public:
typedef container_type base_container_type;
typedef typename container_type::size_type size_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::pointer pointer;
typedef typename container_type::const_pointer const_pointer;
typedef typename container_type::iterator iterator;
typedef typename container_type::const_iterator const_iterator;
typedef typename container_type::reverse_iterator reverse_iterator;
typedef typename container_type::const_reverse_iterator const_reverse_iterator;
container_range_wrapper(container_type & container_) : container(&container_) {}
template<typename SomethingT>
container_range_wrapper( viennagrid::element_range_proxy<SomethingT> range_proxy )
{ *this = elements< value_type >( range_proxy() ); }
template<typename SomethingT>
container_range_wrapper operator=( viennagrid::element_range_proxy<SomethingT> range_proxy )
{
*this = elements< value_type >( range_proxy() );
return *this;
}
iterator begin() { return container->begin(); }
const_iterator begin() const { return container->begin(); }
iterator end() { return container->end(); }
const_iterator end() const { return container->end(); }
reverse_iterator rbegin() { return container->rbegin(); }
const_reverse_iterator rbegin() const { return container->rbegin(); }
reverse_iterator rend() { return container->rend(); }
const_reverse_iterator rend() const { return container->rend(); }
reference front() { return container->front(); }
const_reference front() const { return container->front(); }
reference back() { return container->back(); }
const_reference back() const { return container->back(); }
reference operator[] (size_type index) { return (*container)[index]; }
const_reference operator[] (size_type index) const { return (*container)[index]; }
bool empty() const { return container->empty(); }
size_type size() const { return container->size(); }
typedef typename container_type::handle_type handle_type;
typedef typename container_type::const_handle_type const_handle_type;
iterator erase( iterator pos ) { return container->erase( pos ); }
handle_type handle_at(std::size_t pos)
{ return viennagrid::advance(begin(), pos).handle(); }
const_handle_type handle_at(std::size_t pos) const
{ return viennagrid::advance(begin(), pos).handle(); }
void erase_handle(handle_type handle)
{ container->erase_handle(handle); }
void insert_unique_handle(handle_type handle)
{ container->insert_unique_handle(handle); }
void insert_handle(handle_type handle)
{ container->insert_handle(handle); }
void set_handle_at(handle_type handle, std::size_t pos)
{ container->set_handle(handle, pos); }
container_type * get_base_container() { return container; }
const container_type * get_base_container() const { return container; }
private:
container_type * container;
};
template<typename container_type>
class container_range_wrapper<const container_type>
{
public:
typedef const container_type base_container_type;
typedef typename container_type::size_type size_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::const_reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::const_pointer pointer;
typedef typename container_type::const_pointer const_pointer;
typedef typename container_type::const_iterator iterator;
typedef typename container_type::const_iterator const_iterator;
typedef typename container_type::const_reverse_iterator reverse_iterator;
typedef typename container_type::const_reverse_iterator const_reverse_iterator;
container_range_wrapper(const container_type & _container) : container(&_container) {}
container_range_wrapper(const container_range_wrapper<container_type> & rhs) : container(rhs.container) {}
template<typename SomethingT>
container_range_wrapper( viennagrid::element_range_proxy<SomethingT> range_proxy )
{ *this = elements< value_type >( range_proxy() ); }
template<typename SomethingT>
container_range_wrapper( viennagrid::element_range_proxy<const SomethingT> range_proxy )
{ *this = elements< value_type >( range_proxy() ); }
template<typename SomethingT>
container_range_wrapper operator=( viennagrid::element_range_proxy<SomethingT> range_proxy )
{
*this = elements< value_type >( range_proxy() );
return *this;
}
template<typename SomethingT>
container_range_wrapper operator=( viennagrid::element_range_proxy<const SomethingT> range_proxy )
{
*this = elements< value_type >( range_proxy() );
return *this;
}
iterator begin() { return container->begin(); }
const_iterator begin() const { return container->begin(); }
iterator end() { return container->end(); }
const_iterator end() const { return container->end(); }
reverse_iterator rbegin() { return container->rbegin(); }
const_reverse_iterator rbegin() const { return container->rbegin(); }
reverse_iterator rend() { return container->rend(); }
const_reverse_iterator rend() const { return container->rend(); }
reference front() { return container->front(); }
const_reference front() const { return container->front(); }
reference back() { return container->back(); }
const_reference back() const { return container->back(); }
reference operator[] (size_type index) { return (*container)[index]; }
const_reference operator[] (size_type index) const { return (*container)[index]; }
bool empty() const { return container->empty(); }
size_type size() const { return container->size(); }
typedef typename container_type::const_handle_type handle_type;
typedef typename container_type::const_handle_type const_handle_type;
handle_type handle_at(std::size_t pos)
{ return viennagrid::advance(begin(), pos).handle(); }
const_handle_type handle_at(std::size_t pos) const
{ return viennagrid::advance(begin(), pos).handle(); }
const container_type * get_base_container() const { return container; }
private:
const container_type * container;
};
template<typename iterator_type>
class forward_iterator_range
{
public:
forward_iterator_range(iterator_type _first, iterator_type _last) : first(_first), last(_last) {}
typedef typename iterator_type::T value_type;
typedef typename iterator_type::Reference reference;
typedef const typename iterator_type::Reference const_reference;
typedef typename iterator_type::Pointer pointer;
typedef const typename iterator_type::Pointer const_pointer;
typedef iterator_type iterator;
typedef const iterator_type const_iterator;
iterator begin() { return first; }
const_iterator begin() const { return first; }
iterator end() { return last; }
const_iterator end() const { return last; }
reference front() { return *first; }
const_reference front() const { return *first; }
reference back() { iterator_type tmp = last; return *(--tmp); }
const_reference back() const { iterator_type tmp = last; return *(--tmp); }
bool empty() const { return first == last; }
private:
iterator_type first;
iterator_type last;
};
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef VIENNAGRID_STORAGE_RANGE_HPP
#define VIENNAGRID_STORAGE_RANGE_HPP
namespace viennagrid
{
namespace storage
{
template<typename container_type>
class container_range_wrapper
{
public:
container_range_wrapper(container_type & _container) : container(_container) {}
typedef typename container_type::size_type size_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::pointer pointer;
typedef typename container_type::const_pointer const_pointer;
typedef typename container_type::iterator iterator;
typedef typename container_type::const_iterator const_iterator;
typedef typename container_type::reverse_iterator reverse_iterator;
typedef typename container_type::const_reverse_iterator const_reverse_iterator;
iterator begin() { return container.begin(); }
const_iterator begin() const { return container.begin(); }
iterator end() { return container.end(); }
const_iterator end() const { return container.end(); }
reverse_iterator rbegin() { return container.rbegin(); }
const_reverse_iterator rbegin() const { return container.rbegin(); }
reverse_iterator rend() { return container.rend(); }
const_reverse_iterator rend() const { return container.rend(); }
reference front() { return container.front(); }
const_reference front() const { return container.front(); }
reference back() { return container.back(); }
const_reference back() const { return container.back(); }
reference operator[] (size_type index) { return container[index]; }
const_reference operator[] (size_type index) const { return container[index]; }
bool empty() const { return container.empty(); }
size_type size() const { return container.size(); }
private:
container_type & container;
};
template<typename iterator_type>
class forward_iterator_range
{
public:
forward_iterator_range(iterator_type _first, iterator_type _last) : first(_first), last(_last) {}
typedef typename iterator_type::T value_type;
typedef typename iterator_type::Reference reference;
typedef const typename iterator_type::Reference const_reference;
typedef typename iterator_type::Pointer pointer;
typedef const typename iterator_type::Pointer const_pointer;
typedef iterator_type iterator;
typedef const iterator_type const_iterator;
iterator begin() { return first; }
const_iterator begin() const { return first; }
iterator end() { return last; }
const_iterator end() const { return last; }
reference front() { return *first; }
const_reference front() const { return *first; }
reference back() { iterator_type tmp = last; return *(--tmp); }
const_reference back() const { iterator_type tmp = last; return *(--tmp); }
bool empty() const { return first == last; }
private:
iterator_type first;
iterator_type last;
};
}
}
#endif
<commit_msg>added wrapper for const container<commit_after>#ifndef VIENNAGRID_STORAGE_RANGE_HPP
#define VIENNAGRID_STORAGE_RANGE_HPP
namespace viennagrid
{
namespace storage
{
template<typename container_type>
class container_range_wrapper
{
friend class container_range_wrapper<const container_type>;
public:
container_range_wrapper(container_type & _container) : container(_container) {}
typedef typename container_type::size_type size_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::pointer pointer;
typedef typename container_type::const_pointer const_pointer;
typedef typename container_type::iterator iterator;
typedef typename container_type::const_iterator const_iterator;
typedef typename container_type::reverse_iterator reverse_iterator;
typedef typename container_type::const_reverse_iterator const_reverse_iterator;
iterator begin() { return container.begin(); }
const_iterator begin() const { return container.begin(); }
iterator end() { return container.end(); }
const_iterator end() const { return container.end(); }
reverse_iterator rbegin() { return container.rbegin(); }
const_reverse_iterator rbegin() const { return container.rbegin(); }
reverse_iterator rend() { return container.rend(); }
const_reverse_iterator rend() const { return container.rend(); }
reference front() { return container.front(); }
const_reference front() const { return container.front(); }
reference back() { return container.back(); }
const_reference back() const { return container.back(); }
reference operator[] (size_type index) { return container[index]; }
const_reference operator[] (size_type index) const { return container[index]; }
bool empty() const { return container.empty(); }
size_type size() const { return container.size(); }
private:
container_type & container;
};
template<typename container_type>
class container_range_wrapper<const container_type>
{
public:
container_range_wrapper(const container_type & _container) : container(_container) {}
container_range_wrapper(const container_range_wrapper<container_type> & rhs) : container(rhs.container) {}
typedef typename container_type::size_type size_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::pointer pointer;
typedef typename container_type::const_pointer const_pointer;
typedef typename container_type::const_iterator iterator;
typedef typename container_type::const_iterator const_iterator;
typedef typename container_type::const_reverse_iterator reverse_iterator;
typedef typename container_type::const_reverse_iterator const_reverse_iterator;
iterator begin() { return container.begin(); }
const_iterator begin() const { return container.begin(); }
iterator end() { return container.end(); }
const_iterator end() const { return container.end(); }
reverse_iterator rbegin() { return container.rbegin(); }
const_reverse_iterator rbegin() const { return container.rbegin(); }
reverse_iterator rend() { return container.rend(); }
const_reverse_iterator rend() const { return container.rend(); }
reference front() { return container.front(); }
const_reference front() const { return container.front(); }
reference back() { return container.back(); }
const_reference back() const { return container.back(); }
reference operator[] (size_type index) { return container[index]; }
const_reference operator[] (size_type index) const { return container[index]; }
bool empty() const { return container.empty(); }
size_type size() const { return container.size(); }
private:
const container_type & container;
};
template<typename iterator_type>
class forward_iterator_range
{
public:
forward_iterator_range(iterator_type _first, iterator_type _last) : first(_first), last(_last) {}
typedef typename iterator_type::T value_type;
typedef typename iterator_type::Reference reference;
typedef const typename iterator_type::Reference const_reference;
typedef typename iterator_type::Pointer pointer;
typedef const typename iterator_type::Pointer const_pointer;
typedef iterator_type iterator;
typedef const iterator_type const_iterator;
iterator begin() { return first; }
const_iterator begin() const { return first; }
iterator end() { return last; }
const_iterator end() const { return last; }
reference front() { return *first; }
const_reference front() const { return *first; }
reference back() { iterator_type tmp = last; return *(--tmp); }
const_reference back() const { iterator_type tmp = last; return *(--tmp); }
bool empty() const { return first == last; }
private:
iterator_type first;
iterator_type last;
};
}
}
#endif
<|endoftext|> |
<commit_before>#include "trace_manager.h"
#include "trace_thread.h"
#include "simulator.h"
#include "thread_manager.h"
#include "hooks_manager.h"
#include "config.hpp"
#include <sys/types.h>
#include <sys/stat.h>
TraceManager::TraceManager()
: m_threads(0)
, m_num_threads_running(0)
, m_done(0)
, m_stop_with_first_app(Sim()->getCfg()->getBool("traceinput/stop_with_first_app"))
, m_app_restart(Sim()->getCfg()->getBool("traceinput/restart_apps"))
, m_emulate_syscalls(Sim()->getCfg()->getBool("traceinput/emulate_syscalls"))
, m_num_apps(Sim()->getCfg()->getInt("traceinput/num_apps"))
, m_num_apps_nonfinish(m_num_apps)
, m_app_info(m_num_apps)
{
m_trace_prefix = Sim()->getCfg()->getString("traceinput/trace_prefix");
if (m_emulate_syscalls)
{
if (m_trace_prefix == "")
{
std::cerr << "Error: a trace prefix is required when emulating syscalls." << std::endl;
exit(1);
}
}
if (m_trace_prefix != "")
{
for (UInt32 i = 0 ; i < m_num_apps ; i++ )
{
m_tracefiles.push_back(getFifoName(i, 0, false /*response*/, false /*create*/));
m_responsefiles.push_back(getFifoName(i, 0, true /*response*/, false /*create*/));
}
}
else
{
for (UInt32 i = 0 ; i < m_num_apps ; i++ )
{
m_tracefiles.push_back(Sim()->getCfg()->getString("traceinput/thread_" + itostr(i)));
}
}
}
void TraceManager::init()
{
for (UInt32 i = 0 ; i < m_num_apps ; i++ )
{
newThread(i /*app_id*/, true /*first*/, false /*spawn*/);
}
}
String TraceManager::getFifoName(app_id_t app_id, UInt64 thread_num, bool response, bool create)
{
String filename = m_trace_prefix + (response ? "_response" : "") + ".app" + itostr(app_id) + ".th" + itostr(thread_num) + ".sift";
if (create)
mkfifo(filename.c_str(), 0600);
return filename;
}
thread_id_t TraceManager::createThread(app_id_t app_id)
{
// External version: acquire lock first
ScopedLock sl(m_lock);
return newThread(app_id, false /*first*/, true /*spawn*/);
}
thread_id_t TraceManager::newThread(app_id_t app_id, bool first, bool spawn)
{
// Internal version: assume we're already holding the lock
assert(static_cast<decltype(app_id)>(m_num_apps) > app_id);
String tracefile = "", responsefile = "";
if (first)
{
m_app_info[app_id].num_threads = 1;
m_app_info[app_id].thread_count = 1;
Sim()->getHooksManager()->callHooks(HookType::HOOK_APPLICATION_START, (UInt64)app_id);
tracefile = m_tracefiles[app_id];
if (m_responsefiles.size())
responsefile = m_responsefiles[app_id];
}
else
{
m_app_info[app_id].num_threads++;
int thread_num = m_app_info[app_id].thread_count++;
tracefile = getFifoName(app_id, thread_num, false /*response*/, true /*create*/);
if (m_responsefiles.size())
responsefile = getFifoName(app_id, thread_num, true /*response*/, true /*create*/);
}
m_num_threads_running++;
Thread *thread = Sim()->getThreadManager()->createThread(app_id);
TraceThread *tthread = new TraceThread(thread, tracefile, responsefile, app_id, first ? false : true /*cleaup*/);
m_threads.push_back(tthread);
if (spawn)
{
/* First thread of each app spawns only when initialization is done,
next threads are created once we're running so spawn them right away. */
tthread->spawn(NULL);
}
return thread->getId();
}
void TraceManager::signalDone(Thread *thread, bool aborted)
{
ScopedLock sl(m_lock);
app_id_t app_id = thread->getAppId();
m_app_info[app_id].num_threads--;
if (!aborted)
{
if (m_app_info[app_id].num_threads == 0)
{
m_app_info[app_id].num_runs++;
Sim()->getHooksManager()->callHooks(HookType::HOOK_APPLICATION_EXIT, (UInt64)app_id);
if (m_app_info[app_id].num_runs == 1)
m_num_apps_nonfinish--;
if (m_stop_with_first_app)
{
// First app has ended: stop
stop();
}
else if (m_num_apps_nonfinish == 0)
{
// All apps have completed at least once: stop
stop();
}
else
{
// Stop condition not met. Restart app?
if (m_app_restart)
{
newThread(app_id, true /*first*/, true /*spawn*/);
}
}
}
}
m_num_threads_running--;
m_done.signal();
}
TraceManager::~TraceManager()
{
for(std::vector<TraceThread *>::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
delete *it;
}
void TraceManager::start()
{
for(std::vector<TraceThread *>::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
(*it)->spawn(NULL);
}
void TraceManager::stop()
{
for(std::vector<TraceThread *>::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
(*it)->stop();
}
void TraceManager::wait()
{
while(m_num_threads_running)
{
// Wait until a thread says it's done
m_done.wait();
}
}
void TraceManager::run()
{
start();
wait();
}
UInt64 TraceManager::getProgressExpect()
{
return 1000000;
}
UInt64 TraceManager::getProgressValue()
{
UInt64 value = 0;
for(std::vector<TraceThread *>::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
{
uint64_t expect = (*it)->getProgressExpect();
if (expect)
value = std::max(value, 1000000 * (*it)->getProgressValue() / expect);
}
return value;
}
// This should only be called when already holding the thread lock to prevent migrations while we scan for a core id match
void TraceManager::accessMemory(int core_id, Core::lock_signal_t lock_signal, Core::mem_op_t mem_op_type, IntPtr d_addr, char* data_buffer, UInt32 data_size)
{
for(std::vector<TraceThread *>::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
{
TraceThread *tthread = *it;
assert(tthread != NULL);
if (tthread->getThread() && tthread->getThread()->getCore() && core_id == tthread->getThread()->getCore()->getId())
{
tthread->handleAccessMemory(lock_signal, mem_op_type, d_addr, data_buffer, data_size);
return;
}
}
LOG_PRINT_ERROR("Unable to find core %d", core_id);
}
<commit_msg>[trace] When ending a trace-driven simulation, avoid deadlock by not waiting for all threads to end as they may be blocked (waiting in the barrier, SIFT reader, etc.)<commit_after>#include "trace_manager.h"
#include "trace_thread.h"
#include "simulator.h"
#include "thread_manager.h"
#include "hooks_manager.h"
#include "config.hpp"
#include <sys/types.h>
#include <sys/stat.h>
TraceManager::TraceManager()
: m_threads(0)
, m_num_threads_running(0)
, m_done(0)
, m_stop_with_first_app(Sim()->getCfg()->getBool("traceinput/stop_with_first_app"))
, m_app_restart(Sim()->getCfg()->getBool("traceinput/restart_apps"))
, m_emulate_syscalls(Sim()->getCfg()->getBool("traceinput/emulate_syscalls"))
, m_num_apps(Sim()->getCfg()->getInt("traceinput/num_apps"))
, m_num_apps_nonfinish(m_num_apps)
, m_app_info(m_num_apps)
{
m_trace_prefix = Sim()->getCfg()->getString("traceinput/trace_prefix");
if (m_emulate_syscalls)
{
if (m_trace_prefix == "")
{
std::cerr << "Error: a trace prefix is required when emulating syscalls." << std::endl;
exit(1);
}
}
if (m_trace_prefix != "")
{
for (UInt32 i = 0 ; i < m_num_apps ; i++ )
{
m_tracefiles.push_back(getFifoName(i, 0, false /*response*/, false /*create*/));
m_responsefiles.push_back(getFifoName(i, 0, true /*response*/, false /*create*/));
}
}
else
{
for (UInt32 i = 0 ; i < m_num_apps ; i++ )
{
m_tracefiles.push_back(Sim()->getCfg()->getString("traceinput/thread_" + itostr(i)));
}
}
}
void TraceManager::init()
{
for (UInt32 i = 0 ; i < m_num_apps ; i++ )
{
newThread(i /*app_id*/, true /*first*/, false /*spawn*/);
}
}
String TraceManager::getFifoName(app_id_t app_id, UInt64 thread_num, bool response, bool create)
{
String filename = m_trace_prefix + (response ? "_response" : "") + ".app" + itostr(app_id) + ".th" + itostr(thread_num) + ".sift";
if (create)
mkfifo(filename.c_str(), 0600);
return filename;
}
thread_id_t TraceManager::createThread(app_id_t app_id)
{
// External version: acquire lock first
ScopedLock sl(m_lock);
return newThread(app_id, false /*first*/, true /*spawn*/);
}
thread_id_t TraceManager::newThread(app_id_t app_id, bool first, bool spawn)
{
// Internal version: assume we're already holding the lock
assert(static_cast<decltype(app_id)>(m_num_apps) > app_id);
String tracefile = "", responsefile = "";
if (first)
{
m_app_info[app_id].num_threads = 1;
m_app_info[app_id].thread_count = 1;
Sim()->getHooksManager()->callHooks(HookType::HOOK_APPLICATION_START, (UInt64)app_id);
tracefile = m_tracefiles[app_id];
if (m_responsefiles.size())
responsefile = m_responsefiles[app_id];
}
else
{
m_app_info[app_id].num_threads++;
int thread_num = m_app_info[app_id].thread_count++;
tracefile = getFifoName(app_id, thread_num, false /*response*/, true /*create*/);
if (m_responsefiles.size())
responsefile = getFifoName(app_id, thread_num, true /*response*/, true /*create*/);
}
m_num_threads_running++;
Thread *thread = Sim()->getThreadManager()->createThread(app_id);
TraceThread *tthread = new TraceThread(thread, tracefile, responsefile, app_id, first ? false : true /*cleaup*/);
m_threads.push_back(tthread);
if (spawn)
{
/* First thread of each app spawns only when initialization is done,
next threads are created once we're running so spawn them right away. */
tthread->spawn(NULL);
}
return thread->getId();
}
void TraceManager::signalDone(Thread *thread, bool aborted)
{
ScopedLock sl(m_lock);
app_id_t app_id = thread->getAppId();
m_app_info[app_id].num_threads--;
if (!aborted)
{
if (m_app_info[app_id].num_threads == 0)
{
m_app_info[app_id].num_runs++;
Sim()->getHooksManager()->callHooks(HookType::HOOK_APPLICATION_EXIT, (UInt64)app_id);
if (m_app_info[app_id].num_runs == 1)
m_num_apps_nonfinish--;
if (m_stop_with_first_app)
{
// First app has ended: stop
stop();
}
else if (m_num_apps_nonfinish == 0)
{
// All apps have completed at least once: stop
stop();
}
else
{
// Stop condition not met. Restart app?
if (m_app_restart)
{
newThread(app_id, true /*first*/, true /*spawn*/);
}
}
}
}
m_num_threads_running--;
}
TraceManager::~TraceManager()
{
for(std::vector<TraceThread *>::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
delete *it;
}
void TraceManager::start()
{
for(std::vector<TraceThread *>::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
(*it)->spawn(NULL);
}
void TraceManager::stop()
{
// Signal threads to stop.
for(std::vector<TraceThread *>::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
(*it)->stop();
// Give threads some time to end.
sleep(1);
// Some threads may be blocked (barrier, SIFT reader, etc.). Don't wait for them or we'll deadlock.
m_done.signal();
}
void TraceManager::wait()
{
m_done.wait();
}
void TraceManager::run()
{
start();
wait();
}
UInt64 TraceManager::getProgressExpect()
{
return 1000000;
}
UInt64 TraceManager::getProgressValue()
{
UInt64 value = 0;
for(std::vector<TraceThread *>::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
{
uint64_t expect = (*it)->getProgressExpect();
if (expect)
value = std::max(value, 1000000 * (*it)->getProgressValue() / expect);
}
return value;
}
// This should only be called when already holding the thread lock to prevent migrations while we scan for a core id match
void TraceManager::accessMemory(int core_id, Core::lock_signal_t lock_signal, Core::mem_op_t mem_op_type, IntPtr d_addr, char* data_buffer, UInt32 data_size)
{
for(std::vector<TraceThread *>::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
{
TraceThread *tthread = *it;
assert(tthread != NULL);
if (tthread->getThread() && tthread->getThread()->getCore() && core_id == tthread->getThread()->getCore()->getId())
{
tthread->handleAccessMemory(lock_signal, mem_op_type, d_addr, data_buffer, data_size);
return;
}
}
LOG_PRINT_ERROR("Unable to find core %d", core_id);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkBivariateStatisticsAlgorithm.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkBivariateStatisticsAlgorithm.h"
#include "vtkBivariateStatisticsAlgorithmPrivate.h"
#include "vtkDoubleArray.h"
#include "vtkObjectFactory.h"
#include "vtkStdString.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"
#include <vtkstd/set>
#include <vtksys/ios/sstream>
vtkCxxRevisionMacro(vtkBivariateStatisticsAlgorithm, "1.14");
// ----------------------------------------------------------------------
vtkBivariateStatisticsAlgorithm::vtkBivariateStatisticsAlgorithm()
{
this->NumberOfVariables = 2;
this->Internals = new vtkBivariateStatisticsAlgorithmPrivate;
}
// ----------------------------------------------------------------------
vtkBivariateStatisticsAlgorithm::~vtkBivariateStatisticsAlgorithm()
{
delete this->Internals;
}
// ----------------------------------------------------------------------
void vtkBivariateStatisticsAlgorithm::PrintSelf( ostream &os, vtkIndent indent )
{
this->Superclass::PrintSelf( os, indent );
os << indent << "NumberOfVariables: " << this->NumberOfVariables << endl;
}
// ----------------------------------------------------------------------
void vtkBivariateStatisticsAlgorithm::ResetColumnPairs()
{
this->Internals->Selection.clear();
this->Modified();
}
// ----------------------------------------------------------------------
void vtkBivariateStatisticsAlgorithm::AddColumnPair( const char* namColX, const char* namColY )
{
vtkstd::pair<vtkStdString,vtkStdString> namPair( namColX, namColY );
this->Internals->Selection.insert( namPair );
this->Modified();
}
// ----------------------------------------------------------------------
void vtkBivariateStatisticsAlgorithm::RemoveColumnPair( const char* namColX, const char* namColY )
{
vtkstd::pair<vtkStdString,vtkStdString> namPair( namColX, namColY );
this->Internals->Selection.erase( namPair );
this->Modified();
}
// ----------------------------------------------------------------------
void vtkBivariateStatisticsAlgorithm::SetColumnStatus( const char* namCol, int status )
{
if( status )
{
this->Internals->BufferedColumns.insert( namCol );
}
else
{
this->Internals->BufferedColumns.erase( namCol );
}
this->Internals->Selection.clear();
int i = 0;
for ( vtkstd::set<vtkStdString>::iterator ait = this->Internals->BufferedColumns.begin();
ait != this->Internals->BufferedColumns.end(); ++ ait, ++ i )
{
int j = 0;
for ( vtkstd::set<vtkStdString>::iterator bit = this->Internals->BufferedColumns.begin();
j < i ; ++ bit, ++ j )
{
vtkstd::pair<vtkStdString,vtkStdString> namPair( *bit, *ait );
this->Internals->Selection.insert( namPair );
}
}
this->Modified();
}
// ----------------------------------------------------------------------
void vtkBivariateStatisticsAlgorithm::Assess( vtkTable* inData,
vtkDataObject* inMetaDO,
vtkTable* outData,
vtkDataObject* vtkNotUsed( outMeta ) )
{
vtkTable* inMeta = vtkTable::SafeDownCast( inMetaDO );
if ( ! inMeta )
{
return;
}
if ( ! inData || inData->GetNumberOfColumns() <= 0 )
{
return;
}
vtkIdType nRowD = inData->GetNumberOfRows();
if ( nRowD <= 0 )
{
return;
}
vtkIdType nColP;
if ( this->AssessParameters )
{
nColP = this->AssessParameters->GetNumberOfValues();
if ( inMeta->GetNumberOfColumns() - this->NumberOfVariables < nColP )
{
vtkWarningMacro( "Parameter table has "
<< inMeta->GetNumberOfColumns() - this->NumberOfVariables
<< " parameters < "
<< nColP
<< " columns. Doing nothing." );
return;
}
}
if ( ! inMeta->GetNumberOfRows() )
{
return;
}
// Loop over pairs of columns of interest
for ( vtkstd::set<vtkstd::pair<vtkStdString,vtkStdString> >::iterator it = this->Internals->Selection.begin();
it != this->Internals->Selection.end(); ++ it )
{
vtkStdString varNameX = it->first;
if ( ! inData->GetColumnByName( varNameX ) )
{
vtkWarningMacro( "InData table does not have a column "
<< varNameX.c_str()
<< ". Ignoring this pair." );
continue;
}
vtkStdString varNameY = it->second;
if ( ! inData->GetColumnByName( varNameY ) )
{
vtkWarningMacro( "InData table does not have a column "
<< varNameY.c_str()
<< ". Ignoring this pair." );
continue;
}
vtkStringArray* varNames = vtkStringArray::New();
varNames->SetNumberOfValues( this->NumberOfVariables );
varNames->SetValue( 0, varNameX );
varNames->SetValue( 1, varNameY );
// Store names to be able to use SetValueByName, and create the outData columns
int nv = this->AssessNames->GetNumberOfValues();
vtkStdString* names = new vtkStdString[nv];
for ( int v = 0; v < nv; ++ v )
{
vtksys_ios::ostringstream assessColName;
assessColName << this->AssessNames->GetValue( v )
<< "("
<< varNameX
<< ","
<< varNameY
<< ")";
names[v] = assessColName.str().c_str();
vtkDoubleArray* assessValues = vtkDoubleArray::New();
assessValues->SetName( names[v] );
assessValues->SetNumberOfTuples( nRowD );
outData->AddColumn( assessValues );
assessValues->Delete();
}
// Select assess functor
AssessFunctor* dfunc;
this->SelectAssessFunctor( outData,
inMeta,
varNames,
dfunc );
if ( ! dfunc )
{
// Functor selection did not work. Do nothing.
vtkWarningMacro( "AssessFunctors could not be allocated for column pair ("
<< varNameX.c_str()
<< ","
<< varNameY.c_str()
<< "). Ignoring it." );
delete [] names;
continue;
}
else
{
// Assess each entry of the column
vtkVariantArray* assessResult = vtkVariantArray::New();
for ( vtkIdType r = 0; r < nRowD; ++ r )
{
(*dfunc)( assessResult, r );
for ( int v = 0; v < nv; ++ v )
{
outData->SetValueByName( r, names[v], assessResult->GetValue( v ) );
}
}
assessResult->Delete();
}
delete dfunc;
delete [] names;
varNames->Delete(); // Do not delete earlier! Otherwise, dfunc will be wrecked
}
}
<commit_msg>STYLE: fixed incorrect formatting<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkBivariateStatisticsAlgorithm.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkBivariateStatisticsAlgorithm.h"
#include "vtkBivariateStatisticsAlgorithmPrivate.h"
#include "vtkDoubleArray.h"
#include "vtkObjectFactory.h"
#include "vtkStdString.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"
#include <vtkstd/set>
#include <vtksys/ios/sstream>
vtkCxxRevisionMacro(vtkBivariateStatisticsAlgorithm, "1.15");
// ----------------------------------------------------------------------
vtkBivariateStatisticsAlgorithm::vtkBivariateStatisticsAlgorithm()
{
this->NumberOfVariables = 2;
this->Internals = new vtkBivariateStatisticsAlgorithmPrivate;
}
// ----------------------------------------------------------------------
vtkBivariateStatisticsAlgorithm::~vtkBivariateStatisticsAlgorithm()
{
delete this->Internals;
}
// ----------------------------------------------------------------------
void vtkBivariateStatisticsAlgorithm::PrintSelf( ostream &os, vtkIndent indent )
{
this->Superclass::PrintSelf( os, indent );
os << indent << "NumberOfVariables: " << this->NumberOfVariables << endl;
}
// ----------------------------------------------------------------------
void vtkBivariateStatisticsAlgorithm::ResetColumnPairs()
{
this->Internals->Selection.clear();
this->Modified();
}
// ----------------------------------------------------------------------
void vtkBivariateStatisticsAlgorithm::AddColumnPair( const char* namColX, const char* namColY )
{
vtkstd::pair<vtkStdString,vtkStdString> namPair( namColX, namColY );
this->Internals->Selection.insert( namPair );
this->Modified();
}
// ----------------------------------------------------------------------
void vtkBivariateStatisticsAlgorithm::RemoveColumnPair( const char* namColX, const char* namColY )
{
vtkstd::pair<vtkStdString,vtkStdString> namPair( namColX, namColY );
this->Internals->Selection.erase( namPair );
this->Modified();
}
// ----------------------------------------------------------------------
void vtkBivariateStatisticsAlgorithm::SetColumnStatus( const char* namCol, int status )
{
if( status )
{
this->Internals->BufferedColumns.insert( namCol );
}
else
{
this->Internals->BufferedColumns.erase( namCol );
}
this->Internals->Selection.clear();
int i = 0;
for ( vtkstd::set<vtkStdString>::iterator ait = this->Internals->BufferedColumns.begin();
ait != this->Internals->BufferedColumns.end(); ++ ait, ++ i )
{
int j = 0;
for ( vtkstd::set<vtkStdString>::iterator bit = this->Internals->BufferedColumns.begin();
j < i ; ++ bit, ++ j )
{
vtkstd::pair<vtkStdString,vtkStdString> namPair( *bit, *ait );
this->Internals->Selection.insert( namPair );
}
}
this->Modified();
}
// ----------------------------------------------------------------------
void vtkBivariateStatisticsAlgorithm::Assess( vtkTable* inData,
vtkDataObject* inMetaDO,
vtkTable* outData,
vtkDataObject* vtkNotUsed( outMeta ) )
{
vtkTable* inMeta = vtkTable::SafeDownCast( inMetaDO );
if ( ! inMeta )
{
return;
}
if ( ! inData || inData->GetNumberOfColumns() <= 0 )
{
return;
}
vtkIdType nRowD = inData->GetNumberOfRows();
if ( nRowD <= 0 )
{
return;
}
vtkIdType nColP;
if ( this->AssessParameters )
{
nColP = this->AssessParameters->GetNumberOfValues();
if ( inMeta->GetNumberOfColumns() - this->NumberOfVariables < nColP )
{
vtkWarningMacro( "Parameter table has "
<< inMeta->GetNumberOfColumns() - this->NumberOfVariables
<< " parameters < "
<< nColP
<< " columns. Doing nothing." );
return;
}
}
if ( ! inMeta->GetNumberOfRows() )
{
return;
}
// Loop over pairs of columns of interest
for ( vtkstd::set<vtkstd::pair<vtkStdString,vtkStdString> >::iterator it = this->Internals->Selection.begin();
it != this->Internals->Selection.end(); ++ it )
{
vtkStdString varNameX = it->first;
if ( ! inData->GetColumnByName( varNameX ) )
{
vtkWarningMacro( "InData table does not have a column "
<< varNameX.c_str()
<< ". Ignoring this pair." );
continue;
}
vtkStdString varNameY = it->second;
if ( ! inData->GetColumnByName( varNameY ) )
{
vtkWarningMacro( "InData table does not have a column "
<< varNameY.c_str()
<< ". Ignoring this pair." );
continue;
}
vtkStringArray* varNames = vtkStringArray::New();
varNames->SetNumberOfValues( this->NumberOfVariables );
varNames->SetValue( 0, varNameX );
varNames->SetValue( 1, varNameY );
// Store names to be able to use SetValueByName, and create the outData columns
int nv = this->AssessNames->GetNumberOfValues();
vtkStdString* names = new vtkStdString[nv];
for ( int v = 0; v < nv; ++ v )
{
vtksys_ios::ostringstream assessColName;
assessColName << this->AssessNames->GetValue( v )
<< "("
<< varNameX
<< ","
<< varNameY
<< ")";
names[v] = assessColName.str().c_str();
vtkDoubleArray* assessValues = vtkDoubleArray::New();
assessValues->SetName( names[v] );
assessValues->SetNumberOfTuples( nRowD );
outData->AddColumn( assessValues );
assessValues->Delete();
}
// Select assess functor
AssessFunctor* dfunc;
this->SelectAssessFunctor( outData,
inMeta,
varNames,
dfunc );
if ( ! dfunc )
{
// Functor selection did not work. Do nothing.
vtkWarningMacro( "AssessFunctors could not be allocated for column pair ("
<< varNameX.c_str()
<< ","
<< varNameY.c_str()
<< "). Ignoring it." );
delete [] names;
continue;
}
else
{
// Assess each entry of the column
vtkVariantArray* assessResult = vtkVariantArray::New();
for ( vtkIdType r = 0; r < nRowD; ++ r )
{
(*dfunc)( assessResult, r );
for ( int v = 0; v < nv; ++ v )
{
outData->SetValueByName( r, names[v], assessResult->GetValue( v ) );
}
}
assessResult->Delete();
}
delete dfunc;
delete [] names;
varNames->Delete(); // Do not delete earlier! Otherwise, dfunc will be wrecked
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <cstdint>
#include <atomic>
#include <limits>
#include <utility>
#include <functional>
#include <mutex>
namespace tell {
namespace store {
constexpr const unsigned NUM_LISTS = 64;
extern void init();
extern void destroy();
class allocator {
std::atomic<uint64_t>* cnt_;
static std::mutex mutex_;
public:
allocator();
~allocator();
static void* malloc(std::size_t size);
static void* malloc(std::size_t size, std::size_t align);
static void free(void* ptr, std::function<void()> destruct = []() { });
static void free_in_order(void* ptr, std::function<void()> destruct = []() { });
static void free_now(void* ptr);
};
template<typename T>
static void mark_for_deletion(T* ptr) {
if (ptr)
allocator::free(ptr, [ptr]() {
ptr->~T();
});
}
} // namespace store
} // namespace tell
<commit_msg>Extend the allocator with functions to construct and destroy objects<commit_after>#pragma once
#include <cstdint>
#include <atomic>
#include <limits>
#include <utility>
#include <functional>
#include <mutex>
#include <type_traits>
namespace tell {
namespace store {
constexpr const unsigned NUM_LISTS = 64;
extern void init();
extern void destroy();
class allocator {
std::atomic<uint64_t>* cnt_;
static std::mutex mutex_;
public:
allocator();
~allocator();
static void* malloc(std::size_t size);
static void* malloc(std::size_t size, std::size_t align);
static void free(void* ptr, std::function<void()> destruct = []() { });
static void free_in_order(void* ptr, std::function<void()> destruct = []() { });
static void free_now(void* ptr);
static void invoke(std::function<void()> fun) {
allocator::free(allocator::malloc(0), std::move(fun));
}
template <typename T, typename... Args>
static typename std::enable_if<alignof(T) == alignof(void*), T*>::type construct(Args&&... args) {
return new (allocator::malloc(sizeof(T))) T(std::forward<Args>(args)...);
}
template <typename T, typename... Args>
static typename std::enable_if<(alignof(T) > alignof(void*)) && !(alignof(T) & (alignof(T) - 1)), T*>::type
construct(Args&&... args) {
return new (allocator::malloc(sizeof(T), alignof(T))) T(std::forward<Args>(args)...);
}
template <typename T>
static void destroy(T* ptr) {
if (!ptr) {
return;
}
allocator::free(ptr, [ptr] () {
ptr->~T();
});
}
template <typename T>
static void destroy_in_order(T* ptr) {
if (!ptr) {
return;
}
allocator::free_in_order(ptr, [ptr] () {
ptr->~T();
});
}
template <typename T>
static void destroy_now(T* ptr) {
if (!ptr) {
return;
}
ptr->~T();
allocator::free_now(ptr);
}
};
} // namespace store
} // namespace tell
<|endoftext|> |
<commit_before>#include "ball.h"
#include <GL/gl.h>
Ball::Ball(V2d center, V2d movement):Circle(center, radius){
speed = movement.mod();
direction = movement % 1;
phase = rotation = 0;
}
void Ball::advance(float t){
center+= direction*speed*t;
phase += rotation ? rot_speed : -rot_speed;
}
bool Ball::hit(const Obstacle &toHit, double& tIn, V2d& normalIn){
return toHit.intersection(center, direction, speed, tIn, normalIn);
}
void Ball::revota(V2d normal){
//normal %= 1;
normal = normal * -(normal * direction);
direction += (normal*2);//% 1;
phase += rotation ? rot_speed : -rot_speed;
}
void Ball::inv_mov(){
direction.x = -direction.x;
direction.y = -direction.y;
phase += rotation ? rot_speed : -rot_speed;
}
void Ball::paint()const{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(center.x, center.y, 0);
glScalef(radius, radius, 1);
glBegin(GL_LINE_LOOP);
Circle::circle_vertex();
glEnd();
glRotatef(phase, 0, 0, 1);
glBegin(GL_LINES);
glVertex2f(0,0);
glVertex2f(0,1);
glEnd();
glPopMatrix();
}
<commit_msg>Fixed rotation<commit_after>#include "ball.h"
#include <GL/gl.h>
Ball::Ball(V2d center, V2d movement):Circle(center, radius){
speed = movement.mod();
direction = movement % 1;
phase = rotation = 0;
}
void Ball::advance(float t){
center+= direction*speed*t;
phase= ((phase + (rotation ? 1 :-1)*rot_speed)) % 360;
}
bool Ball::hit(const Obstacle &toHit, double& tIn, V2d& normalIn){
return toHit.intersection(center, direction, speed, tIn, normalIn);
}
void Ball::revota(V2d normal){
//normal %= 1;
normal = normal * -(normal * direction);
direction += (normal*2);//% 1;
rotation= !rotation;
}
void Ball::inv_mov(){
direction.x = -direction.x;
direction.y = -direction.y;
rotation= !rotation;
}
void Ball::paint()const{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(center.x, center.y, 0);
glScalef(radius, radius, 1);
glBegin(GL_LINE_LOOP);
Circle::circle_vertex();
glEnd();
glRotatef(phase, 0, 0, 1);
glBegin(GL_LINES);
glVertex2f(0,0);
glVertex2f(0,1);
glEnd();
glPopMatrix();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
* Copyright (C) 2003, 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2003 Peter Kelly (pmk@post.com)
* Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*
*/
#include "config.h"
#include "ArrayConstructor.h"
#include "ArrayPrototype.h"
#include "Error.h"
#include "JSArray.h"
#include "JSFunction.h"
#include "Lookup.h"
namespace JSC {
ASSERT_CLASS_FITS_IN_CELL(ArrayConstructor);
static JSValue JSC_HOST_CALL arrayConstructorIsArray(ExecState*, JSObject*, JSValue, const ArgList&);
ArrayConstructor::ArrayConstructor(ExecState* exec, PassRefPtr<Structure> structure, ArrayPrototype* arrayPrototype, Structure* prototypeFunctionStructure)
: InternalFunction(&exec->globalData(), structure, Identifier(exec, arrayPrototype->classInfo()->className))
{
// ECMA 15.4.3.1 Array.prototype
putDirectWithoutTransition(exec->propertyNames().prototype, arrayPrototype, DontEnum | DontDelete | ReadOnly);
// no. of arguments for constructor
putDirectWithoutTransition(exec->propertyNames().length, jsNumber(exec, 1), ReadOnly | DontEnum | DontDelete);
// ES5
putDirectFunctionWithoutTransition(exec, new (exec) NativeFunctionWrapper(exec, prototypeFunctionStructure, 1, exec->propertyNames().isArray, arrayConstructorIsArray), DontEnum);
}
static JSObject* constructArrayWithSizeQuirk(ExecState* exec, const ArgList& args)
{
// a single numeric argument denotes the array size (!)
if (args.size() == 1 && args.at(0).isNumber()) {
uint32_t n = args.at(0).toUInt32(exec);
if (n != args.at(0).toNumber(exec))
return throwError(exec, RangeError, "Array size is not a small enough positive integer.");
return new (exec) JSArray(exec->lexicalGlobalObject()->arrayStructure(), n);
}
// otherwise the array is constructed with the arguments in it
return new (exec) JSArray(exec->lexicalGlobalObject()->arrayStructure(), args);
}
static JSObject* constructWithArrayConstructor(ExecState* exec, JSObject*, const ArgList& args)
{
return constructArrayWithSizeQuirk(exec, args);
}
// ECMA 15.4.2
ConstructType ArrayConstructor::getConstructData(ConstructData& constructData)
{
constructData.native.function = constructWithArrayConstructor;
return ConstructTypeHost;
}
static JSValue JSC_HOST_CALL callArrayConstructor(ExecState* exec, JSObject*, JSValue, const ArgList& args)
{
return constructArrayWithSizeQuirk(exec, args);
}
// ECMA 15.6.1
CallType ArrayConstructor::getCallData(CallData& callData)
{
// equivalent to 'new Array(....)'
callData.native.function = callArrayConstructor;
return CallTypeHost;
}
JSValue JSC_HOST_CALL arrayConstructorIsArray(ExecState*, JSObject*, JSValue, const ArgList& args)
{
if (!args.at(0).isObject())
return jsBoolean(false);
return jsBoolean(asObject(args.at(0))->isObject(&JSArray::info));
}
} // namespace JSC
<commit_msg>Try to fix the build when !JIT_OPTIMIZE_NATIVE_CALL<commit_after>/*
* Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
* Copyright (C) 2003, 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2003 Peter Kelly (pmk@post.com)
* Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*
*/
#include "config.h"
#include "ArrayConstructor.h"
#include "ArrayPrototype.h"
#include "Error.h"
#include "JSArray.h"
#include "JSFunction.h"
#include "Lookup.h"
#include "PrototypeFunction.h"
namespace JSC {
ASSERT_CLASS_FITS_IN_CELL(ArrayConstructor);
static JSValue JSC_HOST_CALL arrayConstructorIsArray(ExecState*, JSObject*, JSValue, const ArgList&);
ArrayConstructor::ArrayConstructor(ExecState* exec, PassRefPtr<Structure> structure, ArrayPrototype* arrayPrototype, Structure* prototypeFunctionStructure)
: InternalFunction(&exec->globalData(), structure, Identifier(exec, arrayPrototype->classInfo()->className))
{
// ECMA 15.4.3.1 Array.prototype
putDirectWithoutTransition(exec->propertyNames().prototype, arrayPrototype, DontEnum | DontDelete | ReadOnly);
// no. of arguments for constructor
putDirectWithoutTransition(exec->propertyNames().length, jsNumber(exec, 1), ReadOnly | DontEnum | DontDelete);
// ES5
putDirectFunctionWithoutTransition(exec, new (exec) NativeFunctionWrapper(exec, prototypeFunctionStructure, 1, exec->propertyNames().isArray, arrayConstructorIsArray), DontEnum);
}
static JSObject* constructArrayWithSizeQuirk(ExecState* exec, const ArgList& args)
{
// a single numeric argument denotes the array size (!)
if (args.size() == 1 && args.at(0).isNumber()) {
uint32_t n = args.at(0).toUInt32(exec);
if (n != args.at(0).toNumber(exec))
return throwError(exec, RangeError, "Array size is not a small enough positive integer.");
return new (exec) JSArray(exec->lexicalGlobalObject()->arrayStructure(), n);
}
// otherwise the array is constructed with the arguments in it
return new (exec) JSArray(exec->lexicalGlobalObject()->arrayStructure(), args);
}
static JSObject* constructWithArrayConstructor(ExecState* exec, JSObject*, const ArgList& args)
{
return constructArrayWithSizeQuirk(exec, args);
}
// ECMA 15.4.2
ConstructType ArrayConstructor::getConstructData(ConstructData& constructData)
{
constructData.native.function = constructWithArrayConstructor;
return ConstructTypeHost;
}
static JSValue JSC_HOST_CALL callArrayConstructor(ExecState* exec, JSObject*, JSValue, const ArgList& args)
{
return constructArrayWithSizeQuirk(exec, args);
}
// ECMA 15.6.1
CallType ArrayConstructor::getCallData(CallData& callData)
{
// equivalent to 'new Array(....)'
callData.native.function = callArrayConstructor;
return CallTypeHost;
}
JSValue JSC_HOST_CALL arrayConstructorIsArray(ExecState*, JSObject*, JSValue, const ArgList& args)
{
if (!args.at(0).isObject())
return jsBoolean(false);
return jsBoolean(asObject(args.at(0))->isObject(&JSArray::info));
}
} // namespace JSC
<|endoftext|> |
<commit_before>//
// main.cpp
// Unit Tests
//
// Created by Evan McCartney-Melstad on 12/31/14.
// Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.
//
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "../cPWP/generateSimulatedData.h"
#include "../cPWP/bamsToBin.h"
#include "../cPWP/calcPWP.h"
#include "catch.hpp"
#include <string>
#include <iostream>
#include <fstream>
/*
TEST_CASE( "Simulated reads are generated", "[generateReads]" ) {
// Make sure that the read simulation finishes
REQUIRE( generateReadsAndMap(1, 0.01, "0.0", "300", "50", "1000000", "100", "1234", "scaffold_0.fasta") == 0);
}
*/
TEST_CASE( "Generate reference genome for simulation tests", "[generateReference]") {
REQUIRE( createReferenceGenome(1000000, 0.42668722, "simulatedReferenceGenome.fasta") == 0 );
}
TEST_CASE ( "Mutate a reference genome", "[mutateRefGenome]") {
REQUIRE( createMutatedGenome("simulatedReferenceGenome.fasta", "simulatedReferenceGenomeMutated.fasta", 0.01) == 0);
}
TEST_CASE( "Generate sequence reads", "[perfectReads]") {
REQUIRE( generatePerfectReads ("simulatedReferenceGenome.fasta", 1, 100, 300, "normalRef") == 0);
//generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);
}
TEST_CASE( " Mapping first set of reads", "[mapReads]") {
REQUIRE( mapReads("simulatedReferenceGenome.fasta", "normalRef_R1.fastq", "normalRef_R2.fastq", "normal.bam", "25") == 0);
}
TEST_CASE( "Generate sequence reads 2", "[perfectReads2]") {
REQUIRE( generatePerfectReads ("simulatedReferenceGenomeMutated.fasta", 1, 100, 300, "mutatedRef") == 0);
}
TEST_CASE( " Mapping second set of reads", "[mapReads2]") {
REQUIRE( mapReads("simulatedReferenceGenome.fasta", "mutatedRef_R1.fastq", "mutatedRef_R2.fastq", "mutated.bam", "25") == 0);
}
// Create heterozygous genome
std::ifstream chrom1("simulatedReferenceGenome.fasta");
std::ifstream chrom1a("simulatedReferenceGenomeMutated.fasta");
std::ofstream write ("simulatedHeterozygousGenome.fasta");
std::string line;
std::string line2;
while ( std::getline ( chrom1, line, '\n' ) )
{
write << line << endl;
}
while ( getline ( chrom1a, line2, '\n' ) )
{
write << line2 << endl;
}
read1.close();
read2.close();
write.close();
TEST_CASE( "Run ANGSD on simulated reads", "[runANGSD]" ) {
REQUIRE( runANGSDforReadCounts("bamlist.txt", "angsdOut", "25", "angsdOutLog.txt") == 0);
}
/*
TEST_CASE( "Generate mutated reference genomes and simulate reads", "[genomeAndReadSim]") {
REQUIRE( generateReadsAndMap(3, 0.01, "300", "25", "10000", "100", "1234", "simulatedReferenceGenome.fasta", "25") == 0);
}
TEST_CASE( "Run ANGSD on simulated reads", "[runANGSD]" ) {
REQUIRE( runANGSDforReadCounts("bamlist.txt", "angsdOut", "25", "angsdOutLog.txt") == 0);
}
*/
TEST_CASE( "Convert ANGSD read counts to unsigned chars for major and minor counts", "[convertCountsToBinary]") {
REQUIRE( convertANGSDcountsToBinary("angsdOut", "angsdOut.readCounts.binary", 2, 5000) == 0); // 3 individuals, not 2, because generateReadsAndMap actually generates n+1 individuals, since one individual is identical to the reference genome. And 5000 as a max because we don't want to exclude any loci for this test
}
TEST_CASE( "Calculate PWP from the binary representations of the ANGSD readcounts", "[calcPWP]") {
REQUIRE( calcPWPfromBinaryFile ("angsdOut.readCounts.binary", 0, 2, "testingOut.pwp", 30) == 0);
}
<commit_msg>Minor changes<commit_after>//
// main.cpp
// Unit Tests
//
// Created by Evan McCartney-Melstad on 12/31/14.
// Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.
//
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "../cPWP/generateSimulatedData.h"
#include "../cPWP/bamsToBin.h"
#include "../cPWP/calcPWP.h"
#include "catch.hpp"
#include <string>
#include <iostream>
#include <fstream>
/*
TEST_CASE( "Simulated reads are generated", "[generateReads]" ) {
// Make sure that the read simulation finishes
REQUIRE( generateReadsAndMap(1, 0.01, "0.0", "300", "50", "1000000", "100", "1234", "scaffold_0.fasta") == 0);
}
*/
TEST_CASE( "Generate reference genome for simulation tests", "[generateReference]") {
REQUIRE( createReferenceGenome(1000000, 0.42668722, "simulatedReferenceGenome.fasta") == 0 );
}
TEST_CASE ( "Mutate a reference genome", "[mutateRefGenome]") {
REQUIRE( createMutatedGenome("simulatedReferenceGenome.fasta", "simulatedReferenceGenomeMutated.fasta", 0.01) == 0);
}
TEST_CASE( "Generate sequence reads", "[perfectReads]") {
REQUIRE( generatePerfectReads ("simulatedReferenceGenome.fasta", 1, 100, 300, "normalRef") == 0);
//generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);
}
TEST_CASE( " Mapping first set of reads", "[mapReads]") {
REQUIRE( mapReads("simulatedReferenceGenome.fasta", "normalRef_R1.fastq", "normalRef_R2.fastq", "normal.bam", "25") == 0);
}
TEST_CASE( "Generate sequence reads 2", "[perfectReads2]") {
REQUIRE( generatePerfectReads ("simulatedReferenceGenomeMutated.fasta", 1, 100, 300, "mutatedRef") == 0);
}
TEST_CASE( " Mapping second set of reads", "[mapReads2]") {
REQUIRE( mapReads("simulatedReferenceGenome.fasta", "mutatedRef_R1.fastq", "mutatedRef_R2.fastq", "mutated.bam", "25") == 0);
}
// Create heterozygous genome
std::ifstream chrom1("simulatedReferenceGenome.fasta");
std::ifstream chrom1a("simulatedReferenceGenomeMutated.fasta");
std::ofstream write ("simulatedHeterozygousGenome.fasta");
std::string line;
std::string line2;
while ( std::getline ( chrom1, line, '\n' ) )
{
write << line << endl;
}
while ( getline ( chrom1a, line2, '\n' ) )
{
write << line2 << endl;
}
chrom1.close();
chrom1a.close();
write.close();
TEST_CASE( "Run ANGSD on simulated reads", "[runANGSD]" ) {
REQUIRE( runANGSDforReadCounts("bamlist.txt", "angsdOut", "25", "angsdOutLog.txt") == 0);
}
/*
TEST_CASE( "Generate mutated reference genomes and simulate reads", "[genomeAndReadSim]") {
REQUIRE( generateReadsAndMap(3, 0.01, "300", "25", "10000", "100", "1234", "simulatedReferenceGenome.fasta", "25") == 0);
}
TEST_CASE( "Run ANGSD on simulated reads", "[runANGSD]" ) {
REQUIRE( runANGSDforReadCounts("bamlist.txt", "angsdOut", "25", "angsdOutLog.txt") == 0);
}
*/
TEST_CASE( "Convert ANGSD read counts to unsigned chars for major and minor counts", "[convertCountsToBinary]") {
REQUIRE( convertANGSDcountsToBinary("angsdOut", "angsdOut.readCounts.binary", 2, 5000) == 0); // 3 individuals, not 2, because generateReadsAndMap actually generates n+1 individuals, since one individual is identical to the reference genome. And 5000 as a max because we don't want to exclude any loci for this test
}
TEST_CASE( "Calculate PWP from the binary representations of the ANGSD readcounts", "[calcPWP]") {
REQUIRE( calcPWPfromBinaryFile ("angsdOut.readCounts.binary", 0, 2, "testingOut.pwp", 30) == 0);
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkNavigationDataPlayer.h"
#include <itksys/SystemTools.hxx>
#include <mitkIGTTimeStamp.h>
#include <fstream>
#include "mitkNavigationDataReaderXML.h"
#include "mitkIGTException.h"
mitk::NavigationDataPlayer::NavigationDataPlayer()
: m_CurPlayerState(PlayerStopped),
m_StartPlayingTimeStamp(0.0), m_PauseTimeStamp(0.0)
{
// to get a start time
mitk::IGTTimeStamp::GetInstance()->Start(this);
}
mitk::NavigationDataPlayer::~NavigationDataPlayer()
{
StopPlaying();
}
void mitk::NavigationDataPlayer::GenerateData()
{
//Only produce new output if the player is started
if (m_CurPlayerState != PlayerRunning)
{
//The output is not valid anymore
this->GraftEmptyOutput();
return;
}
// get elapsed time since start of playing
m_TimeStampSinceStart = mitk::IGTTimeStamp::GetInstance()->GetElapsed() - m_StartPlayingTimeStamp;
// iterate through all NavigationData objects of the given tool index
// till the timestamp of the NavigationData is greater then the given timestamp
for (; m_NavigationDataSetIterator != m_NavigationDataSet->End(); ++m_NavigationDataSetIterator)
{
if ( m_NavigationDataSetIterator->at(0)->GetIGTTimeStamp() > m_TimeStampSinceStart)
{
break;
}
}
// first element was greater than timestamp -> return null
if ( m_NavigationDataSetIterator == m_NavigationDataSet->Begin() )
{
MITK_WARN("NavigationDataSet") << "No NavigationData was recorded before given timestamp.";
//The output is not at this time
this->GraftEmptyOutput();
return;
}
for (unsigned int index = 0; index < GetNumberOfOutputs(); index++)
{
mitk::NavigationData* output = this->GetOutput(index);
if( !output ) { mitkThrowException(mitk::IGTException) << "Output of index "<<index<<" is null."; }
mitk::NavigationDataSet::NavigationDataSetIterator curIterator = m_NavigationDataSetIterator-1;
output->Graft(curIterator->at(index));
}
// stop playing if the last NavigationData objects were grafted
if (m_NavigationDataSetIterator == m_NavigationDataSet->End())
{
this->StopPlaying();
}
}
void mitk::NavigationDataPlayer::UpdateOutputInformation()
{
this->Modified(); // make sure that we need to be updated
Superclass::UpdateOutputInformation();
}
void mitk::NavigationDataPlayer::StartPlaying()
{
// make sure that player is initialized before playing starts
this->InitPlayer();
// set state and iterator for playing from start
m_CurPlayerState = PlayerRunning;
m_NavigationDataSetIterator = m_NavigationDataSet->Begin();
// timestamp for indicating playing start is set to the past
// so that the first navigation data object will be shown NOW
m_StartPlayingTimeStamp = mitk::IGTTimeStamp::GetInstance()->GetElapsed()
- m_NavigationDataSet->Begin()->at(0)->GetIGTTimeStamp();
}
void mitk::NavigationDataPlayer::StopPlaying()
{
m_CurPlayerState = PlayerStopped;
// reset playing timestamps
m_StartPlayingTimeStamp = 0;
m_PauseTimeStamp = 0;
}
void mitk::NavigationDataPlayer::Pause()
{
//player runs and pause was called -> pause the player
if(m_CurPlayerState == PlayerRunning)
{
m_CurPlayerState = PlayerPaused;
m_PauseTimeStamp = mitk::IGTTimeStamp::GetInstance()->GetElapsed();
}
else
{
MITK_ERROR << "Player is either not started or already is paused" << std::endl;
}
}
void mitk::NavigationDataPlayer::Resume()
{
// player is in pause mode -> play at the last position
if(m_CurPlayerState == PlayerPaused)
{
m_CurPlayerState = PlayerRunning;
// in this case m_StartPlayingTimeStamp is set to the total elapsed time with NO playback
m_StartPlayingTimeStamp = mitk::IGTTimeStamp::GetInstance()->GetElapsed()
- (m_PauseTimeStamp - m_StartPlayingTimeStamp);
}
else
{
MITK_ERROR << "Player is not paused!" << std::endl;
}
}
mitk::NavigationDataPlayer::PlayerState mitk::NavigationDataPlayer::GetCurrentPlayerState()
{
return m_CurPlayerState;
}
mitk::NavigationDataPlayer::TimeStampType mitk::NavigationDataPlayer::GetTimeStampSinceStart()
{
return m_TimeStampSinceStart;
}<commit_msg>Fixed "time stamp since playing", do not reset player on stop and directly test for successor time stamp in GenerateData().<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkNavigationDataPlayer.h"
#include <itksys/SystemTools.hxx>
#include <mitkIGTTimeStamp.h>
#include <fstream>
#include "mitkNavigationDataReaderXML.h"
#include "mitkIGTException.h"
mitk::NavigationDataPlayer::NavigationDataPlayer()
: m_CurPlayerState(PlayerStopped),
m_StartPlayingTimeStamp(0.0), m_PauseTimeStamp(0.0)
{
// to get a start time
mitk::IGTTimeStamp::GetInstance()->Start(this);
}
mitk::NavigationDataPlayer::~NavigationDataPlayer()
{
StopPlaying();
}
void mitk::NavigationDataPlayer::GenerateData()
{
if ( m_NavigationDataSet->Size() == 0 )
{
MITK_WARN << "Cannot do anything with empty set of navigation datas.";
return;
}
//Only produce new output if the player is started
if (m_CurPlayerState != PlayerRunning)
{
//The output is not valid anymore
this->GraftEmptyOutput();
return;
}
// get elapsed time since start of playing
m_TimeStampSinceStart = mitk::IGTTimeStamp::GetInstance()->GetElapsed() - m_StartPlayingTimeStamp;
// add offset of the first navigation data to the timestamp to start playing
// imediatly with the first navigation data (not to wait till the first time
// stamp is reached)
TimeStampType timeStampSinceStartWithOffset = m_TimeStampSinceStart
+ m_NavigationDataSet->Begin()->at(0)->GetIGTTimeStamp();
// iterate through all NavigationData objects of the given tool index
// till the timestamp of the NavigationData is greater then the given timestamp
for (; m_NavigationDataSetIterator != m_NavigationDataSet->End(); ++m_NavigationDataSetIterator)
{
// test if the timestamp of the successor is greater than the time stamp
if ( m_NavigationDataSetIterator+1 == m_NavigationDataSet->End() ||
(m_NavigationDataSetIterator+1)->at(0)->GetIGTTimeStamp() > timeStampSinceStartWithOffset )
{
break;
}
}
for (unsigned int index = 0; index < GetNumberOfOutputs(); index++)
{
mitk::NavigationData* output = this->GetOutput(index);
if( !output ) { mitkThrowException(mitk::IGTException) << "Output of index "<<index<<" is null."; }
output->Graft(m_NavigationDataSetIterator->at(index));
}
// stop playing if the last NavigationData objects were grafted
if (m_NavigationDataSetIterator+1 == m_NavigationDataSet->End())
{
this->StopPlaying();
// start playing again if repeat is enabled
if ( m_Repeat ) { this->StartPlaying(); }
}
}
void mitk::NavigationDataPlayer::UpdateOutputInformation()
{
this->Modified(); // make sure that we need to be updated
Superclass::UpdateOutputInformation();
}
void mitk::NavigationDataPlayer::StartPlaying()
{
// make sure that player is initialized before playing starts
this->InitPlayer();
// set state and iterator for playing from start
m_CurPlayerState = PlayerRunning;
m_NavigationDataSetIterator = m_NavigationDataSet->Begin();
// reset playing timestamps
m_PauseTimeStamp = 0;
m_TimeStampSinceStart = 0;
// timestamp for indicating playing start set to current elapsed time
m_StartPlayingTimeStamp = mitk::IGTTimeStamp::GetInstance()->GetElapsed();
}
void mitk::NavigationDataPlayer::StopPlaying()
{
m_CurPlayerState = PlayerStopped;
}
void mitk::NavigationDataPlayer::Pause()
{
//player runs and pause was called -> pause the player
if(m_CurPlayerState == PlayerRunning)
{
m_CurPlayerState = PlayerPaused;
m_PauseTimeStamp = mitk::IGTTimeStamp::GetInstance()->GetElapsed();
}
else
{
MITK_ERROR << "Player is either not started or already is paused" << std::endl;
}
}
void mitk::NavigationDataPlayer::Resume()
{
// player is in pause mode -> play at the last position
if(m_CurPlayerState == PlayerPaused)
{
m_CurPlayerState = PlayerRunning;
// in this case m_StartPlayingTimeStamp is set to the total elapsed time with NO playback
m_StartPlayingTimeStamp = mitk::IGTTimeStamp::GetInstance()->GetElapsed()
- (m_PauseTimeStamp - m_StartPlayingTimeStamp);
}
else
{
MITK_ERROR << "Player is not paused!" << std::endl;
}
}
mitk::NavigationDataPlayer::PlayerState mitk::NavigationDataPlayer::GetCurrentPlayerState()
{
return m_CurPlayerState;
}
mitk::NavigationDataPlayer::TimeStampType mitk::NavigationDataPlayer::GetTimeStampSinceStart()
{
return m_TimeStampSinceStart;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "dct.h"
#include "essentiamath.h"
using namespace std;
using namespace essentia;
using namespace standard;
const char* DCT::name = "DCT";
const char* DCT::category = "Standard";
const char* DCT::description = DOC("This algorithm computes the Discrete Cosine Transform of an array.\n"
"It uses the DCT-II form, with the 1/sqrt(2) scaling factor for the first coefficient.\n"
"Note: The 'inputSize' parameter is only used as an optimization when the algorithm is configured. "
"The DCT will automatically adjust to the size of any input.\n"
"\n"
"References:\n"
" [1] Discrete cosine transform - Wikipedia, the free encyclopedia,\n"
" http://en.wikipedia.org/wiki/Discrete_cosine_transform");
void DCT::configure() {
int inputSize = parameter("inputSize").toInt();
_outputSize = parameter("outputSize").toInt();
_type = parameter("dctType").toInt();
if (_type == 2){
createDctTableII(inputSize, _outputSize);
}
else if (_type == 3){
createDctTableIII(inputSize, _outputSize);
}
else {
throw EssentiaException("Bad DCT type.");
}
}
void DCT::createDctTableII(int inputSize, int outputSize) {
// simple implementation using matrix multiplication, can probably be sped up
// using a library like FFTW, for instance.
if (outputSize > inputSize) {
throw EssentiaException("DCT: 'outputSize' is greater than 'inputSize'. You can only compute the DCT with an output size smaller than the input size (i.e. you can only compress information)");
}
_dctTable = vector<vector<Real> >(outputSize, vector<Real>(inputSize));
// scale for index = 0
Real scale0 = 1.0 / sqrt(Real(inputSize));
// scale for index != 0
Real scale1 = Real(sqrt(2.0/inputSize));
for (int i=0; i<outputSize; ++i) {
Real scale = (i==0)? scale0 : scale1;
Real freqMultiplier = Real(M_PI / inputSize * i);
for (int j=0; j<inputSize; ++j) {
_dctTable[i][j] = (Real)(scale * cos( freqMultiplier * ((Real)j + 0.5) ));
}
}
}
void DCT::createDctTableIII(int inputSize, int outputSize) {
// simple implementation using matrix multiplication, can probably be sped up
// using a library like FFTW, for instance.
if (outputSize > inputSize) {
throw EssentiaException("DCT: 'outputSize' is greater than 'inputSize'. You can only compute the DCT with an output size smaller than the input size (i.e. you can only compress information)");
}
_dctTable = vector<vector<Real> >(outputSize, vector<Real>(inputSize));
// scale for index = 0
Real scale0 = 1.0 / sqrt(Real(inputSize));
// scale for index != 0
Real scale1 = Real(sqrt(2.0/inputSize));
Real freqMultiplier;
for (int i=0; i<outputSize; ++i) {
_dctTable[i][0] = scale1 * scale0; // 0.5 or sqrt (0.5)??
for (int j=1; j<inputSize; ++j) {
freqMultiplier = Real(M_PI / inputSize * j);
_dctTable[i][j] = (Real)(scale1 * cos( freqMultiplier * ((Real)i + 0.5) ));
}
}
}
void DCT::compute() {
const vector<Real>& array = _array.get();
vector<Real>& dct = _dct.get();
int inputSize = int(array.size());
if (inputSize == 0) {
throw EssentiaException("DCT: input array cannot be of size 0");
}
if (_dctTable.empty() ||
inputSize != int(_dctTable[0].size()) ||
_outputSize != int(_dctTable.size())) {
if (_type == 2){
createDctTableII(inputSize, _outputSize);
}
else if (_type == 3){
createDctTableIII(inputSize, _outputSize);
}
else {
throw EssentiaException("Bad DCT type.");
}
}
dct.resize(_outputSize);
for (int i=0; i<_outputSize; ++i) {
dct[i] = 0.0;
for (int j=0; j<inputSize; ++j) {
dct[i] += array[j] * _dctTable[i][j];
}
}
}
<commit_msg>DTC: dct type III in order to behave as Librosa #507<commit_after>/*
* Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "dct.h"
#include "essentiamath.h"
using namespace std;
using namespace essentia;
using namespace standard;
const char* DCT::name = "DCT";
const char* DCT::category = "Standard";
const char* DCT::description = DOC("This algorithm computes the Discrete Cosine Transform of an array.\n"
"It uses the DCT-II form, with the 1/sqrt(2) scaling factor for the first coefficient.\n"
"Note: The 'inputSize' parameter is only used as an optimization when the algorithm is configured. "
"The DCT will automatically adjust to the size of any input.\n"
"\n"
"References:\n"
" [1] Discrete cosine transform - Wikipedia, the free encyclopedia,\n"
" http://en.wikipedia.org/wiki/Discrete_cosine_transform");
void DCT::configure() {
int inputSize = parameter("inputSize").toInt();
_outputSize = parameter("outputSize").toInt();
_type = parameter("dctType").toInt();
if (_type == 2){
createDctTableII(inputSize, _outputSize);
}
else if (_type == 3){
createDctTableIII(inputSize, _outputSize);
}
else {
throw EssentiaException("Bad DCT type.");
}
}
void DCT::createDctTableII(int inputSize, int outputSize) {
// simple implementation using matrix multiplication, can probably be sped up
// using a library like FFTW, for instance.
if (outputSize > inputSize) {
throw EssentiaException("DCT: 'outputSize' is greater than 'inputSize'. You can only compute the DCT with an output size smaller than the input size (i.e. you can only compress information)");
}
_dctTable = vector<vector<Real> >(outputSize, vector<Real>(inputSize));
// scale for index = 0
Real scale0 = 1.0 / sqrt(Real(inputSize));
// scale for index != 0
Real scale1 = Real(sqrt(2.0/inputSize));
for (int i=0; i<outputSize; ++i) {
Real scale = (i==0)? scale0 : scale1;
Real freqMultiplier = Real(M_PI / inputSize * i);
for (int j=0; j<inputSize; ++j) {
_dctTable[i][j] = (Real)(scale * cos( freqMultiplier * ((Real)j + 0.5) ));
}
}
}
void DCT::createDctTableIII(int inputSize, int outputSize) {
// simple implementation using matrix multiplication, can probably be sped up
// using a library like FFTW, for instance.
if (outputSize > inputSize) {
throw EssentiaException("DCT: 'outputSize' is greater than 'inputSize'. You can only compute the DCT with an output size smaller than the input size (i.e. you can only compress information)");
}
_dctTable = vector<vector<Real> >(outputSize, vector<Real>(inputSize));
/*
// scale for index = 0
Real scale0 = 1.0 / sqrt(Real(inputSize));
// scale for index != 0
Real scale1 = sqrt(Real(2.0)/inputSize);
Real freqMultiplier;
for (int i=0; i<outputSize; ++i) {
_dctTable[i][0] = scale0; // Imported from librosa.
freqMultiplier = Real( ( M_PI / Real(inputSize) ) * Real(i));
for (int j=1; j<inputSize; ++j) {
_dctTable[i][j] = (Real)(scale1 * cos( freqMultiplier * ((Real)j + 0.5) ));
}
}
*/
// scale for index = 0
Real scale0 = 1.0 / sqrt(Real(inputSize));
// scale for index != 0
Real scale1 = Real(sqrt(2.0/inputSize));
for (int i=0; i<outputSize; ++i) {
Real scale = (i==0)? scale0 : scale1;
Real freqMultiplier = Real(M_PI / inputSize * i);
for (int j=0; j<inputSize; ++j) {
if ( i == 0 ){
_dctTable[i][j] = (Real)(scale);
}
else{
_dctTable[i][j] = (Real)(scale * cos( freqMultiplier * ((Real)j + 0.5) ));
}
}
}
}
void DCT::compute() {
const vector<Real>& array = _array.get();
vector<Real>& dct = _dct.get();
int inputSize = int(array.size());
if (inputSize == 0) {
throw EssentiaException("DCT: input array cannot be of size 0");
}
if (_dctTable.empty() ||
inputSize != int(_dctTable[0].size()) ||
_outputSize != int(_dctTable.size())) {
if (_type == 2){
createDctTableII(inputSize, _outputSize);
}
else if (_type == 3){
createDctTableIII(inputSize, _outputSize);
}
else {
throw EssentiaException("Bad DCT type.");
}
}
dct.resize(_outputSize);
for (int i=0; i<_outputSize; ++i) {
dct[i] = 0.0;
for (int j=0; j<inputSize; ++j) {
dct[i] += array[j] * _dctTable[i][j];
}
}
}
<|endoftext|> |
<commit_before>// -*- C++ -*-
/**
* @file gnuwrapper.cpp
* @brief Replaces malloc family on GNU/Linux with custom versions.
* @author Emery Berger <http://www.emeryberger.com>
* @note Copyright (C) 2010-2020 by Emery Berger.
Heap Layers is distributed under the terms of the Apache 2.0 license.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
*/
#ifndef __GNUC__
#error "This file requires the GNU compiler."
#endif
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <new>
#include <pthread.h>
#include <sys/cdefs.h>
#include "heaplayers.h"
/*
To use this library,
you only need to define the following allocation functions:
- xxmalloc
- xxfree
- xxmemalign
- xxmalloc_usable_size
- xxmalloc_lock
- xxmalloc_unlock
See the extern "C" block below for function prototypes and more
details. YOU SHOULD NOT NEED TO MODIFY ANY OF THE CODE HERE TO
SUPPORT ANY ALLOCATOR.
*/
#define WEAK(x) __attribute__ ((weak, alias(#x)))
#ifndef __THROW
#define __THROW
#endif
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmacro-redefined"
#endif
#define CUSTOM_PREFIX(x) custom##x
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#define ATTRIBUTE_EXPORT __attribute__((visibility("default")))
#define WEAK_REDEF1(type,fname,arg1) ATTRIBUTE_EXPORT type fname(arg1) __THROW WEAK(custom##fname)
#define WEAK_REDEF2(type,fname,arg1,arg2) ATTRIBUTE_EXPORT type fname(arg1,arg2) __THROW WEAK(custom##fname)
#define WEAK_REDEF3(type,fname,arg1,arg2,arg3) ATTRIBUTE_EXPORT type fname(arg1,arg2,arg3) __THROW WEAK(custom##fname)
extern "C" {
WEAK_REDEF1(void *, malloc, size_t);
WEAK_REDEF1(void, free, void *);
WEAK_REDEF1(void, cfree, void *);
WEAK_REDEF2(void *, calloc, size_t, size_t);
WEAK_REDEF2(void *, realloc, void *, size_t);
WEAK_REDEF3(void *, reallocarray, void *, size_t, size_t);
WEAK_REDEF2(void *, memalign, size_t, size_t);
WEAK_REDEF3(int, posix_memalign, void **, size_t, size_t);
WEAK_REDEF2(void *, aligned_alloc, size_t, size_t);
WEAK_REDEF1(size_t, malloc_usable_size, void *);
}
#include "wrapper.cpp"
#include "gnuwrapper-hooks.cpp"
<commit_msg>Added workaround for some versions of Linux.<commit_after>// -*- C++ -*-
/**
* @file gnuwrapper.cpp
* @brief Replaces malloc family on GNU/Linux with custom versions.
* @author Emery Berger <http://www.emeryberger.com>
* @note Copyright (C) 2010-2020 by Emery Berger.
Heap Layers is distributed under the terms of the Apache 2.0 license.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
*/
#ifndef __GNUC__
#error "This file requires the GNU compiler."
#endif
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <new>
#include <pthread.h>
#include <sys/cdefs.h>
#include "heaplayers.h"
/*
To use this library,
you only need to define the following allocation functions:
- xxmalloc
- xxfree
- xxmemalign
- xxmalloc_usable_size
- xxmalloc_lock
- xxmalloc_unlock
See the extern "C" block below for function prototypes and more
details. YOU SHOULD NOT NEED TO MODIFY ANY OF THE CODE HERE TO
SUPPORT ANY ALLOCATOR.
*/
#define WEAK(x) __attribute__ ((weak, alias(#x)))
#ifndef __THROW
#define __THROW
#endif
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmacro-redefined"
#endif
#define CUSTOM_PREFIX(x) custom##x
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#define ATTRIBUTE_EXPORT __attribute__((visibility("default")))
#define WEAK_REDEF1(type,fname,arg1) ATTRIBUTE_EXPORT type fname(arg1) __THROW WEAK(custom##fname)
#define WEAK_REDEF2(type,fname,arg1,arg2) ATTRIBUTE_EXPORT type fname(arg1,arg2) __THROW WEAK(custom##fname)
#define WEAK_REDEF2_NOTHROW(type,fname,arg1,arg2) ATTRIBUTE_EXPORT type fname(arg1,arg2) WEAK(custom##fname)
#define WEAK_REDEF3(type,fname,arg1,arg2,arg3) ATTRIBUTE_EXPORT type fname(arg1,arg2,arg3) __THROW WEAK(custom##fname)
extern "C" {
WEAK_REDEF1(void *, malloc, size_t);
WEAK_REDEF1(void, free, void *);
WEAK_REDEF1(void, cfree, void *);
WEAK_REDEF2(void *, calloc, size_t, size_t);
WEAK_REDEF2(void *, realloc, void *, size_t);
WEAK_REDEF3(void *, reallocarray, void *, size_t, size_t);
WEAK_REDEF2(void *, memalign, size_t, size_t);
WEAK_REDEF3(int, posix_memalign, void **, size_t, size_t);
#ifdef __USE_XOPEN2K // a work-around for an exception anomaly
WEAK_REDEF2_NOTHROW(void *, aligned_alloc, size_t, size_t);
#else
WEAK_REDEF2(void *, aligned_alloc, size_t, size_t);
#endif
WEAK_REDEF1(size_t, malloc_usable_size, void *);
}
#include "wrapper.cpp"
#include "gnuwrapper-hooks.cpp"
<|endoftext|> |
<commit_before>#include "../strainMapping/PrincipalStretchesMapping.h"
#include "StrainMapping_test.h"
#include <sofa/helper/Logger.h>
using sofa::helper::Logger;
namespace sofa {
/// layer over PrincipalStretchesJacobianBlock that is able to order given child forces in the same order while computing J
template<class TIn, class TOut>
class PrincipalStretchesJacobianBlockTester : public defaulttype::PrincipalStretchesJacobianBlock<TIn,TOut>
{
public :
typedef defaulttype::PrincipalStretchesJacobianBlock<TIn,TOut> Inherited;
static const int material_dimensions = Inherited::material_dimensions;
typedef typename Inherited::OutCoord OutCoord;
typedef typename Inherited::OutDeriv OutDeriv;
typedef typename Inherited::InCoord InCoord;
typedef typename Inherited::InDeriv InDeriv;
typedef typename Inherited::Real Real;
unsigned _order[material_dimensions];
void findOrder( const OutCoord& d )
{
OutCoord tmp = d;
for( int i=0 ; i<material_dimensions ; ++i )
{
Real min = std::numeric_limits<Real>::max();
for( int j=0 ; j<material_dimensions ; ++j )
{
if( tmp.getStrain()[j] == min && min != std::numeric_limits<Real>::max() )
{
Logger::mainlog( Logger::Warning, "Several strain components are identical, the test cannot find the comparison order, try with another data set.", "PrincipalStretchesJacobianBlockTester" );
std::cerr<<tmp.getStrain()<<std::endl;
}
if( tmp.getStrain()[j] < min )
{
_order[i] = j;
min = tmp.getStrain()[j];
}
tmp.getStrain()[j] = std::numeric_limits<Real>::max();
}
}
}
virtual OutDeriv preTreatment( const OutDeriv& f )
{
// re-order child forces with the same order used while computing J in addapply
OutDeriv g;
for( int i=0 ; i<material_dimensions ; ++i )
g[i] = f[_order[i]];
return g;
}
void addapply( OutCoord& result, const InCoord& data )
{
Inherited::addapply( result, data );
// find order result.getStrain()[i]
findOrder( result.getStrain() );
}
};
/// layer over PrincipalStretchesMapping that is able to order given child forces in the same order while computing J
template <class TIn, class TOut>
class PrincipalStretchesMappingTester : public BaseStrainMappingT<PrincipalStretchesJacobianBlockTester<TIn,TOut> >
{
public:
typedef BaseStrainMappingT<PrincipalStretchesJacobianBlockTester<TIn,TOut> > Inherited;
typedef typename Inherited::OutVecDeriv OutVecDeriv;
virtual OutVecDeriv preTreatment( const OutVecDeriv& f )
{
OutVecDeriv g(f.size());
for(unsigned int i=0; i<this->jacobian.size(); i++)
{
g[i] = this->jacobian[i].preTreatment(f[i]);
}
return g;
}
};
template <typename _Mapping>
struct PrincipalStretchesMappingTest : public StrainMappingTest<_Mapping>
{
typedef StrainMappingTest<_Mapping> Inherited;
typedef typename Inherited::In In;
typedef typename Inherited::Real Real;
typedef typename Inherited::OutVecCoord OutVecCoord;
typedef typename Inherited::OutCoord OutCoord;
typedef typename Inherited::OutDeriv OutDeriv;
typedef typename Inherited::OutVecDeriv OutVecDeriv;
template<class V>
V sort( const V& a )
{
V aa( a );
std::sort( &aa[0], &aa[0]+V::total_size );
return aa;
}
/// since principal stretches are oder-independent, sort them before comparison
virtual OutDeriv difference( const OutCoord& a, const OutCoord& b )
{
return (OutDeriv)(sort(a)-sort(b));
}
/// since principal stretches are oder-independent, sort them before comparison
virtual OutVecDeriv difference( const OutVecDeriv& a, const OutVecDeriv& b )
{
if( a.size()!=b.size() ){
ADD_FAILURE() << "OutVecDeriv have different sizes";
return OutVecDeriv();
}
OutVecDeriv c(a.size());
for (size_t i=0; i<(size_t)a.size() ; ++i)
{
c[i] = sort(a[i])-sort(b[i]);
}
return c;
}
/// re-order child forces with the same order used while computing J in apply
virtual OutVecDeriv preTreatment( const OutVecDeriv& f )
{
return static_cast<_Mapping*>(this->mapping)->preTreatment( f );
}
bool runTest()
{
this->deltaRange = std::make_pair( 100, 10000 );
this->errorMax = this->deltaRange.second;
this->errorFactorDJ = 10;
defaulttype::Mat<3,3,Real> rotation;
defaulttype::Mat<In::material_dimensions,In::material_dimensions,Real> strain; // stretch only
for( unsigned int i=0 ; i<In::material_dimensions ; ++i )
{
strain[i][i] = (i+1)*2; // todo randomize it being careful not to obtain negative (even too small) eigenvalues
}
helper::Quater<Real>::fromEuler( 0.1, -.2, .3 ).toMatrix(rotation);
OutVecCoord expectedChildCoords(1);
for( unsigned int i=0 ; i<In::material_dimensions ; ++i )
expectedChildCoords[0].getVec()[i] = strain[i][i];
return Inherited::runTest( rotation, strain, expectedChildCoords );
}
};
// Define the list of types to instanciate.
typedef Types<
PrincipalStretchesMappingTester<defaulttype::F331Types,defaulttype::U331Types>
,PrincipalStretchesMappingTester<defaulttype::F321Types,defaulttype::U321Types>
// ,PrincipalStretchesMapping<defaulttype::F331Types,defaulttype::D331Types> // not fully implemented yet (getJ)
// ,PrincipalStretchesMapping<defaulttype::F321Types,defaulttype::D321Types> // not fully implemented yet (getJ)
> PrincipalStretchesDataTypes; // the types to instanciate.
// Test suite for all the instanciations
TYPED_TEST_CASE(PrincipalStretchesMappingTest, PrincipalStretchesDataTypes);
// first test case
TYPED_TEST( PrincipalStretchesMappingTest , test_auto )
{
ASSERT_TRUE( this->runTest() );
}
} // namespace sofa
<commit_msg>[SofaFlexible]: test fix<commit_after>#include "../strainMapping/PrincipalStretchesMapping.h"
#include "StrainMapping_test.h"
#include <sofa/helper/logging/Messaging.h>
namespace sofa {
/// layer over PrincipalStretchesJacobianBlock that is able to order given child forces in the same order while computing J
template<class TIn, class TOut>
class PrincipalStretchesJacobianBlockTester : public defaulttype::PrincipalStretchesJacobianBlock<TIn,TOut>
{
public :
typedef defaulttype::PrincipalStretchesJacobianBlock<TIn,TOut> Inherited;
static const int material_dimensions = Inherited::material_dimensions;
typedef typename Inherited::OutCoord OutCoord;
typedef typename Inherited::OutDeriv OutDeriv;
typedef typename Inherited::InCoord InCoord;
typedef typename Inherited::InDeriv InDeriv;
typedef typename Inherited::Real Real;
unsigned _order[material_dimensions];
void findOrder( const OutCoord& d )
{
OutCoord tmp = d;
for( int i=0 ; i<material_dimensions ; ++i )
{
Real min = std::numeric_limits<Real>::max();
for( int j=0 ; j<material_dimensions ; ++j )
{
if( tmp.getStrain()[j] == min && min != std::numeric_limits<Real>::max() )
{
msg_warning("PrincipalStretchesJacobianBlockTester") << "Several strain components are identical, the test cannot find the comparison order, try with another data set.";
std::cerr<<tmp.getStrain()<<std::endl;
}
if( tmp.getStrain()[j] < min )
{
_order[i] = j;
min = tmp.getStrain()[j];
}
tmp.getStrain()[j] = std::numeric_limits<Real>::max();
}
}
}
virtual OutDeriv preTreatment( const OutDeriv& f )
{
// re-order child forces with the same order used while computing J in addapply
OutDeriv g;
for( int i=0 ; i<material_dimensions ; ++i )
g[i] = f[_order[i]];
return g;
}
void addapply( OutCoord& result, const InCoord& data )
{
Inherited::addapply( result, data );
// find order result.getStrain()[i]
findOrder( result.getStrain() );
}
};
/// layer over PrincipalStretchesMapping that is able to order given child forces in the same order while computing J
template <class TIn, class TOut>
class PrincipalStretchesMappingTester : public BaseStrainMappingT<PrincipalStretchesJacobianBlockTester<TIn,TOut> >
{
public:
typedef BaseStrainMappingT<PrincipalStretchesJacobianBlockTester<TIn,TOut> > Inherited;
typedef typename Inherited::OutVecDeriv OutVecDeriv;
virtual OutVecDeriv preTreatment( const OutVecDeriv& f )
{
OutVecDeriv g(f.size());
for(unsigned int i=0; i<this->jacobian.size(); i++)
{
g[i] = this->jacobian[i].preTreatment(f[i]);
}
return g;
}
};
template <typename _Mapping>
struct PrincipalStretchesMappingTest : public StrainMappingTest<_Mapping>
{
typedef StrainMappingTest<_Mapping> Inherited;
typedef typename Inherited::In In;
typedef typename Inherited::Real Real;
typedef typename Inherited::OutVecCoord OutVecCoord;
typedef typename Inherited::OutCoord OutCoord;
typedef typename Inherited::OutDeriv OutDeriv;
typedef typename Inherited::OutVecDeriv OutVecDeriv;
template<class V>
V sort( const V& a )
{
V aa( a );
std::sort( &aa[0], &aa[0]+V::total_size );
return aa;
}
/// since principal stretches are oder-independent, sort them before comparison
virtual OutDeriv difference( const OutCoord& a, const OutCoord& b )
{
return (OutDeriv)(sort(a)-sort(b));
}
/// since principal stretches are oder-independent, sort them before comparison
virtual OutVecDeriv difference( const OutVecDeriv& a, const OutVecDeriv& b )
{
if( a.size()!=b.size() ){
ADD_FAILURE() << "OutVecDeriv have different sizes";
return OutVecDeriv();
}
OutVecDeriv c(a.size());
for (size_t i=0; i<(size_t)a.size() ; ++i)
{
c[i] = sort(a[i])-sort(b[i]);
}
return c;
}
/// re-order child forces with the same order used while computing J in apply
virtual OutVecDeriv preTreatment( const OutVecDeriv& f )
{
return static_cast<_Mapping*>(this->mapping)->preTreatment( f );
}
bool runTest()
{
this->deltaRange = std::make_pair( 100, 10000 );
this->errorMax = this->deltaRange.second;
this->errorFactorDJ = 10;
defaulttype::Mat<3,3,Real> rotation;
defaulttype::Mat<In::material_dimensions,In::material_dimensions,Real> strain; // stretch only
for( unsigned int i=0 ; i<In::material_dimensions ; ++i )
{
strain[i][i] = (i+1)*2; // todo randomize it being careful not to obtain negative (even too small) eigenvalues
}
helper::Quater<Real>::fromEuler( 0.1, -.2, .3 ).toMatrix(rotation);
OutVecCoord expectedChildCoords(1);
for( unsigned int i=0 ; i<In::material_dimensions ; ++i )
expectedChildCoords[0].getVec()[i] = strain[i][i];
return Inherited::runTest( rotation, strain, expectedChildCoords );
}
};
// Define the list of types to instanciate.
typedef Types<
PrincipalStretchesMappingTester<defaulttype::F331Types,defaulttype::U331Types>
,PrincipalStretchesMappingTester<defaulttype::F321Types,defaulttype::U321Types>
// ,PrincipalStretchesMapping<defaulttype::F331Types,defaulttype::D331Types> // not fully implemented yet (getJ)
// ,PrincipalStretchesMapping<defaulttype::F321Types,defaulttype::D321Types> // not fully implemented yet (getJ)
> PrincipalStretchesDataTypes; // the types to instanciate.
// Test suite for all the instanciations
TYPED_TEST_CASE(PrincipalStretchesMappingTest, PrincipalStretchesDataTypes);
// first test case
TYPED_TEST( PrincipalStretchesMappingTest , test_auto )
{
ASSERT_TRUE( this->runTest() );
}
} // namespace sofa
<|endoftext|> |
<commit_before>/*
* Copyright 2010, 2011 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CSSSelector.h"
#include <assert.h>
#include <org/w3c/dom/Element.h>
#include "CSSStyleDeclarationImp.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
namespace
{
inline bool find(const std::u16string& s, const std::u16string& t)
{
return s.find(t) != std::u16string::npos;
}
// s is a whitespace-separated list of words
inline bool contains(const std::u16string& s, const std::u16string& t)
{
size_t pos = 0;
for (;;) {
pos = s.find(t, pos);
if (pos == std::u16string::npos)
return false;
if ((pos == 0 || isSpace(s[pos])) && (pos + t.length() == s.length() || isSpace(t[pos])))
return true;
++pos;
}
}
inline bool startsWith(const std::u16string& s, const std::u16string& t)
{
return !s.compare(0, t.length(), t);
}
inline bool endsWith(const std::u16string& s, const std::u16string& t)
{
if (s.length() < t.length())
return false;
return !s.compare(s.length() - t.length(), t.length(), t);
}
}
void CSSSelectorsGroup::serialize(std::u16string& result)
{
for (auto i = selectors.begin(); i != selectors.end(); ++i) {
if (i != selectors.begin())
result += u", ";
(*i)->serialize(result);
if (CSSSerializeControl.serializeSpecificity) {
result += u" /* specificity = ";
result += CSSSerializeHex((*i)->getSpecificity());
result += u" */ ";
}
}
}
void CSSSelector::serialize(std::u16string& result)
{
for (auto i = simpleSelectors.begin(); i != simpleSelectors.end(); ++i)
(*i)->serialize(result);
}
void CSSPrimarySelector::serialize(std::u16string& result)
{
if (combinator) {
if (combinator != u' ') {
result += u' ';
result += static_cast<char16_t>(combinator);
}
result += u' ';
}
if (name == u"*")
result += name;
else
result += CSSSerializeIdentifier(name);
for (auto i = chain.begin(); i != chain.end(); ++i)
(*i)->serialize(result);
}
void CSSAttributeSelector::serialize(std::u16string& result)
{
result += u'[';
result += CSSSerializeIdentifier(name);
if (op) {
result += static_cast<char16_t>(op);
if (op != u'=')
result += u'=';
result += CSSSerializeString(value);
}
result += u']';
}
void CSSNthPseudoClassSelector::serialize(std::u16string& text)
{
text += u':' + CSSSerializeIdentifier(name) + u'(';
if (!a)
text += CSSSerializeInteger(b);
else {
if (a == -1) // TODO: Ask Anne about this.
text += '-';
else if (a != 1 && a != -1)
text += CSSSerializeInteger(a);
text += u'n';
if (b) {
if (0 < b)
text += u'+';
text += CSSSerializeInteger(b);
}
}
text += u')';
}
CSSSpecificity CSSPrimarySelector::getSpecificity() {
CSSSpecificity specificity;
if (name != u"*")
specificity += CSSSpecificity(0, 0, 0, 1);
for (auto i = chain.begin(); i != chain.end(); ++i)
specificity += (*i)->getSpecificity();
return specificity;
}
CSSSpecificity CSSSelector::getSpecificity()
{
CSSSpecificity specificity;
for (auto i = simpleSelectors.begin(); i != simpleSelectors.end(); ++i)
specificity += (*i)->getSpecificity();
return specificity;
}
bool CSSPrimarySelector::match(Element e)
{
if (name != u"*") {
if (e.getLocalName() != name)
return false;
if (namespacePrefix != u"*") {
if (!e.getNamespaceURI().hasValue() || e.getNamespaceURI().value() != namespacePrefix)
return false;
}
}
for (auto i = chain.begin(); i != chain.end(); ++i) {
if (!(*i)->match(e))
return false;
}
return true;
}
bool CSSIDSelector::match(Element e)
{
Nullable<std::u16string> id = e.getAttribute(u"id");
if (!id.hasValue())
return false;
return id.value() == name; // TODO: ignore case
}
bool CSSClassSelector::match(Element e)
{
Nullable<std::u16string> classes = e.getAttribute(u"class");
if (!classes.hasValue())
return false;
return contains(classes.value(), name); // TODO: ignore case
}
bool CSSAttributeSelector::match(Element e)
{
Nullable<std::u16string> attr = e.getAttribute(name);
if (!attr.hasValue())
return false;
switch (op) {
case None:
return true;
case Equals:
return attr.value() == value;
case Includes:
if (attr.value().length() == 0 || contains(attr.value(), u" "))
return false;
return contains(attr.value(), value);
case DashMatch:
if (!startsWith(attr.value(), value))
return false;
return attr.value().length() == value.length() || attr.value()[value.length()] == u'-';
case PrefixMatch:
if (attr.value().length() == 0)
return false;
return startsWith(attr.value(), value);
case SuffixMatch:
if (attr.value().length() == 0)
return false;
return endsWith(attr.value(), value);
case SubstringMatch:
if (attr.value().length() == 0)
return false;
return find(attr.value(), value);
default:
return false;
}
}
bool CSSSelector::match(Element e)
{
if (!e || simpleSelectors.size() == 0)
return false;
auto i = simpleSelectors.rbegin();
if (!(*i)->match(e))
return false;
int combinator = (*i)->getCombinator();
++i;
while (i != simpleSelectors.rend()) {
switch (combinator) {
case CSSPrimarySelector::Descendant:
while (e = e.getParentElement()) { // TODO: do we need to retry from here upon failure?
if ((*i)->match(e))
break;
}
if (!e)
return false;
break;
case CSSPrimarySelector::Child:
e = e.getParentElement();
if (!(*i)->match(e))
return false;
break;
case CSSPrimarySelector::AdjacentSibling:
e = e.getPreviousElementSibling();
if (!(*i)->match(e))
return false;
break;
case CSSPrimarySelector::GeneralSibling:
while (e = e.getPreviousElementSibling()) {
if ((*i)->match(e))
break;
}
if (!e)
return false;
default:
return false;
}
combinator = (*i)->getCombinator();
++i;
}
if (combinator != CSSPrimarySelector::None)
return false;
return true;
}
CSSSelector* CSSSelectorsGroup::match(Element e)
{
specificity = CSSSpecificity();
for (auto i = selectors.begin(); i != selectors.end(); ++i) {
if ((*i)->match(e)) {
specificity = (*i)->getSpecificity();
return *i;
}
}
return 0;
}
CSSPseudoElementSelector* CSSPrimarySelector::getPseudoElement() const {
if (chain.empty())
return 0;
if (CSSPseudoElementSelector* pseudo = dynamic_cast<CSSPseudoElementSelector*>(chain.back()))
return pseudo;
return 0;
}
CSSPseudoElementSelector* CSSSelector::getPseudoElement() const {
if (simpleSelectors.empty())
return 0;
simpleSelectors.back()->getPseudoElement();
}
CSSPseudoElementSelector::CSSPseudoElementSelector(int id) :
CSSPseudoSelector(CSSStyleDeclarationImp::getPseudoElementName(id)),
id(id)
{
}
CSSPseudoSelector* CSSPseudoSelector::createPseudoSelector(int type, const std::u16string& ident)
{
if (type == PseudoClass) {
/* Exceptions: :first-line, :first-letter, :before and :after. */
if (ident == u"first-line" || ident == u"first-letter" || ident == u"before" || ident == u"after")
type = PseudoElement;
}
int id = -1;
switch (type) {
case PseudoClass:
return new(std::nothrow) CSSPseudoClassSelector(ident);
break;
case PseudoElement:
id = CSSStyleDeclarationImp::getPseudoElementID(ident);
if (0 <= id)
return new(std::nothrow) CSSPseudoElementSelector(id);
break;
default:
break;
}
return 0;
}
CSSPseudoSelector* CSSPseudoSelector::createPseudoSelector(int type, const CSSParserTerm& function)
{
switch (type) {
case PseudoClass:
return new(std::nothrow) CSSPseudoClassSelector(function);
break;
case PseudoElement:
// No functional pseudo element is defined in CSS 2.1
break;
default:
break;
}
return 0;
}
}}}} // org::w3c::dom::bootstrap<commit_msg>(contains) : Fix a bug.<commit_after>/*
* Copyright 2010, 2011 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CSSSelector.h"
#include <assert.h>
#include <org/w3c/dom/Element.h>
#include "CSSStyleDeclarationImp.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
namespace
{
inline bool find(const std::u16string& s, const std::u16string& t)
{
return s.find(t) != std::u16string::npos;
}
// s is a whitespace-separated list of words
inline bool contains(const std::u16string& s, const std::u16string& t)
{
size_t pos = 0;
for (;;) {
pos = s.find(t, pos);
if (pos == std::u16string::npos)
return false;
if ((pos == 0 || isSpace(s[pos - 1])) && (pos + t.length() == s.length() || isSpace(s[pos + t.length()])))
return true;
++pos;
}
}
inline bool startsWith(const std::u16string& s, const std::u16string& t)
{
return !s.compare(0, t.length(), t);
}
inline bool endsWith(const std::u16string& s, const std::u16string& t)
{
if (s.length() < t.length())
return false;
return !s.compare(s.length() - t.length(), t.length(), t);
}
}
void CSSSelectorsGroup::serialize(std::u16string& result)
{
for (auto i = selectors.begin(); i != selectors.end(); ++i) {
if (i != selectors.begin())
result += u", ";
(*i)->serialize(result);
if (CSSSerializeControl.serializeSpecificity) {
result += u" /* specificity = ";
result += CSSSerializeHex((*i)->getSpecificity());
result += u" */ ";
}
}
}
void CSSSelector::serialize(std::u16string& result)
{
for (auto i = simpleSelectors.begin(); i != simpleSelectors.end(); ++i)
(*i)->serialize(result);
}
void CSSPrimarySelector::serialize(std::u16string& result)
{
if (combinator) {
if (combinator != u' ') {
result += u' ';
result += static_cast<char16_t>(combinator);
}
result += u' ';
}
if (name == u"*")
result += name;
else
result += CSSSerializeIdentifier(name);
for (auto i = chain.begin(); i != chain.end(); ++i)
(*i)->serialize(result);
}
void CSSAttributeSelector::serialize(std::u16string& result)
{
result += u'[';
result += CSSSerializeIdentifier(name);
if (op) {
result += static_cast<char16_t>(op);
if (op != u'=')
result += u'=';
result += CSSSerializeString(value);
}
result += u']';
}
void CSSNthPseudoClassSelector::serialize(std::u16string& text)
{
text += u':' + CSSSerializeIdentifier(name) + u'(';
if (!a)
text += CSSSerializeInteger(b);
else {
if (a == -1) // TODO: Ask Anne about this.
text += '-';
else if (a != 1 && a != -1)
text += CSSSerializeInteger(a);
text += u'n';
if (b) {
if (0 < b)
text += u'+';
text += CSSSerializeInteger(b);
}
}
text += u')';
}
CSSSpecificity CSSPrimarySelector::getSpecificity() {
CSSSpecificity specificity;
if (name != u"*")
specificity += CSSSpecificity(0, 0, 0, 1);
for (auto i = chain.begin(); i != chain.end(); ++i)
specificity += (*i)->getSpecificity();
return specificity;
}
CSSSpecificity CSSSelector::getSpecificity()
{
CSSSpecificity specificity;
for (auto i = simpleSelectors.begin(); i != simpleSelectors.end(); ++i)
specificity += (*i)->getSpecificity();
return specificity;
}
bool CSSPrimarySelector::match(Element e)
{
if (name != u"*") {
if (e.getLocalName() != name)
return false;
if (namespacePrefix != u"*") {
if (!e.getNamespaceURI().hasValue() || e.getNamespaceURI().value() != namespacePrefix)
return false;
}
}
for (auto i = chain.begin(); i != chain.end(); ++i) {
if (!(*i)->match(e))
return false;
}
return true;
}
bool CSSIDSelector::match(Element e)
{
Nullable<std::u16string> id = e.getAttribute(u"id");
if (!id.hasValue())
return false;
return id.value() == name; // TODO: ignore case
}
bool CSSClassSelector::match(Element e)
{
Nullable<std::u16string> classes = e.getAttribute(u"class");
if (!classes.hasValue())
return false;
return contains(classes.value(), name); // TODO: ignore case
}
bool CSSAttributeSelector::match(Element e)
{
Nullable<std::u16string> attr = e.getAttribute(name);
if (!attr.hasValue())
return false;
switch (op) {
case None:
return true;
case Equals:
return attr.value() == value;
case Includes:
if (attr.value().length() == 0 || contains(attr.value(), u" "))
return false;
return contains(attr.value(), value);
case DashMatch:
if (!startsWith(attr.value(), value))
return false;
return attr.value().length() == value.length() || attr.value()[value.length()] == u'-';
case PrefixMatch:
if (attr.value().length() == 0)
return false;
return startsWith(attr.value(), value);
case SuffixMatch:
if (attr.value().length() == 0)
return false;
return endsWith(attr.value(), value);
case SubstringMatch:
if (attr.value().length() == 0)
return false;
return find(attr.value(), value);
default:
return false;
}
}
bool CSSSelector::match(Element e)
{
if (!e || simpleSelectors.size() == 0)
return false;
auto i = simpleSelectors.rbegin();
if (!(*i)->match(e))
return false;
int combinator = (*i)->getCombinator();
++i;
while (i != simpleSelectors.rend()) {
switch (combinator) {
case CSSPrimarySelector::Descendant:
while (e = e.getParentElement()) { // TODO: do we need to retry from here upon failure?
if ((*i)->match(e))
break;
}
if (!e)
return false;
break;
case CSSPrimarySelector::Child:
e = e.getParentElement();
if (!(*i)->match(e))
return false;
break;
case CSSPrimarySelector::AdjacentSibling:
e = e.getPreviousElementSibling();
if (!(*i)->match(e))
return false;
break;
case CSSPrimarySelector::GeneralSibling:
while (e = e.getPreviousElementSibling()) {
if ((*i)->match(e))
break;
}
if (!e)
return false;
default:
return false;
}
combinator = (*i)->getCombinator();
++i;
}
if (combinator != CSSPrimarySelector::None)
return false;
return true;
}
CSSSelector* CSSSelectorsGroup::match(Element e)
{
specificity = CSSSpecificity();
for (auto i = selectors.begin(); i != selectors.end(); ++i) {
if ((*i)->match(e)) {
specificity = (*i)->getSpecificity();
return *i;
}
}
return 0;
}
CSSPseudoElementSelector* CSSPrimarySelector::getPseudoElement() const {
if (chain.empty())
return 0;
if (CSSPseudoElementSelector* pseudo = dynamic_cast<CSSPseudoElementSelector*>(chain.back()))
return pseudo;
return 0;
}
CSSPseudoElementSelector* CSSSelector::getPseudoElement() const {
if (simpleSelectors.empty())
return 0;
simpleSelectors.back()->getPseudoElement();
}
CSSPseudoElementSelector::CSSPseudoElementSelector(int id) :
CSSPseudoSelector(CSSStyleDeclarationImp::getPseudoElementName(id)),
id(id)
{
}
CSSPseudoSelector* CSSPseudoSelector::createPseudoSelector(int type, const std::u16string& ident)
{
if (type == PseudoClass) {
/* Exceptions: :first-line, :first-letter, :before and :after. */
if (ident == u"first-line" || ident == u"first-letter" || ident == u"before" || ident == u"after")
type = PseudoElement;
}
int id = -1;
switch (type) {
case PseudoClass:
return new(std::nothrow) CSSPseudoClassSelector(ident);
break;
case PseudoElement:
id = CSSStyleDeclarationImp::getPseudoElementID(ident);
if (0 <= id)
return new(std::nothrow) CSSPseudoElementSelector(id);
break;
default:
break;
}
return 0;
}
CSSPseudoSelector* CSSPseudoSelector::createPseudoSelector(int type, const CSSParserTerm& function)
{
switch (type) {
case PseudoClass:
return new(std::nothrow) CSSPseudoClassSelector(function);
break;
case PseudoElement:
// No functional pseudo element is defined in CSS 2.1
break;
default:
break;
}
return 0;
}
}}}} // org::w3c::dom::bootstrap<|endoftext|> |
<commit_before>#include <isl/set.h>
#include <isl/union_map.h>
#include <isl/union_set.h>
#include <isl/ast_build.h>
#include <isl/schedule.h>
#include <isl/schedule_node.h>
#include <tiramisu/debug.h>
#include <tiramisu/core.h>
#include <tiramisu/utils.h>
#include <string.h>
#include "configure.h"
#define SCHEDULE_CPU 1
using namespace tiramisu;
int main(int argc, char **argv)
{
init("conv_tiramisu");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
// N: parameters[0]
// K: parameters[1]
// FIn: parameters[2]
// FOut: parameters[3]
// BATCH_SIZE: parameters[4]
var i("i", 0, 5);
input parameters("parameters",{i}, p_int32);
constant C_N("C_N", parameters(0)+ parameters(1));
constant C_N1("C_N1",parameters(0));
constant C_K("C_K", parameters(1));
constant C_FIn("C_FIn", parameters(2));
constant C_FOut("C_FOut", parameters(3));
constant C_BATCH_SIZE("C_BATCH_SIZE", parameters(4));
var x("x", 0, C_N ), y("y", 0, C_N), z("z", 0, C_FOut), n("n", 0, C_BATCH_SIZE ); // input
var k_x("k_x",0,C_K), k_y("k_y",0,C_K), k_z("k_z",0,C_FIn); // filter variables
var x1("x1", 0, C_N1), y1("y1", 0, C_N1); // conv
// Input computations
input c_input("c_input",{n, k_z, y, x} , p_float32);
input bias("bias", {z}, p_float32);
input filter("filter", {z, k_z , k_y, k_x}, p_float32);
// First conv computations
computation conv_init("conv_init",{n, z, y1, x1}, bias(z) );
computation conv("conv",{n, z, y1, x1, k_z, k_y, k_x }, conv_init(n, z, y1, x1) + filter(z, k_z, k_y, k_x) * c_input(n, k_z, y1 + k_y, x1 + k_x));
global::get_implicit_function()->add_context_constraints("[C_N, C_K, C_FIn, C_FOut, C_BATCH_SIZE]->{:C_N>1 and C_K>1 and C_FOut>1 and C_FIn>0 and C_BATCH_SIZE>1 and C_K=5 and C_FIn%16=0 and C_N%16=0}");
// Layer II
if (LARGE_DATA_SET)
{
if (0) {
int vec_len = 32;
int y_block = 32;
int o_block = 4;
conv_init.tag_parallel_level(0);
conv_init.split(3, vec_len);
conv_init.tag_vector_level(4, vec_len);
conv.after(conv_init, 1);
conv.interchange(3, 4);
// conv_init.tile(1, 2, 32, 32);
// conv.tile(1, 2, 32, 32);
// conv.split(1, o_block);
conv.split(2, y_block);
conv.split(5, vec_len);
conv.tag_vector_level(6, vec_len);
conv.tag_unroll_level(7);
conv.tag_unroll_level(8);
}
if (0) {
int vec_len = 32;
int y_block = 32;
int o_block = 4;
conv_init.tag_parallel_level(0);
conv.after(conv_init, 2);
// 0, 1, 2, 3, 4, 5, 6,
// n, z, y, x, r_z, r_y, r_x,
conv.interchange(3, 4);
// n, z, y r_z, x, r_y, r_x,
conv.split(1, o_block);
conv_init.split(1, o_block);
conv.split(3, y_block);
conv.split(6, vec_len);
conv.tag_vector_level(7, vec_len);
conv.tag_unroll_level(9);
conv_init.split(4, vec_len);
conv_init.tag_vector_level(5, vec_len);
}
if (1)
{
int vec_len = 32;
int y_block = 32;
int o_block = 4;
conv_init.tag_parallel_level(0);
conv.after(conv_init, 2);
// 0, 1, 2, 3, 4, 5, 6,
// n, z, y, x, r_z, r_y, r_x,
conv.interchange(3, 4);
// n, z, y, (r_z, x), r_y, r_x,
conv.interchange(3, 2);
// n, z, (r_z, y), x, r_y, r_x,
conv.split(1, o_block);
conv_init.split(1, o_block);
// n, (z, z_t), r_z, y, x, r_y, r_x,
conv.split(3, y_block);
conv.split(6, vec_len);
conv.tag_vector_level(7, vec_len);
conv.tag_unroll_level(8);
conv.tag_unroll_level(9);
// n, z, z_t, r_z, (y, y_t), x, r_y, r_x,
conv_init.split(4, vec_len);
conv_init.tag_vector_level(5, vec_len);
}
}
else if (MEDIUM_DATA_SET)
{
if (0) // Replicate of Halide's schedule. But Halide = 18ms and Tiramisu=54ms, so there is a problem in Tiramisu code generator.
{
int vec_len = 32;
int y_block = 32;
int o_block = 4;
conv_init.tag_parallel_level(0);
conv.after(conv_init, tiramisu::computation::root_dimension);
// 0, 1, 2, 3, 4, 5, 6,
// n, z, y, x, r_z, r_y, r_x,
conv.interchange(3, 4);
// n, z, y, (r_z, x), r_y, r_x,
conv.interchange(3, 2);
// n, z, (r_z, y), x, r_y, r_x,
conv.split(1, o_block);
// n, (z, z_t), r_z, y, x, r_y, r_x,
conv.split(4, y_block);
// n, z, z_t, r_z, (y, y_t), x, r_y, r_x,
conv.interchange(2, 3);
// n, z, (r_z, z_t), y, y_t, x, r_y, r_x,
conv.interchange(3, 4);
// n, z, r_z, (y, z_t), y_t, x, r_y, r_x,
conv.split(6, vec_len);
conv.tag_vector_level(7, vec_len);
conv.tag_unroll_level(8);
conv.tag_unroll_level(9);
conv_init.split(3, vec_len);
conv_init.tag_vector_level(4, vec_len);
}
if (1)
{
int vec_len = 32;
int y_block = 32;
int o_block = 4;
conv_init.tag_parallel_level(0);
conv.after(conv_init, 2);
// 0, 1, 2, 3, 4, 5, 6,
// n, z, y, x, r_z, r_y, r_x,
conv.interchange(3, 4);
// n, z, y, (r_z, x), r_y, r_x,
conv.interchange(3, 2);
// n, z, (r_z, y), x, r_y, r_x,
conv.split(1, o_block);
conv_init.split(1, o_block);
// n, (z, z_t), r_z, y, x, r_y, r_x,
conv.split(3, y_block);
conv.split(6, vec_len);
conv.tag_vector_level(7, vec_len);
// n, z, z_t, r_z, (y, y_t), x, r_y, r_x,
conv_init.split(4, vec_len);
conv_init.tag_vector_level(5, vec_len);
}
}
else if (SMALL_DATA_SET)
{
int vec_len = 16;
int y_block = 8;
int o_block = 4;
conv_init.tag_parallel_level(0);
conv.after(conv_init, 2);
// 0, 1, 2, 3, 4, 5, 6,
// n, z, y, x, r_z, r_y, r_x,
conv.interchange(3, 4);
// n, z, y, (r_z, x), r_y, r_x,
conv.interchange(3, 2);
// n, z, (r_z, y), x, r_y, r_x,
conv.split(1, o_block);
conv_init.split(1, o_block);
// n, (z, z_t), r_z, y, x, r_y, r_x,
conv.split(3, y_block);
conv.split(6, vec_len);
conv.tag_vector_level(7, vec_len);
// n, z, z_t, r_z, (y, y_t), x, r_y, r_x,
conv_init.split(4, vec_len);
conv_init.tag_vector_level(5, vec_len);
}
// Layer III
buffer parameters_buf("parameters_buf", {expr(5)}, p_int32, a_input);
buffer input_buf("input_buf", {expr(C_BATCH_SIZE), expr(C_FIn), expr(C_N), expr(C_N)}, p_float32, a_input);
buffer conv_buf("conv_buf", {expr(C_BATCH_SIZE), expr(C_FOut), expr(C_N1), expr(C_N1)}, p_float32, a_output);
buffer filter_buf("filter_buf", {expr(C_FOut), expr(C_FIn), expr(C_K), expr(C_K)}, p_float32, a_input);
buffer bias_buf("bias_buf", {expr(C_FOut)}, p_float32, a_input);
parameters.store_in(¶meters_buf);
c_input.store_in(&input_buf);
bias.store_in(&bias_buf);
filter.store_in(&filter_buf);
conv_init.store_in(&conv_buf);
conv.store_in(&conv_buf,{n, z, y1, x1});
tiramisu::codegen({¶meters_buf, &input_buf, &filter_buf, &bias_buf, &conv_buf},"generated_conv_tiramisu.o");
return 0;
}
#if 0
int main(int argc, char **argv)
{
ImageParam input{Float(32), 4, "input"};
ImageParam filter{Float(32), 4, "filter"};
ImageParam bias{Float(32), 1, "bias"};
Var x("x"), y("y"), z("z"), n("n");
Func f_conv("conv");
RDom r(0, K, 0, K, 0, FIn);
f_conv(x, y, z, n) = bias(z);
f_conv(x, y, z, n) += filter(r.x, r.y, r.z, z) * input(x + r.x, y + r.y, r.z, n);
/* THE SCHEDULE */
if (SCHEDULE_CPU)
{
if (LARGE_DATA_SET)
{
// Blocking spatially with vectorization
Var z_t("z_t"), y_t("y_t"), par("par");
int vec_len = 128;
int o_block_size = 8;
int y_block = 32;
f_conv.compute_root();
f_conv.fuse(z, n, par).parallel(par);
f_conv.update().reorder(x, y, r.z);
f_conv.update().split(y, y, y_t, y_block);
f_conv.update().split(z, z, z_t, o_block_size);
f_conv.update().reorder(y_t, z_t, y, r.z, z);
f_conv.update().vectorize(x, vec_len);
f_conv.update().unroll(r.x);
f_conv.update().unroll(r.y);
f_conv.update().fuse(z, n, par).parallel(par);
}
else if (MEDIUM_DATA_SET)
{
// Blocking spatially with vectorization
Var z_t("z_t"), y_t("y_t"), par("par");
int vec_len = 32;
int o_block_size = 4;
int y_block = 32;
f_conv.compute_root();
f_conv.fuse(z, n, par).parallel(par);
f_conv.update().reorder(x, y, r.z);
f_conv.update().split(y, y, y_t, y_block);
f_conv.update().split(z, z, z_t, o_block_size);
f_conv.update().reorder(y_t, z_t, y, r.z, z);
f_conv.update().vectorize(x, vec_len);
f_conv.update().unroll(r.x);
f_conv.update().unroll(r.y);
f_conv.update().fuse(z, n, par).parallel(par);
}
else if (SMALL_DATA_SET)
{
// Blocking spatially with vectorization
Var z_t("z_t"), y_t("y_t"), par("par");
int vec_len = 32;
int o_block_size = 8;
int y_block = 32;
f_conv.compute_root();
f_conv.parallel(n);
f_conv.update().reorder(x, y, r.z);
f_conv.update().split(y, y, y_t, y_block);
f_conv.update().split(z, z, z_t, o_block_size);
f_conv.update().reorder(y_t, z_t, y, r.z, z);
f_conv.update().vectorize(x, vec_len);
f_conv.update().unroll(r.x);
f_conv.update().unroll(r.y);
f_conv.update().fuse(z, n, par).parallel(par);
}
}
Halide::Target target = Halide::get_host_target();
f_conv.compile_to_object("generated_conv.o",
{input, filter, bias},
"conv_halide",
target);
return 0;
}
#endif
<commit_msg>Remove unused schedules from conv<commit_after>#include <isl/set.h>
#include <isl/union_map.h>
#include <isl/union_set.h>
#include <isl/ast_build.h>
#include <isl/schedule.h>
#include <isl/schedule_node.h>
#include <tiramisu/debug.h>
#include <tiramisu/core.h>
#include <tiramisu/utils.h>
#include <string.h>
#include "configure.h"
#define SCHEDULE_CPU 1
using namespace tiramisu;
int main(int argc, char **argv)
{
init("conv_tiramisu");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
// N: parameters[0]
// K: parameters[1]
// FIn: parameters[2]
// FOut: parameters[3]
// BATCH_SIZE: parameters[4]
var i("i", 0, 5);
input parameters("parameters",{i}, p_int32);
constant C_N("C_N", parameters(0)+ parameters(1));
constant C_N1("C_N1",parameters(0));
constant C_K("C_K", parameters(1));
constant C_FIn("C_FIn", parameters(2));
constant C_FOut("C_FOut", parameters(3));
constant C_BATCH_SIZE("C_BATCH_SIZE", parameters(4));
var x("x", 0, C_N ), y("y", 0, C_N), z("z", 0, C_FOut), n("n", 0, C_BATCH_SIZE ); // input
var k_x("k_x",0,C_K), k_y("k_y",0,C_K), k_z("k_z",0,C_FIn); // filter variables
var x1("x1", 0, C_N1), y1("y1", 0, C_N1); // conv
// Input computations
input c_input("c_input",{n, k_z, y, x} , p_float32);
input bias("bias", {z}, p_float32);
input filter("filter", {z, k_z , k_y, k_x}, p_float32);
// First conv computations
computation conv_init("conv_init",{n, z, y1, x1}, bias(z) );
computation conv("conv",{n, z, y1, x1, k_z, k_y, k_x }, conv_init(n, z, y1, x1) + filter(z, k_z, k_y, k_x) * c_input(n, k_z, y1 + k_y, x1 + k_x));
global::get_implicit_function()->add_context_constraints("[C_N, C_K, C_FIn, C_FOut, C_BATCH_SIZE]->{:C_N>1 and C_K>1 and C_FOut>1 and C_FIn>0 and C_BATCH_SIZE>1 and C_K=5 and C_FIn%16=0 and C_N%16=0}");
// Layer II
if (LARGE_DATA_SET)
{
int vec_len = 32;
int y_block = 32;
int o_block = 4;
conv_init.tag_parallel_level(0);
conv.after(conv_init, 2);
// 0, 1, 2, 3, 4, 5, 6,
// n, z, y, x, r_z, r_y, r_x,
conv.interchange(3, 4);
// n, z, y, (r_z, x), r_y, r_x,
conv.interchange(3, 2);
// n, z, (r_z, y), x, r_y, r_x,
conv.split(1, o_block);
conv_init.split(1, o_block);
// n, (z, z_t), r_z, y, x, r_y, r_x,
conv.split(3, y_block);
conv.split(6, vec_len);
conv.tag_vector_level(7, vec_len);
conv.tag_unroll_level(8);
conv.tag_unroll_level(9);
// n, z, z_t, r_z, (y, y_t), x, r_y, r_x,
conv_init.split(4, vec_len);
conv_init.tag_vector_level(5, vec_len);
}
else if (MEDIUM_DATA_SET)
{
int vec_len = 32;
int y_block = 32;
int o_block = 4;
conv_init.tag_parallel_level(0);
conv.after(conv_init, 2);
// 0, 1, 2, 3, 4, 5, 6,
// n, z, y, x, r_z, r_y, r_x,
conv.interchange(3, 4);
// n, z, y, (r_z, x), r_y, r_x,
conv.interchange(3, 2);
// n, z, (r_z, y), x, r_y, r_x,
conv.split(1, o_block);
conv_init.split(1, o_block);
// n, (z, z_t), r_z, y, x, r_y, r_x,
conv.split(3, y_block);
conv.split(6, vec_len);
conv.tag_vector_level(7, vec_len);
// n, z, z_t, r_z, (y, y_t), x, r_y, r_x,
conv_init.split(4, vec_len);
conv_init.tag_vector_level(5, vec_len);
}
else if (SMALL_DATA_SET)
{
int vec_len = 16;
int y_block = 8;
int o_block = 4;
conv_init.tag_parallel_level(0);
conv.after(conv_init, 2);
// 0, 1, 2, 3, 4, 5, 6,
// n, z, y, x, r_z, r_y, r_x,
conv.interchange(3, 4);
// n, z, y, (r_z, x), r_y, r_x,
conv.interchange(3, 2);
// n, z, (r_z, y), x, r_y, r_x,
conv.split(1, o_block);
conv_init.split(1, o_block);
// n, (z, z_t), r_z, y, x, r_y, r_x,
conv.split(3, y_block);
conv.split(6, vec_len);
conv.tag_vector_level(7, vec_len);
// n, z, z_t, r_z, (y, y_t), x, r_y, r_x,
conv_init.split(4, vec_len);
conv_init.tag_vector_level(5, vec_len);
}
// Layer III
buffer parameters_buf("parameters_buf", {expr(5)}, p_int32, a_input);
buffer input_buf("input_buf", {expr(C_BATCH_SIZE), expr(C_FIn), expr(C_N), expr(C_N)}, p_float32, a_input);
buffer conv_buf("conv_buf", {expr(C_BATCH_SIZE), expr(C_FOut), expr(C_N1), expr(C_N1)}, p_float32, a_output);
buffer filter_buf("filter_buf", {expr(C_FOut), expr(C_FIn), expr(C_K), expr(C_K)}, p_float32, a_input);
buffer bias_buf("bias_buf", {expr(C_FOut)}, p_float32, a_input);
parameters.store_in(¶meters_buf);
c_input.store_in(&input_buf);
bias.store_in(&bias_buf);
filter.store_in(&filter_buf);
conv_init.store_in(&conv_buf);
conv.store_in(&conv_buf,{n, z, y1, x1});
tiramisu::codegen({¶meters_buf, &input_buf, &filter_buf, &bias_buf, &conv_buf},"generated_conv_tiramisu.o");
return 0;
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2011 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
#include "OgreCompositor.h"
#include "OgreCompositionTechnique.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreTextureManager.h"
#include "OgreHardwarePixelBuffer.h"
namespace Ogre {
//-----------------------------------------------------------------------
Compositor::Compositor(ResourceManager* creator, const String& name, ResourceHandle handle,
const String& group, bool isManual, ManualResourceLoader* loader):
Resource(creator, name, handle, group, isManual, loader),
mCompilationRequired(true)
{
}
//-----------------------------------------------------------------------
Compositor::~Compositor()
{
removeAllTechniques();
// have to call this here reather than in Resource destructor
// since calling virtual methods in base destructors causes crash
unload();
}
//-----------------------------------------------------------------------
CompositionTechnique *Compositor::createTechnique()
{
CompositionTechnique *t = OGRE_NEW CompositionTechnique(this);
mTechniques.push_back(t);
mCompilationRequired = true;
return t;
}
//-----------------------------------------------------------------------
void Compositor::removeTechnique(size_t index)
{
assert (index < mTechniques.size() && "Index out of bounds.");
Techniques::iterator i = mTechniques.begin() + index;
OGRE_DELETE (*i);
mTechniques.erase(i);
mSupportedTechniques.clear();
mCompilationRequired = true;
}
//-----------------------------------------------------------------------
CompositionTechnique *Compositor::getTechnique(size_t index)
{
assert (index < mTechniques.size() && "Index out of bounds.");
return mTechniques[index];
}
//-----------------------------------------------------------------------
size_t Compositor::getNumTechniques()
{
return mTechniques.size();
}
//-----------------------------------------------------------------------
void Compositor::removeAllTechniques()
{
Techniques::iterator i, iend;
iend = mTechniques.end();
for (i = mTechniques.begin(); i != iend; ++i)
{
OGRE_DELETE (*i);
}
mTechniques.clear();
mSupportedTechniques.clear();
mCompilationRequired = true;
}
//-----------------------------------------------------------------------
Compositor::TechniqueIterator Compositor::getTechniqueIterator(void)
{
return TechniqueIterator(mTechniques.begin(), mTechniques.end());
}
//-----------------------------------------------------------------------
CompositionTechnique *Compositor::getSupportedTechnique(size_t index)
{
assert (index < mSupportedTechniques.size() && "Index out of bounds.");
return mSupportedTechniques[index];
}
//-----------------------------------------------------------------------
size_t Compositor::getNumSupportedTechniques()
{
return mSupportedTechniques.size();
}
//-----------------------------------------------------------------------
Compositor::TechniqueIterator Compositor::getSupportedTechniqueIterator(void)
{
return TechniqueIterator(mSupportedTechniques.begin(), mSupportedTechniques.end());
}
//-----------------------------------------------------------------------
void Compositor::loadImpl(void)
{
// compile if required
if (mCompilationRequired)
compile();
createGlobalTextures();
}
//-----------------------------------------------------------------------
void Compositor::unloadImpl(void)
{
freeGlobalTextures();
}
//-----------------------------------------------------------------------
size_t Compositor::calculateSize(void) const
{
return 0;
}
//-----------------------------------------------------------------------
void Compositor::compile()
{
/// Sift out supported techniques
mSupportedTechniques.clear();
Techniques::iterator i, iend;
iend = mTechniques.end();
// Try looking for exact technique support with no texture fallback
for (i = mTechniques.begin(); i != iend; ++i)
{
// Look for exact texture support first
if((*i)->isSupported(false))
{
mSupportedTechniques.push_back(*i);
}
}
if (mSupportedTechniques.empty())
{
// Check again, being more lenient with textures
for (i = mTechniques.begin(); i != iend; ++i)
{
// Allow texture support with degraded pixel format
if((*i)->isSupported(true))
{
mSupportedTechniques.push_back(*i);
}
}
}
mCompilationRequired = false;
}
//---------------------------------------------------------------------
CompositionTechnique* Compositor::getSupportedTechnique(const String& schemeName)
{
for(Techniques::iterator i = mSupportedTechniques.begin(); i != mSupportedTechniques.end(); ++i)
{
if ((*i)->getSchemeName() == schemeName)
{
return *i;
}
}
// didn't find a matching one
for(Techniques::iterator i = mSupportedTechniques.begin(); i != mSupportedTechniques.end(); ++i)
{
if ((*i)->getSchemeName() == StringUtil::BLANK)
{
return *i;
}
}
return 0;
}
//-----------------------------------------------------------------------
String getMRTTexLocalName(const String& baseName, size_t attachment)
{
return baseName + "/" + StringConverter::toString(attachment);
}
//-----------------------------------------------------------------------
void Compositor::createGlobalTextures()
{
static size_t dummyCounter = 0;
if (mSupportedTechniques.empty())
return;
//To make sure that we are consistent, it is demanded that all composition
//techniques define the same set of global textures.
typedef std::set<String> StringSet;
StringSet globalTextureNames;
//Initialize global textures from first supported technique
CompositionTechnique* firstTechnique = mSupportedTechniques[0];
CompositionTechnique::TextureDefinitionIterator texDefIt =
firstTechnique->getTextureDefinitionIterator();
while (texDefIt.hasMoreElements())
{
CompositionTechnique::TextureDefinition* def = texDefIt.getNext();
if (def->scope == CompositionTechnique::TS_GLOBAL)
{
//Check that this is a legit global texture
if (!def->refCompName.empty())
{
OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
"Global compositor texture definition can not be a reference",
"Compositor::createGlobalTextures");
}
if (def->width == 0 || def->height == 0)
{
OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
"Global compositor texture definition must have absolute size",
"Compositor::createGlobalTextures");
}
if (def->pooled)
{
LogManager::getSingleton().logMessage(
"Pooling global compositor textures has no effect");
}
globalTextureNames.insert(def->name);
//TODO GSOC : Heavy copy-pasting from CompositorInstance. How to we solve it?
/// Make the tetxure
RenderTarget* rendTarget;
if (def->formatList.size() > 1)
{
String MRTbaseName = "c" + StringConverter::toString(dummyCounter++) +
"/" + mName + "/" + def->name;
MultiRenderTarget* mrt =
Root::getSingleton().getRenderSystem()->createMultiRenderTarget(MRTbaseName);
mGlobalMRTs[def->name] = mrt;
// create and bind individual surfaces
size_t atch = 0;
for (PixelFormatList::iterator p = def->formatList.begin();
p != def->formatList.end(); ++p, ++atch)
{
String texname = MRTbaseName + "/" + StringConverter::toString(atch);
TexturePtr tex;
tex = TextureManager::getSingleton().createManual(
texname,
ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
(uint)def->width, (uint)def->height, 0, *p, TU_RENDERTARGET, 0,
def->hwGammaWrite && !PixelUtil::isFloatingPoint(*p), def->fsaa);
RenderTexture* rt = tex->getBuffer()->getRenderTarget();
rt->setAutoUpdated(false);
mrt->bindSurface(atch, rt);
// Also add to local textures so we can look up
String mrtLocalName = getMRTTexLocalName(def->name, atch);
mGlobalTextures[mrtLocalName] = tex;
}
rendTarget = mrt;
}
else
{
String texName = "c" + StringConverter::toString(dummyCounter++) +
"/" + mName + "/" + def->name;
// space in the name mixup the cegui in the compositor demo
// this is an auto generated name - so no spaces can't hart us.
std::replace( texName.begin(), texName.end(), ' ', '_' );
TexturePtr tex;
tex = TextureManager::getSingleton().createManual(
texName,
ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
(uint)def->width, (uint)def->height, 0, def->formatList[0], TU_RENDERTARGET, 0,
def->hwGammaWrite && !PixelUtil::isFloatingPoint(def->formatList[0]), def->fsaa);
rendTarget = tex->getBuffer()->getRenderTarget();
mGlobalTextures[def->name] = tex;
}
//Set DepthBuffer pool for sharing
rendTarget->setDepthBufferPool( def->depthBufferId );
}
}
//Validate that all other supported techniques expose the same set of global textures.
for (size_t i=1; i<mSupportedTechniques.size(); i++)
{
CompositionTechnique* technique = mSupportedTechniques[i];
bool isConsistent = true;
size_t numGlobals = 0;
texDefIt = technique->getTextureDefinitionIterator();
while (texDefIt.hasMoreElements())
{
CompositionTechnique::TextureDefinition* texDef = texDefIt.getNext();
if (texDef->scope == CompositionTechnique::TS_GLOBAL)
{
if (globalTextureNames.find(texDef->name) == globalTextureNames.end())
{
isConsistent = false;
break;
}
numGlobals++;
}
}
if (numGlobals != globalTextureNames.size())
isConsistent = false;
if (!isConsistent)
{
OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
"Different composition techniques define different global textures",
"Compositor::createGlobalTextures");
}
}
}
//-----------------------------------------------------------------------
void Compositor::freeGlobalTextures()
{
GlobalTextureMap::iterator i = mGlobalTextures.begin();
while (i != mGlobalTextures.end())
{
TextureManager::getSingleton().remove(i->second->getName());
i++;
}
mGlobalTextures.clear();
GlobalMRTMap::iterator mrti = mGlobalMRTs.begin();
while (mrti != mGlobalMRTs.end())
{
// remove MRT
Root::getSingleton().getRenderSystem()->destroyRenderTarget(mrti->second->getName());
mrti++;
}
mGlobalMRTs.clear();
}
//-----------------------------------------------------------------------
const String& Compositor::getTextureInstanceName(const String& name, size_t mrtIndex)
{
return getTextureInstance(name, mrtIndex)->getName();
}
//-----------------------------------------------------------------------
TexturePtr Compositor::getTextureInstance(const String& name, size_t mrtIndex)
{
//Try simple texture
GlobalTextureMap::iterator i = mGlobalTextures.find(name);
if(i != mGlobalTextures.end())
{
return i->second;
}
//Try MRT
String mrtName = getMRTTexLocalName(name, mrtIndex);
i = mGlobalTextures.find(name);
if(i != mGlobalTextures.end())
{
return i->second;
}
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Non-existent global texture name",
"Compositor::getTextureInstance")
}
//---------------------------------------------------------------------
RenderTarget* Compositor::getRenderTarget(const String& name)
{
// try simple texture
GlobalTextureMap::iterator i = mGlobalTextures.find(name);
if(i != mGlobalTextures.end())
return i->second->getBuffer()->getRenderTarget();
// try MRTs
GlobalMRTMap::iterator mi = mGlobalMRTs.find(name);
if (mi != mGlobalMRTs.end())
return mi->second;
else
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Non-existent global texture name",
"Compositor::getRenderTarget");
}
//---------------------------------------------------------------------
}
<commit_msg>Bug 474: Fix Compositor::getTextureInstance to use the MRT name when searching for a MRT texture name<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2011 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
#include "OgreCompositor.h"
#include "OgreCompositionTechnique.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreTextureManager.h"
#include "OgreHardwarePixelBuffer.h"
namespace Ogre {
//-----------------------------------------------------------------------
Compositor::Compositor(ResourceManager* creator, const String& name, ResourceHandle handle,
const String& group, bool isManual, ManualResourceLoader* loader):
Resource(creator, name, handle, group, isManual, loader),
mCompilationRequired(true)
{
}
//-----------------------------------------------------------------------
Compositor::~Compositor()
{
removeAllTechniques();
// have to call this here reather than in Resource destructor
// since calling virtual methods in base destructors causes crash
unload();
}
//-----------------------------------------------------------------------
CompositionTechnique *Compositor::createTechnique()
{
CompositionTechnique *t = OGRE_NEW CompositionTechnique(this);
mTechniques.push_back(t);
mCompilationRequired = true;
return t;
}
//-----------------------------------------------------------------------
void Compositor::removeTechnique(size_t index)
{
assert (index < mTechniques.size() && "Index out of bounds.");
Techniques::iterator i = mTechniques.begin() + index;
OGRE_DELETE (*i);
mTechniques.erase(i);
mSupportedTechniques.clear();
mCompilationRequired = true;
}
//-----------------------------------------------------------------------
CompositionTechnique *Compositor::getTechnique(size_t index)
{
assert (index < mTechniques.size() && "Index out of bounds.");
return mTechniques[index];
}
//-----------------------------------------------------------------------
size_t Compositor::getNumTechniques()
{
return mTechniques.size();
}
//-----------------------------------------------------------------------
void Compositor::removeAllTechniques()
{
Techniques::iterator i, iend;
iend = mTechniques.end();
for (i = mTechniques.begin(); i != iend; ++i)
{
OGRE_DELETE (*i);
}
mTechniques.clear();
mSupportedTechniques.clear();
mCompilationRequired = true;
}
//-----------------------------------------------------------------------
Compositor::TechniqueIterator Compositor::getTechniqueIterator(void)
{
return TechniqueIterator(mTechniques.begin(), mTechniques.end());
}
//-----------------------------------------------------------------------
CompositionTechnique *Compositor::getSupportedTechnique(size_t index)
{
assert (index < mSupportedTechniques.size() && "Index out of bounds.");
return mSupportedTechniques[index];
}
//-----------------------------------------------------------------------
size_t Compositor::getNumSupportedTechniques()
{
return mSupportedTechniques.size();
}
//-----------------------------------------------------------------------
Compositor::TechniqueIterator Compositor::getSupportedTechniqueIterator(void)
{
return TechniqueIterator(mSupportedTechniques.begin(), mSupportedTechniques.end());
}
//-----------------------------------------------------------------------
void Compositor::loadImpl(void)
{
// compile if required
if (mCompilationRequired)
compile();
createGlobalTextures();
}
//-----------------------------------------------------------------------
void Compositor::unloadImpl(void)
{
freeGlobalTextures();
}
//-----------------------------------------------------------------------
size_t Compositor::calculateSize(void) const
{
return 0;
}
//-----------------------------------------------------------------------
void Compositor::compile()
{
/// Sift out supported techniques
mSupportedTechniques.clear();
Techniques::iterator i, iend;
iend = mTechniques.end();
// Try looking for exact technique support with no texture fallback
for (i = mTechniques.begin(); i != iend; ++i)
{
// Look for exact texture support first
if((*i)->isSupported(false))
{
mSupportedTechniques.push_back(*i);
}
}
if (mSupportedTechniques.empty())
{
// Check again, being more lenient with textures
for (i = mTechniques.begin(); i != iend; ++i)
{
// Allow texture support with degraded pixel format
if((*i)->isSupported(true))
{
mSupportedTechniques.push_back(*i);
}
}
}
mCompilationRequired = false;
}
//---------------------------------------------------------------------
CompositionTechnique* Compositor::getSupportedTechnique(const String& schemeName)
{
for(Techniques::iterator i = mSupportedTechniques.begin(); i != mSupportedTechniques.end(); ++i)
{
if ((*i)->getSchemeName() == schemeName)
{
return *i;
}
}
// didn't find a matching one
for(Techniques::iterator i = mSupportedTechniques.begin(); i != mSupportedTechniques.end(); ++i)
{
if ((*i)->getSchemeName() == StringUtil::BLANK)
{
return *i;
}
}
return 0;
}
//-----------------------------------------------------------------------
String getMRTTexLocalName(const String& baseName, size_t attachment)
{
return baseName + "/" + StringConverter::toString(attachment);
}
//-----------------------------------------------------------------------
void Compositor::createGlobalTextures()
{
static size_t dummyCounter = 0;
if (mSupportedTechniques.empty())
return;
//To make sure that we are consistent, it is demanded that all composition
//techniques define the same set of global textures.
typedef std::set<String> StringSet;
StringSet globalTextureNames;
//Initialize global textures from first supported technique
CompositionTechnique* firstTechnique = mSupportedTechniques[0];
CompositionTechnique::TextureDefinitionIterator texDefIt =
firstTechnique->getTextureDefinitionIterator();
while (texDefIt.hasMoreElements())
{
CompositionTechnique::TextureDefinition* def = texDefIt.getNext();
if (def->scope == CompositionTechnique::TS_GLOBAL)
{
//Check that this is a legit global texture
if (!def->refCompName.empty())
{
OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
"Global compositor texture definition can not be a reference",
"Compositor::createGlobalTextures");
}
if (def->width == 0 || def->height == 0)
{
OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
"Global compositor texture definition must have absolute size",
"Compositor::createGlobalTextures");
}
if (def->pooled)
{
LogManager::getSingleton().logMessage(
"Pooling global compositor textures has no effect");
}
globalTextureNames.insert(def->name);
//TODO GSOC : Heavy copy-pasting from CompositorInstance. How to we solve it?
/// Make the tetxure
RenderTarget* rendTarget;
if (def->formatList.size() > 1)
{
String MRTbaseName = "c" + StringConverter::toString(dummyCounter++) +
"/" + mName + "/" + def->name;
MultiRenderTarget* mrt =
Root::getSingleton().getRenderSystem()->createMultiRenderTarget(MRTbaseName);
mGlobalMRTs[def->name] = mrt;
// create and bind individual surfaces
size_t atch = 0;
for (PixelFormatList::iterator p = def->formatList.begin();
p != def->formatList.end(); ++p, ++atch)
{
String texname = MRTbaseName + "/" + StringConverter::toString(atch);
TexturePtr tex;
tex = TextureManager::getSingleton().createManual(
texname,
ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
(uint)def->width, (uint)def->height, 0, *p, TU_RENDERTARGET, 0,
def->hwGammaWrite && !PixelUtil::isFloatingPoint(*p), def->fsaa);
RenderTexture* rt = tex->getBuffer()->getRenderTarget();
rt->setAutoUpdated(false);
mrt->bindSurface(atch, rt);
// Also add to local textures so we can look up
String mrtLocalName = getMRTTexLocalName(def->name, atch);
mGlobalTextures[mrtLocalName] = tex;
}
rendTarget = mrt;
}
else
{
String texName = "c" + StringConverter::toString(dummyCounter++) +
"/" + mName + "/" + def->name;
// space in the name mixup the cegui in the compositor demo
// this is an auto generated name - so no spaces can't hart us.
std::replace( texName.begin(), texName.end(), ' ', '_' );
TexturePtr tex;
tex = TextureManager::getSingleton().createManual(
texName,
ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
(uint)def->width, (uint)def->height, 0, def->formatList[0], TU_RENDERTARGET, 0,
def->hwGammaWrite && !PixelUtil::isFloatingPoint(def->formatList[0]), def->fsaa);
rendTarget = tex->getBuffer()->getRenderTarget();
mGlobalTextures[def->name] = tex;
}
//Set DepthBuffer pool for sharing
rendTarget->setDepthBufferPool( def->depthBufferId );
}
}
//Validate that all other supported techniques expose the same set of global textures.
for (size_t i=1; i<mSupportedTechniques.size(); i++)
{
CompositionTechnique* technique = mSupportedTechniques[i];
bool isConsistent = true;
size_t numGlobals = 0;
texDefIt = technique->getTextureDefinitionIterator();
while (texDefIt.hasMoreElements())
{
CompositionTechnique::TextureDefinition* texDef = texDefIt.getNext();
if (texDef->scope == CompositionTechnique::TS_GLOBAL)
{
if (globalTextureNames.find(texDef->name) == globalTextureNames.end())
{
isConsistent = false;
break;
}
numGlobals++;
}
}
if (numGlobals != globalTextureNames.size())
isConsistent = false;
if (!isConsistent)
{
OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
"Different composition techniques define different global textures",
"Compositor::createGlobalTextures");
}
}
}
//-----------------------------------------------------------------------
void Compositor::freeGlobalTextures()
{
GlobalTextureMap::iterator i = mGlobalTextures.begin();
while (i != mGlobalTextures.end())
{
TextureManager::getSingleton().remove(i->second->getName());
i++;
}
mGlobalTextures.clear();
GlobalMRTMap::iterator mrti = mGlobalMRTs.begin();
while (mrti != mGlobalMRTs.end())
{
// remove MRT
Root::getSingleton().getRenderSystem()->destroyRenderTarget(mrti->second->getName());
mrti++;
}
mGlobalMRTs.clear();
}
//-----------------------------------------------------------------------
const String& Compositor::getTextureInstanceName(const String& name, size_t mrtIndex)
{
return getTextureInstance(name, mrtIndex)->getName();
}
//-----------------------------------------------------------------------
TexturePtr Compositor::getTextureInstance(const String& name, size_t mrtIndex)
{
//Try simple texture
GlobalTextureMap::iterator i = mGlobalTextures.find(name);
if(i != mGlobalTextures.end())
{
return i->second;
}
//Try MRT
String mrtName = getMRTTexLocalName(name, mrtIndex);
i = mGlobalTextures.find(mrtName);
if(i != mGlobalTextures.end())
{
return i->second;
}
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Non-existent global texture name",
"Compositor::getTextureInstance")
}
//---------------------------------------------------------------------
RenderTarget* Compositor::getRenderTarget(const String& name)
{
// try simple texture
GlobalTextureMap::iterator i = mGlobalTextures.find(name);
if(i != mGlobalTextures.end())
return i->second->getBuffer()->getRenderTarget();
// try MRTs
GlobalMRTMap::iterator mi = mGlobalMRTs.find(name);
if (mi != mGlobalMRTs.end())
return mi->second;
else
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Non-existent global texture name",
"Compositor::getRenderTarget");
}
//---------------------------------------------------------------------
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//
// function blurImage() -- performs a hemispherical blur
//
//-----------------------------------------------------------------------------
#include <blurImage.h>
#include <resizeImage.h>
#include "Iex.h"
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
using namespace Imf;
using namespace Imath;
inline int
toInt (float x)
{
return int (x + 0.5f);
}
inline double
sqr (double x)
{
return x * x;
}
void
blurImage (EnvmapImage &image1, bool verbose)
{
//
// Ideally we would blur the input image directly by convolving
// it with a 180-degree wide blur kernel. Unfortunately this
// is prohibitively expensive when the input image is large.
// In order to keep running times reasonable, we perform the
// blur on a small proxy image that will later be re-sampled
// to the desired output resolution.
//
// Here's how it works:
//
// * If the input image is in latitude-longitude format,
// convert it into a cube-face environment map.
//
// * Repeatedly resample the image, each time shrinking
// it to no less than half its current size, until the
// width of each cube face is MAX_IN_WIDTH pixels.
//
// * Multiply each pixel by a weight that is proportinal
// to the solid angle subtended by the pixel as seen
// from the center of the environment cube.
//
// * Create an output image in cube-face format.
// The cube faces of the output image are OUT_WIDTH
// pixels wide.
//
// * For each pixel of the output image:
//
// Set the output pixel's color to black
//
// Determine the direction, d2, from the center of the
// output environment cube to the center of the output
// pixel.
//
// For each pixel of the input image:
//
// Determine the direction, d1, from the center of
// the input environment cube to the center of the
// input pixel.
//
// Multiply the input pixel's color by max (0, d1.dot(d2))
// and add the result to the output pixel.
//
const int MAX_IN_WIDTH = 40;
const int OUT_WIDTH = 100;
if (verbose)
cout << "blurring map image" << endl;
EnvmapImage image2;
EnvmapImage *iptr1 = &image1;
EnvmapImage *iptr2 = &image2;
int w = image1.dataWindow().max.x - image1.dataWindow().min.x + 1;
int h = w * 6;
if (iptr1->type() == ENVMAP_LATLONG)
{
//
// Convert the input image from latitude-longitude
// to cube-face format.
//
if (verbose)
cout << " converting to cube-face format" << endl;
w /= 4;
h = w * 6;
Box2i dw (V2i (0, 0), V2i (w - 1, h - 1));
resizeCube (*iptr1, *iptr2, dw, 1, 7);
swap (iptr1, iptr2);
}
while (w > MAX_IN_WIDTH)
{
//
// Shrink the image.
//
if (w >= MAX_IN_WIDTH * 2)
w /= 2;
else
w = MAX_IN_WIDTH;
h = w * 6;
if (verbose)
{
cout << " resizing cube faces "
"to " << w << " by " << w << " pixels" << endl;
}
Box2i dw (V2i (0, 0), V2i (w - 1, h - 1));
resizeCube (*iptr1, *iptr2, dw, 1, 7);
swap (iptr1, iptr2);
}
if (verbose)
cout << " computing pixel weights" << endl;
{
//
// Multiply each pixel by a weight that is proportinal
// to the solid angle subtended by the pixel.
//
Box2i dw = iptr1->dataWindow();
int sof = CubeMap::sizeOfFace (dw);
Array2D<Rgba> &pixels = iptr1->pixels();
double weightTotal = 0;
for (int f = CUBEFACE_POS_X; f <= CUBEFACE_NEG_Z; ++f)
{
if (verbose)
cout << " face " << f << endl;
CubeMapFace face = CubeMapFace (f);
V3f faceDir (0, 0, 0);
int ix = 0, iy = 0, iz = 0;
switch (face)
{
case CUBEFACE_POS_X:
faceDir = V3f (1, 0, 0);
ix = 0;
iy = 1;
iz = 2;
break;
case CUBEFACE_NEG_X:
faceDir = V3f (-1, 0, 0);
ix = 0;
iy = 1;
iz = 2;
break;
case CUBEFACE_POS_Y:
faceDir = V3f (0, 1, 0);
ix = 1;
iy = 0;
iz = 2;
break;
case CUBEFACE_NEG_Y:
faceDir = V3f (0, -1, 0);
ix = 1;
iy = 0;
iz = 2;
break;
case CUBEFACE_POS_Z:
faceDir = V3f (0, 0, 1);
ix = 2;
iy = 0;
iz = 1;
break;
case CUBEFACE_NEG_Z:
faceDir = V3f (0, 0, -1);
ix = 2;
iy = 0;
iz = 1;
break;
}
for (int y = 0; y < sof; ++y)
{
bool yEdge = (y == 0 || y == sof - 1);
for (int x = 0; x < sof; ++x)
{
bool xEdge = (x == 0 || x == sof - 1);
V2f posInFace (x, y);
V3f dir =
CubeMap::direction (face, dw, posInFace).normalized();
V2f pos =
CubeMap::pixelPosition (face, dw, posInFace);
//
// The solid angle subtended by pixel (x,y), as seen
// from the center of the cube, is proportional to the
// square of the distance of the pixel from the center
// of the cube and proportional to the dot product of
// the viewing direction and the normal of the cube
// face that contains the pixel.
//
double weight =
(dir ^ faceDir) *
(sqr (dir[iy] / dir[ix]) + sqr (dir[iz] / dir[ix]) + 1);
//
// Pixels at the edges and corners of the
// cube are duplicated; we must adjust the
// pixel weights accordingly.
//
if (xEdge && yEdge)
weight /= 3;
else if (xEdge || yEdge)
weight /= 2;
Rgba &pixel = pixels[toInt (pos.y)][toInt (pos.x)];
pixel.r *= weight;
pixel.g *= weight;
pixel.b *= weight;
pixel.a *= weight;
weightTotal += weight;
}
}
}
//
// The weighting operation above has made the overall image darker.
// Apply a correction to recover the image's original brightness.
//
int w = dw.max.x - dw.min.x + 1;
int h = dw.max.y - dw.min.y + 1;
size_t numPixels = w * h;
double weight = numPixels / weightTotal;
Rgba *p = &pixels[0][0];
Rgba *end = p + numPixels;
while (p < end)
{
p->r *= weight;
p->g *= weight;
p->b *= weight;
p->a *= weight;
++p;
}
}
{
if (verbose)
cout << " generating blurred image" << endl;
Box2i dw1 = iptr1->dataWindow();
int sof1 = CubeMap::sizeOfFace (dw1);
Box2i dw2 (V2i (0, 0), V2i (OUT_WIDTH - 1, OUT_WIDTH * 6 - 1));
int sof2 = CubeMap::sizeOfFace (dw2);
iptr2->resize (ENVMAP_CUBE, dw2);
iptr2->clear ();
Array2D<Rgba> &pixels1 = iptr1->pixels();
Array2D<Rgba> &pixels2 = iptr2->pixels();
for (int f2 = CUBEFACE_POS_X; f2 <= CUBEFACE_NEG_Z; ++f2)
{
if (verbose)
cout << " face " << f2 << endl;
CubeMapFace face2 = CubeMapFace (f2);
for (int y2 = 0; y2 < sof2; ++y2)
{
for (int x2 = 0; x2 < sof2; ++x2)
{
V2f posInFace2 (x2, y2);
V3f dir2 = CubeMap::direction
(face2, dw2, posInFace2);
V2f pos2 = CubeMap::pixelPosition
(face2, dw2, posInFace2);
double weightTotal = 0;
double rTotal = 0;
double gTotal = 0;
double bTotal = 0;
double aTotal = 0;
Rgba &pixel2 =
pixels2[toInt (pos2.y)][toInt (pos2.x)];
for (int f1 = CUBEFACE_POS_X; f1 <= CUBEFACE_NEG_Z; ++f1)
{
CubeMapFace face1 = CubeMapFace (f1);
for (int y1 = 0; y1 < sof1; ++y1)
{
for (int x1 = 0; x1 < sof1; ++x1)
{
V2f posInFace1 (x1, y1);
V3f dir1 = CubeMap::direction
(face1, dw1, posInFace1);
V2f pos1 = CubeMap::pixelPosition
(face1, dw1, posInFace1);
double weight = dir1 ^ dir2;
if (weight <= 0)
continue;
Rgba &pixel1 =
pixels1[toInt (pos1.y)][toInt (pos1.x)];
weightTotal += weight;
rTotal += pixel1.r * weight;
gTotal += pixel1.g * weight;
bTotal += pixel1.b * weight;
aTotal += pixel1.a * weight;
}
}
}
pixel2.r = rTotal / weightTotal;
pixel2.g = gTotal / weightTotal;
pixel2.b = bTotal / weightTotal;
pixel2.a = aTotal / weightTotal;
}
}
}
swap (iptr1, iptr2);
}
//
// Depending on how many times we've re-sampled the image,
// the result is now either in image1 or in image2.
// If necessary, copy the result into image1.
//
if (iptr1 != &image1)
{
if (verbose)
cout << " copying" << endl;
Box2i dw = iptr1->dataWindow();
image1.resize (ENVMAP_CUBE, dw);
int w = dw.max.x - dw.min.x + 1;
int h = dw.max.y - dw.min.y + 1;
size_t size = w * h * sizeof (Rgba);
memcpy (&image1.pixels()[0][0], &iptr1->pixels()[0][0], size);
}
}
<commit_msg>Fix OpenEXR for gcc-4.7<commit_after>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//
// function blurImage() -- performs a hemispherical blur
//
//-----------------------------------------------------------------------------
#include <blurImage.h>
#include <resizeImage.h>
#include <cstring>
#include "Iex.h"
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
using namespace Imf;
using namespace Imath;
inline int
toInt (float x)
{
return int (x + 0.5f);
}
inline double
sqr (double x)
{
return x * x;
}
void
blurImage (EnvmapImage &image1, bool verbose)
{
//
// Ideally we would blur the input image directly by convolving
// it with a 180-degree wide blur kernel. Unfortunately this
// is prohibitively expensive when the input image is large.
// In order to keep running times reasonable, we perform the
// blur on a small proxy image that will later be re-sampled
// to the desired output resolution.
//
// Here's how it works:
//
// * If the input image is in latitude-longitude format,
// convert it into a cube-face environment map.
//
// * Repeatedly resample the image, each time shrinking
// it to no less than half its current size, until the
// width of each cube face is MAX_IN_WIDTH pixels.
//
// * Multiply each pixel by a weight that is proportinal
// to the solid angle subtended by the pixel as seen
// from the center of the environment cube.
//
// * Create an output image in cube-face format.
// The cube faces of the output image are OUT_WIDTH
// pixels wide.
//
// * For each pixel of the output image:
//
// Set the output pixel's color to black
//
// Determine the direction, d2, from the center of the
// output environment cube to the center of the output
// pixel.
//
// For each pixel of the input image:
//
// Determine the direction, d1, from the center of
// the input environment cube to the center of the
// input pixel.
//
// Multiply the input pixel's color by max (0, d1.dot(d2))
// and add the result to the output pixel.
//
const int MAX_IN_WIDTH = 40;
const int OUT_WIDTH = 100;
if (verbose)
cout << "blurring map image" << endl;
EnvmapImage image2;
EnvmapImage *iptr1 = &image1;
EnvmapImage *iptr2 = &image2;
int w = image1.dataWindow().max.x - image1.dataWindow().min.x + 1;
int h = w * 6;
if (iptr1->type() == ENVMAP_LATLONG)
{
//
// Convert the input image from latitude-longitude
// to cube-face format.
//
if (verbose)
cout << " converting to cube-face format" << endl;
w /= 4;
h = w * 6;
Box2i dw (V2i (0, 0), V2i (w - 1, h - 1));
resizeCube (*iptr1, *iptr2, dw, 1, 7);
swap (iptr1, iptr2);
}
while (w > MAX_IN_WIDTH)
{
//
// Shrink the image.
//
if (w >= MAX_IN_WIDTH * 2)
w /= 2;
else
w = MAX_IN_WIDTH;
h = w * 6;
if (verbose)
{
cout << " resizing cube faces "
"to " << w << " by " << w << " pixels" << endl;
}
Box2i dw (V2i (0, 0), V2i (w - 1, h - 1));
resizeCube (*iptr1, *iptr2, dw, 1, 7);
swap (iptr1, iptr2);
}
if (verbose)
cout << " computing pixel weights" << endl;
{
//
// Multiply each pixel by a weight that is proportinal
// to the solid angle subtended by the pixel.
//
Box2i dw = iptr1->dataWindow();
int sof = CubeMap::sizeOfFace (dw);
Array2D<Rgba> &pixels = iptr1->pixels();
double weightTotal = 0;
for (int f = CUBEFACE_POS_X; f <= CUBEFACE_NEG_Z; ++f)
{
if (verbose)
cout << " face " << f << endl;
CubeMapFace face = CubeMapFace (f);
V3f faceDir (0, 0, 0);
int ix = 0, iy = 0, iz = 0;
switch (face)
{
case CUBEFACE_POS_X:
faceDir = V3f (1, 0, 0);
ix = 0;
iy = 1;
iz = 2;
break;
case CUBEFACE_NEG_X:
faceDir = V3f (-1, 0, 0);
ix = 0;
iy = 1;
iz = 2;
break;
case CUBEFACE_POS_Y:
faceDir = V3f (0, 1, 0);
ix = 1;
iy = 0;
iz = 2;
break;
case CUBEFACE_NEG_Y:
faceDir = V3f (0, -1, 0);
ix = 1;
iy = 0;
iz = 2;
break;
case CUBEFACE_POS_Z:
faceDir = V3f (0, 0, 1);
ix = 2;
iy = 0;
iz = 1;
break;
case CUBEFACE_NEG_Z:
faceDir = V3f (0, 0, -1);
ix = 2;
iy = 0;
iz = 1;
break;
}
for (int y = 0; y < sof; ++y)
{
bool yEdge = (y == 0 || y == sof - 1);
for (int x = 0; x < sof; ++x)
{
bool xEdge = (x == 0 || x == sof - 1);
V2f posInFace (x, y);
V3f dir =
CubeMap::direction (face, dw, posInFace).normalized();
V2f pos =
CubeMap::pixelPosition (face, dw, posInFace);
//
// The solid angle subtended by pixel (x,y), as seen
// from the center of the cube, is proportional to the
// square of the distance of the pixel from the center
// of the cube and proportional to the dot product of
// the viewing direction and the normal of the cube
// face that contains the pixel.
//
double weight =
(dir ^ faceDir) *
(sqr (dir[iy] / dir[ix]) + sqr (dir[iz] / dir[ix]) + 1);
//
// Pixels at the edges and corners of the
// cube are duplicated; we must adjust the
// pixel weights accordingly.
//
if (xEdge && yEdge)
weight /= 3;
else if (xEdge || yEdge)
weight /= 2;
Rgba &pixel = pixels[toInt (pos.y)][toInt (pos.x)];
pixel.r *= weight;
pixel.g *= weight;
pixel.b *= weight;
pixel.a *= weight;
weightTotal += weight;
}
}
}
//
// The weighting operation above has made the overall image darker.
// Apply a correction to recover the image's original brightness.
//
int w = dw.max.x - dw.min.x + 1;
int h = dw.max.y - dw.min.y + 1;
size_t numPixels = w * h;
double weight = numPixels / weightTotal;
Rgba *p = &pixels[0][0];
Rgba *end = p + numPixels;
while (p < end)
{
p->r *= weight;
p->g *= weight;
p->b *= weight;
p->a *= weight;
++p;
}
}
{
if (verbose)
cout << " generating blurred image" << endl;
Box2i dw1 = iptr1->dataWindow();
int sof1 = CubeMap::sizeOfFace (dw1);
Box2i dw2 (V2i (0, 0), V2i (OUT_WIDTH - 1, OUT_WIDTH * 6 - 1));
int sof2 = CubeMap::sizeOfFace (dw2);
iptr2->resize (ENVMAP_CUBE, dw2);
iptr2->clear ();
Array2D<Rgba> &pixels1 = iptr1->pixels();
Array2D<Rgba> &pixels2 = iptr2->pixels();
for (int f2 = CUBEFACE_POS_X; f2 <= CUBEFACE_NEG_Z; ++f2)
{
if (verbose)
cout << " face " << f2 << endl;
CubeMapFace face2 = CubeMapFace (f2);
for (int y2 = 0; y2 < sof2; ++y2)
{
for (int x2 = 0; x2 < sof2; ++x2)
{
V2f posInFace2 (x2, y2);
V3f dir2 = CubeMap::direction
(face2, dw2, posInFace2);
V2f pos2 = CubeMap::pixelPosition
(face2, dw2, posInFace2);
double weightTotal = 0;
double rTotal = 0;
double gTotal = 0;
double bTotal = 0;
double aTotal = 0;
Rgba &pixel2 =
pixels2[toInt (pos2.y)][toInt (pos2.x)];
for (int f1 = CUBEFACE_POS_X; f1 <= CUBEFACE_NEG_Z; ++f1)
{
CubeMapFace face1 = CubeMapFace (f1);
for (int y1 = 0; y1 < sof1; ++y1)
{
for (int x1 = 0; x1 < sof1; ++x1)
{
V2f posInFace1 (x1, y1);
V3f dir1 = CubeMap::direction
(face1, dw1, posInFace1);
V2f pos1 = CubeMap::pixelPosition
(face1, dw1, posInFace1);
double weight = dir1 ^ dir2;
if (weight <= 0)
continue;
Rgba &pixel1 =
pixels1[toInt (pos1.y)][toInt (pos1.x)];
weightTotal += weight;
rTotal += pixel1.r * weight;
gTotal += pixel1.g * weight;
bTotal += pixel1.b * weight;
aTotal += pixel1.a * weight;
}
}
}
pixel2.r = rTotal / weightTotal;
pixel2.g = gTotal / weightTotal;
pixel2.b = bTotal / weightTotal;
pixel2.a = aTotal / weightTotal;
}
}
}
swap (iptr1, iptr2);
}
//
// Depending on how many times we've re-sampled the image,
// the result is now either in image1 or in image2.
// If necessary, copy the result into image1.
//
if (iptr1 != &image1)
{
if (verbose)
cout << " copying" << endl;
Box2i dw = iptr1->dataWindow();
image1.resize (ENVMAP_CUBE, dw);
int w = dw.max.x - dw.min.x + 1;
int h = dw.max.y - dw.min.y + 1;
size_t size = w * h * sizeof (Rgba);
memcpy (&image1.pixels()[0][0], &iptr1->pixels()[0][0], size);
}
}
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <Array.hpp>
#include <ops.hpp>
namespace cpu {
namespace kernel {
template<typename Ti, typename To, typename Tw>
struct MeanOp {
Transform<Ti, To, af_add_t> transform;
To runningMean;
Tw runningCount;
MeanOp(Ti mean, Tw count)
: transform(), runningMean(transform(mean)), runningCount(count) {}
void operator()(Ti _newMean, Tw newCount) {
To newMean = transform(_newMean);
if ((newCount != 0) || (runningCount != 0)) {
Tw runningScale = runningCount;
Tw newScale = newCount;
runningCount += newCount;
runningScale = runningScale / runningCount;
newScale = newScale / runningCount;
runningMean = (runningScale * runningMean) + (newScale * newMean);
}
}
};
template<typename T, typename Tw, int D>
struct mean_weighted_dim {
void operator()(Param<T> output, const dim_t outOffset,
const CParam<T> input, const dim_t inOffset,
const CParam<Tw> weight, const dim_t wtOffset,
const int dim) {
const af::dim4 odims = output.dims();
const af::dim4 ostrides = output.strides();
const af::dim4 istrides = input.strides();
const af::dim4 wstrides = weight.strides();
const int D1 = D - 1;
for (dim_t i = 0; i < odims[D1]; i++) {
mean_weighted_dim<T, Tw, D1>()(output, outOffset + i * ostrides[D1],
input, inOffset + i * istrides[D1],
weight, wtOffset + i * wstrides[D1],
dim);
}
}
};
template<typename T, typename Tw>
struct mean_weighted_dim<T, Tw, 0> {
void operator()(Param<T> output, const dim_t outOffset,
const CParam<T> input, const dim_t inOffset,
const CParam<Tw> weight, const dim_t wtOffset,
const int dim) {
const af::dim4 idims = input.dims();
const af::dim4 istrides = input.strides();
const af::dim4 wstrides = weight.strides();
T const* const in = input.get();
Tw const* const wt = weight.get();
T* out = output.get();
dim_t istride = istrides[dim];
dim_t wstride = wstrides[dim];
MeanOp<compute_t<T>, compute_t<T>, compute_t<Tw>> Op(0, 0);
for (dim_t i = 0; i < idims[dim]; i++) {
Op(compute_t<T>(in[inOffset + i * istride]),
compute_t<Tw>(wt[wtOffset + i * wstride]));
}
out[outOffset] = Op.runningMean;
}
};
template<typename Ti, typename Tw, typename To, int D>
struct mean_dim {
void operator()(Param<To> output, const dim_t outOffset,
const CParam<Ti> input, const dim_t inOffset,
const int dim) {
const af::dim4 odims = output.dims();
const af::dim4 ostrides = output.strides();
const af::dim4 istrides = input.strides();
const int D1 = D - 1;
for (dim_t i = 0; i < odims[D1]; i++) {
mean_dim<Ti, Tw, To, D1>()(output, outOffset + i * ostrides[D1],
input, inOffset + i * istrides[D1], dim);
}
}
};
template<typename Ti, typename Tw, typename To>
struct mean_dim<Ti, Tw, To, 0> {
void operator()(Param<To> output, const dim_t outOffset,
const CParam<Ti> input, const dim_t inOffset,
const int dim) {
const af::dim4 idims = input.dims();
const af::dim4 istrides = input.strides();
Ti const* const in = input.get();
To* out = output.get();
dim_t istride = istrides[dim];
dim_t end = inOffset + idims[dim] * istride;
MeanOp<compute_t<Ti>, compute_t<To>, compute_t<Tw>> Op(0, 0);
for (dim_t i = inOffset; i < end; i += istride) {
Op(compute_t<Ti>(in[i]), 1);
}
out[outOffset] = Op.runningMean;
}
};
} // namespace kernel
} // namespace cpu
<commit_msg>Prevent the optimizations in the MeanOp on cpu.<commit_after>/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <Array.hpp>
#include <ops.hpp>
namespace cpu {
namespace kernel {
template<typename Ti, typename To, typename Tw>
struct MeanOp {
Transform<Ti, To, af_add_t> transform;
To runningMean;
Tw runningCount;
MeanOp(Ti mean, Tw count)
: transform(), runningMean(transform(mean)), runningCount(count) {}
/// Prevents the optimzation of the mean calculation by some compiler flags
/// specifically -march=native.
[[gnu::optimize("01")]] void operator()(Ti _newMean, Tw newCount) {
To newMean = transform(_newMean);
if ((newCount != 0) || (runningCount != 0)) {
Tw runningScale = runningCount;
Tw newScale = newCount;
runningCount += newCount;
runningScale = runningScale / runningCount;
newScale = newScale / runningCount;
runningMean = (runningScale * runningMean) + (newScale * newMean);
}
}
};
template<typename T, typename Tw, int D>
struct mean_weighted_dim {
void operator()(Param<T> output, const dim_t outOffset,
const CParam<T> input, const dim_t inOffset,
const CParam<Tw> weight, const dim_t wtOffset,
const int dim) {
const af::dim4 odims = output.dims();
const af::dim4 ostrides = output.strides();
const af::dim4 istrides = input.strides();
const af::dim4 wstrides = weight.strides();
const int D1 = D - 1;
for (dim_t i = 0; i < odims[D1]; i++) {
mean_weighted_dim<T, Tw, D1>()(output, outOffset + i * ostrides[D1],
input, inOffset + i * istrides[D1],
weight, wtOffset + i * wstrides[D1],
dim);
}
}
};
template<typename T, typename Tw>
struct mean_weighted_dim<T, Tw, 0> {
void operator()(Param<T> output, const dim_t outOffset,
const CParam<T> input, const dim_t inOffset,
const CParam<Tw> weight, const dim_t wtOffset,
const int dim) {
const af::dim4 idims = input.dims();
const af::dim4 istrides = input.strides();
const af::dim4 wstrides = weight.strides();
T const* const in = input.get();
Tw const* const wt = weight.get();
T* out = output.get();
dim_t istride = istrides[dim];
dim_t wstride = wstrides[dim];
MeanOp<compute_t<T>, compute_t<T>, compute_t<Tw>> Op(0, 0);
for (dim_t i = 0; i < idims[dim]; i++) {
Op(compute_t<T>(in[inOffset + i * istride]),
compute_t<Tw>(wt[wtOffset + i * wstride]));
}
out[outOffset] = Op.runningMean;
}
};
template<typename Ti, typename Tw, typename To, int D>
struct mean_dim {
void operator()(Param<To> output, const dim_t outOffset,
const CParam<Ti> input, const dim_t inOffset,
const int dim) {
const af::dim4 odims = output.dims();
const af::dim4 ostrides = output.strides();
const af::dim4 istrides = input.strides();
const int D1 = D - 1;
for (dim_t i = 0; i < odims[D1]; i++) {
mean_dim<Ti, Tw, To, D1>()(output, outOffset + i * ostrides[D1],
input, inOffset + i * istrides[D1], dim);
}
}
};
template<typename Ti, typename Tw, typename To>
struct mean_dim<Ti, Tw, To, 0> {
void operator()(Param<To> output, const dim_t outOffset,
const CParam<Ti> input, const dim_t inOffset,
const int dim) {
const af::dim4 idims = input.dims();
const af::dim4 istrides = input.strides();
Ti const* const in = input.get();
To* out = output.get();
dim_t istride = istrides[dim];
dim_t end = inOffset + idims[dim] * istride;
MeanOp<compute_t<Ti>, compute_t<To>, compute_t<Tw>> Op(0, 0);
for (dim_t i = inOffset; i < end; i += istride) {
Op(compute_t<Ti>(in[i]), 1);
}
out[outOffset] = Op.runningMean;
}
};
} // namespace kernel
} // namespace cpu
<|endoftext|> |
<commit_before>//
// RobustTextDetection.cpp
// RobustTextDetection
//
// Created by Saburo Okita on 08/06/14.
// Copyright (c) 2014 Saburo Okita. All rights reserved.
//
#include "RobustTextDetection.h"
#include "ConnectedComponent.h"
#include <numeric>
using namespace std;
using namespace cv;
RobustTextDetection::RobustTextDetection() {
}
RobustTextDetection::RobustTextDetection(RobustTextParam & param) {
this->param = param;
}
/**
* Apply robust text detection algorithm
* It returns the filtered stroke width image which contains the possible
* text in binary format, and also the rect
**/
pair<Mat, Rect> RobustTextDetection::apply( Mat& image ) {
Mat grey = preprocessImage( image );
Mat mser_mask = createMSERMask( grey );
/* Perform canny edge operator to extract the edges */
Mat edges;
Canny( grey, edges, param.cannyThresh1, param.cannyThresh2 );
/* Create the edge enhanced MSER region */
Mat edge_mser_intersection = edges & mser_mask;
Mat gradient_grown = growEdges( grey, edge_mser_intersection );
Mat edge_enhanced_mser = ~gradient_grown & mser_mask;
/* Find the connected components */
ConnectedComponent conn_comp( param.maxConnCompCount, 4);
Mat labels = conn_comp.apply( edge_enhanced_mser );
vector<ComponentProperty> props = conn_comp.getComponentsProperties();
Mat result( labels.size(), CV_8UC1, Scalar(0));
for( ComponentProperty& prop: props ) {
/* Filtered out connected components that aren't within the criteria */
if( prop.area < param.minConnCompArea || prop.area > param.maxConnCompArea )
continue;
if( prop.eccentricity < param.minEccentricity || prop.eccentricity > param.maxEccentricity )
continue;
if( prop.solidity < param.minSolidity )
continue;
result |= (labels == prop.labelID);
}
/* Calculate the distance transformed from the connected components */
cv::distanceTransform( result, result, CV_DIST_L2, 3 );
result.convertTo( result, CV_32SC1 );
/* Find the stroke width image from the distance transformed */
Mat stroke_width = computeStrokeWidth( result );
/* Filter the stroke width using connected component again */
conn_comp = ConnectedComponent( param.maxConnCompCount, 4);
labels = conn_comp.apply( stroke_width );
props = conn_comp.getComponentsProperties();
Mat filtered_stroke_width( stroke_width.size(), CV_8UC1, Scalar(0) );
for( ComponentProperty prop: props ) {
Mat mask = labels == prop.labelID;
Mat temp;
stroke_width.copyTo( temp, mask );
int area = countNonZero( temp );
/* Since we only want to consider the connected component, ignore the zero pixels */
vector<int> vec = Mat( temp.reshape( 1, temp.rows * temp.cols ) );
vector<int> nonzero_vec;
copy_if( vec.begin(), vec.end(), back_inserter(nonzero_vec), [&](int val){
return val > 0;
});
/* Find mean and std deviation for the connected components */
double mean = std::accumulate( nonzero_vec.begin(), nonzero_vec.end(), 0.0 ) / area;
double accum = 0.0;
for( int val: nonzero_vec )
accum += (val - mean) * (val - mean );
double std_dev = sqrt( accum / area );
/* Filter out those which are out of the prespecified ratio */
if( (std_dev / mean) > param.maxStdDevMeanRatio )
continue;
/* Collect the filtered stroke width */
filtered_stroke_width |= mask;
}
/* Use morphological close and open to create a large connected bounding region from the filtered stroke width */
Mat bounding_region;
morphologyEx( filtered_stroke_width, bounding_region, MORPH_CLOSE, getStructuringElement( MORPH_ELLIPSE, Size(25, 25)) );
morphologyEx( bounding_region, bounding_region, MORPH_OPEN, getStructuringElement( MORPH_ELLIPSE, Size(7, 7)) );
/* ... so that we can get an overall bounding rect */
Mat bounding_region_coord;
findNonZero( bounding_region, bounding_region_coord );
Rect bounding_rect = boundingRect( bounding_region_coord );
Mat bounding_mask( filtered_stroke_width.size(), CV_8UC1, Scalar(0) );
Mat( bounding_mask, bounding_rect ) = 255;
/* Well, add some margin to the bounding rect */
bounding_rect = Rect( bounding_rect.tl() - Point(5, 5), bounding_rect.br() + Point(5, 5) );
bounding_rect = clamp( bounding_rect, image.size() );
/* Well, discard everything outside of the bounding rectangle */
filtered_stroke_width.copyTo( filtered_stroke_width, bounding_mask );
return pair<Mat, Rect>( filtered_stroke_width, bounding_rect );
}
Rect RobustTextDetection::clamp( Rect& rect, Size size ) {
Rect result = rect;
if( result.x < 0 )
result.x = 0;
if( result.x + result.width > size.width )
result.width = size.width - result.x;
if( result.y < 0 )
result.y = 0;
if( result.y + result.height > size.height )
result.height = size.height - result.y;
return result;
}
/**
* Create a mask out from the MSER components
*/
Mat RobustTextDetection::createMSERMask( Mat& grey ) {
/* Find MSER components */
vector<vector<Point>> contours;
MSER mser( 8, param.minMSERArea, param.maxMSERArea, 0.25, 0.1, 100, 1.01, 0.03, 5 );
mser(grey, contours);
/* Create a binary mask out of the MSER */
Mat mser_mask( grey.size(), CV_8UC1, Scalar(0));
for( int i = 0; i < contours.size(); i++ ) {
for( Point& point: contours[i] )
mser_mask.at<uchar>(point) = 255;
}
return mser_mask;
}
/**
* Preprocess image
*/
Mat RobustTextDetection::preprocessImage( Mat& image ) {
/* TODO: Should do contrast enhancement here */
Mat grey;
cvtColor( image, grey, CV_BGR2GRAY );
return grey;
}
/**
* From the angle convert into our neighborhood encoding
* which has the following scheme
* | 2 | 3 | 4 |
* | 1 | 0 | 5 |
* | 8 | 7 | 6 |
*/
int RobustTextDetection::toBin( const float angle, const int neighbors ) {
const float divisor = 180.0 / neighbors;
return static_cast<int>( (( floor(angle / divisor) - 1) / 2) + 1 ) % neighbors + 1;
}
/**
* Grow the edges along with directon of gradient
*/
Mat RobustTextDetection::growEdges(Mat& image, Mat& edges ) {
CV_Assert( edges.type() == CV_8UC1 );
Mat grad_x, grad_y;
Sobel( image, grad_x, CV_32FC1, 1, 0 );
Sobel( image, grad_y, CV_32FC1, 0, 1 );
Mat grad_mag, grad_dir;
cartToPolar( grad_x, grad_y, grad_mag, grad_dir, true );
/* Convert the angle into predefined 3x3 neighbor locations
| 2 | 3 | 4 |
| 1 | 0 | 5 |
| 8 | 7 | 6 |
*/
for( int y = 0; y < grad_dir.rows; y++ ) {
float * grad_ptr = grad_dir.ptr<float>(y);
for( int x = 0; x < grad_dir.cols; x++ ) {
if( grad_ptr[x] != 0 )
grad_ptr[x] = toBin( grad_ptr[x] );
}
}
grad_dir.convertTo( grad_dir, CV_8UC1 );
/* Perform region growing based on the gradient direction */
Mat result = edges.clone();
uchar * prev_ptr = result.ptr<uchar>(0);
uchar * curr_ptr = result.ptr<uchar>(1);
for( int y = 1; y < edges.rows - 1; y++ ) {
uchar * edge_ptr = edges.ptr<uchar>(y);
uchar * grad_ptr = grad_dir.ptr<uchar>(y);
uchar * next_ptr = result.ptr<uchar>(y + 1);
for( int x = 1; x < edges.cols - 1; x++ ) {
/* Only consider the contours */
if( edge_ptr[x] != 0 ) {
/* .. there should be a better way .... */
switch( grad_ptr[x] ) {
case 1: curr_ptr[x-1] = 255; break;
case 2: prev_ptr[x-1] = 255; break;
case 3: prev_ptr[x ] = 255; break;
case 4: prev_ptr[x+1] = 255; break;
case 5: curr_ptr[x ] = 255; break;
case 6: next_ptr[x+1] = 255; break;
case 7: next_ptr[x ] = 255; break;
case 8: next_ptr[x-1] = 255; break;
default: break;
}
}
}
prev_ptr = curr_ptr;
curr_ptr = next_ptr;
}
return result;
}
/**
* Convert from our encoded 8 bit uchar to the (8) neighboring coordinates
*/
vector<Point> RobustTextDetection::convertToCoords( int x, int y, bitset<8> neighbors ) {
vector<Point> coords;
if( neighbors[0] ) coords.push_back( Point(x - 1, y ) );
if( neighbors[1] ) coords.push_back( Point(x - 1, y - 1) );
if( neighbors[2] ) coords.push_back( Point(x , y - 1) );
if( neighbors[3] ) coords.push_back( Point(x + 1, y - 1) );
if( neighbors[4] ) coords.push_back( Point(x + 1, y ) );
if( neighbors[5] ) coords.push_back( Point(x + 1, y + 1) );
if( neighbors[6] ) coords.push_back( Point(x , y + 1) );
if( neighbors[7] ) coords.push_back( Point(x - 1, y + 1) );
return coords;
}
/**
* Overloaded function for convertToCoords
*/
vector<Point> RobustTextDetection::convertToCoords( Point& coord, bitset<8> neighbors ) {
return convertToCoords( coord.x, coord.y, neighbors );
}
/**
* Overloaded function for convertToCoords
*/
vector<Point> RobustTextDetection::convertToCoords( Point& coord, uchar neighbors ) {
return convertToCoords( coord.x, coord.y, bitset<8>(neighbors) );
}
/**
* Get a set of 8 neighbors that are less than given value
* | 2 | 3 | 4 |
* | 1 | 0 | 5 |
* | 8 | 7 | 6 |
*/
inline bitset<8> RobustTextDetection::getNeighborsLessThan( int * curr_ptr, int x, int * prev_ptr, int * next_ptr ) {
bitset<8> neighbors;
neighbors[0] = curr_ptr[x-1] == 0 ? 0 : curr_ptr[x-1] < curr_ptr[x];
neighbors[1] = prev_ptr[x-1] == 0 ? 0 : prev_ptr[x-1] < curr_ptr[x];
neighbors[2] = prev_ptr[x ] == 0 ? 0 : prev_ptr[x] < curr_ptr[x];
neighbors[3] = prev_ptr[x+1] == 0 ? 0 : prev_ptr[x+1] < curr_ptr[x];
neighbors[4] = curr_ptr[x+1] == 0 ? 0 : curr_ptr[x+1] < curr_ptr[x];
neighbors[5] = next_ptr[x+1] == 0 ? 0 : next_ptr[x+1] < curr_ptr[x];
neighbors[6] = next_ptr[x ] == 0 ? 0 : next_ptr[x] < curr_ptr[x];
neighbors[7] = next_ptr[x-1] == 0 ? 0 : next_ptr[x-1] < curr_ptr[x];
return neighbors;
}
/**
* Compute the stroke width image out from the distance transform matrix
* It will propagate the max values of each connected component from the ridge
* to outer boundaries
**/
Mat RobustTextDetection::computeStrokeWidth( Mat& dist ) {
/* Pad the distance transformed matrix to avoid boundary checking */
Mat padded( dist.rows + 1, dist.cols + 1, dist.type(), Scalar(0) );
dist.copyTo( Mat( padded, Rect(1, 1, dist.cols, dist.rows ) ) );
Mat lookup( padded.size(), CV_8UC1, Scalar(0) );
int * prev_ptr = padded.ptr<int>(0);
int * curr_ptr = padded.ptr<int>(1);
for( int y = 1; y < padded.rows - 1; y++ ) {
uchar * lookup_ptr = lookup.ptr<uchar>(y);
int * next_ptr = padded.ptr<int>(y+1);
for( int x = 1; x < padded.cols - 1; x++ ) {
/* Extract all the neighbors whose value < curr_ptr[x], encoded in 8-bit uchar */
if( curr_ptr[x] != 0 )
lookup_ptr[x] = static_cast<uchar>( getNeighborsLessThan(curr_ptr, x, prev_ptr, next_ptr).to_ullong() );
}
prev_ptr = curr_ptr;
curr_ptr = next_ptr;
}
/* Get max stroke from the distance transformed */
double max_val_double;
minMaxLoc( padded, 0, &max_val_double );
int max_stroke = static_cast<int>(round( max_val_double ));
for( int stroke = max_stroke; stroke > 0; stroke-- ) {
Mat stroke_indices_mat;
findNonZero( padded == stroke, stroke_indices_mat );
vector<Point> stroke_indices;
stroke_indices_mat.copyTo( stroke_indices );
vector<Point> neighbors;
for( Point& stroke_index : stroke_indices ) {
vector<Point> temp = convertToCoords( stroke_index, lookup.at<uchar>(stroke_index) );
neighbors.insert( neighbors.end(), temp.begin(), temp.end() );
}
while( !neighbors.empty() ){
for( Point& neighbor: neighbors )
padded.at<int>(neighbor) = stroke;
neighbors.clear();
vector<Point> temp( neighbors );
neighbors.clear();
/* Recursively gets neighbors of the current neighbors */
for( Point& neighbor: temp ) {
vector<Point> temp = convertToCoords( neighbor, lookup.at<uchar>(neighbor) );
neighbors.insert( neighbors.end(), temp.begin(), temp.end() );
}
}
}
return Mat( padded, Rect(1, 1, dist.cols, dist.rows) );
}
<commit_msg>Some minor update<commit_after>//
// RobustTextDetection.cpp
// RobustTextDetection
//
// Created by Saburo Okita on 08/06/14.
// Copyright (c) 2014 Saburo Okita. All rights reserved.
//
#include "RobustTextDetection.h"
#include "ConnectedComponent.h"
#include <numeric>
using namespace std;
using namespace cv;
RobustTextDetection::RobustTextDetection() {
}
RobustTextDetection::RobustTextDetection(RobustTextParam & param) {
this->param = param;
}
/**
* Apply robust text detection algorithm
* It returns the filtered stroke width image which contains the possible
* text in binary format, and also the rect
**/
pair<Mat, Rect> RobustTextDetection::apply( Mat& image ) {
Mat grey = preprocessImage( image );
Mat mser_mask = createMSERMask( grey );
/* Perform canny edge operator to extract the edges */
Mat edges;
Canny( grey, edges, param.cannyThresh1, param.cannyThresh2 );
/* Create the edge enhanced MSER region */
Mat edge_mser_intersection = edges & mser_mask;
Mat gradient_grown = growEdges( grey, edge_mser_intersection );
Mat edge_enhanced_mser = ~gradient_grown & mser_mask;
/* Find the connected components */
ConnectedComponent conn_comp( param.maxConnCompCount, 4);
Mat labels = conn_comp.apply( edge_enhanced_mser );
vector<ComponentProperty> props = conn_comp.getComponentsProperties();
Mat result( labels.size(), CV_8UC1, Scalar(0));
for( ComponentProperty& prop: props ) {
/* Filtered out connected components that aren't within the criteria */
if( prop.area < param.minConnCompArea || prop.area > param.maxConnCompArea )
continue;
if( prop.eccentricity < param.minEccentricity || prop.eccentricity > param.maxEccentricity )
continue;
if( prop.solidity < param.minSolidity )
continue;
result |= (labels == prop.labelID);
}
/* Calculate the distance transformed from the connected components */
cv::distanceTransform( result, result, CV_DIST_L2, 3 );
result.convertTo( result, CV_32SC1 );
/* Find the stroke width image from the distance transformed */
Mat stroke_width = computeStrokeWidth( result );
/* Filter the stroke width using connected component again */
conn_comp = ConnectedComponent( param.maxConnCompCount, 4);
labels = conn_comp.apply( stroke_width );
props = conn_comp.getComponentsProperties();
Mat filtered_stroke_width( stroke_width.size(), CV_8UC1, Scalar(0) );
for( ComponentProperty& prop: props ) {
Mat mask = labels == prop.labelID;
Mat temp;
stroke_width.copyTo( temp, mask );
int area = countNonZero( temp );
/* Since we only want to consider the connected component, ignore the zero pixels */
vector<int> vec = Mat( temp.reshape( 1, temp.rows * temp.cols ) );
vector<int> nonzero_vec;
copy_if( vec.begin(), vec.end(), back_inserter(nonzero_vec), [&](int val){
return val > 0;
});
/* Find mean and std deviation for the connected components */
double mean = std::accumulate( nonzero_vec.begin(), nonzero_vec.end(), 0.0 ) / area;
double accum = 0.0;
for( int val: nonzero_vec )
accum += (val - mean) * (val - mean );
double std_dev = sqrt( accum / area );
/* Filter out those which are out of the prespecified ratio */
if( (std_dev / mean) > param.maxStdDevMeanRatio )
continue;
/* Collect the filtered stroke width */
filtered_stroke_width |= mask;
}
/* Use morphological close and open to create a large connected bounding region from the filtered stroke width */
Mat bounding_region;
morphologyEx( filtered_stroke_width, bounding_region, MORPH_CLOSE, getStructuringElement( MORPH_ELLIPSE, Size(25, 25)) );
morphologyEx( bounding_region, bounding_region, MORPH_OPEN, getStructuringElement( MORPH_ELLIPSE, Size(7, 7)) );
/* ... so that we can get an overall bounding rect */
Mat bounding_region_coord;
findNonZero( bounding_region, bounding_region_coord );
Rect bounding_rect = boundingRect( bounding_region_coord );
Mat bounding_mask( filtered_stroke_width.size(), CV_8UC1, Scalar(0) );
Mat( bounding_mask, bounding_rect ) = 255;
/* Well, add some margin to the bounding rect */
bounding_rect = Rect( bounding_rect.tl() - Point(5, 5), bounding_rect.br() + Point(5, 5) );
bounding_rect = clamp( bounding_rect, image.size() );
/* Well, discard everything outside of the bounding rectangle */
filtered_stroke_width.copyTo( filtered_stroke_width, bounding_mask );
return pair<Mat, Rect>( filtered_stroke_width, bounding_rect );
}
Rect RobustTextDetection::clamp( Rect& rect, Size size ) {
Rect result = rect;
if( result.x < 0 )
result.x = 0;
if( result.x + result.width > size.width )
result.width = size.width - result.x;
if( result.y < 0 )
result.y = 0;
if( result.y + result.height > size.height )
result.height = size.height - result.y;
return result;
}
/**
* Create a mask out from the MSER components
*/
Mat RobustTextDetection::createMSERMask( Mat& grey ) {
/* Find MSER components */
vector<vector<Point>> contours;
MSER mser( 8, param.minMSERArea, param.maxMSERArea, 0.25, 0.1, 100, 1.01, 0.03, 5 );
mser(grey, contours);
/* Create a binary mask out of the MSER */
Mat mser_mask( grey.size(), CV_8UC1, Scalar(0));
for( int i = 0; i < contours.size(); i++ ) {
for( Point& point: contours[i] )
mser_mask.at<uchar>(point) = 255;
}
return mser_mask;
}
/**
* Preprocess image
*/
Mat RobustTextDetection::preprocessImage( Mat& image ) {
/* TODO: Should do contrast enhancement here */
Mat grey;
cvtColor( image, grey, CV_BGR2GRAY );
return grey;
}
/**
* From the angle convert into our neighborhood encoding
* which has the following scheme
* | 2 | 3 | 4 |
* | 1 | 0 | 5 |
* | 8 | 7 | 6 |
*/
int RobustTextDetection::toBin( const float angle, const int neighbors ) {
const float divisor = 180.0 / neighbors;
return static_cast<int>( (( floor(angle / divisor) - 1) / 2) + 1 ) % neighbors + 1;
}
/**
* Grow the edges along with directon of gradient
*/
Mat RobustTextDetection::growEdges(Mat& image, Mat& edges ) {
CV_Assert( edges.type() == CV_8UC1 );
Mat grad_x, grad_y;
Sobel( image, grad_x, CV_32FC1, 1, 0 );
Sobel( image, grad_y, CV_32FC1, 0, 1 );
Mat grad_mag, grad_dir;
cartToPolar( grad_x, grad_y, grad_mag, grad_dir, true );
/* Convert the angle into predefined 3x3 neighbor locations
| 2 | 3 | 4 |
| 1 | 0 | 5 |
| 8 | 7 | 6 |
*/
for( int y = 0; y < grad_dir.rows; y++ ) {
float * grad_ptr = grad_dir.ptr<float>(y);
for( int x = 0; x < grad_dir.cols; x++ ) {
if( grad_ptr[x] != 0 )
grad_ptr[x] = toBin( grad_ptr[x] );
}
}
grad_dir.convertTo( grad_dir, CV_8UC1 );
/* Perform region growing based on the gradient direction */
Mat result = edges.clone();
uchar * prev_ptr = result.ptr<uchar>(0);
uchar * curr_ptr = result.ptr<uchar>(1);
for( int y = 1; y < edges.rows - 1; y++ ) {
uchar * edge_ptr = edges.ptr<uchar>(y);
uchar * grad_ptr = grad_dir.ptr<uchar>(y);
uchar * next_ptr = result.ptr<uchar>(y + 1);
for( int x = 1; x < edges.cols - 1; x++ ) {
/* Only consider the contours */
if( edge_ptr[x] != 0 ) {
/* .. there should be a better way .... */
switch( grad_ptr[x] ) {
case 1: curr_ptr[x-1] = 255; break;
case 2: prev_ptr[x-1] = 255; break;
case 3: prev_ptr[x ] = 255; break;
case 4: prev_ptr[x+1] = 255; break;
case 5: curr_ptr[x ] = 255; break;
case 6: next_ptr[x+1] = 255; break;
case 7: next_ptr[x ] = 255; break;
case 8: next_ptr[x-1] = 255; break;
default: break;
}
}
}
prev_ptr = curr_ptr;
curr_ptr = next_ptr;
}
return result;
}
/**
* Convert from our encoded 8 bit uchar to the (8) neighboring coordinates
*/
vector<Point> RobustTextDetection::convertToCoords( int x, int y, bitset<8> neighbors ) {
vector<Point> coords;
if( neighbors[0] ) coords.push_back( Point(x - 1, y ) );
if( neighbors[1] ) coords.push_back( Point(x - 1, y - 1) );
if( neighbors[2] ) coords.push_back( Point(x , y - 1) );
if( neighbors[3] ) coords.push_back( Point(x + 1, y - 1) );
if( neighbors[4] ) coords.push_back( Point(x + 1, y ) );
if( neighbors[5] ) coords.push_back( Point(x + 1, y + 1) );
if( neighbors[6] ) coords.push_back( Point(x , y + 1) );
if( neighbors[7] ) coords.push_back( Point(x - 1, y + 1) );
return coords;
}
/**
* Overloaded function for convertToCoords
*/
vector<Point> RobustTextDetection::convertToCoords( Point& coord, bitset<8> neighbors ) {
return convertToCoords( coord.x, coord.y, neighbors );
}
/**
* Overloaded function for convertToCoords
*/
vector<Point> RobustTextDetection::convertToCoords( Point& coord, uchar neighbors ) {
return convertToCoords( coord.x, coord.y, bitset<8>(neighbors) );
}
/**
* Get a set of 8 neighbors that are less than given value
* | 2 | 3 | 4 |
* | 1 | 0 | 5 |
* | 8 | 7 | 6 |
*/
inline bitset<8> RobustTextDetection::getNeighborsLessThan( int * curr_ptr, int x, int * prev_ptr, int * next_ptr ) {
bitset<8> neighbors;
neighbors[0] = curr_ptr[x-1] == 0 ? 0 : curr_ptr[x-1] < curr_ptr[x];
neighbors[1] = prev_ptr[x-1] == 0 ? 0 : prev_ptr[x-1] < curr_ptr[x];
neighbors[2] = prev_ptr[x ] == 0 ? 0 : prev_ptr[x] < curr_ptr[x];
neighbors[3] = prev_ptr[x+1] == 0 ? 0 : prev_ptr[x+1] < curr_ptr[x];
neighbors[4] = curr_ptr[x+1] == 0 ? 0 : curr_ptr[x+1] < curr_ptr[x];
neighbors[5] = next_ptr[x+1] == 0 ? 0 : next_ptr[x+1] < curr_ptr[x];
neighbors[6] = next_ptr[x ] == 0 ? 0 : next_ptr[x] < curr_ptr[x];
neighbors[7] = next_ptr[x-1] == 0 ? 0 : next_ptr[x-1] < curr_ptr[x];
return neighbors;
}
/**
* Compute the stroke width image out from the distance transform matrix
* It will propagate the max values of each connected component from the ridge
* to outer boundaries
**/
Mat RobustTextDetection::computeStrokeWidth( Mat& dist ) {
/* Pad the distance transformed matrix to avoid boundary checking */
Mat padded( dist.rows + 1, dist.cols + 1, dist.type(), Scalar(0) );
dist.copyTo( Mat( padded, Rect(1, 1, dist.cols, dist.rows ) ) );
Mat lookup( padded.size(), CV_8UC1, Scalar(0) );
int * prev_ptr = padded.ptr<int>(0);
int * curr_ptr = padded.ptr<int>(1);
for( int y = 1; y < padded.rows - 1; y++ ) {
uchar * lookup_ptr = lookup.ptr<uchar>(y);
int * next_ptr = padded.ptr<int>(y+1);
for( int x = 1; x < padded.cols - 1; x++ ) {
/* Extract all the neighbors whose value < curr_ptr[x], encoded in 8-bit uchar */
if( curr_ptr[x] != 0 )
lookup_ptr[x] = static_cast<uchar>( getNeighborsLessThan(curr_ptr, x, prev_ptr, next_ptr).to_ullong() );
}
prev_ptr = curr_ptr;
curr_ptr = next_ptr;
}
/* Get max stroke from the distance transformed */
double max_val_double;
minMaxLoc( padded, 0, &max_val_double );
int max_stroke = static_cast<int>(round( max_val_double ));
for( int stroke = max_stroke; stroke > 0; stroke-- ) {
Mat stroke_indices_mat;
findNonZero( padded == stroke, stroke_indices_mat );
vector<Point> stroke_indices;
stroke_indices_mat.copyTo( stroke_indices );
vector<Point> neighbors;
for( Point& stroke_index : stroke_indices ) {
vector<Point> temp = convertToCoords( stroke_index, lookup.at<uchar>(stroke_index) );
neighbors.insert( neighbors.end(), temp.begin(), temp.end() );
}
while( !neighbors.empty() ){
for( Point& neighbor: neighbors )
padded.at<int>(neighbor) = stroke;
neighbors.clear();
vector<Point> temp( neighbors );
neighbors.clear();
/* Recursively gets neighbors of the current neighbors */
for( Point& neighbor: temp ) {
vector<Point> temp = convertToCoords( neighbor, lookup.at<uchar>(neighbor) );
neighbors.insert( neighbors.end(), temp.begin(), temp.end() );
}
}
}
return Mat( padded, Rect(1, 1, dist.cols, dist.rows) );
}
<|endoftext|> |
<commit_before>#include "ResourceHandler.h"
#ifdef _DEBUG
void Resources::ResourceHandler::ResetQueryCounter()
{
queriesPerFrame = 0;
}
#endif // _DEBUG
Resources::ResourceHandler::ResourceHandler()
{
this->m_modelHandler = new ModelHandler(50);
}
Resources::ResourceHandler::ResourceHandler(ID3D11Device * device, ID3D11DeviceContext * context)
{
this->m_device = device;
this->m_context = context;
this->m_modelHandler = new ModelHandler(50);
m_modelHandler->SetDevice(device);
}
Resources::ResourceHandler::~ResourceHandler()
{
delete m_modelHandler;
delete m_CurrentLevel;
}
Resources::Status Resources::ResourceHandler::LoadLevel(unsigned int id)
{
if (m_device == nullptr){
std::cout << "No device is set. Cannot load resources" << std::endl;
return Status::ST_DEVICE_MISSING;
}
/*
- Load level information,
- Load all models that are in the level.
- Construct the models, load resources if needed and add a reference counter to all the resources used in the model
- Unload the last level, decrement the reference counterof all the resources.
- if a reference counter hits 0, unload the resource
Alternative,
- Unload last level first.
- Then load the level
- Then loop through the resources and check ref counting
*/
/* T e s t */
FileLoader* fileLoader = Resources::FileLoader::GetInstance();
if (!fileLoader->OpenFile(Resources::FileLoader::Files::BPF_FILE))
std::cout << "Could not open resource file"<<std::endl;
//return ST_ERROR_OPENING_FILE;
// for each model in level
{
//Get id of the model from the level Instructions
unsigned int id = 1337;
ResourceContainer* modelPtr = nullptr;
Status st;
st = m_modelHandler->GetModel(id, modelPtr);
switch (st)
{
case Resources::Status::ST_RES_MISSING:
{
#ifdef _DEBUG
std::cout << "Model missing, loading" << std::endl;
#endif // _DEBUG
//Load the model
Status modelSt = m_modelHandler->LoadModel(id, modelPtr);
//if this fails, placeholder will take the place
break;
}
case Resources::Status::ST_OK:
modelPtr->refCount += 1; //Add the reference count
break;
}
}
if(m_CurrentLevel != nullptr)
UnloadLevel(m_CurrentLevel); //Unload the previous level
//m_CurrentLevel = ne;
fileLoader->CloseFile(Resources::FileLoader::Files::BPF_FILE);
#ifdef _DEBUG
this->ResetQueryCounter();
#endif // _DEBUG
return Resources::Status::ST_OK;
}
Resources::Status Resources::ResourceHandler::LoadLevel(LevelData::ResourceHeader * levelResources, unsigned int numResources)
{
if (m_device == nullptr) {
std::cout << "No device is set. Cannot load resources" << std::endl;
return Status::ST_DEVICE_MISSING;
}
/*
- Load level information,
- Load all models that are in the level.
- Construct the models, load resources if needed and add a reference counter to all the resources used in the model
- Unload the last level, decrement the reference counterof all the resources.
- if a reference counter hits 0, unload the resource
*/
if (m_CurrentLevel != nullptr) {
UnloadLevel(m_CurrentLevel); //Unload the previous level
delete m_CurrentLevel;
m_CurrentLevel = nullptr;
}
FileLoader* fileLoader = Resources::FileLoader::GetInstance();
if (!fileLoader->OpenFile(Resources::FileLoader::Files::BPF_FILE))
{
std::cout << "Could not open BPF file" << std::endl;
return ST_ERROR_OPENING_FILE;
}
LevelResources* newLevel = new LevelResources;
newLevel->ids = new unsigned int[numResources];
newLevel->numResources = numResources;
m_CurrentLevel = newLevel;
// for each model in level
Status st;
for (size_t i = 0; i < numResources; i++)
{
//Get id of the model
unsigned int id = levelResources[i].id;
newLevel->ids[i] = id;
ResourceContainer* modelPtr = nullptr;
st = m_modelHandler->GetModel(id, modelPtr);
switch (st)
{
case Resources::Status::ST_RES_MISSING:
{
#ifdef _DEBUG
//std::cout << "Model not loaded, loading" << std::endl;
#endif // _DEBUG
//Load the model
Status modelSt = m_modelHandler->LoadModel(id, modelPtr); //if this fails, placeholder will take the place
#ifdef _DEBUG
if (modelSt != ST_OK) {
std::cout << "Model not found in BPF, ID: " << id << std::endl;
}
#endif // _DEBUG
break;
}
case Resources::Status::ST_OK:
modelPtr->refCount += 1; //Add the reference count
break;
}
}
fileLoader->CloseFile(Resources::FileLoader::Files::BPF_FILE);
//this->ClearUnusedMemory();
#ifdef _DEBUG
this->ResetQueryCounter();
#endif // _DEBUG
return Resources::Status::ST_OK;
}
Resources::Status Resources::ResourceHandler::UnloadCurrentLevel()
{
Resources::Status status = ST_OK;
if (m_CurrentLevel != nullptr) {
UnloadLevel(m_CurrentLevel); //Unload the previous level
}
else
status = Status::ST_RES_MISSING;
return status;
}
Resources::Status Resources::ResourceHandler::ClearUnusedMemory()
{
return m_modelHandler->ClearUnusedMemory();
}
Resources::ResourceHandler * Resources::ResourceHandler::GetInstance()
{
static ResourceHandler instance;
return &instance;
}
void Resources::ResourceHandler::SetDeviceAndContext(ID3D11Device * device, ID3D11DeviceContext * context)
{
this->m_device = device;
this->m_context = context;
m_modelHandler->SetDevice(device);
}
void Resources::ResourceHandler::SetDevice(ID3D11Device * device)
{
this->m_device = device;
m_modelHandler->SetDevice(device);
}
void Resources::ResourceHandler::SetContext(ID3D11DeviceContext * context)
{
this->m_context = context;
}
Resources::Status Resources::ResourceHandler::GetModel(unsigned int id, Model*& modelPtr)
{
ResourceContainer* modelCont = nullptr;
Status st = m_modelHandler->GetModel(id, modelCont);
#ifdef _DEBUG
this->queriesPerFrame += 1;
#endif // _DEBUG
switch (st)
{
case Status::ST_OK:
modelPtr = (Model*)modelCont->resource;
break;
case Status::ST_RES_MISSING:
/*return placeholder MODEL*/
modelPtr = m_modelHandler->GetPlaceholderModel();
return Resources::Status::ST_RES_MISSING;
break;
default:
return st;
}
return Resources::Status::ST_OK;
}
Resources::Status Resources::ResourceHandler::UnloadLevel(LevelResources* levelRes)
{
//for each model in level
//get id of model and unload id
Status st;
for (size_t i = 0; i < levelRes->numResources; i++)
{
st = m_modelHandler->UnloadModel(levelRes->ids[i]);
#ifdef _DEBUG
if (st != ST_OK)
{
MessageBox(NULL, TEXT("Error in unloading model"), TEXT("ERROR"), MB_OK);
//return st;
}
#endif // _DEBUG
}
return Resources::Status::ST_OK;
}
<commit_msg>UPDATE: restoring level unload to previous usage<commit_after>#include "ResourceHandler.h"
#ifdef _DEBUG
void Resources::ResourceHandler::ResetQueryCounter()
{
queriesPerFrame = 0;
}
#endif // _DEBUG
Resources::ResourceHandler::ResourceHandler()
{
this->m_modelHandler = new ModelHandler(50);
}
Resources::ResourceHandler::ResourceHandler(ID3D11Device * device, ID3D11DeviceContext * context)
{
this->m_device = device;
this->m_context = context;
this->m_modelHandler = new ModelHandler(50);
m_modelHandler->SetDevice(device);
}
Resources::ResourceHandler::~ResourceHandler()
{
delete m_modelHandler;
delete m_CurrentLevel;
}
Resources::Status Resources::ResourceHandler::LoadLevel(unsigned int id)
{
if (m_device == nullptr){
std::cout << "No device is set. Cannot load resources" << std::endl;
return Status::ST_DEVICE_MISSING;
}
/*
- Load level information,
- Load all models that are in the level.
- Construct the models, load resources if needed and add a reference counter to all the resources used in the model
- Unload the last level, decrement the reference counterof all the resources.
- if a reference counter hits 0, unload the resource
Alternative,
- Unload last level first.
- Then load the level
- Then loop through the resources and check ref counting
*/
/* T e s t */
FileLoader* fileLoader = Resources::FileLoader::GetInstance();
if (!fileLoader->OpenFile(Resources::FileLoader::Files::BPF_FILE))
std::cout << "Could not open resource file"<<std::endl;
//return ST_ERROR_OPENING_FILE;
// for each model in level
{
//Get id of the model from the level Instructions
unsigned int id = 1337;
ResourceContainer* modelPtr = nullptr;
Status st;
st = m_modelHandler->GetModel(id, modelPtr);
switch (st)
{
case Resources::Status::ST_RES_MISSING:
{
#ifdef _DEBUG
std::cout << "Model missing, loading" << std::endl;
#endif // _DEBUG
//Load the model
Status modelSt = m_modelHandler->LoadModel(id, modelPtr);
//if this fails, placeholder will take the place
break;
}
case Resources::Status::ST_OK:
modelPtr->refCount += 1; //Add the reference count
break;
}
}
if(m_CurrentLevel != nullptr)
UnloadLevel(m_CurrentLevel); //Unload the previous level
//m_CurrentLevel = ne;
fileLoader->CloseFile(Resources::FileLoader::Files::BPF_FILE);
#ifdef _DEBUG
this->ResetQueryCounter();
#endif // _DEBUG
return Resources::Status::ST_OK;
}
Resources::Status Resources::ResourceHandler::LoadLevel(LevelData::ResourceHeader * levelResources, unsigned int numResources)
{
if (m_device == nullptr) {
std::cout << "No device is set. Cannot load resources" << std::endl;
return Status::ST_DEVICE_MISSING;
}
/*
- Load level information,
- Load all models that are in the level.
- Construct the models, load resources if needed and add a reference counter to all the resources used in the model
- Unload the last level, decrement the reference counterof all the resources.
- if a reference counter hits 0, unload the resource
*/
FileLoader* fileLoader = Resources::FileLoader::GetInstance();
if (!fileLoader->OpenFile(Resources::FileLoader::Files::BPF_FILE))
{
std::cout << "Could not open BPF file" << std::endl;
return ST_ERROR_OPENING_FILE;
}
LevelResources* newLevel = new LevelResources;
newLevel->ids = new unsigned int[numResources];
newLevel->numResources = numResources;
// for each model in level
Status st;
for (size_t i = 0; i < numResources; i++)
{
//Get id of the model
unsigned int id = levelResources[i].id;
newLevel->ids[i] = id;
ResourceContainer* modelPtr = nullptr;
st = m_modelHandler->GetModel(id, modelPtr);
switch (st)
{
case Resources::Status::ST_RES_MISSING:
{
#ifdef _DEBUG
//std::cout << "Model not loaded, loading" << std::endl;
#endif // _DEBUG
//Load the model
Status modelSt = m_modelHandler->LoadModel(id, modelPtr); //if this fails, placeholder will take the place
#ifdef _DEBUG
if (modelSt != ST_OK) {
std::cout << "Model not found in BPF, ID: " << id << std::endl;
}
#endif // _DEBUG
break;
}
case Resources::Status::ST_OK:
modelPtr->refCount += 1; //Add the reference count
break;
}
}
fileLoader->CloseFile(Resources::FileLoader::Files::BPF_FILE);
if (m_CurrentLevel != nullptr) {
UnloadLevel(m_CurrentLevel); //Unload the previous level
}
m_CurrentLevel = newLevel;
//this->ClearUnusedMemory();
#ifdef _DEBUG
this->ResetQueryCounter();
#endif // _DEBUG
return Resources::Status::ST_OK;
}
Resources::Status Resources::ResourceHandler::UnloadCurrentLevel()
{
Resources::Status status = ST_OK;
if (m_CurrentLevel != nullptr) {
UnloadLevel(m_CurrentLevel); //Unload the previous level
delete m_CurrentLevel;
m_CurrentLevel = nullptr;
}
else
status = Status::ST_RES_MISSING;
return status;
}
Resources::Status Resources::ResourceHandler::ClearUnusedMemory()
{
return m_modelHandler->ClearUnusedMemory();
}
Resources::ResourceHandler * Resources::ResourceHandler::GetInstance()
{
static ResourceHandler instance;
return &instance;
}
void Resources::ResourceHandler::SetDeviceAndContext(ID3D11Device * device, ID3D11DeviceContext * context)
{
this->m_device = device;
this->m_context = context;
m_modelHandler->SetDevice(device);
}
void Resources::ResourceHandler::SetDevice(ID3D11Device * device)
{
this->m_device = device;
m_modelHandler->SetDevice(device);
}
void Resources::ResourceHandler::SetContext(ID3D11DeviceContext * context)
{
this->m_context = context;
}
Resources::Status Resources::ResourceHandler::GetModel(unsigned int id, Model*& modelPtr)
{
ResourceContainer* modelCont = nullptr;
Status st = m_modelHandler->GetModel(id, modelCont);
#ifdef _DEBUG
this->queriesPerFrame += 1;
#endif // _DEBUG
switch (st)
{
case Status::ST_OK:
modelPtr = (Model*)modelCont->resource;
break;
case Status::ST_RES_MISSING:
/*return placeholder MODEL*/
modelPtr = m_modelHandler->GetPlaceholderModel();
return Resources::Status::ST_RES_MISSING;
break;
default:
return st;
}
return Resources::Status::ST_OK;
}
Resources::Status Resources::ResourceHandler::UnloadLevel(LevelResources* levelRes)
{
//for each model in level
//get id of model and unload id
Status st;
for (size_t i = 0; i < levelRes->numResources; i++)
{
st = m_modelHandler->UnloadModel(levelRes->ids[i]);
#ifdef _DEBUG
if (st != ST_OK)
{
MessageBox(NULL, TEXT("Error in unloading model"), TEXT("ERROR"), MB_OK);
//return st;
}
#endif // _DEBUG
}
return Resources::Status::ST_OK;
}
<|endoftext|> |
<commit_before>//
// Created by Robert Segal on 2014-04-01.
// Copyright (c) 2016 Get Set Games Inc. All rights reserved.
//
#include "UpsightPrivatePCH.h"
#include "Android/AndroidJNI.h"
#include "AndroidApplication.h"
#if PLATFORM_IOS
#endif
<commit_msg>Validation data function used for several tracking functions<commit_after>//
// Created by Robert Segal on 2014-04-01.
// Copyright (c) 2016 Get Set Games Inc. All rights reserved.
//
#include "UpsightPrivatePCH.h"
#include "Android/AndroidJNI.h"
#include "AndroidApplication.h"
bool ValidateValues(TArray<FString> &Keys, TArray<FString> &Values)
{
const int32 kNumKeys = Keys.Num();
const int32 kNumValues = Values.Num();
if (kNumKeys == 0 || kNumValues == 0)
{
return false;
}
if (kNumKeys != kNumValues)
{
return false;
}
return true;
}
#if PLATFORM_IOS
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbForwardSensorModel.h"
#include "otbInverseSensorModel.h"
int otbSensorModel( int argc, char* argv[] )
{
if (argc!=3)
{
std::cout << argv[0] <<" <input filename> <output filename>"
<< std::endl;
return EXIT_FAILURE;
}
char * filename = argv[1];
char * outFilename = argv[2];
std::ofstream file;
file.open(outFilename);
file << std::setprecision(20);
typedef otb::VectorImage<double, 2> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(filename);
reader->UpdateOutputInformation();
file << "*** KEYWORD LIST ***\n";
file << reader->GetOutput()->GetImageKeywordlist();
file << "\n*** TRANSFORM ***\n";
typedef otb::ForwardSensorModel<double> ForwardSensorModelType;
ForwardSensorModelType::Pointer forwardSensorModel = ForwardSensorModelType::New();
forwardSensorModel->SetImageGeometry(reader->GetOutput()->GetImageKeywordlist());
forwardSensorModel->SetAverageElevation(16.19688987731934);
itk::Point<double,2> imagePoint;
imagePoint[0]=10;
imagePoint[1]=10;
// imagePoint[0]=3069;
// imagePoint[1]=1218;
itk::Point<double,2> geoPoint;
geoPoint = forwardSensorModel->TransformPoint(imagePoint);
file << "Image to geo: " << imagePoint << " -> " << geoPoint << "\n";
typedef otb::InverseSensorModel<double> InverseSensorModelType;
InverseSensorModelType::Pointer inverseSensorModel = InverseSensorModelType::New();
inverseSensorModel->SetImageGeometry(reader->GetOutput()->GetImageKeywordlist());
inverseSensorModel->SetAverageElevation(16.19688987731934);
itk::Point<double,2> reversedImagePoint;
reversedImagePoint = inverseSensorModel->TransformPoint(geoPoint);
file << "Geo to image: " << geoPoint << " -> " << reversedImagePoint << "\n";
file.close();
return EXIT_SUCCESS;
}
<commit_msg>ENH : oups<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbForwardSensorModel.h"
#include "otbInverseSensorModel.h"
int otbSensorModel( int argc, char* argv[] )
{
if (argc!=3)
{
std::cout << argv[0] <<" <input filename> <output filename>"
<< std::endl;
return EXIT_FAILURE;
}
char * filename = argv[1];
char * outFilename = argv[2];
std::ofstream file;
file.open(outFilename);
file << std::setprecision(15);
typedef otb::VectorImage<double, 2> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(filename);
reader->UpdateOutputInformation();
file << "*** KEYWORD LIST ***\n";
file << reader->GetOutput()->GetImageKeywordlist();
file << "\n*** TRANSFORM ***\n";
typedef otb::ForwardSensorModel<double> ForwardSensorModelType;
ForwardSensorModelType::Pointer forwardSensorModel = ForwardSensorModelType::New();
forwardSensorModel->SetImageGeometry(reader->GetOutput()->GetImageKeywordlist());
forwardSensorModel->SetAverageElevation(16.19688987731934);
itk::Point<double,2> imagePoint;
imagePoint[0]=10;
imagePoint[1]=10;
// imagePoint[0]=3069;
// imagePoint[1]=1218;
itk::Point<double,2> geoPoint;
geoPoint = forwardSensorModel->TransformPoint(imagePoint);
file << "Image to geo: " << imagePoint << " -> " << geoPoint << "\n";
typedef otb::InverseSensorModel<double> InverseSensorModelType;
InverseSensorModelType::Pointer inverseSensorModel = InverseSensorModelType::New();
inverseSensorModel->SetImageGeometry(reader->GetOutput()->GetImageKeywordlist());
inverseSensorModel->SetAverageElevation(16.19688987731934);
itk::Point<double,2> reversedImagePoint;
reversedImagePoint = inverseSensorModel->TransformPoint(geoPoint);
file << "Geo to image: " << geoPoint << " -> " << reversedImagePoint << "\n";
file.close();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//
// PushPillar.cpp
// Created by Matt Kaufmann on 03/31/14.
//
#include "ExampleGame/Components/GameScripts/Units/Assassin.h"
#include "ExampleGame/Components/GameScripts/Units/Obstacles/PushPillar.h"
#include "ExampleGame/Components/Grid/GridManager.h"
#include "ExampleGame/Components/Grid/GridNavigator.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "ExampleGame/Messages/Declarations.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/MessageHub/MessageHub.h"
#include "Vajra/Engine/SceneGraph/SceneGraph3D.h"
#include "Vajra/Engine/Timer/Timer.h"
#include "Vajra/Utilities/MathUtilities.h"
PushPillar::PushPillar() : BaseUnit() {
this->init();
}
PushPillar::PushPillar(Object* object_) : BaseUnit(object_) {
this->init();
}
PushPillar::~PushPillar() {
this->destroy();
}
void PushPillar::init() {
this->unitType = UNIT_TYPE_PILLAR;
this->gridNavRef->SetMaxNavigableUnitType(UNIT_TYPE_NONE);
this->gridNavRef->SetMovementSpeed(2.0f);
this->isSliding = false;
this->slideX = 0;
this->slideZ = 0;
this->targetPosition = ZERO_VEC3;
this->riderId = OBJECT_ID_INVALID;
this->addSubscriptionToMessageType(MESSAGE_TYPE_NAVIGATION_REACHED_DESTINATION, this->GetTypeId(), false);
this->addSubscriptionToMessageType(MESSAGE_TYPE_GRID_ZONE_ENTERED , this->GetTypeId(), false);
this->addSubscriptionToMessageType(MESSAGE_TYPE_GRID_ZONE_ENTERED_CELL , this->GetTypeId(), false);
this->addSubscriptionToMessageType(MESSAGE_TYPE_GRID_ZONE_EXITED_CELL , this->GetTypeId(), false);
}
void PushPillar::destroy() {
}
void PushPillar::HandleMessage(MessageChunk messageChunk) {
BaseUnit::HandleMessage(messageChunk);
switch (messageChunk->GetMessageType()) {
case MESSAGE_TYPE_NAVIGATION_REACHED_DESTINATION:
if (this->isSliding) {
this->slide();
}
break;
case MESSAGE_TYPE_GRID_ZONE_ENTERED:
if (this->isSliding && (messageChunk->GetSenderId() != this->gameObjectRef->GetId())) {
this->childUnitOnTop();
}
break;
case MESSAGE_TYPE_GRID_ZONE_ENTERED_CELL:
if (messageChunk->GetSenderId() == this->GetObject()->GetId()) {
this->onZoneEnteredCell(messageChunk->messageData.iv1.x, messageChunk->messageData.iv1.z);
}
break;
case MESSAGE_TYPE_GRID_ZONE_EXITED_CELL:
if (messageChunk->GetSenderId() == this->GetObject()->GetId()) {
this->onZoneExitedCell(messageChunk->messageData.iv1.x, messageChunk->messageData.iv1.z);
}
break;
}
}
bool PushPillar::CanBeKilledBy(ObjectIdType /*id*/, glm::vec3 /*source*/) {
/*
GameObject* gObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(id);
ASSERT(gObj != nullptr, "GameObject exists with id %d", id);
if (gObj != nullptr) {
BaseUnit* unit = gObj->GetComponent<BaseUnit>();
if (unit != nullptr) {
// Pillars can only be pushed by the assassin.
if (unit->GetUnitType() == UNIT_TYPE_ASSASSIN) {
return true;
}
}
}
*/
return false;
}
void PushPillar::start() {
this->gridNavRef->SetTurnSpeedRadians(0.0f);
}
void PushPillar::end() {
}
void PushPillar::update() {
if (this->isSliding) {
this->slide();
}
}
void PushPillar::onUnitSpecialHit(ObjectIdType id, int gridX, int gridZ, glm::vec3 source) {
// First check if the attack hit my cell
GridCell* cell = this->gridNavRef->GetCurrentCell();
if (cell != nullptr) {
if ((cell->x == gridX) && (cell->z == gridZ)) {
// Check if the attacker can kill me
//if (this->CanBeKilledBy(id, source)) {
GameObject* gObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(id);
ASSERT(gObj != nullptr, "GameObject exists with id %d", id);
if (gObj != nullptr) {
BaseUnit* unit = gObj->GetComponent<BaseUnit>();
if (unit != nullptr) {
// Pillars can only be pushed by the assassin.
if (unit->GetUnitType() == UNIT_TYPE_ASSASSIN) {
// Move it!
this->startSliding(this->gameObjectRef->GetTransform()->GetPositionWorld() - source);
}
}
}
}
}
}
void PushPillar::Kill() {
}
void PushPillar::startSliding(glm::vec3 direction) {
// Convert the direction vector to one of the cardinal directions (N/S/E/W)
if (direction.x > ROUNDING_ERROR) { this->slideX = 1; }
else if (direction.x < -ROUNDING_ERROR) { this->slideX = -1; }
else { this->slideX = 0; }
if (direction.z > ROUNDING_ERROR) { this->slideZ = 1; }
else if (direction.z < -ROUNDING_ERROR) { this->slideZ = -1; }
else { this->slideZ = 0; }
if ((this->slideX != 0) && (this->slideZ != 0)) {
// Pillars can't slide diagonally. If either X or Z greatly outweighs the other, clamp to that direction. Otherwise, don't move.
float ratio = direction.x * this->slideX * this->slideZ / direction.z;
if (ratio < 2.0f) { this->slideX = 0; }
if (ratio > 0.5f) { this->slideZ = 0; }
}
if ((this->slideX != 0) || (this->slideZ != 0)) {
this->setNextTarget();
if (this->targetPosition != ZERO_VEC3) {
this->isSliding = true;
this->childUnitOnTop();
}
}
}
void PushPillar::setNextTarget() {
GridCell* myCell = this->gridNavRef->GetCurrentCell();
if (myCell != nullptr) {
GridCell* targetCell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(myCell->x + this->slideX, myCell->z - this->slideZ);
if (targetCell != nullptr) {
if (this->gridNavRef->canNavigateThroughCellAtElevation(targetCell, this->gridNavRef->GetElevation(), false)) {
this->targetPosition = targetCell->center;
}
else {
this->targetPosition = ZERO_VEC3;
}
}
}
}
void PushPillar::slide() {
float dt = ENGINE->GetTimer()->GetDeltaFrameTime();
float distToTravel = this->gridNavRef->GetMovementSpeed() * dt;
glm::vec3 tempLocation = this->gameObjectRef->GetTransform()->GetPositionWorld();
float distToTarget = glm::distance(tempLocation, this->targetPosition);
while (distToTravel > distToTarget) {
distToTravel -= distToTarget;
tempLocation = this->targetPosition;
this->setNextTarget();
if (this->targetPosition != ZERO_VEC3) {
distToTarget = glm::distance(tempLocation, this->targetPosition);
}
else {
distToTravel = 0.0f;
}
}
float ratio = distToTravel / distToTarget;
lerp(tempLocation, tempLocation, this->targetPosition, ratio);
this->gameObjectRef->GetTransform()->SetPositionWorld(tempLocation);
GridCell* newCell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(tempLocation);
if (newCell != this->gridNavRef->GetCurrentCell()) {
this->changeCell(newCell);
}
if (distToTravel <= 0.0f) {
this->stopSliding();
}
}
void PushPillar::changeCell(GridCell* goalCell, int elevation/*= -1*/) {
// If no elevation or an invalid elevation was specified, keep the navigator at its current elevation.
if ((elevation < 0) || (elevation >= NUM_ELEVATIONS)) {
elevation = this->gridNavRef->GetElevation();
}
int gridX, gridZ;
if (goalCell != nullptr) {
gridX = goalCell->x;
gridZ = goalCell->z;
}
else {
gridX = -1;
gridZ = -1;
}
// Send a message to the GridManager "asking" to move from one cell to another.
MessageChunk cellChangeMessage = ENGINE->GetMessageHub()->GetOneFreeMessage();
cellChangeMessage->SetMessageType(MESSAGE_TYPE_GRID_CELL_CHANGED);
cellChangeMessage->messageData.iv1.x = gridX;
cellChangeMessage->messageData.iv1.y = elevation;
cellChangeMessage->messageData.iv1.z = gridZ;
ENGINE->GetMessageHub()->SendMulticastMessage(cellChangeMessage, this->GetObject()->GetId());
}
void PushPillar::stopSliding() {
this->isSliding = false;
this->unchildUnitOnTop();
}
void PushPillar::childUnitOnTop() {
GridCell* cell = this->gridNavRef->GetCurrentCell();
if (cell != nullptr) {
int elevation = this->gridNavRef->GetElevation() + 1;
this->riderId = cell->GetOccupantIdAtElevation(elevation);
if (this->riderId != OBJECT_ID_INVALID) {
GameObject* gObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(riderId);
if (gObj != nullptr) {
this->gameObjectRef->AddChild_maintainTransform(this->riderId);
// If it's a unit that's moving, stop it:
GridNavigator* gNav = gObj->GetComponent<GridNavigator>();
if (gNav != nullptr) {
if(gObj->GetComponent<BaseUnit>()) {
if(gObj->GetComponent<BaseUnit>()->GetUnitType() == UnitType::UNIT_TYPE_ASSASSIN) {
gObj->GetComponent<Assassin>()->cancelSpecial();
}
}
gNav->HaltMovement();
gNav->DisableNavigation();
}
}
}
}
}
void PushPillar::unchildUnitOnTop() {
if (this->riderId != OBJECT_ID_INVALID) {
GameObject* gObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(this->riderId);
ASSERT(gObj != nullptr, "Object exists with id %d", this->riderId);
if (gObj != nullptr) {
gObj->GetParentSceneGraph()->GetRootGameObject()->AddChild_maintainTransform(this->riderId);
// Re-enable the navigator.
GridNavigator* gNav = gObj->GetComponent<GridNavigator>();
if (gNav != nullptr) {
GridCell* cell = this->gridNavRef->GetCurrentCell();
if (cell != nullptr) {
int elevation = this->gridNavRef->GetElevation() + 1;
gNav->SetGridPosition(cell, elevation);
}
gNav->EnableNavigation();
}
}
this->riderId = OBJECT_ID_INVALID;
}
}
void PushPillar::onZoneEnteredCell(int gridX, int gridZ) {
// When the pillar enters a cell, that cell becomes passable above the pillar
int elevation = this->gridNavRef->GetElevation();
if (elevation < (NUM_ELEVATIONS - 1)) {
SINGLETONS->GetGridManager()->GetGrid()->SetCellPassableAtElevation(gridX, gridZ, elevation + 1, true);
}
}
void PushPillar::onZoneExitedCell(int gridX, int gridZ) {
// When the pillar exits a cell, that cell becomes impassable at the higher elevation
int elevation = this->gridNavRef->GetElevation();
if (elevation < (NUM_ELEVATIONS - 1)) {
SINGLETONS->GetGridManager()->GetGrid()->SetCellPassableAtElevation(gridX, gridZ, elevation + 1, false);
}
}
<commit_msg>Added audio hooks to PushPillar<commit_after>//
// PushPillar.cpp
// Created by Matt Kaufmann on 03/31/14.
//
#include "ExampleGame/Components/GameScripts/Units/Assassin.h"
#include "ExampleGame/Components/GameScripts/Units/Obstacles/PushPillar.h"
#include "ExampleGame/Components/Grid/GridManager.h"
#include "ExampleGame/Components/Grid/GridNavigator.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "ExampleGame/Messages/Declarations.h"
#include "Vajra/Engine/Components/DerivedComponents/Audio/AudioSource.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/MessageHub/MessageHub.h"
#include "Vajra/Engine/SceneGraph/SceneGraph3D.h"
#include "Vajra/Engine/Timer/Timer.h"
#include "Vajra/Utilities/MathUtilities.h"
PushPillar::PushPillar() : BaseUnit() {
this->init();
}
PushPillar::PushPillar(Object* object_) : BaseUnit(object_) {
this->init();
}
PushPillar::~PushPillar() {
this->destroy();
}
void PushPillar::init() {
this->unitType = UNIT_TYPE_PILLAR;
this->gridNavRef->SetMaxNavigableUnitType(UNIT_TYPE_NONE);
this->gridNavRef->SetMovementSpeed(2.0f);
this->isSliding = false;
this->slideX = 0;
this->slideZ = 0;
this->targetPosition = ZERO_VEC3;
this->riderId = OBJECT_ID_INVALID;
this->addSubscriptionToMessageType(MESSAGE_TYPE_NAVIGATION_REACHED_DESTINATION, this->GetTypeId(), false);
this->addSubscriptionToMessageType(MESSAGE_TYPE_GRID_ZONE_ENTERED , this->GetTypeId(), false);
this->addSubscriptionToMessageType(MESSAGE_TYPE_GRID_ZONE_ENTERED_CELL , this->GetTypeId(), false);
this->addSubscriptionToMessageType(MESSAGE_TYPE_GRID_ZONE_EXITED_CELL , this->GetTypeId(), false);
}
void PushPillar::destroy() {
}
void PushPillar::HandleMessage(MessageChunk messageChunk) {
BaseUnit::HandleMessage(messageChunk);
switch (messageChunk->GetMessageType()) {
case MESSAGE_TYPE_NAVIGATION_REACHED_DESTINATION:
if (this->isSliding) {
this->slide();
}
break;
case MESSAGE_TYPE_GRID_ZONE_ENTERED:
if (this->isSliding && (messageChunk->GetSenderId() != this->gameObjectRef->GetId())) {
this->childUnitOnTop();
}
break;
case MESSAGE_TYPE_GRID_ZONE_ENTERED_CELL:
if (messageChunk->GetSenderId() == this->GetObject()->GetId()) {
this->onZoneEnteredCell(messageChunk->messageData.iv1.x, messageChunk->messageData.iv1.z);
}
break;
case MESSAGE_TYPE_GRID_ZONE_EXITED_CELL:
if (messageChunk->GetSenderId() == this->GetObject()->GetId()) {
this->onZoneExitedCell(messageChunk->messageData.iv1.x, messageChunk->messageData.iv1.z);
}
break;
}
}
bool PushPillar::CanBeKilledBy(ObjectIdType /*id*/, glm::vec3 /*source*/) {
/*
GameObject* gObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(id);
ASSERT(gObj != nullptr, "GameObject exists with id %d", id);
if (gObj != nullptr) {
BaseUnit* unit = gObj->GetComponent<BaseUnit>();
if (unit != nullptr) {
// Pillars can only be pushed by the assassin.
if (unit->GetUnitType() == UNIT_TYPE_ASSASSIN) {
return true;
}
}
}
*/
return false;
}
void PushPillar::start() {
this->gridNavRef->SetTurnSpeedRadians(0.0f);
}
void PushPillar::end() {
}
void PushPillar::update() {
if (this->isSliding) {
this->slide();
}
}
void PushPillar::onUnitSpecialHit(ObjectIdType id, int gridX, int gridZ, glm::vec3 source) {
// First check if the attack hit my cell
GridCell* cell = this->gridNavRef->GetCurrentCell();
if (cell != nullptr) {
if ((cell->x == gridX) && (cell->z == gridZ)) {
// Check if the attacker can kill me
//if (this->CanBeKilledBy(id, source)) {
GameObject* gObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(id);
ASSERT(gObj != nullptr, "GameObject exists with id %d", id);
if (gObj != nullptr) {
BaseUnit* unit = gObj->GetComponent<BaseUnit>();
if (unit != nullptr) {
// Pillars can only be pushed by the assassin.
if (unit->GetUnitType() == UNIT_TYPE_ASSASSIN) {
// Move it!
this->startSliding(this->gameObjectRef->GetTransform()->GetPositionWorld() - source);
}
}
}
}
}
}
void PushPillar::Kill() {
}
void PushPillar::startSliding(glm::vec3 direction) {
// Convert the direction vector to one of the cardinal directions (N/S/E/W)
if (direction.x > ROUNDING_ERROR) { this->slideX = 1; }
else if (direction.x < -ROUNDING_ERROR) { this->slideX = -1; }
else { this->slideX = 0; }
if (direction.z > ROUNDING_ERROR) { this->slideZ = 1; }
else if (direction.z < -ROUNDING_ERROR) { this->slideZ = -1; }
else { this->slideZ = 0; }
if ((this->slideX != 0) && (this->slideZ != 0)) {
// Pillars can't slide diagonally. If either X or Z greatly outweighs the other, clamp to that direction. Otherwise, don't move.
float ratio = direction.x * this->slideX * this->slideZ / direction.z;
if (ratio < 2.0f) { this->slideX = 0; }
if (ratio > 0.5f) { this->slideZ = 0; }
}
if ((this->slideX != 0) || (this->slideZ != 0)) {
this->setNextTarget();
if (this->targetPosition != ZERO_VEC3) {
AudioSource* audioSource = this->gameObjectRef->GetComponent<AudioSource>();
if (audioSource != nullptr) {
audioSource->Play("walk", true);
}
this->isSliding = true;
this->childUnitOnTop();
}
}
}
void PushPillar::setNextTarget() {
GridCell* myCell = this->gridNavRef->GetCurrentCell();
if (myCell != nullptr) {
GridCell* targetCell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(myCell->x + this->slideX, myCell->z - this->slideZ);
if (targetCell != nullptr) {
if (this->gridNavRef->canNavigateThroughCellAtElevation(targetCell, this->gridNavRef->GetElevation(), false)) {
this->targetPosition = targetCell->center;
}
else {
this->targetPosition = ZERO_VEC3;
}
}
}
}
void PushPillar::slide() {
float dt = ENGINE->GetTimer()->GetDeltaFrameTime();
float distToTravel = this->gridNavRef->GetMovementSpeed() * dt;
glm::vec3 tempLocation = this->gameObjectRef->GetTransform()->GetPositionWorld();
float distToTarget = glm::distance(tempLocation, this->targetPosition);
while (distToTravel > distToTarget) {
distToTravel -= distToTarget;
tempLocation = this->targetPosition;
this->setNextTarget();
if (this->targetPosition != ZERO_VEC3) {
distToTarget = glm::distance(tempLocation, this->targetPosition);
}
else {
distToTravel = 0.0f;
}
}
float ratio = distToTravel / distToTarget;
lerp(tempLocation, tempLocation, this->targetPosition, ratio);
this->gameObjectRef->GetTransform()->SetPositionWorld(tempLocation);
GridCell* newCell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(tempLocation);
if (newCell != this->gridNavRef->GetCurrentCell()) {
this->changeCell(newCell);
}
if (distToTravel <= 0.0f) {
this->stopSliding();
}
}
void PushPillar::changeCell(GridCell* goalCell, int elevation/*= -1*/) {
// If no elevation or an invalid elevation was specified, keep the navigator at its current elevation.
if ((elevation < 0) || (elevation >= NUM_ELEVATIONS)) {
elevation = this->gridNavRef->GetElevation();
}
int gridX, gridZ;
if (goalCell != nullptr) {
gridX = goalCell->x;
gridZ = goalCell->z;
}
else {
gridX = -1;
gridZ = -1;
}
// Send a message to the GridManager "asking" to move from one cell to another.
MessageChunk cellChangeMessage = ENGINE->GetMessageHub()->GetOneFreeMessage();
cellChangeMessage->SetMessageType(MESSAGE_TYPE_GRID_CELL_CHANGED);
cellChangeMessage->messageData.iv1.x = gridX;
cellChangeMessage->messageData.iv1.y = elevation;
cellChangeMessage->messageData.iv1.z = gridZ;
ENGINE->GetMessageHub()->SendMulticastMessage(cellChangeMessage, this->GetObject()->GetId());
}
void PushPillar::stopSliding() {
AudioSource* audioSource = this->gameObjectRef->GetComponent<AudioSource>();
if (audioSource != nullptr) {
// Stop playing the sliding sound even if there's no additional sound.
audioSource->Stop();
audioSource->Play("halt");
}
this->isSliding = false;
this->unchildUnitOnTop();
}
void PushPillar::childUnitOnTop() {
GridCell* cell = this->gridNavRef->GetCurrentCell();
if (cell != nullptr) {
int elevation = this->gridNavRef->GetElevation() + 1;
this->riderId = cell->GetOccupantIdAtElevation(elevation);
if (this->riderId != OBJECT_ID_INVALID) {
GameObject* gObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(riderId);
if (gObj != nullptr) {
this->gameObjectRef->AddChild_maintainTransform(this->riderId);
// If it's a unit that's moving, stop it:
GridNavigator* gNav = gObj->GetComponent<GridNavigator>();
if (gNav != nullptr) {
if(gObj->GetComponent<BaseUnit>()) {
if(gObj->GetComponent<BaseUnit>()->GetUnitType() == UnitType::UNIT_TYPE_ASSASSIN) {
gObj->GetComponent<Assassin>()->cancelSpecial();
}
}
gNav->HaltMovement();
gNav->DisableNavigation();
}
}
}
}
}
void PushPillar::unchildUnitOnTop() {
if (this->riderId != OBJECT_ID_INVALID) {
GameObject* gObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(this->riderId);
ASSERT(gObj != nullptr, "Object exists with id %d", this->riderId);
if (gObj != nullptr) {
gObj->GetParentSceneGraph()->GetRootGameObject()->AddChild_maintainTransform(this->riderId);
// Re-enable the navigator.
GridNavigator* gNav = gObj->GetComponent<GridNavigator>();
if (gNav != nullptr) {
GridCell* cell = this->gridNavRef->GetCurrentCell();
if (cell != nullptr) {
int elevation = this->gridNavRef->GetElevation() + 1;
gNav->SetGridPosition(cell, elevation);
}
gNav->EnableNavigation();
}
}
this->riderId = OBJECT_ID_INVALID;
}
}
void PushPillar::onZoneEnteredCell(int gridX, int gridZ) {
// When the pillar enters a cell, that cell becomes passable above the pillar
int elevation = this->gridNavRef->GetElevation();
if (elevation < (NUM_ELEVATIONS - 1)) {
SINGLETONS->GetGridManager()->GetGrid()->SetCellPassableAtElevation(gridX, gridZ, elevation + 1, true);
}
}
void PushPillar::onZoneExitedCell(int gridX, int gridZ) {
// When the pillar exits a cell, that cell becomes impassable at the higher elevation
int elevation = this->gridNavRef->GetElevation();
if (elevation < (NUM_ELEVATIONS - 1)) {
SINGLETONS->GetGridManager()->GetGrid()->SetCellPassableAtElevation(gridX, gridZ, elevation + 1, false);
}
}
<|endoftext|> |
<commit_before>namespace mant {
template <typename T>
class CuckooSearch : public PopulationBasedOptimisationAlgorithm<T>{
public:
inline explicit CuckooSearch(
const std::shared_ptr<OptimisationProblem<T>> optimisationProblem,
const unsigned int populationSize) noexcept;
inline void setDiscoveryProbability(
const T prob) noexcept;
inline void setLevyStepSize(
const T stepSize) noexcept;
inline std::string toString() const noexcept override;
protected:
T discoveryProbability_;
T levyStepSize_;
inline void optimiseImplementation() override;
};
//
//Implementation
//
template <typename T>
inline CuckooSearch<T>::CuckooSearch(
const std::shared_ptr<OptimisationProblem<T>> optimisationProblem,
const unsigned int populationSize) noexcept
: PopulationBasedOptimisationAlgorithm<T>(optimisationProblem, populationSize){
setDiscoveryProbability(0.25);
setLevyStepSize(1.0);
}
template <typename T>
inline void CuckooSearch<T>::optimiseImplementation(){
arma::Mat<T> hostNests = arma::randu<arma::Mat<T>>(this->numberOfDimensions_, this->populationSize_);
hostNests.each_col() %= this->getUpperBounds() - this->getLowerBounds();
hostNests.each_col() += this->getLowerBounds();
arma::Col<T> nestFitness(this->populationSize_);
for(std::size_t i = 0; i < this->populationSize_; ++i){
nestFitness(i) = this->getObjectiveValue(hostNests.col(i));
++this->numberOfIterations_;
}
unsigned int rankIndex;
nestFitness.min(rankIndex);
this->bestObjectiveValue_ = nestFitness(rankIndex);
this->bestParameter_ = hostNests.col(rankIndex);
while(!this->isFinished() && !this->isTerminated()){
++this->numberOfIterations_;
nestFitness.min(rankIndex);
arma::Col<T> newCuckoo = hostNests.col(rankIndex);
//bei BentCigar gitb das in einer Expression bessere Ergebnisse aus
//bei SphereFunction das aufgeteilte
//Levy flights by Mantegna's algorithm
arma::Col<T> u = arma::randn<arma::Col<T>>(this->numberOfDimensions_) * pow((tgamma(1+(3/2))*sin(M_PI*(3/2)/2)/(tgamma((1+(3/2))/2)*(3/2)*pow(2,(((3/2)-1)/2)))),(1/(3/2)));
arma::Col<T> step = u/pow(abs(arma::randn<arma::Col<T>>(this->numberOfDimensions_)),1/(3/2));
arma::Col<T> stepSize = levyStepSize_ * 0.01 * step % (newCuckoo - hostNests(rankIndex));
newCuckoo += stepSize ;
//in one expression:
//newCuckoo += levyStepSize_ * 0.01 * ((arma::randn<arma::Col<T>>(this->numberOfDimensions_)
// * pow((tgamma(1+(3/2))*sin(M_PI*(3/2)/2)/(tgamma((1+(3/2))/2)*(3/2)*pow(2,(((3/2)-1)/2)))),(1/(3/2))))
// / pow(abs(arma::randn<arma::Col<T>>(this->numberOfDimensions_)),1/(3/2))) % (newCuckoo - hostNests(rankIndex));
const arma::Col<unsigned int>& belowLowerBound = arma::find(newCuckoo < this->getLowerBounds());
const arma::Col<unsigned int>& aboveUpperBound = arma::find(newCuckoo > this->getUpperBounds());
newCuckoo.elem(belowLowerBound) = this->getLowerBounds().elem(belowLowerBound);
newCuckoo.elem(aboveUpperBound) = this->getUpperBounds().elem(aboveUpperBound);
nestFitness.max(rankIndex);
if(this->getObjectiveValue(newCuckoo) < nestFitness(rankIndex)){
hostNests.col(rankIndex) = newCuckoo;
nestFitness(rankIndex) = this->getObjectiveValue(hostNests.col(rankIndex));
}
for(std::size_t i = 0; i < discoveryProbability_ * this->populationSize_; ++i){
++this->numberOfIterations_;
nestFitness.max(rankIndex);
hostNests.col(rankIndex) = this->getRandomParameter();
nestFitness(rankIndex) = this->getObjectiveValue(hostNests.col(rankIndex));
if(this->isFinished() || this->isTerminated())break;
}
nestFitness.min(rankIndex);
if (this->getObjectiveValue(hostNests.col(rankIndex)) < this->bestObjectiveValue_) {
this->bestObjectiveValue_ = nestFitness(rankIndex);
this->bestParameter_ = hostNests.col(rankIndex);
}
//funktioniert nicht
//this->updateBestParameter(hostNests.col(rankIndex), 0.0, nestFitness(rankIndex));
}
}
template <typename T>
inline void CuckooSearch<T>::setDiscoveryProbability(
const T prob) noexcept{
discoveryProbability_ = prob;
}
template <typename T>
inline void CuckooSearch<T>::setLevyStepSize(
const T stepSize) noexcept{
levyStepSize_ = stepSize;
}
template <typename T>
inline std::string CuckooSearch<T>::toString() const noexcept {
return "CuckooSearch";
}
}
<commit_msg>Removed redundant inlines<commit_after>namespace mant {
template <typename T>
class CuckooSearch : public PopulationBasedOptimisationAlgorithm<T>{
public:
explicit CuckooSearch(
const std::shared_ptr<OptimisationProblem<T>> optimisationProblem,
const unsigned int populationSize) noexcept;
void setDiscoveryProbability(
const T discoveryProbability) noexcept;
void setLevyStepSize(
const T levyStepSize) noexcept;
std::string toString() const noexcept override;
protected:
T discoveryProbability_;
T levyStepSize_;
void optimiseImplementation() override;
};
//
//Implementation
//
template <typename T>
CuckooSearch<T>::CuckooSearch(
const std::shared_ptr<OptimisationProblem<T>> optimisationProblem,
const unsigned int populationSize) noexcept
: PopulationBasedOptimisationAlgorithm<T>(optimisationProblem, populationSize){
setDiscoveryProbability(0.25);
setLevyStepSize(1.0);
}
template <typename T>
void CuckooSearch<T>::optimiseImplementation(){
arma::Mat<T> hostNests = arma::randu<arma::Mat<T>>(this->numberOfDimensions_, this->populationSize_);
hostNests.each_col() %= this->getUpperBounds() - this->getLowerBounds();
hostNests.each_col() += this->getLowerBounds();
arma::Col<T> nestFitness(this->populationSize_);
for(std::size_t i = 0; i < this->populationSize_; ++i){
nestFitness(i) = this->getObjectiveValue(hostNests.col(i));
++this->numberOfIterations_;
}
unsigned int rankIndex;
nestFitness.min(rankIndex);
this->bestObjectiveValue_ = nestFitness(rankIndex);
this->bestParameter_ = hostNests.col(rankIndex);
while(!this->isFinished() && !this->isTerminated()){
++this->numberOfIterations_;
nestFitness.min(rankIndex);
arma::Col<T> newCuckoo = hostNests.col(rankIndex);
//bei BentCigar gitb das in einer Expression bessere Ergebnisse aus
//bei SphereFunction das aufgeteilte
//Levy flights by Mantegna's algorithm
arma::Col<T> u = arma::randn<arma::Col<T>>(this->numberOfDimensions_) * pow((tgamma(1+(3/2))*sin(M_PI*(3/2)/2)/(tgamma((1+(3/2))/2)*(3/2)*pow(2,(((3/2)-1)/2)))),(1/(3/2)));
arma::Col<T> step = u/pow(abs(arma::randn<arma::Col<T>>(this->numberOfDimensions_)),1/(3/2));
arma::Col<T> stepSize = levyStepSize_ * 0.01 * step % (newCuckoo - hostNests(rankIndex));
newCuckoo += stepSize ;
//in one expression:
//newCuckoo += levyStepSize_ * 0.01 * ((arma::randn<arma::Col<T>>(this->numberOfDimensions_)
// * pow((tgamma(1+(3/2))*sin(M_PI*(3/2)/2)/(tgamma((1+(3/2))/2)*(3/2)*pow(2,(((3/2)-1)/2)))),(1/(3/2))))
// / pow(abs(arma::randn<arma::Col<T>>(this->numberOfDimensions_)),1/(3/2))) % (newCuckoo - hostNests(rankIndex));
const arma::Col<unsigned int>& belowLowerBound = arma::find(newCuckoo < this->getLowerBounds());
const arma::Col<unsigned int>& aboveUpperBound = arma::find(newCuckoo > this->getUpperBounds());
newCuckoo.elem(belowLowerBound) = this->getLowerBounds().elem(belowLowerBound);
newCuckoo.elem(aboveUpperBound) = this->getUpperBounds().elem(aboveUpperBound);
nestFitness.max(rankIndex);
if(this->getObjectiveValue(newCuckoo) < nestFitness(rankIndex)){
hostNests.col(rankIndex) = newCuckoo;
nestFitness(rankIndex) = this->getObjectiveValue(hostNests.col(rankIndex));
}
for(std::size_t i = 0; i < discoveryProbability_ * this->populationSize_; ++i){
++this->numberOfIterations_;
nestFitness.max(rankIndex);
hostNests.col(rankIndex) = this->getRandomParameter();
nestFitness(rankIndex) = this->getObjectiveValue(hostNests.col(rankIndex));
if(this->isFinished() || this->isTerminated())break;
}
nestFitness.min(rankIndex);
if (this->getObjectiveValue(hostNests.col(rankIndex)) < this->bestObjectiveValue_) {
this->bestObjectiveValue_ = nestFitness(rankIndex);
this->bestParameter_ = hostNests.col(rankIndex);
}
//funktioniert nicht
//this->updateBestParameter(hostNests.col(rankIndex), 0.0, nestFitness(rankIndex));
}
}
template <typename T>
void CuckooSearch<T>::setDiscoveryProbability(
const T discoveryProbability) noexcept{
discoveryProbability_ = discoveryProbability;
}
template <typename T>
void CuckooSearch<T>::setLevyStepSize(
const T levyStepSize) noexcept{
levyStepSize_ = levyStepSize;
}
template <typename T>
std::string CuckooSearch<T>::toString() const noexcept {
return "CuckooSearch";
}
}
<|endoftext|> |
<commit_before>#include "regex.h"
#include "unicode.h"
namespace regex {
Regex compile(const unicode& pattern) {
return Regex(pattern.encode());
}
REMatch Regex::match(const unicode &str, uint32_t start_pos) const {
REMatch result;
std::locale old;
std::locale::global(std::locale("en_US.UTF-8"));
std::string encoded = str.encode();
boost::match_results<std::string::const_iterator> matches;
std::string::const_iterator start = encoded.begin();
std::string::const_iterator finish = encoded.end();
boost::match_flag_type flags = boost::match_default;
flags |= boost::match_continuous;
boost::regex_search(start + start_pos, finish, matches, _impl, flags);
for(auto match: matches) {
unicode match_string(match.first, match.second);
std::cout << match_string << std::endl;
std::string::const_iterator beg = match.first;
std::string::const_iterator end = match.second;
result.groups_.push_back(REMatch::Group({
match_string,
std::distance(start, beg),
std::distance(start, end)
}));
}
std::locale::global(old);
return result;
}
int REMatch::start(int group) {
return groups_.at(group).start;
}
int REMatch::end(int group) {
return groups_.at(group).end;
}
std::pair<int, int> REMatch::span(int group) {
return std::make_pair(start(group), end(group));
}
std::vector<unicode> REMatch::groups() const {
std::vector<unicode> ret;
for(auto g: groups_) {
ret.push_back(g.str);
}
return ret;
}
unicode REMatch::group(uint32_t i) const {
return groups_.at(i).str;
}
Match match(const Regex& re, const unicode& string) {
Match result;
std::locale old;
std::locale::global(std::locale("en_US.UTF-8"));
std::string encoded = string.encode();
boost::match_results<std::string::const_iterator> matches;
result.matched = boost::regex_match(encoded, matches, re._impl);
for(auto match: matches) {
unicode match_string(match.first, match.second);
std::cout << "SM: " << match_string << std::endl;
result.groups.push_back(match_string);
result.matched = true;
}
std::locale::global(old);
return result;
}
std::vector<Match> search(const Regex& re, const unicode& string) {
std::vector<Match> results;
std::locale old;
std::locale::global(std::locale("en_US.UTF-8"));
auto to_search = string.encode();
std::string::const_iterator start, end;
start = to_search.begin();
end = to_search.end();
boost::match_results<std::string::const_iterator> matches;
while(boost::regex_search(start, end, matches, re._impl)) {
Match new_match;
for(auto match: matches) {
std::string match_string(match.first, match.second);
unicode group(match_string);
new_match.groups.push_back(group);
new_match.matched = true;
}
start = matches[0].second;
results.push_back(new_match);
}
std::locale::global(old);
return results;
}
unicode escape(const unicode& string) {
std::vector<unicode> to_replace = { "\\", "{", "}", "^", "$", "|", "(", ")", "[", "]", "*", "+", "?", "." };
//Could be faster!
unicode result = string;
for(auto u: to_replace) {
result = result.replace(u, _u("\\") + u);
}
return result;
}
}
<commit_msg>Remove cout statement that was for debugging<commit_after>#include "regex.h"
#include "unicode.h"
namespace regex {
Regex compile(const unicode& pattern) {
return Regex(pattern.encode());
}
REMatch Regex::match(const unicode &str, uint32_t start_pos) const {
REMatch result;
std::locale old;
std::locale::global(std::locale("en_US.UTF-8"));
std::string encoded = str.encode();
boost::match_results<std::string::const_iterator> matches;
std::string::const_iterator start = encoded.begin();
std::string::const_iterator finish = encoded.end();
boost::match_flag_type flags = boost::match_default;
flags |= boost::match_continuous;
boost::regex_search(start + start_pos, finish, matches, _impl, flags);
for(auto match: matches) {
unicode match_string(match.first, match.second);
std::string::const_iterator beg = match.first;
std::string::const_iterator end = match.second;
result.groups_.push_back(REMatch::Group({
match_string,
std::distance(start, beg),
std::distance(start, end)
}));
}
std::locale::global(old);
return result;
}
int REMatch::start(int group) {
return groups_.at(group).start;
}
int REMatch::end(int group) {
return groups_.at(group).end;
}
std::pair<int, int> REMatch::span(int group) {
return std::make_pair(start(group), end(group));
}
std::vector<unicode> REMatch::groups() const {
std::vector<unicode> ret;
for(auto g: groups_) {
ret.push_back(g.str);
}
return ret;
}
unicode REMatch::group(uint32_t i) const {
return groups_.at(i).str;
}
Match match(const Regex& re, const unicode& string) {
Match result;
std::locale old;
std::locale::global(std::locale("en_US.UTF-8"));
std::string encoded = string.encode();
boost::match_results<std::string::const_iterator> matches;
result.matched = boost::regex_match(encoded, matches, re._impl);
for(auto match: matches) {
unicode match_string(match.first, match.second);
std::cout << "SM: " << match_string << std::endl;
result.groups.push_back(match_string);
result.matched = true;
}
std::locale::global(old);
return result;
}
std::vector<Match> search(const Regex& re, const unicode& string) {
std::vector<Match> results;
std::locale old;
std::locale::global(std::locale("en_US.UTF-8"));
auto to_search = string.encode();
std::string::const_iterator start, end;
start = to_search.begin();
end = to_search.end();
boost::match_results<std::string::const_iterator> matches;
while(boost::regex_search(start, end, matches, re._impl)) {
Match new_match;
for(auto match: matches) {
std::string match_string(match.first, match.second);
unicode group(match_string);
new_match.groups.push_back(group);
new_match.matched = true;
}
start = matches[0].second;
results.push_back(new_match);
}
std::locale::global(old);
return results;
}
unicode escape(const unicode& string) {
std::vector<unicode> to_replace = { "\\", "{", "}", "^", "$", "|", "(", ")", "[", "]", "*", "+", "?", "." };
//Could be faster!
unicode result = string;
for(auto u: to_replace) {
result = result.replace(u, _u("\\") + u);
}
return result;
}
}
<|endoftext|> |
<commit_before>// ACPICA OSL. This provides the glue between ACPICA and the xv6
// kernel.
extern "C" {
#include "acpi.h"
}
#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "cpu.hh"
#include "semaphore.h"
#include "spinlock.h"
#include "pci.hh"
#include <new>
// Environment
ACPI_STATUS
AcpiOsInitialize(void)
{
return AE_OK;
}
ACPI_STATUS
AcpiOsTerminate(void)
{
return AE_OK;
}
ACPI_PHYSICAL_ADDRESS
AcpiOsGetRootPointer(void)
{
ACPI_SIZE ret;
AcpiFindRootPointer(&ret);
return ret;
}
ACPI_STATUS
AcpiOsPredefinedOverride(const ACPI_PREDEFINED_NAMES *init_val,
ACPI_STRING *new_val)
{
*new_val = nullptr;
return AE_OK;
}
ACPI_STATUS
AcpiOsTableOverride(ACPI_TABLE_HEADER *existing_table,
ACPI_TABLE_HEADER **new_table)
{
*new_table = nullptr;
return AE_OK;
}
ACPI_STATUS
AcpiOsPhysicalTableOverride (ACPI_TABLE_HEADER *existing_table,
ACPI_PHYSICAL_ADDRESS *new_address,
uint32_t *new_table_length)
{
*new_address = 0;
return AE_OK;
}
// Memory management
void *
AcpiOsMapMemory(ACPI_PHYSICAL_ADDRESS where, ACPI_SIZE length)
{
return p2v(where);
}
void
AcpiOsUnmapMemory (void *logical_address, ACPI_SIZE size)
{
}
// ACPI_STATUS
// AcpiOsGetPhysicalAddress(void *logical_address,
// ACPI_PHYSICAL_ADDRESS *physical_address)
// {
// panic("AcpiOsGetPhysicalAddress not implemented");
// }
enum {
// This needs to be large enough to keep the allocated data type
// aligned to ABI requirements
ALLOC_HDR = 8,
// The maximum size that can be kmalloc'd.
ALLOC_LIMIT = PGSIZE,
};
static char alloc_bigbuf[16*1024];
static char *alloc_pos;
static unsigned alloc_used;
void *
AcpiOsAllocate(ACPI_SIZE size)
{
uint8_t *base;
ACPI_SIZE alloc_size = size + ALLOC_HDR;
if (alloc_size < ALLOC_LIMIT) {
base = (uint8_t*)kmalloc(alloc_size, "(acpi)");
if (!base)
return nullptr;
} else {
// kmalloc can't handle this, but large allocations are
// short-lived in practice, so we use a simple scratch allocator.
if (alloc_used == 0)
alloc_pos = alloc_bigbuf;
base = (uint8_t*)alloc_pos;
alloc_pos += alloc_size;
alloc_used += alloc_size;
if (alloc_pos > alloc_bigbuf + sizeof(alloc_bigbuf))
panic("AcpiOsAllocate: overflowed alloc_bigbuf");
}
static_assert(sizeof(ACPI_SIZE) <= ALLOC_HDR, "ALLOC_HDR too small");
*(ACPI_SIZE*)base = alloc_size;
return base + ALLOC_HDR;
}
void
AcpiOsFree(void *ptr)
{
uint8_t *base = (uint8_t*)ptr - ALLOC_HDR;
ACPI_SIZE alloc_size = *(ACPI_SIZE*)base;
if (ptr >= alloc_bigbuf && ptr < alloc_bigbuf + sizeof(alloc_bigbuf))
alloc_used -= alloc_size;
else
kmfree(base, alloc_size);
}
// Multithreading
ACPI_THREAD_ID
AcpiOsGetThreadId(void)
{
proc *p = myproc();
if (p)
return (ACPI_THREAD_ID)p;
// Has to be non-zero
return (ACPI_THREAD_ID)1;
}
ACPI_STATUS
AcpiOsExecute(ACPI_EXECUTE_TYPE type, ACPI_OSD_EXEC_CALLBACK function,
void *context)
{
// XXX
panic("AcpiOsExecute not implemented");
}
void
AcpiOsSleep(uint64_t milliseconds)
{
struct spinlock lock("acpi_sleep_lock");
struct condvar cv("acpi_sleep_cv");
uint64_t target = nsectime() + milliseconds * 1000000;
scoped_acquire l(&lock);
while (nsectime() < target)
cv.sleep_to(&lock, target);
}
void
AcpiOsStall(uint32_t microseconds)
{
uint64_t target = nsectime() + microseconds * 1000;
while (nsectime() < target)
;
}
void
AcpiOsWaitEventsComplete(void)
{
// XXX
panic("AcpiOsWaitEventsComplete not implemented");
}
// Mutual exclusion
ACPI_STATUS
AcpiOsCreateSemaphore(uint32_t max_units, uint32_t initial_units,
struct semaphore **out_handle)
{
if (!out_handle)
return AE_BAD_PARAMETER;
*out_handle = new (std::nothrow) semaphore("acpi", initial_units);
if (!*out_handle)
return AE_NO_MEMORY;
return AE_OK;
}
ACPI_STATUS
AcpiOsDeleteSemaphore(struct semaphore *handle)
{
if (!handle)
return AE_BAD_PARAMETER;
delete handle;
return AE_OK;
}
ACPI_STATUS
AcpiOsWaitSemaphore(struct semaphore* handle, uint32_t units, uint16_t timeout)
{
if (!handle)
return AE_BAD_PARAMETER;
if (timeout == 0xFFFF)
handle->acquire(units);
else if (!handle->try_acquire(units, (uint64_t)timeout * 1000000))
return AE_TIME;
return AE_OK;
}
ACPI_STATUS
AcpiOsSignalSemaphore (struct semaphore* handle, uint32_t units)
{
if (!handle)
return AE_BAD_PARAMETER;
handle->release(units);
return AE_OK;
}
ACPI_STATUS
AcpiOsCreateLock(struct spinlock **out_handle)
{
if (!out_handle)
return AE_BAD_PARAMETER;
*out_handle = new (std::nothrow) spinlock("acpi");
if (!*out_handle)
return AE_NO_MEMORY;
return AE_OK;
}
void
AcpiOsDeleteLock(struct spinlock *handle)
{
delete handle;
}
ACPI_CPU_FLAGS
AcpiOsAcquireLock(struct spinlock *handle)
{
handle->acquire();
return 0;
}
void
AcpiOsReleaseLock(struct spinlock *handle, ACPI_CPU_FLAGS flags)
{
handle->release();
}
// Interrupt handling
ACPI_STATUS
AcpiOsInstallInterruptHandler(uint32_t interrupt_number,
ACPI_OSD_HANDLER service_routine,
void *context)
{
// XXX
cprintf("AcpiOsInstallInterruptHandler not implemented (%u, %p, %p)\n",
interrupt_number, service_routine, context);
return AE_OK;
}
ACPI_STATUS
AcpiOsRemoveInterruptHandler(uint32_t interrupt_number,
ACPI_OSD_HANDLER service_routine)
{
// XXX
panic("AcpiOsRemoveInterruptHandler not impelemtned");
}
// Memory access
ACPI_STATUS
AcpiOsReadMemory(ACPI_PHYSICAL_ADDRESS address, uint64_t *value, uint32_t width)
{
void *p = p2v(address);
switch (width) {
case 8:
*value = *(uint8_t*)p;
return AE_OK;
case 16:
*value = *(uint16_t*)p;
return AE_OK;
case 32:
*value = *(uint32_t*)p;
return AE_OK;
case 64:
*value = *(uint64_t*)p;
return AE_OK;
}
return AE_BAD_PARAMETER;
}
ACPI_STATUS
AcpiOsWriteMemory(ACPI_PHYSICAL_ADDRESS address, uint64_t value, uint32_t width)
{
void *p = p2v(address);
switch (width) {
case 8:
*(uint8_t*)p = value;
return AE_OK;
case 16:
*(uint16_t*)p = value;
return AE_OK;
case 32:
*(uint32_t*)p = value;
return AE_OK;
case 64:
*(uint64_t*)p = value;
return AE_OK;
}
return AE_BAD_PARAMETER;
}
// Port input/output
ACPI_STATUS
AcpiOsReadPort(ACPI_IO_ADDRESS address, uint32_t *value, uint32_t width)
{
switch (width) {
case 8:
*value = inb(address);
return AE_OK;
case 16:
*value = inw(address);
return AE_OK;
case 32:
*value = inl(address);
return AE_OK;
}
return AE_BAD_PARAMETER;
}
ACPI_STATUS
AcpiOsWritePort(ACPI_IO_ADDRESS address, uint32_t value, uint32_t width)
{
switch (width) {
case 8:
outb(address, value);
return AE_OK;
case 16:
outw(address, value);
return AE_OK;
case 32:
outl(address, value);
return AE_OK;
}
return AE_BAD_PARAMETER;
}
// PCI configuration space
ACPI_STATUS
AcpiOsReadPciConfiguration(ACPI_PCI_ID *pci_id, uint32_t reg, uint64_t *value,
uint32_t width)
{
*value = pci_conf_read(pci_id->Segment, pci_id->Bus, pci_id->Device,
pci_id->Function, reg, width);
return AE_OK;
}
ACPI_STATUS
AcpiOsWritePciConfiguration(ACPI_PCI_ID *pci_id, uint32_t reg, uint64_t value,
uint32_t width)
{
pci_conf_write(pci_id->Segment, pci_id->Bus, pci_id->Device, pci_id->Function,
reg, value, width);
return AE_OK;
}
// Formatted output
void ACPI_INTERNAL_VAR_XFACE
AcpiOsPrintf(const char *format, ...)
{
va_list ap;
va_start(ap, format);
vcprintf(format, ap);
va_end(ap);
}
void
AcpiOsVprintf(const char *format, va_list args)
{
vcprintf(format, args);
}
// Miscellaneous
uint64_t
AcpiOsGetTimer(void)
{
// XXX nsectime is really inaccurate
return nsectime() / 100;
}
ACPI_STATUS
AcpiOsSignal(uint32_t function, void *info)
{
if (function == ACPI_SIGNAL_FATAL) {
struct acpi_signal_fatal_info *fi = (struct acpi_signal_fatal_info *)info;
panic("acpi: fatal opcode encountered type %u code %u arg %u",
fi->Type, fi->Code, fi->Argument);
}
return AE_OK;
}
<commit_msg>acpiosl: Remove large allocator hack<commit_after>// ACPICA OSL. This provides the glue between ACPICA and the xv6
// kernel.
extern "C" {
#include "acpi.h"
}
#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "cpu.hh"
#include "semaphore.h"
#include "spinlock.h"
#include "pci.hh"
#include <new>
// Environment
ACPI_STATUS
AcpiOsInitialize(void)
{
return AE_OK;
}
ACPI_STATUS
AcpiOsTerminate(void)
{
return AE_OK;
}
ACPI_PHYSICAL_ADDRESS
AcpiOsGetRootPointer(void)
{
ACPI_SIZE ret;
AcpiFindRootPointer(&ret);
return ret;
}
ACPI_STATUS
AcpiOsPredefinedOverride(const ACPI_PREDEFINED_NAMES *init_val,
ACPI_STRING *new_val)
{
*new_val = nullptr;
return AE_OK;
}
ACPI_STATUS
AcpiOsTableOverride(ACPI_TABLE_HEADER *existing_table,
ACPI_TABLE_HEADER **new_table)
{
*new_table = nullptr;
return AE_OK;
}
ACPI_STATUS
AcpiOsPhysicalTableOverride (ACPI_TABLE_HEADER *existing_table,
ACPI_PHYSICAL_ADDRESS *new_address,
uint32_t *new_table_length)
{
*new_address = 0;
return AE_OK;
}
// Memory management
void *
AcpiOsMapMemory(ACPI_PHYSICAL_ADDRESS where, ACPI_SIZE length)
{
return p2v(where);
}
void
AcpiOsUnmapMemory (void *logical_address, ACPI_SIZE size)
{
}
// ACPI_STATUS
// AcpiOsGetPhysicalAddress(void *logical_address,
// ACPI_PHYSICAL_ADDRESS *physical_address)
// {
// panic("AcpiOsGetPhysicalAddress not implemented");
// }
enum {
// This needs to be large enough to keep the allocated data type
// aligned to ABI requirements
ALLOC_HDR = 8,
};
void *
AcpiOsAllocate(ACPI_SIZE size)
{
uint8_t *base;
ACPI_SIZE alloc_size = size + ALLOC_HDR;
base = (uint8_t*)kmalloc(alloc_size, "(acpi)");
if (!base)
return nullptr;
static_assert(sizeof(ACPI_SIZE) <= ALLOC_HDR, "ALLOC_HDR too small");
*(ACPI_SIZE*)base = alloc_size;
return base + ALLOC_HDR;
}
void
AcpiOsFree(void *ptr)
{
uint8_t *base = (uint8_t*)ptr - ALLOC_HDR;
ACPI_SIZE alloc_size = *(ACPI_SIZE*)base;
kmfree(base, alloc_size);
}
// Multithreading
ACPI_THREAD_ID
AcpiOsGetThreadId(void)
{
proc *p = myproc();
if (p)
return (ACPI_THREAD_ID)p;
// Has to be non-zero
return (ACPI_THREAD_ID)1;
}
ACPI_STATUS
AcpiOsExecute(ACPI_EXECUTE_TYPE type, ACPI_OSD_EXEC_CALLBACK function,
void *context)
{
// XXX
panic("AcpiOsExecute not implemented");
}
void
AcpiOsSleep(uint64_t milliseconds)
{
struct spinlock lock("acpi_sleep_lock");
struct condvar cv("acpi_sleep_cv");
uint64_t target = nsectime() + milliseconds * 1000000;
scoped_acquire l(&lock);
while (nsectime() < target)
cv.sleep_to(&lock, target);
}
void
AcpiOsStall(uint32_t microseconds)
{
uint64_t target = nsectime() + microseconds * 1000;
while (nsectime() < target)
;
}
void
AcpiOsWaitEventsComplete(void)
{
// XXX
panic("AcpiOsWaitEventsComplete not implemented");
}
// Mutual exclusion
ACPI_STATUS
AcpiOsCreateSemaphore(uint32_t max_units, uint32_t initial_units,
struct semaphore **out_handle)
{
if (!out_handle)
return AE_BAD_PARAMETER;
*out_handle = new (std::nothrow) semaphore("acpi", initial_units);
if (!*out_handle)
return AE_NO_MEMORY;
return AE_OK;
}
ACPI_STATUS
AcpiOsDeleteSemaphore(struct semaphore *handle)
{
if (!handle)
return AE_BAD_PARAMETER;
delete handle;
return AE_OK;
}
ACPI_STATUS
AcpiOsWaitSemaphore(struct semaphore* handle, uint32_t units, uint16_t timeout)
{
if (!handle)
return AE_BAD_PARAMETER;
if (timeout == 0xFFFF)
handle->acquire(units);
else if (!handle->try_acquire(units, (uint64_t)timeout * 1000000))
return AE_TIME;
return AE_OK;
}
ACPI_STATUS
AcpiOsSignalSemaphore (struct semaphore* handle, uint32_t units)
{
if (!handle)
return AE_BAD_PARAMETER;
handle->release(units);
return AE_OK;
}
ACPI_STATUS
AcpiOsCreateLock(struct spinlock **out_handle)
{
if (!out_handle)
return AE_BAD_PARAMETER;
*out_handle = new (std::nothrow) spinlock("acpi");
if (!*out_handle)
return AE_NO_MEMORY;
return AE_OK;
}
void
AcpiOsDeleteLock(struct spinlock *handle)
{
delete handle;
}
ACPI_CPU_FLAGS
AcpiOsAcquireLock(struct spinlock *handle)
{
handle->acquire();
return 0;
}
void
AcpiOsReleaseLock(struct spinlock *handle, ACPI_CPU_FLAGS flags)
{
handle->release();
}
// Interrupt handling
ACPI_STATUS
AcpiOsInstallInterruptHandler(uint32_t interrupt_number,
ACPI_OSD_HANDLER service_routine,
void *context)
{
// XXX
cprintf("AcpiOsInstallInterruptHandler not implemented (%u, %p, %p)\n",
interrupt_number, service_routine, context);
return AE_OK;
}
ACPI_STATUS
AcpiOsRemoveInterruptHandler(uint32_t interrupt_number,
ACPI_OSD_HANDLER service_routine)
{
// XXX
panic("AcpiOsRemoveInterruptHandler not impelemtned");
}
// Memory access
ACPI_STATUS
AcpiOsReadMemory(ACPI_PHYSICAL_ADDRESS address, uint64_t *value, uint32_t width)
{
void *p = p2v(address);
switch (width) {
case 8:
*value = *(uint8_t*)p;
return AE_OK;
case 16:
*value = *(uint16_t*)p;
return AE_OK;
case 32:
*value = *(uint32_t*)p;
return AE_OK;
case 64:
*value = *(uint64_t*)p;
return AE_OK;
}
return AE_BAD_PARAMETER;
}
ACPI_STATUS
AcpiOsWriteMemory(ACPI_PHYSICAL_ADDRESS address, uint64_t value, uint32_t width)
{
void *p = p2v(address);
switch (width) {
case 8:
*(uint8_t*)p = value;
return AE_OK;
case 16:
*(uint16_t*)p = value;
return AE_OK;
case 32:
*(uint32_t*)p = value;
return AE_OK;
case 64:
*(uint64_t*)p = value;
return AE_OK;
}
return AE_BAD_PARAMETER;
}
// Port input/output
ACPI_STATUS
AcpiOsReadPort(ACPI_IO_ADDRESS address, uint32_t *value, uint32_t width)
{
switch (width) {
case 8:
*value = inb(address);
return AE_OK;
case 16:
*value = inw(address);
return AE_OK;
case 32:
*value = inl(address);
return AE_OK;
}
return AE_BAD_PARAMETER;
}
ACPI_STATUS
AcpiOsWritePort(ACPI_IO_ADDRESS address, uint32_t value, uint32_t width)
{
switch (width) {
case 8:
outb(address, value);
return AE_OK;
case 16:
outw(address, value);
return AE_OK;
case 32:
outl(address, value);
return AE_OK;
}
return AE_BAD_PARAMETER;
}
// PCI configuration space
ACPI_STATUS
AcpiOsReadPciConfiguration(ACPI_PCI_ID *pci_id, uint32_t reg, uint64_t *value,
uint32_t width)
{
*value = pci_conf_read(pci_id->Segment, pci_id->Bus, pci_id->Device,
pci_id->Function, reg, width);
return AE_OK;
}
ACPI_STATUS
AcpiOsWritePciConfiguration(ACPI_PCI_ID *pci_id, uint32_t reg, uint64_t value,
uint32_t width)
{
pci_conf_write(pci_id->Segment, pci_id->Bus, pci_id->Device, pci_id->Function,
reg, value, width);
return AE_OK;
}
// Formatted output
void ACPI_INTERNAL_VAR_XFACE
AcpiOsPrintf(const char *format, ...)
{
va_list ap;
va_start(ap, format);
vcprintf(format, ap);
va_end(ap);
}
void
AcpiOsVprintf(const char *format, va_list args)
{
vcprintf(format, args);
}
// Miscellaneous
uint64_t
AcpiOsGetTimer(void)
{
// XXX nsectime is really inaccurate
return nsectime() / 100;
}
ACPI_STATUS
AcpiOsSignal(uint32_t function, void *info)
{
if (function == ACPI_SIGNAL_FATAL) {
struct acpi_signal_fatal_info *fi = (struct acpi_signal_fatal_info *)info;
panic("acpi: fatal opcode encountered type %u code %u arg %u",
fi->Type, fi->Code, fi->Argument);
}
return AE_OK;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2022-present ScyllaDB
*/
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#pragma once
#include "mutation_fragment_v2.hh"
template <typename EndConsumer>
requires requires(EndConsumer& c, mutation_fragment_v2 mf) {
{ c(std::move(mf)) };
}
class upgrading_consumer {
const schema& _schema;
reader_permit _permit;
EndConsumer _end_consumer;
range_tombstone_change_generator _rt_gen;
tombstone _current_rt;
std::optional<position_range> _pr;
template <typename Frag>
void do_consume(Frag&& frag) {
_end_consumer(mutation_fragment_v2(_schema, _permit, std::move(frag)));
}
public:
upgrading_consumer(const schema& schema, reader_permit permit, EndConsumer&& end_consumer)
: _schema(schema), _permit(std::move(permit)), _end_consumer(std::move(end_consumer)), _rt_gen(_schema)
{}
void set_position_range(position_range pr) {
_rt_gen.trim(pr.start());
_current_rt = {};
_pr = std::move(pr);
}
bool discardable() const {
return _rt_gen.discardable() && !_current_rt;
}
void flush_tombstones(position_in_partition_view pos) {
_rt_gen.flush(pos, [&] (range_tombstone_change rt) {
_current_rt = rt.tombstone();
do_consume(std::move(rt));
});
}
void consume(partition_start mf) {
_rt_gen.reset();
_current_rt = {};
_pr = {};
do_consume(std::move(mf));
}
void consume(static_row mf) {
do_consume(std::move(mf));
}
void consume(clustering_row mf) {
flush_tombstones(mf.position());
do_consume(std::move(mf));
}
void consume(range_tombstone rt) {
if (_pr && !rt.trim_front(_schema, _pr->start())) {
return;
}
flush_tombstones(rt.position());
_rt_gen.consume(std::move(rt));
}
void consume(partition_end mf) {
flush_tombstones(position_in_partition::after_all_clustered_rows());
if (_current_rt) {
assert(!_pr);
do_consume(range_tombstone_change(position_in_partition::after_all_clustered_rows(), {}));
}
do_consume(std::move(mf));
}
void consume(mutation_fragment&& mf) {
std::move(mf).consume(*this);
}
void on_end_of_stream() {
if (_pr) {
flush_tombstones(_pr->end());
if (_current_rt) {
do_consume(range_tombstone_change(_pr->end(), {}));
}
}
}
};
<commit_msg>readers/upgrading_consumer: workaround for aarch64 miscompilation<commit_after>/*
* Copyright (C) 2022-present ScyllaDB
*/
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#pragma once
#include "mutation_fragment_v2.hh"
template <typename EndConsumer>
requires requires(EndConsumer& c, mutation_fragment_v2 mf) {
{ c(std::move(mf)) };
}
class upgrading_consumer {
const schema& _schema;
reader_permit _permit;
EndConsumer _end_consumer;
range_tombstone_change_generator _rt_gen;
tombstone _current_rt;
std::optional<position_range> _pr;
template <typename Frag>
void do_consume(Frag&& frag) {
_end_consumer(mutation_fragment_v2(_schema, _permit, std::move(frag)));
}
public:
upgrading_consumer(const schema& schema, reader_permit permit, EndConsumer&& end_consumer)
: _schema(schema), _permit(std::move(permit)), _end_consumer(std::move(end_consumer)), _rt_gen(_schema)
{}
void set_position_range(position_range pr) {
_rt_gen.trim(pr.start());
_current_rt = {};
_pr = std::move(pr);
}
bool discardable() const {
return _rt_gen.discardable() && !_current_rt;
}
void flush_tombstones(position_in_partition_view pos) {
_rt_gen.flush(pos, [&] (range_tombstone_change rt) {
_current_rt = rt.tombstone();
do_consume(std::move(rt));
});
}
void consume(partition_start mf) {
_rt_gen.reset();
_current_rt = {};
_pr = {};
do_consume(std::move(mf));
}
void consume(static_row mf) {
do_consume(std::move(mf));
}
void consume(clustering_row mf) {
// FIXME: Avoid a miscompilation on aarch64, where `mf` is moved before
// `flush_tombstones()` can finish, causing the latter to observe a view
// pointing at a moved-from position-in-partition.
position_in_partition pos = position_in_partition(mf.position());
flush_tombstones(pos);
do_consume(std::move(mf));
}
void consume(range_tombstone rt) {
if (_pr && !rt.trim_front(_schema, _pr->start())) {
return;
}
flush_tombstones(rt.position());
_rt_gen.consume(std::move(rt));
}
void consume(partition_end mf) {
flush_tombstones(position_in_partition::after_all_clustered_rows());
if (_current_rt) {
assert(!_pr);
do_consume(range_tombstone_change(position_in_partition::after_all_clustered_rows(), {}));
}
do_consume(std::move(mf));
}
void consume(mutation_fragment&& mf) {
std::move(mf).consume(*this);
}
void on_end_of_stream() {
if (_pr) {
flush_tombstones(_pr->end());
if (_current_rt) {
do_consume(range_tombstone_change(_pr->end(), {}));
}
}
}
};
<|endoftext|> |
<commit_before>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2018 Baldur Karlsson
*
* 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 <QApplication>
#include <QFile>
#include <QStandardPaths>
#include "Code/QRDUtils.h"
#include "QRDInterface.h"
static const QString glsl_stage4[ENUM_ARRAY_SIZE(ShaderStage)] = {
lit("vert"), lit("tesc"), lit("tese"), lit("geom"), lit("frag"), lit("comp"),
};
template <>
std::string DoStringise(const KnownShaderTool &el)
{
BEGIN_ENUM_STRINGISE(KnownShaderTool);
{
STRINGISE_ENUM_CLASS_NAMED(Unknown, "Custom Tool");
STRINGISE_ENUM_CLASS_NAMED(SPIRV_Cross, "SPIRV-Cross");
STRINGISE_ENUM_CLASS_NAMED(spirv_dis, "spirv-dis");
STRINGISE_ENUM_CLASS_NAMED(glslangValidatorGLSL, "glslang (GLSL)");
STRINGISE_ENUM_CLASS_NAMED(glslangValidatorHLSL, "glslang (HLSL)");
STRINGISE_ENUM_CLASS_NAMED(spirv_as, "spirv-as");
}
END_ENUM_STRINGISE();
}
static QString tmpPath(const QString &filename)
{
return QDir(QDir::tempPath()).absoluteFilePath(filename);
}
static ShaderToolOutput RunTool(const ShaderProcessingTool &tool, QWidget *window,
QString input_file, QString output_file, QStringList &argList)
{
bool writesToFile = true;
bool readStdin = false;
int idx = argList.indexOf(lit("{stdin}"));
if(idx >= 0)
{
argList.removeAt(idx);
readStdin = true;
}
if(output_file.isEmpty())
{
output_file = tmpPath(lit("shader_output"));
writesToFile = false;
}
// ensure we don't have any leftover output files.
QFile::remove(output_file);
QString stdout_file = QDir(QDir::tempPath()).absoluteFilePath(lit("shader_stdout"));
ShaderToolOutput ret;
if(tool.executable.isEmpty())
{
ret.log = QApplication::translate("ShaderProcessingTool",
"ERROR: No Executable specified in tool '%1'")
.arg(tool.name);
return ret;
}
QString path = tool.executable;
if(!QDir::isAbsolutePath(path))
{
path = QStandardPaths::findExecutable(path);
if(path.isEmpty())
{
ret.log = QApplication::translate("ShaderProcessingTool",
"ERROR: Couldn't find executable '%1' in path")
.arg(tool.executable);
return ret;
}
}
QByteArray stdout_data;
QProcess process;
LambdaThread *thread = new LambdaThread([&]() {
if(readStdin)
process.setStandardInputFile(input_file);
if(!writesToFile)
process.setStandardOutputFile(output_file);
else
process.setStandardOutputFile(stdout_file);
// for now merge stdout/stderr together. Maybe we should separate these and somehow annotate
// them? Merging is difficult without messing up order, and some tools output non-errors to
// stderr
process.setStandardErrorFile(stdout_file);
process.start(tool.executable, argList);
process.waitForFinished();
{
QFile outputHandle(output_file);
if(outputHandle.open(QFile::ReadOnly))
{
ret.result = outputHandle.readAll();
outputHandle.close();
}
}
{
QFile stdoutHandle(stdout_file);
if(stdoutHandle.open(QFile::ReadOnly))
{
stdout_data = stdoutHandle.readAll();
stdoutHandle.close();
}
}
// The input files typically aren't large and we don't generate unique names so they won't be
// overwritten.
// Leaving them alone means the user can try to recreate the tool invocation themselves.
// QFile::remove(input_file);
QFile::remove(output_file);
QFile::remove(stdout_file);
});
thread->start();
ShowProgressDialog(window, QApplication::translate("ShaderProcessingTool",
"Please wait - running external tool"),
[thread]() { return !thread->isRunning(); });
thread->deleteLater();
QString processStatus;
if(process.exitStatus() == QProcess::CrashExit)
{
processStatus = QApplication::translate("ShaderProcessingTool", "Process crashed with code %1.")
.arg(process.exitCode());
}
else
{
processStatus = QApplication::translate("ShaderProcessingTool", "Process exited with code %1.")
.arg(process.exitCode());
}
ret.log = QApplication::translate("ShaderProcessingTool",
"Running \"%1\" %2\n"
"%3\n"
"%4\n"
"Output file is %5 bytes")
.arg(path)
.arg(argList.join(QLatin1Char(' ')))
.arg(QString::fromUtf8(stdout_data))
.arg(processStatus)
.arg(ret.result.count());
return ret;
}
ShaderToolOutput ShaderProcessingTool::DisassembleShader(QWidget *window,
const ShaderReflection *shaderDetails,
rdcstr arguments) const
{
QStringList argList = ParseArgsList(arguments.isEmpty() ? DefaultArguments() : arguments);
QString input_file, output_file;
input_file = tmpPath(lit("shader_input"));
// replace arguments after expansion to avoid problems with quoting paths etc
for(QString &arg : argList)
{
if(arg == lit("{input_file}"))
arg = input_file;
if(arg == lit("{output_file}"))
arg = output_file = tmpPath(lit("shader_output"));
if(arg == lit("{glsl_stage4}"))
arg = glsl_stage4[int(shaderDetails->stage)];
}
QFile binHandle(input_file);
if(binHandle.open(QFile::WriteOnly | QIODevice::Truncate))
{
binHandle.write(
QByteArray((const char *)shaderDetails->rawBytes.data(), shaderDetails->rawBytes.count()));
binHandle.close();
}
else
{
ShaderToolOutput ret;
ret.log = QApplication::translate("ShaderProcessingTool",
"ERROR: Couldn't write input to temporary file '%1'")
.arg(input_file);
return ret;
}
return RunTool(*this, window, input_file, output_file, argList);
}
ShaderToolOutput ShaderProcessingTool::CompileShader(QWidget *window, rdcstr source,
rdcstr entryPoint, ShaderStage stage,
rdcstr arguments) const
{
QStringList argList = ParseArgsList(arguments.isEmpty() ? DefaultArguments() : arguments);
QString input_file, output_file;
input_file = tmpPath(lit("shader_input"));
// replace arguments after expansion to avoid problems with quoting paths etc
for(QString &arg : argList)
{
if(arg == lit("{input_file}"))
arg = input_file;
if(arg == lit("{output_file}"))
arg = output_file = tmpPath(lit("shader_output"));
if(arg == lit("{entry_point}"))
arg = entryPoint;
if(arg == lit("{glsl_stage4}"))
arg = glsl_stage4[int(stage)];
}
QFile binHandle(input_file);
if(binHandle.open(QFile::WriteOnly | QIODevice::Truncate))
{
binHandle.write(QByteArray((const char *)source.c_str(), source.count()));
binHandle.close();
}
else
{
ShaderToolOutput ret;
ret.log = QApplication::translate("ShaderProcessingTool",
"ERROR: Couldn't write input to temporary file '%1'")
.arg(input_file);
return ret;
}
return RunTool(*this, window, input_file, output_file, argList);
}
<commit_msg>Add hlsl_stage2 substitution to shader processing tool<commit_after>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2018 Baldur Karlsson
*
* 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 <QApplication>
#include <QFile>
#include <QStandardPaths>
#include "Code/QRDUtils.h"
#include "QRDInterface.h"
static const QString glsl_stage4[ENUM_ARRAY_SIZE(ShaderStage)] = {
lit("vert"), lit("tesc"), lit("tese"), lit("geom"), lit("frag"), lit("comp"),
};
static const QString hlsl_stage2[ENUM_ARRAY_SIZE(ShaderStage)] = {
lit("vs"), lit("hs"), lit("ds"), lit("gs"), lit("ps"), lit("cs"),
};
template <>
std::string DoStringise(const KnownShaderTool &el)
{
BEGIN_ENUM_STRINGISE(KnownShaderTool);
{
STRINGISE_ENUM_CLASS_NAMED(Unknown, "Custom Tool");
STRINGISE_ENUM_CLASS_NAMED(SPIRV_Cross, "SPIRV-Cross");
STRINGISE_ENUM_CLASS_NAMED(spirv_dis, "spirv-dis");
STRINGISE_ENUM_CLASS_NAMED(glslangValidatorGLSL, "glslang (GLSL)");
STRINGISE_ENUM_CLASS_NAMED(glslangValidatorHLSL, "glslang (HLSL)");
STRINGISE_ENUM_CLASS_NAMED(spirv_as, "spirv-as");
}
END_ENUM_STRINGISE();
}
static QString tmpPath(const QString &filename)
{
return QDir(QDir::tempPath()).absoluteFilePath(filename);
}
static ShaderToolOutput RunTool(const ShaderProcessingTool &tool, QWidget *window,
QString input_file, QString output_file, QStringList &argList)
{
bool writesToFile = true;
bool readStdin = false;
int idx = argList.indexOf(lit("{stdin}"));
if(idx >= 0)
{
argList.removeAt(idx);
readStdin = true;
}
if(output_file.isEmpty())
{
output_file = tmpPath(lit("shader_output"));
writesToFile = false;
}
// ensure we don't have any leftover output files.
QFile::remove(output_file);
QString stdout_file = QDir(QDir::tempPath()).absoluteFilePath(lit("shader_stdout"));
ShaderToolOutput ret;
if(tool.executable.isEmpty())
{
ret.log = QApplication::translate("ShaderProcessingTool",
"ERROR: No Executable specified in tool '%1'")
.arg(tool.name);
return ret;
}
QString path = tool.executable;
if(!QDir::isAbsolutePath(path))
{
path = QStandardPaths::findExecutable(path);
if(path.isEmpty())
{
ret.log = QApplication::translate("ShaderProcessingTool",
"ERROR: Couldn't find executable '%1' in path")
.arg(tool.executable);
return ret;
}
}
QByteArray stdout_data;
QProcess process;
LambdaThread *thread = new LambdaThread([&]() {
if(readStdin)
process.setStandardInputFile(input_file);
if(!writesToFile)
process.setStandardOutputFile(output_file);
else
process.setStandardOutputFile(stdout_file);
// for now merge stdout/stderr together. Maybe we should separate these and somehow annotate
// them? Merging is difficult without messing up order, and some tools output non-errors to
// stderr
process.setStandardErrorFile(stdout_file);
process.start(tool.executable, argList);
process.waitForFinished();
{
QFile outputHandle(output_file);
if(outputHandle.open(QFile::ReadOnly))
{
ret.result = outputHandle.readAll();
outputHandle.close();
}
}
{
QFile stdoutHandle(stdout_file);
if(stdoutHandle.open(QFile::ReadOnly))
{
stdout_data = stdoutHandle.readAll();
stdoutHandle.close();
}
}
// The input files typically aren't large and we don't generate unique names so they won't be
// overwritten.
// Leaving them alone means the user can try to recreate the tool invocation themselves.
// QFile::remove(input_file);
QFile::remove(output_file);
QFile::remove(stdout_file);
});
thread->start();
ShowProgressDialog(window, QApplication::translate("ShaderProcessingTool",
"Please wait - running external tool"),
[thread]() { return !thread->isRunning(); });
thread->deleteLater();
QString processStatus;
if(process.exitStatus() == QProcess::CrashExit)
{
processStatus = QApplication::translate("ShaderProcessingTool", "Process crashed with code %1.")
.arg(process.exitCode());
}
else
{
processStatus = QApplication::translate("ShaderProcessingTool", "Process exited with code %1.")
.arg(process.exitCode());
}
ret.log = QApplication::translate("ShaderProcessingTool",
"Running \"%1\" %2\n"
"%3\n"
"%4\n"
"Output file is %5 bytes")
.arg(path)
.arg(argList.join(QLatin1Char(' ')))
.arg(QString::fromUtf8(stdout_data))
.arg(processStatus)
.arg(ret.result.count());
return ret;
}
ShaderToolOutput ShaderProcessingTool::DisassembleShader(QWidget *window,
const ShaderReflection *shaderDetails,
rdcstr arguments) const
{
QStringList argList = ParseArgsList(arguments.isEmpty() ? DefaultArguments() : arguments);
QString input_file, output_file;
input_file = tmpPath(lit("shader_input"));
// replace arguments after expansion to avoid problems with quoting paths etc
for(QString &arg : argList)
{
if(arg == lit("{input_file}"))
arg = input_file;
if(arg == lit("{output_file}"))
arg = output_file = tmpPath(lit("shader_output"));
if(arg == lit("{glsl_stage4}"))
arg = glsl_stage4[int(shaderDetails->stage)];
if(arg == lit("{hlsl_stage2}"))
arg = hlsl_stage2[int(shaderDetails->stage)];
}
QFile binHandle(input_file);
if(binHandle.open(QFile::WriteOnly | QIODevice::Truncate))
{
binHandle.write(
QByteArray((const char *)shaderDetails->rawBytes.data(), shaderDetails->rawBytes.count()));
binHandle.close();
}
else
{
ShaderToolOutput ret;
ret.log = QApplication::translate("ShaderProcessingTool",
"ERROR: Couldn't write input to temporary file '%1'")
.arg(input_file);
return ret;
}
return RunTool(*this, window, input_file, output_file, argList);
}
ShaderToolOutput ShaderProcessingTool::CompileShader(QWidget *window, rdcstr source,
rdcstr entryPoint, ShaderStage stage,
rdcstr arguments) const
{
QStringList argList = ParseArgsList(arguments.isEmpty() ? DefaultArguments() : arguments);
QString input_file, output_file;
input_file = tmpPath(lit("shader_input"));
// replace arguments after expansion to avoid problems with quoting paths etc
for(QString &arg : argList)
{
if(arg == lit("{input_file}"))
arg = input_file;
if(arg == lit("{output_file}"))
arg = output_file = tmpPath(lit("shader_output"));
if(arg == lit("{entry_point}"))
arg = entryPoint;
if(arg == lit("{glsl_stage4}"))
arg = glsl_stage4[int(stage)];
if(arg == lit("{hlsl_stage2}"))
arg = hlsl_stage2[int(stage)];
}
QFile binHandle(input_file);
if(binHandle.open(QFile::WriteOnly | QIODevice::Truncate))
{
binHandle.write(QByteArray((const char *)source.c_str(), source.count()));
binHandle.close();
}
else
{
ShaderToolOutput ret;
ret.log = QApplication::translate("ShaderProcessingTool",
"ERROR: Couldn't write input to temporary file '%1'")
.arg(input_file);
return ret;
}
return RunTool(*this, window, input_file, output_file, argList);
}
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
#define sqr(a) (a * a)
// O(log n)
// Returns x ^ n
long pow(long x, long n) {
if (!n) {
return 1;
}
if (n % 2) {
return x * pow(sqr(x), (n - 1) / 2);
} else {
return pow(sqr(x), n / 2);
}
}
// Removed recursion
long pow_loop(long n, long x) {
long r = 1;
while (n) {
if (n & 1) {
r *= x;
n--;
}
x *= x;
n >>= 1;
}
return r;
}
int main () {
return 0;
}
<commit_msg>Fixed danger define<commit_after>#include <iostream>
using namespace std;
#define sqr(a) ((a) * (a))
// O(log n)
// Returns x ^ n
long pow(long x, long n) {
if (!n) {
return 1;
}
if (n % 2) {
return x * pow(sqr(x), (n - 1) / 2);
} else {
return pow(sqr(x), n / 2);
}
}
// Removed recursion
long pow_loop(long n, long x) {
long r = 1;
while (n) {
if (n & 1) {
r *= x;
n--;
}
x *= x;
n >>= 1;
}
return r;
}
int main () {
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014, Calixte DENIZET
// 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 <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef __FASTCAST_HXX__
#define __FASTCAST_HXX__ 1
#if __cplusplus < 201103L
# error "Fastcast must be used with C++11"
#else
#include <cinttypes>
#include <exception>
#include <type_traits>
/**
* The basic idea is to find a single uint to identify a class and to be able to easily determinate if a class
* B derived from A.
* For example, if we have a class A which have children B, C, D, B have children E and F, and D have a child G:
* A--B--E, F
* |
* C
* |
* D--G
*
* A will have id 1 (because it is the root).
* A has 3 children: B(0), C(1), D(2).
* So the id of:
* - B will be 1001 (1 00 1: first 1 is to a delimiter, 00 is the position and 1 is the id of A);
* - C will be 1011 (1 01 1: first 1 is to a delimiter, 01 is the position and 1 is the id of A);
* - D will be 1101 (1 10 1: first 1 is to a delimiter, 10 is the position and 1 is the id of A).
* In following the same scheme, the id of:
* - E will be 101001 (1 0 1001: first 1 is to a delimiter, 0 is the position and 1001 is the id of B);
* - F will be 111001 (1 1 1001: first 1 is to a delimiter, 1 is the position and 1001 is the id of B);
* - G will be 101101 (1 0 1101: first 1 is to a delimiter, 0 is the position and 1101 is the id of D).
* In this case only a uint8_t is required to store the id.
*
* So now it is easy to check if a class is deriving from another one: just check if the derived id "finished"
* its (supposed) parent's one.
* For example, E is a child of B, because B's id finished E's id but G is not a child of B because G's id didn't
* finish B's one.
*
*/
namespace fastcast
{
// The type used for fcast_id
typedef uint64_t fcast_id_t;
struct root
{
struct fcast_hierarchy
{
struct parent
{
struct fcast_hierarchy
{
struct children
{
template<typename U>
constexpr static unsigned int pos() noexcept
{
return 0;
}
};
};
};
struct children
{
template<typename U>
constexpr static unsigned int pos() noexcept
{
return 1;
}
};
constexpr static unsigned int number_of_bits() noexcept
{
return 0;
}
};
};
/**
* @return the number of bits used to represent the argument
*/
constexpr unsigned int number_of_bits(unsigned int n) noexcept
{
return n == 0 ? 0 : (1 + number_of_bits(n >> 1));
}
/**
* @return the corrected position of a child in children list
*/
template<typename U, typename V>
constexpr unsigned int corrected_pos() noexcept
{
return (U::template pos<void>() == 0 ? 0 : (U::template pos<V>() - 1) | (1 << number_of_bits(U::template pos<void>() - 1)));
}
/**
* @return the id of a child according to its position in the list of the parent's children and parent's id.
*/
template<typename Me>
constexpr fcast_id_t id() noexcept
{
return (corrected_pos<typename Me::fcast_hierarchy::parent::fcast_hierarchy::children, Me>() << Me::fcast_hierarchy::number_of_bits()) | id<typename Me::fcast_hierarchy::parent>();
}
// Specialization of the template function id<Me>
template<>
constexpr fcast_id_t id<root>() noexcept { return 0; }
// Specialization of the template function id<Me>
template<>
constexpr fcast_id_t id<root::fcast_hierarchy::parent>() noexcept { return 0; }
/**
* @return the id of the parent
*/
template<typename U>
constexpr fcast_id_t base_id() noexcept
{
return (corrected_pos<typename U::fcast_hierarchy::parent::fcast_hierarchy::children, void>() << U::fcast_hierarchy::number_of_bits()) | id<typename U::fcast_hierarchy::parent>();
}
// Define _children struct
template<unsigned int, typename...>
struct _children;
// Define recursively the chidlren using a variadic template
template<unsigned int N, typename U, typename... C>
struct _children<N, U, C...>
{
typedef _children<N + 1, C...> __children__;
/**
* @return the position of a child in children list
*/
template<typename V>
constexpr static unsigned int pos() noexcept
{
return std::is_same<U, V>::value ? N : __children__::template pos<V>();
}
};
// Last template used in the recursion
template<unsigned int N, typename U>
struct _children<N, U>
{
/**
* @return the position of a child in children list
*/
template<typename V>
constexpr static unsigned int pos() noexcept
{
return N;
}
};
// Define childnre struct used in the hierarchy definition
template<typename... C>
struct children
{
typedef _children<1, C...> __children__;
/**
* @return the position of a child in children list
*/
template<typename V>
constexpr static unsigned int pos() noexcept
{
return __children__::template pos<V>();
}
};
// Define the hierarchy
template<typename Parent, typename Children = void>
struct hierarchy
{
typedef Parent parent;
typedef Children children;
constexpr static unsigned int number_of_bits() noexcept
{
return fastcast::number_of_bits(base_id<parent>());
}
};
// bad_cast exception is used when instanceof as a reference as parameter
class bad_cast : std::exception
{
public:
bad_cast() : std::exception() { }
virtual const char * what() const noexcept
{
return "Bad cast";
}
};
// To be derivated to have a fcast_id
template<typename T, typename U>
struct fcast
{
U _fcast_id;
/**
* Set the _fcast_id field
*/
template<typename V>
inline void set_id() noexcept
{
// Force _id_ to be evaluated at compile-time
constexpr U _id_ = fastcast::id<V>();
_fcast_id = _id_;
}
/**
* @return true if w is an instance of V
*/
template<typename V, typename W>
inline static bool instanceof(W * w) noexcept
{
// Check if V::fcast_id ended w->fcast::_fcast_id in binary representation
// For example, if a=1011011 and b=1011 then b is ending a.
// In the previous case x=a^b=1010000 and x&-x=10000
constexpr U _id_ = fastcast::id<V>();
const fcast_id_t x = w->fcast<T, U>::_fcast_id ^ _id_;
return std::is_base_of<V, W>::value || !x || (_id_ < (x & ((~x) + 1)));
}
/**
* @return true if w is an instance of V
*/
template<typename V, typename W>
inline static bool instanceof(W & w) noexcept
{
return instanceof<V, W>(&w);
}
/**
* @return true if the underlying type of w is V
*/
template<typename V, typename W>
constexpr static bool same(W * w) noexcept
{
return fastcast::id<V>() == w->fcast<T, U>::_fcast_id;
}
/**
* @return true if the underlying type of w is V
*/
template<typename V, typename W>
constexpr static bool same(W & w) noexcept
{
return same<V, W>(&w);
}
/**
* Cast w to a V* pointer
* @return the casted pointer or nullptr if V is not an instance of U
*/
template<typename V, typename W>
inline static V * cast(W * w) noexcept
{
return instanceof<V>(w) ? static_cast<V *>(w) : nullptr;
}
/**
* Cast w to a V reference
* @return the casted reference or throw a fastcast::bad_cast exception
*/
template<typename V, typename W>
inline static V & cast(W & w)
{
return instanceof<V>(w) ? static_cast<V &>(w) : throw fastcast::bad_cast();
}
/**
* Just an alias for static_cast
*/
template<typename V, typename W>
inline static V & cast_unchecked(W & w)
{
return static_cast<V &>(w);
}
};
} // namespace fastcast
#endif // __cplusplus < 201103L
#endif // __FASTCAST_HXX__
<commit_msg>Fix english typo<commit_after>// Copyright (c) 2014, Calixte DENIZET
// 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 <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef __FASTCAST_HXX__
#define __FASTCAST_HXX__ 1
#if __cplusplus < 201103L
# error "Fastcast must be used with C++11"
#else
#include <cinttypes>
#include <exception>
#include <type_traits>
/**
* The basic idea is to find a single uint to identify a class and to be able to easily determinate if a class
* B derived from A.
* For example, if we have a class A which have children B, C, D, B have children E and F, and D have a child G:
* A--B--E, F
* |
* C
* |
* D--G
*
* A will have id 1 (because it is the root).
* A has 3 children: B(0), C(1), D(2).
* So the id of:
* - B will be 1001 (1 00 1: first 1 is a delimiter, 00 is the position and 1 is the id of A);
* - C will be 1011 (1 01 1: first 1 is a delimiter, 01 is the position and 1 is the id of A);
* - D will be 1101 (1 10 1: first 1 is a delimiter, 10 is the position and 1 is the id of A).
* In following the same scheme, the id of:
* - E will be 101001 (1 0 1001: first 1 is a delimiter, 0 is the position and 1001 is the id of B);
* - F will be 111001 (1 1 1001: first 1 is a delimiter, 1 is the position and 1001 is the id of B);
* - G will be 101101 (1 0 1101: first 1 is a delimiter, 0 is the position and 1101 is the id of D).
* In this case only a uint8_t is required to store the id.
*
* So now it is easy to check if a class is deriving from another one: just check if the derived id "finished"
* its (supposed) parent's one.
* For example, E is a child of B, because B's id finished E's id but G is not a child of B because G's id didn't
* finish B's one.
*
*/
namespace fastcast
{
// The type used for fcast_id
typedef uint64_t fcast_id_t;
struct root
{
struct fcast_hierarchy
{
struct parent
{
struct fcast_hierarchy
{
struct children
{
template<typename U>
constexpr static unsigned int pos() noexcept
{
return 0;
}
};
};
};
struct children
{
template<typename U>
constexpr static unsigned int pos() noexcept
{
return 1;
}
};
constexpr static unsigned int number_of_bits() noexcept
{
return 0;
}
};
};
/**
* @return the number of bits used to represent the argument
*/
constexpr unsigned int number_of_bits(unsigned int n) noexcept
{
return n == 0 ? 0 : (1 + number_of_bits(n >> 1));
}
/**
* @return the corrected position of a child in children list
*/
template<typename U, typename V>
constexpr unsigned int corrected_pos() noexcept
{
return (U::template pos<void>() == 0 ? 0 : (U::template pos<V>() - 1) | (1 << number_of_bits(U::template pos<void>() - 1)));
}
/**
* @return the id of a child according to its position in the list of the parent's children and parent's id.
*/
template<typename Me>
constexpr fcast_id_t id() noexcept
{
return (corrected_pos<typename Me::fcast_hierarchy::parent::fcast_hierarchy::children, Me>() << Me::fcast_hierarchy::number_of_bits()) | id<typename Me::fcast_hierarchy::parent>();
}
// Specialization of the template function id<Me>
template<>
constexpr fcast_id_t id<root>() noexcept { return 0; }
// Specialization of the template function id<Me>
template<>
constexpr fcast_id_t id<root::fcast_hierarchy::parent>() noexcept { return 0; }
/**
* @return the id of the parent
*/
template<typename U>
constexpr fcast_id_t base_id() noexcept
{
return (corrected_pos<typename U::fcast_hierarchy::parent::fcast_hierarchy::children, void>() << U::fcast_hierarchy::number_of_bits()) | id<typename U::fcast_hierarchy::parent>();
}
// Define _children struct
template<unsigned int, typename...>
struct _children;
// Define recursively the chidlren using a variadic template
template<unsigned int N, typename U, typename... C>
struct _children<N, U, C...>
{
typedef _children<N + 1, C...> __children__;
/**
* @return the position of a child in children list
*/
template<typename V>
constexpr static unsigned int pos() noexcept
{
return std::is_same<U, V>::value ? N : __children__::template pos<V>();
}
};
// Last template used in the recursion
template<unsigned int N, typename U>
struct _children<N, U>
{
/**
* @return the position of a child in children list
*/
template<typename V>
constexpr static unsigned int pos() noexcept
{
return N;
}
};
// Define childnre struct used in the hierarchy definition
template<typename... C>
struct children
{
typedef _children<1, C...> __children__;
/**
* @return the position of a child in children list
*/
template<typename V>
constexpr static unsigned int pos() noexcept
{
return __children__::template pos<V>();
}
};
// Define the hierarchy
template<typename Parent, typename Children = void>
struct hierarchy
{
typedef Parent parent;
typedef Children children;
constexpr static unsigned int number_of_bits() noexcept
{
return fastcast::number_of_bits(base_id<parent>());
}
};
// bad_cast exception is used when instanceof as a reference as parameter
class bad_cast : std::exception
{
public:
bad_cast() : std::exception() { }
virtual const char * what() const noexcept
{
return "Bad cast";
}
};
// To be derivated to have a fcast_id
template<typename T, typename U>
struct fcast
{
U _fcast_id;
/**
* Set the _fcast_id field
*/
template<typename V>
inline void set_id() noexcept
{
// Force _id_ to be evaluated at compile-time
constexpr U _id_ = fastcast::id<V>();
_fcast_id = _id_;
}
/**
* @return true if w is an instance of V
*/
template<typename V, typename W>
inline static bool instanceof(W * w) noexcept
{
// Check if V::fcast_id ended w->fcast::_fcast_id in binary representation
// For example, if a=1011011 and b=1011 then b is ending a.
// In the previous case x=a^b=1010000 and x&-x=10000
constexpr U _id_ = fastcast::id<V>();
const fcast_id_t x = w->fcast<T, U>::_fcast_id ^ _id_;
return std::is_base_of<V, W>::value || !x || (_id_ < (x & ((~x) + 1)));
}
/**
* @return true if w is an instance of V
*/
template<typename V, typename W>
inline static bool instanceof(W & w) noexcept
{
return instanceof<V, W>(&w);
}
/**
* @return true if the underlying type of w is V
*/
template<typename V, typename W>
constexpr static bool same(W * w) noexcept
{
return fastcast::id<V>() == w->fcast<T, U>::_fcast_id;
}
/**
* @return true if the underlying type of w is V
*/
template<typename V, typename W>
constexpr static bool same(W & w) noexcept
{
return same<V, W>(&w);
}
/**
* Cast w to a V* pointer
* @return the casted pointer or nullptr if V is not an instance of U
*/
template<typename V, typename W>
inline static V * cast(W * w) noexcept
{
return instanceof<V>(w) ? static_cast<V *>(w) : nullptr;
}
/**
* Cast w to a V reference
* @return the casted reference or throw a fastcast::bad_cast exception
*/
template<typename V, typename W>
inline static V & cast(W & w)
{
return instanceof<V>(w) ? static_cast<V &>(w) : throw fastcast::bad_cast();
}
/**
* Just an alias for static_cast
*/
template<typename V, typename W>
inline static V & cast_unchecked(W & w)
{
return static_cast<V &>(w);
}
};
} // namespace fastcast
#endif // __cplusplus < 201103L
#endif // __FASTCAST_HXX__
<|endoftext|> |
<commit_before>#include "TrackingWorker.hpp"
#include <boost/chrono/duration.hpp>
#include <ros/console.h>
#include "../matlab/profiling.hpp"
TrackingWorker::TrackingWorker(IPositionReceiver *receiver) : errorGraph(200, "Difference")
{
assert(receiver != 0);
this->receiver = receiver;
stop = false;
thread = new boost::thread(boost::bind(&TrackingWorker::run, this));
}
TrackingWorker::~TrackingWorker()
{
stop = true;
thread->join();
}
void TrackingWorker::run()
{
ROS_INFO("Started tracking thread");
bool receivedFirstPosition = false;
while (!stop) {
CameraData data = dequeue();
if (data.valid) {
// ROS_DEBUG("Got valid data");
receivedFirstPosition = true;
long int startTime = getNanoTime();
Vector position = tracker.updatePosition(data.cameraVector, data.camNo, data.quadcopterId);
errorGraph.nextPoint(tracker.getDistance());
double duration = getNanoTime() - startTime;
duration /= 1e6;
std::vector<Vector> positions;
std::vector<int> ids;
std::vector<int> updates;
positions.push_back(position);
ids.push_back(data.quadcopterId);
updates.push_back(1);
if (position.isValid()) {
receiver->updatePositions(positions, ids, updates);
} else {
// ROS_DEBUG("Not enough information to get position of quadcopter %d", data.quadcopterId);
}
// ROS_DEBUG("Updating position of quadcopter %d took %.3f ms", data.quadcopterId, duration);
} else if (receivedFirstPosition) {
ROS_WARN("Position update buffer is empty!");
}
}
ROS_INFO("Stopped tracking thread");
}
void TrackingWorker::updatePosition(Vector cameraVector, int camNo, int quadcopterId)
{
CameraData data;
data.cameraVector = cameraVector;
data.camNo = camNo;
data.quadcopterId = quadcopterId;
data.valid = true;
updatePosition(data);
}
void TrackingWorker::updatePosition(CameraData data)
{
// ROS_DEBUG("updatePosition: called");
enqueue(data);
// ROS_DEBUG("updatePosition: Inserted CameraData for camera %d and quadcopter %d", data.camNo, data.quadcopterId);
}
void TrackingWorker::enqueue(CameraData data)
{
// ROS_DEBUG("enqueue: Inserting CameraData");
{
boost::mutex::scoped_lock lock(positionsMutex);
// ROS_DEBUG("enqueue: Got positions lock");
positions.push(data);
if (positions.size() > 25) {
ROS_WARN("Position update buffer is running full (%ld entries). Seems like the position updating can't keep up! Dropping 15 entries.", positions.size());
for (int i = 0; i < 15; i++) {
positions.pop();
}
}
}
// ROS_DEBUG("enqueue: Released positions lock");
// ROS_DEBUG("enqueue: Notifying about new CameraData");
positionsEmpty.notify_one();
// ROS_DEBUG("enqueue: Finished insertion process");
}
CameraData TrackingWorker::dequeue()
{
// ROS_DEBUG("dequeue: Getting positions lock");
{
boost::mutex::scoped_lock lock(positionsMutex);
// ROS_DEBUG("dequeue: Got positions lock");
if (!dataAvailable()) {
positionsEmpty.timed_wait(lock, boost::get_system_time() + boost::posix_time::milliseconds(100));
}
if (dataAvailable()) {
CameraData data = positions.front();
positions.pop();
// ROS_DEBUG("dequeue: Released positions lock");
return data;
} else {
CameraData data;
data.valid = false;
// ROS_DEBUG("dequeue: Released positions lock");
return data;
}
}
}
bool TrackingWorker::dataAvailable()
{
return positions.size() > 0;
}
bool TrackingWorker::calibrate(ChessboardData *chessboard, int camNo)
{
return tracker.calibrate(chessboard, camNo);
}
Vector TrackingWorker::getCameraPosition(int camNo)
{
return tracker.getPosition(camNo);
}
cv::Mat TrackingWorker::getIntrinsicsMatrix(int camNo)
{
return tracker.getIntrinsicsMatrix(camNo);
}
cv::Mat TrackingWorker::getDistortionCoefficients(int camNo)
{
return tracker.getDistortionCoefficients(camNo);
}<commit_msg>Use new position updating algorithm<commit_after>#include "TrackingWorker.hpp"
#include <boost/chrono/duration.hpp>
#include <ros/console.h>
#include "../matlab/profiling.hpp"
TrackingWorker::TrackingWorker(IPositionReceiver *receiver) : errorGraph(200, "Difference"), tracker(true)
{
assert(receiver != 0);
this->receiver = receiver;
stop = false;
thread = new boost::thread(boost::bind(&TrackingWorker::run, this));
}
TrackingWorker::~TrackingWorker()
{
stop = true;
thread->join();
}
void TrackingWorker::run()
{
ROS_INFO("Started tracking thread");
bool receivedFirstPosition = false;
while (!stop) {
CameraData data = dequeue();
if (data.valid) {
// ROS_DEBUG("Got valid data");
receivedFirstPosition = true;
long int startTime = getNanoTime();
Vector position = tracker.updatePosition(data.cameraVector, data.camNo, data.quadcopterId);
errorGraph.nextPoint(tracker.getDistance());
double duration = getNanoTime() - startTime;
duration /= 1e6;
std::vector<Vector> positions;
std::vector<int> ids;
std::vector<int> updates;
positions.push_back(position);
ids.push_back(data.quadcopterId);
updates.push_back(1);
if (position.isValid()) {
receiver->updatePositions(positions, ids, updates);
} else {
// ROS_DEBUG("Not enough information to get position of quadcopter %d", data.quadcopterId);
}
// ROS_DEBUG("Updating position of quadcopter %d took %.3f ms", data.quadcopterId, duration);
} else if (receivedFirstPosition) {
ROS_WARN("Position update buffer is empty!");
}
}
ROS_INFO("Stopped tracking thread");
}
void TrackingWorker::updatePosition(Vector cameraVector, int camNo, int quadcopterId)
{
CameraData data;
data.cameraVector = cameraVector;
data.camNo = camNo;
data.quadcopterId = quadcopterId;
data.valid = true;
updatePosition(data);
}
void TrackingWorker::updatePosition(CameraData data)
{
// ROS_DEBUG("updatePosition: called");
enqueue(data);
// ROS_DEBUG("updatePosition: Inserted CameraData for camera %d and quadcopter %d", data.camNo, data.quadcopterId);
}
void TrackingWorker::enqueue(CameraData data)
{
// ROS_DEBUG("enqueue: Inserting CameraData");
{
boost::mutex::scoped_lock lock(positionsMutex);
// ROS_DEBUG("enqueue: Got positions lock");
positions.push(data);
if (positions.size() > 25) {
ROS_WARN("Position update buffer is running full (%ld entries). Seems like the position updating can't keep up! Dropping 15 entries.", positions.size());
for (int i = 0; i < 15; i++) {
positions.pop();
}
}
}
// ROS_DEBUG("enqueue: Released positions lock");
// ROS_DEBUG("enqueue: Notifying about new CameraData");
positionsEmpty.notify_one();
// ROS_DEBUG("enqueue: Finished insertion process");
}
CameraData TrackingWorker::dequeue()
{
// ROS_DEBUG("dequeue: Getting positions lock");
{
boost::mutex::scoped_lock lock(positionsMutex);
// ROS_DEBUG("dequeue: Got positions lock");
if (!dataAvailable()) {
positionsEmpty.timed_wait(lock, boost::get_system_time() + boost::posix_time::milliseconds(100));
}
if (dataAvailable()) {
CameraData data = positions.front();
positions.pop();
// ROS_DEBUG("dequeue: Released positions lock");
return data;
} else {
CameraData data;
data.valid = false;
// ROS_DEBUG("dequeue: Released positions lock");
return data;
}
}
}
bool TrackingWorker::dataAvailable()
{
return positions.size() > 0;
}
bool TrackingWorker::calibrate(ChessboardData *chessboard, int camNo)
{
return tracker.calibrate(chessboard, camNo);
}
Vector TrackingWorker::getCameraPosition(int camNo)
{
return tracker.getPosition(camNo);
}
cv::Mat TrackingWorker::getIntrinsicsMatrix(int camNo)
{
return tracker.getIntrinsicsMatrix(camNo);
}
cv::Mat TrackingWorker::getDistortionCoefficients(int camNo)
{
return tracker.getDistortionCoefficients(camNo);
}<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <boost/unordered_map.hpp>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget> void
pcl::IterativeClosestPoint<PointSource, PointTarget>::computeTransformation (PointCloudSource &output)
{
pcl::IterativeClosestPoint<PointSource, PointTarget>::computeTransformation (output, Eigen::Matrix4f::Identity());
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget> void
pcl::IterativeClosestPoint<PointSource, PointTarget>::computeTransformation (PointCloudSource &output, const Eigen::Matrix4f &guess)
{
// Allocate enough space to hold the results
std::vector<int> nn_indices (1);
std::vector<float> nn_dists (1);
// Point cloud containing the correspondences of each point in <input, indices>
PointCloudTarget input_corresp;
input_corresp.points.resize (indices_->size ());
nr_iterations_ = 0;
converged_ = false;
double dist_threshold = corr_dist_threshold_ * corr_dist_threshold_;
// If the guessed transformation is non identity
if (guess != Eigen::Matrix4f::Identity ())
{
// Initialise final transformation to the guessed one
final_transformation_ = guess;
// Apply guessed transformation prior to search for neighbours
transformPointCloud (output, output, guess);
}
// Resize the vector of distances between correspondences
std::vector<float> previous_correspondence_distances (indices_->size ());
correspondence_distances_.resize (indices_->size ());
while (!converged_) // repeat until convergence
{
// Save the previously estimated transformation
previous_transformation_ = transformation_;
// And the previous set of distances
previous_correspondence_distances = correspondence_distances_;
int cnt = 0;
std::vector<int> source_indices (indices_->size ());
std::vector<int> target_indices (indices_->size ());
// Iterating over the entire index vector and find all correspondences
for (size_t idx = 0; idx < indices_->size (); ++idx)
{
if (!searchForNeighbors (output, (*indices_)[idx], nn_indices, nn_dists))
{
PCL_ERROR ("[pcl::%s::computeTransformation] Unable to find a nearest neighbor in the target dataset for point %d in the source!\n", getClassName ().c_str (), (*indices_)[idx]);
return;
}
// Check if the distance to the nearest neighbor is smaller than the user imposed threshold
if (nn_dists[0] < dist_threshold)
{
source_indices[cnt] = (*indices_)[idx];
target_indices[cnt] = nn_indices[0];
cnt++;
}
// Save the nn_dists[0] to a global vector of distances
correspondence_distances_[(*indices_)[idx]] = std::min (nn_dists[0], (float)dist_threshold);
}
// Resize to the actual number of valid correspondences
source_indices.resize (cnt); target_indices.resize (cnt);
std::vector<int> source_indices_good;
std::vector<int> target_indices_good;
{
// From the set of correspondences found, attempt to remove outliers
// Create the registration model
typedef typename SampleConsensusModelRegistration<PointSource>::Ptr SampleConsensusModelRegistrationPtr;
SampleConsensusModelRegistrationPtr model;
model.reset (new SampleConsensusModelRegistration<PointSource> (output.makeShared (), source_indices));
// Pass the target_indices
model->setInputTarget (target_, target_indices);
// Create a RANSAC model
RandomSampleConsensus<PointSource> sac (model, inlier_threshold_);
sac.setMaxIterations (1000);
// Compute the set of inliers
if (!sac.computeModel ())
{
source_indices_good = source_indices;
target_indices_good = target_indices;
}
else
{
std::vector<int> inliers;
// Get the inliers
sac.getInliers (inliers);
source_indices_good.resize (inliers.size ());
target_indices_good.resize (inliers.size ());
boost::unordered_map<int, int> source_to_target;
for (unsigned int i = 0; i < source_indices.size(); ++i)
source_to_target[source_indices[i]] = target_indices[i];
// Copy just the inliers
std::copy(inliers.begin(), inliers.end(), source_indices_good.begin());
for (size_t i = 0; i < inliers.size (); ++i)
target_indices_good[i] = source_to_target[inliers[i]];
}
}
// Check whether we have enough correspondences
cnt = (int)source_indices_good.size ();
if (cnt < min_number_correspondences_)
{
PCL_ERROR ("[pcl::%s::computeTransformation] Not enough correspondences found. Relax your threshold parameters.\n", getClassName ().c_str ());
converged_ = false;
return;
}
PCL_DEBUG ("[pcl::%s::computeTransformation] Number of correspondences %d [%f%%] out of %lu points [100.0%%], RANSAC rejected: %lu [%f%%].\n", getClassName ().c_str (), cnt, (cnt * 100.0) / indices_->size (), (unsigned long)indices_->size (), (unsigned long)source_indices.size () - cnt, (source_indices.size () - cnt) * 100.0 / source_indices.size ());
// Estimate the transform
//rigid_transformation_estimation_(output, source_indices_good, *target_, target_indices_good, transformation_);
transformation_estimation_->estimateRigidTransformation (output, source_indices_good, *target_, target_indices_good, transformation_);
// Tranform the data
transformPointCloud (output, output, transformation_);
// Obtain the final transformation
final_transformation_ = transformation_ * final_transformation_;
nr_iterations_++;
// Update the vizualization of icp convergence
if (update_visualizer_ != 0)
update_visualizer_(output, source_indices_good, *target_, target_indices_good );
// Various/Different convergence termination criteria
// 1. Number of iterations has reached the maximum user imposed number of iterations (via
// setMaximumIterations)
// 2. The epsilon (difference) between the previous transformation and the current estimated transformation
// is smaller than an user imposed value (via setTransformationEpsilon)
// 3. The sum of Euclidean squared errors is smaller than a user defined threshold (via
// setEuclideanFitnessEpsilon)
if (nr_iterations_ >= max_iterations_ ||
fabs ((transformation_ - previous_transformation_).sum ()) < transformation_epsilon_ ||
fabs (getFitnessScore (correspondence_distances_, previous_correspondence_distances)) <= euclidean_fitness_epsilon_
)
{
converged_ = true;
PCL_DEBUG ("[pcl::%s::computeTransformation] Convergence reached. Number of iterations: %d out of %d. Transformation difference: %f\n",
getClassName ().c_str (), nr_iterations_, max_iterations_, fabs ((transformation_ - previous_transformation_).sum ()));
PCL_DEBUG ("nr_iterations_ (%d) >= max_iterations_ (%d)\n", nr_iterations_, max_iterations_);
PCL_DEBUG ("fabs ((transformation_ - previous_transformation_).sum ()) (%f) < transformation_epsilon_ (%f)\n",
fabs ((transformation_ - previous_transformation_).sum ()), transformation_epsilon_);
PCL_DEBUG ("fabs (getFitnessScore (correspondence_distances_, previous_correspondence_distances)) (%f) <= euclidean_fitness_epsilon_ (%f)\n",
fabs (getFitnessScore (correspondence_distances_, previous_correspondence_distances)),
euclidean_fitness_epsilon_);
}
}
}
<commit_msg>fixed a problem where if no correspondences would be found via nearestKSearch, the RANSAC-based rejection scheme would fail (thanks to James for reporting this)<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <boost/unordered_map.hpp>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget> void
pcl::IterativeClosestPoint<PointSource, PointTarget>::computeTransformation (PointCloudSource &output)
{
pcl::IterativeClosestPoint<PointSource, PointTarget>::computeTransformation (output, Eigen::Matrix4f::Identity());
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget> void
pcl::IterativeClosestPoint<PointSource, PointTarget>::computeTransformation (PointCloudSource &output, const Eigen::Matrix4f &guess)
{
// Allocate enough space to hold the results
std::vector<int> nn_indices (1);
std::vector<float> nn_dists (1);
// Point cloud containing the correspondences of each point in <input, indices>
PointCloudTarget input_corresp;
input_corresp.points.resize (indices_->size ());
nr_iterations_ = 0;
converged_ = false;
double dist_threshold = corr_dist_threshold_ * corr_dist_threshold_;
// If the guessed transformation is non identity
if (guess != Eigen::Matrix4f::Identity ())
{
// Initialise final transformation to the guessed one
final_transformation_ = guess;
// Apply guessed transformation prior to search for neighbours
transformPointCloud (output, output, guess);
}
// Resize the vector of distances between correspondences
std::vector<float> previous_correspondence_distances (indices_->size ());
correspondence_distances_.resize (indices_->size ());
while (!converged_) // repeat until convergence
{
// Save the previously estimated transformation
previous_transformation_ = transformation_;
// And the previous set of distances
previous_correspondence_distances = correspondence_distances_;
int cnt = 0;
std::vector<int> source_indices (indices_->size ());
std::vector<int> target_indices (indices_->size ());
// Iterating over the entire index vector and find all correspondences
for (size_t idx = 0; idx < indices_->size (); ++idx)
{
if (!searchForNeighbors (output, (*indices_)[idx], nn_indices, nn_dists))
{
PCL_ERROR ("[pcl::%s::computeTransformation] Unable to find a nearest neighbor in the target dataset for point %d in the source!\n", getClassName ().c_str (), (*indices_)[idx]);
return;
}
// Check if the distance to the nearest neighbor is smaller than the user imposed threshold
if (nn_dists[0] < dist_threshold)
{
source_indices[cnt] = (*indices_)[idx];
target_indices[cnt] = nn_indices[0];
cnt++;
}
// Save the nn_dists[0] to a global vector of distances
correspondence_distances_[(*indices_)[idx]] = std::min (nn_dists[0], (float)dist_threshold);
}
if (cnt < min_number_correspondences_)
{
PCL_ERROR ("[pcl::%s::computeTransformation] Not enough correspondences found. Relax your threshold parameters.\n", getClassName ().c_str ());
converged_ = false;
return;
}
// Resize to the actual number of valid correspondences
source_indices.resize (cnt); target_indices.resize (cnt);
std::vector<int> source_indices_good;
std::vector<int> target_indices_good;
{
// From the set of correspondences found, attempt to remove outliers
// Create the registration model
typedef typename SampleConsensusModelRegistration<PointSource>::Ptr SampleConsensusModelRegistrationPtr;
SampleConsensusModelRegistrationPtr model;
model.reset (new SampleConsensusModelRegistration<PointSource> (output.makeShared (), source_indices));
// Pass the target_indices
model->setInputTarget (target_, target_indices);
// Create a RANSAC model
RandomSampleConsensus<PointSource> sac (model, inlier_threshold_);
sac.setMaxIterations (1000);
// Compute the set of inliers
if (!sac.computeModel ())
{
source_indices_good = source_indices;
target_indices_good = target_indices;
}
else
{
std::vector<int> inliers;
// Get the inliers
sac.getInliers (inliers);
source_indices_good.resize (inliers.size ());
target_indices_good.resize (inliers.size ());
boost::unordered_map<int, int> source_to_target;
for (unsigned int i = 0; i < source_indices.size(); ++i)
source_to_target[source_indices[i]] = target_indices[i];
// Copy just the inliers
std::copy(inliers.begin(), inliers.end(), source_indices_good.begin());
for (size_t i = 0; i < inliers.size (); ++i)
target_indices_good[i] = source_to_target[inliers[i]];
}
}
// Check whether we have enough correspondences
cnt = (int)source_indices_good.size ();
if (cnt < min_number_correspondences_)
{
PCL_ERROR ("[pcl::%s::computeTransformation] Not enough correspondences found. Relax your threshold parameters.\n", getClassName ().c_str ());
converged_ = false;
return;
}
PCL_DEBUG ("[pcl::%s::computeTransformation] Number of correspondences %d [%f%%] out of %lu points [100.0%%], RANSAC rejected: %lu [%f%%].\n", getClassName ().c_str (), cnt, (cnt * 100.0) / indices_->size (), (unsigned long)indices_->size (), (unsigned long)source_indices.size () - cnt, (source_indices.size () - cnt) * 100.0 / source_indices.size ());
// Estimate the transform
//rigid_transformation_estimation_(output, source_indices_good, *target_, target_indices_good, transformation_);
transformation_estimation_->estimateRigidTransformation (output, source_indices_good, *target_, target_indices_good, transformation_);
// Tranform the data
transformPointCloud (output, output, transformation_);
// Obtain the final transformation
final_transformation_ = transformation_ * final_transformation_;
nr_iterations_++;
// Update the vizualization of icp convergence
if (update_visualizer_ != 0)
update_visualizer_(output, source_indices_good, *target_, target_indices_good );
// Various/Different convergence termination criteria
// 1. Number of iterations has reached the maximum user imposed number of iterations (via
// setMaximumIterations)
// 2. The epsilon (difference) between the previous transformation and the current estimated transformation
// is smaller than an user imposed value (via setTransformationEpsilon)
// 3. The sum of Euclidean squared errors is smaller than a user defined threshold (via
// setEuclideanFitnessEpsilon)
if (nr_iterations_ >= max_iterations_ ||
fabs ((transformation_ - previous_transformation_).sum ()) < transformation_epsilon_ ||
fabs (getFitnessScore (correspondence_distances_, previous_correspondence_distances)) <= euclidean_fitness_epsilon_
)
{
converged_ = true;
PCL_DEBUG ("[pcl::%s::computeTransformation] Convergence reached. Number of iterations: %d out of %d. Transformation difference: %f\n",
getClassName ().c_str (), nr_iterations_, max_iterations_, fabs ((transformation_ - previous_transformation_).sum ()));
PCL_DEBUG ("nr_iterations_ (%d) >= max_iterations_ (%d)\n", nr_iterations_, max_iterations_);
PCL_DEBUG ("fabs ((transformation_ - previous_transformation_).sum ()) (%f) < transformation_epsilon_ (%f)\n",
fabs ((transformation_ - previous_transformation_).sum ()), transformation_epsilon_);
PCL_DEBUG ("fabs (getFitnessScore (correspondence_distances_, previous_correspondence_distances)) (%f) <= euclidean_fitness_epsilon_ (%f)\n",
fabs (getFitnessScore (correspondence_distances_, previous_correspondence_distances)),
euclidean_fitness_epsilon_);
}
}
}
<|endoftext|> |
<commit_before>/*
* TI Voxel Lib component.
*
* Copyright (c) 2014 Texas Instruments Inc.
*/
#include "DarkPixFilter.h"
namespace Voxel
{
DarkPixFilter::DarkPixFilter(float aThrNear, float phThrNear, float aThrFar, float phThrFar): Filter("DarkPixFilter"), _aThrNear(aThrNear), _phThrNear(phThrNear), _aThrFar(aThrFar), _phThrFar(phThrFar)
{
_addParameters({
FilterParameterPtr(new FloatFilterParameter("aThrNear", "aThrNear", "NearAmpThr", _aThrNear, "", 0.0f, 4095.0f)),
FilterParameterPtr(new FloatFilterParameter("phThrNear", "phThrNear", "NearPhThr", _phThrNear, "", 0.0f, 4095.0f)),
FilterParameterPtr(new FloatFilterParameter("aThrFar", "aThrFar", "FarAmpThr", _aThrFar, "", 0.0f, 4095.0f)),
FilterParameterPtr(new FloatFilterParameter("phThrFar", "phThrFar", "FarPhThr", _phThrFar, "", 0.0f, 4095.0f))
});
}
void DarkPixFilter::_onSet(const FilterParameterPtr &f)
{
if(f->name() == "aThrNear")
{
if(!_get(f->name(), _aThrNear))
{
logger(LOG_WARNING) << "DarkPixFilter: Could not get the recently updated 'aThrNear' parameter" << std::endl;
}
}
else if(f->name() == "phThrNear")
{
if(!_get(f->name(), _phThrNear))
{
logger(LOG_WARNING) << "DarkPixFilter: Could not get the recently updated 'phThrNear' parameter" << std::endl;
}
}
else if(f->name() == "aThrFar")
{
if(!_get(f->name(), _aThrFar))
{
logger(LOG_WARNING) << "DarkPixFilter: Could not get the recently updated 'aThrFar' parameter" << std::endl;
}
}
else if(f->name() == "phThrFar")
{
if(!_get(f->name(), _phThrFar))
{
logger(LOG_WARNING) << "DarkPixFilter: Could not get the recently updated 'phThrFar' parameter" << std::endl;
}
}
}
void DarkPixFilter::reset()
{
_current.clear();
}
template <typename T>
bool DarkPixFilter::_filter(const T *in, T *out)
{
uint s = _size.width*_size.height;
for(auto i = 0; i < s; i++)
out[i] = in[i];
return true;
}
template <typename T, typename T2>
bool DarkPixFilter::_filter2(const T *in, T2 *amp, T *out)
{
uint s = _size.width*_size.height;
for (auto p = 0; p < s; p++)
{
if ( ((amp[p] < _aThrNear) && (in[p] < _phThrNear)) || ((amp[p] > _aThrFar) && (in[p] > _phThrFar)) )
out[p] = 0;
else
out[p] = in[p];
}
return true;
}
bool DarkPixFilter::_filter(const FramePtr &in, FramePtr &out)
{
ToFRawFrame *tofFrame = dynamic_cast<ToFRawFrame *>(in.get());
DepthFrame *depthFrame = dynamic_cast<DepthFrame *>(in.get());
if((!tofFrame && !depthFrame) || !_prepareOutput(in, out))
{
logger(LOG_ERROR) << "DarkPixFilter: Input frame type is not ToFRawFrame or DepthFrame or failed get the output ready" << std::endl;
return false;
}
if(tofFrame)
{
_size = tofFrame->size;
ToFRawFrame *o = dynamic_cast<ToFRawFrame *>(out.get());
if(!o)
{
logger(LOG_ERROR) << "DarkPixFilter: Invalid frame type. Expecting ToFRawFrame." << std::endl;
return false;
}
//logger(LOG_INFO) << "DarkPixFilter: Applying filter with aThr = " << _aThr << " and phThr = " << _phThr << std::endl;
uint s = _size.width*_size.height;
memcpy(o->ambient(), tofFrame->ambient(), s*tofFrame->ambientWordWidth());
memcpy(o->amplitude(), tofFrame->amplitude(), s*tofFrame->amplitudeWordWidth());
memcpy(o->flags(), tofFrame->flags(), s*tofFrame->flagsWordWidth());
if(tofFrame->phaseWordWidth() == 2)
{
if(tofFrame->amplitudeWordWidth() == 1)
return _filter2<uint16_t, uint8_t>((uint16_t *)tofFrame->phase(), (uint8_t *)tofFrame->amplitude(), (uint16_t *)o->phase());
else if(tofFrame->amplitudeWordWidth() == 2)
return _filter2<uint16_t, uint16_t>((uint16_t *)tofFrame->phase(), (uint16_t *)tofFrame->amplitude(), (uint16_t *)o->phase());
else if(tofFrame->amplitudeWordWidth() == 4)
return _filter2<uint16_t, uint32_t>((uint16_t *)tofFrame->phase(), (uint32_t *)tofFrame->amplitude(), (uint16_t *)o->phase());
}
else if(tofFrame->phaseWordWidth() == 1)
{
if(tofFrame->amplitudeWordWidth() == 1)
return _filter2<uint8_t, uint8_t>((uint8_t *)tofFrame->phase(), (uint8_t *)tofFrame->amplitude(), (uint8_t *)o->phase());
else if(tofFrame->amplitudeWordWidth() == 2)
return _filter2<uint8_t, uint16_t>((uint8_t *)tofFrame->phase(), (uint16_t *)tofFrame->amplitude(), (uint8_t *)o->phase());
else if(tofFrame->amplitudeWordWidth() == 4)
return _filter2<uint8_t, uint32_t>((uint8_t *)tofFrame->phase(), (uint32_t *)tofFrame->amplitude(), (uint8_t *)o->phase());
}
else if(tofFrame->phaseWordWidth() == 4)
{
if(tofFrame->amplitudeWordWidth() == 1)
return _filter2<uint32_t, uint8_t>((uint32_t *)tofFrame->phase(), (uint8_t *)tofFrame->amplitude(), (uint32_t *)o->phase());
else if(tofFrame->amplitudeWordWidth() == 2)
return _filter2<uint32_t, uint16_t>((uint32_t *)tofFrame->phase(), (uint16_t *)tofFrame->amplitude(), (uint32_t *)o->phase());
else if(tofFrame->amplitudeWordWidth() == 4)
return _filter2<uint32_t, uint32_t>((uint32_t *)tofFrame->phase(), (uint32_t *)tofFrame->amplitude(), (uint32_t *)o->phase());
}
}
else if(depthFrame)
{
_size = depthFrame->size;
DepthFrame *o = dynamic_cast<DepthFrame *>(out.get());
if(!o)
{
logger(LOG_ERROR) << "DarkPixFilter: Invalid frame type. Expecting DepthFrame." << std::endl;
return false;
}
o->amplitude = depthFrame->amplitude;
return _filter<float>(depthFrame->depth.data(), o->depth.data());
}
else
return false;
}
}
<commit_msg>DarkPixFilter: temporary updates to clamp amplitude as well<commit_after>/*
* TI Voxel Lib component.
*
* Copyright (c) 2014 Texas Instruments Inc.
*/
#include "DarkPixFilter.h"
namespace Voxel
{
DarkPixFilter::DarkPixFilter(float aThrNear, float phThrNear, float aThrFar, float phThrFar): Filter("DarkPixFilter"), _aThrNear(aThrNear), _phThrNear(phThrNear), _aThrFar(aThrFar), _phThrFar(phThrFar)
{
_addParameters({
FilterParameterPtr(new FloatFilterParameter("aThrNear", "aThrNear", "NearAmpThr", _aThrNear, "", 0.0f, 4095.0f)),
FilterParameterPtr(new FloatFilterParameter("phThrNear", "phThrNear", "NearPhThr", _phThrNear, "", 0.0f, 4095.0f)),
FilterParameterPtr(new FloatFilterParameter("aThrFar", "aThrFar", "FarAmpThr", _aThrFar, "", 0.0f, 4095.0f)),
FilterParameterPtr(new FloatFilterParameter("phThrFar", "phThrFar", "FarPhThr", _phThrFar, "", 0.0f, 4095.0f))
});
}
void DarkPixFilter::_onSet(const FilterParameterPtr &f)
{
if(f->name() == "aThrNear")
{
if(!_get(f->name(), _aThrNear))
{
logger(LOG_WARNING) << "DarkPixFilter: Could not get the recently updated 'aThrNear' parameter" << std::endl;
}
}
else if(f->name() == "phThrNear")
{
if(!_get(f->name(), _phThrNear))
{
logger(LOG_WARNING) << "DarkPixFilter: Could not get the recently updated 'phThrNear' parameter" << std::endl;
}
}
else if(f->name() == "aThrFar")
{
if(!_get(f->name(), _aThrFar))
{
logger(LOG_WARNING) << "DarkPixFilter: Could not get the recently updated 'aThrFar' parameter" << std::endl;
}
}
else if(f->name() == "phThrFar")
{
if(!_get(f->name(), _phThrFar))
{
logger(LOG_WARNING) << "DarkPixFilter: Could not get the recently updated 'phThrFar' parameter" << std::endl;
}
}
}
void DarkPixFilter::reset()
{
_current.clear();
}
template <typename T>
bool DarkPixFilter::_filter(const T *in, T *out)
{
uint s = _size.width*_size.height;
for(auto i = 0; i < s; i++)
out[i] = in[i];
return true;
}
template <typename T, typename T2>
bool DarkPixFilter::_filter2(const T *in, T2 *amp, T *out)
{
uint s = _size.width*_size.height;
for (auto p = 0; p < s; p++)
{
if ( ((amp[p] < _aThrNear) && (in[p] < _phThrNear)) || ((amp[p] > _aThrFar) && (in[p] > _phThrFar)) )
out[p] = 0;
else
out[p] = in[p];
}
return true;
}
bool DarkPixFilter::_filter(const FramePtr &in, FramePtr &out)
{
ToFRawFrame *tofFrame = dynamic_cast<ToFRawFrame *>(in.get());
DepthFrame *depthFrame = dynamic_cast<DepthFrame *>(in.get());
if((!tofFrame && !depthFrame) || !_prepareOutput(in, out))
{
logger(LOG_ERROR) << "DarkPixFilter: Input frame type is not ToFRawFrame or DepthFrame or failed get the output ready" << std::endl;
return false;
}
if(tofFrame)
{
_size = tofFrame->size;
ToFRawFrame *o = dynamic_cast<ToFRawFrame *>(out.get());
if(!o)
{
logger(LOG_ERROR) << "DarkPixFilter: Invalid frame type. Expecting ToFRawFrame." << std::endl;
return false;
}
//logger(LOG_INFO) << "DarkPixFilter: Applying filter with aThr = " << _aThr << " and phThr = " << _phThr << std::endl;
uint s = _size.width*_size.height;
memcpy(o->ambient(), tofFrame->ambient(), s*tofFrame->ambientWordWidth());
//memcpy(o->amplitude(), tofFrame->amplitude(), s*tofFrame->amplitudeWordWidth());
memcpy(o->flags(), tofFrame->flags(), s*tofFrame->flagsWordWidth());
if(tofFrame->phaseWordWidth() == 2)
{
if(tofFrame->amplitudeWordWidth() == 1)
return _filter2<uint16_t, uint8_t>((uint16_t *)tofFrame->phase(), (uint8_t *)tofFrame->amplitude(), (uint16_t *)o->phase());
else if(tofFrame->amplitudeWordWidth() == 2) {
_filter2<uint16_t, uint16_t>((uint16_t *)tofFrame->amplitude(), (uint16_t *)tofFrame->amplitude(), (uint16_t *)o->amplitude());
return _filter2<uint16_t, uint16_t>((uint16_t *)tofFrame->phase(), (uint16_t *)tofFrame->amplitude(), (uint16_t *)o->phase());
}
else if(tofFrame->amplitudeWordWidth() == 4)
return _filter2<uint16_t, uint32_t>((uint16_t *)tofFrame->phase(), (uint32_t *)tofFrame->amplitude(), (uint16_t *)o->phase());
}
else if(tofFrame->phaseWordWidth() == 1)
{
if(tofFrame->amplitudeWordWidth() == 1)
return _filter2<uint8_t, uint8_t>((uint8_t *)tofFrame->phase(), (uint8_t *)tofFrame->amplitude(), (uint8_t *)o->phase());
else if(tofFrame->amplitudeWordWidth() == 2)
return _filter2<uint8_t, uint16_t>((uint8_t *)tofFrame->phase(), (uint16_t *)tofFrame->amplitude(), (uint8_t *)o->phase());
else if(tofFrame->amplitudeWordWidth() == 4)
return _filter2<uint8_t, uint32_t>((uint8_t *)tofFrame->phase(), (uint32_t *)tofFrame->amplitude(), (uint8_t *)o->phase());
}
else if(tofFrame->phaseWordWidth() == 4)
{
if(tofFrame->amplitudeWordWidth() == 1)
return _filter2<uint32_t, uint8_t>((uint32_t *)tofFrame->phase(), (uint8_t *)tofFrame->amplitude(), (uint32_t *)o->phase());
else if(tofFrame->amplitudeWordWidth() == 2) {
return _filter2<uint32_t, uint16_t>((uint32_t *)tofFrame->phase(), (uint16_t *)tofFrame->amplitude(), (uint32_t *)o->phase());
}
else if(tofFrame->amplitudeWordWidth() == 4)
return _filter2<uint32_t, uint32_t>((uint32_t *)tofFrame->phase(), (uint32_t *)tofFrame->amplitude(), (uint32_t *)o->phase());
}
}
else if(depthFrame)
{
_size = depthFrame->size;
DepthFrame *o = dynamic_cast<DepthFrame *>(out.get());
if(!o)
{
logger(LOG_ERROR) << "DarkPixFilter: Invalid frame type. Expecting DepthFrame." << std::endl;
return false;
}
o->amplitude = depthFrame->amplitude;
return _filter<float>(depthFrame->depth.data(), o->depth.data());
}
else
return false;
}
}
<|endoftext|> |
<commit_before>#include <ticktack/benchmark.hpp>
#include <blackhole/detail/util/unique.hpp>
#include <blackhole/formatter/string.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/macro.hpp>
#include <blackhole/sink/null.hpp>
#include <blackhole/sink/stream.hpp>
#include "../util.hpp"
#define BH_BASE_LOG(__log__, ...) \
if (auto record = (__log__).open_record()) \
if (blackhole::aux::syntax_check(__VA_ARGS__)) \
blackhole::aux::logger::make_pusher((__log__), record, __VA_ARGS__)
#define BENCHMARK_BASELINE_X(...) void TT_CONCATENATE(f, __LINE__)()
#define BENCHMARK_RELATIVE_X(...) void TT_CONCATENATE(f, __LINE__)()
namespace { enum level_t { debug, info }; }
static const char MESSAGE_LONG[] = "Something bad is going on but I can handle it";
static const std::string FORMAT_BASE = "[%(timestamp)s]: %(message)s";
static const std::string FORMAT_VERBOSE = "[%(timestamp)s] [%(severity)s]: %(message)s";
BENCHMARK(LogStringToNull, Baseline) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::null_t
>(FORMAT_VERBOSE)()();
BH_LOG(log, level_t::info, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
BENCHMARK_BASELINE(Logger, Base) {
static auto log = initialize<
blackhole::logger_base_t,
blackhole::formatter::string_t,
blackhole::sink::null_t
>(FORMAT_BASE)()();
BH_BASE_LOG(log, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
BENCHMARK_RELATIVE(Logger, Verbose) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::null_t
>(FORMAT_VERBOSE)()();
BH_LOG(log, level_t::info, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
BENCHMARK_BASELINE_X(Limits, Practical) {
static const char MESSAGE[] = "[1412592701.561182] [0]: Something bad is going on but I can handle it";
std::cout << MESSAGE << std::endl;
}
BENCHMARK_RELATIVE_X(Limits, Experimental) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::stream_t
>(FORMAT_VERBOSE)(blackhole::sink::stream_t::output_t::stdout)();
BH_LOG(log, level_t::info, MESSAGE_LONG);
}
namespace filter_by {
void verbosity(blackhole::verbose_logger_t<level_t>& log, level_t level) {
log.set_filter(blackhole::keyword::severity<level_t>() >= level);
}
} // namespace filter_by
BENCHMARK_BASELINE(Filtering, Rejected) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::null_t
>(FORMAT_BASE)()(std::bind(&filter_by::verbosity, std::placeholders::_1, level_t::info));
BH_LOG(log, level_t::debug, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
BENCHMARK_RELATIVE(Filtering, Accepted) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::null_t
>(FORMAT_BASE)()(std::bind(&filter_by::verbosity, std::placeholders::_1, level_t::info));
BH_LOG(log, level_t::info, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
<commit_msg>[GCC 4.4] Fix warnings on some ancient compilers.<commit_after>#include <ticktack/benchmark.hpp>
#include <blackhole/detail/util/unique.hpp>
#include <blackhole/formatter/string.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/macro.hpp>
#include <blackhole/sink/null.hpp>
#include <blackhole/sink/stream.hpp>
#include "../util.hpp"
#define BH_BASE_LOG(__log__, ...) \
if (auto record = (__log__).open_record()) \
if (blackhole::aux::syntax_check(__VA_ARGS__)) \
blackhole::aux::logger::make_pusher((__log__), record, __VA_ARGS__)
#define BENCHMARK_BASELINE_X(...) void TT_CONCATENATE(f, __LINE__)()
#define BENCHMARK_RELATIVE_X(...) void TT_CONCATENATE(f, __LINE__)()
namespace { enum level_t { debug, info }; }
#define MESSAGE_LONG "Something bad is going on but I can handle it"
static const std::string FORMAT_BASE = "[%(timestamp)s]: %(message)s";
static const std::string FORMAT_VERBOSE = "[%(timestamp)s] [%(severity)s]: %(message)s";
BENCHMARK(LogStringToNull, Baseline) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::null_t
>(FORMAT_VERBOSE)()();
BH_LOG(log, level_t::info, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
BENCHMARK_BASELINE(Logger, Base) {
static auto log = initialize<
blackhole::logger_base_t,
blackhole::formatter::string_t,
blackhole::sink::null_t
>(FORMAT_BASE)()();
BH_BASE_LOG(log, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
BENCHMARK_RELATIVE(Logger, Verbose) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::null_t
>(FORMAT_VERBOSE)()();
BH_LOG(log, level_t::info, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
BENCHMARK_BASELINE_X(Limits, Practical) {
static const char MESSAGE[] = "[1412592701.561182] [0]: Something bad is going on but I can handle it";
std::cout << MESSAGE << std::endl;
}
BENCHMARK_RELATIVE_X(Limits, Experimental) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::stream_t
>(FORMAT_VERBOSE)(blackhole::sink::stream_t::output_t::stdout)();
BH_LOG(log, level_t::info, MESSAGE_LONG);
}
namespace filter_by {
void verbosity(blackhole::verbose_logger_t<level_t>& log, level_t level) {
log.set_filter(blackhole::keyword::severity<level_t>() >= level);
}
} // namespace filter_by
BENCHMARK_BASELINE(Filtering, Rejected) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::null_t
>(FORMAT_BASE)()(std::bind(&filter_by::verbosity, std::placeholders::_1, level_t::info));
BH_LOG(log, level_t::debug, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
BENCHMARK_RELATIVE(Filtering, Accepted) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::null_t
>(FORMAT_BASE)()(std::bind(&filter_by::verbosity, std::placeholders::_1, level_t::info));
BH_LOG(log, level_t::info, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
<|endoftext|> |
<commit_before>#include <ticktack/benchmark.hpp>
#include <blackhole/detail/util/unique.hpp>
#include <blackhole/formatter/string.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/macro.hpp>
#include <blackhole/sink/null.hpp>
namespace { enum level_t { info }; }
namespace {
static const char FORMAT[] = "[%(timestamp)s]: %(message)s";
static const char DEFAULT_FORMAT[] = "[%(timestamp)s] [%(severity)s]: %(message)s";
static const char MESSAGE_LONG[] = "Something bad is going on but I can handle it";
template<class Log>
Log
initialize(const std::string& format = DEFAULT_FORMAT) {
auto formatter = blackhole::aux::util::make_unique<
blackhole::formatter::string_t
>(format);
auto sink = blackhole::aux::util::make_unique<
blackhole::sink::null_t
>();
auto frontend = blackhole::aux::util::make_unique<
blackhole::frontend_t<
blackhole::formatter::string_t,
blackhole::sink::null_t
>
>(std::move(formatter), std::move(sink));
Log log;
log.add_frontend(std::move(frontend));
return log;
}
} // namespace
#define BH_BASE_LOG(__log__, ...) \
if (auto record = (__log__).open_record()) \
if (blackhole::aux::syntax_check(__VA_ARGS__)) \
blackhole::aux::logger::make_pusher((__log__), record, __VA_ARGS__)
BENCHMARK(LogStringToNull, Baseline) {
static auto log = initialize<blackhole::verbose_logger_t<level_t>>();
BH_LOG(log, level_t::info, MESSAGE_LONG)(
"answer", 42,
"string", "le string"
);
}
BENCHMARK_BASELINE(Logger, Base) {
static auto log = initialize<blackhole::logger_base_t>(FORMAT);
BH_BASE_LOG(log, MESSAGE_LONG)(
"answer", 42,
"string", "le string"
);
}
BENCHMARK_RELATIVE(Logger, Verbose) {
static auto log = initialize<blackhole::verbose_logger_t<level_t>>(FORMAT);
BH_LOG(log, level_t::info, MESSAGE_LONG)(
"answer", 42,
"string", "le string"
);
}
<commit_msg>[Benchmarking] Added tests with theoretical limits.<commit_after>#include <ticktack/benchmark.hpp>
#include <blackhole/detail/util/unique.hpp>
#include <blackhole/formatter/string.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/macro.hpp>
#include <blackhole/sink/null.hpp>
#include <blackhole/sink/stream.hpp>
#define BENCHMARK_BASELINE_X(...) void TT_CONCATENATE(f, __LINE__)()
#define BENCHMARK_RELATIVE_X(...) void TT_CONCATENATE(f, __LINE__)()
namespace { enum level_t { info }; }
namespace {
static const char FORMAT[] = "[%(timestamp)s]: %(message)s";
static const char DEFAULT_FORMAT[] = "[%(timestamp)s] [%(severity)s]: %(message)s";
static const char MESSAGE_LONG[] = "Something bad is going on but I can handle it";
template<class Log>
Log
initialize(const std::string& format = DEFAULT_FORMAT) {
auto formatter = blackhole::aux::util::make_unique<
blackhole::formatter::string_t
>(format);
auto sink = blackhole::aux::util::make_unique<
blackhole::sink::null_t
>();
auto frontend = blackhole::aux::util::make_unique<
blackhole::frontend_t<
blackhole::formatter::string_t,
blackhole::sink::null_t
>
>(std::move(formatter), std::move(sink));
Log log;
log.add_frontend(std::move(frontend));
return log;
}
template<class L, class F, class S>
struct initializer_t {
std::unique_ptr<F> f;
template<class... Args>
L operator()(Args&&... args) {
auto sink = blackhole::aux::util::make_unique<
S
>(std::forward<Args>(args)...);
auto frontend = blackhole::aux::util::make_unique<
blackhole::frontend_t<F, S>
>(std::move(f), std::move(sink));
L log;
log.add_frontend(std::move(frontend));
return log;
}
};
template<class L, class F, class S, class... Args>
initializer_t<L, F, S>
initialize(Args&&... args) {
auto formatter = blackhole::aux::util::make_unique<
F
>(std::forward<Args>(args)...);
return initializer_t<L, F, S> { std::move(formatter) };
}
} // namespace
#define BH_BASE_LOG(__log__, ...) \
if (auto record = (__log__).open_record()) \
if (blackhole::aux::syntax_check(__VA_ARGS__)) \
blackhole::aux::logger::make_pusher((__log__), record, __VA_ARGS__)
BENCHMARK(LogStringToNull, Baseline) {
static auto log = initialize<blackhole::verbose_logger_t<level_t>>();
BH_LOG(log, level_t::info, MESSAGE_LONG)(
"answer", 42,
"string", "le string"
);
}
BENCHMARK_BASELINE(Logger, Base) {
static auto log = initialize<blackhole::logger_base_t>(FORMAT);
BH_BASE_LOG(log, MESSAGE_LONG)(
"answer", 42,
"string", "le string"
);
}
BENCHMARK_RELATIVE(Logger, Verbose) {
static auto log = initialize<blackhole::verbose_logger_t<level_t>>(FORMAT);
BH_LOG(log, level_t::info, MESSAGE_LONG)(
"answer", 42,
"string", "le string"
);
}
BENCHMARK_BASELINE_X(Limits, Practical) {
static const char MESSAGE[] = "[1412592701.561182]: Something bad is going on but I can handle it";
std::cout << MESSAGE << std::endl;
}
BENCHMARK_RELATIVE_X(Limits, Experimental) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::stream_t
>(FORMAT)(blackhole::sink::stream_t::output_t::stdout);
BH_LOG(log, level_t::info, MESSAGE_LONG);
}
<|endoftext|> |
<commit_before>#pragma once
// pqrs::osx::process_info v1.1
// (C) Copyright Takayama Fumihiko 2020.
// Distributed under the Boost Software License, Version 1.0.
// (See http://www.boost.org/LICENSE_1_0.txt)
// `pqrs::osx::process_info` can be used safely in a multi-threaded environment.
#include "process_info/objc.h"
#include <pqrs/cf/string.hpp>
namespace pqrs {
namespace osx {
namespace process_info {
inline std::string globally_unique_string(void) {
char buffer[256];
pqrs_osx_process_info_create_globally_unique_string(buffer, sizeof(buffer));
return buffer;
}
inline int process_identifier(void) {
return pqrs_osx_process_info_process_identifier();
}
void disable_sudden_termination(void) {
pqrs_osx_process_info_disable_sudden_termination();
}
void enable_sudden_termination(void) {
pqrs_osx_process_info_enable_sudden_termination();
}
} // namespace process_info
} // namespace osx
} // namespace pqrs
<commit_msg>Update vendor/cget<commit_after>#pragma once
// pqrs::osx::process_info v1.2
// (C) Copyright Takayama Fumihiko 2020.
// Distributed under the Boost Software License, Version 1.0.
// (See http://www.boost.org/LICENSE_1_0.txt)
// `pqrs::osx::process_info` can be used safely in a multi-threaded environment.
#include "process_info/objc.h"
#include <pqrs/cf/string.hpp>
namespace pqrs {
namespace osx {
namespace process_info {
inline std::string globally_unique_string(void) {
char buffer[256];
pqrs_osx_process_info_create_globally_unique_string(buffer, sizeof(buffer));
return buffer;
}
inline int process_identifier(void) {
return pqrs_osx_process_info_process_identifier();
}
void disable_sudden_termination(void) {
pqrs_osx_process_info_disable_sudden_termination();
}
void enable_sudden_termination(void) {
pqrs_osx_process_info_enable_sudden_termination();
}
class scoped_sudden_termination_blocker final {
public:
scoped_sudden_termination_blocker(void) {
disable_sudden_termination();
}
~scoped_sudden_termination_blocker(void) {
enable_sudden_termination();
}
};
} // namespace process_info
} // namespace osx
} // namespace pqrs
<|endoftext|> |
<commit_before><?hh //strict
/**
* This file is part of hhpack\typesafety package.
*
* (c) Noritaka Horio <holy.shared.design@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace hhpack\typesafety;
use hhpack\typechecker\TypeCheckerClient;
final class Application
{
public async function run(Context $context) : Awaitable<void>
{
$context->started();
$client = new TypeCheckerClient( $context->rootDirectory() );
await $client->init();
await $client->restart();
$result = await $client->check();
$context->finish();
$context->report($result);
$context->terminated($result);
}
}
<commit_msg><commit_after><?hh //strict
/**
* This file is part of hhpack\typesafety package.
*
* (c) Noritaka Horio <holy.shared.design@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace hhpack\typesafety;
use hhpack\typechecker\TypeCheckerClient;
final class Application
{
public async function run(Context $context) : Awaitable<void>
{
$context->started();
$client = new TypeCheckerClient( $context->rootDirectory() );
// await $client->init();
// await $client->restart();
$result = await $client->check();
$context->finish();
$context->report($result);
$context->terminated($result);
}
}
<|endoftext|> |
<commit_before>//MIT License
//Copyright(c) 2016 Patrick Laughrea
#include "utilsNumbers.h"
#include "utilsSweepers.h"
#include <cmath>
using namespace std;
using namespace webss;
#define FUNCTIONS_BIN [&]() { return isDigitBin(*it); }, [&]() { return binToInt(*it); }
#define FUNCTIONS_DEC [&]() { return isDigit(*it); }, [&]() { return charToInt(*it); }
#define FUNCTIONS_HEX [&]() { return isDigitHex(*it); }, [&]() { return hexToInt(*it); }
WebssInt getNumber(SmartIterator& it, NumberMagnitude mag, function<bool()> func1, function<int()> func2)
{
WebssInt number = func2();
while (skipLineJunk(++it) && func1())
number = number * mag + func2();
return number;
}
double checkDecimals(SmartIterator& it, NumberMagnitude mag, function<bool()> func1, function<int()> func2)
{
double numDouble = 0;
int decimalMultiplier = 1;
if (!func1())
throw runtime_error(ERROR_EXPECTED_NUMBER);
do
numDouble += (double)func2() / (decimalMultiplier *= mag);
while (skipLineJunk(++it) && func1());
return numDouble;
}
WebssInt webss::getNumberBin(SmartIterator& it) { return getNumber(it, MAGNITUDE_BIN, FUNCTIONS_BIN); }
WebssInt webss::getNumberDec(SmartIterator& it) { return getNumber(it, MAGNITUDE_DEC, FUNCTIONS_DEC); }
WebssInt webss::getNumberHex(SmartIterator& it) { return getNumber(it, MAGNITUDE_HEX, FUNCTIONS_HEX); }
double webss::getDecimals(SmartIterator& it, NumberMagnitude mag)
{
switch (mag)
{
case MAGNITUDE_BIN:
return checkDecimals(it, mag, FUNCTIONS_BIN);
case MAGNITUDE_DEC:
return checkDecimals(it, mag, FUNCTIONS_DEC);
case MAGNITUDE_HEX:
return checkDecimals(it, mag, FUNCTIONS_HEX);
default:
throw domain_error(ERROR_UNDEFINED);
}
}
double webss::addNumberMagnitude(SmartIterator& it, double num, NumberMagnitude mag)
{
bool negative = checkNumberStart(it);
auto numMagnitude = getNumberDec(it);
return num *= pow((double)mag, (double)(negative ? -numMagnitude : numMagnitude));
}
bool webss::checkNumberStart(SmartIterator& it)
{
bool negative = *it == '-';
if ((negative || *it == '+') && (!skipLineJunk(++it) || !isDigit(*it)))
throw runtime_error(ERROR_EXPECTED_NUMBER);
return negative;
}
<commit_msg>Update utilsNumbers.cpp<commit_after>//MIT License
//Copyright(c) 2016 Patrick Laughrea
#include "utilsNumbers.h"
#include "utilsSweepers.h"
#include <cmath>
using namespace std;
using namespace webss;
#define FUNCTIONS_BIN isDigitBin(c), binToInt(c)
#define FUNCTIONS_DEC isDigit(c), charToInt(c)
#define FUNCTIONS_HEX isDigitHex(c), hexToInt(c)
WebssInt getNumber(SmartIterator& it, NumberMagnitude mag, bool(*isDigit)(char c), int(*charToInt)(char c))
{
WebssInt number = charToInt(*it);
while (skipLineJunk(++it) && isDigit(*it))
number = number * mag + charToInt(*it);
return number;
}
double checkDecimals(SmartIterator& it, NumberMagnitude mag, bool(*isDigit)(char c), int(*charToInt)(char c))
{
double numDouble = 0;
int decimalMultiplier = 1;
if (!isDigit(*it))
throw runtime_error(ERROR_EXPECTED_NUMBER);
do
numDouble += (double)charToInt(*it) / (decimalMultiplier *= mag);
while (skipLineJunk(++it) && isDigit(*it));
return numDouble;
}
WebssInt webss::getNumberBin(SmartIterator& it) { return getNumber(it, MAGNITUDE_BIN, FUNCTIONS_BIN); }
WebssInt webss::getNumberDec(SmartIterator& it) { return getNumber(it, MAGNITUDE_DEC, FUNCTIONS_DEC); }
WebssInt webss::getNumberHex(SmartIterator& it) { return getNumber(it, MAGNITUDE_HEX, FUNCTIONS_HEX); }
double webss::getDecimals(SmartIterator& it, NumberMagnitude mag)
{
switch (mag)
{
case MAGNITUDE_BIN:
return checkDecimals(it, mag, FUNCTIONS_BIN);
case MAGNITUDE_DEC:
return checkDecimals(it, mag, FUNCTIONS_DEC);
case MAGNITUDE_HEX:
return checkDecimals(it, mag, FUNCTIONS_HEX);
default:
throw domain_error(ERROR_UNDEFINED);
}
}
double webss::addNumberMagnitude(SmartIterator& it, double num, NumberMagnitude mag)
{
bool negative = checkNumberStart(it);
auto numMagnitude = getNumberDec(it);
return num *= pow((double)mag, (double)(negative ? -numMagnitude : numMagnitude));
}
bool webss::checkNumberStart(SmartIterator& it)
{
bool negative = *it == '-';
if ((negative || *it == '+') && (!skipLineJunk(++it) || !isDigit(*it)))
throw runtime_error(ERROR_EXPECTED_NUMBER);
return negative;
}
<|endoftext|> |
<commit_before>#include "offeracceptdialogbtc.h"
#include "ui_offeracceptdialogbtc.h"
#include "init.h"
#include "util.h"
#include "offerpaydialog.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "platformstyle.h"
#include "syscoingui.h"
#include <QMessageBox>
#include "rpcserver.h"
#include "pubkey.h"
#include "wallet/wallet.h"
#include "main.h"
#include <QDesktopServices>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
#include <QPixmap>
#if defined(HAVE_CONFIG_H)
#include "config/syscoin-config.h" /* for USE_QRCODE */
#endif
#ifdef USE_QRCODE
#include <qrencode.h>
#endif
using namespace std;
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
extern const CRPCTable tableRPC;
OfferAcceptDialogBTC::OfferAcceptDialogBTC(const PlatformStyle *platformStyle, QString alias, QString offer, QString quantity, QString notes, QString title, QString currencyCode, QString qstrPrice, QString sellerAlias, QString address, QWidget *parent) :
QDialog(parent),
ui(new Ui::OfferAcceptDialogBTC), platformStyle(platformStyle), alias(alias), offer(offer), notes(notes), quantity(quantity), title(title), sellerAlias(sellerAlias), address(address)
{
ui->setupUi(this);
QString theme = GUIUtil::getThemeName();
ui->aboutShadeBTC->setPixmap(QPixmap(":/images/" + theme + "/about_btc"));
double dblPrice = qstrPrice.toDouble()*quantity.toUInt();
string strfPrice = strprintf("%f", dblPrice);
QString fprice = QString::fromStdString(strfPrice);
string strCurrencyCode = currencyCode.toStdString();
ui->escrowDisclaimer->setText(tr("<font color='blue'>Please note escrow is not available since you are paying in BTC, only SYS payments can be escrowed. </font>"));
ui->bitcoinInstructionLabel->setText(tr("After paying for this item, please enter the Bitcoin Transaction ID and click on the confirm button below. You may use the QR Code to the left to scan the payment request into your wallet or click on the Open BTC Wallet if you are on the desktop and have Bitcoin Core installed."));
ui->acceptMessage->setText(tr("Are you sure you want to purchase %1 of '%2' from merchant: '%3'? To complete your purchase please pay %4 BTC using your Bitcoin wallet.").arg(quantity).arg(title).arg(sellerAlias).arg(fprice));
string strPrice = strprintf("%f", dblPrice);
price = QString::fromStdString(strPrice);
if (!platformStyle->getImagesOnButtons())
{
ui->confirmButton->setIcon(QIcon());
ui->openBtcWalletButton->setIcon(QIcon());
ui->cancelButton->setIcon(QIcon());
}
else
{
ui->confirmButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/transaction_confirmed"));
ui->openBtcWalletButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/send"));
ui->cancelButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/quit"));
}
this->offerPaid = false;
connect(ui->confirmButton, SIGNAL(clicked()), this, SLOT(acceptPayment()));
connect(ui->openBtcWalletButton, SIGNAL(clicked()), this, SLOT(openBTCWallet()));
#ifdef USE_QRCODE
QString message = "Payment for offer ID " + this->offer + " on Syscoin Decentralized Marketplace";
QString uri = "bitcoin:" + this->address + "?amount=" + price + "&label=" + this->sellerAlias + "&message=" + GUIUtil::HtmlEscape(message);
ui->lblQRCode->setText("");
if(!uri.isEmpty())
{
// limit URI length
if (uri.length() > MAX_URI_LENGTH)
{
ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
} else {
QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
if (!code)
{
ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
return;
}
QImage myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
myImage.fill(0xffffff);
unsigned char *p = code->data;
for (int y = 0; y < code->width; y++)
{
for (int x = 0; x < code->width; x++)
{
myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
p++;
}
}
QRcode_free(code);
ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(128, 128));
}
}
#endif
}
void OfferAcceptDialogBTC::on_cancelButton_clicked()
{
reject();
}
OfferAcceptDialogBTC::~OfferAcceptDialogBTC()
{
delete ui;
}
void OfferAcceptDialogBTC::acceptPayment()
{
acceptOffer();
}
bool OfferAcceptDialogBTC::CheckPaymentInBTC(const QString &strBTCTxId, const QString& address, const QString& price)
{
LogPrintf("CheckPaymentInBTC\n");
LogPrintf("QNetworkAccessManager\n");
QNetworkAccessManager *nam = new QNetworkAccessManager(this);
QUrl url("https://blockchain.info/tx/" strBTCTxId.toStdString() + "?format=json");
QNetworkReply* reply = nam->get(QNetworkRequest(url));
reply->ignoreSslErrors();
double totalTime = 0;
while(!reply->isFinished())
{
totalTime += 1;
MilliSleep(1000);
if(totalTime > 30)
throw runtime_error("Timeout connecting to blockchain.info!");
}
if(reply->error() == QNetworkReply::NoError) {
LogPrintf("response: %s\n", reply->readAll().toStdString().c_str());
UniValue outerValue(UniValue::VSTR);
bool read = outerValue.read(reply->readAll().toStdString());
if (read)
{
LogPrintf("gotjson!\n");
UniValue outerObj = outerValue.get_obj();
UniValue ratesValue = find_value(outerObj, "rates");
if (ratesValue.isArray())
{
}
}
}
delete reply;
return false;
}
bool OfferAcceptDialogBTC::lookup(const QString &lookupid, QString& address, QString& price)
{
string strError;
string strMethod = string("offerinfo");
UniValue params(UniValue::VARR);
UniValue result;
params.push_back(lookupid.toStdString());
try {
result = tableRPC.execute(strMethod, params);
if (result.type() == UniValue::VOBJ)
{
const UniValue &offerObj = result.get_obj();
const string &strAddress = find_value(offerObj, "address").get_str();
const string &strPrice = find_value(offerObj, "price").get_str();
address = QString(strAddress);
price = QString(strPrice);
return true;
}
}
catch (UniValue& objError)
{
QMessageBox::critical(this, windowTitle(),
tr("Could not find this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + lookupid,
QMessageBox::Ok, QMessageBox::Ok);
return true;
}
catch(std::exception& e)
{
QMessageBox::critical(this, windowTitle(),
tr("There was an exception trying to locate this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + QString::fromStdString(e.what()),
QMessageBox::Ok, QMessageBox::Ok);
return true;
}
return false;
}
// send offeraccept with offer guid/qty as params and then send offerpay with wtxid (first param of response) as param, using RPC commands.
void OfferAcceptDialogBTC::acceptOffer()
{
QString address, price;
if (ui->btctxidEdit->text().trimmed().isEmpty()) {
ui->btctxidEdit->setText("");
QMessageBox::information(this, windowTitle(),
tr("Please enter a valid Bitcoin Transaction ID into the input box and try again"),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
if(!lookup(this->offer, address, price))
{
QMessageBox::information(this, windowTitle(),
tr("Could not find this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + this->offer,
QMessageBox::Ok, QMessageBox::Ok);
return;
}
if(!CheckPaymentInBTC(ui->btctxidEdit->text().trimmed(), address, price))
{
QMessageBox::information(this, windowTitle(),
tr("Could not find this payment, please check the Transaction ID and that it has been confirmed by the Bitcoin blockchain: ") + ui->btctxidEdit->text().trimmed(),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
UniValue params(UniValue::VARR);
UniValue valError;
UniValue valResult;
UniValue valId;
UniValue result ;
string strReply;
string strError;
string strMethod = string("offeraccept");
if(this->quantity.toLong() <= 0)
{
QMessageBox::critical(this, windowTitle(),
tr("Invalid quantity when trying to accept offer!"),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
this->offerPaid = false;
params.push_back(this->alias.toStdString());
params.push_back(this->offer.toStdString());
params.push_back(this->quantity.toStdString());
params.push_back(this->notes.toStdString());
params.push_back(ui->btctxidEdit->text().toStdString());
try {
result = tableRPC.execute(strMethod, params);
if (result.type() != UniValue::VNULL)
{
const UniValue &arr = result.get_array();
string strResult = arr[0].get_str();
QString offerAcceptTXID = QString::fromStdString(strResult);
if(offerAcceptTXID != QString(""))
{
OfferPayDialog dlg(platformStyle, this->title, this->quantity, this->price, "BTC", this);
dlg.exec();
this->offerPaid = true;
OfferAcceptDialogBTC::accept();
return;
}
}
}
catch (UniValue& objError)
{
strError = find_value(objError, "message").get_str();
QMessageBox::critical(this, windowTitle(),
tr("Error accepting offer: \"%1\"").arg(QString::fromStdString(strError)),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
catch(std::exception& e)
{
QMessageBox::critical(this, windowTitle(),
tr("General exception when accepting offer"),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
}
void OfferAcceptDialogBTC::openBTCWallet()
{
QString message = "Payment for offer ID " + this->offer + " on Syscoin Decentralized Marketplace";
QString uri = "bitcoin:" + this->address + "?amount=" + price + "&label=" + this->sellerAlias + "&message=" + GUIUtil::HtmlEscape(message);
QDesktopServices::openUrl(QUrl(uri, QUrl::TolerantMode));
}
bool OfferAcceptDialogBTC::getPaymentStatus()
{
return this->offerPaid;
}
<commit_msg>typo<commit_after>#include "offeracceptdialogbtc.h"
#include "ui_offeracceptdialogbtc.h"
#include "init.h"
#include "util.h"
#include "offerpaydialog.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "platformstyle.h"
#include "syscoingui.h"
#include <QMessageBox>
#include "rpcserver.h"
#include "pubkey.h"
#include "wallet/wallet.h"
#include "main.h"
#include <QDesktopServices>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
#include <QPixmap>
#if defined(HAVE_CONFIG_H)
#include "config/syscoin-config.h" /* for USE_QRCODE */
#endif
#ifdef USE_QRCODE
#include <qrencode.h>
#endif
using namespace std;
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
extern const CRPCTable tableRPC;
OfferAcceptDialogBTC::OfferAcceptDialogBTC(const PlatformStyle *platformStyle, QString alias, QString offer, QString quantity, QString notes, QString title, QString currencyCode, QString qstrPrice, QString sellerAlias, QString address, QWidget *parent) :
QDialog(parent),
ui(new Ui::OfferAcceptDialogBTC), platformStyle(platformStyle), alias(alias), offer(offer), notes(notes), quantity(quantity), title(title), sellerAlias(sellerAlias), address(address)
{
ui->setupUi(this);
QString theme = GUIUtil::getThemeName();
ui->aboutShadeBTC->setPixmap(QPixmap(":/images/" + theme + "/about_btc"));
double dblPrice = qstrPrice.toDouble()*quantity.toUInt();
string strfPrice = strprintf("%f", dblPrice);
QString fprice = QString::fromStdString(strfPrice);
string strCurrencyCode = currencyCode.toStdString();
ui->escrowDisclaimer->setText(tr("<font color='blue'>Please note escrow is not available since you are paying in BTC, only SYS payments can be escrowed. </font>"));
ui->bitcoinInstructionLabel->setText(tr("After paying for this item, please enter the Bitcoin Transaction ID and click on the confirm button below. You may use the QR Code to the left to scan the payment request into your wallet or click on the Open BTC Wallet if you are on the desktop and have Bitcoin Core installed."));
ui->acceptMessage->setText(tr("Are you sure you want to purchase %1 of '%2' from merchant: '%3'? To complete your purchase please pay %4 BTC using your Bitcoin wallet.").arg(quantity).arg(title).arg(sellerAlias).arg(fprice));
string strPrice = strprintf("%f", dblPrice);
price = QString::fromStdString(strPrice);
if (!platformStyle->getImagesOnButtons())
{
ui->confirmButton->setIcon(QIcon());
ui->openBtcWalletButton->setIcon(QIcon());
ui->cancelButton->setIcon(QIcon());
}
else
{
ui->confirmButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/transaction_confirmed"));
ui->openBtcWalletButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/send"));
ui->cancelButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/quit"));
}
this->offerPaid = false;
connect(ui->confirmButton, SIGNAL(clicked()), this, SLOT(acceptPayment()));
connect(ui->openBtcWalletButton, SIGNAL(clicked()), this, SLOT(openBTCWallet()));
#ifdef USE_QRCODE
QString message = "Payment for offer ID " + this->offer + " on Syscoin Decentralized Marketplace";
QString uri = "bitcoin:" + this->address + "?amount=" + price + "&label=" + this->sellerAlias + "&message=" + GUIUtil::HtmlEscape(message);
ui->lblQRCode->setText("");
if(!uri.isEmpty())
{
// limit URI length
if (uri.length() > MAX_URI_LENGTH)
{
ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
} else {
QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
if (!code)
{
ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
return;
}
QImage myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
myImage.fill(0xffffff);
unsigned char *p = code->data;
for (int y = 0; y < code->width; y++)
{
for (int x = 0; x < code->width; x++)
{
myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
p++;
}
}
QRcode_free(code);
ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(128, 128));
}
}
#endif
}
void OfferAcceptDialogBTC::on_cancelButton_clicked()
{
reject();
}
OfferAcceptDialogBTC::~OfferAcceptDialogBTC()
{
delete ui;
}
void OfferAcceptDialogBTC::acceptPayment()
{
acceptOffer();
}
bool OfferAcceptDialogBTC::CheckPaymentInBTC(const QString &strBTCTxId, const QString& address, const QString& price)
{
LogPrintf("CheckPaymentInBTC\n");
LogPrintf("QNetworkAccessManager\n");
QNetworkAccessManager *nam = new QNetworkAccessManager(this);
QUrl url("https://blockchain.info/tx/" strBTCTxId.toStdString() + "?format=json");
QNetworkReply* reply = nam->get(QNetworkRequest(url));
reply->ignoreSslErrors();
double totalTime = 0;
while(!reply->isFinished())
{
totalTime += 1;
MilliSleep(1000);
if(totalTime > 30)
throw runtime_error("Timeout connecting to blockchain.info!");
}
if(reply->error() == QNetworkReply::NoError) {
LogPrintf("response: %s\n", reply->readAll().toStdString().c_str());
UniValue outerValue(UniValue::VSTR);
bool read = outerValue.read(reply->readAll().toStdString());
if (read)
{
LogPrintf("gotjson!\n");
UniValue outerObj = outerValue.get_obj();
UniValue ratesValue = find_value(outerObj, "rates");
if (ratesValue.isArray())
{
}
}
}
delete reply;
return false;
}
bool OfferAcceptDialogBTC::lookup(const QString &lookupid, QString& address, QString& price)
{
string strError;
string strMethod = string("offerinfo");
UniValue params(UniValue::VARR);
UniValue result;
params.push_back(lookupid.toStdString());
try {
result = tableRPC.execute(strMethod, params);
if (result.type() == UniValue::VOBJ)
{
const UniValue &offerObj = result.get_obj();
const string &strAddress = find_value(offerObj, "address").get_str();
const string &strPrice = find_value(offerObj, "price").get_str();
address = QString::fromStdString(strAddress);
price = QString::fromStdString(strPrice);
return true;
}
}
catch (UniValue& objError)
{
QMessageBox::critical(this, windowTitle(),
tr("Could not find this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + lookupid,
QMessageBox::Ok, QMessageBox::Ok);
return true;
}
catch(std::exception& e)
{
QMessageBox::critical(this, windowTitle(),
tr("There was an exception trying to locate this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + QString::fromStdString(e.what()),
QMessageBox::Ok, QMessageBox::Ok);
return true;
}
return false;
}
// send offeraccept with offer guid/qty as params and then send offerpay with wtxid (first param of response) as param, using RPC commands.
void OfferAcceptDialogBTC::acceptOffer()
{
QString address, price;
if (ui->btctxidEdit->text().trimmed().isEmpty()) {
ui->btctxidEdit->setText("");
QMessageBox::information(this, windowTitle(),
tr("Please enter a valid Bitcoin Transaction ID into the input box and try again"),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
if(!lookup(this->offer, address, price))
{
QMessageBox::information(this, windowTitle(),
tr("Could not find this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + this->offer,
QMessageBox::Ok, QMessageBox::Ok);
return;
}
if(!CheckPaymentInBTC(ui->btctxidEdit->text().trimmed(), address, price))
{
QMessageBox::information(this, windowTitle(),
tr("Could not find this payment, please check the Transaction ID and that it has been confirmed by the Bitcoin blockchain: ") + ui->btctxidEdit->text().trimmed(),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
UniValue params(UniValue::VARR);
UniValue valError;
UniValue valResult;
UniValue valId;
UniValue result ;
string strReply;
string strError;
string strMethod = string("offeraccept");
if(this->quantity.toLong() <= 0)
{
QMessageBox::critical(this, windowTitle(),
tr("Invalid quantity when trying to accept offer!"),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
this->offerPaid = false;
params.push_back(this->alias.toStdString());
params.push_back(this->offer.toStdString());
params.push_back(this->quantity.toStdString());
params.push_back(this->notes.toStdString());
params.push_back(ui->btctxidEdit->text().toStdString());
try {
result = tableRPC.execute(strMethod, params);
if (result.type() != UniValue::VNULL)
{
const UniValue &arr = result.get_array();
string strResult = arr[0].get_str();
QString offerAcceptTXID = QString::fromStdString(strResult);
if(offerAcceptTXID != QString(""))
{
OfferPayDialog dlg(platformStyle, this->title, this->quantity, this->price, "BTC", this);
dlg.exec();
this->offerPaid = true;
OfferAcceptDialogBTC::accept();
return;
}
}
}
catch (UniValue& objError)
{
strError = find_value(objError, "message").get_str();
QMessageBox::critical(this, windowTitle(),
tr("Error accepting offer: \"%1\"").arg(QString::fromStdString(strError)),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
catch(std::exception& e)
{
QMessageBox::critical(this, windowTitle(),
tr("General exception when accepting offer"),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
}
void OfferAcceptDialogBTC::openBTCWallet()
{
QString message = "Payment for offer ID " + this->offer + " on Syscoin Decentralized Marketplace";
QString uri = "bitcoin:" + this->address + "?amount=" + price + "&label=" + this->sellerAlias + "&message=" + GUIUtil::HtmlEscape(message);
QDesktopServices::openUrl(QUrl(uri, QUrl::TolerantMode));
}
bool OfferAcceptDialogBTC::getPaymentStatus()
{
return this->offerPaid;
}
<|endoftext|> |
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved
#ifndef RDB_PROTOCOL_REAL_TABLE_HPP_
#define RDB_PROTOCOL_REAL_TABLE_HPP_
#include <map>
#include <set>
#include <string>
#include <vector>
#include "rdb_protocol/context.hpp"
#include "rdb_protocol/protocol.hpp"
const char *const sindex_blob_prefix = "$reql_index_function$";
class datum_range_t;
namespace ql { namespace changefeed {
class client_t;
} }
/* `real_table_t` is a concrete subclass of `base_table_t` that routes its queries across
the network via the clustering logic to a B-tree. The administration logic is responsible
for constructing and returning them from `reql_cluster_interface_t::table_find()`. */
/* `namespace_interface_access_t` is like a smart pointer to a `namespace_interface_t`.
This is the format in which `real_table_t` expects to receive its
`namespace_interface_t *`. This allows the thing that is constructing the `real_table_t`
to control the lifetime of the `namespace_interface_t`, but also allows the
`real_table_t` to block it from being destroyed while in use. */
class namespace_interface_access_t {
public:
class ref_tracker_t {
public:
virtual void add_ref() = 0;
virtual void release() = 0;
protected:
virtual ~ref_tracker_t() { }
};
namespace_interface_access_t();
namespace_interface_access_t(namespace_interface_t *, ref_tracker_t *, threadnum_t);
namespace_interface_access_t(const namespace_interface_access_t &access);
namespace_interface_access_t &operator=(const namespace_interface_access_t &access);
~namespace_interface_access_t();
namespace_interface_t *get();
private:
namespace_interface_t *nif;
ref_tracker_t *ref_tracker;
threadnum_t thread;
};
class real_table_t :
public base_table_t
{
public:
/* This doesn't automatically wait for readiness. */
real_table_t(
namespace_id_t _uuid,
namespace_interface_access_t _namespace_access,
const std::string &_pkey,
ql::changefeed::client_t *_changefeed_client) :
uuid(_uuid), namespace_access(_namespace_access), pkey(_pkey),
changefeed_client(_changefeed_client) { }
const std::string &get_pkey();
counted_t<const ql::datum_t> read_row(ql::env_t *env,
counted_t<const ql::datum_t> pval, bool use_outdated);
counted_t<ql::datum_stream_t> read_all(
ql::env_t *env,
const std::string &sindex,
const ql::protob_t<const Backtrace> &bt,
const std::string &table_name, /* the table's own name, for display purposes */
const datum_range_t &range,
sorting_t sorting,
bool use_outdated);
counted_t<ql::datum_stream_t> read_row_changes(
ql::env_t *env,
counted_t<const ql::datum_t> pval,
const ql::protob_t<const Backtrace> &bt,
const std::string &table_name);
counted_t<ql::datum_stream_t> read_all_changes(
ql::env_t *env,
const ql::protob_t<const Backtrace> &bt,
const std::string &table_name);
counted_t<ql::datum_stream_t> read_intersecting(
ql::env_t *env,
const std::string &sindex,
const ql::protob_t<const Backtrace> &bt,
const std::string &table_name,
bool use_outdated,
const counted_t<const ql::datum_t> &query_geometry);
counted_t<ql::datum_stream_t> read_nearest(
ql::env_t *env,
const std::string &sindex,
const ql::protob_t<const Backtrace> &bt,
const std::string &table_name,
bool use_outdated,
lat_lon_point_t center,
double max_dist,
uint64_t max_results,
const ellipsoid_spec_t &geo_system,
dist_unit_t dist_unit,
const ql::configured_limits_t &limits);
counted_t<const ql::datum_t> write_batched_replace(ql::env_t *env,
const std::vector<counted_t<const ql::datum_t> > &keys,
const counted_t<const ql::func_t> &func,
return_changes_t _return_changes, durability_requirement_t durability);
counted_t<const ql::datum_t> write_batched_insert(ql::env_t *env,
std::vector<counted_t<const ql::datum_t> > &&inserts,
conflict_behavior_t conflict_behavior, return_changes_t return_changes,
durability_requirement_t durability);
bool write_sync_depending_on_durability(ql::env_t *env,
durability_requirement_t durability);
bool sindex_create(ql::env_t *env,
const std::string &id,
counted_t<const ql::func_t> index_func,
sindex_multi_bool_t multi,
sindex_geo_bool_t geo);
bool sindex_drop(ql::env_t *env,
const std::string &id);
sindex_rename_result_t sindex_rename(ql::env_t *env,
const std::string &old_name,
const std::string &new_name,
bool overwrite);
std::vector<std::string> sindex_list(ql::env_t *env);
std::map<std::string, counted_t<const ql::datum_t> > sindex_status(ql::env_t *env,
const std::set<std::string> &sindexes);
/* These are not part of the `base_table_t` interface. They wrap the `read()`,
`read_outdated()`, and `write()` methods of the underlying `namespace_interface_t` to
add profiling information. Specifically, they:
* Set the explain field in the read_t/write_t object so that the shards know
whether or not to do profiling
* Construct a splitter_t
* Call the corresponding method on the `namespace_if`
* splitter_t::give_splits with the event logs from the shards
These are public because some of the stuff in `datum_stream.hpp` needs to be
able to access them. */
void read_with_profile(ql::env_t *env, const read_t &, read_response_t *response,
bool outdated);
void write_with_profile(ql::env_t *env, write_t *, write_response_t *response);
private:
namespace_id_t uuid;
namespace_interface_access_t namespace_access;
std::string pkey;
ql::changefeed::client_t *changefeed_client;
};
#endif /* RDB_PROTOCOL_REAL_TABLE_HPP_ */
<commit_msg>Made real_table_t be FINAL.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved
#ifndef RDB_PROTOCOL_REAL_TABLE_HPP_
#define RDB_PROTOCOL_REAL_TABLE_HPP_
#include <map>
#include <set>
#include <string>
#include <vector>
#include "rdb_protocol/context.hpp"
#include "rdb_protocol/protocol.hpp"
const char *const sindex_blob_prefix = "$reql_index_function$";
class datum_range_t;
namespace ql { namespace changefeed {
class client_t;
} }
/* `real_table_t` is a concrete subclass of `base_table_t` that routes its queries across
the network via the clustering logic to a B-tree. The administration logic is responsible
for constructing and returning them from `reql_cluster_interface_t::table_find()`. */
/* `namespace_interface_access_t` is like a smart pointer to a `namespace_interface_t`.
This is the format in which `real_table_t` expects to receive its
`namespace_interface_t *`. This allows the thing that is constructing the `real_table_t`
to control the lifetime of the `namespace_interface_t`, but also allows the
`real_table_t` to block it from being destroyed while in use. */
class namespace_interface_access_t {
public:
class ref_tracker_t {
public:
virtual void add_ref() = 0;
virtual void release() = 0;
protected:
virtual ~ref_tracker_t() { }
};
namespace_interface_access_t();
namespace_interface_access_t(namespace_interface_t *, ref_tracker_t *, threadnum_t);
namespace_interface_access_t(const namespace_interface_access_t &access);
namespace_interface_access_t &operator=(const namespace_interface_access_t &access);
~namespace_interface_access_t();
namespace_interface_t *get();
private:
namespace_interface_t *nif;
ref_tracker_t *ref_tracker;
threadnum_t thread;
};
class real_table_t FINAL : public base_table_t {
public:
/* This doesn't automatically wait for readiness. */
real_table_t(
namespace_id_t _uuid,
namespace_interface_access_t _namespace_access,
const std::string &_pkey,
ql::changefeed::client_t *_changefeed_client) :
uuid(_uuid), namespace_access(_namespace_access), pkey(_pkey),
changefeed_client(_changefeed_client) { }
const std::string &get_pkey();
counted_t<const ql::datum_t> read_row(ql::env_t *env,
counted_t<const ql::datum_t> pval, bool use_outdated);
counted_t<ql::datum_stream_t> read_all(
ql::env_t *env,
const std::string &sindex,
const ql::protob_t<const Backtrace> &bt,
const std::string &table_name, /* the table's own name, for display purposes */
const datum_range_t &range,
sorting_t sorting,
bool use_outdated);
counted_t<ql::datum_stream_t> read_row_changes(
ql::env_t *env,
counted_t<const ql::datum_t> pval,
const ql::protob_t<const Backtrace> &bt,
const std::string &table_name);
counted_t<ql::datum_stream_t> read_all_changes(
ql::env_t *env,
const ql::protob_t<const Backtrace> &bt,
const std::string &table_name);
counted_t<ql::datum_stream_t> read_intersecting(
ql::env_t *env,
const std::string &sindex,
const ql::protob_t<const Backtrace> &bt,
const std::string &table_name,
bool use_outdated,
const counted_t<const ql::datum_t> &query_geometry);
counted_t<ql::datum_stream_t> read_nearest(
ql::env_t *env,
const std::string &sindex,
const ql::protob_t<const Backtrace> &bt,
const std::string &table_name,
bool use_outdated,
lat_lon_point_t center,
double max_dist,
uint64_t max_results,
const ellipsoid_spec_t &geo_system,
dist_unit_t dist_unit,
const ql::configured_limits_t &limits);
counted_t<const ql::datum_t> write_batched_replace(ql::env_t *env,
const std::vector<counted_t<const ql::datum_t> > &keys,
const counted_t<const ql::func_t> &func,
return_changes_t _return_changes, durability_requirement_t durability);
counted_t<const ql::datum_t> write_batched_insert(ql::env_t *env,
std::vector<counted_t<const ql::datum_t> > &&inserts,
conflict_behavior_t conflict_behavior, return_changes_t return_changes,
durability_requirement_t durability);
bool write_sync_depending_on_durability(ql::env_t *env,
durability_requirement_t durability);
bool sindex_create(ql::env_t *env,
const std::string &id,
counted_t<const ql::func_t> index_func,
sindex_multi_bool_t multi,
sindex_geo_bool_t geo);
bool sindex_drop(ql::env_t *env,
const std::string &id);
sindex_rename_result_t sindex_rename(ql::env_t *env,
const std::string &old_name,
const std::string &new_name,
bool overwrite);
std::vector<std::string> sindex_list(ql::env_t *env);
std::map<std::string, counted_t<const ql::datum_t> > sindex_status(ql::env_t *env,
const std::set<std::string> &sindexes);
/* These are not part of the `base_table_t` interface. They wrap the `read()`,
`read_outdated()`, and `write()` methods of the underlying `namespace_interface_t` to
add profiling information. Specifically, they:
* Set the explain field in the read_t/write_t object so that the shards know
whether or not to do profiling
* Construct a splitter_t
* Call the corresponding method on the `namespace_if`
* splitter_t::give_splits with the event logs from the shards
These are public because some of the stuff in `datum_stream.hpp` needs to be
able to access them. */
void read_with_profile(ql::env_t *env, const read_t &, read_response_t *response,
bool outdated);
void write_with_profile(ql::env_t *env, write_t *, write_response_t *response);
private:
namespace_id_t uuid;
namespace_interface_access_t namespace_access;
std::string pkey;
ql::changefeed::client_t *changefeed_client;
};
#endif /* RDB_PROTOCOL_REAL_TABLE_HPP_ */
<|endoftext|> |
<commit_before>/**********************************************************************
* File: mainblk.cpp (Formerly main.c)
* Description: Function to call from main() to setup.
* Author: Ray Smith
* Created: Tue Oct 22 11:09:40 BST 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** 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 "fileerr.h"
#ifdef __UNIX__
#include <unistd.h>
#include <signal.h>
#else
#include <io.h>
#endif
#include <stdlib.h>
#include "ccutil.h"
#define VARDIR "configs/" /**< variables files */
#define EXTERN
const ERRCODE NO_PATH =
"Warning:explicit path for executable will not be used for configs";
static const ERRCODE USAGE = "Usage";
namespace tesseract {
/**********************************************************************
* main_setup
*
* Main for mithras demo program. Read the arguments and set up globals.
**********************************************************************/
/**
* @brief CCUtil::main_setup - set location of tessdata and name of image
*
* @param argv0 - paths to the directory with language files and config files.
* An actual value of argv0 is used if not NULL, otherwise TESSDATA_PREFIX is
* used if not NULL, next try to use compiled in -DTESSDATA_PREFIX. If previous
* is not successful - use current directory.
* @param basename - name of image
*/
void CCUtil::main_setup(const char *argv0, const char *basename) {
imagebasename = basename; /**< name of image */
char *tessdata_prefix = getenv("TESSDATA_PREFIX");
if (argv0 != NULL && *argv0 != '\0') {
/* Use tessdata prefix from the command line. */
datadir = argv0;
} else if (tessdata_prefix) {
/* Use tessdata prefix from the environment. */
datadir = tessdata_prefix;
#if defined(_WIN32)
} else if (datadir == NULL || access(datadir.string(), 0) != 0) {
/* Look for tessdata in directory of executable. */
static char dir[128];
static char exe[128];
DWORD length = GetModuleFileName(NULL, exe, sizeof(exe));
if (length > 0 && length < sizeof(exe)) {
_splitpath(exe, NULL, dir, NULL, NULL);
datadir = dir;
}
#endif /* _WIN32 */
#if defined(TESSDATA_PREFIX)
} else {
/* Use tessdata prefix which was compiled in. */
#define _STR(a) #a
#define _XSTR(a) _STR(a)
datadir = _XSTR(TESSDATA_PREFIX) "/tessdata";
#undef _XSTR
#undef _STR
#endif
}
// datadir may still be empty:
if (datadir.length() == 0) {
datadir = "./";
}
// check for missing directory separator
const char *lastchar = datadir.string();
lastchar += datadir.length() - 1;
if ((strcmp(lastchar, "/") != 0) && (strcmp(lastchar, "\\") != 0))
datadir += "/";
}
} // namespace tesseract
<commit_msg>Fixed Tessdata directory for Windows<commit_after>/**********************************************************************
* File: mainblk.cpp (Formerly main.c)
* Description: Function to call from main() to setup.
* Author: Ray Smith
* Created: Tue Oct 22 11:09:40 BST 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** 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 "fileerr.h"
#ifdef __UNIX__
#include <unistd.h>
#include <signal.h>
#else
#include <io.h>
#endif
#include <stdlib.h>
#include "ccutil.h"
#define VARDIR "configs/" /**< variables files */
#define EXTERN
const ERRCODE NO_PATH =
"Warning:explicit path for executable will not be used for configs";
static const ERRCODE USAGE = "Usage";
namespace tesseract {
/**********************************************************************
* main_setup
*
* Main for mithras demo program. Read the arguments and set up globals.
**********************************************************************/
/**
* @brief CCUtil::main_setup - set location of tessdata and name of image
*
* @param argv0 - paths to the directory with language files and config files.
* An actual value of argv0 is used if not NULL, otherwise TESSDATA_PREFIX is
* used if not NULL, next try to use compiled in -DTESSDATA_PREFIX. If previous
* is not successful - use current directory.
* @param basename - name of image
*/
void CCUtil::main_setup(const char *argv0, const char *basename) {
imagebasename = basename; /**< name of image */
char *tessdata_prefix = getenv("TESSDATA_PREFIX");
if (argv0 != NULL && *argv0 != '\0') {
/* Use tessdata prefix from the command line. */
datadir = argv0;
} else if (tessdata_prefix) {
/* Use tessdata prefix from the environment. */
datadir = tessdata_prefix;
#if defined(_WIN32)
} else if (datadir == NULL || access(datadir.string(), 0) != 0) {
/* Look for tessdata in directory of executable. */
static char drive[4];
static char dir[128];
static char exe[128];
DWORD length = GetModuleFileName(NULL, exe, sizeof(exe));
if (length > 0 && length < sizeof(exe)) {
_splitpath(exe, drive, dir, NULL, NULL);
datadir = drive;
datadir += dir;
}
#endif /* _WIN32 */
#if defined(TESSDATA_PREFIX)
} else {
/* Use tessdata prefix which was compiled in. */
#define _STR(a) #a
#define _XSTR(a) _STR(a)
datadir = _XSTR(TESSDATA_PREFIX) "/tessdata";
#undef _XSTR
#undef _STR
#endif
}
// datadir may still be empty:
if (datadir.length() == 0) {
datadir = "./";
}
// check for missing directory separator
const char *lastchar = datadir.string();
lastchar += datadir.length() - 1;
if ((strcmp(lastchar, "/") != 0) && (strcmp(lastchar, "\\") != 0))
datadir += "/";
}
} // namespace tesseract
<|endoftext|> |
<commit_before>#ifndef CONFIG_HPP
#define CONFIG_HPP
// Window DLL support
#ifdef _WINDOWS
# define MAPNIK_DECL __declspec (dllexport)
# pragma warning( disable: 4251 )
# pragma warning( disable: 4275 )
#else
# define MAPNIK_DECL
#endif
#endif
<commit_msg>added pragma to disable 4996 warning<commit_after>#ifndef CONFIG_HPP
#define CONFIG_HPP
// Window DLL support
#ifdef _WINDOWS
# define MAPNIK_DECL __declspec (dllexport)
# pragma warning( disable: 4251 )
# pragma warning( disable: 4275 )
# if (_MSC_VER >= 1400) // vc8
# pragma warning(disable : 4996) //_CRT_SECURE_NO_DEPRECATE
# endif
#else
# define MAPNIK_DECL
#endif
#endif
<|endoftext|> |
<commit_before>//! @Alan
//!
//! Exercise 11.9:
//! Define a map that associates words with a list of
//! line numbers on which the word might occur.
//!
//! Exercise 11.10:
//! Could we define a map from vector<int>::iterator
//! to int? What about from list<int>::iterator to int?
//! In each case, if not, why not?
// vector<int>::iterator to int is ok ,because < is defined
// list<int>::iterator to int is not ok,as no < is defined.
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
#include <list>
int main()
{
//! ex 11.9
std::map<std::string, std::list<std::size_t>> m;
//! ex 11.10
//! can be declared.
std::map<std::vector<int>::iterator, int> mv;
std::map<std::list<int>::iterator, int> ml;
std::vector<int> vi;
mv.insert(std::pair<std::vector<int>::iterator, int>(vi.begin(), 0));
//! but when using this one the compiler complained that
//! error: no match for 'operator<' in '__x < __y'
std::list<int> li;
ml.insert(std::pair<std::list<int>::iterator, int>(li.begin(), 0));
return 0;
}
<commit_msg>Update ex11_9_10.cpp<commit_after>//! @Alan
//!
//! Exercise 11.9:
//! Define a map that associates words with a list of
//! line numbers on which the word might occur.
//!
//! Exercise 11.10:
//! Could we define a map from vector<int>::iterator
//! to int? What about from list<int>::iterator to int?
//! In each case, if not, why not?
// vector<int>::iterator to int is ok ,because < is defined
// list<int>::iterator to int is not ok,as no < is defined.
#include <map>
#include <string>
#include <vector>
#include <list>
#include <cstddef>
#include <algorithm>
using namespace std;
int main()
{
//! ex 11.9
map<string, list<size_t>> m;
//! ex 11.10
//! can be declared
map<vector<int>::iterator, int> mv;
map<list<int>::iterator, int> ml;
vector<int> vi;
mv.insert(pair<vector<int>::iterator, int>(vi.begin(), 0));
//! but when using this one the compiler complained that
//! error: no match for 'operator<' in '_x < _y'
list<int> li;
ml.insert(pair<list<int>::iterator, int>(li.begin(), 0));
}
<|endoftext|> |
<commit_before>/*!
* Copyright (c) 2017 by Contributors
* \file cuda_module.cc
*/
#include "./cuda_module.h"
#if TVM_CUDA_RUNTIME
#include <tvm/runtime/registry.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <vector>
#include <array>
#include <string>
#include <mutex>
#include "./cuda_common.h"
#include "../pack_args.h"
#include "../thread_storage_scope.h"
#include "../meta_data.h"
#include "../file_util.h"
namespace tvm {
namespace runtime {
// Module to support thread-safe multi-GPU execution.
// cuModule is a per-GPU module
// The runtime will contain a per-device module table
// The modules will be lazily loaded
class CUDAModuleNode : public runtime::ModuleNode {
public:
explicit CUDAModuleNode(std::string data,
std::string fmt,
std::unordered_map<std::string, FunctionInfo> fmap,
std::string cuda_source)
: data_(data), fmt_(fmt), fmap_(fmap), cuda_source_(cuda_source) {
std::fill(module_.begin(), module_.end(), nullptr);
}
// destructor
~CUDAModuleNode() {
for (size_t i = 0; i < module_.size(); ++i) {
if (module_[i] != nullptr) {
CUDA_CALL(cudaSetDevice(static_cast<int>(i)));
CUDA_DRIVER_CALL(cuModuleUnload(module_[i]));
}
}
}
const char* type_key() const final {
return "cuda";
}
PackedFunc GetFunction(
const std::string& name,
const std::shared_ptr<ModuleNode>& sptr_to_self) final;
void SaveToFile(const std::string& file_name,
const std::string& format) final {
std::string fmt = GetFileFormat(file_name, format);
std::string meta_file = GetMetaFilePath(file_name);
if (fmt == "cu") {
CHECK_NE(cuda_source_.length(), 0);
SaveMetaDataToFile(meta_file, fmap_);
SaveBinaryToFile(file_name, cuda_source_);
} else {
CHECK_EQ(fmt, fmt_)
<< "Can only save to format=" << fmt_;
SaveMetaDataToFile(meta_file, fmap_);
SaveBinaryToFile(file_name, data_);
}
}
void SaveToBinary(dmlc::Stream* stream) final {
stream->Write(fmt_);
stream->Write(fmap_);
stream->Write(data_);
}
std::string GetSource(const std::string& format) final {
if (format == fmt_) return data_;
if (cuda_source_.length() != 0) {
return cuda_source_;
} else {
if (fmt_ == "ptx") return data_;
return "";
}
}
// get a CUfunction from primary context in device_id
CUfunction GetFunc(int device_id, const std::string& func_name) {
std::lock_guard<std::mutex> lock(mutex_);
// must recheck under the lock scope
if (module_[device_id] == nullptr) {
CUDA_DRIVER_CALL(cuModuleLoadData(&(module_[device_id]), data_.c_str()));
}
CUfunction func;
CUresult result = cuModuleGetFunction(&func, module_[device_id], func_name.c_str());
if (result != CUDA_SUCCESS) {
const char *msg;
cuGetErrorName(result, &msg);
LOG(FATAL)
<< "CUDAError: cuModuleGetFunction " << func_name
<< " failed with error: " << msg;
}
return func;
}
// get a global var from primary context in device_id
CUdeviceptr GetGlobal(int device_id,
const std::string& global_name,
size_t expect_nbytes) {
std::lock_guard<std::mutex> lock(mutex_);
// must recheck under the lock scope
if (module_[device_id] == nullptr) {
CUDA_DRIVER_CALL(cuModuleLoadData(&(module_[device_id]), data_.c_str()));
}
CUdeviceptr global;
size_t nbytes;
CUresult result = cuModuleGetGlobal(&global, &nbytes,
module_[device_id], global_name.c_str());
CHECK_EQ(nbytes, expect_nbytes);
if (result != CUDA_SUCCESS) {
const char *msg;
cuGetErrorName(result, &msg);
LOG(FATAL)
<< "CUDAError: cuModuleGetGlobal " << global_name
<< " failed with error: " << msg;
}
return global;
}
private:
// the binary data
std::string data_;
// The format
std::string fmt_;
// function information table.
std::unordered_map<std::string, FunctionInfo> fmap_;
// The cuda source.
std::string cuda_source_;
// the internal modules per GPU, to be lazily initialized.
std::array<CUmodule, kMaxNumGPUs> module_;
// internal mutex when updating the module
std::mutex mutex_;
};
// a wrapped function class to get packed fucn.
class CUDAWrappedFunc {
public:
// initialize the CUDA function.
void Init(CUDAModuleNode* m,
std::shared_ptr<ModuleNode> sptr,
const std::string& func_name,
size_t num_void_args,
const std::vector<std::string>& thread_axis_tags) {
m_ = m;
sptr_ = sptr;
func_name_ = func_name;
std::fill(fcache_.begin(), fcache_.end(), nullptr);
thread_axis_cfg_.Init(num_void_args, thread_axis_tags);
}
// invoke the function with void arguments
void operator()(TVMArgs args,
TVMRetValue* rv,
void** void_args) const {
int device_id;
CUDA_CALL(cudaGetDevice(&device_id));
if (fcache_[device_id] == nullptr) {
fcache_[device_id] = m_->GetFunc(device_id, func_name_);
}
CUstream strm = static_cast<CUstream>(CUDAThreadEntry::ThreadLocal()->stream);
ThreadWorkLoad wl = thread_axis_cfg_.Extract(args);
CUDA_DRIVER_CALL(cuLaunchKernel(
fcache_[device_id],
wl.grid_dim(0),
wl.grid_dim(1),
wl.grid_dim(2),
wl.block_dim(0),
wl.block_dim(1),
wl.block_dim(2),
0, strm, void_args, 0));
}
private:
// internal module
CUDAModuleNode* m_;
// the resource holder
std::shared_ptr<ModuleNode> sptr_;
// The name of the function.
std::string func_name_;
// Device function cache per device.
// mark as mutable, to enable lazy initialization
mutable std::array<CUfunction, kMaxNumGPUs> fcache_;
// thread axis configuration
ThreadAxisConfig thread_axis_cfg_;
};
class CUDAPrepGlobalBarrier {
public:
CUDAPrepGlobalBarrier(CUDAModuleNode* m,
std::shared_ptr<ModuleNode> sptr)
: m_(m), sptr_(sptr) {
std::fill(pcache_.begin(), pcache_.end(), 0);
}
void operator()(const TVMArgs& args, TVMRetValue* rv) const {
int device_id;
CUDA_CALL(cudaGetDevice(&device_id));
if (pcache_[device_id] == 0) {
pcache_[device_id] = m_->GetGlobal(
device_id, runtime::symbol::tvm_global_barrier_state, sizeof(unsigned));
}
CUDA_DRIVER_CALL(cuMemsetD32(pcache_[device_id], 0, 1));
}
private:
// internal module
CUDAModuleNode* m_;
// the resource holder
std::shared_ptr<ModuleNode> sptr_;
// mark as mutable, to enable lazy initialization
mutable std::array<CUdeviceptr, kMaxNumGPUs> pcache_;
};
PackedFunc CUDAModuleNode::GetFunction(
const std::string& name,
const std::shared_ptr<ModuleNode>& sptr_to_self) {
CHECK_EQ(sptr_to_self.get(), this);
CHECK_NE(name, symbol::tvm_module_main)
<< "Device function do not have main";
if (name == symbol::tvm_prepare_global_barrier) {
return PackedFunc(CUDAPrepGlobalBarrier(this, sptr_to_self));
}
auto it = fmap_.find(name);
if (it == fmap_.end()) return PackedFunc();
const FunctionInfo& info = it->second;
CUDAWrappedFunc f;
f.Init(this, sptr_to_self, name, info.arg_types.size(), info.thread_axis_tags);
return PackFuncVoidAddr(f, info.arg_types);
}
Module CUDAModuleCreate(
std::string data,
std::string fmt,
std::unordered_map<std::string, FunctionInfo> fmap,
std::string cuda_source) {
std::shared_ptr<CUDAModuleNode> n =
std::make_shared<CUDAModuleNode>(data, fmt, fmap, cuda_source);
return Module(n);
}
// Load module from module.
Module CUDAModuleLoadFile(const std::string& file_name,
const std::string& format) {
std::string data;
std::unordered_map<std::string, FunctionInfo> fmap;
std::string fmt = GetFileFormat(file_name, format);
std::string meta_file = GetMetaFilePath(file_name);
LoadBinaryFromFile(file_name, &data);
LoadMetaDataFromFile(meta_file, &fmap);
return CUDAModuleCreate(data, fmt, fmap, std::string());
}
Module CUDAModuleLoadBinary(void* strm) {
dmlc::Stream* stream = static_cast<dmlc::Stream*>(strm);
std::string data;
std::unordered_map<std::string, FunctionInfo> fmap;
std::string fmt;
stream->Read(&fmt);
stream->Read(&fmap);
stream->Read(&data);
return CUDAModuleCreate(data, fmt, fmap, std::string());
}
TVM_REGISTER_GLOBAL("module.loadfile_cubin")
.set_body([](TVMArgs args, TVMRetValue* rv) {
*rv = CUDAModuleLoadFile(args[0], args[1]);
});
TVM_REGISTER_GLOBAL("module.loadfile_ptx")
.set_body([](TVMArgs args, TVMRetValue* rv) {
*rv = CUDAModuleLoadFile(args[0], args[1]);
});
TVM_REGISTER_GLOBAL("module.loadbinary_cuda")
.set_body([](TVMArgs args, TVMRetValue* rv) {
*rv = CUDAModuleLoadBinary(args[0]);
});
} // namespace runtime
} // namespace tvm
#endif // TVM_CUDA_RUNTIME
<commit_msg>[RUNTIME] Better error message in cuda launch (#513)<commit_after>/*!
* Copyright (c) 2017 by Contributors
* \file cuda_module.cc
*/
#include "./cuda_module.h"
#if TVM_CUDA_RUNTIME
#include <tvm/runtime/registry.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <vector>
#include <array>
#include <string>
#include <mutex>
#include "./cuda_common.h"
#include "../pack_args.h"
#include "../thread_storage_scope.h"
#include "../meta_data.h"
#include "../file_util.h"
namespace tvm {
namespace runtime {
// Module to support thread-safe multi-GPU execution.
// cuModule is a per-GPU module
// The runtime will contain a per-device module table
// The modules will be lazily loaded
class CUDAModuleNode : public runtime::ModuleNode {
public:
explicit CUDAModuleNode(std::string data,
std::string fmt,
std::unordered_map<std::string, FunctionInfo> fmap,
std::string cuda_source)
: data_(data), fmt_(fmt), fmap_(fmap), cuda_source_(cuda_source) {
std::fill(module_.begin(), module_.end(), nullptr);
}
// destructor
~CUDAModuleNode() {
for (size_t i = 0; i < module_.size(); ++i) {
if (module_[i] != nullptr) {
CUDA_CALL(cudaSetDevice(static_cast<int>(i)));
CUDA_DRIVER_CALL(cuModuleUnload(module_[i]));
}
}
}
const char* type_key() const final {
return "cuda";
}
PackedFunc GetFunction(
const std::string& name,
const std::shared_ptr<ModuleNode>& sptr_to_self) final;
void SaveToFile(const std::string& file_name,
const std::string& format) final {
std::string fmt = GetFileFormat(file_name, format);
std::string meta_file = GetMetaFilePath(file_name);
if (fmt == "cu") {
CHECK_NE(cuda_source_.length(), 0);
SaveMetaDataToFile(meta_file, fmap_);
SaveBinaryToFile(file_name, cuda_source_);
} else {
CHECK_EQ(fmt, fmt_)
<< "Can only save to format=" << fmt_;
SaveMetaDataToFile(meta_file, fmap_);
SaveBinaryToFile(file_name, data_);
}
}
void SaveToBinary(dmlc::Stream* stream) final {
stream->Write(fmt_);
stream->Write(fmap_);
stream->Write(data_);
}
std::string GetSource(const std::string& format) final {
if (format == fmt_) return data_;
if (cuda_source_.length() != 0) {
return cuda_source_;
} else {
if (fmt_ == "ptx") return data_;
return "";
}
}
// get a CUfunction from primary context in device_id
CUfunction GetFunc(int device_id, const std::string& func_name) {
std::lock_guard<std::mutex> lock(mutex_);
// must recheck under the lock scope
if (module_[device_id] == nullptr) {
CUDA_DRIVER_CALL(cuModuleLoadData(&(module_[device_id]), data_.c_str()));
}
CUfunction func;
CUresult result = cuModuleGetFunction(&func, module_[device_id], func_name.c_str());
if (result != CUDA_SUCCESS) {
const char *msg;
cuGetErrorName(result, &msg);
LOG(FATAL)
<< "CUDAError: cuModuleGetFunction " << func_name
<< " failed with error: " << msg;
}
return func;
}
// get a global var from primary context in device_id
CUdeviceptr GetGlobal(int device_id,
const std::string& global_name,
size_t expect_nbytes) {
std::lock_guard<std::mutex> lock(mutex_);
// must recheck under the lock scope
if (module_[device_id] == nullptr) {
CUDA_DRIVER_CALL(cuModuleLoadData(&(module_[device_id]), data_.c_str()));
}
CUdeviceptr global;
size_t nbytes;
CUresult result = cuModuleGetGlobal(&global, &nbytes,
module_[device_id], global_name.c_str());
CHECK_EQ(nbytes, expect_nbytes);
if (result != CUDA_SUCCESS) {
const char *msg;
cuGetErrorName(result, &msg);
LOG(FATAL)
<< "CUDAError: cuModuleGetGlobal " << global_name
<< " failed with error: " << msg;
}
return global;
}
private:
// the binary data
std::string data_;
// The format
std::string fmt_;
// function information table.
std::unordered_map<std::string, FunctionInfo> fmap_;
// The cuda source.
std::string cuda_source_;
// the internal modules per GPU, to be lazily initialized.
std::array<CUmodule, kMaxNumGPUs> module_;
// internal mutex when updating the module
std::mutex mutex_;
};
// a wrapped function class to get packed fucn.
class CUDAWrappedFunc {
public:
// initialize the CUDA function.
void Init(CUDAModuleNode* m,
std::shared_ptr<ModuleNode> sptr,
const std::string& func_name,
size_t num_void_args,
const std::vector<std::string>& thread_axis_tags) {
m_ = m;
sptr_ = sptr;
func_name_ = func_name;
std::fill(fcache_.begin(), fcache_.end(), nullptr);
thread_axis_cfg_.Init(num_void_args, thread_axis_tags);
}
// invoke the function with void arguments
void operator()(TVMArgs args,
TVMRetValue* rv,
void** void_args) const {
int device_id;
CUDA_CALL(cudaGetDevice(&device_id));
if (fcache_[device_id] == nullptr) {
fcache_[device_id] = m_->GetFunc(device_id, func_name_);
}
CUstream strm = static_cast<CUstream>(CUDAThreadEntry::ThreadLocal()->stream);
ThreadWorkLoad wl = thread_axis_cfg_.Extract(args);
CUresult result = cuLaunchKernel(
fcache_[device_id],
wl.grid_dim(0),
wl.grid_dim(1),
wl.grid_dim(2),
wl.block_dim(0),
wl.block_dim(1),
wl.block_dim(2),
0, strm, void_args, 0);
if (result != CUDA_SUCCESS && result != CUDA_ERROR_DEINITIALIZED) {
const char *msg;
cuGetErrorName(result, &msg);
std::ostringstream os;
os << "CUDALaunch Error: " << msg << "\n"
<< " grid=(" << wl.grid_dim(0) << ","
<< wl.grid_dim(1) << "," << wl.grid_dim(2) << "), "
<< " block=(" << wl.block_dim(0) << ","
<< wl.block_dim(1) << "," << wl.block_dim(2) << ")\n";
std::string cuda = m_->GetSource("");
if (cuda.length() != 0) {
os << "// func_name=" << func_name_ << "\n"
<< "// CUDA Source\n"
<< "// -----------\n"
<< cuda;
}
LOG(FATAL) << os.str();
}
}
private:
// internal module
CUDAModuleNode* m_;
// the resource holder
std::shared_ptr<ModuleNode> sptr_;
// The name of the function.
std::string func_name_;
// Device function cache per device.
// mark as mutable, to enable lazy initialization
mutable std::array<CUfunction, kMaxNumGPUs> fcache_;
// thread axis configuration
ThreadAxisConfig thread_axis_cfg_;
};
class CUDAPrepGlobalBarrier {
public:
CUDAPrepGlobalBarrier(CUDAModuleNode* m,
std::shared_ptr<ModuleNode> sptr)
: m_(m), sptr_(sptr) {
std::fill(pcache_.begin(), pcache_.end(), 0);
}
void operator()(const TVMArgs& args, TVMRetValue* rv) const {
int device_id;
CUDA_CALL(cudaGetDevice(&device_id));
if (pcache_[device_id] == 0) {
pcache_[device_id] = m_->GetGlobal(
device_id, runtime::symbol::tvm_global_barrier_state, sizeof(unsigned));
}
CUDA_DRIVER_CALL(cuMemsetD32(pcache_[device_id], 0, 1));
}
private:
// internal module
CUDAModuleNode* m_;
// the resource holder
std::shared_ptr<ModuleNode> sptr_;
// mark as mutable, to enable lazy initialization
mutable std::array<CUdeviceptr, kMaxNumGPUs> pcache_;
};
PackedFunc CUDAModuleNode::GetFunction(
const std::string& name,
const std::shared_ptr<ModuleNode>& sptr_to_self) {
CHECK_EQ(sptr_to_self.get(), this);
CHECK_NE(name, symbol::tvm_module_main)
<< "Device function do not have main";
if (name == symbol::tvm_prepare_global_barrier) {
return PackedFunc(CUDAPrepGlobalBarrier(this, sptr_to_self));
}
auto it = fmap_.find(name);
if (it == fmap_.end()) return PackedFunc();
const FunctionInfo& info = it->second;
CUDAWrappedFunc f;
f.Init(this, sptr_to_self, name, info.arg_types.size(), info.thread_axis_tags);
return PackFuncVoidAddr(f, info.arg_types);
}
Module CUDAModuleCreate(
std::string data,
std::string fmt,
std::unordered_map<std::string, FunctionInfo> fmap,
std::string cuda_source) {
std::shared_ptr<CUDAModuleNode> n =
std::make_shared<CUDAModuleNode>(data, fmt, fmap, cuda_source);
return Module(n);
}
// Load module from module.
Module CUDAModuleLoadFile(const std::string& file_name,
const std::string& format) {
std::string data;
std::unordered_map<std::string, FunctionInfo> fmap;
std::string fmt = GetFileFormat(file_name, format);
std::string meta_file = GetMetaFilePath(file_name);
LoadBinaryFromFile(file_name, &data);
LoadMetaDataFromFile(meta_file, &fmap);
return CUDAModuleCreate(data, fmt, fmap, std::string());
}
Module CUDAModuleLoadBinary(void* strm) {
dmlc::Stream* stream = static_cast<dmlc::Stream*>(strm);
std::string data;
std::unordered_map<std::string, FunctionInfo> fmap;
std::string fmt;
stream->Read(&fmt);
stream->Read(&fmap);
stream->Read(&data);
return CUDAModuleCreate(data, fmt, fmap, std::string());
}
TVM_REGISTER_GLOBAL("module.loadfile_cubin")
.set_body([](TVMArgs args, TVMRetValue* rv) {
*rv = CUDAModuleLoadFile(args[0], args[1]);
});
TVM_REGISTER_GLOBAL("module.loadfile_ptx")
.set_body([](TVMArgs args, TVMRetValue* rv) {
*rv = CUDAModuleLoadFile(args[0], args[1]);
});
TVM_REGISTER_GLOBAL("module.loadbinary_cuda")
.set_body([](TVMArgs args, TVMRetValue* rv) {
*rv = CUDAModuleLoadBinary(args[0]);
});
} // namespace runtime
} // namespace tvm
#endif // TVM_CUDA_RUNTIME
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/mcbist_workarounds.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mcbist_workarounds.C
/// @brief Workarounds for the MCBISt engine
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <lib/mss_attribute_accessors.H>
#include <generic/memory/lib/utils/scom.H>
#include <generic/memory/lib/utils/pos.H>
#include <lib/dimm/kind.H>
#include <lib/workarounds/mcbist_workarounds.H>
#include <lib/mcbist/mcbist.H>
#include <lib/fir/fir.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
namespace workarounds
{
namespace mcbist
{
///
/// @brief Replace reads with displays in the passed in MCBIST program
/// @param[in,out] the MCBIST program to check for read/display replacement
/// @note Useful for testing
///
void replace_read_helper(mss::mcbist::program<TARGET_TYPE_MCBIST>& io_program)
{
using TT = mss::mcbistTraits<TARGET_TYPE_MCBIST>;
io_program.change_maint_broadcast_mode(mss::OFF);
io_program.change_end_boundary(mss::mcbist::end_boundary::STOP_AFTER_ADDRESS);
for (auto& st : io_program.iv_subtests)
{
uint64_t l_op = 0;
st.iv_mcbmr.extractToRight<TT::OP_TYPE, TT::OP_TYPE_LEN>(l_op);
if (l_op == mss::mcbist::op_type::READ)
{
l_op = mss::mcbist::op_type::DISPLAY;
}
st.iv_mcbmr.insertFromRight<TT::OP_TYPE, TT::OP_TYPE_LEN>(l_op);
}
}
///
/// @brief End of rank work around
/// For Nimbus DD1 the MCBIST engine doesn't detect the end of rank properly
/// for a 1R DIMM during a super-fast read. To work around this, we check the
/// MCBIST to see if any port has a 1R DIMM on it and if so we change our stop
/// conditions to immediate. However, because that doesn't work (by design) with
/// read, we also must change all reads to displays (slow read.)
/// @param[in] i_target the fapi2 target of the mcbist
/// @param[in,out] io_program the mcbist program to check
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode end_of_rank( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,
mss::mcbist::program<TARGET_TYPE_MCBIST>& io_program )
{
using TT = mss::mcbistTraits<TARGET_TYPE_MCBIST>;
// If we don't need the mcbist work-around, we're done.
if (! mss::chip_ec_feature_mcbist_end_of_rank(i_target) )
{
return FAPI2_RC_SUCCESS;
}
// First things first - lets find out if we have an 1R DIMM on our side of the chip.
const auto l_dimm_kinds = dimm::kind::vector( mss::find_targets<TARGET_TYPE_DIMM>(i_target) );
const auto l_kind = std::find_if(l_dimm_kinds.begin(), l_dimm_kinds.end(), [](const dimm::kind & k) -> bool
{
// If total ranks are 1, we have a 1R DIMM, SDP. This is the fellow of concern
return k.iv_total_ranks == 1;
});
// If we don't find the fellow of concern, we can get outta here
if (l_kind == l_dimm_kinds.end())
{
FAPI_INF("no 1R SDP DIMM on this MCBIST (%s), we're ok", mss::c_str(i_target));
return FAPI2_RC_SUCCESS;
}
// Keep in mind that pause-on-error-mode is two bits and it doesn't encode master/slave. The
// end_boundary enums are constructed such that STOP_AFTER_MASTER_RANK is really stop on
// either master or slave for the purposes of this field. So, checking stop-after-master-rank
// will catch both master and slave pauses which is correct for this work-around.
uint64_t l_pause_mode = 0;
io_program.iv_config.extractToRight<TT::CFG_PAUSE_ON_ERROR_MODE, TT::CFG_PAUSE_ON_ERROR_MODE_LEN>(l_pause_mode);
if( l_pause_mode != mss::mcbist::end_boundary::STOP_AFTER_MASTER_RANK )
{
FAPI_INF("not checking rank boundaries on this MCBIST (%s), we're ok", mss::c_str(i_target));
return FAPI2_RC_SUCCESS;
}
// If we're here, we need to fix up our program. We need to set our stop to stop immediate, which implies
// we don't do broadcasts and we can't do read, we have to do display.
FAPI_INF("%s replacing reads and changing broadcast mode due to a chip bug", mss::c_str(i_target));
replace_read_helper(io_program);
return fapi2::FAPI2_RC_SUCCESS;
}
///
/// @brief WAT debug attention
/// For Nimbus DD1 the MCBIST engine uses the WAT debug bit as a workaround
/// @param[in] i_target the fapi2 target of the mcbist
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode wat_debug_attention( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target )
{
// MCBIST attentions are already special attention
if (mss::chip_ec_feature_mss_wat_debug_attn(i_target))
{
fapi2::ReturnCode l_rc;
fir::reg<MCBIST_MCBISTFIRQ> mcbist_fir_register(i_target, l_rc);
FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCBIST_MCBISTFIRQ);
FAPI_TRY(mcbist_fir_register.attention<MCBIST_MCBISTFIRQ_WAT_DEBUG_ATTN>().write());
}
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace mcbist
} // close namespace workarounds
} // close namespace mss
<commit_msg>Updates dramint training structure<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/mcbist_workarounds.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mcbist_workarounds.C
/// @brief Workarounds for the MCBISt engine
/// Workarounds are very device specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <lib/mss_attribute_accessors.H>
#include <generic/memory/lib/utils/scom.H>
#include <generic/memory/lib/utils/pos.H>
#include <lib/dimm/kind.H>
#include <lib/workarounds/mcbist_workarounds.H>
#include <lib/mcbist/mcbist.H>
#include <lib/fir/fir.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
namespace workarounds
{
namespace mcbist
{
///
/// @brief Replace reads with displays in the passed in MCBIST program
/// @param[in,out] the MCBIST program to check for read/display replacement
/// @note Useful for testing
///
void replace_read_helper(mss::mcbist::program<TARGET_TYPE_MCBIST>& io_program)
{
using TT = mss::mcbistTraits<TARGET_TYPE_MCBIST>;
io_program.change_maint_broadcast_mode(mss::OFF);
io_program.change_end_boundary(mss::mcbist::end_boundary::STOP_AFTER_ADDRESS);
for (auto& st : io_program.iv_subtests)
{
uint64_t l_op = 0;
st.iv_mcbmr.extractToRight<TT::OP_TYPE, TT::OP_TYPE_LEN>(l_op);
if (l_op == mss::mcbist::op_type::READ)
{
l_op = mss::mcbist::op_type::DISPLAY;
}
st.iv_mcbmr.insertFromRight<TT::OP_TYPE, TT::OP_TYPE_LEN>(l_op);
}
}
///
/// @brief End of rank work around
/// For Nimbus DD1 the MCBIST engine doesn't detect the end of rank properly
/// for a 1R DIMM during a super-fast read. To work around this, we check the
/// MCBIST to see if any port has a 1R DIMM on it and if so we change our stop
/// conditions to immediate. However, because that doesn't work (by design) with
/// read, we also must change all reads to displays (slow read.)
/// @param[in] i_target the fapi2 target of the mcbist
/// @param[in,out] io_program the mcbist program to check
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode end_of_rank( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,
mss::mcbist::program<TARGET_TYPE_MCBIST>& io_program )
{
using TT = mss::mcbistTraits<TARGET_TYPE_MCBIST>;
// If we don't need the mcbist work-around, we're done.
if (! mss::chip_ec_feature_mcbist_end_of_rank(i_target) )
{
return FAPI2_RC_SUCCESS;
}
// First things first - lets find out if we have an 1R DIMM on our side of the chip.
const auto l_dimm_kinds = dimm::kind::vector( mss::find_targets<TARGET_TYPE_DIMM>(i_target) );
const auto l_kind = std::find_if(l_dimm_kinds.begin(), l_dimm_kinds.end(), [](const dimm::kind & k) -> bool
{
// If total ranks are 1, we have a 1R DIMM, SDP. This is the fellow of concern
return k.iv_total_ranks == 1;
});
// If we don't find the fellow of concern, we can get outta here
if (l_kind == l_dimm_kinds.end())
{
FAPI_INF("no 1R SDP DIMM on this MCBIST (%s), we're ok", mss::c_str(i_target));
return FAPI2_RC_SUCCESS;
}
// Keep in mind that pause-on-error-mode is two bits and it doesn't encode master/slave. The
// end_boundary enums are constructed such that STOP_AFTER_MASTER_RANK is really stop on
// either master or slave for the purposes of this field. So, checking stop-after-master-rank
// will catch both master and slave pauses which is correct for this work-around.
uint64_t l_pause_mode = 0;
io_program.iv_config.extractToRight<TT::CFG_PAUSE_ON_ERROR_MODE, TT::CFG_PAUSE_ON_ERROR_MODE_LEN>(l_pause_mode);
if( l_pause_mode != mss::mcbist::end_boundary::STOP_AFTER_MASTER_RANK )
{
FAPI_INF("not checking rank boundaries on this MCBIST (%s), we're ok", mss::c_str(i_target));
return FAPI2_RC_SUCCESS;
}
// If we're here, we need to fix up our program. We need to set our stop to stop immediate, which implies
// we don't do broadcasts and we can't do read, we have to do display.
FAPI_INF("%s replacing reads and changing broadcast mode due to a chip bug", mss::c_str(i_target));
replace_read_helper(io_program);
return fapi2::FAPI2_RC_SUCCESS;
}
///
/// @brief WAT debug attention
/// For Nimbus DD1 the MCBIST engine uses the WAT debug bit as a workaround
/// @param[in] i_target the fapi2 target of the mcbist
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode wat_debug_attention( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target )
{
// MCBIST attentions are already special attention
if (mss::chip_ec_feature_mss_wat_debug_attn(i_target))
{
fapi2::ReturnCode l_rc;
fir::reg<MCBIST_MCBISTFIRQ> mcbist_fir_register(i_target, l_rc);
FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCBIST_MCBISTFIRQ);
FAPI_TRY(mcbist_fir_register.attention<MCBIST_MCBISTFIRQ_WAT_DEBUG_ATTN>().write());
}
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace mcbist
} // close namespace workarounds
} // close namespace mss
<|endoftext|> |
<commit_before>using namespace std;
class Matrix {
private:
int row, col, **mas;
public:
Matrix(int length = 4);
Matrix(int, int);
Matrix(const Matrix&);
~Matrix();
void fill(const char*);
void show() const;
void rows();
void columns();
Matrix operator+(const Matrix&) const;
Matrix operator*(const Matrix&) const;
};
<commit_msg>Update matrix.hpp<commit_after>#include <fstream>
#include <iostream>
using namespace std;
class Matrix {
private:
int row, col, **mas;
public:
Matrix(int length = 4);
Matrix(int, int);
Matrix(const Matrix&);
~Matrix();
void fill(const char*);
void show() const;
void rows();
void columns();
Matrix operator+(const Matrix&) const;
Matrix operator*(const Matrix&) const;
};
<|endoftext|> |
<commit_before>#ifndef __Z2H_PARSER__
#define __Z2H_PARSER__ = 1
#include <cmath>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
#include <stddef.h>
#include <sys/stat.h>
#include <functional>
#include "token.hpp"
#include "symbol.hpp"
#include "binder.hpp"
using namespace std::placeholders;
namespace z2h {
template <typename TAst>
class Token;
template <typename TAst>
class Symbol;
template <typename TAst, typename TParser>
struct Parser : public Binder<TAst, TParser> {
std::string source;
size_t position;
std::vector<Token<TAst> *> tokens;
size_t index;
~Parser() {
while (!tokens.empty())
delete tokens.back(), tokens.pop_back();
}
Parser()
: source("")
, position(0)
, tokens({})
, index(0) {
}
// Exception must be defined by the inheriting parser, throw exceptions defined there
virtual std::exception Exception(const char *file, size_t line, const std::string &message = "") = 0;
// Symbols must be defined by the inheriting parser
virtual std::vector<Symbol<TAst> *> Symbols() = 0;
// the default for the eof symbol is first in in the list of symbols
virtual Symbol<TAst> * EofSymbol() {
return Symbols()[0];
}
// the default for the eos symbol is second in in the list of symbols
virtual Symbol<TAst> * EosSymbol() {
return Symbols()[1];
}
std::string Open(const std::string &filename) {
struct stat buffer;
if (stat(filename.c_str(), &buffer) != 0)
Exception(__FILE__, __LINE__, filename + " doesn't exist or is unreadable");
std::ifstream file(filename);
std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return text;
}
Token<TAst> * Scan() {
auto eof = EofSymbol();
Token<TAst> *match = nullptr;
if (position < source.length()) {
for (auto symbol : Symbols()) {
auto token = symbol->Scan(symbol, source.substr(position, source.length() - position), position);
if (nullptr == match) {
match = token;
}
else if (nullptr != token && (token->length > match->length || (token->symbol->lbp > match->symbol->lbp && token->length == match->length))) {
delete match;
match = token;
} else {
delete token;
}
}
if (nullptr == match) {
throw Exception(__FILE__, __LINE__, "Parser::Scan: invalid symbol");
}
return match;
}
return new Token<TAst>(eof, "EOF", position, 0, false); //eof
}
Token<TAst> * LookAhead(size_t &distance, bool skips = false) {
Token<TAst> *token = nullptr;
auto i = index;
while (distance) {
if (i < tokens.size()) {
token = tokens[i];
}
else {
token = Scan();
position += token->length;
tokens.push_back(token);
}
if (skips || !token->skip)
--distance;
++i;
}
distance = i - index;
return token;
}
Token<TAst> * Consume(Symbol<TAst> *expected = nullptr, const std::string &message = "") {
size_t distance = 1;
auto token = LookAhead(distance);
index += distance;
if (nullptr != expected && *expected != *token->symbol) {
std::cout << "expected=" << *expected << std:: endl;
std::cout << "token->symbol=" << *token->symbol << std:: endl;
std::cout << "message=" << message << std::endl;
throw Exception(__FILE__, __LINE__, (message.empty() ? "consume failed" : message));
}
return token;
}
std::vector<Token<TAst> *> TokenizeFile(const std::string &filename) {
auto source = Open(filename);
return Tokenize(source);
}
std::vector<Token<TAst> *> Tokenize(std::string source) {
this->index = 0;
this->source = source;
auto eof = EofSymbol();
auto token = Consume();
while (*eof != *token->symbol) {
token = Consume();
}
return tokens;
}
TAst ParseFile(const std::string &filename) {
auto source = Open(filename);
return Parse(source);
}
TAst Parse(std::string source) {
this->index = 0;
this->source = source;
//return Expression();
return Statement();
}
TAst Expression(size_t rbp = 0) {
auto *curr = Consume();
if (nullptr == curr->symbol->Nud) {
std::cout << "no Nud: curr=" << *curr << std::endl;
std::ostringstream out;
out << "unexpected: nullptr==Nud curr=" << *curr;
throw Exception(__FILE__, __LINE__, out.str());
}
TAst left = curr->symbol->Nud(curr);
size_t distance = 1;
auto *next = LookAhead(distance);
while (rbp < next->symbol->lbp) {
std::cout << "before next=" << *next << std::endl;
next = Consume();
std::cout << "after next=" << *next << std::endl;
std::cout << "rbp=" << rbp << " < lbp=" << next->symbol->lbp << std::endl;
std::cout << "before" << std::endl;
left = next->symbol->Led(left, next);
std::cout << "after" << std::endl;
}
return left;
}
TAst Statement() {
size_t distance = 1;
std::cout << "pos=" << position << std::endl;
std::cout << "tokens count=" << tokens.size() << std::endl;
auto *la1 = LookAhead(distance);
std::cout << "pos=" << position << std::endl;
std::cout << "tokens count=" << tokens.size() << std::endl;
std::cout << "tokens[0]=" << *tokens[0] << std::endl;
if (nullptr != la1->symbol->Std) {
std::cout << "Std" << std::endl;
Consume();
std::cout << "Consume" << std::endl;
return la1->symbol->Std();
}
std::cout << "not Std" << std::endl;
std::cout << "pos=" << position << std::endl;
std::cout << "tokens count=" << tokens.size() << std::endl;
auto ast = Expression();
std::cout << "after" << std::endl;
std::cout << "ast=" << ast->Print() << std::endl;
auto eos = EosSymbol();
std::cout << "eos=" << *eos << std::endl;
std::cout << "position=" << position << std::endl;
std::cout << "source=" << source.substr(position, source.length() - position) << std::endl;
Consume(eos, "EndOfStatement expected!");
return ast;
}
size_t Line() {
return 0;
}
size_t Column() {
return 0;
}
};
}
#endif /*__Z2H_PARSER__*/
<commit_msg>removed debug printing and fixed bug by getting curr and next at the beginning of Expression function and the while loop inside... -sai<commit_after>#ifndef __Z2H_PARSER__
#define __Z2H_PARSER__ = 1
#include <cmath>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
#include <stddef.h>
#include <sys/stat.h>
#include <functional>
#include "token.hpp"
#include "symbol.hpp"
#include "binder.hpp"
using namespace std::placeholders;
namespace z2h {
template <typename TAst>
class Token;
template <typename TAst>
class Symbol;
template <typename TAst, typename TParser>
struct Parser : public Binder<TAst, TParser> {
std::string source;
size_t position;
std::vector<Token<TAst> *> tokens;
size_t index;
~Parser() {
while (!tokens.empty())
delete tokens.back(), tokens.pop_back();
}
Parser()
: source("")
, position(0)
, tokens({})
, index(0) {
}
// Exception must be defined by the inheriting parser, throw exceptions defined there
virtual std::exception Exception(const char *file, size_t line, const std::string &message = "") = 0;
// Symbols must be defined by the inheriting parser
virtual std::vector<Symbol<TAst> *> Symbols() = 0;
// the default for the eof symbol is first in in the list of symbols
virtual Symbol<TAst> * EofSymbol() {
return Symbols()[0];
}
// the default for the eos symbol is second in in the list of symbols
virtual Symbol<TAst> * EosSymbol() {
return Symbols()[1];
}
std::string Open(const std::string &filename) {
struct stat buffer;
if (stat(filename.c_str(), &buffer) != 0)
Exception(__FILE__, __LINE__, filename + " doesn't exist or is unreadable");
std::ifstream file(filename);
std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return text;
}
Token<TAst> * Scan() {
auto eof = EofSymbol();
Token<TAst> *match = nullptr;
if (position < source.length()) {
for (auto symbol : Symbols()) {
auto token = symbol->Scan(symbol, source.substr(position, source.length() - position), position);
if (nullptr == match) {
match = token;
}
else if (nullptr != token && (token->length > match->length || (token->symbol->lbp > match->symbol->lbp && token->length == match->length))) {
delete match;
match = token;
} else {
delete token;
}
}
if (nullptr == match) {
throw Exception(__FILE__, __LINE__, "Parser::Scan: invalid symbol");
}
return match;
}
return new Token<TAst>(eof, "EOF", position, 0, false); //eof
}
Token<TAst> * LookAhead(size_t &distance, bool skips = false) {
Token<TAst> *token = nullptr;
auto i = index;
while (distance) {
if (i < tokens.size()) {
token = tokens[i];
}
else {
token = Scan();
position += token->length;
tokens.push_back(token);
}
if (skips || !token->skip) {
--distance;
}
++i;
}
distance = i - index;
return token;
}
Token<TAst> * Consume(Symbol<TAst> *expected = nullptr, const std::string &message = "") {
size_t distance = 1;
auto token = LookAhead(distance);
index += distance;
if (nullptr != expected && *expected != *token->symbol) {
std::cout << "expected = " << *expected << std:: endl;
std::cout << "token->symbol = " << *token->symbol << std:: endl;
std::cout << "message=" << message << std::endl;
throw Exception(__FILE__, __LINE__, (message.empty() ? "consume failed" : message));
}
return token;
}
std::vector<Token<TAst> *> TokenizeFile(const std::string &filename) {
auto source = Open(filename);
return Tokenize(source);
}
std::vector<Token<TAst> *> Tokenize(std::string source) {
this->index = 0;
this->source = source;
auto eof = EofSymbol();
auto token = Consume();
while (*eof != *token->symbol) {
token = Consume();
}
return tokens;
}
TAst ParseFile(const std::string &filename) {
auto source = Open(filename);
return Parse(source);
}
TAst Parse(std::string source) {
this->index = 0;
this->source = source;
return Statement();
}
TAst Expression(size_t rbp = 0) {
auto *curr = Consume();
size_t distance = 1;
auto *next = LookAhead(distance);
TAst left = curr->symbol->Nud(curr);
while (rbp < next->symbol->lbp) {
curr = Consume();
size_t distance = 1;
next = LookAhead(distance);
if (nullptr == curr->symbol->Led) {
std::cout << __LINE__ << "no Led: curr=" << *curr << std::endl;
std::ostringstream out;
out << "unexpected: nullptr==Led curr=" << *curr;
throw Exception(__FILE__, __LINE__, out.str());
}
left = curr->symbol->Led(left, curr);
}
return left;
}
TAst Statement() {
size_t distance = 1;
auto *la1 = LookAhead(distance);
if (nullptr != la1->symbol->Std) {
Consume();
return la1->symbol->Std();
}
auto ast = Expression();
auto eos = EosSymbol();
Consume(eos, "EndOfStatement expected!");
return ast;
}
size_t Line() {
return 0;
}
size_t Column() {
return 0;
}
};
}
#endif /*__Z2H_PARSER__*/
<|endoftext|> |
<commit_before>#include <string>
const size_t n_literals = 27;
size_t letterI(const char letter, const bool is_capital) {
int first_letter_code = static_cast<int>(is_capital ? 'A' : 'a');
size_t result = static_cast<int>(letter) - first_letter_code + 1;
return result;
}
struct person {
char * str;
unsigned char name_i;
unsigned char name_length;
person() : str(nullptr) {
;
}
person(person && _person) : str(_person.str), name_i(_person.name_i), name_length(_person.name_length) {
_person.str = nullptr;
}
person && operator=(person && _person) {
if (this != &_person) {
(shared_pointer<T>(std::move(_person))).swap(*this);
}
return *this;
}
size_t i(size_t sort_i) const {
if (sort_i < name_length) {
return letterI(str[name_i + sort_i], sort_i == 0);
}
else {
return 0;
}
}
char * getName() {
char * temp = new char[name_length + 1];
strncpy(temp, &(str[name_i]), name_length);
temp[name_length] = '\0';
return temp;
} //Boost
void putStr(std::string const & _str) {
str = new char[_str.length() + 1];
strncpy(str, _str.c_str(), _str.length());
str[_str.length()] = '\0';
}
~person() {
delete[] str;
}
};
std::ostream & operator<<(std::ostream & output, person const & _person)
{
output << _person.str << " ";
return output;
}
std::istream & operator>>(std::istream & input, person & _person)
{
input >> _person.str;
/*input >> _person.name;
input >> _person.year;*/
return input;
}
<commit_msg>Update person.hpp<commit_after>#include <string>
const size_t n_literals = 27;
size_t letterI(const char letter, const bool is_capital) {
int first_letter_code = static_cast<int>(is_capital ? 'A' : 'a');
size_t result = static_cast<int>(letter) - first_letter_code + 1;
return result;
}
struct person {
char * str;
unsigned char name_i;
unsigned char name_length;
person() : str(nullptr) {
;
}
person(person && _person) : str(_person.str), name_i(_person.name_i), name_length(_person.name_length) {
_person.str = nullptr;
}
person && operator=(person && _person) {
if (this != &_person) {
(shared_pointer<T>(std::move(_person))).swap(*this);
}
return *this;
}
size_t i(size_t sort_i) const {
if (sort_i < name_length) {
return letterI(str[name_i + sort_i], sort_i == 0);
}
else {
return 0;
}
}
char * getName() {
char * temp = new char[name_length + 1];
strncpy(temp, &(str[name_i]), name_length);
temp[name_length] = '\0';
return temp;
} //Boost
void putStr(std::string const & _str) {
str = new char[_str.length() + 1];
strncpy(str, _str.c_str(), _str.length());
str[_str.length()] = '\0';
}
~person() {
delete[] str;
}
};
std::ostream & operator<<(std::ostream & output, person const & _person)
{
output << _person.str << " ";
return output;
}
std::istream & operator>>(std::istream & input, person & _person)
{
input >> _person.str;
return input;
}
<|endoftext|> |
<commit_before>/*
* D3D11RenderContext.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015-2018 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "D3D11RenderContext.h"
#include "D3D11RenderSystem.h"
#include <LLGL/Platform/NativeHandle.h>
#include "../../Core/Helper.h"
#include "../DXCommon/DXTypes.h"
namespace LLGL
{
D3D11RenderContext::D3D11RenderContext(
IDXGIFactory* factory,
const ComPtr<ID3D11Device>& device,
const ComPtr<ID3D11DeviceContext>& context,
const RenderContextDescriptor& desc,
const std::shared_ptr<Surface>& surface) :
RenderContext { desc.videoMode, desc.vsync },
device_ { device },
context_ { context },
swapChainSamples_ { desc.multiSampling.SampleCount() }
{
/* Setup surface for the render context */
SetOrCreateSurface(surface, desc.videoMode, nullptr);
/* Create D3D objects */
CreateSwapChain(factory);
CreateBackBuffer(GetVideoMode());
/* Initialize v-sync */
OnSetVsync(desc.vsync);
}
void D3D11RenderContext::Present()
{
swapChain_->Present(swapChainInterval_, 0);
}
Format D3D11RenderContext::QueryColorFormat() const
{
return DXTypes::Unmap(colorFormat_);
}
Format D3D11RenderContext::QueryDepthStencilFormat() const
{
return DXTypes::Unmap(depthStencilFormat_);
}
const RenderPass* D3D11RenderContext::GetRenderPass() const
{
return nullptr; // dummy
}
//TODO: depth-stencil and color format does not change, only resizing is considered!
bool D3D11RenderContext::OnSetVideoMode(const VideoModeDescriptor& videoModeDesc)
{
const auto& prevVideoMode = GetVideoMode();
/* Resize back buffer */
if (prevVideoMode.resolution != videoModeDesc.resolution)
ResizeBackBuffer(videoModeDesc);
/* Switch fullscreen mode */
#if 0
if (prevVideoMode.fullscreen != videoModeDesc.fullscreen)
{
auto hr = swapChain_->SetFullscreenState(videoModeDesc.fullscreen ? TRUE : FALSE, nullptr);
return SUCCEEDED(hr);
}
#else
/* Switch fullscreen mode */
if (!SwitchFullscreenMode(videoModeDesc))
return false;
#endif
return true;
}
bool D3D11RenderContext::OnSetVsync(const VsyncDescriptor& vsyncDesc)
{
swapChainInterval_ = (vsyncDesc.enabled ? std::max(1u, std::min(vsyncDesc.interval, 4u)) : 0u);
return true;
}
/*
* ======= Private: =======
*/
void D3D11RenderContext::CreateSwapChain(IDXGIFactory* factory)
{
/* Get current settings */
const auto& videoMode = GetVideoMode();
const auto& vsync = GetVsync();
/* Pick and store color format */
colorFormat_ = DXGI_FORMAT_R8G8B8A8_UNORM;//DXGI_FORMAT_B8G8R8A8_UNORM
/* Create swap chain for window handle */
NativeHandle wndHandle;
GetSurface().GetNativeHandle(&wndHandle);
DXGI_SWAP_CHAIN_DESC swapChainDesc;
InitMemory(swapChainDesc);
{
swapChainDesc.BufferDesc.Width = videoMode.resolution.width;
swapChainDesc.BufferDesc.Height = videoMode.resolution.height;
swapChainDesc.BufferDesc.Format = colorFormat_;
swapChainDesc.BufferDesc.RefreshRate.Numerator = vsync.refreshRate;
swapChainDesc.BufferDesc.RefreshRate.Denominator = vsync.interval;
swapChainDesc.SampleDesc.Count = swapChainSamples_;
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = (videoMode.swapChainSize == 3 ? 2 : 1);
swapChainDesc.OutputWindow = wndHandle.window;
swapChainDesc.Windowed = TRUE;//(videoMode.fullscreen ? FALSE : TRUE);
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
}
auto hr = factory->CreateSwapChain(device_.Get(), &swapChainDesc, swapChain_.ReleaseAndGetAddressOf());
DXThrowIfFailed(hr, "failed to create DXGI swap chain");
}
void D3D11RenderContext::CreateBackBuffer(const VideoModeDescriptor& videoModeDesc)
{
HRESULT hr = 0;
/* Pick and store depth-stencil format */
depthStencilFormat_ = DXPickDepthStencilFormat(videoModeDesc.depthBits, videoModeDesc.stencilBits);
/* Get back buffer from swap chain */
hr = swapChain_->GetBuffer(0, IID_PPV_ARGS(backBuffer_.colorBuffer.ReleaseAndGetAddressOf()));
DXThrowIfFailed(hr, "failed to get D3D11 back buffer from swap chain");
/* Create back buffer RTV */
hr = device_->CreateRenderTargetView(backBuffer_.colorBuffer.Get(), nullptr, backBuffer_.rtv.ReleaseAndGetAddressOf());
DXThrowIfFailed(hr, "failed to create D3D11 render-target-view (RTV) for back buffer");
#if 0//TODO: allow to avoid a depth-buffer
if (videoModeDesc.depthBits > 0 || videoModeDesc.stencilBits > 0)
#endif
{
/* Create depth stencil texture */
D3D11_TEXTURE2D_DESC texDesc;
{
texDesc.Width = videoModeDesc.resolution.width;
texDesc.Height = videoModeDesc.resolution.height;
texDesc.MipLevels = 1;
texDesc.ArraySize = 1;
texDesc.Format = depthStencilFormat_;
texDesc.SampleDesc.Count = swapChainSamples_;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D11_USAGE_DEFAULT;
texDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
texDesc.CPUAccessFlags = 0;
texDesc.MiscFlags = 0;
}
hr = device_->CreateTexture2D(&texDesc, nullptr, backBuffer_.depthStencil.ReleaseAndGetAddressOf());
DXThrowIfFailed(hr, "failed to create D3D11 depth-texture for swap-chain");
/* Create DSV */
hr = device_->CreateDepthStencilView(backBuffer_.depthStencil.Get(), nullptr, backBuffer_.dsv.ReleaseAndGetAddressOf());
DXThrowIfFailed(hr, "failed to create D3D11 depth-stencil-view (DSV) for swap-chain");
}
}
void D3D11RenderContext::ResizeBackBuffer(const VideoModeDescriptor& videoModeDesc)
{
/* Check if the current RTV and DSV is from this render context */
/*ID3D11RenderTargetView* rtv = nullptr;
ID3D11DepthStencilView* dsv = nullptr;
context_->OMGetRenderTargets(1, &rtv, &dsv);
bool rtvFromThis = (rtv == backBuffer_.rtv.Get() && dsv == backBuffer_.dsv.Get());
auto r1 = rtv->Release();
auto r2 = dsv->Release();*/
/* Unset render targets (if the current RTV and DSV was from this render context) */
//if (rtvFromThis)
context_->OMSetRenderTargets(0, nullptr, nullptr);
/* Release buffers */
backBuffer_.colorBuffer.Reset();
backBuffer_.rtv.Reset();
backBuffer_.depthStencil.Reset();
backBuffer_.dsv.Reset();
/* Resize swap-chain buffers, let DXGI find out the client area, and preserve buffer count and format */
auto hr = swapChain_->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0);
DXThrowIfFailed(hr, "failed to resize DXGI swap-chain buffers");
/* Recreate back buffer and reset default render target */
CreateBackBuffer(videoModeDesc);
/* Reset render target (if the previous RTV and DSV was from this render context) */
//if (rtvFromThis)
/*{
ID3D11RenderTargetView* rtvList[] = { backBuffer_.rtv.Get() };
context_->OMSetRenderTargets(1, rtvList, backBuffer_.dsv.Get());
}*/
}
} // /namespace LLGL
// ================================================================================
<commit_msg>Added check for supported number of multi-samples to D3D11RenderContext.<commit_after>/*
* D3D11RenderContext.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015-2018 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "D3D11RenderContext.h"
#include "D3D11RenderSystem.h"
#include <LLGL/Platform/NativeHandle.h>
#include "../../Core/Helper.h"
#include "../DXCommon/DXTypes.h"
namespace LLGL
{
D3D11RenderContext::D3D11RenderContext(
IDXGIFactory* factory,
const ComPtr<ID3D11Device>& device,
const ComPtr<ID3D11DeviceContext>& context,
const RenderContextDescriptor& desc,
const std::shared_ptr<Surface>& surface) :
RenderContext { desc.videoMode, desc.vsync },
device_ { device },
context_ { context },
swapChainSamples_ { desc.multiSampling.SampleCount() }
{
/* Setup surface for the render context */
SetOrCreateSurface(surface, desc.videoMode, nullptr);
/* Create D3D objects */
CreateSwapChain(factory);
CreateBackBuffer(GetVideoMode());
/* Initialize v-sync */
OnSetVsync(desc.vsync);
}
void D3D11RenderContext::Present()
{
swapChain_->Present(swapChainInterval_, 0);
}
Format D3D11RenderContext::QueryColorFormat() const
{
return DXTypes::Unmap(colorFormat_);
}
Format D3D11RenderContext::QueryDepthStencilFormat() const
{
return DXTypes::Unmap(depthStencilFormat_);
}
const RenderPass* D3D11RenderContext::GetRenderPass() const
{
return nullptr; // dummy
}
//TODO: depth-stencil and color format does not change, only resizing is considered!
bool D3D11RenderContext::OnSetVideoMode(const VideoModeDescriptor& videoModeDesc)
{
const auto& prevVideoMode = GetVideoMode();
/* Resize back buffer */
if (prevVideoMode.resolution != videoModeDesc.resolution)
ResizeBackBuffer(videoModeDesc);
/* Switch fullscreen mode */
#if 0
if (prevVideoMode.fullscreen != videoModeDesc.fullscreen)
{
auto hr = swapChain_->SetFullscreenState(videoModeDesc.fullscreen ? TRUE : FALSE, nullptr);
return SUCCEEDED(hr);
}
#else
/* Switch fullscreen mode */
if (!SwitchFullscreenMode(videoModeDesc))
return false;
#endif
return true;
}
bool D3D11RenderContext::OnSetVsync(const VsyncDescriptor& vsyncDesc)
{
swapChainInterval_ = (vsyncDesc.enabled ? std::max(1u, std::min(vsyncDesc.interval, 4u)) : 0u);
return true;
}
/*
* ======= Private: =======
*/
static bool FintSuitableMultisamples(ID3D11Device* device, DXGI_FORMAT format, UINT& sampleCount)
{
bool result = true;
for (; sampleCount > 1; --sampleCount)
{
UINT numLevels = 0;
if (device->CheckMultisampleQualityLevels(format, sampleCount, &numLevels) == S_OK)
{
if (numLevels > 0)
return sampleCount;
else
result = false;
}
}
return result;
}
void D3D11RenderContext::CreateSwapChain(IDXGIFactory* factory)
{
/* Get current settings */
const auto& videoMode = GetVideoMode();
const auto& vsync = GetVsync();
/* Pick and store color format */
colorFormat_ = DXGI_FORMAT_R8G8B8A8_UNORM;//DXGI_FORMAT_B8G8R8A8_UNORM
/* Find suitable multi-samples for color format */
FintSuitableMultisamples(device_.Get(), colorFormat_, swapChainSamples_);
/* Create swap chain for window handle */
NativeHandle wndHandle;
GetSurface().GetNativeHandle(&wndHandle);
DXGI_SWAP_CHAIN_DESC swapChainDesc;
InitMemory(swapChainDesc);
{
swapChainDesc.BufferDesc.Width = videoMode.resolution.width;
swapChainDesc.BufferDesc.Height = videoMode.resolution.height;
swapChainDesc.BufferDesc.Format = colorFormat_;
swapChainDesc.BufferDesc.RefreshRate.Numerator = vsync.refreshRate;
swapChainDesc.BufferDesc.RefreshRate.Denominator = vsync.interval;
swapChainDesc.SampleDesc.Count = swapChainSamples_;
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = (videoMode.swapChainSize == 3 ? 2 : 1);
swapChainDesc.OutputWindow = wndHandle.window;
swapChainDesc.Windowed = TRUE;//(videoMode.fullscreen ? FALSE : TRUE);
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
}
auto hr = factory->CreateSwapChain(device_.Get(), &swapChainDesc, swapChain_.ReleaseAndGetAddressOf());
DXThrowIfFailed(hr, "failed to create DXGI swap chain");
}
void D3D11RenderContext::CreateBackBuffer(const VideoModeDescriptor& videoModeDesc)
{
HRESULT hr = 0;
/* Pick and store depth-stencil format */
depthStencilFormat_ = DXPickDepthStencilFormat(videoModeDesc.depthBits, videoModeDesc.stencilBits);
/* Get back buffer from swap chain */
hr = swapChain_->GetBuffer(0, IID_PPV_ARGS(backBuffer_.colorBuffer.ReleaseAndGetAddressOf()));
DXThrowIfFailed(hr, "failed to get D3D11 back buffer from swap chain");
/* Create back buffer RTV */
hr = device_->CreateRenderTargetView(backBuffer_.colorBuffer.Get(), nullptr, backBuffer_.rtv.ReleaseAndGetAddressOf());
DXThrowIfFailed(hr, "failed to create D3D11 render-target-view (RTV) for back buffer");
#if 0//TODO: allow to avoid a depth-buffer
if (videoModeDesc.depthBits > 0 || videoModeDesc.stencilBits > 0)
#endif
{
/* Create depth stencil texture */
D3D11_TEXTURE2D_DESC texDesc;
{
texDesc.Width = videoModeDesc.resolution.width;
texDesc.Height = videoModeDesc.resolution.height;
texDesc.MipLevels = 1;
texDesc.ArraySize = 1;
texDesc.Format = depthStencilFormat_;
texDesc.SampleDesc.Count = swapChainSamples_;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D11_USAGE_DEFAULT;
texDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
texDesc.CPUAccessFlags = 0;
texDesc.MiscFlags = 0;
}
hr = device_->CreateTexture2D(&texDesc, nullptr, backBuffer_.depthStencil.ReleaseAndGetAddressOf());
DXThrowIfFailed(hr, "failed to create D3D11 depth-texture for swap-chain");
/* Create DSV */
hr = device_->CreateDepthStencilView(backBuffer_.depthStencil.Get(), nullptr, backBuffer_.dsv.ReleaseAndGetAddressOf());
DXThrowIfFailed(hr, "failed to create D3D11 depth-stencil-view (DSV) for swap-chain");
}
}
void D3D11RenderContext::ResizeBackBuffer(const VideoModeDescriptor& videoModeDesc)
{
/* Check if the current RTV and DSV is from this render context */
/*ID3D11RenderTargetView* rtv = nullptr;
ID3D11DepthStencilView* dsv = nullptr;
context_->OMGetRenderTargets(1, &rtv, &dsv);
bool rtvFromThis = (rtv == backBuffer_.rtv.Get() && dsv == backBuffer_.dsv.Get());
auto r1 = rtv->Release();
auto r2 = dsv->Release();*/
/* Unset render targets (if the current RTV and DSV was from this render context) */
//if (rtvFromThis)
context_->OMSetRenderTargets(0, nullptr, nullptr);
/* Release buffers */
backBuffer_.colorBuffer.Reset();
backBuffer_.rtv.Reset();
backBuffer_.depthStencil.Reset();
backBuffer_.dsv.Reset();
/* Resize swap-chain buffers, let DXGI find out the client area, and preserve buffer count and format */
auto hr = swapChain_->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0);
DXThrowIfFailed(hr, "failed to resize DXGI swap-chain buffers");
/* Recreate back buffer and reset default render target */
CreateBackBuffer(videoModeDesc);
/* Reset render target (if the previous RTV and DSV was from this render context) */
//if (rtvFromThis)
/*{
ID3D11RenderTargetView* rtvList[] = { backBuffer_.rtv.Get() };
context_->OMSetRenderTargets(1, rtvList, backBuffer_.dsv.Get());
}*/
}
} // /namespace LLGL
// ================================================================================
<|endoftext|> |
<commit_before>#include "person.h"
#include <algorithm>
#include <string>
using namespace std;
Person::Person()
{
}
Person::Person(string name, char gender, int birth, int death, string comment, int id)
{
_name = name;
_gender = gender;
_yearOfBirth = birth;
_yearOfDeath = death;
_comment = comment;
_id = id;
if(_yearOfDeath > 0)
{
_age = _yearOfDeath - _yearOfBirth;
}
else
{
_age = 2016 - _yearOfBirth;
}
_lowerCaseName = name;
transform(_lowerCaseName.begin(), _lowerCaseName.end(), _lowerCaseName.begin(), ::tolower);
}
<commit_msg>eitt tab<commit_after>#include "person.h"
#include <algorithm>
#include <string>
using namespace std;
Person::Person()
{
}
Person::Person(string name, char gender, int birth, int death, string comment, int id)
{
_name = name;
_gender = gender;
_yearOfBirth = birth;
_yearOfDeath = death;
_comment = comment;
_id = id;
if(_yearOfDeath > 0)
{
_age = _yearOfDeath - _yearOfBirth;
}
else
{
_age = 2016 - _yearOfBirth;
}
_lowerCaseName = name;
transform(_lowerCaseName.begin(), _lowerCaseName.end(), _lowerCaseName.begin(), ::tolower);
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2018 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#undef NDEBUG
// sg
#include "SceneGraph.h"
#include "sg/geometry/Spheres.h"
#include "detail_xyz/Model.h"
namespace ospray {
namespace sg {
void importXYZ(const std::shared_ptr<Node> &world, const FileName &fileName)
{
particle::Model m;
if (fileName.ext() == "xyz")
m.loadXYZ(fileName);
else if (fileName.ext() == "xyz2")
m.loadXYZ2(fileName);
else if (fileName.ext() == "xyz3")
m.loadXYZ3(fileName);
for (size_t i = 0; i < m.atomType.size(); i++) {
auto name = fileName.str() + "_type_" + std::to_string(i);
auto spGeom = createNode(name + "_geometry",
"Spheres")->nodeAs<Spheres>();
spGeom->createChild("bytes_per_sphere", "int",
int(sizeof(particle::Model::Atom)));
spGeom->createChild("offset_center", "int", int(0));
spGeom->createChild("offset_radius", "int", int(3*sizeof(float)));
auto spheres =
std::make_shared<DataVectorT<particle::Model::Atom, OSP_RAW>>();
spheres->setName("spheres");
auto atomTypeID = m.atomTypeByName[m.atomType[i]->name];
spheres->v = std::move(m.atom[atomTypeID]);
spGeom->add(spheres);
auto &material = spGeom->child("material");
material["d"] = 1.f;
material["Kd"] = m.atomType[i]->color;
material["Ks"] = vec3f(0.2f, 0.2f, 0.2f);
auto model = createNode(name + "_model", "Model");
model->add(spGeom);
auto instance = createNode(name + "_instance", "Instance");
instance->setChild("model", model);
model->setParent(instance);
world->add(instance);
}
}
} // ::ospray::sg
} // ::ospray
<commit_msg>create a material child for XYZ files<commit_after>// ======================================================================== //
// Copyright 2009-2018 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#undef NDEBUG
// sg
#include "SceneGraph.h"
#include "sg/geometry/Spheres.h"
#include "detail_xyz/Model.h"
namespace ospray {
namespace sg {
void importXYZ(const std::shared_ptr<Node> &world, const FileName &fileName)
{
particle::Model m;
if (fileName.ext() == "xyz")
m.loadXYZ(fileName);
else if (fileName.ext() == "xyz2")
m.loadXYZ2(fileName);
else if (fileName.ext() == "xyz3")
m.loadXYZ3(fileName);
for (size_t i = 0; i < m.atomType.size(); i++) {
auto name = fileName.str() + "_type_" + std::to_string(i);
auto spGeom = createNode(name + "_geometry",
"Spheres")->nodeAs<Spheres>();
spGeom->createChild("bytes_per_sphere", "int",
int(sizeof(particle::Model::Atom)));
spGeom->createChild("offset_center", "int", int(0));
spGeom->createChild("offset_radius", "int", int(3*sizeof(float)));
spGeom->createChild("material", "Material");
auto spheres =
std::make_shared<DataVectorT<particle::Model::Atom, OSP_RAW>>();
spheres->setName("spheres");
auto atomTypeID = m.atomTypeByName[m.atomType[i]->name];
spheres->v = std::move(m.atom[atomTypeID]);
spGeom->add(spheres);
auto &material = spGeom->child("material");
material["d"] = 1.f;
material["Kd"] = m.atomType[i]->color;
material["Ks"] = vec3f(0.2f, 0.2f, 0.2f);
auto model = createNode(name + "_model", "Model");
model->add(spGeom);
auto instance = createNode(name + "_instance", "Instance");
instance->setChild("model", model);
model->setParent(instance);
world->add(instance);
}
}
} // ::ospray::sg
} // ::ospray
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "RestServer/FortuneFeature.h"
#include "Logger/Logger.h"
#include "ProgramOptions/Parameters.h"
#include "ProgramOptions/ProgramOptions.h"
#include "Random/RandomGenerator.h"
using namespace arangodb;
using namespace arangodb::options;
namespace {
static char const* cookies[] = {
"The number of computer scientists in a room is inversely proportional to the number of bugs in their code.",
"Unnamed Law: If it happens, it must be possible.",
"Of course there's no reason for it, it's just our policy.",
"Your mode of life will be changed to ASCII.",
"My program works if i take out the bugs",
"Your lucky number has been disconnected.",
"Any sufficiently advanced bug is indistinguishable from a feature.",
"Real Users hate Real Programmers.",
"Reality is just a crutch for people who can't handle science fiction.",
"You're definitely on their list. The question to ask next is what list it is.",
"Any given program will expand to fill available memory.",
"Steinbach's Guideline for Systems Programming: Never test for an error condition you don't know how to handle.",
"Bug, n: A son of a glitch.",
"Recursion n.: See Recursion.",
"I think we're in trouble. -- Han Solo",
"18,446,744,073,709,551,616 is a big number",
"Civilization, as we know it, will end sometime this evening. See SYSNOTE tomorrow for more information.",
"Everything ends badly. Otherwise it wouldn't end.",
"The moon may be smaller than Earth, but it's further away.",
"Never make anything simple and efficient when a way can be found to make it complex and wonderful.",
""
};
} // namespace
FortuneFeature::FortuneFeature(
application_features::ApplicationServer& server)
: ApplicationFeature(server, "Fortune"), _fortune(false) {
startsAfter("Bootstrap");
}
void FortuneFeature::collectOptions(std::shared_ptr<ProgramOptions> options) {
options->addHiddenOption("fortune", "show fortune cookie on startup",
new BooleanParameter(&_fortune));
}
void FortuneFeature::start() {
if (!_fortune) {
return;
}
uint32_t r = RandomGenerator::interval(sizeof(::cookies) / sizeof(::cookies)[0]);
if (strlen(::cookies[r]) > 0) {
LOG_TOPIC(INFO, Logger::FIXME) << ::cookies[r];
}
}
<commit_msg>fix cast for macosx<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "RestServer/FortuneFeature.h"
#include "Logger/Logger.h"
#include "ProgramOptions/Parameters.h"
#include "ProgramOptions/ProgramOptions.h"
#include "Random/RandomGenerator.h"
using namespace arangodb;
using namespace arangodb::options;
namespace {
static char const* cookies[] = {
"The number of computer scientists in a room is inversely proportional to the number of bugs in their code.",
"Unnamed Law: If it happens, it must be possible.",
"Of course there's no reason for it, it's just our policy.",
"Your mode of life will be changed to ASCII.",
"My program works if i take out the bugs",
"Your lucky number has been disconnected.",
"Any sufficiently advanced bug is indistinguishable from a feature.",
"Real Users hate Real Programmers.",
"Reality is just a crutch for people who can't handle science fiction.",
"You're definitely on their list. The question to ask next is what list it is.",
"Any given program will expand to fill available memory.",
"Steinbach's Guideline for Systems Programming: Never test for an error condition you don't know how to handle.",
"Bug, n: A son of a glitch.",
"Recursion n.: See Recursion.",
"I think we're in trouble. -- Han Solo",
"18,446,744,073,709,551,616 is a big number",
"Civilization, as we know it, will end sometime this evening. See SYSNOTE tomorrow for more information.",
"Everything ends badly. Otherwise it wouldn't end.",
"The moon may be smaller than Earth, but it's further away.",
"Never make anything simple and efficient when a way can be found to make it complex and wonderful.",
""
};
} // namespace
FortuneFeature::FortuneFeature(
application_features::ApplicationServer& server)
: ApplicationFeature(server, "Fortune"), _fortune(false) {
startsAfter("Bootstrap");
}
void FortuneFeature::collectOptions(std::shared_ptr<ProgramOptions> options) {
options->addHiddenOption("fortune", "show fortune cookie on startup",
new BooleanParameter(&_fortune));
}
void FortuneFeature::start() {
if (!_fortune) {
return;
}
uint32_t r = RandomGenerator::interval(static_cast<uint32_t>(sizeof(::cookies) / sizeof(::cookies)[0]));
if (strlen(::cookies[r]) > 0) {
LOG_TOPIC(INFO, Logger::FIXME) << ::cookies[r];
}
}
<|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 "ash/accelerators/accelerator_table.h"
#include "base/basictypes.h"
#include "ui/base/events.h"
namespace ash {
const AcceleratorData kAcceleratorData[] = {
// We have to define 3 entries for Shift+Alt. VKEY_[LR]MENU might be sent to
// the accelerator controller when RenderWidgetHostViewAura is focused, and
// VKEY_MENU might be when it's not (e.g. when NativeWidgetAura is focused).
{ false, ui::VKEY_LMENU, ui::EF_SHIFT_DOWN, NEXT_IME },
{ false, ui::VKEY_MENU, ui::EF_SHIFT_DOWN, NEXT_IME },
{ false, ui::VKEY_RMENU, ui::EF_SHIFT_DOWN, NEXT_IME },
// The same is true for Alt+Shift.
{ false, ui::VKEY_LSHIFT, ui::EF_ALT_DOWN, NEXT_IME },
{ false, ui::VKEY_SHIFT, ui::EF_ALT_DOWN, NEXT_IME },
{ false, ui::VKEY_RSHIFT, ui::EF_ALT_DOWN, NEXT_IME },
#if defined(OS_CHROMEOS)
// When X11 is in use, a modifier-only accelerator like Shift+Alt could be
// sent to the accelerator controller in unnormalized form (e.g. when
// NativeWidgetAura is focused). To handle such accelerators, the following 2
// entries are necessary. For more details, see crbug.com/127142#c8 and #c14.
{ false, ui::VKEY_MENU, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN, NEXT_IME },
{ false, ui::VKEY_SHIFT, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN, NEXT_IME },
#endif
{ true, ui::VKEY_SPACE, ui::EF_CONTROL_DOWN, PREVIOUS_IME },
// Shortcuts for Japanese IME.
{ true, ui::VKEY_CONVERT, ui::EF_NONE, SWITCH_IME },
{ true, ui::VKEY_NONCONVERT, ui::EF_NONE, SWITCH_IME },
{ true, ui::VKEY_DBE_SBCSCHAR, ui::EF_NONE, SWITCH_IME },
{ true, ui::VKEY_DBE_DBCSCHAR, ui::EF_NONE, SWITCH_IME },
// Shortcut for Koren IME.
{ true, ui::VKEY_HANGUL, ui::EF_NONE, SWITCH_IME },
{ true, ui::VKEY_TAB,
ui::EF_ALT_DOWN, CYCLE_FORWARD_MRU },
{ true, ui::VKEY_TAB, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN,
CYCLE_BACKWARD_MRU },
{ true, ui::VKEY_F5, ui::EF_NONE, CYCLE_FORWARD_LINEAR },
#if defined(OS_CHROMEOS)
{ true, ui::VKEY_BRIGHTNESS_DOWN, ui::EF_NONE, BRIGHTNESS_DOWN },
{ true, ui::VKEY_BRIGHTNESS_UP, ui::EF_NONE, BRIGHTNESS_UP },
{ true, ui::VKEY_F4, ui::EF_CONTROL_DOWN, CYCLE_DISPLAY_MODE },
{ true, ui::VKEY_L, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN, LOCK_SCREEN },
{ true, ui::VKEY_O, ui::EF_CONTROL_DOWN, OPEN_FILE_MANAGER_DIALOG },
{ true, ui::VKEY_M, ui::EF_CONTROL_DOWN, OPEN_FILE_MANAGER_TAB },
{ true, ui::VKEY_T, ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN, OPEN_CROSH },
#endif
{ true, ui::VKEY_Q, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN, EXIT },
{ true, ui::VKEY_Z, ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN,
TOGGLE_SPOKEN_FEEDBACK },
// When you change the shortcuts for NEW_INCOGNITO_WINDOW, NEW_WINDOW, or
// NEW_TAB, you also need to modify
// ToolbarView::GetAcceleratorForCommandId() in
// chrome/browser/ui/views/toolbar_view.cc.
{ true, ui::VKEY_N, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN,
NEW_INCOGNITO_WINDOW },
{ true, ui::VKEY_N, ui::EF_CONTROL_DOWN, NEW_WINDOW },
{ true, ui::VKEY_T, ui::EF_CONTROL_DOWN, NEW_TAB },
{ true, ui::VKEY_F5, ui::EF_SHIFT_DOWN, CYCLE_BACKWARD_LINEAR },
{ true, ui::VKEY_T, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN, RESTORE_TAB },
{ true, ui::VKEY_F5, ui::EF_CONTROL_DOWN, TAKE_SCREENSHOT },
{ true, ui::VKEY_F5, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN,
TAKE_PARTIAL_SCREENSHOT },
{ true, ui::VKEY_PRINT, ui::EF_NONE, TAKE_SCREENSHOT },
// On Chrome OS, Search key is mapped to LWIN.
{ true, ui::VKEY_LWIN, ui::EF_NONE, TOGGLE_APP_LIST },
{ true, ui::VKEY_BROWSER_SEARCH, ui::EF_NONE, TOGGLE_APP_LIST },
{ true, ui::VKEY_LWIN, ui::EF_SHIFT_DOWN, TOGGLE_CAPS_LOCK },
{ true, ui::VKEY_F6, ui::EF_NONE, BRIGHTNESS_DOWN },
{ true, ui::VKEY_F7, ui::EF_NONE, BRIGHTNESS_UP },
{ true, ui::VKEY_F8, ui::EF_NONE, VOLUME_MUTE },
{ true, ui::VKEY_VOLUME_MUTE, ui::EF_NONE, VOLUME_MUTE },
{ true, ui::VKEY_F9, ui::EF_NONE, VOLUME_DOWN },
{ true, ui::VKEY_VOLUME_DOWN, ui::EF_NONE, VOLUME_DOWN },
{ true, ui::VKEY_F10, ui::EF_NONE, VOLUME_UP },
{ true, ui::VKEY_VOLUME_UP, ui::EF_NONE, VOLUME_UP },
{ true, ui::VKEY_L, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN, FOCUS_LAUNCHER },
{ true, ui::VKEY_S, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN, FOCUS_SYSTEM_TRAY },
{ true, ui::VKEY_F7, ui::EF_CONTROL_DOWN, MAGNIFY_SCREEN_ZOOM_IN},
{ true, ui::VKEY_F6, ui::EF_CONTROL_DOWN, MAGNIFY_SCREEN_ZOOM_OUT},
{ true, ui::VKEY_OEM_2, ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN,
SHOW_KEYBOARD_OVERLAY },
{ true, ui::VKEY_OEM_2,
ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN,
SHOW_KEYBOARD_OVERLAY },
{ true, ui::VKEY_F1, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN, SHOW_OAK },
{ true, ui::VKEY_ESCAPE, ui::EF_SHIFT_DOWN, SHOW_TASK_MANAGER },
{ true, ui::VKEY_1, ui::EF_ALT_DOWN, SELECT_WIN_0 },
{ true, ui::VKEY_2, ui::EF_ALT_DOWN, SELECT_WIN_1 },
{ true, ui::VKEY_3, ui::EF_ALT_DOWN, SELECT_WIN_2 },
{ true, ui::VKEY_4, ui::EF_ALT_DOWN, SELECT_WIN_3 },
{ true, ui::VKEY_5, ui::EF_ALT_DOWN, SELECT_WIN_4 },
{ true, ui::VKEY_6, ui::EF_ALT_DOWN, SELECT_WIN_5 },
{ true, ui::VKEY_7, ui::EF_ALT_DOWN, SELECT_WIN_6 },
{ true, ui::VKEY_8, ui::EF_ALT_DOWN, SELECT_WIN_7 },
{ true, ui::VKEY_9, ui::EF_ALT_DOWN, SELECT_LAST_WIN },
// Window management shortcuts.
{ true, ui::VKEY_OEM_4, ui::EF_ALT_DOWN, WINDOW_SNAP_LEFT },
{ true, ui::VKEY_OEM_6, ui::EF_ALT_DOWN, WINDOW_SNAP_RIGHT },
{ true, ui::VKEY_OEM_MINUS, ui::EF_ALT_DOWN, WINDOW_MINIMIZE },
{ true, ui::VKEY_OEM_PLUS, ui::EF_ALT_DOWN, WINDOW_MAXIMIZE_RESTORE },
{ true, ui::VKEY_OEM_PLUS, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN,
WINDOW_POSITION_CENTER },
{ true, ui::VKEY_F2, ui::EF_CONTROL_DOWN, FOCUS_NEXT_PANE },
{ true, ui::VKEY_F1, ui::EF_CONTROL_DOWN, FOCUS_PREVIOUS_PANE },
{ true, ui::VKEY_F3,
ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN,
ROTATE_WINDOWS },
{ true, ui::VKEY_HOME, ui::EF_CONTROL_DOWN, ROTATE_SCREEN },
{ true, ui::VKEY_B, ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN,
TOGGLE_DESKTOP_BACKGROUND_MODE },
{ true, ui::VKEY_F11, ui::EF_CONTROL_DOWN, TOGGLE_ROOT_WINDOW_FULL_SCREEN },
// For testing on systems where Alt-Tab is already mapped.
{ true, ui::VKEY_W, ui::EF_ALT_DOWN, CYCLE_FORWARD_MRU },
{ true, ui::VKEY_W, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN, CYCLE_BACKWARD_MRU },
{ true, ui::VKEY_F4, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN, DISPLAY_CYCLE },
{ true, ui::VKEY_F4, ui::EF_SHIFT_DOWN, DISPLAY_ADD_REMOVE },
{ true, ui::VKEY_HOME, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN,
DISPLAY_TOGGLE_SCALE },
#if !defined(NDEBUG)
{ true, ui::VKEY_L, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN,
PRINT_LAYER_HIERARCHY },
{ true, ui::VKEY_W, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN,
PRINT_WINDOW_HIERARCHY },
#endif
// TODO(yusukes): Handle VKEY_MEDIA_STOP, VKEY_MEDIA_PLAY_PAUSE,
// VKEY_MEDIA_LAUNCH_MAIL, and VKEY_MEDIA_LAUNCH_APP2 (aka Calculator button).
};
const size_t kAcceleratorDataLength = arraysize(kAcceleratorData);
const AcceleratorAction kReservedActions[] = {
CYCLE_BACKWARD_MRU,
CYCLE_FORWARD_MRU,
};
const size_t kReservedActionsLength = arraysize(kReservedActions);
const AcceleratorAction kActionsAllowedAtLoginOrLockScreen[] = {
BRIGHTNESS_DOWN,
BRIGHTNESS_UP,
#if defined(OS_CHROMEOS)
CYCLE_DISPLAY_MODE,
#endif // defined(OS_CHROMEOS)
NEXT_IME,
PREVIOUS_IME,
SWITCH_IME, // Switch to another IME depending on the accelerator.
TAKE_SCREENSHOT,
TAKE_PARTIAL_SCREENSHOT,
TOGGLE_CAPS_LOCK,
TOGGLE_SPOKEN_FEEDBACK,
VOLUME_DOWN,
VOLUME_MUTE,
VOLUME_UP,
ROTATE_WINDOWS,
#if !defined(NDEBUG)
PRINT_LAYER_HIERARCHY,
PRINT_WINDOW_HIERARCHY,
ROTATE_SCREEN,
#endif
};
const size_t kActionsAllowedAtLoginOrLockScreenLength =
arraysize(kActionsAllowedAtLoginOrLockScreen);
const AcceleratorAction kActionsAllowedAtLockScreen[] = {
EXIT,
};
const size_t kActionsAllowedAtLockScreenLength =
arraysize(kActionsAllowedAtLockScreen);
} // namespace ash
<commit_msg>Support F3 and F4 keys on an Apple keyboard.<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 "ash/accelerators/accelerator_table.h"
#include "base/basictypes.h"
#include "ui/base/events.h"
namespace ash {
const AcceleratorData kAcceleratorData[] = {
// We have to define 3 entries for Shift+Alt. VKEY_[LR]MENU might be sent to
// the accelerator controller when RenderWidgetHostViewAura is focused, and
// VKEY_MENU might be when it's not (e.g. when NativeWidgetAura is focused).
{ false, ui::VKEY_LMENU, ui::EF_SHIFT_DOWN, NEXT_IME },
{ false, ui::VKEY_MENU, ui::EF_SHIFT_DOWN, NEXT_IME },
{ false, ui::VKEY_RMENU, ui::EF_SHIFT_DOWN, NEXT_IME },
// The same is true for Alt+Shift.
{ false, ui::VKEY_LSHIFT, ui::EF_ALT_DOWN, NEXT_IME },
{ false, ui::VKEY_SHIFT, ui::EF_ALT_DOWN, NEXT_IME },
{ false, ui::VKEY_RSHIFT, ui::EF_ALT_DOWN, NEXT_IME },
#if defined(OS_CHROMEOS)
// When X11 is in use, a modifier-only accelerator like Shift+Alt could be
// sent to the accelerator controller in unnormalized form (e.g. when
// NativeWidgetAura is focused). To handle such accelerators, the following 2
// entries are necessary. For more details, see crbug.com/127142#c8 and #c14.
{ false, ui::VKEY_MENU, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN, NEXT_IME },
{ false, ui::VKEY_SHIFT, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN, NEXT_IME },
#endif
{ true, ui::VKEY_SPACE, ui::EF_CONTROL_DOWN, PREVIOUS_IME },
// Shortcuts for Japanese IME.
{ true, ui::VKEY_CONVERT, ui::EF_NONE, SWITCH_IME },
{ true, ui::VKEY_NONCONVERT, ui::EF_NONE, SWITCH_IME },
{ true, ui::VKEY_DBE_SBCSCHAR, ui::EF_NONE, SWITCH_IME },
{ true, ui::VKEY_DBE_DBCSCHAR, ui::EF_NONE, SWITCH_IME },
// Shortcut for Koren IME.
{ true, ui::VKEY_HANGUL, ui::EF_NONE, SWITCH_IME },
{ true, ui::VKEY_TAB,
ui::EF_ALT_DOWN, CYCLE_FORWARD_MRU },
{ true, ui::VKEY_TAB, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN,
CYCLE_BACKWARD_MRU },
{ true, ui::VKEY_F5, ui::EF_NONE, CYCLE_FORWARD_LINEAR },
{ true, ui::VKEY_MEDIA_LAUNCH_APP1, ui::EF_NONE, CYCLE_FORWARD_LINEAR },
#if defined(OS_CHROMEOS)
{ true, ui::VKEY_BRIGHTNESS_DOWN, ui::EF_NONE, BRIGHTNESS_DOWN },
{ true, ui::VKEY_BRIGHTNESS_UP, ui::EF_NONE, BRIGHTNESS_UP },
{ true, ui::VKEY_F4, ui::EF_CONTROL_DOWN, CYCLE_DISPLAY_MODE },
{ true, ui::VKEY_L, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN, LOCK_SCREEN },
{ true, ui::VKEY_O, ui::EF_CONTROL_DOWN, OPEN_FILE_MANAGER_DIALOG },
{ true, ui::VKEY_M, ui::EF_CONTROL_DOWN, OPEN_FILE_MANAGER_TAB },
{ true, ui::VKEY_T, ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN, OPEN_CROSH },
#endif
{ true, ui::VKEY_Q, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN, EXIT },
{ true, ui::VKEY_Z, ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN,
TOGGLE_SPOKEN_FEEDBACK },
// When you change the shortcuts for NEW_INCOGNITO_WINDOW, NEW_WINDOW, or
// NEW_TAB, you also need to modify
// ToolbarView::GetAcceleratorForCommandId() in
// chrome/browser/ui/views/toolbar_view.cc.
{ true, ui::VKEY_N, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN,
NEW_INCOGNITO_WINDOW },
{ true, ui::VKEY_N, ui::EF_CONTROL_DOWN, NEW_WINDOW },
{ true, ui::VKEY_T, ui::EF_CONTROL_DOWN, NEW_TAB },
{ true, ui::VKEY_F5, ui::EF_SHIFT_DOWN, CYCLE_BACKWARD_LINEAR },
{ true, ui::VKEY_MEDIA_LAUNCH_APP1, ui::EF_SHIFT_DOWN,
CYCLE_BACKWARD_LINEAR },
{ true, ui::VKEY_T, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN, RESTORE_TAB },
{ true, ui::VKEY_F5, ui::EF_CONTROL_DOWN, TAKE_SCREENSHOT },
{ true, ui::VKEY_F5, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN,
TAKE_PARTIAL_SCREENSHOT },
{ true, ui::VKEY_PRINT, ui::EF_NONE, TAKE_SCREENSHOT },
// On Chrome OS, Search key is mapped to LWIN.
{ true, ui::VKEY_LWIN, ui::EF_NONE, TOGGLE_APP_LIST },
{ true, ui::VKEY_MEDIA_LAUNCH_APP2, ui::EF_NONE, TOGGLE_APP_LIST },
{ true, ui::VKEY_BROWSER_SEARCH, ui::EF_NONE, TOGGLE_APP_LIST },
{ true, ui::VKEY_LWIN, ui::EF_SHIFT_DOWN, TOGGLE_CAPS_LOCK },
{ true, ui::VKEY_F6, ui::EF_NONE, BRIGHTNESS_DOWN },
{ true, ui::VKEY_F7, ui::EF_NONE, BRIGHTNESS_UP },
{ true, ui::VKEY_F8, ui::EF_NONE, VOLUME_MUTE },
{ true, ui::VKEY_VOLUME_MUTE, ui::EF_NONE, VOLUME_MUTE },
{ true, ui::VKEY_F9, ui::EF_NONE, VOLUME_DOWN },
{ true, ui::VKEY_VOLUME_DOWN, ui::EF_NONE, VOLUME_DOWN },
{ true, ui::VKEY_F10, ui::EF_NONE, VOLUME_UP },
{ true, ui::VKEY_VOLUME_UP, ui::EF_NONE, VOLUME_UP },
{ true, ui::VKEY_L, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN, FOCUS_LAUNCHER },
{ true, ui::VKEY_S, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN, FOCUS_SYSTEM_TRAY },
{ true, ui::VKEY_F7, ui::EF_CONTROL_DOWN, MAGNIFY_SCREEN_ZOOM_IN},
{ true, ui::VKEY_F6, ui::EF_CONTROL_DOWN, MAGNIFY_SCREEN_ZOOM_OUT},
{ true, ui::VKEY_OEM_2, ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN,
SHOW_KEYBOARD_OVERLAY },
{ true, ui::VKEY_OEM_2,
ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN,
SHOW_KEYBOARD_OVERLAY },
{ true, ui::VKEY_F1, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN, SHOW_OAK },
{ true, ui::VKEY_ESCAPE, ui::EF_SHIFT_DOWN, SHOW_TASK_MANAGER },
{ true, ui::VKEY_1, ui::EF_ALT_DOWN, SELECT_WIN_0 },
{ true, ui::VKEY_2, ui::EF_ALT_DOWN, SELECT_WIN_1 },
{ true, ui::VKEY_3, ui::EF_ALT_DOWN, SELECT_WIN_2 },
{ true, ui::VKEY_4, ui::EF_ALT_DOWN, SELECT_WIN_3 },
{ true, ui::VKEY_5, ui::EF_ALT_DOWN, SELECT_WIN_4 },
{ true, ui::VKEY_6, ui::EF_ALT_DOWN, SELECT_WIN_5 },
{ true, ui::VKEY_7, ui::EF_ALT_DOWN, SELECT_WIN_6 },
{ true, ui::VKEY_8, ui::EF_ALT_DOWN, SELECT_WIN_7 },
{ true, ui::VKEY_9, ui::EF_ALT_DOWN, SELECT_LAST_WIN },
// Window management shortcuts.
{ true, ui::VKEY_OEM_4, ui::EF_ALT_DOWN, WINDOW_SNAP_LEFT },
{ true, ui::VKEY_OEM_6, ui::EF_ALT_DOWN, WINDOW_SNAP_RIGHT },
{ true, ui::VKEY_OEM_MINUS, ui::EF_ALT_DOWN, WINDOW_MINIMIZE },
{ true, ui::VKEY_OEM_PLUS, ui::EF_ALT_DOWN, WINDOW_MAXIMIZE_RESTORE },
{ true, ui::VKEY_OEM_PLUS, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN,
WINDOW_POSITION_CENTER },
{ true, ui::VKEY_F2, ui::EF_CONTROL_DOWN, FOCUS_NEXT_PANE },
{ true, ui::VKEY_F1, ui::EF_CONTROL_DOWN, FOCUS_PREVIOUS_PANE },
{ true, ui::VKEY_F3,
ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN,
ROTATE_WINDOWS },
{ true, ui::VKEY_HOME, ui::EF_CONTROL_DOWN, ROTATE_SCREEN },
{ true, ui::VKEY_B, ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN,
TOGGLE_DESKTOP_BACKGROUND_MODE },
{ true, ui::VKEY_F11, ui::EF_CONTROL_DOWN, TOGGLE_ROOT_WINDOW_FULL_SCREEN },
// For testing on systems where Alt-Tab is already mapped.
{ true, ui::VKEY_W, ui::EF_ALT_DOWN, CYCLE_FORWARD_MRU },
{ true, ui::VKEY_W, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN, CYCLE_BACKWARD_MRU },
{ true, ui::VKEY_F4, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN, DISPLAY_CYCLE },
{ true, ui::VKEY_F4, ui::EF_SHIFT_DOWN, DISPLAY_ADD_REMOVE },
{ true, ui::VKEY_HOME, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN,
DISPLAY_TOGGLE_SCALE },
#if !defined(NDEBUG)
{ true, ui::VKEY_L, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN,
PRINT_LAYER_HIERARCHY },
{ true, ui::VKEY_W, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN,
PRINT_WINDOW_HIERARCHY },
#endif
// TODO(yusukes): Handle VKEY_MEDIA_STOP, VKEY_MEDIA_PLAY_PAUSE,
// VKEY_MEDIA_LAUNCH_MAIL, and VKEY_MEDIA_LAUNCH_APP2 (aka Calculator button).
};
const size_t kAcceleratorDataLength = arraysize(kAcceleratorData);
const AcceleratorAction kReservedActions[] = {
CYCLE_BACKWARD_MRU,
CYCLE_FORWARD_MRU,
};
const size_t kReservedActionsLength = arraysize(kReservedActions);
const AcceleratorAction kActionsAllowedAtLoginOrLockScreen[] = {
BRIGHTNESS_DOWN,
BRIGHTNESS_UP,
#if defined(OS_CHROMEOS)
CYCLE_DISPLAY_MODE,
#endif // defined(OS_CHROMEOS)
NEXT_IME,
PREVIOUS_IME,
SWITCH_IME, // Switch to another IME depending on the accelerator.
TAKE_SCREENSHOT,
TAKE_PARTIAL_SCREENSHOT,
TOGGLE_CAPS_LOCK,
TOGGLE_SPOKEN_FEEDBACK,
VOLUME_DOWN,
VOLUME_MUTE,
VOLUME_UP,
ROTATE_WINDOWS,
#if !defined(NDEBUG)
PRINT_LAYER_HIERARCHY,
PRINT_WINDOW_HIERARCHY,
ROTATE_SCREEN,
#endif
};
const size_t kActionsAllowedAtLoginOrLockScreenLength =
arraysize(kActionsAllowedAtLoginOrLockScreen);
const AcceleratorAction kActionsAllowedAtLockScreen[] = {
EXIT,
};
const size_t kActionsAllowedAtLockScreenLength =
arraysize(kActionsAllowedAtLockScreen);
} // namespace ash
<|endoftext|> |
<commit_before>#ifndef STAN_IO_STAN_CSV_READER_HPP
#define STAN_IO_STAN_CSV_READER_HPP
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <Eigen/Dense>
#include <istream>
#include <iostream>
#include <sstream>
#include <string>
namespace stan {
namespace io {
// FIXME: should consolidate with the options from
// the command line in stan::lang
struct stan_csv_metadata {
int stan_version_major;
int stan_version_minor;
int stan_version_patch;
std::string model;
std::string data;
std::string init;
size_t chain_id;
size_t seed;
bool random_seed;
size_t num_samples;
size_t num_warmup;
bool save_warmup;
size_t thin;
bool append_samples;
std::string algorithm;
std::string engine;
stan_csv_metadata()
: stan_version_major(0), stan_version_minor(0), stan_version_patch(0),
model(""), data(""), init(""),
chain_id(1), seed(0), random_seed(false),
num_samples(0), num_warmup(0), save_warmup(false), thin(0),
append_samples(false),
algorithm(""), engine("") {}
};
struct stan_csv_adaptation {
double step_size;
Eigen::MatrixXd metric;
stan_csv_adaptation()
: step_size(0), metric(0, 0) {}
};
struct stan_csv_timing {
double warmup;
double sampling;
stan_csv_timing()
: warmup(0), sampling(0) {}
};
struct stan_csv {
stan_csv_metadata metadata;
Eigen::Matrix<std::string, Eigen::Dynamic, 1> header;
stan_csv_adaptation adaptation;
Eigen::MatrixXd samples;
stan_csv_timing timing;
};
/**
* Reads from a Stan output csv file.
*/
class stan_csv_reader {
public:
stan_csv_reader() {}
~stan_csv_reader() {}
static bool read_metadata(std::istream& in, stan_csv_metadata& metadata,
std::ostream* out) {
std::stringstream ss;
std::string line;
if (in.peek() != '#')
return false;
while (in.peek() == '#') {
std::getline(in, line);
ss << line << '\n';
}
ss.seekg(std::ios_base::beg);
char comment;
std::string lhs;
std::string name;
std::string value;
while (ss.good()) {
ss >> comment;
std::getline(ss, lhs);
size_t equal = lhs.find("=");
if (equal != std::string::npos) {
name = lhs.substr(0, equal);
boost::trim(name);
value = lhs.substr(equal + 2, lhs.size());
boost::replace_first(value, " (Default)", "");
} else {
if (lhs.compare(" data") == 0) {
ss >> comment;
std::getline(ss, lhs);
size_t equal = lhs.find("=");
if (equal != std::string::npos) {
name = lhs.substr(0, equal);
boost::trim(name);
value = lhs.substr(equal + 2, lhs.size());
boost::replace_first(value, " (Default)", "");
}
if (name.compare("file") == 0)
metadata.data = value;
continue;
}
}
if (name.compare("stan_version_major") == 0) {
metadata.stan_version_major = boost::lexical_cast<int>(value);
} else if (name.compare("stan_version_minor") == 0) {
metadata.stan_version_minor = boost::lexical_cast<int>(value);
} else if (name.compare("stan_version_patch") == 0) {
metadata.stan_version_patch = boost::lexical_cast<int>(value);
} else if (name.compare("model") == 0) {
metadata.model = value;
} else if (name.compare("num_samples") == 0) {
metadata.num_samples = boost::lexical_cast<int>(value);
} else if (name.compare("num_warmup") == 0) {
metadata.num_warmup = boost::lexical_cast<int>(value);
} else if (name.compare("save_warmup") == 0) {
metadata.save_warmup = boost::lexical_cast<bool>(value);
} else if (name.compare("thin") == 0) {
metadata.thin = boost::lexical_cast<int>(value);
} else if (name.compare("chain_id") == 0) {
metadata.chain_id = boost::lexical_cast<int>(value);
} else if (name.compare("init") == 0) {
metadata.init = value;
boost::trim(metadata.init);
} else if (name.compare("seed") == 0) {
metadata.seed = boost::lexical_cast<unsigned int>(value);
metadata.random_seed = false;
} else if (name.compare("append_samples") == 0) {
metadata.append_samples = boost::lexical_cast<bool>(value);
} else if (name.compare("algorithm") == 0) {
metadata.algorithm = value;
} else if (name.compare("engine") == 0) {
metadata.engine = value;
}
}
if (ss.good() == true)
return false;
return true;
} // read_metadata
static bool
read_header(std::istream& in,
Eigen::Matrix<std::string, Eigen::Dynamic, 1>& header,
std::ostream* out) {
std::string line;
if (in.peek() != 'l')
return false;
std::getline(in, line);
std::stringstream ss(line);
header.resize(std::count(line.begin(), line.end(), ',') + 1);
int idx = 0;
while (ss.good()) {
std::string token;
std::getline(ss, token, ',');
boost::trim(token);
int pos = token.find('.');
if (pos > 0) {
token.replace(pos, 1, "[");
std::replace(token.begin(), token.end(), '.', ',');
token += "]";
}
header(idx++) = token;
}
return true;
}
static bool read_adaptation(std::istream& in,
stan_csv_adaptation& adaptation,
std::ostream* out) {
std::stringstream ss;
std::string line;
int lines = 0;
if (in.peek() != '#' || in.good() == false)
return false;
while (in.peek() == '#') {
std::getline(in, line);
ss << line << std::endl;
lines++;
}
ss.seekg(std::ios_base::beg);
if (lines < 4)
return false;
char comment; // Buffer for comment indicator, #
// Skip first two lines
std::getline(ss, line);
// Stepsize
std::getline(ss, line, '=');
boost::trim(line);
ss >> adaptation.step_size;
// Metric parameters
std::getline(ss, line);
std::getline(ss, line);
std::getline(ss, line);
int rows = lines - 3;
int cols = std::count(line.begin(), line.end(), ',') + 1;
adaptation.metric.resize(rows, cols);
for (int row = 0; row < rows; row++) {
std::stringstream line_ss;
line_ss.str(line);
line_ss >> comment;
for (int col = 0; col < cols; col++) {
std::string token;
std::getline(line_ss, token, ',');
boost::trim(token);
adaptation.metric(row, col) = boost::lexical_cast<double>(token);
}
std::getline(ss, line); // Read in next line
}
if (ss.good())
return false;
else
return true;
}
static bool read_samples(std::istream& in, Eigen::MatrixXd& samples,
stan_csv_timing& timing, std::ostream* out) {
std::stringstream ss;
std::string line;
int rows = 0;
int cols = -1;
if (in.peek() == '#' || in.good() == false)
return false;
while (in.good()) {
bool comment_line = (in.peek() == '#');
bool empty_line = (in.peek() == '\n');
std::getline(in, line);
if (empty_line)
continue;
if (!line.length())
break;
if (comment_line) {
if (line.find("(Warm-up)") != std::string::npos) {
int left = 17;
int right = line.find(" seconds");
timing.warmup
+= boost::lexical_cast<double>(line.substr(left, right - left));
} else if (line.find("(Sampling)") != std::string::npos) {
int left = 17;
int right = line.find(" seconds");
timing.sampling
+= boost::lexical_cast<double>(line.substr(left, right - left));
}
} else {
ss << line << '\n';
int current_cols = std::count(line.begin(), line.end(), ',') + 1;
if (cols == -1) {
cols = current_cols;
} else if (cols != current_cols) {
if (out)
*out << "Error: expected " << cols << " columns, but found "
<< current_cols << " instead for row " << rows + 1
<< std::endl;
return false;
}
rows++;
}
in.peek();
}
ss.seekg(std::ios_base::beg);
if (rows > 0) {
samples.resize(rows, cols);
for (int row = 0; row < rows; row++) {
std::getline(ss, line);
std::stringstream ls(line);
for (int col = 0; col < cols; col++) {
std::getline(ls, line, ',');
boost::trim(line);
samples(row, col) = boost::lexical_cast<double>(line);
}
}
}
return true;
}
/**
* Parses the file.
*
* @param[in] in input stream to parse
* @param[out] out output stream to send messages
*/
static stan_csv parse(std::istream& in, std::ostream* out) {
stan_csv data;
if (!read_metadata(in, data.metadata, out)) {
if (out)
*out << "Warning: non-fatal error reading metadata" << std::endl;
}
if (!read_header(in, data.header, out)) {
if (out)
*out << "Error: error reading header" << std::endl;
throw std::invalid_argument
("Error with header of input file in parse");
}
if (!read_adaptation(in, data.adaptation, out)) {
if (out)
*out << "Warning: non-fatal error reading adapation data"
<< std::endl;
}
data.timing.warmup = 0;
data.timing.sampling = 0;
if (!read_samples(in, data.samples, data.timing, out)) {
if (out)
*out << "Warning: non-fatal error reading samples" << std::endl;
}
return data;
}
};
} // io
} // stan
#endif
<commit_msg>Make stan_csv_reader insensitive to whitespace around rhs of .csv file metadata.<commit_after>#ifndef STAN_IO_STAN_CSV_READER_HPP
#define STAN_IO_STAN_CSV_READER_HPP
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <Eigen/Dense>
#include <istream>
#include <iostream>
#include <sstream>
#include <string>
namespace stan {
namespace io {
// FIXME: should consolidate with the options from
// the command line in stan::lang
struct stan_csv_metadata {
int stan_version_major;
int stan_version_minor;
int stan_version_patch;
std::string model;
std::string data;
std::string init;
size_t chain_id;
size_t seed;
bool random_seed;
size_t num_samples;
size_t num_warmup;
bool save_warmup;
size_t thin;
bool append_samples;
std::string algorithm;
std::string engine;
stan_csv_metadata()
: stan_version_major(0), stan_version_minor(0), stan_version_patch(0),
model(""), data(""), init(""),
chain_id(1), seed(0), random_seed(false),
num_samples(0), num_warmup(0), save_warmup(false), thin(0),
append_samples(false),
algorithm(""), engine("") {}
};
struct stan_csv_adaptation {
double step_size;
Eigen::MatrixXd metric;
stan_csv_adaptation()
: step_size(0), metric(0, 0) {}
};
struct stan_csv_timing {
double warmup;
double sampling;
stan_csv_timing()
: warmup(0), sampling(0) {}
};
struct stan_csv {
stan_csv_metadata metadata;
Eigen::Matrix<std::string, Eigen::Dynamic, 1> header;
stan_csv_adaptation adaptation;
Eigen::MatrixXd samples;
stan_csv_timing timing;
};
/**
* Reads from a Stan output csv file.
*/
class stan_csv_reader {
public:
stan_csv_reader() {}
~stan_csv_reader() {}
static bool read_metadata(std::istream& in, stan_csv_metadata& metadata,
std::ostream* out) {
std::stringstream ss;
std::string line;
if (in.peek() != '#')
return false;
while (in.peek() == '#') {
std::getline(in, line);
ss << line << '\n';
}
ss.seekg(std::ios_base::beg);
char comment;
std::string lhs;
std::string name;
std::string value;
while (ss.good()) {
ss >> comment;
std::getline(ss, lhs);
size_t equal = lhs.find("=");
if (equal != std::string::npos) {
name = lhs.substr(0, equal);
boost::trim(name);
value = lhs.substr(equal + 1, lhs.size());
boost::trim(value);
boost::replace_first(value, " (Default)", "");
} else {
if (lhs.compare(" data") == 0) {
ss >> comment;
std::getline(ss, lhs);
size_t equal = lhs.find("=");
if (equal != std::string::npos) {
name = lhs.substr(0, equal);
boost::trim(name);
value = lhs.substr(equal + 2, lhs.size());
boost::replace_first(value, " (Default)", "");
}
if (name.compare("file") == 0)
metadata.data = value;
continue;
}
}
if (name.compare("stan_version_major") == 0) {
metadata.stan_version_major = boost::lexical_cast<int>(value);
} else if (name.compare("stan_version_minor") == 0) {
metadata.stan_version_minor = boost::lexical_cast<int>(value);
} else if (name.compare("stan_version_patch") == 0) {
metadata.stan_version_patch = boost::lexical_cast<int>(value);
} else if (name.compare("model") == 0) {
metadata.model = value;
} else if (name.compare("num_samples") == 0) {
metadata.num_samples = boost::lexical_cast<int>(value);
} else if (name.compare("num_warmup") == 0) {
metadata.num_warmup = boost::lexical_cast<int>(value);
} else if (name.compare("save_warmup") == 0) {
metadata.save_warmup = boost::lexical_cast<bool>(value);
} else if (name.compare("thin") == 0) {
metadata.thin = boost::lexical_cast<int>(value);
} else if (name.compare("chain_id") == 0) {
metadata.chain_id = boost::lexical_cast<int>(value);
} else if (name.compare("init") == 0) {
metadata.init = value;
boost::trim(metadata.init);
} else if (name.compare("seed") == 0) {
metadata.seed = boost::lexical_cast<unsigned int>(value);
metadata.random_seed = false;
} else if (name.compare("append_samples") == 0) {
metadata.append_samples = boost::lexical_cast<bool>(value);
} else if (name.compare("algorithm") == 0) {
metadata.algorithm = value;
} else if (name.compare("engine") == 0) {
metadata.engine = value;
}
}
if (ss.good() == true)
return false;
return true;
} // read_metadata
static bool
read_header(std::istream& in,
Eigen::Matrix<std::string, Eigen::Dynamic, 1>& header,
std::ostream* out) {
std::string line;
if (in.peek() != 'l')
return false;
std::getline(in, line);
std::stringstream ss(line);
header.resize(std::count(line.begin(), line.end(), ',') + 1);
int idx = 0;
while (ss.good()) {
std::string token;
std::getline(ss, token, ',');
boost::trim(token);
int pos = token.find('.');
if (pos > 0) {
token.replace(pos, 1, "[");
std::replace(token.begin(), token.end(), '.', ',');
token += "]";
}
header(idx++) = token;
}
return true;
}
static bool read_adaptation(std::istream& in,
stan_csv_adaptation& adaptation,
std::ostream* out) {
std::stringstream ss;
std::string line;
int lines = 0;
if (in.peek() != '#' || in.good() == false)
return false;
while (in.peek() == '#') {
std::getline(in, line);
ss << line << std::endl;
lines++;
}
ss.seekg(std::ios_base::beg);
if (lines < 4)
return false;
char comment; // Buffer for comment indicator, #
// Skip first two lines
std::getline(ss, line);
// Stepsize
std::getline(ss, line, '=');
boost::trim(line);
ss >> adaptation.step_size;
// Metric parameters
std::getline(ss, line);
std::getline(ss, line);
std::getline(ss, line);
int rows = lines - 3;
int cols = std::count(line.begin(), line.end(), ',') + 1;
adaptation.metric.resize(rows, cols);
for (int row = 0; row < rows; row++) {
std::stringstream line_ss;
line_ss.str(line);
line_ss >> comment;
for (int col = 0; col < cols; col++) {
std::string token;
std::getline(line_ss, token, ',');
boost::trim(token);
adaptation.metric(row, col) = boost::lexical_cast<double>(token);
}
std::getline(ss, line); // Read in next line
}
if (ss.good())
return false;
else
return true;
}
static bool read_samples(std::istream& in, Eigen::MatrixXd& samples,
stan_csv_timing& timing, std::ostream* out) {
std::stringstream ss;
std::string line;
int rows = 0;
int cols = -1;
if (in.peek() == '#' || in.good() == false)
return false;
while (in.good()) {
bool comment_line = (in.peek() == '#');
bool empty_line = (in.peek() == '\n');
std::getline(in, line);
if (empty_line)
continue;
if (!line.length())
break;
if (comment_line) {
if (line.find("(Warm-up)") != std::string::npos) {
int left = 17;
int right = line.find(" seconds");
timing.warmup
+= boost::lexical_cast<double>(line.substr(left, right - left));
} else if (line.find("(Sampling)") != std::string::npos) {
int left = 17;
int right = line.find(" seconds");
timing.sampling
+= boost::lexical_cast<double>(line.substr(left, right - left));
}
} else {
ss << line << '\n';
int current_cols = std::count(line.begin(), line.end(), ',') + 1;
if (cols == -1) {
cols = current_cols;
} else if (cols != current_cols) {
if (out)
*out << "Error: expected " << cols << " columns, but found "
<< current_cols << " instead for row " << rows + 1
<< std::endl;
return false;
}
rows++;
}
in.peek();
}
ss.seekg(std::ios_base::beg);
if (rows > 0) {
samples.resize(rows, cols);
for (int row = 0; row < rows; row++) {
std::getline(ss, line);
std::stringstream ls(line);
for (int col = 0; col < cols; col++) {
std::getline(ls, line, ',');
boost::trim(line);
samples(row, col) = boost::lexical_cast<double>(line);
}
}
}
return true;
}
/**
* Parses the file.
*
* @param[in] in input stream to parse
* @param[out] out output stream to send messages
*/
static stan_csv parse(std::istream& in, std::ostream* out) {
stan_csv data;
if (!read_metadata(in, data.metadata, out)) {
if (out)
*out << "Warning: non-fatal error reading metadata" << std::endl;
}
if (!read_header(in, data.header, out)) {
if (out)
*out << "Error: error reading header" << std::endl;
throw std::invalid_argument
("Error with header of input file in parse");
}
if (!read_adaptation(in, data.adaptation, out)) {
if (out)
*out << "Warning: non-fatal error reading adapation data"
<< std::endl;
}
data.timing.warmup = 0;
data.timing.sampling = 0;
if (!read_samples(in, data.samples, data.timing, out)) {
if (out)
*out << "Warning: non-fatal error reading samples" << std::endl;
}
return data;
}
};
} // io
} // stan
#endif
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// //
// This file is part of Swift2D. //
// //
// Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer //
// //
////////////////////////////////////////////////////////////////////////////////
// includes -------------------------------------------------------------------
#include <swift2d/graphics/Window.hpp>
#include <swift2d/graphics/WindowManager.hpp>
#include <swift2d/utils/Logger.hpp>
#include <GLFW/glfw3.h>
namespace swift {
////////////////////////////////////////////////////////////////////////////////
Window::Window()
: pVSync(false)
, pFullscreen(false) {
pOpen.on_change().connect([&](bool val) {
if (val) {
open_();
} else {
close_();
}
});
}
////////////////////////////////////////////////////////////////////////////////
Window::~Window() {
close_();
glfwDestroyWindow(window_);
}
////////////////////////////////////////////////////////////////////////////////
void Window::process_input() {
glfwPollEvents();
}
////////////////////////////////////////////////////////////////////////////////
void Window::set_active(bool active) {
if (window_) {
glfwMakeContextCurrent(window_);
}
}
////////////////////////////////////////////////////////////////////////////////
void Window::display() {
if (window_) {
glfwSwapBuffers(window_);
render_context_.gl.Clear().ColorBuffer();
}
}
////////////////////////////////////////////////////////////////////////////////
void Window::open_() {
if (!window_) {
render_context_.size = math::vec2i(800, 800);
window_ = glfwCreateWindow(
render_context_.size.x(), render_context_.size.y(),
"Hello World",
pFullscreen.get() ? glfwGetPrimaryMonitor() : nullptr,
nullptr);
WindowManager::windows[window_] = this;
set_active(true);
glewInit();
render_context_.gl.Disable(oglplus::Capability::DepthTest);
render_context_.gl.Enable(oglplus::Capability::Blend);
render_context_.gl.ClearColor(0.1f, 0.1f, 0.1f, 0.0f);
render_context_.gl.BlendFunc(
oglplus::BlendFunction::SrcAlpha,
oglplus::BlendFunction::OneMinusSrcAlpha
);
glfwSetWindowCloseCallback(window_, [](GLFWwindow* w) {
WindowManager::windows[w]->on_close.emit();
});
glfwSetFramebufferSizeCallback(window_, [](GLFWwindow* w, int width, int height) {
WindowManager::windows[w]->get_context().size = math::vec2i(width, height);
WindowManager::windows[w]->on_resize.emit(math::vec2i(width, height));
});
glfwSetKeyCallback(window_, [](GLFWwindow* w, int key, int scancode, int action, int mods) {
WindowManager::windows[w]->on_key_press.emit(static_cast<Key>(key), scancode, action, mods);
});
// apply vsync -------------------------------------------------------------
auto on_vsync_change = [&](bool val) {
glfwSwapInterval(val ? 1 : 0);
};
on_vsync_change(pVSync.get());
pVSync.on_change().connect(on_vsync_change);
}
}
////////////////////////////////////////////////////////////////////////////////
void Window::close_() {
if (window_) {
glfwDestroyWindow(window_);
window_ = nullptr;
}
}
////////////////////////////////////////////////////////////////////////////////
}
<commit_msg>added version debug<commit_after>////////////////////////////////////////////////////////////////////////////////
// //
// This file is part of Swift2D. //
// //
// Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer //
// //
////////////////////////////////////////////////////////////////////////////////
// includes -------------------------------------------------------------------
#include <swift2d/graphics/Window.hpp>
#include <swift2d/graphics/WindowManager.hpp>
#include <swift2d/utils/Logger.hpp>
#include <GLFW/glfw3.h>
namespace swift {
////////////////////////////////////////////////////////////////////////////////
Window::Window()
: pVSync(false)
, pFullscreen(false) {
pOpen.on_change().connect([&](bool val) {
if (val) {
open_();
} else {
close_();
}
});
}
////////////////////////////////////////////////////////////////////////////////
Window::~Window() {
close_();
glfwDestroyWindow(window_);
}
////////////////////////////////////////////////////////////////////////////////
void Window::process_input() {
glfwPollEvents();
}
////////////////////////////////////////////////////////////////////////////////
void Window::set_active(bool active) {
if (window_) {
glfwMakeContextCurrent(window_);
}
}
////////////////////////////////////////////////////////////////////////////////
void Window::display() {
if (window_) {
glfwSwapBuffers(window_);
render_context_.gl.Clear().ColorBuffer();
}
}
////////////////////////////////////////////////////////////////////////////////
void Window::open_() {
if (!window_) {
render_context_.size = math::vec2i(800, 800);
window_ = glfwCreateWindow(
render_context_.size.x(), render_context_.size.y(),
"Hello World",
pFullscreen.get() ? glfwGetPrimaryMonitor() : nullptr,
nullptr);
WindowManager::windows[window_] = this;
set_active(true);
glewInit();
Logger::LOG_DEBUG << "Created OpenGL context with version "
<< render_context_.gl.MajorVersion()
<< "." << render_context_.gl.MinorVersion() << std::endl;
render_context_.gl.Disable(oglplus::Capability::DepthTest);
render_context_.gl.Enable(oglplus::Capability::Blend);
render_context_.gl.ClearColor(0.1f, 0.1f, 0.1f, 0.0f);
render_context_.gl.BlendFunc(
oglplus::BlendFunction::SrcAlpha,
oglplus::BlendFunction::OneMinusSrcAlpha
);
glfwSetWindowCloseCallback(window_, [](GLFWwindow* w) {
WindowManager::windows[w]->on_close.emit();
});
glfwSetFramebufferSizeCallback(window_, [](GLFWwindow* w, int width, int height) {
WindowManager::windows[w]->get_context().size = math::vec2i(width, height);
WindowManager::windows[w]->on_resize.emit(math::vec2i(width, height));
});
glfwSetKeyCallback(window_, [](GLFWwindow* w, int key, int scancode, int action, int mods) {
WindowManager::windows[w]->on_key_press.emit(static_cast<Key>(key), scancode, action, mods);
});
// apply vsync -------------------------------------------------------------
auto on_vsync_change = [&](bool val) {
glfwSwapInterval(val ? 1 : 0);
};
on_vsync_change(pVSync.get());
pVSync.on_change().connect(on_vsync_change);
}
}
////////////////////////////////////////////////////////////////////////////////
void Window::close_() {
if (window_) {
glfwDestroyWindow(window_);
window_ = nullptr;
}
}
////////////////////////////////////////////////////////////////////////////////
}
<|endoftext|> |
<commit_before>#include "ShardQuorumContext.h"
#include "Framework/Replication/ReplicationConfig.h"
#include "Framework/Replication/Paxos/PaxosMessage.h"
#include "Application/Common/ContextTransport.h"
#include "ShardQuorumProcessor.h"
#include "ShardServer.h"
void ShardQuorumContext::Init(ConfigQuorum* configQuorum,
ShardQuorumProcessor* quorumProcessor_)
{
uint64_t* it;
SortedList<uint64_t> activeNodes;
quorumProcessor = quorumProcessor_;
quorumID = configQuorum->quorumID;
configQuorum->GetVolatileActiveNodes(activeNodes);
FOREACH (it, activeNodes)
quorum.AddNode(*it);
transport.SetQuorum(&quorum);
transport.SetQuorumID(quorumID);
database.Init(this,
quorumProcessor->GetShardServer()->GetDatabaseManager()->GetQuorumPaxosShard(quorumID),
quorumProcessor->GetShardServer()->GetDatabaseManager()->GetQuorumLogShard(quorumID));
replicatedLog.Init(this);
replicatedLog.SetUseProposeTimeouts(false);
replicatedLog.SetCommitChaining(true);
replicatedLog.SetAsyncCommit(true);
transport.SetQuorumID(quorumID);
highestPaxosID = 0;
isReplicationActive = true;
}
void ShardQuorumContext::Shutdown()
{
replicatedLog.Shutdown();
}
//void ShardQuorumContext::SetActiveNodes(SortedList<uint64_t>& activeNodes)
//{
// unsigned i;
// uint64_t* it;
// uint64_t* oldNodes;
//
// oldNodes = (uint64_t*) quorum.GetNodes();
//
// if (activeNodes.GetLength() != quorum.GetNumNodes())
// {
// ReconfigureQuorum(activeNodes);
// return;
// }
//
// i = 0;
// FOREACH (it, activeNodes)
// {
// if (oldNodes[i] != *it)
// {
// ReconfigureQuorum(activeNodes);
// return;
// }
// i++;
// }
//}
void ShardQuorumContext::SetQuorumNodes(SortedList<uint64_t>& activeNodes)
{
uint64_t* it;
quorum.ClearNodes();
FOREACH (it, activeNodes)
{
// Log_Debug("New nodes: %U", *it);
quorum.AddNode(*it);
}
}
void ShardQuorumContext::RestartReplication()
{
replicatedLog.Restart();
}
void ShardQuorumContext::TryReplicationCatchup()
{
replicatedLog.TryCatchup();
}
void ShardQuorumContext::AppendDummy()
{
Log_Trace();
replicatedLog.TryAppendDummy();
}
void ShardQuorumContext::Append()
{
ASSERT(nextValue.GetLength() > 0);
replicatedLog.TryAppendNextValue();
}
bool ShardQuorumContext::IsAppending()
{
return (nextValue.GetLength() != 0);
}
void ShardQuorumContext::OnAppendComplete()
{
replicatedLog.OnAppendComplete();
}
void ShardQuorumContext::NewPaxosRound()
{
replicatedLog.NewPaxosRound();
}
void ShardQuorumContext::WriteReplicationState()
{
replicatedLog.WriteState();
}
uint64_t ShardQuorumContext::GetMemoryUsage()
{
return nextValue.GetSize() + replicatedLog.GetMemoryUsage();
}
bool ShardQuorumContext::IsLeaseOwner()
{
return quorumProcessor->IsPrimary();
}
bool ShardQuorumContext::IsLeaseKnown()
{
return quorumProcessor->GetShardServer()->IsLeaseKnown(quorumID);
}
uint64_t ShardQuorumContext::GetLeaseOwner()
{
return quorumProcessor->GetShardServer()->GetLeaseOwner(quorumID);
}
bool ShardQuorumContext::IsLeader()
{
return IsLeaseOwner() && replicatedLog.IsMultiPaxosEnabled();
}
void ShardQuorumContext::OnLearnLease()
{
replicatedLog.OnLearnLease();
}
void ShardQuorumContext::OnLeaseTimeout()
{
nextValue.Clear();
replicatedLog.OnLeaseTimeout();
}
void ShardQuorumContext::OnIsLeader()
{
// nothing
}
uint64_t ShardQuorumContext::GetQuorumID()
{
return quorumID;
}
void ShardQuorumContext::SetPaxosID(uint64_t paxosID)
{
replicatedLog.SetPaxosID(paxosID);
}
uint64_t ShardQuorumContext::GetPaxosID()
{
return replicatedLog.GetPaxosID();
}
uint64_t ShardQuorumContext::GetHighestPaxosID()
{
return highestPaxosID;
}
Quorum* ShardQuorumContext::GetQuorum()
{
return &quorum;
}
QuorumDatabase* ShardQuorumContext::GetDatabase()
{
return &database;
}
QuorumTransport* ShardQuorumContext::GetTransport()
{
return &transport;
}
void ShardQuorumContext::OnStartProposing()
{
quorumProcessor->OnStartProposing();
}
void ShardQuorumContext::OnAppend(uint64_t paxosID, Buffer& value, bool ownAppend)
{
nextValue.Clear();
quorumProcessor->OnAppend(paxosID, value, ownAppend);
}
bool ShardQuorumContext::IsPaxosBlocked()
{
return quorumProcessor->IsPaxosBlocked();
}
Buffer& ShardQuorumContext::GetNextValue()
{
return nextValue;
}
void ShardQuorumContext::OnStartCatchup()
{
quorumProcessor->OnStartCatchup();
}
void ShardQuorumContext::OnCatchupComplete(uint64_t paxosID)
{
replicatedLog.OnCatchupComplete(paxosID);
}
void ShardQuorumContext::StopReplication()
{
isReplicationActive = false;
replicatedLog.Stop();
}
void ShardQuorumContext::ContinueReplication()
{
isReplicationActive = true;
replicatedLog.Continue();
}
void ShardQuorumContext::ResetReplicationState()
{
replicatedLog.ResetPaxosState();
}
void ShardQuorumContext::OnMessage(uint64_t /*nodeID*/, ReadBuffer buffer)
{
char proto;
Log_Trace("%R", &buffer);
if (buffer.GetLength() < 2)
ASSERT_FAIL();
proto = buffer.GetCharAt(0);
ASSERT(buffer.GetCharAt(1) == ':');
switch(proto)
{
case PAXOS_PROTOCOL_ID: // 'P':
if (!isReplicationActive)
break;
OnPaxosMessage(buffer);
break;
case CATCHUP_PROTOCOL_ID: // 'C'
OnCatchupMessage(buffer);
break;
default:
ASSERT_FAIL();
break;
}
}
void ShardQuorumContext::RegisterPaxosID(uint64_t paxosID)
{
if (paxosID > highestPaxosID)
highestPaxosID = paxosID;
if (IsLeaseKnown())
replicatedLog.RegisterPaxosID(paxosID, GetLeaseOwner());
}
void ShardQuorumContext::OnPaxosMessage(ReadBuffer buffer)
{
PaxosMessage msg;
msg.Read(buffer);
RegisterPaxosID(msg.paxosID);
replicatedLog.RegisterPaxosID(msg.paxosID, msg.nodeID);
replicatedLog.OnMessage(msg);
}
void ShardQuorumContext::OnCatchupMessage(ReadBuffer buffer)
{
CatchupMessage msg;
msg.Read(buffer);
quorumProcessor->OnCatchupMessage(msg);
}
//void ShardQuorumContext::ReconfigureQuorum(SortedList<uint64_t>& activeNodes)
//{
// uint64_t* it;
//
// Log_Debug("Reconfiguring quorum");
//
// for (unsigned i = 0; i < quorum.GetNumNodes(); i++)
// Log_Debug("Old nodes: %U", quorum.GetNodes()[i]);
//
// quorum.ClearNodes();
// FOREACH (it, activeNodes)
// {
// Log_Debug("New nodes: %U", *it);
// quorum.AddNode(*it);
// }
//
// if (replicatedLog.IsAppending())
// replicatedLog.Restart();
//}
<commit_msg>Fix bug where RequestChosen was sent during catchup, which resulted in catchup running in a loop. Fixes #197<commit_after>#include "ShardQuorumContext.h"
#include "Framework/Replication/ReplicationConfig.h"
#include "Framework/Replication/Paxos/PaxosMessage.h"
#include "Application/Common/ContextTransport.h"
#include "ShardQuorumProcessor.h"
#include "ShardServer.h"
void ShardQuorumContext::Init(ConfigQuorum* configQuorum,
ShardQuorumProcessor* quorumProcessor_)
{
uint64_t* it;
SortedList<uint64_t> activeNodes;
quorumProcessor = quorumProcessor_;
quorumID = configQuorum->quorumID;
configQuorum->GetVolatileActiveNodes(activeNodes);
FOREACH (it, activeNodes)
quorum.AddNode(*it);
transport.SetQuorum(&quorum);
transport.SetQuorumID(quorumID);
database.Init(this,
quorumProcessor->GetShardServer()->GetDatabaseManager()->GetQuorumPaxosShard(quorumID),
quorumProcessor->GetShardServer()->GetDatabaseManager()->GetQuorumLogShard(quorumID));
replicatedLog.Init(this);
replicatedLog.SetUseProposeTimeouts(false);
replicatedLog.SetCommitChaining(true);
replicatedLog.SetAsyncCommit(true);
transport.SetQuorumID(quorumID);
highestPaxosID = 0;
isReplicationActive = true;
}
void ShardQuorumContext::Shutdown()
{
replicatedLog.Shutdown();
}
//void ShardQuorumContext::SetActiveNodes(SortedList<uint64_t>& activeNodes)
//{
// unsigned i;
// uint64_t* it;
// uint64_t* oldNodes;
//
// oldNodes = (uint64_t*) quorum.GetNodes();
//
// if (activeNodes.GetLength() != quorum.GetNumNodes())
// {
// ReconfigureQuorum(activeNodes);
// return;
// }
//
// i = 0;
// FOREACH (it, activeNodes)
// {
// if (oldNodes[i] != *it)
// {
// ReconfigureQuorum(activeNodes);
// return;
// }
// i++;
// }
//}
void ShardQuorumContext::SetQuorumNodes(SortedList<uint64_t>& activeNodes)
{
uint64_t* it;
quorum.ClearNodes();
FOREACH (it, activeNodes)
{
// Log_Debug("New nodes: %U", *it);
quorum.AddNode(*it);
}
}
void ShardQuorumContext::RestartReplication()
{
replicatedLog.Restart();
}
void ShardQuorumContext::TryReplicationCatchup()
{
replicatedLog.TryCatchup();
}
void ShardQuorumContext::AppendDummy()
{
Log_Trace();
replicatedLog.TryAppendDummy();
}
void ShardQuorumContext::Append()
{
ASSERT(nextValue.GetLength() > 0);
replicatedLog.TryAppendNextValue();
}
bool ShardQuorumContext::IsAppending()
{
return (nextValue.GetLength() != 0);
}
void ShardQuorumContext::OnAppendComplete()
{
replicatedLog.OnAppendComplete();
}
void ShardQuorumContext::NewPaxosRound()
{
replicatedLog.NewPaxosRound();
}
void ShardQuorumContext::WriteReplicationState()
{
replicatedLog.WriteState();
}
uint64_t ShardQuorumContext::GetMemoryUsage()
{
return nextValue.GetSize() + replicatedLog.GetMemoryUsage();
}
bool ShardQuorumContext::IsLeaseOwner()
{
return quorumProcessor->IsPrimary();
}
bool ShardQuorumContext::IsLeaseKnown()
{
return quorumProcessor->GetShardServer()->IsLeaseKnown(quorumID);
}
uint64_t ShardQuorumContext::GetLeaseOwner()
{
return quorumProcessor->GetShardServer()->GetLeaseOwner(quorumID);
}
bool ShardQuorumContext::IsLeader()
{
return IsLeaseOwner() && replicatedLog.IsMultiPaxosEnabled();
}
void ShardQuorumContext::OnLearnLease()
{
replicatedLog.OnLearnLease();
}
void ShardQuorumContext::OnLeaseTimeout()
{
nextValue.Clear();
replicatedLog.OnLeaseTimeout();
}
void ShardQuorumContext::OnIsLeader()
{
// nothing
}
uint64_t ShardQuorumContext::GetQuorumID()
{
return quorumID;
}
void ShardQuorumContext::SetPaxosID(uint64_t paxosID)
{
replicatedLog.SetPaxosID(paxosID);
}
uint64_t ShardQuorumContext::GetPaxosID()
{
return replicatedLog.GetPaxosID();
}
uint64_t ShardQuorumContext::GetHighestPaxosID()
{
return highestPaxosID;
}
Quorum* ShardQuorumContext::GetQuorum()
{
return &quorum;
}
QuorumDatabase* ShardQuorumContext::GetDatabase()
{
return &database;
}
QuorumTransport* ShardQuorumContext::GetTransport()
{
return &transport;
}
void ShardQuorumContext::OnStartProposing()
{
quorumProcessor->OnStartProposing();
}
void ShardQuorumContext::OnAppend(uint64_t paxosID, Buffer& value, bool ownAppend)
{
nextValue.Clear();
quorumProcessor->OnAppend(paxosID, value, ownAppend);
}
bool ShardQuorumContext::IsPaxosBlocked()
{
return quorumProcessor->IsPaxosBlocked();
}
Buffer& ShardQuorumContext::GetNextValue()
{
return nextValue;
}
void ShardQuorumContext::OnStartCatchup()
{
quorumProcessor->OnStartCatchup();
}
void ShardQuorumContext::OnCatchupComplete(uint64_t paxosID)
{
replicatedLog.OnCatchupComplete(paxosID);
}
void ShardQuorumContext::StopReplication()
{
isReplicationActive = false;
replicatedLog.Stop();
}
void ShardQuorumContext::ContinueReplication()
{
isReplicationActive = true;
replicatedLog.Continue();
}
void ShardQuorumContext::ResetReplicationState()
{
replicatedLog.ResetPaxosState();
}
void ShardQuorumContext::OnMessage(uint64_t /*nodeID*/, ReadBuffer buffer)
{
char proto;
Log_Trace("%R", &buffer);
if (buffer.GetLength() < 2)
ASSERT_FAIL();
proto = buffer.GetCharAt(0);
ASSERT(buffer.GetCharAt(1) == ':');
switch(proto)
{
case PAXOS_PROTOCOL_ID: // 'P':
if (!isReplicationActive)
break;
OnPaxosMessage(buffer);
break;
case CATCHUP_PROTOCOL_ID: // 'C'
OnCatchupMessage(buffer);
break;
default:
ASSERT_FAIL();
break;
}
}
void ShardQuorumContext::RegisterPaxosID(uint64_t paxosID)
{
if (paxosID > highestPaxosID)
highestPaxosID = paxosID;
// ReplicatedLog::RegisterPaxosID() will perform a RequestChosen()
// so don't call it if replication is inactive,
// because catchup is already running
if (isReplicationActive && IsLeaseKnown())
replicatedLog.RegisterPaxosID(paxosID, GetLeaseOwner());
}
void ShardQuorumContext::OnPaxosMessage(ReadBuffer buffer)
{
PaxosMessage msg;
msg.Read(buffer);
RegisterPaxosID(msg.paxosID);
replicatedLog.RegisterPaxosID(msg.paxosID, msg.nodeID);
replicatedLog.OnMessage(msg);
}
void ShardQuorumContext::OnCatchupMessage(ReadBuffer buffer)
{
CatchupMessage msg;
msg.Read(buffer);
quorumProcessor->OnCatchupMessage(msg);
}
//void ShardQuorumContext::ReconfigureQuorum(SortedList<uint64_t>& activeNodes)
//{
// uint64_t* it;
//
// Log_Debug("Reconfiguring quorum");
//
// for (unsigned i = 0; i < quorum.GetNumNodes(); i++)
// Log_Debug("Old nodes: %U", quorum.GetNodes()[i]);
//
// quorum.ClearNodes();
// FOREACH (it, activeNodes)
// {
// Log_Debug("New nodes: %U", *it);
// quorum.AddNode(*it);
// }
//
// if (replicatedLog.IsAppending())
// replicatedLog.Restart();
//}
<|endoftext|> |
<commit_before>/***************************************************************************
* io/test_cancel.cpp
*
* Part of the STXXL. See http://stxxl.sourceforge.net
*
* Copyright (C) 2009 Johannes Singler <singler@ira.uka.de>
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
**************************************************************************/
#include <stxxl/io>
#include <stxxl/aligned_alloc>
//! \example io/test_cancel.cpp
//! This tests the request cancellation mechanisms.
using stxxl::file;
struct my_handler
{
void operator () (stxxl::request * ptr)
{
STXXL_MSG("Request completed: " << ptr);
}
};
int main(int argc, char ** argv)
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " tempdir" << std::endl;
return -1;
}
const int size = 64 * 1024 * 1024;
char * buffer = (char *)stxxl::aligned_alloc<4096>(size);
memset(buffer, 0, size);
std::string tempfilename = std::string(argv[1]) + "/test_cancel.dat";
stxxl::syscall_file file(tempfilename, file::CREAT | file::RDWR | file::DIRECT, 1);
stxxl::request_ptr req[16];
//without cancellation
stxxl::stats_data stats1(*stxxl::stats::get_instance());
unsigned i = 0;
for ( ; i < 16; i++)
req[i] = file.awrite(buffer, i * size, size, my_handler());
wait_all(req, 16);
std::cout << stxxl::stats_data(*stxxl::stats::get_instance()) - stats1;
//with cancellation
stxxl::stats_data stats2(*stxxl::stats::get_instance());
for (unsigned i = 0; i < 16; i++)
req[i] = file.awrite(buffer, i * size, size, my_handler());
//cancel first half
unsigned num_cancelled = cancel_all(req, req + 8);
STXXL_MSG("Cancelled " << num_cancelled << " requests.");
//cancel every second in second half
for (unsigned i = 8; i < 16; i += 2)
{
if (req[i]->cancel())
STXXL_MSG("Cancelled request " << &(*(req[i])));
}
wait_all(req, 16);
std::cout << stxxl::stats_data(*stxxl::stats::get_instance()) - stats2;
stxxl::aligned_dealloc<4096>(buffer);
unlink(tempfilename.c_str());
return 0;
}
<commit_msg>Set file size before writing. Refactoring.<commit_after>/***************************************************************************
* io/test_cancel.cpp
*
* Part of the STXXL. See http://stxxl.sourceforge.net
*
* Copyright (C) 2009 Johannes Singler <singler@ira.uka.de>
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
**************************************************************************/
#include <stxxl/io>
#include <stxxl/aligned_alloc>
//! \example io/test_cancel.cpp
//! This tests the request cancellation mechanisms.
using stxxl::file;
struct my_handler
{
void operator () (stxxl::request * ptr)
{
STXXL_MSG("Request completed: " << ptr);
}
};
int main(int argc, char ** argv)
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " tempdir" << std::endl;
return -1;
}
const stxxl::uint64 size = 64 * 1024 * 1024, num_blocks = 16;
char * buffer = (char *)stxxl::aligned_alloc<4096>(size);
memset(buffer, 0, size);
std::string tempfilename = std::string(argv[1]) + "/test_cancel.dat";
stxxl::syscall_file file(tempfilename, file::CREAT | file::RDWR | file::DIRECT, 1);
file.set_size(num_blocks * size);
stxxl::request_ptr req[num_blocks];
//without cancellation
stxxl::stats_data stats1(*stxxl::stats::get_instance());
unsigned i = 0;
for ( ; i < num_blocks; i++)
req[i] = file.awrite(buffer, i * size, size, my_handler());
wait_all(req, num_blocks);
std::cout << stxxl::stats_data(*stxxl::stats::get_instance()) - stats1;
//with cancellation
stxxl::stats_data stats2(*stxxl::stats::get_instance());
for (unsigned i = 0; i < num_blocks; i++)
req[i] = file.awrite(buffer, i * size, size, my_handler());
//cancel first half
unsigned num_cancelled = cancel_all(req, req + 8);
STXXL_MSG("Cancelled " << num_cancelled << " requests.");
//cancel every second in second half
for (unsigned i = num_blocks / 2; i < num_blocks; i += 2)
{
if (req[i]->cancel())
STXXL_MSG("Cancelled request " << &(*(req[i])));
}
wait_all(req, num_blocks);
std::cout << stxxl::stats_data(*stxxl::stats::get_instance()) - stats2;
stxxl::aligned_dealloc<4096>(buffer);
unlink(tempfilename.c_str());
return 0;
}
<|endoftext|> |
<commit_before>#include "planet.h"
//GET FUNCTIONS
double Planet::getx()
{
return x;
}
double Planet::gety()
{
return y;
}
double& Planet::getxv()
{
return xv;
}
double& Planet::getyv()
{
return yv;
}
double Planet::getmass()
{
return mass;
}
double Planet::getDist(Planet forcer)
{
return sqrt((forcer.getx() - getx())*(forcer.getx() - getx()) + (forcer.gety() - gety()) * (forcer.gety() - gety()));
}
double Planet::getRad()
{
return radi;
}
pType Planet::getType()
{
return planetType;
}
double Planet::getId()
{
return id;
}
double Planet::getG()
{
return G;
}
void Planet::mark(double i)
{
id = i;
life.giveId(i);
}
std::string Planet::getFlavorTextLife()
{
switch ((int) getLife().getTypeEnum())
{
case (0):
{
return "Lifeless planet. Either the conditions\nfor life are not met or life has yet to evolve.";
}
case (1):
{
return "Organisms that consist of one cell. The first form of life.\nOften lives in fluids in, on or under the surface.";
}
case (2):
{
return "Aggregate from either cell division or individuals cells\ncoming togheter. The next step in the evolution of life.";
}
case (3):
{
return "Enormous numbers of cells work togheter to\nsupport a sizable lifeform. These can often be found\nroaming the surface of the planet.";
}
case (4):
{
return "The organisms have developed intelligence and are banding\ntogheter in groups. Often using simple technology.";
}
case (5):
{
return "The organisms are now the dominant species on the planet.\nThey have created advanced technology and culture.";
}
case (6):
{
return "The organisms technology has enabled them to spread to other planets.\nOnly a truly devestating event can end their civilization now.";
}
case (7):
{
return "An outpost made by the organisms. With time it will\ngrow to a fully capable part of the civilization.";
}
}
}
//SIMULATION FUNCTIONS
void Planet::updateVel(Planet forcer, double tidsskritt)
{
double aks = 0;
double distance = sqrt((forcer.getx() - getx())*(forcer.getx() - getx()) + (forcer.gety() - gety()) * (forcer.gety() - gety()));
double angle = atan2(forcer.gety() - gety(), forcer.getx() - getx());
if (distance != 0) aks = G * forcer.getmass() / (distance*distance);
if (aks > STRENGTH_strongest_attractor)
{
STRENGTH_strongest_attractor = aks;
ID_strongest_attractor = forcer.getId();
}
xv += cos(angle) * aks * tidsskritt;
yv += sin(angle) * aks * tidsskritt;
}
void Planet::updateTemp()
{
temperature = temp();
}
void Planet::move(double tidsskritt)
{
x += xv * tidsskritt;
y += yv * tidsskritt;
circle.setPosition(x, y);
}
void Planet::updateRadiAndType()
{
if (mass < ROCKYLIMIT)
{
planetType = ROCKY;
density = 0.5;
circle.setOutlineThickness(0);
circle.setPointCount(30);
}
else if (mass < TERRESTIALLIMIT)
{
planetType = TERRESTIAL;
density = 0.5;
circle.setPointCount(40);
}
else if (mass < GASGIANTLIMIT)
{
planetType = GASGIANT;
density = 0.3;
circle.setPointCount(50);
}
else if (mass < SMALLSTARLIMIT)
{
planetType = SMALLSTAR;
density = 0.2;
circle.setOutlineColor(sf::Color(255, 0, 0, 60));
circle.setOutlineThickness(3);
circle.setPointCount(90);
}
else if (mass < STARLIMIT)
{
planetType = STAR;
density = 0.15;
circle.setOutlineThickness(7);
circle.setPointCount(90);
}
else if (mass < BIGSTARLIMIT)
{
planetType = BIGSTAR;
density = 0.1;
circle.setOutlineColor(sf::Color(150, 150, 255, 60));
circle.setOutlineThickness(10);
circle.setPointCount(150);
}
else
{
planetType = BLACKHOLE;
density = 10;
circle.setFillColor(sf::Color(20, 20, 20));
circle.setOutlineThickness(0);
circle.setPointCount(20);
}
radi = cbrt(mass) / density;
circle.setRadius(radi);
circle.setOrigin(radi, radi);
}
void Planet::incMass(double m)
{
mass += m;
updateRadiAndType();
}
void Planet::printInfo()
{
std::cout << "\n#############\n" << std::endl;
std::cout << "Mass: " << getmass() << std::endl;
std::cout << "X-posisjon: " << getx() << std::endl;
std::cout << "Y-posisjon: " << gety() << std::endl;
std::cout << "X-hastighet: " << getxv() << std::endl;
std::cout << "Y-hastighet: " << getyv() << std::endl;
std::cout << "\n#############\n" << std::endl;
}
void Planet::printInfoShort()
{
std::cout << "ID: " << getId() << " // " << "M: " << getmass() << " X: " << getx() << " | " << getxv() << " Y: " << gety() << " | " << getyv() << " | " << std::endl;
}
void Planet::kollisjon(Planet p)
{
xv = (mass*xv + p.mass*p.getxv()) / (mass + p.getmass());
yv = (mass*yv + p.mass*p.getyv()) / (mass + p.getmass());
double dXV = xv - p.getxv();
double dYV = yv - p.getyv();
incTEnergy(COLLISION_HEAT_MULTIPLIER*((dXV*dXV + dYV*dYV)*p.getmass()));
}
void Planet::draw(sf::RenderWindow &w, double xx, double yy)
{
circle.setPosition(x-xx,y-yy);
if (planetType != GASGIANT)
{
w.draw(circle);
}
else
{
w.draw(circle);
for (int i = 0; i < atmoLinesBrightness.size(); i++)
{
sf::CircleShape atmoLine;
//SETTING FEATURES
int midlLines = (numAtmoLines - 1);
atmoLine.setRadius(circle.getRadius() - i * i * i * circle.getRadius() / (midlLines*midlLines*midlLines));
atmoLine.setOrigin(atmoLine.getRadius(), atmoLine.getRadius());
atmoLine.setPosition(circle.getPosition());
atmoLine.setOutlineThickness(0);
//FINDING COLOR
double r = atmoCol_r + atmoLinesBrightness[i] + temperature / 10;
double g = atmoCol_g + atmoLinesBrightness[i] - temperature / 15;
double b = atmoCol_b + atmoLinesBrightness[i] - temperature / 15;
if (r > 255) r = 255;
if (g > 255) g = 255;
if (b > 255) b = 255;
if (r < 0) r = 0;
if (g < 0) g = 0;
if (b < 0) b = 0;
atmoLine.setFillColor(sf::Color(r, g, b));
w.draw(atmoLine);
}
}
}
void Planet::setColor()
{
if (planetType != ROCKY && planetType != TERRESTIAL && planetType != BLACKHOLE && planetType != GASGIANT)
{
circle.setFillColor(getStarCol());
circle.setOutlineColor(sf::Color(circle.getFillColor().r, circle.getFillColor().g, circle.getFillColor().b, 20));
}
else if (planetType == ROCKY || planetType == TERRESTIAL)
{
double r = 100 + randBrightness +temperature / 10;
double g = 100 + randBrightness -temperature / 15 + getLife().getBmass() /20;
double b = 100 + randBrightness -temperature / 15;
if (r > 255) r = 255;
if (g > 255) g = 255;
if (b > 255) b = 255;
if (r < 0) r = 0;
if (g < 0) g = 0;
if (b < 0) b = 0;
circle.setFillColor(sf::Color(r, g, b));
}
else if (planetType == GASGIANT)
{
double r = atmoCol_r +temperature / 10;
double g = atmoCol_g -temperature / 15;
double b = atmoCol_b -temperature / 15;
if (r > 255) r = 255;
if (g > 255) g = 255;
if (b > 255) b = 255;
if (r < 0) r = 0;
if (g < 0) g = 0;
if (b < 0) b = 0;
circle.setFillColor(sf::Color(r, g, b));
}
}
std::string convertDoubleToString(double number)
{
std::string Result;
std::stringstream convert;
convert << number;
return convert.str();
}
std::string Planet::genName()
{
std::vector<std::string> navn_del_en = { "Jup", "Jor", "Ear", "Mar", "Ven", "Cer", "Sat", "Pl", "Nep", "Ur", "Ker", "Mer", "Jov", "Qur", "Deb", "Car", "Xet", "Nayt", "Erist", "Hamar", "Bjork", "Deat", "Limus", "Lant", "Hypor", "Hyper", "Tell", "It", "As", "Ka", "Po", "Yt", "Pertat" };
std::vector<std::string> navn_del_to = { "it", "enden", "orden", "eptux", "atur", "oper", "uqtor", "axax" };
std::vector<std::string> navn_del_tre = {"er", "us" , "o", "i", "atara", "ankara", "oxos", "upol", "ol", "eq"};
int selectorOne = modernRandomWithLimits(0, navn_del_en.size()-1);
int selectorTwo = modernRandomWithLimits(0, navn_del_to.size()-1);
int selectorThree = modernRandomWithLimits(0, navn_del_tre.size()-1);
std::string number = "";
if (modernRandomWithLimits(0, 100) < 20) number = " " + convertDoubleToString(modernRandomWithLimits(100, 999));
std::string navn = navn_del_en[selectorOne] + navn_del_to[selectorTwo] + navn_del_tre[selectorThree] + number;
return navn;
}<commit_msg>Remove unecessary square root in planet update<commit_after>#include "planet.h"
//GET FUNCTIONS
double Planet::getx()
{
return x;
}
double Planet::gety()
{
return y;
}
double& Planet::getxv()
{
return xv;
}
double& Planet::getyv()
{
return yv;
}
double Planet::getmass()
{
return mass;
}
double Planet::getDist(Planet forcer)
{
return sqrt((forcer.getx() - getx())*(forcer.getx() - getx()) + (forcer.gety() - gety()) * (forcer.gety() - gety()));
}
double Planet::getRad()
{
return radi;
}
pType Planet::getType()
{
return planetType;
}
double Planet::getId()
{
return id;
}
double Planet::getG()
{
return G;
}
void Planet::mark(double i)
{
id = i;
life.giveId(i);
}
std::string Planet::getFlavorTextLife()
{
switch ((int) getLife().getTypeEnum())
{
case (0):
{
return "Lifeless planet. Either the conditions\nfor life are not met or life has yet to evolve.";
}
case (1):
{
return "Organisms that consist of one cell. The first form of life.\nOften lives in fluids in, on or under the surface.";
}
case (2):
{
return "Aggregate from either cell division or individuals cells\ncoming togheter. The next step in the evolution of life.";
}
case (3):
{
return "Enormous numbers of cells work togheter to\nsupport a sizable lifeform. These can often be found\nroaming the surface of the planet.";
}
case (4):
{
return "The organisms have developed intelligence and are banding\ntogheter in groups. Often using simple technology.";
}
case (5):
{
return "The organisms are now the dominant species on the planet.\nThey have created advanced technology and culture.";
}
case (6):
{
return "The organisms technology has enabled them to spread to other planets.\nOnly a truly devestating event can end their civilization now.";
}
case (7):
{
return "An outpost made by the organisms. With time it will\ngrow to a fully capable part of the civilization.";
}
}
}
//SIMULATION FUNCTIONS
void Planet::updateVel(Planet forcer, double tidsskritt)
{
double aks = 0;
double distanceSquared = (forcer.getx() - getx())*(forcer.getx() - getx()) + (forcer.gety() - gety()) * (forcer.gety() - gety());
double angle = atan2(forcer.gety() - gety(), forcer.getx() - getx());
if (distanceSquared != 0) aks = G * forcer.getmass() / (distanceSquared);
if (aks > STRENGTH_strongest_attractor)
{
STRENGTH_strongest_attractor = aks;
ID_strongest_attractor = forcer.getId();
}
xv += cos(angle) * aks * tidsskritt;
yv += sin(angle) * aks * tidsskritt;
}
void Planet::updateTemp()
{
temperature = temp();
}
void Planet::move(double tidsskritt)
{
x += xv * tidsskritt;
y += yv * tidsskritt;
circle.setPosition(x, y);
}
void Planet::updateRadiAndType()
{
if (mass < ROCKYLIMIT)
{
planetType = ROCKY;
density = 0.5;
circle.setOutlineThickness(0);
circle.setPointCount(30);
}
else if (mass < TERRESTIALLIMIT)
{
planetType = TERRESTIAL;
density = 0.5;
circle.setPointCount(40);
}
else if (mass < GASGIANTLIMIT)
{
planetType = GASGIANT;
density = 0.3;
circle.setPointCount(50);
}
else if (mass < SMALLSTARLIMIT)
{
planetType = SMALLSTAR;
density = 0.2;
circle.setOutlineColor(sf::Color(255, 0, 0, 60));
circle.setOutlineThickness(3);
circle.setPointCount(90);
}
else if (mass < STARLIMIT)
{
planetType = STAR;
density = 0.15;
circle.setOutlineThickness(7);
circle.setPointCount(90);
}
else if (mass < BIGSTARLIMIT)
{
planetType = BIGSTAR;
density = 0.1;
circle.setOutlineColor(sf::Color(150, 150, 255, 60));
circle.setOutlineThickness(10);
circle.setPointCount(150);
}
else
{
planetType = BLACKHOLE;
density = 10;
circle.setFillColor(sf::Color(20, 20, 20));
circle.setOutlineThickness(0);
circle.setPointCount(20);
}
radi = cbrt(mass) / density;
circle.setRadius(radi);
circle.setOrigin(radi, radi);
}
void Planet::incMass(double m)
{
mass += m;
updateRadiAndType();
}
void Planet::printInfo()
{
std::cout << "\n#############\n" << std::endl;
std::cout << "Mass: " << getmass() << std::endl;
std::cout << "X-posisjon: " << getx() << std::endl;
std::cout << "Y-posisjon: " << gety() << std::endl;
std::cout << "X-hastighet: " << getxv() << std::endl;
std::cout << "Y-hastighet: " << getyv() << std::endl;
std::cout << "\n#############\n" << std::endl;
}
void Planet::printInfoShort()
{
std::cout << "ID: " << getId() << " // " << "M: " << getmass() << " X: " << getx() << " | " << getxv() << " Y: " << gety() << " | " << getyv() << " | " << std::endl;
}
void Planet::kollisjon(Planet p)
{
xv = (mass*xv + p.mass*p.getxv()) / (mass + p.getmass());
yv = (mass*yv + p.mass*p.getyv()) / (mass + p.getmass());
double dXV = xv - p.getxv();
double dYV = yv - p.getyv();
incTEnergy(COLLISION_HEAT_MULTIPLIER*((dXV*dXV + dYV*dYV)*p.getmass()));
}
void Planet::draw(sf::RenderWindow &w, double xx, double yy)
{
circle.setPosition(x-xx,y-yy);
if (planetType != GASGIANT)
{
w.draw(circle);
}
else
{
w.draw(circle);
for (int i = 0; i < atmoLinesBrightness.size(); i++)
{
sf::CircleShape atmoLine;
//SETTING FEATURES
int midlLines = (numAtmoLines - 1);
atmoLine.setRadius(circle.getRadius() - i * i * i * circle.getRadius() / (midlLines*midlLines*midlLines));
atmoLine.setOrigin(atmoLine.getRadius(), atmoLine.getRadius());
atmoLine.setPosition(circle.getPosition());
atmoLine.setOutlineThickness(0);
//FINDING COLOR
double r = atmoCol_r + atmoLinesBrightness[i] + temperature / 10;
double g = atmoCol_g + atmoLinesBrightness[i] - temperature / 15;
double b = atmoCol_b + atmoLinesBrightness[i] - temperature / 15;
if (r > 255) r = 255;
if (g > 255) g = 255;
if (b > 255) b = 255;
if (r < 0) r = 0;
if (g < 0) g = 0;
if (b < 0) b = 0;
atmoLine.setFillColor(sf::Color(r, g, b));
w.draw(atmoLine);
}
}
}
void Planet::setColor()
{
if (planetType != ROCKY && planetType != TERRESTIAL && planetType != BLACKHOLE && planetType != GASGIANT)
{
circle.setFillColor(getStarCol());
circle.setOutlineColor(sf::Color(circle.getFillColor().r, circle.getFillColor().g, circle.getFillColor().b, 20));
}
else if (planetType == ROCKY || planetType == TERRESTIAL)
{
double r = 100 + randBrightness +temperature / 10;
double g = 100 + randBrightness -temperature / 15 + getLife().getBmass() /20;
double b = 100 + randBrightness -temperature / 15;
if (r > 255) r = 255;
if (g > 255) g = 255;
if (b > 255) b = 255;
if (r < 0) r = 0;
if (g < 0) g = 0;
if (b < 0) b = 0;
circle.setFillColor(sf::Color(r, g, b));
}
else if (planetType == GASGIANT)
{
double r = atmoCol_r +temperature / 10;
double g = atmoCol_g -temperature / 15;
double b = atmoCol_b -temperature / 15;
if (r > 255) r = 255;
if (g > 255) g = 255;
if (b > 255) b = 255;
if (r < 0) r = 0;
if (g < 0) g = 0;
if (b < 0) b = 0;
circle.setFillColor(sf::Color(r, g, b));
}
}
std::string convertDoubleToString(double number)
{
std::string Result;
std::stringstream convert;
convert << number;
return convert.str();
}
std::string Planet::genName()
{
std::vector<std::string> navn_del_en = { "Jup", "Jor", "Ear", "Mar", "Ven", "Cer", "Sat", "Pl", "Nep", "Ur", "Ker", "Mer", "Jov", "Qur", "Deb", "Car", "Xet", "Nayt", "Erist", "Hamar", "Bjork", "Deat", "Limus", "Lant", "Hypor", "Hyper", "Tell", "It", "As", "Ka", "Po", "Yt", "Pertat" };
std::vector<std::string> navn_del_to = { "it", "enden", "orden", "eptux", "atur", "oper", "uqtor", "axax" };
std::vector<std::string> navn_del_tre = {"er", "us" , "o", "i", "atara", "ankara", "oxos", "upol", "ol", "eq"};
int selectorOne = modernRandomWithLimits(0, navn_del_en.size()-1);
int selectorTwo = modernRandomWithLimits(0, navn_del_to.size()-1);
int selectorThree = modernRandomWithLimits(0, navn_del_tre.size()-1);
std::string number = "";
if (modernRandomWithLimits(0, 100) < 20) number = " " + convertDoubleToString(modernRandomWithLimits(100, 999));
std::string navn = navn_del_en[selectorOne] + navn_del_to[selectorTwo] + navn_del_tre[selectorThree] + number;
return navn;
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <iostream>
#include <vector>
#include <boost/numeric/odeint.hpp>
#include <stan/agrad/rev.hpp>
#include <stan/math/ode/solve_ode_diff_integrator.hpp>
#include <stan/math/ode/solve_ode.hpp>
//calculates finite diffs for solve_ode with varying parameters
template <typename F>
std::vector<std::vector<double> > finite_diff_params(const F& f,
const double& t_in,
const std::vector<double>& ts,
const std::vector<double>& y_in,
const std::vector<double>& theta,
const std::vector<double>& x,
const std::vector<int>& x_int,
const int& param_index,
const double& diff) {
std::vector<double> theta_ub(theta.size());
std::vector<double> theta_lb(theta.size());
for (int i = 0; i < theta.size(); i++) {
if (i == param_index) {
theta_ub[i] = theta[i] + diff;
theta_lb[i] = theta[i] - diff;
} else {
theta_ub[i] = theta[i];
theta_lb[i] = theta[i];
}
}
std::vector<std::vector<double> > ode_res_ub;
std::vector<std::vector<double> > ode_res_lb;
ode_res_ub = stan::math::solve_ode(f, y_in, t_in,
ts, theta_ub, x, x_int);
ode_res_lb = stan::math::solve_ode(f, y_in, t_in,
ts, theta_lb, x, x_int);
std::vector<std::vector<double> > results(ts.size());
for (int i = 0; i < ode_res_ub.size(); i++)
for (int j = 0; j < ode_res_ub[j].size(); j++)
results[i].push_back((ode_res_ub[i][j] - ode_res_lb[i][j]) / (2*diff));
return results;
}
//test solve_ode with initial positions as doubles and parameters as vars
//against finite differences
template <typename F>
void test_ode_dv(const F& f,
const double& t_in,
const std::vector<double>& ts,
const std::vector<double>& y_in,
const std::vector<double>& theta,
const std::vector<double>& x,
const std::vector<int>& x_int,
const double& diff,
const double& diff2) {
std::vector<std::vector<std::vector<double> > > finite_diff_res(theta.size());
for (int i = 0; i < theta.size(); i++)
finite_diff_res[i] = finite_diff_params(f, t_in, ts, y_in, theta, x, x_int, i, diff);
std::vector<double> grads_eff;
std::vector<stan::agrad::var> theta_v;
for (int i = 0; i < theta.size(); i++)
theta_v.push_back(theta[i]);
std::vector<std::vector<stan::agrad::var> > ode_res;
ode_res = stan::math::solve_ode(f, y_in, t_in,
ts, theta_v, x, x_int);
for (int i = 0; i < ts.size(); i++) {
for (int j = 0; j < y_in.size(); j++) {
grads_eff.clear();
ode_res[i][j].grad(theta_v, grads_eff);
for (int k = 0; k < theta.size(); k++)
EXPECT_NEAR(grads_eff[k], finite_diff_res[k][i][j], diff2)
<< "Gradient of solve_ode failed with initial positions"
<< " known and parameters unknown at time index " << i
<< ", equation index " << j
<< ", and parameter index: " << k;
stan::agrad::set_zero_all_adjoints();
}
}
}
//calculates finite diffs for solve_ode with varying initial positions
template <typename F>
std::vector<std::vector<double> >
finite_diff_initial_position(const F& f,
const double& t_in,
const std::vector<double>& ts,
const std::vector<double>& y_in,
const std::vector<double>& theta,
const std::vector<double>& x,
const std::vector<int>& x_int,
const int& param_index,
const double& diff) {
std::vector<double> y_in_ub(y_in.size());
std::vector<double> y_in_lb(y_in.size());
for (int i = 0; i < y_in.size(); i++) {
if (i == param_index) {
y_in_ub[i] = y_in[i] + diff;
y_in_lb[i] = y_in[i] - diff;
} else {
y_in_ub[i] = y_in[i];
y_in_lb[i] = y_in[i];
}
}
std::vector<std::vector<double> > ode_res_ub;
std::vector<std::vector<double> > ode_res_lb;
ode_res_ub = stan::math::solve_ode(f, y_in_ub, t_in,
ts, theta, x, x_int);
ode_res_lb = stan::math::solve_ode(f, y_in_lb, t_in,
ts, theta, x, x_int);
std::vector<std::vector<double> > results(ts.size());
for (int i = 0; i < ode_res_ub.size(); i++)
for (int j = 0; j < ode_res_ub[j].size(); j++)
results[i].push_back((ode_res_ub[i][j] - ode_res_lb[i][j]) / (2*diff));
return results;
}
//test solve_ode with initial positions as vars and parameters as doubles
//against finite differences
template <typename F>
void test_ode_vd(const F& f,
const double& t_in,
const std::vector<double>& ts,
const std::vector<double>& y_in,
const std::vector<double>& theta,
const std::vector<double>& x,
const std::vector<int>& x_int,
const double& diff,
const double& diff2) {
std::vector<std::vector<std::vector<double> > > finite_diff_res(y_in.size());
for (int i = 0; i < y_in.size(); i++)
finite_diff_res[i] = finite_diff_initial_position(f, t_in, ts, y_in, theta, x, x_int, i, diff);
std::vector<double> grads_eff;
std::vector<stan::agrad::var> y_in_v;
for (int k = 0; k < y_in.size(); k++)
y_in_v.push_back(y_in[k]);
std::vector<std::vector<stan::agrad::var> > ode_res;
ode_res = stan::math::solve_ode(f, y_in_v, t_in,
ts, theta, x, x_int);
for (int i = 0; i < ts.size(); i++) {
for (int j = 0; j < y_in.size(); j++) {
grads_eff.clear();
ode_res[i][j].grad(y_in_v, grads_eff);
for (int k = 0; k < y_in.size(); k++)
EXPECT_NEAR(grads_eff[k], finite_diff_res[k][i][j], diff2)
<< "Gradient of solve_ode failed with initial positions"
<< " unknown and parameters known at time index " << i
<< ", equation index " << j
<< ", and parameter index: " << k;
stan::agrad::set_zero_all_adjoints();
}
}
}
//test solve_ode with initial positions as vars and parameters as vars
//against finite differences
template <typename F>
void test_ode_vv(const F& f,
const double& t_in,
const std::vector<double>& ts,
const std::vector<double>& y_in,
const std::vector<double>& theta,
const std::vector<double>& x,
const std::vector<int>& x_int,
const double& diff,
const double& diff2) {
std::vector<std::vector<std::vector<double> > > finite_diff_res_y(y_in.size());
for (int i = 0; i < y_in.size(); i++)
finite_diff_res_y[i] = finite_diff_initial_position(f, t_in, ts, y_in,
theta, x, x_int, i, diff);
std::vector<std::vector<std::vector<double> > > finite_diff_res_p(theta.size());
for (int i = 0; i < theta.size(); i++)
finite_diff_res_p[i] = finite_diff_params(f, t_in, ts, y_in, theta, x,
x_int, i, diff);
std::vector<double> grads_eff;
std::vector<stan::agrad::var> y_in_v;
for (int i = 0; i < y_in.size(); i++)
y_in_v.push_back(y_in[i]);
std::vector<stan::agrad::var> vars = y_in_v;
std::vector<stan::agrad::var> theta_v;
for (int i = 0; i < theta.size(); i++)
theta_v.push_back(theta[i]);
for (int i = 0; i < theta_v.size(); i++)
vars.push_back(theta_v[i]);
std::vector<std::vector<stan::agrad::var> > ode_res;
ode_res = stan::math::solve_ode(f, y_in_v, t_in,
ts, theta_v, x, x_int);
for (int i = 0; i < ts.size(); i++) {
for (int j = 0; j < y_in.size(); j++) {
grads_eff.clear();
ode_res[i][j].grad(vars, grads_eff);
for (int k = 0; k < theta.size(); k++)
EXPECT_NEAR(grads_eff[k+y_in.size()], finite_diff_res_p[k][i][j], diff2)
<< "Gradient of solve_ode failed with initial positions"
<< " unknown and parameters unknown for param at time index " << i
<< ", equation index " << j
<< ", and parameter index: " << k;
for (int k = 0; k < y_in.size(); k++)
EXPECT_NEAR(grads_eff[k], finite_diff_res_y[k][i][j], diff2)
<< "Gradient of solve_ode failed with initial positions"
<< " unknown and parameters known for initial position at time index " << i
<< ", equation index " << j
<< ", and parameter index: " << k;
stan::agrad::set_zero_all_adjoints();
}
}
}
// template <typename F>
// inline void solve_ode_diff_integrator(const F& f,
// const std::vector<double>& y0_dbl,
// const double& t0_dbl,
// const std::vector<double>& ts_dbl,
// const std::vector<double>& theta_dbl,
// const std::vector<double>& x,
// const std::vector<int>& x_int,
// const int& iteration_number,
// const int& eqn_number,
// double& value,
// std::vector<double>& gradients) {
// std::vector<stan::agrad::var> y0;
// for (int i = 0; i < y0_dbl.size(); i++)
// y0.push_back(y0_dbl[i]);
// double t0;
// t0 = t0_dbl;
// std::vector<double> ts;
// for (int i = 0; i < ts_dbl.size(); i++)
// ts.push_back(ts_dbl[i]);
// std::vector<stan::agrad::var> theta;
// for (int i = 0; i < theta_dbl.size(); i++)
// theta.push_back(theta_dbl[i]);
// std::vector<stan::agrad::var> vars;
// for (int i = 0; i < theta.size(); i++)
// vars.push_back(theta[i]);
// for (int i = 0; i < y0.size(); i++)
// vars.push_back(y0[i]);
// std::vector<std::vector<stan::agrad::var> > ode_res;
// ode_res = stan::math::solve_ode_diff_integrator(f, y0, t0,
// ts, theta, x, x_int);
// value = ode_res[iteration_number][eqn_number].val();
// ode_res[iteration_number][eqn_number].grad(vars, gradients);
// }
<commit_msg>remove unused function in test/unit/math/ode/util<commit_after>#include <gtest/gtest.h>
#include <iostream>
#include <vector>
#include <boost/numeric/odeint.hpp>
#include <stan/agrad/rev.hpp>
#include <stan/math/ode/solve_ode_diff_integrator.hpp>
#include <stan/math/ode/solve_ode.hpp>
//calculates finite diffs for solve_ode with varying parameters
template <typename F>
std::vector<std::vector<double> > finite_diff_params(const F& f,
const double& t_in,
const std::vector<double>& ts,
const std::vector<double>& y_in,
const std::vector<double>& theta,
const std::vector<double>& x,
const std::vector<int>& x_int,
const int& param_index,
const double& diff) {
std::vector<double> theta_ub(theta.size());
std::vector<double> theta_lb(theta.size());
for (int i = 0; i < theta.size(); i++) {
if (i == param_index) {
theta_ub[i] = theta[i] + diff;
theta_lb[i] = theta[i] - diff;
} else {
theta_ub[i] = theta[i];
theta_lb[i] = theta[i];
}
}
std::vector<std::vector<double> > ode_res_ub;
std::vector<std::vector<double> > ode_res_lb;
ode_res_ub = stan::math::solve_ode(f, y_in, t_in,
ts, theta_ub, x, x_int);
ode_res_lb = stan::math::solve_ode(f, y_in, t_in,
ts, theta_lb, x, x_int);
std::vector<std::vector<double> > results(ts.size());
for (int i = 0; i < ode_res_ub.size(); i++)
for (int j = 0; j < ode_res_ub[j].size(); j++)
results[i].push_back((ode_res_ub[i][j] - ode_res_lb[i][j]) / (2*diff));
return results;
}
//test solve_ode with initial positions as doubles and parameters as vars
//against finite differences
template <typename F>
void test_ode_dv(const F& f,
const double& t_in,
const std::vector<double>& ts,
const std::vector<double>& y_in,
const std::vector<double>& theta,
const std::vector<double>& x,
const std::vector<int>& x_int,
const double& diff,
const double& diff2) {
std::vector<std::vector<std::vector<double> > > finite_diff_res(theta.size());
for (int i = 0; i < theta.size(); i++)
finite_diff_res[i] = finite_diff_params(f, t_in, ts, y_in, theta, x, x_int, i, diff);
std::vector<double> grads_eff;
std::vector<stan::agrad::var> theta_v;
for (int i = 0; i < theta.size(); i++)
theta_v.push_back(theta[i]);
std::vector<std::vector<stan::agrad::var> > ode_res;
ode_res = stan::math::solve_ode(f, y_in, t_in,
ts, theta_v, x, x_int);
for (int i = 0; i < ts.size(); i++) {
for (int j = 0; j < y_in.size(); j++) {
grads_eff.clear();
ode_res[i][j].grad(theta_v, grads_eff);
for (int k = 0; k < theta.size(); k++)
EXPECT_NEAR(grads_eff[k], finite_diff_res[k][i][j], diff2)
<< "Gradient of solve_ode failed with initial positions"
<< " known and parameters unknown at time index " << i
<< ", equation index " << j
<< ", and parameter index: " << k;
stan::agrad::set_zero_all_adjoints();
}
}
}
//calculates finite diffs for solve_ode with varying initial positions
template <typename F>
std::vector<std::vector<double> >
finite_diff_initial_position(const F& f,
const double& t_in,
const std::vector<double>& ts,
const std::vector<double>& y_in,
const std::vector<double>& theta,
const std::vector<double>& x,
const std::vector<int>& x_int,
const int& param_index,
const double& diff) {
std::vector<double> y_in_ub(y_in.size());
std::vector<double> y_in_lb(y_in.size());
for (int i = 0; i < y_in.size(); i++) {
if (i == param_index) {
y_in_ub[i] = y_in[i] + diff;
y_in_lb[i] = y_in[i] - diff;
} else {
y_in_ub[i] = y_in[i];
y_in_lb[i] = y_in[i];
}
}
std::vector<std::vector<double> > ode_res_ub;
std::vector<std::vector<double> > ode_res_lb;
ode_res_ub = stan::math::solve_ode(f, y_in_ub, t_in,
ts, theta, x, x_int);
ode_res_lb = stan::math::solve_ode(f, y_in_lb, t_in,
ts, theta, x, x_int);
std::vector<std::vector<double> > results(ts.size());
for (int i = 0; i < ode_res_ub.size(); i++)
for (int j = 0; j < ode_res_ub[j].size(); j++)
results[i].push_back((ode_res_ub[i][j] - ode_res_lb[i][j]) / (2*diff));
return results;
}
//test solve_ode with initial positions as vars and parameters as doubles
//against finite differences
template <typename F>
void test_ode_vd(const F& f,
const double& t_in,
const std::vector<double>& ts,
const std::vector<double>& y_in,
const std::vector<double>& theta,
const std::vector<double>& x,
const std::vector<int>& x_int,
const double& diff,
const double& diff2) {
std::vector<std::vector<std::vector<double> > > finite_diff_res(y_in.size());
for (int i = 0; i < y_in.size(); i++)
finite_diff_res[i] = finite_diff_initial_position(f, t_in, ts, y_in, theta, x, x_int, i, diff);
std::vector<double> grads_eff;
std::vector<stan::agrad::var> y_in_v;
for (int k = 0; k < y_in.size(); k++)
y_in_v.push_back(y_in[k]);
std::vector<std::vector<stan::agrad::var> > ode_res;
ode_res = stan::math::solve_ode(f, y_in_v, t_in,
ts, theta, x, x_int);
for (int i = 0; i < ts.size(); i++) {
for (int j = 0; j < y_in.size(); j++) {
grads_eff.clear();
ode_res[i][j].grad(y_in_v, grads_eff);
for (int k = 0; k < y_in.size(); k++)
EXPECT_NEAR(grads_eff[k], finite_diff_res[k][i][j], diff2)
<< "Gradient of solve_ode failed with initial positions"
<< " unknown and parameters known at time index " << i
<< ", equation index " << j
<< ", and parameter index: " << k;
stan::agrad::set_zero_all_adjoints();
}
}
}
//test solve_ode with initial positions as vars and parameters as vars
//against finite differences
template <typename F>
void test_ode_vv(const F& f,
const double& t_in,
const std::vector<double>& ts,
const std::vector<double>& y_in,
const std::vector<double>& theta,
const std::vector<double>& x,
const std::vector<int>& x_int,
const double& diff,
const double& diff2) {
std::vector<std::vector<std::vector<double> > > finite_diff_res_y(y_in.size());
for (int i = 0; i < y_in.size(); i++)
finite_diff_res_y[i] = finite_diff_initial_position(f, t_in, ts, y_in,
theta, x, x_int, i, diff);
std::vector<std::vector<std::vector<double> > > finite_diff_res_p(theta.size());
for (int i = 0; i < theta.size(); i++)
finite_diff_res_p[i] = finite_diff_params(f, t_in, ts, y_in, theta, x,
x_int, i, diff);
std::vector<double> grads_eff;
std::vector<stan::agrad::var> y_in_v;
for (int i = 0; i < y_in.size(); i++)
y_in_v.push_back(y_in[i]);
std::vector<stan::agrad::var> vars = y_in_v;
std::vector<stan::agrad::var> theta_v;
for (int i = 0; i < theta.size(); i++)
theta_v.push_back(theta[i]);
for (int i = 0; i < theta_v.size(); i++)
vars.push_back(theta_v[i]);
std::vector<std::vector<stan::agrad::var> > ode_res;
ode_res = stan::math::solve_ode(f, y_in_v, t_in,
ts, theta_v, x, x_int);
for (int i = 0; i < ts.size(); i++) {
for (int j = 0; j < y_in.size(); j++) {
grads_eff.clear();
ode_res[i][j].grad(vars, grads_eff);
for (int k = 0; k < theta.size(); k++)
EXPECT_NEAR(grads_eff[k+y_in.size()], finite_diff_res_p[k][i][j], diff2)
<< "Gradient of solve_ode failed with initial positions"
<< " unknown and parameters unknown for param at time index " << i
<< ", equation index " << j
<< ", and parameter index: " << k;
for (int k = 0; k < y_in.size(); k++)
EXPECT_NEAR(grads_eff[k], finite_diff_res_y[k][i][j], diff2)
<< "Gradient of solve_ode failed with initial positions"
<< " unknown and parameters known for initial position at time index " << i
<< ", equation index " << j
<< ", and parameter index: " << k;
stan::agrad::set_zero_all_adjoints();
}
}
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include "../stubs/database/DB_ReadWrite.h"
#include "../../application/database/Database.h"
#include "../../application/interface/digital/output/leds/DataTypes.h"
#include "../../application/interface/display/Config.h"
class DatabaseTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
//init checks - no point in running further tests if these conditions fail
database.init();
EXPECT_TRUE(database.getDBsize() < LESSDB_SIZE);
EXPECT_TRUE(database.isSignatureValid());
}
virtual void TearDown()
{
}
Database database = Database(DatabaseStub::memoryRead, DatabaseStub::memoryWrite);
};
TEST_F(DatabaseTest, ReadInitialValues)
{
//verify default values
database.factoryReset(initFull);
for (int i=0; i<database.getSupportedPresets(); i++)
{
EXPECT_EQ(database.setPreset(i), true);
//MIDI block
//feature section
//all values should be set to 0
for (int i=0; i<MIDI_FEATURES; i++)
EXPECT_EQ(database.read(DB_BLOCK_GLOBAL, dbSection_global_midiFeatures, i), 0);
//merge section
//all values should be set to 0
EXPECT_EQ(database.read(DB_BLOCK_GLOBAL, dbSection_global_midiMerge, midiMergeType), 0);
EXPECT_EQ(database.read(DB_BLOCK_GLOBAL, dbSection_global_midiMerge, midiMergeUSBchannel), 0);
EXPECT_EQ(database.read(DB_BLOCK_GLOBAL, dbSection_global_midiMerge, midiMergeDINchannel), 0);
//button block
//type section
//all values should be set to 0 (default type)
for (int i=0; i<MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG+MAX_TOUCHSCREEN_BUTTONS; i++)
EXPECT_EQ(database.read(DB_BLOCK_BUTTONS, dbSection_buttons_type, i), 0);
//midi message section
//all values should be set to 0 (default type)
for (int i=0; i<MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG+MAX_TOUCHSCREEN_BUTTONS; i++)
EXPECT_EQ(database.read(DB_BLOCK_BUTTONS, dbSection_buttons_midiMessage, i), 0);
//midi id section
//incremental values - first value should be 0, each successive value should be incremented by 1
for (int i=0; i<MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG+MAX_TOUCHSCREEN_BUTTONS; i++)
EXPECT_EQ(database.read(DB_BLOCK_BUTTONS, dbSection_buttons_midiID, i), i);
//midi velocity section
//all values should be set to 127
for (int i=0; i<MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG+MAX_TOUCHSCREEN_BUTTONS; i++)
EXPECT_EQ(database.read(DB_BLOCK_BUTTONS, dbSection_buttons_velocity, i), 127);
//midi channel section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG+MAX_TOUCHSCREEN_BUTTONS; i++)
EXPECT_EQ(database.read(DB_BLOCK_BUTTONS, dbSection_buttons_midiChannel, i), 0);
//encoders block
//enable section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ENCODERS; i++)
EXPECT_EQ(database.read(DB_BLOCK_ENCODERS, dbSection_encoders_enable, i), 0);
//invert section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ENCODERS; i++)
EXPECT_EQ(database.read(DB_BLOCK_ENCODERS, dbSection_encoders_invert, i), 0);
//mode section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ENCODERS; i++)
EXPECT_EQ(database.read(DB_BLOCK_ENCODERS, dbSection_encoders_mode, i), 0);
//midi id section
//incremental values - first value should be set to 0, each successive value should be incremented by 1
for (int i=0; i<MAX_NUMBER_OF_ENCODERS; i++)
EXPECT_EQ(database.read(DB_BLOCK_ENCODERS, dbSection_encoders_midiID, i), i);
//midi channel section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ENCODERS; i++)
EXPECT_EQ(database.read(DB_BLOCK_ENCODERS, dbSection_encoders_midiChannel, i), 0);
//pulses per step section
//all values should be set to 4
for (int i=0; i<MAX_NUMBER_OF_ENCODERS; i++)
EXPECT_EQ(database.read(DB_BLOCK_ENCODERS, dbSection_encoders_pulsesPerStep, i), 4);
//analog block
//enable section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++)
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_enable, i), 0);
//invert section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++)
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_invert, i), 0);
//type section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++)
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_invert, i), 0);
//midi id section
//incremental values - first value should be set to 0, each successive value should be incremented by 1
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++)
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_midiID, i), i);
//lower limit section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++)
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_lowerLimit, i), 0);
//upper limit section
//all values should be set to 16383
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++)
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_upperLimit, i), 16383);
//midi channel section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++)
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_midiChannel, i), 0);
//LED block
//global section
//all values should be set to 0
for (int i=0; i<LED_GLOBAL_PARAMETERS; i++)
EXPECT_EQ(database.read(DB_BLOCK_LEDS, dbSection_leds_global, i), 0);
//activation id section
//incremental values - first value should be set to 0, each successive value should be incremented by 1
for (int i=0; i<MAX_NUMBER_OF_LEDS; i++)
EXPECT_EQ(database.read(DB_BLOCK_LEDS, dbSection_leds_activationID, i), i);
//rgb enable section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_LEDS; i++)
EXPECT_EQ(database.read(DB_BLOCK_LEDS, dbSection_leds_rgbEnable, i), 0);
//control type section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_LEDS; i++)
EXPECT_EQ(database.read(DB_BLOCK_LEDS, dbSection_leds_controlType, i), 0);
//activation value section
//all values should be set to 127
for (int i=0; i<MAX_NUMBER_OF_LEDS; i++)
EXPECT_EQ(database.read(DB_BLOCK_LEDS, dbSection_leds_activationValue, i), 127);
//midi channel section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_LEDS; i++)
EXPECT_EQ(database.read(DB_BLOCK_LEDS, dbSection_leds_midiChannel, i), 0);
//display block
//feature section
//this section uses custom values
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureEnable), 0);
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureWelcomeMsg), 0);
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureVInfoMsg), 0);
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventRetention), 0);
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDInotesAlternate), 0);
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventTime), MIN_MESSAGE_RETENTION_TIME);
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureOctaveNormalization), 0);
//hw section
//this section uses custom values
//all values should be set to 0
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwController), DISPLAY_CONTROLLERS);
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwResolution), DISPLAY_RESOLUTIONS);
}
}
TEST_F(DatabaseTest, Presets)
{
database.init();
database.factoryReset(initFull);
//verify that first preset is active
EXPECT_EQ(database.getPreset(), 0);
for (int i=0; i<database.getSupportedPresets(); i++)
{
EXPECT_EQ(database.setPreset(i), true);
EXPECT_EQ(database.getPreset(), i);
}
if (database.getSupportedPresets() > 1)
{
//try setting value in preset 1, switch back to preset 0 and verify preset 0 still contains default value
EXPECT_EQ(database.setPreset(1), true);
EXPECT_TRUE(database.update(DB_BLOCK_ANALOG, dbSection_analog_midiID, 5, 1));
EXPECT_EQ(database.setPreset(0), true);
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_midiID, 5), 5);
}
}
TEST_F(DatabaseTest, FactoryReset)
{
database.init();
database.factoryReset(initFull);
//change random values
EXPECT_TRUE(database.update(DB_BLOCK_BUTTONS, dbSection_buttons_midiID, 5, 1));
EXPECT_TRUE(database.update(DB_BLOCK_ENCODERS, dbSection_analog_midiChannel, 2, 11));
EXPECT_TRUE(database.update(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwController, displayController_ssd1306));
database.factoryReset(initFull);
//expect default values
EXPECT_TRUE(database.update(DB_BLOCK_BUTTONS, dbSection_buttons_midiID, 5, 5));
EXPECT_TRUE(database.update(DB_BLOCK_ENCODERS, dbSection_analog_midiChannel, 2, 0));
EXPECT_TRUE(database.update(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwController, DISPLAY_CONTROLLERS));
database.setPresetPreserveState(true);
EXPECT_TRUE(database.getPresetPreserveState());
}
TEST_F(DatabaseTest, LEDs)
{
database.init();
database.factoryReset(initFull);
//regression test
//by default, rgb state should be disabled
for (int i=0; i<MAX_NUMBER_OF_RGB_LEDS; i++)
EXPECT_FALSE(database.read(DB_BLOCK_LEDS, dbSection_leds_rgbEnable, i));
EXPECT_TRUE(database.update(DB_BLOCK_LEDS, dbSection_leds_controlType, 0, ledControlLocal_PCStateOnly));
//rgb state shouldn't change
for (int i=0; i<MAX_NUMBER_OF_RGB_LEDS; i++)
EXPECT_FALSE(database.read(DB_BLOCK_LEDS, dbSection_leds_rgbEnable, i));
}<commit_msg>more tests<commit_after>#include <gtest/gtest.h>
#include "../stubs/database/DB_ReadWrite.h"
#include "../../application/database/Database.h"
#include "../../application/interface/digital/output/leds/DataTypes.h"
#include "../../application/interface/display/Config.h"
class DatabaseTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
//init checks - no point in running further tests if these conditions fail
database.init();
EXPECT_TRUE(database.getDBsize() < LESSDB_SIZE);
EXPECT_TRUE(database.isSignatureValid());
}
virtual void TearDown()
{
}
Database database = Database(DatabaseStub::memoryRead, DatabaseStub::memoryWrite);
};
TEST_F(DatabaseTest, ReadInitialValues)
{
//verify default values
database.factoryReset(initFull);
for (int i=0; i<database.getSupportedPresets(); i++)
{
EXPECT_EQ(database.setPreset(i), true);
//MIDI block
//feature section
//all values should be set to 0
for (int i=0; i<MIDI_FEATURES; i++)
EXPECT_EQ(database.read(DB_BLOCK_GLOBAL, dbSection_global_midiFeatures, i), 0);
//merge section
//all values should be set to 0
EXPECT_EQ(database.read(DB_BLOCK_GLOBAL, dbSection_global_midiMerge, midiMergeType), 0);
EXPECT_EQ(database.read(DB_BLOCK_GLOBAL, dbSection_global_midiMerge, midiMergeUSBchannel), 0);
EXPECT_EQ(database.read(DB_BLOCK_GLOBAL, dbSection_global_midiMerge, midiMergeDINchannel), 0);
//button block
//type section
//all values should be set to 0 (default type)
for (int i=0; i<MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG+MAX_TOUCHSCREEN_BUTTONS; i++)
EXPECT_EQ(database.read(DB_BLOCK_BUTTONS, dbSection_buttons_type, i), 0);
//midi message section
//all values should be set to 0 (default type)
for (int i=0; i<MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG+MAX_TOUCHSCREEN_BUTTONS; i++)
EXPECT_EQ(database.read(DB_BLOCK_BUTTONS, dbSection_buttons_midiMessage, i), 0);
//midi id section
//incremental values - first value should be 0, each successive value should be incremented by 1
for (int i=0; i<MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG+MAX_TOUCHSCREEN_BUTTONS; i++)
EXPECT_EQ(database.read(DB_BLOCK_BUTTONS, dbSection_buttons_midiID, i), i);
//midi velocity section
//all values should be set to 127
for (int i=0; i<MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG+MAX_TOUCHSCREEN_BUTTONS; i++)
EXPECT_EQ(database.read(DB_BLOCK_BUTTONS, dbSection_buttons_velocity, i), 127);
//midi channel section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_BUTTONS+MAX_NUMBER_OF_ANALOG+MAX_TOUCHSCREEN_BUTTONS; i++)
EXPECT_EQ(database.read(DB_BLOCK_BUTTONS, dbSection_buttons_midiChannel, i), 0);
//encoders block
//enable section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ENCODERS; i++)
EXPECT_EQ(database.read(DB_BLOCK_ENCODERS, dbSection_encoders_enable, i), 0);
//invert section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ENCODERS; i++)
EXPECT_EQ(database.read(DB_BLOCK_ENCODERS, dbSection_encoders_invert, i), 0);
//mode section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ENCODERS; i++)
EXPECT_EQ(database.read(DB_BLOCK_ENCODERS, dbSection_encoders_mode, i), 0);
//midi id section
//incremental values - first value should be set to 0, each successive value should be incremented by 1
for (int i=0; i<MAX_NUMBER_OF_ENCODERS; i++)
EXPECT_EQ(database.read(DB_BLOCK_ENCODERS, dbSection_encoders_midiID, i), i);
//midi channel section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ENCODERS; i++)
EXPECT_EQ(database.read(DB_BLOCK_ENCODERS, dbSection_encoders_midiChannel, i), 0);
//pulses per step section
//all values should be set to 4
for (int i=0; i<MAX_NUMBER_OF_ENCODERS; i++)
EXPECT_EQ(database.read(DB_BLOCK_ENCODERS, dbSection_encoders_pulsesPerStep, i), 4);
//analog block
//enable section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++)
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_enable, i), 0);
//invert section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++)
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_invert, i), 0);
//type section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++)
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_invert, i), 0);
//midi id section
//incremental values - first value should be set to 0, each successive value should be incremented by 1
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++)
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_midiID, i), i);
//lower limit section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++)
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_lowerLimit, i), 0);
//upper limit section
//all values should be set to 16383
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++)
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_upperLimit, i), 16383);
//midi channel section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_ANALOG; i++)
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_midiChannel, i), 0);
//LED block
//global section
//all values should be set to 0
for (int i=0; i<LED_GLOBAL_PARAMETERS; i++)
EXPECT_EQ(database.read(DB_BLOCK_LEDS, dbSection_leds_global, i), 0);
//activation id section
//incremental values - first value should be set to 0, each successive value should be incremented by 1
for (int i=0; i<MAX_NUMBER_OF_LEDS; i++)
EXPECT_EQ(database.read(DB_BLOCK_LEDS, dbSection_leds_activationID, i), i);
//rgb enable section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_LEDS; i++)
EXPECT_EQ(database.read(DB_BLOCK_LEDS, dbSection_leds_rgbEnable, i), 0);
//control type section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_LEDS; i++)
EXPECT_EQ(database.read(DB_BLOCK_LEDS, dbSection_leds_controlType, i), 0);
//activation value section
//all values should be set to 127
for (int i=0; i<MAX_NUMBER_OF_LEDS; i++)
EXPECT_EQ(database.read(DB_BLOCK_LEDS, dbSection_leds_activationValue, i), 127);
//midi channel section
//all values should be set to 0
for (int i=0; i<MAX_NUMBER_OF_LEDS; i++)
EXPECT_EQ(database.read(DB_BLOCK_LEDS, dbSection_leds_midiChannel, i), 0);
//display block
//feature section
//this section uses custom values
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureEnable), 0);
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureWelcomeMsg), 0);
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureVInfoMsg), 0);
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventRetention), 0);
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDInotesAlternate), 0);
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventTime), MIN_MESSAGE_RETENTION_TIME);
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureOctaveNormalization), 0);
//hw section
//this section uses custom values
//all values should be set to 0
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwController), DISPLAY_CONTROLLERS);
EXPECT_EQ(database.read(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwResolution), DISPLAY_RESOLUTIONS);
}
}
TEST_F(DatabaseTest, Presets)
{
database.init();
database.factoryReset(initFull);
//verify that first preset is active
EXPECT_EQ(database.getPreset(), 0);
for (int i=0; i<database.getSupportedPresets(); i++)
{
EXPECT_EQ(database.setPreset(i), true);
EXPECT_EQ(database.getPreset(), i);
}
if (database.getSupportedPresets() > 1)
{
//try setting value in preset 1, switch back to preset 0 and verify preset 0 still contains default value
EXPECT_EQ(database.setPreset(1), true);
EXPECT_TRUE(database.update(DB_BLOCK_ANALOG, dbSection_analog_midiID, 5, 1));
EXPECT_EQ(database.setPreset(0), true);
EXPECT_EQ(database.read(DB_BLOCK_ANALOG, dbSection_analog_midiID, 5), 5);
}
//enable preset preservation, perform factory reset and verify that preservation is disabled
database.setPresetPreserveState(true);
EXPECT_TRUE(database.getPresetPreserveState());
database.factoryReset(initFull);
database.init();
EXPECT_FALSE(database.getPresetPreserveState());
}
TEST_F(DatabaseTest, FactoryReset)
{
database.init();
database.factoryReset(initFull);
//change random values
EXPECT_TRUE(database.update(DB_BLOCK_BUTTONS, dbSection_buttons_midiID, 5, 1));
EXPECT_TRUE(database.update(DB_BLOCK_ENCODERS, dbSection_analog_midiChannel, 2, 11));
EXPECT_TRUE(database.update(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwController, displayController_ssd1306));
database.factoryReset(initFull);
//expect default values
EXPECT_TRUE(database.update(DB_BLOCK_BUTTONS, dbSection_buttons_midiID, 5, 5));
EXPECT_TRUE(database.update(DB_BLOCK_ENCODERS, dbSection_analog_midiChannel, 2, 0));
EXPECT_TRUE(database.update(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwController, DISPLAY_CONTROLLERS));
database.setPresetPreserveState(true);
EXPECT_TRUE(database.getPresetPreserveState());
}
TEST_F(DatabaseTest, LEDs)
{
database.init();
database.factoryReset(initFull);
//regression test
//by default, rgb state should be disabled
for (int i=0; i<MAX_NUMBER_OF_RGB_LEDS; i++)
EXPECT_FALSE(database.read(DB_BLOCK_LEDS, dbSection_leds_rgbEnable, i));
EXPECT_TRUE(database.update(DB_BLOCK_LEDS, dbSection_leds_controlType, 0, ledControlLocal_PCStateOnly));
//rgb state shouldn't change
for (int i=0; i<MAX_NUMBER_OF_RGB_LEDS; i++)
EXPECT_FALSE(database.read(DB_BLOCK_LEDS, dbSection_leds_rgbEnable, i));
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008-2019 the MRtrix3 contributors.
*
* 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/
*
* MRtrix3 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.
*
* For more details, see http://www.mrtrix.org/
*/
#include "command.h"
#include "image.h"
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
#define DEFAULT_SIZE 5
using namespace MR;
using namespace App;
const char* const dtypes[] = { "float32", "float64", NULL };
const char* const estimators[] = { "exp1", "exp2", NULL };
void usage ()
{
SYNOPSIS = "Denoise DWI data and estimate the noise level based on the optimal threshold for PCA";
DESCRIPTION
+ "DWI data denoising and noise map estimation by exploiting data redundancy in the PCA domain "
"using the prior knowledge that the eigenspectrum of random covariance matrices is described by "
"the universal Marchenko-Pastur (MP) distribution. Fitting the MP distribution to the spectrum "
"of patch-wise signal matrices hence provides an estimator of the noise level 'sigma', as was "
"first shown in Veraart et al. (2016) and later improved in Cordero-Grande et al. (2019). This "
"noise level estimate then determines the optimal cut-off for PCA denoising."
+ "Important note: image denoising must be performed as the first step of the image processing pipeline. "
"The routine will fail if interpolation or smoothing has been applied to the data prior to denoising."
+ "Note that this function does not correct for non-Gaussian noise biases.";
AUTHOR = "Daan Christiaens (daan.christiaens@kcl.ac.uk) & "
"Jelle Veraart (jelle.veraart@nyumc.org) & "
"J-Donald Tournier (jdtournier@gmail.com)";
REFERENCES
+ "Veraart, J.; Novikov, D.S.; Christiaens, D.; Ades-aron, B.; Sijbers, J. & Fieremans, E. " // Internal
"Denoising of diffusion MRI using random matrix theory. "
"NeuroImage, 2016, 142, 394-406, doi: 10.1016/j.neuroimage.2016.08.016"
+ "Veraart, J.; Fieremans, E. & Novikov, D.S. " // Internal
"Diffusion MRI noise mapping using random matrix theory. "
"Magn. Res. Med., 2016, 76(5), 1582-1593, doi: 10.1002/mrm.26059"
+ "Cordero-Grande, L.; Christiaens, D.; Hutter, J.; Price, A.N.; Hajnal, J.V. " // Internal
"Complex diffusion-weighted image estimation via matrix recovery under general noise models. "
"NeuroImage, 2019, 200, 391-404, doi: 10.1016/j.neuroimage.2019.06.039";
ARGUMENTS
+ Argument ("dwi", "the input diffusion-weighted image.").type_image_in ()
+ Argument ("out", "the output denoised DWI image.").type_image_out ();
OPTIONS
+ Option ("mask", "only perform computation within the specified binary brain mask image.")
+ Argument ("image").type_image_in()
+ Option ("extent", "set the window size of the denoising filter. (default = " + str(DEFAULT_SIZE) + "," + str(DEFAULT_SIZE) + "," + str(DEFAULT_SIZE) + ")")
+ Argument ("window").type_sequence_int ()
+ Option ("noise", "the output noise map, i.e., the estimated noise level 'sigma' in the data.")
+ Argument ("level").type_image_out()
+ Option ("datatype", "datatype for SVD (single or double precision).")
+ Argument ("float32/float64").type_choice(dtypes)
+ Option ("estimator", "select noise level estimator (default = Exp2), either \n"
"Exp1: the original estimator used in Veraart et al. (2016), or \n"
"Exp2: the improved estimator introduced in Cordero-Grande et al. (2019).")
+ Argument ("Exp1/Exp2").type_choice(estimators);
COPYRIGHT = "Copyright (c) 2016 New York University, University of Antwerp, and the MRtrix3 contributors \n \n"
"Permission is hereby granted, free of charge, to any non-commercial entity ('Recipient') obtaining a copy of this software and "
"associated documentation files (the 'Software'), to the Software solely for non-commercial research, including the rights to "
"use, copy and modify the Software, subject to the following conditions: \n \n"
"\t 1. The above copyright notice and this permission notice shall be included by Recipient in all copies or substantial portions of "
"the Software. \n \n"
"\t 2. 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. \n \n"
"\t 3. In no event shall NYU be liable for direct, indirect, special, incidental or consequential damages in connection with the Software. "
"Recipient will defend, indemnify and hold NYU harmless from any claims or liability resulting from the use of the Software by recipient. \n \n"
"\t 4. Neither anything contained herein nor the delivery of the Software to recipient shall be deemed to grant the Recipient any right or "
"licenses under any patents or patent application owned by NYU. \n \n"
"\t 5. The Software may only be used for non-commercial research and may not be used for clinical care. \n \n"
"\t 6. Any publication by Recipient of research involving the Software shall cite the references listed below.";
}
using real_type = float;
template <typename F = float>
class DenoisingFunctor {
MEMALIGN(DenoisingFunctor)
public:
using MatrixType = Eigen::Matrix<F, Eigen::Dynamic, Eigen::Dynamic>;
using SValsType = Eigen::VectorXd;
DenoisingFunctor (int ndwi, const vector<int>& extent,
Image<bool>& mask, Image<real_type>& noise, bool exp1)
: extent {{extent[0]/2, extent[1]/2, extent[2]/2}},
m (ndwi), n (extent[0]*extent[1]*extent[2]),
r (std::min(m,n)), q (std::max(m,n)), exp1(exp1),
X (m,n), pos {{0, 0, 0}},
mask (mask), noise (noise)
{ }
template <typename ImageType>
void operator () (ImageType& dwi, ImageType& out)
{
// Process voxels in mask only
if (mask.valid()) {
assign_pos_of (dwi).to (mask);
if (!mask.value())
return;
}
// Load data in local window
load_data (dwi);
// Compute Eigendecomposition:
MatrixType XtX (r,r);
if (m <= n)
XtX.template triangularView<Eigen::Lower>() = X * X.adjoint();
else
XtX.template triangularView<Eigen::Lower>() = X.adjoint() * X;
Eigen::SelfAdjointEigenSolver<MatrixType> eig (XtX);
// eigenvalues provide squared singular values, sorted in increasing order:
SValsType s = eig.eigenvalues().template cast<double>();
// Marchenko-Pastur optimal threshold
const double lam_r = std::max(s[0], 0.0) / q;
double clam = 0.0;
sigma2 = 0.0;
ssize_t cutoff_p = 0;
for (ssize_t p = 0; p < r; ++p) // p+1 is the number of noise components
{ // (as opposed to the paper where p is defined as the number of signal components)
double lam = std::max(s[p], 0.0) / q;
clam += lam;
double gam = double(p+1) / (exp1 ? q : q-(r-p-1));
double sigsq1 = clam / double(p+1);
double sigsq2 = (lam - lam_r) / (4.0 * std::sqrt(gam));
// sigsq2 > sigsq1 if signal else noise
if (sigsq2 < sigsq1) {
sigma2 = sigsq1;
cutoff_p = p+1;
}
}
if (cutoff_p > 0) {
// recombine data using only eigenvectors above threshold:
s.head (cutoff_p).setZero();
s.tail (r-cutoff_p).setOnes();
if (m <= n)
X.col (n/2) = eig.eigenvectors() * ( s.cast<F>().asDiagonal() * ( eig.eigenvectors().adjoint() * X.col(n/2) ));
else
X.col (n/2) = X * ( eig.eigenvectors() * ( s.cast<F>().asDiagonal() * eig.eigenvectors().adjoint().col(n/2) ));
}
// Store output
assign_pos_of(dwi).to(out);
out.row(3) = X.col(n/2);
// store noise map if requested:
if (noise.valid()) {
assign_pos_of(dwi).to(noise);
noise.value() = real_type (std::sqrt(sigma2));
}
}
private:
const std::array<ssize_t, 3> extent;
const ssize_t m, n, r, q;
const bool exp1;
MatrixType X;
std::array<ssize_t, 3> pos;
double sigma2;
Image<bool> mask;
Image<real_type> noise;
template <typename ImageType>
void load_data (ImageType& dwi) {
pos[0] = dwi.index(0); pos[1] = dwi.index(1); pos[2] = dwi.index(2);
// fill patch
X.setZero();
size_t k = 0;
for (int z = -extent[2]; z <= extent[2]; z++) {
dwi.index(2) = wrapindex(z, 2, dwi.size(2));
for (int y = -extent[1]; y <= extent[1]; y++) {
dwi.index(1) = wrapindex(y, 1, dwi.size(1));
for (int x = -extent[0]; x <= extent[0]; x++, k++) {
dwi.index(0) = wrapindex(x, 0, dwi.size(0));
X.col(k) = dwi.row(3);
}
}
}
// reset image position
dwi.index(0) = pos[0];
dwi.index(1) = pos[1];
dwi.index(2) = pos[2];
}
inline size_t wrapindex(int r, int axis, int max) const {
// patch handling at image edges
int rr = pos[axis] + r;
if (rr < 0) rr = extent[axis] - r;
if (rr >= max) rr = (max-1) - extent[axis] - r;
return rr;
}
};
template <typename T>
void process_image (Header& data, Image<bool>& mask, Image<real_type> noise,
const std::string& output_name, const vector<int>& extent, bool exp1)
{
auto input = data.get_image<T>().with_direct_io(3);
// create output
Header header (data);
header.datatype() = DataType::from<T>();
auto output = Image<T>::create (output_name, header);
// run
DenoisingFunctor<T> func (data.size(3), extent, mask, noise, exp1);
ThreadedLoop ("running MP-PCA denoising", data, 0, 3).run (func, input, output);
}
void run ()
{
auto dwi = Header::open (argument[0]);
if (dwi.ndim() != 4 || dwi.size(3) <= 1)
throw Exception ("input image must be 4-dimensional");
Image<bool> mask;
auto opt = get_options ("mask");
if (opt.size()) {
mask = Image<bool>::open (opt[0][0]);
check_dimensions (mask, dwi, 0, 3);
}
opt = get_options("extent");
vector<int> extent = { DEFAULT_SIZE, DEFAULT_SIZE, DEFAULT_SIZE };
if (opt.size()) {
extent = parse_ints(opt[0][0]);
if (extent.size() == 1)
extent = {extent[0], extent[0], extent[0]};
if (extent.size() != 3)
throw Exception ("-extent must be either a scalar or a list of length 3");
for (auto &e : extent)
if (!(e & 1))
throw Exception ("-extent must be a (list of) odd numbers");
}
bool exp1 = get_option_value("estimator", 1) == 0; // default: Exp2 (unbiased estimator)
Image<real_type> noise;
opt = get_options("noise");
if (opt.size()) {
Header header (dwi);
header.ndim() = 3;
header.datatype() = DataType::Float32;
noise = Image<real_type>::create (opt[0][0], header);
}
int prec = get_option_value("datatype", 0); // default: single precision
if (dwi.datatype().is_complex()) prec += 2; // support complex input data
switch (prec) {
case 0:
INFO("select real float32 for processing");
process_image<float>(dwi, mask, noise, argument[1], extent, exp1);
break;
case 1:
INFO("select real float64 for processing");
process_image<double>(dwi, mask, noise, argument[1], extent, exp1);
break;
case 2:
INFO("select complex float32 for processing");
process_image<cfloat>(dwi, mask, noise, argument[1], extent, exp1);
break;
case 3:
INFO("select complex float64 for processing");
process_image<cdouble>(dwi, mask, noise, argument[1], extent, exp1);
break;
}
}
<commit_msg>dwidenoise: update documentation<commit_after>/*
* Copyright (c) 2008-2019 the MRtrix3 contributors.
*
* 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/
*
* MRtrix3 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.
*
* For more details, see http://www.mrtrix.org/
*/
#include "command.h"
#include "image.h"
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
#define DEFAULT_SIZE 5
using namespace MR;
using namespace App;
const char* const dtypes[] = { "float32", "float64", NULL };
const char* const estimators[] = { "exp1", "exp2", NULL };
void usage ()
{
SYNOPSIS = "dMRI noise level estimation and denoising using Marchenko-Pastur PCA";
DESCRIPTION
+ "DWI data denoising and noise map estimation by exploiting data redundancy in the PCA domain "
"using the prior knowledge that the eigenspectrum of random covariance matrices is described by "
"the universal Marchenko-Pastur (MP) distribution. Fitting the MP distribution to the spectrum "
"of patch-wise signal matrices hence provides an estimator of the noise level 'sigma', as was "
"first shown in Veraart et al. (2016) and later improved in Cordero-Grande et al. (2019). This "
"noise level estimate then determines the optimal cut-off for PCA denoising."
+ "Important note: image denoising must be performed as the first step of the image processing pipeline. "
"The routine will fail if interpolation or smoothing has been applied to the data prior to denoising."
+ "Note that this function does not correct for non-Gaussian noise biases present in "
"magnitude-reconstructed MRI images. If available, including the MRI phase data can "
"reduce such non-Gaussian biases, and the command now supports complex input data.";
AUTHOR = "Daan Christiaens (daan.christiaens@kcl.ac.uk) & "
"Jelle Veraart (jelle.veraart@nyumc.org) & "
"J-Donald Tournier (jdtournier@gmail.com)";
REFERENCES
+ "Veraart, J.; Novikov, D.S.; Christiaens, D.; Ades-aron, B.; Sijbers, J. & Fieremans, E. " // Internal
"Denoising of diffusion MRI using random matrix theory. "
"NeuroImage, 2016, 142, 394-406, doi: 10.1016/j.neuroimage.2016.08.016"
+ "Veraart, J.; Fieremans, E. & Novikov, D.S. " // Internal
"Diffusion MRI noise mapping using random matrix theory. "
"Magn. Res. Med., 2016, 76(5), 1582-1593, doi: 10.1002/mrm.26059"
+ "Cordero-Grande, L.; Christiaens, D.; Hutter, J.; Price, A.N.; Hajnal, J.V. " // Internal
"Complex diffusion-weighted image estimation via matrix recovery under general noise models. "
"NeuroImage, 2019, 200, 391-404, doi: 10.1016/j.neuroimage.2019.06.039";
ARGUMENTS
+ Argument ("dwi", "the input diffusion-weighted image.").type_image_in ()
+ Argument ("out", "the output denoised DWI image.").type_image_out ();
OPTIONS
+ Option ("mask", "only perform computation within the specified binary brain mask image.")
+ Argument ("image").type_image_in()
+ Option ("extent", "set the window size of the denoising filter. (default = " + str(DEFAULT_SIZE) + "," + str(DEFAULT_SIZE) + "," + str(DEFAULT_SIZE) + ")")
+ Argument ("window").type_sequence_int ()
+ Option ("noise", "the output noise map, i.e., the estimated noise level 'sigma' in the data. "
"Note that on complex input data, this will be the total noise level across "
"real and imaginary channels, so a scale factor sqrt(2) applies.")
+ Argument ("level").type_image_out()
+ Option ("datatype", "datatype for the eigenvalue decomposition (single or double precision). "
"For complex input data, this will select complex float32 or complex float64 datatypes.")
+ Argument ("float32/float64").type_choice(dtypes)
+ Option ("estimator", "select noise level estimator (default = Exp2), either \n"
"Exp1: the original estimator used in Veraart et al. (2016), or \n"
"Exp2: the improved estimator introduced in Cordero-Grande et al. (2019).")
+ Argument ("Exp1/Exp2").type_choice(estimators);
COPYRIGHT = "Copyright (c) 2016 New York University, University of Antwerp, and the MRtrix3 contributors \n \n"
"Permission is hereby granted, free of charge, to any non-commercial entity ('Recipient') obtaining a copy of this software and "
"associated documentation files (the 'Software'), to the Software solely for non-commercial research, including the rights to "
"use, copy and modify the Software, subject to the following conditions: \n \n"
"\t 1. The above copyright notice and this permission notice shall be included by Recipient in all copies or substantial portions of "
"the Software. \n \n"
"\t 2. 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. \n \n"
"\t 3. In no event shall NYU be liable for direct, indirect, special, incidental or consequential damages in connection with the Software. "
"Recipient will defend, indemnify and hold NYU harmless from any claims or liability resulting from the use of the Software by recipient. \n \n"
"\t 4. Neither anything contained herein nor the delivery of the Software to recipient shall be deemed to grant the Recipient any right or "
"licenses under any patents or patent application owned by NYU. \n \n"
"\t 5. The Software may only be used for non-commercial research and may not be used for clinical care. \n \n"
"\t 6. Any publication by Recipient of research involving the Software shall cite the references listed below.";
}
using real_type = float;
template <typename F = float>
class DenoisingFunctor {
MEMALIGN(DenoisingFunctor)
public:
using MatrixType = Eigen::Matrix<F, Eigen::Dynamic, Eigen::Dynamic>;
using SValsType = Eigen::VectorXd;
DenoisingFunctor (int ndwi, const vector<int>& extent,
Image<bool>& mask, Image<real_type>& noise, bool exp1)
: extent {{extent[0]/2, extent[1]/2, extent[2]/2}},
m (ndwi), n (extent[0]*extent[1]*extent[2]),
r (std::min(m,n)), q (std::max(m,n)), exp1(exp1),
X (m,n), pos {{0, 0, 0}},
mask (mask), noise (noise)
{ }
template <typename ImageType>
void operator () (ImageType& dwi, ImageType& out)
{
// Process voxels in mask only
if (mask.valid()) {
assign_pos_of (dwi).to (mask);
if (!mask.value())
return;
}
// Load data in local window
load_data (dwi);
// Compute Eigendecomposition:
MatrixType XtX (r,r);
if (m <= n)
XtX.template triangularView<Eigen::Lower>() = X * X.adjoint();
else
XtX.template triangularView<Eigen::Lower>() = X.adjoint() * X;
Eigen::SelfAdjointEigenSolver<MatrixType> eig (XtX);
// eigenvalues sorted in increasing order:
SValsType s = eig.eigenvalues().template cast<double>();
// Marchenko-Pastur optimal threshold
const double lam_r = std::max(s[0], 0.0) / q;
double clam = 0.0;
sigma2 = 0.0;
ssize_t cutoff_p = 0;
for (ssize_t p = 0; p < r; ++p) // p+1 is the number of noise components
{ // (as opposed to the paper where p is defined as the number of signal components)
double lam = std::max(s[p], 0.0) / q;
clam += lam;
double gam = double(p+1) / (exp1 ? q : q-(r-p-1));
double sigsq1 = clam / double(p+1);
double sigsq2 = (lam - lam_r) / (4.0 * std::sqrt(gam));
// sigsq2 > sigsq1 if signal else noise
if (sigsq2 < sigsq1) {
sigma2 = sigsq1;
cutoff_p = p+1;
}
}
if (cutoff_p > 0) {
// recombine data using only eigenvectors above threshold:
s.head (cutoff_p).setZero();
s.tail (r-cutoff_p).setOnes();
if (m <= n)
X.col (n/2) = eig.eigenvectors() * ( s.cast<F>().asDiagonal() * ( eig.eigenvectors().adjoint() * X.col(n/2) ));
else
X.col (n/2) = X * ( eig.eigenvectors() * ( s.cast<F>().asDiagonal() * eig.eigenvectors().adjoint().col(n/2) ));
}
// Store output
assign_pos_of(dwi).to(out);
out.row(3) = X.col(n/2);
// store noise map if requested:
if (noise.valid()) {
assign_pos_of(dwi).to(noise);
noise.value() = real_type (std::sqrt(sigma2));
}
}
private:
const std::array<ssize_t, 3> extent;
const ssize_t m, n, r, q;
const bool exp1;
MatrixType X;
std::array<ssize_t, 3> pos;
double sigma2;
Image<bool> mask;
Image<real_type> noise;
template <typename ImageType>
void load_data (ImageType& dwi) {
pos[0] = dwi.index(0); pos[1] = dwi.index(1); pos[2] = dwi.index(2);
// fill patch
X.setZero();
size_t k = 0;
for (int z = -extent[2]; z <= extent[2]; z++) {
dwi.index(2) = wrapindex(z, 2, dwi.size(2));
for (int y = -extent[1]; y <= extent[1]; y++) {
dwi.index(1) = wrapindex(y, 1, dwi.size(1));
for (int x = -extent[0]; x <= extent[0]; x++, k++) {
dwi.index(0) = wrapindex(x, 0, dwi.size(0));
X.col(k) = dwi.row(3);
}
}
}
// reset image position
dwi.index(0) = pos[0];
dwi.index(1) = pos[1];
dwi.index(2) = pos[2];
}
inline size_t wrapindex(int r, int axis, int max) const {
// patch handling at image edges
int rr = pos[axis] + r;
if (rr < 0) rr = extent[axis] - r;
if (rr >= max) rr = (max-1) - extent[axis] - r;
return rr;
}
};
template <typename T>
void process_image (Header& data, Image<bool>& mask, Image<real_type> noise,
const std::string& output_name, const vector<int>& extent, bool exp1)
{
auto input = data.get_image<T>().with_direct_io(3);
// create output
Header header (data);
header.datatype() = DataType::from<T>();
auto output = Image<T>::create (output_name, header);
// run
DenoisingFunctor<T> func (data.size(3), extent, mask, noise, exp1);
ThreadedLoop ("running MP-PCA denoising", data, 0, 3).run (func, input, output);
}
void run ()
{
auto dwi = Header::open (argument[0]);
if (dwi.ndim() != 4 || dwi.size(3) <= 1)
throw Exception ("input image must be 4-dimensional");
Image<bool> mask;
auto opt = get_options ("mask");
if (opt.size()) {
mask = Image<bool>::open (opt[0][0]);
check_dimensions (mask, dwi, 0, 3);
}
opt = get_options("extent");
vector<int> extent = { DEFAULT_SIZE, DEFAULT_SIZE, DEFAULT_SIZE };
if (opt.size()) {
extent = parse_ints(opt[0][0]);
if (extent.size() == 1)
extent = {extent[0], extent[0], extent[0]};
if (extent.size() != 3)
throw Exception ("-extent must be either a scalar or a list of length 3");
for (auto &e : extent)
if (!(e & 1))
throw Exception ("-extent must be a (list of) odd numbers");
}
bool exp1 = get_option_value("estimator", 1) == 0; // default: Exp2 (unbiased estimator)
Image<real_type> noise;
opt = get_options("noise");
if (opt.size()) {
Header header (dwi);
header.ndim() = 3;
header.datatype() = DataType::Float32;
noise = Image<real_type>::create (opt[0][0], header);
}
int prec = get_option_value("datatype", 0); // default: single precision
if (dwi.datatype().is_complex()) prec += 2; // support complex input data
switch (prec) {
case 0:
INFO("select real float32 for processing");
process_image<float>(dwi, mask, noise, argument[1], extent, exp1);
break;
case 1:
INFO("select real float64 for processing");
process_image<double>(dwi, mask, noise, argument[1], extent, exp1);
break;
case 2:
INFO("select complex float32 for processing");
process_image<cfloat>(dwi, mask, noise, argument[1], extent, exp1);
break;
case 3:
INFO("select complex float64 for processing");
process_image<cdouble>(dwi, mask, noise, argument[1], extent, exp1);
break;
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include "../../../shared/util.h"
#include <QtDeclarative/qdeclarativecomponent.h>
#include <QtDeclarative/qdeclarativeengine.h>
#include <QtDeclarative/qsgitem.h>
#include <QtDeclarative/qsgview.h>
class tst_qdeclarativeapplication : public QObject
{
Q_OBJECT
public:
tst_qdeclarativeapplication();
private slots:
void active();
void layoutDirection();
private:
QDeclarativeEngine engine;
};
tst_qdeclarativeapplication::tst_qdeclarativeapplication()
{
}
void tst_qdeclarativeapplication::active()
{
QDeclarativeComponent component(&engine);
component.setData("import QtQuick 2.0; Item { property bool active: Qt.application.active }", QUrl::fromLocalFile(""));
QSGItem *item = qobject_cast<QSGItem *>(component.create());
QVERIFY(item);
QSGView view;
item->setParentItem(view.rootObject());
// not active
QVERIFY(!item->property("active").toBool());
QCOMPARE(item->property("active").toBool(), QApplication::activeWindow() != 0);
// active
view.show();
view.requestActivateWindow();
QTest::qWait(50);
QTRY_COMPARE(view.status(), QSGView::Ready);
QCOMPARE(item->property("active").toBool(), QApplication::activeWindow() != 0);
// not active again
// on mac, setActiveWindow(0) on mac does not deactivate the current application
// (you have to switch to a different app or hide the current app to trigger this)
#if !defined(Q_WS_MAC)
QApplication::setActiveWindow(0);
QVERIFY(!item->property("active").toBool());
QCOMPARE(item->property("active").toBool(), QApplication::activeWindow() != 0);
#endif
}
void tst_qdeclarativeapplication::layoutDirection()
{
QDeclarativeComponent component(&engine);
component.setData("import QtQuick 2.0; Item { property bool layoutDirection: Qt.application.layoutDirection }", QUrl::fromLocalFile(""));
QSGItem *item = qobject_cast<QSGItem *>(component.create());
QVERIFY(item);
QSGView view;
item->setParentItem(view.rootObject());
// not mirrored
QCOMPARE(Qt::LayoutDirection(item->property("layoutDirection").toInt()), Qt::LeftToRight);
// mirrored
QApplication::setLayoutDirection(Qt::RightToLeft);
QCOMPARE(Qt::LayoutDirection(item->property("layoutDirection").toInt()), Qt::RightToLeft);
// not mirrored again
QApplication::setLayoutDirection(Qt::LeftToRight);
QCOMPARE(Qt::LayoutDirection(item->property("layoutDirection").toInt()), Qt::LeftToRight);
}
QTEST_MAIN(tst_qdeclarativeapplication)
#include "tst_qdeclarativeapplication.moc"
<commit_msg>Make qdeclarativeapplication test compile again<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include "../../../shared/util.h"
#include <QtDeclarative/qdeclarativecomponent.h>
#include <QtDeclarative/qdeclarativeengine.h>
#include <QtDeclarative/qsgitem.h>
#include <QtDeclarative/qsgview.h>
class tst_qdeclarativeapplication : public QObject
{
Q_OBJECT
public:
tst_qdeclarativeapplication();
private slots:
void active();
void layoutDirection();
private:
QDeclarativeEngine engine;
};
tst_qdeclarativeapplication::tst_qdeclarativeapplication()
{
}
void tst_qdeclarativeapplication::active()
{
QSKIP("QTBUG-21573", SkipAll);
QDeclarativeComponent component(&engine);
component.setData("import QtQuick 2.0; Item { property bool active: Qt.application.active }", QUrl::fromLocalFile(""));
QSGItem *item = qobject_cast<QSGItem *>(component.create());
QVERIFY(item);
QSGView view;
item->setParentItem(view.rootObject());
// not active
QVERIFY(!item->property("active").toBool());
QCOMPARE(item->property("active").toBool(), QGuiApplication::activeWindow() != 0);
// active
view.show();
view.requestActivateWindow();
QTest::qWait(50);
QTRY_COMPARE(view.status(), QSGView::Ready);
QCOMPARE(item->property("active").toBool(), QGuiApplication::activeWindow() != 0);
// not active again
// on mac, setActiveWindow(0) on mac does not deactivate the current application
// (you have to switch to a different app or hide the current app to trigger this)
#if !defined(Q_WS_MAC)
// QTBUG-21573
// QGuiApplication::setActiveWindow(0);
QVERIFY(!item->property("active").toBool());
QCOMPARE(item->property("active").toBool(), QGuiApplication::activeWindow() != 0);
#endif
}
void tst_qdeclarativeapplication::layoutDirection()
{
QSKIP("QTBUG-21573", SkipAll);
QDeclarativeComponent component(&engine);
component.setData("import QtQuick 2.0; Item { property bool layoutDirection: Qt.application.layoutDirection }", QUrl::fromLocalFile(""));
QSGItem *item = qobject_cast<QSGItem *>(component.create());
QVERIFY(item);
QSGView view;
item->setParentItem(view.rootObject());
// not mirrored
QCOMPARE(Qt::LayoutDirection(item->property("layoutDirection").toInt()), Qt::LeftToRight);
// mirrored
QGuiApplication::setLayoutDirection(Qt::RightToLeft);
QCOMPARE(Qt::LayoutDirection(item->property("layoutDirection").toInt()), Qt::RightToLeft);
// not mirrored again
QGuiApplication::setLayoutDirection(Qt::LeftToRight);
QCOMPARE(Qt::LayoutDirection(item->property("layoutDirection").toInt()), Qt::LeftToRight);
}
QTEST_MAIN(tst_qdeclarativeapplication)
#include "tst_qdeclarativeapplication.moc"
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016 Barrett Adair
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
HEADER GUARDS INTENTIONALLY OMITTED
DO NOT INCLUDE THIS HEADER DIRECTLY
*/
#define BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
#define BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE std::false_type
#include <boost/callable_traits/detail/unguarded/function_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
#undef BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE
#ifdef BOOST_CLBL_TRTS_ENABLE_TRANSACTION_SAFE
#define BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE std::true_type
#define BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE transaction_safe
#include <boost/callable_traits/detail/unguarded/function_2.hpp>
#undef BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
#undef BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE
#endif // #ifdef BOOST_CLBL_TRTS_ENABLE_TRANSACTION_SAFE<commit_msg>Delete function.hpp<commit_after><|endoftext|> |
<commit_before><commit_msg>removed extraneous file<commit_after><|endoftext|> |
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGTank.cpp
Author: Jon Berndt
Date started: 01/21/99
Called by: FGAircraft
------------- Copyright (C) 1999 Jon S. Berndt (jsb@hal-pc.org) -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
See header file.
HISTORY
--------------------------------------------------------------------------------
01/21/99 JSB Created
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGTank.h"
#if !defined ( sgi ) || defined( __GNUC__ )
using std::cerr;
using std::endl;
using std::cout;
#endif
namespace JSBSim {
static const char *IdSrc = "$Id: FGTank.cpp,v 1.28 2003/06/03 09:53:50 ehofman Exp $";
static const char *IdHdr = ID_TANK;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGTank::FGTank(FGConfigFile* AC_cfg)
{
string token;
type = AC_cfg->GetValue("TYPE");
if (type == "FUEL") Type = ttFUEL;
else if (type == "OXIDIZER") Type = ttOXIDIZER;
else Type = ttUNKNOWN;
AC_cfg->GetNextConfigLine();
while ((token = AC_cfg->GetValue()) != string("/AC_TANK")) {
if (token == "XLOC") *AC_cfg >> X;
else if (token == "YLOC") *AC_cfg >> Y;
else if (token == "ZLOC") *AC_cfg >> Z;
else if (token == "RADIUS") *AC_cfg >> Radius;
else if (token == "CAPACITY") *AC_cfg >> Capacity;
else if (token == "CONTENTS") *AC_cfg >> Contents;
else cerr << "Unknown identifier: " << token << " in tank definition." << endl;
}
Selected = true;
if (Capacity != 0) {
PctFull = 100.0*Contents/Capacity; // percent full; 0 to 100.0
} else {
Contents = 0;
PctFull = 0;
}
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGTank::~FGTank()
{
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGTank::Reduce(double used)
{
double shortage = Contents - used;
if (shortage >= 0) {
Contents -= used;
PctFull = 100.0*Contents/Capacity;
} else {
Contents = 0.0;
PctFull = 0.0;
Selected = false;
}
return shortage;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGTank::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
cout << " " << type << " tank holds " << Capacity << " lbs. " << type << endl;
cout << " currently at " << PctFull << "% of maximum capacity" << endl;
cout << " Tank location (X, Y, Z): " << X << ", " << Y << ", " << Z << endl;
cout << " Effective radius: " << Radius << " inches" << endl;
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGTank" << endl;
if (from == 1) cout << "Destroyed: FGTank" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
}
<commit_msg>Fix a problem where the contents could be specified by JSBSim and by FlightGear, where JSBSim would override the FlightGear specified value. Now the JSBSim specified value will be discarded if Contents is already set.<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGTank.cpp
Author: Jon Berndt
Date started: 01/21/99
Called by: FGAircraft
------------- Copyright (C) 1999 Jon S. Berndt (jsb@hal-pc.org) -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
See header file.
HISTORY
--------------------------------------------------------------------------------
01/21/99 JSB Created
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGTank.h"
#if !defined ( sgi ) || defined( __GNUC__ )
using std::cerr;
using std::endl;
using std::cout;
#endif
namespace JSBSim {
static const char *IdSrc = "$Id: FGTank.cpp,v 1.29 2003/06/07 09:19:33 ehofman Exp $";
static const char *IdHdr = ID_TANK;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGTank::FGTank(FGConfigFile* AC_cfg)
: Contents(0.0)
{
string token;
type = AC_cfg->GetValue("TYPE");
if (type == "FUEL") Type = ttFUEL;
else if (type == "OXIDIZER") Type = ttOXIDIZER;
else Type = ttUNKNOWN;
AC_cfg->GetNextConfigLine();
while ((token = AC_cfg->GetValue()) != string("/AC_TANK")) {
if (token == "XLOC") *AC_cfg >> X;
else if (token == "YLOC") *AC_cfg >> Y;
else if (token == "ZLOC") *AC_cfg >> Z;
else if (token == "RADIUS") *AC_cfg >> Radius;
else if (token == "CAPACITY") *AC_cfg >> Capacity;
else if (token == "CONTENTS") {
if (Contents == 0.0) *AC_cfg >> Contents;
} else cerr << "Unknown identifier: " << token << " in tank definition." << endl;
}
Selected = true;
if (Capacity != 0) {
PctFull = 100.0*Contents/Capacity; // percent full; 0 to 100.0
} else {
Contents = 0;
PctFull = 0;
}
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGTank::~FGTank()
{
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGTank::Reduce(double used)
{
double shortage = Contents - used;
if (shortage >= 0) {
Contents -= used;
PctFull = 100.0*Contents/Capacity;
} else {
Contents = 0.0;
PctFull = 0.0;
Selected = false;
}
return shortage;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGTank::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
cout << " " << type << " tank holds " << Capacity << " lbs. " << type << endl;
cout << " currently at " << PctFull << "% of maximum capacity" << endl;
cout << " Tank location (X, Y, Z): " << X << ", " << Y << ", " << Z << endl;
cout << " Effective radius: " << Radius << " inches" << endl;
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGTank" << endl;
if (from == 1) cout << "Destroyed: FGTank" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
}
<|endoftext|> |
<commit_before>#include "errors.hpp"
#include <boost/bind.hpp>
#include <boost/program_options.hpp>
#include "arch/arch.hpp"
#include "arch/runtime/starter.hpp"
#include "arch/os_signal.hpp"
#include "clustering/administration/main/command_line.hpp"
#include "clustering/administration/main/serve.hpp"
#include "clustering/administration/metadata.hpp"
#include "clustering/administration/persist.hpp"
#include "mock/dummy_protocol.hpp"
namespace po = boost::program_options;
static const int default_peer_port = 20300;
class host_and_port_t {
public:
host_and_port_t(const std::string& h, int p) : host(h), port(p) { }
std::string host;
int port;
};
void run_rethinkdb_create(const std::string &filepath, bool *result_out) {
if (metadata_persistence::check_existence(filepath)) {
std::cout << "ERROR: The path '" << filepath << "' already exists. "
"Delete it and try again." << std::endl;
*result_out = false;
return;
}
machine_id_t our_machine_id = generate_uuid();
std::cout << "Our machine ID: " << our_machine_id << std::endl;
cluster_semilattice_metadata_t metadata;
metadata.machines.machines.insert(std::make_pair(
our_machine_id,
machine_semilattice_metadata_t()
));
metadata_persistence::create(filepath, our_machine_id, metadata);
std::cout << "Created directory '" << filepath << "' and a metadata file "
"inside it." << std::endl;
*result_out = true;
}
std::vector<peer_address_t> look_up_peers_addresses(std::vector<host_and_port_t> names) {
std::vector<peer_address_t> peers;
for (int i = 0; i < (int)names.size(); i++) {
peers.push_back(peer_address_t(ip_address_t(names[i].host), names[i].port));
}
return peers;
}
void run_rethinkdb_serve(const std::string &filepath, const std::vector<host_and_port_t> &joins, int port, int client_port, bool *result_out) {
os_signal_cond_t c;
if (!metadata_persistence::check_existence(filepath)) {
std::cout << "ERROR: The directory '" << filepath << "' does not "
"exist. Run 'rethinkdb create -d \"" << filepath << "\"' and try "
"again." << std::endl;
*result_out = false;
return;
}
machine_id_t persisted_machine_id;
cluster_semilattice_metadata_t persisted_semilattice_metadata;
try {
metadata_persistence::read(filepath, &persisted_machine_id, &persisted_semilattice_metadata);
} catch (metadata_persistence::file_exc_t e) {
std::cout << "ERROR: Could not read metadata file: " << e.what() << ". "
<< std::endl;
*result_out = false;
return;
}
*result_out = serve(filepath, look_up_peers_addresses(joins), port, client_port, persisted_machine_id, persisted_semilattice_metadata);
}
void run_rethinkdb_porcelain(const std::string &filepath, const std::vector<host_and_port_t> &joins, int port, int client_port, bool *result_out) {
os_signal_cond_t c;
std::cout << "Checking if directory '" << filepath << "' already "
"exists..." << std::endl;
if (metadata_persistence::check_existence(filepath)) {
std::cout << "It already exists. Loading data..." << std::endl;
machine_id_t persisted_machine_id;
cluster_semilattice_metadata_t persisted_semilattice_metadata;
metadata_persistence::read(filepath, &persisted_machine_id, &persisted_semilattice_metadata);
*result_out = serve(filepath, look_up_peers_addresses(joins), port, client_port, persisted_machine_id, persisted_semilattice_metadata);
} else {
std::cout << "It does not already exist. Creating it..." << std::endl;
machine_id_t our_machine_id = generate_uuid();
cluster_semilattice_metadata_t semilattice_metadata;
if (joins.empty()) {
std::cout << "Creating a default namespace and default data center "
"for your convenience. (This is because you ran 'rethinkdb' "
"without 'create', 'serve', or '--join', and the directory '" <<
filepath << "' did not already exist.)" << std::endl;
datacenter_id_t datacenter_id = generate_uuid();
datacenter_semilattice_metadata_t datacenter_metadata;
datacenter_metadata.name = vclock_t<std::string>("Welcome", our_machine_id);
semilattice_metadata.datacenters.datacenters.insert(std::make_pair(
datacenter_id,
deletable_t<datacenter_semilattice_metadata_t>(datacenter_metadata)
));
/* Add ourselves as a member of the "Welcome" datacenter. */
machine_semilattice_metadata_t our_machine_metadata;
our_machine_metadata.datacenter = vclock_t<datacenter_id_t>(datacenter_id, our_machine_id);
semilattice_metadata.machines.machines.insert(std::make_pair(
our_machine_id,
deletable_t<machine_semilattice_metadata_t>(our_machine_metadata)
));
namespace_id_t namespace_id = generate_uuid();
namespace_semilattice_metadata_t<memcached_protocol_t> namespace_metadata;
namespace_metadata.name = vclock_t<std::string>("Welcome", our_machine_id);
persistable_blueprint_t<memcached_protocol_t> blueprint;
std::map<key_range_t, blueprint_details::role_t> roles;
roles.insert(std::make_pair(key_range_t::entire_range(), blueprint_details::role_primary));
blueprint.machines_roles.insert(std::make_pair(our_machine_id, roles));
namespace_metadata.blueprint = vclock_t<persistable_blueprint_t<memcached_protocol_t> >(blueprint, our_machine_id);
namespace_metadata.primary_datacenter = vclock_t<datacenter_id_t>(datacenter_id, our_machine_id);
std::map<datacenter_id_t, int> affinities;
affinities.insert(std::make_pair(datacenter_id, 0));
namespace_metadata.replica_affinities = vclock_t<std::map<datacenter_id_t, int> >(affinities, our_machine_id);
std::set<key_range_t> shards;
shards.insert(key_range_t::entire_range());
namespace_metadata.shards = vclock_t<std::set<key_range_t> >(shards, our_machine_id);
semilattice_metadata.memcached_namespaces.namespaces.insert(std::make_pair(namespace_id, namespace_metadata));
} else {
semilattice_metadata.machines.machines.insert(std::make_pair(
our_machine_id,
machine_semilattice_metadata_t()
));
}
metadata_persistence::create(filepath, our_machine_id, semilattice_metadata);
*result_out = serve(filepath, look_up_peers_addresses(joins), port, client_port, our_machine_id, semilattice_metadata);
}
}
po::options_description get_file_option() {
po::options_description desc("File path options");
desc.add_options()
("directory,d", po::value<std::string>()->default_value("rethinkdb_cluster_data"), "specify directory to store data and metadata");
return desc;
}
/* This allows `host_and_port_t` to be used as a command-line argument with
`boost::program_options`. */
void validate(boost::any& value_out, const std::vector<std::string>& words,
host_and_port_t *, int)
{
po::validators::check_first_occurrence(value_out);
const std::string& word = po::validators::get_single_string(words);
size_t colon_loc = word.find_first_of(':');
if (colon_loc == std::string::npos) {
throw po::validation_error(po::validation_error::invalid_option_value, word);
} else {
std::string host = word.substr(0, colon_loc);
int port = atoi(word.substr(colon_loc + 1).c_str());
if (host.size() == 0 || port == 0) {
throw po::validation_error(po::validation_error::invalid_option_value, word);
}
value_out = host_and_port_t(host, port);
}
}
po::options_description get_network_options() {
po::options_description desc("Network options");
desc.add_options()
("port", po::value<int>()->default_value(default_peer_port), "port for communicating with other nodes")
#ifndef NDEBUG
("client-port", po::value<int>()->default_value(0), "port to use when connecting to other nodes")
#endif
("join,j", po::value<std::vector<host_and_port_t> >()->composing(), "host:port of a node that we will connect to");
return desc;
}
po::options_description get_rethinkdb_create_options() {
po::options_description desc("Allowed options");
desc.add(get_file_option());
return desc;
}
po::options_description get_rethinkdb_serve_options() {
po::options_description desc("Allowed options");
desc.add(get_file_option());
desc.add(get_network_options());
return desc;
}
po::options_description get_rethinkdb_porcelain_options() {
po::options_description desc("Allowed options");
desc.add(get_file_option());
desc.add(get_network_options());
return desc;
}
int main_rethinkdb_create(int argc, char *argv[]) {
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, get_rethinkdb_create_options()), vm);
po::notify(vm);
std::string filepath = vm["directory"].as<std::string>();
bool result;
run_in_thread_pool(boost::bind(&run_rethinkdb_create, filepath, &result));
return result ? 0 : 1;
}
int main_rethinkdb_serve(int argc, char *argv[]) {
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, get_rethinkdb_serve_options()), vm);
po::notify(vm);
std::string filepath = vm["directory"].as<std::string>();
std::vector<host_and_port_t> joins;
if (vm.count("join") > 0) {
joins = vm["join"].as<std::vector<host_and_port_t> >();
}
int port = vm["port"].as<int>();
#ifndef NDEBUG
int client_port = vm["client-port"].as<int>();
#else
int client_port = 0;
#endif
bool result;
run_in_thread_pool(boost::bind(&run_rethinkdb_serve, filepath, joins, port, client_port, &result));
return result ? 0 : 1;
}
int main_rethinkdb_porcelain(int argc, char *argv[]) {
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, get_rethinkdb_porcelain_options()), vm);
po::notify(vm);
std::string filepath = vm["directory"].as<std::string>();
std::vector<host_and_port_t> joins;
if (vm.count("join") > 0) {
joins = vm["join"].as<std::vector<host_and_port_t> >();
}
int port = vm["port"].as<int>();
#ifndef NDEBUG
int client_port = vm["client-port"].as<int>();
#else
int client_port = 0;
#endif
bool result;
run_in_thread_pool(boost::bind(&run_rethinkdb_porcelain, filepath, joins, port, client_port, &result));
return result ? 0 : 1;
}
void help_rethinkdb_create() {
std::cout << "'rethinkdb create' is used to prepare a directory to act "
"as the storage location for a RethinkDB cluster node." << std::endl;
std::cout << get_rethinkdb_create_options() << std::endl;
}
void help_rethinkdb_serve() {
std::cout << "'rethinkdb serve' is the actual process for a RethinkDB "
"cluster node." << std::endl;
std::cout << get_rethinkdb_serve_options() << std::endl;
}
<commit_msg>Removed use of cout from command_line.cc but malheureusement not streams completely.<commit_after>#include "errors.hpp"
#include <boost/bind.hpp>
#include <boost/program_options.hpp>
#include "arch/arch.hpp"
#include "arch/runtime/starter.hpp"
#include "arch/os_signal.hpp"
#include "clustering/administration/main/command_line.hpp"
#include "clustering/administration/main/serve.hpp"
#include "clustering/administration/metadata.hpp"
#include "clustering/administration/persist.hpp"
#include "mock/dummy_protocol.hpp"
namespace po = boost::program_options;
static const int default_peer_port = 20300;
class host_and_port_t {
public:
host_and_port_t(const std::string& h, int p) : host(h), port(p) { }
std::string host;
int port;
};
void run_rethinkdb_create(const std::string &filepath, bool *result_out) {
if (metadata_persistence::check_existence(filepath)) {
printf("ERROR: The path '%s' already exists. Delete it and try again.\n", filepath.c_str());
*result_out = false;
return;
}
machine_id_t our_machine_id = generate_uuid();
printf("Our machine ID: %s\n", uuid_to_str(our_machine_id).c_str());
cluster_semilattice_metadata_t metadata;
metadata.machines.machines.insert(std::make_pair(
our_machine_id,
machine_semilattice_metadata_t()
));
metadata_persistence::create(filepath, our_machine_id, metadata);
printf("Created directory '%s' and a metadata file inside it.\n", filepath.c_str());
*result_out = true;
}
std::vector<peer_address_t> look_up_peers_addresses(std::vector<host_and_port_t> names) {
std::vector<peer_address_t> peers;
for (int i = 0; i < (int)names.size(); i++) {
peers.push_back(peer_address_t(ip_address_t(names[i].host), names[i].port));
}
return peers;
}
void run_rethinkdb_serve(const std::string &filepath, const std::vector<host_and_port_t> &joins, int port, int client_port, bool *result_out) {
os_signal_cond_t c;
if (!metadata_persistence::check_existence(filepath)) {
printf("ERROR: The directory '%s' does not exist. Run 'rethinkdb create -d \"%s\"' and try again.\n", filepath.c_str(), filepath.c_str());
*result_out = false;
return;
}
machine_id_t persisted_machine_id;
cluster_semilattice_metadata_t persisted_semilattice_metadata;
try {
metadata_persistence::read(filepath, &persisted_machine_id, &persisted_semilattice_metadata);
} catch (metadata_persistence::file_exc_t e) {
printf("ERROR: Could not read metadata file: %s\n", e.what());
*result_out = false;
return;
}
*result_out = serve(filepath, look_up_peers_addresses(joins), port, client_port, persisted_machine_id, persisted_semilattice_metadata);
}
void run_rethinkdb_porcelain(const std::string &filepath, const std::vector<host_and_port_t> &joins, int port, int client_port, bool *result_out) {
os_signal_cond_t c;
printf("Checking if directory '%s' already exists...\n", filepath.c_str());
if (metadata_persistence::check_existence(filepath)) {
printf("It already exists. Loading data...\n");
machine_id_t persisted_machine_id;
cluster_semilattice_metadata_t persisted_semilattice_metadata;
metadata_persistence::read(filepath, &persisted_machine_id, &persisted_semilattice_metadata);
*result_out = serve(filepath, look_up_peers_addresses(joins), port, client_port, persisted_machine_id, persisted_semilattice_metadata);
} else {
printf("It does not already exist. Creating it...\n");
machine_id_t our_machine_id = generate_uuid();
cluster_semilattice_metadata_t semilattice_metadata;
if (joins.empty()) {
printf("Creating a default namespace and default data center "
"for your convenience. (This is because you ran 'rethinkdb' "
"without 'create', 'serve', or '--join', and the directory '%s' did not already exist.)\n",
filepath.c_str());
datacenter_id_t datacenter_id = generate_uuid();
datacenter_semilattice_metadata_t datacenter_metadata;
datacenter_metadata.name = vclock_t<std::string>("Welcome", our_machine_id);
semilattice_metadata.datacenters.datacenters.insert(std::make_pair(
datacenter_id,
deletable_t<datacenter_semilattice_metadata_t>(datacenter_metadata)
));
/* Add ourselves as a member of the "Welcome" datacenter. */
machine_semilattice_metadata_t our_machine_metadata;
our_machine_metadata.datacenter = vclock_t<datacenter_id_t>(datacenter_id, our_machine_id);
semilattice_metadata.machines.machines.insert(std::make_pair(
our_machine_id,
deletable_t<machine_semilattice_metadata_t>(our_machine_metadata)
));
namespace_id_t namespace_id = generate_uuid();
namespace_semilattice_metadata_t<memcached_protocol_t> namespace_metadata;
namespace_metadata.name = vclock_t<std::string>("Welcome", our_machine_id);
persistable_blueprint_t<memcached_protocol_t> blueprint;
std::map<key_range_t, blueprint_details::role_t> roles;
roles.insert(std::make_pair(key_range_t::entire_range(), blueprint_details::role_primary));
blueprint.machines_roles.insert(std::make_pair(our_machine_id, roles));
namespace_metadata.blueprint = vclock_t<persistable_blueprint_t<memcached_protocol_t> >(blueprint, our_machine_id);
namespace_metadata.primary_datacenter = vclock_t<datacenter_id_t>(datacenter_id, our_machine_id);
std::map<datacenter_id_t, int> affinities;
affinities.insert(std::make_pair(datacenter_id, 0));
namespace_metadata.replica_affinities = vclock_t<std::map<datacenter_id_t, int> >(affinities, our_machine_id);
std::set<key_range_t> shards;
shards.insert(key_range_t::entire_range());
namespace_metadata.shards = vclock_t<std::set<key_range_t> >(shards, our_machine_id);
semilattice_metadata.memcached_namespaces.namespaces.insert(std::make_pair(namespace_id, namespace_metadata));
} else {
semilattice_metadata.machines.machines.insert(std::make_pair(
our_machine_id,
machine_semilattice_metadata_t()
));
}
metadata_persistence::create(filepath, our_machine_id, semilattice_metadata);
*result_out = serve(filepath, look_up_peers_addresses(joins), port, client_port, our_machine_id, semilattice_metadata);
}
}
po::options_description get_file_option() {
po::options_description desc("File path options");
desc.add_options()
("directory,d", po::value<std::string>()->default_value("rethinkdb_cluster_data"), "specify directory to store data and metadata");
return desc;
}
/* This allows `host_and_port_t` to be used as a command-line argument with
`boost::program_options`. */
void validate(boost::any& value_out, const std::vector<std::string>& words,
host_and_port_t *, int)
{
po::validators::check_first_occurrence(value_out);
const std::string& word = po::validators::get_single_string(words);
size_t colon_loc = word.find_first_of(':');
if (colon_loc == std::string::npos) {
throw po::validation_error(po::validation_error::invalid_option_value, word);
} else {
std::string host = word.substr(0, colon_loc);
int port = atoi(word.substr(colon_loc + 1).c_str());
if (host.size() == 0 || port == 0) {
throw po::validation_error(po::validation_error::invalid_option_value, word);
}
value_out = host_and_port_t(host, port);
}
}
po::options_description get_network_options() {
po::options_description desc("Network options");
desc.add_options()
("port", po::value<int>()->default_value(default_peer_port), "port for communicating with other nodes")
#ifndef NDEBUG
("client-port", po::value<int>()->default_value(0), "port to use when connecting to other nodes")
#endif
("join,j", po::value<std::vector<host_and_port_t> >()->composing(), "host:port of a node that we will connect to");
return desc;
}
po::options_description get_rethinkdb_create_options() {
po::options_description desc("Allowed options");
desc.add(get_file_option());
return desc;
}
po::options_description get_rethinkdb_serve_options() {
po::options_description desc("Allowed options");
desc.add(get_file_option());
desc.add(get_network_options());
return desc;
}
po::options_description get_rethinkdb_porcelain_options() {
po::options_description desc("Allowed options");
desc.add(get_file_option());
desc.add(get_network_options());
return desc;
}
int main_rethinkdb_create(int argc, char *argv[]) {
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, get_rethinkdb_create_options()), vm);
po::notify(vm);
std::string filepath = vm["directory"].as<std::string>();
bool result;
run_in_thread_pool(boost::bind(&run_rethinkdb_create, filepath, &result));
return result ? 0 : 1;
}
int main_rethinkdb_serve(int argc, char *argv[]) {
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, get_rethinkdb_serve_options()), vm);
po::notify(vm);
std::string filepath = vm["directory"].as<std::string>();
std::vector<host_and_port_t> joins;
if (vm.count("join") > 0) {
joins = vm["join"].as<std::vector<host_and_port_t> >();
}
int port = vm["port"].as<int>();
#ifndef NDEBUG
int client_port = vm["client-port"].as<int>();
#else
int client_port = 0;
#endif
bool result;
run_in_thread_pool(boost::bind(&run_rethinkdb_serve, filepath, joins, port, client_port, &result));
return result ? 0 : 1;
}
int main_rethinkdb_porcelain(int argc, char *argv[]) {
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, get_rethinkdb_porcelain_options()), vm);
po::notify(vm);
std::string filepath = vm["directory"].as<std::string>();
std::vector<host_and_port_t> joins;
if (vm.count("join") > 0) {
joins = vm["join"].as<std::vector<host_and_port_t> >();
}
int port = vm["port"].as<int>();
#ifndef NDEBUG
int client_port = vm["client-port"].as<int>();
#else
int client_port = 0;
#endif
bool result;
run_in_thread_pool(boost::bind(&run_rethinkdb_porcelain, filepath, joins, port, client_port, &result));
return result ? 0 : 1;
}
void help_rethinkdb_create() {
printf("'rethinkdb create' is used to prepare a directory to act "
"as the storage location for a RethinkDB cluster node.\n");
std::stringstream sstream;
sstream << get_rethinkdb_create_options();
printf("%s\n", sstream.str().c_str());
}
void help_rethinkdb_serve() {
printf("'rethinkdb serve' is the actual process for a RethinkDB cluster node.\n");
std::stringstream sstream;
sstream << get_rethinkdb_serve_options();
printf("%s\n", sstream.str().c_str());
}
<|endoftext|> |
<commit_before>/*
* SimmelianOverlapAttributizer.cpp
*
* Created on: 22.07.2014
* Author: Gerd Lindner
*/
#include "SimmelianOverlapAttributizer.h"
#include <limits>
namespace NetworKit {
SimmelianOverlapAttributizer::SimmelianOverlapAttributizer(count maxRank) :
maxRank(maxRank) {}
EdgeAttribute SimmelianOverlapAttributizer::getAttribute(const Graph& graph, const EdgeAttribute& attribute) {
std::vector<RankedNeighbors> neighbors = getRankedNeighborhood(graph, attribute);
EdgeAttribute overlapAttribute(graph.upperEdgeIdBound(), 1.0);
graph.forEdges([&](node u, node v, edgeid eid) {
Redundancy redundancy = getOverlap(u, v, neighbors, maxRank);
overlapAttribute[eid] = std::min((double) redundancy.overlap, overlapAttribute[eid]);
});
return overlapAttribute;
}
} /* namespace NetworKit */
<commit_msg>Fixed Simmelian Backbone Overlap. Min/max confusion...<commit_after>/*
* SimmelianOverlapAttributizer.cpp
*
* Created on: 22.07.2014
* Author: Gerd Lindner
*/
#include "SimmelianOverlapAttributizer.h"
#include <limits>
namespace NetworKit {
SimmelianOverlapAttributizer::SimmelianOverlapAttributizer(count maxRank) :
maxRank(maxRank) {}
EdgeAttribute SimmelianOverlapAttributizer::getAttribute(const Graph& graph, const EdgeAttribute& attribute) {
std::vector<RankedNeighbors> neighbors = getRankedNeighborhood(graph, attribute);
EdgeAttribute overlapAttribute(graph.upperEdgeIdBound(), 0.0);
graph.forEdges([&](node u, node v, edgeid eid) {
Redundancy redundancy = getOverlap(u, v, neighbors, maxRank);
overlapAttribute[eid] = std::max((double) redundancy.overlap, overlapAttribute[eid]);
});
return overlapAttribute;
}
} /* namespace NetworKit */
<|endoftext|> |
<commit_before>#include "oclint/rule/UnusedMethodParameterRule.h"
#include "oclint/RuleSet.h"
#include "oclint/ViolationSet.h"
#include "oclint/Violation.h"
#include "oclint/helper/CursorHelper.h"
#include "oclint/helper/DeclHelper.h"
#include <clang/AST/Decl.h>
#include <clang/AST/DeclCXX.h>
#include <clang/AST/DeclObjC.h>
using namespace clang;
RuleSet UnusedMethodParameterRule::rules(new UnusedMethodParameterRule());
bool UnusedMethodParameterRule::isFunctionDeclaration(DeclContext *context) {
FunctionDecl *decl = dyn_cast<FunctionDecl>(context);
return decl && !decl->doesThisDeclarationHaveABody();
}
bool UnusedMethodParameterRule::isBlockDeclaration(DeclContext *context) {
return dyn_cast<BlockDecl>(context);
}
bool UnusedMethodParameterRule::isObjCMethodDeclaration(DeclContext *context) {
ObjCMethodDecl *decl = dyn_cast<ObjCMethodDecl>(context);
return DeclHelper::isObjCMethodDeclLocatedInInterfaceContainer(decl);
}
bool UnusedMethodParameterRule::isObjCOverrideMethod(DeclContext *context) {
ObjCMethodDecl *decl = dyn_cast<ObjCMethodDecl>(context);
return DeclHelper::isObjCMethodDeclaredInSuperClass(decl) || DeclHelper::isObjCMethodDeclaredInProtocol(decl);
}
bool UnusedMethodParameterRule::isCppFunctionDeclaration(DeclContext *context) {
FunctionDecl *decl = dyn_cast<FunctionDecl>(context);
return isa<CXXRecordDecl>(context) || (decl && !decl->hasBody());
}
bool UnusedMethodParameterRule::isCppOverrideFunction(DeclContext *context) {
CXXMethodDecl *decl = dyn_cast<CXXMethodDecl>(context);
if (decl) {
return decl->isVirtual();
}
return false;
}
bool UnusedMethodParameterRule::isExistingByContract(DeclContext *context) {
return isFunctionDeclaration(context) ||
isBlockDeclaration(context) ||
isObjCMethodDeclaration(context) ||
isObjCOverrideMethod(context) ||
isCppFunctionDeclaration(context) ||
isCppOverrideFunction(context);
}
bool UnusedMethodParameterRule::isExistingByContract(ParmVarDecl *decl) {
DeclContext *lexicalContext = decl->getLexicalDeclContext();
while (lexicalContext) {
if (isExistingByContract(lexicalContext)) {
return true;
}
lexicalContext = lexicalContext->getLexicalParent();
}
return false;
}
void UnusedMethodParameterRule::apply(CXCursor& node, CXCursor& parentNode, ViolationSet& violationSet) {
Decl *decl = CursorHelper::getDecl(node);
if (decl) {
ParmVarDecl *varDecl = dyn_cast<ParmVarDecl>(decl);
if (varDecl && !varDecl->isUsed() && !isExistingByContract(varDecl)) {
Violation violation(node, this);
violationSet.addViolation(violation);
}
}
}
const string UnusedMethodParameterRule::name() const {
return "unused method parameter";
}
<commit_msg>clean UnusedMethodParameterRule a little<commit_after>#include "oclint/rule/UnusedMethodParameterRule.h"
#include "oclint/RuleSet.h"
#include "oclint/ViolationSet.h"
#include "oclint/Violation.h"
#include "oclint/helper/CursorHelper.h"
#include "oclint/helper/DeclHelper.h"
#include <clang/AST/Decl.h>
#include <clang/AST/DeclCXX.h>
#include <clang/AST/DeclObjC.h>
using namespace clang;
RuleSet UnusedMethodParameterRule::rules(new UnusedMethodParameterRule());
bool UnusedMethodParameterRule::isFunctionDeclaration(DeclContext *context) {
FunctionDecl *decl = dyn_cast<FunctionDecl>(context);
return decl && !decl->doesThisDeclarationHaveABody();
}
bool UnusedMethodParameterRule::isBlockDeclaration(DeclContext *context) {
return dyn_cast<BlockDecl>(context);
}
bool UnusedMethodParameterRule::isObjCMethodDeclaration(DeclContext *context) {
ObjCMethodDecl *decl = dyn_cast<ObjCMethodDecl>(context);
return DeclHelper::isObjCMethodDeclLocatedInInterfaceContainer(decl);
}
bool UnusedMethodParameterRule::isObjCOverrideMethod(DeclContext *context) {
ObjCMethodDecl *decl = dyn_cast<ObjCMethodDecl>(context);
return DeclHelper::isObjCMethodDeclaredInSuperClass(decl) || DeclHelper::isObjCMethodDeclaredInProtocol(decl);
}
bool UnusedMethodParameterRule::isCppFunctionDeclaration(DeclContext *context) {
FunctionDecl *decl = dyn_cast<FunctionDecl>(context);
return isa<CXXRecordDecl>(context) || (decl && !decl->hasBody());
}
bool UnusedMethodParameterRule::isCppOverrideFunction(DeclContext *context) {
CXXMethodDecl *decl = dyn_cast<CXXMethodDecl>(context);
return decl && decl->isVirtual();
}
bool UnusedMethodParameterRule::isExistingByContract(DeclContext *context) {
return isFunctionDeclaration(context) ||
isBlockDeclaration(context) ||
isObjCMethodDeclaration(context) ||
isObjCOverrideMethod(context) ||
isCppFunctionDeclaration(context) ||
isCppOverrideFunction(context);
}
bool UnusedMethodParameterRule::isExistingByContract(ParmVarDecl *decl) {
DeclContext *lexicalContext = decl->getLexicalDeclContext();
while (lexicalContext) {
if (isExistingByContract(lexicalContext)) {
return true;
}
lexicalContext = lexicalContext->getLexicalParent();
}
return false;
}
void UnusedMethodParameterRule::apply(CXCursor& node, CXCursor& parentNode, ViolationSet& violationSet) {
Decl *decl = CursorHelper::getDecl(node);
if (decl) {
ParmVarDecl *varDecl = dyn_cast<ParmVarDecl>(decl);
if (varDecl && !varDecl->isUsed() && !isExistingByContract(varDecl)) {
Violation violation(node, this);
violationSet.addViolation(violation);
}
}
}
const string UnusedMethodParameterRule::name() const {
return "unused method parameter";
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativecamera_p.h"
#include "qdeclarativecamerafocus_p.h"
QT_BEGIN_NAMESPACE
/*!
\qmltype CameraFocus
\instantiates QDeclarativeCameraFocus
\inqmlmodule QtMultimedia 5.0
\brief An interface for focus related camera settings.
\ingroup multimedia_qml
\ingroup camera_qml
CameraFocus is part of the \b{QtMultimedia 5.0} module.
This type allows control over manual and automatic
focus settings, including information about any parts of the
camera frame that are selected for autofocusing.
It should not be constructed separately, instead the
\c focus property of a \l Camera should be used.
\qml
import QtQuick 2.0
import QtMultimedia 5.0
Item {
width: 640
height: 360
Camera {
id: camera
focus {
focusMode: Camera.FocusMacro
focusPointMode: Camera.FocusPointCustom
customFocusPoint: Qt.point(0.2, 0.2) // Focus relative to top-left corner
}
}
VideoOutput {
source: camera
anchors.fill: parent
}
}
\endqml
*/
/*!
\class QDeclarativeCameraFocus
\internal
\brief An interface for focus related camera settings.
*/
/*!
Construct a declarative camera focus object using \a parent object.
*/
QDeclarativeCameraFocus::QDeclarativeCameraFocus(QCamera *camera, QObject *parent) :
QObject(parent)
{
m_focus = camera->focus();
m_focusZones = new FocusZonesModel(this);
updateFocusZones();
connect(m_focus, SIGNAL(focusZonesChanged()), SLOT(updateFocusZones()));
}
QDeclarativeCameraFocus::~QDeclarativeCameraFocus()
{
}
/*!
\property QDeclarativeCameraFocus::focusMode
This property holds the current camera focus mode.
It's possible to combine multiple QCameraFocus::FocusMode enum values,
for example QCameraFocus::MacroFocus + QCameraFocus::ContinuousFocus.
In automatic focusing modes, the \l focusPointMode
and \l focusZones properties provide information and control
over how automatic focusing is performed.
*/
/*!
\qmlproperty enumeration CameraFocus::focusMode
This property holds the current camera focus mode, which can be one of the following values:
\table
\header
\li Value
\li Description
\row
\li FocusManual
\li Manual or fixed focus mode.
\row
\li FocusHyperfocal
\li Focus to hyperfocal distance, with the maximum depth of field achieved. All objects at distances from half of this distance out to infinity will be acceptably sharp.
\row
\li FocusInfinity
\li Focus strictly to infinity.
\row
\li FocusAuto
\li One-shot auto focus mode.
\row
\li FocusContinuous
\li Continuous auto focus mode.
\row
\li FocusMacro
\li One shot auto focus to objects close to camera.
\endtable
It's possible to combine multiple Camera::FocusMode values,
for example Camera.FocusMacro + Camera.FocusContinuous.
In automatic focusing modes, the \l focusPointMode property
and \l focusZones property provide information and control
over how automatic focusing is performed.
*/
QDeclarativeCamera::FocusMode QDeclarativeCameraFocus::focusMode() const
{
return QDeclarativeCamera::FocusMode(int(m_focus->focusMode()));
}
/*!
\qmlmethod bool QtMultimedia5::CameraFocus::isFocusModeSupported(mode) const
Returns true if the supplied \a mode is a supported focus mode, and
false otherwise.
*/
bool QDeclarativeCameraFocus::isFocusModeSupported(QDeclarativeCamera::FocusMode mode) const
{
return m_focus->isFocusModeSupported(QCameraFocus::FocusModes(int(mode)));
}
void QDeclarativeCameraFocus::setFocusMode(QDeclarativeCamera::FocusMode mode)
{
m_focus->setFocusMode(QCameraFocus::FocusModes(int(mode)));
}
/*!
\property QDeclarativeCameraFocus::focusPointMode
This property holds the current camera focus point mode. It is used in
automatic focusing modes to determine what to focus on.
If the current focus point mode is \l QCameraFocus::FocusPointCustom, the
\l customFocusPoint property allows you to specify which part of
the frame to focus on.
*/
/*!
\qmlproperty enumeration CameraFocus::focusPointMode
This property holds the current camera focus point mode. It is used in automatic
focusing modes to determine what to focus on. If the current
focus point mode is \c Camera.FocusPointCustom, the \l customFocusPoint
property allows you to specify which part of the frame to focus on.
The property can take one of the following values:
\table
\header
\li Value
\li Description
\row
\li FocusPointAuto
\li Automatically select one or multiple focus points.
\row
\li FocusPointCenter
\li Focus to the frame center.
\row
\li FocusPointFaceDetection
\li Focus on faces in the frame.
\row
\li FocusPointCustom
\li Focus to the custom point, defined by the customFocusPoint property.
\endtable
*/
QDeclarativeCamera::FocusPointMode QDeclarativeCameraFocus::focusPointMode() const
{
return QDeclarativeCamera::FocusPointMode(m_focus->focusPointMode());
}
void QDeclarativeCameraFocus::setFocusPointMode(QDeclarativeCamera::FocusPointMode mode)
{
if (mode != focusPointMode()) {
m_focus->setFocusPointMode(QCameraFocus::FocusPointMode(mode));
emit focusPointModeChanged(focusPointMode());
}
}
/*!
\qmlmethod bool QtMultimedia5::CameraFocus::isFocusPointModeSupported(mode) const
Returns true if the supplied \a mode is a supported focus point mode, and
false otherwise.
*/
bool QDeclarativeCameraFocus::isFocusPointModeSupported(QDeclarativeCamera::FocusPointMode mode) const
{
return m_focus->isFocusPointModeSupported(QCameraFocus::FocusPointMode(mode));
}
/*!
\property QDeclarativeCameraFocus::customFocusPoint
This property holds the position of the custom focus point in relative
frame coordinates. For example, QPointF(0,0) pointing to the left top corner of the frame, and QPointF(0.5,0.5)
pointing to the center of the frame.
Custom focus point is used only in QCameraFocus::FocusPointCustom focus mode.
*/
/*!
\qmlproperty point QtMultimedia5::CameraFocus::customFocusPoint
This property holds the position of custom focus point, in relative frame coordinates:
QPointF(0,0) points to the left top frame point, QPointF(0.5,0.5)
points to the frame center.
Custom focus point is used only in FocusPointCustom focus mode.
*/
QPointF QDeclarativeCameraFocus::customFocusPoint() const
{
return m_focus->customFocusPoint();
}
void QDeclarativeCameraFocus::setCustomFocusPoint(const QPointF &point)
{
if (point != customFocusPoint()) {
m_focus->setCustomFocusPoint(point);
emit customFocusPointChanged(customFocusPoint());
}
}
/*!
\property QDeclarativeCameraFocus::focusZones
This property holds the list of current camera focus zones,
each including \c area specified in the same coordinates as \l customFocusPoint, and zone \c status as one of the following values:
\table
\header \li Value \li Description
\row \li QCameraFocusZone::Unused \li This focus point area is currently unused in autofocusing.
\row \li QCameraFocusZone::Selected \li This focus point area is used in autofocusing, but is not in focus.
\row \li QCameraFocusZone::Focused \li This focus point is used in autofocusing, and is in focus.
\endtable
*/
/*!
\qmlproperty list<focusZone> QtMultimedia5::CameraFocus::focusZones
This property holds the list of current camera focus zones,
each including \c area specified in the same coordinates as \l customFocusPoint,
and zone \c status as one of the following values:
\table
\header \li Value \li Description
\row \li Camera.FocusAreaUnused \li This focus point area is currently unused in autofocusing.
\row \li Camera.FocusAreaSelected \li This focus point area is used in autofocusing, but is not in focus.
\row \li Camera.FocusAreaFocused \li This focus point is used in autofocusing, and is in focus.
\endtable
\qml
VideoOutput {
id: viewfinder
source: camera
//display focus areas on camera viewfinder:
Repeater {
model: camera.focus.focusZones
Rectangle {
border {
width: 2
color: status == Camera.FocusAreaFocused ? "green" : "white"
}
color: "transparent"
// Map from the relative, normalized frame coordinates
property variant mappedRect: viewfinder.mapNormalizedRectToItem(area);
x: mappedRect.x
y: mappedRect.y
width: mappedRect.width
height: mappedRect.height
}
}
}
\endqml
*/
QAbstractListModel *QDeclarativeCameraFocus::focusZones() const
{
return m_focusZones;
}
/*! \internal */
void QDeclarativeCameraFocus::updateFocusZones()
{
m_focusZones->setFocusZones(m_focus->focusZones());
}
FocusZonesModel::FocusZonesModel(QObject *parent)
:QAbstractListModel(parent)
{
QHash<int, QByteArray> roles;
roles[StatusRole] = "status";
roles[AreaRole] = "area";
setRoleNames(roles);
}
int FocusZonesModel::rowCount(const QModelIndex &parent) const
{
if (parent == QModelIndex())
return m_focusZones.count();
return 0;
}
QVariant FocusZonesModel::data(const QModelIndex &index, int role) const
{
if (index.row() < 0 || index.row() > m_focusZones.count())
return QVariant();
QCameraFocusZone zone = m_focusZones.value(index.row());
if (role == StatusRole)
return zone.status();
if (role == AreaRole)
return zone.area();
return QVariant();
}
void FocusZonesModel::setFocusZones(const QCameraFocusZoneList &zones)
{
beginResetModel();
m_focusZones = zones;
endResetModel();
}
QT_END_NAMESPACE
#include "moc_qdeclarativecamerafocus_p.cpp"
<commit_msg>Fixed signal not being emitted in QDeclarativeCameraFocus.<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativecamera_p.h"
#include "qdeclarativecamerafocus_p.h"
QT_BEGIN_NAMESPACE
/*!
\qmltype CameraFocus
\instantiates QDeclarativeCameraFocus
\inqmlmodule QtMultimedia 5.0
\brief An interface for focus related camera settings.
\ingroup multimedia_qml
\ingroup camera_qml
CameraFocus is part of the \b{QtMultimedia 5.0} module.
This type allows control over manual and automatic
focus settings, including information about any parts of the
camera frame that are selected for autofocusing.
It should not be constructed separately, instead the
\c focus property of a \l Camera should be used.
\qml
import QtQuick 2.0
import QtMultimedia 5.0
Item {
width: 640
height: 360
Camera {
id: camera
focus {
focusMode: Camera.FocusMacro
focusPointMode: Camera.FocusPointCustom
customFocusPoint: Qt.point(0.2, 0.2) // Focus relative to top-left corner
}
}
VideoOutput {
source: camera
anchors.fill: parent
}
}
\endqml
*/
/*!
\class QDeclarativeCameraFocus
\internal
\brief An interface for focus related camera settings.
*/
/*!
Construct a declarative camera focus object using \a parent object.
*/
QDeclarativeCameraFocus::QDeclarativeCameraFocus(QCamera *camera, QObject *parent) :
QObject(parent)
{
m_focus = camera->focus();
m_focusZones = new FocusZonesModel(this);
updateFocusZones();
connect(m_focus, SIGNAL(focusZonesChanged()), SLOT(updateFocusZones()));
}
QDeclarativeCameraFocus::~QDeclarativeCameraFocus()
{
}
/*!
\property QDeclarativeCameraFocus::focusMode
This property holds the current camera focus mode.
It's possible to combine multiple QCameraFocus::FocusMode enum values,
for example QCameraFocus::MacroFocus + QCameraFocus::ContinuousFocus.
In automatic focusing modes, the \l focusPointMode
and \l focusZones properties provide information and control
over how automatic focusing is performed.
*/
/*!
\qmlproperty enumeration CameraFocus::focusMode
This property holds the current camera focus mode, which can be one of the following values:
\table
\header
\li Value
\li Description
\row
\li FocusManual
\li Manual or fixed focus mode.
\row
\li FocusHyperfocal
\li Focus to hyperfocal distance, with the maximum depth of field achieved. All objects at distances from half of this distance out to infinity will be acceptably sharp.
\row
\li FocusInfinity
\li Focus strictly to infinity.
\row
\li FocusAuto
\li One-shot auto focus mode.
\row
\li FocusContinuous
\li Continuous auto focus mode.
\row
\li FocusMacro
\li One shot auto focus to objects close to camera.
\endtable
It's possible to combine multiple Camera::FocusMode values,
for example Camera.FocusMacro + Camera.FocusContinuous.
In automatic focusing modes, the \l focusPointMode property
and \l focusZones property provide information and control
over how automatic focusing is performed.
*/
QDeclarativeCamera::FocusMode QDeclarativeCameraFocus::focusMode() const
{
return QDeclarativeCamera::FocusMode(int(m_focus->focusMode()));
}
/*!
\qmlmethod bool QtMultimedia5::CameraFocus::isFocusModeSupported(mode) const
Returns true if the supplied \a mode is a supported focus mode, and
false otherwise.
*/
bool QDeclarativeCameraFocus::isFocusModeSupported(QDeclarativeCamera::FocusMode mode) const
{
return m_focus->isFocusModeSupported(QCameraFocus::FocusModes(int(mode)));
}
void QDeclarativeCameraFocus::setFocusMode(QDeclarativeCamera::FocusMode mode)
{
if (mode != focusMode()) {
m_focus->setFocusMode(QCameraFocus::FocusModes(int(mode)));
emit focusModeChanged(focusMode());
}
}
/*!
\property QDeclarativeCameraFocus::focusPointMode
This property holds the current camera focus point mode. It is used in
automatic focusing modes to determine what to focus on.
If the current focus point mode is \l QCameraFocus::FocusPointCustom, the
\l customFocusPoint property allows you to specify which part of
the frame to focus on.
*/
/*!
\qmlproperty enumeration CameraFocus::focusPointMode
This property holds the current camera focus point mode. It is used in automatic
focusing modes to determine what to focus on. If the current
focus point mode is \c Camera.FocusPointCustom, the \l customFocusPoint
property allows you to specify which part of the frame to focus on.
The property can take one of the following values:
\table
\header
\li Value
\li Description
\row
\li FocusPointAuto
\li Automatically select one or multiple focus points.
\row
\li FocusPointCenter
\li Focus to the frame center.
\row
\li FocusPointFaceDetection
\li Focus on faces in the frame.
\row
\li FocusPointCustom
\li Focus to the custom point, defined by the customFocusPoint property.
\endtable
*/
QDeclarativeCamera::FocusPointMode QDeclarativeCameraFocus::focusPointMode() const
{
return QDeclarativeCamera::FocusPointMode(m_focus->focusPointMode());
}
void QDeclarativeCameraFocus::setFocusPointMode(QDeclarativeCamera::FocusPointMode mode)
{
if (mode != focusPointMode()) {
m_focus->setFocusPointMode(QCameraFocus::FocusPointMode(mode));
emit focusPointModeChanged(focusPointMode());
}
}
/*!
\qmlmethod bool QtMultimedia5::CameraFocus::isFocusPointModeSupported(mode) const
Returns true if the supplied \a mode is a supported focus point mode, and
false otherwise.
*/
bool QDeclarativeCameraFocus::isFocusPointModeSupported(QDeclarativeCamera::FocusPointMode mode) const
{
return m_focus->isFocusPointModeSupported(QCameraFocus::FocusPointMode(mode));
}
/*!
\property QDeclarativeCameraFocus::customFocusPoint
This property holds the position of the custom focus point in relative
frame coordinates. For example, QPointF(0,0) pointing to the left top corner of the frame, and QPointF(0.5,0.5)
pointing to the center of the frame.
Custom focus point is used only in QCameraFocus::FocusPointCustom focus mode.
*/
/*!
\qmlproperty point QtMultimedia5::CameraFocus::customFocusPoint
This property holds the position of custom focus point, in relative frame coordinates:
QPointF(0,0) points to the left top frame point, QPointF(0.5,0.5)
points to the frame center.
Custom focus point is used only in FocusPointCustom focus mode.
*/
QPointF QDeclarativeCameraFocus::customFocusPoint() const
{
return m_focus->customFocusPoint();
}
void QDeclarativeCameraFocus::setCustomFocusPoint(const QPointF &point)
{
if (point != customFocusPoint()) {
m_focus->setCustomFocusPoint(point);
emit customFocusPointChanged(customFocusPoint());
}
}
/*!
\property QDeclarativeCameraFocus::focusZones
This property holds the list of current camera focus zones,
each including \c area specified in the same coordinates as \l customFocusPoint, and zone \c status as one of the following values:
\table
\header \li Value \li Description
\row \li QCameraFocusZone::Unused \li This focus point area is currently unused in autofocusing.
\row \li QCameraFocusZone::Selected \li This focus point area is used in autofocusing, but is not in focus.
\row \li QCameraFocusZone::Focused \li This focus point is used in autofocusing, and is in focus.
\endtable
*/
/*!
\qmlproperty list<focusZone> QtMultimedia5::CameraFocus::focusZones
This property holds the list of current camera focus zones,
each including \c area specified in the same coordinates as \l customFocusPoint,
and zone \c status as one of the following values:
\table
\header \li Value \li Description
\row \li Camera.FocusAreaUnused \li This focus point area is currently unused in autofocusing.
\row \li Camera.FocusAreaSelected \li This focus point area is used in autofocusing, but is not in focus.
\row \li Camera.FocusAreaFocused \li This focus point is used in autofocusing, and is in focus.
\endtable
\qml
VideoOutput {
id: viewfinder
source: camera
//display focus areas on camera viewfinder:
Repeater {
model: camera.focus.focusZones
Rectangle {
border {
width: 2
color: status == Camera.FocusAreaFocused ? "green" : "white"
}
color: "transparent"
// Map from the relative, normalized frame coordinates
property variant mappedRect: viewfinder.mapNormalizedRectToItem(area);
x: mappedRect.x
y: mappedRect.y
width: mappedRect.width
height: mappedRect.height
}
}
}
\endqml
*/
QAbstractListModel *QDeclarativeCameraFocus::focusZones() const
{
return m_focusZones;
}
/*! \internal */
void QDeclarativeCameraFocus::updateFocusZones()
{
m_focusZones->setFocusZones(m_focus->focusZones());
}
FocusZonesModel::FocusZonesModel(QObject *parent)
:QAbstractListModel(parent)
{
QHash<int, QByteArray> roles;
roles[StatusRole] = "status";
roles[AreaRole] = "area";
setRoleNames(roles);
}
int FocusZonesModel::rowCount(const QModelIndex &parent) const
{
if (parent == QModelIndex())
return m_focusZones.count();
return 0;
}
QVariant FocusZonesModel::data(const QModelIndex &index, int role) const
{
if (index.row() < 0 || index.row() > m_focusZones.count())
return QVariant();
QCameraFocusZone zone = m_focusZones.value(index.row());
if (role == StatusRole)
return zone.status();
if (role == AreaRole)
return zone.area();
return QVariant();
}
void FocusZonesModel::setFocusZones(const QCameraFocusZoneList &zones)
{
beginResetModel();
m_focusZones = zones;
endResetModel();
}
QT_END_NAMESPACE
#include "moc_qdeclarativecamerafocus_p.cpp"
<|endoftext|> |
<commit_before>/*
Copyright (C) 2008 Patrick Spendrin <ps_ml@gmx.de>
This file is part of the KDE project
This library is free software you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
aint with this library see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "KMLHrefTagHandler.h"
#include <QtCore/QDebug>
#include <QtCore/QUrl>
#include "KMLElementDictionary.h"
#include "GeoDataIconStyle.h"
#include "GeoDataParser.h"
using namespace GeoDataElementDictionary;
KML_DEFINE_TAG_HANDLER( href )
KMLhrefTagHandler::KMLhrefTagHandler()
: GeoTagHandler()
{
}
KMLhrefTagHandler::~KMLhrefTagHandler()
{
}
GeoNode* KMLhrefTagHandler::parse( GeoParser& parser ) const
{
Q_ASSERT( parser.isStartElement() && parser.isValidElement( kmlTag_href ) );
GeoStackItem parentItem = parser.parentElement();
if ( parentItem.represents( kmlTag_Icon ) ) {
// we need a more elaborate version of this part
QString filename = QUrl( ).toLocalFile();
parentItem.nodeAs<GeoDataIconStyle>()->setIcon( filename );
qDebug() << "Parsed <" << kmlTag_href << "> containing: " << parser.readElementText().trimmed()
<< " parent item name: " << parentItem.qualifiedName().first;
}
return 0;
}
<commit_msg>small fix<commit_after>/*
Copyright (C) 2008 Patrick Spendrin <ps_ml@gmx.de>
This file is part of the KDE project
This library is free software you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
aint with this library see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "KMLHrefTagHandler.h"
#include <QtCore/QDebug>
#include <QtCore/QUrl>
#include "KMLElementDictionary.h"
#include "GeoDataIconStyle.h"
#include "GeoDataParser.h"
using namespace GeoDataElementDictionary;
KML_DEFINE_TAG_HANDLER( href )
KMLhrefTagHandler::KMLhrefTagHandler()
: GeoTagHandler()
{
}
KMLhrefTagHandler::~KMLhrefTagHandler()
{
}
GeoNode* KMLhrefTagHandler::parse( GeoParser& parser ) const
{
Q_ASSERT( parser.isStartElement() && parser.isValidElement( kmlTag_href ) );
GeoStackItem parentItem = parser.parentElement();
if ( parentItem.represents( kmlTag_Icon ) ) {
// we need a more elaborate version of this part
QString filename = QUrl( parser.readElementText().trimmed() ).toLocalFile();
parentItem.nodeAs<GeoDataIconStyle>()->setIcon( filename );
qDebug() << "Parsed <" << kmlTag_href << "> containing: " << parser.readElementText().trimmed()
<< " parent item name: " << parentItem.qualifiedName().first;
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file log_softmax_layer.hpp
* @author Marcus Edel
*
* Definition of the LogSoftmaxLayer class.
*/
#ifndef __MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_LAYER_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* Implementation of the log softmax layer. The log softmax loss layer computes
* the multinomial logistic loss of the softmax of its inputs. This layer is
* meant to be used in combination with the negative log likelihood layer
* (NegativeLogLikelihoodLayer), which expects that the input contains
* log-probabilities for each class.
*
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
typename InputDataType = arma::mat,
typename OutputDataType = arma::mat
>
class LogSoftmaxLayer
{
public:
/**
* Create the LogSoftmaxLayer object.
*/
LogSoftmaxLayer() { /* Nothing to do here. */ }
/**
* Ordinary feed forward pass of a neural network, evaluating the function
* f(x) by propagating the activity forward through f.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
arma::mat maxInput = arma::repmat(arma::max(input), input.n_rows, 1);
output = (maxInput - input);
// Approximation of the hyperbolic tangent. The acuracy however is
// about 0.00001 lower as using tanh. Credits go to Leon Bottou.
output.transform( [](double x)
{
//! Fast approximation of exp(-x) for x positive.
static const double A0 = 1.0;
static const double A1 = 0.125;
static const double A2 = 0.0078125;
static const double A3 = 0.00032552083;
static const double A4 = 1.0172526e-5;
if (x < 13.0)
{
double y = A0 + x * (A1 + x * (A2 + x * (A3 + x * A4)));
y *= y;
y *= y;
y *= y;
y = 1 / y;
return y;
}
return 0.0;
} );
output = input - (maxInput + std::log(arma::accu(output)));
}
/**
* Ordinary feed backward pass of a neural network, calculating the function
* f(x) by propagating x backwards trough f. Using the results from the feed
* forward pass.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Backward(const arma::Mat<eT>& input,
const arma::Mat<eT>& gy,
arma::Mat<eT>& g)
{
g = gy - arma::exp(input) * arma::accu(gy);
}
//! Get the input parameter.
InputDataType& InputParameter() const { return inputParameter; }
//! Modify the input parameter.
InputDataType& InputParameter() { return inputParameter; }
//! Get the output parameter.
OutputDataType& OutputParameter() const { return outputParameter; }
//! Modify the output parameter.
OutputDataType& OutputParameter() { return outputParameter; }
//! Get the delta.
InputDataType& Delta() const { return delta; }
//! Modify the delta.
InputDataType& Delta() { return delta; }
private:
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored input parameter object.
InputDataType inputParameter;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
}; // class LogSoftmaxLayer
}; // namespace ann
}; // namespace mlpack
#endif
<commit_msg>use constexpr to replace static const<commit_after>/**
* @file log_softmax_layer.hpp
* @author Marcus Edel
*
* Definition of the LogSoftmaxLayer class.
*/
#ifndef __MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_LAYER_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* Implementation of the log softmax layer. The log softmax loss layer computes
* the multinomial logistic loss of the softmax of its inputs. This layer is
* meant to be used in combination with the negative log likelihood layer
* (NegativeLogLikelihoodLayer), which expects that the input contains
* log-probabilities for each class.
*
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
typename InputDataType = arma::mat,
typename OutputDataType = arma::mat
>
class LogSoftmaxLayer
{
public:
/**
* Create the LogSoftmaxLayer object.
*/
LogSoftmaxLayer() { /* Nothing to do here. */ }
/**
* Ordinary feed forward pass of a neural network, evaluating the function
* f(x) by propagating the activity forward through f.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
arma::mat maxInput = arma::repmat(arma::max(input), input.n_rows, 1);
output = (maxInput - input);
// Approximation of the hyperbolic tangent. The acuracy however is
// about 0.00001 lower as using tanh. Credits go to Leon Bottou.
output.transform( [](double x)
{
//! Fast approximation of exp(-x) for x positive.
constexpr double A0 = 1.0;
constexpr double A1 = 0.125;
constexpr double A2 = 0.0078125;
constexpr double A3 = 0.00032552083;
constexpr double A4 = 1.0172526e-5;
if (x < 13.0)
{
double y = A0 + x * (A1 + x * (A2 + x * (A3 + x * A4)));
y *= y;
y *= y;
y *= y;
y = 1 / y;
return y;
}
return 0.0;
} );
output = input - (maxInput + std::log(arma::accu(output)));
}
/**
* Ordinary feed backward pass of a neural network, calculating the function
* f(x) by propagating x backwards trough f. Using the results from the feed
* forward pass.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Backward(const arma::Mat<eT>& input,
const arma::Mat<eT>& gy,
arma::Mat<eT>& g)
{
g = gy - arma::exp(input) * arma::accu(gy);
}
//! Get the input parameter.
InputDataType& InputParameter() const { return inputParameter; }
//! Modify the input parameter.
InputDataType& InputParameter() { return inputParameter; }
//! Get the output parameter.
OutputDataType& OutputParameter() const { return outputParameter; }
//! Modify the output parameter.
OutputDataType& OutputParameter() { return outputParameter; }
//! Get the delta.
InputDataType& Delta() const { return delta; }
//! Modify the delta.
InputDataType& Delta() { return delta; }
private:
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored input parameter object.
InputDataType inputParameter;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
}; // class LogSoftmaxLayer
}; // namespace ann
}; // namespace mlpack
#endif
<|endoftext|> |
<commit_before>/**
* @file
* @brief Implements the particle generator
* @remark Based on code from John Idarraga
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied
* verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities
* granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "GeneratorActionG4.hpp"
#include <limits>
#include <memory>
#include <G4Event.hh>
#include <G4GeneralParticleSource.hh>
#include <G4ParticleDefinition.hh>
#include <G4ParticleTable.hh>
#include <array>
#include <TROOT.h>
#include <TRandom.h>
#include "core/config/exceptions.h"
#include "core/utils/log.h"
#include "tools/geant4.h"
using namespace allpix;
GeneratorActionG4::GeneratorActionG4(const Configuration& config)
: particle_source_(std::make_unique<G4GeneralParticleSource>()) {
// Set verbosity of source to off
particle_source_->SetVerbosity(0);
// Get source specific parameters
auto single_source = particle_source_->GetCurrentSource();
auto source_type = config.get<std::string>("beam_source_type", "");
// Find Geant4 particle
auto pdg_table = G4ParticleTable::GetParticleTable();
auto particle_type = config.get<std::string>("particle_type", "");
std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower);
auto particle_code = config.get<int>("particle_code", 0);
G4ParticleDefinition* particle = nullptr;
if(source_type.empty() && !particle_type.empty() && particle_code != 0) {
// if(!particle_type.empty() && particle_code != 0) {
if(pdg_table->FindParticle(particle_type) == pdg_table->FindParticle(particle_code)) {
LOG(WARNING) << "particle_type and particle_code given. Continuing because t hey match.";
particle = pdg_table->FindParticle(particle_code);
if(particle == nullptr) {
throw InvalidValueError(config, "particle_code", "particle code does not exist.");
}
} else {
throw InvalidValueError(
config, "particle_type", "Given particle_type does not match particle_code. Please remove one of them.");
}
} else if(source_type.empty() && particle_type.empty() && particle_code == 0) {
throw InvalidValueError(config, "particle_code", "Please set particle_code or particle_type.");
} else if(source_type.empty() && particle_code != 0) {
particle = pdg_table->FindParticle(particle_code);
if(particle == nullptr) {
throw InvalidValueError(config, "particle_code", "particle code does not exist.");
}
} else if(source_type.empty() && !particle_type.empty()) {
particle = pdg_table->FindParticle(particle_type);
if(particle == nullptr) {
throw InvalidValueError(config, "particle_type", "particle type does not exist.");
}
} else {
if(source_type.empty()) {
throw InvalidValueError(config, "source_type", "Please set source type.");
}
}
LOG(DEBUG) << "Using particle " << particle->GetParticleName() << " (ID " << particle->GetPDGEncoding() << ").";
// Set global parameters of the source
if(!particle_type.empty() || particle_code != 0) {
single_source->SetNumberOfParticles(1);
single_source->SetParticleDefinition(particle);
// Set the primary track's start time in for the current event to zero:
single_source->SetParticleTime(0.0);
}
// Set position parameters
single_source->GetPosDist()->SetPosDisType("Beam");
single_source->GetPosDist()->SetBeamSigmaInR(config.get<double>("beam_size", 0));
single_source->GetPosDist()->SetCentreCoords(config.get<G4ThreeVector>("beam_position"));
// Set angle distribution parameters
single_source->GetAngDist()->SetAngDistType("beam2d");
single_source->GetAngDist()->DefineAngRefAxes("angref1", G4ThreeVector(-1., 0, 0));
G4TwoVector divergence = config.get<G4TwoVector>("beam_divergence", G4TwoVector(0., 0.));
single_source->GetAngDist()->SetBeamSigmaInAngX(divergence.x());
single_source->GetAngDist()->SetBeamSigmaInAngY(divergence.y());
G4ThreeVector direction = config.get<G4ThreeVector>("beam_direction");
if(fabs(direction.mag() - 1.0) > std::numeric_limits<double>::epsilon()) {
LOG(WARNING) << "Momentum direction is not a unit vector: magnitude is ignored";
}
if(!particle_type.empty() || particle_code != 0) {
single_source->GetAngDist()->SetParticleMomentumDirection(direction);
}
// Set energy parameters
auto energy_type = config.get<std::string>("beam_energy_type", "");
if(energy_type == "User") {
single_source->GetEneDist()->SetEnergyDisType(energy_type);
auto beam_hist_point = config.getArray<G4ThreeVector>("beam_hist_point");
for(auto& hist_point : beam_hist_point) {
single_source->GetEneDist()->UserEnergyHisto(hist_point);
}
} else if(source_type == "Iron-55") {
std::stringstream ss;
ss << "gamma";
particle_type.assign(ss.str());
std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower);
particle = pdg_table->FindParticle(particle_type);
single_source->SetNumberOfParticles(1);
single_source->SetParticleDefinition(particle);
single_source->SetParticleTime(0.0);
single_source->GetAngDist()->SetParticleMomentumDirection(direction);
single_source->GetEneDist()->SetEnergyDisType("User");
G4double energy_hist_1[10];
G4double intensity_hist_1[10];
for(G4int i = 0; i < 10; i++) {
energy_hist_1[i] = 0.0059 + 0.0001 * gRandom->Gaus(0, 1);
intensity_hist_1[i] = 28. + 0.01 * gRandom->Gaus(0, 1);
single_source->GetEneDist()->UserEnergyHisto(G4ThreeVector(energy_hist_1[i], intensity_hist_1[i], 0.));
}
G4double energy_hist_2[10];
G4double intensity_hist_2[10];
for(G4int i = 0; i < 10; i++) {
energy_hist_2[i] = 0.00649 + 0.00005 * gRandom->Gaus(0, 1);
intensity_hist_2[i] = 2.85 + 0.001 * gRandom->Gaus(0, 1);
single_source->GetEneDist()->UserEnergyHisto(G4ThreeVector(energy_hist_2[i], intensity_hist_2[i], 0.));
}
} else {
single_source->GetEneDist()->SetEnergyDisType("Gauss");
single_source->GetEneDist()->SetMonoEnergy(config.get<double>("beam_energy"));
}
single_source->GetEneDist()->SetBeamSigmaInE(config.get<double>("beam_energy_spread", 0.));
}
/**
* Called automatically for every event
*/
void GeneratorActionG4::GeneratePrimaries(G4Event* event) {
particle_source_->GeneratePrimaryVertex(event);
}
<commit_msg>Change geometry of GeneratorActionG4.cpp aaccording to Simon's suggestion and it's just a rough version<commit_after>/**
* @file
* @brief Implements the particle generator
* @remark Based on code from John Idarraga
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied
* verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities
* granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "GeneratorActionG4.hpp"
#include <limits>
#include <memory>
#include <G4Event.hh>
#include <G4GeneralParticleSource.hh>
#include <G4ParticleDefinition.hh>
#include <G4ParticleTable.hh>
#include <array>
#include <TROOT.h>
#include <TRandom.h>
#include "core/config/exceptions.h"
#include "core/utils/log.h"
#include "tools/geant4.h"
using namespace allpix;
GeneratorActionG4::GeneratorActionG4(const Configuration& config)
: particle_source_(std::make_unique<G4GeneralParticleSource>()) {
// Set verbosity of source to off
particle_source_->SetVerbosity(0);
// Get source specific parameters
auto single_source = particle_source_->GetCurrentSource();
auto source_type = config.get<std::string>("source_type", "");
// Find Geant4 particle
auto pdg_table = G4ParticleTable::GetParticleTable();
auto particle_type = config.get<std::string>("particle_type", "");
std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower);
auto particle_code = config.get<int>("particle_code", 0);
G4ParticleDefinition* particle = nullptr;
if(source_type.empty() && !particle_type.empty() && particle_code != 0) {
// if(!particle_type.empty() && particle_code != 0) {
if(pdg_table->FindParticle(particle_type) == pdg_table->FindParticle(particle_code)) {
LOG(WARNING) << "particle_type and particle_code given. Continuing because t hey match.";
particle = pdg_table->FindParticle(particle_code);
if(particle == nullptr) {
throw InvalidValueError(config, "particle_code", "particle code does not exist.");
}
} else {
throw InvalidValueError(
config, "particle_type", "Given particle_type does not match particle_code. Please remove one of them.");
}
} else if(source_type.empty() && particle_type.empty() && particle_code == 0) {
throw InvalidValueError(config, "particle_code", "Please set particle_code or particle_type.");
} else if(source_type.empty() && particle_code != 0) {
particle = pdg_table->FindParticle(particle_code);
if(particle == nullptr) {
throw InvalidValueError(config, "particle_code", "particle code does not exist.");
}
} else if(source_type.empty() && !particle_type.empty()) {
particle = pdg_table->FindParticle(particle_type);
if(particle == nullptr) {
throw InvalidValueError(config, "particle_type", "particle type does not exist.");
}
} else {
if(source_type.empty()) {
throw InvalidValueError(config, "source_type", "Please set source type.");
}
}
LOG(DEBUG) << "Using particle " << particle->GetParticleName() << " (ID " << particle->GetPDGEncoding() << ").";
// Set global parameters of the source
if(!particle_type.empty() || particle_code != 0) {
single_source->SetNumberOfParticles(1);
single_source->SetParticleDefinition(particle);
// Set the primary track's start time in for the current event to zero:
single_source->SetParticleTime(0.0);
}
// Set position parameters
single_source->GetPosDist()->SetPosDisType("Beam");
single_source->GetPosDist()->SetBeamSigmaInR(config.get<double>("beam_size", 0));
single_source->GetPosDist()->SetCentreCoords(config.get<G4ThreeVector>("beam_position"));
// Set angle distribution parameters
single_source->GetAngDist()->SetAngDistType("beam2d");
single_source->GetAngDist()->DefineAngRefAxes("angref1", G4ThreeVector(-1., 0, 0));
G4TwoVector divergence = config.get<G4TwoVector>("beam_divergence", G4TwoVector(0., 0.));
single_source->GetAngDist()->SetBeamSigmaInAngX(divergence.x());
single_source->GetAngDist()->SetBeamSigmaInAngY(divergence.y());
G4ThreeVector direction = config.get<G4ThreeVector>("beam_direction");
if(fabs(direction.mag() - 1.0) > std::numeric_limits<double>::epsilon()) {
LOG(WARNING) << "Momentum direction is not a unit vector: magnitude is ignored";
}
if(!particle_type.empty() || particle_code != 0) {
single_source->GetAngDist()->SetParticleMomentumDirection(direction);
}
// Set energy parameters
auto energy_type = config.get<std::string>("beam_energy_type", "");
if(source_type == "radioactive_source") {
auto sample = config.get<std::string>("sample", "");
if(sample == "gamma-decay-single") {
particle_type.assign("gamma");
std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower);
particle = pdg_table->FindParticle(particle_type);
single_source->SetNumberOfParticles(1);
single_source->SetParticleDefinition(particle);
single_source->SetParticleTime(0.0);
single_source->GetAngDist()->SetParticleMomentumDirection(direction);
single_source->GetEneDist()->SetEnergyDisType("Gauss");
single_source->GetEneDist()->SetMonoEnergy(0.0059);
single_source->GetEneDist()->SetBeamSigmaInE(0.0001);
} else if(sample == "gamma-decay-double") { // using iron55 as an example
particle_type.assign("gamma");
std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower);
particle = pdg_table->FindParticle(particle_type);
single_source->SetNumberOfParticles(1);
single_source->SetParticleDefinition(particle);
single_source->SetParticleTime(0.0);
single_source->GetAngDist()->SetParticleMomentumDirection(direction);
single_source->GetEneDist()->SetEnergyDisType("User");
G4ThreeVector hist_point1(0.0059, 28., 0.1), hist_point2(0.00649, 2.85, 0.1);
std::array<G4ThreeVector, 2> beam_hist_point_test = {hist_point1, hist_point2};
for(auto& hist_point : beam_hist_point_test) {
single_source->GetEneDist()->UserEnergyHisto(hist_point);
}
} else if(sample == "beta-decay-single") {
particle_type.assign("e-");
std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower);
particle = pdg_table->FindParticle(particle_type);
single_source->SetNumberOfParticles(1);
single_source->SetParticleDefinition(particle);
single_source->SetParticleTime(0.0);
single_source->GetAngDist()->SetParticleMomentumDirection(direction);
single_source->GetEneDist()->SetEnergyDisType("Gauss");
single_source->GetEneDist()->SetMonoEnergy(0.0059);
single_source->GetEneDist()->SetBeamSigmaInE(0.0001);
} else if(sample == "beta-decay-double") {
particle_type.assign("e-");
std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower);
particle = pdg_table->FindParticle(particle_type);
single_source->SetNumberOfParticles(1);
single_source->SetParticleDefinition(particle);
single_source->SetParticleTime(0.0);
single_source->GetAngDist()->SetParticleMomentumDirection(direction);
single_source->GetEneDist()->SetEnergyDisType("User");
G4double energy_hist_1[10];
G4double intensity_hist_1[10];
for(G4int i = 0; i < 10; i++) {
energy_hist_1[i] = 0.0059 + 0.0001 * gRandom->Gaus(0, 1);
intensity_hist_1[i] = 28. + 0.01 * gRandom->Gaus(0, 1);
single_source->GetEneDist()->UserEnergyHisto(G4ThreeVector(energy_hist_1[i], intensity_hist_1[i], 0.));
}
G4double energy_hist_2[10];
G4double intensity_hist_2[10];
for(G4int i = 0; i < 10; i++) {
energy_hist_2[i] = 0.00649 + 0.00005 * gRandom->Gaus(0, 1);
intensity_hist_2[i] = 2.85 + 0.001 * gRandom->Gaus(0, 1);
single_source->GetEneDist()->UserEnergyHisto(G4ThreeVector(energy_hist_2[i], intensity_hist_2[i], 0.));
}
} else if(sample == "alpha-decay") {
particle_type.assign("gamma");
std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower);
particle = pdg_table->FindParticle(particle_type);
single_source->SetNumberOfParticles(1);
single_source->SetParticleDefinition(particle);
single_source->SetParticleTime(0.0);
single_source->GetAngDist()->SetParticleMomentumDirection(direction);
single_source->GetEneDist()->SetEnergyDisType("Gauss");
single_source->GetEneDist()->SetMonoEnergy(0.0059);
single_source->GetEneDist()->SetBeamSigmaInE(0.0001);
} else if(sample == "user") {
single_source->GetEneDist()->SetEnergyDisType(energy_type);
auto beam_hist_point = config.getArray<G4ThreeVector>("beam_hist_point");
for(auto& hist_point : beam_hist_point) {
single_source->GetEneDist()->UserEnergyHisto(hist_point);
}
} else {
throw InvalidValueError(config, "sample", "Please set a sample.");
}
} else {
single_source->GetEneDist()->SetEnergyDisType("Gauss");
single_source->GetEneDist()->SetMonoEnergy(config.get<double>("beam_energy"));
}
single_source->GetEneDist()->SetBeamSigmaInE(config.get<double>("beam_energy_spread", 0.));
}
/**
* Called automatically for every event
*/
void GeneratorActionG4::GeneratePrimaries(G4Event* event) {
particle_source_->GeneratePrimaryVertex(event);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011 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.
*/
// Author: sligocki@google.com (Shawn Ligocki)
#include "net/instaweb/rewriter/public/css_rewrite_test_base.h"
#include "base/logging.h"
#include "net/instaweb/htmlparse/public/html_parse_test_base.h"
#include "net/instaweb/http/public/content_type.h"
#include "net/instaweb/rewriter/public/resource_namer.h"
#include "net/instaweb/util/public/google_url.h"
#include "net/instaweb/util/public/gtest.h"
#include "net/instaweb/util/public/hasher.h"
#include "net/instaweb/util/public/statistics.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/util/public/string_util.h"
namespace net_instaweb {
CssRewriteTestBase::~CssRewriteTestBase() {}
// Check that inline CSS gets rewritten correctly.
void CssRewriteTestBase::ValidateRewriteInlineCss(
const StringPiece& id,
const StringPiece& css_input,
const StringPiece& expected_css_output,
int flags) {
static const char prefix[] =
"<head>\n"
" <title>Example style outline</title>\n"
" <!-- Style starts here -->\n"
" <style type='text/css'>";
static const char suffix[] = "</style>\n"
" <!-- Style ends here -->\n"
"</head>";
CheckFlags(flags);
GoogleString html_input = StrCat(prefix, css_input, suffix);
GoogleString html_output = StrCat(prefix, expected_css_output, suffix);
ValidateWithStats(id, html_input, html_output,
css_input, expected_css_output, flags);
}
void CssRewriteTestBase::ResetStats() {
num_blocks_rewritten_->Set(0);
num_fallback_rewrites_->Set(0);
num_parse_failures_->Set(0);
num_rewrites_dropped_->Set(0);
total_bytes_saved_->Set(0);
total_original_bytes_->Set(0);
num_uses_->Set(0);
num_flatten_imports_charset_mismatch_->Set(0);
num_flatten_imports_invalid_url_->Set(0);
num_flatten_imports_limit_exceeded_->Set(0);
num_flatten_imports_minify_failed_->Set(0);
num_flatten_imports_recursion_->Set(0);
num_flatten_imports_complex_queries_->Set(0);
}
void CssRewriteTestBase::ValidateWithStats(
const StringPiece& id,
const GoogleString& html_input, const GoogleString& expected_html_output,
const StringPiece& css_input, const StringPiece& expected_css_output,
int flags) {
ResetStats();
// Rewrite
ValidateExpected(id, html_input, expected_html_output);
// Check stats
if (!FlagSet(flags, kNoStatCheck)) {
if (FlagSet(flags, kExpectSuccess)) {
EXPECT_EQ(1, num_blocks_rewritten_->Get()) << id;
EXPECT_EQ(0, num_fallback_rewrites_->Get()) << id;
EXPECT_EQ(0, num_parse_failures_->Get()) << id;
EXPECT_EQ(0, num_rewrites_dropped_->Get()) << id;
EXPECT_EQ(static_cast<int>(css_input.size()) -
static_cast<int>(expected_css_output.size()),
total_bytes_saved_->Get()) << id;
EXPECT_EQ(css_input.size(), total_original_bytes_->Get()) << id;
EXPECT_EQ(1, num_uses_->Get()) << id;
} else if (FlagSet(flags, kExpectNoChange)) {
EXPECT_EQ(0, num_blocks_rewritten_->Get()) << id;
EXPECT_EQ(0, num_fallback_rewrites_->Get()) << id;
EXPECT_EQ(0, num_parse_failures_->Get()) << id;
// TODO(sligocki): Test num_rewrites_dropped_. Currently a couple tests
// have kExpectNoChange, but fail at a different place in the code, so
// they do not trigger the num_rewrites_dropped_ variable.
// EXPECT_EQ(1, num_rewrites_dropped_->Get()) << id;
EXPECT_EQ(0, total_bytes_saved_->Get()) << id;
EXPECT_EQ(0, total_original_bytes_->Get()) << id;
EXPECT_EQ(0, num_uses_->Get()) << id;
} else if (FlagSet(flags, kExpectFallback)) {
EXPECT_EQ(0, num_blocks_rewritten_->Get()) << id;
EXPECT_EQ(1, num_fallback_rewrites_->Get()) << id;
EXPECT_EQ(1, num_parse_failures_->Get()) << id;
EXPECT_EQ(0, num_rewrites_dropped_->Get()) << id;
EXPECT_EQ(0, total_bytes_saved_->Get()) << id;
EXPECT_EQ(0, total_original_bytes_->Get()) << id;
EXPECT_EQ(1, num_uses_->Get()) << id;
} else {
CHECK(FlagSet(flags, kExpectFailure));
EXPECT_EQ(0, num_blocks_rewritten_->Get()) << id;
EXPECT_EQ(0, num_fallback_rewrites_->Get()) << id;
EXPECT_EQ(1, num_parse_failures_->Get()) << id;
EXPECT_EQ(0, num_rewrites_dropped_->Get()) << id;
EXPECT_EQ(0, total_bytes_saved_->Get()) << id;
EXPECT_EQ(0, total_original_bytes_->Get()) << id;
EXPECT_EQ(0, num_uses_->Get()) << id;
}
}
// Check each of the import flattening statistics. Since each of these
// is controlled individually they are not gated by kNoStatCheck above.
EXPECT_EQ(FlagSet(flags, kFlattenImportsCharsetMismatch) ? 1 : 0,
num_flatten_imports_charset_mismatch_->Get()) << id;
EXPECT_EQ(FlagSet(flags, kFlattenImportsInvalidUrl) ? 1 : 0,
num_flatten_imports_invalid_url_->Get()) << id;
EXPECT_EQ(FlagSet(flags, kFlattenImportsLimitExceeded) ? 1 : 0,
num_flatten_imports_limit_exceeded_->Get()) << id;
EXPECT_EQ(FlagSet(flags, kFlattenImportsMinifyFailed) ? 1 : 0,
num_flatten_imports_minify_failed_->Get()) << id;
EXPECT_EQ(FlagSet(flags, kFlattenImportsRecursion) ? 1 : 0,
num_flatten_imports_recursion_->Get()) << id;
EXPECT_EQ(FlagSet(flags, kFlattenImportsComplexQueries) ? 1 : 0,
num_flatten_imports_complex_queries_->Get()) << id;
}
GoogleString CssRewriteTestBase::ExpectedRewrittenUrl(
const StringPiece& original_url,
const StringPiece& expected_contents,
const StringPiece& filter_id,
const ContentType& content_type) {
GoogleUrl original_gurl(original_url);
DCHECK(original_gurl.is_valid());
return EncodeWithBase(original_gurl.Origin(),
original_gurl.AllExceptLeaf(), filter_id,
hasher()->Hash(expected_contents),
original_gurl.LeafWithQuery(),
content_type.file_extension() + 1); // +1 to skip '.'
}
void CssRewriteTestBase::GetNamerForCss(const StringPiece& leaf_name,
const GoogleString& expected_css_output,
ResourceNamer* namer) {
namer->set_id(RewriteOptions::kCssFilterId);
namer->set_hash(hasher()->Hash(expected_css_output));
namer->set_ext("css");
namer->set_name(leaf_name);
}
GoogleString CssRewriteTestBase::ExpectedUrlForNamer(
const ResourceNamer& namer) {
return Encode(kTestDomain, namer.id(), namer.hash(), namer.name(),
namer.ext());
}
GoogleString CssRewriteTestBase::ExpectedUrlForCss(
const StringPiece& id,
const GoogleString& expected_css_output) {
ResourceNamer namer;
GetNamerForCss(StrCat(id, ".css"), expected_css_output, &namer);
return ExpectedUrlForNamer(namer);
}
// Check that external CSS gets rewritten correctly.
void CssRewriteTestBase::ValidateRewriteExternalCssUrl(
const StringPiece& css_url,
const GoogleString& css_input,
const GoogleString& expected_css_output,
int flags) {
CheckFlags(flags);
// Set input file.
if (!FlagSet(flags, kNoClearFetcher)) {
ClearFetcherResponses();
}
SetResponseWithDefaultHeaders(css_url, kContentTypeCss, css_input, 300);
GoogleString link_extras("");
if (FlagSet(flags, kLinkCharsetIsUTF8)) {
link_extras = " charset='utf-8'";
}
if (FlagSet(flags, kLinkScreenMedia) && FlagSet(flags, kLinkPrintMedia)) {
StrAppend(&link_extras, " media='screen,print'");
} else if (FlagSet(flags, kLinkScreenMedia)) {
StrAppend(&link_extras, " media='screen'");
} else if (FlagSet(flags, kLinkPrintMedia)) {
StrAppend(&link_extras, " media='print'");
}
GoogleString meta_tag("");
if (FlagSet(flags, kMetaCharsetUTF8)) {
StrAppend(&meta_tag, " <meta charset=\"utf-8\">");
}
if (FlagSet(flags, kMetaCharsetISO88591)) {
StrAppend(&meta_tag, " <meta charset=ISO-8859-1>");
}
if (FlagSet(flags, kMetaHttpEquiv)) {
StrAppend(&meta_tag,
" <meta http-equiv=\"Content-Type\" "
"content=\"text/html; charset=UTF-8\">");
}
if (FlagSet(flags, kMetaHttpEquivUnquoted)) {
// Same as the previous one but content's value isn't quoted!
StrAppend(&meta_tag,
" <meta http-equiv=\"Content-Type\" "
"content=text/html; charset=ISO-8859-1>");
}
static const char html_template[] =
"<head>\n"
" <title>Example style outline</title>\n"
"%s"
" <!-- Style starts here -->\n"
" <link rel='stylesheet' type='text/css' href='%s'%s>\n"
" <!-- Style ends here -->\n"
"</head>";
GoogleString html_input = StringPrintf(html_template, meta_tag.c_str(),
css_url.as_string().c_str(),
link_extras.c_str());
GoogleString html_output;
ResourceNamer namer;
GoogleUrl css_gurl(css_url);
GetNamerForCss(css_gurl.LeafWithQuery(), expected_css_output, &namer);
GoogleString expected_new_url =
Encode(css_gurl.AllExceptLeaf(), namer.id(), namer.hash(),
namer.name(), namer.ext());
if (FlagSet(flags, kExpectSuccess) || FlagSet(flags, kExpectFallback)) {
html_output = StringPrintf(html_template, meta_tag.c_str(),
expected_new_url.c_str(), link_extras.c_str());
} else {
html_output = html_input;
}
ValidateWithStats(css_url, html_input, html_output,
css_input, expected_css_output, flags);
// If we produced a new output resource, check it.
if (FlagSet(flags, kExpectSuccess) || FlagSet(flags, kExpectFallback)) {
GoogleString actual_output;
// TODO(sligocki): This will only work with mock_hasher.
EXPECT_TRUE(FetchResourceUrl(expected_new_url, &actual_output)) << css_url;
EXPECT_EQ(expected_css_output, actual_output) << css_url;
// Serve from new context.
if (!FlagSet(flags, kNoOtherContexts)) {
ServeResourceFromManyContexts(expected_new_url, expected_css_output);
}
}
}
// Helper to test for how we handle trailing junk
void CssRewriteTestBase::TestCorruptUrl(const char* new_suffix) {
const char kInput[] = " div { } ";
const char kOutput[] = "div{}";
// Compute normal version
ValidateRewriteExternalCss("rep", kInput, kOutput, kExpectSuccess);
// Fetch with messed up extension
GoogleString css_url = ExpectedUrlForCss("rep", kOutput);
ASSERT_TRUE(StringCaseEndsWith(css_url, ".css"));
GoogleString munged_url =
ChangeSuffix(css_url, false /*replace*/, ".css", new_suffix);
GoogleString output;
EXPECT_TRUE(FetchResourceUrl(munged_url, &output));
// Now see that output is correct
ValidateRewriteExternalCss(
"rep", kInput, kOutput,
kExpectSuccess | kNoClearFetcher | kNoStatCheck);
}
} // namespace net_instaweb
<commit_msg>Verify caching headers of constructed CSS across many tests, including CssImageCombineTest.SpritesImagesExternal<commit_after>/*
* Copyright 2011 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.
*/
// Author: sligocki@google.com (Shawn Ligocki)
#include "net/instaweb/rewriter/public/css_rewrite_test_base.h"
#include "base/logging.h"
#include "net/instaweb/htmlparse/public/html_parse_test_base.h"
#include "net/instaweb/http/public/content_type.h"
#include "net/instaweb/rewriter/public/resource_namer.h"
#include "net/instaweb/util/public/google_url.h"
#include "net/instaweb/util/public/gtest.h"
#include "net/instaweb/util/public/hasher.h"
#include "net/instaweb/util/public/statistics.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/util/public/string_util.h"
#include "net/instaweb/util/public/timer.h"
namespace net_instaweb {
CssRewriteTestBase::~CssRewriteTestBase() {}
// Check that inline CSS gets rewritten correctly.
void CssRewriteTestBase::ValidateRewriteInlineCss(
const StringPiece& id,
const StringPiece& css_input,
const StringPiece& expected_css_output,
int flags) {
static const char prefix[] =
"<head>\n"
" <title>Example style outline</title>\n"
" <!-- Style starts here -->\n"
" <style type='text/css'>";
static const char suffix[] = "</style>\n"
" <!-- Style ends here -->\n"
"</head>";
CheckFlags(flags);
GoogleString html_input = StrCat(prefix, css_input, suffix);
GoogleString html_output = StrCat(prefix, expected_css_output, suffix);
ValidateWithStats(id, html_input, html_output,
css_input, expected_css_output, flags);
}
void CssRewriteTestBase::ResetStats() {
num_blocks_rewritten_->Set(0);
num_fallback_rewrites_->Set(0);
num_parse_failures_->Set(0);
num_rewrites_dropped_->Set(0);
total_bytes_saved_->Set(0);
total_original_bytes_->Set(0);
num_uses_->Set(0);
num_flatten_imports_charset_mismatch_->Set(0);
num_flatten_imports_invalid_url_->Set(0);
num_flatten_imports_limit_exceeded_->Set(0);
num_flatten_imports_minify_failed_->Set(0);
num_flatten_imports_recursion_->Set(0);
num_flatten_imports_complex_queries_->Set(0);
}
void CssRewriteTestBase::ValidateWithStats(
const StringPiece& id,
const GoogleString& html_input, const GoogleString& expected_html_output,
const StringPiece& css_input, const StringPiece& expected_css_output,
int flags) {
ResetStats();
// Rewrite
ValidateExpected(id, html_input, expected_html_output);
// Check stats
if (!FlagSet(flags, kNoStatCheck)) {
if (FlagSet(flags, kExpectSuccess)) {
EXPECT_EQ(1, num_blocks_rewritten_->Get()) << id;
EXPECT_EQ(0, num_fallback_rewrites_->Get()) << id;
EXPECT_EQ(0, num_parse_failures_->Get()) << id;
EXPECT_EQ(0, num_rewrites_dropped_->Get()) << id;
EXPECT_EQ(static_cast<int>(css_input.size()) -
static_cast<int>(expected_css_output.size()),
total_bytes_saved_->Get()) << id;
EXPECT_EQ(css_input.size(), total_original_bytes_->Get()) << id;
EXPECT_EQ(1, num_uses_->Get()) << id;
} else if (FlagSet(flags, kExpectNoChange)) {
EXPECT_EQ(0, num_blocks_rewritten_->Get()) << id;
EXPECT_EQ(0, num_fallback_rewrites_->Get()) << id;
EXPECT_EQ(0, num_parse_failures_->Get()) << id;
// TODO(sligocki): Test num_rewrites_dropped_. Currently a couple tests
// have kExpectNoChange, but fail at a different place in the code, so
// they do not trigger the num_rewrites_dropped_ variable.
// EXPECT_EQ(1, num_rewrites_dropped_->Get()) << id;
EXPECT_EQ(0, total_bytes_saved_->Get()) << id;
EXPECT_EQ(0, total_original_bytes_->Get()) << id;
EXPECT_EQ(0, num_uses_->Get()) << id;
} else if (FlagSet(flags, kExpectFallback)) {
EXPECT_EQ(0, num_blocks_rewritten_->Get()) << id;
EXPECT_EQ(1, num_fallback_rewrites_->Get()) << id;
EXPECT_EQ(1, num_parse_failures_->Get()) << id;
EXPECT_EQ(0, num_rewrites_dropped_->Get()) << id;
EXPECT_EQ(0, total_bytes_saved_->Get()) << id;
EXPECT_EQ(0, total_original_bytes_->Get()) << id;
EXPECT_EQ(1, num_uses_->Get()) << id;
} else {
CHECK(FlagSet(flags, kExpectFailure));
EXPECT_EQ(0, num_blocks_rewritten_->Get()) << id;
EXPECT_EQ(0, num_fallback_rewrites_->Get()) << id;
EXPECT_EQ(1, num_parse_failures_->Get()) << id;
EXPECT_EQ(0, num_rewrites_dropped_->Get()) << id;
EXPECT_EQ(0, total_bytes_saved_->Get()) << id;
EXPECT_EQ(0, total_original_bytes_->Get()) << id;
EXPECT_EQ(0, num_uses_->Get()) << id;
}
}
// Check each of the import flattening statistics. Since each of these
// is controlled individually they are not gated by kNoStatCheck above.
EXPECT_EQ(FlagSet(flags, kFlattenImportsCharsetMismatch) ? 1 : 0,
num_flatten_imports_charset_mismatch_->Get()) << id;
EXPECT_EQ(FlagSet(flags, kFlattenImportsInvalidUrl) ? 1 : 0,
num_flatten_imports_invalid_url_->Get()) << id;
EXPECT_EQ(FlagSet(flags, kFlattenImportsLimitExceeded) ? 1 : 0,
num_flatten_imports_limit_exceeded_->Get()) << id;
EXPECT_EQ(FlagSet(flags, kFlattenImportsMinifyFailed) ? 1 : 0,
num_flatten_imports_minify_failed_->Get()) << id;
EXPECT_EQ(FlagSet(flags, kFlattenImportsRecursion) ? 1 : 0,
num_flatten_imports_recursion_->Get()) << id;
EXPECT_EQ(FlagSet(flags, kFlattenImportsComplexQueries) ? 1 : 0,
num_flatten_imports_complex_queries_->Get()) << id;
}
GoogleString CssRewriteTestBase::ExpectedRewrittenUrl(
const StringPiece& original_url,
const StringPiece& expected_contents,
const StringPiece& filter_id,
const ContentType& content_type) {
GoogleUrl original_gurl(original_url);
DCHECK(original_gurl.is_valid());
return EncodeWithBase(original_gurl.Origin(),
original_gurl.AllExceptLeaf(), filter_id,
hasher()->Hash(expected_contents),
original_gurl.LeafWithQuery(),
content_type.file_extension() + 1); // +1 to skip '.'
}
void CssRewriteTestBase::GetNamerForCss(const StringPiece& leaf_name,
const GoogleString& expected_css_output,
ResourceNamer* namer) {
namer->set_id(RewriteOptions::kCssFilterId);
namer->set_hash(hasher()->Hash(expected_css_output));
namer->set_ext("css");
namer->set_name(leaf_name);
}
GoogleString CssRewriteTestBase::ExpectedUrlForNamer(
const ResourceNamer& namer) {
return Encode(kTestDomain, namer.id(), namer.hash(), namer.name(),
namer.ext());
}
GoogleString CssRewriteTestBase::ExpectedUrlForCss(
const StringPiece& id,
const GoogleString& expected_css_output) {
ResourceNamer namer;
GetNamerForCss(StrCat(id, ".css"), expected_css_output, &namer);
return ExpectedUrlForNamer(namer);
}
// Check that external CSS gets rewritten correctly.
void CssRewriteTestBase::ValidateRewriteExternalCssUrl(
const StringPiece& css_url,
const GoogleString& css_input,
const GoogleString& expected_css_output,
int flags) {
CheckFlags(flags);
// Set input file.
if (!FlagSet(flags, kNoClearFetcher)) {
ClearFetcherResponses();
}
SetResponseWithDefaultHeaders(css_url, kContentTypeCss, css_input, 300);
GoogleString link_extras("");
if (FlagSet(flags, kLinkCharsetIsUTF8)) {
link_extras = " charset='utf-8'";
}
if (FlagSet(flags, kLinkScreenMedia) && FlagSet(flags, kLinkPrintMedia)) {
StrAppend(&link_extras, " media='screen,print'");
} else if (FlagSet(flags, kLinkScreenMedia)) {
StrAppend(&link_extras, " media='screen'");
} else if (FlagSet(flags, kLinkPrintMedia)) {
StrAppend(&link_extras, " media='print'");
}
GoogleString meta_tag("");
if (FlagSet(flags, kMetaCharsetUTF8)) {
StrAppend(&meta_tag, " <meta charset=\"utf-8\">");
}
if (FlagSet(flags, kMetaCharsetISO88591)) {
StrAppend(&meta_tag, " <meta charset=ISO-8859-1>");
}
if (FlagSet(flags, kMetaHttpEquiv)) {
StrAppend(&meta_tag,
" <meta http-equiv=\"Content-Type\" "
"content=\"text/html; charset=UTF-8\">");
}
if (FlagSet(flags, kMetaHttpEquivUnquoted)) {
// Same as the previous one but content's value isn't quoted!
StrAppend(&meta_tag,
" <meta http-equiv=\"Content-Type\" "
"content=text/html; charset=ISO-8859-1>");
}
static const char html_template[] =
"<head>\n"
" <title>Example style outline</title>\n"
"%s"
" <!-- Style starts here -->\n"
" <link rel='stylesheet' type='text/css' href='%s'%s>\n"
" <!-- Style ends here -->\n"
"</head>";
GoogleString html_input = StringPrintf(html_template, meta_tag.c_str(),
css_url.as_string().c_str(),
link_extras.c_str());
GoogleString html_output;
ResourceNamer namer;
GoogleUrl css_gurl(css_url);
GetNamerForCss(css_gurl.LeafWithQuery(), expected_css_output, &namer);
GoogleString expected_new_url =
Encode(css_gurl.AllExceptLeaf(), namer.id(), namer.hash(),
namer.name(), namer.ext());
if (FlagSet(flags, kExpectSuccess) || FlagSet(flags, kExpectFallback)) {
html_output = StringPrintf(html_template, meta_tag.c_str(),
expected_new_url.c_str(), link_extras.c_str());
} else {
html_output = html_input;
}
ValidateWithStats(css_url, html_input, html_output,
css_input, expected_css_output, flags);
// If we produced a new output resource, check it.
if (FlagSet(flags, kExpectSuccess) || FlagSet(flags, kExpectFallback)) {
GoogleString actual_output;
// TODO(sligocki): This will only work with mock_hasher.
ResponseHeaders headers_out;
EXPECT_TRUE(FetchResourceUrl(expected_new_url, &actual_output,
&headers_out)) << css_url;
EXPECT_EQ(expected_css_output, actual_output) << css_url;
// Non-fallback CSS should have very long caching headers
if (!FlagSet(flags, kExpectFallback)) {
EXPECT_TRUE(headers_out.IsCacheable());
EXPECT_TRUE(headers_out.IsProxyCacheable());
EXPECT_LE(Timer::kYearMs, headers_out.cache_ttl_ms());
}
// Serve from new context.
if (!FlagSet(flags, kNoOtherContexts)) {
ServeResourceFromManyContexts(expected_new_url, expected_css_output);
}
}
}
// Helper to test for how we handle trailing junk
void CssRewriteTestBase::TestCorruptUrl(const char* new_suffix) {
const char kInput[] = " div { } ";
const char kOutput[] = "div{}";
// Compute normal version
ValidateRewriteExternalCss("rep", kInput, kOutput, kExpectSuccess);
// Fetch with messed up extension
GoogleString css_url = ExpectedUrlForCss("rep", kOutput);
ASSERT_TRUE(StringCaseEndsWith(css_url, ".css"));
GoogleString munged_url =
ChangeSuffix(css_url, false /*replace*/, ".css", new_suffix);
GoogleString output;
EXPECT_TRUE(FetchResourceUrl(munged_url, &output));
// Now see that output is correct
ValidateRewriteExternalCss(
"rep", kInput, kOutput,
kExpectSuccess | kNoClearFetcher | kNoStatCheck);
}
} // namespace net_instaweb
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2014 Calin Cruceru <crucerucalincristian@gmail.com>
//
// Self
#include "EditPolylineDialog.h"
#include "ui_EditPolylineDialog.h"
// Qt
#include <QColorDialog>
// Marble
#include "GeoDataPlacemark.h"
#include "GeoDataStyle.h"
namespace Marble
{
class EditPolylineDialog::Private : public Ui::UiEditPolylineDialog
{
public:
Private( GeoDataPlacemark *placemark);
~Private();
// Used to tell whether the settings before showing the dialog should be restored on
// pressing the 'Cancel' button or not.
bool m_firstEditing;
QColorDialog *m_linesDialog;
GeoDataPlacemark *m_placemark;
};
EditPolylineDialog::Private::Private( GeoDataPlacemark *placemark ) :
Ui::UiEditPolylineDialog(),
m_firstEditing( false ),
m_linesDialog( 0 ),
m_placemark( placemark )
{
// nothing to do
}
EditPolylineDialog::Private::~Private()
{
delete m_linesDialog;
}
EditPolylineDialog::EditPolylineDialog( GeoDataPlacemark *placemark, QWidget *parent ) :
QDialog( parent ) ,
d ( new Private( placemark ) )
{
d->setupUi( this );
// If the polygon has just been drawn, assign it a default name.
if ( d->m_placemark->name().isNull() ) {
d->m_placemark->setName( tr("Untitled Path") );
}
d->m_name->setText( placemark->name() );
d->m_description->setText( placemark->description() );
d->m_linesWidth->setRange( 0.1, 5.0 );
// Get the current style properties.
const GeoDataLineStyle lineStyle = placemark->style()->lineStyle();
d->m_linesWidth->setValue( lineStyle.width() );
// Adjust the color button's icon to the current lines color.
QPixmap linesPixmap( d->m_linesColorButton->iconSize().width(),
d->m_linesColorButton->iconSize().height() );
linesPixmap.fill( lineStyle.color() );
d->m_linesColorButton->setIcon( QIcon( linesPixmap ) );
// Setup the color dialogs.
d->m_linesDialog = new QColorDialog( this );
d->m_linesDialog->setOption( QColorDialog::ShowAlphaChannel );
d->m_linesDialog->setCurrentColor( lineStyle.color() );
connect( d->m_linesColorButton, SIGNAL(clicked()), d->m_linesDialog, SLOT(exec()) );
connect( d->m_linesDialog, SIGNAL(colorSelected(QColor)), this, SLOT(updateLinesDialog(const QColor&)) );
// Promote "Ok" button to default button.
d->buttonBox->button( QDialogButtonBox::Ok )->setDefault( true );
connect( d->buttonBox->button( QDialogButtonBox::Ok ), SIGNAL(pressed()), this, SLOT(checkFields()) );
connect( d->buttonBox, SIGNAL(accepted()), this, SLOT(updatePolyline()) );
connect( this, SIGNAL(rejected()), SLOT(restoreInitial()) );
// Ensure that the dialog gets deleted when closing it (either when clicking OK or
// Close).
connect( this, SIGNAL(finished(int)), SLOT(deleteLater()) );
}
EditPolylineDialog::~EditPolylineDialog()
{
delete d;
}
void EditPolylineDialog::setFirstTimeEditing( bool enabled )
{
d->m_firstEditing = enabled;
}
void EditPolylineDialog::updatePolyline()
{
emit polylineUpdated( d->m_placemark );
}
void EditPolylineDialog::updateLinesDialog( const QColor &color )
{
QPixmap linesPixmap( d->m_linesColorButton->iconSize().width(),
d->m_linesColorButton->iconSize().height() );
linesPixmap.fill( color );
d->m_linesColorButton->setIcon( QIcon( linesPixmap ) );
}
void EditPolylineDialog::restoreInitial()
{
emit polylineUpdated( d->m_placemark );
}
void EditPolylineDialog::checkFields()
{
}
}
#include "EditPolylineDialog.moc"
<commit_msg>EditPolylineDialog is completely implemented<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2014 Calin Cruceru <crucerucalincristian@gmail.com>
//
// Self
#include "EditPolylineDialog.h"
#include "ui_EditPolylineDialog.h"
// Qt
#include <QColorDialog>
#include <QMessageBox>
// Marble
#include "GeoDataPlacemark.h"
#include "GeoDataStyle.h"
namespace Marble
{
class EditPolylineDialog::Private : public Ui::UiEditPolylineDialog
{
public:
Private( GeoDataPlacemark *placemark);
~Private();
// Used to tell whether the settings before showing the dialog should be restored on
// pressing the 'Cancel' button or not.
bool m_firstEditing;
QColorDialog *m_linesDialog;
GeoDataPlacemark *m_placemark;
// Used to restore if the Cancel button is pressed.
QString m_initialName;
QString m_initialDescription;
GeoDataLineStyle m_initialLineStyle;
};
EditPolylineDialog::Private::Private( GeoDataPlacemark *placemark ) :
Ui::UiEditPolylineDialog(),
m_firstEditing( false ),
m_linesDialog( 0 ),
m_placemark( placemark )
{
// nothing to do
}
EditPolylineDialog::Private::~Private()
{
delete m_linesDialog;
}
EditPolylineDialog::EditPolylineDialog( GeoDataPlacemark *placemark, QWidget *parent ) :
QDialog( parent ) ,
d ( new Private( placemark ) )
{
d->setupUi( this );
// If the polygon has just been drawn, assign it a default name.
if ( d->m_placemark->name().isNull() ) {
d->m_placemark->setName( tr("Untitled Path") );
}
d->m_name->setText( placemark->name() );
d->m_initialName = d->m_name->text();
d->m_description->setText( placemark->description() );
d->m_initialDescription = d->m_description->toPlainText();
d->m_linesWidth->setRange( 0.1, 5.0 );
// Get the current style properties.
const GeoDataLineStyle lineStyle = placemark->style()->lineStyle();
d->m_linesWidth->setValue( lineStyle.width() );
d->m_initialLineStyle = lineStyle;
// Adjust the color button's icon to the current lines color.
QPixmap linesPixmap( d->m_linesColorButton->iconSize().width(),
d->m_linesColorButton->iconSize().height() );
linesPixmap.fill( lineStyle.color() );
d->m_linesColorButton->setIcon( QIcon( linesPixmap ) );
// Setup the color dialogs.
d->m_linesDialog = new QColorDialog( this );
d->m_linesDialog->setOption( QColorDialog::ShowAlphaChannel );
d->m_linesDialog->setCurrentColor( lineStyle.color() );
connect( d->m_linesColorButton, SIGNAL(clicked()), d->m_linesDialog, SLOT(exec()) );
connect( d->m_linesDialog, SIGNAL(colorSelected(QColor)), this, SLOT(updateLinesDialog(const QColor&)) );
// Promote "Ok" button to default button.
d->buttonBox->button( QDialogButtonBox::Ok )->setDefault( true );
connect( d->buttonBox->button( QDialogButtonBox::Ok ), SIGNAL(pressed()), this, SLOT(checkFields()) );
connect( d->buttonBox, SIGNAL(accepted()), this, SLOT(updatePolyline()) );
connect( this, SIGNAL(rejected()), SLOT(restoreInitial()) );
// Ensure that the dialog gets deleted when closing it (either when clicking OK or
// Close).
connect( this, SIGNAL(finished(int)), SLOT(deleteLater()) );
}
EditPolylineDialog::~EditPolylineDialog()
{
delete d;
}
void EditPolylineDialog::setFirstTimeEditing( bool enabled )
{
d->m_firstEditing = enabled;
}
void EditPolylineDialog::updatePolyline()
{
d->m_placemark->setDescription( d->m_description->toPlainText() );
d->m_placemark->setName( d->m_name->text() );
GeoDataStyle *newStyle = new GeoDataStyle( *d->m_placemark->style() );
newStyle->lineStyle().setColor( d->m_linesDialog->currentColor() );
newStyle->lineStyle().setWidth( d->m_linesWidth->value() );
d->m_placemark->setStyle( newStyle );
emit polylineUpdated( d->m_placemark );
}
void EditPolylineDialog::updateLinesDialog( const QColor &color )
{
QPixmap linesPixmap( d->m_linesColorButton->iconSize().width(),
d->m_linesColorButton->iconSize().height() );
linesPixmap.fill( color );
d->m_linesColorButton->setIcon( QIcon( linesPixmap ) );
}
void EditPolylineDialog::restoreInitial()
{
// Make sure the polyline gets removed if the 'Cancel' button is pressed immediately after
// the 'Add Path' has been clicked.
if ( d->m_firstEditing ) {
emit removeRequested();
return;
}
if ( d->m_placemark->name() != d->m_initialName ) {
d->m_placemark->setName( d->m_initialName );
}
if ( d->m_placemark->description() != d->m_initialDescription ) {
d->m_placemark->setDescription( d->m_initialDescription );
}
if ( d->m_placemark->style()->lineStyle() != d->m_initialLineStyle ) {
GeoDataStyle *newStyle = new GeoDataStyle( *d->m_placemark->style() );
newStyle->setLineStyle( d->m_initialLineStyle );
d->m_placemark->setStyle( newStyle );
}
emit polylineUpdated( d->m_placemark );
}
void EditPolylineDialog::checkFields()
{
if ( d->m_name->text().isEmpty() ) {
QMessageBox::warning( this,
tr( "No name specified" ),
tr( "Please specify a name for this polyline." ) );
}
}
}
#include "EditPolylineDialog.moc"
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.