text
stringlengths 54
60.6k
|
---|
<commit_before>#include "stdafx.h"
#include "include/framework.h"
#include "include/debug.h"
#include "include/exceptions.h"
namespace yappy {
namespace framework {
using error::checkWin32Result;
///////////////////////////////////////////////////////////////////////////////
// class ResourceManager impl
///////////////////////////////////////////////////////////////////////////////
#pragma region ResourceManager
ResourceManager::ResourceManager(size_t resSetCount) :
m_texMapVec(resSetCount), m_fontMapVec(resSetCount), m_seMapVec(resSetCount)
{}
namespace {
template <class T, class U>
void addResource(ResourceManager::ResMapVec<T> *targetMapVec,
size_t setId, const char * resId, std::function<U> loadFunc)
{
IdString fixedResId;
util::createFixedString(&fixedResId, resId);
std::unordered_map<IdString, Resource<T>> &map =
targetMapVec->at(setId);
if (map.count(fixedResId) != 0) {
throw std::invalid_argument(std::string("Resource ID already exists: ") + resId);
}
// key = IdString(fixedResId)
// value = Resource<T>(loadfunc)
map.emplace(std::piecewise_construct,
std::forward_as_tuple(fixedResId),
std::forward_as_tuple(loadFunc));
}
} // namespace
void ResourceManager::addTexture(size_t setId, const char * resId,
std::function<graphics::DGraphics::TextureResourcePtr()> loadFunc)
{
addResource(&m_texMapVec, setId, resId, loadFunc);
}
void ResourceManager::addFont(size_t setId, const char *resId,
std::function<graphics::DGraphics::FontResourcePtr()> loadFunc)
{
addResource(&m_fontMapVec, setId, resId, loadFunc);
}
void ResourceManager::addSoundEffect(size_t setId, const char *resId,
std::function<sound::XAudio2::SeResourcePtr()> loadFunc)
{
addResource(&m_seMapVec, setId, resId, loadFunc);
}
namespace {
template <class T>
void loadAll(ResourceManager::ResMapVec<T> *targetMapVec, size_t setId)
{
for (auto &elem : targetMapVec->at(setId)) {
elem.second.load();
}
}
template <class T>
void unloadAll(ResourceManager::ResMapVec<T> *targetMapVec, size_t setId)
{
for (auto &elem : targetMapVec->at(setId)) {
elem.second.unload();
}
}
} // namespace
void ResourceManager::loadResourceSet(size_t setId)
{
loadAll(&m_texMapVec, setId);
loadAll(&m_fontMapVec, setId);
loadAll(&m_seMapVec, setId);
}
void ResourceManager::unloadResourceSet(size_t setId)
{
unloadAll(&m_texMapVec, setId);
unloadAll(&m_fontMapVec, setId);
unloadAll(&m_seMapVec, setId);
}
#pragma endregion
///////////////////////////////////////////////////////////////////////////////
// class FrameControl impl
///////////////////////////////////////////////////////////////////////////////
#pragma region FrameControl
namespace {
inline int64_t getTimeCounter()
{
LARGE_INTEGER cur;
BOOL b = ::QueryPerformanceCounter(&cur);
checkWin32Result(b != 0, "QueryPerformanceCounter() failed");
return cur.QuadPart;
}
} // namespace
FrameControl::FrameControl(uint32_t fps, uint32_t skipCount) :
m_skipCount(skipCount),
m_fpsPeriod(fps)
{
// counter/sec
LARGE_INTEGER freq;
BOOL b = ::QueryPerformanceFrequency(&freq);
checkWin32Result(b != FALSE, "QueryPerformanceFrequency() failed");
m_freq = freq.QuadPart;
// counter/frame = (counter/sec) / (frame/sec)
// = m_freq / fps
m_counterPerFrame = m_freq / fps;
}
bool FrameControl::shouldSkipFrame()
{
return m_frameCount != 0;
}
void FrameControl::endFrame()
{
// for fps calc
if (!shouldSkipFrame()) {
m_fpsFrameAcc++;
}
int64_t target = m_base + m_counterPerFrame;
int64_t cur = getTimeCounter();
if (m_base == 0) {
// force OK
m_base = cur;
}
else if (cur < target) {
// OK, wait for next frame
while (cur < target) {
::Sleep(1);
cur = getTimeCounter();
}
// may overrun a little bit, add it to next frame
m_base = target;
}
else {
// too late, probably immediately right after vsync
m_base = cur;
}
// m_frameCount++;
// m_frameCount %= (#draw(=1) + #skip)
m_frameCount = (m_frameCount + 1) % (1 + m_skipCount);
// for fps calc
m_fpsCount++;
if (m_fpsCount >= m_fpsPeriod) {
double sec = static_cast<double>(cur - m_fpsBase) / m_freq;
m_fps = m_fpsFrameAcc / sec;
m_fpsCount = 0;
m_fpsFrameAcc = 0;
m_fpsBase = cur;
}
}
double FrameControl::getFramePerSec()
{
return m_fps;
}
#pragma endregion
///////////////////////////////////////////////////////////////////////////////
// class Application impl
///////////////////////////////////////////////////////////////////////////////
#pragma region Application
Application::Application(const AppParam &appParam, const graphics::GraphicsParam &graphParam):
m_param(appParam),
m_graphParam(graphParam),
m_frameCtrl(graphParam.refreshRate, appParam.frameSkip)
{
// window
initializeWindow();
m_graphParam.hWnd = m_hWnd.get();
// DirectGraphics
auto *tmpDg = new graphics::DGraphics(m_graphParam);
m_dg.reset(tmpDg);
// XAudio2
auto *tmpXa2 = new sound::XAudio2();
m_ds.reset(tmpXa2);
// DirectInput
auto *tmpDi = new input::DInput(m_param.hInstance, m_hWnd.get());
m_di.reset(tmpDi);
}
void Application::initializeWindow()
{
debug::writeLine(L"Initializing window...");
// Register class
WNDCLASSEX cls = { 0 };
cls.cbSize = sizeof(WNDCLASSEX);
cls.style = 0;
cls.lpfnWndProc = wndProc;
cls.cbClsExtra = 0;
cls.cbWndExtra = 0;
cls.hInstance = m_param.hInstance;
cls.hIcon = m_param.hIcon;
cls.hCursor = LoadCursor(NULL, IDC_ARROW);
cls.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BTNFACE + 1);
cls.lpszMenuName = nullptr;
cls.lpszClassName = m_param.wndClsName;
cls.hIconSm = m_param.hIconSm;
checkWin32Result(::RegisterClassEx(&cls) != 0, "RegisterClassEx() failed");
const DWORD wndStyle = WS_OVERLAPPEDWINDOW & ~WS_SIZEBOX & ~WS_MAXIMIZEBOX;
RECT rc = { 0, 0, m_graphParam.w, m_graphParam.h };
checkWin32Result(::AdjustWindowRect(&rc, wndStyle, FALSE) != FALSE,
"AdjustWindowRect() failed");
HWND hWnd = ::CreateWindow(m_param.wndClsName, m_param.title, wndStyle,
CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top,
nullptr, nullptr, m_param.hInstance, this);
checkWin32Result(hWnd != nullptr, "CreateWindow() failed");
m_hWnd.reset(hWnd);
// for frame processing while window drugging etc.
::SetTimer(m_hWnd.get(), TimerEventId, 1, nullptr);
// Show cursor
if (m_param.showCursor) {
while (::ShowCursor(TRUE) < 0);
}
else {
while (::ShowCursor(FALSE) >= 0);
}
debug::writeLine(L"Initializing window OK");
}
Application::~Application()
{
debug::writeLine(L"Finalize Application Window");
}
LRESULT CALLBACK Application::wndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == WM_CREATE) {
// Associate this ptr with hWnd
void *userData = reinterpret_cast<LPCREATESTRUCT>(lParam)->lpCreateParams;
::SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(userData));
}
LONG_PTR user = ::GetWindowLongPtr(hWnd, GWLP_USERDATA);
Application *self = reinterpret_cast<Application *>(user);
switch (msg) {
case WM_TIMER:
self->onIdle();
return 0;
case WM_SIZE:
return self->onSize(hWnd, msg, wParam, lParam);
case WM_CLOSE:
self->m_hWnd.reset();
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return ::DefWindowProc(hWnd, msg, wParam, lParam);
}
LRESULT Application::onSize(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return m_dg->onSize(hWnd, msg, wParam, lParam);
}
// main work
// update(), then draw() if FrameControl allowed
void Application::onIdle()
{
updateInternal();
if (!m_frameCtrl.shouldSkipFrame()) {
renderInternal();
}
m_frameCtrl.endFrame();
// fps
wchar_t buf[256] = { 0 };
swprintf_s(buf, L"%s fps=%.2f (%d)", m_param.title,
m_frameCtrl.getFramePerSec(), m_param.frameSkip);
::SetWindowText(m_hWnd.get(), buf);
}
void Application::updateInternal()
{
m_ds->processFrame();
m_di->processFrame();
// Call user code
update();
}
void Application::renderInternal()
{
// TEST: frame skip
/*
uint32_t skip = 3;
::Sleep(17 * skip);
//*/
// Call user code
render();
m_dg->render();
}
int Application::run()
{
// Call user code
init();
::ShowWindow(m_hWnd.get(), m_param.nCmdShow);
::UpdateWindow(m_hWnd.get());
MSG msg = { 0 };
while (msg.message != WM_QUIT) {
if (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
else {
// main work
onIdle();
}
}
return static_cast<int>(msg.wParam);
}
void Application::addTextureResource(size_t setId, const char *resId, const wchar_t *path)
{
std::wstring pathCopy(path);
m_resMgr.addTexture(setId, resId, [this, pathCopy]() {
yappy::debug::writef(L"LoadTexture: %s", pathCopy.c_str());
return m_dg->loadTexture(pathCopy.c_str());
});
}
void Application::addFontResource(size_t setId, const char *resId,
const wchar_t *fontName, uint32_t startChar, uint32_t endChar,
uint32_t w, uint32_t h)
{
std::wstring fontNameCopy(fontName);
m_resMgr.addFont(setId, resId, [this, fontNameCopy,]() {
yappy::debug::writef(L"CreateFont: %s", fontNameCopy.c_str());
return m_dg->loadFont();
});
}
void Application::addSeResource(size_t setId, const char *resId, const wchar_t *path)
{
std::wstring pathCopy(path);
m_resMgr.addSoundEffect(setId, resId, [this, pathCopy]() {
yappy::debug::writef(L"LoadSoundEffect: %s", pathCopy.c_str());
return m_ds->loadSoundEffect(pathCopy.c_str());
});
}
void Application::loadResourceSet(size_t setId)
{
m_resMgr.loadResourceSet(setId);
}
void Application::unloadResourceSet(size_t setId)
{
m_resMgr.unloadResourceSet(setId);
}
#pragma endregion
}
}
<commit_msg>Fix compile error<commit_after>#include "stdafx.h"
#include "include/framework.h"
#include "include/debug.h"
#include "include/exceptions.h"
namespace yappy {
namespace framework {
using error::checkWin32Result;
///////////////////////////////////////////////////////////////////////////////
// class ResourceManager impl
///////////////////////////////////////////////////////////////////////////////
#pragma region ResourceManager
ResourceManager::ResourceManager(size_t resSetCount) :
m_texMapVec(resSetCount), m_fontMapVec(resSetCount), m_seMapVec(resSetCount)
{}
namespace {
template <class T, class U>
void addResource(ResourceManager::ResMapVec<T> *targetMapVec,
size_t setId, const char * resId, std::function<U> loadFunc)
{
IdString fixedResId;
util::createFixedString(&fixedResId, resId);
std::unordered_map<IdString, Resource<T>> &map =
targetMapVec->at(setId);
if (map.count(fixedResId) != 0) {
throw std::invalid_argument(std::string("Resource ID already exists: ") + resId);
}
// key = IdString(fixedResId)
// value = Resource<T>(loadfunc)
map.emplace(std::piecewise_construct,
std::forward_as_tuple(fixedResId),
std::forward_as_tuple(loadFunc));
}
} // namespace
void ResourceManager::addTexture(size_t setId, const char * resId,
std::function<graphics::DGraphics::TextureResourcePtr()> loadFunc)
{
addResource(&m_texMapVec, setId, resId, loadFunc);
}
void ResourceManager::addFont(size_t setId, const char *resId,
std::function<graphics::DGraphics::FontResourcePtr()> loadFunc)
{
addResource(&m_fontMapVec, setId, resId, loadFunc);
}
void ResourceManager::addSoundEffect(size_t setId, const char *resId,
std::function<sound::XAudio2::SeResourcePtr()> loadFunc)
{
addResource(&m_seMapVec, setId, resId, loadFunc);
}
namespace {
template <class T>
void loadAll(ResourceManager::ResMapVec<T> *targetMapVec, size_t setId)
{
for (auto &elem : targetMapVec->at(setId)) {
elem.second.load();
}
}
template <class T>
void unloadAll(ResourceManager::ResMapVec<T> *targetMapVec, size_t setId)
{
for (auto &elem : targetMapVec->at(setId)) {
elem.second.unload();
}
}
} // namespace
void ResourceManager::loadResourceSet(size_t setId)
{
loadAll(&m_texMapVec, setId);
loadAll(&m_fontMapVec, setId);
loadAll(&m_seMapVec, setId);
}
void ResourceManager::unloadResourceSet(size_t setId)
{
unloadAll(&m_texMapVec, setId);
unloadAll(&m_fontMapVec, setId);
unloadAll(&m_seMapVec, setId);
}
#pragma endregion
///////////////////////////////////////////////////////////////////////////////
// class FrameControl impl
///////////////////////////////////////////////////////////////////////////////
#pragma region FrameControl
namespace {
inline int64_t getTimeCounter()
{
LARGE_INTEGER cur;
BOOL b = ::QueryPerformanceCounter(&cur);
checkWin32Result(b != 0, "QueryPerformanceCounter() failed");
return cur.QuadPart;
}
} // namespace
FrameControl::FrameControl(uint32_t fps, uint32_t skipCount) :
m_skipCount(skipCount),
m_fpsPeriod(fps)
{
// counter/sec
LARGE_INTEGER freq;
BOOL b = ::QueryPerformanceFrequency(&freq);
checkWin32Result(b != FALSE, "QueryPerformanceFrequency() failed");
m_freq = freq.QuadPart;
// counter/frame = (counter/sec) / (frame/sec)
// = m_freq / fps
m_counterPerFrame = m_freq / fps;
}
bool FrameControl::shouldSkipFrame()
{
return m_frameCount != 0;
}
void FrameControl::endFrame()
{
// for fps calc
if (!shouldSkipFrame()) {
m_fpsFrameAcc++;
}
int64_t target = m_base + m_counterPerFrame;
int64_t cur = getTimeCounter();
if (m_base == 0) {
// force OK
m_base = cur;
}
else if (cur < target) {
// OK, wait for next frame
while (cur < target) {
::Sleep(1);
cur = getTimeCounter();
}
// may overrun a little bit, add it to next frame
m_base = target;
}
else {
// too late, probably immediately right after vsync
m_base = cur;
}
// m_frameCount++;
// m_frameCount %= (#draw(=1) + #skip)
m_frameCount = (m_frameCount + 1) % (1 + m_skipCount);
// for fps calc
m_fpsCount++;
if (m_fpsCount >= m_fpsPeriod) {
double sec = static_cast<double>(cur - m_fpsBase) / m_freq;
m_fps = m_fpsFrameAcc / sec;
m_fpsCount = 0;
m_fpsFrameAcc = 0;
m_fpsBase = cur;
}
}
double FrameControl::getFramePerSec()
{
return m_fps;
}
#pragma endregion
///////////////////////////////////////////////////////////////////////////////
// class Application impl
///////////////////////////////////////////////////////////////////////////////
#pragma region Application
Application::Application(const AppParam &appParam, const graphics::GraphicsParam &graphParam):
m_param(appParam),
m_graphParam(graphParam),
m_frameCtrl(graphParam.refreshRate, appParam.frameSkip)
{
// window
initializeWindow();
m_graphParam.hWnd = m_hWnd.get();
// DirectGraphics
auto *tmpDg = new graphics::DGraphics(m_graphParam);
m_dg.reset(tmpDg);
// XAudio2
auto *tmpXa2 = new sound::XAudio2();
m_ds.reset(tmpXa2);
// DirectInput
auto *tmpDi = new input::DInput(m_param.hInstance, m_hWnd.get());
m_di.reset(tmpDi);
}
void Application::initializeWindow()
{
debug::writeLine(L"Initializing window...");
// Register class
WNDCLASSEX cls = { 0 };
cls.cbSize = sizeof(WNDCLASSEX);
cls.style = 0;
cls.lpfnWndProc = wndProc;
cls.cbClsExtra = 0;
cls.cbWndExtra = 0;
cls.hInstance = m_param.hInstance;
cls.hIcon = m_param.hIcon;
cls.hCursor = LoadCursor(NULL, IDC_ARROW);
cls.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BTNFACE + 1);
cls.lpszMenuName = nullptr;
cls.lpszClassName = m_param.wndClsName;
cls.hIconSm = m_param.hIconSm;
checkWin32Result(::RegisterClassEx(&cls) != 0, "RegisterClassEx() failed");
const DWORD wndStyle = WS_OVERLAPPEDWINDOW & ~WS_SIZEBOX & ~WS_MAXIMIZEBOX;
RECT rc = { 0, 0, m_graphParam.w, m_graphParam.h };
checkWin32Result(::AdjustWindowRect(&rc, wndStyle, FALSE) != FALSE,
"AdjustWindowRect() failed");
HWND hWnd = ::CreateWindow(m_param.wndClsName, m_param.title, wndStyle,
CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top,
nullptr, nullptr, m_param.hInstance, this);
checkWin32Result(hWnd != nullptr, "CreateWindow() failed");
m_hWnd.reset(hWnd);
// for frame processing while window drugging etc.
::SetTimer(m_hWnd.get(), TimerEventId, 1, nullptr);
// Show cursor
if (m_param.showCursor) {
while (::ShowCursor(TRUE) < 0);
}
else {
while (::ShowCursor(FALSE) >= 0);
}
debug::writeLine(L"Initializing window OK");
}
Application::~Application()
{
debug::writeLine(L"Finalize Application Window");
}
LRESULT CALLBACK Application::wndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == WM_CREATE) {
// Associate this ptr with hWnd
void *userData = reinterpret_cast<LPCREATESTRUCT>(lParam)->lpCreateParams;
::SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(userData));
}
LONG_PTR user = ::GetWindowLongPtr(hWnd, GWLP_USERDATA);
Application *self = reinterpret_cast<Application *>(user);
switch (msg) {
case WM_TIMER:
self->onIdle();
return 0;
case WM_SIZE:
return self->onSize(hWnd, msg, wParam, lParam);
case WM_CLOSE:
self->m_hWnd.reset();
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return ::DefWindowProc(hWnd, msg, wParam, lParam);
}
LRESULT Application::onSize(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return m_dg->onSize(hWnd, msg, wParam, lParam);
}
// main work
// update(), then draw() if FrameControl allowed
void Application::onIdle()
{
updateInternal();
if (!m_frameCtrl.shouldSkipFrame()) {
renderInternal();
}
m_frameCtrl.endFrame();
// fps
wchar_t buf[256] = { 0 };
swprintf_s(buf, L"%s fps=%.2f (%d)", m_param.title,
m_frameCtrl.getFramePerSec(), m_param.frameSkip);
::SetWindowText(m_hWnd.get(), buf);
}
void Application::updateInternal()
{
m_ds->processFrame();
m_di->processFrame();
// Call user code
update();
}
void Application::renderInternal()
{
// TEST: frame skip
/*
uint32_t skip = 3;
::Sleep(17 * skip);
//*/
// Call user code
render();
m_dg->render();
}
int Application::run()
{
// Call user code
init();
::ShowWindow(m_hWnd.get(), m_param.nCmdShow);
::UpdateWindow(m_hWnd.get());
MSG msg = { 0 };
while (msg.message != WM_QUIT) {
if (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
else {
// main work
onIdle();
}
}
return static_cast<int>(msg.wParam);
}
void Application::addTextureResource(size_t setId, const char *resId, const wchar_t *path)
{
std::wstring pathCopy(path);
m_resMgr.addTexture(setId, resId, [this, pathCopy]() {
yappy::debug::writef(L"LoadTexture: %s", pathCopy.c_str());
return m_dg->loadTexture(pathCopy.c_str());
});
}
void Application::addFontResource(size_t setId, const char *resId,
const wchar_t *fontName, uint32_t startChar, uint32_t endChar,
uint32_t w, uint32_t h)
{
std::wstring fontNameCopy(fontName);
m_resMgr.addFont(setId, resId, [this, fontNameCopy, startChar, endChar, w, h]() {
yappy::debug::writef(L"CreateFont: %s", fontNameCopy.c_str());
return m_dg->loadFont(fontNameCopy.c_str(), startChar, endChar, w, h);
});
}
void Application::addSeResource(size_t setId, const char *resId, const wchar_t *path)
{
std::wstring pathCopy(path);
m_resMgr.addSoundEffect(setId, resId, [this, pathCopy]() {
yappy::debug::writef(L"LoadSoundEffect: %s", pathCopy.c_str());
return m_ds->loadSoundEffect(pathCopy.c_str());
});
}
void Application::loadResourceSet(size_t setId)
{
m_resMgr.loadResourceSet(setId);
}
void Application::unloadResourceSet(size_t setId)
{
m_resMgr.unloadResourceSet(setId);
}
#pragma endregion
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: abstdlg.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2007-10-15 13:07:27 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <vcl/abstdlg.hxx>
#include "cuilib.hxx"
#include <osl/module.hxx>
#include <tools/string.hxx>
typedef VclAbstractDialogFactory* (__LOADONCALLAPI *FuncPtrCreateDialogFactory)();
extern "C" { static void SAL_CALL thisModule() {} }
VclAbstractDialogFactory* VclAbstractDialogFactory::Create()
{
FuncPtrCreateDialogFactory fp = 0;
static ::osl::Module aDialogLibrary;
if ( aDialogLibrary.is() || aDialogLibrary.loadRelative( &thisModule, String( RTL_CONSTASCII_USTRINGPARAM( DLL_NAME ) ) ) )
fp = ( VclAbstractDialogFactory* (__LOADONCALLAPI*)() )
aDialogLibrary.getFunctionSymbol( ::rtl::OUString::createFromAscii("CreateDialogFactory") );
if ( fp )
return fp();
return 0;
}
VclAbstractDialog::~VclAbstractDialog()
{
}
// virtual
VclAbstractDialog2::~VclAbstractDialog2()
{
}
<commit_msg>INTEGRATION: CWS changefileheader (1.8.160); FILE MERGED 2008/03/28 15:44:59 rt 1.8.160.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: abstdlg.cxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <vcl/abstdlg.hxx>
#include "cuilib.hxx"
#include <osl/module.hxx>
#include <tools/string.hxx>
typedef VclAbstractDialogFactory* (__LOADONCALLAPI *FuncPtrCreateDialogFactory)();
extern "C" { static void SAL_CALL thisModule() {} }
VclAbstractDialogFactory* VclAbstractDialogFactory::Create()
{
FuncPtrCreateDialogFactory fp = 0;
static ::osl::Module aDialogLibrary;
if ( aDialogLibrary.is() || aDialogLibrary.loadRelative( &thisModule, String( RTL_CONSTASCII_USTRINGPARAM( DLL_NAME ) ) ) )
fp = ( VclAbstractDialogFactory* (__LOADONCALLAPI*)() )
aDialogLibrary.getFunctionSymbol( ::rtl::OUString::createFromAscii("CreateDialogFactory") );
if ( fp )
return fp();
return 0;
}
VclAbstractDialog::~VclAbstractDialog()
{
}
// virtual
VclAbstractDialog2::~VclAbstractDialog2()
{
}
<|endoftext|> |
<commit_before>/**
* @file lldockcontrol.cpp
* @brief Creates a panel of a specific kind for a toast
*
* $LicenseInfo:firstyear=2000&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "lldockcontrol.h"
#include "lldockablefloater.h"
LLDockControl::LLDockControl(LLView* dockWidget, LLFloater* dockableFloater,
const LLUIImagePtr& dockTongue, DocAt dockAt, get_allowed_rect_callback_t get_allowed_rect_callback) :
mDockWidget(dockWidget),
mDockableFloater(dockableFloater),
mDockTongue(dockTongue),
mDockTongueX(0),
mDockTongueY(0)
{
mDockAt = dockAt;
if (dockableFloater->isDocked())
{
on();
}
else
{
off();
}
if (!(get_allowed_rect_callback))
{
mGetAllowedRectCallback = boost::bind(&LLDockControl::getAllowedRect, this, _1);
}
else
{
mGetAllowedRectCallback = get_allowed_rect_callback;
}
if (dockWidget != NULL)
{
repositionDockable();
}
if (mDockWidget != NULL)
{
mDockWidgetVisible = isDockVisible();
}
else
{
mDockWidgetVisible = false;
}
}
LLDockControl::~LLDockControl()
{
}
void LLDockControl::setDock(LLView* dockWidget)
{
mDockWidget = dockWidget;
if (mDockWidget != NULL)
{
repositionDockable();
mDockWidgetVisible = isDockVisible();
}
else
{
mDockWidgetVisible = false;
}
}
void LLDockControl::getAllowedRect(LLRect& rect)
{
rect = mDockableFloater->getRootView()->getRect();
}
void LLDockControl::repositionDockable()
{
LLRect dockRect = mDockWidget->calcScreenRect();
LLRect rootRect;
mGetAllowedRectCallback(rootRect);
// recalculate dockable position if dock position changed, dock visibility changed,
// root view rect changed or recalculation is forced
if (mPrevDockRect != dockRect || mDockWidgetVisible != isDockVisible()
|| mRootRect != rootRect || mRecalculateDocablePosition)
{
// undock dockable and off() if dock not visible
if (!isDockVisible())
{
mDockableFloater->setDocked(false);
// force off() since dockable may not have dockControll at this time
off();
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if(dockable_floater != NULL)
{
dockable_floater->onDockHidden();
}
}
else
{
if(mEnabled)
{
moveDockable();
}
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if(dockable_floater != NULL)
{
dockable_floater->onDockShown();
}
}
mPrevDockRect = dockRect;
mRootRect = rootRect;
mRecalculateDocablePosition = false;
mDockWidgetVisible = isDockVisible();
}
}
bool LLDockControl::isDockVisible()
{
bool res = true;
if (mDockWidget != NULL)
{
//we should check all hierarchy
res = mDockWidget->isInVisibleChain();
if (res)
{
LLRect dockRect = mDockWidget->calcScreenRect();
switch (mDockAt)
{
case LEFT: // to keep compiler happy
break;
case BOTTOM:
case TOP:
{
// check is dock inside parent rect
// assume that parent for all dockable flaoters
// is the root view
LLRect dockParentRect =
mDockWidget->getRootView()->calcScreenRect();
if (dockRect.mRight <= dockParentRect.mLeft
|| dockRect.mLeft >= dockParentRect.mRight)
{
res = false;
}
break;
}
default:
break;
}
}
}
return res;
}
void LLDockControl::moveDockable()
{
// calculate new dockable position
LLRect dockRect = mDockWidget->calcScreenRect();
LLRect rootRect;
mGetAllowedRectCallback(rootRect);
bool use_tongue = false;
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if (dockable_floater != NULL)
{
use_tongue = dockable_floater->getUseTongue();
}
LLRect dockableRect = mDockableFloater->calcScreenRect();
S32 x = 0;
S32 y = 0;
LLRect dockParentRect;
switch (mDockAt)
{
case LEFT:
x = dockRect.mLeft;
y = dockRect.mTop + mDockTongue->getHeight() + dockableRect.getHeight();
// check is dockable inside root view rect
if (x < rootRect.mLeft)
{
x = rootRect.mLeft;
}
if (x + dockableRect.getWidth() > rootRect.mRight)
{
x = rootRect.mRight - dockableRect.getWidth();
}
mDockTongueX = x + dockableRect.getWidth()/2 - mDockTongue->getWidth() / 2;
mDockTongueY = dockRect.mTop;
break;
case TOP:
x = dockRect.getCenterX() - dockableRect.getWidth() / 2;
y = dockRect.mTop + dockableRect.getHeight();
// unique docking used with dock tongue, so add tongue height to the Y coordinate
if (use_tongue)
{
y += mDockTongue->getHeight();
if ( y > rootRect.mTop)
{
y = rootRect.mTop;
}
}
// check is dockable inside root view rect
if (x < rootRect.mLeft)
{
x = rootRect.mLeft;
}
if (x + dockableRect.getWidth() > rootRect.mRight)
{
x = rootRect.mRight - dockableRect.getWidth();
}
// calculate dock tongue position
dockParentRect = mDockWidget->getParent()->calcScreenRect();
if (dockRect.getCenterX() < dockParentRect.mLeft)
{
mDockTongueX = dockParentRect.mLeft - mDockTongue->getWidth() / 2;
}
else if (dockRect.getCenterX() > dockParentRect.mRight)
{
mDockTongueX = dockParentRect.mRight - mDockTongue->getWidth() / 2;;
}
else
{
mDockTongueX = dockRect.getCenterX() - mDockTongue->getWidth() / 2;
}
mDockTongueY = dockRect.mTop;
break;
case BOTTOM:
x = dockRect.getCenterX() - dockableRect.getWidth() / 2;
y = dockRect.mBottom;
// unique docking used with dock tongue, so add tongue height to the Y coordinate
if (use_tongue)
{
y -= mDockTongue->getHeight();
}
// check is dockable inside root view rect
if (x < rootRect.mLeft)
{
x = rootRect.mLeft;
}
if (x + dockableRect.getWidth() > rootRect.mRight)
{
x = rootRect.mRight - dockableRect.getWidth();
}
// calculate dock tongue position
dockParentRect = mDockWidget->getParent()->calcScreenRect();
if (dockRect.getCenterX() < dockParentRect.mLeft)
{
mDockTongueX = dockParentRect.mLeft - mDockTongue->getWidth() / 2;
}
else if (dockRect.getCenterX() > dockParentRect.mRight)
{
mDockTongueX = dockParentRect.mRight - mDockTongue->getWidth() / 2;;
}
else
{
mDockTongueX = dockRect.getCenterX() - mDockTongue->getWidth() / 2;
}
mDockTongueY = dockRect.mBottom - mDockTongue->getHeight();
break;
}
S32 max_available_height = rootRect.getHeight() - (rootRect.mBottom - mDockTongueY) - mDockTongue->getHeight();
// A floater should be shrunk so it doesn't cover a part of its docking tongue and
// there is a space between a dockable floater and a control to which it is docked.
if (use_tongue && dockableRect.getHeight() >= max_available_height)
{
dockableRect.setLeftTopAndSize(x, y, dockableRect.getWidth(), max_available_height);
mDockableFloater->reshape(dockableRect.getWidth(), dockableRect.getHeight());
}
else
{
// move dockable
dockableRect.setLeftTopAndSize(x, y, dockableRect.getWidth(),
dockableRect.getHeight());
}
LLRect localDocableParentRect;
mDockableFloater->getParent()->screenRectToLocal(dockableRect,
&localDocableParentRect);
mDockableFloater->setRect(localDocableParentRect);
mDockableFloater->screenPointToLocal(mDockTongueX, mDockTongueY,
&mDockTongueX, &mDockTongueY);
}
void LLDockControl::on()
{
if (isDockVisible())
{
mEnabled = true;
mRecalculateDocablePosition = true;
}
}
void LLDockControl::off()
{
mEnabled = false;
}
void LLDockControl::forceRecalculatePosition()
{
mRecalculateDocablePosition = true;
}
void LLDockControl::drawToungue()
{
bool use_tongue = false;
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if (dockable_floater != NULL)
{
use_tongue = dockable_floater->getUseTongue();
}
if (mEnabled && use_tongue)
{
mDockTongue->draw(mDockTongueX, mDockTongueY);
}
}
<commit_msg>Automated merge with ssh://hg.lindenlab.com/richard/viewer-experience-fui<commit_after>/**
* @file lldockcontrol.cpp
* @brief Creates a panel of a specific kind for a toast
*
* $LicenseInfo:firstyear=2000&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "lldockcontrol.h"
#include "lldockablefloater.h"
LLDockControl::LLDockControl(LLView* dockWidget, LLFloater* dockableFloater,
const LLUIImagePtr& dockTongue, DocAt dockAt, get_allowed_rect_callback_t get_allowed_rect_callback) :
mDockWidget(dockWidget),
mDockableFloater(dockableFloater),
mDockTongue(dockTongue),
mDockTongueX(0),
mDockTongueY(0)
{
mDockAt = dockAt;
if (dockableFloater->isDocked())
{
on();
}
else
{
off();
}
if (!(get_allowed_rect_callback))
{
mGetAllowedRectCallback = boost::bind(&LLDockControl::getAllowedRect, this, _1);
}
else
{
mGetAllowedRectCallback = get_allowed_rect_callback;
}
if (dockWidget != NULL)
{
repositionDockable();
}
if (mDockWidget != NULL)
{
mDockWidgetVisible = isDockVisible();
}
else
{
mDockWidgetVisible = false;
}
}
LLDockControl::~LLDockControl()
{
}
void LLDockControl::setDock(LLView* dockWidget)
{
mDockWidget = dockWidget;
if (mDockWidget != NULL)
{
repositionDockable();
mDockWidgetVisible = isDockVisible();
}
else
{
mDockWidgetVisible = false;
}
}
void LLDockControl::getAllowedRect(LLRect& rect)
{
rect = mDockableFloater->getRootView()->getRect();
}
void LLDockControl::repositionDockable()
{
if (!mDockWidget) return;
LLRect dockRect = mDockWidget->calcScreenRect();
LLRect rootRect;
mGetAllowedRectCallback(rootRect);
// recalculate dockable position if dock position changed, dock visibility changed,
// root view rect changed or recalculation is forced
if (mPrevDockRect != dockRect || mDockWidgetVisible != isDockVisible()
|| mRootRect != rootRect || mRecalculateDocablePosition)
{
// undock dockable and off() if dock not visible
if (!isDockVisible())
{
mDockableFloater->setDocked(false);
// force off() since dockable may not have dockControll at this time
off();
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if(dockable_floater != NULL)
{
dockable_floater->onDockHidden();
}
}
else
{
if(mEnabled)
{
moveDockable();
}
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if(dockable_floater != NULL)
{
dockable_floater->onDockShown();
}
}
mPrevDockRect = dockRect;
mRootRect = rootRect;
mRecalculateDocablePosition = false;
mDockWidgetVisible = isDockVisible();
}
}
bool LLDockControl::isDockVisible()
{
bool res = true;
if (mDockWidget != NULL)
{
//we should check all hierarchy
res = mDockWidget->isInVisibleChain();
if (res)
{
LLRect dockRect = mDockWidget->calcScreenRect();
switch (mDockAt)
{
case LEFT: // to keep compiler happy
break;
case BOTTOM:
case TOP:
{
// check is dock inside parent rect
// assume that parent for all dockable flaoters
// is the root view
LLRect dockParentRect =
mDockWidget->getRootView()->calcScreenRect();
if (dockRect.mRight <= dockParentRect.mLeft
|| dockRect.mLeft >= dockParentRect.mRight)
{
res = false;
}
break;
}
default:
break;
}
}
}
return res;
}
void LLDockControl::moveDockable()
{
// calculate new dockable position
LLRect dockRect = mDockWidget->calcScreenRect();
LLRect rootRect;
mGetAllowedRectCallback(rootRect);
bool use_tongue = false;
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if (dockable_floater != NULL)
{
use_tongue = dockable_floater->getUseTongue();
}
LLRect dockableRect = mDockableFloater->calcScreenRect();
S32 x = 0;
S32 y = 0;
LLRect dockParentRect;
switch (mDockAt)
{
case LEFT:
x = dockRect.mLeft;
y = dockRect.mTop + mDockTongue->getHeight() + dockableRect.getHeight();
// check is dockable inside root view rect
if (x < rootRect.mLeft)
{
x = rootRect.mLeft;
}
if (x + dockableRect.getWidth() > rootRect.mRight)
{
x = rootRect.mRight - dockableRect.getWidth();
}
mDockTongueX = x + dockableRect.getWidth()/2 - mDockTongue->getWidth() / 2;
mDockTongueY = dockRect.mTop;
break;
case TOP:
x = dockRect.getCenterX() - dockableRect.getWidth() / 2;
y = dockRect.mTop + dockableRect.getHeight();
// unique docking used with dock tongue, so add tongue height to the Y coordinate
if (use_tongue)
{
y += mDockTongue->getHeight();
if ( y > rootRect.mTop)
{
y = rootRect.mTop;
}
}
// check is dockable inside root view rect
if (x < rootRect.mLeft)
{
x = rootRect.mLeft;
}
if (x + dockableRect.getWidth() > rootRect.mRight)
{
x = rootRect.mRight - dockableRect.getWidth();
}
// calculate dock tongue position
dockParentRect = mDockWidget->getParent()->calcScreenRect();
if (dockRect.getCenterX() < dockParentRect.mLeft)
{
mDockTongueX = dockParentRect.mLeft - mDockTongue->getWidth() / 2;
}
else if (dockRect.getCenterX() > dockParentRect.mRight)
{
mDockTongueX = dockParentRect.mRight - mDockTongue->getWidth() / 2;;
}
else
{
mDockTongueX = dockRect.getCenterX() - mDockTongue->getWidth() / 2;
}
mDockTongueY = dockRect.mTop;
break;
case BOTTOM:
x = dockRect.getCenterX() - dockableRect.getWidth() / 2;
y = dockRect.mBottom;
// unique docking used with dock tongue, so add tongue height to the Y coordinate
if (use_tongue)
{
y -= mDockTongue->getHeight();
}
// check is dockable inside root view rect
if (x < rootRect.mLeft)
{
x = rootRect.mLeft;
}
if (x + dockableRect.getWidth() > rootRect.mRight)
{
x = rootRect.mRight - dockableRect.getWidth();
}
// calculate dock tongue position
dockParentRect = mDockWidget->getParent()->calcScreenRect();
if (dockRect.getCenterX() < dockParentRect.mLeft)
{
mDockTongueX = dockParentRect.mLeft - mDockTongue->getWidth() / 2;
}
else if (dockRect.getCenterX() > dockParentRect.mRight)
{
mDockTongueX = dockParentRect.mRight - mDockTongue->getWidth() / 2;;
}
else
{
mDockTongueX = dockRect.getCenterX() - mDockTongue->getWidth() / 2;
}
mDockTongueY = dockRect.mBottom - mDockTongue->getHeight();
break;
}
S32 max_available_height = rootRect.getHeight() - (rootRect.mBottom - mDockTongueY) - mDockTongue->getHeight();
// A floater should be shrunk so it doesn't cover a part of its docking tongue and
// there is a space between a dockable floater and a control to which it is docked.
if (use_tongue && dockableRect.getHeight() >= max_available_height)
{
dockableRect.setLeftTopAndSize(x, y, dockableRect.getWidth(), max_available_height);
mDockableFloater->reshape(dockableRect.getWidth(), dockableRect.getHeight());
}
else
{
// move dockable
dockableRect.setLeftTopAndSize(x, y, dockableRect.getWidth(),
dockableRect.getHeight());
}
LLRect localDocableParentRect;
mDockableFloater->getParent()->screenRectToLocal(dockableRect,
&localDocableParentRect);
mDockableFloater->setRect(localDocableParentRect);
mDockableFloater->screenPointToLocal(mDockTongueX, mDockTongueY,
&mDockTongueX, &mDockTongueY);
}
void LLDockControl::on()
{
if (isDockVisible())
{
mEnabled = true;
mRecalculateDocablePosition = true;
}
}
void LLDockControl::off()
{
mEnabled = false;
}
void LLDockControl::forceRecalculatePosition()
{
mRecalculateDocablePosition = true;
}
void LLDockControl::drawToungue()
{
bool use_tongue = false;
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if (dockable_floater != NULL)
{
use_tongue = dockable_floater->getUseTongue();
}
if (mEnabled && use_tongue)
{
mDockTongue->draw(mDockTongueX, mDockTongueY);
}
}
<|endoftext|> |
<commit_before>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2021, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <gtest/gtest.h>
#include <mrpt/core/Clock.h>
#include <chrono>
#include <thread>
static void test_delay()
{
const double t0 = mrpt::Clock::nowDouble();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
const double t1 = mrpt::Clock::nowDouble();
EXPECT_GT(t1 - t0, 0.008); // ideally, near 0.010
EXPECT_LT(t1 - t0, 5.0); // just detect it's not a crazy number
}
TEST(clock, delay_Realtime)
{
// Default:
test_delay();
// Monotonic:
mrpt::Clock::setActiveClock(mrpt::Clock::Source::Monotonic);
test_delay();
// mono->rt offset:
const uint64_t d1 = mrpt::Clock::getMonotonicToRealtimeOffset();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
mrpt::Clock::resetMonotonicToRealTimeEpoch();
const uint64_t d2 = mrpt::Clock::getMonotonicToRealtimeOffset();
EXPECT_GT(d1, d2);
// Realtime:
mrpt::Clock::setActiveClock(mrpt::Clock::Source::Realtime);
test_delay();
}
TEST(clock, changeSource)
{
const double t0 = mrpt::Clock::nowDouble();
mrpt::Clock::setActiveClock(mrpt::Clock::Source::Monotonic);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
const double t1 = mrpt::Clock::nowDouble();
mrpt::Clock::setActiveClock(mrpt::Clock::Source::Realtime);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
const double t2 = mrpt::Clock::nowDouble();
EXPECT_GT(t1 - t0, 0.008); // ideally, near 0.010
EXPECT_LT(t1 - t0, 5.0); // just detect it's not a crazy number
EXPECT_GT(t2 - t1, 0.008); // ideally, near 0.010
EXPECT_LT(t2 - t1, 5.0); // just detect it's not a crazy number
}
TEST(clock, checkSynchEpoch)
{
for (int i = 0; i < 20; i++)
{
std::this_thread::sleep_for(std::chrono::milliseconds(5));
const int64_t err = mrpt::Clock::resetMonotonicToRealTimeEpoch();
// it should be a really small number in a regular computer,
// but we set the threshold much higher due to spurious errors
// when running unit tests in VMs (build farms)
EXPECT_LT(std::abs(err), 70000);
}
}
TEST(clock, simulatedTime)
{
const auto t0 = mrpt::Clock::now();
const auto prevSrc = mrpt::Clock::getActiveClock();
// Enable simulated time:
mrpt::Clock::setActiveClock(mrpt::Clock::Simulated);
// Check that time is stopped:
mrpt::Clock::setSimulatedTime(t0);
const auto t1 = mrpt::Clock::now();
EXPECT_EQ(t0, t1);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
const auto t2 = mrpt::Clock::now();
EXPECT_EQ(t0, t2);
// Check time moving forward:
auto tset2 = t0 + std::chrono::milliseconds(1000);
mrpt::Clock::setSimulatedTime(tset2);
const auto t3 = mrpt::Clock::now();
EXPECT_EQ(tset2, t3);
// Restore
mrpt::Clock::setActiveClock(prevSrc);
}
<commit_msg>avoid problematic test<commit_after>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2021, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <gtest/gtest.h>
#include <mrpt/core/Clock.h>
#include <chrono>
#include <thread>
static void test_delay()
{
const double t0 = mrpt::Clock::nowDouble();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
const double t1 = mrpt::Clock::nowDouble();
EXPECT_GT(t1 - t0, 0.008); // ideally, near 0.010
EXPECT_LT(t1 - t0, 5.0); // just detect it's not a crazy number
}
TEST(clock, delay_Realtime)
{
// Default:
test_delay();
// Monotonic:
mrpt::Clock::setActiveClock(mrpt::Clock::Source::Monotonic);
test_delay();
#if 0 // not repetitive results
// mono->rt offset:
const uint64_t d1 = mrpt::Clock::getMonotonicToRealtimeOffset();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
mrpt::Clock::resetMonotonicToRealTimeEpoch();
const uint64_t d2 = mrpt::Clock::getMonotonicToRealtimeOffset();
EXPECT_GT(d1, d2);
#endif
// Realtime:
mrpt::Clock::setActiveClock(mrpt::Clock::Source::Realtime);
test_delay();
}
TEST(clock, changeSource)
{
const double t0 = mrpt::Clock::nowDouble();
mrpt::Clock::setActiveClock(mrpt::Clock::Source::Monotonic);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
const double t1 = mrpt::Clock::nowDouble();
mrpt::Clock::setActiveClock(mrpt::Clock::Source::Realtime);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
const double t2 = mrpt::Clock::nowDouble();
EXPECT_GT(t1 - t0, 0.008); // ideally, near 0.010
EXPECT_LT(t1 - t0, 5.0); // just detect it's not a crazy number
EXPECT_GT(t2 - t1, 0.008); // ideally, near 0.010
EXPECT_LT(t2 - t1, 5.0); // just detect it's not a crazy number
}
TEST(clock, checkSynchEpoch)
{
for (int i = 0; i < 20; i++)
{
std::this_thread::sleep_for(std::chrono::milliseconds(5));
const int64_t err = mrpt::Clock::resetMonotonicToRealTimeEpoch();
// it should be a really small number in a regular computer,
// but we set the threshold much higher due to spurious errors
// when running unit tests in VMs (build farms)
EXPECT_LT(std::abs(err), 70000);
}
}
TEST(clock, simulatedTime)
{
const auto t0 = mrpt::Clock::now();
const auto prevSrc = mrpt::Clock::getActiveClock();
// Enable simulated time:
mrpt::Clock::setActiveClock(mrpt::Clock::Simulated);
// Check that time is stopped:
mrpt::Clock::setSimulatedTime(t0);
const auto t1 = mrpt::Clock::now();
EXPECT_EQ(t0, t1);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
const auto t2 = mrpt::Clock::now();
EXPECT_EQ(t0, t2);
// Check time moving forward:
auto tset2 = t0 + std::chrono::milliseconds(1000);
mrpt::Clock::setSimulatedTime(tset2);
const auto t3 = mrpt::Clock::now();
EXPECT_EQ(tset2, t3);
// Restore
mrpt::Clock::setActiveClock(prevSrc);
}
<|endoftext|> |
<commit_before><commit_msg>can resolve multiple links now<commit_after><|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File: Expression.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////
#ifndef NEKTAR_LIB_UTILITIES_EXPRESSION_HPP
#define NEKTAR_LIB_UTILITIES_EXPRESSION_HPP
#ifdef NEKTAR_USE_EXPRESSION_TEMPLATES
#include <boost/call_traits.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/type_traits/is_reference.hpp>
#include <boost/mpl/and.hpp>
#include <boost/static_assert.hpp>
#include <boost/mpl/assert.hpp>
#include <LibUtilities/ExpressionTemplates/Accumulator.hpp>
#include <LibUtilities/ExpressionTemplates/NullOp.hpp>
#include <algorithm>
namespace Nektar
{
template<typename DataType>
struct CreateFromMetadata
{
template<typename MetadataType>
static DataType Apply(const MetadataType&)
{
return DataType();
}
};
/// \brief An expression is an arbitrary combination of operations acting on arbitrary amountsw of data to
/// produce a result. The expressions stores the operations and data but does not evaluate it until requested.
///
/// \param PolicyType The type of expression.
template<typename PolicyType>
class Expression
{
public:
// The type of the data which will be the result of evaluating the expression.
typedef typename PolicyType::ResultType ResultType;
// The type of the unevaluated subexpressions or data.
typedef typename PolicyType::DataType DataType;
typedef typename PolicyType::MetadataType MetadataType;
typedef typename boost::remove_const<typename boost::remove_reference<DataType>::type >::type BaseDataType;
public:
/// This constructor allows temporaries. I can't find a way to prevent this
/// from happening without also preventing constant parameters, so this will
/// need to be a "don't do that" type warning.
template<typename T>
explicit Expression(const T& data) :
m_data(data),
m_metadata()
{
PolicyType::InitializeMetadata(m_data, m_metadata);
}
explicit Expression(BaseDataType& data) :
m_data(data),
m_metadata()
{
//using boost::mpl::and_;
//using boost::is_reference;
//using boost::is_same;
//using boost::is_const;
//BOOST_MPL_ASSERT( ( is_const<BaseDataType> ) );
PolicyType::InitializeMetadata(m_data, m_metadata);
}
//template<typename T>
//explicit Expression(const T& data) :
// m_data(data),
// m_metadata()
//{
// //BOOST_STATIC_ASSERT(0);
// using boost::mpl::and_;
// using boost::is_reference;
// using boost::is_same;
// BOOST_MPL_ASSERT_NOT( (and_<is_reference<DataType>, is_same<BaseDataType, T> >) );
// PolicyType::InitializeMetadata(m_data, m_metadata);
//}
Expression(const Expression<PolicyType>& rhs) :
m_data(rhs.m_data),
m_metadata(rhs.m_metadata)
{
}
~Expression() {}
ResultType Evaluate() const
{
ResultType result = CreateFromMetadata<ResultType>::Apply(m_metadata);
Evaluate(result);
return result;
}
void Evaluate(typename boost::call_traits<ResultType>::reference result) const
{
if( !PolicyType::ContainsReference(result, m_data) )
{
Accumulator<ResultType> accum(result);
PolicyType::Evaluate(accum, m_data);
}
else
{
ResultType temp(result);
Accumulator<ResultType> accum(temp);
PolicyType::Evaluate(accum, m_data);
result = temp;
}
}
void Evaluate(Accumulator<ResultType>& accum) const
{
Evaluate<BinaryNullOp>(accum);
}
template<template <typename, typename> class ParentOpType>
void Evaluate(Accumulator<ResultType>& accum) const
{
PolicyType::template Evaluate<ParentOpType>(accum, m_data);
}
template<template <typename> class ParentOpType>
void Evaluate(Accumulator<ResultType>& accum) const
{
PolicyType::template Evaluate<ParentOpType>(accum, m_data);
}
// template<template <typename, typename> class ParentOpType>
// void ApplyEqual(Accumulator<ResultType>& accum) const
// {
// PolicyType::template ApplyEqual<ParentOpType>(accum, m_data);
// }
const MetadataType& GetMetadata() const
{
return m_metadata;
}
void Print(std::ostream& os) const
{
PolicyType::Print(os, m_data);
}
typename boost::call_traits<DataType>::reference operator*()
{
return m_data;
}
typename boost::call_traits<DataType>::const_reference operator*() const
{
return m_data;
}
private:
Expression<PolicyType>& operator=(const Expression<PolicyType>& rhs);
DataType m_data;
MetadataType m_metadata;
};
template<typename DataType, typename PolicyType>
void Assign(DataType& result, const Expression<PolicyType>& expr)
{
expr.Evaluate(result);
}
}
#endif //NEKTAR_USE_EXPRESSION_TEMPLATES
#endif // NEKTAR_LIB_UTILITIES_EXPRESSION_HPP
/**
$Log: Expression.hpp,v $
Revision 1.20 2008/01/20 20:10:09 bnelson
*** empty log message ***
Revision 1.19 2008/01/07 04:58:59 bnelson
Changed binary expressions so the OpType is listed second instead of third.
Updates to Commutative and Associative traits so they work with expressions instead of data types.
Revision 1.18 2008/01/03 04:16:41 bnelson
Changed method name in the expression library from Apply to Evaluate.
Revision 1.17 2007/12/24 02:20:01 bnelson
Fixed an error with aliasing.
Revision 1.16 2007/12/19 06:00:06 bnelson
*** empty log message ***
Revision 1.15 2007/12/19 05:09:21 bnelson
First pass at detecting aliasing. Still need to test performance implications.
Revision 1.14 2007/11/13 18:07:25 bnelson
Added Assign helper function for those classes the user can't modfiy.
Revision 1.13 2007/10/04 03:48:54 bnelson
*** empty log message ***
Revision 1.12 2007/10/03 02:57:39 bnelson
Removed the restriction on passing temporaries to expressions.
Revision 1.11 2007/08/16 02:14:21 bnelson
Moved expression templates to the Nektar namespace.
Revision 1.10 2007/07/26 00:07:36 bnelson
Fixed linux compiler errors.
Revision 1.8 2007/07/20 00:36:05 bnelson
*** empty log message ***
Revision 1.7 2007/01/30 23:37:16 bnelson
*** empty log message ***
Revision 1.6 2007/01/16 17:37:55 bnelson
Wrapped everything with #ifdef NEKTAR_USE_EXPRESSION_TEMPLATES
Revision 1.5 2007/01/16 05:29:50 bnelson
Major improvements for expression templates.
Revision 1.4 2006/09/14 02:08:59 bnelson
Fixed gcc compile errors
Revision 1.3 2006/09/11 03:24:24 bnelson
Updated expression templates so they are all specializations of an Expression object, using policies to differentiate.
Revision 1.2 2006/08/28 02:39:53 bnelson
*** empty log message ***
Revision 1.1 2006/08/25 01:33:47 bnelson
no message
**/
<commit_msg>Added the beginnings of a method to count the temporaries created by an expression.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File: Expression.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////
#ifndef NEKTAR_LIB_UTILITIES_EXPRESSION_HPP
#define NEKTAR_LIB_UTILITIES_EXPRESSION_HPP
#ifdef NEKTAR_USE_EXPRESSION_TEMPLATES
#include <boost/call_traits.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/type_traits/is_reference.hpp>
#include <boost/mpl/and.hpp>
#include <boost/static_assert.hpp>
#include <boost/mpl/assert.hpp>
#include <LibUtilities/ExpressionTemplates/Accumulator.hpp>
#include <LibUtilities/ExpressionTemplates/NullOp.hpp>
#include <algorithm>
namespace Nektar
{
template<typename DataType>
struct CreateFromMetadata
{
template<typename MetadataType>
static DataType Apply(const MetadataType&)
{
return DataType();
}
};
/// \brief An expression is an arbitrary combination of operations acting on arbitrary amountsw of data to
/// produce a result. The expressions stores the operations and data but does not evaluate it until requested.
///
/// \param PolicyType The type of expression.
template<typename PolicyType>
class Expression
{
public:
// The type of the data which will be the result of evaluating the expression.
typedef typename PolicyType::ResultType ResultType;
// The type of the unevaluated subexpressions or data.
typedef typename PolicyType::DataType DataType;
typedef typename PolicyType::MetadataType MetadataType;
typedef typename boost::remove_const<typename boost::remove_reference<DataType>::type >::type BaseDataType;
public:
/// This constructor allows temporaries. I can't find a way to prevent this
/// from happening without also preventing constant parameters, so this will
/// need to be a "don't do that" type warning.
template<typename T>
explicit Expression(const T& data) :
m_data(data),
m_metadata()
{
PolicyType::InitializeMetadata(m_data, m_metadata);
}
explicit Expression(BaseDataType& data) :
m_data(data),
m_metadata()
{
//using boost::mpl::and_;
//using boost::is_reference;
//using boost::is_same;
//using boost::is_const;
//BOOST_MPL_ASSERT( ( is_const<BaseDataType> ) );
PolicyType::InitializeMetadata(m_data, m_metadata);
}
//template<typename T>
//explicit Expression(const T& data) :
// m_data(data),
// m_metadata()
//{
// //BOOST_STATIC_ASSERT(0);
// using boost::mpl::and_;
// using boost::is_reference;
// using boost::is_same;
// BOOST_MPL_ASSERT_NOT( (and_<is_reference<DataType>, is_same<BaseDataType, T> >) );
// PolicyType::InitializeMetadata(m_data, m_metadata);
//}
Expression(const Expression<PolicyType>& rhs) :
m_data(rhs.m_data),
m_metadata(rhs.m_metadata)
{
}
~Expression() {}
ResultType Evaluate() const
{
ResultType result = CreateFromMetadata<ResultType>::Apply(m_metadata);
Evaluate(result);
return result;
}
void Evaluate(typename boost::call_traits<ResultType>::reference result) const
{
if( !PolicyType::ContainsReference(result, m_data) )
{
Accumulator<ResultType> accum(result);
PolicyType::Evaluate(accum, m_data);
}
else
{
ResultType temp(result);
Accumulator<ResultType> accum(temp);
PolicyType::Evaluate(accum, m_data);
result = temp;
}
}
void Evaluate(Accumulator<ResultType>& accum) const
{
Evaluate<BinaryNullOp>(accum);
}
template<template <typename, typename> class ParentOpType>
void Evaluate(Accumulator<ResultType>& accum) const
{
PolicyType::template Evaluate<ParentOpType>(accum, m_data);
}
template<template <typename> class ParentOpType>
void Evaluate(Accumulator<ResultType>& accum) const
{
PolicyType::template Evaluate<ParentOpType>(accum, m_data);
}
const MetadataType& GetMetadata() const
{
return m_metadata;
}
void Print(std::ostream& os) const
{
PolicyType::Print(os, m_data);
}
typename boost::call_traits<DataType>::reference operator*()
{
return m_data;
}
typename boost::call_traits<DataType>::const_reference operator*() const
{
return m_data;
}
/// Utility Methods
unsigned int CountRequiredTemporaries() const
{
return CountRequiredTemporaries<BinaryNullOp>();
}
template<template <typename> class ParentOpType>
unsigned int CountRequiredTemporaries() const
{
return PolicyType::template CountRequiredTemporaries<ParentOpType>(m_data);
}
template<template <typename, typename> class ParentOpType>
unsigned int CountRequiredTemporaries() const
{
return PolicyType::template CountRequiredTemporaries<ParentOpType>(m_data);
}
private:
Expression<PolicyType>& operator=(const Expression<PolicyType>& rhs);
DataType m_data;
MetadataType m_metadata;
};
template<typename DataType, typename PolicyType>
void Assign(DataType& result, const Expression<PolicyType>& expr)
{
expr.Evaluate(result);
}
}
#endif //NEKTAR_USE_EXPRESSION_TEMPLATES
#endif // NEKTAR_LIB_UTILITIES_EXPRESSION_HPP
/**
$Log: Expression.hpp,v $
Revision 1.21 2008/01/22 03:15:21 bnelson
Added CreateFromMetadata.
Revision 1.20 2008/01/20 20:10:09 bnelson
*** empty log message ***
Revision 1.19 2008/01/07 04:58:59 bnelson
Changed binary expressions so the OpType is listed second instead of third.
Updates to Commutative and Associative traits so they work with expressions instead of data types.
Revision 1.18 2008/01/03 04:16:41 bnelson
Changed method name in the expression library from Apply to Evaluate.
Revision 1.17 2007/12/24 02:20:01 bnelson
Fixed an error with aliasing.
Revision 1.16 2007/12/19 06:00:06 bnelson
*** empty log message ***
Revision 1.15 2007/12/19 05:09:21 bnelson
First pass at detecting aliasing. Still need to test performance implications.
Revision 1.14 2007/11/13 18:07:25 bnelson
Added Assign helper function for those classes the user can't modfiy.
Revision 1.13 2007/10/04 03:48:54 bnelson
*** empty log message ***
Revision 1.12 2007/10/03 02:57:39 bnelson
Removed the restriction on passing temporaries to expressions.
Revision 1.11 2007/08/16 02:14:21 bnelson
Moved expression templates to the Nektar namespace.
Revision 1.10 2007/07/26 00:07:36 bnelson
Fixed linux compiler errors.
Revision 1.8 2007/07/20 00:36:05 bnelson
*** empty log message ***
Revision 1.7 2007/01/30 23:37:16 bnelson
*** empty log message ***
Revision 1.6 2007/01/16 17:37:55 bnelson
Wrapped everything with #ifdef NEKTAR_USE_EXPRESSION_TEMPLATES
Revision 1.5 2007/01/16 05:29:50 bnelson
Major improvements for expression templates.
Revision 1.4 2006/09/14 02:08:59 bnelson
Fixed gcc compile errors
Revision 1.3 2006/09/11 03:24:24 bnelson
Updated expression templates so they are all specializations of an Expression object, using policies to differentiate.
Revision 1.2 2006/08/28 02:39:53 bnelson
*** empty log message ***
Revision 1.1 2006/08/25 01:33:47 bnelson
no message
**/
<|endoftext|> |
<commit_before>#pragma once
#include "../geometry/point2d.hpp"
#include "../geometry/rect2d.hpp"
#include "../base/math.hpp"
struct MercatorBounds
{
static double minX;
static double maxX;
static double minY;
static double maxY;
inline static double ClampX(double d)
{
if (d < MercatorBounds::minX) return MercatorBounds::minX;
if (d > MercatorBounds::maxX) return MercatorBounds::maxX;
return d;
}
inline static double ClampY(double d)
{
if (d < MercatorBounds::minY) return MercatorBounds::minY;
if (d > MercatorBounds::maxY) return MercatorBounds::maxY;
return d;
}
inline static double YToLat(double y)
{
return my::RadToDeg(2.0 * atan(exp(my::DegToRad(y))) - math::pi / 2.0);
}
inline static double LatToY(double lat)
{
lat = my::clamp(lat, -86.0, 86.0);
double const res = my::RadToDeg(log(tan(my::DegToRad(45.0 + lat * 0.5))));
return my::clamp(res, -180.0, 180.0);
}
inline static double XToLon(double x)
{
return x;
}
inline static double LonToX(double lon)
{
return lon;
}
static double const degreeInMetres;
/// @name Get rect for center point (lon, lat) and dimensions in metres.
//@{
/// @return mercator rect.
static m2::RectD MetresToXY(double lon, double lat,
double lonMetresR, double latMetresR);
inline static m2::RectD MetresToXY(double lon, double lat, double metresR)
{
return MetresToXY(lon, lat, metresR, metresR);
}
//@}
inline static m2::RectD RectByCenterXYAndSizeInMeters(double centerX, double centerY,
double sizeX, double sizeY)
{
ASSERT_GREATER_OR_EQUAL(sizeX, 0, ());
ASSERT_GREATER_OR_EQUAL(sizeY, 0, ());
return MetresToXY(XToLon(centerX), YToLat(centerY), sizeX, sizeY);
}
inline static m2::RectD RectByCenterXYAndSizeInMeters(m2::PointD const & center, double size)
{
return RectByCenterXYAndSizeInMeters(center.x, center.y, size, size);
}
static double GetCellID2PointAbsEpsilon() { return 1.0E-4; }
};
<commit_msg>Add some functions for coordinates checking.<commit_after>#pragma once
#include "../geometry/point2d.hpp"
#include "../geometry/rect2d.hpp"
#include "../base/math.hpp"
struct MercatorBounds
{
static double minX;
static double maxX;
static double minY;
static double maxY;
inline static bool ValidLon(double d)
{
return my::between_s(-180.0, 180.0, d);
}
inline static bool ValidLat(double d)
{
return my::between_s(-90.0, 90.0, d);
}
inline static bool ValidX(double d)
{
return my::between_s(minX, maxX, d);
}
inline static bool ValidY(double d)
{
return my::between_s(minY, maxY, d);
}
inline static double ClampX(double d)
{
return my::clamp(d, minX, maxX);
}
inline static double ClampY(double d)
{
return my::clamp(d, minY, maxY);
}
inline static double YToLat(double y)
{
return my::RadToDeg(2.0 * atan(exp(my::DegToRad(y))) - math::pi / 2.0);
}
inline static double LatToY(double lat)
{
lat = my::clamp(lat, -86.0, 86.0);
double const res = my::RadToDeg(log(tan(my::DegToRad(45.0 + lat * 0.5))));
return my::clamp(res, -180.0, 180.0);
}
inline static double XToLon(double x)
{
return x;
}
inline static double LonToX(double lon)
{
return lon;
}
static double const degreeInMetres;
/// @name Get rect for center point (lon, lat) and dimensions in metres.
//@{
/// @return mercator rect.
static m2::RectD MetresToXY(double lon, double lat,
double lonMetresR, double latMetresR);
inline static m2::RectD MetresToXY(double lon, double lat, double metresR)
{
return MetresToXY(lon, lat, metresR, metresR);
}
//@}
inline static m2::RectD RectByCenterXYAndSizeInMeters(double centerX, double centerY,
double sizeX, double sizeY)
{
ASSERT_GREATER_OR_EQUAL(sizeX, 0, ());
ASSERT_GREATER_OR_EQUAL(sizeY, 0, ());
return MetresToXY(XToLon(centerX), YToLat(centerY), sizeX, sizeY);
}
inline static m2::RectD RectByCenterXYAndSizeInMeters(m2::PointD const & center, double size)
{
return RectByCenterXYAndSizeInMeters(center.x, center.y, size, size);
}
static double GetCellID2PointAbsEpsilon() { return 1.0E-4; }
};
<|endoftext|> |
<commit_before>/*
* FUNCTION:
* Base class for SQL-backed persistent storage.
*
* HISTORY:
* Copyright (c) 2016 Linas Vepstas <[email protected]> except for
* MurmurHash2 written by Austin Appleby which is separately placed into
* the public domain.
*
* LICENSE:
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/base/Atom.h>
#include "OutgoingHash.h"
//-----------------------------------------------------------------------------
// MurmurHash2 was written by Austin Appleby, and is placed in the public
// domain. The author hereby disclaims copyright to this source code.
// Note - This code makes a few assumptions about how your machine behaves -
// 1. We can read a 4-byte value from any address without crashing
// 2. sizeof(int) == 4
// And it has a few limitations -
// 1. It will not work incrementally.
// 2. It will not produce the same results on little-endian and big-endian
// machines.
//-----------------------------------------------------------------------------
// MurmurHash2, 64-bit versions, by Austin Appleby
// The same caveats as 32-bit MurmurHash2 apply here - beware of alignment
// and endian-ness issues if used across multiple platforms.
// 64-bit hash for 64-bit platforms
#define BIG_CONSTANT(x) (x##LLU)
uint64_t MurmurHash64A ( const void * key, int len, uint64_t seed )
{
const uint64_t m = BIG_CONSTANT(0xc6a4a7935bd1e995);
const int r = 47;
uint64_t h = seed ^ (len * m);
const uint64_t * data = (const uint64_t *)key;
const uint64_t * end = data + (len/8);
while(data != end)
{
uint64_t k = *data++;
k *= m;
k ^= k >> r;
k *= m;
h ^= k;
h *= m;
}
const unsigned char * data2 = (const unsigned char*)data;
switch(len & 7)
{
case 7: h ^= uint64_t(data2[6]) << 48;
case 6: h ^= uint64_t(data2[5]) << 40;
case 5: h ^= uint64_t(data2[4]) << 32;
case 4: h ^= uint64_t(data2[3]) << 24;
case 3: h ^= uint64_t(data2[2]) << 16;
case 2: h ^= uint64_t(data2[1]) << 8;
case 1: h ^= uint64_t(data2[0]);
h *= m;
};
h ^= h >> r;
h *= m;
h ^= h >> r;
return h;
}
/*
* BEGIN PORTION:
* Copyright (c) 2016 Linas Vepstas <[email protected]> except for
* MurmurHash2 written by Austin Appleby which is separately placed into
* the public domain.
*/
using namespace opencog;
int64_t opencog::hash_outgoing(const HandleSeq& outgoing, uint64_t seed)
{
std::vector<UUID> uuids;
size_t handle_count = outgoing.size();
uint64_t hash;
// Reserve the full size.
uuids.reserve(handle_count);
// Now copy the UUIDs into the vector.
int position = 0;
for (auto handle : outgoing)
{
if (handle == NULL)
{
throw RuntimeException(TRACE_INFO, "Fatal Error: hash_outgoing - "
"NULL handle in outgoing set\n");
}
UUID uuid = TLB::addAtom(handle, Handle::INVALID_UUID);
uuids[position++] = uuid;
}
// Hash the vector in place.
hash = MurmurHash64A(uuids.data(), handle_count * sizeof(UUID), seed);
// Return the hash type-casted to be compatible with PostgreSQL's BIGINT
// which is signed.
return (int64_t) hash;
}
<commit_msg>Ooops, missed a spot<commit_after>/*
* FUNCTION:
* Base class for SQL-backed persistent storage.
*
* HISTORY:
* Copyright (c) 2016 Linas Vepstas <[email protected]> except for
* MurmurHash2 written by Austin Appleby which is separately placed into
* the public domain.
*
* LICENSE:
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/base/Atom.h>
#include "OutgoingHash.h"
//-----------------------------------------------------------------------------
// MurmurHash2 was written by Austin Appleby, and is placed in the public
// domain. The author hereby disclaims copyright to this source code.
// Note - This code makes a few assumptions about how your machine behaves -
// 1. We can read a 4-byte value from any address without crashing
// 2. sizeof(int) == 4
// And it has a few limitations -
// 1. It will not work incrementally.
// 2. It will not produce the same results on little-endian and big-endian
// machines.
//-----------------------------------------------------------------------------
// MurmurHash2, 64-bit versions, by Austin Appleby
// The same caveats as 32-bit MurmurHash2 apply here - beware of alignment
// and endian-ness issues if used across multiple platforms.
// 64-bit hash for 64-bit platforms
#define BIG_CONSTANT(x) (x##LLU)
uint64_t MurmurHash64A ( const void * key, int len, uint64_t seed )
{
const uint64_t m = BIG_CONSTANT(0xc6a4a7935bd1e995);
const int r = 47;
uint64_t h = seed ^ (len * m);
const uint64_t * data = (const uint64_t *)key;
const uint64_t * end = data + (len/8);
while(data != end)
{
uint64_t k = *data++;
k *= m;
k ^= k >> r;
k *= m;
h ^= k;
h *= m;
}
const unsigned char * data2 = (const unsigned char*)data;
switch(len & 7)
{
case 7: h ^= uint64_t(data2[6]) << 48;
case 6: h ^= uint64_t(data2[5]) << 40;
case 5: h ^= uint64_t(data2[4]) << 32;
case 4: h ^= uint64_t(data2[3]) << 24;
case 3: h ^= uint64_t(data2[2]) << 16;
case 2: h ^= uint64_t(data2[1]) << 8;
case 1: h ^= uint64_t(data2[0]);
h *= m;
};
h ^= h >> r;
h *= m;
h ^= h >> r;
return h;
}
/*
* BEGIN PORTION:
* Copyright (c) 2016 Linas Vepstas <[email protected]> except for
* MurmurHash2 written by Austin Appleby which is separately placed into
* the public domain.
*/
using namespace opencog;
int64_t opencog::hash_outgoing(const HandleSeq& outgoing, uint64_t seed)
{
std::vector<UUID> uuids;
size_t handle_count = outgoing.size();
uint64_t hash;
// Reserve the full size.
uuids.reserve(handle_count);
// Now copy the UUIDs into the vector.
int position = 0;
for (auto handle : outgoing)
{
if (handle == NULL)
{
throw RuntimeException(TRACE_INFO, "Fatal Error: hash_outgoing - "
"NULL handle in outgoing set\n");
}
UUID uuid = TLB::addAtom(handle, TLB::INVALID_UUID);
uuids[position++] = uuid;
}
// Hash the vector in place.
hash = MurmurHash64A(uuids.data(), handle_count * sizeof(UUID), seed);
// Return the hash type-casted to be compatible with PostgreSQL's BIGINT
// which is signed.
return (int64_t) hash;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2017, EPL-Vizards
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the EPL-Vizards nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL EPL-Vizards BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
* \file CyCoTreeItem.cpp
*/
#include "CyCoTreeItem.hpp"
#include "EPLEnum2Str.hpp"
using namespace EPL_DataCollect;
using namespace EPL_Viz;
using namespace std::chrono;
CyCoTreeItem::CyCoTreeItem(TreeModelItemBase *parent, ProtectedCycle &cycle, size_t packetIndexs)
: TreeModelItemBase(parent), c(cycle), pIndex(packetIndexs) {}
CyCoTreeItem::~CyCoTreeItem() {}
Qt::ItemFlags CyCoTreeItem::flags() { return Qt::ItemIsEnabled; }
bool CyCoTreeItem::hasChanged() { return false; }
QVariant CyCoTreeItem::dataDisplay(int column) {
auto lock = c.getLock();
if (pIndex >= c->getPackets().size())
return QVariant();
Packet & packet = c->getPackets().at(pIndex);
system_clock::time_point SoC = c->getPackets().at(0).getTimeStamp();
system_clock::time_point last;
if (pIndex == 0) {
last = SoC;
} else {
last = c->getPackets().at(pIndex - 1).getTimeStamp();
}
switch (column) {
case 0: // TYPE
return QVariant(EPLEnum2Str::toStr(packet.getType()).c_str());
case 1: // SOURCE
return QVariant(static_cast<int>(packet.getSrcNode()));
case 2: // DEST
return QVariant(static_cast<int>(packet.getDestNode()));
case 3: // Relative SoC
return QVariant(std::to_string((packet.getTimeStamp() - SoC).count()).c_str());
case 4: // Relative lasts
return QVariant(std::to_string((packet.getTimeStamp() - last).count()).c_str());
default: return QVariant();
}
}
QVariant CyCoTreeItem::dataTooltip(int column) {
switch (column) {
case 0: // TYPE
return QVariant("The packet type of the current entry");
case 1: // SOURCE
return QVariant("The source of the current packet");
case 2: // DEST
return QVariant("The destination of the current packet");
case 3: // Relative SoC
return QVariant("The time passed since the last SoC");
case 4: // Relative lasts
return QVariant("The time passed since the last packet");
default: return QVariant();
}
}
QVariant CyCoTreeItem::data(int column, Qt::ItemDataRole role) {
if (role != Qt::DisplayRole)
return QVariant();
switch (role) {
case Qt::DisplayRole: return dataDisplay(column);
case Qt::ToolTipRole: return dataTooltip(column);
default: return QVariant();
}
}
<commit_msg>smal memory fix<commit_after>/* Copyright (c) 2017, EPL-Vizards
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the EPL-Vizards nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL EPL-Vizards BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
* \file CyCoTreeItem.cpp
*/
#include "CyCoTreeItem.hpp"
#include "EPLEnum2Str.hpp"
using namespace EPL_DataCollect;
using namespace EPL_Viz;
using namespace std::chrono;
CyCoTreeItem::CyCoTreeItem(TreeModelItemBase *parent, ProtectedCycle &cycle, size_t packetIndexs)
: TreeModelItemBase(parent), c(cycle), pIndex(packetIndexs) {}
CyCoTreeItem::~CyCoTreeItem() {}
Qt::ItemFlags CyCoTreeItem::flags() { return Qt::ItemIsEnabled; }
bool CyCoTreeItem::hasChanged() { return false; }
QVariant CyCoTreeItem::dataDisplay(int column) {
auto lock = c.getLock();
if (pIndex >= c->getPackets().size())
return QVariant();
Packet packet = c->getPackets().at(pIndex);
system_clock::time_point SoC = c->getPackets().at(0).getTimeStamp();
system_clock::time_point last;
if (pIndex == 0) {
last = SoC;
} else {
last = c->getPackets().at(pIndex - 1).getTimeStamp();
}
switch (column) {
case 0: // TYPE
return QVariant(EPLEnum2Str::toStr(packet.getType()).c_str());
case 1: // SOURCE
return QVariant(static_cast<int>(packet.getSrcNode()));
case 2: // DEST
return QVariant(static_cast<int>(packet.getDestNode()));
case 3: // Relative SoC
return QVariant(std::to_string((packet.getTimeStamp() - SoC).count()).c_str());
case 4: // Relative lasts
return QVariant(std::to_string((packet.getTimeStamp() - last).count()).c_str());
default: return QVariant();
}
}
QVariant CyCoTreeItem::dataTooltip(int column) {
switch (column) {
case 0: // TYPE
return QVariant("The packet type of the current entry");
case 1: // SOURCE
return QVariant("The source of the current packet");
case 2: // DEST
return QVariant("The destination of the current packet");
case 3: // Relative SoC
return QVariant("The time passed since the last SoC");
case 4: // Relative lasts
return QVariant("The time passed since the last packet");
default: return QVariant();
}
}
QVariant CyCoTreeItem::data(int column, Qt::ItemDataRole role) {
if (role != Qt::DisplayRole)
return QVariant();
switch (role) {
case Qt::DisplayRole: return dataDisplay(column);
case Qt::ToolTipRole: return dataTooltip(column);
default: return QVariant();
}
}
<|endoftext|> |
<commit_before>
// STL includes
#include <cstring>
#include <cstdio>
#include <iostream>
#include <cerrno>
// Linux includes
#include <fcntl.h>
#include <sys/ioctl.h>
// Local Hyperion includes
#include "ProviderSpi.h"
#include <utils/Logger.h>
ProviderSpi::ProviderSpi(const Json::Value &deviceConfig)
: LedDevice()
, _fid(-1)
{
setConfig(deviceConfig);
memset(&_spi, 0, sizeof(_spi));
Debug(_log, "_spiDataInvert %d, _spiMode %d", _spiDataInvert, _spiMode);
}
ProviderSpi::~ProviderSpi()
{
// close(_fid);
}
bool ProviderSpi::setConfig(const Json::Value &deviceConfig)
{
_deviceName = deviceConfig.get("output","/dev/spidev0.0").asString();
_baudRate_Hz = deviceConfig.get("rate",1000000).asInt();
_latchTime_ns = deviceConfig.get("latchtime",0).asInt();
_spiMode = deviceConfig.get("spimode",SPI_MODE_0).asInt();
_spiDataInvert = deviceConfig.get("invert",false).asBool();
return true;
}
int ProviderSpi::open()
{
const int bitsPerWord = 8;
_fid = ::open(_deviceName.c_str(), O_RDWR);
if (_fid < 0)
{
Error( _log, "Failed to open device (%s). Error message: %s", _deviceName.c_str(), strerror(errno) );
return -1;
}
if (ioctl(_fid, SPI_IOC_WR_MODE, &_spiMode) == -1 || ioctl(_fid, SPI_IOC_RD_MODE, &_spiMode) == -1)
{
return -2;
}
if (ioctl(_fid, SPI_IOC_WR_BITS_PER_WORD, &bitsPerWord) == -1 || ioctl(_fid, SPI_IOC_RD_BITS_PER_WORD, &bitsPerWord) == -1)
{
return -4;
}
if (ioctl(_fid, SPI_IOC_WR_MAX_SPEED_HZ, &_baudRate_Hz) == -1 || ioctl(_fid, SPI_IOC_RD_MAX_SPEED_HZ, &_baudRate_Hz) == -1)
{
return -6;
}
return 0;
}
int ProviderSpi::writeBytes(const unsigned size, const uint8_t * data)
{
if (_fid < 0)
{
return -1;
}
_spi.tx_buf = __u64(data);
_spi.len = __u32(size);
if (_spiDataInvert)
{
uint8_t * newdata = (uint8_t *)malloc(size);
for (unsigned i = 0; i<size; i++) {
newdata[i] = data[i] ^ 0xff;
}
_spi.tx_buf = __u64(newdata);
}
int retVal = ioctl(_fid, SPI_IOC_MESSAGE(1), &_spi);
if (retVal == 0 && _latchTime_ns > 0)
{
// The 'latch' time for latching the shifted-value into the leds
timespec latchTime;
latchTime.tv_sec = 0;
latchTime.tv_nsec = _latchTime_ns;
// Sleep to latch the leds (only if write succesfull)
nanosleep(&latchTime, NULL);
}
return retVal;
}
<commit_msg>Added debug logging to ProviderSpi.cpp on writes. If you have more leds configured than the SPI buffer can support you now get this: [HYPERIOND LedDevice] <DEBUG> <ProviderSpi.cpp:92:writeBytes()> SPI failed to write. errno: 90, Message too long<commit_after>
// STL includes
#include <cstring>
#include <cstdio>
#include <iostream>
#include <cerrno>
// Linux includes
#include <fcntl.h>
#include <sys/ioctl.h>
// Local Hyperion includes
#include "ProviderSpi.h"
#include <utils/Logger.h>
ProviderSpi::ProviderSpi(const Json::Value &deviceConfig)
: LedDevice()
, _fid(-1)
{
setConfig(deviceConfig);
memset(&_spi, 0, sizeof(_spi));
Debug(_log, "_spiDataInvert %d, _spiMode %d", _spiDataInvert, _spiMode);
}
ProviderSpi::~ProviderSpi()
{
// close(_fid);
}
bool ProviderSpi::setConfig(const Json::Value &deviceConfig)
{
_deviceName = deviceConfig.get("output","/dev/spidev0.0").asString();
_baudRate_Hz = deviceConfig.get("rate",1000000).asInt();
_latchTime_ns = deviceConfig.get("latchtime",0).asInt();
_spiMode = deviceConfig.get("spimode",SPI_MODE_0).asInt();
_spiDataInvert = deviceConfig.get("invert",false).asBool();
return true;
}
int ProviderSpi::open()
{
const int bitsPerWord = 8;
_fid = ::open(_deviceName.c_str(), O_RDWR);
if (_fid < 0)
{
Error( _log, "Failed to open device (%s). Error message: %s", _deviceName.c_str(), strerror(errno) );
return -1;
}
if (ioctl(_fid, SPI_IOC_WR_MODE, &_spiMode) == -1 || ioctl(_fid, SPI_IOC_RD_MODE, &_spiMode) == -1)
{
return -2;
}
if (ioctl(_fid, SPI_IOC_WR_BITS_PER_WORD, &bitsPerWord) == -1 || ioctl(_fid, SPI_IOC_RD_BITS_PER_WORD, &bitsPerWord) == -1)
{
return -4;
}
if (ioctl(_fid, SPI_IOC_WR_MAX_SPEED_HZ, &_baudRate_Hz) == -1 || ioctl(_fid, SPI_IOC_RD_MAX_SPEED_HZ, &_baudRate_Hz) == -1)
{
return -6;
}
return 0;
}
int ProviderSpi::writeBytes(const unsigned size, const uint8_t * data)
{
if (_fid < 0)
{
return -1;
}
_spi.tx_buf = __u64(data);
_spi.len = __u32(size);
if (_spiDataInvert)
{
uint8_t * newdata = (uint8_t *)malloc(size);
for (unsigned i = 0; i<size; i++) {
newdata[i] = data[i] ^ 0xff;
}
_spi.tx_buf = __u64(newdata);
}
int retVal = ioctl(_fid, SPI_IOC_MESSAGE(1), &_spi);
DebugIf((retVal < 0), _log, "SPI failed to write. errno: %d, %s", errno, strerror(errno) );
if (retVal == 0 && _latchTime_ns > 0)
{
// The 'latch' time for latching the shifted-value into the leds
timespec latchTime;
latchTime.tv_sec = 0;
latchTime.tv_nsec = _latchTime_ns;
// Sleep to latch the leds (only if write succesfull)
nanosleep(&latchTime, NULL);
}
return retVal;
}
<|endoftext|> |
<commit_before><commit_msg>Made the horizontal move of parallax more reasonable<commit_after><|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <cstddef>
#include <type_traits>
#include <cassert>
// typedef decltype(nullptr) nullptr_t;
struct A
{
A(std::nullptr_t) {}
};
int main()
{
static_assert(sizeof(std::nullptr_t) == sizeof(void*),
"sizeof(std::nullptr_t) == sizeof(void*)");
A* p = 0;
assert(p == nullptr);
void (A::*pmf)() = 0;
#ifdef __clang__
// GCC 4.2 can't handle this
assert(pmf == nullptr);
#endif
int A::*pmd = 0;
assert(pmd == nullptr);
A a1(nullptr);
A a2(0);
bool b = nullptr;
assert(!b);
assert(nullptr == nullptr);
assert(nullptr <= nullptr);
assert(nullptr >= nullptr);
assert(!(nullptr != nullptr));
assert(!(nullptr < nullptr));
assert(!(nullptr > nullptr));
}
<commit_msg>patch by Jesse Towner, and bug fix by Sebastian Redl<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <cstddef>
#include <type_traits>
#include <cassert>
// typedef decltype(nullptr) nullptr_t;
struct A
{
A(std::nullptr_t) {}
};
int main()
{
static_assert(sizeof(std::nullptr_t) == sizeof(void*),
"sizeof(std::nullptr_t) == sizeof(void*)");
A* p = 0;
assert(p == nullptr);
assert(nullptr == p);
#if !((__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ <= 5))
// GCC 4.2 through 4.5 can't handle this
void (A::*pmf)() = 0;
assert(pmf == nullptr);
#endif
int A::*pmd = 0;
assert(pmd == nullptr);
A a1(nullptr);
A a2(0);
bool b = nullptr;
assert(!b);
assert(nullptr == nullptr);
assert(nullptr <= nullptr);
assert(nullptr >= nullptr);
assert(!(nullptr != nullptr));
assert(!(nullptr < nullptr));
assert(!(nullptr > nullptr));
assert(!(&a1 == nullptr));
assert(!(nullptr == &a1));
assert(&a1 != nullptr);
assert(nullptr != &a1);
assert(nullptr < &a1);
assert(nullptr <= &a1);
assert(!(nullptr < p));
assert(nullptr <= p);
assert(!(&a1 < nullptr));
assert(!(&a1 <= nullptr));
assert(!(p < nullptr));
assert(p <= nullptr);
assert(!(nullptr > &a1));
assert(!(nullptr >= &a1));
assert(!(nullptr > p));
assert(nullptr >= p);
}
<|endoftext|> |
<commit_before>#pragma once
#include <iostream>
#include "binary.hxx"
#include "bitnode.hxx"
namespace despairagus {
namespace bitwisetrieNS {
using std::cout;
using std::ostream;
using namespace bitnodeNS;
using namespace binaryNS;
template <typename A, typename B>
class bitwisetrie final {
template<typename C>
using conref = const C&;
using bitA = std::bitset<sizeof(A) << 3>;
using byte = unsigned char;
using bit = bool;
constexpr static const size_t limit{sizeof(A) << 3};
static inline bitnode<B>* navigate(bitnode<B>* currNode, conref<A> data) {
return bitwisetrie<A,B>::navigate(currNode, data, 0);
}
static inline bitnode<B>* navigate(bitnode<B>* currNode, conref<A> data, conref<size_t> idx) {
binary<A> bitHolder{data};
return bitwisetrie<A,B>::navigate(currNode, bitHolder, idx);
}
static bitnode<B>* navigate(bitnode<B>* currNode, conref<binary<A>> bits, conref<size_t> idx) {
if (idx < limit) {
if (bits.getBit(idx)) {
if (currNode->getOne() == nullptr) {
currNode->setOne(new bitnode<B>);
}
return bitwisetrie<A,B>::navigate(currNode->getOne(), bits, idx + 1);
} else {
if (currNode->getZero() == nullptr) {
currNode->setZero(new bitnode<B>);
}
return bitwisetrie<A,B>::navigate(currNode->getZero(), bits, idx + 1);
}
}
return currNode;
}
public:
explicit bitwisetrie(void) : root{new bitnode<B>} {}
template <typename... C>
explicit bitwisetrie(C...) = delete;
inline explicit operator bool (void) {
return this->root->isBarren();
}
template <typename C>
explicit operator C (void) = delete;
inline bool insertOnEmpty(conref<A> a, conref<B> b) noexcept {
bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);
if (leafNode->isEmpty()) {
leafNode->setData(b);
return true;
}
return false;
}
inline bool insertOnNotEmpty(conref<A> a, conref<B> b) noexcept {
bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);
if (leafNode->isNotEmpty()) {
leafNode->setData(b);
return true;
}
return false;
}
inline void insert(conref<A> a, conref<B> b) noexcept {
bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);
leafNode->setData(a);
}
inline bool remove(conref<A> a) noexcept {
bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);
if (leafNode->isNotEmpty()) {
leafNode->dump();
return true;
}
return false;
}
inline bool contains(conref<A> a) noexcept {
bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);
return leafNode->isNotEmpty();
}
inline bool notContains(conref<A> a) noexcept {
bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);
return leafNode->isEmpty();
}
private:
bitnode<B>* root;
};
}
}
<commit_msg>do not reimplement - use negation<commit_after>#pragma once
#include <iostream>
#include "binary.hxx"
#include "bitnode.hxx"
namespace despairagus {
namespace bitwisetrieNS {
using std::cout;
using std::ostream;
using namespace bitnodeNS;
using namespace binaryNS;
template <typename A, typename B>
class bitwisetrie final {
template<typename C>
using conref = const C&;
using bitA = std::bitset<sizeof(A) << 3>;
using byte = unsigned char;
using bit = bool;
constexpr static const size_t limit{sizeof(A) << 3};
static inline bitnode<B>* navigate(bitnode<B>* currNode, conref<A> data) {
return bitwisetrie<A,B>::navigate(currNode, data, 0);
}
static inline bitnode<B>* navigate(bitnode<B>* currNode, conref<A> data, conref<size_t> idx) {
binary<A> bitHolder{data};
return bitwisetrie<A,B>::navigate(currNode, bitHolder, idx);
}
static bitnode<B>* navigate(bitnode<B>* currNode, conref<binary<A>> bits, conref<size_t> idx) {
if (idx < limit) {
if (bits.getBit(idx)) {
if (currNode->getOne() == nullptr) {
currNode->setOne(new bitnode<B>);
}
return bitwisetrie<A,B>::navigate(currNode->getOne(), bits, idx + 1);
} else {
if (currNode->getZero() == nullptr) {
currNode->setZero(new bitnode<B>);
}
return bitwisetrie<A,B>::navigate(currNode->getZero(), bits, idx + 1);
}
}
return currNode;
}
public:
explicit bitwisetrie(void) : root{new bitnode<B>} {}
template <typename... C>
explicit bitwisetrie(C...) = delete;
inline explicit operator bool (void) {
return this->root->isBarren();
}
template <typename C>
explicit operator C (void) = delete;
inline bool insertOnEmpty(conref<A> a, conref<B> b) noexcept {
bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);
if (leafNode->isEmpty()) {
leafNode->setData(b);
return true;
}
return false;
}
inline bool insertOnNotEmpty(conref<A> a, conref<B> b) noexcept {
bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);
if (leafNode->isNotEmpty()) {
leafNode->setData(b);
return true;
}
return false;
}
inline void insert(conref<A> a, conref<B> b) noexcept {
bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);
leafNode->setData(a);
}
inline bool remove(conref<A> a) noexcept {
bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);
if (leafNode->isNotEmpty()) {
leafNode->dump();
return true;
}
return false;
}
inline bool contains(conref<A> a) noexcept {
bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);
return leafNode->isNotEmpty();
}
inline bool notContains(conref<A> a) noexcept {
return !this->contains(a);
}
private:
bitnode<B>* root;
};
}
}
<|endoftext|> |
<commit_before>#include "MifareClassic.h"
#define BLOCK_SIZE 16
#define MIFARE_CLASSIC ("Mifare Classic")
MifareClassic::MifareClassic(Adafruit_NFCShield_I2C& nfcShield)
{
_nfcShield = &nfcShield;
}
MifareClassic::~MifareClassic()
{
}
NfcTag MifareClassic::read(byte *uid, unsigned int uidLength)
{
uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 };
int currentBlock = 4;
int messageStartIndex = 0;
int messageLength = 0;
byte data[BLOCK_SIZE];
// read first block to get message length
int success = _nfcShield->mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
if (success)
{
success = _nfcShield->mifareclassic_ReadDataBlock(currentBlock, data);
if (success)
{
if (!decodeTlv(data, messageLength, messageStartIndex)) {
return NfcTag(uid, uidLength, "ERROR"); // TODO should the error message go in NfcTag?
}
}
else
{
Serial.print(F("Error. Failed read block "));Serial.println(currentBlock);
return NfcTag(uid, uidLength, MIFARE_CLASSIC);
}
}
else
{
Serial.print(F("Error. Block Authentication failed for "));Serial.println(currentBlock);
Serial.println(F("Tag is not NDEF formatted."));
// TODO set tag.isFormatted = false
return NfcTag(uid, uidLength, MIFARE_CLASSIC);
}
// this should be nested in the message length loop
int index = 0;
int bufferSize = getBufferSize(messageLength);
uint8_t buffer[bufferSize];
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Message Length "));Serial.println(messageLength);
Serial.print(F("Buffer Size "));Serial.println(bufferSize);
#endif
while (index < bufferSize)
{
// authenticate on every sector
if (_nfcShield->mifareclassic_IsFirstBlock(currentBlock))
{
success = _nfcShield->mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
if (!success)
{
Serial.print(F("Error. Block Authentication failed for "));Serial.println(currentBlock);
// TODO error handling
}
}
// read the data
success = _nfcShield->mifareclassic_ReadDataBlock(currentBlock, &buffer[index]);
if (success)
{
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Block "));Serial.print(currentBlock);Serial.print(" ");
_nfcShield->PrintHexChar(&buffer[index], BLOCK_SIZE);
#endif
}
else
{
Serial.print(F("Read failed "));Serial.println(currentBlock);
// TODO handle errors here
}
index += BLOCK_SIZE;
currentBlock++;
// skip the trailer block
if (_nfcShield->mifareclassic_IsTrailerBlock(currentBlock))
{
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Skipping block "));Serial.println(currentBlock);
#endif
currentBlock++;
}
}
return NfcTag(uid, uidLength, MIFARE_CLASSIC, &buffer[messageStartIndex], messageLength);
}
// TODO this needs to take into account the tlvStartIndex
int MifareClassic::getBufferSize(int messageLength)
{
// TLV header is 4 bytes. TLV terminator is 1 byte.
int bufferSize = messageLength + 5;
// bufferSize needs to be a multiple of BLOCK_SIZE
if (bufferSize % BLOCK_SIZE != 0)
{
bufferSize = ((bufferSize / BLOCK_SIZE) + 1) * BLOCK_SIZE;
}
return bufferSize;
}
// skip null tlvs (0x0) before the real message
// technically unlimited null tlvs, but we assume
// T & L of TLV in the first block we read
int MifareClassic::getNdefStartIndex(byte *data) {
for (int i = 0; i < BLOCK_SIZE; i++) {
if (data[i] == 0x0) {
// do nothing, skip
} else if (data[i] == 0x3) {
return i;
} else {
Serial.print("Unknown TLV ");Serial.println(data[i], HEX);
return -2;
}
}
return -1;
}
// Decode the NDEF data length from the Mifare TLV
// Leading null TLVs (0x0) are skipped
// Assuming T & L of TLV will be in the first block
// messageLength and messageStartIndex written to the parameters
// success or failure status is returned
//
// { 0x3, LENGTH }
// { 0x3, 0xFF, LENGTH, LENGTH }
bool MifareClassic::decodeTlv(byte *data, int &messageLength, int &messageStartIndex) {
int i = getNdefStartIndex(data);
int shortTlvSize = 2;
int longTlvSize = 4;
if (i < 0 || data[i] != 0x3) {
Serial.println(F("Error. Can't decode message length."));
return false;
} else {
if (data[i+1] == 0xFF) {
messageLength = ((0xFF & data[i+2]) << 8) | (0xFF & data[i+3]);
messageStartIndex = i + longTlvSize;
} else {
messageLength = data[i+1];
messageStartIndex = i + shortTlvSize;
}
}
return true;
}
boolean MifareClassic::write(NdefMessage& m, byte * uid, unsigned int uidLength)
{
uint8_t encoded[m.getEncodedSize()];
m.encode(encoded);
uint8_t buffer[getBufferSize(sizeof(encoded))];
memset(buffer, 0, sizeof(buffer));
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("sizeof(encoded) "));Serial.println(sizeof(encoded));
Serial.print(F("sizeof(buffer) "));Serial.println(sizeof(buffer));
#endif
buffer[1] = 0x3;
buffer[2] = sizeof(encoded);
memcpy(&buffer[3], encoded, sizeof(encoded));
buffer[2+sizeof(encoded)] = 0xFE; // terminator
// Write to tag
int index = 0;
int currentBlock = 4;
uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 }; // this is Sector 1 - 15 key
while (index < sizeof(buffer))
{
if (_nfcShield->mifareclassic_IsFirstBlock(currentBlock))
{
int success = _nfcShield->mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
if (!success)
{
Serial.print(F("Error. Block Authentication failed for "));Serial.println(currentBlock);
return false;
}
}
int write_success = _nfcShield->mifareclassic_WriteDataBlock (currentBlock, &buffer[index]);
if (write_success)
{
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Wrote block "));Serial.print(currentBlock);Serial.print(" - ");
_nfcShield->PrintHexChar(&buffer[index], BLOCK_SIZE);
#endif
}
else
{
Serial.print(F("Write failed "));Serial.println(currentBlock);
return false;
}
index += BLOCK_SIZE;
currentBlock++;
if (_nfcShield->mifareclassic_IsTrailerBlock(currentBlock))
{
// can't write to trailer block
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Skipping block "));Serial.println(currentBlock);
#endif
currentBlock++;
}
}
return true;
}<commit_msg>off by one<commit_after>#include "MifareClassic.h"
#define BLOCK_SIZE 16
#define MIFARE_CLASSIC ("Mifare Classic")
MifareClassic::MifareClassic(Adafruit_NFCShield_I2C& nfcShield)
{
_nfcShield = &nfcShield;
}
MifareClassic::~MifareClassic()
{
}
NfcTag MifareClassic::read(byte *uid, unsigned int uidLength)
{
uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 };
int currentBlock = 4;
int messageStartIndex = 0;
int messageLength = 0;
byte data[BLOCK_SIZE];
// read first block to get message length
int success = _nfcShield->mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
if (success)
{
success = _nfcShield->mifareclassic_ReadDataBlock(currentBlock, data);
if (success)
{
if (!decodeTlv(data, messageLength, messageStartIndex)) {
return NfcTag(uid, uidLength, "ERROR"); // TODO should the error message go in NfcTag?
}
}
else
{
Serial.print(F("Error. Failed read block "));Serial.println(currentBlock);
return NfcTag(uid, uidLength, MIFARE_CLASSIC);
}
}
else
{
Serial.print(F("Error. Block Authentication failed for "));Serial.println(currentBlock);
Serial.println(F("Tag is not NDEF formatted."));
// TODO set tag.isFormatted = false
return NfcTag(uid, uidLength, MIFARE_CLASSIC);
}
// this should be nested in the message length loop
int index = 0;
int bufferSize = getBufferSize(messageLength);
uint8_t buffer[bufferSize];
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Message Length "));Serial.println(messageLength);
Serial.print(F("Buffer Size "));Serial.println(bufferSize);
#endif
while (index < bufferSize)
{
// authenticate on every sector
if (_nfcShield->mifareclassic_IsFirstBlock(currentBlock))
{
success = _nfcShield->mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
if (!success)
{
Serial.print(F("Error. Block Authentication failed for "));Serial.println(currentBlock);
// TODO error handling
}
}
// read the data
success = _nfcShield->mifareclassic_ReadDataBlock(currentBlock, &buffer[index]);
if (success)
{
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Block "));Serial.print(currentBlock);Serial.print(" ");
_nfcShield->PrintHexChar(&buffer[index], BLOCK_SIZE);
#endif
}
else
{
Serial.print(F("Read failed "));Serial.println(currentBlock);
// TODO handle errors here
}
index += BLOCK_SIZE;
currentBlock++;
// skip the trailer block
if (_nfcShield->mifareclassic_IsTrailerBlock(currentBlock))
{
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Skipping block "));Serial.println(currentBlock);
#endif
currentBlock++;
}
}
return NfcTag(uid, uidLength, MIFARE_CLASSIC, &buffer[messageStartIndex], messageLength);
}
int MifareClassic::getBufferSize(int messageLength)
{
// TLV header is 2 bytes. TLV terminator is 1 byte.
int bufferSize = messageLength + 3;
// bufferSize needs to be a multiple of BLOCK_SIZE
if (bufferSize % BLOCK_SIZE != 0)
{
bufferSize = ((bufferSize / BLOCK_SIZE) + 1) * BLOCK_SIZE;
}
return bufferSize;
}
// skip null tlvs (0x0) before the real message
// technically unlimited null tlvs, but we assume
// T & L of TLV in the first block we read
int MifareClassic::getNdefStartIndex(byte *data) {
for (int i = 0; i < BLOCK_SIZE; i++) {
if (data[i] == 0x0) {
// do nothing, skip
} else if (data[i] == 0x3) {
return i;
} else {
Serial.print("Unknown TLV ");Serial.println(data[i], HEX);
return -2;
}
}
return -1;
}
// Decode the NDEF data length from the Mifare TLV
// Leading null TLVs (0x0) are skipped
// Assuming T & L of TLV will be in the first block
// messageLength and messageStartIndex written to the parameters
// success or failure status is returned
//
// { 0x3, LENGTH }
// { 0x3, 0xFF, LENGTH, LENGTH }
bool MifareClassic::decodeTlv(byte *data, int &messageLength, int &messageStartIndex) {
int i = getNdefStartIndex(data);
int shortTlvSize = 2;
int longTlvSize = 4;
if (i < 0 || data[i] != 0x3) {
Serial.println(F("Error. Can't decode message length."));
return false;
} else {
if (data[i+1] == 0xFF) {
messageLength = ((0xFF & data[i+2]) << 8) | (0xFF & data[i+3]);
messageStartIndex = i + longTlvSize;
} else {
messageLength = data[i+1];
messageStartIndex = i + shortTlvSize;
}
}
return true;
}
boolean MifareClassic::write(NdefMessage& m, byte * uid, unsigned int uidLength)
{
uint8_t encoded[m.getEncodedSize()];
m.encode(encoded);
uint8_t buffer[getBufferSize(sizeof(encoded))];
memset(buffer, 0, sizeof(buffer));
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("sizeof(encoded) "));Serial.println(sizeof(encoded));
Serial.print(F("sizeof(buffer) "));Serial.println(sizeof(buffer));
#endif
buffer[0] = 0x3;
buffer[1] = sizeof(encoded);
memcpy(&buffer[2], encoded, sizeof(encoded));
buffer[2+sizeof(encoded)] = 0xFE; // terminator
// Write to tag
int index = 0;
int currentBlock = 4;
uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 }; // this is Sector 1 - 15 key
while (index < sizeof(buffer))
{
if (_nfcShield->mifareclassic_IsFirstBlock(currentBlock))
{
int success = _nfcShield->mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
if (!success)
{
Serial.print(F("Error. Block Authentication failed for "));Serial.println(currentBlock);
return false;
}
}
int write_success = _nfcShield->mifareclassic_WriteDataBlock (currentBlock, &buffer[index]);
if (write_success)
{
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Wrote block "));Serial.print(currentBlock);Serial.print(" - ");
_nfcShield->PrintHexChar(&buffer[index], BLOCK_SIZE);
#endif
}
else
{
Serial.print(F("Write failed "));Serial.println(currentBlock);
return false;
}
index += BLOCK_SIZE;
currentBlock++;
if (_nfcShield->mifareclassic_IsTrailerBlock(currentBlock))
{
// can't write to trailer block
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Skipping block "));Serial.println(currentBlock);
#endif
currentBlock++;
}
}
return true;
}<|endoftext|> |
<commit_before>/*
* 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 Library 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.
*
* OpenDmxThread.h
* Thread for the open dmx device
* Copyright (C) 2005-2007 Simon Newton
*/
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <string>
#include "ola/BaseTypes.h"
#include "ola/Logging.h"
#include "plugins/opendmx/OpenDmxThread.h"
namespace ola {
namespace plugin {
namespace opendmx {
using std::string;
using ola::thread::Mutex;
using ola::thread::MutexLocker;
/*
* Create a new OpenDmxThread object
*/
OpenDmxThread::OpenDmxThread(const string &path)
: ola::thread::Thread(),
m_fd(INVALID_FD),
m_path(path),
m_term(false) {
}
/*
* Run this thread
*/
void *OpenDmxThread::Run() {
uint8_t buffer[DMX_UNIVERSE_SIZE+1];
unsigned int length = DMX_UNIVERSE_SIZE;
struct timeval tv;
struct timespec ts;
// should close other fd here
// start code
buffer[0] = 0x00;
m_fd = open(m_path.c_str(), O_WRONLY);
while (true) {
{
MutexLocker lock(&m_term_mutex);
if (m_term)
break;
}
if (m_fd == INVALID_FD) {
if (gettimeofday(&tv, NULL) < 0) {
OLA_WARN << "gettimeofday error";
break;
}
ts.tv_sec = tv.tv_sec + 1;
ts.tv_nsec = tv.tv_usec * 1000;
// wait for either a signal that we should terminate, or ts seconds
m_term_mutex.Lock();
if (m_term)
break;
m_term_cond.TimedWait(&m_term_mutex, &ts);
m_term_mutex.Unlock();
m_fd = open(m_path.c_str(), O_WRONLY);
if (m_fd == INVALID_FD)
OLA_WARN << "Open " << m_path << ": " << strerror(errno);
} else {
length = DMX_UNIVERSE_SIZE;
{
MutexLocker locker(&m_mutex);
m_buffer.Get(buffer + 1, &length);
}
if (write(m_fd, buffer, length + 1) < 0) {
// if you unplug the dongle
OLA_WARN << "Error writing to device: " << strerror(errno);
if (close(m_fd) < 0)
OLA_WARN << "Close failed " << strerror(errno);
m_fd = INVALID_FD;
}
}
}
return NULL;
}
/*
* Stop the thread
*/
bool OpenDmxThread::Stop() {
{
MutexLocker locker(&m_mutex);
m_term = true;
}
m_term_cond.Signal();
return Join();
}
/*
* Store the data in the shared buffer
*
*/
bool OpenDmxThread::WriteDmx(const DmxBuffer &buffer) {
MutexLocker locker(&m_mutex);
m_buffer = buffer;
return true;
}
} // opendmx
} // plugin
} // ola
<commit_msg> * avoid reference counting the output buffer<commit_after>/*
* 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 Library 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.
*
* OpenDmxThread.h
* Thread for the open dmx device
* Copyright (C) 2005-2007 Simon Newton
*/
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <string>
#include "ola/BaseTypes.h"
#include "ola/Logging.h"
#include "plugins/opendmx/OpenDmxThread.h"
namespace ola {
namespace plugin {
namespace opendmx {
using std::string;
using ola::thread::Mutex;
using ola::thread::MutexLocker;
/*
* Create a new OpenDmxThread object
*/
OpenDmxThread::OpenDmxThread(const string &path)
: ola::thread::Thread(),
m_fd(INVALID_FD),
m_path(path),
m_term(false) {
}
/*
* Run this thread
*/
void *OpenDmxThread::Run() {
uint8_t buffer[DMX_UNIVERSE_SIZE+1];
unsigned int length = DMX_UNIVERSE_SIZE;
struct timeval tv;
struct timespec ts;
// should close other fd here
// start code
buffer[0] = 0x00;
m_fd = open(m_path.c_str(), O_WRONLY);
while (true) {
{
MutexLocker lock(&m_term_mutex);
if (m_term)
break;
}
if (m_fd == INVALID_FD) {
if (gettimeofday(&tv, NULL) < 0) {
OLA_WARN << "gettimeofday error";
break;
}
ts.tv_sec = tv.tv_sec + 1;
ts.tv_nsec = tv.tv_usec * 1000;
// wait for either a signal that we should terminate, or ts seconds
m_term_mutex.Lock();
if (m_term)
break;
m_term_cond.TimedWait(&m_term_mutex, &ts);
m_term_mutex.Unlock();
m_fd = open(m_path.c_str(), O_WRONLY);
if (m_fd == INVALID_FD)
OLA_WARN << "Open " << m_path << ": " << strerror(errno);
} else {
length = DMX_UNIVERSE_SIZE;
{
MutexLocker locker(&m_mutex);
m_buffer.Get(buffer + 1, &length);
}
if (write(m_fd, buffer, length + 1) < 0) {
// if you unplug the dongle
OLA_WARN << "Error writing to device: " << strerror(errno);
if (close(m_fd) < 0)
OLA_WARN << "Close failed " << strerror(errno);
m_fd = INVALID_FD;
}
}
}
return NULL;
}
/*
* Stop the thread
*/
bool OpenDmxThread::Stop() {
{
MutexLocker locker(&m_mutex);
m_term = true;
}
m_term_cond.Signal();
return Join();
}
/*
* Store the data in the shared buffer
*
*/
bool OpenDmxThread::WriteDmx(const DmxBuffer &buffer) {
MutexLocker locker(&m_mutex);
// avoid the reference counting
m_buffer.Set(buffer);
return true;
}
} // opendmx
} // plugin
} // ola
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: salsys.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2003-04-15 16:08:33 $
*
* 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 <salsys.hxx>
#include <stacktrace.hxx>
#include <stdio.h>
#include <salunx.h>
#include <saldisp.hxx>
#include <dtint.hxx>
#include <msgbox.hxx>
#include <button.hxx>
#include <svdata.hxx>
// -----------------------------------------------------------------------
String GetSalSummarySystemInfos( ULONG nFlags )
{
sal_PostMortem aPostMortem;
/*
* unimplemented flags:
* SALSYSTEM_GETSYSTEMINFO_MODULES
* SALSYSTEM_GETSYSTEMINFO_MOUSEINFO
* SALSYSTEM_GETSYSTEMINFO_SYSTEMDIRS
* SALSYSTEM_GETSYSTEMINFO_LOCALVOLUMES
*/
ByteString aRet;
if( nFlags & SALSYSTEM_GETSYSTEMINFO_SYSTEMVERSION )
aRet += aPostMortem.getSystemInfo();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_CPUTYPE )
aRet += aPostMortem.getProcessorInfo();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_MEMORYINFO )
aRet += aPostMortem.getMemoryInfo();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_STACK )
aRet += aPostMortem.getStackTrace();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_GRAPHICSSYSTEM )
aRet += aPostMortem.getGraphicsSystem();
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "SalSystem::GetSummarySystemInfos() =\n%s", aRet.GetBuffer() );
#endif
return String( aRet, RTL_TEXTENCODING_ISO_8859_1 );
}
bool GetSalSystemDisplayInfo( System::DisplayInfo& rInfo )
{
bool bSuccess = false;
Display* pDisplay = XOpenDisplay( NULL );
if( pDisplay )
{
int nScreen = DefaultScreen( pDisplay );
XVisualInfo aVI;
/* note: SalDisplay::BestVisual does not
* access saldata or any other data available
* only after InitVCL; nor does SalOpenGL:MakeVisualWeights
* which gets called by SalDisplay::BestVisual.
* this is crucial since GetSalSystemDisplayInfo
* gets called BEFORE Init.
*/
SalDisplay::BestVisual( pDisplay, nScreen, aVI );
rInfo.nDepth = aVI.depth;
rInfo.nWidth = DisplayWidth( pDisplay, nScreen );
rInfo.nHeight = DisplayHeight( pDisplay, nScreen );
XCloseDisplay( pDisplay );
bSuccess = true;
}
return bSuccess;
}
int ImplShowNativeDialog( const String& rTitle, const String& rMessage, const std::list< String >& rButtons, int nDefButton )
{
int nRet = -1;
ImplSVData* pSVData = ImplGetSVData();
if( pSVData->mpIntroWindow )
pSVData->mpIntroWindow->Hide();
DtIntegrator* pIntegrator = DtIntegrator::CreateDtIntegrator( NULL );
if( pIntegrator->GetDtType() == DtGNOME )
{
ByteString aCmdLine( "msgbox-gnome ");
int nButton = 0;
for( std::list< String >::const_iterator it = rButtons.begin(); it != rButtons.end(); ++it )
{
if( nButton == nDefButton )
aCmdLine.Append( "-defaultbutton" );
else
aCmdLine.Append( "-button" );
nButton++;
aCmdLine.Append( " \"" );
aCmdLine.Append( ByteString( *it, RTL_TEXTENCODING_UTF8 ) );
aCmdLine.Append( "\" " );
}
aCmdLine.Append( " \"" );
aCmdLine.Append( ByteString( rTitle, RTL_TEXTENCODING_UTF8 ) );
aCmdLine.Append( "\" \"" );
aCmdLine.Append( ByteString( rMessage, RTL_TEXTENCODING_UTF8 ) );
aCmdLine.Append( "\" 2>/dev/null" );
FILE* fp = popen( aCmdLine.GetBuffer(), "r" );
if( fp )
{
ByteString aAnswer;
char buf[16];
while( fgets( buf, sizeof( buf ), fp ) )
{
aAnswer.Append( buf );
}
pclose( fp );
nRet = aAnswer.ToInt32();
}
}
else // default to a VCL dialogue since we do not have a native implementation
{
WarningBox aWarn( NULL, WB_STDWORK, rMessage );
aWarn.SetText( rTitle );
aWarn.Clear();
USHORT nButton = 0;
for( std::list< String >::const_iterator it = rButtons.begin(); it != rButtons.end(); ++it )
{
aWarn.AddButton( *it, nButton+1, nButton == (USHORT)nDefButton ? BUTTONDIALOG_DEFBUTTON : 0 );
nButton++;
}
aWarn.SetFocusButton( (USHORT)nDefButton+1 );
nRet = ((int)aWarn.Execute()) - 1;
}
// normalize behaviour, actually this should never happen
if( nRet < -1 || nRet >= rButtons.size() )
nRet = -1;
return nRet;
}
int ImplShowNativeMessageBox(const String& rTitle, const String& rMessage, int nButtonCombination, int nDefaultButton)
{
int nDefButton = 0;
std::list< String > aButtons;
int nButtonIds[5], nBut = 0;
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL )
{
aButtons.push_back( Button::GetStandardText( BUTTON_OK ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO )
{
aButtons.push_back( Button::GetStandardText( BUTTON_YES ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_YES;
aButtons.push_back( Button::GetStandardText( BUTTON_NO ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO;
if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO )
nDefButton = 1;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
{
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
{
aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
}
aButtons.push_back( Button::GetStandardText( BUTTON_CANCEL ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL;
if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL )
nDefButton = aButtons.size()-1;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_ABORT_RETRY_IGNORE )
{
aButtons.push_back( Button::GetStandardText( BUTTON_ABORT ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_ABORT;
aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
aButtons.push_back( Button::GetStandardText( BUTTON_IGNORE ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE;
switch( nDefaultButton )
{
case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY: nDefButton = 1;break;
case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE: nDefButton = 2;break;
}
}
int nResult = ImplShowNativeDialog( rTitle, rMessage, aButtons, nDefButton );
return nResult != -1 ? nButtonIds[ nResult ] : 0;
}
<commit_msg>INTEGRATION: CWS vclplug (1.7.172); FILE MERGED 2003/10/21 15:53:53 pl 1.7.172.1: #i21232# first round of virtualizing the Sal classes, Unix works, Windows to come<commit_after>/*************************************************************************
*
* $RCSfile: salsys.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: kz $ $Date: 2003-11-18 14:42: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 <stacktrace.hxx>
#include <salunx.h>
#include <salsys.hxx>
#include <dtint.hxx>
#include <msgbox.hxx>
#include <button.hxx>
#include <svdata.hxx>
#include <salinst.h>
#include <saldisp.hxx>
#include <cstdio>
class X11SalSystem : public SalSystem
{
public:
X11SalSystem() {}
virtual ~X11SalSystem();
// overload pure virtual methods
virtual String GetSalSummarySystemInfos( ULONG nFlags );
virtual bool GetSalSystemDisplayInfo( System::DisplayInfo& rInfo );
virtual int ShowNativeDialog( const String& rTitle,
const String& rMessage,
const std::list< String >& rButtons,
int nDefButton );
virtual int ShowNativeMessageBox( const String& rTitle,
const String& rMessage,
int nButtonCombination,
int nDefaultButton);
};
SalSystem* X11SalInstance::CreateSalSystem()
{
return new X11SalSystem();
}
// -----------------------------------------------------------------------
X11SalSystem::~X11SalSystem()
{
}
String X11SalSystem::GetSalSummarySystemInfos( ULONG nFlags )
{
sal_PostMortem aPostMortem;
/*
* unimplemented flags:
* SALSYSTEM_GETSYSTEMINFO_MODULES
* SALSYSTEM_GETSYSTEMINFO_MOUSEINFO
* SALSYSTEM_GETSYSTEMINFO_SYSTEMDIRS
* SALSYSTEM_GETSYSTEMINFO_LOCALVOLUMES
*/
ByteString aRet;
if( nFlags & SALSYSTEM_GETSYSTEMINFO_SYSTEMVERSION )
aRet += aPostMortem.getSystemInfo();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_CPUTYPE )
aRet += aPostMortem.getProcessorInfo();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_MEMORYINFO )
aRet += aPostMortem.getMemoryInfo();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_STACK )
aRet += aPostMortem.getStackTrace();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_GRAPHICSSYSTEM )
aRet += aPostMortem.getGraphicsSystem();
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "SalSystem::GetSummarySystemInfos() =\n%s", aRet.GetBuffer() );
#endif
return String( aRet, RTL_TEXTENCODING_ISO_8859_1 );
}
bool X11SalSystem::GetSalSystemDisplayInfo( System::DisplayInfo& rInfo )
{
bool bSuccess = false;
Display* pDisplay = XOpenDisplay( NULL );
if( pDisplay )
{
int nScreen = DefaultScreen( pDisplay );
XVisualInfo aVI;
/* note: SalDisplay::BestVisual does not
* access saldata or any other data available
* only after InitVCL; nor does SalOpenGL:MakeVisualWeights
* which gets called by SalDisplay::BestVisual.
* this is crucial since GetSalSystemDisplayInfo
* gets called BEFORE Init.
*/
SalDisplay::BestVisual( pDisplay, nScreen, aVI );
rInfo.nDepth = aVI.depth;
rInfo.nWidth = DisplayWidth( pDisplay, nScreen );
rInfo.nHeight = DisplayHeight( pDisplay, nScreen );
XCloseDisplay( pDisplay );
bSuccess = true;
}
return bSuccess;
}
int X11SalSystem::ShowNativeDialog( const String& rTitle, const String& rMessage, const std::list< String >& rButtons, int nDefButton )
{
int nRet = -1;
ImplSVData* pSVData = ImplGetSVData();
if( pSVData->mpIntroWindow )
pSVData->mpIntroWindow->Hide();
DtIntegrator* pIntegrator = DtIntegrator::CreateDtIntegrator();
if( pIntegrator->GetDtType() == DtGNOME )
{
ByteString aCmdLine( "msgbox-gnome ");
int nButton = 0;
for( std::list< String >::const_iterator it = rButtons.begin(); it != rButtons.end(); ++it )
{
if( nButton == nDefButton )
aCmdLine.Append( "-defaultbutton" );
else
aCmdLine.Append( "-button" );
nButton++;
aCmdLine.Append( " \"" );
aCmdLine.Append( ByteString( *it, RTL_TEXTENCODING_UTF8 ) );
aCmdLine.Append( "\" " );
}
aCmdLine.Append( " \"" );
aCmdLine.Append( ByteString( rTitle, RTL_TEXTENCODING_UTF8 ) );
aCmdLine.Append( "\" \"" );
aCmdLine.Append( ByteString( rMessage, RTL_TEXTENCODING_UTF8 ) );
aCmdLine.Append( "\" 2>/dev/null" );
FILE* fp = popen( aCmdLine.GetBuffer(), "r" );
if( fp )
{
ByteString aAnswer;
char buf[16];
while( fgets( buf, sizeof( buf ), fp ) )
{
aAnswer.Append( buf );
}
pclose( fp );
nRet = aAnswer.ToInt32();
}
}
else // default to a VCL dialogue since we do not have a native implementation
{
WarningBox aWarn( NULL, WB_STDWORK, rMessage );
aWarn.SetText( rTitle );
aWarn.Clear();
USHORT nButton = 0;
for( std::list< String >::const_iterator it = rButtons.begin(); it != rButtons.end(); ++it )
{
aWarn.AddButton( *it, nButton+1, nButton == (USHORT)nDefButton ? BUTTONDIALOG_DEFBUTTON : 0 );
nButton++;
}
aWarn.SetFocusButton( (USHORT)nDefButton+1 );
nRet = ((int)aWarn.Execute()) - 1;
}
// normalize behaviour, actually this should never happen
if( nRet < -1 || nRet >= rButtons.size() )
nRet = -1;
return nRet;
}
int X11SalSystem::ShowNativeMessageBox(const String& rTitle, const String& rMessage, int nButtonCombination, int nDefaultButton)
{
int nDefButton = 0;
std::list< String > aButtons;
int nButtonIds[5], nBut = 0;
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL )
{
aButtons.push_back( Button::GetStandardText( BUTTON_OK ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO )
{
aButtons.push_back( Button::GetStandardText( BUTTON_YES ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_YES;
aButtons.push_back( Button::GetStandardText( BUTTON_NO ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO;
if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO )
nDefButton = 1;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
{
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
{
aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
}
aButtons.push_back( Button::GetStandardText( BUTTON_CANCEL ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL;
if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL )
nDefButton = aButtons.size()-1;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_ABORT_RETRY_IGNORE )
{
aButtons.push_back( Button::GetStandardText( BUTTON_ABORT ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_ABORT;
aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
aButtons.push_back( Button::GetStandardText( BUTTON_IGNORE ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE;
switch( nDefaultButton )
{
case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY: nDefButton = 1;break;
case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE: nDefButton = 2;break;
}
}
int nResult = ShowNativeDialog( rTitle, rMessage, aButtons, nDefButton );
return nResult != -1 ? nButtonIds[ nResult ] : 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
#ifndef MFEM_INTRULES
#define MFEM_INTRULES
#include "../config/config.hpp"
#include "../general/array.hpp"
namespace mfem
{
/* Classes for IntegrationPoint, IntegrationRule, and container class
IntegrationRules. Declares the global variable IntRules */
/// Class for integration point with weight
class IntegrationPoint
{
public:
double x, y, z, weight;
int index;
void Init(int const i)
{
x = y = z = weight = 0.0;
index = i;
}
void Set(const double *p, const int dim)
{
MFEM_ASSERT(1 <= dim && dim <= 3, "invalid dim: " << dim);
x = p[0];
if (dim > 1)
{
y = p[1];
if (dim > 2)
{
z = p[2];
}
}
}
void Get(double *p, const int dim) const
{
MFEM_ASSERT(1 <= dim && dim <= 3, "invalid dim: " << dim);
p[0] = x;
if (dim > 1)
{
p[1] = y;
if (dim > 2)
{
p[2] = z;
}
}
}
void Set(const double x1, const double x2, const double x3, const double w)
{ x = x1; y = x2; z = x3; weight = w; }
void Set3w(const double *p) { x = p[0]; y = p[1]; z = p[2]; weight = p[3]; }
void Set3(const double x1, const double x2, const double x3)
{ x = x1; y = x2; z = x3; }
void Set3(const double *p) { x = p[0]; y = p[1]; z = p[2]; }
void Set2w(const double x1, const double x2, const double w)
{ x = x1; y = x2; weight = w; }
void Set2w(const double *p) { x = p[0]; y = p[1]; weight = p[2]; }
void Set2(const double x1, const double x2) { x = x1; y = x2; }
void Set2(const double *p) { x = p[0]; y = p[1]; }
void Set1w(const double x1, const double w) { x = x1; weight = w; }
void Set1w(const double *p) { x = p[0]; weight = p[1]; }
};
/// Class for an integration rule - an Array of IntegrationPoint.
class IntegrationRule : public Array<IntegrationPoint>
{
private:
friend class IntegrationRules;
int Order;
/** @brief The quadrature weights gathered as a contiguous array. Created
by request with the method GetWeights(). */
mutable Array<double> weights;
/**
* @brief Sets the indices of each quadrature point on initialization.
*/
void SetPointIndices();
/// Define n-simplex rule (triangle/tetrahedron for n=2/3) of order (2s+1)
void GrundmannMollerSimplexRule(int s, int n = 3);
void AddTriMidPoint(const int off, const double weight)
{ IntPoint(off).Set2w(1./3., 1./3., weight); }
void AddTriPoints3(const int off, const double a, const double b,
const double weight)
{
IntPoint(off + 0).Set2w(a, a, weight);
IntPoint(off + 1).Set2w(a, b, weight);
IntPoint(off + 2).Set2w(b, a, weight);
}
void AddTriPoints3(const int off, const double a, const double weight)
{ AddTriPoints3(off, a, 1. - 2.*a, weight); }
void AddTriPoints3b(const int off, const double b, const double weight)
{ AddTriPoints3(off, (1. - b)/2., b, weight); }
void AddTriPoints3R(const int off, const double a, const double b,
const double c, const double weight)
{
IntPoint(off + 0).Set2w(a, b, weight);
IntPoint(off + 1).Set2w(c, a, weight);
IntPoint(off + 2).Set2w(b, c, weight);
}
void AddTriPoints3R(const int off, const double a, const double b,
const double weight)
{ AddTriPoints3R(off, a, b, 1. - a - b, weight); }
void AddTriPoints6(const int off, const double a, const double b,
const double c, const double weight)
{
IntPoint(off + 0).Set2w(a, b, weight);
IntPoint(off + 1).Set2w(b, a, weight);
IntPoint(off + 2).Set2w(a, c, weight);
IntPoint(off + 3).Set2w(c, a, weight);
IntPoint(off + 4).Set2w(b, c, weight);
IntPoint(off + 5).Set2w(c, b, weight);
}
void AddTriPoints6(const int off, const double a, const double b,
const double weight)
{ AddTriPoints6(off, a, b, 1. - a - b, weight); }
// add the permutations of (a,a,b)
void AddTetPoints3(const int off, const double a, const double b,
const double weight)
{
IntPoint(off + 0).Set(a, a, b, weight);
IntPoint(off + 1).Set(a, b, a, weight);
IntPoint(off + 2).Set(b, a, a, weight);
}
// add the permutations of (a,b,c)
void AddTetPoints6(const int off, const double a, const double b,
const double c, const double weight)
{
IntPoint(off + 0).Set(a, b, c, weight);
IntPoint(off + 1).Set(a, c, b, weight);
IntPoint(off + 2).Set(b, c, a, weight);
IntPoint(off + 3).Set(b, a, c, weight);
IntPoint(off + 4).Set(c, a, b, weight);
IntPoint(off + 5).Set(c, b, a, weight);
}
void AddTetMidPoint(const int off, const double weight)
{ IntPoint(off).Set(0.25, 0.25, 0.25, weight); }
// given a, add the permutations of (a,a,a,b), where 3*a + b = 1
void AddTetPoints4(const int off, const double a, const double weight)
{
IntPoint(off).Set(a, a, a, weight);
AddTetPoints3(off + 1, a, 1. - 3.*a, weight);
}
// given b, add the permutations of (a,a,a,b), where 3*a + b = 1
void AddTetPoints4b(const int off, const double b, const double weight)
{
const double a = (1. - b)/3.;
IntPoint(off).Set(a, a, a, weight);
AddTetPoints3(off + 1, a, b, weight);
}
// add the permutations of (a,a,b,b), 2*(a + b) = 1
void AddTetPoints6(const int off, const double a, const double weight)
{
const double b = 0.5 - a;
AddTetPoints3(off, a, b, weight);
AddTetPoints3(off + 3, b, a, weight);
}
// given (a,b) or (a,c), add the permutations of (a,a,b,c), 2*a + b + c = 1
void AddTetPoints12(const int off, const double a, const double bc,
const double weight)
{
const double cb = 1. - 2*a - bc;
AddTetPoints3(off, a, bc, weight);
AddTetPoints3(off + 3, a, cb, weight);
AddTetPoints6(off + 6, a, bc, cb, weight);
}
// given (b,c), add the permutations of (a,a,b,c), 2*a + b + c = 1
void AddTetPoints12bc(const int off, const double b, const double c,
const double weight)
{
const double a = (1. - b - c)/2.;
AddTetPoints3(off, a, b, weight);
AddTetPoints3(off + 3, a, c, weight);
AddTetPoints6(off + 6, a, b, c, weight);
}
public:
IntegrationRule() :
Array<IntegrationPoint>(), Order(0) { }
/// Construct an integration rule with given number of points
explicit IntegrationRule(int NP) :
Array<IntegrationPoint>(NP), Order(0)
{
for (int i = 0; i < this->Size(); i++)
{
(*this)[i].Init(i);
}
}
/// Tensor product of two 1D integration rules
IntegrationRule(IntegrationRule &irx, IntegrationRule &iry);
/// Tensor product of three 1D integration rules
IntegrationRule(IntegrationRule &irx, IntegrationRule &iry,
IntegrationRule &irz);
/// Returns the order of the integration rule
int GetOrder() const { return Order; }
/** @brief Sets the order of the integration rule. This is only for keeping
order information, it does not alter any data in the IntegrationRule. */
void SetOrder(const int order) { Order = order; }
/// Returns the number of the points in the integration rule
int GetNPoints() const { return Size(); }
/// Returns a reference to the i-th integration point
IntegrationPoint &IntPoint(int i) { return (*this)[i]; }
/// Returns a const reference to the i-th integration point
const IntegrationPoint &IntPoint(int i) const { return (*this)[i]; }
/// Return the quadrature weights in a contiguous array.
/** If a contiguous array is not required, the weights can be accessed with
a call like this: `IntPoint(i).weight`. */
const Array<double> &GetWeights() const;
/// Destroys an IntegrationRule object
~IntegrationRule() { }
};
/// A Class that defines 1-D numerical quadrature rules on [0,1].
class QuadratureFunctions1D
{
public:
/** @name Methods for calculating quadrature rules.
These methods calculate the actual points and weights for the different
types of quadrature rules. */
///@{
void GaussLegendre(const int np, IntegrationRule* ir);
void GaussLobatto(const int np, IntegrationRule *ir);
void OpenUniform(const int np, IntegrationRule *ir);
void ClosedUniform(const int np, IntegrationRule *ir);
void OpenHalfUniform(const int np, IntegrationRule *ir);
///@}
/// A helper function that will play nice with Poly_1D::OpenPoints and
/// Poly_1D::ClosedPoints
void GivePolyPoints(const int np, double *pts, const int type);
private:
void CalculateUniformWeights(IntegrationRule *ir, const int type);
};
/// A class container for 1D quadrature type constants.
class Quadrature1D
{
public:
enum
{
Invalid = -1,
GaussLegendre = 0,
GaussLobatto = 1,
OpenUniform = 2, ///< aka open Newton-Cotes
ClosedUniform = 3, ///< aka closed Newton-Cotes
OpenHalfUniform = 4 ///< aka "open half" Newton-Cotes
};
/** @brief If the Quadrature1D type is not closed return Invalid; otherwise
return type. */
static int CheckClosed(int type);
/** @brief If the Quadrature1D type is not open return Invalid; otherwise
return type. */
static int CheckOpen(int type);
};
/// Container class for integration rules
class IntegrationRules
{
private:
/// Taken from the Quadrature1D class anonymous enum
/// Determines the type of numerical quadrature used for
/// segment, square, and cube geometries
const int quad_type;
int own_rules, refined;
/// Function that generates quadrature points and weights on [0,1]
QuadratureFunctions1D quad_func;
Array<IntegrationRule *> PointIntRules;
Array<IntegrationRule *> SegmentIntRules;
Array<IntegrationRule *> TriangleIntRules;
Array<IntegrationRule *> SquareIntRules;
Array<IntegrationRule *> TetrahedronIntRules;
Array<IntegrationRule *> PrismIntRules;
Array<IntegrationRule *> CubeIntRules;
void AllocIntRule(Array<IntegrationRule *> &ir_array, int Order)
{
if (ir_array.Size() <= Order)
{
ir_array.SetSize(Order + 1, NULL);
}
}
bool HaveIntRule(Array<IntegrationRule *> &ir_array, int Order)
{
return (ir_array.Size() > Order && ir_array[Order] != NULL);
}
int GetSegmentRealOrder(int Order) const
{
return Order | 1; // valid for all quad_type's
}
/// The following methods allocate new IntegrationRule objects without
/// checking if they already exist. To avoid memory leaks use
/// IntegrationRules::Get(int GeomType, int Order) instead.
IntegrationRule *GenerateIntegrationRule(int GeomType, int Order);
IntegrationRule *PointIntegrationRule(int Order);
IntegrationRule *SegmentIntegrationRule(int Order);
IntegrationRule *TriangleIntegrationRule(int Order);
IntegrationRule *SquareIntegrationRule(int Order);
IntegrationRule *TetrahedronIntegrationRule(int Order);
IntegrationRule *PrismIntegrationRule(int Order);
IntegrationRule *CubeIntegrationRule(int Order);
void DeleteIntRuleArray(Array<IntegrationRule *> &ir_array);
public:
/// Sets initial sizes for the integration rule arrays, but rules
/// are defined the first time they are requested with the Get method.
explicit IntegrationRules(int Ref = 0,
int type = Quadrature1D::GaussLegendre);
/// Returns an integration rule for given GeomType and Order.
const IntegrationRule &Get(int GeomType, int Order);
void Set(int GeomType, int Order, IntegrationRule &IntRule);
void SetOwnRules(int o) { own_rules = o; }
/// Destroys an IntegrationRules object
~IntegrationRules();
};
/// A global object with all integration rules (defined in intrules.cpp)
extern IntegrationRules IntRules;
/// A global object with all refined integration rules
extern IntegrationRules RefinedIntRules;
}
#endif
<commit_msg>minor<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
#ifndef MFEM_INTRULES
#define MFEM_INTRULES
#include "../config/config.hpp"
#include "../general/array.hpp"
namespace mfem
{
/* Classes for IntegrationPoint, IntegrationRule, and container class
IntegrationRules. Declares the global variable IntRules */
/// Class for integration point with weight
class IntegrationPoint
{
public:
double x, y, z, weight;
int index;
void Init(int const i)
{
x = y = z = weight = 0.0;
index = i;
}
void Set(const double *p, const int dim)
{
MFEM_ASSERT(1 <= dim && dim <= 3, "invalid dim: " << dim);
x = p[0];
if (dim > 1)
{
y = p[1];
if (dim > 2)
{
z = p[2];
}
}
}
void Get(double *p, const int dim) const
{
MFEM_ASSERT(1 <= dim && dim <= 3, "invalid dim: " << dim);
p[0] = x;
if (dim > 1)
{
p[1] = y;
if (dim > 2)
{
p[2] = z;
}
}
}
void Set(const double x1, const double x2, const double x3, const double w)
{ x = x1; y = x2; z = x3; weight = w; }
void Set3w(const double *p) { x = p[0]; y = p[1]; z = p[2]; weight = p[3]; }
void Set3(const double x1, const double x2, const double x3)
{ x = x1; y = x2; z = x3; }
void Set3(const double *p) { x = p[0]; y = p[1]; z = p[2]; }
void Set2w(const double x1, const double x2, const double w)
{ x = x1; y = x2; weight = w; }
void Set2w(const double *p) { x = p[0]; y = p[1]; weight = p[2]; }
void Set2(const double x1, const double x2) { x = x1; y = x2; }
void Set2(const double *p) { x = p[0]; y = p[1]; }
void Set1w(const double x1, const double w) { x = x1; weight = w; }
void Set1w(const double *p) { x = p[0]; weight = p[1]; }
};
/// Class for an integration rule - an Array of IntegrationPoint.
class IntegrationRule : public Array<IntegrationPoint>
{
private:
friend class IntegrationRules;
int Order;
/** @brief The quadrature weights gathered as a contiguous array. Created
by request with the method GetWeights(). */
mutable Array<double> weights;
/// Sets the indices of each quadrature point on initialization.
void SetPointIndices();
/// Define n-simplex rule (triangle/tetrahedron for n=2/3) of order (2s+1)
void GrundmannMollerSimplexRule(int s, int n = 3);
void AddTriMidPoint(const int off, const double weight)
{ IntPoint(off).Set2w(1./3., 1./3., weight); }
void AddTriPoints3(const int off, const double a, const double b,
const double weight)
{
IntPoint(off + 0).Set2w(a, a, weight);
IntPoint(off + 1).Set2w(a, b, weight);
IntPoint(off + 2).Set2w(b, a, weight);
}
void AddTriPoints3(const int off, const double a, const double weight)
{ AddTriPoints3(off, a, 1. - 2.*a, weight); }
void AddTriPoints3b(const int off, const double b, const double weight)
{ AddTriPoints3(off, (1. - b)/2., b, weight); }
void AddTriPoints3R(const int off, const double a, const double b,
const double c, const double weight)
{
IntPoint(off + 0).Set2w(a, b, weight);
IntPoint(off + 1).Set2w(c, a, weight);
IntPoint(off + 2).Set2w(b, c, weight);
}
void AddTriPoints3R(const int off, const double a, const double b,
const double weight)
{ AddTriPoints3R(off, a, b, 1. - a - b, weight); }
void AddTriPoints6(const int off, const double a, const double b,
const double c, const double weight)
{
IntPoint(off + 0).Set2w(a, b, weight);
IntPoint(off + 1).Set2w(b, a, weight);
IntPoint(off + 2).Set2w(a, c, weight);
IntPoint(off + 3).Set2w(c, a, weight);
IntPoint(off + 4).Set2w(b, c, weight);
IntPoint(off + 5).Set2w(c, b, weight);
}
void AddTriPoints6(const int off, const double a, const double b,
const double weight)
{ AddTriPoints6(off, a, b, 1. - a - b, weight); }
// add the permutations of (a,a,b)
void AddTetPoints3(const int off, const double a, const double b,
const double weight)
{
IntPoint(off + 0).Set(a, a, b, weight);
IntPoint(off + 1).Set(a, b, a, weight);
IntPoint(off + 2).Set(b, a, a, weight);
}
// add the permutations of (a,b,c)
void AddTetPoints6(const int off, const double a, const double b,
const double c, const double weight)
{
IntPoint(off + 0).Set(a, b, c, weight);
IntPoint(off + 1).Set(a, c, b, weight);
IntPoint(off + 2).Set(b, c, a, weight);
IntPoint(off + 3).Set(b, a, c, weight);
IntPoint(off + 4).Set(c, a, b, weight);
IntPoint(off + 5).Set(c, b, a, weight);
}
void AddTetMidPoint(const int off, const double weight)
{ IntPoint(off).Set(0.25, 0.25, 0.25, weight); }
// given a, add the permutations of (a,a,a,b), where 3*a + b = 1
void AddTetPoints4(const int off, const double a, const double weight)
{
IntPoint(off).Set(a, a, a, weight);
AddTetPoints3(off + 1, a, 1. - 3.*a, weight);
}
// given b, add the permutations of (a,a,a,b), where 3*a + b = 1
void AddTetPoints4b(const int off, const double b, const double weight)
{
const double a = (1. - b)/3.;
IntPoint(off).Set(a, a, a, weight);
AddTetPoints3(off + 1, a, b, weight);
}
// add the permutations of (a,a,b,b), 2*(a + b) = 1
void AddTetPoints6(const int off, const double a, const double weight)
{
const double b = 0.5 - a;
AddTetPoints3(off, a, b, weight);
AddTetPoints3(off + 3, b, a, weight);
}
// given (a,b) or (a,c), add the permutations of (a,a,b,c), 2*a + b + c = 1
void AddTetPoints12(const int off, const double a, const double bc,
const double weight)
{
const double cb = 1. - 2*a - bc;
AddTetPoints3(off, a, bc, weight);
AddTetPoints3(off + 3, a, cb, weight);
AddTetPoints6(off + 6, a, bc, cb, weight);
}
// given (b,c), add the permutations of (a,a,b,c), 2*a + b + c = 1
void AddTetPoints12bc(const int off, const double b, const double c,
const double weight)
{
const double a = (1. - b - c)/2.;
AddTetPoints3(off, a, b, weight);
AddTetPoints3(off + 3, a, c, weight);
AddTetPoints6(off + 6, a, b, c, weight);
}
public:
IntegrationRule() :
Array<IntegrationPoint>(), Order(0) { }
/// Construct an integration rule with given number of points
explicit IntegrationRule(int NP) :
Array<IntegrationPoint>(NP), Order(0)
{
for (int i = 0; i < this->Size(); i++)
{
(*this)[i].Init(i);
}
}
/// Tensor product of two 1D integration rules
IntegrationRule(IntegrationRule &irx, IntegrationRule &iry);
/// Tensor product of three 1D integration rules
IntegrationRule(IntegrationRule &irx, IntegrationRule &iry,
IntegrationRule &irz);
/// Returns the order of the integration rule
int GetOrder() const { return Order; }
/** @brief Sets the order of the integration rule. This is only for keeping
order information, it does not alter any data in the IntegrationRule. */
void SetOrder(const int order) { Order = order; }
/// Returns the number of the points in the integration rule
int GetNPoints() const { return Size(); }
/// Returns a reference to the i-th integration point
IntegrationPoint &IntPoint(int i) { return (*this)[i]; }
/// Returns a const reference to the i-th integration point
const IntegrationPoint &IntPoint(int i) const { return (*this)[i]; }
/// Return the quadrature weights in a contiguous array.
/** If a contiguous array is not required, the weights can be accessed with
a call like this: `IntPoint(i).weight`. */
const Array<double> &GetWeights() const;
/// Destroys an IntegrationRule object
~IntegrationRule() { }
};
/// A Class that defines 1-D numerical quadrature rules on [0,1].
class QuadratureFunctions1D
{
public:
/** @name Methods for calculating quadrature rules.
These methods calculate the actual points and weights for the different
types of quadrature rules. */
///@{
void GaussLegendre(const int np, IntegrationRule* ir);
void GaussLobatto(const int np, IntegrationRule *ir);
void OpenUniform(const int np, IntegrationRule *ir);
void ClosedUniform(const int np, IntegrationRule *ir);
void OpenHalfUniform(const int np, IntegrationRule *ir);
///@}
/// A helper function that will play nice with Poly_1D::OpenPoints and
/// Poly_1D::ClosedPoints
void GivePolyPoints(const int np, double *pts, const int type);
private:
void CalculateUniformWeights(IntegrationRule *ir, const int type);
};
/// A class container for 1D quadrature type constants.
class Quadrature1D
{
public:
enum
{
Invalid = -1,
GaussLegendre = 0,
GaussLobatto = 1,
OpenUniform = 2, ///< aka open Newton-Cotes
ClosedUniform = 3, ///< aka closed Newton-Cotes
OpenHalfUniform = 4 ///< aka "open half" Newton-Cotes
};
/** @brief If the Quadrature1D type is not closed return Invalid; otherwise
return type. */
static int CheckClosed(int type);
/** @brief If the Quadrature1D type is not open return Invalid; otherwise
return type. */
static int CheckOpen(int type);
};
/// Container class for integration rules
class IntegrationRules
{
private:
/// Taken from the Quadrature1D class anonymous enum
/// Determines the type of numerical quadrature used for
/// segment, square, and cube geometries
const int quad_type;
int own_rules, refined;
/// Function that generates quadrature points and weights on [0,1]
QuadratureFunctions1D quad_func;
Array<IntegrationRule *> PointIntRules;
Array<IntegrationRule *> SegmentIntRules;
Array<IntegrationRule *> TriangleIntRules;
Array<IntegrationRule *> SquareIntRules;
Array<IntegrationRule *> TetrahedronIntRules;
Array<IntegrationRule *> PrismIntRules;
Array<IntegrationRule *> CubeIntRules;
void AllocIntRule(Array<IntegrationRule *> &ir_array, int Order)
{
if (ir_array.Size() <= Order)
{
ir_array.SetSize(Order + 1, NULL);
}
}
bool HaveIntRule(Array<IntegrationRule *> &ir_array, int Order)
{
return (ir_array.Size() > Order && ir_array[Order] != NULL);
}
int GetSegmentRealOrder(int Order) const
{
return Order | 1; // valid for all quad_type's
}
/// The following methods allocate new IntegrationRule objects without
/// checking if they already exist. To avoid memory leaks use
/// IntegrationRules::Get(int GeomType, int Order) instead.
IntegrationRule *GenerateIntegrationRule(int GeomType, int Order);
IntegrationRule *PointIntegrationRule(int Order);
IntegrationRule *SegmentIntegrationRule(int Order);
IntegrationRule *TriangleIntegrationRule(int Order);
IntegrationRule *SquareIntegrationRule(int Order);
IntegrationRule *TetrahedronIntegrationRule(int Order);
IntegrationRule *PrismIntegrationRule(int Order);
IntegrationRule *CubeIntegrationRule(int Order);
void DeleteIntRuleArray(Array<IntegrationRule *> &ir_array);
public:
/// Sets initial sizes for the integration rule arrays, but rules
/// are defined the first time they are requested with the Get method.
explicit IntegrationRules(int Ref = 0,
int type = Quadrature1D::GaussLegendre);
/// Returns an integration rule for given GeomType and Order.
const IntegrationRule &Get(int GeomType, int Order);
void Set(int GeomType, int Order, IntegrationRule &IntRule);
void SetOwnRules(int o) { own_rules = o; }
/// Destroys an IntegrationRules object
~IntegrationRules();
};
/// A global object with all integration rules (defined in intrules.cpp)
extern IntegrationRules IntRules;
/// A global object with all refined integration rules
extern IntegrationRules RefinedIntRules;
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2017 The GalaxyCash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include "base58.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int i = 0; i < count; i++)
{
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x4e;
pchMessageStart[1] = 0xe6;
pchMessageStart[2] = 0xe6;
pchMessageStart[3] = 0x4e;
// Subsidy halvings
nSubsidyHalvingInterval = 210000;
// POS
stakeLimit = uint256S("00000fffff000000000000000000000000000000000000000000000000000000");
nPOSFirstBlock = 61300;
// Merge
nMergeFirstBlock = nCoinbaseMaturity + 2;
nMergeLastBlock = 95;
// Last PoW block
nLastPowBlock = 130000;
// Ports
nDefaultPort = 7604;
nRPCPort = 4604;
// POW params
powLimit = uint256S("00000fffff000000000000000000000000000000000000000000000000000000");
nPowTargetSpacing = 3 * 60; // 3 minutes
nPowTargetSpacing2 = 10 * 60; // 10 minutes
nPowTargetSpacingPOS = 2 * 60; // 2 minutes
nPowTargetTimespan = 6 * 60 * 60; // 6 hours
nPowTargetTimespan2 = 24 * 60 * 60; // 24 hours
nPowTargetTimespanPOS = 6 * 60 * 60; // 6 hours
fPOWNoRetargeting = false;
// Build the genesis block. Note that the output of the genesis coinbase cannot
// be spent as it did not originally exist in the database.
//
const char* pszTimestamp = "15/october/2017 The development of Galaxy Cash started.";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CScriptNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1515086697, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 9;
genesis.nTime = 1515086697;
genesis.nBits = UintToArith256(powLimit).GetCompact();
genesis.nNonce = 1303736;
hashGenesisBlock = genesis.GetHash();
nPoolMaxTransactions = 3;
strAnonsendPoolDummyAddress = "GMY5kZMSgtJs22VDiQKtYMYcapy4FKaBVu";
assert(hashGenesisBlock == uint256S("0x00000076b947553b6888ca82875e04a4db21fd904aae46589e1d183b63327468"));
assert(genesis.hashMerkleRoot == uint256S("0xa3df636e1166133b477fad35d677e81ab93f9c9d242bcdd0e9955c9982615915"));
vSeeds.clear();
vSeeds.push_back(CDNSSeedData("galaxycash.main","195.133.201.213:7604"));
vSeeds.push_back(CDNSSeedData("galaxycash.1node","195.133.147.242:9992"));
vSeeds.push_back(CDNSSeedData("galaxycash.2node","45.77.154.137:7604"));
vSeeds.push_back(CDNSSeedData("galaxycash.3node","212.237.11.136:7604"));
vSeeds.push_back(CDNSSeedData("galaxycash.4node","45.77.31.169:7604"));
vSeeds.push_back(CDNSSeedData("galaxycash.5node","91.92.136.58:7604"));
vSeeds.push_back(CDNSSeedData("galaxycash.6node","59.18.162.74:7604"));
vSeeds.push_back(CDNSSeedData("galaxycash.7node","81.169.150.193:7688"));
vSeeds.push_back(CDNSSeedData("galaxycash.8node","212.47.227.141:7688"));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,38);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,99);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,89);
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x1D)(0x88)(0xB2)(0x23).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x1D)(0x88)(0x2D)(0x56).convert_to_container<std::vector<unsigned char> >();
vFixedSeeds.clear();
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual string NetworkIDString() const { return "main"; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestParams : public CMainParams {
public:
CTestParams() {
strDataDir = "test";
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xe6;
pchMessageStart[1] = 0x2a;
pchMessageStart[2] = 0xe6;
pchMessageStart[3] = 0x4e;
// POW
fPOWNoRetargeting = GetBoolArg("-pownoretargeting", true);
// Merge params
nMergeFirstBlock = nMergeLastBlock = 0;
nSubsidyHalvingInterval = 100;
// POS params
nPOSFirstBlock = 0;
// Ports
nDefaultPort = 17604;
nRPCPort = 14604;
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,41);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,51);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,61);
}
virtual Network NetworkID() const { return CChainParams::TEST; }
virtual string NetworkIDString() const { return "test"; }
};
static CTestParams testParams;
//
// Testnet
//
class CEasyParams : public CMainParams {
public:
CEasyParams() {
strDataDir = "easy";
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x2a;
pchMessageStart[1] = 0x2a;
pchMessageStart[2] = 0xe6;
pchMessageStart[3] = 0x4e;
// Merge params
nMergeFirstBlock = nMergeLastBlock = 0;
// Subsidy halvings
nSubsidyHalvingInterval = 380;
// POS params
nPOSFirstBlock = 0;
// POW params
fPOWNoRetargeting = true;
// Ports
nDefaultPort = 18604;
nRPCPort = 15604;
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,40);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,50);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,60);
}
virtual Network NetworkID() const { return CChainParams::EASY; }
virtual string NetworkIDString() const { return "easy"; }
};
static CEasyParams easyParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::EASY:
pCurrentParams = &easyParams;
break;
case CChainParams::TEST:
pCurrentParams = &testParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
bool fEasyNet = GetBoolArg("-easynet", false);
if (fTestNet)
SelectParams(CChainParams::TEST);
else if (fEasyNet)
SelectParams(CChainParams::EASY);
else
SelectParams(CChainParams::MAIN);
return true;
}
<commit_msg>nodes<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2017 The GalaxyCash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include "base58.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int i = 0; i < count; i++)
{
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x4e;
pchMessageStart[1] = 0xe6;
pchMessageStart[2] = 0xe6;
pchMessageStart[3] = 0x4e;
// Subsidy halvings
nSubsidyHalvingInterval = 210000;
// POS
stakeLimit = uint256S("00000fffff000000000000000000000000000000000000000000000000000000");
nPOSFirstBlock = 61300;
// Merge
nMergeFirstBlock = nCoinbaseMaturity + 2;
nMergeLastBlock = 95;
// Last PoW block
nLastPowBlock = 130000;
// Ports
nDefaultPort = 7604;
nRPCPort = 4604;
// POW params
powLimit = uint256S("00000fffff000000000000000000000000000000000000000000000000000000");
nPowTargetSpacing = 3 * 60; // 3 minutes
nPowTargetSpacing2 = 10 * 60; // 10 minutes
nPowTargetSpacingPOS = 2 * 60; // 2 minutes
nPowTargetTimespan = 6 * 60 * 60; // 6 hours
nPowTargetTimespan2 = 24 * 60 * 60; // 24 hours
nPowTargetTimespanPOS = 6 * 60 * 60; // 6 hours
fPOWNoRetargeting = false;
// Build the genesis block. Note that the output of the genesis coinbase cannot
// be spent as it did not originally exist in the database.
//
const char* pszTimestamp = "15/october/2017 The development of Galaxy Cash started.";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CScriptNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1515086697, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 9;
genesis.nTime = 1515086697;
genesis.nBits = UintToArith256(powLimit).GetCompact();
genesis.nNonce = 1303736;
hashGenesisBlock = genesis.GetHash();
nPoolMaxTransactions = 3;
strAnonsendPoolDummyAddress = "GMY5kZMSgtJs22VDiQKtYMYcapy4FKaBVu";
assert(hashGenesisBlock == uint256S("0x00000076b947553b6888ca82875e04a4db21fd904aae46589e1d183b63327468"));
assert(genesis.hashMerkleRoot == uint256S("0xa3df636e1166133b477fad35d677e81ab93f9c9d242bcdd0e9955c9982615915"));
vSeeds.clear();
vSeeds.push_back(CDNSSeedData("galaxycash.1main","195.133.201.213:7604"));
vSeeds.push_back(CDNSSeedData("galaxycash.2main","195.133.201.213:7605"));
vSeeds.push_back(CDNSSeedData("galaxycash.4main","195.133.147.242:9992"));
vSeeds.push_back(CDNSSeedData("galaxycash.5main","195.133.147.242:3626"));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,38);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,99);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,89);
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x1D)(0x88)(0xB2)(0x23).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x1D)(0x88)(0x2D)(0x56).convert_to_container<std::vector<unsigned char> >();
vFixedSeeds.clear();
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual string NetworkIDString() const { return "main"; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestParams : public CMainParams {
public:
CTestParams() {
strDataDir = "test";
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xe6;
pchMessageStart[1] = 0x2a;
pchMessageStart[2] = 0xe6;
pchMessageStart[3] = 0x4e;
// POW
fPOWNoRetargeting = GetBoolArg("-pownoretargeting", true);
// Merge params
nMergeFirstBlock = nMergeLastBlock = 0;
nSubsidyHalvingInterval = 100;
// POS params
nPOSFirstBlock = 0;
// Ports
nDefaultPort = 17604;
nRPCPort = 14604;
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,41);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,51);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,61);
}
virtual Network NetworkID() const { return CChainParams::TEST; }
virtual string NetworkIDString() const { return "test"; }
};
static CTestParams testParams;
//
// Testnet
//
class CEasyParams : public CMainParams {
public:
CEasyParams() {
strDataDir = "easy";
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x2a;
pchMessageStart[1] = 0x2a;
pchMessageStart[2] = 0xe6;
pchMessageStart[3] = 0x4e;
// Merge params
nMergeFirstBlock = nMergeLastBlock = 0;
// Subsidy halvings
nSubsidyHalvingInterval = 380;
// POS params
nPOSFirstBlock = 0;
// POW params
fPOWNoRetargeting = true;
// Ports
nDefaultPort = 18604;
nRPCPort = 15604;
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,40);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,50);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,60);
}
virtual Network NetworkID() const { return CChainParams::EASY; }
virtual string NetworkIDString() const { return "easy"; }
};
static CEasyParams easyParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::EASY:
pCurrentParams = &easyParams;
break;
case CChainParams::TEST:
pCurrentParams = &testParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
bool fEasyNet = GetBoolArg("-easynet", false);
if (fTestNet)
SelectParams(CChainParams::TEST);
else if (fEasyNet)
SelectParams(CChainParams::EASY);
else
SelectParams(CChainParams::MAIN);
return true;
}
<|endoftext|> |
<commit_before>#include <wayfire/plugin.hpp>
#include <wayfire/output.hpp>
#include <wayfire/core.hpp>
#include <wayfire/view.hpp>
#include <wayfire/view-transform.hpp>
#include <wayfire/render-manager.hpp>
#include <wayfire/workspace-stream.hpp>
#include <wayfire/workspace-manager.hpp>
#include <wayfire/signal-definitions.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <wayfire/util/duration.hpp>
#include <cmath>
#include <utility>
#include <wayfire/plugins/common/workspace-wall.hpp>
#include <wayfire/plugins/common/geometry-animation.hpp>
#include "vswipe-processing.hpp"
class vswipe : public wf::plugin_interface_t
{
private:
enum swipe_direction_t
{
HORIZONTAL = 0,
VERTICAL,
UNKNOWN,
};
struct {
bool swiping = false;
bool animating = false;
swipe_direction_t direction;
wf::pointf_t initial_deltas;
double delta_prev = 0.0;
double delta_last = 0.0;
int vx = 0;
int vy = 0;
int vw = 0;
int vh = 0;
} state;
std::unique_ptr<wf::workspace_wall_t> wall;
wf::option_wrapper_t<bool> enable_horizontal{"vswipe/enable_horizontal"};
wf::option_wrapper_t<bool> enable_vertical{"vswipe/enable_vertical"};
wf::option_wrapper_t<bool> smooth_transition{"vswipe/enable_smooth_transition"};
wf::option_wrapper_t<wf::color_t> background_color{"vswipe/background"};
wf::option_wrapper_t<int> animation_duration{"vswipe/duration"};
wf::animation::simple_animation_t smooth_delta{animation_duration};
wf::option_wrapper_t<int> fingers{"vswipe/fingers"};
wf::option_wrapper_t<double> gap{"vswipe/gap"};
wf::option_wrapper_t<double> threshold{"vswipe/threshold"};
wf::option_wrapper_t<double> delta_threshold{"vswipe/delta_threshold"};
wf::option_wrapper_t<double> speed_factor{"vswipe/speed_factor"};
wf::option_wrapper_t<double> speed_cap{"vswipe/speed_cap"};
public:
void init() override
{
grab_interface->name = "vswipe";
grab_interface->capabilities = wf::CAPABILITY_MANAGE_COMPOSITOR;
grab_interface->callbacks.cancel = [=] () { finalize_and_exit(); };
wf::get_core().connect_signal("pointer_swipe_begin", &on_swipe_begin);
wf::get_core().connect_signal("pointer_swipe_update", &on_swipe_update);
wf::get_core().connect_signal("pointer_swipe_end", &on_swipe_end);
wall = std::make_unique<wf::workspace_wall_t> (output);
wall->connect_signal("frame", &this->on_frame);
}
wf::signal_connection_t on_frame = {[=] (wf::signal_data_t*)
{
if (!smooth_delta.running() && !state.swiping)
{
finalize_and_exit();
return;
}
output->render->schedule_redraw();
wf::point_t current_workspace = {state.vx, state.vy};
int dx = 0, dy = 0;
if (state.direction == HORIZONTAL) {
dx = 1;
} else if (state.direction == VERTICAL) {
dy = 1;
}
wf::point_t next_ws = {current_workspace.x + dx, current_workspace.y + dy};
auto g1 = wall->get_workspace_rectangle(current_workspace);
auto g2 = wall->get_workspace_rectangle(next_ws);
wall->set_viewport(wf::interpolate(g1, g2, -smooth_delta));
}};
template<class wlr_event> using event = wf::input_event_signal<wlr_event>;
wf::signal_callback_t on_swipe_begin = [=] (wf::signal_data_t *data)
{
if (!enable_horizontal && !enable_vertical)
return;
if (output->is_plugin_active(grab_interface->name))
return;
auto ev = static_cast<
event<wlr_event_pointer_swipe_begin>*> (data)->event;
if (static_cast<int>(ev->fingers) != fingers)
return;
// Plugins are per output, swipes are global, so we need to handle
// the swipe only when the cursor is on *our* (plugin instance's) output
if (!(output->get_relative_geometry() & output->get_cursor_position()))
return;
state.swiping = true;
state.direction = UNKNOWN;
state.initial_deltas = {0.0, 0.0};
smooth_delta.set(0, 0);
state.delta_last = 0;
state.delta_prev = 0;
// We switch the actual workspace before the finishing animation,
// so the rendering of the animation cannot dynamically query current
// workspace again, so it's stored here
auto grid = output->workspace->get_workspace_grid_size();
auto ws = output->workspace->get_current_workspace();
state.vw = grid.width;
state.vh = grid.height;
state.vx = ws.x;
state.vy = ws.y;
};
void start_swipe(swipe_direction_t direction)
{
assert(direction != UNKNOWN);
state.direction = direction;
if (!output->activate_plugin(grab_interface))
return;
grab_interface->grab();
wf::get_core().focus_output(output);
auto ws = output->workspace->get_current_workspace();
wall->set_background_color(background_color);
wall->set_gap_size(gap);
wall->set_viewport(wall->get_workspace_rectangle(ws));
wall->start_output_renderer();
}
wf::signal_callback_t on_swipe_update = [&] (wf::signal_data_t *data)
{
if (!state.swiping)
return;
auto ev = static_cast<
event<wlr_event_pointer_swipe_update>*> (data)->event;
if (state.direction == UNKNOWN)
{
auto grid = output->workspace->get_workspace_grid_size();
// XXX: how to determine this??
static constexpr double initial_direction_threshold = 0.05;
state.initial_deltas.x +=
std::abs(ev->dx) / speed_factor;
state.initial_deltas.y +=
std::abs(ev->dy) / speed_factor;
bool horizontal =
state.initial_deltas.x > initial_direction_threshold;
bool vertical =
state.initial_deltas.y > initial_direction_threshold;
horizontal &= state.initial_deltas.x > state.initial_deltas.y;
vertical &= state.initial_deltas.y > state.initial_deltas.x;
if (horizontal && grid.width > 1 && enable_horizontal)
{
start_swipe(HORIZONTAL);
}
else if (vertical && grid.height > 1 && enable_vertical)
{
start_swipe(VERTICAL);
}
if (state.direction == UNKNOWN)
return;
}
const double cap = speed_cap;
const double fac = speed_factor;
state.delta_prev = state.delta_last;
double current_delta_processed;
if (state.direction == HORIZONTAL)
{
current_delta_processed = vswipe_process_delta(ev->dx,
smooth_delta, state.vx, state.vw, cap, fac);
state.delta_last = ev->dx;
} else
{
current_delta_processed = vswipe_process_delta(ev->dy,
smooth_delta, state.vy, state.vh, cap, fac);
state.delta_last = ev->dy;
}
double new_delta_end = smooth_delta.end + current_delta_processed;
double new_delta_start = smooth_transition ? smooth_delta : new_delta_end;
smooth_delta.animate(new_delta_start, new_delta_end);
};
wf::signal_callback_t on_swipe_end = [=] (wf::signal_data_t *data)
{
if (!state.swiping || !output->is_plugin_active(grab_interface->name))
{
state.swiping = false;
return;
}
state.swiping = false;
const double move_threshold = wf::clamp((double)threshold, 0.0, 1.0);
const double fast_threshold = wf::clamp((double)delta_threshold, 0.0, 1000.0);
int target_delta = 0;
wf::point_t target_workspace = {state.vx, state.vy};
switch (state.direction)
{
case UNKNOWN:
target_delta = 0;
break;
case HORIZONTAL:
target_delta = vswipe_finish_target(smooth_delta.end,
state.vx, state.vw, state.delta_prev + state.delta_last,
move_threshold, fast_threshold);
target_workspace.x -= target_delta;
break;
case VERTICAL:
target_delta = vswipe_finish_target(smooth_delta.end,
state.vy, state.vh, state.delta_prev + state.delta_last,
move_threshold, fast_threshold);
target_workspace.y -= target_delta;
break;
}
smooth_delta.animate(target_delta);
output->workspace->set_workspace(target_workspace);
state.animating = true;
};
void finalize_and_exit()
{
state.swiping = false;
grab_interface->ungrab();
output->deactivate_plugin(grab_interface);
wall->stop_output_renderer(true);
state.animating = false;
}
void fini() override
{
if (state.swiping)
finalize_and_exit();
wf::get_core().disconnect_signal("pointer_swipe_begin", &on_swipe_begin);
wf::get_core().disconnect_signal("pointer_swipe_update", &on_swipe_update);
wf::get_core().disconnect_signal("pointer_swipe_end", &on_swipe_end);
}
};
DECLARE_WAYFIRE_PLUGIN(vswipe);
<commit_msg>vswipe: add preliminary support for diagonal swiping<commit_after>#include <wayfire/plugin.hpp>
#include <wayfire/output.hpp>
#include <wayfire/core.hpp>
#include <wayfire/view.hpp>
#include <wayfire/view-transform.hpp>
#include <wayfire/render-manager.hpp>
#include <wayfire/workspace-stream.hpp>
#include <wayfire/workspace-manager.hpp>
#include <wayfire/signal-definitions.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <wayfire/util/duration.hpp>
#include <wayfire/util/log.hpp>
#include <cmath>
#include <utility>
#include <wayfire/plugins/common/workspace-wall.hpp>
#include <wayfire/plugins/common/geometry-animation.hpp>
#include "vswipe-processing.hpp"
using namespace wf::animation;
class vswipe_smoothing_t : public duration_t
{
public:
using duration_t::duration_t;
timed_transition_t dx{*this};
timed_transition_t dy{*this};
};
static inline wf::geometry_t interpolate(wf::geometry_t a, wf::geometry_t b,
double xalpha, double yalpha)
{
const auto& interp = [=] (int32_t wf::geometry_t::* member, double alpha) -> int32_t {
return std::round((1 - alpha) * a.*member + alpha * b.*member);
};
return {
interp(&wf::geometry_t::x, xalpha),
interp(&wf::geometry_t::y, yalpha),
interp(&wf::geometry_t::width, xalpha),
interp(&wf::geometry_t::height, yalpha)
};
}
class vswipe : public wf::plugin_interface_t
{
private:
enum swipe_direction_t
{
HORIZONTAL = 1,
VERTICAL = 2,
DIAGONAL = HORIZONTAL | VERTICAL,
UNKNOWN = 0,
};
struct {
bool swiping = false;
bool animating = false;
swipe_direction_t direction;
wf::pointf_t initial_deltas;
wf::pointf_t delta_prev;
wf::pointf_t delta_last;
int vx = 0;
int vy = 0;
int vw = 0;
int vh = 0;
} state;
std::unique_ptr<wf::workspace_wall_t> wall;
wf::option_wrapper_t<bool> enable_horizontal{"vswipe/enable_horizontal"};
wf::option_wrapper_t<bool> enable_vertical{"vswipe/enable_vertical"};
wf::option_wrapper_t<bool> smooth_transition{"vswipe/enable_smooth_transition"};
wf::option_wrapper_t<wf::color_t> background_color{"vswipe/background"};
wf::option_wrapper_t<int> animation_duration{"vswipe/duration"};
vswipe_smoothing_t smooth_delta{animation_duration};
wf::option_wrapper_t<int> fingers{"vswipe/fingers"};
wf::option_wrapper_t<double> gap{"vswipe/gap"};
wf::option_wrapper_t<double> threshold{"vswipe/threshold"};
wf::option_wrapper_t<double> delta_threshold{"vswipe/delta_threshold"};
wf::option_wrapper_t<double> speed_factor{"vswipe/speed_factor"};
wf::option_wrapper_t<double> speed_cap{"vswipe/speed_cap"};
public:
void init() override
{
grab_interface->name = "vswipe";
grab_interface->capabilities = wf::CAPABILITY_MANAGE_COMPOSITOR;
grab_interface->callbacks.cancel = [=] () { finalize_and_exit(); };
wf::get_core().connect_signal("pointer_swipe_begin", &on_swipe_begin);
wf::get_core().connect_signal("pointer_swipe_update", &on_swipe_update);
wf::get_core().connect_signal("pointer_swipe_end", &on_swipe_end);
wall = std::make_unique<wf::workspace_wall_t> (output);
wall->connect_signal("frame", &this->on_frame);
}
wf::signal_connection_t on_frame = {[=] (wf::signal_data_t*)
{
if (!smooth_delta.running() && !state.swiping)
{
finalize_and_exit();
return;
}
output->render->schedule_redraw();
wf::point_t current_workspace = {state.vx, state.vy};
int dx = 0, dy = 0;
if (state.direction & HORIZONTAL)
dx = 1;
if (state.direction & VERTICAL)
dy = 1;
wf::point_t next_ws = {current_workspace.x + dx, current_workspace.y + dy};
auto g1 = wall->get_workspace_rectangle(current_workspace);
auto g2 = wall->get_workspace_rectangle(next_ws);
wall->set_viewport(interpolate(g1, g2, -smooth_delta.dx, -smooth_delta.dy));
}};
template<class wlr_event> using event = wf::input_event_signal<wlr_event>;
wf::signal_callback_t on_swipe_begin = [=] (wf::signal_data_t *data)
{
if (!enable_horizontal && !enable_vertical)
return;
if (output->is_plugin_active(grab_interface->name))
return;
auto ev = static_cast<
event<wlr_event_pointer_swipe_begin>*> (data)->event;
if (static_cast<int>(ev->fingers) != fingers)
return;
// Plugins are per output, swipes are global, so we need to handle
// the swipe only when the cursor is on *our* (plugin instance's) output
if (!(output->get_relative_geometry() & output->get_cursor_position()))
return;
state.swiping = true;
state.direction = UNKNOWN;
state.initial_deltas = {0.0, 0.0};
smooth_delta.dx.set(0, 0);
smooth_delta.dy.set(0, 0);
state.delta_last = {0, 0};
state.delta_prev = {0, 0};
// We switch the actual workspace before the finishing animation,
// so the rendering of the animation cannot dynamically query current
// workspace again, so it's stored here
auto grid = output->workspace->get_workspace_grid_size();
auto ws = output->workspace->get_current_workspace();
state.vw = grid.width;
state.vh = grid.height;
state.vx = ws.x;
state.vy = ws.y;
};
void start_swipe(swipe_direction_t direction)
{
assert(direction != UNKNOWN);
state.direction = direction;
if (!output->activate_plugin(grab_interface))
return;
grab_interface->grab();
wf::get_core().focus_output(output);
auto ws = output->workspace->get_current_workspace();
wall->set_background_color(background_color);
wall->set_gap_size(gap);
wall->set_viewport(wall->get_workspace_rectangle(ws));
wall->start_output_renderer();
}
swipe_direction_t calculate_direction(wf::pointf_t deltas)
{
auto grid = output->workspace->get_workspace_grid_size();
// XXX: how to determine this??
static constexpr double initial_direction_threshold = 0.05;
static constexpr double diagonal_threshold = 3;
bool horizontal = deltas.x > initial_direction_threshold;
bool vertical = deltas.y > initial_direction_threshold;
horizontal &= grid.width > 1 && enable_horizontal;
vertical &= grid.height > 1 && enable_vertical;
horizontal &= deltas.x > deltas.y;
vertical &= deltas.y > deltas.x;
double d = deltas.x / deltas.y;
bool diagonal =
wf::clamp(d, 1.0 / diagonal_threshold, diagonal_threshold) == d;
if ((horizontal || vertical) && diagonal) {
return DIAGONAL;
} if (horizontal) {
return HORIZONTAL;
} else if (vertical) {
return VERTICAL;
}
return UNKNOWN;
};
wf::signal_callback_t on_swipe_update = [&] (wf::signal_data_t *data)
{
if (!state.swiping)
return;
auto ev = static_cast<
event<wlr_event_pointer_swipe_update>*> (data)->event;
if (state.direction == UNKNOWN)
{
state.initial_deltas.x +=
std::abs(ev->dx) / speed_factor;
state.initial_deltas.y +=
std::abs(ev->dy) / speed_factor;
state.direction = calculate_direction(state.initial_deltas);
if (state.direction == UNKNOWN)
return;
start_swipe(state.direction);
}
const double cap = speed_cap;
const double fac = speed_factor;
state.delta_prev = state.delta_last;
double current_delta_processed;
const auto& process_delta = [&] (double delta,
wf::timed_transition_t& total_delta, int ws, int ws_max)
{
current_delta_processed = vswipe_process_delta(delta, total_delta,
ws, ws_max, cap, fac);
double new_delta_end = total_delta.end + current_delta_processed;
double new_delta_start =
smooth_transition ? total_delta : new_delta_end;
total_delta.set(new_delta_start, new_delta_end);
};
if (state.direction & HORIZONTAL)
process_delta(ev->dx, smooth_delta.dx, state.vx, state.vw);
if (state.direction & VERTICAL)
process_delta(ev->dy, smooth_delta.dy, state.vy, state.vh);
state.delta_last = {ev->dx, ev->dy};
smooth_delta.start();
};
wf::signal_callback_t on_swipe_end = [=] (wf::signal_data_t *data)
{
if (!state.swiping || !output->is_plugin_active(grab_interface->name))
{
state.swiping = false;
return;
}
state.swiping = false;
const double move_threshold = wf::clamp((double)threshold, 0.0, 1.0);
const double fast_threshold = wf::clamp((double)delta_threshold, 0.0, 1000.0);
wf::point_t target_delta = {0, 0};
wf::point_t target_workspace = {state.vx, state.vy};
if (state.direction & HORIZONTAL)
{
target_delta.x = vswipe_finish_target(smooth_delta.dx.end,
state.vx, state.vw, state.delta_prev.x + state.delta_last.x,
move_threshold, fast_threshold);
target_workspace.x -= target_delta.x;
}
if (state.direction & VERTICAL)
{
target_delta.y = vswipe_finish_target(smooth_delta.dy.end,
state.vy, state.vh, state.delta_prev.y + state.delta_last.y,
move_threshold, fast_threshold);
target_workspace.y -= target_delta.y;
}
smooth_delta.dx.restart_with_end(target_delta.x);
smooth_delta.dy.restart_with_end(target_delta.y);
smooth_delta.start();
output->workspace->set_workspace(target_workspace);
state.animating = true;
};
void finalize_and_exit()
{
state.swiping = false;
grab_interface->ungrab();
output->deactivate_plugin(grab_interface);
wall->stop_output_renderer(true);
state.animating = false;
}
void fini() override
{
if (state.swiping)
finalize_and_exit();
wf::get_core().disconnect_signal("pointer_swipe_begin", &on_swipe_begin);
wf::get_core().disconnect_signal("pointer_swipe_update", &on_swipe_update);
wf::get_core().disconnect_signal("pointer_swipe_end", &on_swipe_end);
}
};
DECLARE_WAYFIRE_PLUGIN(vswipe);
<|endoftext|> |
<commit_before><commit_msg>Made a GenericProp template and created the specific properties from that.<commit_after><|endoftext|> |
<commit_before><commit_msg>Nanoseconds are unsigned<commit_after><|endoftext|> |
<commit_before>#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
for (size_t i = 0; i < argc; i++) {
printf("%s \n", argv[i]);
}
getchar();
}<commit_msg>mudanças na main<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <string>
using std::string;
int main(int argc, char *argv[]) {
if (argc < 4) {
printf("Sao necessarios 3 argumentos para executar o montador:\n");
printf("cmd>Montador <Tipo de Operacao> <Arquivo de Entrada> <Arquivo de Saida>\n");
}
string tipoOperacao(argv[1]);
if (tipoOperacao == "-p") {
}
return 0;
}<|endoftext|> |
<commit_before>/* Copyright 2010 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <fstream>
#include <string>
#include <getopt.h>
#include <boost/filesystem.hpp>
#include "libconfig.h++"
#include "singletonConfig.h"
#include "logger.h"
namespace {
class singleton_config_lock {
public:
singleton_config_lock() { watcher::SingletonConfig::lock(); }
~singleton_config_lock() { watcher::SingletonConfig::unlock(); }
};
void usage(const char *prog)
{
std::cout << "usage: " << prog << " [ -c CONFIG ] [ -h ] [ -n STREAMUID ]" << std::endl;
exit(0);
}
}
DECLARE_GLOBAL_LOGGER("watcherGlobalLogger");
namespace watcher {
namespace config {
std::string Server("localhost");
int StreamUid = -1;
void initialize(int argc, char **argv)
{
libconfig::Config& config = watcher::SingletonConfig::instance();
singleton_config_lock lock;
std::string configFilename(std::string(boost::filesystem::basename(argv[0])) + ".cfg");
std::string logPropsFilename(std::string(boost::filesystem::basename(argv[0])) + ".log.properties");
int i;
while ((i = getopt(argc, argv, "c:n:h")) != -1) {
switch(i) {
case 'c':
configFilename = std::string(optarg);
break;
case 'n':
StreamUid = strtol(optarg, 0, 0);
break;
case 'h':
usage(argv[0]);
}
}
try {
// make sure it exists.
if (!boost::filesystem::exists(configFilename)) {
std::cerr << "Configuration file \"" << configFilename << "\", not found. Creating it." << std::endl;
std::ofstream f(configFilename.c_str(), std::ios_base::in | std::ios_base::out);
f.close();
} else
config.readFile(configFilename.c_str());
watcher::SingletonConfig::setConfigFile(configFilename);
} catch (libconfig::ParseException &e) {
std::cerr << "Error reading configuration file " << configFilename << ": " << e.what() << std::endl;
std::cerr << "Error: \"" << e.getError() << "\" on line: " << e.getLine() << std::endl;
exit(EXIT_FAILURE); // !!!
}
libconfig::Setting& root = config.getRoot();
if (!root.lookupValue("logProperties", logPropsFilename))
root.add("logProperties", libconfig::Setting::TypeString) = logPropsFilename;
if (!root.lookupValue("server", watcher::config::Server))
root.add("server", libconfig::Setting::TypeString) = watcher::config::Server;
if (!boost::filesystem::exists(logPropsFilename)) {
std::cerr << "Log properties file not found - logging disabled." << std::endl;
Logger::getRootLogger()->setLevel(Level::getOff());
} else {
LOAD_LOG_PROPS(logPropsFilename);
LOG_INFO("Logger initialized from file \"" << logPropsFilename << "\"");
}
}
} // config
} // watcher
// vim:sw=4
<commit_msg>added [-s server] and [-l loglevel] to command line args for dataWatcher.<commit_after>/* Copyright 2010 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <fstream>
#include <string>
#include <getopt.h>
#include <boost/filesystem.hpp>
#include "libconfig.h++"
#include "singletonConfig.h"
#include "logger.h"
namespace {
class singleton_config_lock {
public:
singleton_config_lock() { watcher::SingletonConfig::lock(); }
~singleton_config_lock() { watcher::SingletonConfig::unlock(); }
};
void usage(const char *prog)
{
std::cout << "usage: " << prog << " [ -c CONFIG ] [ -h ] [ -n STREAMUID ] [ -s WATCHERSERVER ] [ -l LOGLEVEL ]" << std::endl;
std::cout << " WATCHERSERVER - the address or resolvable name of the watcher server." << std::endl;
std::cout << " LOGLEVEL - one of off, fatal, error, warn, info, debug, or trace. " << std::endl;
exit(0);
}
}
DECLARE_GLOBAL_LOGGER("watcherGlobalLogger");
namespace watcher {
namespace config {
std::string Server;
int StreamUid = -1;
void initialize(int argc, char **argv)
{
libconfig::Config& config = watcher::SingletonConfig::instance();
singleton_config_lock lock;
bool serverSpecified=false;
std::string configFilename(std::string(boost::filesystem::basename(argv[0])) + ".cfg");
std::string logPropsFilename(std::string(boost::filesystem::basename(argv[0])) + ".log.properties");
std::string logLevel;
int i;
while ((i = getopt(argc, argv, "l:s:c:n:h")) != -1) {
switch(i) {
case 'c':
configFilename = std::string(optarg);
break;
case 'n':
StreamUid = strtol(optarg, 0, 0);
break;
case 's':
Server = std::string(optarg);
serverSpecified=true;
break;
case 'l':
logLevel = std::string(optarg);
if (logLevel!="off" && logLevel!="fatal" && logLevel!="error" && logLevel!="warn" &&
logLevel!="info" && logLevel!="debug" && logLevel!="trace") {
std::cerr << std::endl << "logLevel must be one of off, fatal, error, warn, info, debug, or trace." << std::endl;
exit(EXIT_FAILURE);
}
break;
case 'h':
usage(argv[0]);
}
}
try {
// make sure it exists.
if (!boost::filesystem::exists(configFilename)) {
std::cerr << "Configuration file \"" << configFilename << "\", not found. Creating it." << std::endl;
std::ofstream f(configFilename.c_str(), std::ios_base::in | std::ios_base::out);
f.close();
} else
config.readFile(configFilename.c_str());
watcher::SingletonConfig::setConfigFile(configFilename);
} catch (libconfig::ParseException &e) {
std::cerr << "Error reading configuration file " << configFilename << ": " << e.what() << std::endl;
std::cerr << "Error: \"" << e.getError() << "\" on line: " << e.getLine() << std::endl;
exit(EXIT_FAILURE); // !!!
}
libconfig::Setting& root = config.getRoot();
if (!root.lookupValue("logProperties", logPropsFilename))
root.add("logProperties", libconfig::Setting::TypeString) = logPropsFilename;
if (Server.empty()) {
Server="localhost";
if (!root.lookupValue("server", watcher::config::Server))
root.add("server", libconfig::Setting::TypeString) = watcher::config::Server;
}
if (!boost::filesystem::exists(logPropsFilename)) {
std::cerr << "Log properties file not found - logging disabled." << std::endl;
Logger::getRootLogger()->setLevel(Level::getOff());
} else {
LOAD_LOG_PROPS(logPropsFilename);
LOG_INFO("Logger initialized from file \"" << logPropsFilename << "\"");
}
if (!logLevel.empty()) {
std::cout << "Setting default log level to " << logLevel << std::endl;
Logger::getRootLogger()->setLevel(Level::toLevel(logLevel));
}
}
} // config
} // watcher
// vim:sw=4
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: mapnik_python.cc 27 2005-03-30 21:45:40Z pavlenko $
#include <boost/python.hpp>
#include <boost/get_pointer.hpp>
#include <boost/python/detail/api_placeholder.hpp>
#include <boost/python/exception_translator.hpp>
void register_cairo();
void export_color();
void export_coord();
void export_layer();
void export_parameters();
void export_envelope();
void export_query();
void export_geometry();
void export_image();
void export_image_view();
void export_map();
void export_python();
void export_filter();
void export_rule();
void export_style();
void export_stroke();
void export_feature();
void export_featureset();
void export_datasource();
void export_datasource_cache();
void export_point_symbolizer();
void export_line_symbolizer();
void export_line_pattern_symbolizer();
void export_polygon_symbolizer();
void export_polygon_pattern_symbolizer();
void export_raster_symbolizer();
void export_text_symbolizer();
void export_shield_symbolizer();
void export_font_engine();
void export_projection();
void export_proj_transform();
#include <mapnik/map.hpp>
#include <mapnik/agg_renderer.hpp>
#ifdef HAVE_CAIRO
#include <mapnik/cairo_renderer.hpp>
#endif
#include <mapnik/graphics.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/save_map.hpp>
#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)
#include <pycairo.h>
#endif
void render(const mapnik::Map& map,mapnik::Image32& image, unsigned offset_x = 0, unsigned offset_y = 0)
{
Py_BEGIN_ALLOW_THREADS
mapnik::agg_renderer<mapnik::Image32> ren(map,image,offset_x, offset_y);
ren.apply();
Py_END_ALLOW_THREADS
}
void render2(const mapnik::Map& map,mapnik::Image32& image)
{
Py_BEGIN_ALLOW_THREADS
mapnik::agg_renderer<mapnik::Image32> ren(map,image);
ren.apply();
Py_END_ALLOW_THREADS
}
#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)
void render3(const mapnik::Map& map,PycairoSurface* surface, unsigned offset_x = 0, unsigned offset_y = 0)
{
Py_BEGIN_ALLOW_THREADS
Cairo::RefPtr<Cairo::Surface> s(new Cairo::Surface(surface->surface));
mapnik::cairo_renderer<Cairo::Surface> ren(map,s,offset_x, offset_y);
ren.apply();
Py_END_ALLOW_THREADS
}
void render4(const mapnik::Map& map,PycairoSurface* surface)
{
Py_BEGIN_ALLOW_THREADS
Cairo::RefPtr<Cairo::Surface> s(new Cairo::Surface(surface->surface));
mapnik::cairo_renderer<Cairo::Surface> ren(map,s);
ren.apply();
Py_END_ALLOW_THREADS
}
#endif
void render_tile_to_file(const mapnik::Map& map,
unsigned offset_x, unsigned offset_y,
unsigned width, unsigned height,
const std::string& file,
const std::string& format)
{
mapnik::Image32 image(width,height);
render(map,image,offset_x, offset_y);
mapnik::save_to_file(image.data(),file,format);
}
void render_to_file1(const mapnik::Map& map,
const std::string& filename,
const std::string& format)
{
mapnik::Image32 image(map.getWidth(),map.getHeight());
render(map,image,0,0);
mapnik::save_to_file(image,filename,format);
}
void render_to_file2(const mapnik::Map& map,
const std::string& filename)
{
mapnik::Image32 image(map.getWidth(),map.getHeight());
render(map,image,0,0);
mapnik::save_to_file(image,filename);
}
double scale_denominator(mapnik::Map const &map, bool geographic)
{
return mapnik::scale_denominator(map, geographic);
}
void translator(mapnik::config_error const & ex) {
PyErr_SetString(PyExc_UserWarning, ex.what());
}
BOOST_PYTHON_FUNCTION_OVERLOADS(load_map_overloads, load_map, 2, 3);
BOOST_PYTHON_FUNCTION_OVERLOADS(load_map_string_overloads, load_map_string, 2, 3);
BOOST_PYTHON_MODULE(_mapnik)
{
using namespace boost::python;
using mapnik::load_map;
using mapnik::load_map_string;
using mapnik::save_map;
register_exception_translator<mapnik::config_error>(translator);
register_cairo();
export_query();
export_geometry();
export_feature();
export_featureset();
export_datasource();
export_parameters();
export_color();
export_envelope();
export_image();
export_image_view();
export_filter();
export_rule();
export_style();
export_layer();
export_stroke();
export_datasource_cache();
export_point_symbolizer();
export_line_symbolizer();
export_line_pattern_symbolizer();
export_polygon_symbolizer();
export_polygon_pattern_symbolizer();
export_raster_symbolizer();
export_text_symbolizer();
export_shield_symbolizer();
export_font_engine();
export_projection();
export_proj_transform();
export_coord();
export_map();
def("render_to_file",&render_to_file1);
def("render_to_file",&render_to_file2);
def("render_tile_to_file",&render_tile_to_file);
def("render",&render);
def("render",&render2);
#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)
def("render",&render3);
def("render",&render4);
#endif
def("scale_denominator", &scale_denominator);
def("load_map", & load_map, load_map_overloads());
def("load_map_from_string", & load_map_string, load_map_string_overloads());
def("save_map", & save_map, "save Map object to XML");
using mapnik::symbolizer;
class_<symbolizer>("Symbolizer",no_init)
;
register_ptr_to_python<mapnik::filter_ptr>();
}
<commit_msg>+ mapnik-fix-threaded-python-exceptions.patch from jonb<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: mapnik_python.cc 27 2005-03-30 21:45:40Z pavlenko $
#include <boost/python.hpp>
#include <boost/get_pointer.hpp>
#include <boost/python/detail/api_placeholder.hpp>
#include <boost/python/exception_translator.hpp>
void register_cairo();
void export_color();
void export_coord();
void export_layer();
void export_parameters();
void export_envelope();
void export_query();
void export_geometry();
void export_image();
void export_image_view();
void export_map();
void export_python();
void export_filter();
void export_rule();
void export_style();
void export_stroke();
void export_feature();
void export_featureset();
void export_datasource();
void export_datasource_cache();
void export_point_symbolizer();
void export_line_symbolizer();
void export_line_pattern_symbolizer();
void export_polygon_symbolizer();
void export_polygon_pattern_symbolizer();
void export_raster_symbolizer();
void export_text_symbolizer();
void export_shield_symbolizer();
void export_font_engine();
void export_projection();
void export_proj_transform();
#include <mapnik/map.hpp>
#include <mapnik/agg_renderer.hpp>
#ifdef HAVE_CAIRO
#include <mapnik/cairo_renderer.hpp>
#endif
#include <mapnik/graphics.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/save_map.hpp>
#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)
#include <pycairo.h>
#endif
void render(const mapnik::Map& map,mapnik::Image32& image, unsigned offset_x = 0, unsigned offset_y = 0)
{
Py_BEGIN_ALLOW_THREADS
try
{
mapnik::agg_renderer<mapnik::Image32> ren(map,image,offset_x, offset_y);
ren.apply();
}
catch (...)
{
Py_BLOCK_THREADS
throw;
}
Py_END_ALLOW_THREADS
}
void render2(const mapnik::Map& map,mapnik::Image32& image)
{
Py_BEGIN_ALLOW_THREADS
try
{
mapnik::agg_renderer<mapnik::Image32> ren(map,image);
ren.apply();
}
catch (...)
{
Py_BLOCK_THREADS
throw;
}
Py_END_ALLOW_THREADS
}
#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)
void render3(const mapnik::Map& map,PycairoSurface* surface, unsigned offset_x = 0, unsigned offset_y = 0)
{
Py_BEGIN_ALLOW_THREADS
try
{
Cairo::RefPtr<Cairo::Surface> s(new Cairo::Surface(surface->surface));
mapnik::cairo_renderer<Cairo::Surface> ren(map,s,offset_x, offset_y);
ren.apply();
}
catch (...)
{
Py_BLOCK_THREADS
throw;
}
Py_END_ALLOW_THREADS
}
void render4(const mapnik::Map& map,PycairoSurface* surface)
{
Py_BEGIN_ALLOW_THREADS
try
{
Cairo::RefPtr<Cairo::Surface> s(new Cairo::Surface(surface->surface));
mapnik::cairo_renderer<Cairo::Surface> ren(map,s);
ren.apply();
}
catch (...)
{
Py_BLOCK_THREADS
throw;
}
Py_END_ALLOW_THREADS
}
#endif
void render_tile_to_file(const mapnik::Map& map,
unsigned offset_x, unsigned offset_y,
unsigned width, unsigned height,
const std::string& file,
const std::string& format)
{
mapnik::Image32 image(width,height);
render(map,image,offset_x, offset_y);
mapnik::save_to_file(image.data(),file,format);
}
void render_to_file1(const mapnik::Map& map,
const std::string& filename,
const std::string& format)
{
mapnik::Image32 image(map.getWidth(),map.getHeight());
render(map,image,0,0);
mapnik::save_to_file(image,filename,format);
}
void render_to_file2(const mapnik::Map& map,
const std::string& filename)
{
mapnik::Image32 image(map.getWidth(),map.getHeight());
render(map,image,0,0);
mapnik::save_to_file(image,filename);
}
double scale_denominator(mapnik::Map const &map, bool geographic)
{
return mapnik::scale_denominator(map, geographic);
}
void translator(mapnik::config_error const & ex) {
PyErr_SetString(PyExc_UserWarning, ex.what());
}
BOOST_PYTHON_FUNCTION_OVERLOADS(load_map_overloads, load_map, 2, 3);
BOOST_PYTHON_FUNCTION_OVERLOADS(load_map_string_overloads, load_map_string, 2, 3);
BOOST_PYTHON_MODULE(_mapnik)
{
using namespace boost::python;
using mapnik::load_map;
using mapnik::load_map_string;
using mapnik::save_map;
register_exception_translator<mapnik::config_error>(translator);
register_cairo();
export_query();
export_geometry();
export_feature();
export_featureset();
export_datasource();
export_parameters();
export_color();
export_envelope();
export_image();
export_image_view();
export_filter();
export_rule();
export_style();
export_layer();
export_stroke();
export_datasource_cache();
export_point_symbolizer();
export_line_symbolizer();
export_line_pattern_symbolizer();
export_polygon_symbolizer();
export_polygon_pattern_symbolizer();
export_raster_symbolizer();
export_text_symbolizer();
export_shield_symbolizer();
export_font_engine();
export_projection();
export_proj_transform();
export_coord();
export_map();
def("render_to_file",&render_to_file1);
def("render_to_file",&render_to_file2);
def("render_tile_to_file",&render_tile_to_file);
def("render",&render);
def("render",&render2);
#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)
def("render",&render3);
def("render",&render4);
#endif
def("scale_denominator", &scale_denominator);
def("load_map", & load_map, load_map_overloads());
def("load_map_from_string", & load_map_string, load_map_string_overloads());
def("save_map", & save_map, "save Map object to XML");
using mapnik::symbolizer;
class_<symbolizer>("Symbolizer",no_init)
;
register_ptr_to_python<mapnik::filter_ptr>();
}
<|endoftext|> |
<commit_before>#include "estimator/dcm_attitude_estimator.hpp"
#include "hal.h"
#include "protocol/messages.hpp"
#include "unit_config.hpp"
DCMAttitudeEstimator::DCMAttitudeEstimator(Communicator& communicator)
: dcm(Eigen::Matrix3f::Identity()),
attitudeMessageStream(communicator, 20) {
}
attitude_estimate_t DCMAttitudeEstimator::update(gyroscope_reading_t& gyroReading, accelerometer_reading_t& accelReading) {
Eigen::Vector3f gyro(gyroReading.axes.data());
Eigen::Vector3f accel(accelReading.axes.data());
float accWeight = 0.02f;
if(accel.norm() > 1.05 * 9.8 || accel.norm() < 0.95 * 9.8) {
accWeight = 0.0f;
}
accel.normalize();
Eigen::Vector3f corr = Eigen::Vector3f::Zero();
corr += gyro * unit_config::DT * (1.0f - accWeight);
corr -= dcm.col(2).cross(-accel) * accWeight;
Eigen::Matrix3f dcmStep;
dcmStep << 1.0f, corr.z(), -corr.y(),
-corr.z(), 1.0f, corr.x(),
corr.y(), -corr.x(), 1.0f;
dcm = dcmStep * dcm;
orthonormalize();
attitude_estimate_t estimate {
// TODO: Are these trig functions safe at extreme angles?
.roll = -atan2f(dcm(2, 1), dcm(2, 2)) * dcm(0, 0) + atan2f(dcm(2, 0), dcm(2, 2)) * dcm(0, 1),
.pitch = atan2f(dcm(2, 0), dcm(2, 2)) * dcm(1, 1) - atan2f(dcm(2, 1), dcm(2, 2)) * dcm(1, 0),
.yaw = 0.0f, // atan2f(dcm(1, 1), dcm(0, 1)),
.roll_vel = gyro.x(),
.pitch_vel = gyro.y(),
.yaw_vel = gyro.z()
};
if(attitudeMessageStream.ready()) {
protocol::message::attitude_message_t m {
.dcm = {
// estimate.roll, estimate.pitch, estimate.yaw,
// accel(0), accel(1), accel(2),
// gyro(0), gyro(1), gyro(2),
dcm(0, 0), dcm(0, 1), dcm(0, 2),
dcm(1, 0), dcm(1, 1), dcm(1, 2),
dcm(2, 0), dcm(2, 1), dcm(2, 2)
}
};
attitudeMessageStream.publish(m);
}
return estimate;
}
void DCMAttitudeEstimator::orthonormalize() {
// Make the i and j vectors orthogonal
float error = dcm.row(0).dot(dcm.row(1));
Eigen::Matrix3f corr = Eigen::Matrix3f::Zero();
corr.row(0) = dcm.row(1) * (-error) / 2;
corr.row(1) = dcm.row(0) * (-error) / 2;
dcm.row(0) += corr.row(0);
dcm.row(1) += corr.row(1);
// Estimate k vector from corrected i and j vectors
dcm.row(2) = dcm.row(0).cross(dcm.row(1));
// Normalize all vectors
dcm.rowwise().normalize();
}
<commit_msg>Lower accelerometer weighting and use abs.<commit_after>#include "estimator/dcm_attitude_estimator.hpp"
#include "hal.h"
#include "protocol/messages.hpp"
#include "unit_config.hpp"
DCMAttitudeEstimator::DCMAttitudeEstimator(Communicator& communicator)
: dcm(Eigen::Matrix3f::Identity()),
attitudeMessageStream(communicator, 20) {
}
attitude_estimate_t DCMAttitudeEstimator::update(gyroscope_reading_t& gyroReading, accelerometer_reading_t& accelReading) {
Eigen::Vector3f gyro(gyroReading.axes.data());
Eigen::Vector3f accel(accelReading.axes.data());
float accWeight = 0.002f;
if(abs(accel.norm()) > 1.5 || abs(accel.norm()) < 0.5) {
accWeight = 0.0f;
}
accel.normalize();
Eigen::Vector3f corr = Eigen::Vector3f::Zero();
corr += gyro * unit_config::DT * (1.0f - accWeight);
corr -= dcm.col(2).cross(-accel) * accWeight;
Eigen::Matrix3f dcmStep;
dcmStep << 1.0f, corr.z(), -corr.y(),
-corr.z(), 1.0f, corr.x(),
corr.y(), -corr.x(), 1.0f;
dcm = dcmStep * dcm;
orthonormalize();
attitude_estimate_t estimate {
// TODO: Are these trig functions safe at extreme angles?
.roll = -atan2f(dcm(2, 1), dcm(2, 2)) * dcm(0, 0) + atan2f(dcm(2, 0), dcm(2, 2)) * dcm(0, 1),
.pitch = atan2f(dcm(2, 0), dcm(2, 2)) * dcm(1, 1) - atan2f(dcm(2, 1), dcm(2, 2)) * dcm(1, 0),
.yaw = 0.0f, // atan2f(dcm(1, 1), dcm(0, 1)),
.roll_vel = gyro.x(),
.pitch_vel = gyro.y(),
.yaw_vel = gyro.z()
};
if(attitudeMessageStream.ready()) {
protocol::message::attitude_message_t m {
.dcm = {
// estimate.roll, estimate.pitch, estimate.yaw,
// accel(0), accel(1), accel(2),
// gyro(0), gyro(1), gyro(2),
dcm(0, 0), dcm(0, 1), dcm(0, 2),
dcm(1, 0), dcm(1, 1), dcm(1, 2),
dcm(2, 0), dcm(2, 1), dcm(2, 2)
}
};
attitudeMessageStream.publish(m);
}
return estimate;
}
void DCMAttitudeEstimator::orthonormalize() {
// Make the i and j vectors orthogonal
float error = dcm.row(0).dot(dcm.row(1));
Eigen::Matrix3f corr = Eigen::Matrix3f::Zero();
corr.row(0) = dcm.row(1) * (-error) / 2;
corr.row(1) = dcm.row(0) * (-error) / 2;
dcm.row(0) += corr.row(0);
dcm.row(1) += corr.row(1);
// Estimate k vector from corrected i and j vectors
dcm.row(2) = dcm.row(0).cross(dcm.row(1));
// Normalize all vectors
dcm.rowwise().normalize();
}
<|endoftext|> |
<commit_before>#include "NeuralNetwork.h"
#include <iostream> /////////////////
#include <time.h>
#include <cmath>
int randSeed = (int)(time(NULL)%10000); /* Random seed */ ///////////////Test max limit
int randA = 4545; /* Random a value */
int randB = 8334; /* Random b value */
int randM = 8427; /* Random m value */
double ActivationFunction(double z){
double activation = 1.0/(1+exp(z*(-1))); /* Sigmoid */
//double activation = tanh(z); /* Hyperbolic tangent */
return activation;
}
int RandomNumber(int zeroToX)
{
randSeed = (((randSeed*randA) + randB)%randM);
return (int)floor((((double)randSeed/(double)randM)*(double)zeroToX));
}
Neuron::Neuron(int lastLayer)
{
for(int nOW = 0; nOW < lastLayer; nOW++){
int positivNegativ = RandomNumber(2) == 0 ? -1 : 1;
int answer = RandomNumber(128)*positivNegativ;
this->weights.push_back(answer); /* Binary: 1111111 */
}
}
double Neuron::WeightInput(std::vector< double > inputFromLastLayer){
double neuronSum = 0;
for(int neuronIndex = 0; neuronIndex < inputFromLastLayer.size()-1; neuronIndex++){
neuronSum += (inputFromLastLayer.at(neuronIndex) * this->weights.at(neuronIndex));
}
return ActivationFunction(neuronSum);
}
Layer::Layer(int numberOfNeurons, int lastLayer)
{
for(int nON = 0; nON < numberOfNeurons; nON++){
neurons.push_back(Neuron(lastLayer+1));
}
}
std::vector< double > Layer::WeightNeurons(std::vector< double > inputFromLastLayer){
inputFromLastLayer.push_back(1.0);
std::vector< double > outputVector;
for(int neuronIndex = 0; neuronIndex < this->neurons.size(); neuronIndex++){
outputVector.push_back(this->neurons.at(neuronIndex).WeightInput(inputFromLastLayer));
}
outputVector.push_back(1); /* Bias value */
return outputVector;
}
NeuralNetwork::NeuralNetwork(std::vector< int > networkSize)
{
for(int nOL = 1; nOL < networkSize.size(); nOL++){
layers.push_back(Layer(networkSize.at(nOL), networkSize.at(nOL-1))); /* Runs through the rest of the layers */
}
fitness = 0; /* Fitness is set to zero from beginning */
}
std::vector< double > NeuralNetwork::GetOutput(std::vector< double > NNInput)
{
for(int layerIndex = 1; layerIndex < this->layers.size(); layerIndex++){
NNInput = this->layers.at(layerIndex).WeightNeurons(NNInput);
}
std::vector< double > outputVector;
for(int outputWithoutBias = 0; outputWithoutBias < NNInput.size()-1; outputWithoutBias++){
outputVector.push_back(NNInput.at(outputWithoutBias));
}
return outputVector;
}
void NeuralNetwork::addFitness(double fitnessScore)
{
this->fitness = fitnessScore;
}
double NeuralNetwork::getFitness()
{
return this->fitness;
}
NetworkContainer::NetworkContainer(int numberOfNetworks, std::vector< int > networkSize)
{
for(int networkIndex = 0; networkIndex < numberOfNetworks; networkIndex++){
this->NeuralNetworks.push_back(NeuralNetwork(networkSize));
}
}
void NetworkContainer::breed()
{
}
<commit_msg>Delete NeuralNetwork.cpp<commit_after><|endoftext|> |
<commit_before>/* The Image Registration Toolkit (IRTK)
*
* Copyright 2008-2015 Imperial College London
*
* 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 <irtkEulerMethod.h>
#include <irtkDeformableSurfaceModel.h>
// =============================================================================
// Auxiliary functors
// =============================================================================
namespace irtkEulerMethodUtils {
// -----------------------------------------------------------------------------
/// Negate deformable surface model gradient to obtain sum of forces
class NegateValues
{
const double *_Input;
double *_Output;
public:
NegateValues(double *b, const double *a = NULL)
:
_Input(a ? a : b), _Output(b)
{}
void operator ()(const blocked_range<int> &re) const
{
for (int i = re.begin(); i != re.end(); ++i) {
_Output[i] = -_Input[i];
}
}
};
// -----------------------------------------------------------------------------
/// Compute/update node velocities
class ComputeVelocities
{
irtkEulerMethod *_Optimizer;
const double *_Force;
vtkDataArray *_Velocity;
public:
ComputeVelocities(irtkEulerMethod *obj, const double *f, vtkDataArray *v)
:
_Optimizer(obj), _Force(f), _Velocity(v)
{}
void operator ()(const blocked_range<int> &re) const
{
double v[3];
const double *f = _Force + 3 * re.begin();
for (int ptId = re.begin(); ptId != re.end(); ++ptId, f += 3) {
_Velocity->GetTuple(ptId, v);
_Optimizer->ComputeVelocity(v, f);
_Velocity->SetTuple(ptId, v);
}
}
};
// -----------------------------------------------------------------------------
/// Compute displacements from velocities and temporal integration step length
class ComputeDisplacements
{
irtkEulerMethod *_Optimizer;
vtkDataArray *_Velocity;
double *_Displacement;
double _StepLength;
public:
ComputeDisplacements(irtkEulerMethod *obj, vtkDataArray *v, double dt, double *d)
:
_Optimizer(obj), _Velocity(v), _Displacement(d), _StepLength(dt)
{}
void operator ()(const blocked_range<int> &re) const
{
double v[3], *d = _Displacement + 3 * re.begin();
for (int ptId = re.begin(); ptId != re.end(); ++ptId, d += 3) {
_Velocity->GetTuple(ptId, v);
d[0] = v[0] * _StepLength;
d[1] = v[1] * _StepLength;
d[2] = v[2] * _StepLength;
}
}
};
} // namespace irtkEulerMethodUtils
using namespace irtkEulerMethodUtils;
// =============================================================================
// Construction/Destruction
// =============================================================================
// -----------------------------------------------------------------------------
void irtkEulerMethod::Copy(const irtkEulerMethod &other)
{
Deallocate(_Force);
Deallocate(_Displacement);
_NumberOfSteps = other._NumberOfSteps;
_DampingFactor = other._DampingFactor;
_StepLength = other._StepLength;
_NumberOfDOFs = other._NumberOfDOFs;
if (_NumberOfDOFs > 0) {
_Force = Allocate<double>(_NumberOfDOFs);
memcpy(_Force, other._Force, _NumberOfDOFs * sizeof(double));
_Displacement = Allocate<double>(_NumberOfDOFs);
memcpy(_Displacement, other._Displacement, _NumberOfDOFs * sizeof(double));
}
}
// -----------------------------------------------------------------------------
irtkEulerMethod::irtkEulerMethod(irtkObjectiveFunction *f)
:
irtkLocalOptimizer(f),
_NumberOfSteps(100),
_DampingFactor(1),
_StepLength(1.0),
_Force(NULL),
_Displacement(NULL),
_NumberOfDOFs(0)
{
}
// -----------------------------------------------------------------------------
irtkEulerMethod::irtkEulerMethod(const irtkEulerMethod &other)
:
irtkLocalOptimizer(other),
_Force(NULL),
_Displacement(NULL)
{
Copy(other);
}
// -----------------------------------------------------------------------------
irtkEulerMethod &irtkEulerMethod::operator =(const irtkEulerMethod &other)
{
irtkLocalOptimizer::operator =(other);
Copy(other);
return *this;
}
// -----------------------------------------------------------------------------
irtkEulerMethod::~irtkEulerMethod()
{
Deallocate(_Force);
Deallocate(_Displacement);
}
// =============================================================================
// Parameters
// =============================================================================
// -----------------------------------------------------------------------------
bool irtkEulerMethod::Set(const char *name, const char *value)
{
if (strcmp(name, "Maximum no. of iterations") == 0 ||
strcmp(name, "Maximum number of iterations") == 0 ||
strcmp(name, "Maximum no. of gradient steps") == 0 ||
strcmp(name, "Maximum number of gradient steps") == 0 ||
strcmp(name, "No. of iterations") == 0 ||
strcmp(name, "Number of iterations") == 0 ||
strcmp(name, "No. of gradient steps") == 0 ||
strcmp(name, "Number of gradient steps") == 0) {
return FromString(value, _NumberOfSteps);
}
if (strcmp(name, "Deformable surface damping") == 0) {
return FromString(value, _DampingFactor);
}
if (strcmp(name, "Deformable surface step length") == 0 ||
strcmp(name, "Length of steps") == 0 ||
strcmp(name, "Maximum length of steps") == 0) {
return FromString(value, _StepLength);
}
return irtkLocalOptimizer::Set(name, value);
}
// -----------------------------------------------------------------------------
irtkParameterList irtkEulerMethod::Parameter() const
{
irtkParameterList params = irtkLocalOptimizer::Parameter();
Insert(params, "Maximum no. of iterations", _NumberOfSteps);
Insert(params, "Deformable surface damping", _DampingFactor);
Insert(params, "Length of steps", _StepLength);
return params;
}
// =============================================================================
// Optimization
// =============================================================================
// -----------------------------------------------------------------------------
void irtkEulerMethod::Initialize()
{
// Initialize base class
irtkLocalOptimizer::Initialize();
// Cast objective function to deformable surface model
_Model = dynamic_cast<irtkDeformableSurfaceModel *>(_Function);
if (_Model == NULL) {
cerr << "irtkEulerMethod::Initialize: Objective function must be a deformable surface model" << endl;
exit(1);
}
if (_Model->Transformation()) {
cerr << "irtkEulerMethod::Initialize: Optimizer can only be used for non-parametric deformable surface models" << endl;
exit(1);
}
// Allocate memory for node vectors if not done before
if (_Model->NumberOfDOFs() > _NumberOfDOFs) {
Deallocate(_Force);
Deallocate(_Displacement);
_NumberOfDOFs = _Model->NumberOfDOFs();
Allocate(_Force, _NumberOfDOFs);
Allocate(_Displacement, _NumberOfDOFs);
}
// Add point data array with initial node velocities such that these
// are interpolated at new node positions during the remeshing
vtkSmartPointer<vtkDataArray> velocity;
velocity = _Model->Output()->GetPointData()->GetArray("Velocity");
if (!velocity) {
velocity = vtkSmartPointer<vtkFloatArray>::New();
velocity->SetName("Velocity");
velocity->SetNumberOfComponents(3);
_Model->Output()->GetPointData()->AddArray(velocity);
}
velocity->SetNumberOfTuples(_Model->NumberOfPoints());
velocity->FillComponent(0, .0);
velocity->FillComponent(1, .0);
velocity->FillComponent(2, .0);
}
// -----------------------------------------------------------------------------
double irtkEulerMethod::Run()
{
// Initialize
this->Initialize();
// Initial update of deformable surface model before start event because
// the update can trigger some lazy initialization which in turn may
// broadcast some log events for verbose command output
_Model->Update(true);
// Notify observers about start of optimization
Broadcast(StartEvent);
// Get initial energy value
double value = _Model->Value();
if (IsNaN(value)) {
cerr << "irtkEulerMethod::Run:" << __LINE__ << ": NaN objective function value!" << endl;
exit(1);
}
// Perform explicit integration steps
irtkIteration step(0, _NumberOfSteps);
while (step.Next()) {
// Notify observers about start of iteration
Broadcast(IterationStartEvent, &step);
// Update node velocities
this->UpdateVelocity();
// Check equilibrium condition
//
// TODO: Determine ratio of nodes with (close to) zero velocity and
// break if it falls below a user-defined threshold.
vtkDataArray *velocity = _Model->Output()->GetPointData()->GetArray("Velocity");
const double max_delta = velocity->GetMaxNorm();
if (fequal(max_delta, .0)) break;
// Move points of surface model
ComputeDisplacements mul(this, velocity, _StepLength / max_delta, _Displacement);
parallel_for(blocked_range<int>(0, _Model->NumberOfPoints()), mul);
_Model->EnforceHardConstraints(_Displacement);
_Model->SmoothGradient(_Displacement);
if (_Model->GradientNorm(_Displacement) <= _Delta) break;
_Model->Step(_Displacement);
// Perform local adaptive remeshing
if (_Model->Remesh()) {
if (_Model->NumberOfDOFs() > _NumberOfDOFs) {
Deallocate(_Force);
Deallocate(_Displacement);
_NumberOfDOFs = _Model->NumberOfDOFs();
Allocate(_Force, _NumberOfDOFs);
Allocate(_Displacement, _NumberOfDOFs);
}
}
// Update deformable surface model
_Model->Update(true);
// Check convergence towards local minimum of energy function
//
// For deformable surface models which are not defined as a local minimum
// of a well-defined energy function but only via the equilibrium of
// internal and external forces, the energy values corresponding to the
// external forces are infinite and hence the total energy value
if (!IsInf(value)) {
const double prev = value;
value = _Model->Value();
if (IsNaN(value)) {
cerr << "irtkEulerMethod::Run:" << __LINE__ << ": NaN objective function value!" << endl;
exit(1);
}
if (fabs(value - prev) <= _Epsilon) break;
}
// Notify observers about end of iteration
Broadcast(IterationEndEvent, &step);
}
// Notify observers about end of optimization
Broadcast(EndEvent, &value);
// Finalize
this->Finalize();
return value;
}
// -----------------------------------------------------------------------------
void irtkEulerMethod::UpdateVelocity()
{
// Compute forces
double * const gradient = _Force;
_Model->Gradient(gradient);
NegateValues negate(_Force, gradient);
parallel_for(blocked_range<int>(0, _Model->NumberOfDOFs()), negate);
// Update velocities
vtkDataArray *velocity = _Model->Output()->GetPointData()->GetArray("Velocity");
ComputeVelocities eval(this, _Force, velocity);
parallel_for(blocked_range<int>(0, _Model->NumberOfPoints()), eval);
}
// -----------------------------------------------------------------------------
void irtkEulerMethod::ComputeVelocity(double *v, const double *f) const
{
v[0] = f[0] / _DampingFactor;
v[1] = f[1] / _DampingFactor;
v[2] = f[2] / _DampingFactor;
}
// -----------------------------------------------------------------------------
void irtkEulerMethod::Finalize()
{
Deallocate(_Force);
Deallocate(_Displacement);
_Model->Output()->GetPointData()->RemoveArray("Velocity");
}
<commit_msg>#49 Remove unused private attribute in irtkEulerMethod.cc<commit_after>/* The Image Registration Toolkit (IRTK)
*
* Copyright 2008-2015 Imperial College London
*
* 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 <irtkEulerMethod.h>
#include <irtkDeformableSurfaceModel.h>
// =============================================================================
// Auxiliary functors
// =============================================================================
namespace irtkEulerMethodUtils {
// -----------------------------------------------------------------------------
/// Negate deformable surface model gradient to obtain sum of forces
class NegateValues
{
const double *_Input;
double *_Output;
public:
NegateValues(double *b, const double *a = NULL)
:
_Input(a ? a : b), _Output(b)
{}
void operator ()(const blocked_range<int> &re) const
{
for (int i = re.begin(); i != re.end(); ++i) {
_Output[i] = -_Input[i];
}
}
};
// -----------------------------------------------------------------------------
/// Compute/update node velocities
class ComputeVelocities
{
irtkEulerMethod *_Optimizer;
const double *_Force;
vtkDataArray *_Velocity;
public:
ComputeVelocities(irtkEulerMethod *obj, const double *f, vtkDataArray *v)
:
_Optimizer(obj), _Force(f), _Velocity(v)
{}
void operator ()(const blocked_range<int> &re) const
{
double v[3];
const double *f = _Force + 3 * re.begin();
for (int ptId = re.begin(); ptId != re.end(); ++ptId, f += 3) {
_Velocity->GetTuple(ptId, v);
_Optimizer->ComputeVelocity(v, f);
_Velocity->SetTuple(ptId, v);
}
}
};
// -----------------------------------------------------------------------------
/// Compute displacements from velocities and temporal integration step length
class ComputeDisplacements
{
vtkDataArray *_Velocity;
double *_Displacement;
double _StepLength;
public:
ComputeDisplacements(vtkDataArray *v, double dt, double *d)
:
_Velocity(v), _Displacement(d), _StepLength(dt)
{}
void operator ()(const blocked_range<int> &re) const
{
double v[3], *d = _Displacement + 3 * re.begin();
for (int ptId = re.begin(); ptId != re.end(); ++ptId, d += 3) {
_Velocity->GetTuple(ptId, v);
d[0] = v[0] * _StepLength;
d[1] = v[1] * _StepLength;
d[2] = v[2] * _StepLength;
}
}
};
} // namespace irtkEulerMethodUtils
using namespace irtkEulerMethodUtils;
// =============================================================================
// Construction/Destruction
// =============================================================================
// -----------------------------------------------------------------------------
void irtkEulerMethod::Copy(const irtkEulerMethod &other)
{
Deallocate(_Force);
Deallocate(_Displacement);
_NumberOfSteps = other._NumberOfSteps;
_DampingFactor = other._DampingFactor;
_StepLength = other._StepLength;
_NumberOfDOFs = other._NumberOfDOFs;
if (_NumberOfDOFs > 0) {
_Force = Allocate<double>(_NumberOfDOFs);
memcpy(_Force, other._Force, _NumberOfDOFs * sizeof(double));
_Displacement = Allocate<double>(_NumberOfDOFs);
memcpy(_Displacement, other._Displacement, _NumberOfDOFs * sizeof(double));
}
}
// -----------------------------------------------------------------------------
irtkEulerMethod::irtkEulerMethod(irtkObjectiveFunction *f)
:
irtkLocalOptimizer(f),
_NumberOfSteps(100),
_DampingFactor(1),
_StepLength(1.0),
_Force(NULL),
_Displacement(NULL),
_NumberOfDOFs(0)
{
}
// -----------------------------------------------------------------------------
irtkEulerMethod::irtkEulerMethod(const irtkEulerMethod &other)
:
irtkLocalOptimizer(other),
_Force(NULL),
_Displacement(NULL)
{
Copy(other);
}
// -----------------------------------------------------------------------------
irtkEulerMethod &irtkEulerMethod::operator =(const irtkEulerMethod &other)
{
irtkLocalOptimizer::operator =(other);
Copy(other);
return *this;
}
// -----------------------------------------------------------------------------
irtkEulerMethod::~irtkEulerMethod()
{
Deallocate(_Force);
Deallocate(_Displacement);
}
// =============================================================================
// Parameters
// =============================================================================
// -----------------------------------------------------------------------------
bool irtkEulerMethod::Set(const char *name, const char *value)
{
if (strcmp(name, "Maximum no. of iterations") == 0 ||
strcmp(name, "Maximum number of iterations") == 0 ||
strcmp(name, "Maximum no. of gradient steps") == 0 ||
strcmp(name, "Maximum number of gradient steps") == 0 ||
strcmp(name, "No. of iterations") == 0 ||
strcmp(name, "Number of iterations") == 0 ||
strcmp(name, "No. of gradient steps") == 0 ||
strcmp(name, "Number of gradient steps") == 0) {
return FromString(value, _NumberOfSteps);
}
if (strcmp(name, "Deformable surface damping") == 0) {
return FromString(value, _DampingFactor);
}
if (strcmp(name, "Deformable surface step length") == 0 ||
strcmp(name, "Length of steps") == 0 ||
strcmp(name, "Maximum length of steps") == 0) {
return FromString(value, _StepLength);
}
return irtkLocalOptimizer::Set(name, value);
}
// -----------------------------------------------------------------------------
irtkParameterList irtkEulerMethod::Parameter() const
{
irtkParameterList params = irtkLocalOptimizer::Parameter();
Insert(params, "Maximum no. of iterations", _NumberOfSteps);
Insert(params, "Deformable surface damping", _DampingFactor);
Insert(params, "Length of steps", _StepLength);
return params;
}
// =============================================================================
// Optimization
// =============================================================================
// -----------------------------------------------------------------------------
void irtkEulerMethod::Initialize()
{
// Initialize base class
irtkLocalOptimizer::Initialize();
// Cast objective function to deformable surface model
_Model = dynamic_cast<irtkDeformableSurfaceModel *>(_Function);
if (_Model == NULL) {
cerr << "irtkEulerMethod::Initialize: Objective function must be a deformable surface model" << endl;
exit(1);
}
if (_Model->Transformation()) {
cerr << "irtkEulerMethod::Initialize: Optimizer can only be used for non-parametric deformable surface models" << endl;
exit(1);
}
// Allocate memory for node vectors if not done before
if (_Model->NumberOfDOFs() > _NumberOfDOFs) {
Deallocate(_Force);
Deallocate(_Displacement);
_NumberOfDOFs = _Model->NumberOfDOFs();
Allocate(_Force, _NumberOfDOFs);
Allocate(_Displacement, _NumberOfDOFs);
}
// Add point data array with initial node velocities such that these
// are interpolated at new node positions during the remeshing
vtkSmartPointer<vtkDataArray> velocity;
velocity = _Model->Output()->GetPointData()->GetArray("Velocity");
if (!velocity) {
velocity = vtkSmartPointer<vtkFloatArray>::New();
velocity->SetName("Velocity");
velocity->SetNumberOfComponents(3);
_Model->Output()->GetPointData()->AddArray(velocity);
}
velocity->SetNumberOfTuples(_Model->NumberOfPoints());
velocity->FillComponent(0, .0);
velocity->FillComponent(1, .0);
velocity->FillComponent(2, .0);
}
// -----------------------------------------------------------------------------
double irtkEulerMethod::Run()
{
// Initialize
this->Initialize();
// Initial update of deformable surface model before start event because
// the update can trigger some lazy initialization which in turn may
// broadcast some log events for verbose command output
_Model->Update(true);
// Notify observers about start of optimization
Broadcast(StartEvent);
// Get initial energy value
double value = _Model->Value();
if (IsNaN(value)) {
cerr << "irtkEulerMethod::Run:" << __LINE__ << ": NaN objective function value!" << endl;
exit(1);
}
// Perform explicit integration steps
irtkIteration step(0, _NumberOfSteps);
while (step.Next()) {
// Notify observers about start of iteration
Broadcast(IterationStartEvent, &step);
// Update node velocities
this->UpdateVelocity();
// Check equilibrium condition
//
// TODO: Determine ratio of nodes with (close to) zero velocity and
// break if it falls below a user-defined threshold.
vtkDataArray *velocity = _Model->Output()->GetPointData()->GetArray("Velocity");
const double max_delta = velocity->GetMaxNorm();
if (fequal(max_delta, .0)) break;
// Move points of surface model
ComputeDisplacements mul(velocity, _StepLength / max_delta, _Displacement);
parallel_for(blocked_range<int>(0, _Model->NumberOfPoints()), mul);
_Model->EnforceHardConstraints(_Displacement);
_Model->SmoothGradient(_Displacement);
if (_Model->GradientNorm(_Displacement) <= _Delta) break;
_Model->Step(_Displacement);
// Perform local adaptive remeshing
if (_Model->Remesh()) {
if (_Model->NumberOfDOFs() > _NumberOfDOFs) {
Deallocate(_Force);
Deallocate(_Displacement);
_NumberOfDOFs = _Model->NumberOfDOFs();
Allocate(_Force, _NumberOfDOFs);
Allocate(_Displacement, _NumberOfDOFs);
}
}
// Update deformable surface model
_Model->Update(true);
// Check convergence towards local minimum of energy function
//
// For deformable surface models which are not defined as a local minimum
// of a well-defined energy function but only via the equilibrium of
// internal and external forces, the energy values corresponding to the
// external forces are infinite and hence the total energy value
if (!IsInf(value)) {
const double prev = value;
value = _Model->Value();
if (IsNaN(value)) {
cerr << "irtkEulerMethod::Run:" << __LINE__ << ": NaN objective function value!" << endl;
exit(1);
}
if (fabs(value - prev) <= _Epsilon) break;
}
// Notify observers about end of iteration
Broadcast(IterationEndEvent, &step);
}
// Notify observers about end of optimization
Broadcast(EndEvent, &value);
// Finalize
this->Finalize();
return value;
}
// -----------------------------------------------------------------------------
void irtkEulerMethod::UpdateVelocity()
{
// Compute forces
double * const gradient = _Force;
_Model->Gradient(gradient);
NegateValues negate(_Force, gradient);
parallel_for(blocked_range<int>(0, _Model->NumberOfDOFs()), negate);
// Update velocities
vtkDataArray *velocity = _Model->Output()->GetPointData()->GetArray("Velocity");
ComputeVelocities eval(this, _Force, velocity);
parallel_for(blocked_range<int>(0, _Model->NumberOfPoints()), eval);
}
// -----------------------------------------------------------------------------
void irtkEulerMethod::ComputeVelocity(double *v, const double *f) const
{
v[0] = f[0] / _DampingFactor;
v[1] = f[1] / _DampingFactor;
v[2] = f[2] / _DampingFactor;
}
// -----------------------------------------------------------------------------
void irtkEulerMethod::Finalize()
{
Deallocate(_Force);
Deallocate(_Displacement);
_Model->Output()->GetPointData()->RemoveArray("Velocity");
}
<|endoftext|> |
<commit_before>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2006 Laurent Ribon ([email protected])
Version 0.9.6, packaged on June, 2006.
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLC-lib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_geometry.cpp Implementation of the GLC_Geometry class.
#include <QtDebug>
#include "glc_geometry.h"
#include "glc_openglexception.h"
//////////////////////////////////////////////////////////////////////
// Constructor destructor
//////////////////////////////////////////////////////////////////////
GLC_Geometry::GLC_Geometry(const QString& name, const QColor &color)
:GLC_Object(name)
, m_IsSelected(false) // By default geometry is not selected
, m_MatPos() // default constructor identity matrix
, m_ListID(0) // By default Display List = 0
, m_ListIsValid(false) // By default Display List is invalid
, m_GeometryIsValid(false) // By default geometry is invalid
, m_pMaterial(NULL) // By default No material
, m_IsBlended(false) // By default No Blending
, m_PolyFace(GL_FRONT_AND_BACK) // Default Faces style
, m_PolyMode(GL_FILL) // Default polyganal mode
, m_Color(color) // the Color
, m_Thikness(1.0) // By default thickness = 1.0
, m_IsVisible(true) // By default Visibility is true
{
if (!m_Color.isValid())
{
m_Color= Qt::white;
}
}
GLC_Geometry::GLC_Geometry(const GLC_Geometry& sourceGeom)
:GLC_Object(sourceGeom)
, m_MatPos(sourceGeom.m_MatPos)
, m_ListID(0) // By default Display List = 0
, m_ListIsValid(false) // By default Display List is invalid
, m_GeometryIsValid(false) // By default geometry is invalid
, m_pMaterial(NULL) // have to be set later in constructor
, m_IsBlended(sourceGeom.m_IsBlended)
, m_PolyFace(sourceGeom.m_PolyFace)
, m_PolyMode(sourceGeom.m_PolyMode)
, m_Thikness(sourceGeom.m_Thikness)
, m_IsVisible(sourceGeom.m_IsVisible)
{
m_Color= sourceGeom.m_Color;
// Material is set here
setMaterial(sourceGeom.getMaterial());
}
GLC_Geometry::~GLC_Geometry(void)
{
deleteList();
if (!!m_pMaterial)
{
m_pMaterial->delGLC_Geom(getID()); //Remove Geometry from the material usage collection
m_pMaterial= NULL;
}
}
/////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////
// Return Visibility state of geometry
const bool GLC_Geometry::isVisible(void) const
{
return m_IsVisible;
}
// Return an array of 4 GLfloat which represent the color
QColor GLC_Geometry::getRGBA(void) const
{
return m_Color;
}
// Return Color Red component
GLdouble GLC_Geometry::getdRed(void) const
{
return static_cast<GLdouble>(m_Color.redF());
}
// Return Color Green component
GLdouble GLC_Geometry::getdGreen(void) const
{
return static_cast<GLdouble>(m_Color.greenF());
}
// Return Color blue component
GLdouble GLC_Geometry::getdBlue(void) const
{
return static_cast<GLdouble>(m_Color.blueF());
}
// Return Color Alpha component
GLdouble GLC_Geometry::getdAlpha(void) const
{
return static_cast<GLdouble>(m_Color.alphaF());
}
// Return transfomation 4x4Matrix
const GLC_Matrix4x4 GLC_Geometry::getMatrix(void) const
{
return m_MatPos;
}
// Return thickness
const float GLC_Geometry::getThickness(void) const
{
return m_Thikness;
}
// Return associated OpenGL list ID
GLuint GLC_Geometry::getListID(void)
{
return m_ListID;
}
// Return Validity of associated OpenGL list
bool GLC_Geometry::getListIsValid(void) const
{
return m_ListIsValid;
}
// Return Validity of geometry
bool GLC_Geometry::getValidity(void) const
{
return (m_GeometryIsValid && m_ListIsValid);
}
// Return material of geometry
GLC_Material* GLC_Geometry::getMaterial(void) const
{
return m_pMaterial;
}
// Return true if blending is enable
bool GLC_Geometry::getBlending(void) const
{
return m_IsBlended;
}
// return the geometry bounding box
GLC_BoundingBox* GLC_Geometry::getBoundingBox(void) const
{
return NULL;
}
/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Select the Geometry
void GLC_Geometry::select(void)
{
m_IsSelected= true;
m_GeometryIsValid = false;
m_ListIsValid= false; // GLC_Mesh2 compatibility
}
// Unselect the Geometry
void GLC_Geometry::unselect(void)
{
m_IsSelected= false;
m_GeometryIsValid = false;
m_ListIsValid= false; // GLC_Mesh2 compatibility
}
// Set visibility statement
void GLC_Geometry::setVisibility(bool v)
{
m_IsVisible= v;
m_GeometryIsValid= false;
}
// Set Color RGBA component
void GLC_Geometry::setRGBAColor(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha)
{
m_Color.setRgbF(red, green, blue, alpha);
m_GeometryIsValid= false;
}
// Set Color RGBA component with an array of 4 GLfloat
void GLC_Geometry::setRGBAColor(const QColor& setCol)
{
m_Color= setCol;
m_GeometryIsValid= false;
}
// Geometry translation
void GLC_Geometry::translate(double Tx, double Ty, double Tz)
{
GLC_Matrix4x4 MatTrans(Tx, Ty, Tz);
multMatrix(MatTrans);
}
// move Geometry with a 4x4Matrix
void GLC_Geometry::multMatrix(const GLC_Matrix4x4 &MultMat)
{
m_MatPos= MultMat * m_MatPos;
m_GeometryIsValid= false;
}
// Replace the Geometry Matrix
void GLC_Geometry::setMatrix(const GLC_Matrix4x4 &SetMat)
{
m_MatPos= SetMat;
m_GeometryIsValid= false;
}
// Reset the Geometry Matrix
void GLC_Geometry::resetMatrix(void)
{
m_MatPos.setToIdentity();
m_GeometryIsValid= false;
}
// Set Wire thickness
void GLC_Geometry::setThikness(float SetEp)
{
SetEp= fabs(SetEp);
m_Thikness= SetEp;
m_GeometryIsValid= false;
}
// Set Blending
void GLC_Geometry::setBlending(bool Blending)
{
m_IsBlended= Blending;
m_GeometryIsValid= false;
}
// Polygon's display style
void GLC_Geometry::setPolygonMode(GLenum Face, GLenum Mode)
{
m_PolyFace= Face;
m_PolyMode= Mode;
m_GeometryIsValid = false;
}
// Material
void GLC_Geometry::setMaterial(GLC_Material* pMat)
{
if (pMat != m_pMaterial)
{
if (!!pMat)
{
if (!pMat->addGLC_Geom(this))
{
return;
}
}
if (!!m_pMaterial)
{
m_pMaterial->delGLC_Geom(getID());
}
m_pMaterial= pMat;
m_Color= pMat->getAmbientColor();
m_GeometryIsValid = false;
m_ListIsValid= false; // GLC_Mesh2 compatibility
}
else
{
// Force la mise � jour
m_GeometryIsValid = false;
m_ListIsValid= false; // GLC_Mesh2 compatibility
}
}
// Remove Geometry from the material without update material usage table
void GLC_Geometry::delMaterial(GLC_Geometry* pGeom)
{
//! \todo modify this algo
if (this == pGeom)
{
m_pMaterial= NULL;
}
else
{
qDebug("GLC_Geometrie::DelMatiere : Erreur GLC_Geometrie* not Match");
}
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
// Create and execute Geometry's display list
bool GLC_Geometry::createList(GLenum Mode)
{
if(!m_ListID) // The list doesn't exist
{
m_ListID= glGenLists(1);
if (!m_ListID) // List ID not obtain
{
glDraw();
qDebug("GLC_Geometry::createList ERROR Display list not created");
return false; // Display geometry whithout OpenGL display list
}
}
// List setting up
glNewList(m_ListID, Mode);
// Geometrie set up and display
glDraw(); // Virtual function defined in concrete class
glEndList();
// List is valid
m_ListIsValid= true;
return true; // Display geometry with OpenGL display list
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Geometry::createList ", error);
throw(OpenGlException);
}
}
// Geometry display
void GLC_Geometry::glExecute(GLenum Mode)
{
if (isVisible())
{
// Object ID for selection purpose
glLoadName(getID());
// Save current OpenGL Matrix
glPushMatrix();
// Define Geometry's property
glPropGeom(); // Virtual function defined in concrete class
// Geometry validity set to true
m_GeometryIsValid= true;
if (!getListIsValid())
{
// The list is not up to date or doesn't exist
createList(Mode);
}
else
{
glCallList(m_ListID);
}
// To avoid Blending issue
glDepthMask(GL_TRUE);
glPopMatrix();
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Geometry::GlExecute ", error);
throw(OpenGlException);
}
}
else
{
m_GeometryIsValid= true; // Used to avoid multi list creation
}
}
//////////////////////////////////////////////////////////////////////
// Protected services functions
//////////////////////////////////////////////////////////////////////
// Delete OpenGL list
/* Call by GLC_Geometry::~GLC_Geometry*/
void GLC_Geometry::deleteList()
{
// If display list is valid : delete it
if (glIsList(m_ListID))
{
glDeleteLists(m_ListID, 1);
}
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Geometry::DeleteList ", error);
throw(OpenGlException);
}
}
<commit_msg>Add the glPropGeom method to GLC_Geometry class. (no longer pure virtual) remove QColor property Use a default GLC_Material When GLC_Geometry is deleted, if the material is not used it deleted<commit_after>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2006 Laurent Ribon ([email protected])
Version 0.9.6, packaged on June, 2006.
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLC-lib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_geometry.cpp Implementation of the GLC_Geometry class.
#include <QtDebug>
#include "glc_geometry.h"
#include "glc_openglexception.h"
#include "glc_selectionmaterial.h"
//////////////////////////////////////////////////////////////////////
// Constructor destructor
//////////////////////////////////////////////////////////////////////
GLC_Geometry::GLC_Geometry(const QString& name, const QColor &color, const bool typeIsWire)
:GLC_Object(name)
, m_IsSelected(false) // By default geometry is not selected
, m_MatPos() // default constructor identity matrix
, m_ListID(0) // By default Display List = 0
, m_ListIsValid(false) // By default Display List is invalid
, m_GeometryIsValid(false) // By default geometry is invalid
, m_pMaterial(NULL) // have to be set later in constructor
, m_IsBlended(false) // By default No Blending
, m_PolyFace(GL_FRONT_AND_BACK) // Default Faces style
, m_PolyMode(GL_FILL) // Default polyganal mode
, m_Thikness(1.0) // By default thickness = 1.0
, m_IsVisible(true) // By default Visibility is true
, m_IsWire(typeIsWire) // the geometry type
{
// Material is set here
setMaterial(new GLC_Material(color));
}
GLC_Geometry::GLC_Geometry(const GLC_Geometry& sourceGeom)
:GLC_Object(sourceGeom)
, m_MatPos(sourceGeom.m_MatPos)
, m_ListID(0) // By default Display List = 0
, m_ListIsValid(false) // By default Display List is invalid
, m_GeometryIsValid(false) // By default geometry is invalid
, m_pMaterial(NULL) // have to be set later in constructor
, m_IsBlended(sourceGeom.m_IsBlended)
, m_PolyFace(sourceGeom.m_PolyFace)
, m_PolyMode(sourceGeom.m_PolyMode)
, m_Thikness(sourceGeom.m_Thikness)
, m_IsVisible(sourceGeom.m_IsVisible)
, m_IsWire(sourceGeom.m_IsWire)
{
// Material is set here
setMaterial(sourceGeom.getMaterial());
}
GLC_Geometry::~GLC_Geometry(void)
{
deleteList();
if (!!m_pMaterial)
{
m_pMaterial->delGLC_Geom(getID()); //Remove Geometry from the material usage collection
if (m_pMaterial->isUnused()) delete m_pMaterial;
m_pMaterial= NULL;
}
}
/////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////
// Return Visibility state of geometry
const bool GLC_Geometry::isVisible(void) const
{
return m_IsVisible;
}
// Return an array of 4 GLfloat which represent the color
QColor GLC_Geometry::getRGBA(void) const
{
return m_pMaterial->getAmbientColor();
}
// Return Color Red component
GLdouble GLC_Geometry::getdRed(void) const
{
return static_cast<GLdouble>(m_pMaterial->getAmbientColor().redF());
}
// Return Color Green component
GLdouble GLC_Geometry::getdGreen(void) const
{
return static_cast<GLdouble>(m_pMaterial->getAmbientColor().greenF());
}
// Return Color blue component
GLdouble GLC_Geometry::getdBlue(void) const
{
return static_cast<GLdouble>(m_pMaterial->getAmbientColor().blueF());
}
// Return Color Alpha component
GLdouble GLC_Geometry::getdAlpha(void) const
{
return static_cast<GLdouble>(m_pMaterial->getAmbientColor().alphaF());
}
// Return transfomation 4x4Matrix
const GLC_Matrix4x4 GLC_Geometry::getMatrix(void) const
{
return m_MatPos;
}
// Return thickness
const float GLC_Geometry::getThickness(void) const
{
return m_Thikness;
}
// Return associated OpenGL list ID
GLuint GLC_Geometry::getListID(void)
{
return m_ListID;
}
// Return Validity of associated OpenGL list
bool GLC_Geometry::getListIsValid(void) const
{
return m_ListIsValid;
}
// Return Validity of geometry
bool GLC_Geometry::getValidity(void) const
{
return (m_GeometryIsValid && m_ListIsValid);
}
// Return material of geometry
GLC_Material* GLC_Geometry::getMaterial(void) const
{
return m_pMaterial;
}
// Return true if blending is enable
bool GLC_Geometry::getBlending(void) const
{
return m_IsBlended;
}
// return the geometry bounding box
GLC_BoundingBox* GLC_Geometry::getBoundingBox(void) const
{
return NULL;
}
/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Select the Geometry
void GLC_Geometry::select(void)
{
m_IsSelected= true;
m_GeometryIsValid = false;
m_ListIsValid= false; // GLC_Mesh2 compatibility
}
// Unselect the Geometry
void GLC_Geometry::unselect(void)
{
m_IsSelected= false;
m_GeometryIsValid = false;
m_ListIsValid= false; // GLC_Mesh2 compatibility
}
// Set visibility statement
void GLC_Geometry::setVisibility(bool v)
{
m_IsVisible= v;
m_GeometryIsValid= false;
}
// Set Color RGBA component
void GLC_Geometry::setRGBAColor(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha)
{
QColor setColor;
setColor.setRgbF(red, green, blue, alpha);
m_pMaterial->setAmbientColor(setColor);
m_GeometryIsValid= false;
}
// Set Color RGBA component with an array of 4 GLfloat
void GLC_Geometry::setRGBAColor(const QColor& setCol)
{
m_pMaterial->setAmbientColor(setCol);
m_GeometryIsValid= false;
}
// Geometry translation
void GLC_Geometry::translate(double Tx, double Ty, double Tz)
{
GLC_Matrix4x4 MatTrans(Tx, Ty, Tz);
multMatrix(MatTrans);
}
// move Geometry with a 4x4Matrix
void GLC_Geometry::multMatrix(const GLC_Matrix4x4 &MultMat)
{
m_MatPos= MultMat * m_MatPos;
m_GeometryIsValid= false;
}
// Replace the Geometry Matrix
void GLC_Geometry::setMatrix(const GLC_Matrix4x4 &SetMat)
{
m_MatPos= SetMat;
m_GeometryIsValid= false;
}
// Reset the Geometry Matrix
void GLC_Geometry::resetMatrix(void)
{
m_MatPos.setToIdentity();
m_GeometryIsValid= false;
}
// Set Wire thickness
void GLC_Geometry::setThikness(float SetEp)
{
SetEp= fabs(SetEp);
m_Thikness= SetEp;
m_GeometryIsValid= false;
}
// Set Blending
void GLC_Geometry::setBlending(bool Blending)
{
m_IsBlended= Blending;
m_GeometryIsValid= false;
}
// Polygon's display style
void GLC_Geometry::setPolygonMode(GLenum Face, GLenum Mode)
{
m_PolyFace= Face;
m_PolyMode= Mode;
m_GeometryIsValid = false;
}
// Material
void GLC_Geometry::setMaterial(GLC_Material* pMat)
{
if (pMat != m_pMaterial)
{
if (!!pMat)
{
if (!pMat->addGLC_Geom(this))
{
return;
}
}
if (!!m_pMaterial)
{
m_pMaterial->delGLC_Geom(getID());
if (m_pMaterial->isUnused()) delete m_pMaterial;
}
m_pMaterial= pMat;
m_GeometryIsValid = false;
m_ListIsValid= false; // GLC_Mesh2 compatibility
}
else
{
// Force la mise � jour
m_GeometryIsValid = false;
m_ListIsValid= false; // GLC_Mesh2 compatibility
}
}
// Remove Geometry from the material without update material usage table
void GLC_Geometry::delMaterial(GLC_Geometry* pGeom)
{
//! \todo modify this algo
if (this == pGeom)
{
m_pMaterial= NULL;
}
else
{
qDebug("GLC_Geometrie::DelMatiere : Erreur GLC_Geometrie* not Match");
}
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
// Create and execute Geometry's display list
bool GLC_Geometry::createList(GLenum Mode)
{
if(!m_ListID) // The list doesn't exist
{
m_ListID= glGenLists(1);
if (!m_ListID) // List ID not obtain
{
glDraw();
qDebug("GLC_Geometry::createList ERROR Display list not created");
return false; // Display geometry whithout OpenGL display list
}
}
// List setting up
glNewList(m_ListID, Mode);
// Geometrie set up and display
glDraw(); // Virtual function defined in concrete class
glEndList();
// List is valid
m_ListIsValid= true;
return true; // Display geometry with OpenGL display list
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Geometry::createList ", error);
throw(OpenGlException);
}
}
// Geometry display
void GLC_Geometry::glExecute(GLenum Mode)
{
if (isVisible())
{
// Object ID for selection purpose
glLoadName(getID());
// Save current OpenGL Matrix
glPushMatrix();
// Define Geometry's property
glPropGeom(); // Virtual function defined in concrete class
// Geometry validity set to true
m_GeometryIsValid= true;
if (!getListIsValid())
{
// The list is not up to date or doesn't exist
createList(Mode);
}
else
{
glCallList(m_ListID);
}
// To avoid Blending issue
glDepthMask(GL_TRUE);
glPopMatrix();
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Geometry::GlExecute ", error);
throw(OpenGlException);
}
}
else
{
m_GeometryIsValid= true; // Used to avoid multi list creation
}
}
//////////////////////////////////////////////////////////////////////
// Protected services functions
//////////////////////////////////////////////////////////////////////
// Delete OpenGL list
/* Call by GLC_Geometry::~GLC_Geometry*/
void GLC_Geometry::deleteList()
{
// If display list is valid : delete it
if (glIsList(m_ListID))
{
glDeleteLists(m_ListID, 1);
}
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Geometry::DeleteList ", error);
throw(OpenGlException);
}
}
// Virtual interface for OpenGL Geometry properties.
void GLC_Geometry::glPropGeom()
{
//! Change the current matrix
glMultMatrixd(m_MatPos.return_dMat());
// Polygons display mode
glPolygonMode(m_PolyFace, m_PolyMode);
if (m_IsBlended && !m_IsSelected)
{
glEnable(GL_BLEND);
glDepthMask(GL_FALSE);
}
else
{
glDisable(GL_BLEND);
}
if((m_PolyMode != GL_FILL) || m_IsWire)
{
glDisable(GL_TEXTURE_2D);
glDisable(GL_LIGHTING);
glLineWidth(getThickness()); // is thikness
if (m_IsSelected) GLC_SelectionMaterial::glExecute();
else glColor4d(getdRed(), getdGreen(), getdBlue(), getdAlpha()); // is color
}
else if (m_pMaterial->getAddRgbaTexture() && !m_IsSelected)
{
glEnable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
m_pMaterial->glExecute();
}
else
{
glDisable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
if (m_IsSelected) GLC_SelectionMaterial::glExecute();
else m_pMaterial->glExecute();
}
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Geometry::GlPropGeom ", error);
throw(OpenGlException);
}
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2006-2008 Matthias Kretz <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "globalconfig_p.h"
#include "factory_p.h"
#include "objectdescription.h"
#include "phonondefs_p.h"
#include "platformplugin.h"
#include "backendinterface.h"
#include "qsettingsgroup_p.h"
#include "phononnamespace_p.h"
#include <QtCore/QList>
#include <QtCore/QVariant>
QT_BEGIN_NAMESPACE
namespace Phonon
{
GlobalConfig::GlobalConfig(QObject *parent)
: QObject(parent)
, m_config(QLatin1String("kde.org"), QLatin1String("libphonon"))
{
}
GlobalConfig::~GlobalConfig()
{
}
static void filterAdvanced(BackendInterface *backendIface, QList<int> *list)
{
QMutableListIterator<int> it(*list);
while (it.hasNext()) {
const QHash<QByteArray, QVariant> properties = backendIface->objectDescriptionProperties(Phonon::AudioOutputDeviceType, it.next());
QVariant var = properties.value("isAdvanced");
if (var.isValid() && var.toBool()) {
it.remove();
}
}
}
static QList<int> listSortedByConfig(const QSettingsGroup &backendConfig, Phonon::Category category, QList<int> &defaultList)
{
if (defaultList.size() <= 1) {
// nothing to sort
return defaultList;
} else {
// make entries unique
QSet<int> seen;
QMutableListIterator<int> it(defaultList);
while (it.hasNext()) {
if (seen.contains(it.next())) {
it.remove();
} else {
seen.insert(it.value());
}
}
}
QString categoryKey = QLatin1String("Category") + QString::number(static_cast<int>(category));
if (!backendConfig.hasKey(categoryKey)) {
// no list in config for the given category
categoryKey = QLatin1String("Category") + QString::number(static_cast<int>(Phonon::NoCategory));
if (!backendConfig.hasKey(categoryKey)) {
// no list in config for NoCategory
return defaultList;
}
}
//Now the list from m_config
QList<int> deviceList = backendConfig.value(categoryKey, QList<int>());
//if there are devices in m_config that the backend doesn't report, remove them from the list
QMutableListIterator<int> i(deviceList);
while (i.hasNext()) {
if (0 == defaultList.removeAll(i.next())) {
i.remove();
}
}
//if the backend reports more devices that are not in m_config append them to the list
deviceList += defaultList;
return deviceList;
}
QList<int> GlobalConfig::audioOutputDeviceListFor(Phonon::Category category, HideAdvancedDevicesOverride override) const
{
//The devices need to be stored independently for every backend
const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioOutputDevice")); // + Factory::identifier());
const QSettingsGroup generalGroup(&m_config, QLatin1String("General"));
const bool hideAdvancedDevices = (override == FromSettings
? generalGroup.value(QLatin1String("HideAdvancedDevices"), true)
: static_cast<bool>(override));
PlatformPlugin *platformPlugin = Factory::platformPlugin();
BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend());
QList<int> defaultList;
if (platformPlugin) {
// the platform plugin lists the audio devices for the platform
// this list already is in default order (as defined by the platform plugin)
defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioOutputDeviceType);
QMutableListIterator<int> it(defaultList);
while (it.hasNext()) {
AudioOutputDevice objDesc = AudioOutputDevice::fromIndex(it.next());
const QVariant var = objDesc.property("isAdvanced");
if (var.isValid() && var.toBool()) {
it.remove();
}
}
}
// lookup the available devices directly from the backend (mostly for virtual devices)
if (backendIface) {
// this list already is in default order (as defined by the backend)
QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioOutputDeviceType);
if (hideAdvancedDevices) {
filterAdvanced(backendIface, &list);
}
defaultList += list;
}
return listSortedByConfig(backendConfig, category, defaultList);
}
int GlobalConfig::audioOutputDeviceFor(Phonon::Category category) const
{
QList<int> ret = audioOutputDeviceListFor(category);
if (ret.isEmpty())
return -1;
return ret.first();
}
QList<int> GlobalConfig::audioCaptureDeviceListFor(Phonon::Category category, HideAdvancedDevicesOverride override) const
{
//The devices need to be stored independently for every backend
const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioCaptureDevice")); // + Factory::identifier());
const QSettingsGroup generalGroup(&m_config, QLatin1String("General"));
const bool hideAdvancedDevices = (override == FromSettings
? generalGroup.value(QLatin1String("HideAdvancedDevices"), true)
: static_cast<bool>(override));
PlatformPlugin *platformPlugin = Factory::platformPlugin();
BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend());
QList<int> defaultList;
if (platformPlugin) {
// the platform plugin lists the audio devices for the platform
// this list already is in default order (as defined by the platform plugin)
defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType);
QMutableListIterator<int> it(defaultList);
while (it.hasNext()) {
AudioCaptureDevice objDesc = AudioCaptureDevice::fromIndex(it.next());
const QVariant var = objDesc.property("isAdvanced");
if (var.isValid() && var.toBool()) {
it.remove();
}
}
}
// lookup the available devices directly from the backend (mostly for virtual devices)
if (backendIface) {
// this list already is in default order (as defined by the backend)
QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType);
if (hideAdvancedDevices) {
filterAdvanced(backendIface, &list);
}
defaultList += list;
}
return listSortedByConfig(backendConfig, category, defaultList);
}
int GlobalConfig::audioCaptureDeviceFor(Phonon::Category category) const
{
QList<int> ret = audioCaptureDeviceListFor(category);
if (ret.isEmpty())
return -1;
return ret.first();
}
} // namespace Phonon
QT_END_NAMESPACE
#include "moc_globalconfig_p.cpp"
// vim: sw=4 ts=4
<commit_msg>filter out devices with isHardwareDevice set, if the platform plugin provides a list of devices already<commit_after>/* This file is part of the KDE project
Copyright (C) 2006-2008 Matthias Kretz <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "globalconfig_p.h"
#include "factory_p.h"
#include "objectdescription.h"
#include "phonondefs_p.h"
#include "platformplugin.h"
#include "backendinterface.h"
#include "qsettingsgroup_p.h"
#include "phononnamespace_p.h"
#include <QtCore/QList>
#include <QtCore/QVariant>
QT_BEGIN_NAMESPACE
namespace Phonon
{
GlobalConfig::GlobalConfig(QObject *parent)
: QObject(parent)
, m_config(QLatin1String("kde.org"), QLatin1String("libphonon"))
{
}
GlobalConfig::~GlobalConfig()
{
}
enum WhatToFilter {
FilterAdvancedDevices = 1,
FilterHardwareDevices = 2
};
static void filter(ObjectDescriptionType type, BackendInterface *backendIface, QList<int> *list, int whatToFilter)
{
QMutableListIterator<int> it(*list);
while (it.hasNext()) {
const QHash<QByteArray, QVariant> properties = backendIface->objectDescriptionProperties(type, it.next());
QVariant var;
if (whatToFilter & FilterAdvancedDevices) {
var = properties.value("isAdvanced");
if (var.isValid() && var.toBool()) {
it.remove();
continue;
}
}
if (whatToFilter & FilterHardwareDevices) {
var = properties.value("isHardwareDevice");
if (var.isValid() && var.toBool()) {
it.remove();
continue;
}
}
}
}
static QList<int> listSortedByConfig(const QSettingsGroup &backendConfig, Phonon::Category category, QList<int> &defaultList)
{
if (defaultList.size() <= 1) {
// nothing to sort
return defaultList;
} else {
// make entries unique
QSet<int> seen;
QMutableListIterator<int> it(defaultList);
while (it.hasNext()) {
if (seen.contains(it.next())) {
it.remove();
} else {
seen.insert(it.value());
}
}
}
QString categoryKey = QLatin1String("Category") + QString::number(static_cast<int>(category));
if (!backendConfig.hasKey(categoryKey)) {
// no list in config for the given category
categoryKey = QLatin1String("Category") + QString::number(static_cast<int>(Phonon::NoCategory));
if (!backendConfig.hasKey(categoryKey)) {
// no list in config for NoCategory
return defaultList;
}
}
//Now the list from m_config
QList<int> deviceList = backendConfig.value(categoryKey, QList<int>());
//if there are devices in m_config that the backend doesn't report, remove them from the list
QMutableListIterator<int> i(deviceList);
while (i.hasNext()) {
if (0 == defaultList.removeAll(i.next())) {
i.remove();
}
}
//if the backend reports more devices that are not in m_config append them to the list
deviceList += defaultList;
return deviceList;
}
QList<int> GlobalConfig::audioOutputDeviceListFor(Phonon::Category category, HideAdvancedDevicesOverride override) const
{
//The devices need to be stored independently for every backend
const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioOutputDevice")); // + Factory::identifier());
const QSettingsGroup generalGroup(&m_config, QLatin1String("General"));
const bool hideAdvancedDevices = (override == FromSettings
? generalGroup.value(QLatin1String("HideAdvancedDevices"), true)
: static_cast<bool>(override));
PlatformPlugin *platformPlugin = Factory::platformPlugin();
BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend());
QList<int> defaultList;
if (platformPlugin) {
// the platform plugin lists the audio devices for the platform
// this list already is in default order (as defined by the platform plugin)
defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioOutputDeviceType);
QMutableListIterator<int> it(defaultList);
while (it.hasNext()) {
AudioOutputDevice objDesc = AudioOutputDevice::fromIndex(it.next());
const QVariant var = objDesc.property("isAdvanced");
if (var.isValid() && var.toBool()) {
it.remove();
}
}
}
// lookup the available devices directly from the backend (mostly for virtual devices)
if (backendIface) {
// this list already is in default order (as defined by the backend)
QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioOutputDeviceType);
if (hideAdvancedDevices || !defaultList.isEmpty()) {
filter(AudioOutputDeviceType, backendIface, &list,
(hideAdvancedDevices ? FilterAdvancedDevices : 0)
// the platform plugin already provided the hardware devices
| (defaultList.isEmpty() ? 0 : FilterHardwareDevices)
);
}
defaultList += list;
}
return listSortedByConfig(backendConfig, category, defaultList);
}
int GlobalConfig::audioOutputDeviceFor(Phonon::Category category) const
{
QList<int> ret = audioOutputDeviceListFor(category);
if (ret.isEmpty())
return -1;
return ret.first();
}
QList<int> GlobalConfig::audioCaptureDeviceListFor(Phonon::Category category, HideAdvancedDevicesOverride override) const
{
//The devices need to be stored independently for every backend
const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioCaptureDevice")); // + Factory::identifier());
const QSettingsGroup generalGroup(&m_config, QLatin1String("General"));
const bool hideAdvancedDevices = (override == FromSettings
? generalGroup.value(QLatin1String("HideAdvancedDevices"), true)
: static_cast<bool>(override));
PlatformPlugin *platformPlugin = Factory::platformPlugin();
BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend());
QList<int> defaultList;
if (platformPlugin) {
// the platform plugin lists the audio devices for the platform
// this list already is in default order (as defined by the platform plugin)
defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType);
QMutableListIterator<int> it(defaultList);
while (it.hasNext()) {
AudioCaptureDevice objDesc = AudioCaptureDevice::fromIndex(it.next());
const QVariant var = objDesc.property("isAdvanced");
if (var.isValid() && var.toBool()) {
it.remove();
}
}
}
// lookup the available devices directly from the backend (mostly for virtual devices)
if (backendIface) {
// this list already is in default order (as defined by the backend)
QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType);
if (hideAdvancedDevices || !defaultList.isEmpty()) {
filter(AudioCaptureDeviceType, backendIface, &list,
(hideAdvancedDevices ? FilterAdvancedDevices : 0)
// the platform plugin already provided the hardware devices
| (defaultList.isEmpty() ? 0 : FilterHardwareDevices)
);
}
defaultList += list;
}
return listSortedByConfig(backendConfig, category, defaultList);
}
int GlobalConfig::audioCaptureDeviceFor(Phonon::Category category) const
{
QList<int> ret = audioCaptureDeviceListFor(category);
if (ret.isEmpty())
return -1;
return ret.first();
}
} // namespace Phonon
QT_END_NAMESPACE
#include "moc_globalconfig_p.cpp"
// vim: sw=4 ts=4
<|endoftext|> |
<commit_before>
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkColorPriv.h"
#include "SkGeometry.h"
#include "SkShader.h"
static void tesselate(const SkPath& src, SkPath* dst) {
SkPath::Iter iter(src, true);
SkPoint pts[4];
SkPath::Verb verb;
while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
switch (verb) {
case SkPath::kMove_Verb:
dst->moveTo(pts[0]);
break;
case SkPath::kLine_Verb:
dst->lineTo(pts[1]);
break;
case SkPath::kQuad_Verb: {
SkPoint p;
for (int i = 1; i <= 8; ++i) {
SkEvalQuadAt(pts, i / 8.0f, &p, NULL);
dst->lineTo(p);
}
} break;
case SkPath::kCubic_Verb: {
SkPoint p;
for (int i = 1; i <= 8; ++i) {
SkEvalCubicAt(pts, i / 8.0f, &p, NULL, NULL);
dst->lineTo(p);
}
} break;
}
}
}
static void setFade(SkPaint* paint, bool showGL) {
paint->setAlpha(showGL ? 0x66 : 0xFF);
}
static void setGLFrame(SkPaint* paint) {
paint->setColor(0xFFFF0000);
paint->setStyle(SkPaint::kStroke_Style);
paint->setAntiAlias(true);
paint->setStrokeWidth(1.1f);
}
static void show_mesh(SkCanvas* canvas, const SkRect& r) {
SkPaint paint;
setGLFrame(&paint);
canvas->drawRect(r, paint);
canvas->drawLine(r.fLeft, r.fTop, r.fRight, r.fBottom, paint);
}
static void drawLine(SkCanvas* canvas, const SkPoint& p0, const SkPoint& p1,
const SkPaint& paint) {
canvas->drawLine(p0.fX, p0.fY, p1.fX, p1.fY, paint);
}
static void show_mesh(SkCanvas* canvas, const SkPoint pts[],
const uint16_t indices[], int count) {
SkPaint paint;
setGLFrame(&paint);
for (int i = 0; i < count - 2; ++i) {
drawLine(canvas, pts[indices[i]], pts[indices[i+1]], paint);
drawLine(canvas, pts[indices[i+1]], pts[indices[i+2]], paint);
drawLine(canvas, pts[indices[i+2]], pts[indices[i]], paint);
}
}
static void show_glframe(SkCanvas* canvas, const SkPath& path) {
SkPaint paint;
setGLFrame(&paint);
canvas->drawPath(path, paint);
}
static void show_mesh_between(SkCanvas* canvas, const SkPath& p0, const SkPath& p1) {
SkPath d0, d1;
tesselate(p0, &d0);
tesselate(p1, &d1);
SkPoint pts0[256*2], pts1[256];
int count = d0.getPoints(pts0, SK_ARRAY_COUNT(pts0));
int count1 = d1.getPoints(pts1, SK_ARRAY_COUNT(pts1));
SkASSERT(count == count1);
memcpy(&pts0[count], pts1, count * sizeof(SkPoint));
uint16_t indices[256*6];
uint16_t* ndx = indices;
for (int i = 0; i < count; ++i) {
*ndx++ = i;
*ndx++ = i + count;
}
*ndx++ = 0;
show_mesh(canvas, pts0, indices, ndx - indices);
}
static void show_fan(SkCanvas* canvas, const SkPath& path, SkScalar cx, SkScalar cy) {
SkPaint paint;
setGLFrame(&paint);
canvas->drawPath(path, paint);
SkPoint pts[256];
int count = path.getPoints(pts, SK_ARRAY_COUNT(pts));
for (int i = 0; i < count; ++i) {
canvas->drawLine(pts[i].fX, pts[i].fY, cx, cy, paint);
}
}
///////////////////////////////////////////////////////////////////////////////
typedef void (*DrawProc)(SkCanvas* canvas, bool showGL, int flags);
static void draw_line(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
canvas->drawLine(50, 50, 400, 100, paint);
canvas->rotate(40);
setFade(&paint, showGL);
paint.setStrokeWidth(40);
canvas->drawLine(100, 50, 450, 50, paint);
if (showGL) {
show_mesh(canvas, SkRect::MakeLTRB(100, 50-20, 450, 50+20));
}
}
static void draw_rect(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
SkRect r = SkRect::MakeLTRB(50, 50, 250, 350);
setFade(&paint, showGL);
canvas->drawRect(r, paint);
if (showGL) {
show_mesh(canvas, r);
}
canvas->translate(320, 0);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(25);
canvas->drawRect(r, paint);
if (showGL) {
SkScalar rad = paint.getStrokeWidth() / 2;
SkPoint pts[8];
r.outset(rad, rad);
r.toQuad(&pts[0]);
r.inset(rad*2, rad*2);
r.toQuad(&pts[4]);
const uint16_t indices[] = {
0, 4, 1, 5, 2, 6, 3, 7, 0, 4
};
show_mesh(canvas, pts, indices, SK_ARRAY_COUNT(indices));
}
}
static void draw_oval(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
SkRect r = SkRect::MakeLTRB(50, 50, 250, 350);
setFade(&paint, showGL);
canvas->drawOval(r, paint);
if (showGL) {
switch (flags) {
case 0: {
SkPath path;
path.addOval(r);
show_glframe(canvas, path);
} break;
case 1: {
SkPath src, dst;
src.addOval(r);
tesselate(src, &dst);
show_fan(canvas, dst, r.centerX(), r.centerY());
} break;
}
}
canvas->translate(320, 0);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(25);
canvas->drawOval(r, paint);
if (showGL) {
switch (flags) {
case 0: {
SkPath path;
SkScalar rad = paint.getStrokeWidth() / 2;
r.outset(rad, rad);
path.addOval(r);
r.inset(rad*2, rad*2);
path.addOval(r);
show_glframe(canvas, path);
} break;
case 1: {
SkPath path0, path1;
SkScalar rad = paint.getStrokeWidth() / 2;
r.outset(rad, rad);
path0.addOval(r);
r.inset(rad*2, rad*2);
path1.addOval(r);
show_mesh_between(canvas, path0, path1);
} break;
}
}
}
static void draw_image(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
canvas->drawLine(10, 10, 400, 30, paint);
paint.setStrokeWidth(10);
canvas->drawLine(50, 50, 400, 400, paint);
}
static void draw_text(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
canvas->drawLine(10, 10, 400, 30, paint);
paint.setStrokeWidth(10);
canvas->drawLine(50, 50, 400, 400, paint);
}
static const struct {
DrawProc fProc;
const char* fName;
} gRec[] = {
{ draw_line, "Lines" },
{ draw_rect, "Rects" },
{ draw_oval, "Ovals" },
{ draw_image, "Images" },
{ draw_text, "Text" },
};
class TalkGM : public skiagm::GM {
DrawProc fProc;
SkString fName;
bool fShowGL;
int fFlags;
public:
TalkGM(int index, bool showGL, int flags = 0) {
fProc = gRec[index].fProc;
fName.set(gRec[index].fName);
if (showGL) {
fName.append("-gl");
}
fShowGL = showGL;
fFlags = flags;
}
protected:
virtual SkString onShortName() {
return fName;
}
virtual SkISize onISize() {
return SkISize::Make(640, 480);
}
virtual void onDraw(SkCanvas* canvas) {
SkRect dst = SkRect::MakeWH(canvas->getDevice()->width(), canvas->getDevice()->height());
SkRect src = SkRect::MakeWH(640, 480);
SkMatrix matrix;
matrix.setRectToRect(src, dst, SkMatrix::kCenter_ScaleToFit);
canvas->concat(matrix);
fProc(canvas, fShowGL, fFlags);
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
#define GM_CONCAT(X,Y) GM_CONCAT_IMPL(X,Y)
#define GM_CONCAT_IMPL(X,Y) X##Y
#define FACTORY_NAME GM_CONCAT(Factory, __LINE__)
#define REGISTRY_NAME GM_CONCAT(gReg, __LINE__)
#define ADD_GM(Class, args) \
static skiagm::GM* FACTORY_NAME(void*) { return new Class args; } \
static skiagm::GMRegistry REGISTRY_NAME(FACTORY_NAME);
ADD_GM(TalkGM, (0, false))
ADD_GM(TalkGM, (0, true))
ADD_GM(TalkGM, (1, false))
ADD_GM(TalkGM, (1, true))
ADD_GM(TalkGM, (2, false))
ADD_GM(TalkGM, (2, true))
ADD_GM(TalkGM, (2, true, 1))
ADD_GM(TalkGM, (3, false))
ADD_GM(TalkGM, (3, true))
ADD_GM(TalkGM, (4, false))
ADD_GM(TalkGM, (4, true))
//static GM* MyFactory(void*) { return new TalkGM(0, false); }
//static GMRegistry reg(MyFactory);
<commit_msg>update<commit_after>
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkColorPriv.h"
#include "SkGeometry.h"
#include "SkShader.h"
static void tesselate(const SkPath& src, SkPath* dst) {
SkPath::Iter iter(src, true);
SkPoint pts[4];
SkPath::Verb verb;
while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
switch (verb) {
case SkPath::kMove_Verb:
dst->moveTo(pts[0]);
break;
case SkPath::kLine_Verb:
dst->lineTo(pts[1]);
break;
case SkPath::kQuad_Verb: {
SkPoint p;
for (int i = 1; i <= 8; ++i) {
SkEvalQuadAt(pts, i / 8.0f, &p, NULL);
dst->lineTo(p);
}
} break;
case SkPath::kCubic_Verb: {
SkPoint p;
for (int i = 1; i <= 8; ++i) {
SkEvalCubicAt(pts, i / 8.0f, &p, NULL, NULL);
dst->lineTo(p);
}
} break;
}
}
}
static void setFade(SkPaint* paint, bool showGL) {
paint->setAlpha(showGL ? 0x66 : 0xFF);
}
static void setGLFrame(SkPaint* paint) {
paint->setColor(0xFFFF0000);
paint->setStyle(SkPaint::kStroke_Style);
paint->setAntiAlias(true);
paint->setStrokeWidth(1.1f);
}
static void show_mesh(SkCanvas* canvas, const SkRect& r) {
SkPaint paint;
setGLFrame(&paint);
canvas->drawRect(r, paint);
canvas->drawLine(r.fLeft, r.fTop, r.fRight, r.fBottom, paint);
}
static void drawLine(SkCanvas* canvas, const SkPoint& p0, const SkPoint& p1,
const SkPaint& paint) {
canvas->drawLine(p0.fX, p0.fY, p1.fX, p1.fY, paint);
}
static void show_mesh(SkCanvas* canvas, const SkPoint pts[],
const uint16_t indices[], int count) {
SkPaint paint;
setGLFrame(&paint);
for (int i = 0; i < count - 2; ++i) {
drawLine(canvas, pts[indices[i]], pts[indices[i+1]], paint);
drawLine(canvas, pts[indices[i+1]], pts[indices[i+2]], paint);
drawLine(canvas, pts[indices[i+2]], pts[indices[i]], paint);
}
}
static void show_glframe(SkCanvas* canvas, const SkPath& path) {
SkPaint paint;
setGLFrame(&paint);
canvas->drawPath(path, paint);
}
static void show_mesh_between(SkCanvas* canvas, const SkPath& p0, const SkPath& p1) {
SkPath d0, d1;
tesselate(p0, &d0);
tesselate(p1, &d1);
SkPoint pts0[256*2], pts1[256];
int count = d0.getPoints(pts0, SK_ARRAY_COUNT(pts0));
int count1 = d1.getPoints(pts1, SK_ARRAY_COUNT(pts1));
SkASSERT(count == count1);
memcpy(&pts0[count], pts1, count * sizeof(SkPoint));
uint16_t indices[256*6];
uint16_t* ndx = indices;
for (int i = 0; i < count; ++i) {
*ndx++ = i;
*ndx++ = i + count;
}
*ndx++ = 0;
show_mesh(canvas, pts0, indices, ndx - indices);
}
static void show_fan(SkCanvas* canvas, const SkPath& path, SkScalar cx, SkScalar cy) {
SkPaint paint;
setGLFrame(&paint);
canvas->drawPath(path, paint);
SkPoint pts[256];
int count = path.getPoints(pts, SK_ARRAY_COUNT(pts));
for (int i = 0; i < count; ++i) {
canvas->drawLine(pts[i].fX, pts[i].fY, cx, cy, paint);
}
}
///////////////////////////////////////////////////////////////////////////////
typedef void (*DrawProc)(SkCanvas* canvas, bool showGL, int flags);
static void draw_line(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
canvas->drawLine(50, 50, 400, 100, paint);
canvas->rotate(40);
setFade(&paint, showGL);
paint.setStrokeWidth(40);
canvas->drawLine(100, 50, 450, 50, paint);
if (showGL) {
show_mesh(canvas, SkRect::MakeLTRB(100, 50-20, 450, 50+20));
}
}
static void draw_rect(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
SkRect r = SkRect::MakeLTRB(50, 70, 250, 370);
setFade(&paint, showGL);
canvas->drawRect(r, paint);
if (showGL) {
show_mesh(canvas, r);
}
canvas->translate(320, 0);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(25);
canvas->drawRect(r, paint);
if (showGL) {
SkScalar rad = paint.getStrokeWidth() / 2;
SkPoint pts[8];
r.outset(rad, rad);
r.toQuad(&pts[0]);
r.inset(rad*2, rad*2);
r.toQuad(&pts[4]);
const uint16_t indices[] = {
0, 4, 1, 5, 2, 6, 3, 7, 0, 4
};
show_mesh(canvas, pts, indices, SK_ARRAY_COUNT(indices));
}
}
static void draw_oval(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
SkRect r = SkRect::MakeLTRB(50, 70, 250, 370);
setFade(&paint, showGL);
canvas->drawOval(r, paint);
if (showGL) {
switch (flags) {
case 0: {
SkPath path;
path.addOval(r);
show_glframe(canvas, path);
} break;
case 1:
case 2: {
SkPath src, dst;
src.addOval(r);
tesselate(src, &dst);
show_fan(canvas, dst, r.centerX(), r.centerY());
} break;
}
}
canvas->translate(320, 0);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(25);
canvas->drawOval(r, paint);
if (showGL) {
switch (flags) {
case 0: {
SkPath path;
SkScalar rad = paint.getStrokeWidth() / 2;
r.outset(rad, rad);
path.addOval(r);
r.inset(rad*2, rad*2);
path.addOval(r);
show_glframe(canvas, path);
} break;
case 1: {
SkPath path0, path1;
SkScalar rad = paint.getStrokeWidth() / 2;
r.outset(rad, rad);
path0.addOval(r);
r.inset(rad*2, rad*2);
path1.addOval(r);
show_mesh_between(canvas, path0, path1);
} break;
case 2: {
SkScalar rad = paint.getStrokeWidth() / 2;
r.outset(rad, rad);
SkPaint paint;
paint.setAlpha(0x33);
canvas->drawRect(r, paint);
show_mesh(canvas, r);
} break;
}
}
}
#include "SkImageDecoder.h"
static void draw_image(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
setFade(&paint, showGL);
SkBitmap bm;
SkImageDecoder::DecodeFile("/skimages/startrek.png", &bm);
SkRect r = SkRect::MakeWH(bm.width(), bm.height());
canvas->save();
canvas->translate(30, 30);
canvas->scale(0.8f, 0.8f);
canvas->drawBitmap(bm, 0, 0, &paint);
if (showGL) {
show_mesh(canvas, r);
}
canvas->restore();
canvas->translate(210, 290);
canvas->rotate(-35);
canvas->drawBitmap(bm, 0, 0, &paint);
if (showGL) {
show_mesh(canvas, r);
}
}
static void draw_text(SkCanvas* canvas, bool showGL, int flags) {
SkPaint paint;
paint.setAntiAlias(true);
const char text[] = "Graphics at Google";
size_t len = strlen(text);
setFade(&paint, showGL);
canvas->translate(40, 50);
for (int i = 0; i < 10; ++i) {
paint.setTextSize(12 + i * 3);
canvas->drawText(text, len, 0, 0, paint);
if (showGL) {
SkRect bounds[256];
SkScalar widths[256];
int count = paint.getTextWidths(text, len, widths, bounds);
SkScalar adv = 0;
for (int j = 0; j < count; ++j) {
bounds[j].offset(adv, 0);
show_mesh(canvas, bounds[j]);
adv += widths[j];
}
}
canvas->translate(0, paint.getTextSize() * 3 / 2);
}
}
static const struct {
DrawProc fProc;
const char* fName;
} gRec[] = {
{ draw_line, "Lines" },
{ draw_rect, "Rects" },
{ draw_oval, "Ovals" },
{ draw_image, "Images" },
{ draw_text, "Text" },
};
class TalkGM : public skiagm::GM {
DrawProc fProc;
SkString fName;
bool fShowGL;
int fFlags;
public:
TalkGM(int index, bool showGL, int flags = 0) {
fProc = gRec[index].fProc;
fName.set(gRec[index].fName);
if (showGL) {
fName.append("-gl");
}
fShowGL = showGL;
fFlags = flags;
}
protected:
virtual SkString onShortName() {
return fName;
}
virtual SkISize onISize() {
return SkISize::Make(640, 480);
}
virtual void onDraw(SkCanvas* canvas) {
SkRect dst = SkRect::MakeWH(canvas->getDevice()->width(), canvas->getDevice()->height());
SkRect src = SkRect::MakeWH(640, 480);
SkMatrix matrix;
matrix.setRectToRect(src, dst, SkMatrix::kCenter_ScaleToFit);
canvas->concat(matrix);
fProc(canvas, fShowGL, fFlags);
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
#define GM_CONCAT(X,Y) GM_CONCAT_IMPL(X,Y)
#define GM_CONCAT_IMPL(X,Y) X##Y
#define FACTORY_NAME GM_CONCAT(Factory, __LINE__)
#define REGISTRY_NAME GM_CONCAT(gReg, __LINE__)
#define ADD_GM(Class, args) \
static skiagm::GM* FACTORY_NAME(void*) { return new Class args; } \
static skiagm::GMRegistry REGISTRY_NAME(FACTORY_NAME);
ADD_GM(TalkGM, (0, false))
ADD_GM(TalkGM, (0, true))
ADD_GM(TalkGM, (1, false))
ADD_GM(TalkGM, (1, true))
ADD_GM(TalkGM, (2, false))
ADD_GM(TalkGM, (2, true))
ADD_GM(TalkGM, (2, true, 1))
ADD_GM(TalkGM, (2, true, 2))
ADD_GM(TalkGM, (3, false))
ADD_GM(TalkGM, (3, true))
ADD_GM(TalkGM, (4, false))
ADD_GM(TalkGM, (4, true))
//static GM* MyFactory(void*) { return new TalkGM(0, false); }
//static GMRegistry reg(MyFactory);
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds array into usable address objects.
static void convertSeeds(std::vector<CAddress> &vSeedsOut, const unsigned int *data, unsigned int count, int port)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int k = 0; k < count; ++k)
{
struct in_addr ip;
unsigned int i = data[k], t;
// -- convert to big endian
t = (i & 0x000000ff) << 24u
| (i & 0x0000ff00) << 8u
| (i & 0x00ff0000) >> 8u
| (i & 0xff000000) >> 24u;
memcpy(&ip, &t, sizeof(ip));
CAddress addr(CService(ip, port));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xa6;
pchMessageStart[1] = 0x3c;
pchMessageStart[2] = 0x8a;
pchMessageStart[3] = 0xa9;
vAlertPubKey = ParseHex("04cc14ab103c128c1d9cf4db2ebb1e8esdfsdfsdsdfsdfs1sdfsdf1cecb3bbfa813127fcb9dd9b84d44112081827ed7c49a648af9fe788ff41e316aee665879c553f099155299d6b54edd7e0");
nDefaultPort = 26566;
nRPCPort = 26565;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
const char* pszTimestamp = "December 19, 2016: Truck plows through Berlin Christmas market; 12 killed";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1482148800, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1482148800;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 48480;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x00008b645780949ad9a346df272390396d10f6c67a3bef9e2fe2114854786ac3"));
assert(genesis.hashMerkleRoot == uint256("0xffc835b4aab6d5002db95706cd864c5614dfb1d7cfda1ce3beedf740a9aca558"));
base58Prefixes[PUBKEY_ADDRESS] = list_of(63);
base58Prefixes[SCRIPT_ADDRESS] = list_of(85);
base58Prefixes[SECRET_KEY] = list_of(153);
base58Prefixes[STEALTH_ADDRESS] = list_of(40);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4);
vSeeds.push_back(CDNSSeedData("snapcoin.online", "seednode1.snapcoin.online"));
convertSeeds(vFixedSeeds, pnSeed, ARRAYLEN(pnSeed), nDefaultPort);
nPoolMaxTransactions = 3;
strDarksendPoolDummyAddress = "SnapCoinDarksendPoo1DummyAdy4viSr";
nLastPOWBlock = 5000000;
nPOSStartBlock = 1;
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x4a;
pchMessageStart[1] = 0xee;
pchMessageStart[2] = 0xd8;
pchMessageStart[3] = 0xb9;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
vAlertPubKey = ParseHex("9as8d7f9a1sd76f90a7df90a1sdfhadf8asdfnhasdfn7as1d8f7awefh9asd189asd78fhasd81fhasdf7891asdf89");
nDefaultPort = 27170;
nRPCPort = 27171;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = 520159231;
genesis.nNonce = 80086;
// assert(hashGenesisBlock == uint256("0x"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = list_of(97);
base58Prefixes[SCRIPT_ADDRESS] = list_of(196);
base58Prefixes[SECRET_KEY] = list_of(239);
base58Prefixes[STEALTH_ADDRESS] = list_of(40);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94);
convertSeeds(vFixedSeeds, pnTestnetSeed, ARRAYLEN(pnTestnetSeed), nDefaultPort);
nLastPOWBlock = 0x7fffffff;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<commit_msg>Update chain nNonce<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds array into usable address objects.
static void convertSeeds(std::vector<CAddress> &vSeedsOut, const unsigned int *data, unsigned int count, int port)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int k = 0; k < count; ++k)
{
struct in_addr ip;
unsigned int i = data[k], t;
// -- convert to big endian
t = (i & 0x000000ff) << 24u
| (i & 0x0000ff00) << 8u
| (i & 0x00ff0000) >> 8u
| (i & 0xff000000) >> 24u;
memcpy(&ip, &t, sizeof(ip));
CAddress addr(CService(ip, port));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xa6;
pchMessageStart[1] = 0x3c;
pchMessageStart[2] = 0x8a;
pchMessageStart[3] = 0xa9;
vAlertPubKey = ParseHex("04cc14ab103c128c1d9cf4db2ebb1e8esdfsdfsdsdfsdfs1sdfsdf1cecb3bbfa813127fcb9dd9b84d44112081827ed7c49a648af9fe788ff41e316aee665879c553f099155299d6b54edd7e0");
nDefaultPort = 26566;
nRPCPort = 26565;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
const char* pszTimestamp = "December 19, 2016: Truck plows through Berlin Christmas market; 12 killed";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1482148800, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1482148800;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 0;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x00008b645780949ad9a346df272390396d10f6c67a3bef9e2fe2114854786ac3"));
assert(genesis.hashMerkleRoot == uint256("0xffc835b4aab6d5002db95706cd864c5614dfb1d7cfda1ce3beedf740a9aca558"));
base58Prefixes[PUBKEY_ADDRESS] = list_of(63);
base58Prefixes[SCRIPT_ADDRESS] = list_of(85);
base58Prefixes[SECRET_KEY] = list_of(153);
base58Prefixes[STEALTH_ADDRESS] = list_of(40);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4);
vSeeds.push_back(CDNSSeedData("snapcoin.online", "seednode1.snapcoin.online"));
convertSeeds(vFixedSeeds, pnSeed, ARRAYLEN(pnSeed), nDefaultPort);
nPoolMaxTransactions = 3;
strDarksendPoolDummyAddress = "SnapCoinDarksendPoo1DummyAdy4viSr";
nLastPOWBlock = 5000000;
nPOSStartBlock = 1;
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x4a;
pchMessageStart[1] = 0xee;
pchMessageStart[2] = 0xd8;
pchMessageStart[3] = 0xb9;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
vAlertPubKey = ParseHex("9as8d7f9a1sd76f90a7df90a1sdfhadf8asdfnhasdfn7as1d8f7awefh9asd189asd78fhasd81fhasdf7891asdf89");
nDefaultPort = 27170;
nRPCPort = 27171;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = 520159231;
genesis.nNonce = 80086;
// assert(hashGenesisBlock == uint256("0x"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = list_of(97);
base58Prefixes[SCRIPT_ADDRESS] = list_of(196);
base58Prefixes[SECRET_KEY] = list_of(239);
base58Prefixes[STEALTH_ADDRESS] = list_of(40);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94);
convertSeeds(vFixedSeeds, pnTestnetSeed, ARRAYLEN(pnTestnetSeed), nDefaultPort);
nLastPOWBlock = 0x7fffffff;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "headers.h"
#include "checkpoints.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("6546a33a727700e35973b3fe6b1cb9125e40eafd63c5ec5bed0468bee34a44a3"))
;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
if (i == mapCheckpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0;
return mapCheckpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<commit_msg>changed pubkey, genesis hash<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "headers.h"
#include "checkpoints.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x6546a33a727700e35973b3fe6b1cb9125e40eafd63c5ec5bed0468bee34a44a3"))
;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
if (i == mapCheckpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0;
return mapCheckpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2013-2014 The Dogecoin developers
// Copyright (c) 2014 The Inutoshi developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64_t nTimeLastCheckpoint;
int64_t nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
bool fEnabled = true;
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x1a91e3dace36e2be3bf030a65679fe821aa1d6ef92e7c9902eb318182c355691"))
( 42279, uint256("0x8444c3ef39a46222e87584ef956ad2c9ef401578bd8b51e8e4b9a86ec3134d3a"))
( 42400, uint256("0x557bb7c17ed9e6d4a6f9361cfddf7c1fc0bdc394af7019167442b41f507252b4"))
( 104679, uint256("0x35eb87ae90d44b98898fec8c39577b76cb1eb08e1261cfc10706c8ce9a1d01cf"))
( 128370, uint256("0x3f9265c94cab7dc3bd6a2ad2fb26c8845cb41cff437e0a75ae006997b4974be6"))
( 145000, uint256("0xcc47cae70d7c5c92828d3214a266331dde59087d4a39071fa76ddfff9b7bde72"))
( 165393, uint256("0x7154efb4009e18c1c6a6a79fc6015f48502bcd0a1edd9c20e44cd7cbbe2eeef1"))
( 186774, uint256("0x3c712c49b34a5f34d4b963750d6ba02b73e8a938d2ee415dcda141d89f5cb23a"))
( 199992, uint256("0x3408ff829b7104eebaf61fd2ba2203ef2a43af38b95b353e992ef48f00ebb190"))
( 225000, uint256("be148d9c5eab4a33392a6367198796784479720d06bfdd07bd547fe934eea15a"))
( 250000, uint256("0e4bcfe8d970979f7e30e2809ab51908d435677998cf759169407824d4f36460"))
( 270639, uint256("c587a36dd4f60725b9dd01d99694799bef111fc584d659f6756ab06d2a90d911"))
( 299742, uint256("1cc89c0c8a58046bf0222fe131c099852bd9af25a80e07922918ef5fb39d6742"))
( 323141, uint256("60c9f919f9b271add6ef5671e9538bad296d79f7fdc6487ba702bf2ba131d31d"))
( 339202, uint256("8c29048df5ae9df38a67ea9470fdd404d281a3a5c6f33080cd5bf14aa496ab03"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1398694748, // * UNIX timestamp of last checkpoint block
9493347, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
8000.0 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0x"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1369685559,
37581,
300
};
static MapCheckpoints mapCheckpointsRegtest =
boost::assign::map_list_of
( 0, uint256("3d2160a3b5dc4a9d62e7e66a295f70313ac808440ef7400d6c0772171ce973a5"))
;
static const CCheckpointData dataRegtest = {
&mapCheckpointsRegtest,
0,
0,
0
};
const CCheckpointData &Checkpoints() {
if (Params().NetworkID() == CChainParams::TESTNET)
return dataTestnet;
else if (Params().NetworkID() == CChainParams::MAIN)
return data;
else
return dataRegtest;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!fEnabled)
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
if (pindex==NULL)
return 0.0;
int64_t nNow = time(NULL);
double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkpoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!fEnabled)
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!fEnabled)
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<commit_msg>Updated checkpoint statistics.<commit_after>// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2013-2014 The Dogecoin developers
// Copyright (c) 2014 The Inutoshi developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64_t nTimeLastCheckpoint;
int64_t nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
bool fEnabled = true;
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x1a91e3dace36e2be3bf030a65679fe821aa1d6ef92e7c9902eb318182c355691"))
( 42279, uint256("0x8444c3ef39a46222e87584ef956ad2c9ef401578bd8b51e8e4b9a86ec3134d3a"))
( 42400, uint256("0x557bb7c17ed9e6d4a6f9361cfddf7c1fc0bdc394af7019167442b41f507252b4"))
( 104679, uint256("0x35eb87ae90d44b98898fec8c39577b76cb1eb08e1261cfc10706c8ce9a1d01cf"))
( 128370, uint256("0x3f9265c94cab7dc3bd6a2ad2fb26c8845cb41cff437e0a75ae006997b4974be6"))
( 145000, uint256("0xcc47cae70d7c5c92828d3214a266331dde59087d4a39071fa76ddfff9b7bde72"))
( 165393, uint256("0x7154efb4009e18c1c6a6a79fc6015f48502bcd0a1edd9c20e44cd7cbbe2eeef1"))
( 186774, uint256("0x3c712c49b34a5f34d4b963750d6ba02b73e8a938d2ee415dcda141d89f5cb23a"))
( 199992, uint256("0x3408ff829b7104eebaf61fd2ba2203ef2a43af38b95b353e992ef48f00ebb190"))
( 225000, uint256("be148d9c5eab4a33392a6367198796784479720d06bfdd07bd547fe934eea15a"))
( 250000, uint256("0e4bcfe8d970979f7e30e2809ab51908d435677998cf759169407824d4f36460"))
( 270639, uint256("c587a36dd4f60725b9dd01d99694799bef111fc584d659f6756ab06d2a90d911"))
( 299742, uint256("1cc89c0c8a58046bf0222fe131c099852bd9af25a80e07922918ef5fb39d6742"))
( 323141, uint256("60c9f919f9b271add6ef5671e9538bad296d79f7fdc6487ba702bf2ba131d31d"))
( 339202, uint256("8c29048df5ae9df38a67ea9470fdd404d281a3a5c6f33080cd5bf14aa496ab03"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1408192466, // * UNIX timestamp of last checkpoint block
11177651, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
20000.0 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0x"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1369685559,
37581,
300
};
static MapCheckpoints mapCheckpointsRegtest =
boost::assign::map_list_of
( 0, uint256("3d2160a3b5dc4a9d62e7e66a295f70313ac808440ef7400d6c0772171ce973a5"))
;
static const CCheckpointData dataRegtest = {
&mapCheckpointsRegtest,
0,
0,
0
};
const CCheckpointData &Checkpoints() {
if (Params().NetworkID() == CChainParams::TESTNET)
return dataTestnet;
else if (Params().NetworkID() == CChainParams::MAIN)
return data;
else
return dataRegtest;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!fEnabled)
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
if (pindex==NULL)
return 0.0;
int64_t nNow = time(NULL);
double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkpoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!fEnabled)
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!fEnabled)
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 %s -triple %itanium_abi_triple -fms-extensions -emit-llvm -o - | FileCheck %s
// Test optnone on both function declarations and function definitions.
// Verify also that we don't generate invalid IR functions with
// both alwaysinline and noinline. (optnone implies noinline and wins
// over alwaysinline, in all cases.)
// Test optnone on extern declaration only.
extern int decl_only(int a) __attribute__((optnone));
// This function should be marked 'optnone'.
int decl_only(int a) {
return a + a + a + a;
}
// CHECK: define i32 @_Z9decl_onlyi(i32 %a) [[OPTNONE:#[0-9]+]]
// Test optnone on definition but not extern declaration.
extern int def_only(int a);
__attribute__((optnone))
int def_only(int a) {
return a + a + a + a;
}
// Function def_only is a optnone function and therefore it should not be
// inlined inside 'user_of_def_only'.
int user_of_def_only() {
return def_only(5);
}
// CHECK: define i32 @_Z8def_onlyi(i32 %a) [[OPTNONE]]
// CHECK: define i32 @_Z16user_of_def_onlyv() [[NORMAL:#[0-9]+]]
// Test optnone on both definition and declaration.
extern int def_and_decl(int a) __attribute__((optnone));
__attribute__((optnone))
int def_and_decl(int a) {
return a + a + a + a;
}
// CHECK: define i32 @_Z12def_and_decli(i32 %a) [[OPTNONE]]
// Check that optnone wins over always_inline.
// Test optnone on definition and always_inline on declaration.
extern int always_inline_function(int a) __attribute__((always_inline));
__attribute__((optnone))
extern int always_inline_function(int a) {
return a + a + a + a;
}
// CHECK: define i32 @_Z22always_inline_functioni(i32 %a) [[OPTNONE]]
int user_of_always_inline_function() {
return always_inline_function(4);
}
// CHECK: define i32 @_Z30user_of_always_inline_functionv() [[NORMAL]]
// Test optnone on declaration and always_inline on definition.
extern int optnone_function(int a) __attribute__((optnone));
__attribute__((always_inline))
int optnone_function(int a) {
return a + a + a + a;
}
// CHECK: define i32 @_Z16optnone_functioni(i32 %a) [[OPTNONE]]
int user_of_optnone_function() {
return optnone_function(4);
}
// CHECK: define i32 @_Z24user_of_optnone_functionv() [[NORMAL]]
// Test the combination of optnone with forceinline (optnone wins).
extern __forceinline int forceinline_optnone_function(int a, int b);
__attribute__((optnone))
extern int forceinline_optnone_function(int a, int b) {
return a + b;
}
int user_of_forceinline_optnone_function() {
return forceinline_optnone_function(4,5);
}
// CHECK: @_Z36user_of_forceinline_optnone_functionv() [[NORMAL]]
// CHECK: @_Z28forceinline_optnone_functionii(i32 %a, i32 %b) [[OPTNONE]]
// CHECK: attributes [[OPTNONE]] = { noinline nounwind optnone {{.*}} }
// CHECK: attributes [[NORMAL]] = { nounwind {{.*}} }
<commit_msg>See if this fixes Mips bot; ignore contents of parameter lists.<commit_after>// RUN: %clang_cc1 %s -triple %itanium_abi_triple -fms-extensions -emit-llvm -o - | FileCheck %s
// Test optnone on both function declarations and function definitions.
// Verify also that we don't generate invalid IR functions with
// both alwaysinline and noinline. (optnone implies noinline and wins
// over alwaysinline, in all cases.)
// Test optnone on extern declaration only.
extern int decl_only(int a) __attribute__((optnone));
// This function should be marked 'optnone'.
int decl_only(int a) {
return a + a + a + a;
}
// CHECK: define i32 @_Z9decl_onlyi({{.*}}) [[OPTNONE:#[0-9]+]]
// Test optnone on definition but not extern declaration.
extern int def_only(int a);
__attribute__((optnone))
int def_only(int a) {
return a + a + a + a;
}
// Function def_only is a optnone function and therefore it should not be
// inlined inside 'user_of_def_only'.
int user_of_def_only() {
return def_only(5);
}
// CHECK: define i32 @_Z8def_onlyi({{.*}}) [[OPTNONE]]
// CHECK: define i32 @_Z16user_of_def_onlyv() [[NORMAL:#[0-9]+]]
// Test optnone on both definition and declaration.
extern int def_and_decl(int a) __attribute__((optnone));
__attribute__((optnone))
int def_and_decl(int a) {
return a + a + a + a;
}
// CHECK: define i32 @_Z12def_and_decli({{.*}}) [[OPTNONE]]
// Check that optnone wins over always_inline.
// Test optnone on definition and always_inline on declaration.
extern int always_inline_function(int a) __attribute__((always_inline));
__attribute__((optnone))
extern int always_inline_function(int a) {
return a + a + a + a;
}
// CHECK: define i32 @_Z22always_inline_functioni({{.*}}) [[OPTNONE]]
int user_of_always_inline_function() {
return always_inline_function(4);
}
// CHECK: define i32 @_Z30user_of_always_inline_functionv() [[NORMAL]]
// Test optnone on declaration and always_inline on definition.
extern int optnone_function(int a) __attribute__((optnone));
__attribute__((always_inline))
int optnone_function(int a) {
return a + a + a + a;
}
// CHECK: define i32 @_Z16optnone_functioni({{.*}}) [[OPTNONE]]
int user_of_optnone_function() {
return optnone_function(4);
}
// CHECK: define i32 @_Z24user_of_optnone_functionv() [[NORMAL]]
// Test the combination of optnone with forceinline (optnone wins).
extern __forceinline int forceinline_optnone_function(int a, int b);
__attribute__((optnone))
extern int forceinline_optnone_function(int a, int b) {
return a + b;
}
int user_of_forceinline_optnone_function() {
return forceinline_optnone_function(4,5);
}
// CHECK: @_Z36user_of_forceinline_optnone_functionv() [[NORMAL]]
// CHECK: @_Z28forceinline_optnone_functionii({{.*}}) [[OPTNONE]]
// CHECK: attributes [[OPTNONE]] = { noinline nounwind optnone {{.*}} }
// CHECK: attributes [[NORMAL]] = { nounwind {{.*}} }
<|endoftext|> |
<commit_before>// Copyright 2016 The RE2 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 <stddef.h>
#include <stdint.h>
#include <map>
#include <string>
#include "re2/re2.h"
using re2::StringPiece;
using std::string;
// NOT static, NOT signed.
uint8_t dummy = 0;
void Test(StringPiece pattern, const RE2::Options& options, StringPiece text) {
RE2 re(pattern, options);
if (!re.ok())
return;
// Don't waste time fuzzing high-size programs.
// (They can cause bug reports due to fuzzer timeouts.)
int size = re.ProgramSize();
if (size > 9999)
return;
// Don't waste time fuzzing high-fanout programs.
// (They can also cause bug reports due to fuzzer timeouts.)
std::map<int, int> histogram;
int fanout = re.ProgramFanout(&histogram);
if (fanout > 9)
return;
StringPiece sp1, sp2, sp3, sp4;
string s1, s2, s3, s4;
int i1, i2, i3, i4;
double d1, d2, d3, d4;
RE2::FullMatch(text, re, &sp1, &sp2, &sp3, &sp4);
RE2::PartialMatch(text, re, &s1, &s2, &s3, &s4);
sp1 = sp2 = text;
RE2::Consume(&sp1, re, &i1, &i2, &i3, &i4);
RE2::FindAndConsume(&sp2, re, &d1, &d2, &d3, &d4);
s3 = s4 = string(text);
RE2::Replace(&s3, re, "");
RE2::GlobalReplace(&s4, re, "");
// Exercise some other API functionality.
dummy += re.NumberOfCapturingGroups();
dummy += RE2::QuoteMeta(pattern).size();
}
// Entry point for libFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
if (size == 0 || size > 512)
return 0;
// Crudely limit the use of \p and \P.
// Otherwise, we will waste time on inputs that have long runs of Unicode
// character classes. The fuzzer has shown itself to be easily capable of
// generating such patterns that fall within the other limits, but result
// in timeouts nonetheless. The marginal cost is high - even more so when
// counted repetition is involved - whereas the marginal benefit is zero.
int backslash_p = 0;
for (size_t i = 0; i < size; i++) {
if (data[i] == '\\' && i+1 < size && (data[i+1] == 'p' || data[i+1] == 'P'))
backslash_p++;
}
if (backslash_p > 10)
return 0;
// The one-at-a-time hash by Bob Jenkins.
uint32_t hash = 0;
for (size_t i = 0; i < size; i++) {
hash += data[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
RE2::Options options;
options.set_log_errors(false);
options.set_max_mem(64 << 20);
options.set_encoding(hash & 1 ? RE2::Options::EncodingLatin1
: RE2::Options::EncodingUTF8);
options.set_posix_syntax(hash & 2);
options.set_longest_match(hash & 4);
options.set_literal(hash & 8);
options.set_never_nl(hash & 16);
options.set_dot_nl(hash & 32);
options.set_never_capture(hash & 64);
options.set_case_sensitive(hash & 128);
options.set_perl_classes(hash & 256);
options.set_word_boundary(hash & 512);
options.set_one_line(hash & 1024);
const char* ptr = reinterpret_cast<const char*>(data);
int len = static_cast<int>(size);
StringPiece pattern(ptr, len);
StringPiece text(ptr, len);
Test(pattern, options, text);
return 0;
}
<commit_msg>Adjust a couple of the limits for fuzzing.<commit_after>// Copyright 2016 The RE2 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 <stddef.h>
#include <stdint.h>
#include <map>
#include <string>
#include "re2/re2.h"
using re2::StringPiece;
using std::string;
// NOT static, NOT signed.
uint8_t dummy = 0;
void Test(StringPiece pattern, const RE2::Options& options, StringPiece text) {
RE2 re(pattern, options);
if (!re.ok())
return;
// Don't waste time fuzzing high-size programs.
// (They can cause bug reports due to fuzzer timeouts.)
int size = re.ProgramSize();
if (size > 9999)
return;
// Don't waste time fuzzing high-fanout programs.
// (They can also cause bug reports due to fuzzer timeouts.)
std::map<int, int> histogram;
int fanout = re.ProgramFanout(&histogram);
if (fanout > 9)
return;
StringPiece sp1, sp2, sp3, sp4;
string s1, s2, s3, s4;
int i1, i2, i3, i4;
double d1, d2, d3, d4;
RE2::FullMatch(text, re, &sp1, &sp2, &sp3, &sp4);
RE2::PartialMatch(text, re, &s1, &s2, &s3, &s4);
sp1 = sp2 = text;
RE2::Consume(&sp1, re, &i1, &i2, &i3, &i4);
RE2::FindAndConsume(&sp2, re, &d1, &d2, &d3, &d4);
s3 = s4 = string(text);
RE2::Replace(&s3, re, "");
RE2::GlobalReplace(&s4, re, "");
// Exercise some other API functionality.
dummy += re.NumberOfCapturingGroups();
dummy += RE2::QuoteMeta(pattern).size();
}
// Entry point for libFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
if (size == 0 || size > 999)
return 0;
// Crudely limit the use of \p and \P.
// Otherwise, we will waste time on inputs that have long runs of Unicode
// character classes. The fuzzer has shown itself to be easily capable of
// generating such patterns that fall within the other limits, but result
// in timeouts nonetheless. The marginal cost is high - even more so when
// counted repetition is involved - whereas the marginal benefit is zero.
int backslash_p = 0;
for (size_t i = 0; i < size; i++) {
if (data[i] != '\\')
continue;
i++;
if (i >= size)
break;
if (data[i] == 'p' || data[i] == 'P')
backslash_p++;
}
if (backslash_p > 1)
return 0;
// The one-at-a-time hash by Bob Jenkins.
uint32_t hash = 0;
for (size_t i = 0; i < size; i++) {
hash += data[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
RE2::Options options;
options.set_log_errors(false);
options.set_max_mem(64 << 20);
options.set_encoding(hash & 1 ? RE2::Options::EncodingLatin1
: RE2::Options::EncodingUTF8);
options.set_posix_syntax(hash & 2);
options.set_longest_match(hash & 4);
options.set_literal(hash & 8);
options.set_never_nl(hash & 16);
options.set_dot_nl(hash & 32);
options.set_never_capture(hash & 64);
options.set_case_sensitive(hash & 128);
options.set_perl_classes(hash & 256);
options.set_word_boundary(hash & 512);
options.set_one_line(hash & 1024);
const char* ptr = reinterpret_cast<const char*>(data);
int len = static_cast<int>(size);
StringPiece pattern(ptr, len);
StringPiece text(ptr, len);
Test(pattern, options, text);
return 0;
}
<|endoftext|> |
<commit_before>
// Library includes
#include <string>
#include <ostream>
#include <iostream>
#include <memory>
#include "grl/KukaFRI.hpp"
#include "grl/KukaFriClientData.hpp"
#include <boost/log/trivial.hpp>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>
#include <vector>
#include <iostream>
//
//template<typename T,typename V>
//inline T& printseq(T& out, V& v){
// out << "[";
// size_t last = v.size() - 1;
// for(size_t i = 0; i < v.size(); ++i) {
// out << v[i];
// if (i != last)
// out << ", ";
// }
// out << "]";
// return out;
//}
//
//template<typename T,size_t N>
//inline boost::log::formatting_ostream& operator<< (boost::log::formatting_ostream& out, const boost::container::static_vector<T,N>& v) {
// return printseq(out,v);
//}
//
//
//template<typename T,size_t N>
//ostream& operator<< (ostream& out, const boost::container::static_vector<T,N>& v) {
// return printseq(out,v);
//}
//
//
//template<typename T>
//inline boost::log::formatting_ostream& operator<<(boost::log::formatting_ostream& out, std::vector<T>& v)
//{
// return printseq(out, v);
//}
//template<typename T>
//inline std::ostream& operator<<(std::ostream& out, std::vector<T>& v)
//{
// return printseq(out,v);
//}
using boost::asio::ip::udp;
#include <chrono>
/// @see https://stackoverflow.com/questions/2808398/easily-measure-elapsed-time
template<typename TimeT = std::chrono::milliseconds>
struct periodic
{
periodic():start(std::chrono::system_clock::now()){};
template<typename F, typename ...Args>
typename TimeT::rep execution(F func, Args&&... args)
{
auto duration = std::chrono::duration_cast< TimeT>
(std::chrono::system_clock::now() - start);
auto count = duration.count();
if(count > previous_count) func(std::forward<Args>(args)...);
previous_count = count;
return count;
}
std::chrono::time_point<std::chrono::system_clock> start;
std::size_t previous_count;
};
enum { max_length = 1024 };
int main(int argc, char* argv[])
{
periodic<> callIfMinPeriodPassed;
try
{
std::string localhost("192.170.10.100");
std::string localport("30200");
std::string remotehost("192.170.10.2");
std::string remoteport("30200");
std::cout << "argc: " << argc << "\n";
/// @todo add default localhost/localport
if (argc !=5 && argc !=1)
{
std::cerr << "Usage: " << argv[0] << " <localip> <localport> <remoteip> <remoteport>\n";
return 1;
}
if(argc ==5){
localhost = std::string(argv[1]);
localport = std::string(argv[2]);
remotehost = std::string(argv[3]);
remoteport = std::string(argv[4]);
}
std::cout << "using: " << argv[0] << " " << localhost << " " << localport << " " << remotehost << " " << remoteport << "\n";
boost::asio::io_service io_service;
std::shared_ptr<KUKA::FRI::ClientData> friData(std::make_shared<KUKA::FRI::ClientData>(7));
std::chrono::time_point<std::chrono::high_resolution_clock> startTime;
BOOST_VERIFY(friData);
double delta = -0.0001;
/// consider moving joint angles based on time
int joint_to_move = 6;
BOOST_LOG_TRIVIAL(warning) << "WARNING: YOU COULD DAMAGE OR DESTROY YOUR KUKA ROBOT "
<< "if joint angle delta variable is too large with respect to "
<< "the time it takes to go around the loop and change it. "
<< "Current delta (radians/update): " << delta << " Joint to move: " << joint_to_move << "\n";
std::vector<double> ipoJointPos(7,0);
std::vector<double> offsetFromipoJointPos(7,0); // length 7, value 0
std::vector<double> jointStateToCommand(7,0);
grl::robot::arm::KukaFRIClientDataDriver driver(io_service,
std::make_tuple(localhost,localport,remotehost,remoteport,grl::robot::arm::KukaFRIClientDataDriver::run_automatically)
);
for (std::size_t i = 0;;++i) {
/// use the interpolated joint position from the previous update as the base
/// @todo why is this?
if(i!=0 && friData) grl::robot::arm::copy(friData->monitoringMsg,ipoJointPos.begin(),grl::revolute_joint_angle_interpolated_open_chain_state_tag());
/// perform the update step, receiving and sending data to/from the arm
boost::system::error_code send_ec, recv_ec;
std::size_t send_bytes_transferred = 0, recv_bytes_transferred = 0;
bool haveNewData = !driver.update_state(friData, recv_ec, recv_bytes_transferred, send_ec, send_bytes_transferred);
// if data didn't arrive correctly, skip and try again
if(send_ec || recv_ec )
{
std::cout << "receive error: " << recv_ec << "receive bytes: " << recv_bytes_transferred << " send error: " << send_ec << " send bytes: " << send_bytes_transferred << " iteration: "<< i << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
// If we didn't receive anything new that is normal behavior,
// but we can't process the new data so try updating again immediately.
if(!haveNewData)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
/// use the interpolated joint position from the previous update as the base
/// @todo why is this?
if(i!=0 && friData) grl::robot::arm::copy(friData->monitoringMsg,ipoJointPos.begin(),grl::revolute_joint_angle_interpolated_open_chain_state_tag());
if (grl::robot::arm::get(friData->monitoringMsg,KUKA::FRI::ESessionState()) == KUKA::FRI::COMMANDING_ACTIVE)
{
#if 1 // disabling this block causes the robot to simply sit in place, which seems to work correctly. Enabling it causes the joint to rotate.
callIfMinPeriodPassed.execution( [&offsetFromipoJointPos,&delta,joint_to_move]()
{
offsetFromipoJointPos[joint_to_move]+=delta;
// swap directions when a half circle was completed
if (
(offsetFromipoJointPos[joint_to_move] > 0.2 && delta > 0) ||
(offsetFromipoJointPos[joint_to_move] < -0.2 && delta < 0)
)
{
delta *=-1;
}
});
#endif
}
KUKA::FRI::ESessionState sessionState = grl::robot::arm::get(friData->monitoringMsg,KUKA::FRI::ESessionState());
// copy current joint position to commanded position
if (sessionState == KUKA::FRI::COMMANDING_WAIT || sessionState == KUKA::FRI::COMMANDING_ACTIVE)
{
boost::transform ( ipoJointPos, offsetFromipoJointPos, jointStateToCommand.begin(), std::plus<double>());
grl::robot::arm::set(friData->commandMsg, jointStateToCommand, grl::revolute_joint_angle_open_chain_command_tag());
}
// vector addition between ipoJointPosition and ipoJointPositionOffsets, copying the result into jointStateToCommand
/// @todo should we take the current joint state into consideration?
//BOOST_LOG_TRIVIAL(trace) << "position: " << state.position << " us: " << std::chrono::duration_cast<std::chrono::microseconds>(state.timestamp - startTime).count() << " connectionQuality: " << state.connectionQuality << " operationMode: " << state.operationMode << " sessionState: " << state.sessionState << " driveState: " << state.driveState << " ipoJointPosition: " << state.ipoJointPosition << " ipoJointPositionOffsets: " << state.ipoJointPositionOffsets << "\n";
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
<commit_msg>KukaFRIClientDataDriverTest improved periodic struct to make delay between updates configurable<commit_after>
// Library includes
#include <string>
#include <ostream>
#include <iostream>
#include <memory>
#include "grl/KukaFRI.hpp"
#include "grl/KukaFriClientData.hpp"
#include <boost/log/trivial.hpp>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>
#include <vector>
#include <iostream>
//
//template<typename T,typename V>
//inline T& printseq(T& out, V& v){
// out << "[";
// size_t last = v.size() - 1;
// for(size_t i = 0; i < v.size(); ++i) {
// out << v[i];
// if (i != last)
// out << ", ";
// }
// out << "]";
// return out;
//}
//
//template<typename T,size_t N>
//inline boost::log::formatting_ostream& operator<< (boost::log::formatting_ostream& out, const boost::container::static_vector<T,N>& v) {
// return printseq(out,v);
//}
//
//
//template<typename T,size_t N>
//ostream& operator<< (ostream& out, const boost::container::static_vector<T,N>& v) {
// return printseq(out,v);
//}
//
//
//template<typename T>
//inline boost::log::formatting_ostream& operator<<(boost::log::formatting_ostream& out, std::vector<T>& v)
//{
// return printseq(out, v);
//}
//template<typename T>
//inline std::ostream& operator<<(std::ostream& out, std::vector<T>& v)
//{
// return printseq(out,v);
//}
using boost::asio::ip::udp;
#include <chrono>
/// @see https://stackoverflow.com/questions/2808398/easily-measure-elapsed-time for the code I based this on
template<typename TimeT = std::chrono::milliseconds>
struct periodic
{
periodic(TimeT duration = TimeT(1)):
start(std::chrono::system_clock::now()),period_duration(duration.count()){};
template<typename F, typename ...Args>
typename TimeT::rep execution(F func, Args&&... args)
{
auto duration = std::chrono::duration_cast< TimeT>
(std::chrono::system_clock::now() - start);
auto count = duration.count();
if(count > previous_count + period_duration)
{
func(std::forward<Args>(args)...);
previous_count = count;
}
return count;
}
std::chrono::time_point<std::chrono::system_clock> start;
typename TimeT::rep period_duration;
typename TimeT::rep previous_count;
};
enum { max_length = 1024 };
int main(int argc, char* argv[])
{
periodic<> callIfMinPeriodPassed;
try
{
std::string localhost("192.170.10.100");
std::string localport("30200");
std::string remotehost("192.170.10.2");
std::string remoteport("30200");
std::cout << "argc: " << argc << "\n";
/// @todo add default localhost/localport
if (argc !=5 && argc !=1)
{
std::cerr << "Usage: " << argv[0] << " <localip> <localport> <remoteip> <remoteport>\n";
return 1;
}
if(argc ==5){
localhost = std::string(argv[1]);
localport = std::string(argv[2]);
remotehost = std::string(argv[3]);
remoteport = std::string(argv[4]);
}
std::cout << "using: " << argv[0] << " " << localhost << " " << localport << " " << remotehost << " " << remoteport << "\n";
boost::asio::io_service io_service;
std::shared_ptr<KUKA::FRI::ClientData> friData(std::make_shared<KUKA::FRI::ClientData>(7));
std::chrono::time_point<std::chrono::high_resolution_clock> startTime;
BOOST_VERIFY(friData);
double delta = -0.0001;
/// consider moving joint angles based on time
int joint_to_move = 6;
BOOST_LOG_TRIVIAL(warning) << "WARNING: YOU COULD DAMAGE OR DESTROY YOUR KUKA ROBOT "
<< "if joint angle delta variable is too large with respect to "
<< "the time it takes to go around the loop and change it. "
<< "Current delta (radians/update): " << delta << " Joint to move: " << joint_to_move << "\n";
std::vector<double> ipoJointPos(7,0);
std::vector<double> offsetFromipoJointPos(7,0); // length 7, value 0
std::vector<double> jointStateToCommand(7,0);
grl::robot::arm::KukaFRIClientDataDriver driver(io_service,
std::make_tuple(localhost,localport,remotehost,remoteport,grl::robot::arm::KukaFRIClientDataDriver::run_automatically)
);
for (std::size_t i = 0;;++i) {
/// use the interpolated joint position from the previous update as the base
/// @todo why is this?
if(i!=0 && friData) grl::robot::arm::copy(friData->monitoringMsg,ipoJointPos.begin(),grl::revolute_joint_angle_interpolated_open_chain_state_tag());
/// perform the update step, receiving and sending data to/from the arm
boost::system::error_code send_ec, recv_ec;
std::size_t send_bytes_transferred = 0, recv_bytes_transferred = 0;
bool haveNewData = !driver.update_state(friData, recv_ec, recv_bytes_transferred, send_ec, send_bytes_transferred);
// if data didn't arrive correctly, skip and try again
if(send_ec || recv_ec )
{
std::cout << "receive error: " << recv_ec << "receive bytes: " << recv_bytes_transferred << " send error: " << send_ec << " send bytes: " << send_bytes_transferred << " iteration: "<< i << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
// If we didn't receive anything new that is normal behavior,
// but we can't process the new data so try updating again immediately.
if(!haveNewData)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
/// use the interpolated joint position from the previous update as the base
/// @todo why is this?
if(i!=0 && friData) grl::robot::arm::copy(friData->monitoringMsg,ipoJointPos.begin(),grl::revolute_joint_angle_interpolated_open_chain_state_tag());
if (grl::robot::arm::get(friData->monitoringMsg,KUKA::FRI::ESessionState()) == KUKA::FRI::COMMANDING_ACTIVE)
{
#if 1 // disabling this block causes the robot to simply sit in place, which seems to work correctly. Enabling it causes the joint to rotate.
callIfMinPeriodPassed.execution( [&offsetFromipoJointPos,&delta,joint_to_move]()
{
offsetFromipoJointPos[joint_to_move]+=delta;
// swap directions when a half circle was completed
if (
(offsetFromipoJointPos[joint_to_move] > 0.2 && delta > 0) ||
(offsetFromipoJointPos[joint_to_move] < -0.2 && delta < 0)
)
{
delta *=-1;
}
});
#endif
}
KUKA::FRI::ESessionState sessionState = grl::robot::arm::get(friData->monitoringMsg,KUKA::FRI::ESessionState());
// copy current joint position to commanded position
if (sessionState == KUKA::FRI::COMMANDING_WAIT || sessionState == KUKA::FRI::COMMANDING_ACTIVE)
{
boost::transform ( ipoJointPos, offsetFromipoJointPos, jointStateToCommand.begin(), std::plus<double>());
grl::robot::arm::set(friData->commandMsg, jointStateToCommand, grl::revolute_joint_angle_open_chain_command_tag());
}
// vector addition between ipoJointPosition and ipoJointPositionOffsets, copying the result into jointStateToCommand
/// @todo should we take the current joint state into consideration?
//BOOST_LOG_TRIVIAL(trace) << "position: " << state.position << " us: " << std::chrono::duration_cast<std::chrono::microseconds>(state.timestamp - startTime).count() << " connectionQuality: " << state.connectionQuality << " operationMode: " << state.operationMode << " sessionState: " << state.sessionState << " driveState: " << state.driveState << " ipoJointPosition: " << state.ipoJointPosition << " ipoJointPositionOffsets: " << state.ipoJointPositionOffsets << "\n";
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef STATIC_LINK
#define IMPLEMENT_API
#endif
#if defined(HX_WINDOWS) || defined(HX_MACOS) || defined(HX_LINUX)
#define NEKO_COMPATIBLE
#endif
#include <hx/CFFI.h>
#include "AdMobEx.h"
using namespace admobex;
AutoGCRoot* intestitialEventHandle = NULL;
static value admobex_init(value banner_id,value interstitial_id, value gravity_mode, value testing_ads, value tagForChildDirectedTreatment, value onInterstitialEvent){
intestitialEventHandle = new AutoGCRoot(onInterstitialEvent);
init(val_string(banner_id),val_string(interstitial_id), val_string(gravity_mode), val_bool(testing_ads), val_bool(tagForChildDirectedTreatment));
return alloc_null();
}
DEFINE_PRIM(admobex_init,6);
static value admobex_banner_show(){
showBanner();
return alloc_null();
}
DEFINE_PRIM(admobex_banner_show,0);
static value admobex_banner_hide(){
hideBanner();
return alloc_null();
}
DEFINE_PRIM(admobex_banner_hide,0);
static value admobex_banner_refresh(){
refreshBanner();
return alloc_null();
}
DEFINE_PRIM(admobex_banner_refresh,0);
extern "C" void admobex_main () {
val_int(0); // Fix Neko init
}
DEFINE_ENTRY_POINT (admobex_main);
static value admobex_interstitial_show(){
return alloc_bool(showInterstitial());
}
DEFINE_PRIM(admobex_interstitial_show,0);
extern "C" int admobex_register_prims () { return 0; }
extern "C" void reportInterstitialEvent(const char* event)
{
if(intestitialEventHandle == NULL) return;
// value o = alloc_empty_object();
// alloc_field(o,val_id("event"),alloc_string(event));
val_call1(intestitialEventHandle->get(), alloc_string(event));
}<commit_msg>Fix "Primitive not found : admobex_init__MULT" Runtime Exception<commit_after>#ifndef STATIC_LINK
#define IMPLEMENT_API
#endif
#if defined(HX_WINDOWS) || defined(HX_MACOS) || defined(HX_LINUX)
#define NEKO_COMPATIBLE
#endif
#include <hx/CFFI.h>
#include "AdMobEx.h"
using namespace admobex;
AutoGCRoot* intestitialEventHandle = NULL;
static value admobex_init(value *args, int count){
value on_interstitial_event = args[5];
intestitialEventHandle = new AutoGCRoot(on_interstitial_event);
const char* banner_id_str = val_string(args[0]);
const char* interstitial_id_str = val_string(args[1]);
const char* gravity_mode_str = val_string(args[2]);
bool testing_ads = val_bool(args[3]);
bool child_directed_treatment = val_bool(args[4]);
init(banner_id_str, interstitial_id_str, gravity_mode_str, testing_ads, child_directed_treatment);
return alloc_null();
}
DEFINE_PRIM_MULT(admobex_init);
static value admobex_banner_show(){
showBanner();
return alloc_null();
}
DEFINE_PRIM(admobex_banner_show,0);
static value admobex_banner_hide(){
hideBanner();
return alloc_null();
}
DEFINE_PRIM(admobex_banner_hide,0);
static value admobex_banner_refresh(){
refreshBanner();
return alloc_null();
}
DEFINE_PRIM(admobex_banner_refresh,0);
extern "C" void admobex_main () {
val_int(0); // Fix Neko init
}
DEFINE_ENTRY_POINT (admobex_main);
static value admobex_interstitial_show(){
return alloc_bool(showInterstitial());
}
DEFINE_PRIM(admobex_interstitial_show,0);
extern "C" int admobex_register_prims () { return 0; }
extern "C" void reportInterstitialEvent(const char* event)
{
if(intestitialEventHandle == NULL) return;
// value o = alloc_empty_object();
// alloc_field(o,val_id("event"),alloc_string(event));
val_call1(intestitialEventHandle->get(), alloc_string(event));
}
<|endoftext|> |
<commit_before>#ifndef G2_FIELD_CORE_INCLUDE_FIELD_STRUCTS_HH_
#define G2_FIELD_CORE_INCLUDE_FIELD_STRUCTS_HH_
/*===========================================================================*\
author: Matthias W. Smith
email: [email protected]
file: field_constants.hh
about: A header file for constant parameters used across field team
software.
\*===========================================================================*/
//--- project includes -----------------------------------------------------//
#include <vector>
//--- project includes -----------------------------------------------------//
#include "field_constants.hh"
namespace g2field {
// A macro to define nmr structs since they are very similar.
#define MAKE_NMR_STRUCT(name, num_ch, len_tr)\
struct name {\
Double_t sys_clock[num_ch];\
Double_t gps_clock[num_ch];\
Double_t dev_clock[num_ch];\
Double_t snr[num_ch];\
Double_t len[num_ch];\
Double_t freq[num_ch];\
Double_t ferr[num_ch];\
Double_t freq_zc[num_ch];\
Double_t ferr_zc[num_ch];\
UShort_t health[num_ch];\
UShort_t method[num_ch];\
UShort_t trace[num_ch][len_tr];\
};
// Might as well define a root branch string for the struct.
#define MAKE_NMR_STRING(name, num_ch, len_tr) NMR_HELPER(name, num_ch, len_tr)
#define NMR_HELPER(name, num_ch, len_tr) \
const char * const name = "sys_clock["#num_ch"]/D:gps_clock["#num_ch"]/D:"\
"dev_clock["#num_ch"]/D:snr["#num_ch"]/D:len["#num_ch"]/D:freq["#num_ch"]/D:"\
"ferr["#num_ch"]/D:freq_zc["#num_ch"]/D:ferr_zc["#num_ch"]/D:"\
"health["#num_ch"]/s:method["#num_ch"]/s:trace["#num_ch"]["#len_tr"]/s"
// NMR structs
MAKE_NMR_STRUCT(fixed_t, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD);
MAKE_NMR_STRING(fixed_str, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD);
MAKE_NMR_STRUCT(online_fixed_t, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE);
MAKE_NMR_STRING(online_fixed_str, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE);
// Flexible struct built from the basic nmr attributes.
struct nmr_vector {
std::vector<Double_t> sys_clock;
std::vector<Double_t> gps_clock;
std::vector<Double_t> dev_clock;
std::vector<Double_t> snr;
std::vector<Double_t> len;
std::vector<Double_t> freq;
std::vector<Double_t> ferr;
std::vector<Double_t> freq_zc;
std::vector<Double_t> ferr_zc;
std::vector<UShort_t> health;
std::vector<UShort_t> method;
std::vector< std::array<UShort_t, NMR_FID_LENGTH_ONLINE> > trace;
inline void Resize(int size) {
sys_clock.resize(size);
gps_clock.resize(size);
dev_clock.resize(size);
snr.resize(size);
len.resize(size);
freq.resize(size);
ferr.resize(size);
freq_zc.resize(size);
ferr_zc.resize(size);
health.resize(size);
method.resize(size);
trace.resize(size);
}
};
//Trolley data structs
struct trolley_nmr_t{
ULong64_t local_clock;
UShort_t probe_index;
UShort_t length;
UShort_t TS_OffSet;
UShort_t RF_Prescale;
UShort_t Probe_Command;
UShort_t Preamp_Delay;
UShort_t Preamp_Period;
UShort_t ADC_Gate_Delay;
UShort_t ADC_Gate_Offset;
UShort_t ADC_Gate_Period;
UShort_t TX_On;
UShort_t TX_Delay;
UShort_t TX_Period;
UShort_t UserDefinedData;
Short_t trace[TRLY_NMR_LENGTH];
};
#define MAKE_TLNMR_STRING(len) HELPER_TLNMR_STRING(len)
#define HELPER_TLNMR_STRING(len) \
const char * const trolley_nmr_str = "gps_clock/l:probe_index/s:len/s:TS_Offset/s:RF_Prescale/s:Probe_Command/s:Preamp_Delay/s:Preamp_Period/s:ADC_Gate_Delay/s:ADC_Gate_Offset/s:ADC_Gate_Period/s:TX_On/s:TX_Delay/s:TX_Period/s:UserDefinedData/s:trace["#len"]/S"
MAKE_TLNMR_STRING(TRLY_NMR_LENGTH);
struct trolley_barcode_t{
ULong64_t local_clock;
UShort_t length_per_ch;
UShort_t Sampling_Period;
UShort_t Acquisition_Delay;
UShort_t DAC_1_Config;
UShort_t DAC_2_Config;
UShort_t Ref_CM;
UShort_t traces[TRLY_BARCODE_LENGTH]; //All channels
};
#define MAKE_BARCODE_STRING(len) HELPER_BARCODE_STRING(len)
#define HELPER_BARCODE_STRING(len) \
const char * const trolley_barcode_str = "gps_clock/l:len_per_ch/s:Sampling_Period/s:Acquisition_Delay/s:DAC_1_Config/s:DAC_2_Config/s:Ref_CM/s:traces["#len"]/s"
MAKE_BARCODE_STRING(TRLY_BARCODE_LENGTH);
struct trolley_monitor_t{
ULong64_t local_clock_cycle_start;
UInt_t PMonitorVal;
UInt_t PMonitorTemp;
UInt_t RFPower1;
UInt_t RFPower2;
UInt_t NMRCheckSum;
UInt_t ConfigCheckSum;
UInt_t FrameCheckSum;
UInt_t NMRFrameSum;
UInt_t ConfigFrameSum;
UInt_t FrameSum;
UInt_t FrameIndex;
UShort_t StatusBits;
UShort_t TMonitorIn;
UShort_t TMonitorExt1;
UShort_t TMonitorExt2;
UShort_t TMonitorExt3;
UShort_t V1Min;
UShort_t V1Max;
UShort_t V2Min;
UShort_t V2Max;
UShort_t length_per_ch;
UShort_t Trolley_Command;
UShort_t TIC_Stop;
UShort_t TC_Start;
UShort_t TD_Start;
UShort_t TC_Stop;
UShort_t Switch_RF;
UShort_t PowerEnable;
UShort_t RF_Enable;
UShort_t Switch_Comm;
UShort_t TIC_Start;
UShort_t Cycle_Length;
UShort_t Power_Control_1;
UShort_t Power_Control_2;
UShort_t trace_VMonitor1[TRLY_MONITOR_LENGTH];
UShort_t trace_VMonitor2[TRLY_MONITOR_LENGTH];
};
#define MAKE_MONITOR_STRING(len) HELPER_MONITOR_STRING(len)
#define HELPER_MONITOR_STRING(len) \
const char * const trolley_monitor_str = "gps_clock_cycle_start/l:PMonitorVal/i:PMonitorTemp/i:RFPower1/i:RFPower2/i:"\
"NMRCheckSum/i:ConfigCheckSum/i:FrameCheckSum/i:NMRFrameSum/i:ConfigFrameSum/i:FrameSum/i:FrameIndex/i:StatusBits/s:"\
"TMonitorIn/s:TMonitorExt1/s:TMonitorExt2/s:TMonitorExt3/s:V1Min/s:V1Max/s:V2Min/s:V2Max/s:len_per_ch/s:"\
"Trolley Command/s:TIC_Stop/s:TC_Start/s:TD_Start/s:TC_Stop/s:Switch_RF/s:PowerEnable/s:RF_Enable/s:"\
"Switch_Comm/s:TIC_Start/s:Cycle_Length/s:Power_Control_1/s:Power_Control_2/s:"\
"trace_VMonitor1["#len"]/s:trace_VMonitor2["#len"]/s"
MAKE_MONITOR_STRING(TRLY_MONITOR_LENGTH);
//Galil Data structs
struct galil_data_t{
ULong64_t TimeStamp;
Int_t Tensions[2];
Int_t Positions[3];
Int_t Velocities[3];
Int_t OutputVs[3];
};
const char * const galil_data_str = "TimeStamp/l:Tensions[2]/I:Positions[3]/I:Velocities[3]/I:OutputVs[3]/I";
//This struct is auxiliary
struct galil_data_d_t{
Double_t Tensions[2];
Double_t Positions[3];
Double_t Velocities[3];
Double_t OutputVs[3];
};
//Absolute probe data struct
struct absolute_nmr_info_t{
ULong64_t time_stamp;
UInt_t length;
Int_t Pos[4]; //Coordinate X,Y,Z,S
UShort_t flay_run_number;
UShort_t probe_index;
//Because the length of the trace varies too much, it is not included in this struct
};
#define MAKE_ABSNMR_STRING() HELPER_ABSNMR_STRING()
#define HELPER_ABSNMR_STRING() \
const char * const absolute_nmr_info_str = "time_stamp/l:length/i:Pos[4]/i:flay_run_number/s:probe_index/s"
MAKE_ABSNMR_STRING();
// Absolute calibration NMR structs
MAKE_NMR_STRUCT(abs_fixed_t, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD);
MAKE_NMR_STRING(abs_fixed_str, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD);
MAKE_NMR_STRUCT(abs_online_fixed_t, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE);
MAKE_NMR_STRING(abs_online_fixed_str, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE);
//Surface coil struct
struct surface_coil_t{
Double_t bot_sys_clock[SC_NUM_COILS];
Double_t top_sys_clock[SC_NUM_COILS];
Double_t bot_coil_currents[SC_NUM_COILS];
Double_t top_coil_currents[SC_NUM_COILS];
Double_t bot_coil_temps[SC_NUM_COILS];
Double_t top_coil_temps[SC_NUM_COILS];
};
#define MAKE_SC_STRING(name,num_coils) SC_HELPER(name,num_coils)
#define SC_HELPER(name,num_coils)\
const char * const name = "sys_clock["#num_coils"]/D:bot_coil_currents["#num_coils"]/D:top_coil_currents["#num_coils"]/D:bot_coil_temps["#num_coils"]/D:top_coil_temps["#num_coils"]/D"
MAKE_SC_STRING(sc_str,SC_NUM_COILS);
// Yokogawa struct
struct yokogawa_t{
ULong64_t sys_clock; // system clock
ULong64_t gps_clock; // GPS clock
Int_t mode; // device mode (0 = voltage, 1 = current)
Int_t is_enabled; // is the output enabled (0 = false, 1 = true)
Double_t current; // current setting (in mA)
Double_t voltage; // voltage setting (in V)
};
#define MAKE_YOKO_STRING() HELPER_YOKO_STRING()
#define HELPER_YOKO_STRING() \
const char * const yokogawa_str = "sys_clock/l:gps_clock/l:is_enabled/i:current/D"
MAKE_YOKO_STRING();
} // ::g2field
#endif
<commit_msg>update galil<commit_after>#ifndef G2_FIELD_CORE_INCLUDE_FIELD_STRUCTS_HH_
#define G2_FIELD_CORE_INCLUDE_FIELD_STRUCTS_HH_
/*===========================================================================*\
author: Matthias W. Smith
email: [email protected]
file: field_constants.hh
about: A header file for constant parameters used across field team
software.
\*===========================================================================*/
//--- project includes -----------------------------------------------------//
#include <vector>
//--- project includes -----------------------------------------------------//
#include "field_constants.hh"
namespace g2field {
// A macro to define nmr structs since they are very similar.
#define MAKE_NMR_STRUCT(name, num_ch, len_tr)\
struct name {\
Double_t sys_clock[num_ch];\
Double_t gps_clock[num_ch];\
Double_t dev_clock[num_ch];\
Double_t snr[num_ch];\
Double_t len[num_ch];\
Double_t freq[num_ch];\
Double_t ferr[num_ch];\
Double_t freq_zc[num_ch];\
Double_t ferr_zc[num_ch];\
UShort_t health[num_ch];\
UShort_t method[num_ch];\
UShort_t trace[num_ch][len_tr];\
};
// Might as well define a root branch string for the struct.
#define MAKE_NMR_STRING(name, num_ch, len_tr) NMR_HELPER(name, num_ch, len_tr)
#define NMR_HELPER(name, num_ch, len_tr) \
const char * const name = "sys_clock["#num_ch"]/D:gps_clock["#num_ch"]/D:"\
"dev_clock["#num_ch"]/D:snr["#num_ch"]/D:len["#num_ch"]/D:freq["#num_ch"]/D:"\
"ferr["#num_ch"]/D:freq_zc["#num_ch"]/D:ferr_zc["#num_ch"]/D:"\
"health["#num_ch"]/s:method["#num_ch"]/s:trace["#num_ch"]["#len_tr"]/s"
// NMR structs
MAKE_NMR_STRUCT(fixed_t, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD);
MAKE_NMR_STRING(fixed_str, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD);
MAKE_NMR_STRUCT(online_fixed_t, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE);
MAKE_NMR_STRING(online_fixed_str, NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE);
// Flexible struct built from the basic nmr attributes.
struct nmr_vector {
std::vector<Double_t> sys_clock;
std::vector<Double_t> gps_clock;
std::vector<Double_t> dev_clock;
std::vector<Double_t> snr;
std::vector<Double_t> len;
std::vector<Double_t> freq;
std::vector<Double_t> ferr;
std::vector<Double_t> freq_zc;
std::vector<Double_t> ferr_zc;
std::vector<UShort_t> health;
std::vector<UShort_t> method;
std::vector< std::array<UShort_t, NMR_FID_LENGTH_ONLINE> > trace;
inline void Resize(int size) {
sys_clock.resize(size);
gps_clock.resize(size);
dev_clock.resize(size);
snr.resize(size);
len.resize(size);
freq.resize(size);
ferr.resize(size);
freq_zc.resize(size);
ferr_zc.resize(size);
health.resize(size);
method.resize(size);
trace.resize(size);
}
};
//Trolley data structs
struct trolley_nmr_t{
ULong64_t local_clock;
UShort_t probe_index;
UShort_t length;
UShort_t TS_OffSet;
UShort_t RF_Prescale;
UShort_t Probe_Command;
UShort_t Preamp_Delay;
UShort_t Preamp_Period;
UShort_t ADC_Gate_Delay;
UShort_t ADC_Gate_Offset;
UShort_t ADC_Gate_Period;
UShort_t TX_On;
UShort_t TX_Delay;
UShort_t TX_Period;
UShort_t UserDefinedData;
Short_t trace[TRLY_NMR_LENGTH];
};
#define MAKE_TLNMR_STRING(len) HELPER_TLNMR_STRING(len)
#define HELPER_TLNMR_STRING(len) \
const char * const trolley_nmr_str = "gps_clock/l:probe_index/s:len/s:TS_Offset/s:RF_Prescale/s:Probe_Command/s:Preamp_Delay/s:Preamp_Period/s:ADC_Gate_Delay/s:ADC_Gate_Offset/s:ADC_Gate_Period/s:TX_On/s:TX_Delay/s:TX_Period/s:UserDefinedData/s:trace["#len"]/S"
MAKE_TLNMR_STRING(TRLY_NMR_LENGTH);
struct trolley_barcode_t{
ULong64_t local_clock;
UShort_t length_per_ch;
UShort_t Sampling_Period;
UShort_t Acquisition_Delay;
UShort_t DAC_1_Config;
UShort_t DAC_2_Config;
UShort_t Ref_CM;
UShort_t traces[TRLY_BARCODE_LENGTH]; //All channels
};
#define MAKE_BARCODE_STRING(len) HELPER_BARCODE_STRING(len)
#define HELPER_BARCODE_STRING(len) \
const char * const trolley_barcode_str = "gps_clock/l:len_per_ch/s:Sampling_Period/s:Acquisition_Delay/s:DAC_1_Config/s:DAC_2_Config/s:Ref_CM/s:traces["#len"]/s"
MAKE_BARCODE_STRING(TRLY_BARCODE_LENGTH);
struct trolley_monitor_t{
ULong64_t local_clock_cycle_start;
UInt_t PMonitorVal;
UInt_t PMonitorTemp;
UInt_t RFPower1;
UInt_t RFPower2;
UInt_t NMRCheckSum;
UInt_t ConfigCheckSum;
UInt_t FrameCheckSum;
UInt_t NMRFrameSum;
UInt_t ConfigFrameSum;
UInt_t FrameSum;
UInt_t FrameIndex;
UShort_t StatusBits;
UShort_t TMonitorIn;
UShort_t TMonitorExt1;
UShort_t TMonitorExt2;
UShort_t TMonitorExt3;
UShort_t V1Min;
UShort_t V1Max;
UShort_t V2Min;
UShort_t V2Max;
UShort_t length_per_ch;
UShort_t Trolley_Command;
UShort_t TIC_Stop;
UShort_t TC_Start;
UShort_t TD_Start;
UShort_t TC_Stop;
UShort_t Switch_RF;
UShort_t PowerEnable;
UShort_t RF_Enable;
UShort_t Switch_Comm;
UShort_t TIC_Start;
UShort_t Cycle_Length;
UShort_t Power_Control_1;
UShort_t Power_Control_2;
UShort_t trace_VMonitor1[TRLY_MONITOR_LENGTH];
UShort_t trace_VMonitor2[TRLY_MONITOR_LENGTH];
};
#define MAKE_MONITOR_STRING(len) HELPER_MONITOR_STRING(len)
#define HELPER_MONITOR_STRING(len) \
const char * const trolley_monitor_str = "gps_clock_cycle_start/l:PMonitorVal/i:PMonitorTemp/i:RFPower1/i:RFPower2/i:"\
"NMRCheckSum/i:ConfigCheckSum/i:FrameCheckSum/i:NMRFrameSum/i:ConfigFrameSum/i:FrameSum/i:FrameIndex/i:StatusBits/s:"\
"TMonitorIn/s:TMonitorExt1/s:TMonitorExt2/s:TMonitorExt3/s:V1Min/s:V1Max/s:V2Min/s:V2Max/s:len_per_ch/s:"\
"Trolley Command/s:TIC_Stop/s:TC_Start/s:TD_Start/s:TC_Stop/s:Switch_RF/s:PowerEnable/s:RF_Enable/s:"\
"Switch_Comm/s:TIC_Start/s:Cycle_Length/s:Power_Control_1/s:Power_Control_2/s:"\
"trace_VMonitor1["#len"]/s:trace_VMonitor2["#len"]/s"
MAKE_MONITOR_STRING(TRLY_MONITOR_LENGTH);
//Galil Data structs
struct galil_trolley_t{
ULong64_t TimeStamp;
Int_t Tensions[2];
Int_t Temperatures[2];
Int_t Positions[3];
Int_t Velocities[3];
Int_t OutputVs[3];
};
const char * const galil_trolley_str = "TimeStamp/l:Tensions[2]/I:Positions[3]/I:Velocities[3]/I:OutputVs[3]/I";
struct galil_plunging_probe_t{
ULong64_t TimeStamp;
Int_t Positions[3];
Int_t Velocities[3];
Int_t OutputVs[3];
};
const char * const galil_plunging_probe_str = "TimeStamp/l:Positions[3]/I:Velocities[3]/I:OutputVs[3]/I";
//Absolute probe data struct
struct absolute_nmr_info_t{
ULong64_t time_stamp;
UInt_t length;
Int_t Pos[4]; //Coordinate X,Y,Z,S
UShort_t flay_run_number;
UShort_t probe_index;
//Because the length of the trace varies too much, it is not included in this struct
};
#define MAKE_ABSNMR_STRING() HELPER_ABSNMR_STRING()
#define HELPER_ABSNMR_STRING() \
const char * const absolute_nmr_info_str = "time_stamp/l:length/i:Pos[4]/i:flay_run_number/s:probe_index/s"
MAKE_ABSNMR_STRING();
// Absolute calibration NMR structs
MAKE_NMR_STRUCT(abs_fixed_t, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD);
MAKE_NMR_STRING(abs_fixed_str, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_RECORD);
MAKE_NMR_STRUCT(abs_online_fixed_t, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE);
MAKE_NMR_STRING(abs_online_fixed_str, ABS_NMR_NUM_FIXED_PROBES, NMR_FID_LENGTH_ONLINE);
//Surface coil struct
struct surface_coil_t{
Double_t bot_sys_clock[SC_NUM_COILS];
Double_t top_sys_clock[SC_NUM_COILS];
Double_t bot_coil_currents[SC_NUM_COILS];
Double_t top_coil_currents[SC_NUM_COILS];
Double_t bot_coil_temps[SC_NUM_COILS];
Double_t top_coil_temps[SC_NUM_COILS];
};
#define MAKE_SC_STRING(name,num_coils) SC_HELPER(name,num_coils)
#define SC_HELPER(name,num_coils)\
const char * const name = "sys_clock["#num_coils"]/D:bot_coil_currents["#num_coils"]/D:top_coil_currents["#num_coils"]/D:bot_coil_temps["#num_coils"]/D:top_coil_temps["#num_coils"]/D"
MAKE_SC_STRING(sc_str,SC_NUM_COILS);
// Yokogawa struct
struct yokogawa_t{
ULong64_t sys_clock; // system clock
ULong64_t gps_clock; // GPS clock
Int_t mode; // device mode (0 = voltage, 1 = current)
Int_t is_enabled; // is the output enabled (0 = false, 1 = true)
Double_t current; // current setting (in mA)
Double_t voltage; // voltage setting (in V)
};
#define MAKE_YOKO_STRING() HELPER_YOKO_STRING()
#define HELPER_YOKO_STRING() \
const char * const yokogawa_str = "sys_clock/l:gps_clock/l:is_enabled/i:current/D"
MAKE_YOKO_STRING();
} // ::g2field
#endif
<|endoftext|> |
<commit_before>// Copyright Daniel Wallin 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef LUABIND_SHARED_PTR_CONVERTER_090211_HPP
# define LUABIND_SHARED_PTR_CONVERTER_090211_HPP
# include <luabind/detail/decorate_type.hpp> // for LUABIND_DECORATE_TYPE
# include <luabind/detail/policy.hpp> // for default_converter, etc
# include <luabind/detail/yes_no.hpp>
# include <luabind/get_main_thread.hpp> // for get_main_thread
# include <luabind/handle.hpp> // for handle
# include <boost/mpl/bool.hpp> // for bool_, false_
# include <boost/smart_ptr/shared_ptr.hpp> // for shared_ptr, get_deleter
namespace luabind {
namespace mpl = boost::mpl;
namespace detail
{
struct shared_ptr_deleter
{
shared_ptr_deleter(lua_State* L, int index)
: life_support(get_main_thread(L), L, index)
{}
void operator()(void const*)
{
handle().swap(life_support);
}
handle life_support;
};
// From http://stackoverflow.com/a/1007175/2128694
// (by Johannes Schaub - litb, "based on a brilliant idea of someone on
// usenet")
template <typename T>
struct has_shared_from_this_aux
{
has_shared_from_this_aux(); // not implemented; silence Clang warning
private:
struct fallback { int shared_from_this; }; // introduce member name
struct derived : T, fallback
{
derived(); // not implemented; silence MSVC warnings C4510 and C4610
};
template<typename C, C> struct check;
template<typename C> static no_t f(
check<int fallback::*, &C::shared_from_this>*);
template<typename C> static yes_t f(...);
public:
BOOST_STATIC_CONSTANT(bool, value =
sizeof(f<derived>(0)) == sizeof(yes_t));
};
template <typename T>
struct has_shared_from_this:
mpl::bool_<has_shared_from_this_aux<T>::value>
{};
} // namespace detail
using boost::get_deleter;
namespace detail {
template <class P>
struct shared_ptr_converter
: default_converter<typename P::element_type*>
{
private:
typedef P ptr_t;
typedef typename ptr_t::element_type* rawptr_t;
detail::value_converter m_val_cv;
int m_val_score;
// no shared_from_this() available
ptr_t shared_from_raw(rawptr_t raw, lua_State* L, int index, mpl::false_)
{
return ptr_t(raw, detail::shared_ptr_deleter(L, index));
}
// shared_from_this() available.
ptr_t shared_from_raw(rawptr_t raw, lua_State*, int, mpl::true_)
{
return ptr_t(raw->shared_from_this(), raw);
}
public:
shared_ptr_converter(): m_val_score(-1) {}
typedef mpl::false_ is_native;
template <class U>
int match(lua_State* L, U, int index)
{
// Check if the value on the stack is a holder with exactly ptr_t
// as pointer type.
m_val_score = m_val_cv.match(L, LUABIND_DECORATE_TYPE(ptr_t), index);
if (m_val_score >= 0)
return m_val_score;
// Fall back to raw_ptr.
return default_converter<rawptr_t>::match(
L, LUABIND_DECORATE_TYPE(rawptr_t), index);
}
template <class U>
ptr_t apply(lua_State* L, U, int index)
{
// First, check if we got away without upcasting.
if (m_val_score >= 0)
{
ptr_t ptr = m_val_cv.apply(
L, LUABIND_DECORATE_TYPE(ptr_t), index);
return ptr;
}
// If not obtain, a raw pointer and construct are shared one from it.
rawptr_t raw_ptr = default_converter<rawptr_t>::apply(
L, LUABIND_DECORATE_TYPE(rawptr_t), index);
if (!raw_ptr)
return ptr_t();
return shared_from_raw(
raw_ptr, L, index,
detail::has_shared_from_this<typename ptr_t::element_type>());
}
void apply(lua_State* L, ptr_t const& p)
{
if (detail::shared_ptr_deleter* d =
get_deleter<detail::shared_ptr_deleter>(p)) // Rely on ADL.
{
d->life_support.push(L);
}
else
{
detail::value_converter().apply(L, p);
}
}
template <class U>
void converter_postcall(lua_State*, U const&, int)
{}
};
} // namepace detail
template <typename T>
struct default_converter<boost::shared_ptr<T> >:
detail::shared_ptr_converter<boost::shared_ptr<T> > {};
template <typename T>
struct default_converter<boost::shared_ptr<T> const&>:
detail::shared_ptr_converter<boost::shared_ptr<T> > {};
} // namespace luabind
#endif // LUABIND_SHARED_PTR_CONVERTER_090211_HPP
<commit_msg>shared_ptr_converter: Use existing value converter.<commit_after>// Copyright Daniel Wallin 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef LUABIND_SHARED_PTR_CONVERTER_090211_HPP
# define LUABIND_SHARED_PTR_CONVERTER_090211_HPP
# include <luabind/detail/decorate_type.hpp> // for LUABIND_DECORATE_TYPE
# include <luabind/detail/policy.hpp> // for default_converter, etc
# include <luabind/detail/yes_no.hpp>
# include <luabind/get_main_thread.hpp> // for get_main_thread
# include <luabind/handle.hpp> // for handle
# include <boost/mpl/bool.hpp> // for bool_, false_
# include <boost/smart_ptr/shared_ptr.hpp> // for shared_ptr, get_deleter
namespace luabind {
namespace mpl = boost::mpl;
namespace detail
{
struct shared_ptr_deleter
{
shared_ptr_deleter(lua_State* L, int index)
: life_support(get_main_thread(L), L, index)
{}
void operator()(void const*)
{
handle().swap(life_support);
}
handle life_support;
};
// From http://stackoverflow.com/a/1007175/2128694
// (by Johannes Schaub - litb, "based on a brilliant idea of someone on
// usenet")
template <typename T>
struct has_shared_from_this_aux
{
has_shared_from_this_aux(); // not implemented; silence Clang warning
private:
struct fallback { int shared_from_this; }; // introduce member name
struct derived : T, fallback
{
derived(); // not implemented; silence MSVC warnings C4510 and C4610
};
template<typename C, C> struct check;
template<typename C> static no_t f(
check<int fallback::*, &C::shared_from_this>*);
template<typename C> static yes_t f(...);
public:
BOOST_STATIC_CONSTANT(bool, value =
sizeof(f<derived>(0)) == sizeof(yes_t));
};
template <typename T>
struct has_shared_from_this:
mpl::bool_<has_shared_from_this_aux<T>::value>
{};
} // namespace detail
using boost::get_deleter;
namespace detail {
template <class P>
struct shared_ptr_converter
: default_converter<typename P::element_type*>
{
private:
typedef P ptr_t;
typedef typename ptr_t::element_type* rawptr_t;
detail::value_converter m_val_cv;
int m_val_score;
// no shared_from_this() available
ptr_t shared_from_raw(rawptr_t raw, lua_State* L, int index, mpl::false_)
{
return ptr_t(raw, detail::shared_ptr_deleter(L, index));
}
// shared_from_this() available.
ptr_t shared_from_raw(rawptr_t raw, lua_State*, int, mpl::true_)
{
return ptr_t(raw->shared_from_this(), raw);
}
public:
shared_ptr_converter(): m_val_score(-1) {}
typedef mpl::false_ is_native;
template <class U>
int match(lua_State* L, U, int index)
{
// Check if the value on the stack is a holder with exactly ptr_t
// as pointer type.
m_val_score = m_val_cv.match(L, LUABIND_DECORATE_TYPE(ptr_t), index);
if (m_val_score >= 0)
return m_val_score;
// Fall back to raw_ptr.
return default_converter<rawptr_t>::match(
L, LUABIND_DECORATE_TYPE(rawptr_t), index);
}
template <class U>
ptr_t apply(lua_State* L, U, int index)
{
// First, check if we got away without upcasting.
if (m_val_score >= 0)
{
ptr_t ptr = m_val_cv.apply(
L, LUABIND_DECORATE_TYPE(ptr_t), index);
return ptr;
}
// If not obtain, a raw pointer and construct are shared one from it.
rawptr_t raw_ptr = default_converter<rawptr_t>::apply(
L, LUABIND_DECORATE_TYPE(rawptr_t), index);
if (!raw_ptr)
return ptr_t();
return shared_from_raw(
raw_ptr, L, index,
detail::has_shared_from_this<typename ptr_t::element_type>());
}
void apply(lua_State* L, ptr_t const& p)
{
if (detail::shared_ptr_deleter* d =
get_deleter<detail::shared_ptr_deleter>(p)) // Rely on ADL.
{
d->life_support.push(L);
}
else
{
m_val_cv.apply(L, p);
}
}
template <class U>
void converter_postcall(lua_State*, U const&, int)
{}
};
} // namepace detail
template <typename T>
struct default_converter<boost::shared_ptr<T> >:
detail::shared_ptr_converter<boost::shared_ptr<T> > {};
template <typename T>
struct default_converter<boost::shared_ptr<T> const&>:
detail::shared_ptr_converter<boost::shared_ptr<T> > {};
} // namespace luabind
#endif // LUABIND_SHARED_PTR_CONVERTER_090211_HPP
<|endoftext|> |
<commit_before>/**
* \file
* \brief SignalsWaitTestCase class implementation
*
* \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-05-16
*/
#include "SignalsWaitTestCase.hpp"
#include "priorityTestPhases.hpp"
#include "SequenceAsserter.hpp"
#include "distortos/StaticThread.hpp"
#include "distortos/statistics.hpp"
#include "distortos/ThisThread-Signals.hpp"
#include "distortos/ThisThread.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {384};
/// bit shift of signal number encoded in signal value
constexpr size_t signalNumberShift {(sizeof(decltype(sigval{}.sival_int)) / 2) * 8};
/// mask used to obtain sequence point from signal value (by removing encoded signal number)
constexpr decltype(sigval{}.sival_int) signalValueMask {(1 << signalNumberShift) - 1};
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// type of test thread function
using TestThreadFunction = void(SequenceAsserter&, unsigned int);
/// type of test thread
using TestThread = decltype(makeStaticThread<testThreadStackSize, true, totalThreads>({},
std::declval<TestThreadFunction>(), std::ref(std::declval<SequenceAsserter&>()), std::declval<unsigned int>()));
/// function executed to trigger unblocking of test thread
using Trigger = bool(TestThread&, size_t, const TestPhase&);
/// pair with functions for one stage
using Stage = std::pair<const TestThreadFunction&, const Trigger&>;
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Test thread for signals that were "generated"
*
* Marks the first sequence point in SequenceAsserter, waits for any possible signal. The signal number of first
* accepted signal is used to calculate "sequence point offset". This value is then used to mark sequence points for all
* following signals that will be accepted.
*
* It is assumed that \a totalThreads signals will be generated for each test thread.
*
* First \a totalThreads sequence points will be marked before test threads block waiting for signal. Then each test
* thread must mark sequence points in the range <em>[totalThreads * (i + 1); totalThreads * (i + 2))</em>, where \a i
* is the index of unblocked thread in <em>[0; totalThreads)</em> range. Because it is not possible to fit all required
* sequence points into signal number values, these are "encoded". The ranges of sequence points mentioned earlier are
* obtained from ranges of received signal numbers in the following form <em>[0 + 1; totalThreads + i)</em>.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] firstSequencePoint is the first sequence point of this instance
*/
void generatedSignalsThread(SequenceAsserter& sequenceAsserter, const unsigned int firstSequencePoint)
{
sequenceAsserter.sequencePoint(firstSequencePoint);
const SignalSet signalSet {SignalSet::full};
auto waitResult = ThisThread::Signals::wait(signalSet);
if (waitResult.first != 0)
return;
const auto& signalInformation = waitResult.second;
if (signalInformation.getCode() != SignalInformation::Code::Generated)
return;
const auto signalNumber = signalInformation.getSignalNumber();
const auto sequencePointOffset = totalThreads + totalThreads * signalNumber - signalNumber;
sequenceAsserter.sequencePoint(signalNumber + sequencePointOffset);
while (waitResult = ThisThread::Signals::tryWait(signalSet), waitResult.first == 0 &&
signalInformation.getCode() == SignalInformation::Code::Generated)
sequenceAsserter.sequencePoint(signalInformation.getSignalNumber() + sequencePointOffset);
}
/**
* \brief Trigger function that "generates" signals.
*
* \param [in] thread is a reference to TestThread that will be triggered
* \param [in] index is the index of currently triggered thread - equal to the order in which this function is called
* during single phase
* \param [in] phase is a reference to current TestPhase
*
* \return true if trigger check succeeded, false otherwise
*/
bool generatedSignalsTrigger(TestThread& thread, const size_t index, const TestPhase& phase)
{
for (size_t i = 0; i < phase.second.size(); ++i)
{
const auto ret = thread.generateSignal(index + phase.second[i]);
if (ret != 0)
return false;
}
return true;
}
/**
* \brief Test thread for signals that were "queued"
*
* Marks the first sequence point in SequenceAsserter, waits for any possible signal. Value of each accepted signal
* is split into two parts:
* - sequence point which is obtained by masking with \a signalValueMask,
* - signal number which is obtained by shifting right by \a signalNumberShift.
* Signal number taken from SignalInformation object must be equal to signal number encoded in signal value.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] firstSequencePoint is the first sequence point of this instance
*/
void queuedSignalsThread(SequenceAsserter& sequenceAsserter, const unsigned int firstSequencePoint)
{
sequenceAsserter.sequencePoint(firstSequencePoint);
const SignalSet signalSet {SignalSet::full};
auto waitResult = ThisThread::Signals::wait(signalSet);
if (waitResult.first != 0)
return;
const auto& signalInformation = waitResult.second;
if (signalInformation.getCode() != SignalInformation::Code::Queued)
return;
const auto signalNumber = signalInformation.getSignalNumber();
const auto signalValue = signalInformation.getValue().sival_int;
if (signalNumber != signalValue >> signalNumberShift)
return;
sequenceAsserter.sequencePoint(signalValue & signalValueMask);
while (waitResult = ThisThread::Signals::tryWait(signalSet), waitResult.first == 0 &&
signalInformation.getCode() == SignalInformation::Code::Queued &&
signalInformation.getSignalNumber() == signalInformation.getValue().sival_int >> signalNumberShift)
sequenceAsserter.sequencePoint(signalInformation.getValue().sival_int & signalValueMask);
}
/**
* \brief Trigger function that "queues" signals.
*
* \param [in] thread is a reference to TestThread that will be triggered
* \param [in] index is the index of currently triggered thread - equal to the order in which this function is called
* during single phase
* \param [in] phase is a reference to current TestPhase
*
* \return true if trigger check succeeded, false otherwise
*/
bool queuedSignalsTrigger(TestThread& thread, const size_t index, const TestPhase& phase)
{
for (size_t i = 0; i < phase.second.size(); ++i)
{
const auto signalNumber = UINT8_MAX - phase.first[phase.second[i]].first;
const decltype(sigval{}.sival_int) signalValue =
(totalThreads * (index + 1) + phase.first[phase.second[i]].second) |
(signalNumber << signalNumberShift);
const auto ret = thread.queueSignal(signalNumber, sigval{signalValue});
if (ret != 0)
return false;
}
return true;
}
/**
* \brief Builder of TestThread objects.
*
* \param [in] testThreadFunction is a reference to test thread function that will be used in TestThread
* \param [in] priority is the thread's priority
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] firstSequencePoint is the first sequence point for this instance - equal to the order in which this
* thread will be started
*
* \return constructed TestThread object
*/
TestThread makeTestThread(const TestThreadFunction& testThreadFunction, const uint8_t priority,
SequenceAsserter& sequenceAsserter, const unsigned int firstSequencePoint)
{
return makeStaticThread<testThreadStackSize, true, totalThreads>(priority, testThreadFunction,
std::ref(sequenceAsserter), static_cast<unsigned int>(firstSequencePoint));
}
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// test stages
const std::array<Stage, 2> stages
{{
{generatedSignalsThread, generatedSignalsTrigger},
{queuedSignalsThread, queuedSignalsTrigger},
}};
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool SignalsWaitTestCase::run_() const
{
// priority required for this whole test to work
static_assert(testCasePriority_ + 2 <= UINT8_MAX, "Invalid test case priority");
constexpr decltype(testCasePriority_) testThreadPriority {testCasePriority_ + 1};
constexpr decltype(testCasePriority_) aboveTestThreadPriority {testThreadPriority + 1};
const auto contextSwitchCount = statistics::getContextSwitchCount();
std::remove_const<decltype(contextSwitchCount)>::type expectedContextSwitchCount {};
for (const auto& stage : stages)
for (const auto& phase : priorityTestPhases)
{
SequenceAsserter sequenceAsserter;
auto& threadFunction = stage.first;
std::array<TestThread, totalThreads> threads
{{
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 0),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 1),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 2),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 3),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 4),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 5),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 6),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 7),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 8),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 9),
}};
bool result {true};
for (auto& thread : threads)
{
thread.start();
// 2 context switches: "into" the thread and "back" to main thread when test thread blocks
expectedContextSwitchCount += 2;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
result = false;
}
if (sequenceAsserter.assertSequence(totalThreads) == false)
result = false;
for (size_t i = 0; i < phase.second.size(); ++i)
{
auto& thread = threads[phase.second[i]];
ThisThread::setPriority(aboveTestThreadPriority);
const auto triggerResult = stage.second(thread, i, phase); // execute "trigger"
if (triggerResult == false)
result = false;
ThisThread::setPriority(testCasePriority_);
// 2 context switches: into" the unblocked thread and "back" to main thread when test thread terminates
expectedContextSwitchCount += 2;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
result = false;
}
for (auto& thread : threads)
thread.join();
if (result == false || sequenceAsserter.assertSequence(totalThreads * (totalThreads + 1)) == false)
return false;
}
constexpr auto totalContextSwitches = 4 * totalThreads * priorityTestPhases.size() * stages.size();
if (statistics::getContextSwitchCount() - contextSwitchCount != totalContextSwitches)
return false;
return true;
}
} // namespace test
} // namespace distortos
<commit_msg>test: check state of waiting threads in SignalsWaitTestCase<commit_after>/**
* \file
* \brief SignalsWaitTestCase class implementation
*
* \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-12-02
*/
#include "SignalsWaitTestCase.hpp"
#include "priorityTestPhases.hpp"
#include "SequenceAsserter.hpp"
#include "distortos/StaticThread.hpp"
#include "distortos/statistics.hpp"
#include "distortos/ThisThread-Signals.hpp"
#include "distortos/ThisThread.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {384};
/// bit shift of signal number encoded in signal value
constexpr size_t signalNumberShift {(sizeof(decltype(sigval{}.sival_int)) / 2) * 8};
/// mask used to obtain sequence point from signal value (by removing encoded signal number)
constexpr decltype(sigval{}.sival_int) signalValueMask {(1 << signalNumberShift) - 1};
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// type of test thread function
using TestThreadFunction = void(SequenceAsserter&, unsigned int);
/// type of test thread
using TestThread = decltype(makeStaticThread<testThreadStackSize, true, totalThreads>({},
std::declval<TestThreadFunction>(), std::ref(std::declval<SequenceAsserter&>()), std::declval<unsigned int>()));
/// function executed to trigger unblocking of test thread
using Trigger = bool(TestThread&, size_t, const TestPhase&);
/// pair with functions for one stage
using Stage = std::pair<const TestThreadFunction&, const Trigger&>;
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Test thread for signals that were "generated"
*
* Marks the first sequence point in SequenceAsserter, waits for any possible signal. The signal number of first
* accepted signal is used to calculate "sequence point offset". This value is then used to mark sequence points for all
* following signals that will be accepted.
*
* It is assumed that \a totalThreads signals will be generated for each test thread.
*
* First \a totalThreads sequence points will be marked before test threads block waiting for signal. Then each test
* thread must mark sequence points in the range <em>[totalThreads * (i + 1); totalThreads * (i + 2))</em>, where \a i
* is the index of unblocked thread in <em>[0; totalThreads)</em> range. Because it is not possible to fit all required
* sequence points into signal number values, these are "encoded". The ranges of sequence points mentioned earlier are
* obtained from ranges of received signal numbers in the following form <em>[0 + 1; totalThreads + i)</em>.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] firstSequencePoint is the first sequence point of this instance
*/
void generatedSignalsThread(SequenceAsserter& sequenceAsserter, const unsigned int firstSequencePoint)
{
sequenceAsserter.sequencePoint(firstSequencePoint);
const SignalSet signalSet {SignalSet::full};
auto waitResult = ThisThread::Signals::wait(signalSet);
if (waitResult.first != 0)
return;
const auto& signalInformation = waitResult.second;
if (signalInformation.getCode() != SignalInformation::Code::Generated)
return;
const auto signalNumber = signalInformation.getSignalNumber();
const auto sequencePointOffset = totalThreads + totalThreads * signalNumber - signalNumber;
sequenceAsserter.sequencePoint(signalNumber + sequencePointOffset);
while (waitResult = ThisThread::Signals::tryWait(signalSet), waitResult.first == 0 &&
signalInformation.getCode() == SignalInformation::Code::Generated)
sequenceAsserter.sequencePoint(signalInformation.getSignalNumber() + sequencePointOffset);
}
/**
* \brief Trigger function that "generates" signals.
*
* \param [in] thread is a reference to TestThread that will be triggered
* \param [in] index is the index of currently triggered thread - equal to the order in which this function is called
* during single phase
* \param [in] phase is a reference to current TestPhase
*
* \return true if trigger check succeeded, false otherwise
*/
bool generatedSignalsTrigger(TestThread& thread, const size_t index, const TestPhase& phase)
{
for (size_t i = 0; i < phase.second.size(); ++i)
{
const auto ret = thread.generateSignal(index + phase.second[i]);
if (ret != 0)
return false;
}
return true;
}
/**
* \brief Test thread for signals that were "queued"
*
* Marks the first sequence point in SequenceAsserter, waits for any possible signal. Value of each accepted signal
* is split into two parts:
* - sequence point which is obtained by masking with \a signalValueMask,
* - signal number which is obtained by shifting right by \a signalNumberShift.
* Signal number taken from SignalInformation object must be equal to signal number encoded in signal value.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] firstSequencePoint is the first sequence point of this instance
*/
void queuedSignalsThread(SequenceAsserter& sequenceAsserter, const unsigned int firstSequencePoint)
{
sequenceAsserter.sequencePoint(firstSequencePoint);
const SignalSet signalSet {SignalSet::full};
auto waitResult = ThisThread::Signals::wait(signalSet);
if (waitResult.first != 0)
return;
const auto& signalInformation = waitResult.second;
if (signalInformation.getCode() != SignalInformation::Code::Queued)
return;
const auto signalNumber = signalInformation.getSignalNumber();
const auto signalValue = signalInformation.getValue().sival_int;
if (signalNumber != signalValue >> signalNumberShift)
return;
sequenceAsserter.sequencePoint(signalValue & signalValueMask);
while (waitResult = ThisThread::Signals::tryWait(signalSet), waitResult.first == 0 &&
signalInformation.getCode() == SignalInformation::Code::Queued &&
signalInformation.getSignalNumber() == signalInformation.getValue().sival_int >> signalNumberShift)
sequenceAsserter.sequencePoint(signalInformation.getValue().sival_int & signalValueMask);
}
/**
* \brief Trigger function that "queues" signals.
*
* \param [in] thread is a reference to TestThread that will be triggered
* \param [in] index is the index of currently triggered thread - equal to the order in which this function is called
* during single phase
* \param [in] phase is a reference to current TestPhase
*
* \return true if trigger check succeeded, false otherwise
*/
bool queuedSignalsTrigger(TestThread& thread, const size_t index, const TestPhase& phase)
{
for (size_t i = 0; i < phase.second.size(); ++i)
{
const auto signalNumber = UINT8_MAX - phase.first[phase.second[i]].first;
const decltype(sigval{}.sival_int) signalValue =
(totalThreads * (index + 1) + phase.first[phase.second[i]].second) |
(signalNumber << signalNumberShift);
const auto ret = thread.queueSignal(signalNumber, sigval{signalValue});
if (ret != 0)
return false;
}
return true;
}
/**
* \brief Builder of TestThread objects.
*
* \param [in] testThreadFunction is a reference to test thread function that will be used in TestThread
* \param [in] priority is the thread's priority
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] firstSequencePoint is the first sequence point for this instance - equal to the order in which this
* thread will be started
*
* \return constructed TestThread object
*/
TestThread makeTestThread(const TestThreadFunction& testThreadFunction, const uint8_t priority,
SequenceAsserter& sequenceAsserter, const unsigned int firstSequencePoint)
{
return makeStaticThread<testThreadStackSize, true, totalThreads>(priority, testThreadFunction,
std::ref(sequenceAsserter), static_cast<unsigned int>(firstSequencePoint));
}
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// test stages
const std::array<Stage, 2> stages
{{
{generatedSignalsThread, generatedSignalsTrigger},
{queuedSignalsThread, queuedSignalsTrigger},
}};
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool SignalsWaitTestCase::run_() const
{
// priority required for this whole test to work
static_assert(testCasePriority_ + 2 <= UINT8_MAX, "Invalid test case priority");
constexpr decltype(testCasePriority_) testThreadPriority {testCasePriority_ + 1};
constexpr decltype(testCasePriority_) aboveTestThreadPriority {testThreadPriority + 1};
const auto contextSwitchCount = statistics::getContextSwitchCount();
std::remove_const<decltype(contextSwitchCount)>::type expectedContextSwitchCount {};
for (const auto& stage : stages)
for (const auto& phase : priorityTestPhases)
{
SequenceAsserter sequenceAsserter;
auto& threadFunction = stage.first;
std::array<TestThread, totalThreads> threads
{{
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 0),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 1),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 2),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 3),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 4),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 5),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 6),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 7),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 8),
makeTestThread(threadFunction, testThreadPriority, sequenceAsserter, 9),
}};
bool result {true};
for (auto& thread : threads)
{
thread.start();
// 2 context switches: "into" the thread and "back" to main thread when test thread blocks
expectedContextSwitchCount += 2;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
result = false;
}
for (const auto& thread : threads)
if (thread.getState() != ThreadState::WaitingForSignal)
result = false;
if (sequenceAsserter.assertSequence(totalThreads) == false)
result = false;
for (size_t i = 0; i < phase.second.size(); ++i)
{
auto& thread = threads[phase.second[i]];
ThisThread::setPriority(aboveTestThreadPriority);
const auto triggerResult = stage.second(thread, i, phase); // execute "trigger"
if (triggerResult == false)
result = false;
ThisThread::setPriority(testCasePriority_);
// 2 context switches: into" the unblocked thread and "back" to main thread when test thread terminates
expectedContextSwitchCount += 2;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
result = false;
}
for (auto& thread : threads)
thread.join();
if (result == false || sequenceAsserter.assertSequence(totalThreads * (totalThreads + 1)) == false)
return false;
}
constexpr auto totalContextSwitches = 4 * totalThreads * priorityTestPhases.size() * stages.size();
if (statistics::getContextSwitchCount() - contextSwitchCount != totalContextSwitches)
return false;
return true;
}
} // namespace test
} // namespace distortos
<|endoftext|> |
<commit_before>#include <cassert>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <cstring>
#include <gtkmm.h>
#include <gtksourceviewmm.h>
#include <glib/gmessages.h>
using namespace std ;
using namespace Gtk;
using namespace Glib;
using namespace Gsv ;
#define LOG(message) \
std::cout << __PRETTY_FUNCTION__ << ":" << __FILE__<< ":" << __LINE__ << ":" \
<< message << endl
#define THROW(message) \
LOG ("throwing exception: " + string (#message)) ; \
throw std::runtime_error (message) ;
#define THROW_IF_FAIL(cond) if (!(cond)) {\
THROW (std::string ("condition failed: ") + std::string (#cond)) \
}
class SearchDialog : public Dialog {
//non copyable
SearchDialog (const SearchDialog&) ;
SearchDialog& operator= (const SearchDialog&) ;
Gtk::HBox *m_hbox ;
Gtk::Entry *m_entry ;
Gtk::Button *m_search_forward_button ;
Gtk::Button *m_search_backward_button ;
sigc::signal<void> m_forward_search_requested_signal ;
sigc::signal<void> m_backward_search_requested_signal ;
void init_members ()
{
m_hbox = 0 ;
m_entry = 0 ;
m_search_forward_button = 0;
m_search_backward_button = 0;
}
void build_widget ()
{
add_button (Stock::CLOSE, RESPONSE_ACCEPT) ;
m_hbox = manage (new HBox) ;
get_vbox ()->pack_start (*m_hbox) ;
Label *label = manage (new Label ("Search: ")) ;
m_hbox->pack_start (*label) ;
m_entry = manage (new Entry ()) ;
m_hbox->pack_start (*m_entry) ;
m_search_forward_button = manage (new Button ("search forward")) ;
m_search_forward_button->signal_clicked ().connect (sigc::mem_fun
(*this, &SearchDialog::on_search_forward_button_clicked_signal)) ;
m_hbox->pack_start (*m_search_forward_button, PACK_SHRINK) ;
m_search_backward_button = manage (new Button ("search backward")) ;
m_search_backward_button->signal_clicked ().connect (sigc::mem_fun
(*this, &SearchDialog::on_search_backward_button_clicked_signal));
m_hbox->pack_start (*m_search_backward_button, PACK_SHRINK) ;
m_hbox->show_all () ;
}
void on_search_forward_button_clicked_signal ()
{
forward_search_requested_signal ().emit () ;
}
void on_search_backward_button_clicked_signal ()
{
backward_search_requested_signal ().emit () ;
}
public:
SearchDialog (const ustring &a_title="") :
Dialog (a_title)
{
init_members () ;
build_widget () ;
}
~SearchDialog ()
{
}
void get_search_string (ustring &a_str)
{
THROW_IF_FAIL (m_entry) ;
a_str = m_entry->get_text () ;
}
sigc::signal<void>& forward_search_requested_signal ()
{
return m_forward_search_requested_signal ;
}
sigc::signal<void>& backward_search_requested_signal ()
{
return m_backward_search_requested_signal ;
}
};//end class SearchDialog
class App {
//non copyable
App (const App&) ;
App& operator= (const App&) ;
Window *m_window ;
MenuBar *m_menu_bar ;
Menu *m_file_menu ;
MenuItem *m_file_menu_item ;
MenuItem *m_open_menu_item ;
Menu *m_edit_menu;
MenuItem *m_edit_menu_item ;
MenuItem *m_search_menu_item ;
VBox *m_main_vbox ;
View *m_source_view;
public:
App ()
{
init_members () ;
init_menu () ;
init_body () ;
}
void init_members ()
{
m_window = new Window ;
m_menu_bar = 0 ;
m_file_menu = 0 ;
m_file_menu_item = 0 ;
m_main_vbox = 0 ;
m_source_view = 0 ;
m_open_menu_item = 0 ;
m_edit_menu_item = 0 ;
m_search_menu_item = 0 ;
}
~App ()
{
if (m_window) {
delete m_window ;
m_window = 0 ;
}
}
//********************
//<signal handlers>
//********************
void on_open_menu_item_activate_signal ()
{
try {
FileChooserDialog fc_dialog ("open a file",
FILE_CHOOSER_ACTION_OPEN);
fc_dialog.set_select_multiple (false) ;
fc_dialog.add_button (Stock::CANCEL, RESPONSE_CANCEL) ;
fc_dialog.add_button (Stock::OK, RESPONSE_ACCEPT) ;
int res = fc_dialog.run () ;
if (res != RESPONSE_ACCEPT) {return;}
ustring filename = fc_dialog.get_filename () ;
if (filename == "") {return;}
open_file (filename) ;
} catch (...) {
LOG ("exception caught") ;
}
}
void on_search_menu_item_activate_signal ()
{
SearchDialog search_dialog ;
search_dialog.forward_search_requested_signal ().connect
(sigc::bind (sigc::mem_fun (*this,
&App::on_search_signal),
&search_dialog,
true)) ;
search_dialog.backward_search_requested_signal ().connect
(sigc::bind (sigc::mem_fun (*this,
&App::on_search_signal),
&search_dialog,
false)) ;
search_dialog.run () ;
search_dialog.hide () ;
}
void on_search_signal (SearchDialog *a_dialog,
bool a_forward)
{
if (!a_dialog) {return;}
ustring search_str ;
a_dialog->get_search_string (search_str) ;
if (search_str == "") {return ;}
if (!do_search (search_str, a_forward)) {
MessageDialog dialog (*a_dialog,
"Did not find string " + search_str,
MESSAGE_WARNING) ;
dialog.run () ;
dialog.hide () ;
}
}
bool do_search (const ustring &a_text,
bool a_forward)
{
THROW_IF_FAIL (m_source_view) ;
RefPtr<Buffer> source_buffer = m_source_view->get_source_buffer () ;
TextIter search_iter (source_buffer->begin ());
TextIter start, end, limit ;
if (!a_forward) {
search_iter = source_buffer->end () ;
search_iter-- ;
}
TextIter last_sel_start ;
bool found=false ;
if (a_forward) {
if (source_buffer->get_selection_bounds (start, last_sel_start)) {
search_iter = last_sel_start ;
}
limit = source_buffer->end () ;
found = search_iter.forward_search
(a_text,
TEXT_SEARCH_TEXT_ONLY | TEXT_SEARCH_CASE_INSENSITIVE,
start,
end,
limit) ;
} else {
if (source_buffer->get_selection_bounds (last_sel_start, end)) {
search_iter = last_sel_start ;
}
limit = source_buffer->begin () ;
found = search_iter.backward_search
(a_text,
TEXT_SEARCH_TEXT_ONLY | TEXT_SEARCH_CASE_INSENSITIVE,
start,
end,
limit) ;
}
if (found) {
m_source_view->scroll_to (start, 0.1) ;
m_source_view->get_source_buffer ()->select_range (start, end) ;
return true ;
}
return false ;
}
//********************
//</signal handlers>
//********************
void init_menu ()
{
if (m_menu_bar) {return;}
//********************
//<build the menu bar>
//*********************
m_menu_bar = manage (new MenuBar) ;
//********************
//build the File menu
//**********************
m_file_menu = manage (new Menu) ;
m_file_menu_item = manage (new MenuItem ("File")) ;
m_file_menu_item->set_submenu (*m_file_menu) ;
m_open_menu_item = manage (new MenuItem ("Open")) ;
m_file_menu->insert (*m_open_menu_item, -1) ;
//*********************
//build the edit menu
//*********************
m_edit_menu_item = manage (new MenuItem ("Edit")) ;
m_edit_menu = manage (new Menu) ;
m_edit_menu_item->set_submenu (*m_edit_menu) ;
m_search_menu_item = manage (new MenuItem ("Search")) ;
m_edit_menu->insert (*m_search_menu_item, -1) ;
//now pack the menus into the menu_bar
m_menu_bar->insert(*m_file_menu_item, -1) ;
m_menu_bar->insert (*m_edit_menu_item, -1) ;
//********************
//</build the menu bar>
//*********************
connect_menu_signals () ;
}
void connect_menu_signals ()
{
THROW_IF_FAIL (m_open_menu_item) ;
THROW_IF_FAIL (m_search_menu_item) ;
m_open_menu_item->signal_activate ().connect (sigc::mem_fun
(*this, &App::on_open_menu_item_activate_signal)) ;
m_search_menu_item->signal_activate ().connect (sigc::mem_fun
(*this, &App::on_search_menu_item_activate_signal)) ;
}
void init_body ()
{
if (m_main_vbox) {return;}
m_main_vbox = manage (new VBox) ;
g_return_if_fail (m_menu_bar) ;
m_main_vbox->pack_start (*m_menu_bar, PACK_SHRINK) ;
m_source_view = manage (new View) ;
m_main_vbox->pack_start (*m_source_view) ;
get_widget ().add (*m_main_vbox) ;
}
Window& get_widget ()
{
THROW_IF_FAIL (m_window) ;
return *m_window ;
}
void open_file (const ustring& a_path)
{
if (a_path == "") {return;}
THROW_IF_FAIL (m_source_view) ;
ifstream file (filename_from_utf8 (a_path).c_str ()) ;
if (!file.good ()) {
LOG ("Could not open file " + locale_to_utf8 (a_path)) ;
return ;
}
static const int BUFFER_SIZE=1024*10 ;
static char buffer[BUFFER_SIZE + 1] ;
memset (buffer, 0, BUFFER_SIZE + 1) ;
RefPtr<Buffer> source_buffer = m_source_view->get_source_buffer () ;
for (;;) {
file.read (buffer, BUFFER_SIZE) ;
THROW_IF_FAIL (file.good () || file.eof ()) ;
source_buffer->insert (source_buffer->end (),
buffer,
buffer + file.gcount ()) ;
if (file.gcount () != BUFFER_SIZE) {break ;}
}
file.close () ;
}
};//end class App
int
main (int argc, char **argv)
{
//***************
//init plumbing
//***************
Main kit (argc, argv) ;
Gsv::init () ;
App app ;
app.get_widget ().set_size_request (500, 400) ;
app.get_widget ().show_all () ;
if (argc == 2) {
app.open_file (filename_to_utf8 (argv[1])) ;
}
kit.run (app.get_widget ()) ;
return 0 ;
}
<commit_msg>Fix distcheck.<commit_after>#include <cassert>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <cstring>
#include <gtkmm.h>
#include <gtksourceviewmm.h>
#include <glib/gmessages.h>
using namespace std ;
using namespace Gtk;
using namespace Glib;
using namespace Gsv ;
#define LOG(message) \
std::cout << __PRETTY_FUNCTION__ << ":" << __FILE__<< ":" << __LINE__ << ":" \
<< message << endl
#define THROW(message) \
LOG ("throwing exception: " + string (#message)) ; \
throw std::runtime_error (message) ;
#define THROW_IF_FAIL(cond) if (!(cond)) {\
THROW (std::string ("condition failed: ") + std::string (#cond)) \
}
class SearchDialog : public Dialog {
//non copyable
SearchDialog (const SearchDialog&) ;
SearchDialog& operator= (const SearchDialog&) ;
Gtk::HBox *m_hbox ;
Gtk::Entry *m_entry ;
Gtk::Button *m_search_forward_button ;
Gtk::Button *m_search_backward_button ;
sigc::signal<void> m_forward_search_requested_signal ;
sigc::signal<void> m_backward_search_requested_signal ;
void init_members ()
{
m_hbox = 0 ;
m_entry = 0 ;
m_search_forward_button = 0;
m_search_backward_button = 0;
}
void build_widget ()
{
add_button (Stock::CLOSE, RESPONSE_ACCEPT) ;
m_hbox = manage (new HBox) ;
get_content_area ()->pack_start (*m_hbox) ;
Label *label = manage (new Label ("Search: ")) ;
m_hbox->pack_start (*label) ;
m_entry = manage (new Entry ()) ;
m_hbox->pack_start (*m_entry) ;
m_search_forward_button = manage (new Button ("search forward")) ;
m_search_forward_button->signal_clicked ().connect (sigc::mem_fun
(*this, &SearchDialog::on_search_forward_button_clicked_signal)) ;
m_hbox->pack_start (*m_search_forward_button, PACK_SHRINK) ;
m_search_backward_button = manage (new Button ("search backward")) ;
m_search_backward_button->signal_clicked ().connect (sigc::mem_fun
(*this, &SearchDialog::on_search_backward_button_clicked_signal));
m_hbox->pack_start (*m_search_backward_button, PACK_SHRINK) ;
m_hbox->show_all () ;
}
void on_search_forward_button_clicked_signal ()
{
forward_search_requested_signal ().emit () ;
}
void on_search_backward_button_clicked_signal ()
{
backward_search_requested_signal ().emit () ;
}
public:
SearchDialog (const ustring &a_title="") :
Dialog (a_title)
{
init_members () ;
build_widget () ;
}
~SearchDialog ()
{
}
void get_search_string (ustring &a_str)
{
THROW_IF_FAIL (m_entry) ;
a_str = m_entry->get_text () ;
}
sigc::signal<void>& forward_search_requested_signal ()
{
return m_forward_search_requested_signal ;
}
sigc::signal<void>& backward_search_requested_signal ()
{
return m_backward_search_requested_signal ;
}
};//end class SearchDialog
class App {
//non copyable
App (const App&) ;
App& operator= (const App&) ;
Window *m_window ;
MenuBar *m_menu_bar ;
Menu *m_file_menu ;
MenuItem *m_file_menu_item ;
MenuItem *m_open_menu_item ;
Menu *m_edit_menu;
MenuItem *m_edit_menu_item ;
MenuItem *m_search_menu_item ;
VBox *m_main_vbox ;
View *m_source_view;
public:
App ()
{
init_members () ;
init_menu () ;
init_body () ;
}
void init_members ()
{
m_window = new Window ;
m_menu_bar = 0 ;
m_file_menu = 0 ;
m_file_menu_item = 0 ;
m_main_vbox = 0 ;
m_source_view = 0 ;
m_open_menu_item = 0 ;
m_edit_menu_item = 0 ;
m_search_menu_item = 0 ;
}
~App ()
{
if (m_window) {
delete m_window ;
m_window = 0 ;
}
}
//********************
//<signal handlers>
//********************
void on_open_menu_item_activate_signal ()
{
try {
FileChooserDialog fc_dialog ("open a file",
FILE_CHOOSER_ACTION_OPEN);
fc_dialog.set_select_multiple (false) ;
fc_dialog.add_button (Stock::CANCEL, RESPONSE_CANCEL) ;
fc_dialog.add_button (Stock::OK, RESPONSE_ACCEPT) ;
int res = fc_dialog.run () ;
if (res != RESPONSE_ACCEPT) {return;}
ustring filename = fc_dialog.get_filename () ;
if (filename == "") {return;}
open_file (filename) ;
} catch (...) {
LOG ("exception caught") ;
}
}
void on_search_menu_item_activate_signal ()
{
SearchDialog search_dialog ;
search_dialog.forward_search_requested_signal ().connect
(sigc::bind (sigc::mem_fun (*this,
&App::on_search_signal),
&search_dialog,
true)) ;
search_dialog.backward_search_requested_signal ().connect
(sigc::bind (sigc::mem_fun (*this,
&App::on_search_signal),
&search_dialog,
false)) ;
search_dialog.run () ;
search_dialog.hide () ;
}
void on_search_signal (SearchDialog *a_dialog,
bool a_forward)
{
if (!a_dialog) {return;}
ustring search_str ;
a_dialog->get_search_string (search_str) ;
if (search_str == "") {return ;}
if (!do_search (search_str, a_forward)) {
MessageDialog dialog (*a_dialog,
"Did not find string " + search_str,
MESSAGE_WARNING) ;
dialog.run () ;
dialog.hide () ;
}
}
bool do_search (const ustring &a_text,
bool a_forward)
{
THROW_IF_FAIL (m_source_view) ;
RefPtr<Buffer> source_buffer = m_source_view->get_source_buffer () ;
TextIter search_iter (source_buffer->begin ());
TextIter start, end, limit ;
if (!a_forward) {
search_iter = source_buffer->end () ;
search_iter-- ;
}
TextIter last_sel_start ;
bool found=false ;
if (a_forward) {
if (source_buffer->get_selection_bounds (start, last_sel_start)) {
search_iter = last_sel_start ;
}
limit = source_buffer->end () ;
found = search_iter.forward_search
(a_text,
TEXT_SEARCH_TEXT_ONLY | TEXT_SEARCH_CASE_INSENSITIVE,
start,
end,
limit) ;
} else {
if (source_buffer->get_selection_bounds (last_sel_start, end)) {
search_iter = last_sel_start ;
}
limit = source_buffer->begin () ;
found = search_iter.backward_search
(a_text,
TEXT_SEARCH_TEXT_ONLY | TEXT_SEARCH_CASE_INSENSITIVE,
start,
end,
limit) ;
}
if (found) {
m_source_view->scroll_to (start, 0.1) ;
m_source_view->get_source_buffer ()->select_range (start, end) ;
return true ;
}
return false ;
}
//********************
//</signal handlers>
//********************
void init_menu ()
{
if (m_menu_bar) {return;}
//********************
//<build the menu bar>
//*********************
m_menu_bar = manage (new MenuBar) ;
//********************
//build the File menu
//**********************
m_file_menu = manage (new Menu) ;
m_file_menu_item = manage (new MenuItem ("File")) ;
m_file_menu_item->set_submenu (*m_file_menu) ;
m_open_menu_item = manage (new MenuItem ("Open")) ;
m_file_menu->insert (*m_open_menu_item, -1) ;
//*********************
//build the edit menu
//*********************
m_edit_menu_item = manage (new MenuItem ("Edit")) ;
m_edit_menu = manage (new Menu) ;
m_edit_menu_item->set_submenu (*m_edit_menu) ;
m_search_menu_item = manage (new MenuItem ("Search")) ;
m_edit_menu->insert (*m_search_menu_item, -1) ;
//now pack the menus into the menu_bar
m_menu_bar->insert(*m_file_menu_item, -1) ;
m_menu_bar->insert (*m_edit_menu_item, -1) ;
//********************
//</build the menu bar>
//*********************
connect_menu_signals () ;
}
void connect_menu_signals ()
{
THROW_IF_FAIL (m_open_menu_item) ;
THROW_IF_FAIL (m_search_menu_item) ;
m_open_menu_item->signal_activate ().connect (sigc::mem_fun
(*this, &App::on_open_menu_item_activate_signal)) ;
m_search_menu_item->signal_activate ().connect (sigc::mem_fun
(*this, &App::on_search_menu_item_activate_signal)) ;
}
void init_body ()
{
if (m_main_vbox) {return;}
m_main_vbox = manage (new VBox) ;
g_return_if_fail (m_menu_bar) ;
m_main_vbox->pack_start (*m_menu_bar, PACK_SHRINK) ;
m_source_view = manage (new View) ;
m_main_vbox->pack_start (*m_source_view) ;
get_widget ().add (*m_main_vbox) ;
}
Window& get_widget ()
{
THROW_IF_FAIL (m_window) ;
return *m_window ;
}
void open_file (const ustring& a_path)
{
if (a_path == "") {return;}
THROW_IF_FAIL (m_source_view) ;
ifstream file (filename_from_utf8 (a_path).c_str ()) ;
if (!file.good ()) {
LOG ("Could not open file " + locale_to_utf8 (a_path)) ;
return ;
}
static const int BUFFER_SIZE=1024*10 ;
static char buffer[BUFFER_SIZE + 1] ;
memset (buffer, 0, BUFFER_SIZE + 1) ;
RefPtr<Buffer> source_buffer = m_source_view->get_source_buffer () ;
for (;;) {
file.read (buffer, BUFFER_SIZE) ;
THROW_IF_FAIL (file.good () || file.eof ()) ;
source_buffer->insert (source_buffer->end (),
buffer,
buffer + file.gcount ()) ;
if (file.gcount () != BUFFER_SIZE) {break ;}
}
file.close () ;
}
};//end class App
int
main (int argc, char **argv)
{
//***************
//init plumbing
//***************
Main kit (argc, argv) ;
Gsv::init () ;
App app ;
app.get_widget ().set_size_request (500, 400) ;
app.get_widget ().show_all () ;
if (argc == 2) {
app.open_file (filename_to_utf8 (argv[1])) ;
}
kit.run (app.get_widget ()) ;
return 0 ;
}
<|endoftext|> |
<commit_before>#include <cassert>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <cstring>
#include <gtkmm.h>
#include <gtksourceviewmm.h>
#include <glib/gmessages.h>
using namespace std ;
using namespace Gtk;
using namespace Glib;
using namespace Gsv ;
#define LOG(message) \
std::cout << __PRETTY_FUNCTION__ << ":" << __FILE__<< ":" << __LINE__ << ":" \
<< message << endl
#define THROW(message) \
LOG ("throwing exception: " + string (#message)) ; \
throw std::runtime_error (message) ;
#define THROW_IF_FAIL(cond) if (!(cond)) {\
THROW (std::string ("condition failed: ") + std::string (#cond)) \
}
class SearchDialog : public Dialog {
//non copyable
SearchDialog (const SearchDialog&) ;
SearchDialog& operator= (const SearchDialog&) ;
Gtk::HBox *m_hbox ;
Gtk::Entry *m_entry ;
Gtk::Button *m_search_forward_button ;
Gtk::Button *m_search_backward_button ;
sigc::signal<void> m_forward_search_requested_signal ;
sigc::signal<void> m_backward_search_requested_signal ;
void init_members ()
{
m_hbox = 0 ;
m_entry = 0 ;
m_search_forward_button = 0;
m_search_backward_button = 0;
}
void build_widget ()
{
add_button (Stock::CLOSE, RESPONSE_ACCEPT) ;
m_hbox = manage (new HBox) ;
get_content_area ()->pack_start (*m_hbox) ;
Label *label = manage (new Label ("Search: ")) ;
m_hbox->pack_start (*label) ;
m_entry = manage (new Entry ()) ;
m_hbox->pack_start (*m_entry) ;
m_search_forward_button = manage (new Button ("search forward")) ;
m_search_forward_button->signal_clicked ().connect (sigc::mem_fun
(*this, &SearchDialog::on_search_forward_button_clicked_signal)) ;
m_hbox->pack_start (*m_search_forward_button, PACK_SHRINK) ;
m_search_backward_button = manage (new Button ("search backward")) ;
m_search_backward_button->signal_clicked ().connect (sigc::mem_fun
(*this, &SearchDialog::on_search_backward_button_clicked_signal));
m_hbox->pack_start (*m_search_backward_button, PACK_SHRINK) ;
m_hbox->show_all () ;
}
void on_search_forward_button_clicked_signal ()
{
forward_search_requested_signal ().emit () ;
}
void on_search_backward_button_clicked_signal ()
{
backward_search_requested_signal ().emit () ;
}
public:
SearchDialog (const ustring &a_title="") :
Dialog (a_title)
{
init_members () ;
build_widget () ;
}
~SearchDialog ()
{
}
void get_search_string (ustring &a_str)
{
THROW_IF_FAIL (m_entry) ;
a_str = m_entry->get_text () ;
}
sigc::signal<void>& forward_search_requested_signal ()
{
return m_forward_search_requested_signal ;
}
sigc::signal<void>& backward_search_requested_signal ()
{
return m_backward_search_requested_signal ;
}
};//end class SearchDialog
class App {
//non copyable
App (const App&) ;
App& operator= (const App&) ;
Window *m_window ;
MenuBar *m_menu_bar ;
Menu *m_file_menu ;
MenuItem *m_file_menu_item ;
MenuItem *m_open_menu_item ;
Menu *m_edit_menu;
MenuItem *m_edit_menu_item ;
MenuItem *m_search_menu_item ;
VBox *m_main_vbox ;
View *m_source_view;
public:
App ()
{
init_members () ;
init_menu () ;
init_body () ;
}
void init_members ()
{
m_window = new Window ;
m_menu_bar = 0 ;
m_file_menu = 0 ;
m_file_menu_item = 0 ;
m_main_vbox = 0 ;
m_source_view = 0 ;
m_open_menu_item = 0 ;
m_edit_menu_item = 0 ;
m_search_menu_item = 0 ;
}
~App ()
{
if (m_window) {
delete m_window ;
m_window = 0 ;
}
}
//********************
//<signal handlers>
//********************
void on_open_menu_item_activate_signal ()
{
try {
FileChooserDialog fc_dialog ("open a file",
FILE_CHOOSER_ACTION_OPEN);
fc_dialog.set_select_multiple (false) ;
fc_dialog.add_button (Stock::CANCEL, RESPONSE_CANCEL) ;
fc_dialog.add_button (Stock::OK, RESPONSE_ACCEPT) ;
int res = fc_dialog.run () ;
if (res != RESPONSE_ACCEPT) {return;}
ustring filename = fc_dialog.get_filename () ;
if (filename == "") {return;}
open_file (filename) ;
} catch (...) {
LOG ("exception caught") ;
}
}
void on_search_menu_item_activate_signal ()
{
SearchDialog search_dialog ;
search_dialog.forward_search_requested_signal ().connect
(sigc::bind (sigc::mem_fun (*this,
&App::on_search_signal),
&search_dialog,
true)) ;
search_dialog.backward_search_requested_signal ().connect
(sigc::bind (sigc::mem_fun (*this,
&App::on_search_signal),
&search_dialog,
false)) ;
search_dialog.run () ;
search_dialog.hide () ;
}
void on_search_signal (SearchDialog *a_dialog,
bool a_forward)
{
if (!a_dialog) {return;}
ustring search_str ;
a_dialog->get_search_string (search_str) ;
if (search_str == "") {return ;}
if (!do_search (search_str, a_forward)) {
MessageDialog dialog (*a_dialog,
"Did not find string " + search_str,
MESSAGE_WARNING) ;
dialog.run () ;
dialog.hide () ;
}
}
bool do_search (const ustring &a_text,
bool a_forward)
{
THROW_IF_FAIL (m_source_view) ;
RefPtr<Buffer> source_buffer = m_source_view->get_source_buffer () ;
TextIter search_iter (source_buffer->begin ());
TextIter start, end, limit ;
if (!a_forward) {
search_iter = source_buffer->end () ;
search_iter-- ;
}
TextIter last_sel_start ;
bool found=false ;
if (a_forward) {
if (source_buffer->get_selection_bounds (start, last_sel_start)) {
search_iter = last_sel_start ;
}
limit = source_buffer->end () ;
found = search_iter.forward_search
(a_text,
TEXT_SEARCH_TEXT_ONLY | TEXT_SEARCH_CASE_INSENSITIVE,
start,
end,
limit) ;
} else {
if (source_buffer->get_selection_bounds (last_sel_start, end)) {
search_iter = last_sel_start ;
}
limit = source_buffer->begin () ;
found = search_iter.backward_search
(a_text,
TEXT_SEARCH_TEXT_ONLY | TEXT_SEARCH_CASE_INSENSITIVE,
start,
end,
limit) ;
}
if (found) {
m_source_view->scroll_to (start, 0.1) ;
m_source_view->get_source_buffer ()->select_range (start, end) ;
return true ;
}
return false ;
}
//********************
//</signal handlers>
//********************
void init_menu ()
{
if (m_menu_bar) {return;}
//********************
//<build the menu bar>
//*********************
m_menu_bar = manage (new MenuBar) ;
//********************
//build the File menu
//**********************
m_file_menu = manage (new Menu) ;
m_file_menu_item = manage (new MenuItem ("File")) ;
m_file_menu_item->set_submenu (*m_file_menu) ;
m_open_menu_item = manage (new MenuItem ("Open")) ;
m_file_menu->insert (*m_open_menu_item, -1) ;
//*********************
//build the edit menu
//*********************
m_edit_menu_item = manage (new MenuItem ("Edit")) ;
m_edit_menu = manage (new Menu) ;
m_edit_menu_item->set_submenu (*m_edit_menu) ;
m_search_menu_item = manage (new MenuItem ("Search")) ;
m_edit_menu->insert (*m_search_menu_item, -1) ;
//now pack the menus into the menu_bar
m_menu_bar->insert(*m_file_menu_item, -1) ;
m_menu_bar->insert (*m_edit_menu_item, -1) ;
//********************
//</build the menu bar>
//*********************
connect_menu_signals () ;
}
void connect_menu_signals ()
{
THROW_IF_FAIL (m_open_menu_item) ;
THROW_IF_FAIL (m_search_menu_item) ;
m_open_menu_item->signal_activate ().connect (sigc::mem_fun
(*this, &App::on_open_menu_item_activate_signal)) ;
m_search_menu_item->signal_activate ().connect (sigc::mem_fun
(*this, &App::on_search_menu_item_activate_signal)) ;
}
void init_body ()
{
if (m_main_vbox) {return;}
m_main_vbox = manage (new VBox) ;
g_return_if_fail (m_menu_bar) ;
m_main_vbox->pack_start (*m_menu_bar, PACK_SHRINK) ;
m_source_view = manage (new View) ;
m_main_vbox->pack_start (*m_source_view) ;
get_widget ().add (*m_main_vbox) ;
}
Window& get_widget ()
{
THROW_IF_FAIL (m_window) ;
return *m_window ;
}
void open_file (const ustring& a_path)
{
if (a_path == "") {return;}
THROW_IF_FAIL (m_source_view) ;
ifstream file (filename_from_utf8 (a_path).c_str ()) ;
if (!file.good ()) {
LOG ("Could not open file " + locale_to_utf8 (a_path)) ;
return ;
}
static const int BUFFER_SIZE=1024*10 ;
static char buffer[BUFFER_SIZE + 1] ;
memset (buffer, 0, BUFFER_SIZE + 1) ;
RefPtr<Buffer> source_buffer = m_source_view->get_source_buffer () ;
for (;;) {
file.read (buffer, BUFFER_SIZE) ;
THROW_IF_FAIL (file.good () || file.eof ()) ;
source_buffer->insert (source_buffer->end (),
buffer,
buffer + file.gcount ()) ;
if (file.gcount () != BUFFER_SIZE) {break ;}
}
file.close () ;
}
};//end class App
int
main (int argc, char **argv)
{
//***************
//init plumbing
//***************
Main kit (argc, argv) ;
Gsv::init () ;
App app ;
app.get_widget ().set_size_request (500, 400) ;
app.get_widget ().show_all () ;
if (argc == 2) {
app.open_file (filename_to_utf8 (argv[1])) ;
}
kit.run (app.get_widget ()) ;
return 0 ;
}
<commit_msg>Examples: Do not include gmessages.h directly.<commit_after>#include <cassert>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <cstring>
#include <gtkmm.h>
#include <gtksourceviewmm.h>
#include <glib.h> //For <gmessages.h>
using namespace std ;
using namespace Gtk;
using namespace Glib;
using namespace Gsv ;
#define LOG(message) \
std::cout << __PRETTY_FUNCTION__ << ":" << __FILE__<< ":" << __LINE__ << ":" \
<< message << endl
#define THROW(message) \
LOG ("throwing exception: " + string (#message)) ; \
throw std::runtime_error (message) ;
#define THROW_IF_FAIL(cond) if (!(cond)) {\
THROW (std::string ("condition failed: ") + std::string (#cond)) \
}
class SearchDialog : public Dialog {
//non copyable
SearchDialog (const SearchDialog&) ;
SearchDialog& operator= (const SearchDialog&) ;
Gtk::HBox *m_hbox ;
Gtk::Entry *m_entry ;
Gtk::Button *m_search_forward_button ;
Gtk::Button *m_search_backward_button ;
sigc::signal<void> m_forward_search_requested_signal ;
sigc::signal<void> m_backward_search_requested_signal ;
void init_members ()
{
m_hbox = 0 ;
m_entry = 0 ;
m_search_forward_button = 0;
m_search_backward_button = 0;
}
void build_widget ()
{
add_button (Stock::CLOSE, RESPONSE_ACCEPT) ;
m_hbox = manage (new HBox) ;
get_content_area ()->pack_start (*m_hbox) ;
Label *label = manage (new Label ("Search: ")) ;
m_hbox->pack_start (*label) ;
m_entry = manage (new Entry ()) ;
m_hbox->pack_start (*m_entry) ;
m_search_forward_button = manage (new Button ("search forward")) ;
m_search_forward_button->signal_clicked ().connect (sigc::mem_fun
(*this, &SearchDialog::on_search_forward_button_clicked_signal)) ;
m_hbox->pack_start (*m_search_forward_button, PACK_SHRINK) ;
m_search_backward_button = manage (new Button ("search backward")) ;
m_search_backward_button->signal_clicked ().connect (sigc::mem_fun
(*this, &SearchDialog::on_search_backward_button_clicked_signal));
m_hbox->pack_start (*m_search_backward_button, PACK_SHRINK) ;
m_hbox->show_all () ;
}
void on_search_forward_button_clicked_signal ()
{
forward_search_requested_signal ().emit () ;
}
void on_search_backward_button_clicked_signal ()
{
backward_search_requested_signal ().emit () ;
}
public:
SearchDialog (const ustring &a_title="") :
Dialog (a_title)
{
init_members () ;
build_widget () ;
}
~SearchDialog ()
{
}
void get_search_string (ustring &a_str)
{
THROW_IF_FAIL (m_entry) ;
a_str = m_entry->get_text () ;
}
sigc::signal<void>& forward_search_requested_signal ()
{
return m_forward_search_requested_signal ;
}
sigc::signal<void>& backward_search_requested_signal ()
{
return m_backward_search_requested_signal ;
}
};//end class SearchDialog
class App {
//non copyable
App (const App&) ;
App& operator= (const App&) ;
Window *m_window ;
MenuBar *m_menu_bar ;
Menu *m_file_menu ;
MenuItem *m_file_menu_item ;
MenuItem *m_open_menu_item ;
Menu *m_edit_menu;
MenuItem *m_edit_menu_item ;
MenuItem *m_search_menu_item ;
VBox *m_main_vbox ;
View *m_source_view;
public:
App ()
{
init_members () ;
init_menu () ;
init_body () ;
}
void init_members ()
{
m_window = new Window ;
m_menu_bar = 0 ;
m_file_menu = 0 ;
m_file_menu_item = 0 ;
m_main_vbox = 0 ;
m_source_view = 0 ;
m_open_menu_item = 0 ;
m_edit_menu_item = 0 ;
m_search_menu_item = 0 ;
}
~App ()
{
if (m_window) {
delete m_window ;
m_window = 0 ;
}
}
//********************
//<signal handlers>
//********************
void on_open_menu_item_activate_signal ()
{
try {
FileChooserDialog fc_dialog ("open a file",
FILE_CHOOSER_ACTION_OPEN);
fc_dialog.set_select_multiple (false) ;
fc_dialog.add_button (Stock::CANCEL, RESPONSE_CANCEL) ;
fc_dialog.add_button (Stock::OK, RESPONSE_ACCEPT) ;
int res = fc_dialog.run () ;
if (res != RESPONSE_ACCEPT) {return;}
ustring filename = fc_dialog.get_filename () ;
if (filename == "") {return;}
open_file (filename) ;
} catch (...) {
LOG ("exception caught") ;
}
}
void on_search_menu_item_activate_signal ()
{
SearchDialog search_dialog ;
search_dialog.forward_search_requested_signal ().connect
(sigc::bind (sigc::mem_fun (*this,
&App::on_search_signal),
&search_dialog,
true)) ;
search_dialog.backward_search_requested_signal ().connect
(sigc::bind (sigc::mem_fun (*this,
&App::on_search_signal),
&search_dialog,
false)) ;
search_dialog.run () ;
search_dialog.hide () ;
}
void on_search_signal (SearchDialog *a_dialog,
bool a_forward)
{
if (!a_dialog) {return;}
ustring search_str ;
a_dialog->get_search_string (search_str) ;
if (search_str == "") {return ;}
if (!do_search (search_str, a_forward)) {
MessageDialog dialog (*a_dialog,
"Did not find string " + search_str,
MESSAGE_WARNING) ;
dialog.run () ;
dialog.hide () ;
}
}
bool do_search (const ustring &a_text,
bool a_forward)
{
THROW_IF_FAIL (m_source_view) ;
RefPtr<Buffer> source_buffer = m_source_view->get_source_buffer () ;
TextIter search_iter (source_buffer->begin ());
TextIter start, end, limit ;
if (!a_forward) {
search_iter = source_buffer->end () ;
search_iter-- ;
}
TextIter last_sel_start ;
bool found=false ;
if (a_forward) {
if (source_buffer->get_selection_bounds (start, last_sel_start)) {
search_iter = last_sel_start ;
}
limit = source_buffer->end () ;
found = search_iter.forward_search
(a_text,
TEXT_SEARCH_TEXT_ONLY | TEXT_SEARCH_CASE_INSENSITIVE,
start,
end,
limit) ;
} else {
if (source_buffer->get_selection_bounds (last_sel_start, end)) {
search_iter = last_sel_start ;
}
limit = source_buffer->begin () ;
found = search_iter.backward_search
(a_text,
TEXT_SEARCH_TEXT_ONLY | TEXT_SEARCH_CASE_INSENSITIVE,
start,
end,
limit) ;
}
if (found) {
m_source_view->scroll_to (start, 0.1) ;
m_source_view->get_source_buffer ()->select_range (start, end) ;
return true ;
}
return false ;
}
//********************
//</signal handlers>
//********************
void init_menu ()
{
if (m_menu_bar) {return;}
//********************
//<build the menu bar>
//*********************
m_menu_bar = manage (new MenuBar) ;
//********************
//build the File menu
//**********************
m_file_menu = manage (new Menu) ;
m_file_menu_item = manage (new MenuItem ("File")) ;
m_file_menu_item->set_submenu (*m_file_menu) ;
m_open_menu_item = manage (new MenuItem ("Open")) ;
m_file_menu->insert (*m_open_menu_item, -1) ;
//*********************
//build the edit menu
//*********************
m_edit_menu_item = manage (new MenuItem ("Edit")) ;
m_edit_menu = manage (new Menu) ;
m_edit_menu_item->set_submenu (*m_edit_menu) ;
m_search_menu_item = manage (new MenuItem ("Search")) ;
m_edit_menu->insert (*m_search_menu_item, -1) ;
//now pack the menus into the menu_bar
m_menu_bar->insert(*m_file_menu_item, -1) ;
m_menu_bar->insert (*m_edit_menu_item, -1) ;
//********************
//</build the menu bar>
//*********************
connect_menu_signals () ;
}
void connect_menu_signals ()
{
THROW_IF_FAIL (m_open_menu_item) ;
THROW_IF_FAIL (m_search_menu_item) ;
m_open_menu_item->signal_activate ().connect (sigc::mem_fun
(*this, &App::on_open_menu_item_activate_signal)) ;
m_search_menu_item->signal_activate ().connect (sigc::mem_fun
(*this, &App::on_search_menu_item_activate_signal)) ;
}
void init_body ()
{
if (m_main_vbox) {return;}
m_main_vbox = manage (new VBox) ;
g_return_if_fail (m_menu_bar) ;
m_main_vbox->pack_start (*m_menu_bar, PACK_SHRINK) ;
m_source_view = manage (new View) ;
m_main_vbox->pack_start (*m_source_view) ;
get_widget ().add (*m_main_vbox) ;
}
Window& get_widget ()
{
THROW_IF_FAIL (m_window) ;
return *m_window ;
}
void open_file (const ustring& a_path)
{
if (a_path == "") {return;}
THROW_IF_FAIL (m_source_view) ;
ifstream file (filename_from_utf8 (a_path).c_str ()) ;
if (!file.good ()) {
LOG ("Could not open file " + locale_to_utf8 (a_path)) ;
return ;
}
static const int BUFFER_SIZE=1024*10 ;
static char buffer[BUFFER_SIZE + 1] ;
memset (buffer, 0, BUFFER_SIZE + 1) ;
RefPtr<Buffer> source_buffer = m_source_view->get_source_buffer () ;
for (;;) {
file.read (buffer, BUFFER_SIZE) ;
THROW_IF_FAIL (file.good () || file.eof ()) ;
source_buffer->insert (source_buffer->end (),
buffer,
buffer + file.gcount ()) ;
if (file.gcount () != BUFFER_SIZE) {break ;}
}
file.close () ;
}
};//end class App
int
main (int argc, char **argv)
{
//***************
//init plumbing
//***************
Main kit (argc, argv) ;
Gsv::init () ;
App app ;
app.get_widget ().set_size_request (500, 400) ;
app.get_widget ().show_all () ;
if (argc == 2) {
app.open_file (filename_to_utf8 (argv[1])) ;
}
kit.run (app.get_widget ()) ;
return 0 ;
}
<|endoftext|> |
<commit_before>//
// Created by nprat on 7/4/16.
//
#include <chrono>
#include <string>
#include "openGL.h"
std::shared_ptr<OpenGL> OpenGL::m_openGL = nullptr;
OpenGL::OpenGL()
{
m_openGL = nullptr;
m_renderChain = nullptr;
m_obj = nullptr;
m_display = nullptr;
m_lowestTime = 0;
}
OpenGL::~OpenGL()
{}
bool OpenGL::InitOpenGL(int width, int height, std::string title)
{
std::cout << "Creating API" << std::endl;
gl::InitAPI();
std::cout << "Finished Creating API" << std::endl;
try
{
m_display = std::make_shared<GlutDisplay>(width, height, title);
m_renderChain = std::make_shared<RenderChain>(10);
m_obj = std::make_shared<TestObject>(m_display);
m_obj2 = std::make_shared<TestObject>(m_display);
}
catch (const char* error)
{
std::cout << "Error: " << error << std::endl;
return false;
}
m_obj->Translate(glm::translate(glm::mat4(1.0f), glm::vec3(0.5f, 0.5f, -0.5f)));
//obj->Scale(glm::scale(glm::vec3(0.5f, 1.0f, 1.0f)));
//obj->Rotate(glm::rotate(glm::pi<float>(), glm::vec3(0.0f, 0.0f, 1.0f)));
//obj->Translate(glm::translate(glm::mat4(1.0f), glm::vec3(1.0f, 0.0f, 0.0f)));
std::cout << "Information: " << std::endl;
std::cout << "\tGL Version: " << glGetString(GL_VERSION) << std::endl;
std::cout << "\tDisplay Address: " << m_display << std::endl;
std::cout << "\tRender Chain Address: " << m_renderChain << std::endl;
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
return true;
}
void OpenGL::Destroy()
{
}
void OpenGL::DisplayFunc()
{
//std::cout << "DisplayFunc()" << std::endl;
//auto start = std::chrono::high_resolution_clock::now();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//std::cout << "OpenGL::DisplayFunc()" << std::endl;
m_renderChain->AttachRenderObject(m_obj.get());
m_renderChain->AttachRenderObject(m_obj2.get());
m_renderChain->RenderObjectChain();
glutSwapBuffers();
/*auto finish = std::chrono::high_resolution_clock::now();
if(time < m_lowestTime || m_lowestTime == 0)
{
std::cout << "Fastest render : " << time << std::endl;
m_lowestTime = time;
}*/
/*
if(m_display->GetInputModule()->IsKeyPressed(Key_W))
{
m_display->GetCameraModule()->MoveCamera(glm::vec3(0.0f, 0.0f, 0.1f));
}
if(m_display->GetInputModule()->IsKeyPressed(Key_S))
{
m_display->GetCameraModule()->MoveCamera(glm::vec3(0.0f, 0.0f, -0.1f));
}
if(m_display->GetInputModule()->IsKeyPressed(Key_A))
{
m_display->GetCameraModule()->MoveCamera(glm::vec3(0.1f, 0.0f, 0.0f));
}
if(m_display->GetInputModule()->IsKeyPressed(Key_D))
{
m_display->GetCameraModule()->MoveCamera(glm::vec3(-0.1f, 0.0f, 0.0f));
}
if(m_display->GetInputModule()->IsKeyPressed(Key_Space))
{
std::cout << "Frame Time: " << std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count() << std::endl;
}
*/
}
void OpenGL::DestroyInstance()
{
m_openGL->Destroy();
m_openGL = nullptr;
}
bool OpenGL::CreateInstance(int width, int height, std::string title)
{
if(m_openGL != nullptr)
{
std::cout << "OpenGL has already been created, destroy first";
return false;
}
m_openGL = std::make_shared<OpenGL>();
if(!m_openGL->InitOpenGL(width, height, title))
{
std::cout << "Couldn't initialize OpenGL project" << std::endl;
return false;
}
return true;
}
std::shared_ptr<OpenGL> OpenGL::getInstance()
{
return m_openGL;
}
<commit_msg>Removed comments<commit_after>//
// Created by nprat on 7/4/16.
//
#include <chrono>
#include <string>
#include "openGL.h"
std::shared_ptr<OpenGL> OpenGL::m_openGL = nullptr;
OpenGL::OpenGL()
{
m_openGL = nullptr;
m_renderChain = nullptr;
m_obj = nullptr;
m_display = nullptr;
m_lowestTime = 0;
}
OpenGL::~OpenGL()
{}
bool OpenGL::InitOpenGL(int width, int height, std::string title)
{
std::cout << "Creating API" << std::endl;
gl::InitAPI();
std::cout << "Finished Creating API" << std::endl;
try
{
m_display = std::make_shared<GlutDisplay>(width, height, title);
m_renderChain = std::make_shared<RenderChain>(10);
m_obj = std::make_shared<TestObject>(m_display);
m_obj2 = std::make_shared<TestObject>(m_display);
}
catch (const char* error)
{
std::cout << "Error: " << error << std::endl;
return false;
}
m_obj->Translate(glm::translate(glm::mat4(1.0f), glm::vec3(0.5f, 0.5f, -0.5f)));
std::cout << "Information: " << std::endl;
std::cout << "\tGL Version: " << glGetString(GL_VERSION) << std::endl;
std::cout << "\tDisplay Address: " << m_display << std::endl;
std::cout << "\tRender Chain Address: " << m_renderChain << std::endl;
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
return true;
}
void OpenGL::Destroy()
{
}
void OpenGL::DisplayFunc()
{
//auto start = std::chrono::high_resolution_clock::now();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_renderChain->AttachRenderObject(m_obj.get());
m_renderChain->AttachRenderObject(m_obj2.get());
m_renderChain->RenderObjectChain();
glutSwapBuffers();
/*auto finish = std::chrono::high_resolution_clock::now();
if(time < m_lowestTime || m_lowestTime == 0)
{
std::cout << "Fastest render : " << time << std::endl;
m_lowestTime = time;
}*/
/*
if(m_display->GetInputModule()->IsKeyPressed(Key_W))
{
m_display->GetCameraModule()->MoveCamera(glm::vec3(0.0f, 0.0f, 0.1f));
}
if(m_display->GetInputModule()->IsKeyPressed(Key_S))
{
m_display->GetCameraModule()->MoveCamera(glm::vec3(0.0f, 0.0f, -0.1f));
}
if(m_display->GetInputModule()->IsKeyPressed(Key_A))
{
m_display->GetCameraModule()->MoveCamera(glm::vec3(0.1f, 0.0f, 0.0f));
}
if(m_display->GetInputModule()->IsKeyPressed(Key_D))
{
m_display->GetCameraModule()->MoveCamera(glm::vec3(-0.1f, 0.0f, 0.0f));
}
if(m_display->GetInputModule()->IsKeyPressed(Key_Space))
{
std::cout << "Frame Time: " << std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count() << std::endl;
}
*/
}
void OpenGL::DestroyInstance()
{
m_openGL->Destroy();
m_openGL = nullptr;
}
bool OpenGL::CreateInstance(int width, int height, std::string title)
{
if(m_openGL != nullptr)
{
std::cout << "OpenGL has already been created, destroy first";
return false;
}
m_openGL = std::make_shared<OpenGL>();
if(!m_openGL->InitOpenGL(width, height, title))
{
std::cout << "Couldn't initialize OpenGL project" << std::endl;
return false;
}
return true;
}
std::shared_ptr<OpenGL> OpenGL::getInstance()
{
return m_openGL;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <ShlObj.h>
#include "Osiris.hpp"
#include "Modules/OsirisModule.hpp"
#include "Modules/OsirisModules.hpp"
#include <Utils/Utils.hpp>
#include <Ausar/Ausar.hpp>
#include <vector>
#include <iterator>
Osiris::Osiris()
{
wchar_t UserPath[MAX_PATH] = { 0 };
SHGetSpecialFolderPathW(nullptr, UserPath, CSIDL_PROFILE, false);
std::wstring LogPath(UserPath);
LogPath += L"\\AppData\\Local\\Packages\\Microsoft.Halo5Forge_8wekyb3d8bbwe\\TempState\\Log.txt";
Util::Log::Instance()->SetFile(LogPath);
LOG << "Osiris" << "---- ";
LOG << '[' << __DATE__ << " : " << __TIME__ << ']' << std::endl;
LOG << "\t-https://github.com/Wunkolo/Osiris\n";
LOG << std::wstring(80, '-') << std::endl;
LOG << std::hex << std::uppercase << std::setfill(L'0')
<< "Process Base: 0x" << Util::Process::Base() << std::endl;
LOG << "Osiris Thread ID: 0x" << Util::Thread::GetCurrentThreadId() << std::endl;
LOG << "Osiris Base: 0x" << Util::Process::GetModuleBase("Osiris.dll") << std::endl;
LOG << "---- Loaded Modules ----" << std::endl;
Util::Process::IterateModules(
[](const char* Name, const char* Path, Util::Pointer Base, size_t Size) -> bool
{
LOG << "0x" << std::hex << Base << " - 0x" << std::hex << Base(Size) << " | " << Path << std::endl;
return true;
}
);
// Push Commands
PushModule<LogModule>("logging");
PushModule<GlobalInfo>("globals");
}
Osiris::~Osiris()
{
}
void Osiris::Tick(const std::chrono::high_resolution_clock::duration &DeltaTime)
{
for( std::pair<std::string, std::shared_ptr<OsirisModule>> Command : Commands )
{
if( Command.second )
{
Command.second->Tick(DeltaTime);
}
}
}
bool Osiris::RunModule(const std::string &Name, const std::vector<std::string> &Arguments)
{
std::map<std::string, std::shared_ptr<OsirisModule>>::iterator CommandIter;
CommandIter = Commands.find(Name);
if( CommandIter != Commands.end() )
{
return CommandIter->second.get()->Execute(Arguments);
}
return false;
}<commit_msg>Changed module iterator to use constant references<commit_after>#include <iostream>
#include <iomanip>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <ShlObj.h>
#include "Osiris.hpp"
#include "Modules/OsirisModule.hpp"
#include "Modules/OsirisModules.hpp"
#include <Utils/Utils.hpp>
#include <Ausar/Ausar.hpp>
#include <vector>
#include <iterator>
Osiris::Osiris()
{
wchar_t UserPath[MAX_PATH] = { 0 };
SHGetSpecialFolderPathW(nullptr, UserPath, CSIDL_PROFILE, false);
std::wstring LogPath(UserPath);
LogPath += L"\\AppData\\Local\\Packages\\Microsoft.Halo5Forge_8wekyb3d8bbwe\\TempState\\Log.txt";
Util::Log::Instance()->SetFile(LogPath);
LOG << "Osiris" << "---- ";
LOG << '[' << __DATE__ << " : " << __TIME__ << ']' << std::endl;
LOG << "\t-https://github.com/Wunkolo/Osiris\n";
LOG << std::wstring(80, '-') << std::endl;
LOG << std::hex << std::uppercase << std::setfill(L'0')
<< "Process Base: 0x" << Util::Process::Base() << std::endl;
LOG << "Osiris Thread ID: 0x" << Util::Thread::GetCurrentThreadId() << std::endl;
LOG << "Osiris Base: 0x" << Util::Process::GetModuleBase("Osiris.dll") << std::endl;
LOG << "---- Loaded Modules ----" << std::endl;
Util::Process::IterateModules(
[](const char* Name, const char* Path, Util::Pointer Base, size_t Size) -> bool
{
LOG << "0x" << std::hex << Base << " - 0x" << std::hex << Base(Size) << " | " << Path << std::endl;
return true;
}
);
// Push Commands
PushModule<LogModule>("logging");
PushModule<GlobalInfo>("globals");
}
Osiris::~Osiris()
{
}
void Osiris::Tick(const std::chrono::high_resolution_clock::duration &DeltaTime)
{
for( const std::pair<std::string, std::shared_ptr<OsirisModule>>& Command : Commands )
{
if( Command.second )
{
Command.second->Tick(DeltaTime);
}
}
}
bool Osiris::RunModule(const std::string &Name, const std::vector<std::string> &Arguments)
{
std::map<std::string, std::shared_ptr<OsirisModule>>::const_iterator CommandIter;
CommandIter = Commands.find(Name);
if( CommandIter != Commands.end() )
{
return CommandIter->second.get()->Execute(Arguments);
}
return false;
}<|endoftext|> |
<commit_before>#ifndef MJOLNIR_POTENTIAL_LOCAL_FLEXIBLE_LOCAL_ANGLE_POTENTIAL_HPP
#define MJOLNIR_POTENTIAL_LOCAL_FLEXIBLE_LOCAL_ANGLE_POTENTIAL_HPP
#include <array>
#include <algorithm>
#include <limits>
#include <cassert>
#include <cmath>
namespace mjolnir
{
template<typename T> class System;
// Flexible Local Angle potential (T. Terakawa and S. Takada Biophys J 2011)
// NOTE: It assumes that each theta value in histogram is same as the default.
// : It requires the unit to be [kcal/mol] & [angstrom]!
//
// Here, the implementation is derived from the original implementation in
// the CGMD package, Cafemol (Kenzaki et al., JCTC 2011).
// As the original implementation does, the first term represents the value of
// energy, and the second term represents the value of the *second* derivative
// of the energy.
template<typename realT>
class FlexibleLocalAnglePotential
{
public:
using real_type = realT;
// TODO: support unit systems
static constexpr real_type max_force = 30.0;
static constexpr real_type min_force = -30.0;
static constexpr std::array<real_type, 10> thetas = {
{1.30900, 1.48353, 1.65806, 1.83260, 2.00713,
2.18166, 2.35619, 2.53073, 2.70526, 2.87979}
};
static constexpr real_type dtheta = (2.87979 - 1.30900) / 9.0;
static constexpr real_type rdtheta = 1.0 / dtheta;
public:
FlexibleLocalAnglePotential(const real_type k,
const std::array<real_type, 10>& ys,
const std::array<real_type, 10>& d2ys)
: min_theta(thetas.front()), max_theta(thetas.back()),
k_(k), ys_(ys), d2ys_(d2ys)
{
// set the range and the parameters from table
// from cafemol3/mloop_flexible_local.F90
real_type th = thetas[0];
const real_type center_th = (max_theta + min_theta) * 0.5;
this->min_theta_ene = spline_interpolate(min_theta);
this->max_theta_ene = spline_interpolate(max_theta - 1e-4);
this->min_energy = min_theta_ene;
while(th < max_theta)
{
const real_type energy = this->spline_interpolate(th);
const real_type force = this->spline_derivative(th);
this->min_energy = std::min(min_energy, energy);
if(force < min_force)
{
this->min_theta = th;
this->min_theta_ene = energy;
}
if(max_force < force && center_th < th && max_theta == thetas.back())
{
this->max_theta = th;
this->max_theta_ene = energy;
}
th += 1e-4;
}
}
~FlexibleLocalAnglePotential() = default;
real_type potential(const real_type th) const noexcept
{
if(th < min_theta)
{
return ((min_force * th + min_theta_ene - min_force * min_theta) -
min_energy) * k_;
}
else if(th >= max_theta)
{
return ((max_force * th + max_theta_ene - max_force * max_theta) -
min_energy) * k_;
}
else
{
return k_ * (this->spline_interpolate(th) - min_energy);
}
}
real_type derivative(const real_type th) const noexcept
{
if (th < min_theta) {return min_force;}
else if(th >= max_theta) {return max_force;}
else {return this->spline_derivative(th) * k_;}
}
template<typename T>
void update(const System<T>&) const noexcept {return;}
static const char* name() noexcept {return "FlexibleLocalAngle";}
real_type k() const noexcept {return k_;}
std::array<real_type, 10> const& y() const noexcept {return ys_;}
std::array<real_type, 10> const& d2y() const noexcept {return d2ys_;}
real_type cutoff() const noexcept // no cutoff exists.
{return std::numeric_limits<real_type>::infinity();}
private:
real_type spline_interpolate(const real_type th) const noexcept
{
constexpr real_type one_over_six = real_type(1.0) / real_type(6.0);
const std::size_t n = std::floor((th - min_theta) * rdtheta);
assert(n < 9);
const real_type a = (thetas[n+1] - th) * rdtheta;
const real_type b = (th - thetas[n ]) * rdtheta;
const real_type e1 = a * ys_[n] + b * ys_[n+1];
const real_type e2 =
((a * a * a - a) * d2ys_[n] + (b * b * b - b) * d2ys_[n+1]) *
dtheta * dtheta * one_over_six;
return e1 + e2;
}
real_type spline_derivative(const real_type th) const noexcept
{
constexpr real_type one_over_six = real_type(1.0) / real_type(6.0);
const std::size_t n = std::floor((th - min_theta) * rdtheta);
assert(n < 9);
const real_type a = (thetas[n+1] - th) * rdtheta;
const real_type b = (th - thetas[n ]) * rdtheta;
const real_type f1 = (ys_[n+1] - ys_[n]) * rdtheta;
const real_type f2 = (
(3 * b * b - 1) * d2ys_[n+1] - (3 * a * a - 1) * d2ys_[n]
) * dtheta * one_over_six;
return f1 + f2;
}
private:
real_type min_energy;
real_type min_theta;
real_type max_theta;
real_type min_theta_ene;
real_type max_theta_ene;
real_type k_;
std::array<real_type, 10> ys_;
std::array<real_type, 10> d2ys_;
};
template<typename realT>
constexpr realT FlexibleLocalAnglePotential<realT>::max_force;
template<typename realT>
constexpr realT FlexibleLocalAnglePotential<realT>::min_force;
template<typename realT>
constexpr realT FlexibleLocalAnglePotential<realT>::dtheta;
template<typename realT>
constexpr realT FlexibleLocalAnglePotential<realT>::rdtheta;
template<typename realT>
constexpr std::array<realT, 10> FlexibleLocalAnglePotential<realT>::thetas;
} // mjolnir
#endif // MJOLNIR_FLEXIBLE_LOCAL_ANGLE_POTENTIAL
<commit_msg>feat: enable to set different theta values<commit_after>#ifndef MJOLNIR_POTENTIAL_LOCAL_FLEXIBLE_LOCAL_ANGLE_POTENTIAL_HPP
#define MJOLNIR_POTENTIAL_LOCAL_FLEXIBLE_LOCAL_ANGLE_POTENTIAL_HPP
#include <array>
#include <algorithm>
#include <limits>
#include <cassert>
#include <cmath>
namespace mjolnir
{
template<typename T> class System;
// Flexible Local Angle potential (T. Terakawa and S. Takada Biophys J 2011)
// NOTE: It assumes that each theta value in histogram is same as the default.
// : It requires the unit to be [kcal/mol] & [angstrom]!
//
// Here, the implementation is derived from the original implementation in
// the CGMD package, Cafemol (Kenzaki et al., JCTC 2011).
// As the original implementation does, the first term represents the value of
// energy, and the second term represents the value of the *second* derivative
// of the energy.
template<typename realT>
class FlexibleLocalAnglePotential
{
public:
using real_type = realT;
// TODO: support unit systems
static constexpr real_type max_force = 30.0;
static constexpr real_type min_force = -30.0;
public:
FlexibleLocalAnglePotential(const real_type k,
const std::array<real_type, 10>& ys,
const std::array<real_type, 10>& d2ys)
: min_theta(1.30900), max_theta(2.87979), k_(k),
dtheta((2.87979 - 1.30900) / 9.0), rdtheta(1.0 / dtheta),
thetas{
{1.30900, 1.48353, 1.65806, 1.83260, 2.00713,
2.18166, 2.35619, 2.53073, 2.70526, 2.87979}
}, ys_(ys), d2ys_(d2ys)
{
// set the range and the parameters from table
// from cafemol3/mloop_flexible_local.F90
real_type th = thetas[0];
const real_type center_th = (max_theta + min_theta) * 0.5;
this->min_theta_ene = spline_interpolate(min_theta);
this->max_theta_ene = spline_interpolate(max_theta - 1e-4);
this->min_energy = min_theta_ene;
while(th < max_theta)
{
const real_type energy = this->spline_interpolate(th);
const real_type force = this->spline_derivative(th);
this->min_energy = std::min(min_energy, energy);
if(force < min_force)
{
this->min_theta = th;
this->min_theta_ene = energy;
}
if(max_force < force && center_th < th && max_theta == thetas.back())
{
this->max_theta = th;
this->max_theta_ene = energy;
}
th += 1e-4;
}
}
~FlexibleLocalAnglePotential() = default;
real_type potential(const real_type th) const noexcept
{
if(th < min_theta)
{
return ((min_force * th + min_theta_ene - min_force * min_theta) -
min_energy) * k_;
}
else if(th >= max_theta)
{
return ((max_force * th + max_theta_ene - max_force * max_theta) -
min_energy) * k_;
}
else
{
return k_ * (this->spline_interpolate(th) - min_energy);
}
}
real_type derivative(const real_type th) const noexcept
{
if (th < min_theta) {return min_force;}
else if(th >= max_theta) {return max_force;}
else {return this->spline_derivative(th) * k_;}
}
template<typename T>
void update(const System<T>&) const noexcept {return;}
static const char* name() noexcept {return "FlexibleLocalAngle";}
real_type k() const noexcept {return k_;}
std::array<real_type, 10> const& y() const noexcept {return ys_;}
std::array<real_type, 10> const& d2y() const noexcept {return d2ys_;}
real_type cutoff() const noexcept // no cutoff exists.
{return std::numeric_limits<real_type>::infinity();}
private:
real_type spline_interpolate(const real_type th) const noexcept
{
constexpr real_type one_over_six = real_type(1.0) / real_type(6.0);
const std::size_t n = std::floor((th - min_theta) * rdtheta);
assert(n < 9);
const real_type a = (thetas[n+1] - th) * rdtheta;
const real_type b = (th - thetas[n ]) * rdtheta;
const real_type e1 = a * ys_[n] + b * ys_[n+1];
const real_type e2 =
((a * a * a - a) * d2ys_[n] + (b * b * b - b) * d2ys_[n+1]) *
dtheta * dtheta * one_over_six;
return e1 + e2;
}
real_type spline_derivative(const real_type th) const noexcept
{
constexpr real_type one_over_six = real_type(1.0) / real_type(6.0);
const std::size_t n = std::floor((th - min_theta) * rdtheta);
assert(n < 9);
const real_type a = (thetas[n+1] - th) * rdtheta;
const real_type b = (th - thetas[n ]) * rdtheta;
const real_type f1 = (ys_[n+1] - ys_[n]) * rdtheta;
const real_type f2 = (
(3 * b * b - 1) * d2ys_[n+1] - (3 * a * a - 1) * d2ys_[n]
) * dtheta * one_over_six;
return f1 + f2;
}
private:
real_type min_energy;
real_type min_theta;
real_type max_theta;
real_type min_theta_ene;
real_type max_theta_ene;
real_type k_, dtheta, rdtheta;
std::array<real_type, 10> thetas;
std::array<real_type, 10> ys_;
std::array<real_type, 10> d2ys_;
};
template<typename realT>
constexpr realT FlexibleLocalAnglePotential<realT>::max_force;
template<typename realT>
constexpr realT FlexibleLocalAnglePotential<realT>::min_force;
} // mjolnir
#endif // MJOLNIR_FLEXIBLE_LOCAL_ANGLE_POTENTIAL
<|endoftext|> |
<commit_before>/* $Id$ */
// Helper macros can be found in this file
// A set of them can be used to connect to proof and execute selectors.
TProof* connectProof(const char* proofServer)
{
TProof* proof = TProof::Open(proofServer);
if (!proof)
{
printf("ERROR: PROOF connection not established.\n");
return 0;
}
// enable the new packetizer
//proof->AddInput(new TNamed("PROOF_Packetizer", "TPacketizerProgressive"));
proof->ClearInput();
return proof;
}
Bool_t prepareQuery(TString libraries, TString packages, Int_t useAliRoot)
{
// if not proof load libraries
if (!gProof)
{
TObjArray* librariesList = libraries.Tokenize(";");
for (Int_t i=0; i<librariesList->GetEntries(); ++i)
{
TObjString* str = dynamic_cast<TObjString*> (librariesList->At(i));
if (!str)
continue;
printf("Loading %s...", str->String().Data());
Int_t result = CheckLoadLibrary(str->String());
if (result < 0)
{
printf("failed\n");
//return kFALSE;
}
else
printf("succeeded\n");
}
}
else
{
if (useAliRoot > 0)
ProofEnableAliRoot(useAliRoot);
TObjArray* packagesList = packages.Tokenize(";");
for (Int_t i=0; i<packagesList->GetEntries(); ++i)
{
TObjString* str = dynamic_cast<TObjString*> (packagesList->At(i));
if (!str)
continue;
/*if (!EnablePackageLocal(str->String()))
{
printf("Loading of package %s locally failed\n", str->String().Data());
return kFALSE;
}*/
if (gProof->UploadPackage(Form("%s.par", str->String().Data())))
{
printf("Uploading of package %s failed\n", str->String().Data());
return kFALSE;
}
if (gProof->EnablePackage(str->String()))
{
printf("Loading of package %s failed\n", str->String().Data());
return kFALSE;
}
}
}
return kTRUE;
}
Int_t executeQuery(TChain* chain, TList* inputList, TString selectorName, const char* option = "", Long64_t entries = TChain::kBigNumber)
{
if (!gProof)
chain->GetUserInfo()->AddAll(inputList);
else
{
for (Int_t i=0; i<inputList->GetEntries(); ++i)
gProof->AddInput(inputList->At(i));
}
TStopwatch timer;
timer.Start();
Long64_t result = -1;
if (gProof)
{
chain->SetProof();
result = chain->Process(selectorName, option, entries);
}
else
result = chain->Process(selectorName, option, entries);
if (result < 0)
printf("ERROR: Executing process failed with %d.\n", result);
timer.Stop();
timer.Print();
return result;
}
void ProofEnableAliRoot(Int_t aliroot)
{
// enables a locally deployed AliRoot in a PROOF cluster
/* executes the following commands on each node:
gSystem->Setenv("ALICE_ROOT", "/home/alicecaf/ALICE/aliroot-head")
gSystem->AddIncludePath("/home/alicecaf/ALICE/aliroot-head/include");
gSystem->SetDynamicPath(Form("%s:%s", gSystem->GetDynamicPath(), "/home/alicecaf/ALICE/aliroot-head/lib/tgt_linux"))
gSystem->Load("libMinuit");
gROOT->Macro("$ALICE_ROOT/macros/loadlibs.C");
*/
const char* location = 0;
const char* target = "tgt_linux";
switch (aliroot)
{
case 1: location = "/home/alicecaf/ALICE/aliroot-v4-04-Release"; break;
case 2: location = "/home/alicecaf/ALICE/aliroot-head"; break;
case 11: location = "/data1/qfiete/aliroot-head"; target = "tgt_linuxx8664gcc"; break;
default: return;
}
gProof->Exec(Form("gSystem->Setenv(\"ALICE_ROOT\", \"%s\")", location), kTRUE);
gProof->AddIncludePath(Form("%s/include", location));
gProof->AddDynamicPath(Form("%s/lib/%s", location, target));
// load all libraries
gProof->Exec("gSystem->Load(\"libMinuit\")");
gProof->Exec("gROOT->Macro(\"$ALICE_ROOT/macros/loadlibs.C\")");
}
Bool_t EnablePackageLocal(const char* package)
{
printf("Enabling package %s locally...\n", package);
TString currentDir(gSystem->pwd());
if (!gSystem->cd(package))
return kFALSE;
gROOT->ProcessLine(".x PROOF-INF/SETUP.C");
gSystem->cd(currentDir);
return kTRUE;
}
Int_t CheckLoadLibrary(const char* library)
{
// checks if a library is already loaded, if not loads the library
if (strlen(gSystem->GetLibraries(Form("%s.so", library), "", kFALSE)) > 0)
return 1;
return gSystem->Load(library);
}
void redeployPackages(const char* proofServer, Bool_t localAliRoot = kTRUE)
{
// deploys PWG0base and PWG0dep (the latter only when localAliRoot is true) that are expected in $ALICE_ROOT
// when localAliRoot is false ESD.par is also deployed
TProof::Reset(proofServer);
TVirtualProof* proof = TProof::Open(proofServer);
proof->ClearPackages();
if (localAliRoot)
ProofEnableAliRoot();
else
{
proof->UploadPackage("$ALICE_ROOT/ESD.par");
proof->EnablePackage("ESD");
}
proof->UploadPackage("$ALICE_ROOT/PWG0base.par");
proof->EnablePackage("PWG0base");
proof->UploadPackage("$ALICE_ROOT/PWG0dep.par");
proof->EnablePackage("PWG0dep");
}
<commit_msg>new aliroot path on CAF<commit_after>/* $Id$ */
// Helper macros can be found in this file
// A set of them can be used to connect to proof and execute selectors.
TProof* connectProof(const char* proofServer)
{
TProof* proof = TProof::Open(proofServer);
if (!proof)
{
printf("ERROR: PROOF connection not established.\n");
return 0;
}
// enable the new packetizer
//proof->AddInput(new TNamed("PROOF_Packetizer", "TPacketizerProgressive"));
proof->ClearInput();
return proof;
}
Bool_t prepareQuery(TString libraries, TString packages, Int_t useAliRoot)
{
// if not proof load libraries
if (!gProof)
{
TObjArray* librariesList = libraries.Tokenize(";");
for (Int_t i=0; i<librariesList->GetEntries(); ++i)
{
TObjString* str = dynamic_cast<TObjString*> (librariesList->At(i));
if (!str)
continue;
printf("Loading %s...", str->String().Data());
Int_t result = CheckLoadLibrary(str->String());
if (result < 0)
{
printf("failed\n");
//return kFALSE;
}
else
printf("succeeded\n");
}
}
else
{
if (useAliRoot > 0)
ProofEnableAliRoot(useAliRoot);
TObjArray* packagesList = packages.Tokenize(";");
for (Int_t i=0; i<packagesList->GetEntries(); ++i)
{
TObjString* str = dynamic_cast<TObjString*> (packagesList->At(i));
if (!str)
continue;
/*if (!EnablePackageLocal(str->String()))
{
printf("Loading of package %s locally failed\n", str->String().Data());
return kFALSE;
}*/
if (gProof->UploadPackage(Form("%s.par", str->String().Data())))
{
printf("Uploading of package %s failed\n", str->String().Data());
return kFALSE;
}
if (gProof->EnablePackage(str->String()))
{
printf("Loading of package %s failed\n", str->String().Data());
return kFALSE;
}
}
}
return kTRUE;
}
Int_t executeQuery(TChain* chain, TList* inputList, TString selectorName, const char* option = "", Long64_t entries = TChain::kBigNumber)
{
if (!gProof)
chain->GetUserInfo()->AddAll(inputList);
else
{
for (Int_t i=0; i<inputList->GetEntries(); ++i)
gProof->AddInput(inputList->At(i));
}
TStopwatch timer;
timer.Start();
Long64_t result = -1;
if (gProof)
{
chain->SetProof();
result = chain->Process(selectorName, option, entries);
}
else
result = chain->Process(selectorName, option, entries);
if (result < 0)
printf("ERROR: Executing process failed with %d.\n", result);
timer.Stop();
timer.Print();
return result;
}
void ProofEnableAliRoot(Int_t aliroot)
{
// enables a locally deployed AliRoot in a PROOF cluster
/* executes the following commands on each node:
gSystem->Setenv("ALICE_ROOT", "/home/alicecaf/ALICE/aliroot-head")
gSystem->AddIncludePath("/home/alicecaf/ALICE/aliroot-head/include");
gSystem->SetDynamicPath(Form("%s:%s", gSystem->GetDynamicPath(), "/home/alicecaf/ALICE/aliroot-head/lib/tgt_linux"))
gSystem->Load("libMinuit");
gROOT->Macro("$ALICE_ROOT/macros/loadlibs.C");
*/
const char* location = 0;
const char* target = "tgt_linux";
switch (aliroot)
{
case 1: location = "/afs/cern.ch/alice/caf/sw/ALICE/v4-04-Release/slc4_ia32_gcc34/aliroot"; break;
default: return;
}
gProof->Exec(Form("gSystem->Setenv(\"ALICE_ROOT\", \"%s\")", location), kTRUE);
gProof->AddIncludePath(Form("%s/include", location));
gProof->AddDynamicPath(Form("%s/lib/%s", location, target));
// load all libraries
gProof->Exec("gSystem->Load(\"libMinuit\")");
gProof->Exec("gROOT->Macro(\"$ALICE_ROOT/macros/loadlibs.C\")");
}
Bool_t EnablePackageLocal(const char* package)
{
printf("Enabling package %s locally...\n", package);
TString currentDir(gSystem->pwd());
if (!gSystem->cd(package))
return kFALSE;
gROOT->ProcessLine(".x PROOF-INF/SETUP.C");
gSystem->cd(currentDir);
return kTRUE;
}
Int_t CheckLoadLibrary(const char* library)
{
// checks if a library is already loaded, if not loads the library
if (strlen(gSystem->GetLibraries(Form("%s.so", library), "", kFALSE)) > 0)
return 1;
return gSystem->Load(library);
}
void redeployPackages(const char* proofServer, Bool_t localAliRoot = kTRUE)
{
// deploys PWG0base and PWG0dep (the latter only when localAliRoot is true) that are expected in $ALICE_ROOT
// when localAliRoot is false ESD.par is also deployed
TProof::Reset(proofServer);
TVirtualProof* proof = TProof::Open(proofServer);
proof->ClearPackages();
if (localAliRoot)
ProofEnableAliRoot();
else
{
proof->UploadPackage("$ALICE_ROOT/ESD.par");
proof->EnablePackage("ESD");
}
proof->UploadPackage("$ALICE_ROOT/PWG0base.par");
proof->EnablePackage("PWG0base");
proof->UploadPackage("$ALICE_ROOT/PWG0dep.par");
proof->EnablePackage("PWG0dep");
}
<|endoftext|> |
<commit_before>#ifndef _SDD_HOM_EVALUATION_HH_
#define _SDD_HOM_EVALUATION_HH_
#include <cassert>
#include <iosfwd>
#include "sdd/hom/context_fwd.hh"
namespace sdd { namespace hom {
/// @cond INTERNAL_DOC
/*-------------------------------------------------------------------------------------------*/
/// @brief Evaluate an homomorphism.
template <typename C>
struct evaluation
{
/// @brief Used by internal::util::variant.
typedef SDD<C> result_type;
template <typename H>
bool
operator()(const H& h, const zero_terminal<C>&, const SDD<C>&, context<C>&)
const noexcept
{
assert(false);
__builtin_unreachable();
}
template <typename H>
SDD<C>
operator()(const H& h, const one_terminal<C>&, const SDD<C>& x, context<C>& cxt)
const
{
return h(cxt, x);
}
/// @brief Dispatch evaluation to the concrete homomorphism.
///
/// Implement a part of the automatic saturation: evaluation is propagated on successors
/// whenever possible.
template <typename H, typename Node>
SDD<C>
operator()(const H& h, const Node& node, const SDD<C>& x, context<C>& cxt)
const
{
if (h.skip(node.variable()))
{
square_union<C, typename Node::valuation_type> su;
su.reserve(node.size());
for (const auto& arc : node)
{
SDD<C> new_successor = h(cxt, arc.successor());
if (not new_successor.empty())
{
su.add(new_successor, arc.valuation());
}
}
return SDD<C>(node.variable(), su(cxt.sdd_context()));
}
else
{
return h(cxt, x);
}
}
};
/*-------------------------------------------------------------------------------------------*/
/// @brief Default traits for homomorphisms.
template <typename T>
struct homomorphism_traits
{
static constexpr bool should_cache = true;
};
/*-------------------------------------------------------------------------------------------*/
/// @brief The evaluation of an homomorphism in the cache.
template <typename C>
struct cached_homomorphism
{
/// @brief Needed by the cache.
typedef SDD<C> result_type;
/// @brief The evaluation context.
context<C>& cxt_;
/// @brief The homomorphism to evaluate.
const homomorphism<C> h_;
/// @brief The homomorphism's operand.
const SDD<C> sdd_;
/// @brief Constructor.
cached_homomorphism(context<C>& cxt, const homomorphism<C>& h, const SDD<C>& s)
: cxt_(cxt)
, h_(h)
, sdd_(s)
{
}
/// @brief Launch the evaluation.
SDD<C>
operator()()
const
{
return apply_binary_visitor(evaluation<C>(), h_->data(), sdd_->data(), sdd_, cxt_);
}
};
/*-------------------------------------------------------------------------------------------*/
/// @related cached_homomorphism
template <typename C>
inline
bool
operator==(const cached_homomorphism<C>& lhs, const cached_homomorphism<C>& rhs)
noexcept
{
return lhs.h_ == rhs.h_ and lhs.sdd_ == rhs.sdd_;
}
/// @related cached_homomorphism
template <typename C>
std::ostream&
operator<<(std::ostream& os, const cached_homomorphism<C>& ch)
{
return os << ch.h_;
}
/*-------------------------------------------------------------------------------------------*/
/// @brief Used by the cache as a filter to know if an homomorphism should be cached.
template <typename C>
struct should_cache
{
/// @brief Needed by variant.
typedef bool result_type;
/// @brief Dispatch to each homomorphism's trait.
template <typename T>
constexpr bool
operator()(const T&)
const noexcept
{
return homomorphism_traits<T>::should_cache;
}
/// @brief Application.
bool
operator()(const cached_homomorphism<C>& ch)
const noexcept
{
return apply_visitor(*this, ch.h_->data());
}
};
/*-------------------------------------------------------------------------------------------*/
}} // namespace sdd::hom
namespace std {
/*-------------------------------------------------------------------------------------------*/
/// @brief Hash specialization for sdd::hom::cached_homomorphism
template <typename C>
struct hash<sdd::hom::cached_homomorphism<C>>
{
std::size_t
operator()(const sdd::hom::cached_homomorphism<C>& op)
const noexcept
{
std::size_t seed = 0;
sdd::internal::util::hash_combine(seed, op.h_);
sdd::internal::util::hash_combine(seed, op.sdd_);
return seed;
}
};
/// @endcond
/*-------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_HOM_EVALUATION_HH_
<commit_msg>Correct propagation when skipping a variable.<commit_after>#ifndef _SDD_HOM_EVALUATION_HH_
#define _SDD_HOM_EVALUATION_HH_
#include <cassert>
#include <iosfwd>
#include "sdd/hom/context_fwd.hh"
namespace sdd { namespace hom {
/// @cond INTERNAL_DOC
/*-------------------------------------------------------------------------------------------*/
/// @brief Evaluate an homomorphism.
template <typename C>
struct evaluation
{
/// @brief Used by internal::util::variant.
typedef SDD<C> result_type;
template <typename H>
bool
operator()( const H& h, const zero_terminal<C>&
, const SDD<C>&, context<C>&, const homomorphism<C>&)
const noexcept
{
assert(false);
__builtin_unreachable();
}
template <typename H>
SDD<C>
operator()( const H& h, const one_terminal<C>&
, const SDD<C>& x, context<C>& cxt, const homomorphism<C>&)
const
{
return h(cxt, x);
}
/// @brief Dispatch evaluation to the concrete homomorphism.
///
/// Implement a part of the automatic saturation: evaluation is propagated on successors
/// whenever possible.
template <typename H, typename Node>
SDD<C>
operator()( const H& h, const Node& node
, const SDD<C>& x, context<C>& cxt, const homomorphism<C>& hom_proxy)
const
{
if (h.skip(node.variable()))
{
square_union<C, typename Node::valuation_type> su;
su.reserve(node.size());
for (const auto& arc : node)
{
SDD<C> new_successor = hom_proxy(cxt, arc.successor());
if (not new_successor.empty())
{
su.add(new_successor, arc.valuation());
}
}
return SDD<C>(node.variable(), su(cxt.sdd_context()));
}
else
{
return h(cxt, x);
}
}
};
/*-------------------------------------------------------------------------------------------*/
/// @brief Default traits for homomorphisms.
template <typename T>
struct homomorphism_traits
{
static constexpr bool should_cache = true;
};
/*-------------------------------------------------------------------------------------------*/
/// @brief The evaluation of an homomorphism in the cache.
template <typename C>
struct cached_homomorphism
{
/// @brief Needed by the cache.
typedef SDD<C> result_type;
/// @brief The evaluation context.
context<C>& cxt_;
/// @brief The homomorphism to evaluate.
const homomorphism<C> h_;
/// @brief The homomorphism's operand.
const SDD<C> sdd_;
/// @brief Constructor.
cached_homomorphism(context<C>& cxt, const homomorphism<C>& h, const SDD<C>& s)
: cxt_(cxt)
, h_(h)
, sdd_(s)
{
}
/// @brief Launch the evaluation.
SDD<C>
operator()()
const
{
return apply_binary_visitor(evaluation<C>(), h_->data(), sdd_->data(), sdd_, cxt_, h_);
}
};
/*-------------------------------------------------------------------------------------------*/
/// @related cached_homomorphism
template <typename C>
inline
bool
operator==(const cached_homomorphism<C>& lhs, const cached_homomorphism<C>& rhs)
noexcept
{
return lhs.h_ == rhs.h_ and lhs.sdd_ == rhs.sdd_;
}
/// @related cached_homomorphism
template <typename C>
std::ostream&
operator<<(std::ostream& os, const cached_homomorphism<C>& ch)
{
return os << ch.h_;
}
/*-------------------------------------------------------------------------------------------*/
/// @brief Used by the cache as a filter to know if an homomorphism should be cached.
template <typename C>
struct should_cache
{
/// @brief Needed by variant.
typedef bool result_type;
/// @brief Dispatch to each homomorphism's trait.
template <typename T>
constexpr bool
operator()(const T&)
const noexcept
{
return homomorphism_traits<T>::should_cache;
}
/// @brief Application.
bool
operator()(const cached_homomorphism<C>& ch)
const noexcept
{
return apply_visitor(*this, ch.h_->data());
}
};
/*-------------------------------------------------------------------------------------------*/
}} // namespace sdd::hom
namespace std {
/*-------------------------------------------------------------------------------------------*/
/// @brief Hash specialization for sdd::hom::cached_homomorphism
template <typename C>
struct hash<sdd::hom::cached_homomorphism<C>>
{
std::size_t
operator()(const sdd::hom::cached_homomorphism<C>& op)
const noexcept
{
std::size_t seed = 0;
sdd::internal::util::hash_combine(seed, op.h_);
sdd::internal::util::hash_combine(seed, op.sdd_);
return seed;
}
};
/// @endcond
/*-------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_HOM_EVALUATION_HH_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ZipPackageSink.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: mtg $ $Date: 2001-11-15 20:28:55 $
*
* 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): Martin Gallwey ([email protected])
*
*
************************************************************************/
#ifndef _ZIP_PACKAGE_SINK_HXX
#define _ZIP_PACKAGE_SINK_HXX
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASINK_HPP_
#include <com/sun/star/io/XActiveDataSink.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
class ZipPackageSink : public ::cppu::WeakImplHelper1
<
com::sun::star::io::XActiveDataSink
>
{
protected:
com::sun::star::uno::Reference < com::sun::star::io::XInputStream > xStream;
public:
ZipPackageSink();
virtual ~ZipPackageSink();
virtual void SAL_CALL setInputStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream( )
throw(::com::sun::star::uno::RuntimeException);
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.218); FILE MERGED 2005/09/05 18:49:15 rt 1.3.218.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ZipPackageSink.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:19:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _ZIP_PACKAGE_SINK_HXX
#define _ZIP_PACKAGE_SINK_HXX
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASINK_HPP_
#include <com/sun/star/io/XActiveDataSink.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
class ZipPackageSink : public ::cppu::WeakImplHelper1
<
com::sun::star::io::XActiveDataSink
>
{
protected:
com::sun::star::uno::Reference < com::sun::star::io::XInputStream > xStream;
public:
ZipPackageSink();
virtual ~ZipPackageSink();
virtual void SAL_CALL setInputStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream( )
throw(::com::sun::star::uno::RuntimeException);
};
#endif
<|endoftext|> |
<commit_before>#include "fastext/FASTex.hpp"
#include <fmo/detector.hpp>
#include <fmo/processing.hpp>
namespace fmo {
const int THRESHOLD = 19;
const bool NON_MAX_SUP = false;
const size_t LEVELS = 6;
const size_t SKIPPED_LEVELS = 1;
const size_t PROCESSED_LEVELS = LEVELS - SKIPPED_LEVELS;
/// Implementation details of class Detector.
struct Detector::Impl {
Impl() : fastText(THRESHOLD, NON_MAX_SUP, cmp::FastFeatureDetectorC::KEY_POINTS_WHITE) {
keypoints.resize(PROCESSED_LEVELS);
debugVis.resize(PROCESSED_LEVELS);
}
void setInput(const Mat& src) {
fmo::pyramid(src, cascade, LEVELS);
cv::Mat noMask;
for (size_t i = 0; i < PROCESSED_LEVELS; i++) {
Image& image = cascade[i + SKIPPED_LEVELS];
auto& imageKeypoints = keypoints[i];
fastText.detect(image.wrap(), imageKeypoints, noMask);
}
}
const std::vector<Image>& getDebugImages() {
for (size_t i = 0; i < PROCESSED_LEVELS; i++) {
Image& image = cascade[i + SKIPPED_LEVELS];
Image& out = debugVis[i];
fmo::convert(image, out, Format::BGR);
// draw keypoints
cv::Mat outMat = out.wrap();
for (auto& keypoint : keypoints[i]) {
cv::Point pt{static_cast<int>(keypoint.pt.x), static_cast<int>(keypoint.pt.y)};
outMat.at<cv::Vec3b>(pt) = cv::Vec3b(0, 0, 255);
}
}
return debugVis;
}
private:
std::vector<Image> cascade;
std::vector<Image> debugVis;
cmp::FASTextGray fastText;
std::vector<std::vector<cmp::FastKeyPoint>> keypoints;
};
Detector::~Detector() = default;
Detector::Detector() : mImpl(new Impl) {}
Detector::Detector(Detector&&) = default;
Detector& Detector::operator=(Detector&&) = default;
void Detector::setInput(const Mat& src) { mImpl->setInput(src); }
const std::vector<Image>& Detector::getDebugImages() { return mImpl->getDebugImages(); }
}
<commit_msg>Tune settings<commit_after>#include "fastext/FASTex.hpp"
#include <fmo/detector.hpp>
#include <fmo/processing.hpp>
namespace fmo {
const int THRESHOLD = 12;
const bool NON_MAX_SUP = true;
const size_t LEVELS = 6;
const size_t SKIPPED_LEVELS = 1;
const size_t PROCESSED_LEVELS = LEVELS - SKIPPED_LEVELS;
/// Implementation details of class Detector.
struct Detector::Impl {
Impl() : fastText(THRESHOLD, NON_MAX_SUP, cmp::FastFeatureDetectorC::KEY_POINTS_WHITE) {
keypoints.resize(PROCESSED_LEVELS);
debugVis.resize(PROCESSED_LEVELS);
}
void setInput(const Mat& src) {
fmo::pyramid(src, cascade, LEVELS);
cv::Mat noMask;
for (size_t i = 0; i < PROCESSED_LEVELS; i++) {
Image& image = cascade[i + SKIPPED_LEVELS];
auto& imageKeypoints = keypoints[i];
fastText.detect(image.wrap(), imageKeypoints, noMask);
}
}
const std::vector<Image>& getDebugImages() {
for (size_t i = 0; i < PROCESSED_LEVELS; i++) {
Image& image = cascade[i + SKIPPED_LEVELS];
Image& out = debugVis[i];
fmo::convert(image, out, Format::BGR);
// draw keypoints
cv::Mat outMat = out.wrap();
for (auto& keypoint : keypoints[i]) {
cv::Point pt{static_cast<int>(keypoint.pt.x), static_cast<int>(keypoint.pt.y)};
outMat.at<cv::Vec3b>(pt) = cv::Vec3b(0, 0, 255);
}
}
return debugVis;
}
private:
std::vector<Image> cascade;
std::vector<Image> debugVis;
cmp::FASTextGray fastText;
std::vector<std::vector<cmp::FastKeyPoint>> keypoints;
};
Detector::~Detector() = default;
Detector::Detector() : mImpl(new Impl) {}
Detector::Detector(Detector&&) = default;
Detector& Detector::operator=(Detector&&) = default;
void Detector::setInput(const Mat& src) { mImpl->setInput(src); }
const std::vector<Image>& Detector::getDebugImages() { return mImpl->getDebugImages(); }
}
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include <algorithm>
#include <array>
#include <cstdint>
#include <fmo/image.hpp>
#include <fstream>
const char* const IM_4x2_FILE = "assets/4x2.png";
const fmo::Image::Dims IM_4X2_DIMS = {4, 2};
const std::array<uint8_t, 24> IM_4x2_BGR = {
0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, // RGBC
0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, // MYKW
};
const std::array<uint8_t, 8> IM_4x2_GRAY = {
0x1D, 0x95, 0x4C, 0xB2, // RGBC gray
0x69, 0xE1, 0x00, 0xFF, // MYKW gray
};
const std::array<uint8_t, 12> IM_4x2_YUV420SP = {
0x1D, 0x95, 0x4C, 0xB2, // RGBC gray
0x69, 0xE1, 0x00, 0xFF, // MYKW gray
0x80, 0x80, 0x80, 0x80, // UVUV gray
};
template <typename Lhs, typename Rhs>
bool exact_match(const Lhs& lhs, const Rhs& rhs) {
auto res = std::mismatch(begin(lhs), end(lhs), begin(rhs), end(rhs));
return res.first == end(lhs) && res.second == end(rhs);
}
template <typename Lhs, typename Rhs>
bool almost_exact_match(const Lhs& lhs, const Rhs& rhs) {
auto res = std::mismatch(begin(lhs), end(lhs), begin(rhs), end(rhs), [](uint8_t l, uint8_t r) {
return (std::max(l, r) - std::min(l, r)) <= 1;
});
return res.first == end(lhs) && res.second == end(rhs);
}
SCENARIO("reading images from files", "[image]") {
WHEN("loading and converting a known image to BGR") {
fmo::Image image{IM_4x2_FILE, fmo::Image::Format::BGR};
THEN("image has correct dimensions") {
REQUIRE(image.dims() == IM_4X2_DIMS);
AND_THEN("image has correct format") {
REQUIRE(image.format() == fmo::Image::Format::BGR);
AND_THEN("image matches hard-coded values") {
REQUIRE(exact_match(image, IM_4x2_BGR));
}
}
}
}
WHEN("loading and converting a known image to GRAY") {
fmo::Image image{IM_4x2_FILE, fmo::Image::Format::GRAY};
THEN("image has correct dimensions") {
REQUIRE(image.dims() == IM_4X2_DIMS);
AND_THEN("image has correct format") {
REQUIRE(image.format() == fmo::Image::Format::GRAY);
AND_THEN("image matches hard-coded values") {
REQUIRE(exact_match(image, IM_4x2_GRAY));
}
}
}
}
WHEN("loading into an unsupported format") {
THEN("constructor throws") {
REQUIRE_THROWS(fmo::Image(IM_4x2_FILE, fmo::Image::Format::UNKNOWN));
}
}
WHEN("the image file doesn't exist") {
THEN("constructor throws") {
REQUIRE_THROWS(fmo::Image("Eh3qUrSOFl", fmo::Image::Format::BGR));
}
}
}
SCENARIO("performing color conversions", "[image]") {
GIVEN("an empty destination image") {
fmo::Image dest{};
GIVEN("a BGR source image") {
fmo::Image src{fmo::Image::Format::BGR, IM_4X2_DIMS, IM_4x2_BGR.data()};
WHEN("converting to GRAY") {
fmo::Image::convert(src, dest, fmo::Image::Format::GRAY);
THEN("result image has correct dimensions") {
REQUIRE(dest.dims() == IM_4X2_DIMS);
AND_THEN("result image has correct format") {
REQUIRE(dest.format() == fmo::Image::Format::GRAY);
AND_THEN("result image matches hard-coded values") {
REQUIRE(almost_exact_match(dest, IM_4x2_GRAY));
}
}
}
}
}
}
}
<commit_msg>Test conversion: GRAY to BGR<commit_after>#include "catch.hpp"
#include <algorithm>
#include <array>
#include <cstdint>
#include <fmo/image.hpp>
#include <fstream>
const char* const IM_4x2_FILE = "assets/4x2.png";
const fmo::Image::Dims IM_4x2_DIMS = {4, 2};
const std::array<uint8_t, 24> IM_4x2_BGR = {
0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, // RGBC
0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, // MYKW
};
const std::array<uint8_t, 8> IM_4x2_GRAY = {
0x1D, 0x95, 0x4C, 0xB2, // RGBC gray
0x69, 0xE1, 0x00, 0xFF, // MYKW gray
};
const std::array<uint8_t, 24> IM_4x2_GRAY_3 = {
0x1D, 0x1D, 0x1D, 0x95, 0x95, 0x95, 0x4C, 0x4C, 0x4C, 0xB2, 0xB2, 0xB2, // RGBC gray 3x
0x69, 0x69, 0x69, 0xE1, 0xE1, 0xE1, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, // MYKW gray 3x
};
const std::array<uint8_t, 12> IM_4x2_YUV420SP = {
0x1D, 0x95, 0x4C, 0xB2, // RGBC gray
0x69, 0xE1, 0x00, 0xFF, // MYKW gray
0x80, 0x80, 0x80, 0x80, // UVUV gray
};
template <typename Lhs, typename Rhs>
bool exact_match(const Lhs& lhs, const Rhs& rhs) {
auto res = std::mismatch(begin(lhs), end(lhs), begin(rhs), end(rhs));
return res.first == end(lhs) && res.second == end(rhs);
}
template <typename Lhs, typename Rhs>
bool almost_exact_match(const Lhs& lhs, const Rhs& rhs) {
auto res = std::mismatch(begin(lhs), end(lhs), begin(rhs), end(rhs), [](uint8_t l, uint8_t r) {
return (std::max(l, r) - std::min(l, r)) <= 1;
});
return res.first == end(lhs) && res.second == end(rhs);
}
SCENARIO("reading images from files", "[image]") {
WHEN("loading and converting a known image to BGR") {
fmo::Image image{IM_4x2_FILE, fmo::Image::Format::BGR};
THEN("image has correct dimensions") {
REQUIRE(image.dims() == IM_4x2_DIMS);
AND_THEN("image has correct format") {
REQUIRE(image.format() == fmo::Image::Format::BGR);
AND_THEN("image matches hard-coded values") {
REQUIRE(exact_match(image, IM_4x2_BGR));
}
}
}
}
WHEN("loading and converting a known image to GRAY") {
fmo::Image image{IM_4x2_FILE, fmo::Image::Format::GRAY};
THEN("image has correct dimensions") {
REQUIRE(image.dims() == IM_4x2_DIMS);
AND_THEN("image has correct format") {
REQUIRE(image.format() == fmo::Image::Format::GRAY);
AND_THEN("image matches hard-coded values") {
REQUIRE(exact_match(image, IM_4x2_GRAY));
}
}
}
}
WHEN("loading into an unsupported format") {
THEN("constructor throws") {
REQUIRE_THROWS(fmo::Image(IM_4x2_FILE, fmo::Image::Format::UNKNOWN));
}
}
WHEN("the image file doesn't exist") {
THEN("constructor throws") {
REQUIRE_THROWS(fmo::Image("Eh3qUrSOFl", fmo::Image::Format::BGR));
}
}
}
SCENARIO("performing color conversions", "[image]") {
GIVEN("an empty destination image") {
fmo::Image dest{};
GIVEN("a BGR source image") {
fmo::Image src{fmo::Image::Format::BGR, IM_4x2_DIMS, IM_4x2_BGR.data()};
WHEN("converting to GRAY") {
fmo::Image::convert(src, dest, fmo::Image::Format::GRAY);
THEN("result image has correct dimensions") {
REQUIRE(dest.dims() == IM_4x2_DIMS);
AND_THEN("result image has correct format") {
REQUIRE(dest.format() == fmo::Image::Format::GRAY);
AND_THEN("result image matches hard-coded values") {
REQUIRE(almost_exact_match(dest, IM_4x2_GRAY));
}
}
}
}
}
GIVEN("a GRAY source image") {
fmo::Image src{fmo::Image::Format::GRAY, IM_4x2_DIMS, IM_4x2_GRAY.data()};
WHEN("converting to BGR") {
fmo::Image::convert(src, dest, fmo::Image::Format::BGR);
THEN("result image has correct dimensions") {
REQUIRE(dest.dims() == IM_4x2_DIMS);
AND_THEN("result image has correct format") {
REQUIRE(dest.format() == fmo::Image::Format::BGR);
AND_THEN("result image matches hard-coded values") {
REQUIRE(exact_match(dest, IM_4x2_GRAY_3));
}
}
}
}
}
}
}
<|endoftext|> |
<commit_before>//===--- Compilation.cpp - Compilation Task Implementation ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/ToolChain.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang::driver;
using namespace clang;
using namespace llvm::opt;
Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
InputArgList *_Args, DerivedArgList *_TranslatedArgs)
: TheDriver(D), DefaultToolChain(_DefaultToolChain),
CudaHostToolChain(&DefaultToolChain), CudaDeviceToolChain(nullptr),
Args(_Args), TranslatedArgs(_TranslatedArgs), Redirects(nullptr),
ForDiagnostics(false) {}
Compilation::~Compilation() {
delete TranslatedArgs;
delete Args;
// Free any derived arg lists.
for (llvm::DenseMap<std::pair<const ToolChain*, const char*>,
DerivedArgList*>::iterator it = TCArgs.begin(),
ie = TCArgs.end(); it != ie; ++it)
if (it->second != TranslatedArgs)
delete it->second;
// Free redirections of stdout/stderr.
if (Redirects) {
delete Redirects[1];
delete Redirects[2];
delete [] Redirects;
}
}
const DerivedArgList &Compilation::getArgsForToolChain(const ToolChain *TC,
const char *BoundArch) {
if (!TC)
TC = &DefaultToolChain;
DerivedArgList *&Entry = TCArgs[std::make_pair(TC, BoundArch)];
if (!Entry) {
Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch);
if (!Entry)
Entry = TranslatedArgs;
}
return *Entry;
}
bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
// FIXME: Why are we trying to remove files that we have not created? For
// example we should only try to remove a temporary assembly file if
// "clang -cc1" succeed in writing it. Was this a workaround for when
// clang was writing directly to a .s file and sometimes leaving it behind
// during a failure?
// FIXME: If this is necessary, we can still try to split
// llvm::sys::fs::remove into a removeFile and a removeDir and avoid the
// duplicated stat from is_regular_file.
// Don't try to remove files which we don't have write access to (but may be
// able to remove), or non-regular files. Underlying tools may have
// intentionally not overwritten them.
if (!llvm::sys::fs::can_write(File) || !llvm::sys::fs::is_regular_file(File))
return true;
if (std::error_code EC = llvm::sys::fs::remove(File)) {
// Failure is only failure if the file exists and is "regular". We checked
// for it being regular before, and llvm::sys::fs::remove ignores ENOENT,
// so we don't need to check again.
if (IssueErrors)
getDriver().Diag(clang::diag::err_drv_unable_to_remove_file)
<< EC.message();
return false;
}
return true;
}
bool Compilation::CleanupFileList(const ArgStringList &Files,
bool IssueErrors) const {
bool Success = true;
for (ArgStringList::const_iterator
it = Files.begin(), ie = Files.end(); it != ie; ++it)
Success &= CleanupFile(*it, IssueErrors);
return Success;
}
bool Compilation::CleanupFileMap(const ArgStringMap &Files,
const JobAction *JA,
bool IssueErrors) const {
bool Success = true;
for (ArgStringMap::const_iterator
it = Files.begin(), ie = Files.end(); it != ie; ++it) {
// If specified, only delete the files associated with the JobAction.
// Otherwise, delete all files in the map.
if (JA && it->first != JA)
continue;
Success &= CleanupFile(it->second, IssueErrors);
}
return Success;
}
int Compilation::ExecuteCommand(const Command &C,
const Command *&FailingCommand) const {
if ((getDriver().CCPrintOptions ||
getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
raw_ostream *OS = &llvm::errs();
// Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
// output stream.
if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
std::error_code EC;
OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename, EC,
llvm::sys::fs::F_Append |
llvm::sys::fs::F_Text);
if (EC) {
getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)
<< EC.message();
FailingCommand = &C;
delete OS;
return 1;
}
}
if (getDriver().CCPrintOptions)
*OS << "[Logging clang options]";
C.Print(*OS, "\n", /*Quote=*/getDriver().CCPrintOptions);
if (OS != &llvm::errs())
delete OS;
}
std::string Error;
bool ExecutionFailed;
int Res = C.Execute(Redirects, &Error, &ExecutionFailed);
if (!Error.empty()) {
assert(Res && "Error string set with 0 result code!");
getDriver().Diag(clang::diag::err_drv_command_failure) << Error;
}
if (Res)
FailingCommand = &C;
return ExecutionFailed ? 1 : Res;
}
void Compilation::ExecuteJobs(
const JobList &Jobs,
SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) const {
for (const auto &Job : Jobs) {
const Command *FailingCommand = nullptr;
if (int Res = ExecuteCommand(Job, FailingCommand)) {
FailingCommands.push_back(std::make_pair(Res, FailingCommand));
// Bail as soon as one command fails, so we don't output duplicate error
// messages if we die on e.g. the same file.
return;
}
}
}
void Compilation::initCompilationForDiagnostics() {
ForDiagnostics = true;
// Free actions and jobs.
Actions.clear();
AllActions.clear();
Jobs.clear();
// Clear temporary/results file lists.
TempFiles.clear();
ResultFiles.clear();
FailureResultFiles.clear();
// Remove any user specified output. Claim any unclaimed arguments, so as
// to avoid emitting warnings about unused args.
OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD,
options::OPT_MMD };
for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
if (TranslatedArgs->hasArg(OutputOpts[i]))
TranslatedArgs->eraseArg(OutputOpts[i]);
}
TranslatedArgs->ClaimAllArgs();
// Redirect stdout/stderr to /dev/null.
Redirects = new const StringRef*[3]();
Redirects[0] = nullptr;
Redirects[1] = new StringRef();
Redirects[2] = new StringRef();
}
StringRef Compilation::getSysRoot() const {
return getDriver().SysRoot;
}
<commit_msg>Revert "Bail on compilation as soon as a job fails."<commit_after>//===--- Compilation.cpp - Compilation Task Implementation ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/ToolChain.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang::driver;
using namespace clang;
using namespace llvm::opt;
Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
InputArgList *_Args, DerivedArgList *_TranslatedArgs)
: TheDriver(D), DefaultToolChain(_DefaultToolChain),
CudaHostToolChain(&DefaultToolChain), CudaDeviceToolChain(nullptr),
Args(_Args), TranslatedArgs(_TranslatedArgs), Redirects(nullptr),
ForDiagnostics(false) {}
Compilation::~Compilation() {
delete TranslatedArgs;
delete Args;
// Free any derived arg lists.
for (llvm::DenseMap<std::pair<const ToolChain*, const char*>,
DerivedArgList*>::iterator it = TCArgs.begin(),
ie = TCArgs.end(); it != ie; ++it)
if (it->second != TranslatedArgs)
delete it->second;
// Free redirections of stdout/stderr.
if (Redirects) {
delete Redirects[1];
delete Redirects[2];
delete [] Redirects;
}
}
const DerivedArgList &Compilation::getArgsForToolChain(const ToolChain *TC,
const char *BoundArch) {
if (!TC)
TC = &DefaultToolChain;
DerivedArgList *&Entry = TCArgs[std::make_pair(TC, BoundArch)];
if (!Entry) {
Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch);
if (!Entry)
Entry = TranslatedArgs;
}
return *Entry;
}
bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
// FIXME: Why are we trying to remove files that we have not created? For
// example we should only try to remove a temporary assembly file if
// "clang -cc1" succeed in writing it. Was this a workaround for when
// clang was writing directly to a .s file and sometimes leaving it behind
// during a failure?
// FIXME: If this is necessary, we can still try to split
// llvm::sys::fs::remove into a removeFile and a removeDir and avoid the
// duplicated stat from is_regular_file.
// Don't try to remove files which we don't have write access to (but may be
// able to remove), or non-regular files. Underlying tools may have
// intentionally not overwritten them.
if (!llvm::sys::fs::can_write(File) || !llvm::sys::fs::is_regular_file(File))
return true;
if (std::error_code EC = llvm::sys::fs::remove(File)) {
// Failure is only failure if the file exists and is "regular". We checked
// for it being regular before, and llvm::sys::fs::remove ignores ENOENT,
// so we don't need to check again.
if (IssueErrors)
getDriver().Diag(clang::diag::err_drv_unable_to_remove_file)
<< EC.message();
return false;
}
return true;
}
bool Compilation::CleanupFileList(const ArgStringList &Files,
bool IssueErrors) const {
bool Success = true;
for (ArgStringList::const_iterator
it = Files.begin(), ie = Files.end(); it != ie; ++it)
Success &= CleanupFile(*it, IssueErrors);
return Success;
}
bool Compilation::CleanupFileMap(const ArgStringMap &Files,
const JobAction *JA,
bool IssueErrors) const {
bool Success = true;
for (ArgStringMap::const_iterator
it = Files.begin(), ie = Files.end(); it != ie; ++it) {
// If specified, only delete the files associated with the JobAction.
// Otherwise, delete all files in the map.
if (JA && it->first != JA)
continue;
Success &= CleanupFile(it->second, IssueErrors);
}
return Success;
}
int Compilation::ExecuteCommand(const Command &C,
const Command *&FailingCommand) const {
if ((getDriver().CCPrintOptions ||
getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
raw_ostream *OS = &llvm::errs();
// Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
// output stream.
if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
std::error_code EC;
OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename, EC,
llvm::sys::fs::F_Append |
llvm::sys::fs::F_Text);
if (EC) {
getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)
<< EC.message();
FailingCommand = &C;
delete OS;
return 1;
}
}
if (getDriver().CCPrintOptions)
*OS << "[Logging clang options]";
C.Print(*OS, "\n", /*Quote=*/getDriver().CCPrintOptions);
if (OS != &llvm::errs())
delete OS;
}
std::string Error;
bool ExecutionFailed;
int Res = C.Execute(Redirects, &Error, &ExecutionFailed);
if (!Error.empty()) {
assert(Res && "Error string set with 0 result code!");
getDriver().Diag(clang::diag::err_drv_command_failure) << Error;
}
if (Res)
FailingCommand = &C;
return ExecutionFailed ? 1 : Res;
}
typedef SmallVectorImpl< std::pair<int, const Command *> > FailingCommandList;
static bool ActionFailed(const Action *A,
const FailingCommandList &FailingCommands) {
if (FailingCommands.empty())
return false;
for (FailingCommandList::const_iterator CI = FailingCommands.begin(),
CE = FailingCommands.end(); CI != CE; ++CI)
if (A == &(CI->second->getSource()))
return true;
for (Action::const_iterator AI = A->begin(), AE = A->end(); AI != AE; ++AI)
if (ActionFailed(*AI, FailingCommands))
return true;
return false;
}
static bool InputsOk(const Command &C,
const FailingCommandList &FailingCommands) {
return !ActionFailed(&C.getSource(), FailingCommands);
}
void Compilation::ExecuteJobs(const JobList &Jobs,
FailingCommandList &FailingCommands) const {
for (const auto &Job : Jobs) {
if (!InputsOk(Job, FailingCommands))
continue;
const Command *FailingCommand = nullptr;
if (int Res = ExecuteCommand(Job, FailingCommand))
FailingCommands.push_back(std::make_pair(Res, FailingCommand));
}
}
void Compilation::initCompilationForDiagnostics() {
ForDiagnostics = true;
// Free actions and jobs.
Actions.clear();
AllActions.clear();
Jobs.clear();
// Clear temporary/results file lists.
TempFiles.clear();
ResultFiles.clear();
FailureResultFiles.clear();
// Remove any user specified output. Claim any unclaimed arguments, so as
// to avoid emitting warnings about unused args.
OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD,
options::OPT_MMD };
for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
if (TranslatedArgs->hasArg(OutputOpts[i]))
TranslatedArgs->eraseArg(OutputOpts[i]);
}
TranslatedArgs->ClaimAllArgs();
// Redirect stdout/stderr to /dev/null.
Redirects = new const StringRef*[3]();
Redirects[0] = nullptr;
Redirects[1] = new StringRef();
Redirects[2] = new StringRef();
}
StringRef Compilation::getSysRoot() const {
return getDriver().SysRoot;
}
<|endoftext|> |
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2007 Alexandr Goncearenco <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "sdfinputstream.h"
#include "subinputstream.h"
#include "kmpsearcher.h"
#include <iostream>
#include <sstream>
#include <cstring>
using namespace std;
using namespace Strigi;
const string SdfInputStream::delimiter("$$$$");
const string SdfInputStream::label("V2000");
SdfInputStream::SdfInputStream(InputStream* input)
: SubStreamProvider(input), substream(0),
entrynumber(0), previousStartOfDelimiter(0) {
m_searcher.setQuery(delimiter);
}
SdfInputStream::~SdfInputStream() {
if (substream && substream != m_entrystream) {
delete substream;
}
}
bool
SdfInputStream::checkHeader(const char* data, int32_t datasize) {
// expect at least 64 bytes
if (datasize < 64) return false;
KmpSearcher searcher;
searcher.setQuery(label);
const char* found = searcher.search(data, datasize);
return found > 0;
}
InputStream*
SdfInputStream::nextEntry() {
if (m_status != Ok) return 0;
m_input->reset(previousStartOfDelimiter);
// read anything that's left over in the previous substream
if (substream) {
substream->reset(0);
const char* dummy;
while (substream->status() == Ok) {
substream->read(dummy, 1, 0);
}
if (substream->status() == Error) {
m_status = Error;
}
if (substream && substream != m_entrystream) {
delete substream;
}
substream = 0;
delete m_entrystream;
m_entrystream = 0;
m_input->reset(previousStartOfDelimiter);
// eat delimiter and following newlines
if (m_input->status() == Ok) {
m_input->read(dummy, 4, 4);
if (strncmp(dummy, delimiter.c_str(), 4) == 0) {
m_input->read(dummy, 1, 1);
while (m_input->status() == Ok &&
(strncmp(dummy, "\n", 1) == 0
|| strncmp(dummy, "\r", 1) == 0)) {
m_input->read(dummy, 1, 1);
}
}
}
}
// make sure it is not a MOL
// we can not check it in checkHeader due to low header size limit
// There is only one way to destinguish between MOL and SD:
// MOL does not have $$$$ delimiter. Return no entries if it is a MOL.
const char* start;
const char* end;
int32_t nread = 0;
int32_t total = 0;
const int64_t pos = m_input->position();
int64_t len=0;
while (m_input->status() == Ok) {
nread = m_input->read(start, 1, 0);
if (nread > 0) {
end = m_searcher.search(start, nread);
if (end) {
len = end - start + total;
break;
}
total += nread;
}
}
if (m_input->status() == Error) {
m_status = Error;
m_entrystream = new SubInputStream(m_input);
return 0;
}
m_input->reset(pos);
if (len > 0) {
// this stream is an SD
substream = new SubInputStream(m_input, len);
previousStartOfDelimiter = m_input->position() + len;
m_entryinfo.type = EntryInfo::File;
m_entryinfo.size = len;
m_entryinfo.filename.assign("Molecule");
entrynumber++;
ostringstream o;
o << entrynumber;
m_entryinfo.filename.append(o.str());
m_entrystream = substream;
return m_entrystream;
} else {
// this stream is a MOL itself, not an SD
m_status = Eof;
m_entrystream = new SubInputStream(m_input);
return 0;
}
}
<commit_msg>Replace tabs with spaces.<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2007 Alexandr Goncearenco <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "sdfinputstream.h"
#include "subinputstream.h"
#include "kmpsearcher.h"
#include <iostream>
#include <sstream>
#include <cstring>
using namespace std;
using namespace Strigi;
const string SdfInputStream::delimiter("$$$$");
const string SdfInputStream::label("V2000");
SdfInputStream::SdfInputStream(InputStream* input)
: SubStreamProvider(input), substream(0),
entrynumber(0), previousStartOfDelimiter(0) {
m_searcher.setQuery(delimiter);
}
SdfInputStream::~SdfInputStream() {
if (substream && substream != m_entrystream) {
delete substream;
}
}
bool
SdfInputStream::checkHeader(const char* data, int32_t datasize) {
// expect at least 64 bytes
if (datasize < 64) return false;
KmpSearcher searcher;
searcher.setQuery(label);
const char* found = searcher.search(data, datasize);
return found > 0;
}
InputStream*
SdfInputStream::nextEntry() {
if (m_status != Ok) return 0;
m_input->reset(previousStartOfDelimiter);
// read anything that's left over in the previous substream
if (substream) {
substream->reset(0);
const char* dummy;
while (substream->status() == Ok) {
substream->read(dummy, 1, 0);
}
if (substream->status() == Error) {
m_status = Error;
}
if (substream && substream != m_entrystream) {
delete substream;
}
substream = 0;
delete m_entrystream;
m_entrystream = 0;
m_input->reset(previousStartOfDelimiter);
// eat delimiter and following newlines
if (m_input->status() == Ok) {
m_input->read(dummy, 4, 4);
if (strncmp(dummy, delimiter.c_str(), 4) == 0) {
m_input->read(dummy, 1, 1);
while (m_input->status() == Ok &&
(strncmp(dummy, "\n", 1) == 0
|| strncmp(dummy, "\r", 1) == 0)) {
m_input->read(dummy, 1, 1);
}
}
}
}
// make sure it is not a MOL
// we can not check it in checkHeader due to low header size limit
// There is only one way to destinguish between MOL and SD:
// MOL does not have $$$$ delimiter. Return no entries if it is a MOL.
const char* start;
const char* end;
int32_t nread = 0;
int32_t total = 0;
const int64_t pos = m_input->position();
int64_t len=0;
while (m_input->status() == Ok) {
nread = m_input->read(start, 1, 0);
if (nread > 0) {
end = m_searcher.search(start, nread);
if (end) {
len = end - start + total;
break;
}
total += nread;
}
}
if (m_input->status() == Error) {
m_status = Error;
m_entrystream = new SubInputStream(m_input);
return 0;
}
m_input->reset(pos);
if (len > 0) {
// this stream is an SD
substream = new SubInputStream(m_input, len);
previousStartOfDelimiter = m_input->position() + len;
m_entryinfo.type = EntryInfo::File;
m_entryinfo.size = len;
m_entryinfo.filename.assign("Molecule");
entrynumber++;
ostringstream o;
o << entrynumber;
m_entryinfo.filename.append(o.str());
m_entrystream = substream;
return m_entrystream;
} else {
// this stream is a MOL itself, not an SD
m_status = Eof;
m_entrystream = new SubInputStream(m_input);
return 0;
}
}
<|endoftext|> |
<commit_before>#include "config.hpp"
#include "handler.hpp"
#include <engine.hpp>
#if WINDOWS
#include <windows/context.hpp>
#endif
using namespace std;
using namespace e_engine;
using namespace OS_NAMESPACE;
#define KDEVELOP 0
#define COLOR 0
#define DO_SHA 0
void hexPrint( std::vector<unsigned char> const &_v ) {
for ( unsigned char const & c : _v )
printf( "%02X ", c );
printf( "\n\n" );
fflush( stdout );
}
// #undef UNIX
// #define UNIX 0
int main( int argc, char **argv ) {
WinData.win.width = 800;
WinData.win.height = 600;
WinData.win.fullscreen = false;
WinData.win.windowName = "Engine Test";
WinData.win.iconName = "ICON is missing";
WinData.win.xlibWindowName = "My icon";
//WinData.win.winType = e_engine::TOOLBAR;
WinData.useAutoOpenGLVersion();
WinData.config.appName = "E Engine";
#if ! KDEVELOP || COLOR
WinData.log.logOUT.colors = FULL;
WinData.log.logERR.colors = FULL;
#else
WinData.log.logOUT.colors = DISABLED;
WinData.log.logERR.colors = DISABLED;
WinData.log.width = 175;
#endif
WinData.log.logOUT.Time = LEFT_FULL;
WinData.log.logOUT.File = RIGHT_FULL;
WinData.log.logERR.Time = LEFT_FULL;
WinData.log.logERR.File = RIGHT_FULL;
WinData.log.logFILE.File = RIGHT_FULL;
WinData.win.restoreOldScreenRes = false;
RandISAAC myRand;
r = 0;
g = 0;
b = 0;
double a = 0;
LOG.devInit();
LOG.startLogLoop();
iLOG "User Name: " ADD SYSTEM.getUserName() END
iLOG "User Login: " ADD SYSTEM.getUserLogin() END
iLOG "Home: " ADD SYSTEM.getUserHomeDirectory() END
iLOG "Main config: " ADD SYSTEM.getMainConfigDirPath() END
iLOG "Log File Path: " ADD SYSTEM.getLogFilePath() END
windows_win32::eContext lec;
lec.createContext();
lec.enableVSync();
while(1) {
glClearColor(r,g,b,a);
glClear(GL_COLOR_BUFFER_BIT);
lec.swapBuffers();
}
iLOG "Credits: " ADD 'B', 'G', "Daniel ( Hitler ) Mensinger" END
B_SLEEP( seconds, 1 );
return EXIT_SUCCESS;
}
// kate: indent-mode cstyle; indent-width 3; replace-tabs on;
<commit_msg>Bug Fix<commit_after>#include "config.hpp"
#include "handler.hpp"
#include <engine.hpp>
#if WINDOWS
#include <windows/context.hpp>
#endif
using namespace std;
using namespace e_engine;
using namespace OS_NAMESPACE;
#define KDEVELOP 0
#define COLOR 0
#define DO_SHA 0
void hexPrint( std::vector<unsigned char> const &_v ) {
for ( unsigned char const & c : _v )
printf( "%02X ", c );
printf( "\n\n" );
fflush( stdout );
}
// #undef UNIX
// #define UNIX 0
int main( int argc, char **argv ) {
WinData.win.width = 800;
WinData.win.height = 600;
WinData.win.fullscreen = false;
WinData.win.windowName = "Engine Test";
WinData.win.iconName = "ICON is missing";
WinData.win.xlibWindowName = "My icon";
//WinData.win.winType = e_engine::TOOLBAR;
WinData.useAutoOpenGLVersion();
WinData.config.appName = "E Engine";
#if ! KDEVELOP || COLOR
WinData.log.logOUT.colors = FULL;
WinData.log.logERR.colors = FULL;
#else
WinData.log.logOUT.colors = DISABLED;
WinData.log.logERR.colors = DISABLED;
WinData.log.width = 175;
#endif
WinData.log.logOUT.Time = LEFT_FULL;
WinData.log.logOUT.File = RIGHT_FULL;
WinData.log.logERR.Time = LEFT_FULL;
WinData.log.logERR.File = RIGHT_FULL;
WinData.log.logFILE.File = RIGHT_FULL;
WinData.win.restoreOldScreenRes = false;
RandISAAC myRand;
r = 0;
g = 0;
b = 0;
double a = 0;
LOG.devInit();
LOG.startLogLoop();
iLOG "User Name: " ADD SYSTEM.getUserName() END
iLOG "User Login: " ADD SYSTEM.getUserLogin() END
iLOG "Home: " ADD SYSTEM.getUserHomeDirectory() END
iLOG "Main config: " ADD SYSTEM.getMainConfigDirPath() END
iLOG "Log File Path: " ADD SYSTEM.getLogFilePath() END
windows_win32::eContext lec;
lec.createContext();
lec.enableVSync();
while(1) {
glClearColor(r,g,b,a);
glClear(GL_COLOR_BUFFER_BIT);
lec.swapBuffers();
}
iLOG "Credits: " ADD 'B', 'G', "Daniel ( GOTT ) Mensinger" END
B_SLEEP( seconds, 1 );
return EXIT_SUCCESS;
}
// kate: indent-mode cstyle; indent-width 3; replace-tabs on;
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <boost/optional.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <iostream>
#include <queue>
using namespace std;
class pool
{
public:
pool(int max_size_ = 10): max_size(max_size_) {};
void push(int el)
{
cout << "\033[1;31m DGDG \033[0m push start\n";
queue_mutex.lock();
if (queue.size() < max_size) {
cout << "queue push\n" << queue.size();
queue.push(el);
wait_sec(1);
}
else {
queue_mutex.unlock();
wait_sec(1);
queue_mutex.lock();
}
queue_mutex.unlock();
};
void pop()
{
cout << "\033[1;31m DGDG \033[0m pop start\n";
queue_mutex.lock();
if (queue.size() > 0) {
cout << "queue pop\n" << queue.size();
queue.pop();
wait_sec(1);
}
else {
queue_mutex.unlock();
wait_sec(1);
queue_mutex.lock();
}
queue_mutex.unlock();
}
private:
void wait_sec(int seconds)
{
cout << "wait\n";
boost::posix_time::seconds work_time(1);
boost::this_thread::sleep(work_time);
}
std::queue<int> queue;
mutable boost::mutex queue_mutex;
mutable boost::mutex push_mutex, pop_mutex;
int max_size;
};
class producer
{
public:
producer(boost::shared_ptr<pool> storage_): storage(storage_) {};
void produce()
{
while (true) {
storage->push(1);
}
}
private:
boost::shared_ptr<pool> storage;
};
class consumer
{
public:
consumer(boost::shared_ptr<pool> storage_) : storage(storage_) {};
void consume()
{
while (true) {
storage->pop();
}
};
private:
boost::shared_ptr<pool> storage;
};
class market
{
public:
market(int producers_number_, int consumers_number_):
storage(new pool),
producers_number(producers_number_),
consumers_number(consumers_number_)
{}
void start_market()
{
producer prod(storage);
consumer cons(storage);
boost::thread prod_thread(&producer::produce, &prod);
boost::thread cons_thread(&consumer::consume, &cons);
cons_thread.join();
prod_thread.join();
};
private:
boost::shared_ptr<pool> storage;
int producers_number;
int consumers_number;
};
void worker_function()
{
boost::posix_time::seconds work_time(3);
std::cout << "worker running" << std::endl;
boost::this_thread::sleep(work_time);
std::cout << "worker finished" << std::endl;
}
TEST(test1, DISABLED_thread_spawn)
{
cout << "start\n";
boost::thread worker_thread(worker_function);
cout << "wait\n";
worker_thread.join();
cout << "stop\n";
}
TEST(test1, producer_consumer)
{
market market_(1, 1);
market_.start_market();
}
<commit_msg>conditon variable use/instead of sleep/<commit_after>#include <gtest/gtest.h>
#include <boost/optional.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/mutex.hpp>
#include <iostream>
#include <queue>
using namespace std;
class pool
{
public:
pool(int max_size_ = 10): max_size(max_size_) {};
void push(int el)
{
cout << "\033[1;31m DGDG \033[0m push start\n";
if (queue.size() < max_size) {
boost::mutex::scoped_lock lock(mtx);
cout << "queue push\n" << queue.size();
queue.push(el);
wait_sec(1);
cond_queue.notify_one();
}
else {
wait_sec(1);
}
};
void pop()
{
cout << "\033[1;31m DGDG \033[0m pop start\n";
boost::mutex::scoped_lock lock(mtx);
if (queue.size() > 0) {
cout << "queue pop\n" << queue.size();
queue.pop();
wait_sec(1);
}
else {
cond_queue.wait(lock);
wait_sec(1);
}
}
private:
void wait_sec(int seconds)
{
cout << "wait\n";
boost::posix_time::seconds work_time(1);
boost::this_thread::sleep(work_time);
}
std::queue<int> queue;
mutable boost::mutex mtx;
mutable boost::condition_variable cond_queue;
int max_size;
};
class producer
{
public:
producer(boost::shared_ptr<pool> storage_): storage(storage_) {};
void produce()
{
while (true) {
storage->push(1);
}
}
private:
boost::shared_ptr<pool> storage;
};
class consumer
{
public:
consumer(boost::shared_ptr<pool> storage_) : storage(storage_) {};
void consume()
{
while (true) {
storage->pop();
}
};
private:
boost::shared_ptr<pool> storage;
};
class market
{
public:
market(int producers_number_, int consumers_number_):
storage(new pool),
producers_number(producers_number_),
consumers_number(consumers_number_)
{}
void start_market()
{
producer prod(storage);
consumer cons(storage);
boost::thread prod_thread(&producer::produce, &prod);
boost::thread cons_thread(&consumer::consume, &cons);
cons_thread.join();
prod_thread.join();
};
private:
boost::shared_ptr<pool> storage;
int producers_number;
int consumers_number;
};
TEST(test1, producer_consumer)
{
market market_(1, 1);
market_.start_market();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/Random.h>
#include <atomic>
#include <unistd.h>
#include <sys/time.h>
#include <random>
#include <array>
#include <glog/logging.h>
#include <folly/File.h>
#include <folly/FileUtil.h>
namespace folly {
namespace {
// Keep it open for the duration of the program
File randomDevice("/dev/urandom");
void readRandomDevice(void* data, size_t size) {
PCHECK(readFull(randomDevice.fd(), data, size) == size);
}
class BufferedRandomDevice {
public:
static constexpr size_t kDefaultBufferSize = 128;
explicit BufferedRandomDevice(size_t bufferSize = kDefaultBufferSize);
void get(void* data, size_t size) {
if (LIKELY(size <= remaining())) {
memcpy(data, ptr_, size);
ptr_ += size;
} else {
getSlow(static_cast<unsigned char*>(data), size);
}
}
private:
void getSlow(unsigned char* data, size_t size);
inline size_t remaining() const {
return buffer_.get() + bufferSize_ - ptr_;
}
const size_t bufferSize_;
std::unique_ptr<unsigned char[]> buffer_;
unsigned char* ptr_;
};
BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize)
: bufferSize_(bufferSize),
buffer_(new unsigned char[bufferSize]),
ptr_(buffer_.get() + bufferSize) { // refill on first use
}
void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) {
DCHECK_GT(size, remaining());
if (size >= bufferSize_) {
// Just read directly.
readRandomDevice(data, size);
return;
}
size_t copied = remaining();
memcpy(data, ptr_, copied);
data += copied;
size -= copied;
// refill
readRandomDevice(buffer_.get(), bufferSize_);
ptr_ = buffer_.get();
memcpy(data, ptr_, size);
ptr_ += size;
}
ThreadLocal<BufferedRandomDevice> bufferedRandomDevice;
} // namespace
void Random::secureRandom(void* data, size_t size) {
bufferedRandomDevice->get(data, size);
}
folly::ThreadLocalPtr<ThreadLocalPRNG::LocalInstancePRNG>
ThreadLocalPRNG::localInstance;
class ThreadLocalPRNG::LocalInstancePRNG {
public:
LocalInstancePRNG() : rng(Random::create()) { }
Random::DefaultGenerator rng;
};
ThreadLocalPRNG::LocalInstancePRNG* ThreadLocalPRNG::initLocal() {
auto ret = new LocalInstancePRNG;
localInstance.reset(ret);
return ret;
}
uint32_t ThreadLocalPRNG::getImpl(LocalInstancePRNG* local) {
return local->rng();
}
}
<commit_msg>Move static global variable randomDevice inside the scope of the function<commit_after>/*
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/Random.h>
#include <atomic>
#include <unistd.h>
#include <sys/time.h>
#include <random>
#include <array>
#include <glog/logging.h>
#include <folly/File.h>
#include <folly/FileUtil.h>
namespace folly {
namespace {
void readRandomDevice(void* data, size_t size) {
// Keep it open for the duration of the program
static File randomDevice("/dev/urandom");
PCHECK(readFull(randomDevice.fd(), data, size) == size);
}
class BufferedRandomDevice {
public:
static constexpr size_t kDefaultBufferSize = 128;
explicit BufferedRandomDevice(size_t bufferSize = kDefaultBufferSize);
void get(void* data, size_t size) {
if (LIKELY(size <= remaining())) {
memcpy(data, ptr_, size);
ptr_ += size;
} else {
getSlow(static_cast<unsigned char*>(data), size);
}
}
private:
void getSlow(unsigned char* data, size_t size);
inline size_t remaining() const {
return buffer_.get() + bufferSize_ - ptr_;
}
const size_t bufferSize_;
std::unique_ptr<unsigned char[]> buffer_;
unsigned char* ptr_;
};
BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize)
: bufferSize_(bufferSize),
buffer_(new unsigned char[bufferSize]),
ptr_(buffer_.get() + bufferSize) { // refill on first use
}
void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) {
DCHECK_GT(size, remaining());
if (size >= bufferSize_) {
// Just read directly.
readRandomDevice(data, size);
return;
}
size_t copied = remaining();
memcpy(data, ptr_, copied);
data += copied;
size -= copied;
// refill
readRandomDevice(buffer_.get(), bufferSize_);
ptr_ = buffer_.get();
memcpy(data, ptr_, size);
ptr_ += size;
}
ThreadLocal<BufferedRandomDevice> bufferedRandomDevice;
} // namespace
void Random::secureRandom(void* data, size_t size) {
bufferedRandomDevice->get(data, size);
}
folly::ThreadLocalPtr<ThreadLocalPRNG::LocalInstancePRNG>
ThreadLocalPRNG::localInstance;
class ThreadLocalPRNG::LocalInstancePRNG {
public:
LocalInstancePRNG() : rng(Random::create()) { }
Random::DefaultGenerator rng;
};
ThreadLocalPRNG::LocalInstancePRNG* ThreadLocalPRNG::initLocal() {
auto ret = new LocalInstancePRNG;
localInstance.reset(ret);
return ret;
}
uint32_t ThreadLocalPRNG::getImpl(LocalInstancePRNG* local) {
return local->rng();
}
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "Input.h"
static std::vector<FoneOSPoint> _points;
void Input::Init()
{
}
void Input::SendTouch(FoneOSPoint point)
{
_points.push_back(point);
}
FoneOSPoint Input::GetTouch()
{
if (_points.size() == 0)
{
return FoneOSPoint();
}
FoneOSPoint ret = _points[0];
Logging::LogMessage(Utils::IntToString(ret.x) + STR("-") + Utils::IntToString(ret.y) + STR("-") + Utils::IntToString(ret.z));
_points.erase(_points.begin());
return ret;
}
<commit_msg>stop logging every point<commit_after>#include "stdafx.h"
#include "Input.h"
static std::vector<FoneOSPoint> _points;
void Input::Init()
{
}
void Input::SendTouch(FoneOSPoint point)
{
_points.push_back(point);
}
FoneOSPoint Input::GetTouch()
{
if (_points.size() == 0)
{
return FoneOSPoint();
}
FoneOSPoint ret = _points[0];
//Logging::LogMessage(Utils::IntToString(ret.x) + STR("-") + Utils::IntToString(ret.y) + STR("-") + Utils::IntToString(ret.z));
_points.erase(_points.begin());
return ret;
}
<|endoftext|> |
<commit_before>#define CATCH_CONFIG_MAIN
#include <random>
#include <catch2/catch.hpp>
#include "delaunay.h"
TEST_CASE("Delaunay triangulation should be able to triangulate 3 points as float", "[DelaunayTest]") {
std::vector<Vector2<float> > points;
points.push_back(Vector2<float>(0.0f, 0.0f));
points.push_back(Vector2<float>(1.0f, 0.0f));
points.push_back(Vector2<float>(0.0f, 1.0f));
Delaunay<float> triangulation;
const std::vector<Triangle<float> > triangles = triangulation.triangulate(points);
REQUIRE(1 == triangles.size());
// const std::vector<Edge<float> > edges = triangulation.getEdges();
}
TEST_CASE( "Delaunay triangulation should be able to triangulate 3 points as double", "[DelaunayTest]" ) {
std::vector<Vector2<double> > points;
points.push_back(Vector2<double>(0.0, 0.0));
points.push_back(Vector2<double>(1.0, 0.0));
points.push_back(Vector2<double>(0.0, 1.0));
Delaunay<double> triangulation;
const std::vector<Triangle<double> > triangles = triangulation.triangulate(points);
REQUIRE(1 == triangles.size());
// const std::vector<Edge<double> > edges = triangulation.getEdges();
}
TEST_CASE("Delaunay triangulation should be able to handle duplicated 3 points as double", "[DelaunayTest]") {
std::vector<Vector2<double> > points;
points.push_back(Vector2<double>(0.0, 0.0));
points.push_back(Vector2<double>(0.0, 0.0));
points.push_back(Vector2<double>(1.0, 0.0));
points.push_back(Vector2<double>(0.0, 1.0));
Delaunay<double> triangulation;
const std::vector<Triangle<double> > triangles = triangulation.triangulate(points);
REQUIRE(1 == triangles.size());
// const std::vector<Edge<double> > edges = triangulation.getEdges();
}
std::default_random_engine eng(std::random_device{}());
TEST_CASE("Delaunay triangulation should be able to handle 10000 points as float", "[DelaunayTest]") {
std::uniform_real_distribution<float> dist(0,
std::numeric_limits<float>::max());
std::vector<Vector2<float> > points(1e4);
for (size_t i=0; i < 1e4; ++i)
{
const float x = dist(eng);
const float y = dist(eng);
points.at(i) = Vector2<float>(x, y);
}
REQUIRE(10000 == points.size());
Delaunay<float> triangulation;
const std::vector<Triangle<float> > triangles = triangulation.triangulate(points);
}
TEST_CASE("Delaunay triangulation should be able to handle 10000 points as double", "[DelaunayTest]") {
std::uniform_real_distribution<double> dist(0,
std::numeric_limits<double>::max());
std::vector<Vector2<double> > points(1e4);
for (size_t i=0; i < 1e4; ++i)
{
const double x = dist(eng);
const double y = dist(eng);
points.at(i) = Vector2<double>(x, y);
}
REQUIRE(10000 == points.size());
Delaunay<double> triangulation;
const std::vector<Triangle<double> > triangles = triangulation.triangulate(points);
}
<commit_msg>tests : fix conversion errors<commit_after>#define CATCH_CONFIG_MAIN
#include <random>
#include <catch2/catch.hpp>
#include "delaunay.h"
TEST_CASE("Delaunay triangulation should be able to triangulate 3 points as float", "[DelaunayTest]") {
std::vector<Vector2<float> > points;
points.push_back(Vector2<float>(0.0f, 0.0f));
points.push_back(Vector2<float>(1.0f, 0.0f));
points.push_back(Vector2<float>(0.0f, 1.0f));
Delaunay<float> triangulation;
const std::vector<Triangle<float> > triangles = triangulation.triangulate(points);
REQUIRE(1 == triangles.size());
// const std::vector<Edge<float> > edges = triangulation.getEdges();
}
TEST_CASE( "Delaunay triangulation should be able to triangulate 3 points as double", "[DelaunayTest]" ) {
std::vector<Vector2<double> > points;
points.push_back(Vector2<double>(0.0, 0.0));
points.push_back(Vector2<double>(1.0, 0.0));
points.push_back(Vector2<double>(0.0, 1.0));
Delaunay<double> triangulation;
const std::vector<Triangle<double> > triangles = triangulation.triangulate(points);
REQUIRE(1 == triangles.size());
// const std::vector<Edge<double> > edges = triangulation.getEdges();
}
TEST_CASE("Delaunay triangulation should be able to handle duplicated 3 points as double", "[DelaunayTest]") {
std::vector<Vector2<double> > points;
points.push_back(Vector2<double>(0.0, 0.0));
points.push_back(Vector2<double>(0.0, 0.0));
points.push_back(Vector2<double>(1.0, 0.0));
points.push_back(Vector2<double>(0.0, 1.0));
Delaunay<double> triangulation;
const std::vector<Triangle<double> > triangles = triangulation.triangulate(points);
REQUIRE(1 == triangles.size());
// const std::vector<Edge<double> > edges = triangulation.getEdges();
}
std::default_random_engine eng(std::random_device{}());
TEST_CASE("Delaunay triangulation should be able to handle 10000 points as float", "[DelaunayTest]") {
std::uniform_real_distribution<float> dist(0,
std::numeric_limits<float>::max());
constexpr size_t nb_pts = 1e4;
std::vector<Vector2<float> > points(nb_pts);
for (size_t i=0; i < nb_pts; ++i)
{
const float x = dist(eng);
const float y = dist(eng);
points.at(i) = Vector2<float>(x, y);
}
REQUIRE(points.size() == nb_pts);
Delaunay<float> triangulation;
const std::vector<Triangle<float> > triangles = triangulation.triangulate(points);
}
TEST_CASE("Delaunay triangulation should be able to handle 10000 points as double", "[DelaunayTest]") {
std::uniform_real_distribution<double> dist(0,
std::numeric_limits<double>::max());
constexpr size_t nb_pts = 1e4;
std::vector<Vector2<double> > points(nb_pts);
for (size_t i=0; i < nb_pts; ++i)
{
const double x = dist(eng);
const double y = dist(eng);
points.at(i) = Vector2<double>(x, y);
}
REQUIRE(points.size() == nb_pts);
Delaunay<double> triangulation;
const std::vector<Triangle<double> > triangles = triangulation.triangulate(points);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xmlsecuritycontext_mscryptimpl.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2005-03-10 18:11:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SAL_CONFIG_H_
#include <sal/config.h>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _XSECURITYENVIRONMENT_MSCRYPTIMPL_HXX_
#include "securityenvironment_mscryptimpl.hxx"
#endif
#ifndef _XMLSECURITYCONTEXT_MSCRYPTIMPL_HXX_
#include "xmlsecuritycontext_mscryptimpl.hxx"
#endif
#ifndef _XMLSTREAMIO_XMLSECIMPL_HXX_
#include "xmlstreamio.hxx"
#endif
#include "xmlsec/xmlsec.h"
#include "xmlsec/keysmngr.h"
#include "xmlsec/crypto.h"
#include "xmlsec/mscrypto/akmngr.h"
using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::lang ;
using ::com::sun::star::lang::XMultiServiceFactory ;
using ::com::sun::star::lang::XSingleServiceFactory ;
using ::rtl::OUString ;
using ::com::sun::star::xml::crypto::XSecurityEnvironment ;
using ::com::sun::star::xml::crypto::XXMLSecurityContext ;
XMLSecurityContext_MSCryptImpl :: XMLSecurityContext_MSCryptImpl( const Reference< XMultiServiceFactory >& aFactory )
://m_pKeysMngr( NULL ) ,
m_xServiceManager( aFactory ),
m_xSecurityEnvironment( NULL )
{
//Init xmlsec library
if( xmlSecInit() < 0 ) {
throw RuntimeException() ;
}
//Init xmlsec crypto engine library
if( xmlSecCryptoInit() < 0 ) {
xmlSecShutdown() ;
throw RuntimeException() ;
}
//Enable external stream handlers
if( xmlEnableStreamInputCallbacks() < 0 ) {
xmlSecCryptoShutdown() ;
xmlSecShutdown() ;
throw RuntimeException() ;
}
}
XMLSecurityContext_MSCryptImpl :: ~XMLSecurityContext_MSCryptImpl() {
xmlDisableStreamInputCallbacks() ;
xmlSecCryptoShutdown() ;
xmlSecShutdown() ;
}
//i39448 : new methods
sal_Int32 SAL_CALL XMLSecurityContext_MSCryptImpl::addSecurityEnvironment(
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment >& aSecurityEnvironment)
throw (::com::sun::star::security::SecurityInfrastructureException, ::com::sun::star::uno::RuntimeException)
{
if( !aSecurityEnvironment.is() )
{
throw RuntimeException() ;
}
m_xSecurityEnvironment = aSecurityEnvironment;
return 0;
}
sal_Int32 SAL_CALL XMLSecurityContext_MSCryptImpl::getSecurityEnvironmentNumber( )
throw (::com::sun::star::uno::RuntimeException)
{
return 1;
}
::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment > SAL_CALL
XMLSecurityContext_MSCryptImpl::getSecurityEnvironmentByIndex( sal_Int32 index )
throw (::com::sun::star::uno::RuntimeException)
{
if (index == 0)
{
return m_xSecurityEnvironment;
}
else
throw RuntimeException() ;
}
::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment > SAL_CALL
XMLSecurityContext_MSCryptImpl::getSecurityEnvironment( )
throw (::com::sun::star::uno::RuntimeException)
{
return m_xSecurityEnvironment;
}
sal_Int32 SAL_CALL XMLSecurityContext_MSCryptImpl::getDefaultSecurityEnvironmentIndex( )
throw (::com::sun::star::uno::RuntimeException)
{
return 0;
}
void SAL_CALL XMLSecurityContext_MSCryptImpl::setDefaultSecurityEnvironmentIndex( sal_Int32 nDefaultEnvIndex )
throw (::com::sun::star::uno::RuntimeException)
{
//dummy
}
#if 0
/* XXMLSecurityContext */
void SAL_CALL XMLSecurityContext_MSCryptImpl :: setSecurityEnvironment( const Reference< XSecurityEnvironment >& aSecurityEnvironment ) throw( com::sun::star::security::SecurityInfrastructureException ) {
HCERTSTORE hkeyStore ;
HCERTSTORE hCertStore ;
HCRYPTKEY symKey ;
HCRYPTKEY pubKey ;
HCRYPTKEY priKey ;
unsigned int i ;
if( !aSecurityEnvironment.is() )
throw RuntimeException() ;
m_xSecurityEnvironment = aSecurityEnvironment ;
//Clear key manager
if( m_pKeysMngr != NULL ) {
xmlSecKeysMngrDestroy( m_pKeysMngr ) ;
m_pKeysMngr = NULL ;
}
//Create key manager
Reference< XUnoTunnel > xEnvTunnel( m_xSecurityEnvironment , UNO_QUERY ) ;
if( !xEnvTunnel.is() ) {
throw RuntimeException() ;
}
SecurityEnvironment_MSCryptImpl* pSecEnv = ( SecurityEnvironment_MSCryptImpl* )xEnvTunnel->getSomething( SecurityEnvironment_MSCryptImpl::getUnoTunnelId() ) ;
if( pSecEnv == NULL )
throw RuntimeException() ;
hkeyStore = pSecEnv->getCryptoSlot() ;
hCertStore = pSecEnv->getCertDb() ;
/*-
* The following lines is based on the of xmlsec-mscrypto crypto engine
*/
m_pKeysMngr = xmlSecMSCryptoAppliedKeysMngrCreate( hkeyStore , hCertStore ) ;
if( m_pKeysMngr == NULL )
throw RuntimeException() ;
/*-
* Adopt symmetric key into keys manager
*/
for( i = 0 ; ( symKey = pSecEnv->getSymKey( i ) ) != NULL ; i ++ ) {
if( xmlSecMSCryptoAppliedKeysMngrSymKeyLoad( m_pKeysMngr, symKey ) < 0 ) {
throw RuntimeException() ;
}
}
/*-
* Adopt asymmetric public key into keys manager
*/
for( i = 0 ; ( pubKey = pSecEnv->getPubKey( i ) ) != NULL ; i ++ ) {
if( xmlSecMSCryptoAppliedKeysMngrPubKeyLoad( m_pKeysMngr, pubKey ) < 0 ) {
throw RuntimeException() ;
}
}
/*-
* Adopt asymmetric private key into keys manager
*/
for( i = 0 ; ( priKey = pSecEnv->getPriKey( i ) ) != NULL ; i ++ ) {
if( xmlSecMSCryptoAppliedKeysMngrPriKeyLoad( m_pKeysMngr, priKey ) < 0 ) {
throw RuntimeException() ;
}
}
/*-
* Adopt system default certificate store.
*/
if( pSecEnv->defaultEnabled() ) {
HCERTSTORE hSystemStore ;
//Add system key store into the keys manager.
hSystemStore = CertOpenSystemStore( 0, "MY" ) ;
if( hSystemStore != NULL ) {
if( xmlSecMSCryptoAppliedKeysMngrAdoptKeyStore( m_pKeysMngr, hSystemStore ) < 0 ) {
CertCloseStore( hSystemStore, CERT_CLOSE_STORE_CHECK_FLAG ) ;
throw RuntimeException() ;
}
}
//Add system root store into the keys manager.
hSystemStore = CertOpenSystemStore( 0, "Root" ) ;
if( hSystemStore != NULL ) {
if( xmlSecMSCryptoAppliedKeysMngrAdoptTrustedStore( m_pKeysMngr, hSystemStore ) < 0 ) {
CertCloseStore( hSystemStore, CERT_CLOSE_STORE_CHECK_FLAG ) ;
throw RuntimeException() ;
}
}
//Add system trusted store into the keys manager.
hSystemStore = CertOpenSystemStore( 0, "Trust" ) ;
if( hSystemStore != NULL ) {
if( xmlSecMSCryptoAppliedKeysMngrAdoptUntrustedStore( m_pKeysMngr, hSystemStore ) < 0 ) {
CertCloseStore( hSystemStore, CERT_CLOSE_STORE_CHECK_FLAG ) ;
throw RuntimeException() ;
}
}
//Add system CA store into the keys manager.
hSystemStore = CertOpenSystemStore( 0, "CA" ) ;
if( hSystemStore != NULL ) {
if( xmlSecMSCryptoAppliedKeysMngrAdoptUntrustedStore( m_pKeysMngr, hSystemStore ) < 0 ) {
CertCloseStore( hSystemStore, CERT_CLOSE_STORE_CHECK_FLAG ) ;
throw RuntimeException() ;
}
}
}
}
/* XXMLSecurityContext */
Reference< XSecurityEnvironment > SAL_CALL XMLSecurityContext_MSCryptImpl :: getSecurityEnvironment()
throw (RuntimeException)
{
return m_xSecurityEnvironment ;
}
#endif
/* XInitialization */
void SAL_CALL XMLSecurityContext_MSCryptImpl :: initialize( const Sequence< Any >& aArguments ) throw( Exception, RuntimeException ) {
// TBD
} ;
/* XServiceInfo */
OUString SAL_CALL XMLSecurityContext_MSCryptImpl :: getImplementationName() throw( RuntimeException ) {
return impl_getImplementationName() ;
}
/* XServiceInfo */
sal_Bool SAL_CALL XMLSecurityContext_MSCryptImpl :: supportsService( const OUString& serviceName) throw( RuntimeException ) {
Sequence< OUString > seqServiceNames = getSupportedServiceNames() ;
const OUString* pArray = seqServiceNames.getConstArray() ;
for( sal_Int32 i = 0 ; i < seqServiceNames.getLength() ; i ++ ) {
if( *( pArray + i ) == serviceName )
return sal_True ;
}
return sal_False ;
}
/* XServiceInfo */
Sequence< OUString > SAL_CALL XMLSecurityContext_MSCryptImpl :: getSupportedServiceNames() throw( RuntimeException ) {
return impl_getSupportedServiceNames() ;
}
//Helper for XServiceInfo
Sequence< OUString > XMLSecurityContext_MSCryptImpl :: impl_getSupportedServiceNames() {
::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ) ;
Sequence< OUString > seqServiceNames( 1 ) ;
seqServiceNames.getArray()[0] = OUString::createFromAscii( "com.sun.star.xml.crypto.XMLSecurityContext" ) ;
return seqServiceNames ;
}
OUString XMLSecurityContext_MSCryptImpl :: impl_getImplementationName() throw( RuntimeException ) {
return OUString::createFromAscii( "com.sun.star.xml.security.bridge.xmlsec.XMLSecurityContext_MSCryptImpl" ) ;
}
//Helper for registry
Reference< XInterface > SAL_CALL XMLSecurityContext_MSCryptImpl :: impl_createInstance( const Reference< XMultiServiceFactory >& aServiceManager ) throw( RuntimeException ) {
return Reference< XInterface >( *new XMLSecurityContext_MSCryptImpl( aServiceManager ) ) ;
}
Reference< XSingleServiceFactory > XMLSecurityContext_MSCryptImpl :: impl_createFactory( const Reference< XMultiServiceFactory >& aServiceManager ) {
//Reference< XSingleServiceFactory > xFactory ;
//xFactory = ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName , impl_createInstance , impl_getSupportedServiceNames ) ;
//return xFactory ;
return ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName() , impl_createInstance , impl_getSupportedServiceNames() ) ;
}
#if 0
/* XUnoTunnel */
sal_Int64 SAL_CALL XMLSecurityContext_MSCryptImpl :: getSomething( const Sequence< sal_Int8 >& aIdentifier )
throw (RuntimeException)
{
if( aIdentifier.getLength() == 16 && 0 == rtl_compareMemory( getUnoTunnelId().getConstArray(), aIdentifier.getConstArray(), 16 ) ) {
return ( sal_Int64 )this ;
}
return 0 ;
}
/* XUnoTunnel extension */
const Sequence< sal_Int8>& XMLSecurityContext_MSCryptImpl :: getUnoTunnelId() {
static Sequence< sal_Int8 >* pSeq = 0 ;
if( !pSeq ) {
::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ) ;
if( !pSeq ) {
static Sequence< sal_Int8> aSeq( 16 ) ;
rtl_createUuid( ( sal_uInt8* )aSeq.getArray() , 0 , sal_True ) ;
pSeq = &aSeq ;
}
}
return *pSeq ;
}
/* XUnoTunnel extension */
XMLSecurityContext_MSCryptImpl* XMLSecurityContext_MSCryptImpl :: getImplementation( const Reference< XInterface > xObj ) {
Reference< XUnoTunnel > xUT( xObj , UNO_QUERY ) ;
if( xUT.is() ) {
return ( XMLSecurityContext_MSCryptImpl* )xUT->getSomething( getUnoTunnelId() ) ;
} else
return NULL ;
}
/* Native methods */
xmlSecKeysMngrPtr XMLSecurityContext_MSCryptImpl :: keysManager() throw( Exception, RuntimeException ) {
return m_pKeysMngr ;
}
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.52); FILE MERGED 2005/09/05 17:01:59 rt 1.2.52.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlsecuritycontext_mscryptimpl.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 17:32:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SAL_CONFIG_H_
#include <sal/config.h>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _XSECURITYENVIRONMENT_MSCRYPTIMPL_HXX_
#include "securityenvironment_mscryptimpl.hxx"
#endif
#ifndef _XMLSECURITYCONTEXT_MSCRYPTIMPL_HXX_
#include "xmlsecuritycontext_mscryptimpl.hxx"
#endif
#ifndef _XMLSTREAMIO_XMLSECIMPL_HXX_
#include "xmlstreamio.hxx"
#endif
#include "xmlsec/xmlsec.h"
#include "xmlsec/keysmngr.h"
#include "xmlsec/crypto.h"
#include "xmlsec/mscrypto/akmngr.h"
using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::lang ;
using ::com::sun::star::lang::XMultiServiceFactory ;
using ::com::sun::star::lang::XSingleServiceFactory ;
using ::rtl::OUString ;
using ::com::sun::star::xml::crypto::XSecurityEnvironment ;
using ::com::sun::star::xml::crypto::XXMLSecurityContext ;
XMLSecurityContext_MSCryptImpl :: XMLSecurityContext_MSCryptImpl( const Reference< XMultiServiceFactory >& aFactory )
://m_pKeysMngr( NULL ) ,
m_xServiceManager( aFactory ),
m_xSecurityEnvironment( NULL )
{
//Init xmlsec library
if( xmlSecInit() < 0 ) {
throw RuntimeException() ;
}
//Init xmlsec crypto engine library
if( xmlSecCryptoInit() < 0 ) {
xmlSecShutdown() ;
throw RuntimeException() ;
}
//Enable external stream handlers
if( xmlEnableStreamInputCallbacks() < 0 ) {
xmlSecCryptoShutdown() ;
xmlSecShutdown() ;
throw RuntimeException() ;
}
}
XMLSecurityContext_MSCryptImpl :: ~XMLSecurityContext_MSCryptImpl() {
xmlDisableStreamInputCallbacks() ;
xmlSecCryptoShutdown() ;
xmlSecShutdown() ;
}
//i39448 : new methods
sal_Int32 SAL_CALL XMLSecurityContext_MSCryptImpl::addSecurityEnvironment(
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment >& aSecurityEnvironment)
throw (::com::sun::star::security::SecurityInfrastructureException, ::com::sun::star::uno::RuntimeException)
{
if( !aSecurityEnvironment.is() )
{
throw RuntimeException() ;
}
m_xSecurityEnvironment = aSecurityEnvironment;
return 0;
}
sal_Int32 SAL_CALL XMLSecurityContext_MSCryptImpl::getSecurityEnvironmentNumber( )
throw (::com::sun::star::uno::RuntimeException)
{
return 1;
}
::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment > SAL_CALL
XMLSecurityContext_MSCryptImpl::getSecurityEnvironmentByIndex( sal_Int32 index )
throw (::com::sun::star::uno::RuntimeException)
{
if (index == 0)
{
return m_xSecurityEnvironment;
}
else
throw RuntimeException() ;
}
::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment > SAL_CALL
XMLSecurityContext_MSCryptImpl::getSecurityEnvironment( )
throw (::com::sun::star::uno::RuntimeException)
{
return m_xSecurityEnvironment;
}
sal_Int32 SAL_CALL XMLSecurityContext_MSCryptImpl::getDefaultSecurityEnvironmentIndex( )
throw (::com::sun::star::uno::RuntimeException)
{
return 0;
}
void SAL_CALL XMLSecurityContext_MSCryptImpl::setDefaultSecurityEnvironmentIndex( sal_Int32 nDefaultEnvIndex )
throw (::com::sun::star::uno::RuntimeException)
{
//dummy
}
#if 0
/* XXMLSecurityContext */
void SAL_CALL XMLSecurityContext_MSCryptImpl :: setSecurityEnvironment( const Reference< XSecurityEnvironment >& aSecurityEnvironment ) throw( com::sun::star::security::SecurityInfrastructureException ) {
HCERTSTORE hkeyStore ;
HCERTSTORE hCertStore ;
HCRYPTKEY symKey ;
HCRYPTKEY pubKey ;
HCRYPTKEY priKey ;
unsigned int i ;
if( !aSecurityEnvironment.is() )
throw RuntimeException() ;
m_xSecurityEnvironment = aSecurityEnvironment ;
//Clear key manager
if( m_pKeysMngr != NULL ) {
xmlSecKeysMngrDestroy( m_pKeysMngr ) ;
m_pKeysMngr = NULL ;
}
//Create key manager
Reference< XUnoTunnel > xEnvTunnel( m_xSecurityEnvironment , UNO_QUERY ) ;
if( !xEnvTunnel.is() ) {
throw RuntimeException() ;
}
SecurityEnvironment_MSCryptImpl* pSecEnv = ( SecurityEnvironment_MSCryptImpl* )xEnvTunnel->getSomething( SecurityEnvironment_MSCryptImpl::getUnoTunnelId() ) ;
if( pSecEnv == NULL )
throw RuntimeException() ;
hkeyStore = pSecEnv->getCryptoSlot() ;
hCertStore = pSecEnv->getCertDb() ;
/*-
* The following lines is based on the of xmlsec-mscrypto crypto engine
*/
m_pKeysMngr = xmlSecMSCryptoAppliedKeysMngrCreate( hkeyStore , hCertStore ) ;
if( m_pKeysMngr == NULL )
throw RuntimeException() ;
/*-
* Adopt symmetric key into keys manager
*/
for( i = 0 ; ( symKey = pSecEnv->getSymKey( i ) ) != NULL ; i ++ ) {
if( xmlSecMSCryptoAppliedKeysMngrSymKeyLoad( m_pKeysMngr, symKey ) < 0 ) {
throw RuntimeException() ;
}
}
/*-
* Adopt asymmetric public key into keys manager
*/
for( i = 0 ; ( pubKey = pSecEnv->getPubKey( i ) ) != NULL ; i ++ ) {
if( xmlSecMSCryptoAppliedKeysMngrPubKeyLoad( m_pKeysMngr, pubKey ) < 0 ) {
throw RuntimeException() ;
}
}
/*-
* Adopt asymmetric private key into keys manager
*/
for( i = 0 ; ( priKey = pSecEnv->getPriKey( i ) ) != NULL ; i ++ ) {
if( xmlSecMSCryptoAppliedKeysMngrPriKeyLoad( m_pKeysMngr, priKey ) < 0 ) {
throw RuntimeException() ;
}
}
/*-
* Adopt system default certificate store.
*/
if( pSecEnv->defaultEnabled() ) {
HCERTSTORE hSystemStore ;
//Add system key store into the keys manager.
hSystemStore = CertOpenSystemStore( 0, "MY" ) ;
if( hSystemStore != NULL ) {
if( xmlSecMSCryptoAppliedKeysMngrAdoptKeyStore( m_pKeysMngr, hSystemStore ) < 0 ) {
CertCloseStore( hSystemStore, CERT_CLOSE_STORE_CHECK_FLAG ) ;
throw RuntimeException() ;
}
}
//Add system root store into the keys manager.
hSystemStore = CertOpenSystemStore( 0, "Root" ) ;
if( hSystemStore != NULL ) {
if( xmlSecMSCryptoAppliedKeysMngrAdoptTrustedStore( m_pKeysMngr, hSystemStore ) < 0 ) {
CertCloseStore( hSystemStore, CERT_CLOSE_STORE_CHECK_FLAG ) ;
throw RuntimeException() ;
}
}
//Add system trusted store into the keys manager.
hSystemStore = CertOpenSystemStore( 0, "Trust" ) ;
if( hSystemStore != NULL ) {
if( xmlSecMSCryptoAppliedKeysMngrAdoptUntrustedStore( m_pKeysMngr, hSystemStore ) < 0 ) {
CertCloseStore( hSystemStore, CERT_CLOSE_STORE_CHECK_FLAG ) ;
throw RuntimeException() ;
}
}
//Add system CA store into the keys manager.
hSystemStore = CertOpenSystemStore( 0, "CA" ) ;
if( hSystemStore != NULL ) {
if( xmlSecMSCryptoAppliedKeysMngrAdoptUntrustedStore( m_pKeysMngr, hSystemStore ) < 0 ) {
CertCloseStore( hSystemStore, CERT_CLOSE_STORE_CHECK_FLAG ) ;
throw RuntimeException() ;
}
}
}
}
/* XXMLSecurityContext */
Reference< XSecurityEnvironment > SAL_CALL XMLSecurityContext_MSCryptImpl :: getSecurityEnvironment()
throw (RuntimeException)
{
return m_xSecurityEnvironment ;
}
#endif
/* XInitialization */
void SAL_CALL XMLSecurityContext_MSCryptImpl :: initialize( const Sequence< Any >& aArguments ) throw( Exception, RuntimeException ) {
// TBD
} ;
/* XServiceInfo */
OUString SAL_CALL XMLSecurityContext_MSCryptImpl :: getImplementationName() throw( RuntimeException ) {
return impl_getImplementationName() ;
}
/* XServiceInfo */
sal_Bool SAL_CALL XMLSecurityContext_MSCryptImpl :: supportsService( const OUString& serviceName) throw( RuntimeException ) {
Sequence< OUString > seqServiceNames = getSupportedServiceNames() ;
const OUString* pArray = seqServiceNames.getConstArray() ;
for( sal_Int32 i = 0 ; i < seqServiceNames.getLength() ; i ++ ) {
if( *( pArray + i ) == serviceName )
return sal_True ;
}
return sal_False ;
}
/* XServiceInfo */
Sequence< OUString > SAL_CALL XMLSecurityContext_MSCryptImpl :: getSupportedServiceNames() throw( RuntimeException ) {
return impl_getSupportedServiceNames() ;
}
//Helper for XServiceInfo
Sequence< OUString > XMLSecurityContext_MSCryptImpl :: impl_getSupportedServiceNames() {
::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ) ;
Sequence< OUString > seqServiceNames( 1 ) ;
seqServiceNames.getArray()[0] = OUString::createFromAscii( "com.sun.star.xml.crypto.XMLSecurityContext" ) ;
return seqServiceNames ;
}
OUString XMLSecurityContext_MSCryptImpl :: impl_getImplementationName() throw( RuntimeException ) {
return OUString::createFromAscii( "com.sun.star.xml.security.bridge.xmlsec.XMLSecurityContext_MSCryptImpl" ) ;
}
//Helper for registry
Reference< XInterface > SAL_CALL XMLSecurityContext_MSCryptImpl :: impl_createInstance( const Reference< XMultiServiceFactory >& aServiceManager ) throw( RuntimeException ) {
return Reference< XInterface >( *new XMLSecurityContext_MSCryptImpl( aServiceManager ) ) ;
}
Reference< XSingleServiceFactory > XMLSecurityContext_MSCryptImpl :: impl_createFactory( const Reference< XMultiServiceFactory >& aServiceManager ) {
//Reference< XSingleServiceFactory > xFactory ;
//xFactory = ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName , impl_createInstance , impl_getSupportedServiceNames ) ;
//return xFactory ;
return ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName() , impl_createInstance , impl_getSupportedServiceNames() ) ;
}
#if 0
/* XUnoTunnel */
sal_Int64 SAL_CALL XMLSecurityContext_MSCryptImpl :: getSomething( const Sequence< sal_Int8 >& aIdentifier )
throw (RuntimeException)
{
if( aIdentifier.getLength() == 16 && 0 == rtl_compareMemory( getUnoTunnelId().getConstArray(), aIdentifier.getConstArray(), 16 ) ) {
return ( sal_Int64 )this ;
}
return 0 ;
}
/* XUnoTunnel extension */
const Sequence< sal_Int8>& XMLSecurityContext_MSCryptImpl :: getUnoTunnelId() {
static Sequence< sal_Int8 >* pSeq = 0 ;
if( !pSeq ) {
::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ) ;
if( !pSeq ) {
static Sequence< sal_Int8> aSeq( 16 ) ;
rtl_createUuid( ( sal_uInt8* )aSeq.getArray() , 0 , sal_True ) ;
pSeq = &aSeq ;
}
}
return *pSeq ;
}
/* XUnoTunnel extension */
XMLSecurityContext_MSCryptImpl* XMLSecurityContext_MSCryptImpl :: getImplementation( const Reference< XInterface > xObj ) {
Reference< XUnoTunnel > xUT( xObj , UNO_QUERY ) ;
if( xUT.is() ) {
return ( XMLSecurityContext_MSCryptImpl* )xUT->getSomething( getUnoTunnelId() ) ;
} else
return NULL ;
}
/* Native methods */
xmlSecKeysMngrPtr XMLSecurityContext_MSCryptImpl :: keysManager() throw( Exception, RuntimeException ) {
return m_pKeysMngr ;
}
#endif
<|endoftext|> |
<commit_before>#ifndef REMAPFUNCBASE_HPP
#define REMAPFUNCBASE_HPP
#include "bridge.h"
#include "FromEvent.hpp"
#include "IOLogWrapper.hpp"
#include "KeyCode.hpp"
#include "ListHookedKeyboard.hpp"
#include "RemapFuncClasses.hpp"
#include "ToEvent.hpp"
namespace org_pqrs_Karabiner {
namespace RemapFunc {
class RemapFuncBase {
public:
RemapFuncBase(unsigned int type) : type_(type), ignorePassThrough_(false) {}
virtual ~RemapFuncBase(void) {}
virtual void add(AddDataType datatype, AddValue newval) = 0;
virtual bool remap(RemapParams& remapParams) { return false; }
virtual bool drop(const Params_KeyboardEventCallBack& params) { return false; }
unsigned int getType(void) const { return type_; }
void setIgnorePassThrough(bool v) { ignorePassThrough_ = v; }
bool getIgnorePassThrough(void) const { return ignorePassThrough_; }
private:
unsigned int type_;
bool ignorePassThrough_;
};
}
}
#endif
<commit_msg>add virtual methods<commit_after>#ifndef REMAPFUNCBASE_HPP
#define REMAPFUNCBASE_HPP
#include "bridge.h"
#include "FromEvent.hpp"
#include "IOLogWrapper.hpp"
#include "KeyCode.hpp"
#include "ListHookedKeyboard.hpp"
#include "RemapFuncClasses.hpp"
#include "ToEvent.hpp"
namespace org_pqrs_Karabiner {
namespace RemapFunc {
class RemapFuncBase {
public:
RemapFuncBase(unsigned int type) : type_(type), ignorePassThrough_(false) {}
virtual ~RemapFuncBase(void) {}
virtual void add(AddDataType datatype, AddValue newval) = 0;
virtual bool remap(RemapParams& remapParams) { return false; }
virtual bool drop(const Params_KeyboardEventCallBack& params) { return false; }
virtual bool remapSimultaneousKeyPresses(bool keyuponly) { return false; }
virtual bool remapSetKeyboardType(KeyboardType& keyboardType) { return false; }
virtual bool remapForceNumLockOn(ListHookedKeyboard::Item* item) { return false; }
unsigned int getType(void) const { return type_; }
void setIgnorePassThrough(bool v) { ignorePassThrough_ = v; }
bool getIgnorePassThrough(void) const { return ignorePassThrough_; }
private:
unsigned int type_;
bool ignorePassThrough_;
};
}
}
#endif
<|endoftext|> |
<commit_before><commit_msg>Final implementation of multiple camera support for operator WebCamera<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2016 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <lz4.h>
#include <zlib.h>
#include <snappy-c.h>
#include "compress.hh"
#include "utils/class_registrator.hh"
const sstring compressor::namespace_prefix = "org.apache.cassandra.io.compress.";
class lz4_processor: public compressor {
public:
using compressor::compressor;
size_t uncompress(const char* input, size_t input_len, char* output,
size_t output_len) const override;
size_t compress(const char* input, size_t input_len, char* output,
size_t output_len) const override;
size_t compress_max_size(size_t input_len) const override;
};
class snappy_processor: public compressor {
public:
using compressor::compressor;
size_t uncompress(const char* input, size_t input_len, char* output,
size_t output_len) const override;
size_t compress(const char* input, size_t input_len, char* output,
size_t output_len) const override;
size_t compress_max_size(size_t input_len) const override;
};
class deflate_processor: public compressor {
public:
using compressor::compressor;
size_t uncompress(const char* input, size_t input_len, char* output,
size_t output_len) const override;
size_t compress(const char* input, size_t input_len, char* output,
size_t output_len) const override;
size_t compress_max_size(size_t input_len) const override;
};
compressor::compressor(sstring name)
: _name(std::move(name))
{}
std::set<sstring> compressor::option_names() const {
return {};
}
std::map<sstring, sstring> compressor::options() const {
return {};
}
shared_ptr<compressor> compressor::create(const sstring& name, const opt_getter& opts) {
if (name.empty()) {
return {};
}
qualified_name qn(namespace_prefix, name);
for (auto& c : { lz4, snappy, deflate }) {
if (c->name() == qn) {
return c;
}
}
return compressor_registry::create(qn, opts);
}
shared_ptr<compressor> compressor::create(const std::map<sstring, sstring>& options) {
auto i = options.find(compression_parameters::SSTABLE_COMPRESSION);
if (i != options.end() && !i->second.empty()) {
return create(i->second, [&options](const sstring& key) -> opt_string {
auto i = options.find(key);
if (i == options.end()) {
return std::experimental::nullopt;
}
return { i->second };
});
}
return {};
}
thread_local const shared_ptr<compressor> compressor::lz4 = make_shared<lz4_processor>(namespace_prefix + "LZ4Compressor");
thread_local const shared_ptr<compressor> compressor::snappy = make_shared<snappy_processor>(namespace_prefix + "SnappyCompressor");
thread_local const shared_ptr<compressor> compressor::deflate = make_shared<deflate_processor>(namespace_prefix + "DeflateCompressor");
const sstring compression_parameters::SSTABLE_COMPRESSION = "sstable_compression";
const sstring compression_parameters::CHUNK_LENGTH_KB = "chunk_length_kb";
const sstring compression_parameters::CRC_CHECK_CHANCE = "crc_check_chance";
compression_parameters::compression_parameters()
: compression_parameters(nullptr)
{}
compression_parameters::~compression_parameters()
{}
compression_parameters::compression_parameters(compressor_ptr c)
: _compressor(std::move(c))
{}
compression_parameters::compression_parameters(const std::map<sstring, sstring>& options) {
_compressor = compressor::create(options);
validate_options(options);
auto chunk_length = options.find(CHUNK_LENGTH_KB);
if (chunk_length != options.end()) {
try {
_chunk_length = std::stoi(chunk_length->second) * 1024;
} catch (const std::exception& e) {
throw exceptions::syntax_exception(sstring("Invalid integer value ") + chunk_length->second + " for " + CHUNK_LENGTH_KB);
}
}
auto crc_chance = options.find(CRC_CHECK_CHANCE);
if (crc_chance != options.end()) {
try {
_crc_check_chance = std::stod(crc_chance->second);
} catch (const std::exception& e) {
throw exceptions::syntax_exception(sstring("Invalid double value ") + crc_chance->second + "for " + CRC_CHECK_CHANCE);
}
}
}
void compression_parameters::validate() {
if (_chunk_length) {
auto chunk_length = _chunk_length.value();
if (chunk_length <= 0) {
throw exceptions::configuration_exception(sstring("Invalid negative or null ") + CHUNK_LENGTH_KB);
}
// _chunk_length must be a power of two
if (chunk_length & (chunk_length - 1)) {
throw exceptions::configuration_exception(sstring(CHUNK_LENGTH_KB) + " must be a power of 2.");
}
}
if (_crc_check_chance && (_crc_check_chance.value() < 0.0 || _crc_check_chance.value() > 1.0)) {
throw exceptions::configuration_exception(sstring(CRC_CHECK_CHANCE) + " must be between 0.0 and 1.0.");
}
}
std::map<sstring, sstring> compression_parameters::get_options() const {
if (!_compressor) {
return std::map<sstring, sstring>();
}
auto opts = _compressor->options();
opts.emplace(compression_parameters::SSTABLE_COMPRESSION, _compressor->name());
if (_chunk_length) {
opts.emplace(sstring(CHUNK_LENGTH_KB), std::to_string(_chunk_length.value() / 1024));
}
if (_crc_check_chance) {
opts.emplace(sstring(CRC_CHECK_CHANCE), std::to_string(_crc_check_chance.value()));
}
return opts;
}
bool compression_parameters::operator==(const compression_parameters& other) const {
return _compressor == other._compressor
&& _chunk_length == other._chunk_length
&& _crc_check_chance == other._crc_check_chance;
}
bool compression_parameters::operator!=(const compression_parameters& other) const {
return !(*this == other);
}
void compression_parameters::validate_options(const std::map<sstring, sstring>& options) {
// currently, there are no options specific to a particular compressor
static std::set<sstring> keywords({
sstring(SSTABLE_COMPRESSION),
sstring(CHUNK_LENGTH_KB),
sstring(CRC_CHECK_CHANCE),
});
std::set<sstring> ckw;
if (_compressor) {
ckw = _compressor->option_names();
}
for (auto&& opt : options) {
if (!keywords.count(opt.first) && !ckw.count(opt.first)) {
throw exceptions::configuration_exception(sprint("Unknown compression option '%s'.", opt.first));
}
}
}
size_t lz4_processor::uncompress(const char* input, size_t input_len,
char* output, size_t output_len) const {
// We use LZ4_decompress_safe(). According to the documentation, the
// function LZ4_decompress_fast() is slightly faster, but maliciously
// crafted compressed data can cause it to overflow the output buffer.
// Theoretically, our compressed data is created by us so is not malicious
// (and accidental corruption is avoided by the compressed-data checksum),
// but let's not take that chance for now, until we've actually measured
// the performance benefit that LZ4_decompress_fast() would bring.
// Cassandra's LZ4Compressor prepends to the chunk its uncompressed length
// in 4 bytes little-endian (!) order. We don't need this information -
// we already know the uncompressed data is at most the given chunk size
// (and usually is exactly that, except in the last chunk). The advance
// knowledge of the uncompressed size could be useful if we used
// LZ4_decompress_fast(), but we prefer LZ4_decompress_safe() anyway...
input += 4;
input_len -= 4;
auto ret = LZ4_decompress_safe(input, output, input_len, output_len);
if (ret < 0) {
throw std::runtime_error("LZ4 uncompression failure");
}
return ret;
}
size_t lz4_processor::compress(const char* input, size_t input_len,
char* output, size_t output_len) const {
if (output_len < LZ4_COMPRESSBOUND(input_len) + 4) {
throw std::runtime_error("LZ4 compression failure: length of output is too small");
}
// Write input_len (32-bit data) to beginning of output in little-endian representation.
output[0] = input_len & 0xFF;
output[1] = (input_len >> 8) & 0xFF;
output[2] = (input_len >> 16) & 0xFF;
output[3] = (input_len >> 24) & 0xFF;
#ifdef HAVE_LZ4_COMPRESS_DEFAULT
auto ret = LZ4_compress_default(input, output + 4, input_len, LZ4_compressBound(input_len));
#else
auto ret = LZ4_compress(input, output + 4, input_len);
#endif
if (ret == 0) {
throw std::runtime_error("LZ4 compression failure: LZ4_compress() failed");
}
return ret + 4;
}
size_t lz4_processor::compress_max_size(size_t input_len) const {
return LZ4_COMPRESSBOUND(input_len) + 4;
}
size_t deflate_processor::uncompress(const char* input,
size_t input_len, char* output, size_t output_len) const {
z_stream zs;
zs.zalloc = Z_NULL;
zs.zfree = Z_NULL;
zs.opaque = Z_NULL;
zs.avail_in = 0;
zs.next_in = Z_NULL;
if (inflateInit(&zs) != Z_OK) {
throw std::runtime_error("deflate uncompression init failure");
}
// yuck, zlib is not const-correct, and also uses unsigned char while we use char :-(
zs.next_in = reinterpret_cast<unsigned char*>(const_cast<char*>(input));
zs.avail_in = input_len;
zs.next_out = reinterpret_cast<unsigned char*>(output);
zs.avail_out = output_len;
auto res = inflate(&zs, Z_FINISH);
inflateEnd(&zs);
if (res == Z_STREAM_END) {
return output_len - zs.avail_out;
} else {
throw std::runtime_error("deflate uncompression failure");
}
}
size_t deflate_processor::compress(const char* input,
size_t input_len, char* output, size_t output_len) const {
z_stream zs;
zs.zalloc = Z_NULL;
zs.zfree = Z_NULL;
zs.opaque = Z_NULL;
zs.avail_in = 0;
zs.next_in = Z_NULL;
if (deflateInit(&zs, Z_DEFAULT_COMPRESSION) != Z_OK) {
throw std::runtime_error("deflate compression init failure");
}
zs.next_in = reinterpret_cast<unsigned char*>(const_cast<char*>(input));
zs.avail_in = input_len;
zs.next_out = reinterpret_cast<unsigned char*>(output);
zs.avail_out = output_len;
auto res = ::deflate(&zs, Z_FINISH);
deflateEnd(&zs);
if (res == Z_STREAM_END) {
return output_len - zs.avail_out;
} else {
throw std::runtime_error("deflate compression failure");
}
}
size_t deflate_processor::compress_max_size(size_t input_len) const {
z_stream zs;
zs.zalloc = Z_NULL;
zs.zfree = Z_NULL;
zs.opaque = Z_NULL;
zs.avail_in = 0;
zs.next_in = Z_NULL;
if (deflateInit(&zs, Z_DEFAULT_COMPRESSION) != Z_OK) {
throw std::runtime_error("deflate compression init failure");
}
auto res = deflateBound(&zs, input_len);
deflateEnd(&zs);
return res;
}
size_t snappy_processor::uncompress(const char* input, size_t input_len,
char* output, size_t output_len) const {
if (snappy_uncompress(input, input_len, output, &output_len)
== SNAPPY_OK) {
return output_len;
} else {
throw std::runtime_error("snappy uncompression failure");
}
}
size_t snappy_processor::compress(const char* input, size_t input_len,
char* output, size_t output_len) const {
auto ret = snappy_compress(input, input_len, output, &output_len);
if (ret != SNAPPY_OK) {
throw std::runtime_error("snappy compression failure: snappy_compress() failed");
}
return output_len;
}
size_t snappy_processor::compress_max_size(size_t input_len) const {
return snappy_max_compressed_length(input_len);
}
<commit_msg>compress: adjust HAVE_LZ4_COMPRESS_DEFAULT macro for new name<commit_after>/*
* Copyright (C) 2016 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <lz4.h>
#include <zlib.h>
#include <snappy-c.h>
#include "compress.hh"
#include "utils/class_registrator.hh"
const sstring compressor::namespace_prefix = "org.apache.cassandra.io.compress.";
class lz4_processor: public compressor {
public:
using compressor::compressor;
size_t uncompress(const char* input, size_t input_len, char* output,
size_t output_len) const override;
size_t compress(const char* input, size_t input_len, char* output,
size_t output_len) const override;
size_t compress_max_size(size_t input_len) const override;
};
class snappy_processor: public compressor {
public:
using compressor::compressor;
size_t uncompress(const char* input, size_t input_len, char* output,
size_t output_len) const override;
size_t compress(const char* input, size_t input_len, char* output,
size_t output_len) const override;
size_t compress_max_size(size_t input_len) const override;
};
class deflate_processor: public compressor {
public:
using compressor::compressor;
size_t uncompress(const char* input, size_t input_len, char* output,
size_t output_len) const override;
size_t compress(const char* input, size_t input_len, char* output,
size_t output_len) const override;
size_t compress_max_size(size_t input_len) const override;
};
compressor::compressor(sstring name)
: _name(std::move(name))
{}
std::set<sstring> compressor::option_names() const {
return {};
}
std::map<sstring, sstring> compressor::options() const {
return {};
}
shared_ptr<compressor> compressor::create(const sstring& name, const opt_getter& opts) {
if (name.empty()) {
return {};
}
qualified_name qn(namespace_prefix, name);
for (auto& c : { lz4, snappy, deflate }) {
if (c->name() == qn) {
return c;
}
}
return compressor_registry::create(qn, opts);
}
shared_ptr<compressor> compressor::create(const std::map<sstring, sstring>& options) {
auto i = options.find(compression_parameters::SSTABLE_COMPRESSION);
if (i != options.end() && !i->second.empty()) {
return create(i->second, [&options](const sstring& key) -> opt_string {
auto i = options.find(key);
if (i == options.end()) {
return std::experimental::nullopt;
}
return { i->second };
});
}
return {};
}
thread_local const shared_ptr<compressor> compressor::lz4 = make_shared<lz4_processor>(namespace_prefix + "LZ4Compressor");
thread_local const shared_ptr<compressor> compressor::snappy = make_shared<snappy_processor>(namespace_prefix + "SnappyCompressor");
thread_local const shared_ptr<compressor> compressor::deflate = make_shared<deflate_processor>(namespace_prefix + "DeflateCompressor");
const sstring compression_parameters::SSTABLE_COMPRESSION = "sstable_compression";
const sstring compression_parameters::CHUNK_LENGTH_KB = "chunk_length_kb";
const sstring compression_parameters::CRC_CHECK_CHANCE = "crc_check_chance";
compression_parameters::compression_parameters()
: compression_parameters(nullptr)
{}
compression_parameters::~compression_parameters()
{}
compression_parameters::compression_parameters(compressor_ptr c)
: _compressor(std::move(c))
{}
compression_parameters::compression_parameters(const std::map<sstring, sstring>& options) {
_compressor = compressor::create(options);
validate_options(options);
auto chunk_length = options.find(CHUNK_LENGTH_KB);
if (chunk_length != options.end()) {
try {
_chunk_length = std::stoi(chunk_length->second) * 1024;
} catch (const std::exception& e) {
throw exceptions::syntax_exception(sstring("Invalid integer value ") + chunk_length->second + " for " + CHUNK_LENGTH_KB);
}
}
auto crc_chance = options.find(CRC_CHECK_CHANCE);
if (crc_chance != options.end()) {
try {
_crc_check_chance = std::stod(crc_chance->second);
} catch (const std::exception& e) {
throw exceptions::syntax_exception(sstring("Invalid double value ") + crc_chance->second + "for " + CRC_CHECK_CHANCE);
}
}
}
void compression_parameters::validate() {
if (_chunk_length) {
auto chunk_length = _chunk_length.value();
if (chunk_length <= 0) {
throw exceptions::configuration_exception(sstring("Invalid negative or null ") + CHUNK_LENGTH_KB);
}
// _chunk_length must be a power of two
if (chunk_length & (chunk_length - 1)) {
throw exceptions::configuration_exception(sstring(CHUNK_LENGTH_KB) + " must be a power of 2.");
}
}
if (_crc_check_chance && (_crc_check_chance.value() < 0.0 || _crc_check_chance.value() > 1.0)) {
throw exceptions::configuration_exception(sstring(CRC_CHECK_CHANCE) + " must be between 0.0 and 1.0.");
}
}
std::map<sstring, sstring> compression_parameters::get_options() const {
if (!_compressor) {
return std::map<sstring, sstring>();
}
auto opts = _compressor->options();
opts.emplace(compression_parameters::SSTABLE_COMPRESSION, _compressor->name());
if (_chunk_length) {
opts.emplace(sstring(CHUNK_LENGTH_KB), std::to_string(_chunk_length.value() / 1024));
}
if (_crc_check_chance) {
opts.emplace(sstring(CRC_CHECK_CHANCE), std::to_string(_crc_check_chance.value()));
}
return opts;
}
bool compression_parameters::operator==(const compression_parameters& other) const {
return _compressor == other._compressor
&& _chunk_length == other._chunk_length
&& _crc_check_chance == other._crc_check_chance;
}
bool compression_parameters::operator!=(const compression_parameters& other) const {
return !(*this == other);
}
void compression_parameters::validate_options(const std::map<sstring, sstring>& options) {
// currently, there are no options specific to a particular compressor
static std::set<sstring> keywords({
sstring(SSTABLE_COMPRESSION),
sstring(CHUNK_LENGTH_KB),
sstring(CRC_CHECK_CHANCE),
});
std::set<sstring> ckw;
if (_compressor) {
ckw = _compressor->option_names();
}
for (auto&& opt : options) {
if (!keywords.count(opt.first) && !ckw.count(opt.first)) {
throw exceptions::configuration_exception(sprint("Unknown compression option '%s'.", opt.first));
}
}
}
size_t lz4_processor::uncompress(const char* input, size_t input_len,
char* output, size_t output_len) const {
// We use LZ4_decompress_safe(). According to the documentation, the
// function LZ4_decompress_fast() is slightly faster, but maliciously
// crafted compressed data can cause it to overflow the output buffer.
// Theoretically, our compressed data is created by us so is not malicious
// (and accidental corruption is avoided by the compressed-data checksum),
// but let's not take that chance for now, until we've actually measured
// the performance benefit that LZ4_decompress_fast() would bring.
// Cassandra's LZ4Compressor prepends to the chunk its uncompressed length
// in 4 bytes little-endian (!) order. We don't need this information -
// we already know the uncompressed data is at most the given chunk size
// (and usually is exactly that, except in the last chunk). The advance
// knowledge of the uncompressed size could be useful if we used
// LZ4_decompress_fast(), but we prefer LZ4_decompress_safe() anyway...
input += 4;
input_len -= 4;
auto ret = LZ4_decompress_safe(input, output, input_len, output_len);
if (ret < 0) {
throw std::runtime_error("LZ4 uncompression failure");
}
return ret;
}
size_t lz4_processor::compress(const char* input, size_t input_len,
char* output, size_t output_len) const {
if (output_len < LZ4_COMPRESSBOUND(input_len) + 4) {
throw std::runtime_error("LZ4 compression failure: length of output is too small");
}
// Write input_len (32-bit data) to beginning of output in little-endian representation.
output[0] = input_len & 0xFF;
output[1] = (input_len >> 8) & 0xFF;
output[2] = (input_len >> 16) & 0xFF;
output[3] = (input_len >> 24) & 0xFF;
#ifdef SEASTAR_HAVE_LZ4_COMPRESS_DEFAULT
auto ret = LZ4_compress_default(input, output + 4, input_len, LZ4_compressBound(input_len));
#else
auto ret = LZ4_compress(input, output + 4, input_len);
#endif
if (ret == 0) {
throw std::runtime_error("LZ4 compression failure: LZ4_compress() failed");
}
return ret + 4;
}
size_t lz4_processor::compress_max_size(size_t input_len) const {
return LZ4_COMPRESSBOUND(input_len) + 4;
}
size_t deflate_processor::uncompress(const char* input,
size_t input_len, char* output, size_t output_len) const {
z_stream zs;
zs.zalloc = Z_NULL;
zs.zfree = Z_NULL;
zs.opaque = Z_NULL;
zs.avail_in = 0;
zs.next_in = Z_NULL;
if (inflateInit(&zs) != Z_OK) {
throw std::runtime_error("deflate uncompression init failure");
}
// yuck, zlib is not const-correct, and also uses unsigned char while we use char :-(
zs.next_in = reinterpret_cast<unsigned char*>(const_cast<char*>(input));
zs.avail_in = input_len;
zs.next_out = reinterpret_cast<unsigned char*>(output);
zs.avail_out = output_len;
auto res = inflate(&zs, Z_FINISH);
inflateEnd(&zs);
if (res == Z_STREAM_END) {
return output_len - zs.avail_out;
} else {
throw std::runtime_error("deflate uncompression failure");
}
}
size_t deflate_processor::compress(const char* input,
size_t input_len, char* output, size_t output_len) const {
z_stream zs;
zs.zalloc = Z_NULL;
zs.zfree = Z_NULL;
zs.opaque = Z_NULL;
zs.avail_in = 0;
zs.next_in = Z_NULL;
if (deflateInit(&zs, Z_DEFAULT_COMPRESSION) != Z_OK) {
throw std::runtime_error("deflate compression init failure");
}
zs.next_in = reinterpret_cast<unsigned char*>(const_cast<char*>(input));
zs.avail_in = input_len;
zs.next_out = reinterpret_cast<unsigned char*>(output);
zs.avail_out = output_len;
auto res = ::deflate(&zs, Z_FINISH);
deflateEnd(&zs);
if (res == Z_STREAM_END) {
return output_len - zs.avail_out;
} else {
throw std::runtime_error("deflate compression failure");
}
}
size_t deflate_processor::compress_max_size(size_t input_len) const {
z_stream zs;
zs.zalloc = Z_NULL;
zs.zfree = Z_NULL;
zs.opaque = Z_NULL;
zs.avail_in = 0;
zs.next_in = Z_NULL;
if (deflateInit(&zs, Z_DEFAULT_COMPRESSION) != Z_OK) {
throw std::runtime_error("deflate compression init failure");
}
auto res = deflateBound(&zs, input_len);
deflateEnd(&zs);
return res;
}
size_t snappy_processor::uncompress(const char* input, size_t input_len,
char* output, size_t output_len) const {
if (snappy_uncompress(input, input_len, output, &output_len)
== SNAPPY_OK) {
return output_len;
} else {
throw std::runtime_error("snappy uncompression failure");
}
}
size_t snappy_processor::compress(const char* input, size_t input_len,
char* output, size_t output_len) const {
auto ret = snappy_compress(input, input_len, output, &output_len);
if (ret != SNAPPY_OK) {
throw std::runtime_error("snappy compression failure: snappy_compress() failed");
}
return output_len;
}
size_t snappy_processor::compress_max_size(size_t input_len) const {
return snappy_max_compressed_length(input_len);
}
<|endoftext|> |
<commit_before>#include "Args.hpp"
#include <QApplication>
#include <QCommandLineParser>
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QStringList>
namespace chatterino {
Args::Args(const QApplication &app)
{
QCommandLineParser parser;
parser.setApplicationDescription("Chatterino 2 Client for Twitch Chat");
parser.addHelpOption();
// Used internally by app to restart after unexpected crashes
QCommandLineOption crashRecoveryOption("crash-recovery");
crashRecoveryOption.setHidden(true);
parser.addOptions({
{{"v", "version"}, "Displays version information."},
crashRecoveryOption,
});
parser.addOption(QCommandLineOption(
{"c", "channels"},
"Joins only supplied channels on startup. Use letters with colons to "
"specify platform. Only twitch channels are supported at the moment.\n"
"If platform isn't specified, default is Twitch.",
"t:channel1;t:channel2;..."));
parser.process(app);
const QStringList args = parser.positionalArguments();
this->shouldRunBrowserExtensionHost =
(args.size() > 0 && (args[0].startsWith("chrome-extension://") ||
args[0].endsWith(".json")));
if (parser.isSet("c"))
{
QJsonArray channelArray;
QStringList channelArgList = parser.value("c").split(";");
for (QString channelArg : channelArgList)
{
// Twitch is default platform
QString platform = "t";
QString channelName = channelArg;
const QRegExp regExp("(.):(.*)");
if (regExp.indexIn(channelArg) != -1)
{
platform = regExp.cap(1);
channelName = regExp.cap(2);
}
// Twitch (default)
if (platform == "t")
{
// TODO: try not to parse JSON
QString channelObjectString =
"{\"splits2\": { \"data\": { \"name\": \"" + channelName +
"\", \"type\": \"twitch\" }, \"type\": \"split\" }}";
channelArray.push_back(
QJsonDocument::fromJson(channelObjectString.toUtf8())
.object());
}
}
if (channelArray.size() > 0)
{
this->dontSaveSettings = true;
this->channelsToJoin = channelArray;
}
}
this->printVersion = parser.isSet("v");
this->crashRecovery = parser.isSet("crash-recovery");
}
static Args *instance = nullptr;
void initArgs(const QApplication &app)
{
instance = new Args(app);
}
const Args &getArgs()
{
assert(instance);
return *instance;
}
} // namespace chatterino
<commit_msg>Do error-handling ourselves in argument parsing.<commit_after>#include "Args.hpp"
#include <QApplication>
#include <QCommandLineParser>
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QStringList>
namespace chatterino {
Args::Args(const QApplication &app)
{
QCommandLineParser parser;
parser.setApplicationDescription("Chatterino 2 Client for Twitch Chat");
parser.addHelpOption();
// Used internally by app to restart after unexpected crashes
QCommandLineOption crashRecoveryOption("crash-recovery");
crashRecoveryOption.setHidden(true);
parser.addOptions({
{{"v", "version"}, "Displays version information."},
crashRecoveryOption,
});
parser.addOption(QCommandLineOption(
{"c", "channels"},
"Joins only supplied channels on startup. Use letters with colons to "
"specify platform. Only twitch channels are supported at the moment.\n"
"If platform isn't specified, default is Twitch.",
"t:channel1;t:channel2;..."));
if (!parser.parse(app.arguments()))
{
qDebug() << "Warning: Unhandled options:"
<< parser.unknownOptionNames();
}
if (parser.isSet("help"))
{
qDebug().noquote() << parser.helpText();
::exit(EXIT_SUCCESS);
}
const QStringList args = parser.positionalArguments();
this->shouldRunBrowserExtensionHost =
(args.size() > 0 && (args[0].startsWith("chrome-extension://") ||
args[0].endsWith(".json")));
if (parser.isSet("c"))
{
QJsonArray channelArray;
QStringList channelArgList = parser.value("c").split(";");
for (QString channelArg : channelArgList)
{
// Twitch is default platform
QString platform = "t";
QString channelName = channelArg;
const QRegExp regExp("(.):(.*)");
if (regExp.indexIn(channelArg) != -1)
{
platform = regExp.cap(1);
channelName = regExp.cap(2);
}
// Twitch (default)
if (platform == "t")
{
// TODO: try not to parse JSON
QString channelObjectString =
"{\"splits2\": { \"data\": { \"name\": \"" + channelName +
"\", \"type\": \"twitch\" }, \"type\": \"split\" }}";
channelArray.push_back(
QJsonDocument::fromJson(channelObjectString.toUtf8())
.object());
}
}
if (channelArray.size() > 0)
{
this->dontSaveSettings = true;
this->channelsToJoin = channelArray;
}
}
this->printVersion = parser.isSet("v");
this->crashRecovery = parser.isSet("crash-recovery");
}
static Args *instance = nullptr;
void initArgs(const QApplication &app)
{
instance = new Args(app);
}
const Args &getArgs()
{
assert(instance);
return *instance;
}
} // namespace chatterino
<|endoftext|> |
<commit_before><commit_msg>fdo#78153 SwTxtFrm::ManipOfst() requires a valid position<commit_after><|endoftext|> |
<commit_before>/*********************************************************************
* thread-sleep: Force Node.js to sleep
*
* Copyright (c) 2015 Forbes Lindesay
* Copyright (c) 2015 Tiancheng "Timothy" Gu
*
* MIT License
********************************************************************/
#include <nan.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <ctime>
#endif
using v8::FunctionTemplate;
using Nan::GetFunction;
using Nan::New;
using Nan::Set;
void SleepSync(const Nan::FunctionCallbackInfo<v8::Value>& info) {
#ifdef _WIN32
// expect a number as the first argument
DWORD millisec = info[0]->Uint32Value();
Sleep(millisec);
#else
// expect a number as the first argument
uint32_t millisec = info[0]->Uint32Value();
struct timespec req;
req.tv_sec = millisec / 1000;
req.tv_nsec = (millisec % 1000) * 1000000L;
nanosleep(&req, (struct timespec *)NULL);
#endif
info.GetReturnValue().Set(millisec);
}
// Expose SleepSync() as sleep() in JS
NAN_MODULE_INIT(InitAll) {
Set(target, New("sleep").ToLocalChecked(),
GetFunction(New<FunctionTemplate>(SleepSync)).ToLocalChecked());
}
NODE_MODULE(thread_sleep, InitAll)
<commit_msg>Fix build on Windows<commit_after>/*********************************************************************
* thread-sleep: Force Node.js to sleep
*
* Copyright (c) 2015 Forbes Lindesay
* Copyright (c) 2015 Tiancheng "Timothy" Gu
*
* MIT License
********************************************************************/
#include <nan.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <ctime>
#endif
using v8::FunctionTemplate;
using Nan::GetFunction;
using Nan::New;
using Nan::Set;
void SleepSync(const Nan::FunctionCallbackInfo<v8::Value>& info) {
// expect a number as the first argument
uint32_t millisec = info[0]->Uint32Value();
#ifdef _WIN32
Sleep(millisec);
#else
struct timespec req;
req.tv_sec = millisec / 1000;
req.tv_nsec = (millisec % 1000) * 1000000L;
nanosleep(&req, (struct timespec *)NULL);
#endif
info.GetReturnValue().Set(millisec);
}
// Expose SleepSync() as sleep() in JS
NAN_MODULE_INIT(InitAll) {
Set(target, New("sleep").ToLocalChecked(),
GetFunction(New<FunctionTemplate>(SleepSync)).ToLocalChecked());
}
NODE_MODULE(thread_sleep, InitAll)
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/ref_counted.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
class RenderViewHostManagerTest : public InProcessBrowserTest {
public:
RenderViewHostManagerTest() {
EnableDOMAutomation();
}
};
// Test for crbug.com/24447. Following a cross-site link with rel=noreferrer
// and target=_blank should create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
SwapProcessWithRelNoreferrerAndTargetBlank) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server_(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server_.Start());
// Load a page with links that open in a new window.
ui_test_utils::NavigateToURL(browser(), test_server()->GetURL(
"files/click-noreferrer-links.html"));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a rel=noreferrer + target=blank link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickNoRefTargetBlankLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition to finish.
ui_test_utils::WaitForLoadStop(
&(browser()->GetSelectedTabContents()->controller()));
// Opens in new tab.
EXPECT_EQ(2, browser()->tab_count());
EXPECT_EQ(1, browser()->selected_index());
EXPECT_EQ(L"Title Of Awesomeness",
browser()->GetSelectedTabContents()->GetTitle());
// Should have a new SiteInstance.
scoped_refptr<SiteInstance> noref_blank_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_NE(orig_site_instance, noref_blank_site_instance);
}
// Test for crbug.com/24447. Following a cross-site link with just
// target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DontSwapProcessWithOnlyTargetBlank) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server_(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server_.Start());
// Load a page with links that open in a new window.
ui_test_utils::NavigateToURL(browser(), test_server()->GetURL(
"files/click-noreferrer-links.html"));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a target=blank link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickTargetBlankLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition to finish.
ui_test_utils::WaitForLoadStop(
&(browser()->GetSelectedTabContents()->controller()));
// Opens in new tab.
EXPECT_EQ(2, browser()->tab_count());
EXPECT_EQ(1, browser()->selected_index());
EXPECT_EQ(L"Title Of Awesomeness",
browser()->GetSelectedTabContents()->GetTitle());
// Should have the same SiteInstance.
scoped_refptr<SiteInstance> blank_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, blank_site_instance);
}
// Test for crbug.com/24447. Following a cross-site link with rel=noreferrer
// and no target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DontSwapProcessWithOnlyRelNoreferrer) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server_(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server_.Start());
// Load a page with links that open in a new window.
ui_test_utils::NavigateToURL(browser(), test_server()->GetURL(
"files/click-noreferrer-links.html"));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a rel=noreferrer link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickNoRefLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition to finish.
ui_test_utils::WaitForLoadStop(
&(browser()->GetSelectedTabContents()->controller()));
// Opens in same tab.
EXPECT_EQ(1, browser()->tab_count());
EXPECT_EQ(0, browser()->selected_index());
EXPECT_EQ(L"Title Of Awesomeness",
browser()->GetSelectedTabContents()->GetTitle());
// Should have the same SiteInstance.
scoped_refptr<SiteInstance> noref_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, noref_site_instance);
}
// Hangs flakily in Win, http://crbug.com/45040.
#if defined(OS_WIN)
#define MAYBE_ChromeURLAfterDownload DISABLED_ChromeURLAfterDownload
#else
#defne MAYBE_ChromeURLAfterDownload ChromeURLAfterDownload
#endif // defined(OS_WIN)
// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
MAYBE_ChromeURLAfterDownload) {
GURL downloads_url("chrome://downloads");
GURL extensions_url("chrome://extensions");
FilePath zip_download;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
GURL zip_url = net::FilePathToFileURL(zip_download);
ui_test_utils::NavigateToURL(browser(), downloads_url);
ui_test_utils::NavigateToURL(browser(), zip_url);
ui_test_utils::WaitForDownloadCount(
browser()->profile()->GetDownloadManager(), 1);
ui_test_utils::NavigateToURL(browser(), extensions_url);
TabContents *contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool domui_responded = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.domAutomationController.send(window.domui_responded_);",
&domui_responded));
EXPECT_TRUE(domui_responded);
}
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
// NotificationObserver
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::BROWSER_CLOSED:
MessageLoopForUI::current()->Quit();
break;
}
}
private:
NotificationRegistrar registrar_;
};
// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
// TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix
// must be found before this can be re-enabled.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DISABLED_BrowserCloseAfterDownload) {
GURL downloads_url("chrome://downloads");
FilePath zip_download;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
ASSERT_TRUE(file_util::PathExists(zip_download));
GURL zip_url = net::FilePathToFileURL(zip_download);
ui_test_utils::NavigateToURL(browser(), downloads_url);
TabContents *contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool result = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.onunload = function() { var do_nothing = 0; }; "
L"window.domAutomationController.send(true);",
&result));
EXPECT_TRUE(result);
ui_test_utils::NavigateToURL(browser(), zip_url);
ui_test_utils::WaitForDownloadCount(
browser()->profile()->GetDownloadManager(), 1);
browser()->CloseWindow();
BrowserClosedObserver wait_for_close(browser());
}
<commit_msg>Disable hangy RenderViewHostManagerTest tests:<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/ref_counted.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
class RenderViewHostManagerTest : public InProcessBrowserTest {
public:
RenderViewHostManagerTest() {
EnableDOMAutomation();
}
};
// Test for crbug.com/24447. Following a cross-site link with rel=noreferrer
// and target=_blank should create a new SiteInstance.
// Disabled, http://crbug.com/60079.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DISABLED_SwapProcessWithRelNoreferrerAndTargetBlank) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server_(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server_.Start());
// Load a page with links that open in a new window.
ui_test_utils::NavigateToURL(browser(), test_server()->GetURL(
"files/click-noreferrer-links.html"));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a rel=noreferrer + target=blank link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickNoRefTargetBlankLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition to finish.
ui_test_utils::WaitForLoadStop(
&(browser()->GetSelectedTabContents()->controller()));
// Opens in new tab.
EXPECT_EQ(2, browser()->tab_count());
EXPECT_EQ(1, browser()->selected_index());
EXPECT_EQ(L"Title Of Awesomeness",
browser()->GetSelectedTabContents()->GetTitle());
// Should have a new SiteInstance.
scoped_refptr<SiteInstance> noref_blank_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_NE(orig_site_instance, noref_blank_site_instance);
}
// Test for crbug.com/24447. Following a cross-site link with just
// target=_blank should not create a new SiteInstance.
// Disabled, http://crbug.com/60078.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DISABLED_DontSwapProcessWithOnlyTargetBlank) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server_(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server_.Start());
// Load a page with links that open in a new window.
ui_test_utils::NavigateToURL(browser(), test_server()->GetURL(
"files/click-noreferrer-links.html"));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a target=blank link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickTargetBlankLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition to finish.
ui_test_utils::WaitForLoadStop(
&(browser()->GetSelectedTabContents()->controller()));
// Opens in new tab.
EXPECT_EQ(2, browser()->tab_count());
EXPECT_EQ(1, browser()->selected_index());
EXPECT_EQ(L"Title Of Awesomeness",
browser()->GetSelectedTabContents()->GetTitle());
// Should have the same SiteInstance.
scoped_refptr<SiteInstance> blank_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, blank_site_instance);
}
// Test for crbug.com/24447. Following a cross-site link with rel=noreferrer
// and no target=_blank should not create a new SiteInstance.
// Disabled, http://crbug.com/60077.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DISABLED_DontSwapProcessWithOnlyRelNoreferrer) {
// Start two servers with different sites.
ASSERT_TRUE(test_server()->Start());
net::TestServer https_server_(
net::TestServer::TYPE_HTTPS,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(https_server_.Start());
// Load a page with links that open in a new window.
ui_test_utils::NavigateToURL(browser(), test_server()->GetURL(
"files/click-noreferrer-links.html"));
// Get the original SiteInstance for later comparison.
scoped_refptr<SiteInstance> orig_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_TRUE(orig_site_instance != NULL);
// Test clicking a rel=noreferrer link.
bool success = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(clickNoRefLink());",
&success));
EXPECT_TRUE(success);
// Wait for the cross-site transition to finish.
ui_test_utils::WaitForLoadStop(
&(browser()->GetSelectedTabContents()->controller()));
// Opens in same tab.
EXPECT_EQ(1, browser()->tab_count());
EXPECT_EQ(0, browser()->selected_index());
EXPECT_EQ(L"Title Of Awesomeness",
browser()->GetSelectedTabContents()->GetTitle());
// Should have the same SiteInstance.
scoped_refptr<SiteInstance> noref_site_instance(
browser()->GetSelectedTabContents()->GetSiteInstance());
EXPECT_EQ(orig_site_instance, noref_site_instance);
}
// Hangs flakily in Win, http://crbug.com/45040.
#if defined(OS_WIN)
#define MAYBE_ChromeURLAfterDownload DISABLED_ChromeURLAfterDownload
#else
#defne MAYBE_ChromeURLAfterDownload ChromeURLAfterDownload
#endif // defined(OS_WIN)
// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
MAYBE_ChromeURLAfterDownload) {
GURL downloads_url("chrome://downloads");
GURL extensions_url("chrome://extensions");
FilePath zip_download;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
GURL zip_url = net::FilePathToFileURL(zip_download);
ui_test_utils::NavigateToURL(browser(), downloads_url);
ui_test_utils::NavigateToURL(browser(), zip_url);
ui_test_utils::WaitForDownloadCount(
browser()->profile()->GetDownloadManager(), 1);
ui_test_utils::NavigateToURL(browser(), extensions_url);
TabContents *contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool domui_responded = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.domAutomationController.send(window.domui_responded_);",
&domui_responded));
EXPECT_TRUE(domui_responded);
}
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
// NotificationObserver
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::BROWSER_CLOSED:
MessageLoopForUI::current()->Quit();
break;
}
}
private:
NotificationRegistrar registrar_;
};
// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
// TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix
// must be found before this can be re-enabled.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
DISABLED_BrowserCloseAfterDownload) {
GURL downloads_url("chrome://downloads");
FilePath zip_download;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
ASSERT_TRUE(file_util::PathExists(zip_download));
GURL zip_url = net::FilePathToFileURL(zip_download);
ui_test_utils::NavigateToURL(browser(), downloads_url);
TabContents *contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool result = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.onunload = function() { var do_nothing = 0; }; "
L"window.domAutomationController.send(true);",
&result));
EXPECT_TRUE(result);
ui_test_utils::NavigateToURL(browser(), zip_url);
ui_test_utils::WaitForDownloadCount(
browser()->profile()->GetDownloadManager(), 1);
browser()->CloseWindow();
BrowserClosedObserver wait_for_close(browser());
}
<|endoftext|> |
<commit_before>#include "Formatting.h"
#include <assert.h>
#include <string.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include "Buffers/Buffer.h"
#include "Buffers/ReadBuffer.h"
/*
* Readf is a simple sscanf replacement for working with non-null
* terminated strings
*
* specifiers:
* %% reads the '%' character
* %c (char) reads a char
* %d (int) reads a signed int
* %u (unsigned) reads an unsigned int
* %I (int64_t) reads a signed int64
* %U (uint64_t) reads an unsigned int64
*
* %B (Buffer* b) copies the rest into b.buffer by calling b.Write()
* and sets b.length
* %#B (Buffer* b) reads a <prefix>:<buffer> into b.length and copies
* the buffer into b.buffer by calling b.Write()
*
* %R (ReadBuffer* b) points to the rest of the buffer with b.buffer
* and sets b.length
* %#R (ReadBuffer* b) reads a <prefix>:<buffer> into b.length and sets
* b.buffer to point to the position
*
* Readf returns the number of bytes read from buffer, or -1
* if the format string did not match the buffer
*/
int Readf(char* buffer, unsigned length, const char* format, ...)
{
int read;
va_list ap;
va_start(ap, format);
read = VReadf(buffer, length, format, ap);
va_end(ap);
return read;
}
int VReadf(char* buffer, unsigned length, const char* format, va_list ap)
{
char* c;
int* d;
unsigned* u;
int64_t* i64;
uint64_t* u64;
Buffer* b;
ReadBuffer* rb;
unsigned n, l;
int read;
#define ADVANCE(f, b) { format += f; buffer += b; length -= b; read += b; }
#define EXIT() { return -1; }
#define REQUIRE(r) { if (length < r) EXIT() }
read = 0;
while(format[0] != '\0')
{
if (format[0] == '%')
{
if (format[1] == '\0')
EXIT(); // % cannot be at the end of the format string
if (format[1] == '%') // %%
{
REQUIRE(1);
if (buffer[0] != '%') EXIT();
ADVANCE(2, 1);
}
else if (format[1] == 'c') // %c
{
REQUIRE(1);
c = va_arg(ap, char*);
*c = buffer[0];
ADVANCE(2, 1);
}
else if (format[1] == 'd') // %d
{
d = va_arg(ap, int*);
*d = BufferToInt64(buffer, length, &n);
if (n < 1) EXIT();
ADVANCE(2, n);
}
else if (format[1] == 'u') // %u
{
u = va_arg(ap, unsigned*);
*u = BufferToUInt64(buffer, length, &n);
if (n < 1) EXIT();
ADVANCE(2, n);
}
else if (format[1] == 'I') // %I
{
i64 = va_arg(ap, int64_t*);
*i64 = BufferToInt64(buffer, length, &n);
if (n < 1) EXIT();
ADVANCE(2, n);
}
else if (format[1] == 'U') // %U
{
u64 = va_arg(ap, uint64_t*);
*u64 = BufferToUInt64(buffer, length, &n);
if (n < 1) EXIT();
ADVANCE(2, n);
}
else if (format[1] == 'B') // %B no prefix, copies rest
{
b = va_arg(ap, Buffer*);
b->Write(buffer, length);
ADVANCE(2, b->GetLength());
}
else if (length >= 3 && format[1] == '#' && format[2] == 'B') // %#B with prefix, copies
{
b = va_arg(ap, Buffer*);
// read the length prefix
l = BufferToUInt64(buffer, length, &n);
if (n < 1) EXIT();
ADVANCE(0, n);
// read the ':'
REQUIRE(1);
if (buffer[0] != ':') EXIT();
ADVANCE(0, 1);
// read the message body
REQUIRE(l);
b->Write(buffer, l);
ADVANCE(3, b->GetLength());
}
else if (format[1] == 'R') // %R no prefix, points to rest
{
rb = va_arg(ap, ReadBuffer*);
rb->Set(buffer, length);
ADVANCE(2, rb->GetLength());
}
else if (length >= 3 && format[1] == '#' && format[2] == 'R') // %#R with prefix, points
{
rb = va_arg(ap, ReadBuffer*);
// read the length prefix
l = BufferToUInt64(buffer, length, &n);
if (n < 1) EXIT();
ADVANCE(0, n);
// read the ':'
REQUIRE(1);
if (buffer[0] != ':') EXIT();
ADVANCE(0, 1);
// read the message body
REQUIRE(l);
rb->SetBuffer(buffer);
rb->SetLength(l);
ADVANCE(3, rb->GetLength());
}
else
{
ASSERT_FAIL();
}
}
else
{
REQUIRE(1);
if (buffer[0] != format[0]) EXIT();
ADVANCE(1, 1);
}
}
if (format[0] != '\0')
return -1;
return read;
#undef ADVANCE
#undef EXIT
#undef REQUIRE
}
/*
* Writef is a simple snprintf replacement for working with
* non-null terminated strings
*
* supported specifiers:
* %% prints the '%' character
* %c (char) prints a char
* %d (int) prints a signed int
* %u (unsigned) prints an unsigned int
* %I (int64_t) prints a signed int64
* %U (uint64_t) prints an unsigned int64
* %s (char* p) copies strlen(p) bytes from p to the output buffer
*
* %B (Buffer* b) copies b.buffer without prefix
* %#B (Buffer* b) copies b.buffer with prefix
*
* %R (ReadBuffer* b) copies b.buffer without prefix
* %#R (ReadBuffer* b) copies b.buffer with prefix
*
* Writef does not null-terminate the resulting buffer
* returns the number of bytes required or written, or -1 on error
* (if size bytes were not enough, Writef writes size bytes and returns the
* number of bytes that would have been required)
*/
int Writef(char* buffer, unsigned size, const char* format, ...)
{
int required;
va_list ap;
va_start(ap, format);
required = VWritef(buffer, size, format, ap);
va_end(ap);
return required;
}
int VWritef(char* buffer, unsigned size, const char* format, va_list ap)
{
char c;
int d;
unsigned u;
int n;
int64_t i64;
uint64_t u64;
char* p;
unsigned l, length;
Buffer* b;
ReadBuffer* rb;
int required;
char local[64];
bool ghost;
#define ADVANCE(f, b) { format += f; length -= f; if (!ghost) { buffer += b; size -= b; } }
#define EXIT() { return -1; }
#define REQUIRE(r) { required += r; if (size < (unsigned)r) ghost = true; }
ghost = false;
required = 0;
length = strlen(format);
while(format[0] != '\0')
{
if (format[0] == '%')
{
if (format[1] == '\0')
EXIT(); // % cannot be at the end of the format string
if (format[1] == '%') // %%
{
REQUIRE(1);
if (!ghost) buffer[0] = '%';
ADVANCE(2, (ghost ? 0 : 1));
}
else if (format[1] == 'c') // %c
{
REQUIRE(1);
c = va_arg(ap, int);
if (!ghost) buffer[0] = c;
ADVANCE(2, 1);
}
else if (format[1] == 'd') // %d
{
d = va_arg(ap, int);
n = snprintf(local, sizeof(local), "%d", d);
if (n < 0) EXIT();
REQUIRE(n);
if (ghost) n = size;
memcpy(buffer, local, n);
ADVANCE(2, n);
}
else if (format[1] == 'u') // %u
{
u = va_arg(ap, unsigned);
n = snprintf(local, sizeof(local), "%u", u);
if (n < 0) EXIT();
REQUIRE(n);
if (ghost) n = size;
memcpy(buffer, local, n);
ADVANCE(2, n);
}
else if (format[1] == 'I') // %I to print an int64_t
{
i64 = va_arg(ap, int64_t);
n = snprintf(local, sizeof(local), "%" PRIi64 "", i64);
if (n < 0) EXIT();
REQUIRE(n);
if (ghost) n = size;
memcpy(buffer, local, n);
ADVANCE(2, n);
}
else if (format[1] == 'U') // %U tp print an uint64_t
{
u64 = va_arg(ap, uint64_t);
n = snprintf(local, sizeof(local), "%" PRIu64 "", u64);
if (n < 0) EXIT();
REQUIRE(n);
if (ghost) n = size;
memcpy(buffer, local, n);
ADVANCE(2, n);
}
else if (format[1] == 's') // %s to print a string
{
p = va_arg(ap, char*);
l = strlen(p);
REQUIRE(l);
if (ghost) l = size;
memcpy(buffer, p, l);
ADVANCE(2, l);
}
else if (format[1] == 'B') // %B
{
b = va_arg(ap, Buffer*);
p = b->GetBuffer();
l = b->GetLength();
REQUIRE(l);
if (ghost) l = size;
memcpy(buffer, p, l);
ADVANCE(2, l);
}
else if (length >= 3 && format[1] == '#' && format[2] == 'B') // %#B
{
b = va_arg(ap, Buffer*);
n = snprintf(local, sizeof(local), "%u:", b->GetLength());
if (n < 0) EXIT();
REQUIRE(n);
if (ghost) n = size;
memcpy(buffer, local, n);
ADVANCE(0, n);
REQUIRE(b->GetLength());
l = b->GetLength();
if (ghost) l = size;
memmove(buffer, b->GetBuffer(), l);
ADVANCE(2, l);
}
else if (format[1] == 'B') // %R
{
rb = va_arg(ap, ReadBuffer*);
p = rb->GetBuffer();
l = rb->GetLength();
REQUIRE(l);
if (ghost) l = size;
memcpy(buffer, p, l);
ADVANCE(2, l);
}
else if (length >= 3 && format[1] == '#' && format[2] == 'R') // %#R
{
rb = va_arg(ap, ReadBuffer*);
n = snprintf(local, sizeof(local), "%u:", rb->GetLength());
if (n < 0) EXIT();
REQUIRE(n);
if (ghost) n = size;
memcpy(buffer, local, n);
ADVANCE(0, n);
REQUIRE(rb->GetLength());
l = rb->GetLength();
if (ghost) l = size;
memmove(buffer, rb->GetBuffer(), l);
ADVANCE(2, l);
}
else
{
ASSERT_FAIL();
}
}
else
{
REQUIRE(1);
if (!ghost) buffer[0] = format[0];
ADVANCE(1, (ghost ? 0 : 1));
}
}
return required;
#undef ADVANCE
#undef EXIT
#undef REQUIRE
}
<commit_msg>Fixed bug in formatting.<commit_after>#include "Formatting.h"
#include <assert.h>
#include <string.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include "Buffers/Buffer.h"
#include "Buffers/ReadBuffer.h"
/*
* Readf is a simple sscanf replacement for working with non-null
* terminated strings
*
* specifiers:
* %% reads the '%' character
* %c (char) reads a char
* %d (int) reads a signed int
* %u (unsigned) reads an unsigned int
* %I (int64_t) reads a signed int64
* %U (uint64_t) reads an unsigned int64
*
* %B (Buffer* b) copies the rest into b.buffer by calling b.Write()
* and sets b.length
* %#B (Buffer* b) reads a <prefix>:<buffer> into b.length and copies
* the buffer into b.buffer by calling b.Write()
*
* %R (ReadBuffer* b) points to the rest of the buffer with b.buffer
* and sets b.length
* %#R (ReadBuffer* b) reads a <prefix>:<buffer> into b.length and sets
* b.buffer to point to the position
*
* Readf returns the number of bytes read from buffer, or -1
* if the format string did not match the buffer
*/
int Readf(char* buffer, unsigned length, const char* format, ...)
{
int read;
va_list ap;
va_start(ap, format);
read = VReadf(buffer, length, format, ap);
va_end(ap);
return read;
}
int VReadf(char* buffer, unsigned length, const char* format, va_list ap)
{
char* c;
int* d;
unsigned* u;
int64_t* i64;
uint64_t* u64;
Buffer* b;
ReadBuffer* rb;
unsigned n, l;
int read;
#define ADVANCE(f, b) { format += f; buffer += b; length -= b; read += b; }
#define EXIT() { return -1; }
#define REQUIRE(r) { if (length < r) EXIT() }
read = 0;
while(format[0] != '\0')
{
if (format[0] == '%')
{
if (format[1] == '\0')
EXIT(); // % cannot be at the end of the format string
if (format[1] == '%') // %%
{
REQUIRE(1);
if (buffer[0] != '%') EXIT();
ADVANCE(2, 1);
}
else if (format[1] == 'c') // %c
{
REQUIRE(1);
c = va_arg(ap, char*);
*c = buffer[0];
ADVANCE(2, 1);
}
else if (format[1] == 'd') // %d
{
d = va_arg(ap, int*);
*d = BufferToInt64(buffer, length, &n);
if (n < 1) EXIT();
ADVANCE(2, n);
}
else if (format[1] == 'u') // %u
{
u = va_arg(ap, unsigned*);
*u = BufferToUInt64(buffer, length, &n);
if (n < 1) EXIT();
ADVANCE(2, n);
}
else if (format[1] == 'I') // %I
{
i64 = va_arg(ap, int64_t*);
*i64 = BufferToInt64(buffer, length, &n);
if (n < 1) EXIT();
ADVANCE(2, n);
}
else if (format[1] == 'U') // %U
{
u64 = va_arg(ap, uint64_t*);
*u64 = BufferToUInt64(buffer, length, &n);
if (n < 1) EXIT();
ADVANCE(2, n);
}
else if (format[1] == 'B') // %B no prefix, copies rest
{
b = va_arg(ap, Buffer*);
b->Write(buffer, length);
ADVANCE(2, b->GetLength());
}
else if (length >= 3 && format[1] == '#' && format[2] == 'B') // %#B with prefix, copies
{
b = va_arg(ap, Buffer*);
// read the length prefix
l = BufferToUInt64(buffer, length, &n);
if (n < 1) EXIT();
ADVANCE(0, n);
// read the ':'
REQUIRE(1);
if (buffer[0] != ':') EXIT();
ADVANCE(0, 1);
// read the message body
REQUIRE(l);
b->Write(buffer, l);
ADVANCE(3, b->GetLength());
}
else if (format[1] == 'R') // %R no prefix, points to rest
{
rb = va_arg(ap, ReadBuffer*);
rb->Set(buffer, length);
ADVANCE(2, rb->GetLength());
}
else if (length >= 3 && format[1] == '#' && format[2] == 'R') // %#R with prefix, points
{
rb = va_arg(ap, ReadBuffer*);
// read the length prefix
l = BufferToUInt64(buffer, length, &n);
if (n < 1) EXIT();
ADVANCE(0, n);
// read the ':'
REQUIRE(1);
if (buffer[0] != ':') EXIT();
ADVANCE(0, 1);
// read the message body
REQUIRE(l);
rb->SetBuffer(buffer);
rb->SetLength(l);
ADVANCE(3, rb->GetLength());
}
else
{
ASSERT_FAIL();
}
}
else
{
REQUIRE(1);
if (buffer[0] != format[0]) EXIT();
ADVANCE(1, 1);
}
}
if (format[0] != '\0')
return -1;
return read;
#undef ADVANCE
#undef EXIT
#undef REQUIRE
}
/*
* Writef is a simple snprintf replacement for working with
* non-null terminated strings
*
* supported specifiers:
* %% prints the '%' character
* %c (char) prints a char
* %d (int) prints a signed int
* %u (unsigned) prints an unsigned int
* %I (int64_t) prints a signed int64
* %U (uint64_t) prints an unsigned int64
* %s (char* p) copies strlen(p) bytes from p to the output buffer
*
* %B (Buffer* b) copies b.buffer without prefix
* %#B (Buffer* b) copies b.buffer with prefix
*
* %R (ReadBuffer* b) copies b.buffer without prefix
* %#R (ReadBuffer* b) copies b.buffer with prefix
*
* Writef does not null-terminate the resulting buffer
* returns the number of bytes required or written, or -1 on error
* (if size bytes were not enough, Writef writes size bytes and returns the
* number of bytes that would have been required)
*/
int Writef(char* buffer, unsigned size, const char* format, ...)
{
int required;
va_list ap;
va_start(ap, format);
required = VWritef(buffer, size, format, ap);
va_end(ap);
return required;
}
int VWritef(char* buffer, unsigned size, const char* format, va_list ap)
{
char c;
int d;
unsigned u;
int n;
int64_t i64;
uint64_t u64;
char* p;
unsigned l, length;
Buffer* b;
ReadBuffer* rb;
int required;
char local[64];
bool ghost;
#define ADVANCE(f, b) { format += f; length -= f; if (!ghost) { buffer += b; size -= b; } }
#define EXIT() { return -1; }
#define REQUIRE(r) { required += r; if (size < (unsigned)r) ghost = true; }
ghost = false;
required = 0;
length = strlen(format);
while(format[0] != '\0')
{
if (format[0] == '%')
{
if (format[1] == '\0')
EXIT(); // % cannot be at the end of the format string
if (format[1] == '%') // %%
{
REQUIRE(1);
if (!ghost) buffer[0] = '%';
ADVANCE(2, (ghost ? 0 : 1));
}
else if (format[1] == 'c') // %c
{
REQUIRE(1);
c = va_arg(ap, int);
if (!ghost) buffer[0] = c;
ADVANCE(2, 1);
}
else if (format[1] == 'd') // %d
{
d = va_arg(ap, int);
n = snprintf(local, sizeof(local), "%d", d);
if (n < 0) EXIT();
REQUIRE(n);
if (ghost) n = size;
memcpy(buffer, local, n);
ADVANCE(2, n);
}
else if (format[1] == 'u') // %u
{
u = va_arg(ap, unsigned);
n = snprintf(local, sizeof(local), "%u", u);
if (n < 0) EXIT();
REQUIRE(n);
if (ghost) n = size;
memcpy(buffer, local, n);
ADVANCE(2, n);
}
else if (format[1] == 'I') // %I to print an int64_t
{
i64 = va_arg(ap, int64_t);
n = snprintf(local, sizeof(local), "%" PRIi64 "", i64);
if (n < 0) EXIT();
REQUIRE(n);
if (ghost) n = size;
memcpy(buffer, local, n);
ADVANCE(2, n);
}
else if (format[1] == 'U') // %U tp print an uint64_t
{
u64 = va_arg(ap, uint64_t);
n = snprintf(local, sizeof(local), "%" PRIu64 "", u64);
if (n < 0) EXIT();
REQUIRE(n);
if (ghost) n = size;
memcpy(buffer, local, n);
ADVANCE(2, n);
}
else if (format[1] == 's') // %s to print a string
{
p = va_arg(ap, char*);
l = strlen(p);
REQUIRE(l);
if (ghost) l = size;
memcpy(buffer, p, l);
ADVANCE(2, l);
}
else if (format[1] == 'B') // %B
{
b = va_arg(ap, Buffer*);
p = b->GetBuffer();
l = b->GetLength();
REQUIRE(l);
if (ghost) l = size;
memcpy(buffer, p, l);
ADVANCE(2, l);
}
else if (length >= 3 && format[1] == '#' && format[2] == 'B') // %#B
{
b = va_arg(ap, Buffer*);
n = snprintf(local, sizeof(local), "%u:", b->GetLength());
if (n < 0) EXIT();
REQUIRE(n);
if (ghost) n = size;
memcpy(buffer, local, n);
ADVANCE(0, n);
REQUIRE(b->GetLength());
l = b->GetLength();
if (ghost) l = size;
memmove(buffer, b->GetBuffer(), l);
ADVANCE(2, l);
}
else if (format[1] == 'R') // %R
{
rb = va_arg(ap, ReadBuffer*);
p = rb->GetBuffer();
l = rb->GetLength();
REQUIRE(l);
if (ghost) l = size;
memcpy(buffer, p, l);
ADVANCE(2, l);
}
else if (length >= 3 && format[1] == '#' && format[2] == 'R') // %#R
{
rb = va_arg(ap, ReadBuffer*);
n = snprintf(local, sizeof(local), "%u:", rb->GetLength());
if (n < 0) EXIT();
REQUIRE(n);
if (ghost) n = size;
memcpy(buffer, local, n);
ADVANCE(0, n);
REQUIRE(rb->GetLength());
l = rb->GetLength();
if (ghost) l = size;
memmove(buffer, rb->GetBuffer(), l);
ADVANCE(2, l);
}
else
{
ASSERT_FAIL();
}
}
else
{
REQUIRE(1);
if (!ghost) buffer[0] = format[0];
ADVANCE(1, (ghost ? 0 : 1));
}
}
return required;
#undef ADVANCE
#undef EXIT
#undef REQUIRE
}
<|endoftext|> |
<commit_before>#pragma once
#include "adjustment.hpp"
#include "io.hpp"
#include "vec.hpp"
#include "voxel.hpp"
#include <string>
#include <tuple>
#include <vector>
template <typename color_t>
void convert(const std::string &fname)
{
std::vector<voxel<color_t>> volume;
vec min, max;
uint64_t x, y, z;
std::cout << "Reading data..." << std::endl;
std::tie(volume, x, y, z, min, max) = input<color_t>(fname);
std::cout << "Size: " << x << 'x' << y << 'x' << z << std::endl;
std::cout << "Min: (" << min.x << ", " << min.y << ", " << min.z << ')' << std::endl;
std::cout << "Max: (" << max.x << ", " << max.y << ", " << max.z << ')' << std::endl;
vec d = {
(max.x - min.x) / (x - 1),
(max.y - min.y) / (y - 1),
(max.z - min.z) / (z - 1)
};
std::cout << "Delta: (" << d.x << ", " << d.y << ", " << d.z << ')' << std::endl << std::endl;
std::cout << "Adjustment..." << std::endl;
auto result = adjustment<color_t>(x, y, z, d, min, volume);
std::cout << "Saving result..." << std::endl;
output<color_t>(fname, result, { x, y, z, min, max, d, color_t::format() });
std::cout << "Done." << std::endl;
delete[] result;
}<commit_msg>Change output<commit_after>#pragma once
#include "adjustment.hpp"
#include "io.hpp"
#include "vec.hpp"
#include "voxel.hpp"
#include <string>
#include <tuple>
#include <vector>
template <typename color_t>
void convert(const std::string &fname)
{
std::vector<voxel<color_t>> volume;
vec min, max;
uint64_t x, y, z;
std::cout << "Reading data..." << std::endl;
std::tie(volume, x, y, z, min, max) = input<color_t>(fname);
std::cout << "Size: " << x << 'x' << y << 'x' << z << std::endl;
std::cout << "Min: (" << min.x << ", " << min.y << ", " << min.z << ')' << std::endl;
std::cout << "Max: (" << max.x << ", " << max.y << ", " << max.z << ')' << std::endl;
vec d = {
(max.x - min.x) / (x - 1),
(max.y - min.y) / (y - 1),
(max.z - min.z) / (z - 1)
};
std::cout << "Delta: (" << d.x << ", " << d.y << ", " << d.z << ')' << std::endl << std::endl;
std::cout << "Adjustment..." << std::endl;
auto result = adjustment<color_t>(x, y, z, d, min, volume);
std::cout << "Saving result..." << std::endl;
output<color_t>(fname, result, { x, y, z, min, max, d, color_t::format() });
std::cout << "Done." << std::endl << std::endl;
delete[] result;
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 Patrick Kelsey. 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 AUTHOR 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 AUTHOR 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 <tr1/unordered_map>
#include <common/buffer.h>
#include <common/test.h>
#include <event/event_callback.h>
#include <event/typed_callback.h>
#include <event/event_main.h>
#include <io/pipe/splice.h>
#include <io/pipe/splice_pair.h>
#include <io/socket/resolver.h>
#include <io/socket/socket_uinet_promisc.h>
#include <io/io_uinet.h>
class Listener {
struct ConnInfo {
struct uinet_in_conninfo inc;
struct uinet_in_l2info l2i;
bool operator== (const ConnInfo& other) const
{
if ((inc.inc_fibnum != other.inc.inc_fibnum) ||
(inc.inc_ie.ie_laddr.s_addr != other.inc.inc_ie.ie_laddr.s_addr) ||
(inc.inc_ie.ie_lport != other.inc.inc_ie.ie_lport) ||
(inc.inc_ie.ie_faddr.s_addr != other.inc.inc_ie.ie_faddr.s_addr) ||
(inc.inc_ie.ie_fport != other.inc.inc_ie.ie_fport))
return (false);
if (0 != uinet_l2tagstack_cmp(&l2i.inl2i_tagstack, &other.l2i.inl2i_tagstack))
return (false);
return (true);
}
};
struct SpliceInfo {
ConnInfo conninfo;
uinet_synf_deferral_t deferral;
Action *connect_action;
SocketUinetPromisc *inbound;
SocketUinetPromisc *outbound;
Splice *splice_inbound;
Splice *splice_outbound;
SplicePair *splice_pair;
Action *splice_action;
Action *close_action;
};
struct ConnInfoHasher {
std::size_t operator()(const ConnInfo& ci) const
{
std::size_t hash;
hash =
(ci.inc.inc_fibnum << 11) ^
ci.inc.inc_ie.ie_laddr.s_addr ^
ci.inc.inc_ie.ie_lport ^
ci.inc.inc_ie.ie_faddr.s_addr ^
ci.inc.inc_ie.ie_fport;
hash ^= uinet_l2tagstack_hash(&ci.l2i.inl2i_tagstack);
return (hash);
}
};
LogHandle log_;
SocketUinetPromisc *listen_socket_;
Mutex mtx_;
Action *action_;
unsigned int inbound_cdom_;
unsigned int outbound_cdom_;
SocketUinetPromisc::SynfilterCallback *synfilter_callback_;
std::tr1::unordered_map<ConnInfo,SpliceInfo,ConnInfoHasher> connections_;
public:
Listener(const std::string& where, unsigned int inbound_cdom, unsigned int outbound_cdom)
: log_("/listener"),
mtx_("Listener"),
action_(NULL),
inbound_cdom_(inbound_cdom),
outbound_cdom_(outbound_cdom)
{
synfilter_callback_ = callback(this, &Listener::synfilter);
listen_socket_ = SocketUinetPromisc::create(SocketAddressFamilyIPv4, SocketTypeStream, "tcp", "", inbound_cdom_);
if (listen_socket_ == NULL)
return;
listen_socket_->setsynfilter(synfilter_callback_);
/*
* Setting l2info with a tag count of -1 on a listen socket
* means to listen on all VLANs. A tag count of 0 (default)
* would mean only listen for untagged traffic.
*/
if (0 != listen_socket_->setl2info2(NULL, NULL, UINET_INL2I_TAG_ANY, NULL))
return;
if (!listen_socket_->bind(where))
return;
if (!listen_socket_->listen())
return;
{
ScopedLock _(&mtx_);
SocketEventCallback *cb = callback(this, &Listener::accept_complete);
action_ = listen_socket_->accept(cb);
}
}
~Listener()
{
ScopedLock _(&mtx_);
if (action_ != NULL)
action_->cancel();
action_ = NULL;
if (listen_socket_ != NULL)
delete listen_socket_;
listen_socket_ = NULL;
}
/*
* This will get invoked for every SYN received on listen_socket_.
* The connection details for the SYN are tracked in the
* connections_ table for two reasons. The first is that we only
* want to take action (that is, open an outbound connection to the
* destination) for a given SYN once, not each time it may be
* retransmitted. The second is that when a SYN is accepted by the
* filter, the stack then processes it in the normal path, resulting
* in a subsequent accept, and that accept has to be able to locate
* the outbound connection made by the filter and associate it with
* the inbound connection being accepted. There is no way to pass
* any context to that subsequent accept from this syn filter
* through the stack (because, syncookies).
*/
void synfilter(SocketUinetPromisc::SynfilterCallbackParam param)
{
ScopedLock _(&mtx_);
ConnInfo ci;
ci.inc = *param.inc;
ci.l2i = *param.l2i;
if (connections_.find(ci) == connections_.end()) {
struct uinet_in_l2info *l2i = param.l2i;
SpliceInfo& si = connections_[ci];
si.conninfo = ci;
/*
* Get deferral context for the SYN filter result.
*/
si.deferral = listen_socket_->synfdefer(param.cookie);
/*
* Set up outbound connection.
*/
si.inbound = NULL;
si.outbound = SocketUinetPromisc::create(SocketAddressFamilyIPv4, SocketTypeStream, "tcp", "", outbound_cdom_);
if (NULL == si.outbound)
goto out;
/*
* Use the L2 details of the foreign host that sent this SYN.
*/
si.outbound->setl2info2(l2i->inl2i_foreign_addr, l2i->inl2i_local_addr,
l2i->inl2i_flags, &l2i->inl2i_tagstack);
/*
* Use the IP address and port number of the foreign
* host that sent this SYN.
*/
/* XXX perhaps resolver could support us a bit better here */
socket_address addr1;
addr1.addr_.inet_.sin_len = sizeof(struct sockaddr_in);
addr1.addr_.inet_.sin_family = AF_INET;
addr1.addr_.inet_.sin_port = ci.inc.inc_ie.ie_fport;
addr1.addr_.inet_.sin_addr.s_addr = ci.inc.inc_ie.ie_faddr.s_addr;
addr1.addrlen_ = addr1.addr_.inet_.sin_len;
si.outbound->bind(addr1);
/*
* Connect to the same IP address and port number
* that the foreign host that sent this SYN is
* trying to connect to. On connection completion,
* the deferred SYN filter decision will be
* delivered. Once the deferred decision is
* delivered, and if it is UINET_SYNF_ACCEPT, the
* accept for the original inbound connection will
* complete.
*/
EventCallback *cb = callback(this, &Listener::connect_complete, ci);
socket_address addr2;
addr2.addr_.inet_.sin_len = sizeof(struct sockaddr_in);
addr2.addr_.inet_.sin_family = AF_INET;
addr2.addr_.inet_.sin_port = ci.inc.inc_ie.ie_lport;
addr2.addr_.inet_.sin_addr.s_addr = ci.inc.inc_ie.ie_laddr.s_addr;
addr2.addrlen_ = addr2.addr_.inet_.sin_len;
si.connect_action = si.outbound->connect(addr2, cb);
DEBUG(log_) << "Outbound from " << (std::string)addr1 << " to " << (std::string)addr2;
*param.result = UINET_SYNF_DEFER;
return;
}
out:
*param.result = UINET_SYNF_REJECT;
}
void accept_complete(Event e, Socket *socket)
{
ScopedLock _(&mtx_);
action_->cancel();
action_ = NULL;
switch (e.type_) {
case Event::Done: {
DEBUG(log_) << "Inbound from " << socket->getpeername() << " to " << socket->getsockname();
SocketUinetPromisc *promisc = (SocketUinetPromisc *)socket;
ConnInfo ci;
promisc->getconninfo(&ci.inc);
promisc->getl2info(&ci.l2i);
SpliceInfo& si = connections_[ci];
si.inbound = promisc;
si.splice_inbound = new Splice(log_ + "/inbound", si.inbound, NULL, si.outbound);
si.splice_outbound = new Splice(log_ + "/outbound", si.outbound, NULL, si.inbound);
si.splice_pair = new SplicePair(si.splice_inbound, si.splice_outbound);
EventCallback *cb = callback(this, &Listener::splice_complete, ci);
si.splice_action = si.splice_pair->start(cb);
break;
}
default:
ERROR(log_) << "Unexpected event: " << e;
return;
}
SocketEventCallback *cb = callback(this, &Listener::accept_complete);
action_ = listen_socket_->accept(cb);
}
void connect_complete(Event e, ConnInfo ci)
{
ScopedLock _(&mtx_);
SpliceInfo& si = connections_[ci];
si.connect_action->cancel();
si.connect_action = NULL;
switch (e.type_) {
case Event::Done:
listen_socket_->synfdeferraldeliver(si.deferral, UINET_SYNF_ACCEPT);
break;
default:
connections_.erase(ci);
listen_socket_->synfdeferraldeliver(si.deferral, UINET_SYNF_REJECT);
/* XXX Close socket? */
ERROR(log_) << "Unexpected event: " << e;
break;
}
}
void splice_complete(Event e, ConnInfo ci)
{
ScopedLock _(&mtx_);
SpliceInfo& si = connections_[ci];
si.splice_action->cancel();
si.splice_action = NULL;
switch (e.type_) {
case Event::Done:
break;
default:
ERROR(log_) << "Splice exiting unexpectedly: " << e;
break;
}
ASSERT(log_, si.splice_pair != NULL);
delete si.splice_pair;
si.splice_pair = NULL;
ASSERT(log_, si.splice_inbound != NULL);
delete si.splice_inbound;
si.splice_inbound = NULL;
ASSERT(log_, si.splice_outbound != NULL);
delete si.splice_outbound;
si.splice_outbound = NULL;
SimpleCallback *cb = callback(this, &Listener::close_complete, ci);
si.close_action = si.outbound->close(cb);
}
void close_complete(ConnInfo ci)
{
ScopedLock _(&mtx_);
SpliceInfo& si = connections_[ci];
si.close_action->cancel();
si.close_action = NULL;
if (si.outbound != NULL) {
delete si.outbound;
si.outbound = NULL;
SimpleCallback *cb = callback(this, &Listener::close_complete, ci);
si.close_action = si.inbound->close(cb);
return;
}
delete si.inbound;
si.inbound = NULL;
connections_.erase(ci);
}
};
int
main(void)
{
IOUinet::instance()->start(false);
IOUinet::instance()->add_interface(UINET_IFTYPE_NETMAP, "vale0:1", "proxy-a-side", 1, -1);
IOUinet::instance()->interface_up("proxy-a-side", true);
IOUinet::instance()->add_interface(UINET_IFTYPE_NETMAP, "vale1:1", "proxy-b-side", 2, -1);
IOUinet::instance()->interface_up("proxy-b-side", true);
Listener *l = new Listener("[0.0.0.0]:0", 1, 2);
event_main();
#if notquiteyet
IOUinet::instance()->remove_interface("proxy-a-side");
IOUinet::instance()->remove_interface("proxy-b-side");
#endif
delete l;
}
<commit_msg>Removed stale comment.<commit_after>/*
* Copyright (c) 2013 Patrick Kelsey. 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 AUTHOR 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 AUTHOR 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 <tr1/unordered_map>
#include <common/buffer.h>
#include <common/test.h>
#include <event/event_callback.h>
#include <event/typed_callback.h>
#include <event/event_main.h>
#include <io/pipe/splice.h>
#include <io/pipe/splice_pair.h>
#include <io/socket/resolver.h>
#include <io/socket/socket_uinet_promisc.h>
#include <io/io_uinet.h>
class Listener {
struct ConnInfo {
struct uinet_in_conninfo inc;
struct uinet_in_l2info l2i;
bool operator== (const ConnInfo& other) const
{
if ((inc.inc_fibnum != other.inc.inc_fibnum) ||
(inc.inc_ie.ie_laddr.s_addr != other.inc.inc_ie.ie_laddr.s_addr) ||
(inc.inc_ie.ie_lport != other.inc.inc_ie.ie_lport) ||
(inc.inc_ie.ie_faddr.s_addr != other.inc.inc_ie.ie_faddr.s_addr) ||
(inc.inc_ie.ie_fport != other.inc.inc_ie.ie_fport))
return (false);
if (0 != uinet_l2tagstack_cmp(&l2i.inl2i_tagstack, &other.l2i.inl2i_tagstack))
return (false);
return (true);
}
};
struct SpliceInfo {
ConnInfo conninfo;
uinet_synf_deferral_t deferral;
Action *connect_action;
SocketUinetPromisc *inbound;
SocketUinetPromisc *outbound;
Splice *splice_inbound;
Splice *splice_outbound;
SplicePair *splice_pair;
Action *splice_action;
Action *close_action;
};
struct ConnInfoHasher {
std::size_t operator()(const ConnInfo& ci) const
{
std::size_t hash;
hash =
(ci.inc.inc_fibnum << 11) ^
ci.inc.inc_ie.ie_laddr.s_addr ^
ci.inc.inc_ie.ie_lport ^
ci.inc.inc_ie.ie_faddr.s_addr ^
ci.inc.inc_ie.ie_fport;
hash ^= uinet_l2tagstack_hash(&ci.l2i.inl2i_tagstack);
return (hash);
}
};
LogHandle log_;
SocketUinetPromisc *listen_socket_;
Mutex mtx_;
Action *action_;
unsigned int inbound_cdom_;
unsigned int outbound_cdom_;
SocketUinetPromisc::SynfilterCallback *synfilter_callback_;
std::tr1::unordered_map<ConnInfo,SpliceInfo,ConnInfoHasher> connections_;
public:
Listener(const std::string& where, unsigned int inbound_cdom, unsigned int outbound_cdom)
: log_("/listener"),
mtx_("Listener"),
action_(NULL),
inbound_cdom_(inbound_cdom),
outbound_cdom_(outbound_cdom)
{
synfilter_callback_ = callback(this, &Listener::synfilter);
listen_socket_ = SocketUinetPromisc::create(SocketAddressFamilyIPv4, SocketTypeStream, "tcp", "", inbound_cdom_);
if (listen_socket_ == NULL)
return;
listen_socket_->setsynfilter(synfilter_callback_);
if (0 != listen_socket_->setl2info2(NULL, NULL, UINET_INL2I_TAG_ANY, NULL))
return;
if (!listen_socket_->bind(where))
return;
if (!listen_socket_->listen())
return;
{
ScopedLock _(&mtx_);
SocketEventCallback *cb = callback(this, &Listener::accept_complete);
action_ = listen_socket_->accept(cb);
}
}
~Listener()
{
ScopedLock _(&mtx_);
if (action_ != NULL)
action_->cancel();
action_ = NULL;
if (listen_socket_ != NULL)
delete listen_socket_;
listen_socket_ = NULL;
}
/*
* This will get invoked for every SYN received on listen_socket_.
* The connection details for the SYN are tracked in the
* connections_ table for two reasons. The first is that we only
* want to take action (that is, open an outbound connection to the
* destination) for a given SYN once, not each time it may be
* retransmitted. The second is that when a SYN is accepted by the
* filter, the stack then processes it in the normal path, resulting
* in a subsequent accept, and that accept has to be able to locate
* the outbound connection made by the filter and associate it with
* the inbound connection being accepted. There is no way to pass
* any context to that subsequent accept from this syn filter
* through the stack (because, syncookies).
*/
void synfilter(SocketUinetPromisc::SynfilterCallbackParam param)
{
ScopedLock _(&mtx_);
ConnInfo ci;
ci.inc = *param.inc;
ci.l2i = *param.l2i;
if (connections_.find(ci) == connections_.end()) {
struct uinet_in_l2info *l2i = param.l2i;
SpliceInfo& si = connections_[ci];
si.conninfo = ci;
/*
* Get deferral context for the SYN filter result.
*/
si.deferral = listen_socket_->synfdefer(param.cookie);
/*
* Set up outbound connection.
*/
si.inbound = NULL;
si.outbound = SocketUinetPromisc::create(SocketAddressFamilyIPv4, SocketTypeStream, "tcp", "", outbound_cdom_);
if (NULL == si.outbound)
goto out;
/*
* Use the L2 details of the foreign host that sent this SYN.
*/
si.outbound->setl2info2(l2i->inl2i_foreign_addr, l2i->inl2i_local_addr,
l2i->inl2i_flags, &l2i->inl2i_tagstack);
/*
* Use the IP address and port number of the foreign
* host that sent this SYN.
*/
/* XXX perhaps resolver could support us a bit better here */
socket_address addr1;
addr1.addr_.inet_.sin_len = sizeof(struct sockaddr_in);
addr1.addr_.inet_.sin_family = AF_INET;
addr1.addr_.inet_.sin_port = ci.inc.inc_ie.ie_fport;
addr1.addr_.inet_.sin_addr.s_addr = ci.inc.inc_ie.ie_faddr.s_addr;
addr1.addrlen_ = addr1.addr_.inet_.sin_len;
si.outbound->bind(addr1);
/*
* Connect to the same IP address and port number
* that the foreign host that sent this SYN is
* trying to connect to. On connection completion,
* the deferred SYN filter decision will be
* delivered. Once the deferred decision is
* delivered, and if it is UINET_SYNF_ACCEPT, the
* accept for the original inbound connection will
* complete.
*/
EventCallback *cb = callback(this, &Listener::connect_complete, ci);
socket_address addr2;
addr2.addr_.inet_.sin_len = sizeof(struct sockaddr_in);
addr2.addr_.inet_.sin_family = AF_INET;
addr2.addr_.inet_.sin_port = ci.inc.inc_ie.ie_lport;
addr2.addr_.inet_.sin_addr.s_addr = ci.inc.inc_ie.ie_laddr.s_addr;
addr2.addrlen_ = addr2.addr_.inet_.sin_len;
si.connect_action = si.outbound->connect(addr2, cb);
DEBUG(log_) << "Outbound from " << (std::string)addr1 << " to " << (std::string)addr2;
*param.result = UINET_SYNF_DEFER;
return;
}
out:
*param.result = UINET_SYNF_REJECT;
}
void accept_complete(Event e, Socket *socket)
{
ScopedLock _(&mtx_);
action_->cancel();
action_ = NULL;
switch (e.type_) {
case Event::Done: {
DEBUG(log_) << "Inbound from " << socket->getpeername() << " to " << socket->getsockname();
SocketUinetPromisc *promisc = (SocketUinetPromisc *)socket;
ConnInfo ci;
promisc->getconninfo(&ci.inc);
promisc->getl2info(&ci.l2i);
SpliceInfo& si = connections_[ci];
si.inbound = promisc;
si.splice_inbound = new Splice(log_ + "/inbound", si.inbound, NULL, si.outbound);
si.splice_outbound = new Splice(log_ + "/outbound", si.outbound, NULL, si.inbound);
si.splice_pair = new SplicePair(si.splice_inbound, si.splice_outbound);
EventCallback *cb = callback(this, &Listener::splice_complete, ci);
si.splice_action = si.splice_pair->start(cb);
break;
}
default:
ERROR(log_) << "Unexpected event: " << e;
return;
}
SocketEventCallback *cb = callback(this, &Listener::accept_complete);
action_ = listen_socket_->accept(cb);
}
void connect_complete(Event e, ConnInfo ci)
{
ScopedLock _(&mtx_);
SpliceInfo& si = connections_[ci];
si.connect_action->cancel();
si.connect_action = NULL;
switch (e.type_) {
case Event::Done:
listen_socket_->synfdeferraldeliver(si.deferral, UINET_SYNF_ACCEPT);
break;
default:
connections_.erase(ci);
listen_socket_->synfdeferraldeliver(si.deferral, UINET_SYNF_REJECT);
/* XXX Close socket? */
ERROR(log_) << "Unexpected event: " << e;
break;
}
}
void splice_complete(Event e, ConnInfo ci)
{
ScopedLock _(&mtx_);
SpliceInfo& si = connections_[ci];
si.splice_action->cancel();
si.splice_action = NULL;
switch (e.type_) {
case Event::Done:
break;
default:
ERROR(log_) << "Splice exiting unexpectedly: " << e;
break;
}
ASSERT(log_, si.splice_pair != NULL);
delete si.splice_pair;
si.splice_pair = NULL;
ASSERT(log_, si.splice_inbound != NULL);
delete si.splice_inbound;
si.splice_inbound = NULL;
ASSERT(log_, si.splice_outbound != NULL);
delete si.splice_outbound;
si.splice_outbound = NULL;
SimpleCallback *cb = callback(this, &Listener::close_complete, ci);
si.close_action = si.outbound->close(cb);
}
void close_complete(ConnInfo ci)
{
ScopedLock _(&mtx_);
SpliceInfo& si = connections_[ci];
si.close_action->cancel();
si.close_action = NULL;
if (si.outbound != NULL) {
delete si.outbound;
si.outbound = NULL;
SimpleCallback *cb = callback(this, &Listener::close_complete, ci);
si.close_action = si.inbound->close(cb);
return;
}
delete si.inbound;
si.inbound = NULL;
connections_.erase(ci);
}
};
int
main(void)
{
IOUinet::instance()->start(false);
IOUinet::instance()->add_interface(UINET_IFTYPE_NETMAP, "vale0:1", "proxy-a-side", 1, -1);
IOUinet::instance()->interface_up("proxy-a-side", true);
IOUinet::instance()->add_interface(UINET_IFTYPE_NETMAP, "vale1:1", "proxy-b-side", 2, -1);
IOUinet::instance()->interface_up("proxy-b-side", true);
Listener *l = new Listener("[0.0.0.0]:0", 1, 2);
event_main();
#if notquiteyet
IOUinet::instance()->remove_interface("proxy-a-side");
IOUinet::instance()->remove_interface("proxy-b-side");
#endif
delete l;
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
/**
* \file brw_wm_channel_expressions.cpp
*
* Breaks vector operations down into operations on each component.
*
* The 965 fragment shader receives 8 or 16 pixels at a time, so each
* channel of a vector is laid out as 1 or 2 8-float registers. Each
* ALU operation operates on one of those channel registers. As a
* result, there is no value to the 965 fragment shader in tracking
* "vector" expressions in the sense of GLSL fragment shaders, when
* doing a channel at a time may help in constant folding, algebraic
* simplification, and reducing the liveness of channel registers.
*
* The exception to the desire to break everything down to floats is
* texturing. The texture sampler returns a writemasked masked
* 4/8-register sequence containing the texture values. We don't want
* to dispatch to the sampler separately for each channel we need, so
* we do retain the vector types in that case.
*/
extern "C" {
#include "main/core.h"
#include "brw_wm.h"
}
#include "../glsl/ir.h"
#include "../glsl/ir_expression_flattening.h"
#include "../glsl/glsl_types.h"
class ir_channel_expressions_visitor : public ir_hierarchical_visitor {
public:
ir_channel_expressions_visitor()
{
this->progress = false;
this->mem_ctx = NULL;
}
ir_visitor_status visit_leave(ir_assignment *);
ir_rvalue *get_element(ir_variable *var, unsigned int element);
void assign(ir_assignment *ir, int elem, ir_rvalue *val);
bool progress;
void *mem_ctx;
};
static bool
channel_expressions_predicate(ir_instruction *ir)
{
ir_expression *expr = ir->as_expression();
unsigned int i;
if (!expr)
return false;
for (i = 0; i < expr->get_num_operands(); i++) {
if (expr->operands[i]->type->is_vector())
return true;
}
return false;
}
extern "C" {
GLboolean
brw_do_channel_expressions(exec_list *instructions)
{
ir_channel_expressions_visitor v;
/* Pull out any matrix expression to a separate assignment to a
* temp. This will make our handling of the breakdown to
* operations on the matrix's vector components much easier.
*/
do_expression_flattening(instructions, channel_expressions_predicate);
visit_list_elements(&v, instructions);
return v.progress;
}
}
ir_rvalue *
ir_channel_expressions_visitor::get_element(ir_variable *var, unsigned int elem)
{
ir_dereference *deref;
if (var->type->is_scalar())
return new(mem_ctx) ir_dereference_variable(var);
assert(elem < var->type->components());
deref = new(mem_ctx) ir_dereference_variable(var);
return new(mem_ctx) ir_swizzle(deref, elem, 0, 0, 0, 1);
}
void
ir_channel_expressions_visitor::assign(ir_assignment *ir, int elem, ir_rvalue *val)
{
ir_dereference *lhs = ir->lhs->clone(mem_ctx, NULL);
ir_assignment *assign;
ir_swizzle *val_swiz;
/* This assign-of-expression should have been generated by the
* expression flattening visitor (since we never short circit to
* not flatten, even for plain assignments of variables), so the
* writemask is always full.
*/
assert(ir->write_mask == (1 << ir->lhs->type->components()) - 1);
assign = new(mem_ctx) ir_assignment(lhs, val, NULL, (1 << elem));
ir->insert_before(assign);
}
ir_visitor_status
ir_channel_expressions_visitor::visit_leave(ir_assignment *ir)
{
ir_expression *expr = ir->rhs->as_expression();
bool found_vector = false;
unsigned int i, vector_elements = 1;
ir_variable *op_var[2];
if (!expr)
return visit_continue;
if (!this->mem_ctx)
this->mem_ctx = talloc_parent(ir);
for (i = 0; i < expr->get_num_operands(); i++) {
if (expr->operands[i]->type->is_vector()) {
found_vector = true;
vector_elements = expr->operands[i]->type->vector_elements;
break;
}
}
if (!found_vector)
return visit_continue;
/* Store the expression operands in temps so we can use them
* multiple times.
*/
for (i = 0; i < expr->get_num_operands(); i++) {
ir_assignment *assign;
ir_dereference *deref;
assert(!expr->operands[i]->type->is_matrix());
op_var[i] = new(mem_ctx) ir_variable(expr->operands[i]->type,
"channel_expressions",
ir_var_temporary);
ir->insert_before(op_var[i]);
deref = new(mem_ctx) ir_dereference_variable(op_var[i]);
assign = new(mem_ctx) ir_assignment(deref,
expr->operands[i],
NULL);
ir->insert_before(assign);
}
const glsl_type *element_type = glsl_type::get_instance(ir->lhs->type->base_type,
1, 1);
/* OK, time to break down this vector operation. */
switch (expr->operation) {
case ir_unop_bit_not:
case ir_unop_logic_not:
case ir_unop_neg:
case ir_unop_abs:
case ir_unop_sign:
case ir_unop_rcp:
case ir_unop_rsq:
case ir_unop_sqrt:
case ir_unop_exp:
case ir_unop_log:
case ir_unop_exp2:
case ir_unop_log2:
case ir_unop_f2i:
case ir_unop_i2f:
case ir_unop_f2b:
case ir_unop_b2f:
case ir_unop_i2b:
case ir_unop_b2i:
case ir_unop_u2f:
case ir_unop_trunc:
case ir_unop_ceil:
case ir_unop_floor:
case ir_unop_fract:
case ir_unop_sin:
case ir_unop_cos:
case ir_unop_dFdx:
case ir_unop_dFdy:
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
assign(ir, i, new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
NULL));
}
break;
case ir_binop_add:
case ir_binop_sub:
case ir_binop_mul:
case ir_binop_div:
case ir_binop_mod:
case ir_binop_min:
case ir_binop_max:
case ir_binop_pow:
case ir_binop_lshift:
case ir_binop_rshift:
case ir_binop_bit_and:
case ir_binop_bit_xor:
case ir_binop_bit_or:
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
ir_rvalue *op1 = get_element(op_var[1], i);
assign(ir, i, new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
op1));
}
break;
case ir_unop_any: {
ir_expression *temp;
temp = new(mem_ctx) ir_expression(ir_binop_logic_or,
element_type,
get_element(op_var[0], 0),
get_element(op_var[0], 1));
for (i = 2; i < vector_elements; i++) {
temp = new(mem_ctx) ir_expression(ir_binop_logic_or,
element_type,
get_element(op_var[0], i),
temp);
}
assign(ir, 0, temp);
break;
}
case ir_binop_dot: {
ir_expression *last = NULL;
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
ir_rvalue *op1 = get_element(op_var[1], i);
ir_expression *temp;
temp = new(mem_ctx) ir_expression(ir_binop_mul,
element_type,
op0,
op1);
if (last) {
last = new(mem_ctx) ir_expression(ir_binop_add,
element_type,
temp,
last);
} else {
last = temp;
}
}
assign(ir, 0, last);
break;
}
case ir_binop_cross: {
for (i = 0; i < vector_elements; i++) {
int swiz0 = (i + 1) % 3;
int swiz1 = (i + 2) % 3;
ir_expression *temp1, *temp2;
temp1 = new(mem_ctx) ir_expression(ir_binop_mul,
element_type,
get_element(op_var[0], swiz0),
get_element(op_var[1], swiz1));
temp2 = new(mem_ctx) ir_expression(ir_binop_mul,
element_type,
get_element(op_var[1], swiz0),
get_element(op_var[0], swiz1));
temp2 = new(mem_ctx) ir_expression(ir_unop_neg,
element_type,
temp2,
NULL);
assign(ir, i, new(mem_ctx) ir_expression(ir_binop_add,
element_type,
temp1, temp2));
}
break;
}
case ir_binop_less:
case ir_binop_greater:
case ir_binop_lequal:
case ir_binop_gequal:
case ir_binop_logic_and:
case ir_binop_logic_xor:
case ir_binop_logic_or:
ir->print();
printf("\n");
assert(!"not reached: expression operates on scalars only");
break;
case ir_binop_equal:
case ir_binop_nequal: {
ir_expression *last = NULL;
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
ir_rvalue *op1 = get_element(op_var[1], i);
ir_expression *temp;
ir_expression_operation join;
if (expr->operation == ir_binop_equal)
join = ir_binop_logic_and;
else
join = ir_binop_logic_or;
temp = new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
op1);
if (last) {
last = new(mem_ctx) ir_expression(join,
element_type,
temp,
last);
} else {
last = temp;
}
}
assign(ir, 0, last);
break;
}
case ir_unop_noise:
assert(!"noise should have been broken down to function call");
break;
}
ir->remove();
this->progress = true;
return visit_continue;
}
<commit_msg>i965: Update expression splitting for the vector-result change to compares.<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
/**
* \file brw_wm_channel_expressions.cpp
*
* Breaks vector operations down into operations on each component.
*
* The 965 fragment shader receives 8 or 16 pixels at a time, so each
* channel of a vector is laid out as 1 or 2 8-float registers. Each
* ALU operation operates on one of those channel registers. As a
* result, there is no value to the 965 fragment shader in tracking
* "vector" expressions in the sense of GLSL fragment shaders, when
* doing a channel at a time may help in constant folding, algebraic
* simplification, and reducing the liveness of channel registers.
*
* The exception to the desire to break everything down to floats is
* texturing. The texture sampler returns a writemasked masked
* 4/8-register sequence containing the texture values. We don't want
* to dispatch to the sampler separately for each channel we need, so
* we do retain the vector types in that case.
*/
extern "C" {
#include "main/core.h"
#include "brw_wm.h"
}
#include "../glsl/ir.h"
#include "../glsl/ir_expression_flattening.h"
#include "../glsl/glsl_types.h"
class ir_channel_expressions_visitor : public ir_hierarchical_visitor {
public:
ir_channel_expressions_visitor()
{
this->progress = false;
this->mem_ctx = NULL;
}
ir_visitor_status visit_leave(ir_assignment *);
ir_rvalue *get_element(ir_variable *var, unsigned int element);
void assign(ir_assignment *ir, int elem, ir_rvalue *val);
bool progress;
void *mem_ctx;
};
static bool
channel_expressions_predicate(ir_instruction *ir)
{
ir_expression *expr = ir->as_expression();
unsigned int i;
if (!expr)
return false;
for (i = 0; i < expr->get_num_operands(); i++) {
if (expr->operands[i]->type->is_vector())
return true;
}
return false;
}
extern "C" {
GLboolean
brw_do_channel_expressions(exec_list *instructions)
{
ir_channel_expressions_visitor v;
/* Pull out any matrix expression to a separate assignment to a
* temp. This will make our handling of the breakdown to
* operations on the matrix's vector components much easier.
*/
do_expression_flattening(instructions, channel_expressions_predicate);
visit_list_elements(&v, instructions);
return v.progress;
}
}
ir_rvalue *
ir_channel_expressions_visitor::get_element(ir_variable *var, unsigned int elem)
{
ir_dereference *deref;
if (var->type->is_scalar())
return new(mem_ctx) ir_dereference_variable(var);
assert(elem < var->type->components());
deref = new(mem_ctx) ir_dereference_variable(var);
return new(mem_ctx) ir_swizzle(deref, elem, 0, 0, 0, 1);
}
void
ir_channel_expressions_visitor::assign(ir_assignment *ir, int elem, ir_rvalue *val)
{
ir_dereference *lhs = ir->lhs->clone(mem_ctx, NULL);
ir_assignment *assign;
/* This assign-of-expression should have been generated by the
* expression flattening visitor (since we never short circit to
* not flatten, even for plain assignments of variables), so the
* writemask is always full.
*/
assert(ir->write_mask == (1 << ir->lhs->type->components()) - 1);
assign = new(mem_ctx) ir_assignment(lhs, val, NULL, (1 << elem));
ir->insert_before(assign);
}
ir_visitor_status
ir_channel_expressions_visitor::visit_leave(ir_assignment *ir)
{
ir_expression *expr = ir->rhs->as_expression();
bool found_vector = false;
unsigned int i, vector_elements = 1;
ir_variable *op_var[2];
if (!expr)
return visit_continue;
if (!this->mem_ctx)
this->mem_ctx = talloc_parent(ir);
for (i = 0; i < expr->get_num_operands(); i++) {
if (expr->operands[i]->type->is_vector()) {
found_vector = true;
vector_elements = expr->operands[i]->type->vector_elements;
break;
}
}
if (!found_vector)
return visit_continue;
/* Store the expression operands in temps so we can use them
* multiple times.
*/
for (i = 0; i < expr->get_num_operands(); i++) {
ir_assignment *assign;
ir_dereference *deref;
assert(!expr->operands[i]->type->is_matrix());
op_var[i] = new(mem_ctx) ir_variable(expr->operands[i]->type,
"channel_expressions",
ir_var_temporary);
ir->insert_before(op_var[i]);
deref = new(mem_ctx) ir_dereference_variable(op_var[i]);
assign = new(mem_ctx) ir_assignment(deref,
expr->operands[i],
NULL);
ir->insert_before(assign);
}
const glsl_type *element_type = glsl_type::get_instance(ir->lhs->type->base_type,
1, 1);
/* OK, time to break down this vector operation. */
switch (expr->operation) {
case ir_unop_bit_not:
case ir_unop_logic_not:
case ir_unop_neg:
case ir_unop_abs:
case ir_unop_sign:
case ir_unop_rcp:
case ir_unop_rsq:
case ir_unop_sqrt:
case ir_unop_exp:
case ir_unop_log:
case ir_unop_exp2:
case ir_unop_log2:
case ir_unop_f2i:
case ir_unop_i2f:
case ir_unop_f2b:
case ir_unop_b2f:
case ir_unop_i2b:
case ir_unop_b2i:
case ir_unop_u2f:
case ir_unop_trunc:
case ir_unop_ceil:
case ir_unop_floor:
case ir_unop_fract:
case ir_unop_sin:
case ir_unop_cos:
case ir_unop_dFdx:
case ir_unop_dFdy:
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
assign(ir, i, new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
NULL));
}
break;
case ir_binop_add:
case ir_binop_sub:
case ir_binop_mul:
case ir_binop_div:
case ir_binop_mod:
case ir_binop_min:
case ir_binop_max:
case ir_binop_pow:
case ir_binop_lshift:
case ir_binop_rshift:
case ir_binop_bit_and:
case ir_binop_bit_xor:
case ir_binop_bit_or:
case ir_binop_less:
case ir_binop_greater:
case ir_binop_lequal:
case ir_binop_gequal:
case ir_binop_equal:
case ir_binop_nequal:
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
ir_rvalue *op1 = get_element(op_var[1], i);
assign(ir, i, new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
op1));
}
break;
case ir_unop_any: {
ir_expression *temp;
temp = new(mem_ctx) ir_expression(ir_binop_logic_or,
element_type,
get_element(op_var[0], 0),
get_element(op_var[0], 1));
for (i = 2; i < vector_elements; i++) {
temp = new(mem_ctx) ir_expression(ir_binop_logic_or,
element_type,
get_element(op_var[0], i),
temp);
}
assign(ir, 0, temp);
break;
}
case ir_binop_dot: {
ir_expression *last = NULL;
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
ir_rvalue *op1 = get_element(op_var[1], i);
ir_expression *temp;
temp = new(mem_ctx) ir_expression(ir_binop_mul,
element_type,
op0,
op1);
if (last) {
last = new(mem_ctx) ir_expression(ir_binop_add,
element_type,
temp,
last);
} else {
last = temp;
}
}
assign(ir, 0, last);
break;
}
case ir_binop_cross: {
for (i = 0; i < vector_elements; i++) {
int swiz0 = (i + 1) % 3;
int swiz1 = (i + 2) % 3;
ir_expression *temp1, *temp2;
temp1 = new(mem_ctx) ir_expression(ir_binop_mul,
element_type,
get_element(op_var[0], swiz0),
get_element(op_var[1], swiz1));
temp2 = new(mem_ctx) ir_expression(ir_binop_mul,
element_type,
get_element(op_var[1], swiz0),
get_element(op_var[0], swiz1));
temp2 = new(mem_ctx) ir_expression(ir_unop_neg,
element_type,
temp2,
NULL);
assign(ir, i, new(mem_ctx) ir_expression(ir_binop_add,
element_type,
temp1, temp2));
}
break;
}
case ir_binop_logic_and:
case ir_binop_logic_xor:
case ir_binop_logic_or:
ir->print();
printf("\n");
assert(!"not reached: expression operates on scalars only");
break;
case ir_binop_all_equal:
case ir_binop_any_nequal: {
ir_expression *last = NULL;
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
ir_rvalue *op1 = get_element(op_var[1], i);
ir_expression *temp;
ir_expression_operation join;
if (expr->operation == ir_binop_all_equal)
join = ir_binop_logic_and;
else
join = ir_binop_logic_or;
temp = new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
op1);
if (last) {
last = new(mem_ctx) ir_expression(join,
element_type,
temp,
last);
} else {
last = temp;
}
}
assign(ir, 0, last);
break;
}
case ir_unop_noise:
assert(!"noise should have been broken down to function call");
break;
}
ir->remove();
this->progress = true;
return visit_continue;
}
<|endoftext|> |
<commit_before>#include "test_cast.h"
#include <rtti.h>
#include <debug.h>
#include <memory>
namespace {
struct A
{
int a = 1;
virtual ~A() = default;
DECLARE_CLASSINFO
};
struct B: A
{
int b = 2;
DECLARE_CLASSINFO
};
struct C: B
{
int c = 3;
DECLARE_CLASSINFO
};
struct D
{
int d = 4;
virtual ~D() = default;
DECLARE_CLASSINFO
};
struct E: C, D
{
int e = 5;
DECLARE_CLASSINFO
};
struct VB1: virtual B
{
int vb1 = 10;
DECLARE_CLASSINFO
};
struct VB2: virtual B
{
int vb2 = 20;
DECLARE_CLASSINFO
};
struct VC: VB1, VB2
{
int vc = 100;
DECLARE_CLASSINFO
};
void register_classes()
{
using namespace rtti;
global_define()
._namespace("anonimous_1")
._class<A>("A")._end()
._class<B>("B")._base<A>()._end()
._class<C>("C")._base<B>()._end()
._class<D>("D")._end()
._class<E>("E")._base<C, D>()._end()
._class<VB1>("VB1")._base<B>()._end()
._class<VB2>("VB2")._base<B>()._end()
._class<VC>("VC")._base<VB1, VB2>()._end()
._end()
;
}
} // namespace
void test_cast_1()
{
using namespace std;
register_classes();
{
using namespace rtti;
auto a = unique_ptr<A>(new B());
auto b1 = meta_cast<B>(a.get());
assert(b1 && b1->b == 2);
auto &b2 = meta_cast<B>(*a);
assert(b2.b == 2);
}
{
using namespace rtti;
auto a = unique_ptr<const A>(new B());
auto b1 = meta_cast<B>(a.get());
assert(b1 && b1->b == 2);
auto &b2 = meta_cast<B>(*a);
assert(b2.b == 2);
}
{
using namespace rtti;
auto a = unique_ptr<A>(new C());
auto c1 = meta_cast<C>(a.get());
assert(c1 && c1->c == 3);
auto &c2 = meta_cast<C>(*a);
assert(c2.c == 3);
auto b1 = meta_cast<B>(a.get());
assert(b1 && b1->b == 2);
auto &b2 = meta_cast<B>(*a);
assert(b2.b == 2);
auto a1 = meta_cast<A>(a.get());
assert(a1 && a1->a == 1);
auto &a2 = meta_cast<A>(*a);
assert(a2.a == 1);
auto d1 = meta_cast<D>(a.get());
assert(!d1);
try
{
//should throw exception
auto &d2 = meta_cast<D>(*a);
(void) d2;
assert(false);
}
catch(const bad_meta_cast &e)
{
printf(e.what());
printf("\n\n");
}
}
{
using namespace rtti;
auto d = unique_ptr<D>(new E());
auto e1 = meta_cast<E>(d.get());
assert(e1 && e1->e == 5);
auto &e2 = meta_cast<E>(*d);
assert(e2.e == 5);
auto d1 = meta_cast<D>(d.get());
assert(d1 && d1->d == 4);
auto &d2 = meta_cast<D>(*d);
assert(d2.d == 4);
auto c1 = meta_cast<C>(d.get());
assert(c1 && c1->c == 3);
auto &c2 = meta_cast<C>(*d);
assert(c2.c == 3);
auto b1 = meta_cast<B>(d.get());
assert(b1 && b1->b == 2);
auto &b2 = meta_cast<B>(*d);
assert(b2.b == 2);
auto a1 = meta_cast<A>(d.get());
assert(a1 && a1->a == 1);
auto &a2 = meta_cast<A>(*d);
assert(a2.a == 1);
}
{
using namespace rtti;
auto a = unique_ptr<A>(new VC());
auto c1 = meta_cast<VC>(a.get());
assert(c1 && c1->vc == 100);
auto &c2 = meta_cast<VC>(*a);
assert(c2.vc == 100);
auto vb1 = meta_cast<VB1>(a.get());
assert(vb1 && vb1->vb1 == 10);
auto &vb11 = meta_cast<VB1>(*a);
assert(vb11.vb1 == 10);
auto vb2 = meta_cast<VB2>(a.get());
assert(vb2 && vb2->vb2 == 20);
auto &vb21 = meta_cast<VB2>(*a);
assert(vb21.vb2 == 20);
auto b1 = meta_cast<B>(a.get());
assert(b1 && b1->b == 2);
auto &b2 = meta_cast<B>(*a);
assert(b2.b == 2);
auto a1 = meta_cast<A>(a.get());
assert(a1 && a1->a == 1);
auto &a2 = meta_cast<A>(*a);
assert(a2.a == 1);
}
}
<commit_msg>Space removed<commit_after>#include "test_cast.h"
#include <rtti.h>
#include <debug.h>
#include <memory>
namespace {
struct A
{
int a = 1;
virtual ~A() = default;
DECLARE_CLASSINFO
};
struct B: A
{
int b = 2;
DECLARE_CLASSINFO
};
struct C: B
{
int c = 3;
DECLARE_CLASSINFO
};
struct D
{
int d = 4;
virtual ~D() = default;
DECLARE_CLASSINFO
};
struct E: C, D
{
int e = 5;
DECLARE_CLASSINFO
};
struct VB1: virtual B
{
int vb1 = 10;
DECLARE_CLASSINFO
};
struct VB2: virtual B
{
int vb2 = 20;
DECLARE_CLASSINFO
};
struct VC: VB1, VB2
{
int vc = 100;
DECLARE_CLASSINFO
};
void register_classes()
{
using namespace rtti;
global_define()
._namespace("anonimous_1")
._class<A>("A")._end()
._class<B>("B")._base<A>()._end()
._class<C>("C")._base<B>()._end()
._class<D>("D")._end()
._class<E>("E")._base<C, D>()._end()
._class<VB1>("VB1")._base<B>()._end()
._class<VB2>("VB2")._base<B>()._end()
._class<VC>("VC")._base<VB1, VB2>()._end()
._end()
;
}
} // namespace
void test_cast_1()
{
using namespace std;
register_classes();
{
using namespace rtti;
auto a = unique_ptr<A>(new B());
auto b1 = meta_cast<B>(a.get());
assert(b1 && b1->b == 2);
auto &b2 = meta_cast<B>(*a);
assert(b2.b == 2);
}
{
using namespace rtti;
auto a = unique_ptr<const A>(new B());
auto b1 = meta_cast<B>(a.get());
assert(b1 && b1->b == 2);
auto &b2 = meta_cast<B>(*a);
assert(b2.b == 2);
}
{
using namespace rtti;
auto a = unique_ptr<A>(new C());
auto c1 = meta_cast<C>(a.get());
assert(c1 && c1->c == 3);
auto &c2 = meta_cast<C>(*a);
assert(c2.c == 3);
auto b1 = meta_cast<B>(a.get());
assert(b1 && b1->b == 2);
auto &b2 = meta_cast<B>(*a);
assert(b2.b == 2);
auto a1 = meta_cast<A>(a.get());
assert(a1 && a1->a == 1);
auto &a2 = meta_cast<A>(*a);
assert(a2.a == 1);
auto d1 = meta_cast<D>(a.get());
assert(!d1);
try
{
//should throw exception
auto &d2 = meta_cast<D>(*a);
(void) d2;
assert(false);
}
catch(const bad_meta_cast &e)
{
printf(e.what());
printf("\n\n");
}
}
{
using namespace rtti;
auto d = unique_ptr<D>(new E());
auto e1 = meta_cast<E>(d.get());
assert(e1 && e1->e == 5);
auto &e2 = meta_cast<E>(*d);
assert(e2.e == 5);
auto d1 = meta_cast<D>(d.get());
assert(d1 && d1->d == 4);
auto &d2 = meta_cast<D>(*d);
assert(d2.d == 4);
auto c1 = meta_cast<C>(d.get());
assert(c1 && c1->c == 3);
auto &c2 = meta_cast<C>(*d);
assert(c2.c == 3);
auto b1 = meta_cast<B>(d.get());
assert(b1 && b1->b == 2);
auto &b2 = meta_cast<B>(*d);
assert(b2.b == 2);
auto a1 = meta_cast<A>(d.get());
assert(a1 && a1->a == 1);
auto &a2 = meta_cast<A>(*d);
assert(a2.a == 1);
}
{
using namespace rtti;
auto a = unique_ptr<A>(new VC());
auto c1 = meta_cast<VC>(a.get());
assert(c1 && c1->vc == 100);
auto &c2 = meta_cast<VC>(*a);
assert(c2.vc == 100);
auto vb1 = meta_cast<VB1>(a.get());
assert(vb1 && vb1->vb1 == 10);
auto &vb11 = meta_cast<VB1>(*a);
assert(vb11.vb1 == 10);
auto vb2 = meta_cast<VB2>(a.get());
assert(vb2 && vb2->vb2 == 20);
auto &vb21 = meta_cast<VB2>(*a);
assert(vb21.vb2 == 20);
auto b1 = meta_cast<B>(a.get());
assert(b1 && b1->b == 2);
auto &b2 = meta_cast<B>(*a);
assert(b2.b == 2);
auto a1 = meta_cast<A>(a.get());
assert(a1 && a1->a == 1);
auto &a2 = meta_cast<A>(*a);
assert(a2.a == 1);
}
}
<|endoftext|> |
<commit_before>#include "CommentHandler.h"
#include <sstream>
#include "JZLogger.h"
using namespace std;
#define COMMENT_FLAG_NON 0
#define COMMENT_FLAG_SRC 1
#define COMMENT_FLAG_LINE_COMMENT 2
#define COMMENT_FLAG_BLOCK_COMMENT 3
#define COMMENT_FLAG_END 4
#define COMMENT_FLAG_STR 5
CommentHandler::CommentHandler()
{
}
CommentHandler* CommentHandler::getInstance()
{
static CommentHandler* instance = NULL;
if (NULL == instance)
{
instance = new CommentHandler();
}
return instance;
}
std::string CommentHandler::eraseComment(const std::string& src)
{
int flag = COMMENT_FLAG_NON;
stringstream ioStream;
ioStream << src;
string line;
while(false != getline(ioStream, line))
{
JZWRITE_DEBUG("get line : %s", line.c_str());
for (int i = 0; i < line.size; i++) {
if ('\\' == line[i])
{
//handle "\" here
}
if('"' == line[i] && (flag == COMMENT_FLAG_NON || flag == COMMENT_FLAG_SRC))
{
//in src code ,now enter the str mode
flag = COMMENT_FLAG_STR;
continue;
}
switch(flag)
{
case COMMENT_FLAG_NON:
{
break;
}
default:
{
break;
}
}
}
}
return "";
}
<commit_msg>先删掉没想清楚的代码<commit_after>#include "CommentHandler.h"
#include <sstream>
#include "JZLogger.h"
using namespace std;
#define COMMENT_FLAG_NON 0
#define COMMENT_FLAG_SRC 1
#define COMMENT_FLAG_LINE_COMMENT 2
#define COMMENT_FLAG_BLOCK_COMMENT 3
#define COMMENT_FLAG_END 4
#define COMMENT_FLAG_STR 5
CommentHandler::CommentHandler()
{
}
CommentHandler* CommentHandler::getInstance()
{
static CommentHandler* instance = NULL;
if (NULL == instance)
{
instance = new CommentHandler();
}
return instance;
}
std::string CommentHandler::eraseComment(const std::string& src)
{
return "";
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 Patrick Kelsey. 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 AUTHOR 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 AUTHOR 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 <tr1/unordered_map>
#include <common/buffer.h>
#include <common/test.h>
#include <event/event_callback.h>
#include <event/typed_callback.h>
#include <event/event_main.h>
#include <io/pipe/splice.h>
#include <io/pipe/splice_pair.h>
#include <io/socket/resolver.h>
#include <io/socket/socket_uinet_promisc.h>
#include <io/io_uinet.h>
class Listener {
struct ConnInfo {
struct uinet_in_conninfo inc;
struct uinet_in_l2info l2i;
bool operator== (const ConnInfo& other) const
{
if ((inc.inc_fibnum != other.inc.inc_fibnum) ||
(inc.inc_ie.ie_laddr.s_addr != other.inc.inc_ie.ie_laddr.s_addr) ||
(inc.inc_ie.ie_lport != other.inc.inc_ie.ie_lport) ||
(inc.inc_ie.ie_faddr.s_addr != other.inc.inc_ie.ie_faddr.s_addr) ||
(inc.inc_ie.ie_fport != other.inc.inc_ie.ie_fport))
return (false);
if (0 != uinet_l2tagstack_cmp(&l2i.inl2i_tagstack, &other.l2i.inl2i_tagstack))
return (false);
return (true);
}
};
struct SpliceInfo {
ConnInfo conninfo;
uinet_synf_deferral_t deferral;
Action *connect_action;
SocketUinetPromisc *inbound;
SocketUinetPromisc *outbound;
Splice *splice_inbound;
Splice *splice_outbound;
SplicePair *splice_pair;
Action *splice_action;
Action *close_action;
};
struct ConnInfoHasher {
std::size_t operator()(const ConnInfo& ci) const
{
std::size_t hash;
hash =
(ci.inc.inc_fibnum << 11) ^
ci.inc.inc_ie.ie_laddr.s_addr ^
ci.inc.inc_ie.ie_lport ^
ci.inc.inc_ie.ie_faddr.s_addr ^
ci.inc.inc_ie.ie_fport;
hash ^= uinet_l2tagstack_hash(&ci.l2i.inl2i_tagstack);
return (hash);
}
};
LogHandle log_;
SocketUinetPromisc *listen_socket_;
Mutex mtx_;
Action *action_;
unsigned int inbound_cdom_;
unsigned int outbound_cdom_;
SocketUinetPromisc::SynfilterCallback *synfilter_callback_;
std::tr1::unordered_map<ConnInfo,SpliceInfo,ConnInfoHasher> connections_;
public:
Listener(const std::string& where, unsigned int inbound_cdom, unsigned int outbound_cdom)
: log_("/listener"),
mtx_("Listener"),
action_(NULL),
inbound_cdom_(inbound_cdom),
outbound_cdom_(outbound_cdom)
{
synfilter_callback_ = callback(this, &Listener::synfilter);
listen_socket_ = SocketUinetPromisc::create(SocketAddressFamilyIPv4, SocketTypeStream, "tcp", "", inbound_cdom_);
if (listen_socket_ == NULL)
return;
listen_socket_->setsynfilter(synfilter_callback_);
if (0 != listen_socket_->setl2info2(NULL, NULL, UINET_INL2I_TAG_ANY, NULL))
return;
if (!listen_socket_->bind(where))
return;
if (!listen_socket_->listen())
return;
{
ScopedLock _(&mtx_);
SocketEventCallback *cb = callback(this, &Listener::accept_complete);
action_ = listen_socket_->accept(cb);
}
}
~Listener()
{
ScopedLock _(&mtx_);
if (action_ != NULL)
action_->cancel();
action_ = NULL;
if (listen_socket_ != NULL)
delete listen_socket_;
listen_socket_ = NULL;
}
/*
* This will get invoked for every SYN received on listen_socket_.
* The connection details for the SYN are tracked in the
* connections_ table for two reasons. The first is that we only
* want to take action (that is, open an outbound connection to the
* destination) for a given SYN once, not each time it may be
* retransmitted. The second is that when a SYN is accepted by the
* filter, the stack then processes it in the normal path, resulting
* in a subsequent accept, and that accept has to be able to locate
* the outbound connection made by the filter and associate it with
* the inbound connection being accepted. There is no way to pass
* any context to that subsequent accept from this syn filter
* through the stack (because, syncookies).
*/
void synfilter(SocketUinetPromisc::SynfilterCallbackParam param)
{
ScopedLock _(&mtx_);
ConnInfo ci;
ci.inc = *param.inc;
ci.l2i = *param.l2i;
if (connections_.find(ci) == connections_.end()) {
struct uinet_in_l2info *l2i = param.l2i;
SpliceInfo& si = connections_[ci];
si.conninfo = ci;
/*
* Get deferral context for the SYN filter result.
*/
si.deferral = listen_socket_->synfdefer(param.cookie);
/*
* Set up outbound connection.
*/
si.inbound = NULL;
si.outbound = SocketUinetPromisc::create(SocketAddressFamilyIPv4, SocketTypeStream, "tcp", "", outbound_cdom_);
if (NULL == si.outbound)
goto out;
/*
* Use the L2 details of the foreign host that sent this SYN.
*/
si.outbound->setl2info2(l2i->inl2i_foreign_addr, l2i->inl2i_local_addr,
l2i->inl2i_flags, &l2i->inl2i_tagstack);
/*
* Use the IP address and port number of the foreign
* host that sent this SYN.
*/
/* XXX perhaps resolver could support us a bit better here */
socket_address addr1;
addr1.addr_.inet_.sin_len = sizeof(struct sockaddr_in);
addr1.addr_.inet_.sin_family = AF_INET;
addr1.addr_.inet_.sin_port = ci.inc.inc_ie.ie_fport;
addr1.addr_.inet_.sin_addr.s_addr = ci.inc.inc_ie.ie_faddr.s_addr;
addr1.addrlen_ = addr1.addr_.inet_.sin_len;
si.outbound->bind(addr1);
/*
* Connect to the same IP address and port number
* that the foreign host that sent this SYN is
* trying to connect to. On connection completion,
* the deferred SYN filter decision will be
* delivered. Once the deferred decision is
* delivered, and if it is UINET_SYNF_ACCEPT, the
* accept for the original inbound connection will
* complete.
*/
EventCallback *cb = callback(this, &Listener::connect_complete, ci);
socket_address addr2;
addr2.addr_.inet_.sin_len = sizeof(struct sockaddr_in);
addr2.addr_.inet_.sin_family = AF_INET;
addr2.addr_.inet_.sin_port = ci.inc.inc_ie.ie_lport;
addr2.addr_.inet_.sin_addr.s_addr = ci.inc.inc_ie.ie_laddr.s_addr;
addr2.addrlen_ = addr2.addr_.inet_.sin_len;
si.connect_action = si.outbound->connect(addr2, cb);
DEBUG(log_) << "Outbound from " << (std::string)addr1 << " to " << (std::string)addr2;
*param.result = UINET_SYNF_DEFER;
return;
}
out:
*param.result = UINET_SYNF_REJECT;
}
void accept_complete(Event e, Socket *socket)
{
ScopedLock _(&mtx_);
action_->cancel();
action_ = NULL;
switch (e.type_) {
case Event::Done: {
DEBUG(log_) << "Inbound from " << socket->getpeername() << " to " << socket->getsockname();
SocketUinetPromisc *promisc = (SocketUinetPromisc *)socket;
ConnInfo ci;
promisc->getconninfo(&ci.inc);
promisc->getl2info(&ci.l2i);
SpliceInfo& si = connections_[ci];
si.inbound = promisc;
si.splice_inbound = new Splice(log_ + "/inbound", si.inbound, NULL, si.outbound);
si.splice_outbound = new Splice(log_ + "/outbound", si.outbound, NULL, si.inbound);
si.splice_pair = new SplicePair(si.splice_inbound, si.splice_outbound);
EventCallback *cb = callback(this, &Listener::splice_complete, ci);
si.splice_action = si.splice_pair->start(cb);
break;
}
default:
ERROR(log_) << "Unexpected event: " << e;
return;
}
SocketEventCallback *cb = callback(this, &Listener::accept_complete);
action_ = listen_socket_->accept(cb);
}
void connect_complete(Event e, ConnInfo ci)
{
ScopedLock _(&mtx_);
SpliceInfo& si = connections_[ci];
si.connect_action->cancel();
si.connect_action = NULL;
switch (e.type_) {
case Event::Done:
listen_socket_->synfdeferraldeliver(si.deferral, UINET_SYNF_ACCEPT);
break;
default:
connections_.erase(ci);
listen_socket_->synfdeferraldeliver(si.deferral, UINET_SYNF_REJECT);
/* XXX Close socket? */
ERROR(log_) << "Unexpected event: " << e;
break;
}
}
void splice_complete(Event e, ConnInfo ci)
{
ScopedLock _(&mtx_);
SpliceInfo& si = connections_[ci];
si.splice_action->cancel();
si.splice_action = NULL;
switch (e.type_) {
case Event::Done:
break;
default:
ERROR(log_) << "Splice exiting unexpectedly: " << e;
break;
}
ASSERT(log_, si.splice_pair != NULL);
delete si.splice_pair;
si.splice_pair = NULL;
ASSERT(log_, si.splice_inbound != NULL);
delete si.splice_inbound;
si.splice_inbound = NULL;
ASSERT(log_, si.splice_outbound != NULL);
delete si.splice_outbound;
si.splice_outbound = NULL;
SimpleCallback *cb = callback(this, &Listener::close_complete, ci);
si.close_action = si.outbound->close(cb);
}
void close_complete(ConnInfo ci)
{
ScopedLock _(&mtx_);
SpliceInfo& si = connections_[ci];
si.close_action->cancel();
si.close_action = NULL;
if (si.outbound != NULL) {
delete si.outbound;
si.outbound = NULL;
SimpleCallback *cb = callback(this, &Listener::close_complete, ci);
si.close_action = si.inbound->close(cb);
return;
}
delete si.inbound;
si.inbound = NULL;
connections_.erase(ci);
}
};
int
main(void)
{
IOUinet::instance()->start(false);
IOUinet::instance()->add_interface(UINET_IFTYPE_NETMAP, "vale0:1", "proxy-a-side", 1, -1);
IOUinet::instance()->interface_up("proxy-a-side", true);
IOUinet::instance()->add_interface(UINET_IFTYPE_NETMAP, "vale1:1", "proxy-b-side", 2, -1);
IOUinet::instance()->interface_up("proxy-b-side", true);
Listener *l = new Listener("[0.0.0.0]:0", 1, 2);
event_main();
#if notquiteyet
IOUinet::instance()->remove_interface("proxy-a-side");
IOUinet::instance()->remove_interface("proxy-b-side");
#endif
delete l;
}
<commit_msg>Avoid setting sin_len when it does not exist in sockaddr.<commit_after>/*
* Copyright (c) 2013 Patrick Kelsey. 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 AUTHOR 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 AUTHOR 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 <tr1/unordered_map>
#include <common/buffer.h>
#include <common/test.h>
#include <event/event_callback.h>
#include <event/typed_callback.h>
#include <event/event_main.h>
#include <io/pipe/splice.h>
#include <io/pipe/splice_pair.h>
#include <io/socket/resolver.h>
#include <io/socket/socket_uinet_promisc.h>
#include <io/io_uinet.h>
class Listener {
struct ConnInfo {
struct uinet_in_conninfo inc;
struct uinet_in_l2info l2i;
bool operator== (const ConnInfo& other) const
{
if ((inc.inc_fibnum != other.inc.inc_fibnum) ||
(inc.inc_ie.ie_laddr.s_addr != other.inc.inc_ie.ie_laddr.s_addr) ||
(inc.inc_ie.ie_lport != other.inc.inc_ie.ie_lport) ||
(inc.inc_ie.ie_faddr.s_addr != other.inc.inc_ie.ie_faddr.s_addr) ||
(inc.inc_ie.ie_fport != other.inc.inc_ie.ie_fport))
return (false);
if (0 != uinet_l2tagstack_cmp(&l2i.inl2i_tagstack, &other.l2i.inl2i_tagstack))
return (false);
return (true);
}
};
struct SpliceInfo {
ConnInfo conninfo;
uinet_synf_deferral_t deferral;
Action *connect_action;
SocketUinetPromisc *inbound;
SocketUinetPromisc *outbound;
Splice *splice_inbound;
Splice *splice_outbound;
SplicePair *splice_pair;
Action *splice_action;
Action *close_action;
};
struct ConnInfoHasher {
std::size_t operator()(const ConnInfo& ci) const
{
std::size_t hash;
hash =
(ci.inc.inc_fibnum << 11) ^
ci.inc.inc_ie.ie_laddr.s_addr ^
ci.inc.inc_ie.ie_lport ^
ci.inc.inc_ie.ie_faddr.s_addr ^
ci.inc.inc_ie.ie_fport;
hash ^= uinet_l2tagstack_hash(&ci.l2i.inl2i_tagstack);
return (hash);
}
};
LogHandle log_;
SocketUinetPromisc *listen_socket_;
Mutex mtx_;
Action *action_;
unsigned int inbound_cdom_;
unsigned int outbound_cdom_;
SocketUinetPromisc::SynfilterCallback *synfilter_callback_;
std::tr1::unordered_map<ConnInfo,SpliceInfo,ConnInfoHasher> connections_;
public:
Listener(const std::string& where, unsigned int inbound_cdom, unsigned int outbound_cdom)
: log_("/listener"),
mtx_("Listener"),
action_(NULL),
inbound_cdom_(inbound_cdom),
outbound_cdom_(outbound_cdom)
{
synfilter_callback_ = callback(this, &Listener::synfilter);
listen_socket_ = SocketUinetPromisc::create(SocketAddressFamilyIPv4, SocketTypeStream, "tcp", "", inbound_cdom_);
if (listen_socket_ == NULL)
return;
listen_socket_->setsynfilter(synfilter_callback_);
if (0 != listen_socket_->setl2info2(NULL, NULL, UINET_INL2I_TAG_ANY, NULL))
return;
if (!listen_socket_->bind(where))
return;
if (!listen_socket_->listen())
return;
{
ScopedLock _(&mtx_);
SocketEventCallback *cb = callback(this, &Listener::accept_complete);
action_ = listen_socket_->accept(cb);
}
}
~Listener()
{
ScopedLock _(&mtx_);
if (action_ != NULL)
action_->cancel();
action_ = NULL;
if (listen_socket_ != NULL)
delete listen_socket_;
listen_socket_ = NULL;
}
/*
* This will get invoked for every SYN received on listen_socket_.
* The connection details for the SYN are tracked in the
* connections_ table for two reasons. The first is that we only
* want to take action (that is, open an outbound connection to the
* destination) for a given SYN once, not each time it may be
* retransmitted. The second is that when a SYN is accepted by the
* filter, the stack then processes it in the normal path, resulting
* in a subsequent accept, and that accept has to be able to locate
* the outbound connection made by the filter and associate it with
* the inbound connection being accepted. There is no way to pass
* any context to that subsequent accept from this syn filter
* through the stack (because, syncookies).
*/
void synfilter(SocketUinetPromisc::SynfilterCallbackParam param)
{
ScopedLock _(&mtx_);
ConnInfo ci;
ci.inc = *param.inc;
ci.l2i = *param.l2i;
if (connections_.find(ci) == connections_.end()) {
struct uinet_in_l2info *l2i = param.l2i;
SpliceInfo& si = connections_[ci];
si.conninfo = ci;
/*
* Get deferral context for the SYN filter result.
*/
si.deferral = listen_socket_->synfdefer(param.cookie);
/*
* Set up outbound connection.
*/
si.inbound = NULL;
si.outbound = SocketUinetPromisc::create(SocketAddressFamilyIPv4, SocketTypeStream, "tcp", "", outbound_cdom_);
if (NULL == si.outbound)
goto out;
/*
* Use the L2 details of the foreign host that sent this SYN.
*/
si.outbound->setl2info2(l2i->inl2i_foreign_addr, l2i->inl2i_local_addr,
l2i->inl2i_flags, &l2i->inl2i_tagstack);
/*
* Use the IP address and port number of the foreign
* host that sent this SYN.
*/
/* XXX perhaps resolver could support us a bit better here */
socket_address addr1;
addr1.addrlen_ = sizeof(struct sockaddr_in);
/* XXX */
#if !defined(__linux__)
addr1.addr_.inet_.sin_len = addr1.addlen_;
#endif
addr1.addr_.inet_.sin_family = AF_INET;
addr1.addr_.inet_.sin_port = ci.inc.inc_ie.ie_fport;
addr1.addr_.inet_.sin_addr.s_addr = ci.inc.inc_ie.ie_faddr.s_addr;
si.outbound->bind(addr1);
/*
* Connect to the same IP address and port number
* that the foreign host that sent this SYN is
* trying to connect to. On connection completion,
* the deferred SYN filter decision will be
* delivered. Once the deferred decision is
* delivered, and if it is UINET_SYNF_ACCEPT, the
* accept for the original inbound connection will
* complete.
*/
EventCallback *cb = callback(this, &Listener::connect_complete, ci);
socket_address addr2;
addr2.addrlen_ = sizeof(struct sockaddr_in);
/* XXX */
#if !defined(__linux__)
addr2.addr_.inet_.sin_len = addr2.addlen_;
#endif
addr2.addr_.inet_.sin_family = AF_INET;
addr2.addr_.inet_.sin_port = ci.inc.inc_ie.ie_lport;
addr2.addr_.inet_.sin_addr.s_addr = ci.inc.inc_ie.ie_laddr.s_addr;
si.connect_action = si.outbound->connect(addr2, cb);
DEBUG(log_) << "Outbound from " << (std::string)addr1 << " to " << (std::string)addr2;
*param.result = UINET_SYNF_DEFER;
return;
}
out:
*param.result = UINET_SYNF_REJECT;
}
void accept_complete(Event e, Socket *socket)
{
ScopedLock _(&mtx_);
action_->cancel();
action_ = NULL;
switch (e.type_) {
case Event::Done: {
DEBUG(log_) << "Inbound from " << socket->getpeername() << " to " << socket->getsockname();
SocketUinetPromisc *promisc = (SocketUinetPromisc *)socket;
ConnInfo ci;
promisc->getconninfo(&ci.inc);
promisc->getl2info(&ci.l2i);
SpliceInfo& si = connections_[ci];
si.inbound = promisc;
si.splice_inbound = new Splice(log_ + "/inbound", si.inbound, NULL, si.outbound);
si.splice_outbound = new Splice(log_ + "/outbound", si.outbound, NULL, si.inbound);
si.splice_pair = new SplicePair(si.splice_inbound, si.splice_outbound);
EventCallback *cb = callback(this, &Listener::splice_complete, ci);
si.splice_action = si.splice_pair->start(cb);
break;
}
default:
ERROR(log_) << "Unexpected event: " << e;
return;
}
SocketEventCallback *cb = callback(this, &Listener::accept_complete);
action_ = listen_socket_->accept(cb);
}
void connect_complete(Event e, ConnInfo ci)
{
ScopedLock _(&mtx_);
SpliceInfo& si = connections_[ci];
si.connect_action->cancel();
si.connect_action = NULL;
switch (e.type_) {
case Event::Done:
listen_socket_->synfdeferraldeliver(si.deferral, UINET_SYNF_ACCEPT);
break;
default:
connections_.erase(ci);
listen_socket_->synfdeferraldeliver(si.deferral, UINET_SYNF_REJECT);
/* XXX Close socket? */
ERROR(log_) << "Unexpected event: " << e;
break;
}
}
void splice_complete(Event e, ConnInfo ci)
{
ScopedLock _(&mtx_);
SpliceInfo& si = connections_[ci];
si.splice_action->cancel();
si.splice_action = NULL;
switch (e.type_) {
case Event::Done:
break;
default:
ERROR(log_) << "Splice exiting unexpectedly: " << e;
break;
}
ASSERT(log_, si.splice_pair != NULL);
delete si.splice_pair;
si.splice_pair = NULL;
ASSERT(log_, si.splice_inbound != NULL);
delete si.splice_inbound;
si.splice_inbound = NULL;
ASSERT(log_, si.splice_outbound != NULL);
delete si.splice_outbound;
si.splice_outbound = NULL;
SimpleCallback *cb = callback(this, &Listener::close_complete, ci);
si.close_action = si.outbound->close(cb);
}
void close_complete(ConnInfo ci)
{
ScopedLock _(&mtx_);
SpliceInfo& si = connections_[ci];
si.close_action->cancel();
si.close_action = NULL;
if (si.outbound != NULL) {
delete si.outbound;
si.outbound = NULL;
SimpleCallback *cb = callback(this, &Listener::close_complete, ci);
si.close_action = si.inbound->close(cb);
return;
}
delete si.inbound;
si.inbound = NULL;
connections_.erase(ci);
}
};
int
main(void)
{
IOUinet::instance()->start(false);
IOUinet::instance()->add_interface(UINET_IFTYPE_NETMAP, "vale0:1", "proxy-a-side", 1, -1);
IOUinet::instance()->interface_up("proxy-a-side", true);
IOUinet::instance()->add_interface(UINET_IFTYPE_NETMAP, "vale1:1", "proxy-b-side", 2, -1);
IOUinet::instance()->interface_up("proxy-b-side", true);
Listener *l = new Listener("[0.0.0.0]:0", 1, 2);
event_main();
#if notquiteyet
IOUinet::instance()->remove_interface("proxy-a-side");
IOUinet::instance()->remove_interface("proxy-b-side");
#endif
delete l;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <functional>
#include <memory>
#include <atomic>
#include <cmath>
#include "integration_test_helper.h"
#include "dronecore.h"
#include "plugins/telemetry/telemetry.h"
#include "plugins/action/action.h"
#include "plugins/gimbal/gimbal.h"
#include "plugins/offboard/offboard.h"
using namespace dronecore;
void send_new_gimbal_command(std::shared_ptr<Gimbal> gimbal, int i);
void send_gimbal_roi_location(std::shared_ptr<Gimbal> gimbal, double latitude_deg,
double longitude_deg, float altitude_m);
void receive_gimbal_result(Gimbal::Result result);
void receive_gimbal_attitude_euler_angles(Telemetry::EulerAngle euler_angle);
TEST_F(SitlTest, GimbalMove)
{
DroneCore dc;
ConnectionResult ret = dc.add_udp_connection();
ASSERT_EQ(ret, ConnectionResult::SUCCESS);
// Wait for device to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
Device &device = dc.device();
auto telemetry = std::make_shared<Telemetry>(device);
auto gimbal = std::make_shared<Gimbal>(device);
telemetry->set_rate_camera_attitude(10.0);
telemetry->camera_attitude_euler_angle_async(
&receive_gimbal_attitude_euler_angles);
for (int i = 0; i < 500; i += 1) {
send_new_gimbal_command(gimbal, i);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
TEST_F(SitlTest, GimbalTakeoffAndMove)
{
DroneCore dc;
ConnectionResult ret = dc.add_udp_connection();
ASSERT_EQ(ret, ConnectionResult::SUCCESS);
// Wait for device to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
Device &device = dc.device();
auto telemetry = std::make_shared<Telemetry>(device);
auto gimbal = std::make_shared<Gimbal>(device);
auto action = std::make_shared<Action>(device);
while (!telemetry->health_all_ok()) {
LogInfo() << "waiting for device to be ready";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
Action::Result action_result = action->arm();
EXPECT_EQ(action_result, Action::Result::SUCCESS);
action_result = action->takeoff();
EXPECT_EQ(action_result, Action::Result::SUCCESS);
telemetry->set_rate_camera_attitude(10.0);
telemetry->camera_attitude_euler_angle_async(
&receive_gimbal_attitude_euler_angles);
for (int i = 0; i < 500; i += 1) {
send_new_gimbal_command(gimbal, i);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
action->land();
std::this_thread::sleep_for(std::chrono::seconds(3));
}
TEST_F(SitlTest, GimbalROIOffboard)
{
DroneCore dc;
ConnectionResult ret = dc.add_udp_connection();
ASSERT_EQ(ret, ConnectionResult::SUCCESS);
// Wait for device to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
Device &device = dc.device();
auto telemetry = std::make_shared<Telemetry>(device);
auto gimbal = std::make_shared<Gimbal>(device);
auto action = std::make_shared<Action>(device);
auto offboard = std::make_shared<Offboard>(device);
while (!telemetry->health_all_ok()) {
LogInfo() << "waiting for device to be ready";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
const Telemetry::Position &position = telemetry->position();
// set the ROI location: a bit to the north of the vehicle's location
const double latitude_offset_deg = 3. / 111111.; // this is about 3 m
send_gimbal_roi_location(gimbal, position.latitude_deg + latitude_offset_deg,
position.longitude_deg, position.absolute_altitude_m + 1.f);
Action::Result action_result = action->arm();
EXPECT_EQ(action_result, Action::Result::SUCCESS);
action_result = action->takeoff();
EXPECT_EQ(action_result, Action::Result::SUCCESS);
std::this_thread::sleep_for(std::chrono::seconds(5));
telemetry->set_rate_camera_attitude(10.0);
telemetry->camera_attitude_euler_angle_async(
&receive_gimbal_attitude_euler_angles);
// Send it once before starting offboard, otherwise it will be rejected.
offboard->set_velocity_ned({0.0f, 0.0f, 0.0f, 0.0f});
Offboard::Result offboard_result = offboard->start();
EXPECT_EQ(offboard_result, Offboard::Result::SUCCESS);
auto fly_straight = [&offboard](int step_count, float max_speed) {
for (int i = 0; i < step_count; ++i) {
int k = (i <= step_count / 2) ? i : step_count - i;
float vy = static_cast<float>(k) / (step_count / 2) * max_speed;
offboard->set_velocity_ned({0.0f, vy, 0.0f, 90.0f});
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
};
// fly east for a bit
fly_straight(300, 2.f);
// fly in north-south direction (back & forth a few times)
const float step_size = 0.01f;
const float one_cycle = 2.0f * M_PI_F;
const unsigned steps = static_cast<unsigned>(2.5f * one_cycle / step_size);
for (unsigned i = 0; i < steps; ++i) {
float vx = 5.0f * sinf(i * step_size);
offboard->set_velocity_ned({vx, 0.0f, 0.0f, 90.0f});
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// fly west for a bit
fly_straight(600, -4.f);
action->land();
std::this_thread::sleep_for(std::chrono::seconds(3));
}
void send_new_gimbal_command(std::shared_ptr<Gimbal> gimbal, int i)
{
float pitch_deg = 30.0f * cosf(i / 360.0f * 2 * M_PI_F);
float yaw_deg = 45.0f * sinf(i / 360.0f * 2 * M_PI_F);
gimbal->set_pitch_and_yaw_async(pitch_deg, yaw_deg, &receive_gimbal_result);
}
void send_gimbal_roi_location(std::shared_ptr<Gimbal> gimbal, double latitude_deg,
double longitude_deg, float altitude_m)
{
gimbal->set_roi_location_async(latitude_deg, longitude_deg, altitude_m,
&receive_gimbal_result);
}
void receive_gimbal_result(Gimbal::Result result)
{
EXPECT_EQ(result, Gimbal::Result::SUCCESS);
}
void receive_gimbal_attitude_euler_angles(Telemetry::EulerAngle euler_angle)
{
LogInfo() << "Received gimbal attitude: "
<< euler_angle.roll_deg << ", "
<< euler_angle.pitch_deg << ", "
<< euler_angle.yaw_deg;
}
<commit_msg>integration_tests: fix build<commit_after>#include <atomic>
#include <cmath>
#include <functional>
#include <iostream>
#include <memory>
#include "dronecore.h"
#include "integration_test_helper.h"
#include "plugins/action/action.h"
#include "plugins/action/action_result.h"
#include "plugins/gimbal/gimbal.h"
#include "plugins/offboard/offboard.h"
#include "plugins/telemetry/telemetry.h"
using namespace dronecore;
void send_new_gimbal_command(std::shared_ptr<Gimbal> gimbal, int i);
void send_gimbal_roi_location(std::shared_ptr<Gimbal> gimbal, double latitude_deg,
double longitude_deg, float altitude_m);
void receive_gimbal_result(Gimbal::Result result);
void receive_gimbal_attitude_euler_angles(Telemetry::EulerAngle euler_angle);
TEST_F(SitlTest, GimbalMove)
{
DroneCore dc;
ConnectionResult ret = dc.add_udp_connection();
ASSERT_EQ(ret, ConnectionResult::SUCCESS);
// Wait for device to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
Device &device = dc.device();
auto telemetry = std::make_shared<Telemetry>(device);
auto gimbal = std::make_shared<Gimbal>(device);
telemetry->set_rate_camera_attitude(10.0);
telemetry->camera_attitude_euler_angle_async(
&receive_gimbal_attitude_euler_angles);
for (int i = 0; i < 500; i += 1) {
send_new_gimbal_command(gimbal, i);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
TEST_F(SitlTest, GimbalTakeoffAndMove)
{
DroneCore dc;
ConnectionResult ret = dc.add_udp_connection();
ASSERT_EQ(ret, ConnectionResult::SUCCESS);
// Wait for device to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
Device &device = dc.device();
auto telemetry = std::make_shared<Telemetry>(device);
auto gimbal = std::make_shared<Gimbal>(device);
auto action = std::make_shared<Action>(device);
while (!telemetry->health_all_ok()) {
LogInfo() << "waiting for device to be ready";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
ActionResult action_result = action->arm();
EXPECT_EQ(action_result, ActionResult::SUCCESS);
action_result = action->takeoff();
EXPECT_EQ(action_result, ActionResult::SUCCESS);
telemetry->set_rate_camera_attitude(10.0);
telemetry->camera_attitude_euler_angle_async(
&receive_gimbal_attitude_euler_angles);
for (int i = 0; i < 500; i += 1) {
send_new_gimbal_command(gimbal, i);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
action->land();
std::this_thread::sleep_for(std::chrono::seconds(3));
}
TEST_F(SitlTest, GimbalROIOffboard)
{
DroneCore dc;
ConnectionResult ret = dc.add_udp_connection();
ASSERT_EQ(ret, ConnectionResult::SUCCESS);
// Wait for device to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
Device &device = dc.device();
auto telemetry = std::make_shared<Telemetry>(device);
auto gimbal = std::make_shared<Gimbal>(device);
auto action = std::make_shared<Action>(device);
auto offboard = std::make_shared<Offboard>(device);
while (!telemetry->health_all_ok()) {
LogInfo() << "waiting for device to be ready";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
const Telemetry::Position &position = telemetry->position();
// set the ROI location: a bit to the north of the vehicle's location
const double latitude_offset_deg = 3. / 111111.; // this is about 3 m
send_gimbal_roi_location(gimbal, position.latitude_deg + latitude_offset_deg,
position.longitude_deg, position.absolute_altitude_m + 1.f);
ActionResult action_result = action->arm();
EXPECT_EQ(action_result, ActionResult::SUCCESS);
action_result = action->takeoff();
EXPECT_EQ(action_result, ActionResult::SUCCESS);
std::this_thread::sleep_for(std::chrono::seconds(5));
telemetry->set_rate_camera_attitude(10.0);
telemetry->camera_attitude_euler_angle_async(
&receive_gimbal_attitude_euler_angles);
// Send it once before starting offboard, otherwise it will be rejected.
offboard->set_velocity_ned({0.0f, 0.0f, 0.0f, 0.0f});
Offboard::Result offboard_result = offboard->start();
EXPECT_EQ(offboard_result, Offboard::Result::SUCCESS);
auto fly_straight = [&offboard](int step_count, float max_speed) {
for (int i = 0; i < step_count; ++i) {
int k = (i <= step_count / 2) ? i : step_count - i;
float vy = static_cast<float>(k) / (step_count / 2) * max_speed;
offboard->set_velocity_ned({0.0f, vy, 0.0f, 90.0f});
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
};
// fly east for a bit
fly_straight(300, 2.f);
// fly in north-south direction (back & forth a few times)
const float step_size = 0.01f;
const float one_cycle = 2.0f * M_PI_F;
const unsigned steps = static_cast<unsigned>(2.5f * one_cycle / step_size);
for (unsigned i = 0; i < steps; ++i) {
float vx = 5.0f * sinf(i * step_size);
offboard->set_velocity_ned({vx, 0.0f, 0.0f, 90.0f});
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// fly west for a bit
fly_straight(600, -4.f);
action->land();
std::this_thread::sleep_for(std::chrono::seconds(3));
}
void send_new_gimbal_command(std::shared_ptr<Gimbal> gimbal, int i)
{
float pitch_deg = 30.0f * cosf(i / 360.0f * 2 * M_PI_F);
float yaw_deg = 45.0f * sinf(i / 360.0f * 2 * M_PI_F);
gimbal->set_pitch_and_yaw_async(pitch_deg, yaw_deg, &receive_gimbal_result);
}
void send_gimbal_roi_location(std::shared_ptr<Gimbal> gimbal, double latitude_deg,
double longitude_deg, float altitude_m)
{
gimbal->set_roi_location_async(latitude_deg, longitude_deg, altitude_m,
&receive_gimbal_result);
}
void receive_gimbal_result(Gimbal::Result result)
{
EXPECT_EQ(result, Gimbal::Result::SUCCESS);
}
void receive_gimbal_attitude_euler_angles(Telemetry::EulerAngle euler_angle)
{
LogInfo() << "Received gimbal attitude: "
<< euler_angle.roll_deg << ", "
<< euler_angle.pitch_deg << ", "
<< euler_angle.yaw_deg;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageWrapPad.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageWrapPad.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
vtkCxxRevisionMacro(vtkImageWrapPad, "1.30");
vtkStandardNewMacro(vtkImageWrapPad);
//----------------------------------------------------------------------------
// Just clip the request.
void vtkImageWrapPad::ComputeInputUpdateExtent (int inExt[6], int outExt[6],
int wholeExtent[6])
{
int idx;
int min, max, width, imageMin, imageMax, imageWidth;
// Clip
for (idx = 0; idx < 3; ++idx)
{
min = outExt[idx * 2];
max = outExt[idx * 2 + 1];
imageMin = wholeExtent[idx * 2];
imageMax = wholeExtent[idx * 2 + 1];
if (min > max || imageMin > imageMax)
{ // Empty output request.
inExt[0] = inExt[2] = inExt[4] = 0;
inExt[1] = inExt[3] = inExt[5] = -1;
return;
}
width = max - min + 1;
imageWidth = imageMax - imageMin + 1;
// convert min max to image extent range.
min = ((min - imageMin) % imageWidth);
if (min < 0)
{ // Mod does not handle negative numbers as I think it should.
min += imageWidth;
}
min += imageMin;
max = min + width - 1;
// if request region wraps, we need the whole input
// (unless we make multiple requests! Write Update instead??)
if (max > imageMax)
{
max = imageMax;
min = imageMin;
}
inExt[idx * 2] = min;
inExt[idx * 2 + 1] = max;
}
}
//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
template <class T>
void vtkImageWrapPadExecute(vtkImageWrapPad *self,
vtkImageData *inData, T *vtkNotUsed(inPtr),
vtkImageData *outData, T *outPtr,
int outExt[6], int id)
{
int min0, max0;
int imageMin0, imageMax0, imageMin1, imageMax1,
imageMin2, imageMax2;
int outIdx0, outIdx1, outIdx2;
int start0, start1, start2;
int inIdx0, inIdx1, inIdx2;
int inInc0, inInc1, inInc2;
int outIncX, outIncY, outIncZ;
T *inPtr0, *inPtr1, *inPtr2;
unsigned long count = 0;
unsigned long target;
int inMaxC, idxC, maxC;
// Get information to march through data
inData->GetIncrements(inInc0, inInc1, inInc2);
inData->GetWholeExtent(imageMin0, imageMax0, imageMin1, imageMax1,
imageMin2, imageMax2);
outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);
// initialize pointers to coresponding pixels.
start0 = ((outExt[0] - imageMin0) % (imageMax0-imageMin0+1)) + imageMin0;
if (start0 < 0)
{
start0 += (imageMax0-imageMin0+1);
}
start1 = ((outExt[2] - imageMin1) % (imageMax1-imageMin1+1)) + imageMin1;
if (start1 < 0)
{
start1 += (imageMax1-imageMin1+1);
}
start2 = ((outExt[4] - imageMin2) % (imageMax2-imageMin2+1)) + imageMin2;
if (start2 < 0)
{
start2 += (imageMax2-imageMin2+1);
}
inPtr2 = (T *)(inData->GetScalarPointer(start0, start1, start2));
min0 = outExt[0];
max0 = outExt[1];
inMaxC = inData->GetNumberOfScalarComponents();
maxC = outData->GetNumberOfScalarComponents();
target = (unsigned long)((outExt[5]-outExt[4]+1)*
(outExt[3]-outExt[2]+1)/50.0);
target++;
inIdx2 = start2;
for (outIdx2 = outExt[4]; outIdx2 <= outExt[5]; ++outIdx2, ++inIdx2)
{
if (inIdx2 > imageMax2)
{ // we need to wrap(rewind) the input on this axis
inIdx2 = imageMin2;
inPtr2 -= (imageMax2-imageMin2+1)*inInc2;
}
inPtr1 = inPtr2;
inIdx1 = start1;
for (outIdx1 = outExt[2];
!self->AbortExecute && outIdx1 <= outExt[3]; ++outIdx1, ++inIdx1)
{
if (!id)
{
if (!(count%target))
{
self->UpdateProgress(count/(50.0*target));
}
count++;
}
if (inIdx1 > imageMax1)
{ // we need to wrap(rewind) the input on this axis
inIdx1 = imageMin1;
inPtr1 -= (imageMax1-imageMin1+1)*inInc1;
}
inPtr0 = inPtr1;
inIdx0 = start0;
// if components are same much faster
if ((maxC == inMaxC) && (maxC == 1))
{
for (outIdx0 = min0; outIdx0 <= max0; ++outIdx0, ++inIdx0)
{
if (inIdx0 > imageMax0)
{ // we need to wrap(rewind) the input on this axis
inIdx0 = imageMin0;
inPtr0 -= (imageMax0-imageMin0+1)*inInc0;
}
// Copy Pixel
*outPtr = *inPtr0;
outPtr++; inPtr0++;
}
}
else
{
for (outIdx0 = min0; outIdx0 <= max0; ++outIdx0, ++inIdx0)
{
if (inIdx0 > imageMax0)
{ // we need to wrap(rewind) the input on this axis
inIdx0 = imageMin0;
inPtr0 -= (imageMax0-imageMin0+1)*inInc0;
}
for (idxC = 0; idxC < maxC; idxC++)
{
// Copy Pixel
*outPtr = inPtr0[idxC%inMaxC];
outPtr++;
}
inPtr0 += inInc0;
}
}
outPtr += outIncY;
inPtr1 += inInc1;
}
outPtr += outIncZ;
inPtr2 += inInc2;
}
}
//----------------------------------------------------------------------------
// This method is passed a input and output data, and executes the filter
// algorithm to fill the output from the input.
// It just executes a switch statement to call the correct function for
// the regions data types.
void vtkImageWrapPad::ThreadedRequestData (
vtkInformation * vtkNotUsed( request ),
vtkInformationVector** inputVector,
vtkInformationVector * vtkNotUsed( outputVector ),
vtkImageData ***inData,
vtkImageData **outData,
int outExt[6], int id)
{
int inExt[6];
// get the whole extent
int wExt[6];
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(),wExt);
this->ComputeInputUpdateExtent(inExt,outExt,wExt);
void *inPtr = inData[0][0]->GetScalarPointerForExtent(inExt);
void *outPtr = outData[0]->GetScalarPointerForExtent(outExt);
vtkDebugMacro(<< "Execute: inData = " << inData[0][0]
<< ", outData = " << outData[0]);
// this filter expects that input is the same type as output.
if (inData[0][0]->GetScalarType() != outData[0]->GetScalarType())
{
vtkErrorMacro(<< "Execute: input ScalarType, "
<< inData[0][0]->GetScalarType()
<< ", must match out ScalarType "
<< outData[0]->GetScalarType());
return;
}
switch (inData[0][0]->GetScalarType())
{
vtkTemplateMacro7(vtkImageWrapPadExecute, this, inData[0][0],
(VTK_TT *)inPtr, outData[0],
(VTK_TT *)(outPtr), outExt, id);
default:
vtkErrorMacro(<< "Execute: Unknown ScalarType");
return;
}
}
<commit_msg>ENH: fix for possible infinite loop<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageWrapPad.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageWrapPad.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
vtkCxxRevisionMacro(vtkImageWrapPad, "1.31");
vtkStandardNewMacro(vtkImageWrapPad);
//----------------------------------------------------------------------------
// Just clip the request.
void vtkImageWrapPad::ComputeInputUpdateExtent (int inExt[6], int outExt[6],
int wholeExtent[6])
{
int idx;
int min, max, width, imageMin, imageMax, imageWidth;
// Clip
for (idx = 0; idx < 3; ++idx)
{
min = outExt[idx * 2];
max = outExt[idx * 2 + 1];
imageMin = wholeExtent[idx * 2];
imageMax = wholeExtent[idx * 2 + 1];
if (min > max || imageMin > imageMax)
{ // Empty output request.
inExt[0] = inExt[2] = inExt[4] = 0;
inExt[1] = inExt[3] = inExt[5] = -1;
return;
}
width = max - min + 1;
imageWidth = imageMax - imageMin + 1;
// convert min max to image extent range.
min = ((min - imageMin) % imageWidth);
if (min < 0)
{ // Mod does not handle negative numbers as I think it should.
min += imageWidth;
}
min += imageMin;
max = min + width - 1;
// if request region wraps, we need the whole input
// (unless we make multiple requests! Write Update instead??)
if (max > imageMax)
{
max = imageMax;
min = imageMin;
}
inExt[idx * 2] = min;
inExt[idx * 2 + 1] = max;
}
}
//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
template <class T>
void vtkImageWrapPadExecute(vtkImageWrapPad *self,
vtkImageData *inData, T *vtkNotUsed(inPtr),
vtkImageData *outData, T *outPtr,
int outExt[6], int id)
{
int min0, max0;
int imageMin0, imageMax0, imageMin1, imageMax1,
imageMin2, imageMax2;
int outIdx0, outIdx1, outIdx2;
int start0, start1, start2;
int inIdx0, inIdx1, inIdx2;
int inInc0, inInc1, inInc2;
int outIncX, outIncY, outIncZ;
T *inPtr0, *inPtr1, *inPtr2;
unsigned long count = 0;
unsigned long target;
int inMaxC, idxC, maxC;
// Get information to march through data
inData->GetIncrements(inInc0, inInc1, inInc2);
inData->GetWholeExtent(imageMin0, imageMax0, imageMin1, imageMax1,
imageMin2, imageMax2);
outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);
// initialize pointers to coresponding pixels.
start0 = ((outExt[0] - imageMin0) % (imageMax0-imageMin0+1)) + imageMin0;
if (start0 < 0)
{
start0 += (imageMax0-imageMin0+1);
}
start1 = ((outExt[2] - imageMin1) % (imageMax1-imageMin1+1)) + imageMin1;
if (start1 < 0)
{
start1 += (imageMax1-imageMin1+1);
}
start2 = ((outExt[4] - imageMin2) % (imageMax2-imageMin2+1)) + imageMin2;
if (start2 < 0)
{
start2 += (imageMax2-imageMin2+1);
}
inPtr2 = (T *)(inData->GetScalarPointer(start0, start1, start2));
min0 = outExt[0];
max0 = outExt[1];
inMaxC = inData->GetNumberOfScalarComponents();
maxC = outData->GetNumberOfScalarComponents();
target = (unsigned long)((outExt[5]-outExt[4]+1)*
(outExt[3]-outExt[2]+1)/50.0);
target++;
inIdx2 = start2;
for (outIdx2 = outExt[4]; outIdx2 <= outExt[5]; ++outIdx2, ++inIdx2)
{
if (inIdx2 > imageMax2)
{ // we need to wrap(rewind) the input on this axis
inIdx2 = imageMin2;
inPtr2 -= (imageMax2-imageMin2+1)*inInc2;
}
inPtr1 = inPtr2;
inIdx1 = start1;
for (outIdx1 = outExt[2];
!self->AbortExecute && outIdx1 <= outExt[3]; ++outIdx1, ++inIdx1)
{
if (!id)
{
if (!(count%target))
{
self->UpdateProgress(count/(50.0*target));
}
count++;
}
if (inIdx1 > imageMax1)
{ // we need to wrap(rewind) the input on this axis
inIdx1 = imageMin1;
inPtr1 -= (imageMax1-imageMin1+1)*inInc1;
}
inPtr0 = inPtr1;
inIdx0 = start0;
// if components are same much faster
if ((maxC == inMaxC) && (maxC == 1))
{
for (outIdx0 = min0; outIdx0 <= max0; ++outIdx0, ++inIdx0)
{
if (inIdx0 > imageMax0)
{ // we need to wrap(rewind) the input on this axis
inIdx0 = imageMin0;
inPtr0 -= (imageMax0-imageMin0+1)*inInc0;
}
// Copy Pixel
*outPtr = *inPtr0;
outPtr++; inPtr0++;
}
}
else
{
for (outIdx0 = min0; outIdx0 <= max0; ++outIdx0, ++inIdx0)
{
if (inIdx0 > imageMax0)
{ // we need to wrap(rewind) the input on this axis
inIdx0 = imageMin0;
inPtr0 -= (imageMax0-imageMin0+1)*inInc0;
}
for (idxC = 0; idxC < maxC; idxC++)
{
// Copy Pixel
*outPtr = inPtr0[idxC%inMaxC];
outPtr++;
}
inPtr0 += inInc0;
}
}
outPtr += outIncY;
inPtr1 += inInc1;
}
outPtr += outIncZ;
inPtr2 += inInc2;
}
}
//----------------------------------------------------------------------------
// This method is passed a input and output data, and executes the filter
// algorithm to fill the output from the input.
// It just executes a switch statement to call the correct function for
// the regions data types.
void vtkImageWrapPad::ThreadedRequestData (
vtkInformation * vtkNotUsed( request ),
vtkInformationVector** inputVector,
vtkInformationVector * vtkNotUsed( outputVector ),
vtkImageData ***inData,
vtkImageData **outData,
int outExt[6], int id)
{
// return if nothing to do
if (outExt[1] < outExt[0] ||
outExt[3] < outExt[2] ||
outExt[5] < outExt[4])
{
return;
}
int inExt[6];
// get the whole extent
int wExt[6];
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(),wExt);
this->ComputeInputUpdateExtent(inExt,outExt,wExt);
void *inPtr = inData[0][0]->GetScalarPointerForExtent(inExt);
void *outPtr = outData[0]->GetScalarPointerForExtent(outExt);
vtkDebugMacro(<< "Execute: inData = " << inData[0][0]
<< ", outData = " << outData[0]);
// this filter expects that input is the same type as output.
if (inData[0][0]->GetScalarType() != outData[0]->GetScalarType())
{
vtkErrorMacro(<< "Execute: input ScalarType, "
<< inData[0][0]->GetScalarType()
<< ", must match out ScalarType "
<< outData[0]->GetScalarType());
return;
}
switch (inData[0][0]->GetScalarType())
{
vtkTemplateMacro7(vtkImageWrapPadExecute, this, inData[0][0],
(VTK_TT *)inPtr, outData[0],
(VTK_TT *)(outPtr), outExt, id);
default:
vtkErrorMacro(<< "Execute: Unknown ScalarType");
return;
}
}
<|endoftext|> |
<commit_before>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// 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/pipelines/localization/SfM_Localizer.hpp"
#include "openMVG/cameras/Camera_Common.hpp"
#include "openMVG/cameras/Camera_Intrinsics.hpp"
#include "openMVG/cameras/Camera_Pinhole.hpp"
#include "openMVG/multiview/solver_resection_kernel.hpp"
#include "openMVG/multiview/solver_resection_p3p.hpp"
#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/sfm/sfm_data_BA.hpp"
#include "openMVG/sfm/sfm_data_BA_ceres.hpp"
#include "openMVG/sfm/sfm_landmark.hpp"
#include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp"
#include "openMVG/robust_estimation/robust_estimator_ACRansacKernelAdaptator.hpp"
#include <memory>
#include <utility>
namespace openMVG
{
/// Pose/Resection Kernel adapter for the A contrario model estimator with
/// known camera intrinsics.
template <typename SolverArg,
typename ModelArg = Mat34>
class ACKernelAdaptorResection_Intrinsics
{
public:
using Solver = SolverArg;
using Model = ModelArg;
ACKernelAdaptorResection_Intrinsics
(
const Mat & x2d, // Undistorted 2d feature_point location
const Mat & x3D, // 3D corresponding points
const cameras::IntrinsicBase * camera
):x2d_(x2d),
x3D_(x3D),
logalpha0_(log10(M_PI)),
N1_(Mat3::Identity()),
camera_(camera)
{
N1_.diagonal().head(2) *= camera->imagePlane_toCameraPlaneError(1.0);
assert(2 == x2d_.rows());
assert(3 == x3D_.rows());
assert(x2d_.cols() == x3D_.cols());
bearing_vectors_= camera->operator()(x2d_);
}
enum { MINIMUM_SAMPLES = Solver::MINIMUM_SAMPLES };
enum { MAX_MODELS = Solver::MAX_MODELS };
void Fit(const std::vector<uint32_t> &samples, std::vector<Model> *models) const {
Solver::Solve(ExtractColumns(bearing_vectors_, samples), // bearing vectors
ExtractColumns(x3D_, samples), // 3D points
models); // Found model hypothesis
}
double Error(uint32_t sample, const Model &model) const {
const Vec3 t = model.block(0, 3, 3, 1);
const geometry::Pose3 pose(model.block(0, 0, 3, 3),
- model.block(0, 0, 3, 3).transpose() * t);
const bool ignore_distortion = true; // We ignore distortion since we are using undistorted bearing vector as input
return (camera_->residual(pose(x3D_.col(sample)),
x2d_.col(sample),
ignore_distortion) * N1_(0,0)).squaredNorm();
}
void Errors(const Model & model, std::vector<double> & vec_errors) const
{
const Vec3 t = model.block(0, 3, 3, 1);
const geometry::Pose3 pose(model.block(0, 0, 3, 3),
- model.block(0, 0, 3, 3).transpose() * t);
vec_errors.resize(x2d_.cols());
for (Mat::Index sample = 0; sample < x2d_.cols(); ++sample)
{
vec_errors[sample] = this->Error(sample, model);
}
}
size_t NumSamples() const { return x2d_.cols(); }
void Unnormalize(Model * model) const {
}
double logalpha0() const {return logalpha0_;}
double multError() const {return 1.0;} // point to point error
Mat3 normalizer1() const {return Mat3::Identity();}
Mat3 normalizer2() const {return N1_;}
double unormalizeError(double val) const {return sqrt(val) / N1_(0,0);}
private:
Mat x2d_, bearing_vectors_;
const Mat & x3D_;
Mat3 N1_;
double logalpha0_; // Alpha0 is used to make the error adaptive to the image size
const cameras::IntrinsicBase * camera_; // Intrinsic camera parameter
};
} // namespace openMVG
namespace openMVG {
namespace sfm {
struct ResectionSquaredResidualError {
// Compute the residual of the projection distance(pt2D, Project(P,pt3D))
// Return the squared error
static double Error(const Mat34 & P, const Vec2 & pt2D, const Vec3 & pt3D) {
const Vec2 x = Project(P, pt3D);
return (x - pt2D).squaredNorm();
}
};
bool SfM_Localizer::Localize
(
const resection::SolverType & solver_type,
const Pair & image_size,
const cameras::IntrinsicBase * optional_intrinsics,
Image_Localizer_Match_Data & resection_data,
geometry::Pose3 & pose
)
{
// --
// Compute the camera pose (resectioning)
// --
Mat34 P;
resection_data.vec_inliers.clear();
// Setup the admissible upper bound residual error
const double dPrecision =
resection_data.error_max == std::numeric_limits<double>::infinity() ?
std::numeric_limits<double>::infinity() :
Square(resection_data.error_max);
size_t MINIMUM_SAMPLES = 0;
switch (solver_type)
{
case resection::SolverType::DLT_6POINTS:
{
//--
// Classic resection (try to compute the entire P matrix)
using SolverType = openMVG::resection::kernel::SixPointResectionSolver;
MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;
using KernelType =
openMVG::robust::ACKernelAdaptorResection<
SolverType,
ResectionSquaredResidualError,
openMVG::robust::UnnormalizerResection,
Mat34>;
KernelType kernel(resection_data.pt2D, image_size.first, image_size.second,
resection_data.pt3D);
// Robust estimation of the pose and its precision
const std::pair<double,double> ACRansacOut =
openMVG::robust::ACRANSAC(kernel,
resection_data.vec_inliers,
resection_data.max_iteration,
&P,
dPrecision,
true);
// Update the upper bound precision of the model found by AC-RANSAC
resection_data.error_max = ACRansacOut.first;
}
break;
case resection::SolverType::P3P_KE_CVPR17:
{
if (!optional_intrinsics)
{
std::cerr << "Intrinsic data is required for P3P solvers." << std::endl;
return false;
}
//--
// Since the intrinsic data is known, compute only the pose
using SolverType = openMVG::euclidean_resection::P3PSolver_Ke;
MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;
using KernelType =
ACKernelAdaptorResection_Intrinsics<
SolverType,
Mat34>;
KernelType kernel(resection_data.pt2D, resection_data.pt3D, optional_intrinsics);
// Robust estimation of the pose matrix and its precision
const auto ACRansacOut =
openMVG::robust::ACRANSAC(kernel,
resection_data.vec_inliers,
resection_data.max_iteration,
&P,
dPrecision,
true);
// Update the upper bound precision of the model found by AC-RANSAC
resection_data.error_max = ACRansacOut.first;
}
break;
case resection::SolverType::P3P_KNEIP_CVPR11:
{
if (!optional_intrinsics)
{
std::cerr << "Intrinsic data is required for P3P solvers." << std::endl;
return false;
}
//--
// Since the intrinsic data is known, compute only the pose
using SolverType = openMVG::euclidean_resection::P3PSolver_Kneip;
MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;
using KernelType =
ACKernelAdaptorResection_Intrinsics<
SolverType,
Mat34>;
KernelType kernel(resection_data.pt2D, resection_data.pt3D, optional_intrinsics);
// Robust estimation of the pose matrix and its precision
const auto ACRansacOut =
openMVG::robust::ACRANSAC(kernel,
resection_data.vec_inliers,
resection_data.max_iteration,
&P,
dPrecision,
true);
// Update the upper bound precision of the model found by AC-RANSAC
resection_data.error_max = ACRansacOut.first;
}
break;
default:
{
std::cerr << "Unknown absolute pose solver type." << std::endl;
return false;
}
}
// Test if the mode support some points (more than those required for estimation)
const bool bResection = (resection_data.vec_inliers.size() > 2.5 * MINIMUM_SAMPLES);
if (bResection)
{
resection_data.projection_matrix = P;
Mat3 K, R;
Vec3 t;
KRt_From_P(P, &K, &R, &t);
pose = geometry::Pose3(R, -R.transpose() * t);
}
std::cout << "\n"
<< "-------------------------------" << "\n"
<< "-- Robust Resection " << "\n"
<< "-- Resection status: " << bResection << "\n"
<< "-- #Points used for Resection: " << resection_data.pt2D.cols() << "\n"
<< "-- #Points validated by robust Resection: " << resection_data.vec_inliers.size() << "\n"
<< "-- Threshold: " << resection_data.error_max << "\n"
<< "-------------------------------" << std::endl;
return bResection;
}
bool SfM_Localizer::RefinePose
(
cameras::IntrinsicBase * intrinsics,
geometry::Pose3 & pose,
Image_Localizer_Match_Data & matching_data,
bool b_refine_pose,
bool b_refine_intrinsic
)
{
if (!b_refine_pose && !b_refine_intrinsic)
{
// Nothing to do (There is no parameter to refine)
return false;
}
// Setup a tiny SfM scene with the corresponding 2D-3D data
SfM_Data sfm_data;
// view
sfm_data.views.insert({0, std::make_shared<View>("",0, 0, 0)});
// pose
sfm_data.poses[0] = pose;
// intrinsic
std::shared_ptr<cameras::IntrinsicBase> shared_intrinsics(intrinsics->clone());
sfm_data.intrinsics[0] = shared_intrinsics;
// structure data (2D-3D correspondences)
for (size_t i = 0; i < matching_data.vec_inliers.size(); ++i)
{
const size_t idx = matching_data.vec_inliers[i];
Landmark landmark;
landmark.X = matching_data.pt3D.col(idx);
landmark.obs[0] = Observation(matching_data.pt2D.col(idx), UndefinedIndexT);
sfm_data.structure[i] = std::move(landmark);
}
// Configure BA options (refine the intrinsic and the pose parameter only if requested)
const Optimize_Options ba_refine_options
(
(b_refine_intrinsic) ? cameras::Intrinsic_Parameter_Type::ADJUST_ALL : cameras::Intrinsic_Parameter_Type::NONE,
(b_refine_pose) ? Extrinsic_Parameter_Type::ADJUST_ALL : Extrinsic_Parameter_Type::NONE,
Structure_Parameter_Type::NONE // STRUCTURE must remain constant
);
Bundle_Adjustment_Ceres bundle_adjustment_obj;
const bool b_BA_Status = bundle_adjustment_obj.Adjust(
sfm_data,
ba_refine_options);
if (b_BA_Status)
{
pose = sfm_data.poses[0];
if (b_refine_intrinsic)
*intrinsics = *shared_intrinsics;
}
return b_BA_Status;
}
} // namespace sfm
} // namespace openMVG
<commit_msg>[sfm] Corrected a problem with updating intrinsics after BA in localization mode. #1369<commit_after>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// 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/pipelines/localization/SfM_Localizer.hpp"
#include "openMVG/cameras/Camera_Common.hpp"
#include "openMVG/cameras/Camera_Intrinsics.hpp"
#include "openMVG/cameras/Camera_Pinhole.hpp"
#include "openMVG/multiview/solver_resection_kernel.hpp"
#include "openMVG/multiview/solver_resection_p3p.hpp"
#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/sfm/sfm_data_BA.hpp"
#include "openMVG/sfm/sfm_data_BA_ceres.hpp"
#include "openMVG/sfm/sfm_landmark.hpp"
#include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp"
#include "openMVG/robust_estimation/robust_estimator_ACRansacKernelAdaptator.hpp"
#include <memory>
#include <utility>
namespace openMVG
{
/// Pose/Resection Kernel adapter for the A contrario model estimator with
/// known camera intrinsics.
template <typename SolverArg,
typename ModelArg = Mat34>
class ACKernelAdaptorResection_Intrinsics
{
public:
using Solver = SolverArg;
using Model = ModelArg;
ACKernelAdaptorResection_Intrinsics
(
const Mat & x2d, // Undistorted 2d feature_point location
const Mat & x3D, // 3D corresponding points
const cameras::IntrinsicBase * camera
):x2d_(x2d),
x3D_(x3D),
logalpha0_(log10(M_PI)),
N1_(Mat3::Identity()),
camera_(camera)
{
N1_.diagonal().head(2) *= camera->imagePlane_toCameraPlaneError(1.0);
assert(2 == x2d_.rows());
assert(3 == x3D_.rows());
assert(x2d_.cols() == x3D_.cols());
bearing_vectors_= camera->operator()(x2d_);
}
enum { MINIMUM_SAMPLES = Solver::MINIMUM_SAMPLES };
enum { MAX_MODELS = Solver::MAX_MODELS };
void Fit(const std::vector<uint32_t> &samples, std::vector<Model> *models) const {
Solver::Solve(ExtractColumns(bearing_vectors_, samples), // bearing vectors
ExtractColumns(x3D_, samples), // 3D points
models); // Found model hypothesis
}
double Error(uint32_t sample, const Model &model) const {
const Vec3 t = model.block(0, 3, 3, 1);
const geometry::Pose3 pose(model.block(0, 0, 3, 3),
- model.block(0, 0, 3, 3).transpose() * t);
const bool ignore_distortion = true; // We ignore distortion since we are using undistorted bearing vector as input
return (camera_->residual(pose(x3D_.col(sample)),
x2d_.col(sample),
ignore_distortion) * N1_(0,0)).squaredNorm();
}
void Errors(const Model & model, std::vector<double> & vec_errors) const
{
const Vec3 t = model.block(0, 3, 3, 1);
const geometry::Pose3 pose(model.block(0, 0, 3, 3),
- model.block(0, 0, 3, 3).transpose() * t);
vec_errors.resize(x2d_.cols());
for (Mat::Index sample = 0; sample < x2d_.cols(); ++sample)
{
vec_errors[sample] = this->Error(sample, model);
}
}
size_t NumSamples() const { return x2d_.cols(); }
void Unnormalize(Model * model) const {
}
double logalpha0() const {return logalpha0_;}
double multError() const {return 1.0;} // point to point error
Mat3 normalizer1() const {return Mat3::Identity();}
Mat3 normalizer2() const {return N1_;}
double unormalizeError(double val) const {return sqrt(val) / N1_(0,0);}
private:
Mat x2d_, bearing_vectors_;
const Mat & x3D_;
Mat3 N1_;
double logalpha0_; // Alpha0 is used to make the error adaptive to the image size
const cameras::IntrinsicBase * camera_; // Intrinsic camera parameter
};
} // namespace openMVG
namespace openMVG {
namespace sfm {
struct ResectionSquaredResidualError {
// Compute the residual of the projection distance(pt2D, Project(P,pt3D))
// Return the squared error
static double Error(const Mat34 & P, const Vec2 & pt2D, const Vec3 & pt3D) {
const Vec2 x = Project(P, pt3D);
return (x - pt2D).squaredNorm();
}
};
bool SfM_Localizer::Localize
(
const resection::SolverType & solver_type,
const Pair & image_size,
const cameras::IntrinsicBase * optional_intrinsics,
Image_Localizer_Match_Data & resection_data,
geometry::Pose3 & pose
)
{
// --
// Compute the camera pose (resectioning)
// --
Mat34 P;
resection_data.vec_inliers.clear();
// Setup the admissible upper bound residual error
const double dPrecision =
resection_data.error_max == std::numeric_limits<double>::infinity() ?
std::numeric_limits<double>::infinity() :
Square(resection_data.error_max);
size_t MINIMUM_SAMPLES = 0;
switch (solver_type)
{
case resection::SolverType::DLT_6POINTS:
{
//--
// Classic resection (try to compute the entire P matrix)
using SolverType = openMVG::resection::kernel::SixPointResectionSolver;
MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;
using KernelType =
openMVG::robust::ACKernelAdaptorResection<
SolverType,
ResectionSquaredResidualError,
openMVG::robust::UnnormalizerResection,
Mat34>;
KernelType kernel(resection_data.pt2D, image_size.first, image_size.second,
resection_data.pt3D);
// Robust estimation of the pose and its precision
const std::pair<double,double> ACRansacOut =
openMVG::robust::ACRANSAC(kernel,
resection_data.vec_inliers,
resection_data.max_iteration,
&P,
dPrecision,
true);
// Update the upper bound precision of the model found by AC-RANSAC
resection_data.error_max = ACRansacOut.first;
}
break;
case resection::SolverType::P3P_KE_CVPR17:
{
if (!optional_intrinsics)
{
std::cerr << "Intrinsic data is required for P3P solvers." << std::endl;
return false;
}
//--
// Since the intrinsic data is known, compute only the pose
using SolverType = openMVG::euclidean_resection::P3PSolver_Ke;
MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;
using KernelType =
ACKernelAdaptorResection_Intrinsics<
SolverType,
Mat34>;
KernelType kernel(resection_data.pt2D, resection_data.pt3D, optional_intrinsics);
// Robust estimation of the pose matrix and its precision
const auto ACRansacOut =
openMVG::robust::ACRANSAC(kernel,
resection_data.vec_inliers,
resection_data.max_iteration,
&P,
dPrecision,
true);
// Update the upper bound precision of the model found by AC-RANSAC
resection_data.error_max = ACRansacOut.first;
}
break;
case resection::SolverType::P3P_KNEIP_CVPR11:
{
if (!optional_intrinsics)
{
std::cerr << "Intrinsic data is required for P3P solvers." << std::endl;
return false;
}
//--
// Since the intrinsic data is known, compute only the pose
using SolverType = openMVG::euclidean_resection::P3PSolver_Kneip;
MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;
using KernelType =
ACKernelAdaptorResection_Intrinsics<
SolverType,
Mat34>;
KernelType kernel(resection_data.pt2D, resection_data.pt3D, optional_intrinsics);
// Robust estimation of the pose matrix and its precision
const auto ACRansacOut =
openMVG::robust::ACRANSAC(kernel,
resection_data.vec_inliers,
resection_data.max_iteration,
&P,
dPrecision,
true);
// Update the upper bound precision of the model found by AC-RANSAC
resection_data.error_max = ACRansacOut.first;
}
break;
default:
{
std::cerr << "Unknown absolute pose solver type." << std::endl;
return false;
}
}
// Test if the mode support some points (more than those required for estimation)
const bool bResection = (resection_data.vec_inliers.size() > 2.5 * MINIMUM_SAMPLES);
if (bResection)
{
resection_data.projection_matrix = P;
Mat3 K, R;
Vec3 t;
KRt_From_P(P, &K, &R, &t);
pose = geometry::Pose3(R, -R.transpose() * t);
}
std::cout << "\n"
<< "-------------------------------" << "\n"
<< "-- Robust Resection " << "\n"
<< "-- Resection status: " << bResection << "\n"
<< "-- #Points used for Resection: " << resection_data.pt2D.cols() << "\n"
<< "-- #Points validated by robust Resection: " << resection_data.vec_inliers.size() << "\n"
<< "-- Threshold: " << resection_data.error_max << "\n"
<< "-------------------------------" << std::endl;
return bResection;
}
bool SfM_Localizer::RefinePose
(
cameras::IntrinsicBase * intrinsics,
geometry::Pose3 & pose,
Image_Localizer_Match_Data & matching_data,
bool b_refine_pose,
bool b_refine_intrinsic
)
{
if (!b_refine_pose && !b_refine_intrinsic)
{
// Nothing to do (There is no parameter to refine)
return false;
}
// Setup a tiny SfM scene with the corresponding 2D-3D data
SfM_Data sfm_data;
// view
sfm_data.views.insert({0, std::make_shared<View>("",0, 0, 0)});
// pose
sfm_data.poses[0] = pose;
// intrinsic
std::shared_ptr<cameras::IntrinsicBase> shared_intrinsics(intrinsics->clone());
sfm_data.intrinsics[0] = shared_intrinsics;
// structure data (2D-3D correspondences)
for (size_t i = 0; i < matching_data.vec_inliers.size(); ++i)
{
const size_t idx = matching_data.vec_inliers[i];
Landmark landmark;
landmark.X = matching_data.pt3D.col(idx);
landmark.obs[0] = Observation(matching_data.pt2D.col(idx), UndefinedIndexT);
sfm_data.structure[i] = std::move(landmark);
}
// Configure BA options (refine the intrinsic and the pose parameter only if requested)
const Optimize_Options ba_refine_options
(
(b_refine_intrinsic) ? cameras::Intrinsic_Parameter_Type::ADJUST_ALL : cameras::Intrinsic_Parameter_Type::NONE,
(b_refine_pose) ? Extrinsic_Parameter_Type::ADJUST_ALL : Extrinsic_Parameter_Type::NONE,
Structure_Parameter_Type::NONE // STRUCTURE must remain constant
);
Bundle_Adjustment_Ceres bundle_adjustment_obj;
const bool b_BA_Status = bundle_adjustment_obj.Adjust(
sfm_data,
ba_refine_options);
if (b_BA_Status)
{
pose = sfm_data.poses[0];
if (b_refine_intrinsic)
intrinsics->updateFromParams(shared_intrinsics->getParams());
}
return b_BA_Status;
}
} // namespace sfm
} // namespace openMVG
<|endoftext|> |
<commit_before>/**
* @file sparse_bias_layer.hpp
* @author Tham Ngap Wei
*
* Definition of the SparseBiasLayer class.
*/
#ifndef __MLPACK_METHODS_ANN_LAYER_SPARSE_BIAS_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_SPARSE_BIAS_LAYER_HPP
#include <mlpack/core.hpp>
#include <mlpack/methods/ann/layer/layer_traits.hpp>
#include <mlpack/methods/ann/init_rules/zero_init.hpp>
#include <mlpack/methods/ann/optimizer/rmsprop.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* An implementation of a bias layer design for sparse autoencoder.
* The BiasLayer class represents the bias part of sparse autoencoder.
*
*
* @tparam OptimizerType Type of the optimizer used to update the weights.
* @tparam WeightInitRule Rule used to initialize the weight matrix.
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
template<typename, typename> class OptimizerType = mlpack::ann::RMSPROP,
class WeightInitRule = ZeroInitialization,
typename InputDataType = arma::mat,
typename OutputDataType = arma::mat
>
class SparseBiasLayer
{
public:
/**
* Create the BiasLayer object using the specified number of units and bias
* parameter.
*
* @param outSize The number of output units.
* @param sampleSize The size of the training data(how many data for training)
* @param bias The bias value.
* @param WeightInitRule The weight initialization rule used to initialize the
* weight matrix.
*/
SparseBiasLayer(const size_t outSize,
const size_t sampleSize,
WeightInitRule weightInitRule = WeightInitRule()) :
outSize(outSize),
sampleSize(sampleSize),
optimizer(new OptimizerType<SparseBiasLayer<OptimizerType,
WeightInitRule,
InputDataType,
OutputDataType>,
InputDataType>(*this)),
ownsOptimizer(true)
{
weightInitRule.Initialize(weights, outSize, 1);
}
SparseBiasLayer(SparseBiasLayer &&layer) noexcept
{
*this = std::move(layer);
}
SparseBiasLayer& operator=(SparseBiasLayer &&layer) noexcept
{
optimizer = layer.optimizer;
ownsOptimizer = layer.ownsOptimizer;
layer.optimizer = nullptr;
layer.ownsOptimizer = false;
outSize = layer.outSize;
sampleSize = layer.sampleSize;
weights.swap(layer.weights);
delta.swap(layer.delta);
gradient.swap(layer.gradient);
inputParameter.swap(layer.inputParameter);
outputParameter.swap(layer.outputParameter);
return *this;
}
/**
* Delete the bias layer object and its optimizer.
*/
~SparseBiasLayer()
{
if (ownsOptimizer)
delete optimizer;
}
/**
* Ordinary feed forward pass of a neural network, evaluating the function
* f(x) by propagating the activity forward through f.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
output = input + arma::repmat(weights, 1, input.n_cols);
}
/**
* Ordinary feed backward pass of a neural network, calculating the function
* f(x) by propagating x backwards trough f. Using the results from the feed
* forward pass.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename DataType, typename ErrorType>
void Backward(const DataType& /* unused */,
const ErrorType& gy,
ErrorType& g)
{
g = gy;
}
/*
* Calculate the gradient using the output delta and the bias.
*
* @param d The calculated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Gradient(const arma::Mat<eT>& d, InputDataType& g)
{
using inputDataType = std::decay<decltype(inputParameter[0])>::type;
g = arma::sum(d, 1) / static_cast<inputDataType>(sampleSize);
}
//! Get the optimizer.
OptimizerType<SparseBiasLayer<OptimizerType,
WeightInitRule,
InputDataType,
OutputDataType>, InputDataType>& Optimizer() const
{
return *optimizer;
}
//! Modify the optimizer.
OptimizerType<SparseBiasLayer<OptimizerType,
WeightInitRule,
InputDataType,
OutputDataType>, InputDataType>& Optimizer()
{
return *optimizer;
}
//! Get the weights.
InputDataType& Weights() const { return weights; }
//! Modify the weights.
InputDataType& Weights() { return weights; }
//! Get the input parameter.
InputDataType& InputParameter() const {return inputParameter; }
//! Modify the input parameter.
InputDataType& InputParameter() { return inputParameter; }
//! Get the output parameter.
OutputDataType& OutputParameter() const {return outputParameter; }
//! Modify the output parameter.
OutputDataType& OutputParameter() { return outputParameter; }
//! Get the delta.
OutputDataType& Delta() const {return delta; }
//! Modify the delta.
OutputDataType& Delta() { return delta; }
//! Get the gradient.
InputDataType& Gradient() const {return gradient; }
//! Modify the gradient.
InputDataType& Gradient() { return gradient; }
private:
//! Locally-stored number of output units.
size_t outSize;
//! Sample size of the training data
size_t sampleSize;
//! Locally-stored weight object.
InputDataType weights;
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored gradient object.
InputDataType gradient;
//! Locally-stored input parameter object.
InputDataType inputParameter;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
//! Locally-stored pointer to the optimzer object.
OptimizerType<SparseBiasLayer<OptimizerType,
WeightInitRule,
InputDataType,
OutputDataType>, InputDataType>* optimizer;
//! Parameter that indicates if the class owns a optimizer object.
bool ownsOptimizer;
}; // class SparseBiasLayer
//! Layer traits for the SparseBiasLayer.
template<
template<typename, typename> class OptimizerType,
typename WeightInitRule,
typename InputDataType,
typename OutputDataType
>
class LayerTraits<SparseBiasLayer<
OptimizerType, WeightInitRule, InputDataType, OutputDataType> >
{
public:
static const bool IsBinary = false;
static const bool IsOutputLayer = false;
static const bool IsBiasLayer = true;
static const bool IsLSTMLayer = false;
static const bool IsConnection = true;
};
} // namespace ann
} // namespace mlpack
#endif
<commit_msg>1 : change sampleSize to batchSize 2 : able to access batchSize 3 : fix bug--const correctness<commit_after>/**
* @file bias_layer.hpp
* @author Marcus Edel
*
* Definition of the BiasLayer class.
*/
#ifndef __MLPACK_METHODS_ANN_LAYER_SPARSE_BIAS_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_SPARSE_BIAS_LAYER_HPP
#include <mlpack/core.hpp>
#include <mlpack/methods/ann/layer/layer_traits.hpp>
#include <mlpack/methods/ann/init_rules/zero_init.hpp>
#include <mlpack/methods/ann/optimizer/rmsprop.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* An implementation of a bias layer design for sparse autoencoder.
* The BiasLayer class represents a single layer of a neural network.
*
* A convenient typedef is given:
*
* - 2DBiasLayer
*
* @tparam OptimizerType Type of the optimizer used to update the weights.
* @tparam WeightInitRule Rule used to initialize the weight matrix.
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
template<typename, typename> class OptimizerType = mlpack::ann::RMSPROP,
class WeightInitRule = ZeroInitialization,
typename InputDataType = arma::mat,
typename OutputDataType = arma::mat
>
class SparseBiasLayer
{
public:
/**
* Create the BiasLayer object using the specified number of units and bias
* parameter.
*
* @param outSize The number of output units.
* @param batchSize The batch size used to train the network.
* @param bias The bias value.
* @param WeightInitRule The weight initialization rule used to initialize the
* weight matrix.
*/
SparseBiasLayer(const size_t outSize,
const size_t batchSize,
WeightInitRule weightInitRule = WeightInitRule()) :
outSize(outSize),
batchSize(batchSize),
optimizer(new OptimizerType<SparseBiasLayer<OptimizerType,
WeightInitRule,
InputDataType,
OutputDataType>,
InputDataType>(*this)),
ownsOptimizer(true)
{
weightInitRule.Initialize(weights, outSize, 1);
}
SparseBiasLayer(SparseBiasLayer &&layer) noexcept
{
*this = std::move(layer);
}
SparseBiasLayer& operator=(SparseBiasLayer &&layer) noexcept
{
optimizer = layer.optimizer;
ownsOptimizer = layer.ownsOptimizer;
layer.optimizer = nullptr;
layer.ownsOptimizer = false;
outSize = layer.outSize;
batchSize = layer.batchSize;
weights.swap(layer.weights);
delta.swap(layer.delta);
gradient.swap(layer.gradient);
inputParameter.swap(layer.inputParameter);
outputParameter.swap(layer.outputParameter);
return *this;
}
/**
* Delete the bias layer object and its optimizer.
*/
~SparseBiasLayer()
{
if (ownsOptimizer)
delete optimizer;
}
/**
* Ordinary feed forward pass of a neural network, evaluating the function
* f(x) by propagating the activity forward through f.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
output = input + arma::repmat(weights, 1, input.n_cols);
}
/**
* Ordinary feed backward pass of a neural network, calculating the function
* f(x) by propagating x backwards trough f. Using the results from the feed
* forward pass.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename DataType, typename ErrorType>
void Backward(const DataType& /* unused */,
const ErrorType& gy,
ErrorType& g)
{
g = gy;
}
/*
* Calculate the gradient using the output delta and the bias.
*
* @param d The calculated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Gradient(const arma::Mat<eT>& d, InputDataType& g)
{
using inputDataType = std::decay<decltype(inputParameter[0])>::type;
g = arma::sum(d, 1) / static_cast<inputDataType>(batchSize);
}
//! Get the optimizer.
OptimizerType<SparseBiasLayer<OptimizerType,
WeightInitRule,
InputDataType,
OutputDataType>, InputDataType>& Optimizer() const
{
return *optimizer;
}
//! Modify the optimizer.
OptimizerType<SparseBiasLayer<OptimizerType,
WeightInitRule,
InputDataType,
OutputDataType>, InputDataType>& Optimizer()
{
return *optimizer;
}
//! Get the batch size
size_t BatchSize() const { return batchSize; }
//! Modify the batch size
size_t& BatchSize() { return batchSize; }
//! Get the weights.
InputDataType const& Weights() const { return weights; }
//! Modify the weights.
InputDataType& Weights() { return weights; }
//! Get the input parameter.
InputDataType const& InputParameter() const {return inputParameter; }
//! Modify the input parameter.
InputDataType& InputParameter() { return inputParameter; }
//! Get the output parameter.
OutputDataType const& OutputParameter() const {return outputParameter; }
//! Modify the output parameter.
OutputDataType& OutputParameter() { return outputParameter; }
//! Get the delta.
OutputDataType const& Delta() const {return delta; }
//! Modify the delta.
OutputDataType& Delta() { return delta; }
//! Get the gradient.
InputDataType const& Gradient() const {return gradient; }
//! Modify the gradient.
InputDataType& Gradient() { return gradient; }
private:
//! Locally-stored number of output units.
size_t outSize;
//! The batch size used to train the network.
size_t batchSize;
//! Locally-stored weight object.
InputDataType weights;
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored gradient object.
InputDataType gradient;
//! Locally-stored input parameter object.
InputDataType inputParameter;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
//! Locally-stored pointer to the optimzer object.
OptimizerType<SparseBiasLayer<OptimizerType,
WeightInitRule,
InputDataType,
OutputDataType>, InputDataType>* optimizer;
//! Parameter that indicates if the class owns a optimizer object.
bool ownsOptimizer;
}; // class BiasLayer
//! Layer traits for the bias layer.
template<
template<typename, typename> class OptimizerType,
typename WeightInitRule,
typename InputDataType,
typename OutputDataType
>
class LayerTraits<SparseBiasLayer<
OptimizerType, WeightInitRule, InputDataType, OutputDataType> >
{
public:
static const bool IsBinary = false;
static const bool IsOutputLayer = false;
static const bool IsBiasLayer = true;
static const bool IsLSTMLayer = false;
static const bool IsConnection = true;
};
} // namespace ann
} // namespace mlpack
#endif
<|endoftext|> |
<commit_before>#ifndef CELL_AUTOMATA_ISING_SPIN_PARAMS
#define CELL_AUTOMATA_ISING_SPIN_PARAMS
template<typename spin_T, typename simulator_T>
struct Spin_params;
template<typename simulator_T>
class Neuman_flip_spin;
template<typename simulator_T>
struct Spin_params<Neuman_flip_spin<simulator_T>, simulator_T>
{
using numerical_type = typename simulator_T::numerical_type;
Spin_params(numerical_type t, numerical_type m, numerical_type s):
tempreture(t), magnetic_flux_density(m), spin_interaction(s){};
numerical_type tempreture, magnetic_flux_density, spin_interaction;
};
#endif /* CELL_AUTOMATA_ISING_SPIN_PARAMS */
<commit_msg>set default template parameter.<commit_after>#ifndef CELL_AUTOMATA_ISING_SPIN_PARAMS
#define CELL_AUTOMATA_ISING_SPIN_PARAMS
template<typename spin_T, typename simulator_T = typename spin_T::simulator_traits>
struct Spin_params;
template<typename simulator_T>
class Neuman_flip_spin;
template<typename simulator_T>
struct Spin_params<Neuman_flip_spin<simulator_T>, simulator_T>
{
using numerical_type = typename simulator_T::numerical_type;
Spin_params(numerical_type t, numerical_type m, numerical_type s):
tempreture(t), magnetic_flux_density(m), spin_interaction(s){};
numerical_type tempreture, magnetic_flux_density, spin_interaction;
};
#endif /* CELL_AUTOMATA_ISING_SPIN_PARAMS */
<|endoftext|> |
<commit_before>/*******************************************************************************
Copyright (c) 2014, Jan Koester [email protected]
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include <cstring>
#include <config.h>
#include "connections.h"
#include "utils.h"
const char* libhttppp::ConnectionData::getData(){
return _Data;
}
size_t libhttppp::ConnectionData::getDataSize(){
return _DataSize;
}
libhttppp::ConnectionData *libhttppp::ConnectionData::nextConnectionData(){
return _nextConnectionData;
}
libhttppp::ConnectionData::ConnectionData(const char*data,size_t datasize){
_nextConnectionData=NULL;
scopy(data,data+datasize,_Data);
_DataSize=datasize;
}
libhttppp::ConnectionData::~ConnectionData() {
delete _nextConnectionData;
}
libhttppp::ClientSocket *libhttppp::Connection::getClientSocket(){
return _ClientSocket;
}
/** \brief a method to add Data to Sendqueue
* \param data an const char* to add to sendqueue
* \param datasize an size_t to set datasize
* \return the last ConnectionData Block from Sendqueue
*
* This method does unbelievably useful things.
* And returns exceptionally the new connection data block.
* Use it everyday with good health.
*/
libhttppp::ConnectionData *libhttppp::Connection::addSendQueue(const char*data,size_t datasize){
size_t written=0;
for(size_t cursize=datasize; cursize>0; cursize=datasize-written){
if(cursize>BLOCKSIZE){
cursize=BLOCKSIZE;
}
if(!_SendDataFirst){
_SendDataFirst= new ConnectionData(data+written,cursize);
_SendDataLast=_SendDataFirst;
}else{
_SendDataLast->_nextConnectionData=new ConnectionData(data+written,cursize);
_SendDataLast=_SendDataLast->_nextConnectionData;
}
written+=cursize;
}
_SendDataSize+=written;
return _SendDataLast;
}
void libhttppp::Connection::cleanSendData(){
delete _SendDataFirst;
_SendDataFirst=NULL;
_SendDataLast=NULL;
_SendDataSize=0;
}
libhttppp::ConnectionData *libhttppp::Connection::resizeSendQueue(size_t size){
if(size>0)
return _resizeQueue(&_SendDataFirst,&_SendDataLast,&_SendDataSize,size);
return _SendDataFirst;
}
libhttppp::ConnectionData* libhttppp::Connection::getSendData(){
return _SendDataFirst;
}
size_t libhttppp::Connection::getSendSize(){
return _SendDataSize;
}
libhttppp::ConnectionData *libhttppp::Connection::addRecvQueue(const char data[BLOCKSIZE],size_t datasize){
if(datasize<0)
return _ReadDataLast;
if(!_ReadDataFirst){
_ReadDataFirst= new ConnectionData(data,datasize);
_ReadDataLast=_ReadDataFirst;
}else{
_ReadDataLast->_nextConnectionData=new ConnectionData(data,datasize);
_ReadDataLast=_ReadDataLast->_nextConnectionData;
}
_ReadDataSize+=datasize;
return _ReadDataLast;
}
void libhttppp::Connection::cleanRecvData(){
delete _ReadDataFirst;
_ReadDataFirst=NULL;
_ReadDataLast=NULL;
_ReadDataSize=0;
}
libhttppp::ConnectionData *libhttppp::Connection::resizeRecvQueue(size_t size){
if(size>0)
return _resizeQueue(&_ReadDataFirst,&_ReadDataLast,&_ReadDataSize,size);
return _ReadDataFirst;
}
libhttppp::ConnectionData *libhttppp::Connection::getRecvData(){
return _ReadDataFirst;
}
size_t libhttppp::Connection::getRecvSize(){
return _ReadDataSize;
}
libhttppp::ConnectionData *libhttppp::Connection::_resizeQueue(ConnectionData** firstdata, ConnectionData** lastdata,
size_t *qsize, size_t size){
ConnectionData *firstdat=*firstdata;
while(firstdat!=NULL && size>0){
size_t delsize=0;
if(size>=firstdat->getDataSize()){
delsize=firstdat->getDataSize();
ConnectionData *deldat=firstdat;
firstdat=firstdat->_nextConnectionData;
if(deldat==*lastdata)
*lastdata=firstdat;
deldat->_nextConnectionData=NULL;
delete deldat;
}else{
delsize=size;
firstdat->_DataSize-=size;
scopy(firstdat->_Data+delsize,firstdat->_Data+BLOCKSIZE,firstdat->_Data);
firstdat->_Data[firstdat->_DataSize]='\0';
}
size-=delsize;
*qsize-=delsize;
}
*firstdata=firstdat;
return firstdat;
}
int libhttppp::Connection::copyValue(ConnectionData* startblock, int startpos,
ConnectionData* endblock, int endpos, char** buffer){
size_t copysize=0,copypos=0;
for(ConnectionData *curdat=startblock; curdat; curdat=curdat->nextConnectionData()){
if(curdat==endblock){
copysize+=endpos;
break;
}
copysize+=curdat->getDataSize();
}
copysize-=startpos;
char *buf;
buf = new char[(copysize+1)]; //one more for termination
for(ConnectionData *curdat=startblock; curdat; curdat=curdat->nextConnectionData()){
if(curdat==startblock && curdat==endblock){
scopy(curdat->_Data+startpos,curdat->_Data+(endpos-startpos),buf+copypos);
}else if(curdat==startblock){
scopy(curdat->_Data+startpos,curdat->_Data+(curdat->getDataSize()-startpos),buf+copypos);
copypos+=curdat->getDataSize()-startpos;
}else if(curdat==endblock){
scopy(curdat->_Data,curdat->_Data+endpos,buf+copypos);
copypos+=endpos;
}else{
scopy(curdat->_Data,curdat->_Data+curdat->getDataSize(),buf+copypos);
copypos+=curdat->getDataSize();
}
if(curdat==endblock)
break;
}
buf[copysize]='\0';
*buffer=buf;
return copysize; //not include termination
}
int libhttppp::Connection::searchValue(ConnectionData* startblock, ConnectionData** findblock,
const char* keyword){
return searchValue(startblock, findblock, keyword,getlen(keyword));
}
int libhttppp::Connection::searchValue(ConnectionData* startblock, ConnectionData** findblock,
const char* keyword,size_t keylen){
size_t fpos=0,fcurpos=0;
for(ConnectionData *curdat=startblock; curdat; curdat=curdat->nextConnectionData()){
for(size_t pos=0; pos<curdat->getDataSize(); pos++){
if(keyword[fcurpos]==curdat->_Data[pos]){
if(fcurpos==0){
fpos=pos;
*findblock=curdat;
}
fcurpos++;
}else{
fcurpos=0;
fpos=0;
*findblock=NULL;
}
if(fcurpos==keylen)
return fpos;
}
}
return -1;
}
libhttppp::Connection::Connection(){
_ClientSocket=new ClientSocket();
_ReadDataFirst=NULL;
_ReadDataLast=NULL;
_ReadDataSize=0;
_SendDataFirst=NULL;
_SendDataLast=NULL;
_SendDataSize=0;
}
libhttppp::Connection::~Connection(){
delete _ClientSocket;
delete _ReadDataFirst;
delete _SendDataFirst;
}
<commit_msg>some new debug messages<commit_after>/*******************************************************************************
Copyright (c) 2014, Jan Koester [email protected]
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include <cstring>
#include <config.h>
#include "connections.h"
#include "utils.h"
const char* libhttppp::ConnectionData::getData(){
return _Data;
}
size_t libhttppp::ConnectionData::getDataSize(){
return _DataSize;
}
libhttppp::ConnectionData *libhttppp::ConnectionData::nextConnectionData(){
return _nextConnectionData;
}
libhttppp::ConnectionData::ConnectionData(const char*data,size_t datasize){
_nextConnectionData=NULL;
scopy(data,data+datasize,_Data);
_DataSize=datasize;
}
libhttppp::ConnectionData::~ConnectionData() {
delete _nextConnectionData;
}
libhttppp::ClientSocket *libhttppp::Connection::getClientSocket(){
return _ClientSocket;
}
/** \brief a method to add Data to Sendqueue
* \param data an const char* to add to sendqueue
* \param datasize an size_t to set datasize
* \return the last ConnectionData Block from Sendqueue
*
* This method does unbelievably useful things.
* And returns exceptionally the new connection data block.
* Use it everyday with good health.
*/
libhttppp::ConnectionData *libhttppp::Connection::addSendQueue(const char*data,size_t datasize){
if(datasize<=0){
HTTPException httpexception;
httpexception.Error("addSendQueue","wrong datasize");
throw httpexception;
}
size_t written=0;
for(size_t cursize=datasize; cursize>0; cursize=datasize-written){
if(cursize>BLOCKSIZE){
cursize=BLOCKSIZE;
}
if(!_SendDataFirst){
_SendDataFirst= new ConnectionData(data+written,cursize);
_SendDataLast=_SendDataFirst;
}else{
_SendDataLast->_nextConnectionData=new ConnectionData(data+written,cursize);
_SendDataLast=_SendDataLast->_nextConnectionData;
}
written+=cursize;
}
_SendDataSize+=written;
return _SendDataLast;
}
void libhttppp::Connection::cleanSendData(){
delete _SendDataFirst;
_SendDataFirst=NULL;
_SendDataLast=NULL;
_SendDataSize=0;
}
libhttppp::ConnectionData *libhttppp::Connection::resizeSendQueue(size_t size){
if(size<=0){
HTTPException httpexception;
httpexception.Error("resizeSendQueue","wrong datasize");
throw httpexception;
}
return _resizeQueue(&_SendDataFirst,&_SendDataLast,&_SendDataSize,size);
}
libhttppp::ConnectionData* libhttppp::Connection::getSendData(){
return _SendDataFirst;
}
size_t libhttppp::Connection::getSendSize(){
return _SendDataSize;
}
libhttppp::ConnectionData *libhttppp::Connection::addRecvQueue(const char data[BLOCKSIZE],size_t datasize){
if(datasize<=0){
HTTPException httpexception;
httpexception.Error("addRecvQueue","wrong datasize");
throw httpexception;
}
if(!_ReadDataFirst){
_ReadDataFirst= new ConnectionData(data,datasize);
_ReadDataLast=_ReadDataFirst;
}else{
_ReadDataLast->_nextConnectionData=new ConnectionData(data,datasize);
_ReadDataLast=_ReadDataLast->_nextConnectionData;
}
_ReadDataSize+=datasize;
return _ReadDataLast;
}
void libhttppp::Connection::cleanRecvData(){
delete _ReadDataFirst;
_ReadDataFirst=NULL;
_ReadDataLast=NULL;
_ReadDataSize=0;
}
libhttppp::ConnectionData *libhttppp::Connection::resizeRecvQueue(size_t size){
if(size<=0){
HTTPException httpexception;
httpexception.Error("resizeRecvQueue","wrong datasize");
throw httpexception;
}
return _resizeQueue(&_ReadDataFirst,&_ReadDataLast,&_ReadDataSize,size);
}
libhttppp::ConnectionData *libhttppp::Connection::getRecvData(){
return _ReadDataFirst;
}
size_t libhttppp::Connection::getRecvSize(){
return _ReadDataSize;
}
libhttppp::ConnectionData *libhttppp::Connection::_resizeQueue(ConnectionData** firstdata, ConnectionData** lastdata,
size_t *qsize, size_t size){
ConnectionData *firstdat=*firstdata;
while(firstdat!=NULL && size>0){
size_t delsize=0;
if(size>=firstdat->getDataSize()){
delsize=firstdat->getDataSize();
ConnectionData *deldat=firstdat;
firstdat=firstdat->_nextConnectionData;
if(deldat==*lastdata)
*lastdata=firstdat;
deldat->_nextConnectionData=NULL;
delete deldat;
}else{
delsize=size;
firstdat->_DataSize-=size;
scopy(firstdat->_Data+delsize,firstdat->_Data+BLOCKSIZE,firstdat->_Data);
firstdat->_Data[firstdat->_DataSize]='\0';
}
size-=delsize;
*qsize-=delsize;
}
*firstdata=firstdat;
return firstdat;
}
int libhttppp::Connection::copyValue(ConnectionData* startblock, int startpos,
ConnectionData* endblock, int endpos, char** buffer){
size_t copysize=0,copypos=0;
for(ConnectionData *curdat=startblock; curdat; curdat=curdat->nextConnectionData()){
if(curdat==endblock){
copysize+=endpos;
break;
}
copysize+=curdat->getDataSize();
}
copysize-=startpos;
char *buf;
buf = new char[(copysize+1)]; //one more for termination
for(ConnectionData *curdat=startblock; curdat; curdat=curdat->nextConnectionData()){
if(curdat==startblock && curdat==endblock){
scopy(curdat->_Data+startpos,curdat->_Data+(endpos-startpos),buf+copypos);
}else if(curdat==startblock){
scopy(curdat->_Data+startpos,curdat->_Data+(curdat->getDataSize()-startpos),buf+copypos);
copypos+=curdat->getDataSize()-startpos;
}else if(curdat==endblock){
scopy(curdat->_Data,curdat->_Data+endpos,buf+copypos);
copypos+=endpos;
}else{
scopy(curdat->_Data,curdat->_Data+curdat->getDataSize(),buf+copypos);
copypos+=curdat->getDataSize();
}
if(curdat==endblock)
break;
}
buf[copysize]='\0';
*buffer=buf;
return copysize; //not include termination
}
int libhttppp::Connection::searchValue(ConnectionData* startblock, ConnectionData** findblock,
const char* keyword){
return searchValue(startblock, findblock, keyword,getlen(keyword));
}
int libhttppp::Connection::searchValue(ConnectionData* startblock, ConnectionData** findblock,
const char* keyword,size_t keylen){
size_t fpos=0,fcurpos=0;
for(ConnectionData *curdat=startblock; curdat; curdat=curdat->nextConnectionData()){
for(size_t pos=0; pos<curdat->getDataSize(); pos++){
if(keyword[fcurpos]==curdat->_Data[pos]){
if(fcurpos==0){
fpos=pos;
*findblock=curdat;
}
fcurpos++;
}else{
fcurpos=0;
fpos=0;
*findblock=NULL;
}
if(fcurpos==keylen)
return fpos;
}
}
return -1;
}
libhttppp::Connection::Connection(){
_ClientSocket=new ClientSocket();
_ReadDataFirst=NULL;
_ReadDataLast=NULL;
_ReadDataSize=0;
_SendDataFirst=NULL;
_SendDataLast=NULL;
_SendDataSize=0;
}
libhttppp::Connection::~Connection(){
delete _ClientSocket;
delete _ReadDataFirst;
delete _SendDataFirst;
}
<|endoftext|> |
<commit_before>#include "rbis_fovis_update.hpp"
#include <path_util/path_util.h>
namespace MavStateEst {
FovisHandler::FovisHandler(lcm::LCM* lcm_recv, lcm::LCM* lcm_pub,
BotParam * param, BotFrames * frames): lcm_recv(lcm_recv), lcm_pub(lcm_pub), frames(frames){
verbose_ = true;
publish_diagnostics_ = false;
pc_vis_ = new pronto_vis( lcm_pub->getUnderlyingLCM());
// obj: id name type reset
pc_vis_->obj_cfg_list.push_back( obj_cfg(7000,"Pronto-VO Pose t0",5,1) );
pc_vis_->obj_cfg_list.push_back( obj_cfg(7001,"Pronto-VO Pose t1 kin",5,1) );
pc_vis_->obj_cfg_list.push_back( obj_cfg(7002,"Pronto-VO Pose t1 vo",5,1) );
pc_vis_->obj_cfg_list.push_back( obj_cfg(7003,"Pronto-VO Pose current",5,1) );
char* mode_str = bot_param_get_str_or_fail(param, "state_estimator.fovis.mode");
if (strcmp(mode_str, "lin_rot_rate") == 0) {
mode = FovisHandler::MODE_LIN_AND_ROT_RATE;
std::cout << "FOVIS will provide velocity and rotation rates." << std::endl;
}
else if (strcmp(mode_str, "lin_rate") == 0){
mode = FovisHandler::MODE_LIN_RATE;
std::cout << "FOVIS will provide velocity rates." << std::endl;
}
else if (strcmp(mode_str, "lin") == 0){
mode = FovisHandler::MODE_LIN;
std::cout << "FOVIS will provide linear position corrections." << std::endl;
}
else{
// ... incomplete...
}
free(mode_str);
Eigen::VectorXd R_fovis;
if (mode == MODE_LIN_AND_ROT_RATE) {
z_indices.resize(6);
R_fovis.resize(6);
}
else if (mode == MODE_LIN_RATE){
z_indices.resize(3);
R_fovis.resize(3);
}
else if (mode == MODE_LIN){
z_indices.resize(3);
R_fovis.resize(3);
}
else{
// ... incomplete...
}
// Initialize covariance matrix based on mode.
if (mode == MODE_LIN_AND_ROT_RATE) {
double R_fovis_vxyz = bot_param_get_double_or_fail(param, "state_estimator.fovis.r_vxyz");
double R_fovis_vang = bot_param_get_double_or_fail(param, "state_estimator.fovis.r_vang");
R_fovis(0) = bot_sq(R_fovis_vxyz);
R_fovis(1) = bot_sq(R_fovis_vxyz);
R_fovis(2) = bot_sq(R_fovis_vxyz);
R_fovis(3) = bot_sq(R_fovis_vang);
R_fovis(4) = bot_sq(R_fovis_vang);
R_fovis(5) = bot_sq(R_fovis_vang);
z_indices.head<3>() = eigen_utils::RigidBodyState::velocityInds();
z_indices.tail<3>() = eigen_utils::RigidBodyState::angularVelocityInds();
}else if (mode == MODE_LIN_RATE){
double R_fovis_vxyz = bot_param_get_double_or_fail(param, "state_estimator.fovis.r_vxyz");
R_fovis(0) = bot_sq(R_fovis_vxyz);
R_fovis(1) = bot_sq(R_fovis_vxyz);
R_fovis(2) = bot_sq(R_fovis_vxyz);
z_indices.head<3>() = eigen_utils::RigidBodyState::velocityInds();
}else if (mode == MODE_LIN){
double R_fovis_pxy = bot_param_get_double_or_fail(param, "state_estimator.fovis.r_pxy");
R_fovis(0) = bot_sq(R_fovis_pxy);
R_fovis(1) = bot_sq(R_fovis_pxy);
double R_fovis_pz = bot_param_get_double_or_fail(param, "state_estimator.fovis.r_pz");
R_fovis(2) = bot_sq(R_fovis_pz);
z_indices.head<3>() = eigen_utils::RigidBodyState::positionInds();
}else{
// ..incomplete
}
cov_fovis = R_fovis.asDiagonal();
prev_t0_body_ = Eigen::Isometry3d::Identity();
prev_t0_body_utime_ = 0;
}
int get_trans_with_utime(BotFrames *bot_frames,
const char *from_frame, const char *to_frame, int64_t utime,
Eigen::Isometry3d & mat){
int status;
double matx[16];
status = bot_frames_get_trans_mat_4x4_with_utime( bot_frames, from_frame, to_frame, utime, matx);
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
mat(i,j) = matx[i*4+j];
}
}
return status;
}
// NOTE: this inserts the BotTrans trans_vec
// as the velocity components in the pose
// [duplicated in rbis_legodo_common.cpp]
bot_core::pose_t getBotTransAsBotPoseVelocity(BotTrans bt, int64_t utime ){
bot_core::pose_t pose;
pose.utime = utime;
pose.pos[0] = 0;
pose.pos[1] = 0;
pose.pos[2] = 0;
pose.orientation[0] = 0;
pose.orientation[1] = 0;
pose.orientation[2] = 0;
pose.orientation[3] = 0;
pose.vel[0] = bt.trans_vec[0];
pose.vel[1] = bt.trans_vec[1];
pose.vel[2] = bt.trans_vec[2];
pose.rotation_rate[0] = 0;//bt.rot_quat[0];
pose.rotation_rate[1] = 0;//bt.rot_quat[1];
pose.rotation_rate[2] = 0;//bt.rot_quat[2];
return pose;
}
RBISUpdateInterface * FovisHandler::processMessage(const fovis::update_t * msg, RBIS state, RBIM cov){
Eigen::Isometry3d t0_body = Eigen::Isometry3d::Identity();
if (msg->prev_timestamp != prev_t0_body_utime_){
// TODO check that these trans are valid
int status = get_trans_with_utime(frames, "body" , "local", msg->prev_timestamp, t0_body);
prev_t0_body_ = t0_body;
prev_t0_body_utime_ = msg->prev_timestamp;
}else{
t0_body = prev_t0_body_;
}
Eigen::Isometry3d t1_body = Eigen::Isometry3d::Identity();
get_trans_with_utime(frames, "body" , "local", msg->timestamp, t1_body);
Eigen::Isometry3d t0t1_body_vo = Eigen::Isometry3d::Identity();
t0t1_body_vo.translation() = Eigen::Vector3d( msg->translation[0], msg->translation[1], msg->translation[2] );
t0t1_body_vo.rotate( Eigen::Quaterniond( msg->rotation[0], msg->rotation[1], msg->rotation[2], msg->rotation[3] ) );
Eigen::Isometry3d t1_body_vo = t0_body * t0t1_body_vo; // the pose of the robot as estimated by applying the VO translation on top of t0 state
if (1==0){
Isometry3dTime t0_body_T = Isometry3dTime(msg->prev_timestamp , t0_body );
pc_vis_->pose_to_lcm_from_list(7000, t0_body_T );
Isometry3dTime t1_body_T = Isometry3dTime(msg->timestamp , t1_body );
pc_vis_->pose_to_lcm_from_list(7001, t1_body_T );
Isometry3dTime t1_body_vo_T = Isometry3dTime(msg->timestamp , t1_body_vo );
pc_vis_->pose_to_lcm_from_list(7002, t1_body_vo_T );
Eigen::Isometry3d current_body;
current_body.setIdentity();
current_body.translation() = Eigen::Vector3d( state.position()[0], state.position()[1], state.position()[2] );
current_body.rotate( Eigen::Quaterniond( state.quat.w(), state.quat.x(), state.quat.y(), state.quat.z() ) );
Isometry3dTime current_body_T = Isometry3dTime(msg->timestamp , current_body );
pc_vis_->pose_to_lcm_from_list(7003, current_body_T );
Eigen::Vector3d diff = Eigen::Vector3d( t1_body_vo.translation() - t1_body.translation() );
std::cout << diff.transpose() << " is diff\n";
}
if (msg->estimate_status == fovis::update_t::ESTIMATE_VALID){
}else{
std::cout << "FovisHandler: FOVIS failure, not integrating this measurement\n";
return NULL;
}
// TODO: explore why this is allowed to be published upstream
if ( isnan( msg->translation[0]) ){
std::cout << "FovisHandler: FOVIS produced NaN. x="<< msg->translation[0] << ", quitting\n";
exit(-1); // keep this exit until we have found the source of the NaN in Fovis
return NULL;
}
BotTrans odo_deltaT;
memset(&odo_deltaT, 0, sizeof(odo_deltaT));
memcpy(odo_deltaT.trans_vec, msg->translation, 3 * sizeof(double));
memcpy(odo_deltaT.rot_quat, msg->rotation , 4 * sizeof(double));
BotTrans odo_velT = getTransAsVelocityTrans(odo_deltaT, msg->timestamp, msg->prev_timestamp);
if (publish_diagnostics_){
// Get the velocity as a pose message:
bot_core::pose_t vel_pose = getBotTransAsBotPoseVelocity(odo_velT, msg->timestamp) ;
lcm_pub->publish("POSE_BODY_FOVIS_VELOCITY", &vel_pose );
}
if (mode == MODE_LIN_AND_ROT_RATE) { // Working on this:
Eigen::VectorXd z_meas(6);
Eigen::Quaterniond quat;
eigen_utils::botDoubleToQuaternion(quat, odo_velT.rot_quat);
z_meas.head<3>() = Eigen::Map<const Eigen::Vector3d>(odo_velT.trans_vec);
// eigen_utils::botDoubleToQuaternion(quat, msg->quat);
// z_meas.head<3>() = Eigen::Map<const Eigen::Vector3d>(msg->trans);
return new RBISIndexedPlusOrientationMeasurement(z_indices, z_meas, cov_fovis, quat, RBISUpdateInterface::fovis,
msg->timestamp);
}else if (mode == MODE_LIN_RATE) {
return new RBISIndexedMeasurement(eigen_utils::RigidBodyState::velocityInds(),
Eigen::Map<const Eigen::Vector3d>( odo_velT.trans_vec ), cov_fovis, RBISUpdateInterface::fovis,
msg->timestamp);
}else if (mode == MODE_LIN) {
Eigen::VectorXd z_meas(3);
z_meas.head<3>() = Eigen::Vector3d( t1_body_vo.translation().x() , t1_body_vo.translation().y() , t1_body_vo.translation().z() );
return new RBISIndexedMeasurement(eigen_utils::RigidBodyState::positionInds(),
z_meas, cov_fovis, RBISUpdateInterface::fovis,
msg->timestamp);
}else{
std::cout << "FovisHandler Mode not supported, exiting\n";
return NULL;
}
}
/// Everything below is duplicated in rbis_legodo_common.cpp
void printTrans(BotTrans bt, std::string message){
std::cout << message << ": "
<< bt.trans_vec[0] << ", " << bt.trans_vec[1] << ", " << bt.trans_vec[2] << " | "
<< bt.rot_quat[0] << ", " << bt.rot_quat[1] << ", " << bt.rot_quat[2] << ", " << bt.rot_quat[3] << "\n";
}
// Difference the transform and scale by elapsed time:
BotTrans FovisHandler::getTransAsVelocityTrans(BotTrans msgT, int64_t utime, int64_t prev_utime){
Eigen::Isometry3d msgE = pronto::getBotTransAsEigen(msgT);
Eigen::Isometry3d msgE_vel = pronto::getDeltaAsVelocity(msgE, (utime-prev_utime) );
BotTrans msgT_vel;
msgT_vel = pronto::getEigenAsBotTrans(msgE_vel);
return msgT_vel;
}
/// Publishing Functions
// Convert the delta position into a velocity
// as a bot_pose message for visualization with signal scope:
void FovisHandler::sendTransAsVelocityPose(BotTrans msgT, int64_t utime, int64_t prev_utime, std::string channel){
BotTrans msgT_vel = getTransAsVelocityTrans(msgT, utime, prev_utime);
bot_core::pose_t vel_pose = getBotTransAsBotPoseVelocity(msgT_vel, utime) ;
lcm_pub->publish(channel, &vel_pose );
}
} // end of namespace
<commit_msg>minor<commit_after>#include "rbis_fovis_update.hpp"
#include <path_util/path_util.h>
namespace MavStateEst {
FovisHandler::FovisHandler(lcm::LCM* lcm_recv, lcm::LCM* lcm_pub,
BotParam * param, BotFrames * frames): lcm_recv(lcm_recv), lcm_pub(lcm_pub), frames(frames){
verbose_ = true;
publish_diagnostics_ = false;
pc_vis_ = new pronto_vis( lcm_pub->getUnderlyingLCM());
// obj: id name type reset
pc_vis_->obj_cfg_list.push_back( obj_cfg(7000,"Pronto-VO Pose t0",5,1) );
pc_vis_->obj_cfg_list.push_back( obj_cfg(7001,"Pronto-VO Pose t1 kin",5,1) );
pc_vis_->obj_cfg_list.push_back( obj_cfg(7002,"Pronto-VO Pose t1 vo",5,1) );
pc_vis_->obj_cfg_list.push_back( obj_cfg(7003,"Pronto-VO Pose current",5,1) );
char* mode_str = bot_param_get_str_or_fail(param, "state_estimator.fovis.mode");
if (strcmp(mode_str, "lin_rot_rate") == 0) {
mode = FovisHandler::MODE_LIN_AND_ROT_RATE;
std::cout << "FOVIS will provide velocity and rotation rates." << std::endl;
}
else if (strcmp(mode_str, "lin_rate") == 0){
mode = FovisHandler::MODE_LIN_RATE;
std::cout << "FOVIS will provide velocity rates." << std::endl;
}
else if (strcmp(mode_str, "lin") == 0){
mode = FovisHandler::MODE_LIN;
std::cout << "FOVIS will provide linear position corrections." << std::endl;
}
else{
// ... incomplete...
}
free(mode_str);
Eigen::VectorXd R_fovis;
if (mode == MODE_LIN_AND_ROT_RATE) {
z_indices.resize(6);
R_fovis.resize(6);
}
else if (mode == MODE_LIN_RATE){
z_indices.resize(3);
R_fovis.resize(3);
}
else if (mode == MODE_LIN){
z_indices.resize(3);
R_fovis.resize(3);
}
else{
// ... incomplete...
}
// Initialize covariance matrix based on mode.
if (mode == MODE_LIN_AND_ROT_RATE) {
double R_fovis_vxyz = bot_param_get_double_or_fail(param, "state_estimator.fovis.r_vxyz");
double R_fovis_vang = bot_param_get_double_or_fail(param, "state_estimator.fovis.r_vang");
R_fovis(0) = bot_sq(R_fovis_vxyz);
R_fovis(1) = bot_sq(R_fovis_vxyz);
R_fovis(2) = bot_sq(R_fovis_vxyz);
R_fovis(3) = bot_sq(R_fovis_vang);
R_fovis(4) = bot_sq(R_fovis_vang);
R_fovis(5) = bot_sq(R_fovis_vang);
z_indices.head<3>() = eigen_utils::RigidBodyState::velocityInds();
z_indices.tail<3>() = eigen_utils::RigidBodyState::angularVelocityInds();
}else if (mode == MODE_LIN_RATE){
double R_fovis_vxyz = bot_param_get_double_or_fail(param, "state_estimator.fovis.r_vxyz");
R_fovis(0) = bot_sq(R_fovis_vxyz);
R_fovis(1) = bot_sq(R_fovis_vxyz);
R_fovis(2) = bot_sq(R_fovis_vxyz);
z_indices.head<3>() = eigen_utils::RigidBodyState::velocityInds();
}else if (mode == MODE_LIN){
double R_fovis_pxy = bot_param_get_double_or_fail(param, "state_estimator.fovis.r_pxy");
R_fovis(0) = bot_sq(R_fovis_pxy);
R_fovis(1) = bot_sq(R_fovis_pxy);
double R_fovis_pz = bot_param_get_double_or_fail(param, "state_estimator.fovis.r_pz");
R_fovis(2) = bot_sq(R_fovis_pz);
z_indices.head<3>() = eigen_utils::RigidBodyState::positionInds();
}else{
// ..incomplete
}
cov_fovis = R_fovis.asDiagonal();
prev_t0_body_ = Eigen::Isometry3d::Identity();
prev_t0_body_utime_ = 0;
}
int get_trans_with_utime(BotFrames *bot_frames,
const char *from_frame, const char *to_frame, int64_t utime,
Eigen::Isometry3d & mat){
int status;
double matx[16];
status = bot_frames_get_trans_mat_4x4_with_utime( bot_frames, from_frame, to_frame, utime, matx);
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
mat(i,j) = matx[i*4+j];
}
}
return status;
}
// NOTE: this inserts the BotTrans trans_vec
// as the velocity components in the pose
// [duplicated in rbis_legodo_common.cpp]
bot_core::pose_t getBotTransAsBotPoseVelocity(BotTrans bt, int64_t utime ){
bot_core::pose_t pose;
pose.utime = utime;
pose.pos[0] = 0;
pose.pos[1] = 0;
pose.pos[2] = 0;
pose.orientation[0] = 0;
pose.orientation[1] = 0;
pose.orientation[2] = 0;
pose.orientation[3] = 0;
pose.vel[0] = bt.trans_vec[0];
pose.vel[1] = bt.trans_vec[1];
pose.vel[2] = bt.trans_vec[2];
pose.rotation_rate[0] = 0;//bt.rot_quat[0];
pose.rotation_rate[1] = 0;//bt.rot_quat[1];
pose.rotation_rate[2] = 0;//bt.rot_quat[2];
return pose;
}
RBISUpdateInterface * FovisHandler::processMessage(const fovis::update_t * msg, RBIS state, RBIM cov){
Eigen::Isometry3d t0_body = Eigen::Isometry3d::Identity();
if (msg->prev_timestamp != prev_t0_body_utime_){
// TODO check that these trans are valid
int status = get_trans_with_utime(frames, "body" , "local", msg->prev_timestamp, t0_body);
prev_t0_body_ = t0_body;
prev_t0_body_utime_ = msg->prev_timestamp;
}else{
t0_body = prev_t0_body_;
}
Eigen::Isometry3d t1_body = Eigen::Isometry3d::Identity();
get_trans_with_utime(frames, "body" , "local", msg->timestamp, t1_body);
Eigen::Isometry3d t0t1_body_vo = Eigen::Isometry3d::Identity();
t0t1_body_vo.translation() = Eigen::Vector3d( msg->translation[0], msg->translation[1], msg->translation[2] );
t0t1_body_vo.rotate( Eigen::Quaterniond( msg->rotation[0], msg->rotation[1], msg->rotation[2], msg->rotation[3] ) );
Eigen::Isometry3d t1_body_vo = t0_body * t0t1_body_vo; // the pose of the robot as estimated by applying the VO translation on top of t0 state
if (1==0){
Isometry3dTime t0_body_T = Isometry3dTime(msg->prev_timestamp , t0_body );
pc_vis_->pose_to_lcm_from_list(7000, t0_body_T );
Isometry3dTime t1_body_T = Isometry3dTime(msg->timestamp , t1_body );
pc_vis_->pose_to_lcm_from_list(7001, t1_body_T );
Isometry3dTime t1_body_vo_T = Isometry3dTime(msg->timestamp , t1_body_vo );
pc_vis_->pose_to_lcm_from_list(7002, t1_body_vo_T );
Eigen::Isometry3d current_body;
current_body.setIdentity();
current_body.translation() = Eigen::Vector3d( state.position()[0], state.position()[1], state.position()[2] );
current_body.rotate( Eigen::Quaterniond( state.quat.w(), state.quat.x(), state.quat.y(), state.quat.z() ) );
Isometry3dTime current_body_T = Isometry3dTime(msg->timestamp , current_body );
pc_vis_->pose_to_lcm_from_list(7003, current_body_T );
//std::cout << t1_body.translation().transpose() << " body\n";
//std::cout << t1_body_vo.translation().transpose() << " vo delta\n";
//Eigen::Vector3d diff = Eigen::Vector3d( t1_body_vo.translation() - t1_body.translation() );
//std::cout << diff.transpose() << " is diff\n\n";
}
if (msg->estimate_status == fovis::update_t::ESTIMATE_VALID){
}else{
std::cout << "FovisHandler: FOVIS failure, not integrating this measurement\n";
return NULL;
}
// TODO: explore why this is allowed to be published upstream
if ( isnan( msg->translation[0]) ){
std::cout << "FovisHandler: FOVIS produced NaN. x="<< msg->translation[0] << ", quitting\n";
exit(-1); // keep this exit until we have found the source of the NaN in Fovis
return NULL;
}
BotTrans odo_deltaT;
memset(&odo_deltaT, 0, sizeof(odo_deltaT));
memcpy(odo_deltaT.trans_vec, msg->translation, 3 * sizeof(double));
memcpy(odo_deltaT.rot_quat, msg->rotation , 4 * sizeof(double));
BotTrans odo_velT = getTransAsVelocityTrans(odo_deltaT, msg->timestamp, msg->prev_timestamp);
if (publish_diagnostics_){
// Get the velocity as a pose message:
bot_core::pose_t vel_pose = getBotTransAsBotPoseVelocity(odo_velT, msg->timestamp) ;
lcm_pub->publish("POSE_BODY_FOVIS_VELOCITY", &vel_pose );
}
if (mode == MODE_LIN_AND_ROT_RATE) { // Working on this:
Eigen::VectorXd z_meas(6);
Eigen::Quaterniond quat;
eigen_utils::botDoubleToQuaternion(quat, odo_velT.rot_quat);
z_meas.head<3>() = Eigen::Map<const Eigen::Vector3d>(odo_velT.trans_vec);
// eigen_utils::botDoubleToQuaternion(quat, msg->quat);
// z_meas.head<3>() = Eigen::Map<const Eigen::Vector3d>(msg->trans);
return new RBISIndexedPlusOrientationMeasurement(z_indices, z_meas, cov_fovis, quat, RBISUpdateInterface::fovis,
msg->timestamp);
}else if (mode == MODE_LIN_RATE) {
return new RBISIndexedMeasurement(eigen_utils::RigidBodyState::velocityInds(),
Eigen::Map<const Eigen::Vector3d>( odo_velT.trans_vec ), cov_fovis, RBISUpdateInterface::fovis,
msg->timestamp);
}else if (mode == MODE_LIN) {
Eigen::VectorXd z_meas(3);
z_meas.head<3>() = Eigen::Vector3d( t1_body_vo.translation().x() , t1_body_vo.translation().y() , t1_body_vo.translation().z() );
return new RBISIndexedMeasurement(eigen_utils::RigidBodyState::positionInds(),
z_meas, cov_fovis, RBISUpdateInterface::fovis,
msg->timestamp);
}else{
std::cout << "FovisHandler Mode not supported, exiting\n";
return NULL;
}
}
/// Everything below is duplicated in rbis_legodo_common.cpp
void printTrans(BotTrans bt, std::string message){
std::cout << message << ": "
<< bt.trans_vec[0] << ", " << bt.trans_vec[1] << ", " << bt.trans_vec[2] << " | "
<< bt.rot_quat[0] << ", " << bt.rot_quat[1] << ", " << bt.rot_quat[2] << ", " << bt.rot_quat[3] << "\n";
}
// Difference the transform and scale by elapsed time:
BotTrans FovisHandler::getTransAsVelocityTrans(BotTrans msgT, int64_t utime, int64_t prev_utime){
Eigen::Isometry3d msgE = pronto::getBotTransAsEigen(msgT);
Eigen::Isometry3d msgE_vel = pronto::getDeltaAsVelocity(msgE, (utime-prev_utime) );
BotTrans msgT_vel;
msgT_vel = pronto::getEigenAsBotTrans(msgE_vel);
return msgT_vel;
}
/// Publishing Functions
// Convert the delta position into a velocity
// as a bot_pose message for visualization with signal scope:
void FovisHandler::sendTransAsVelocityPose(BotTrans msgT, int64_t utime, int64_t prev_utime, std::string channel){
BotTrans msgT_vel = getTransAsVelocityTrans(msgT, utime, prev_utime);
bot_core::pose_t vel_pose = getBotTransAsBotPoseVelocity(msgT_vel, utime) ;
lcm_pub->publish(channel, &vel_pose );
}
} // end of namespace
<|endoftext|> |
<commit_before>/*
* Copyright 2012 BrewPi/Elco Jacobs.
*
* This file is part of BrewPi.
*
* BrewPi 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.
*
* BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Brewpi.h"
#include "RotaryEncoder.h"
#include "Pins.h"
#include "util/atomic.h"
#include <limits.h>
#include "Ticks.h"
#include "Display.h"
#include "FastDigitalPin.h"
#include "Brewpi.h"
RotaryEncoder rotaryEncoder;
#if rotarySwitchPin != 7
#error Review interrupt vectors when not using pin 7 for menu push
#endif
#if rotaryAPin != 8
#error Review interrupt vectors when not using pin 8 for menu right
#endif
#if rotaryBPin != 9
#error Review interrupt vectors when not using pin 9 for menu left
#endif
// Implementation based on work of Ben Buxton:
/* Rotary encoder handler for arduino. v1.1
*
* Copyright 2011 Ben Buxton. Licenced under the GNU GPL Version 3.
* Contact: [email protected]
*
* A typical mechanical rotary encoder emits a two bit gray code
* on 3 output pins. Every step in the output (often accompanied
* by a physical 'click') generates a specific sequence of output
* codes on the pins.
*
* There are 3 pins used for the rotary encoding - one common and
* two 'bit' pins.
*
* The following is the typical sequence of code on the output when
* moving from one step to the next:
*
* Position Bit1 Bit2
* ----------------------
* Step1 0 0
* 1/4 1 0
* 1/2 1 1
* 3/4 0 1
* Step2 0 0
*
* From this table, we can see that when moving from one 'click' to
* the next, there are 4 changes in the output code.
*
* - From an initial 0 - 0, Bit1 goes high, Bit0 stays low.
* - Then both bits are high, halfway through the step.
* - Then Bit1 goes low, but Bit2 stays high.
* - Finally at the end of the step, both bits return to 0.
*
* Detecting the direction is easy - the table simply goes in the other
* direction (read up instead of down).
*
* To decode this, we use a simple state machine. Every time the output
* code changes, it follows state, until finally a full steps worth of
* code is received (in the correct order). At the final 0-0, it returns
* a value indicating a step in one direction or the other.
*
* It's also possible to use 'half-step' mode. This just emits an event
* at both the 0-0 and 1-1 positions. This might be useful for some
* encoders where you want to detect all positions.
*
* If an invalid state happens (for example we go from '0-1' straight
* to '1-0'), the state machine resets to the start until 0-0 and the
* next valid codes occur.
*
* The biggest advantage of using a state machine over other algorithms
* is that this has inherent debounce built in. Other algorithms emit spurious
* output with switch bounce, but this one will simply flip between
* sub-states until the bounce settles, then continue along the state
* machine.
* A side effect of debounce is that fast rotations can cause steps to
* be skipped. By not requiring debounce, fast rotations can be accurately
* measured.
* Another advantage is the ability to properly handle bad state, such
* as due to EMI, etc.
* It is also a lot simpler than others - a static state table and less
* than 10 lines of logic.
*/
/*
* The below state table has, for each state (row), the new state
* to set based on the next encoder output. From left to right in,
* the table, the encoder outputs are 00, 01, 10, 11, and the value
* in that position is the new state to set.
*/
#define R_START 0x0
// #define HALF_STEP
#ifdef HALF_STEP
// Use the half-step state table (emits a code at 00 and 11)
#define R_CCW_BEGIN 0x1
#define R_CW_BEGIN 0x2
#define R_START_M 0x3
#define R_CW_BEGIN_M 0x4
#define R_CCW_BEGIN_M 0x5
const unsigned char PROGMEM ttable[6][4] = {
// R_START (00)
{R_START_M, R_CW_BEGIN, R_CCW_BEGIN, R_START},
// R_CCW_BEGIN
{R_START_M | DIR_CCW, R_START, R_CCW_BEGIN, R_START},
// R_CW_BEGIN
{R_START_M | DIR_CW, R_CW_BEGIN, R_START, R_START},
// R_START_M (11)
{R_START_M, R_CCW_BEGIN_M, R_CW_BEGIN_M, R_START},
// R_CW_BEGIN_M
{R_START_M, R_START_M, R_CW_BEGIN_M, R_START | DIR_CW},
// R_CCW_BEGIN_M
{R_START_M, R_CCW_BEGIN_M, R_START_M, R_START | DIR_CCW},
};
#else
// Use the full-step state table (emits a code at 00 only)
#define R_CW_FINAL 0x1
#define R_CW_BEGIN 0x2
#define R_CW_NEXT 0x3
#define R_CCW_BEGIN 0x4
#define R_CCW_FINAL 0x5
#define R_CCW_NEXT 0x6
const unsigned char PROGMEM ttable[7][4] = {
// R_START
{R_START, R_CW_BEGIN, R_CCW_BEGIN, R_START},
// R_CW_FINAL
{R_CW_NEXT, R_START, R_CW_FINAL, R_START | DIR_CW},
// R_CW_BEGIN
{R_CW_NEXT, R_CW_BEGIN, R_START, R_START},
// R_CW_NEXT
{R_CW_NEXT, R_CW_BEGIN, R_CW_FINAL, R_START},
// R_CCW_BEGIN
{R_CCW_NEXT, R_START, R_CCW_BEGIN, R_START},
// R_CCW_FINAL
{R_CCW_NEXT, R_CCW_FINAL, R_START, R_START | DIR_CCW},
// R_CCW_NEXT
{R_CCW_NEXT, R_CCW_FINAL, R_CCW_BEGIN, R_START},
};
#endif
#if ENABLE_ROTARY_ENCODER
#if defined(USBCON)
// Arduino Leonardo
ISR(INT6_vect){
rotaryEncoder.setPushed();
}
#else
// Arduino UNO or older
ISR(PCINT2_vect){
if(!bitRead(PIND,7)){
// high to low transition
rotaryEncoder.setPushed();
}
}
#endif
ISR(PCINT0_vect){
rotaryEncoder.process();
}
#endif
void RotaryEncoder::process(void){
static uint8_t state = 0;
// Grab state of input pins.
#if defined(USBCON)
// Arduino Leonardo
uint8_t currPinA = !bitRead(PINB,4);
uint8_t currPinB = !bitRead(PINB,5);
#else
uint8_t currPinA = bitRead(PINB,0);
uint8_t currPinB = bitRead(PINB,1);
#endif
unsigned char pinstate = (currPinA << 1) | currPinB;
// Determine new state from the pins and state table.
state = pgm_read_byte(&(ttable[state & 0xf][pinstate]));
// Get emit bits, ie the generated event.
uint8_t dir = state & 0x30;
if(dir){
steps = (dir == DIR_CW) ? steps+1 : steps-1;
if(steps > maximum){
steps = minimum;
}
if(steps < minimum){
steps = maximum;
}
display.resetBacklightTimer();
}
}
void RotaryEncoder::setPushed(void){
pushFlag = true;
display.resetBacklightTimer();
}
void RotaryEncoder::init(void){
#if(USE_INTERNAL_PULL_UP_RESISTORS)
fastPinMode(rotaryAPin, INPUT_PULLUP);
fastPinMode(rotaryBPin, INPUT_PULLUP);
fastPinMode(rotarySwitchPin, INPUT_PULLUP);
#else
fastPinMode(rotaryAPin, INPUT);
fastPinMode(rotaryBPin, INPUT);
fastPinMode(rotarySwitchPin, INPUT);
#endif
#if ENABLE_ROTARY_ENCODER
#if defined(USBCON) // Arduino Leonardo
// falling edge interrupt for switch on INT6
EICRB |= (1<<ISC61) | (0<<ISC60);
// enable interrupt for INT6
EIMSK |= (1<<INT6);
// enable pin change interrupts
PCICR |= (1<<PCIE0);
// enable pin change interrupt on Arduino pin 8 and 9
PCMSK0 |= (1<<PCINT5) | (1<<PCINT4);
#else // Arduino UNO
// enable PCINT0 (PCINT0 and PCINT1 pin) and PCINT2 vector (PCINT23 pin)
PCICR |= (1<<PCIE2) | (1<<PCIE0);
// enable mask bits for PCINT0 and PCINT1
PCMSK0 |= (1<<PCINT0) | (1<<PCINT1);
// enable mask bit for PCINT23
PCMSK2 |= (1<<PCINT23);
#endif
#endif
}
void RotaryEncoder::setRange(int start, int minVal, int maxVal){
ATOMIC_BLOCK(ATOMIC_RESTORESTATE){
// this part cannot be interrupted
// Multiply by two to convert to half steps
steps = start;
minimum = minVal;
maximum = maxVal; // +1 to make sure that one step is still two half steps at overflow
prevRead = start;
}
}
bool RotaryEncoder::changed(void){
// returns one if the value changed since the last call of changed.
static int prevValue = 0;
if(read() != prevValue){
prevValue = read();
return 1;
}
if(pushFlag == true){
return 1;
}
return 0;
}
int RotaryEncoder::read(void){
ATOMIC_BLOCK(ATOMIC_RESTORESTATE){
prevRead = steps;
return prevRead;
}
return 0;
}
<commit_msg>corrected direction of rotary encoder<commit_after>/*
* Copyright 2012 BrewPi/Elco Jacobs.
*
* This file is part of BrewPi.
*
* BrewPi 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.
*
* BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Brewpi.h"
#include "RotaryEncoder.h"
#include "Pins.h"
#include "util/atomic.h"
#include <limits.h>
#include "Ticks.h"
#include "Display.h"
#include "FastDigitalPin.h"
#include "Brewpi.h"
RotaryEncoder rotaryEncoder;
#if rotarySwitchPin != 7
#error Review interrupt vectors when not using pin 7 for menu push
#endif
#if rotaryAPin != 8
#error Review interrupt vectors when not using pin 8 for menu right
#endif
#if rotaryBPin != 9
#error Review interrupt vectors when not using pin 9 for menu left
#endif
// Implementation based on work of Ben Buxton:
/* Rotary encoder handler for arduino. v1.1
*
* Copyright 2011 Ben Buxton. Licenced under the GNU GPL Version 3.
* Contact: [email protected]
*
* A typical mechanical rotary encoder emits a two bit gray code
* on 3 output pins. Every step in the output (often accompanied
* by a physical 'click') generates a specific sequence of output
* codes on the pins.
*
* There are 3 pins used for the rotary encoding - one common and
* two 'bit' pins.
*
* The following is the typical sequence of code on the output when
* moving from one step to the next:
*
* Position Bit1 Bit2
* ----------------------
* Step1 0 0
* 1/4 1 0
* 1/2 1 1
* 3/4 0 1
* Step2 0 0
*
* From this table, we can see that when moving from one 'click' to
* the next, there are 4 changes in the output code.
*
* - From an initial 0 - 0, Bit1 goes high, Bit0 stays low.
* - Then both bits are high, halfway through the step.
* - Then Bit1 goes low, but Bit2 stays high.
* - Finally at the end of the step, both bits return to 0.
*
* Detecting the direction is easy - the table simply goes in the other
* direction (read up instead of down).
*
* To decode this, we use a simple state machine. Every time the output
* code changes, it follows state, until finally a full steps worth of
* code is received (in the correct order). At the final 0-0, it returns
* a value indicating a step in one direction or the other.
*
* It's also possible to use 'half-step' mode. This just emits an event
* at both the 0-0 and 1-1 positions. This might be useful for some
* encoders where you want to detect all positions.
*
* If an invalid state happens (for example we go from '0-1' straight
* to '1-0'), the state machine resets to the start until 0-0 and the
* next valid codes occur.
*
* The biggest advantage of using a state machine over other algorithms
* is that this has inherent debounce built in. Other algorithms emit spurious
* output with switch bounce, but this one will simply flip between
* sub-states until the bounce settles, then continue along the state
* machine.
* A side effect of debounce is that fast rotations can cause steps to
* be skipped. By not requiring debounce, fast rotations can be accurately
* measured.
* Another advantage is the ability to properly handle bad state, such
* as due to EMI, etc.
* It is also a lot simpler than others - a static state table and less
* than 10 lines of logic.
*/
/*
* The below state table has, for each state (row), the new state
* to set based on the next encoder output. From left to right in,
* the table, the encoder outputs are 00, 01, 10, 11, and the value
* in that position is the new state to set.
*/
#define R_START 0x0
// #define HALF_STEP
#ifdef HALF_STEP
// Use the half-step state table (emits a code at 00 and 11)
#define R_CCW_BEGIN 0x1
#define R_CW_BEGIN 0x2
#define R_START_M 0x3
#define R_CW_BEGIN_M 0x4
#define R_CCW_BEGIN_M 0x5
const unsigned char PROGMEM ttable[6][4] = {
// R_START (00)
{R_START_M, R_CW_BEGIN, R_CCW_BEGIN, R_START},
// R_CCW_BEGIN
{R_START_M | DIR_CCW, R_START, R_CCW_BEGIN, R_START},
// R_CW_BEGIN
{R_START_M | DIR_CW, R_CW_BEGIN, R_START, R_START},
// R_START_M (11)
{R_START_M, R_CCW_BEGIN_M, R_CW_BEGIN_M, R_START},
// R_CW_BEGIN_M
{R_START_M, R_START_M, R_CW_BEGIN_M, R_START | DIR_CW},
// R_CCW_BEGIN_M
{R_START_M, R_CCW_BEGIN_M, R_START_M, R_START | DIR_CCW},
};
#else
// Use the full-step state table (emits a code at 00 only)
#define R_CW_FINAL 0x1
#define R_CW_BEGIN 0x2
#define R_CW_NEXT 0x3
#define R_CCW_BEGIN 0x4
#define R_CCW_FINAL 0x5
#define R_CCW_NEXT 0x6
const unsigned char PROGMEM ttable[7][4] = {
// R_START
{R_START, R_CW_BEGIN, R_CCW_BEGIN, R_START},
// R_CW_FINAL
{R_CW_NEXT, R_START, R_CW_FINAL, R_START | DIR_CW},
// R_CW_BEGIN
{R_CW_NEXT, R_CW_BEGIN, R_START, R_START},
// R_CW_NEXT
{R_CW_NEXT, R_CW_BEGIN, R_CW_FINAL, R_START},
// R_CCW_BEGIN
{R_CCW_NEXT, R_START, R_CCW_BEGIN, R_START},
// R_CCW_FINAL
{R_CCW_NEXT, R_CCW_FINAL, R_START, R_START | DIR_CCW},
// R_CCW_NEXT
{R_CCW_NEXT, R_CCW_FINAL, R_CCW_BEGIN, R_START},
};
#endif
#if ENABLE_ROTARY_ENCODER
#if defined(USBCON)
// Arduino Leonardo
ISR(INT6_vect){
rotaryEncoder.setPushed();
}
#else
// Arduino UNO or older
ISR(PCINT2_vect){
if(!bitRead(PIND,7)){
// high to low transition
rotaryEncoder.setPushed();
}
}
#endif
ISR(PCINT0_vect){
rotaryEncoder.process();
}
#endif
void RotaryEncoder::process(void){
static uint8_t state = 0;
// Grab state of input pins.
#if defined(USBCON)
// Arduino Leonardo
uint8_t currPinA = !bitRead(PINB,4);
uint8_t currPinB = !bitRead(PINB,5);
#else
uint8_t currPinA = bitRead(PINB,0);
uint8_t currPinB = bitRead(PINB,1);
#endif
unsigned char pinstate = (currPinB << 1) | currPinA;
// Determine new state from the pins and state table.
state = pgm_read_byte(&(ttable[state & 0xf][pinstate]));
// Get emit bits, ie the generated event.
uint8_t dir = state & 0x30;
if(dir){
steps = (dir == DIR_CW) ? steps+1 : steps-1;
if(steps > maximum){
steps = minimum;
}
if(steps < minimum){
steps = maximum;
}
display.resetBacklightTimer();
}
}
void RotaryEncoder::setPushed(void){
pushFlag = true;
display.resetBacklightTimer();
}
void RotaryEncoder::init(void){
#if(USE_INTERNAL_PULL_UP_RESISTORS)
fastPinMode(rotaryAPin, INPUT_PULLUP);
fastPinMode(rotaryBPin, INPUT_PULLUP);
fastPinMode(rotarySwitchPin, INPUT_PULLUP);
#else
fastPinMode(rotaryAPin, INPUT);
fastPinMode(rotaryBPin, INPUT);
fastPinMode(rotarySwitchPin, INPUT);
#endif
#if ENABLE_ROTARY_ENCODER
#if defined(USBCON) // Arduino Leonardo
// falling edge interrupt for switch on INT6
EICRB |= (1<<ISC61) | (0<<ISC60);
// enable interrupt for INT6
EIMSK |= (1<<INT6);
// enable pin change interrupts
PCICR |= (1<<PCIE0);
// enable pin change interrupt on Arduino pin 8 and 9
PCMSK0 |= (1<<PCINT5) | (1<<PCINT4);
#else // Arduino UNO
// enable PCINT0 (PCINT0 and PCINT1 pin) and PCINT2 vector (PCINT23 pin)
PCICR |= (1<<PCIE2) | (1<<PCIE0);
// enable mask bits for PCINT0 and PCINT1
PCMSK0 |= (1<<PCINT0) | (1<<PCINT1);
// enable mask bit for PCINT23
PCMSK2 |= (1<<PCINT23);
#endif
#endif
}
void RotaryEncoder::setRange(int start, int minVal, int maxVal){
ATOMIC_BLOCK(ATOMIC_RESTORESTATE){
// this part cannot be interrupted
// Multiply by two to convert to half steps
steps = start;
minimum = minVal;
maximum = maxVal; // +1 to make sure that one step is still two half steps at overflow
prevRead = start;
}
}
bool RotaryEncoder::changed(void){
// returns one if the value changed since the last call of changed.
static int prevValue = 0;
if(read() != prevValue){
prevValue = read();
return 1;
}
if(pushFlag == true){
return 1;
}
return 0;
}
int RotaryEncoder::read(void){
ATOMIC_BLOCK(ATOMIC_RESTORESTATE){
prevRead = steps;
return prevRead;
}
return 0;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Copyright (c) 2014, Jan Koester [email protected]
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include <algorithm>
#include <mutex>
#include <config.h>
#include "connections.h"
using namespace libhttppp;
const char* ConnectionData::getData(){
return _Data;
}
size_t ConnectionData::getDataSize(){
return _DataSize;
}
ConnectionData *ConnectionData::nextConnectionData(){
return _nextConnectionData;
}
ConnectionData::ConnectionData(const char*data,size_t datasize){
_nextConnectionData=NULL;
std::copy(data,data+datasize,_Data);
_DataSize=datasize;
}
ConnectionData::~ConnectionData(){
if(_nextConnectionData)
delete _nextConnectionData;
}
ClientSocket *Connection::getClientSocket(){
return _ClientSocket;
}
Connection *Connection::nextConnection(){
return _nextConnection;
}
/** \brief a method to add Data to Sendqueue
* \param data an const char* to add to sendqueue
* \param datasize an size_t to set datasize
* \return the last ConnectionData Block from Sendqueue
*
* This method does unbelievably useful things.
* And returns exceptionally the new connection data block.
* Use it everyday with good health.
*/
ConnectionData *Connection::addSendQueue(const char*data,size_t datasize){
size_t written=0;
for(size_t cursize=datasize; cursize>0; cursize=datasize-written){
if(cursize>BLOCKSIZE){
cursize=BLOCKSIZE;
}
if(!_SendDataFirst){
_SendDataFirst= new ConnectionData(data+written,cursize);
_SendDataLast=_SendDataFirst;
}else{
_SendDataLast->_nextConnectionData=new ConnectionData(data+written,cursize);
_SendDataLast=_SendDataLast->_nextConnectionData;
}
written+=cursize;
}
_SendDataSize+=written;
return _SendDataLast;
}
void Connection::cleanSendData(){
if(_SendDataFirst)
delete _SendDataFirst;
_SendDataFirst=NULL;
_SendDataLast=NULL;
_SendDataSize=0;
}
ConnectionData *Connection::resizeSendQueue(size_t size){
return _resizeQueue(&_SendDataFirst,&_SendDataLast,&_SendDataSize,size);
}
ConnectionData* Connection::getSendData(){
return _SendDataFirst;
}
size_t Connection::getSendSize(){
return _SendDataSize;
}
ConnectionData *Connection::addRecvQueue(const char data[BLOCKSIZE],size_t datasize){
if(!_ReadDataFirst){
_ReadDataFirst= new ConnectionData(data,datasize);
_ReadDataLast=_ReadDataFirst;
}else{
_ReadDataLast->_nextConnectionData=new ConnectionData(data,datasize);
_ReadDataLast=_ReadDataLast->_nextConnectionData;
}
std::copy(data,data+datasize,_ReadDataLast->_Data);
_ReadDataLast->_DataSize=datasize;
_ReadDataSize+=datasize;
return _ReadDataLast;
}
void Connection::cleanRecvData(){
delete _ReadDataFirst;
_ReadDataFirst=NULL;
_ReadDataLast=NULL;
_ReadDataSize=0;
}
ConnectionData *Connection::resizeRecvQueue(size_t size){
return _resizeQueue(&_ReadDataFirst,&_ReadDataLast,&_ReadDataSize,size);
}
ConnectionData *Connection::getRecvData(){
return _ReadDataFirst;
}
size_t Connection::getRecvSize(){
return _ReadDataSize;
}
ConnectionData *Connection::_resizeQueue(ConnectionData** firstdata, ConnectionData** lastdata,
size_t *qsize, size_t size){
ConnectionData *firstdat=*firstdata;
while(firstdata && size!=0){
size_t delsize=0;
if(size<=firstdat->getDataSize()){
delsize=firstdat->getDataSize();
ConnectionData *deldat=*firstdata;
*firstdata=firstdat->_nextConnectionData;
if(deldat==*lastdata)
*lastdata=*firstdata;
deldat->_nextConnectionData=NULL;
delete deldat;
}else{
delsize=size;
firstdat->_DataSize-=size;
}
size-=delsize;
*qsize-=delsize;
}
return firstdat;
}
int Connection::copyValue(ConnectionData* startblock, int startpos,
ConnectionData* endblock, int endpos, char** buffer){
size_t copysize=0,copypos=0;
for(ConnectionData *curdat=startblock; curdat; curdat=curdat->nextConnectionData()){
if(curdat==endblock){
copysize+=endpos;
break;
}
copysize+=curdat->getDataSize();
}
copysize-=startpos;
char *buf;
buf = new char[(copysize+1)]; //one more for termination
for(ConnectionData *curdat=startblock; curdat; curdat=curdat->nextConnectionData()){
if(curdat==startblock){
std::copy(curdat->_Data+startpos,curdat->_Data+(curdat->getDataSize()-startpos),buf+copypos);
copypos+=curdat->getDataSize()-startpos;
}else if(curdat==endblock){
std::copy(curdat->_Data,curdat->_Data+endpos,buf+copypos);
copypos+=endpos;
}else{
std::copy(curdat->_Data,curdat->_Data+curdat->getDataSize(),buf+copypos);
copypos+=curdat->getDataSize();
}
if(curdat==endblock)
break;
}
buf[copysize+1]='\0';
*buffer=buf;
return copysize; //not include termination
}
int Connection::searchValue(ConnectionData* startblock, ConnectionData** findblock,
const char* keyword){
return searchValue(startblock, findblock, keyword,strlen(keyword));
}
int Connection::searchValue(ConnectionData* startblock, ConnectionData** findblock,
const char* keyword,size_t keylen){
size_t fpos=0,fcurpos=0;
for(ConnectionData *curdat=startblock; curdat; curdat=curdat->nextConnectionData()){
for(size_t pos=0; pos<curdat->getDataSize(); pos++){
if(keyword[fcurpos]==curdat->_Data[pos]){
if(fcurpos==0){
fpos=pos;
*findblock=curdat;
}
fcurpos++;
}else{
fcurpos=0;
fpos=0;
*findblock=NULL;
}
if(fcurpos==keylen)
return fpos;
}
}
return -1;
}
bool Connection::tryLock(){
try{
_Locked->try_lock();
return true;
}catch(HTTPException &e){
return false;
}
}
bool Connection::tryUnlock(){
try{
_Locked->unlock();
return true;
}catch(HTTPException &e){
return false;
}
}
Connection::Connection(){
_ClientSocket=new ClientSocket;
_nextConnection=NULL;
_ReadDataFirst=NULL;
_ReadDataLast=NULL;
_ReadDataSize=0;
_SendDataFirst=NULL;
_SendDataLast=NULL;
_SendDataSize=0;
}
Connection::~Connection(){
delete _ClientSocket;
delete _ReadDataFirst;
delete _SendDataFirst;
delete _nextConnection;
}
ConnectionPool::ConnectionPool(ServerSocket *socket){
_firstConnection=NULL;
_lastConnection=NULL;
_ServerSocket=socket;
if(!_ServerSocket){
_httpexception.Cirtical("ServerSocket not set!");
throw _httpexception;
}
}
ConnectionPool::~ConnectionPool(){
delete _firstConnection;
}
Connection* ConnectionPool::addConnection(){
if(!_firstConnection){
_firstConnection=new Connection;
_lastConnection=_firstConnection;
}else{
_lastConnection->_nextConnection=new Connection;
_lastConnection=_lastConnection->_nextConnection;
}
return _lastConnection;
}
#ifndef Windows
Connection* ConnectionPool::delConnection(int socket){
return delConnection(getConnection(socket));
}
#else
Connection* ConnectionPool::delConnection(SOCKET socket){
return delConnection(getConnection(socket));
}
#endif
Connection* ConnectionPool::delConnection(ClientSocket *clientsocket){
return delConnection(getConnection(clientsocket));
}
Connection* ConnectionPool::delConnection(Connection *delcon){
Connection *prevcon=NULL;
for(Connection *curcon=_firstConnection; curcon; curcon=curcon->nextConnection()){
if(curcon==delcon){
if(prevcon){
prevcon->_nextConnection=curcon->_nextConnection;
if(_lastConnection==delcon)
_lastConnection=prevcon;
}else{
_firstConnection=curcon->_nextConnection;
if(_lastConnection==delcon)
_lastConnection=_firstConnection;
}
curcon->_nextConnection=NULL;
delete curcon;
break;
}
prevcon=curcon;
}
if(prevcon && prevcon->_nextConnection)
return prevcon->_nextConnection;
else
return _firstConnection;
}
Connection* ConnectionPool::getConnection(ClientSocket *clientsocket){
for(Connection *curcon=_firstConnection; curcon; curcon=curcon->nextConnection()){
if(curcon->getClientSocket()==clientsocket)
return curcon;
}
return NULL;
}
#ifndef Windows
Connection* ConnectionPool::getConnection(int socket){
#else
Connection* ConnectionPool::getConnection(SOCKET socket){
#endif
for(Connection *curcon=_firstConnection; curcon; curcon=curcon->nextConnection()){
if(curcon->getClientSocket()->getSocket()==socket)
return curcon;
}
return NULL;
}<commit_msg>added forgotten case to copyvalue<commit_after>/*******************************************************************************
Copyright (c) 2014, Jan Koester [email protected]
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include <algorithm>
#include <mutex>
#include <config.h>
#include "connections.h"
using namespace libhttppp;
const char* ConnectionData::getData(){
return _Data;
}
size_t ConnectionData::getDataSize(){
return _DataSize;
}
ConnectionData *ConnectionData::nextConnectionData(){
return _nextConnectionData;
}
ConnectionData::ConnectionData(const char*data,size_t datasize){
_nextConnectionData=NULL;
std::copy(data,data+datasize,_Data);
_DataSize=datasize;
}
ConnectionData::~ConnectionData(){
if(_nextConnectionData)
delete _nextConnectionData;
}
ClientSocket *Connection::getClientSocket(){
return _ClientSocket;
}
Connection *Connection::nextConnection(){
return _nextConnection;
}
/** \brief a method to add Data to Sendqueue
* \param data an const char* to add to sendqueue
* \param datasize an size_t to set datasize
* \return the last ConnectionData Block from Sendqueue
*
* This method does unbelievably useful things.
* And returns exceptionally the new connection data block.
* Use it everyday with good health.
*/
ConnectionData *Connection::addSendQueue(const char*data,size_t datasize){
size_t written=0;
for(size_t cursize=datasize; cursize>0; cursize=datasize-written){
if(cursize>BLOCKSIZE){
cursize=BLOCKSIZE;
}
if(!_SendDataFirst){
_SendDataFirst= new ConnectionData(data+written,cursize);
_SendDataLast=_SendDataFirst;
}else{
_SendDataLast->_nextConnectionData=new ConnectionData(data+written,cursize);
_SendDataLast=_SendDataLast->_nextConnectionData;
}
written+=cursize;
}
_SendDataSize+=written;
return _SendDataLast;
}
void Connection::cleanSendData(){
if(_SendDataFirst)
delete _SendDataFirst;
_SendDataFirst=NULL;
_SendDataLast=NULL;
_SendDataSize=0;
}
ConnectionData *Connection::resizeSendQueue(size_t size){
return _resizeQueue(&_SendDataFirst,&_SendDataLast,&_SendDataSize,size);
}
ConnectionData* Connection::getSendData(){
return _SendDataFirst;
}
size_t Connection::getSendSize(){
return _SendDataSize;
}
ConnectionData *Connection::addRecvQueue(const char data[BLOCKSIZE],size_t datasize){
if(!_ReadDataFirst){
_ReadDataFirst= new ConnectionData(data,datasize);
_ReadDataLast=_ReadDataFirst;
}else{
_ReadDataLast->_nextConnectionData=new ConnectionData(data,datasize);
_ReadDataLast=_ReadDataLast->_nextConnectionData;
}
std::copy(data,data+datasize,_ReadDataLast->_Data);
_ReadDataLast->_DataSize=datasize;
_ReadDataSize+=datasize;
return _ReadDataLast;
}
void Connection::cleanRecvData(){
delete _ReadDataFirst;
_ReadDataFirst=NULL;
_ReadDataLast=NULL;
_ReadDataSize=0;
}
ConnectionData *Connection::resizeRecvQueue(size_t size){
return _resizeQueue(&_ReadDataFirst,&_ReadDataLast,&_ReadDataSize,size);
}
ConnectionData *Connection::getRecvData(){
return _ReadDataFirst;
}
size_t Connection::getRecvSize(){
return _ReadDataSize;
}
ConnectionData *Connection::_resizeQueue(ConnectionData** firstdata, ConnectionData** lastdata,
size_t *qsize, size_t size){
ConnectionData *firstdat=*firstdata;
while(firstdata && size!=0){
size_t delsize=0;
if(size<=firstdat->getDataSize()){
delsize=firstdat->getDataSize();
ConnectionData *deldat=*firstdata;
*firstdata=firstdat->_nextConnectionData;
if(deldat==*lastdata)
*lastdata=*firstdata;
deldat->_nextConnectionData=NULL;
delete deldat;
}else{
delsize=size;
firstdat->_DataSize-=size;
}
size-=delsize;
*qsize-=delsize;
}
return firstdat;
}
int Connection::copyValue(ConnectionData* startblock, int startpos,
ConnectionData* endblock, int endpos, char** buffer){
size_t copysize=0,copypos=0;
for(ConnectionData *curdat=startblock; curdat; curdat=curdat->nextConnectionData()){
if(curdat==endblock){
copysize+=endpos;
break;
}
copysize+=curdat->getDataSize();
}
copysize-=startpos;
char *buf;
buf = new char[(copysize+1)]; //one more for termination
for(ConnectionData *curdat=startblock; curdat; curdat=curdat->nextConnectionData()){
if(curdat==startblock && curdat==endblock){
std::copy(curdat->_Data+startpos,curdat->_Data+(endpos-startpos),buf+copypos);
}else if(curdat==startblock){
std::copy(curdat->_Data+startpos,curdat->_Data+(curdat->getDataSize()-startpos),buf+copypos);
copypos+=curdat->getDataSize()-startpos;
}else if(curdat==endblock){
std::copy(curdat->_Data,curdat->_Data+endpos,buf+copypos);
copypos+=endpos;
}else{
std::copy(curdat->_Data,curdat->_Data+curdat->getDataSize(),buf+copypos);
copypos+=curdat->getDataSize();
}
if(curdat==endblock)
break;
}
buf[copysize]='\0';
*buffer=buf;
return copysize; //not include termination
}
int Connection::searchValue(ConnectionData* startblock, ConnectionData** findblock,
const char* keyword){
return searchValue(startblock, findblock, keyword,strlen(keyword));
}
int Connection::searchValue(ConnectionData* startblock, ConnectionData** findblock,
const char* keyword,size_t keylen){
size_t fpos=0,fcurpos=0;
for(ConnectionData *curdat=startblock; curdat; curdat=curdat->nextConnectionData()){
for(size_t pos=0; pos<curdat->getDataSize(); pos++){
if(keyword[fcurpos]==curdat->_Data[pos]){
if(fcurpos==0){
fpos=pos;
*findblock=curdat;
}
fcurpos++;
}else{
fcurpos=0;
fpos=0;
*findblock=NULL;
}
if(fcurpos==keylen)
return fpos;
}
}
return -1;
}
bool Connection::tryLock(){
try{
_Locked->try_lock();
return true;
}catch(HTTPException &e){
return false;
}
}
bool Connection::tryUnlock(){
try{
_Locked->unlock();
return true;
}catch(HTTPException &e){
return false;
}
}
Connection::Connection(){
_ClientSocket=new ClientSocket;
_nextConnection=NULL;
_ReadDataFirst=NULL;
_ReadDataLast=NULL;
_ReadDataSize=0;
_SendDataFirst=NULL;
_SendDataLast=NULL;
_SendDataSize=0;
}
Connection::~Connection(){
delete _ClientSocket;
delete _ReadDataFirst;
delete _SendDataFirst;
delete _nextConnection;
}
ConnectionPool::ConnectionPool(ServerSocket *socket){
_firstConnection=NULL;
_lastConnection=NULL;
_ServerSocket=socket;
if(!_ServerSocket){
_httpexception.Cirtical("ServerSocket not set!");
throw _httpexception;
}
}
ConnectionPool::~ConnectionPool(){
delete _firstConnection;
}
Connection* ConnectionPool::addConnection(){
if(!_firstConnection){
_firstConnection=new Connection;
_lastConnection=_firstConnection;
}else{
_lastConnection->_nextConnection=new Connection;
_lastConnection=_lastConnection->_nextConnection;
}
return _lastConnection;
}
#ifndef Windows
Connection* ConnectionPool::delConnection(int socket){
return delConnection(getConnection(socket));
}
#else
Connection* ConnectionPool::delConnection(SOCKET socket){
return delConnection(getConnection(socket));
}
#endif
Connection* ConnectionPool::delConnection(ClientSocket *clientsocket){
return delConnection(getConnection(clientsocket));
}
Connection* ConnectionPool::delConnection(Connection *delcon){
Connection *prevcon=NULL;
for(Connection *curcon=_firstConnection; curcon; curcon=curcon->nextConnection()){
if(curcon==delcon){
if(prevcon){
prevcon->_nextConnection=curcon->_nextConnection;
if(_lastConnection==delcon)
_lastConnection=prevcon;
}else{
_firstConnection=curcon->_nextConnection;
if(_lastConnection==delcon)
_lastConnection=_firstConnection;
}
curcon->_nextConnection=NULL;
delete curcon;
break;
}
prevcon=curcon;
}
if(prevcon && prevcon->_nextConnection)
return prevcon->_nextConnection;
else
return _firstConnection;
}
Connection* ConnectionPool::getConnection(ClientSocket *clientsocket){
for(Connection *curcon=_firstConnection; curcon; curcon=curcon->nextConnection()){
if(curcon->getClientSocket()==clientsocket)
return curcon;
}
return NULL;
}
#ifndef Windows
Connection* ConnectionPool::getConnection(int socket){
#else
Connection* ConnectionPool::getConnection(SOCKET socket){
#endif
for(Connection *curcon=_firstConnection; curcon; curcon=curcon->nextConnection()){
if(curcon->getClientSocket()->getSocket()==socket)
return curcon;
}
return NULL;
}<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief Library to build up VPack documents.
///
/// DISCLAIMER
///
/// Copyright 2015 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Jan Steemann
/// @author Copyright 2015, ArangoDB GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <chrono>
#include <thread>
#include "velocypack/vpack.h"
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "simdjson.h"
using namespace arangodb::velocypack;
enum ParserType {
VPACK,
RAPIDJSON,
SIMDJSON
};
static void usage(char* argv[]) {
std::cout << "Usage: " << argv[0]
<< " FILENAME.json RUNTIME_IN_SECONDS COPIES TYPE" << std::endl;
std::cout << "This program reads the file into a string, makes COPIES copies"
<< std::endl;
std::cout << "and then parses the copies in a round-robin fashion to VPack."
<< std::endl;
std::cout << "1 copy means its running in cache, more copies make it run"
<< std::endl;
std::cout << "out of cache. The target areas are also in a different memory"
<< std::endl;
std::cout << "area for each copy." << std::endl;
std::cout << "TYPE must b: vpack/rapidjson/simdjson." << std::endl;
}
static std::string tryReadFile(std::string const& filename) {
std::string s;
std::ifstream ifs(filename.c_str(), std::ifstream::in);
if (!ifs.is_open()) {
std::cerr << "Cannot open input file '" << filename << "'" << std::endl;
::exit(EXIT_FAILURE);
}
char buffer[4096];
while (ifs.good()) {
ifs.read(&buffer[0], sizeof(buffer));
s.append(buffer, ifs.gcount());
}
ifs.close();
return s;
}
static std::string readFile(std::string filename) {
#ifdef _WIN32
std::string const separator("\\");
#else
std::string const separator("/");
#endif
filename = "tests" + separator + "jsonSample" + separator + filename;
for (size_t i = 0; i < 3; ++i) {
try {
return tryReadFile(filename);
} catch (...) {
filename = ".." + separator + filename;
}
}
throw "cannot open input file";
}
static ValueType fromSimdJsonType(simdjson::dom::element_type type) {
using etype = simdjson::dom::element_type;
switch (type) {
case etype::ARRAY: return ValueType::Array;
case etype::OBJECT: return ValueType::Object;
case etype::BOOL: return ValueType::Bool;
case etype::INT64: return ValueType::Int;
case etype::UINT64: return ValueType::UInt;
case etype::STRING: return ValueType::String;
case etype::DOUBLE: return ValueType::Double;
case etype::NULL_VALUE: return ValueType::Null;
default:
assert(false);
}
}
static Value drain_simdjson(simdjson::dom::element& doc, Builder* builder, bool opened) {
using namespace simdjson;
// std::cerr << opened << " parsing: " << doc.type() << " " << doc << std::endl;
switch (doc.type()) {
case dom::element_type::OBJECT: {
if (!opened) {
builder->add(Value(ValueType::Object));
}
for (auto field : doc.get_object()) {
auto subType = fromSimdJsonType(field.value.type());
if (subType == ValueType::Array || subType == ValueType::Object) {
builder->add(field.key, Value(subType));
drain_simdjson(field.value, builder, true);
builder->close();
} else {
Value sub = drain_simdjson(field.value, builder, true);
builder->add(field.key, sub);
}
}
if (!opened) {
builder->close();
}
return Value(ValueType::Object);
}
case dom::element_type::ARRAY: {
if (!opened) {
builder->add(Value(ValueType::Array));
}
for (auto field : doc.get_array()) {
auto subType = fromSimdJsonType(field.type());
if (subType == ValueType::Array || subType == ValueType::Object) {
builder->add(Value(subType));
drain_simdjson(field, builder, true);
builder->close();
} else {
Value sub = drain_simdjson(field, builder, false);
builder->add(sub);
}
}
if (!opened) {
builder->close();
}
return Value(ValueType::Array);
}
case dom::element_type::INT64:
return (Value(doc.get_int64()));
case dom::element_type::UINT64:
return (Value(doc.get_uint64()));
case dom::element_type::DOUBLE:
return (Value(doc.get_double()));
case dom::element_type::STRING:
return (Value(doc.get_c_str()));
case dom::element_type::BOOL:
return (Value(doc.get_bool()));
case dom::element_type::NULL_VALUE:
return (Value(ValueType::Null));
}
}
static void run(std::string& data, int runTime, size_t copies, ParserType parserType,
bool fullOutput) {
Options options;
std::vector<std::string> inputs;
std::vector<Parser*> outputs;
inputs.push_back(data);
outputs.push_back(new Parser(&options));
for (size_t i = 1; i < copies; i++) {
// Make an explicit copy:
data.clear();
data.insert(data.begin(), inputs[0].begin(), inputs[0].end());
inputs.push_back(data);
outputs.push_back(new Parser(&options));
}
for (auto& input : inputs) {
input.reserve(input.size() + simdjson::SIMDJSON_PADDING);
}
size_t count = 0;
size_t total = 0;
auto start = std::chrono::high_resolution_clock::now();
decltype(start) now;
simdjson::dom::parser parser;
Builder simd_buffer;
try {
do {
for (int i = 0; i < 2; i++) {
switch (parserType) {
case VPACK: {
outputs[count]->clear();
outputs[count]->parse(inputs[count]);
break;
}
case RAPIDJSON: {
rapidjson::Document d;
d.Parse(inputs[count].c_str());
break;
}
case SIMDJSON: {
simdjson::dom::element doc;
auto error = parser.parse(inputs[count]).get(doc);
if (error) {
std::cerr << "simdjson parse failed" << error << std::endl;
exit(EXIT_FAILURE);
}
simd_buffer.clear();
drain_simdjson(doc, &simd_buffer, false);
break;
}
}
count++;
if (count >= copies) {
count = 0;
}
total++;
}
now = std::chrono::high_resolution_clock::now();
} while (std::chrono::duration_cast<std::chrono::duration<int>>(now - start)
.count() < runTime);
std::chrono::duration<double> totalTime =
std::chrono::duration_cast<std::chrono::duration<double>>(now - start);
if (fullOutput) {
std::cout << "Total runtime: " << totalTime.count() << " s" << std::endl;
std::cout << "Have parsed " << total << " times with "
<< parserType << " using " << copies
<< " copies of JSON data, each of size " << inputs[0].size()
<< "." << std::endl;
std::cout << "Parsed " << inputs[0].size() * total << " bytes in total."
<< std::endl;
}
std::cout << std::setprecision(2) << std::fixed
<< " | "
<< std::setw(14)
<< static_cast<double>(inputs[0].size() * total) /
totalTime.count() << " bytes/s"
<< " | "
<< std::setw(14)
<< total / totalTime.count()
<< " | "
<< std::endl;
} catch (Exception const& ex) {
std::cerr << "An exception occurred while running bench: " << ex.what()
<< std::endl;
::exit(EXIT_FAILURE);
} catch (std::exception const& ex) {
std::cerr << "An exception occurred while running bench: " << ex.what()
<< std::endl;
::exit(EXIT_FAILURE);
} catch (...) {
std::cerr << "An unknown exception occurred while running bench"
<< std::endl;
::exit(EXIT_FAILURE);
}
for (auto& it : outputs) {
delete it;
}
}
static void runDefaultBench(bool all) {
bool fullOutput = !all;
int runSeconds = all ? 5 : 10;
auto runComparison = [&](std::string const& filename) {
std::string data = std::move(readFile(filename));
std::cout << std::endl;
std::cout << "# " << filename << " ";
for (size_t i = 0; i < 30 - filename.size(); ++i) {
std::cout << "#";
}
std::cout << std::endl;
std::cout << "|" << filename << " | " << "vpack ";
run(data, runSeconds, 1, ParserType::VPACK, fullOutput);
std::cout << "|" << filename << " | " << "rapidjson ";
run(data, runSeconds, 1, ParserType::RAPIDJSON, fullOutput);
std::cout << "|" << filename << " | " << "simdjson ";
run(data, runSeconds, 1, ParserType::SIMDJSON, fullOutput);
};
std::vector<std::string> files = {
// default
"small.json",
"sample.json",
"sampleNoWhite.json",
"commits.json",
// all dataset
"api-docs.json",
"countries.json",
"directory-tree.json",
"doubles-small.json",
"doubles.json",
"file-list.json",
"object.json",
"pass1.json",
"pass2.json",
"pass3.json",
"random1.json",
"random2.json",
"random3.json"
};
int dataSetSize = all ? files.size() : 4;
for (int i = 0; i < dataSetSize; i++) {
runComparison(files[i]);
}
}
int main(int argc, char* argv[]) {
if (argc == 1) {
runDefaultBench(false);
return EXIT_FAILURE;
}
if (argc == 2 && ::strcmp(argv[1], "all") == 0) {
runDefaultBench(true);
return EXIT_FAILURE;
}
if (argc != 5) {
usage(argv);
return EXIT_FAILURE;
}
ParserType parserType = ParserType::VPACK;
if (::strcmp(argv[4], "vpack") == 0) {
parserType = ParserType::VPACK;
} else if (::strcmp(argv[4], "rapidjson") == 0) {
parserType = ParserType::RAPIDJSON;
} else if (::strcmp(argv[4], "simdjson") == 0) {
parserType = ParserType::SIMDJSON;
} else {
usage(argv);
return EXIT_FAILURE;
}
size_t copies = std::stoul(argv[3]);
int runTime = std::stoi(argv[2]);
// read input file
std::string s = std::move(readFile(argv[1]));
run(s, runTime, copies, parserType, true);
return EXIT_SUCCESS;
}
<commit_msg>Update tools/bench.cpp<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief Library to build up VPack documents.
///
/// DISCLAIMER
///
/// Copyright 2015 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Jan Steemann
/// @author Copyright 2015, ArangoDB GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <chrono>
#include <thread>
#include "velocypack/vpack.h"
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "simdjson.h"
using namespace arangodb::velocypack;
enum ParserType {
VPACK,
RAPIDJSON,
SIMDJSON
};
static void usage(char* argv[]) {
std::cout << "Usage: " << argv[0]
<< " FILENAME.json RUNTIME_IN_SECONDS COPIES TYPE" << std::endl;
std::cout << "This program reads the file into a string, makes COPIES copies"
<< std::endl;
std::cout << "and then parses the copies in a round-robin fashion to VPack."
<< std::endl;
std::cout << "1 copy means its running in cache, more copies make it run"
<< std::endl;
std::cout << "out of cache. The target areas are also in a different memory"
<< std::endl;
std::cout << "area for each copy." << std::endl;
std::cout << "TYPE must be: vpack/rapidjson/simdjson." << std::endl;
}
static std::string tryReadFile(std::string const& filename) {
std::string s;
std::ifstream ifs(filename.c_str(), std::ifstream::in);
if (!ifs.is_open()) {
std::cerr << "Cannot open input file '" << filename << "'" << std::endl;
::exit(EXIT_FAILURE);
}
char buffer[4096];
while (ifs.good()) {
ifs.read(&buffer[0], sizeof(buffer));
s.append(buffer, ifs.gcount());
}
ifs.close();
return s;
}
static std::string readFile(std::string filename) {
#ifdef _WIN32
std::string const separator("\\");
#else
std::string const separator("/");
#endif
filename = "tests" + separator + "jsonSample" + separator + filename;
for (size_t i = 0; i < 3; ++i) {
try {
return tryReadFile(filename);
} catch (...) {
filename = ".." + separator + filename;
}
}
throw "cannot open input file";
}
static ValueType fromSimdJsonType(simdjson::dom::element_type type) {
using etype = simdjson::dom::element_type;
switch (type) {
case etype::ARRAY: return ValueType::Array;
case etype::OBJECT: return ValueType::Object;
case etype::BOOL: return ValueType::Bool;
case etype::INT64: return ValueType::Int;
case etype::UINT64: return ValueType::UInt;
case etype::STRING: return ValueType::String;
case etype::DOUBLE: return ValueType::Double;
case etype::NULL_VALUE: return ValueType::Null;
default:
assert(false);
}
}
static Value drain_simdjson(simdjson::dom::element& doc, Builder* builder, bool opened) {
using namespace simdjson;
// std::cerr << opened << " parsing: " << doc.type() << " " << doc << std::endl;
switch (doc.type()) {
case dom::element_type::OBJECT: {
if (!opened) {
builder->add(Value(ValueType::Object));
}
for (auto field : doc.get_object()) {
auto subType = fromSimdJsonType(field.value.type());
if (subType == ValueType::Array || subType == ValueType::Object) {
builder->add(field.key, Value(subType));
drain_simdjson(field.value, builder, true);
builder->close();
} else {
Value sub = drain_simdjson(field.value, builder, true);
builder->add(field.key, sub);
}
}
if (!opened) {
builder->close();
}
return Value(ValueType::Object);
}
case dom::element_type::ARRAY: {
if (!opened) {
builder->add(Value(ValueType::Array));
}
for (auto field : doc.get_array()) {
auto subType = fromSimdJsonType(field.type());
if (subType == ValueType::Array || subType == ValueType::Object) {
builder->add(Value(subType));
drain_simdjson(field, builder, true);
builder->close();
} else {
Value sub = drain_simdjson(field, builder, false);
builder->add(sub);
}
}
if (!opened) {
builder->close();
}
return Value(ValueType::Array);
}
case dom::element_type::INT64:
return (Value(doc.get_int64()));
case dom::element_type::UINT64:
return (Value(doc.get_uint64()));
case dom::element_type::DOUBLE:
return (Value(doc.get_double()));
case dom::element_type::STRING:
return (Value(doc.get_c_str()));
case dom::element_type::BOOL:
return (Value(doc.get_bool()));
case dom::element_type::NULL_VALUE:
return (Value(ValueType::Null));
}
}
static void run(std::string& data, int runTime, size_t copies, ParserType parserType,
bool fullOutput) {
Options options;
std::vector<std::string> inputs;
std::vector<Parser*> outputs;
inputs.push_back(data);
outputs.push_back(new Parser(&options));
for (size_t i = 1; i < copies; i++) {
// Make an explicit copy:
data.clear();
data.insert(data.begin(), inputs[0].begin(), inputs[0].end());
inputs.push_back(data);
outputs.push_back(new Parser(&options));
}
for (auto& input : inputs) {
input.reserve(input.size() + simdjson::SIMDJSON_PADDING);
}
size_t count = 0;
size_t total = 0;
auto start = std::chrono::high_resolution_clock::now();
decltype(start) now;
simdjson::dom::parser parser;
Builder simd_buffer;
try {
do {
for (int i = 0; i < 2; i++) {
switch (parserType) {
case VPACK: {
outputs[count]->clear();
outputs[count]->parse(inputs[count]);
break;
}
case RAPIDJSON: {
rapidjson::Document d;
d.Parse(inputs[count].c_str());
break;
}
case SIMDJSON: {
simdjson::dom::element doc;
auto error = parser.parse(inputs[count]).get(doc);
if (error) {
std::cerr << "simdjson parse failed" << error << std::endl;
exit(EXIT_FAILURE);
}
simd_buffer.clear();
drain_simdjson(doc, &simd_buffer, false);
break;
}
}
count++;
if (count >= copies) {
count = 0;
}
total++;
}
now = std::chrono::high_resolution_clock::now();
} while (std::chrono::duration_cast<std::chrono::duration<int>>(now - start)
.count() < runTime);
std::chrono::duration<double> totalTime =
std::chrono::duration_cast<std::chrono::duration<double>>(now - start);
if (fullOutput) {
std::cout << "Total runtime: " << totalTime.count() << " s" << std::endl;
std::cout << "Have parsed " << total << " times with "
<< parserType << " using " << copies
<< " copies of JSON data, each of size " << inputs[0].size()
<< "." << std::endl;
std::cout << "Parsed " << inputs[0].size() * total << " bytes in total."
<< std::endl;
}
std::cout << std::setprecision(2) << std::fixed
<< " | "
<< std::setw(14)
<< static_cast<double>(inputs[0].size() * total) /
totalTime.count() << " bytes/s"
<< " | "
<< std::setw(14)
<< total / totalTime.count()
<< " | "
<< std::endl;
} catch (Exception const& ex) {
std::cerr << "An exception occurred while running bench: " << ex.what()
<< std::endl;
::exit(EXIT_FAILURE);
} catch (std::exception const& ex) {
std::cerr << "An exception occurred while running bench: " << ex.what()
<< std::endl;
::exit(EXIT_FAILURE);
} catch (...) {
std::cerr << "An unknown exception occurred while running bench"
<< std::endl;
::exit(EXIT_FAILURE);
}
for (auto& it : outputs) {
delete it;
}
}
static void runDefaultBench(bool all) {
bool fullOutput = !all;
int runSeconds = all ? 5 : 10;
auto runComparison = [&](std::string const& filename) {
std::string data = std::move(readFile(filename));
std::cout << std::endl;
std::cout << "# " << filename << " ";
for (size_t i = 0; i < 30 - filename.size(); ++i) {
std::cout << "#";
}
std::cout << std::endl;
std::cout << "|" << filename << " | " << "vpack ";
run(data, runSeconds, 1, ParserType::VPACK, fullOutput);
std::cout << "|" << filename << " | " << "rapidjson ";
run(data, runSeconds, 1, ParserType::RAPIDJSON, fullOutput);
std::cout << "|" << filename << " | " << "simdjson ";
run(data, runSeconds, 1, ParserType::SIMDJSON, fullOutput);
};
std::vector<std::string> files = {
// default
"small.json",
"sample.json",
"sampleNoWhite.json",
"commits.json",
// all dataset
"api-docs.json",
"countries.json",
"directory-tree.json",
"doubles-small.json",
"doubles.json",
"file-list.json",
"object.json",
"pass1.json",
"pass2.json",
"pass3.json",
"random1.json",
"random2.json",
"random3.json"
};
int dataSetSize = all ? files.size() : 4;
for (int i = 0; i < dataSetSize; i++) {
runComparison(files[i]);
}
}
int main(int argc, char* argv[]) {
if (argc == 1) {
runDefaultBench(false);
return EXIT_FAILURE;
}
if (argc == 2 && ::strcmp(argv[1], "all") == 0) {
runDefaultBench(true);
return EXIT_FAILURE;
}
if (argc != 5) {
usage(argv);
return EXIT_FAILURE;
}
ParserType parserType = ParserType::VPACK;
if (::strcmp(argv[4], "vpack") == 0) {
parserType = ParserType::VPACK;
} else if (::strcmp(argv[4], "rapidjson") == 0) {
parserType = ParserType::RAPIDJSON;
} else if (::strcmp(argv[4], "simdjson") == 0) {
parserType = ParserType::SIMDJSON;
} else {
usage(argv);
return EXIT_FAILURE;
}
size_t copies = std::stoul(argv[3]);
int runTime = std::stoi(argv[2]);
// read input file
std::string s = std::move(readFile(argv[1]));
run(s, runTime, copies, parserType, true);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* 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.
*
* Written (W) 2012 Viktor Gal
* Copyright (C) 2012 Viktor Gal
*/
#include <shogun/latent/LatentSOSVM.h>
#include <shogun/structure/DualLibQPBMSOSVM.h>
using namespace shogun;
CLatentSOSVM::CLatentSOSVM()
: CLinearLatentMachine()
{
register_parameters();
}
CLatentSOSVM::CLatentSOSVM(CLatentModel* model, CLinearStructuredOutputMachine* so_solver, float64_t C)
: CLinearLatentMachine(model, C)
{
register_parameters();
set_so_solver(so_solver);
}
CLatentSOSVM::~CLatentSOSVM()
{
SG_UNREF(m_so_solver);
}
CLatentLabels* CLatentSOSVM::apply_latent()
{
return NULL;
}
void CLatentSOSVM::set_so_solver(CLinearStructuredOutputMachine* so)
{
SG_UNREF(m_so_solver);
SG_REF(so);
m_so_solver = so;
}
float64_t CLatentSOSVM::do_inner_loop(float64_t cooling_eps)
{
float64_t lambda = 1/m_C;
CDualLibQPBMSOSVM* so = new CDualLibQPBMSOSVM();
so->train();
/* copy the resulting w */
SGVector<float64_t> cur_w = so->get_w();
memcpy(w.vector, cur_w.vector, cur_w.vlen*sizeof(float64_t));
/* get the primal objective value */
float64_t po = so->get_result().Fp;
SG_UNREF(so);
return po;
}
void CLatentSOSVM::register_parameters()
{
m_parameters->add((CSGObject**)&m_so_solver, "so_solver", "Structured Output Solver.");
}
<commit_msg>Added missed lambda usage in LatentSOSVM<commit_after>/*
* 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.
*
* Written (W) 2012 Viktor Gal
* Copyright (C) 2012 Viktor Gal
*/
#include <shogun/latent/LatentSOSVM.h>
#include <shogun/structure/DualLibQPBMSOSVM.h>
using namespace shogun;
CLatentSOSVM::CLatentSOSVM()
: CLinearLatentMachine()
{
register_parameters();
}
CLatentSOSVM::CLatentSOSVM(CLatentModel* model, CLinearStructuredOutputMachine* so_solver, float64_t C)
: CLinearLatentMachine(model, C)
{
register_parameters();
set_so_solver(so_solver);
}
CLatentSOSVM::~CLatentSOSVM()
{
SG_UNREF(m_so_solver);
}
CLatentLabels* CLatentSOSVM::apply_latent()
{
return NULL;
}
void CLatentSOSVM::set_so_solver(CLinearStructuredOutputMachine* so)
{
SG_UNREF(m_so_solver);
SG_REF(so);
m_so_solver = so;
}
float64_t CLatentSOSVM::do_inner_loop(float64_t cooling_eps)
{
float64_t lambda = 1/m_C;
CDualLibQPBMSOSVM* so = new CDualLibQPBMSOSVM();
so->set_lambda(lambda);
so->train();
/* copy the resulting w */
SGVector<float64_t> cur_w = so->get_w();
memcpy(w.vector, cur_w.vector, cur_w.vlen*sizeof(float64_t));
/* get the primal objective value */
float64_t po = so->get_result().Fp;
SG_UNREF(so);
return po;
}
void CLatentSOSVM::register_parameters()
{
m_parameters->add((CSGObject**)&m_so_solver, "so_solver", "Structured Output Solver.");
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "Image.h"
#include "Kernel.h"
#include "ImgLoader.h"
namespace scv {
Image::Image(const scv::Point &p1, const std::string &fileName) : Panel(p1, Point(p1.x + 10, p1.y + 10)) {
_data = NULL;
loadImage(fileName);
setWidth(_realSize.x);
setHeight(_realSize.y);
_type = IMAGE;
_minimumSize = Point(1,1);
}
Image::Image(const scv::Point &p1, const scv::Point &p2, const std::string &fileName) : Panel(p1, p2) {
_data = NULL;
loadImage(fileName);
_minimumSize = Point(1,1);
_type = IMAGE;
}
Image::~Image() {
if (_data != NULL) {
freeImageData(_data);
}
}
void Image::loadImage(const std::string &fileName) {
if (_data != NULL) {
delete _cTexture;
_cTexture = NULL;
freeImageData(_data);
_data = NULL;
}
_path = fileName;
_data = loadImageToArray(fileName, &_realSize.x, &_realSize.y);
createTexture();
}
void Image::display(void) {
static Kernel *kernel = Kernel::getInstance();
static Scissor *scissor = Scissor::getInstance();
static ColorScheme *scheme = ColorScheme::getInstance();
if (_cTexture == NULL || _isVisible == false || _data == NULL) return;
Point currPosition = getAbsolutePosition();
Scissor::Info scissorInfo(currPosition.x, kernel->getHeight() - (getHeight() + currPosition.y), getWidth(), getHeight());
scissor->pushScissor(scissorInfo);
_cTexture->enable();
scheme->applyDefaultModulate();
// image display
_cTexture->display(currPosition.x, currPosition.y, 0, getWidth(), getHeight());
_cTexture->disable();
// components
for (List::const_iterator iter = getChildren().begin(); iter != getChildren().end(); ++iter) {
if (kernel->willAppearOnScreen(*iter))
(*iter)->display();
}
scissor->popScissor();
}
void Image::createTexture(void) {
if (_data == NULL) return;
_cTexture = new ComponentTexture(_realSize.x, _realSize.y);
_cTexture->setTextureEnvMode(GL_MODULATE);
_cTexture->addTexture(Point(0,0), _realSize.x, _realSize.y, _data);
_cTexture->createTexture();
}
} // namespace scv
<commit_msg>glPushAttrib(GL_ALL_ATTRIB_BITS); glEnable(GL_TEXTURE_2D); //<commit_after>#include "stdafx.h"
#include "Image.h"
#include "Kernel.h"
#include "ImgLoader.h"
namespace scv {
Image::Image(const scv::Point &p1, const std::string &fileName) : Panel(p1, Point(p1.x + 10, p1.y + 10)) {
_data = NULL;
loadImage(fileName);
setWidth(_realSize.x);
setHeight(_realSize.y);
_type = IMAGE;
_minimumSize = Point(1,1);
}
Image::Image(const scv::Point &p1, const scv::Point &p2, const std::string &fileName) : Panel(p1, p2) {
_data = NULL;
loadImage(fileName);
_minimumSize = Point(1,1);
_type = IMAGE;
}
Image::~Image() {
if (_data != NULL) {
freeImageData(_data);
}
}
void Image::loadImage(const std::string &fileName) {
if (_data != NULL) {
delete _cTexture;
_cTexture = NULL;
freeImageData(_data);
_data = NULL;
}
_path = fileName;
_data = loadImageToArray(fileName, &_realSize.x, &_realSize.y);
createTexture();
}
void Image::display(void) {
static Kernel *kernel = Kernel::getInstance();
static Scissor *scissor = Scissor::getInstance();
static ColorScheme *scheme = ColorScheme::getInstance();
if (_cTexture == NULL || _isVisible == false || _data == NULL) return;
Point currPosition = getAbsolutePosition();
Scissor::Info scissorInfo(currPosition.x, kernel->getHeight() - (getHeight() + currPosition.y), getWidth(), getHeight());
scissor->pushScissor(scissorInfo);
//Pozzer - 2012
//mantem o estado atual da textura: para dois casos:
//1) render dentro de uma canvas - a textura esta desabilitada
//2) render de componentes do scv - a textura ja deve estar habilitada
glPushAttrib(GL_ALL_ATTRIB_BITS);
glEnable(GL_TEXTURE_2D); //
_cTexture->enable();
scheme->applyDefaultModulate();
// image display
_cTexture->display(currPosition.x, currPosition.y, 0, getWidth(), getHeight());
_cTexture->disable();
//Pozzer - 2012
glPopAttrib();
// components
for (List::const_iterator iter = getChildren().begin(); iter != getChildren().end(); ++iter) {
if (kernel->willAppearOnScreen(*iter))
(*iter)->display();
}
scissor->popScissor();
}
void Image::createTexture(void) {
if (_data == NULL) return;
_cTexture = new ComponentTexture(_realSize.x, _realSize.y);
_cTexture->setTextureEnvMode(GL_MODULATE);
_cTexture->addTexture(Point(0,0), _realSize.x, _realSize.y, _data);
_cTexture->createTexture();
}
} // namespace scv
<|endoftext|> |
<commit_before>/**
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "sensors/buildjson.hpp"
#include "conf.hpp"
#include "sensors/sensor.hpp"
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace conf
{
void from_json(const json& j, conf::SensorConfig& s)
{
j.at("type").get_to(s.type);
j.at("readPath").get_to(s.readPath);
/* The writePath field is optional in a configuration */
auto writePath = j.find("writePath");
if (writePath == j.end())
{
s.writePath = "";
}
else
{
j.at("writePath").get_to(s.writePath);
}
/* The min field is optional in a configuration. */
auto min = j.find("min");
if (min == j.end())
{
s.min = 0;
}
else
{
j.at("min").get_to(s.min);
}
/* The max field is optional in a configuration. */
auto max = j.find("max");
if (max == j.end())
{
s.max = 0;
}
else
{
j.at("max").get_to(s.max);
}
/* The timeout field is optional in a configuration. */
auto timeout = j.find("timeout");
if (timeout == j.end())
{
s.timeout = Sensor::getDefaultTimeout(s.type);
}
else
{
j.at("timeout").get_to(s.timeout);
}
}
} // namespace conf
std::map<std::string, struct conf::SensorConfig>
buildSensorsFromJson(const json& data)
{
std::map<std::string, struct conf::SensorConfig> config;
auto sensors = data["sensors"];
/* TODO: If no sensors, this is invalid, and we should except here or during
* parsing.
*/
for (const auto& sensor : sensors)
{
config[sensor["name"]] = sensor.get<struct conf::SensorConfig>();
}
return config;
}
<commit_msg>sensors: buildjson: minor min/max cleanup<commit_after>/**
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "sensors/buildjson.hpp"
#include "conf.hpp"
#include "sensors/sensor.hpp"
#include <nlohmann/json.hpp>
using json = nlohmann::json;
namespace conf
{
void from_json(const json& j, conf::SensorConfig& s)
{
j.at("type").get_to(s.type);
j.at("readPath").get_to(s.readPath);
/* The writePath field is optional in a configuration */
auto writePath = j.find("writePath");
if (writePath == j.end())
{
s.writePath = "";
}
else
{
j.at("writePath").get_to(s.writePath);
}
s.min = 0;
s.max = 0;
/* The min field is optional in a configuration. */
auto min = j.find("min");
if (min != j.end())
{
j.at("min").get_to(s.min);
}
/* The max field is optional in a configuration. */
auto max = j.find("max");
if (max != j.end())
{
j.at("max").get_to(s.max);
}
/* The timeout field is optional in a configuration. */
auto timeout = j.find("timeout");
if (timeout == j.end())
{
s.timeout = Sensor::getDefaultTimeout(s.type);
}
else
{
j.at("timeout").get_to(s.timeout);
}
}
} // namespace conf
std::map<std::string, struct conf::SensorConfig>
buildSensorsFromJson(const json& data)
{
std::map<std::string, struct conf::SensorConfig> config;
auto sensors = data["sensors"];
/* TODO: If no sensors, this is invalid, and we should except here or during
* parsing.
*/
for (const auto& sensor : sensors)
{
config[sensor["name"]] = sensor.get<struct conf::SensorConfig>();
}
return config;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016 - 2019 [email protected]
*
* 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 <QBuffer>
#include <QFile>
#include <nostalgia/core/consts.hpp>
#include <nostalgia/core/gfx.hpp>
#include "consts.hpp"
#include "new_tilesheet_wizard.hpp"
namespace nostalgia::core {
NewTilesheetWizardPage::NewTilesheetWizardPage(const studio::Context *ctx) {
m_ctx = ctx;
addLineEdit(tr("&Tile Sheet Name:"), QString(TileSheetName) + "*", "", [this](QString name) {
return 0;
});
m_palettePicker = addComboBox(tr("&Palette:"), QString(Palette) + "*", {""});
m_ctx->project->subscribe(studio::ProjectEvent::FileRecognized, m_palettePicker, [this](QString path) {
if (path.startsWith(PaletteDir) && path.endsWith(FileExt_npal)) {
m_palettePicker->addItem(studio::filePathToName(path, PaletteDir, FileExt_npal), path);
}
});
}
int NewTilesheetWizardPage::accept() {
const auto tilesheetName = field(TileSheetName).toString();
const auto palette = m_palettePicker->itemData(field(Palette).toInt()).toString();
const auto outPath = TileSheetDir + tilesheetName + FileExt_ng;
auto outPath = QString(TileSheetDir) + name + FileExt_ng;
auto err = m_ctx->project->exists(outPath);
if (err) {
showValidationError(tr("A tile sheet with this name already exists."));
return err;
}
NostalgiaGraphic ng;
ng.columns = 1;
ng.rows = 1;
ng.defaultPalette = palette.toUtf8().data();
m_ctx->project->writeObj(outPath, &ng);
return 0;
}
}
<commit_msg>[nostalgia/core/studio] Fix build error in NewTileSheetWizard<commit_after>/*
* Copyright 2016 - 2019 [email protected]
*
* 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 <QBuffer>
#include <QFile>
#include <nostalgia/core/consts.hpp>
#include <nostalgia/core/gfx.hpp>
#include "consts.hpp"
#include "new_tilesheet_wizard.hpp"
namespace nostalgia::core {
NewTilesheetWizardPage::NewTilesheetWizardPage(const studio::Context *ctx) {
m_ctx = ctx;
addLineEdit(tr("&Tile Sheet Name:"), QString(TileSheetName) + "*", "", [this](QString) {
return 0;
});
m_palettePicker = addComboBox(tr("&Palette:"), QString(Palette) + "*", {""});
m_ctx->project->subscribe(studio::ProjectEvent::FileRecognized, m_palettePicker, [this](QString path) {
if (path.startsWith(PaletteDir) && path.endsWith(FileExt_npal)) {
m_palettePicker->addItem(studio::filePathToName(path, PaletteDir, FileExt_npal), path);
}
});
}
int NewTilesheetWizardPage::accept() {
const auto tilesheetName = field(TileSheetName).toString();
const auto palette = m_palettePicker->itemData(field(Palette).toInt()).toString();
const auto outPath = QString(TileSheetDir) + tilesheetName + FileExt_ng;
auto err = m_ctx->project->exists(outPath);
if (err) {
showValidationError(tr("A tile sheet with this name already exists."));
return err;
}
NostalgiaGraphic ng;
ng.columns = 1;
ng.rows = 1;
ng.defaultPalette = palette.toUtf8().data();
m_ctx->project->writeObj(outPath, &ng);
return 0;
}
}
<|endoftext|> |
<commit_before>#include <atomic>
#include <string>
#include <gtest/gtest.h>
#include <teelogging/teelogging.h>
#include "../shell.h"
#include "../coroutine.h"
#include "../scheduler.h"
#include "../semaphore.h"
#include "../channel.h"
class CoroTest : testing::Test { };
using namespace cu;
cu::scheduler sch;
TEST(CoroTest, Test_run_ls_strip_quote_grep)
{
cu::channel<std::string> c1(sch);
c1.pipeline(
run()
, strip()
, quote()
, grep("shell_*")
, assert_count(1)
, assert_string("\"shell_exe\"")
, out()
);
c1("ls .");
/////////////////////////////////
cu::channel<std::string> c2(sch);
c2.pipeline(
ls()
, strip()
, quote()
, grep("shell_*")
, assert_count(1)
, assert_string("\"shell_exe\"")
, out()
);
c2(".");
}
TEST(CoroTest, Test_run_ls_sort_grep_uniq_join)
{
cu::channel<std::string> c1(sch);
std::string out_subproces;
c1.pipeline(run(), strip(), sort(), grep("*fes*"), uniq(), join(), out(), out(out_subproces));
c1("ls .");
//
cu::channel<std::string> c2(sch);
std::string out_ls;
c2.pipeline(ls(), sort(), grep("*fes*"), uniq(), join(), out(), out(out_ls));
c2(".");
//
ASSERT_STREQ(out_subproces.c_str(), out_ls.c_str());
}
TEST(CoroTest, TestCut)
{
// cu::channel<std::string> c1(sch);
// c1.pipeline(
// assert_count(1)
// , split()
// , assert_count(3)
// , join()
// , assert_count(1)
// , cut(0)
// , assert_count(1)
// , assert_string("hello")
// );
// c1("hello big world");
//
// cu::channel<std::string> c2(sch);
// c2.pipeline(
// assert_count(1)
// , split()
// , assert_count(3)
// , join()
// , assert_count(1)
// , cut(1)
// , assert_count(1)
// , assert_string("big")
// );
// c2("hello big world");
//
// cu::channel<std::string> c3(sch);
// c3.pipeline(
// assert_count(1)
// , split()
// , assert_count(3)
// , join()
// , assert_count(1)
// , cut(2)
// , assert_count(1)
// , assert_string("world")
// );
// c3("hello big world");
}
TEST(CoroTest, TestGrep)
{
cu::channel<std::string> c1(sch);
c1.pipeline(
split("\n")
, assert_count(3)
, grep("line2")
, assert_count(1)
, assert_string("line2")
);
c1("line1\nline2\nline3");
}
TEST(CoroTest, TestGrep2)
{
cu::channel<std::string> c1(sch);
c1.pipeline(
split("\n")
, assert_count(4)
);
c1("line1\nline2\nline3\n");
}
TEST(CoroTest, TestCount)
{
// cu::channel<std::string> c1(sch);
// int result;
// c1.pipeline(
// split("\n")
// , count()
// , out(result)
// );
// c1("line1\nline2\nline3");
// ASSERT_EQ(result, 3) << "maybe count() is not working well";
}
TEST(CoroTest, TestUpper)
{
cu::scheduler sch_test;
cu::channel<std::string> c1(sch_test, 1);
c1.pipeline(toupper(), out());
sch.spawn([&](auto& yield){
c1(yield, "hola mundo");
});
sch_test.run_until_completed();
std::cout << c1.get() << std::endl;
}
TEST(CoroTest, TestScheduler)
{
cu::scheduler sch1;
cu::channel<int> c1(sch1, 5);
cu::channel<int> c2(sch1, 5);
cu::channel<int> c3(sch1, 5);
sch.spawn([&](auto& yield) {
// productor1
for(int x=0; x<100; ++x)
{
int y = x + 5;
c1(yield, x + y);
}
c1.close(yield);
});
sch.spawn([&](auto& yield) {
// productor2
for(int z=0; z<100; ++z)
{
c2(yield, z + 1);
}
c2.close(yield);
});
sch.spawn([&](auto& yield) {
/*
// proposal 1
cu::for_until_close(yield, {c1, c2}, [](auto& a, auto& b){
c3(yield, a - b);
});
*/
for(;;)
{
auto a = c1.get(yield);
if(a)
{
auto b = c2.get(yield);
if(b)
{
c3(yield, a - b);
}
else
{
break;
}
}
else
{
break;
}
}
});
sch.spawn([&](auto& yield) {
/*
cu::for_until_close(yield, c3, [](auto& r){
std::cout << r + 1 << std::endl;
});
*/
c3.for_each(yield, [](auto& r) {
std::cout << "result = " << r + 1 << std::endl;
});
});
sch1.run_until_completed();
}
<commit_msg>Update test_shell.cpp<commit_after>#include <atomic>
#include <string>
#include <gtest/gtest.h>
#include <teelogging/teelogging.h>
#include "../shell.h"
#include "../coroutine.h"
#include "../scheduler.h"
#include "../semaphore.h"
#include "../channel.h"
class CoroTest : testing::Test { };
using namespace cu;
cu::scheduler sch;
TEST(CoroTest, Test_run_ls_strip_quote_grep)
{
cu::channel<std::string> c1(sch);
c1.pipeline(
run()
, strip()
, quote()
, grep("shell_*")
, assert_count(1)
, assert_string("\"shell_exe\"")
, out()
);
c1("ls .");
/////////////////////////////////
cu::channel<std::string> c2(sch);
c2.pipeline(
ls()
, strip()
, quote()
, grep("shell_*")
, assert_count(1)
, assert_string("\"shell_exe\"")
, out()
);
c2(".");
}
TEST(CoroTest, Test_run_ls_sort_grep_uniq_join)
{
cu::channel<std::string> c1(sch);
std::string out_subproces;
c1.pipeline(run(), strip(), sort(), grep("*fes*"), uniq(), join(), out(), out(out_subproces));
c1("ls .");
//
cu::channel<std::string> c2(sch);
std::string out_ls;
c2.pipeline(ls(), sort(), grep("*fes*"), uniq(), join(), out(), out(out_ls));
c2(".");
//
ASSERT_STREQ(out_subproces.c_str(), out_ls.c_str());
}
TEST(CoroTest, TestCut)
{
// cu::channel<std::string> c1(sch);
// c1.pipeline(
// assert_count(1)
// , split()
// , assert_count(3)
// , join()
// , assert_count(1)
// , cut(0)
// , assert_count(1)
// , assert_string("hello")
// );
// c1("hello big world");
//
// cu::channel<std::string> c2(sch);
// c2.pipeline(
// assert_count(1)
// , split()
// , assert_count(3)
// , join()
// , assert_count(1)
// , cut(1)
// , assert_count(1)
// , assert_string("big")
// );
// c2("hello big world");
//
// cu::channel<std::string> c3(sch);
// c3.pipeline(
// assert_count(1)
// , split()
// , assert_count(3)
// , join()
// , assert_count(1)
// , cut(2)
// , assert_count(1)
// , assert_string("world")
// );
// c3("hello big world");
}
TEST(CoroTest, TestGrep)
{
cu::channel<std::string> c1(sch);
c1.pipeline(
split("\n")
, assert_count(3)
, grep("line2")
, assert_count(1)
, assert_string("line2")
);
c1("line1\nline2\nline3");
}
TEST(CoroTest, TestGrep2)
{
cu::channel<std::string> c1(sch);
c1.pipeline(
split("\n")
, assert_count(4)
);
c1("line1\nline2\nline3\n");
}
TEST(CoroTest, TestCount)
{
// cu::channel<std::string> c1(sch);
// int result;
// c1.pipeline(
// split("\n")
// , count()
// , out(result)
// );
// c1("line1\nline2\nline3");
// ASSERT_EQ(result, 3) << "maybe count() is not working well";
}
TEST(CoroTest, TestUpper)
{
cu::scheduler sch_test;
cu::channel<std::string> c1(sch_test, 1);
c1.pipeline(toupper(), out());
sch.spawn([&](auto& yield){
c1(yield, "hola mundo");
});
sch_test.run_until_complete();
std::cout << c1.get() << std::endl;
}
TEST(CoroTest, TestScheduler)
{
cu::scheduler sch1;
cu::channel<int> c1(sch1, 5);
cu::channel<int> c2(sch1, 5);
cu::channel<int> c3(sch1, 5);
sch.spawn([&](auto& yield) {
// productor1
for(int x=0; x<100; ++x)
{
int y = x + 5;
c1(yield, x + y);
}
c1.close(yield);
});
sch.spawn([&](auto& yield) {
// productor2
for(int z=0; z<100; ++z)
{
c2(yield, z + 1);
}
c2.close(yield);
});
sch.spawn([&](auto& yield) {
/*
// proposal 1
cu::for_until_close(yield, {c1, c2}, [](auto& a, auto& b){
c3(yield, a - b);
});
*/
for(;;)
{
auto a = c1.get(yield);
if(a)
{
auto b = c2.get(yield);
if(b)
{
c3(yield, a - b);
}
else
{
break;
}
}
else
{
break;
}
}
});
sch.spawn([&](auto& yield) {
/*
cu::for_until_close(yield, c3, [](auto& r){
std::cout << r + 1 << std::endl;
});
*/
c3.for_each(yield, [](auto& r) {
std::cout << "result = " << r + 1 << std::endl;
});
});
sch1.run_until_complete();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: togglebuttontoolbarcontroller.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: ihi $ $Date: 2007-07-10 15:08:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FRAMEWORK_UIELEMENT_TOGGLEBUTTONTOOLBARCONTROLLER_HXX_
#define __FRAMEWORK_UIELEMENT_TOGGLEBUTTONTOOLBARCONTROLLER_HXX_
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/frame/XDispatch.hpp>
#include <com/sun/star/frame/ControlCommand.hpp>
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#include <uielement/complextoolbarcontroller.hxx>
#include <vcl/toolbox.hxx>
#include <vcl/image.hxx>
namespace framework
{
class ToolBar;
class ToggleButtonToolbarController : public ComplexToolbarController
{
public:
enum Style
{
STYLE_TOGGLEBUTTON,
STYLE_DROPDOWNBUTTON,
STYLE_TOGGLE_DROPDOWNBUTTON
};
ToggleButtonToolbarController( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServiceManager,
const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
ToolBox* pToolBar,
USHORT nID,
Style eStyle,
const rtl::OUString& aCommand );
virtual ~ToggleButtonToolbarController();
// XComponent
virtual void SAL_CALL dispose() throw ( ::com::sun::star::uno::RuntimeException );
// XToolbarController
virtual void SAL_CALL execute( sal_Int16 KeyModifier ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > SAL_CALL createPopupWindow() throw (::com::sun::star::uno::RuntimeException);
protected:
virtual void executeControlCommand( const ::com::sun::star::frame::ControlCommand& rControlCommand );
private:
DECL_LINK( MenuSelectHdl, Menu *);
Style m_eStyle;
rtl::OUString m_aCurrentSelection;
std::vector< rtl::OUString > m_aDropdownMenuList;
};
}
#endif // __FRAMEWORK_UIELEMENT_TOGGLEBUTTONTOOLBARCONTROLLER_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.3.130); FILE MERGED 2008/03/28 15:34:58 rt 1.3.130.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: togglebuttontoolbarcontroller.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef __FRAMEWORK_UIELEMENT_TOGGLEBUTTONTOOLBARCONTROLLER_HXX_
#define __FRAMEWORK_UIELEMENT_TOGGLEBUTTONTOOLBARCONTROLLER_HXX_
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/frame/XDispatch.hpp>
#include <com/sun/star/frame/ControlCommand.hpp>
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#include <uielement/complextoolbarcontroller.hxx>
#include <vcl/toolbox.hxx>
#include <vcl/image.hxx>
namespace framework
{
class ToolBar;
class ToggleButtonToolbarController : public ComplexToolbarController
{
public:
enum Style
{
STYLE_TOGGLEBUTTON,
STYLE_DROPDOWNBUTTON,
STYLE_TOGGLE_DROPDOWNBUTTON
};
ToggleButtonToolbarController( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServiceManager,
const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
ToolBox* pToolBar,
USHORT nID,
Style eStyle,
const rtl::OUString& aCommand );
virtual ~ToggleButtonToolbarController();
// XComponent
virtual void SAL_CALL dispose() throw ( ::com::sun::star::uno::RuntimeException );
// XToolbarController
virtual void SAL_CALL execute( sal_Int16 KeyModifier ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > SAL_CALL createPopupWindow() throw (::com::sun::star::uno::RuntimeException);
protected:
virtual void executeControlCommand( const ::com::sun::star::frame::ControlCommand& rControlCommand );
private:
DECL_LINK( MenuSelectHdl, Menu *);
Style m_eStyle;
rtl::OUString m_aCurrentSelection;
std::vector< rtl::OUString > m_aDropdownMenuList;
};
}
#endif // __FRAMEWORK_UIELEMENT_TOGGLEBUTTONTOOLBARCONTROLLER_HXX_
<|endoftext|> |
<commit_before>#include <sys/socket.h>
#include "coap/observable.h"
#include "coap-uripath-dispatcher.h"
#include "coap/decoder-subject.hpp"
#include "main.h"
using namespace moducom::pipeline;
using namespace moducom::coap;
using namespace moducom::coap::experimental;
#ifndef FEATURE_MCCOAP_INLINE_TOKEN
#error "Requires inline token support"
#endif
IDispatcherHandler* sensor1_handler(AggregateUriPathObserver::Context& ctx)
{
return nullptr;
}
IDispatcherHandler* sensor2_handler(AggregateUriPathObserver::Context& ctx)
{
return nullptr;
}
IDispatcherHandler* v1_handler(AggregateUriPathObserver::Context& ctx)
{
typedef AggregateUriPathObserver::fn_t fn_t;
typedef AggregateUriPathObserver::item_t item_t;
item_t items[] =
{
fn_t::item("sensor1", sensor1_handler),
fn_t::item("sensor2", sensor2_handler)
};
return new (ctx.objstack) AggregateUriPathObserver(ctx, items);
}
IDispatcherHandler* context_dispatcher(FactoryDispatcherHandlerContext& ctx)
{
return new (ctx.handler_memory.data()) ContextDispatcherHandler(ctx.incoming_context);
}
IDispatcherHandler* v1_dispatcher(FactoryDispatcherHandlerContext& ctx)
{
moducom::dynamic::ObjStack objstack(ctx.handler_memory);
typedef AggregateUriPathObserver::fn_t fn_t;
typedef AggregateUriPathObserver::item_t item_t;
item_t items[] =
{
fn_t::item("v1", v1_handler)
};
// FIX: Since objstack implementation bumps up its own m_data, we can safely pass it
// in for the used memorychunk. However, this is all clumsy and we should be passing
// around objstack more universally
AggregateUriPathObserver* observer = new (objstack)
AggregateUriPathObserver(objstack, ctx.incoming_context, items);
return observer;
}
dispatcher_handler_factory_fn root_factories[] =
{
context_dispatcher,
v1_dispatcher,
// FIX: Enabling this causes a crash in the on_option area
//fallthrough_404
};
template <>
size_t service_coap_in(const struct sockaddr_in& address_in, MemoryChunk& inbuf, MemoryChunk& outbuf)
{
moducom::pipeline::layer1::MemoryChunk<512> buffer;
IncomingContext incoming_context;
FactoryDispatcherHandler dh(buffer, incoming_context, root_factories);
DecoderSubjectBase<IDispatcherHandler&> decoder(dh);
decoder.dispatch(inbuf);
//IncomingContext context;
//DecoderSubjectBase<ObservableOptionObserverBase> decoder(context);
//decoder.dispatch(inbuf);
return 0;
}
// return 0 always, for now
template <>
size_t service_coap_out(struct sockaddr_in* address_out, MemoryChunk& outbuf)
{
return 0;
}
<commit_msg>Commenting<commit_after>#include <sys/socket.h>
#include "coap/observable.h"
#include "coap-uripath-dispatcher.h"
#include "coap/decoder-subject.hpp"
#include "main.h"
using namespace moducom::pipeline;
using namespace moducom::coap;
using namespace moducom::coap::experimental;
#ifndef FEATURE_MCCOAP_INLINE_TOKEN
#error "Requires inline token support"
#endif
IDispatcherHandler* sensor1_handler(AggregateUriPathObserver::Context& ctx)
{
// TODO: In here, handle both a subscription request as well as
// the resource request itself. TBD whether we need to return 'Observe'
// option with the (piggybacked) ACK from here
dispatcher_handler_factory_fn factories[] =
{
};
// FIX: Beware, this results in an alloc which does not get freed
return new (ctx.objstack) FactoryDispatcherHandler(ctx.objstack, ctx.incoming_context, factories);
}
IDispatcherHandler* sensor2_handler(AggregateUriPathObserver::Context& ctx)
{
return nullptr;
}
IDispatcherHandler* v1_handler(AggregateUriPathObserver::Context& ctx)
{
typedef AggregateUriPathObserver::fn_t fn_t;
typedef AggregateUriPathObserver::item_t item_t;
item_t items[] =
{
fn_t::item("sensor1", sensor1_handler),
fn_t::item("sensor2", sensor2_handler)
};
// FIX: Beware, this results in an alloc which does not get freed
return new (ctx.objstack) AggregateUriPathObserver(ctx, items);
}
IDispatcherHandler* context_dispatcher(FactoryDispatcherHandlerContext& ctx)
{
return new (ctx.handler_memory.data()) ContextDispatcherHandler(ctx.incoming_context);
}
IDispatcherHandler* v1_dispatcher(FactoryDispatcherHandlerContext& ctx)
{
moducom::dynamic::ObjStack objstack(ctx.handler_memory);
typedef AggregateUriPathObserver::fn_t fn_t;
typedef AggregateUriPathObserver::item_t item_t;
item_t items[] =
{
fn_t::item("v1", v1_handler)
};
// FIX: Since objstack implementation bumps up its own m_data, we can safely pass it
// in for the used memorychunk. However, this is all clumsy and we should be passing
// around objstack more universally
AggregateUriPathObserver* observer = new (objstack)
AggregateUriPathObserver(objstack, ctx.incoming_context, items);
return observer;
}
static dispatcher_handler_factory_fn root_factories[] =
{
context_dispatcher,
v1_dispatcher
};
template <>
size_t service_coap_in(const struct sockaddr_in& address_in, MemoryChunk& inbuf, MemoryChunk& outbuf)
{
moducom::pipeline::layer1::MemoryChunk<512> buffer;
IncomingContext incoming_context;
FactoryDispatcherHandler dh(buffer, incoming_context, root_factories);
DecoderSubjectBase<IDispatcherHandler&> decoder(dh);
decoder.dispatch(inbuf);
return 0;
}
// return 0 always, for now
template <>
size_t service_coap_out(struct sockaddr_in* address_out, MemoryChunk& outbuf)
{
return 0;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "DtorCorrectnessTest.h"
#include <iostream>
using namespace std;
class CtorDtorCopyCounter {
public:
static int s_outstanding;
static size_t s_construction;
CtorDtorCopyCounter(void) {
s_outstanding++;
s_construction++;
}
CtorDtorCopyCounter(const CtorDtorCopyCounter&) {
s_outstanding++;
s_construction++;
}
~CtorDtorCopyCounter(void) {
s_outstanding--;
}
};
int CtorDtorCopyCounter::s_outstanding = 0;
size_t CtorDtorCopyCounter::s_construction = 0;
class CtorDtorListener:
public virtual EventReceiver
{
public:
virtual void DoFired(CtorDtorCopyCounter ctr) = 0;
virtual Deferred DoDeferred(CtorDtorCopyCounter ctr) = 0;
};
class MyCtorDtorListener:
public CoreThread,
public CtorDtorListener
{
public:
MyCtorDtorListener(const char* name):
CoreThread(name),
m_hitDeferred(false)
{
AcceptDispatchDelivery();
Ready();
}
bool m_hitDeferred;
virtual void DoFired(CtorDtorCopyCounter ctr) {
}
virtual Deferred DoDeferred(CtorDtorCopyCounter ctr) {
m_hitDeferred = true;
return Deferred(this);
}
};
class MyCtorDtorListener1:
public MyCtorDtorListener
{
public:
MyCtorDtorListener1(void):
MyCtorDtorListener("MyCtorDtorListener1")
{}
};
class MyCtorDtorListener2:
public MyCtorDtorListener
{
public:
MyCtorDtorListener2(void):
MyCtorDtorListener("MyCtorDtorListener2")
{}
};
DtorCorrectnessTest::DtorCorrectnessTest(void) {
}
void DtorCorrectnessTest::SetUp(void) {
// Reset counter:
CtorDtorCopyCounter::s_outstanding = 0;
CtorDtorCopyCounter::s_construction = 0;
}
TEST_F(DtorCorrectnessTest, VerifyFiringDtors) {
// Try firing some events and validate the invariant:
cdl(&CtorDtorListener::DoFired)(CtorDtorCopyCounter());
EXPECT_LE(2UL, CtorDtorCopyCounter::s_construction) << "Counter constructors were not invoked the expected number of times when fired";
EXPECT_EQ(0, CtorDtorCopyCounter::s_outstanding) << "Counter mismatch under event firing";
}
TEST_F(DtorCorrectnessTest, VerifyDeferringDtors) {
// Precondition verification:
ASSERT_FALSE(listener1->ShouldStop()) << "Thread was signalled to stop before it even started";
// Simple check of our copy counter under scope:
{
CtorDtorCopyCounter tempCounter;
ASSERT_EQ(1UL, CtorDtorCopyCounter::s_construction) << "Constructor count was not incremented correctly";
CtorDtorCopyCounter::s_construction = 0;
}
ASSERT_EQ(0UL, CtorDtorCopyCounter::s_outstanding) << "Unexpected number of outstanding instances";
// Simple check of anonymous instance handling:
CtorDtorCopyCounter();
ASSERT_EQ(1UL, CtorDtorCopyCounter::s_construction) << "Constructor count was not incremented correctly";
CtorDtorCopyCounter::s_construction = 0;
ASSERT_EQ(0UL, CtorDtorCopyCounter::s_outstanding) << "Unexpected number of outstanding instances";
// Verify that the thread didn't exit too soon:
ASSERT_FALSE(listener1->ShouldStop()) << "Thread was signalled to stop even though it should have been deferring";
// Spin until both threads are ready to accept:
ASSERT_TRUE(listener1->DelayUntilCanAccept()) << "First listener reported it could not accept";
ASSERT_TRUE(listener2->DelayUntilCanAccept()) << "Second listener reported it could not accept";
// Now try deferring:
cout << "Counter value is " << CtorDtorCopyCounter::s_outstanding << endl;
cdl(&CtorDtorListener::DoDeferred)(CtorDtorCopyCounter());
cout << "Counter value is " << CtorDtorCopyCounter::s_outstanding << endl;
// Process all deferred elements and then check to see what we got:
AutoCurrentContext ctxt;
ctxt->InitiateCoreThreads();
listener1->Stop(true);
listener2->Stop(true);
listener1->Wait();
listener2->Wait();
// Verify that we actually hit something:
EXPECT_TRUE(listener1->m_hitDeferred) << "Failed to hit a listener's deferred call";
EXPECT_TRUE(listener2->m_hitDeferred) << "Failed to hit a listener's deferred call";
// Verify hit counts:
EXPECT_LE(2UL, CtorDtorCopyCounter::s_construction) << "Counter constructors were not invoked the expected number of times when deferred";
EXPECT_EQ(0, CtorDtorCopyCounter::s_outstanding) << "Counter mismatch under deferred events";
}<commit_msg>Eliminating spurious debug print statements<commit_after>#include "stdafx.h"
#include "DtorCorrectnessTest.h"
#include <iostream>
using namespace std;
class CtorDtorCopyCounter {
public:
static int s_outstanding;
static size_t s_construction;
CtorDtorCopyCounter(void) {
s_outstanding++;
s_construction++;
}
CtorDtorCopyCounter(const CtorDtorCopyCounter&) {
s_outstanding++;
s_construction++;
}
~CtorDtorCopyCounter(void) {
s_outstanding--;
}
};
int CtorDtorCopyCounter::s_outstanding = 0;
size_t CtorDtorCopyCounter::s_construction = 0;
class CtorDtorListener:
public virtual EventReceiver
{
public:
virtual void DoFired(CtorDtorCopyCounter ctr) = 0;
virtual Deferred DoDeferred(CtorDtorCopyCounter ctr) = 0;
};
class MyCtorDtorListener:
public CoreThread,
public CtorDtorListener
{
public:
MyCtorDtorListener(const char* name):
CoreThread(name),
m_hitDeferred(false)
{
AcceptDispatchDelivery();
Ready();
}
bool m_hitDeferred;
virtual void DoFired(CtorDtorCopyCounter ctr) {
}
virtual Deferred DoDeferred(CtorDtorCopyCounter ctr) {
m_hitDeferred = true;
return Deferred(this);
}
};
class MyCtorDtorListener1:
public MyCtorDtorListener
{
public:
MyCtorDtorListener1(void):
MyCtorDtorListener("MyCtorDtorListener1")
{}
};
class MyCtorDtorListener2:
public MyCtorDtorListener
{
public:
MyCtorDtorListener2(void):
MyCtorDtorListener("MyCtorDtorListener2")
{}
};
DtorCorrectnessTest::DtorCorrectnessTest(void) {
}
void DtorCorrectnessTest::SetUp(void) {
// Reset counter:
CtorDtorCopyCounter::s_outstanding = 0;
CtorDtorCopyCounter::s_construction = 0;
}
TEST_F(DtorCorrectnessTest, VerifyFiringDtors) {
// Try firing some events and validate the invariant:
cdl(&CtorDtorListener::DoFired)(CtorDtorCopyCounter());
EXPECT_LE(2UL, CtorDtorCopyCounter::s_construction) << "Counter constructors were not invoked the expected number of times when fired";
EXPECT_EQ(0, CtorDtorCopyCounter::s_outstanding) << "Counter mismatch under event firing";
}
TEST_F(DtorCorrectnessTest, VerifyDeferringDtors) {
// Precondition verification:
ASSERT_FALSE(listener1->ShouldStop()) << "Thread was signalled to stop before it even started";
// Simple check of our copy counter under scope:
{
CtorDtorCopyCounter tempCounter;
ASSERT_EQ(1UL, CtorDtorCopyCounter::s_construction) << "Constructor count was not incremented correctly";
CtorDtorCopyCounter::s_construction = 0;
}
ASSERT_EQ(0UL, CtorDtorCopyCounter::s_outstanding) << "Unexpected number of outstanding instances";
// Simple check of anonymous instance handling:
CtorDtorCopyCounter();
ASSERT_EQ(1UL, CtorDtorCopyCounter::s_construction) << "Constructor count was not incremented correctly";
CtorDtorCopyCounter::s_construction = 0;
ASSERT_EQ(0UL, CtorDtorCopyCounter::s_outstanding) << "Unexpected number of outstanding instances";
// Verify that the thread didn't exit too soon:
ASSERT_FALSE(listener1->ShouldStop()) << "Thread was signalled to stop even though it should have been deferring";
// Spin until both threads are ready to accept:
ASSERT_TRUE(listener1->DelayUntilCanAccept()) << "First listener reported it could not accept";
ASSERT_TRUE(listener2->DelayUntilCanAccept()) << "Second listener reported it could not accept";
// Now try deferring:
cdl(&CtorDtorListener::DoDeferred)(CtorDtorCopyCounter());
// Process all deferred elements and then check to see what we got:
AutoCurrentContext ctxt;
ctxt->InitiateCoreThreads();
listener1->Stop(true);
listener2->Stop(true);
listener1->Wait();
listener2->Wait();
// Verify that we actually hit something:
EXPECT_TRUE(listener1->m_hitDeferred) << "Failed to hit a listener's deferred call";
EXPECT_TRUE(listener2->m_hitDeferred) << "Failed to hit a listener's deferred call";
// Verify hit counts:
EXPECT_LE(2UL, CtorDtorCopyCounter::s_construction) << "Counter constructors were not invoked the expected number of times when deferred";
EXPECT_EQ(0, CtorDtorCopyCounter::s_outstanding) << "Counter mismatch under deferred events";
}<|endoftext|> |
<commit_before>//
// DynamicVoiceManager.cpp
// C700
//
// Created by osoumen on 2014/11/30.
//
//
#include "DynamicVoiceManager.h"
//-----------------------------------------------------------------------------
DynamicVoiceManager::DynamicVoiceManager() :
mVoiceLimit(8)
{
}
//-----------------------------------------------------------------------------
DynamicVoiceManager::~DynamicVoiceManager()
{
}
//-----------------------------------------------------------------------------
void DynamicVoiceManager::Initialize(int voiceLimit)
{
mVoiceLimit = voiceLimit;
for (int i=0; i<16; i++) {
mChNoteOns[i] = 0;
mChLimit[i] = 127;
}
}
//-----------------------------------------------------------------------------
void DynamicVoiceManager::Reset()
{
mPlayVo.clear();
mWaitVo.clear();
for(int i=0;i<mVoiceLimit;i++){
pushWaitVo(i);
}
for (int i=0; i<16; i++) {
mChNoteOns[i] = 0;
}
for (int i=0; i<MAX_VOICE; i++) {
mVoCh[i] = 0;
mVoPrio[i] = 64;
mVoUniqueID[i] = 0;
mVoKeyOn[i] = false;
}
}
//-----------------------------------------------------------------------------
void DynamicVoiceManager::ChangeVoiceLimit(int voiceLimit)
{
if ( voiceLimit < mVoiceLimit ) {
//空きボイスリストから削除する
for ( int i=voiceLimit; i<mVoiceLimit; i++ ) {
mWaitVo.remove(i);
}
}
if ( voiceLimit > mVoiceLimit ) {
//空きボイスを追加する
for ( int i=mVoiceLimit; i<voiceLimit; i++ ) {
pushWaitVo(i);
}
}
mVoiceLimit = voiceLimit;
}
//-----------------------------------------------------------------------------
int DynamicVoiceManager::AllocVoice(int prio, int ch, int uniqueID, bool monoMode,
int *releasedCh, bool *isLegato)
{
int v = -1;
*releasedCh = -1;
*isLegato = false;
if (monoMode) {
v = ch & 0x07; // 固定のchを確保
if (IsPlayingVoice(v)) {
if (mVoCh[v] == ch) {
// レガートで鳴らした音
// キーオン前に2回叩かれた場合は最後のノートオンだけが有効になるように
if (mVoKeyOn[v]) {
*isLegato = true;
}
}
else {
// 別のchの発音がすでにある場合
mPlayVo.remove(v);
*releasedCh = mVoCh[v];
mChNoteOns[mVoCh[v]]--;
}
}
else {
mWaitVo.remove(v);
}
}
else {
if (mChNoteOns[ch] >= mChLimit[ch]) {
// ch発音数を超えてたら、そのchの音を一つ止めて次の音を鳴らす
v = stealVoice(ch);
if (v != -1) {
mPlayVo.remove(v);
*releasedCh = mVoCh[v];
mChNoteOns[mVoCh[v]]--;
}
}
else {
// 超えてない場合は、後着優先で優先度の低い音を消す
v = findVoice();
if (v >= MAX_VOICE) { //空きがなくてどこかを止めた
v -= MAX_VOICE;
mPlayVo.remove(v);
*releasedCh = mVoCh[v];
mChNoteOns[mVoCh[v]]--;
}
else if (v >= 0) {
mWaitVo.remove(v);
}
}
}
if (v != -1) {
mVoCh[v] = ch;
mVoPrio[v] = prio;
mVoKeyOn[v] = false;
mVoUniqueID[v] = uniqueID;
if (*isLegato == false && !IsPlayingVoice(v)) { // モノモードの同時ノートオン対策
mPlayVo.push_back(v);
mChNoteOns[ch]++;
}
}
return v;
}
//-----------------------------------------------------------------------------
int DynamicVoiceManager::ReleaseVoice(int relPrio, int ch, int uniqueID, int *relVo)
{
int stops = 0;
std::list<int>::iterator it = mPlayVo.begin();
while (it != mPlayVo.end()) {
int vo = *it;
if ( mVoUniqueID[vo] == uniqueID ) {
if (mVoKeyOn[vo]) {
mVoUniqueID[vo] = 0;
mVoPrio[vo] = relPrio;
mVoKeyOn[vo] = false;
}
if ( vo < mVoiceLimit ) {
mWaitVo.push_back(vo);
}
it = mPlayVo.erase(it);
stops++;
mChNoteOns[ch]--;
*relVo = vo;
break; // 2重鳴りはホストに任せる
//continue;
}
it++;
}
return stops;
}
//-----------------------------------------------------------------------------
void DynamicVoiceManager::SetChLimit(int ch, int value)
{
mChLimit[ch & 0xf] = value;
}
//-----------------------------------------------------------------------------
int DynamicVoiceManager::GetChLimit(int ch)
{
return mChLimit[ch & 0xf];
}
//-----------------------------------------------------------------------------
int DynamicVoiceManager::GetNoteOns(int ch)
{
return mChNoteOns[ch & 0xf];
}
//-----------------------------------------------------------------------------
void DynamicVoiceManager::SetKeyOn(int vo)
{
// TODO: voがAlloc済みかどうかチェック
mVoKeyOn[vo] = true;
}
//-----------------------------------------------------------------------------
bool DynamicVoiceManager::IsKeyOn(int vo)
{
return mVoKeyOn[vo];
}
//-----------------------------------------------------------------------------
void DynamicVoiceManager::pushWaitVo(int vo)
{
mWaitVo.push_back(vo);
mVoCh[vo] = 0;
mVoPrio[vo] = 0;
}
//-----------------------------------------------------------------------------
int DynamicVoiceManager::findFreeVoice()
{
int v=-1;
//空きボイスを探す
if ( mWaitVo.size() > 0 ) {
v = mWaitVo.front();
mWaitVo.pop_front();
}
return v;
}
//-----------------------------------------------------------------------------
bool DynamicVoiceManager::IsPlayingVoice(int v)
{
std::list<int>::iterator it = mPlayVo.begin();
while (it != mPlayVo.end()) {
int vo = *it;
if (vo == v) {
return true;
}
it++;
}
return false;
}
//-----------------------------------------------------------------------------
int DynamicVoiceManager::stealVoice(int ch)
{
int v=-1;
int prio_min = 0x7fff;
std::list<int>::reverse_iterator it = mPlayVo.rbegin();
while (it != mPlayVo.rend()) {
int vo = *it;
if ( (mVoPrio[vo] <= prio_min) && (mVoCh[vo] == ch) ) {
prio_min = mVoPrio[vo];
v = vo;
}
it++;
}
return v;
}
//-----------------------------------------------------------------------------
int DynamicVoiceManager::findVoice(int ch)
{
int v=-1;
int prio_min = 0x7fff;
std::list<int>::reverse_iterator it = mPlayVo.rbegin();
while (it != mPlayVo.rend()) {
int vo = *it;
bool chMatch = (mVoCh[vo] == ch) ? true:false;
if (ch == -1) {
chMatch = true;
}
if ( (mVoPrio[vo] <= prio_min) && chMatch ) {
prio_min = mVoPrio[vo];
v = vo + MAX_VOICE;
}
it++;
}
it = mWaitVo.rbegin();
while (it != mWaitVo.rend()) {
int vo = *it;
if (mVoPrio[vo] <= prio_min) {
prio_min = mVoPrio[vo];
v = vo;
}
it++;
}
return v;
}
<commit_msg>発音slotをなるべく維持する機能wip<commit_after>//
// DynamicVoiceManager.cpp
// C700
//
// Created by osoumen on 2014/11/30.
//
//
#include "DynamicVoiceManager.h"
//-----------------------------------------------------------------------------
DynamicVoiceManager::DynamicVoiceManager() :
mVoiceLimit(8)
{
}
//-----------------------------------------------------------------------------
DynamicVoiceManager::~DynamicVoiceManager()
{
}
//-----------------------------------------------------------------------------
void DynamicVoiceManager::Initialize(int voiceLimit)
{
mVoiceLimit = voiceLimit;
for (int i=0; i<16; i++) {
mChNoteOns[i] = 0;
mChLimit[i] = 127;
}
}
//-----------------------------------------------------------------------------
void DynamicVoiceManager::Reset()
{
mPlayVo.clear();
mWaitVo.clear();
for(int i=0;i<mVoiceLimit;i++){
pushWaitVo(i);
}
for (int i=0; i<16; i++) {
mChNoteOns[i] = 0;
}
for (int i=0; i<MAX_VOICE; i++) {
mVoCh[i] = 0;
mVoPrio[i] = 0;
mVoUniqueID[i] = 0;
mVoKeyOn[i] = false;
}
}
//-----------------------------------------------------------------------------
void DynamicVoiceManager::ChangeVoiceLimit(int voiceLimit)
{
if ( voiceLimit < mVoiceLimit ) {
//空きボイスリストから削除する
for ( int i=voiceLimit; i<mVoiceLimit; i++ ) {
mWaitVo.remove(i);
}
}
if ( voiceLimit > mVoiceLimit ) {
//空きボイスを追加する
for ( int i=mVoiceLimit; i<voiceLimit; i++ ) {
pushWaitVo(i);
}
}
mVoiceLimit = voiceLimit;
}
//-----------------------------------------------------------------------------
int DynamicVoiceManager::AllocVoice(int prio, int ch, int uniqueID, bool monoMode,
int *releasedCh, bool *isLegato)
{
int v = -1;
*releasedCh = -1;
*isLegato = false;
if (monoMode) {
v = ch & 0x07; // 固定のchを確保
if (IsPlayingVoice(v)) {
if (mVoCh[v] == ch) {
// レガートで鳴らした音
// キーオン前に2回叩かれた場合は最後のノートオンだけが有効になるように
if (mVoKeyOn[v]) {
*isLegato = true;
}
}
else {
// 別のchの発音がすでにある場合
mPlayVo.remove(v);
*releasedCh = mVoCh[v];
mChNoteOns[mVoCh[v]]--;
}
}
else {
mWaitVo.remove(v);
}
}
else {
if (mChNoteOns[ch] >= mChLimit[ch]) {
// ch発音数を超えてたら、そのchの音を一つ止めて次の音を鳴らす
v = stealVoice(ch);
if (v != -1) {
mPlayVo.remove(v);
*releasedCh = mVoCh[v];
mChNoteOns[mVoCh[v]]--;
}
}
else {
// 超えてない場合は、後着優先で優先度の低い音を消す
v = findVoice(ch);
if (v >= MAX_VOICE) { //空きがなくてどこかを止めた
v -= MAX_VOICE;
mPlayVo.remove(v);
*releasedCh = mVoCh[v];
mChNoteOns[mVoCh[v]]--;
}
else if (v >= 0) {
mWaitVo.remove(v);
}
}
}
if (v != -1) {
mVoCh[v] = ch;
mVoPrio[v] = prio;
mVoKeyOn[v] = false;
mVoUniqueID[v] = uniqueID;
if (*isLegato == false && !IsPlayingVoice(v)) { // モノモードの同時ノートオン対策
mPlayVo.push_back(v);
mChNoteOns[ch]++;
}
}
return v;
}
//-----------------------------------------------------------------------------
int DynamicVoiceManager::ReleaseVoice(int relPrio, int ch, int uniqueID, int *relVo)
{
int stops = 0;
std::list<int>::iterator it = mPlayVo.begin();
while (it != mPlayVo.end()) {
int vo = *it;
if ( mVoUniqueID[vo] == uniqueID ) {
if (mVoKeyOn[vo]) {
mVoUniqueID[vo] = 0;
mVoPrio[vo] = relPrio;
mVoKeyOn[vo] = false;
}
if ( vo < mVoiceLimit ) {
mWaitVo.push_back(vo);
}
it = mPlayVo.erase(it);
stops++;
mChNoteOns[ch]--;
*relVo = vo;
break; // 2重鳴りはホストに任せる
//continue;
}
it++;
}
return stops;
}
//-----------------------------------------------------------------------------
void DynamicVoiceManager::SetChLimit(int ch, int value)
{
mChLimit[ch & 0xf] = value;
}
//-----------------------------------------------------------------------------
int DynamicVoiceManager::GetChLimit(int ch)
{
return mChLimit[ch & 0xf];
}
//-----------------------------------------------------------------------------
int DynamicVoiceManager::GetNoteOns(int ch)
{
return mChNoteOns[ch & 0xf];
}
//-----------------------------------------------------------------------------
void DynamicVoiceManager::SetKeyOn(int vo)
{
// TODO: voがAlloc済みかどうかチェック
mVoKeyOn[vo] = true;
}
//-----------------------------------------------------------------------------
bool DynamicVoiceManager::IsKeyOn(int vo)
{
return mVoKeyOn[vo];
}
//-----------------------------------------------------------------------------
void DynamicVoiceManager::pushWaitVo(int vo)
{
mWaitVo.push_back(vo);
mVoCh[vo] = 0;
mVoPrio[vo] = 0;
}
//-----------------------------------------------------------------------------
int DynamicVoiceManager::findFreeVoice()
{
int v=-1;
//空きボイスを探す
if ( mWaitVo.size() > 0 ) {
v = mWaitVo.front();
mWaitVo.pop_front();
}
return v;
}
//-----------------------------------------------------------------------------
bool DynamicVoiceManager::IsPlayingVoice(int v)
{
std::list<int>::iterator it = mPlayVo.begin();
while (it != mPlayVo.end()) {
int vo = *it;
if (vo == v) {
return true;
}
it++;
}
return false;
}
//-----------------------------------------------------------------------------
int DynamicVoiceManager::stealVoice(int ch)
{
int v=-1;
int prio_min = 0x7fff;
std::list<int>::reverse_iterator it = mPlayVo.rbegin();
while (it != mPlayVo.rend()) {
int vo = *it;
if ( (mVoPrio[vo] <= prio_min) && (mVoCh[vo] == ch) ) {
prio_min = mVoPrio[vo];
v = vo;
}
it++;
}
return v;
}
//-----------------------------------------------------------------------------
int DynamicVoiceManager::findVoice(int ch)
{
int v=-1;
int prio_min = 0x7fff;
std::list<int>::reverse_iterator it = mPlayVo.rbegin();
while (it != mPlayVo.rend()) {
int vo = *it;
if ( mVoPrio[vo] <= prio_min ) {
prio_min = mVoPrio[vo];
v = vo + MAX_VOICE; // どこかを止めて確保した場合は+MAX_VOICEした値を返す
}
it++;
}
// chを指定した場合はそのMIDIchを優先する
if (ch != -1) {
it = mPlayVo.rbegin();
while (it != mPlayVo.rend()) {
int vo = *it;
int prio = 1; // 通常ありえるノートオンプライオリティの最低値
if ( (prio <= prio_min) && mVoCh[vo] == ch ) {
prio_min = prio;
v = vo + MAX_VOICE;
}
it++;
}
}
it = mWaitVo.rbegin();
while (it != mWaitVo.rend()) {
int vo = *it;
int prio = mVoPrio[vo];
if (ch != -1 && ch == mVoCh[vo]) {
prio = -1; // リリースプライオリティのデフォルト値の0より1小さい
}
if (prio <= prio_min) {
prio_min = prio;
v = vo;
}
it++;
}
return v;
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: ModelComponent.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2013 Stanford University and the Authors *
* Author(s): Ajay Seth, Michael Sherman *
* *
* 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. *
* -------------------------------------------------------------------------- */
// INCLUDES
#include "OpenSim/Simulation/Model/ModelComponent.h"
#include "OpenSim/Simulation/Model/Model.h"
using namespace SimTK;
namespace OpenSim {
//==============================================================================
// MODEL COMPONENT
//==============================================================================
ModelComponent::ModelComponent() : _model(NULL)
{
constructProperty_GeometrySet();
}
ModelComponent::ModelComponent(const std::string& fileName, bool updFromXMLNode)
: Component(fileName, updFromXMLNode), _model(NULL)
{
constructProperty_GeometrySet();
}
ModelComponent::ModelComponent(SimTK::Xml::Element& element)
: Component(element), _model(NULL)
{
constructProperty_GeometrySet();
}
const Model& ModelComponent::getModel() const
{
if(!_model)
throw Exception("ModelComponent::getModel(): component '" + getName() +
"' of type " + getConcreteClassName() + " does not belong to a model. "
"Have you called Model::initSystem()?");
return *_model;
}
Model& ModelComponent::updModel()
{
if(!_model)
throw Exception("ModelComponent::updModel(): component '" + getName() +
"' of type " + getConcreteClassName() + " does not belong to a model. "
"Have you called Model::initSystem()?");
return *_model;
}
void ModelComponent::extendConnect(Component &root)
{
Super::extendConnect(root);
Model* model = dynamic_cast<Model*>(&root);
// Allow (model) component to include its own subcomponents
// before calling the base method which automatically invokes
// connect all the subcomponents.
if (model)
connectToModel(*model);
}
// Base class implementation of virtual method.
void ModelComponent::connectToModel(Model& model)
{
_model = &model;
extendConnectToModel(model);
int geomSize = getProperty_GeometrySet().size();
if (geomSize > 0){
for (int i = 0; i < geomSize; ++i)
addComponent(&upd_GeometrySet(i));
}
}
// Base class implementation of virtual method.
void ModelComponent::generateDecorations
(bool fixed,
const ModelDisplayHints& hints,
const SimTK::State& state,
SimTK::Array_<SimTK::DecorativeGeometry>& appendToThis) const
{
for(unsigned int i=0; i < _components.size(); i++){
ModelComponent *mc = dynamic_cast<ModelComponent*>(_components[i]);
if (mc)
mc->generateDecorations(fixed,hints,state,appendToThis);
}
}
void ModelComponent::adoptGeometry(OpenSim::Geometry* geom) {
append_GeometrySet(*geom);
addComponent(geom); // Geometry is a subcomponent.
return;
}
const SimTK::DefaultSystemSubsystem& ModelComponent::
getDefaultSubsystem() const
{ return getModel().getDefaultSubsystem(); }
const SimTK::DefaultSystemSubsystem& ModelComponent::
updDefaultSubsystem()
{ return updModel().updDefaultSubsystem(); }
} // end of namespace OpenSim
<commit_msg>Fix test cases that fails due to adding geometry components more than once.<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: ModelComponent.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2013 Stanford University and the Authors *
* Author(s): Ajay Seth, Michael Sherman *
* *
* 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. *
* -------------------------------------------------------------------------- */
// INCLUDES
#include "OpenSim/Simulation/Model/ModelComponent.h"
#include "OpenSim/Simulation/Model/Model.h"
using namespace SimTK;
namespace OpenSim {
//==============================================================================
// MODEL COMPONENT
//==============================================================================
ModelComponent::ModelComponent() : _model(NULL)
{
constructProperty_GeometrySet();
}
ModelComponent::ModelComponent(const std::string& fileName, bool updFromXMLNode)
: Component(fileName, updFromXMLNode), _model(NULL)
{
constructProperty_GeometrySet();
}
ModelComponent::ModelComponent(SimTK::Xml::Element& element)
: Component(element), _model(NULL)
{
constructProperty_GeometrySet();
}
const Model& ModelComponent::getModel() const
{
if(!_model)
throw Exception("ModelComponent::getModel(): component '" + getName() +
"' of type " + getConcreteClassName() + " does not belong to a model. "
"Have you called Model::initSystem()?");
return *_model;
}
Model& ModelComponent::updModel()
{
if(!_model)
throw Exception("ModelComponent::updModel(): component '" + getName() +
"' of type " + getConcreteClassName() + " does not belong to a model. "
"Have you called Model::initSystem()?");
return *_model;
}
void ModelComponent::extendConnect(Component &root)
{
Super::extendConnect(root);
Model* model = dynamic_cast<Model*>(&root);
// Allow (model) component to include its own subcomponents
// before calling the base method which automatically invokes
// connect all the subcomponents.
if (model)
connectToModel(*model);
}
// Base class implementation of virtual method.
void ModelComponent::connectToModel(Model& model)
{
_model = &model;
extendConnectToModel(model);
int geomSize = getProperty_GeometrySet().size();
if (geomSize > 0){
for (int i = 0; i < geomSize; ++i)
if (findComponent(get_GeometrySet(i).getName())==nullptr)
addComponent(&upd_GeometrySet(i));
}
}
// Base class implementation of virtual method.
void ModelComponent::generateDecorations
(bool fixed,
const ModelDisplayHints& hints,
const SimTK::State& state,
SimTK::Array_<SimTK::DecorativeGeometry>& appendToThis) const
{
for(unsigned int i=0; i < _components.size(); i++){
ModelComponent *mc = dynamic_cast<ModelComponent*>(_components[i]);
if (mc)
mc->generateDecorations(fixed,hints,state,appendToThis);
}
}
void ModelComponent::adoptGeometry(OpenSim::Geometry* geom) {
append_GeometrySet(*geom);
addComponent(geom); // Geometry is a subcomponent.
return;
}
const SimTK::DefaultSystemSubsystem& ModelComponent::
getDefaultSubsystem() const
{ return getModel().getDefaultSubsystem(); }
const SimTK::DefaultSystemSubsystem& ModelComponent::
updDefaultSubsystem()
{ return updModel().updDefaultSubsystem(); }
} // end of namespace OpenSim
<|endoftext|> |
<commit_before>#include <cassert>
#include <cmath>
#include "SDL.h"
#include "AutomapPanel.h"
#include "GameWorldPanel.h"
#include "TextBox.h"
#include "../Game/CardinalDirection.h"
#include "../Game/CardinalDirectionName.h"
#include "../Game/Game.h"
#include "../Game/Options.h"
#include "../Interface/TextAlignment.h"
#include "../Math/Rect.h"
#include "../Math/Vector2.h"
#include "../Media/FontManager.h"
#include "../Media/FontName.h"
#include "../Media/PaletteFile.h"
#include "../Media/PaletteName.h"
#include "../Media/TextureFile.h"
#include "../Media/TextureManager.h"
#include "../Media/TextureName.h"
#include "../Rendering/Renderer.h"
#include "../Rendering/Surface.h"
#include "../Rendering/Texture.h"
#include "../World/VoxelData.h"
#include "../World/VoxelGrid.h"
namespace
{
// Click areas for compass directions.
const Rect UpRegion(264, 23, 14, 14);
const Rect DownRegion(264, 60, 14, 14);
const Rect LeftRegion(245, 41, 14, 14);
const Rect RightRegion(284, 41, 14, 14);
// Colors for automap pixels. Ground pixels (y == 0) are transparent.
const Color AutomapPlayer(247, 255, 0);
const Color AutomapWall(130, 89, 48);
const Color AutomapDoor(146, 0, 0);
const Color AutomapFloorUp(0, 105, 0);
const Color AutomapFloorDown(0, 0, 255);
const Color AutomapWater(109, 138, 174);
const Color AutomapLava(255, 0, 0);
}
AutomapPanel::AutomapPanel(Game *game, const Double2 &playerPosition,
const Double2 &playerDirection, const VoxelGrid &voxelGrid, const std::string &locationName)
: Panel(game), automapCenter(playerPosition)
{
this->locationTextBox = [game, &locationName]()
{
Int2 center(120, 28);
Color color(56, 16, 12); // Shadow color is (150, 101, 52).
auto &font = game->getFontManager().getFont(FontName::A);
auto alignment = TextAlignment::Center;
return std::unique_ptr<TextBox>(new TextBox(
center,
color,
locationName,
font,
alignment,
game->getRenderer()));
}();
this->backToGameButton = []()
{
Int2 center(Renderer::ORIGINAL_WIDTH - 57, Renderer::ORIGINAL_HEIGHT - 29);
int width = 38;
int height = 13;
auto function = [](Game *game)
{
std::unique_ptr<Panel> gamePanel(new GameWorldPanel(game));
game->setPanel(std::move(gamePanel));
};
return std::unique_ptr<Button<Game*>>(
new Button<Game*>(center, width, height, function));
}();
this->mapTexture = [this, &playerPosition, &playerDirection, &voxelGrid]()
{
// Create scratch surface. For the purposes of the automap, left to right is
// the Z axis, and up and down is the X axis, because north is +X in-game.
// - To do: the SDL_Surface should have 3x3 pixels per voxel, since the player arrow is
// drawn with 3 pixels in one automap "pixel". Therefore, it needs to be scaled by 3.
SDL_Surface *surface = Surface::createSurfaceWithFormat(
voxelGrid.getDepth(), voxelGrid.getWidth(), Renderer::DEFAULT_BPP,
Renderer::DEFAULT_PIXELFORMAT);
// Fill with transparent color.
SDL_FillRect(surface, nullptr, SDL_MapRGBA(surface->format, 0, 0, 0, 0));
// Lambda for returning the Y coordinate of the highest non-air voxel in a column.
auto getYHitFloor = [&voxelGrid](int x, int z)
{
const char *voxels = voxelGrid.getVoxels();
for (int y = (voxelGrid.getHeight() - 1); y >= 0; --y)
{
const int index = x + (y * voxelGrid.getWidth()) +
(z * voxelGrid.getWidth() * voxelGrid.getHeight());
// If not air, then get the Y coordinate.
if (voxels[index] != 0)
{
return y;
}
}
// No solid voxel was hit, so return below the ground floor.
// - Perhaps the voxel grid should store the "kind" of water (i.e., lava)?
return -1;
};
// For each automap pixel, walk from the highest Y to the lowest. The color depends
// on the last height that was reached (y == -1 is water/lava, 0 is ground, etc.).
uint32_t *pixels = static_cast<uint32_t*>(surface->pixels);
for (int x = 0; x < surface->h; ++x)
{
for (int z = 0; z < surface->w; ++z)
{
const int index = z + ((surface->h - 1 - x) * surface->w);
const int yFloor = getYHitFloor(x, z);
// Decide which color the pixel will be. Do nothing if ground (y == 0), because
// the ground color is transparent.
if (yFloor == -1)
{
// Water/lava.
pixels[index] = AutomapWater.toARGB();
}
else if (yFloor > 0)
{
// Wall.
pixels[index] = AutomapWall.toARGB();
}
// Other types eventually (doors, stairs, ...).
}
}
// Draw player last. The player arrow is three pixels, dependent on direction.
const Int2 playerVoxelPosition(
static_cast<int>(std::floor(playerPosition.x)),
static_cast<int>(std::floor(playerPosition.y)));
const CardinalDirectionName cardinalDirection =
CardinalDirection::getDirectionName(playerDirection);
// Verify that the player is within the bounds of the map before drawing. Coordinates
// are reversed because +X is north (up) and Z is aliased as Y.
if ((playerVoxelPosition.x >= 0) && (playerVoxelPosition.x < surface->h) &&
(playerVoxelPosition.y >= 0) && (playerVoxelPosition.y < surface->w))
{
const int index = playerVoxelPosition.y +
((surface->h - 1 - playerVoxelPosition.x) * surface->w);
pixels[index] = AutomapPlayer.toARGB();
}
auto &renderer = this->getGame()->getRenderer();
std::unique_ptr<Texture> texture(new Texture(renderer.createTextureFromSurface(surface)));
SDL_FreeSurface(surface);
return texture;
}();
}
AutomapPanel::~AutomapPanel()
{
}
void AutomapPanel::handleEvent(const SDL_Event &e)
{
const auto &inputManager = this->getGame()->getInputManager();
bool escapePressed = inputManager.keyPressed(e, SDLK_ESCAPE);
bool nPressed = inputManager.keyPressed(e, SDLK_n);
if (escapePressed || nPressed)
{
this->backToGameButton->click(this->getGame());
}
bool leftClick = inputManager.mouseButtonPressed(e, SDL_BUTTON_LEFT);
if (leftClick)
{
const Int2 mousePosition = inputManager.getMousePosition();
const Int2 mouseOriginalPoint = this->getGame()->getRenderer()
.nativePointToOriginal(mousePosition);
// Check if "Exit" was clicked.
if (this->backToGameButton->contains(mouseOriginalPoint))
{
this->backToGameButton->click(this->getGame());
}
}
}
void AutomapPanel::handleMouse(double dt)
{
static_cast<void>(dt);
const auto &inputManager = this->getGame()->getInputManager();
const bool leftClick = inputManager.mouseButtonIsDown(SDL_BUTTON_LEFT);
const Int2 mousePosition = inputManager.getMousePosition();
const Int2 mouseOriginalPoint = this->getGame()->getRenderer()
.nativePointToOriginal(mousePosition);
// Check if the LMB is held on one of the compass directions.
if (leftClick)
{
// To do: scroll the map relative to delta time.
if (UpRegion.contains(mouseOriginalPoint))
{
}
else if (DownRegion.contains(mouseOriginalPoint))
{
}
else if (RightRegion.contains(mouseOriginalPoint))
{
}
else if (LeftRegion.contains(mouseOriginalPoint))
{
}
}
}
void AutomapPanel::drawTooltip(const std::string &text, Renderer &renderer)
{
const Font &font = this->getGame()->getFontManager().getFont(FontName::D);
Texture tooltip(Panel::createTooltip(text, font, renderer));
const auto &inputManager = this->getGame()->getInputManager();
const Int2 mousePosition = inputManager.getMousePosition();
const Int2 originalPosition = renderer.nativePointToOriginal(mousePosition);
const int mouseX = originalPosition.x;
const int mouseY = originalPosition.y;
const int x = ((mouseX + 8 + tooltip.getWidth()) < Renderer::ORIGINAL_WIDTH) ?
(mouseX + 8) : (mouseX - tooltip.getWidth());
const int y = ((mouseY + tooltip.getHeight()) < Renderer::ORIGINAL_HEIGHT) ?
(mouseY - 1) : (mouseY - tooltip.getHeight());
renderer.drawToOriginal(tooltip.get(), x, y);
}
void AutomapPanel::tick(double dt)
{
this->handleMouse(dt);
}
void AutomapPanel::render(Renderer &renderer)
{
// Clear full screen.
renderer.clearNative();
renderer.clearOriginal();
// Set palette.
auto &textureManager = this->getGame()->getTextureManager();
textureManager.setPalette(PaletteFile::fromName(PaletteName::Default));
// Draw automap background.
const auto &automapBackground = textureManager.getTexture(
TextureFile::fromName(TextureName::Automap),
PaletteFile::fromName(PaletteName::BuiltIn));
renderer.drawToOriginal(automapBackground.get());
// Draw automap.
renderer.drawToOriginal(this->mapTexture->get(), 25, 40,
this->mapTexture->getWidth() * 3, this->mapTexture->getHeight() * 3);
// Draw text: title.
renderer.drawToOriginal(this->locationTextBox->getTexture(),
this->locationTextBox->getX(), this->locationTextBox->getY());
// Check if the mouse is over the compass directions for tooltips.
const auto &inputManager = this->getGame()->getInputManager();
const Int2 mousePosition = inputManager.getMousePosition();
const Int2 originalPosition = renderer.nativePointToOriginal(mousePosition);
if (UpRegion.contains(originalPosition))
{
this->drawTooltip("Up", renderer);
}
else if (DownRegion.contains(originalPosition))
{
this->drawTooltip("Down", renderer);
}
else if (LeftRegion.contains(originalPosition))
{
this->drawTooltip("Left", renderer);
}
else if (RightRegion.contains(originalPosition))
{
this->drawTooltip("Right", renderer);
}
// Scale the original frame buffer onto the native one.
renderer.drawOriginalToNative();
// Draw quill cursor. This one uses a different point for blitting because
// the tip of the cursor is at the bottom left, not the top left.
const auto &cursor = textureManager.getTexture(
TextureFile::fromName(TextureName::QuillCursor),
TextureFile::fromName(TextureName::Automap));
const auto &options = this->getGame()->getOptions();
const int cursorYOffset = static_cast<int>(
static_cast<double>(cursor.getHeight()) * options.getCursorScale());
renderer.drawToNative(cursor.get(),
mousePosition.x,
mousePosition.y - cursorYOffset,
static_cast<int>(cursor.getWidth() * options.getCursorScale()),
static_cast<int>(cursor.getHeight() * options.getCursorScale()));
}
<commit_msg>Added player arrow to automap.<commit_after>#include <cassert>
#include <cmath>
#include <map>
#include <vector>
#include "SDL.h"
#include "AutomapPanel.h"
#include "GameWorldPanel.h"
#include "TextBox.h"
#include "../Game/CardinalDirection.h"
#include "../Game/CardinalDirectionName.h"
#include "../Game/Game.h"
#include "../Game/Options.h"
#include "../Interface/TextAlignment.h"
#include "../Math/Rect.h"
#include "../Math/Vector2.h"
#include "../Media/FontManager.h"
#include "../Media/FontName.h"
#include "../Media/PaletteFile.h"
#include "../Media/PaletteName.h"
#include "../Media/TextureFile.h"
#include "../Media/TextureManager.h"
#include "../Media/TextureName.h"
#include "../Rendering/Renderer.h"
#include "../Rendering/Surface.h"
#include "../Rendering/Texture.h"
#include "../World/VoxelData.h"
#include "../World/VoxelGrid.h"
namespace
{
// Click areas for compass directions.
const Rect UpRegion(264, 23, 14, 14);
const Rect DownRegion(264, 60, 14, 14);
const Rect LeftRegion(245, 41, 14, 14);
const Rect RightRegion(284, 41, 14, 14);
// Colors for automap pixels. Ground pixels (y == 0) are transparent.
const Color AutomapPlayer(247, 255, 0);
const Color AutomapWall(130, 89, 48);
const Color AutomapDoor(146, 0, 0);
const Color AutomapFloorUp(0, 105, 0);
const Color AutomapFloorDown(0, 0, 255);
const Color AutomapWater(109, 138, 174);
const Color AutomapLava(255, 0, 0);
// Sets of sub-pixel coordinates for drawing each of the player's arrow directions.
// These are offsets from the top-left corner of the 3x3 map pixel that the player
// is in.
const std::map<CardinalDirectionName, std::vector<Int2>> AutomapPlayerArrowPatterns =
{
{ CardinalDirectionName::North, { Int2(1, 0), Int2(0, 1), Int2(2, 1) } },
{ CardinalDirectionName::NorthEast, { Int2(0, 0), Int2(1, 0), Int2(2, 0), Int2(2, 1), Int2(2, 2) } },
{ CardinalDirectionName::East, { Int2(1, 0), Int2(2, 1), Int2(1, 2) } },
{ CardinalDirectionName::SouthEast, { Int2(2, 0), Int2(2, 1), Int2(0, 2), Int2(1, 2), Int2(2, 2) } },
{ CardinalDirectionName::South, { Int2(0, 1), Int2(2, 1), Int2(1, 2) } },
{ CardinalDirectionName::SouthWest, { Int2(0, 0), Int2(0, 1), Int2(0, 2), Int2(1, 2), Int2(2, 2) } },
{ CardinalDirectionName::West, { Int2(1, 0), Int2(0, 1), Int2(1, 2) } },
{ CardinalDirectionName::NorthWest, { Int2(0, 0), Int2(1, 0), Int2(2, 0), Int2(0, 1), Int2(0, 2) } }
};
}
AutomapPanel::AutomapPanel(Game *game, const Double2 &playerPosition,
const Double2 &playerDirection, const VoxelGrid &voxelGrid, const std::string &locationName)
: Panel(game), automapCenter(playerPosition)
{
this->locationTextBox = [game, &locationName]()
{
Int2 center(120, 28);
Color color(56, 16, 12); // Shadow color is (150, 101, 52).
auto &font = game->getFontManager().getFont(FontName::A);
auto alignment = TextAlignment::Center;
return std::unique_ptr<TextBox>(new TextBox(
center,
color,
locationName,
font,
alignment,
game->getRenderer()));
}();
this->backToGameButton = []()
{
Int2 center(Renderer::ORIGINAL_WIDTH - 57, Renderer::ORIGINAL_HEIGHT - 29);
int width = 38;
int height = 13;
auto function = [](Game *game)
{
std::unique_ptr<Panel> gamePanel(new GameWorldPanel(game));
game->setPanel(std::move(gamePanel));
};
return std::unique_ptr<Button<Game*>>(
new Button<Game*>(center, width, height, function));
}();
this->mapTexture = [this, &playerPosition, &playerDirection, &voxelGrid]()
{
// Create scratch surface. For the purposes of the automap, the bottom left corner
// is (0, 0), left to right is the Z axis, and up and down is the X axis, because
// north is +X in-game. It is scaled by 3 so that all directions of the player's
// arrow are representable.
SDL_Surface *surface = Surface::createSurfaceWithFormat(
voxelGrid.getDepth() * 3, voxelGrid.getWidth() * 3, Renderer::DEFAULT_BPP,
Renderer::DEFAULT_PIXELFORMAT);
// Fill with transparent color first.
SDL_FillRect(surface, nullptr, SDL_MapRGBA(surface->format, 0, 0, 0, 0));
// Lambda for returning the Y coordinate of the highest non-air voxel in a column.
auto getYHitFloor = [&voxelGrid](int x, int z)
{
const char *voxels = voxelGrid.getVoxels();
for (int y = (voxelGrid.getHeight() - 1); y >= 0; --y)
{
const int index = x + (y * voxelGrid.getWidth()) +
(z * voxelGrid.getWidth() * voxelGrid.getHeight());
// If not air, then get the Y coordinate.
if (voxels[index] != 0)
{
return y;
}
}
// No solid voxel was hit, so return below the ground floor.
// - Perhaps the voxel grid should store the "kind" of water (i.e., lava)?
return -1;
};
// Lambda for filling a square in the map surface.
auto drawSquare = [surface](int x, int z, uint32_t color)
{
SDL_Rect rect;
rect.x = z * 3;
rect.y = surface->h - 3 - (x * 3);
rect.w = 3;
rect.h = 3;
SDL_FillRect(surface, &rect, color);
};
// For each voxel, walk from the highest Y to the lowest. The color depends
// on the final height that was reached (y == -1 is water/lava, 0 is ground, etc.).
for (int x = 0; x < voxelGrid.getWidth(); ++x)
{
for (int z = 0; z < voxelGrid.getDepth(); ++z)
{
const int yFloor = getYHitFloor(x, z);
// Decide which color the pixel will be. Do nothing if ground (y == 0), because
// the ground color is transparent.
if (yFloor == -1)
{
// Water/lava.
drawSquare(x, z, AutomapWater.toARGB());
}
else if (yFloor > 0)
{
// Wall.
drawSquare(x, z, AutomapWall.toARGB());
}
// To do: Other types eventually (red doors, blue/green stairs, ...). Some
// voxels have priority even if they are between voxels in a column, so this
// drawing loop will eventually need to find the highest priority color instead
// of the first hit.
}
}
// Lambda for drawing the player's arrow in the automap. It's drawn differently
// depending on their direction.
auto drawPlayer = [surface](int x, int z, const Double2 &direction)
{
const CardinalDirectionName cardinalDirection =
CardinalDirection::getDirectionName(direction);
const int surfaceX = z * 3;
const int surfaceY = surface->h - 3 - (x * 3);
uint32_t *pixels = static_cast<uint32_t*>(surface->pixels);
// Draw the player's arrow within the 3x3 map pixel.
const std::vector<Int2> &offsets = AutomapPlayerArrowPatterns.at(cardinalDirection);
for (auto &offset : offsets)
{
const int index = (surfaceX + offset.x) +
((surfaceY + offset.y) * surface->w);
pixels[index] = AutomapPlayer.toARGB();
}
};
const int playerVoxelX = static_cast<int>(std::floor(playerPosition.x));
const int playerVoxelZ = static_cast<int>(std::floor(playerPosition.y));
// Draw player last. Verify that the player is within the bounds of the map
// before drawing.
if ((playerVoxelX >= 0) && (playerVoxelX < voxelGrid.getWidth()) &&
(playerVoxelZ >= 0) && (playerVoxelZ < voxelGrid.getDepth()))
{
drawPlayer(playerVoxelX, playerVoxelZ, playerDirection);
}
auto &renderer = this->getGame()->getRenderer();
std::unique_ptr<Texture> texture(new Texture(renderer.createTextureFromSurface(surface)));
SDL_FreeSurface(surface);
return texture;
}();
}
AutomapPanel::~AutomapPanel()
{
}
void AutomapPanel::handleEvent(const SDL_Event &e)
{
const auto &inputManager = this->getGame()->getInputManager();
bool escapePressed = inputManager.keyPressed(e, SDLK_ESCAPE);
bool nPressed = inputManager.keyPressed(e, SDLK_n);
if (escapePressed || nPressed)
{
this->backToGameButton->click(this->getGame());
}
bool leftClick = inputManager.mouseButtonPressed(e, SDL_BUTTON_LEFT);
if (leftClick)
{
const Int2 mousePosition = inputManager.getMousePosition();
const Int2 mouseOriginalPoint = this->getGame()->getRenderer()
.nativePointToOriginal(mousePosition);
// Check if "Exit" was clicked.
if (this->backToGameButton->contains(mouseOriginalPoint))
{
this->backToGameButton->click(this->getGame());
}
}
}
void AutomapPanel::handleMouse(double dt)
{
static_cast<void>(dt);
const auto &inputManager = this->getGame()->getInputManager();
const bool leftClick = inputManager.mouseButtonIsDown(SDL_BUTTON_LEFT);
const Int2 mousePosition = inputManager.getMousePosition();
const Int2 mouseOriginalPoint = this->getGame()->getRenderer()
.nativePointToOriginal(mousePosition);
// Check if the LMB is held on one of the compass directions.
if (leftClick)
{
// To do: scroll the map relative to delta time.
if (UpRegion.contains(mouseOriginalPoint))
{
}
else if (DownRegion.contains(mouseOriginalPoint))
{
}
else if (RightRegion.contains(mouseOriginalPoint))
{
}
else if (LeftRegion.contains(mouseOriginalPoint))
{
}
}
}
void AutomapPanel::drawTooltip(const std::string &text, Renderer &renderer)
{
const Font &font = this->getGame()->getFontManager().getFont(FontName::D);
Texture tooltip(Panel::createTooltip(text, font, renderer));
const auto &inputManager = this->getGame()->getInputManager();
const Int2 mousePosition = inputManager.getMousePosition();
const Int2 originalPosition = renderer.nativePointToOriginal(mousePosition);
const int mouseX = originalPosition.x;
const int mouseY = originalPosition.y;
const int x = ((mouseX + 8 + tooltip.getWidth()) < Renderer::ORIGINAL_WIDTH) ?
(mouseX + 8) : (mouseX - tooltip.getWidth());
const int y = ((mouseY + tooltip.getHeight()) < Renderer::ORIGINAL_HEIGHT) ?
(mouseY - 1) : (mouseY - tooltip.getHeight());
renderer.drawToOriginal(tooltip.get(), x, y);
}
void AutomapPanel::tick(double dt)
{
this->handleMouse(dt);
}
void AutomapPanel::render(Renderer &renderer)
{
// Clear full screen.
renderer.clearNative();
renderer.clearOriginal();
// Set palette.
auto &textureManager = this->getGame()->getTextureManager();
textureManager.setPalette(PaletteFile::fromName(PaletteName::Default));
// Draw automap background.
const auto &automapBackground = textureManager.getTexture(
TextureFile::fromName(TextureName::Automap),
PaletteFile::fromName(PaletteName::BuiltIn));
renderer.drawToOriginal(automapBackground.get());
// Draw automap.
renderer.drawToOriginal(this->mapTexture->get(), 25, 40,
this->mapTexture->getWidth(), this->mapTexture->getHeight());
// Draw text: title.
renderer.drawToOriginal(this->locationTextBox->getTexture(),
this->locationTextBox->getX(), this->locationTextBox->getY());
// Check if the mouse is over the compass directions for tooltips.
const auto &inputManager = this->getGame()->getInputManager();
const Int2 mousePosition = inputManager.getMousePosition();
const Int2 originalPosition = renderer.nativePointToOriginal(mousePosition);
if (UpRegion.contains(originalPosition))
{
this->drawTooltip("Up", renderer);
}
else if (DownRegion.contains(originalPosition))
{
this->drawTooltip("Down", renderer);
}
else if (LeftRegion.contains(originalPosition))
{
this->drawTooltip("Left", renderer);
}
else if (RightRegion.contains(originalPosition))
{
this->drawTooltip("Right", renderer);
}
// Scale the original frame buffer onto the native one.
renderer.drawOriginalToNative();
// Draw quill cursor. This one uses a different point for blitting because
// the tip of the cursor is at the bottom left, not the top left.
const auto &cursor = textureManager.getTexture(
TextureFile::fromName(TextureName::QuillCursor),
TextureFile::fromName(TextureName::Automap));
const auto &options = this->getGame()->getOptions();
const int cursorYOffset = static_cast<int>(
static_cast<double>(cursor.getHeight()) * options.getCursorScale());
renderer.drawToNative(cursor.get(),
mousePosition.x,
mousePosition.y - cursorYOffset,
static_cast<int>(cursor.getWidth() * options.getCursorScale()),
static_cast<int>(cursor.getHeight() * options.getCursorScale()));
}
<|endoftext|> |
<commit_before>/*
* DistributionContainer.C
*
* Created on: Jul 6, 2012
* Author: alfoa
*/
#include "DistributionContainer.h"
//#include "Factory.h"
//#include "distribution_1D.h"
#include "distribution_min.h"
#include <iostream>
#include <math.h>
#include <cmath>
#include <cstdlib>
#include <stdlib.h>
#include <vector>
#include <map>
using namespace std;
#ifndef mooseError
#define mooseError(msg) { std::cerr << "\n\n" << msg << "\n\n"; }
#endif
class DistributionContainer;
DistributionContainer::DistributionContainer()
{
}
DistributionContainer::~DistributionContainer()
{
}
/*void
DistributionContainer::addDistributionInContainer(const std::string & type, const std::string & name, InputParameters params){
// create the distribution type
distribution * dist = dynamic_cast<distribution *>(_factory.create(type, name, params));
if (_dist_by_name.find(name) == _dist_by_name.end())
_dist_by_name[name] = dist;
else
mooseError("Distribution with name " << name << " already exists");
_dist_by_type[type].push_back(dist);
}*/
void
DistributionContainer::addDistributionInContainer(const std::string & type, const std::string & name, distribution * dist){
// create the distribution type
//distribution * dist = dynamic_cast<distribution *>(_factory.create(type, name, params));
if (_dist_by_name.find(name) == _dist_by_name.end())
_dist_by_name[name] = dist;
else
mooseError("Distribution with name " << name << " already exists");
_dist_by_type[type].push_back(dist);
}
//void
//DistributionContainer::constructDistributionContainer(std::string DistAlias, distribution_type type, double xmin, double xmax, double param1, double param2, unsigned int seed){
// _distribution_cont.push_back(distribution(type, xmin, xmax, param1, param2, seed));
// _vector_pos_map[DistAlias]=_distribution_cont.size()-1;
//}
//void
//DistributionContainer::constructDistributionContainerCustom(std::string DistAlias, distribution_type type, std::vector< double > dist_x, std::vector< double > dist_y, int numPoints, custom_dist_fit_type fit_type, unsigned int seed){
//
// _distribution_cont.push_back(distribution(dist_x, dist_y, numPoints, fit_type, seed));
// _vector_pos_map[DistAlias]=_distribution_cont.size()-1;
//}
std::string
DistributionContainer::getType(char * DistAlias){
return getType(std::string(DistAlias));
}
std::string
DistributionContainer::getType(std::string DistAlias){
if(_dist_by_name.find(DistAlias) != _dist_by_name.end()){
distribution * dist = _dist_by_name.find(DistAlias)->second;
std::string type = getDistributionType(*dist);
if(type == "DistributionError"){
mooseError("Type for distribution " << DistAlias << " not found");
}
return type;
}
else{
mooseError("Distribution " << DistAlias << " not found in distribution container");
return "DistributionError";
}
}
void
DistributionContainer::seedRandom(unsigned int seed){
srand( seed );
}
double
DistributionContainer::random(){
return (static_cast<double>(rand())/
static_cast<double>(RAND_MAX));
// return -1.0;
}
bool DistributionContainer::checkCdf(std::string DistAlias, double value){
bool result;
if (Cdf(std::string(DistAlias),value) >= getVariable(DistAlias,"ProbabilityThreshold")){
result=true;
_dist_by_trigger_status[DistAlias] = true;
}
else{
result=false;
_dist_by_trigger_status[DistAlias] = false;
return result;
}
}
// to be implemented
bool DistributionContainer::checkCdf(char * DistAlias, double value){
return checkCdf(std::string(DistAlias),value);
}
// end to be implemented
double
DistributionContainer::getVariable(char * paramName,char *DistAlias){
return getVariable(std::string(paramName),std::string(DistAlias));
}
double
DistributionContainer::getVariable(std::string paramName,std::string DistAlias){
if(_dist_by_name.find(DistAlias) != _dist_by_name.end()){
distribution * dist = _dist_by_name.find(DistAlias)->second;
return getDistributionVariable(*dist,paramName);
}
mooseError("Distribution " << DistAlias << " not found in distribution container");
return -1;
}
void
DistributionContainer::updateVariable(char * paramName,double newValue,char *DistAlias){
updateVariable(std::string(paramName),newValue,std::string(DistAlias));
}
void
DistributionContainer::updateVariable(std::string paramName,double newValue,std::string DistAlias){
if(_dist_by_name.find(DistAlias) != _dist_by_name.end()){
distribution * dist = _dist_by_name.find(DistAlias)->second;
DistributionUpdateVariable(*dist,paramName,newValue);
}
mooseError("Distribution " + DistAlias + " was not found in distribution container.");
}
double
DistributionContainer::Pdf(char * DistAlias, double x){
return Pdf(std::string(DistAlias),x);
}
double
DistributionContainer::Pdf(std::string DistAlias, double x){
if(_dist_by_name.find(DistAlias) != _dist_by_name.end()){
distribution * dist = _dist_by_name.find(DistAlias)->second;
return DistributionPdf(*dist,x);
}
mooseError("Distribution " + DistAlias + " was not found in distribution container.");
return -1.0;
}
double
DistributionContainer::Cdf(char * DistAlias, double x){
return Cdf(std::string(DistAlias),x);
}
double
DistributionContainer::Cdf(std::string DistAlias, double x){
if(_dist_by_name.find(DistAlias) != _dist_by_name.end()){
distribution * dist = _dist_by_name.find(DistAlias)->second;
return DistributionCdf(*dist,x);
}
mooseError("Distribution " + DistAlias + " was not found in distribution container.");
return -1.0;
}
double
DistributionContainer::randGen(char * DistAlias, double RNG){
return randGen(std::string(DistAlias), RNG);
}
double
DistributionContainer::randGen(std::string DistAlias, double RNG){
if(_dist_by_name.find(DistAlias) != _dist_by_name.end()){
distribution * dist = _dist_by_name.find(DistAlias)->second;
return dist->RandomNumberGenerator(RNG);
}
mooseError("Distribution " + DistAlias + " was not found in distribution container.");
return -1.0;
}
DistributionContainer & DistributionContainer::Instance() {
if(_instance == NULL){
_instance = new DistributionContainer();
}
return *_instance;
}
DistributionContainer * DistributionContainer::_instance = NULL;
/* the str_to_string_p and free_string_p are for python use */
std::string * str_to_string_p(char *s) {
return new std::string(s);
}
const char * string_p_to_str(const std::string * s) {
return s->c_str();
}
void free_string_p(std::string * s) {
delete s;
}
<commit_msg>fixed - added CDF check for distribution<commit_after>/*
* DistributionContainer.C
*
* Created on: Jul 6, 2012
* Author: alfoa
*/
#include "DistributionContainer.h"
//#include "Factory.h"
//#include "distribution_1D.h"
#include "distribution_min.h"
#include <iostream>
#include <math.h>
#include <cmath>
#include <cstdlib>
#include <stdlib.h>
#include <vector>
#include <map>
using namespace std;
#ifndef mooseError
#define mooseError(msg) { std::cerr << "\n\n" << msg << "\n\n"; }
#endif
class DistributionContainer;
DistributionContainer::DistributionContainer()
{
}
DistributionContainer::~DistributionContainer()
{
}
/*void
DistributionContainer::addDistributionInContainer(const std::string & type, const std::string & name, InputParameters params){
// create the distribution type
distribution * dist = dynamic_cast<distribution *>(_factory.create(type, name, params));
if (_dist_by_name.find(name) == _dist_by_name.end())
_dist_by_name[name] = dist;
else
mooseError("Distribution with name " << name << " already exists");
_dist_by_type[type].push_back(dist);
}*/
void
DistributionContainer::addDistributionInContainer(const std::string & type, const std::string & name, distribution * dist){
// create the distribution type
//distribution * dist = dynamic_cast<distribution *>(_factory.create(type, name, params));
if (_dist_by_name.find(name) == _dist_by_name.end())
_dist_by_name[name] = dist;
else
mooseError("Distribution with name " << name << " already exists");
_dist_by_type[type].push_back(dist);
}
//void
//DistributionContainer::constructDistributionContainer(std::string DistAlias, distribution_type type, double xmin, double xmax, double param1, double param2, unsigned int seed){
// _distribution_cont.push_back(distribution(type, xmin, xmax, param1, param2, seed));
// _vector_pos_map[DistAlias]=_distribution_cont.size()-1;
//}
//void
//DistributionContainer::constructDistributionContainerCustom(std::string DistAlias, distribution_type type, std::vector< double > dist_x, std::vector< double > dist_y, int numPoints, custom_dist_fit_type fit_type, unsigned int seed){
//
// _distribution_cont.push_back(distribution(dist_x, dist_y, numPoints, fit_type, seed));
// _vector_pos_map[DistAlias]=_distribution_cont.size()-1;
//}
std::string
DistributionContainer::getType(char * DistAlias){
return getType(std::string(DistAlias));
}
std::string
DistributionContainer::getType(std::string DistAlias){
if(_dist_by_name.find(DistAlias) != _dist_by_name.end()){
distribution * dist = _dist_by_name.find(DistAlias)->second;
std::string type = getDistributionType(*dist);
if(type == "DistributionError"){
mooseError("Type for distribution " << DistAlias << " not found");
}
return type;
}
else{
mooseError("Distribution " << DistAlias << " not found in distribution container");
return "DistributionError";
}
}
void
DistributionContainer::seedRandom(unsigned int seed){
srand( seed );
}
double
DistributionContainer::random(){
return (static_cast<double>(rand())/
static_cast<double>(RAND_MAX));
// return -1.0;
}
bool DistributionContainer::checkCdf(std::string DistAlias, double value){
bool result;
if (Cdf(std::string(DistAlias),value) >= getVariable(DistAlias,"ProbabilityThreshold")){
result=true;
_dist_by_trigger_status[DistAlias] = true;
}
else{
result=false;
_dist_by_trigger_status[DistAlias] = false;
}
return result;
}
// to be implemented
bool DistributionContainer::checkCdf(char * DistAlias, double value){
return checkCdf(std::string(DistAlias),value);
}
// end to be implemented
double
DistributionContainer::getVariable(char * paramName,char *DistAlias){
return getVariable(std::string(paramName),std::string(DistAlias));
}
double
DistributionContainer::getVariable(std::string paramName,std::string DistAlias){
if(_dist_by_name.find(DistAlias) != _dist_by_name.end()){
distribution * dist = _dist_by_name.find(DistAlias)->second;
return getDistributionVariable(*dist,paramName);
}
mooseError("Distribution " << DistAlias << " not found in distribution container");
return -1;
}
void
DistributionContainer::updateVariable(char * paramName,double newValue,char *DistAlias){
updateVariable(std::string(paramName),newValue,std::string(DistAlias));
}
void
DistributionContainer::updateVariable(std::string paramName,double newValue,std::string DistAlias){
if(_dist_by_name.find(DistAlias) != _dist_by_name.end()){
distribution * dist = _dist_by_name.find(DistAlias)->second;
DistributionUpdateVariable(*dist,paramName,newValue);
}
mooseError("Distribution " + DistAlias + " was not found in distribution container.");
}
double
DistributionContainer::Pdf(char * DistAlias, double x){
return Pdf(std::string(DistAlias),x);
}
double
DistributionContainer::Pdf(std::string DistAlias, double x){
if(_dist_by_name.find(DistAlias) != _dist_by_name.end()){
distribution * dist = _dist_by_name.find(DistAlias)->second;
return DistributionPdf(*dist,x);
}
mooseError("Distribution " + DistAlias + " was not found in distribution container.");
return -1.0;
}
double
DistributionContainer::Cdf(char * DistAlias, double x){
return Cdf(std::string(DistAlias),x);
}
double
DistributionContainer::Cdf(std::string DistAlias, double x){
if(_dist_by_name.find(DistAlias) != _dist_by_name.end()){
distribution * dist = _dist_by_name.find(DistAlias)->second;
return DistributionCdf(*dist,x);
}
mooseError("Distribution " + DistAlias + " was not found in distribution container.");
return -1.0;
}
double
DistributionContainer::randGen(char * DistAlias, double RNG){
return randGen(std::string(DistAlias), RNG);
}
double
DistributionContainer::randGen(std::string DistAlias, double RNG){
if(_dist_by_name.find(DistAlias) != _dist_by_name.end()){
distribution * dist = _dist_by_name.find(DistAlias)->second;
return dist->RandomNumberGenerator(RNG);
}
mooseError("Distribution " + DistAlias + " was not found in distribution container.");
return -1.0;
}
DistributionContainer & DistributionContainer::Instance() {
if(_instance == NULL){
_instance = new DistributionContainer();
}
return *_instance;
}
DistributionContainer * DistributionContainer::_instance = NULL;
/* the str_to_string_p and free_string_p are for python use */
std::string * str_to_string_p(char *s) {
return new std::string(s);
}
const char * string_p_to_str(const std::string * s) {
return s->c_str();
}
void free_string_p(std::string * s) {
delete s;
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <iostream>
#include <map>
#include <random>
#include <set>
#include <utility>
#include <vector>
using Coord = std::pair<int,int>;
using RNG = std::mt19937;
int NumDigits(int n) {
int v = 0;
while (n > 0) {
v++;
n/=10;
}
return v;
}
namespace { // State
class State {
public:
State(int n) : n_(n) {
Place(0, 0);
}
void Place(int x, int y) {
auto value = Value(ps_.size());
ps_.push_back({x,y});
ns_[{x,y}] = -value;
nps_[value].erase({x,y});
for (int dx = -1; dx < 2; dx++) {
const auto nx = x + dx;
for (int dy = -1; dy < 2; dy++) {
const auto ny = y + dy;
if (ns_[{nx,ny}] >= 0) {
const auto old_value = ns_[{nx,ny}];
const auto new_value = old_value + value;
ns_[{nx,ny}] = new_value;
nps_[old_value].erase({nx, ny});
nps_[new_value].insert({nx, ny});
}
}
}
}
std::vector<Coord> Next(int max_delta = 10) {
const auto value = Value(ps_.size());
std::vector<Coord> ret;
if (value > 1) {
for (const auto& [x,y]: nps_[value]) {
ret.push_back({x,y});
}
} else {
for (int x = -max_delta; x <= max_delta; x++) {
for (int y = -max_delta; y <= max_delta; y++) {
const auto& key = Coord{x,y};
const auto& found = ns_.find(key);
// if not found or if found but positive
if (found == ns_.end() || found->second >= 0) {
ret.push_back(key);
}
}
}
}
return ret;
}
int Value(int n) const {
return n < n_ ? 1 : (n - n_ + 2);
}
void Draw(bool full=true) const {
int xmin = 0, ymin = 0, xmax = 0, ymax = 0;
for (const auto& [c,_]: ns_) {
const auto& [x,y] = c;
if (xmin > x) xmin = x;
if (ymin > y) ymin = y;
if (xmax < x) xmax = x;
if (ymax < y) ymax = y;
}
const auto dx = xmax - xmin + 1;
const auto dy = ymax - ymin + 1;
const auto N = dx * dy;
// No 0-init in pure C++
auto matrix = static_cast<int*>(calloc(N, sizeof(int)));
int max_v = 0;
for (const auto& [c,v]: ns_) {
const auto& [x,y] = c;
matrix[(x - xmin) * dy + (y - ymin)] = -v;
if (max_v < v) max_v = v;
}
const int width = 1 + NumDigits(max_v);
if (full) {
for (int i = 0; i < dx; i++) {
for (int j = 0; j < dy; j++) {
// C++20 required for fmt
printf("%*d ", width, matrix[i * dy + j]);
}
printf("\n");
}
} else {
for (int i = 0; i < dx; i++) {
for (int j = 0; j < dy; j++) {
if (matrix[i * dy + j] > 0) {
printf("%*d ", width, matrix[i * dy + j]);
} else {
printf("%*c ", width, ' ');
}
}
printf("\n");
}
}
free(matrix);
}
void Debug() const {
std::cout << "n_=" << n_ << ", next=" << Value(ps_.size())
<< ", placed: " << ps_.size() << "\n";
std::cout << "ps_: ";
for (const auto& [x,y]: ps_)
std::cout << "{" << x << "," << y << "} ";
std::cout << "\n";
std::cout << "ns_: ";
for (const auto& [p,v]: ns_) {
if (!v) continue;
const auto& [x,y] = p;
std::cout << "{<" << x << "," << y << ">:" << v << "} ";
}
std::cout << "\n";
std::cout << "nps_:\n";
for (const auto& [k,v]: nps_) {
std::cout << "\t" << k << ":";
for (const auto& [x,y] : v) {
std::cout << " {" << x << "," << y << "}";
}
std::cout << "\n";
}
}
private:
std::vector<Coord> ps_;
std::map<Coord, int> ns_;
std::map<int, std::set<Coord>> nps_;
int n_;
};
void TestEmpty() {
std::cout << "============ TestEmpty ============\n";
State s(2);
s.Draw();
}
void TestPlaceNear() {
std::cout << "========== TestPlaceNear ==========\n";
State s(2);
s.Place(0, 1);
s.Draw();
}
void TestPlaceNext() {
std::cout << "========== TestPlaceNext ==========\n";
State s(2);
s.Place(0, 1);
s.Place(1, 1);
s.Draw();
}
void TestPlaceNext2() {
std::cout << "========== TestPlaceNext2 =========\n";
State s(2);
s.Place(0, 1);
s.Place(1, 1);
s.Place(0, 2);
s.Draw();
}
void TestGetNextPos() {
std::cout << "========== TestGetNextPos =========\n";
State s(2);
s.Place(0, 1);
s.Place(1, 1);
s.Place(0, 2);
for (const auto& [x,y] : s.Next()) {
std::cout << "{" << x << "," << y << "} ";
}
std::cout << "\n";
}
void TestGetNextPos2() {
std::cout << "========= TestGetNextPos2 =========\n";
State s(2);
for (const auto& [x,y] : s.Next(1)) {
std::cout << "{" << x << "," << y << "} ";
}
std::cout << "\n";
}
void TestPlaceNext3() {
std::cout << "========== TestPlaceNext3 =========\n";
State s(3);
while (true) {
const auto next = s.Next(2);
if (!next.size()) break;
const auto& [x,y] = next[0];
s.Place(x, y);
}
s.Draw();
}
void TestPlaceNext4() {
std::cout << "========== TestPlaceNext4 =========\n";
State s(3);
while (true) {
const auto next = s.Next(2);
if (!next.size()) break;
const auto& [x,y] = next[next.size() / 2];
s.Place(x, y);
}
s.Draw();
}
void TestState() {
TestEmpty();
TestPlaceNear();
TestPlaceNext();
TestPlaceNext2();
TestGetNextPos();
TestGetNextPos2();
TestPlaceNext3();
TestPlaceNext4();
}
} // namespace // State
namespace { // Chromo
class Chromo {
public:
Chromo(RNG* rng, int n, int md=10) : fitness_(0), n_(n), rng_(rng), md_(md), s_(n_) {}
int Fitness() {
if (fitness_) return fitness_;
State s(n_);
bool shorter = false;
for (const auto& g: genes_) {
const auto& next = s.Next(md_);
if (!next.size()) {
shorter = true;
break;
}
const auto& [x,y] = next[g % next.size()];
s.Place(x, y);
++fitness_;
}
if (shorter) {
genes_.resize(fitness_);
} else {
while (true) {
const unsigned int g = (*rng_)();
const auto& next = s.Next(md_);
if (!next.size()) break;
const auto& [x,y] = next[g % next.size()];
s.Place(x, y);
genes_.push_back(g);
++fitness_;
}
}
s_ = s;
return fitness_;
}
void Crossover(Chromo& other) {
std::uniform_int_distribution<> distrib(0,
std::min(genes_.size(), other.genes_.size()) - 1);
int ix = distrib(*rng_);
auto ti = genes_.begin() + ix;
auto oi = other.genes_.begin() + ix;
for(; ti != genes_.end() && oi != other.genes_.end(); ++ti, ++oi) {
std::swap(*ti, *oi);
}
}
void Mutate() {
std::uniform_int_distribution<> distrib(0, genes_.size() - 1);
int ix = distrib(*rng_);
++genes_[ix];
}
void NextGen() { fitness_ = 0; }
void Draw() { s_.Draw(false); }
void AddGene(int x) { genes_.push_back(x); } // testing only
void Dump() const { // testing only
std::cout << "{";
for (const auto& g : genes_) std::cout << g << " ";
std::cout << "}\n";
}
private:
std::vector<int> genes_;
int fitness_;
int n_;
RNG* rng_; // not owned
int md_;
State s_; // only computed in Fitness()
};
void TestInitialFitness() {
std::cout << "======= TestInitialFitness ========\n";
RNG gen;
gen.seed(42);
Chromo c(&gen, 3);
std::cout << c.Fitness() << " " << c.Fitness() << "\n";
}
void TestGivenFitness() {
std::cout << "======== TestGivenFitness =========\n";
RNG gen;
gen.seed(42);
Chromo c(&gen, 3);
c.AddGene(200);
std::cout << c.Fitness() << "\n";
}
void TestGivenFitness2() {
std::cout << "======== TestGivenFitness2 ========\n";
RNG gen;
gen.seed(42);
Chromo c(&gen, 3);
for (const auto& g : {200, 200, 3, 3, 0,0,0,0,0,0, 42}) {
c.AddGene(g);
}
std::cout << c.Fitness() << "\n";
c.Dump();
}
void TestCrossover() {
std::cout << "========== TestCrossover ==========\n";
RNG gen;
gen.seed(42);
Chromo c1(&gen, 3);
for (const auto& g : {1,2,3,4,5,6,7}) {
c1.AddGene(g);
}
Chromo c2(&gen, 3);
for (const auto& g : {11,12,13,14,15,16,17,18,19,20}) {
c2.AddGene(g);
}
c1.Dump();
c2.Dump();
c1.Crossover(c2);
c1.Dump();
c2.Dump();
}
void TestMutate() {
std::cout << "=========== TestMutate ============\n";
RNG gen;
gen.seed(42);
Chromo c(&gen, 3);
for (const auto& g : {200, 200, 3, 3, 0,0,0,0,0,0, 42}) {
c.AddGene(g);
}
c.Dump();
c.Mutate();
c.Dump();
}
void TestChromo() {
TestInitialFitness();
TestGivenFitness();
TestGivenFitness2();
TestCrossover();
TestMutate();
}
} // namespace // Chromo
int main() {
#if 0
TestState();
TestChromo();
#else
const int n = 4;
const int pop_size = 100;
const int md = 10;
const float mutation_probability = 0.05;
const int every_iterations = 10000;
struct {
bool operator()(Chromo a, Chromo b) const {
return a.Fitness() > b.Fitness();
}
} FitnessSort;
RNG gen;
std::random_device r;
gen.seed(r());
std::vector<Chromo> population;
for (int i = 0; i < pop_size; i++) {
population.push_back(Chromo(&gen, n, md));
population[i].Fitness();
}
std::sort(population.begin(), population.end(), FitnessSort);
int best_fitness = population[0].Fitness();
int num_iterations = 0;
while (true) {
++num_iterations;
if (num_iterations % every_iterations == 0) {
std::cout << "Iteration " << num_iterations << " best fitness " << best_fitness - n + 2 << "\n";
}
for (int i = 0; i < pop_size; i += 2) {
population[i].Crossover(population[i+1]);
}
for (auto& c : population) {
std::uniform_real_distribution<> u(0, 1);
if (u(gen) < mutation_probability) {
c.Mutate();
}
c.NextGen();
}
// NOTE: why does this need a separate loop?
for (auto& c : population) {
c.Fitness();
}
std::sort(population.begin(), population.end(), FitnessSort);
if (population[0].Fitness() > best_fitness) {
best_fitness = population[0].Fitness();
std::cout << "New best fitness " << best_fitness - n + 2 << " from:\n";
population[0].Draw();
}
}
#endif
return 0;
}
<commit_msg>Increase mutation rate for 1s<commit_after>#include <algorithm>
#include <iostream>
#include <map>
#include <random>
#include <set>
#include <utility>
#include <vector>
using Coord = std::pair<int,int>;
using RNG = std::mt19937;
int NumDigits(int n) {
int v = 0;
while (n > 0) {
v++;
n/=10;
}
return v;
}
namespace { // State
class State {
public:
State(int n) : n_(n) {
Place(0, 0);
}
void Place(int x, int y) {
auto value = Value(ps_.size());
ps_.push_back({x,y});
ns_[{x,y}] = -value;
nps_[value].erase({x,y});
for (int dx = -1; dx < 2; dx++) {
const auto nx = x + dx;
for (int dy = -1; dy < 2; dy++) {
const auto ny = y + dy;
if (ns_[{nx,ny}] >= 0) {
const auto old_value = ns_[{nx,ny}];
const auto new_value = old_value + value;
ns_[{nx,ny}] = new_value;
nps_[old_value].erase({nx, ny});
nps_[new_value].insert({nx, ny});
}
}
}
}
std::vector<Coord> Next(int max_delta = 10) {
const auto value = Value(ps_.size());
std::vector<Coord> ret;
if (value > 1) {
for (const auto& [x,y]: nps_[value]) {
ret.push_back({x,y});
}
} else {
for (int x = -max_delta; x <= max_delta; x++) {
for (int y = -max_delta; y <= max_delta; y++) {
const auto& key = Coord{x,y};
const auto& found = ns_.find(key);
// if not found or if found but positive
if (found == ns_.end() || found->second >= 0) {
ret.push_back(key);
}
}
}
}
return ret;
}
int Value(int n) const {
return n < n_ ? 1 : (n - n_ + 2);
}
void Draw(bool full=true) const {
int xmin = 0, ymin = 0, xmax = 0, ymax = 0;
for (const auto& [c,_]: ns_) {
const auto& [x,y] = c;
if (xmin > x) xmin = x;
if (ymin > y) ymin = y;
if (xmax < x) xmax = x;
if (ymax < y) ymax = y;
}
const auto dx = xmax - xmin + 1;
const auto dy = ymax - ymin + 1;
const auto N = dx * dy;
// No 0-init in pure C++
auto matrix = static_cast<int*>(calloc(N, sizeof(int)));
int max_v = 0;
for (const auto& [c,v]: ns_) {
const auto& [x,y] = c;
matrix[(x - xmin) * dy + (y - ymin)] = -v;
if (max_v < v) max_v = v;
}
const int width = 1 + NumDigits(max_v);
if (full) {
for (int i = 0; i < dx; i++) {
for (int j = 0; j < dy; j++) {
// C++20 required for fmt
printf("%*d ", width, matrix[i * dy + j]);
}
printf("\n");
}
} else {
for (int i = 0; i < dx; i++) {
for (int j = 0; j < dy; j++) {
if (matrix[i * dy + j] > 0) {
printf("%*d ", width, matrix[i * dy + j]);
} else {
printf("%*c ", width, ' ');
}
}
printf("\n");
}
}
free(matrix);
}
void Debug() const {
std::cout << "n_=" << n_ << ", next=" << Value(ps_.size())
<< ", placed: " << ps_.size() << "\n";
std::cout << "ps_: ";
for (const auto& [x,y]: ps_)
std::cout << "{" << x << "," << y << "} ";
std::cout << "\n";
std::cout << "ns_: ";
for (const auto& [p,v]: ns_) {
if (!v) continue;
const auto& [x,y] = p;
std::cout << "{<" << x << "," << y << ">:" << v << "} ";
}
std::cout << "\n";
std::cout << "nps_:\n";
for (const auto& [k,v]: nps_) {
std::cout << "\t" << k << ":";
for (const auto& [x,y] : v) {
std::cout << " {" << x << "," << y << "}";
}
std::cout << "\n";
}
}
private:
std::vector<Coord> ps_;
std::map<Coord, int> ns_;
std::map<int, std::set<Coord>> nps_;
int n_;
};
void TestEmpty() {
std::cout << "============ TestEmpty ============\n";
State s(2);
s.Draw();
}
void TestPlaceNear() {
std::cout << "========== TestPlaceNear ==========\n";
State s(2);
s.Place(0, 1);
s.Draw();
}
void TestPlaceNext() {
std::cout << "========== TestPlaceNext ==========\n";
State s(2);
s.Place(0, 1);
s.Place(1, 1);
s.Draw();
}
void TestPlaceNext2() {
std::cout << "========== TestPlaceNext2 =========\n";
State s(2);
s.Place(0, 1);
s.Place(1, 1);
s.Place(0, 2);
s.Draw();
}
void TestGetNextPos() {
std::cout << "========== TestGetNextPos =========\n";
State s(2);
s.Place(0, 1);
s.Place(1, 1);
s.Place(0, 2);
for (const auto& [x,y] : s.Next()) {
std::cout << "{" << x << "," << y << "} ";
}
std::cout << "\n";
}
void TestGetNextPos2() {
std::cout << "========= TestGetNextPos2 =========\n";
State s(2);
for (const auto& [x,y] : s.Next(1)) {
std::cout << "{" << x << "," << y << "} ";
}
std::cout << "\n";
}
void TestPlaceNext3() {
std::cout << "========== TestPlaceNext3 =========\n";
State s(3);
while (true) {
const auto next = s.Next(2);
if (!next.size()) break;
const auto& [x,y] = next[0];
s.Place(x, y);
}
s.Draw();
}
void TestPlaceNext4() {
std::cout << "========== TestPlaceNext4 =========\n";
State s(3);
while (true) {
const auto next = s.Next(2);
if (!next.size()) break;
const auto& [x,y] = next[next.size() / 2];
s.Place(x, y);
}
s.Draw();
}
void TestState() {
TestEmpty();
TestPlaceNear();
TestPlaceNext();
TestPlaceNext2();
TestGetNextPos();
TestGetNextPos2();
TestPlaceNext3();
TestPlaceNext4();
}
} // namespace // State
namespace { // Chromo
class Chromo {
public:
Chromo(RNG* rng, int n, int md=10) : fitness_(0), n_(n), rng_(rng), md_(md), s_(n_) {}
int Fitness() {
if (fitness_) return fitness_;
State s(n_);
bool shorter = false;
for (const auto& g: genes_) {
const auto& next = s.Next(md_);
if (!next.size()) {
shorter = true;
break;
}
const auto& [x,y] = next[g % next.size()];
s.Place(x, y);
++fitness_;
}
if (shorter) {
genes_.resize(fitness_);
} else {
while (true) {
const unsigned int g = (*rng_)();
const auto& next = s.Next(md_);
if (!next.size()) break;
const auto& [x,y] = next[g % next.size()];
s.Place(x, y);
genes_.push_back(g);
++fitness_;
}
}
s_ = s;
return fitness_;
}
void Crossover(Chromo& other) {
std::uniform_int_distribution<> distrib(0,
std::min(genes_.size(), other.genes_.size()) - 1);
int ix = distrib(*rng_);
auto ti = genes_.begin() + ix;
auto oi = other.genes_.begin() + ix;
for(; ti != genes_.end() && oi != other.genes_.end(); ++ti, ++oi) {
std::swap(*ti, *oi);
}
}
void Mutate() {
std::uniform_int_distribution<> distrib(0, genes_.size() - 1);
int ix = distrib(*rng_);
if (ix < n_) {
std::uniform_int_distribution<> d(0, 100);
genes_[ix] += distrib(*rng_);
} else {
++genes_[ix];
}
}
void NextGen() { fitness_ = 0; }
void Draw() { s_.Draw(false); }
void AddGene(int x) { genes_.push_back(x); } // testing only
void Dump() const { // testing only
std::cout << "{";
for (const auto& g : genes_) std::cout << g << " ";
std::cout << "}\n";
}
private:
std::vector<int> genes_;
int fitness_;
int n_;
RNG* rng_; // not owned
int md_;
State s_; // only computed in Fitness()
};
void TestInitialFitness() {
std::cout << "======= TestInitialFitness ========\n";
RNG gen;
gen.seed(42);
Chromo c(&gen, 3);
std::cout << c.Fitness() << " " << c.Fitness() << "\n";
}
void TestGivenFitness() {
std::cout << "======== TestGivenFitness =========\n";
RNG gen;
gen.seed(42);
Chromo c(&gen, 3);
c.AddGene(200);
std::cout << c.Fitness() << "\n";
}
void TestGivenFitness2() {
std::cout << "======== TestGivenFitness2 ========\n";
RNG gen;
gen.seed(42);
Chromo c(&gen, 3);
for (const auto& g : {200, 200, 3, 3, 0,0,0,0,0,0, 42}) {
c.AddGene(g);
}
std::cout << c.Fitness() << "\n";
c.Dump();
}
void TestCrossover() {
std::cout << "========== TestCrossover ==========\n";
RNG gen;
gen.seed(42);
Chromo c1(&gen, 3);
for (const auto& g : {1,2,3,4,5,6,7}) {
c1.AddGene(g);
}
Chromo c2(&gen, 3);
for (const auto& g : {11,12,13,14,15,16,17,18,19,20}) {
c2.AddGene(g);
}
c1.Dump();
c2.Dump();
c1.Crossover(c2);
c1.Dump();
c2.Dump();
}
void TestMutate() {
std::cout << "=========== TestMutate ============\n";
RNG gen;
gen.seed(42);
Chromo c(&gen, 3);
for (const auto& g : {200, 200, 3, 3, 0,0,0,0,0,0, 42}) {
c.AddGene(g);
}
c.Dump();
c.Mutate();
c.Dump();
}
void TestChromo() {
TestInitialFitness();
TestGivenFitness();
TestGivenFitness2();
TestCrossover();
TestMutate();
}
} // namespace // Chromo
int main() {
#if 0
TestState();
TestChromo();
#else
const int n = 7;
const int pop_size = 100;
const int md = 10;
const float mutation_probability = 0.05;
const int every_iterations = 10000;
struct {
bool operator()(Chromo a, Chromo b) const {
return a.Fitness() > b.Fitness();
}
} FitnessSort;
RNG gen;
std::random_device r;
gen.seed(r());
std::vector<Chromo> population;
for (int i = 0; i < pop_size; i++) {
population.push_back(Chromo(&gen, n, md));
population[i].Fitness();
}
std::sort(population.begin(), population.end(), FitnessSort);
int best_fitness = population[0].Fitness();
int num_iterations = 0;
while (true) {
++num_iterations;
if (num_iterations % every_iterations == 0) {
std::cout << "Iteration " << num_iterations << " best fitness " << best_fitness - n + 2 << "\n";
}
for (int i = 0; i < pop_size; i += 2) {
population[i].Crossover(population[i+1]);
}
for (auto& c : population) {
std::uniform_real_distribution<> u(0, 1);
if (u(gen) < mutation_probability) {
c.Mutate();
}
c.NextGen();
}
// NOTE: why does this need a separate loop?
for (auto& c : population) {
c.Fitness();
}
std::sort(population.begin(), population.end(), FitnessSort);
if (population[0].Fitness() > best_fitness) {
best_fitness = population[0].Fitness();
std::cout << "New best fitness " << best_fitness - n + 2 << " from:\n";
population[0].Draw();
}
}
#endif
return 0;
}
<|endoftext|> |
<commit_before>/* This file is part of VoltDB.
* Copyright (C) 2008-2015 VoltDB Inc.
*
* This file contains original code and/or modifications of original code.
* Any modifications made by VoltDB Inc. are licensed under the following
* terms and conditions:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
/* Copyright (C) 2008 by H-Store Project
* Brown University
* Massachusetts Institute of Technology
* Yale University
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <list>
#include <vector>
#include <utility>
#include "mergereceiveexecutor.h"
#include "common/debuglog.h"
#include "common/common.h"
#include "common/tabletuple.h"
#include "plannodes/receivenode.h"
#include "execution/VoltDBEngine.h"
#include "execution/ProgressMonitorProxy.h"
#include "executors/executorutil.h"
#include "storage/table.h"
#include "storage/tablefactory.h"
#include "storage/tableiterator.h"
#include "storage/tableutil.h"
#include "plannodes/orderbynode.h"
#include "plannodes/limitnode.h"
namespace voltdb {
namespace {
typedef std::vector<TableTuple>::const_iterator tuple_iterator;
typedef std::pair<tuple_iterator, tuple_iterator> tuple_range;
typedef std::list<tuple_range>::iterator range_iterator;
range_iterator min_tuple_range(std::list<tuple_range>& partitions, TupleComparer comp) {
assert(!partitions.empty());
range_iterator smallest_range = partitions.begin();
range_iterator rangeIt = smallest_range;
range_iterator rangeEnd = partitions.end();
++rangeIt;
for (; rangeIt != rangeEnd; ++rangeIt) {
assert(rangeIt->first != rangeIt->second);
if (comp(*rangeIt->first, *smallest_range->first)) {
smallest_range = rangeIt;
}
}
return smallest_range;
}
void merge_sort(const std::vector<TableTuple>& tuples,
std::vector<int64_t>& partitionTupleCounts,
TupleComparer comp,
int limit,
int offset,
TempTable* output_table,
ProgressMonitorProxy pmp) {
if (partitionTupleCounts.empty()) {
return;
}
size_t nonEmptyPartitions = partitionTupleCounts.size();
// Vector to hold pairs of iterators denoting the range of tuples
// for a given partition
std::list<tuple_range> partitions;
tuple_iterator begin = tuples.begin();
for (size_t i = 0; i < nonEmptyPartitions; ++i) {
tuple_iterator end = begin + partitionTupleCounts[i];
partitions.push_back(std::make_pair(begin, end));
begin = end;
assert( i != nonEmptyPartitions -1 || end == tuples.end());
}
int tupleCnt = 0;
int tupleSkipped = 0;
while (true) {
range_iterator rangeIt = partitions.begin();
// remove partitions that are empty
while (rangeIt != partitions.end()) {
if (rangeIt->first == rangeIt->second) {
rangeIt = partitions.erase(rangeIt);
--nonEmptyPartitions;
} else {
++rangeIt;
}
}
if (nonEmptyPartitions == 1) {
// copy the remaining tuples to the output
range_iterator rangeIt = partitions.begin();
while (rangeIt->first != rangeIt->second && (limit == -1 || tupleCnt < limit)) {
TableTuple tuple = *rangeIt->first;
++rangeIt->first;
if (tupleSkipped++ < offset) {
continue;
}
output_table->insertTupleNonVirtual(tuple);
pmp.countdownProgress();
}
return;
}
// Find the range that has the next tuple to be inserted
range_iterator minRangeIt = min_tuple_range(partitions, comp);
// copy the first tuple to the output
TableTuple tuple = *rangeIt->first;
output_table->insertTupleNonVirtual(tuple);
pmp.countdownProgress();
// advance the iterator
++minRangeIt->first;
}
}
}
MergeReceiveExecutor::MergeReceiveExecutor(VoltDBEngine *engine, AbstractPlanNode* abstract_node)
: AbstractExecutor(engine, abstract_node), m_limit_node(NULL), m_tmpInputTable(NULL)
{ }
bool MergeReceiveExecutor::p_init(AbstractPlanNode* abstract_node,
TempTableLimits* limits)
{
VOLT_TRACE("init OrderByMerge Executor");
// Create output table based on output schema from the plan
setTempOutputTable(limits);
// Create a temp table to collect tuples from multiple partitions
m_tmpInputTable = TableFactory::getTempTable(m_abstractNode->databaseId(),
"tempInput",
m_abstractNode->generateTupleSchema(),
m_tmpOutputTable->getColumnNames(),
limits);
// inline OrderByPlanNode
m_orderby_node = dynamic_cast<OrderByPlanNode*>(abstract_node->
getInlinePlanNode(PLAN_NODE_TYPE_ORDERBY));
assert(m_orderby_node != NULL);
// pickup an inlined limit, if one exists
m_limit_node = dynamic_cast<LimitPlanNode*>(m_orderby_node->
getInlinePlanNode(PLAN_NODE_TYPE_LIMIT));
#if defined(VOLT_LOG_LEVEL)
#if VOLT_LOG_LEVEL<=VOLT_LEVEL_TRACE
const std::vector<AbstractExpression*>& sortExprs = m_orderby_node->getSortExpressions();
for (int i = 0; i < sortExprs.size(); ++i) {
VOLT_TRACE("Sort key[%d]:\n%s", i, sortExprs[i]->debug(true).c_str());
}
#endif
#endif
return true;
}
bool MergeReceiveExecutor::p_execute(const NValueArray ¶ms) {
int loadedDeps = 0;
// iterate over dependencies and merge them into the temp table.
// The assumption is that the dependencies results are are sorted.
int64_t previousTupleCount = 0;
std::vector<int64_t> partitionTupleCounts;
//
// OPTIMIZATION: NESTED LIMIT
int limit = -1;
int offset = 0;
if (m_limit_node != NULL) {
m_limit_node->getLimitAndOffsetByReference(params, limit, offset);
}
do {
loadedDeps = m_engine->loadNextDependency(m_tmpInputTable);
int currentTupleCount = m_tmpInputTable->activeTupleCount();
if (currentTupleCount != previousTupleCount) {
partitionTupleCounts.push_back(currentTupleCount - previousTupleCount);
previousTupleCount = currentTupleCount;
}
} while (loadedDeps > 0);
// Unload tuples into a vector to be merge-sorted
VOLT_TRACE("Running MergeReceive '%s'", m_abstractNode->debug().c_str());
VOLT_TRACE("Input Table PreSort:\n '%s'", m_tmpInputTable->debug().c_str());
TableIterator iterator = m_tmpInputTable->iterator();
TableTuple tuple(m_tmpInputTable->schema());
std::vector<TableTuple> xs;
xs.reserve(m_tmpInputTable->activeTupleCount());
ProgressMonitorProxy pmp(m_engine, this);
while (iterator.next(tuple))
{
pmp.countdownProgress();
assert(tuple.isActive());
xs.push_back(tuple);
}
// Merge Sort
TupleComparer comp(m_orderby_node->getSortExpressions(), m_orderby_node->getSortDirections());
merge_sort(xs, partitionTupleCounts, comp, limit, offset, m_tmpOutputTable, pmp);
VOLT_TRACE("Result of MergeReceive:\n '%s'", m_tmpOutputTable->debug().c_str());
return true;
}
}
<commit_msg>work in progress<commit_after>/* This file is part of VoltDB.
* Copyright (C) 2008-2015 VoltDB Inc.
*
* This file contains original code and/or modifications of original code.
* Any modifications made by VoltDB Inc. are licensed under the following
* terms and conditions:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
/* Copyright (C) 2008 by H-Store Project
* Brown University
* Massachusetts Institute of Technology
* Yale University
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <list>
#include <vector>
#include <utility>
#include "mergereceiveexecutor.h"
#include "common/debuglog.h"
#include "common/common.h"
#include "common/tabletuple.h"
#include "plannodes/receivenode.h"
#include "execution/VoltDBEngine.h"
#include "execution/ProgressMonitorProxy.h"
#include "executors/executorutil.h"
#include "storage/table.h"
#include "storage/tablefactory.h"
#include "storage/tableiterator.h"
#include "storage/tableutil.h"
#include "plannodes/orderbynode.h"
#include "plannodes/limitnode.h"
namespace voltdb {
namespace {
typedef std::vector<TableTuple>::const_iterator tuple_iterator;
typedef std::pair<tuple_iterator, tuple_iterator> tuple_range;
typedef std::list<tuple_range>::iterator range_iterator;
range_iterator min_tuple_range(std::list<tuple_range>& partitions, TupleComparer comp) {
assert(!partitions.empty());
range_iterator smallest_range = partitions.begin();
range_iterator rangeIt = smallest_range;
range_iterator rangeEnd = partitions.end();
++rangeIt;
for (; rangeIt != rangeEnd; ++rangeIt) {
assert(rangeIt->first != rangeIt->second);
if (comp(*rangeIt->first, *smallest_range->first)) {
smallest_range = rangeIt;
}
}
return smallest_range;
}
void merge_sort(const std::vector<TableTuple>& tuples,
std::vector<int64_t>& partitionTupleCounts,
TupleComparer comp,
int limit,
int offset,
TempTable* output_table,
ProgressMonitorProxy pmp) {
if (partitionTupleCounts.empty()) {
return;
}
size_t nonEmptyPartitions = partitionTupleCounts.size();
// Vector to hold pairs of iterators denoting the range of tuples
// for a given partition
std::list<tuple_range> partitions;
tuple_iterator begin = tuples.begin();
for (size_t i = 0; i < nonEmptyPartitions; ++i) {
tuple_iterator end = begin + partitionTupleCounts[i];
partitions.push_back(std::make_pair(begin, end));
begin = end;
assert( i != nonEmptyPartitions -1 || end == tuples.end());
}
int tupleCnt = 0;
int tupleSkipped = 0;
while (true) {
range_iterator rangeIt = partitions.begin();
// remove partitions that are empty
while (rangeIt != partitions.end()) {
if (rangeIt->first == rangeIt->second) {
rangeIt = partitions.erase(rangeIt);
--nonEmptyPartitions;
} else {
++rangeIt;
}
}
if (nonEmptyPartitions == 1) {
// copy the remaining tuples to the output
range_iterator rangeIt = partitions.begin();
while (rangeIt->first != rangeIt->second && (limit == -1 || tupleCnt < limit)) {
TableTuple tuple = *rangeIt->first;
++rangeIt->first;
if (tupleSkipped++ < offset) {
continue;
}
output_table->insertTupleNonVirtual(tuple);
pmp.countdownProgress();
}
return;
}
// Find the range that has the next tuple to be inserted
range_iterator minRangeIt = min_tuple_range(partitions, comp);
// copy the first tuple to the output
TableTuple tuple = *rangeIt->first;
output_table->insertTupleNonVirtual(tuple);
pmp.countdownProgress();
// advance the iterator
++minRangeIt->first;
}
}
}
MergeReceiveExecutor::MergeReceiveExecutor(VoltDBEngine *engine, AbstractPlanNode* abstract_node)
: AbstractExecutor(engine, abstract_node), m_limit_node(NULL), m_tmpInputTable(NULL)
{ }
bool MergeReceiveExecutor::p_init(AbstractPlanNode* abstract_node,
TempTableLimits* limits)
{
VOLT_TRACE("init OrderByMerge Executor");
// Create output table based on output schema from the plan
setTempOutputTable(limits);
// Create a temp table to collect tuples from multiple partitions
m_tmpInputTable = TableFactory::getTempTable(m_abstractNode->databaseId(),
"tempInput",
m_abstractNode->generateTupleSchema(),
m_tmpOutputTable->getColumnNames(),
limits);
// inline OrderByPlanNode
m_orderby_node = dynamic_cast<OrderByPlanNode*>(abstract_node->
getInlinePlanNode(PLAN_NODE_TYPE_ORDERBY));
assert(m_orderby_node != NULL);
// pickup an inlined limit, if one exists
m_limit_node = dynamic_cast<LimitPlanNode*>(m_orderby_node->
getInlinePlanNode(PLAN_NODE_TYPE_LIMIT));
#if defined(VOLT_LOG_LEVEL)
#if VOLT_LOG_LEVEL<=VOLT_LEVEL_TRACE
const std::vector<AbstractExpression*>& sortExprs = m_orderby_node->getSortExpressions();
for (int i = 0; i < sortExprs.size(); ++i) {
VOLT_TRACE("Sort key[%d]:\n%s", i, sortExprs[i]->debug(true).c_str());
}
#endif
#endif
return true;
}
bool MergeReceiveExecutor::p_execute(const NValueArray ¶ms) {
int loadedDeps = 0;
// iterate over dependencies and merge them into the temp table.
// The assumption is that the dependencies results are are sorted.
int64_t previousTupleCount = 0;
std::vector<int64_t> partitionTupleCounts;
//
// OPTIMIZATION: NESTED LIMIT
int limit = -1;
int offset = 0;
if (m_limit_node != NULL) {
m_limit_node->getLimitAndOffsetByReference(params, limit, offset);
}
do {
loadedDeps = m_engine->loadNextDependency(m_tmpInputTable);
int currentTupleCount = m_tmpInputTable->activeTupleCount();
if (currentTupleCount != previousTupleCount) {
partitionTupleCounts.push_back(currentTupleCount - previousTupleCount);
previousTupleCount = currentTupleCount;
}
} while (loadedDeps > 0);
// Unload tuples into a vector to be merge-sorted
VOLT_TRACE("Running MergeReceive '%s'", m_abstractNode->debug().c_str());
VOLT_TRACE("Input Table PreSort:\n '%s'", m_tmpInputTable->debug().c_str());
TableIterator iterator = m_tmpInputTable->iterator();
TableTuple tuple(m_tmpInputTable->schema());
std::vector<TableTuple> xs;
xs.reserve(m_tmpInputTable->activeTupleCount());
ProgressMonitorProxy pmp(m_engine, this);
while (iterator.next(tuple))
{
pmp.countdownProgress();
assert(tuple.isActive());
xs.push_back(tuple);
}
// Merge Sort
TupleComparer comp(m_orderby_node->getSortExpressions(), m_orderby_node->getSortDirections());
merge_sort(xs, partitionTupleCounts, comp, limit, offset, m_tmpOutputTable, pmp);
VOLT_TRACE("Result of MergeReceive:\n '%s'", m_tmpOutputTable->debug().c_str());
cleanupInputTempTable(m_tmpInputTable);
return true;
}
}
<|endoftext|> |
<commit_before>#include "ee/jsb/core/jsb_core_common.hpp"
#include "Cocos2dxStore.h"
#include "ee/jsb/core/jsb_templates.hpp"
#include "jsb_cc_soomla_store.hpp"
namespace ee {
namespace core {
template <>
soomla::CCStoreAssets* get_value(const se::Value& value) {
return static_cast<soomla::CCStoreAssets*>(
value.toObject()->getPrivateData());
}
template <>
void set_value(se::Value& value, soomla::CCSoomlaStore* input) {
set_value_from_pointer(value, input);
}
} // namespace core
} // namespace ee
namespace soomla {
static se::Object* __jsb_CCSoomlaStore_proto = nullptr;
static se::Class* __jsb_CCSoomlaStore_class = nullptr;
const static auto jsb_CCSoomlaStore_initialize =
&ee::core::jsb_static_call<&CCSoomlaStore::initialize, CCStoreAssets*,
cocos2d::ValueMap>;
const static auto jsb_CCSoomlaStore_getInstance =
&ee::core::jsb_static_get<CCSoomlaStore*, &CCSoomlaStore::getInstance>;
const auto jsb_CCSoomlaStore_refreshMarketItemsDetails =
&ee::core::jsb_method_call<
CCSoomlaStore, &CCSoomlaStore::refreshMarketItemsDetails, CCError**>;
SE_BIND_FUNC(jsb_CCSoomlaStore_initialize)
SE_BIND_FUNC(jsb_CCSoomlaStore_getInstance)
SE_BIND_FUNC(jsb_CCSoomlaStore_refreshMarketItemsDetails)
bool register_cc_soomla_store_manual(se::Object* globalObj) {
se::Object* soomlaObj = nullptr;
ee::core::getOrCreatePlainObject_r("soomla", globalObj, &soomlaObj);
auto cls = se::Class::create("CCSoomlaStore", soomlaObj, nullptr, nullptr);
cls->defineFunction("refreshMarketItemsDetails",
_SE(jsb_CCSoomlaStore_refreshMarketItemsDetails));
cls->install();
JSBClassType::registerClass<soomla::CCSoomlaStore>(cls);
__jsb_CCSoomlaStore_proto = cls->getProto();
__jsb_CCSoomlaStore_class = cls;
// Register static member variables and static member functions
se::Value ctorVal;
if (soomlaObj->getProperty("CCSoomlaStore", &ctorVal) &&
ctorVal.isObject()) {
ctorVal.toObject()->defineFunction("initialize",
_SE(jsb_CCSoomlaStore_initialize));
ctorVal.toObject()->defineFunction("getInstance",
_SE(jsb_CCSoomlaStore_getInstance));
}
se::ScriptEngine::getInstance()->clearException();
return true;
}
} // namespace soomla
<commit_msg>Update jsb soomla store.<commit_after>#include "ee/jsb/core/jsb_core_common.hpp"
#include "Cocos2dxStore.h"
#include "ee/jsb/core/jsb_templates.hpp"
#include "jsb_cc_soomla_store.hpp"
namespace ee {
namespace core {
template <>
soomla::CCStoreAssets* get_value(const se::Value& value) {
return static_cast<soomla::CCStoreAssets*>(
value.toObject()->getPrivateData());
}
template <>
void set_value(se::Value& value, soomla::CCSoomlaStore* input) {
set_value_from_pointer(value, input);
}
} // namespace core
} // namespace ee
namespace soomla {
static se::Object* __jsb_CCSoomlaStore_proto = nullptr;
static se::Class* __jsb_CCSoomlaStore_class = nullptr;
const static auto jsb_CCSoomlaStore_initialize =
&ee::core::jsb_static_call<&CCSoomlaStore::initialize, CCStoreAssets*,
cocos2d::ValueMap>;
const static auto jsb_CCSoomlaStore_getInstance =
&ee::core::jsb_static_get<CCSoomlaStore*, &CCSoomlaStore::getInstance>;
const auto jsb_CCSoomlaStore_refreshMarketItemsDetails =
&ee::core::jsb_method_call<
CCSoomlaStore, &CCSoomlaStore::refreshMarketItemsDetails, CCError**>;
const auto jsb_CCSoomlaStore_restoreTransactions =
&ee::core::jsb_method_call<CCSoomlaStore,
&CCSoomlaStore::restoreTransactions>;
SE_BIND_FUNC(jsb_CCSoomlaStore_initialize)
SE_BIND_FUNC(jsb_CCSoomlaStore_getInstance)
SE_BIND_FUNC(jsb_CCSoomlaStore_refreshMarketItemsDetails)
SE_BIND_FUNC(jsb_CCSoomlaStore_restoreTransactions)
bool register_cc_soomla_store_manual(se::Object* globalObj) {
se::Object* soomlaObj = nullptr;
ee::core::getOrCreatePlainObject_r("soomla", globalObj, &soomlaObj);
auto cls = se::Class::create("CCSoomlaStore", soomlaObj, nullptr, nullptr);
cls->defineFunction("refreshMarketItemsDetails",
_SE(jsb_CCSoomlaStore_refreshMarketItemsDetails));
cls->defineFunction("restoreTransactions",
_SE(jsb_CCSoomlaStore_restoreTransactions));
cls->install();
JSBClassType::registerClass<soomla::CCSoomlaStore>(cls);
__jsb_CCSoomlaStore_proto = cls->getProto();
__jsb_CCSoomlaStore_class = cls;
// Register static member variables and static member functions
se::Value ctorVal;
if (soomlaObj->getProperty("CCSoomlaStore", &ctorVal) &&
ctorVal.isObject()) {
ctorVal.toObject()->defineFunction("initialize",
_SE(jsb_CCSoomlaStore_initialize));
ctorVal.toObject()->defineFunction("getInstance",
_SE(jsb_CCSoomlaStore_getInstance));
}
se::ScriptEngine::getInstance()->clearException();
return true;
}
} // namespace soomla
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/extensions/theme_preview_infobar_delegate.h"
#include "app/l10n_util.h"
#include "base/string_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "grit/generated_resources.h"
ThemePreviewInfobarDelegate::ThemePreviewInfobarDelegate(
TabContents* tab_contents, const std::string& name)
: ConfirmInfoBarDelegate(tab_contents),
profile_(tab_contents->profile()), name_(name),
selection_made_(false) {
}
void ThemePreviewInfobarDelegate::InfoBarClosed() {
if (!selection_made_)
profile_->ClearTheme();
delete this;
}
std::wstring ThemePreviewInfobarDelegate::GetMessageText() const {
return l10n_util::GetStringF(IDS_THEME_PREVIEW_INFOBAR_LABEL,
UTF8ToWide(name_));
}
SkBitmap* ThemePreviewInfobarDelegate::GetIcon() const {
// TODO(aa): Reply with the theme's icon, but this requires reading it
// asynchronously from disk.
return NULL;
}
int ThemePreviewInfobarDelegate::GetButtons() const {
return BUTTON_OK | BUTTON_CANCEL;
}
std::wstring ThemePreviewInfobarDelegate::GetButtonLabel(
ConfirmInfoBarDelegate::InfoBarButton button) const {
switch (button) {
case BUTTON_OK:
return l10n_util::GetString(IDS_THEME_PREVIEW_INFOBAR_OK_BUTTON);
case BUTTON_CANCEL:
return l10n_util::GetString(IDS_THEME_PREVIEW_INFOBAR_CANCEL_BUTTON);
default:
NOTREACHED();
return L"";
}
}
bool ThemePreviewInfobarDelegate::Accept() {
selection_made_ = true;
return true;
}
bool ThemePreviewInfobarDelegate::Cancel() {
selection_made_ = true;
// Blech, this is a total hack.
//
// a) We should be uninstalling via ExtensionsService, not
// Profile::ClearTheme().
// b) We should be able to view the theme without installing it. This would
// help in edge cases like the user closing the window or tab before making
// a decision.
profile_->ClearTheme();
return true;
}
<commit_msg>Fix broken tree.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/theme_preview_infobar_delegate.h"
#include "app/l10n_util.h"
#include "base/string_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "grit/generated_resources.h"
ThemePreviewInfobarDelegate::ThemePreviewInfobarDelegate(
TabContents* tab_contents, const std::string& name)
: ConfirmInfoBarDelegate(tab_contents),
profile_(tab_contents->profile()), name_(name),
selection_made_(false) {
}
void ThemePreviewInfobarDelegate::InfoBarClosed() {
if (!selection_made_)
profile_->ClearTheme();
delete this;
}
std::wstring ThemePreviewInfobarDelegate::GetMessageText() const {
return l10n_util::GetStringF(IDS_THEME_PREVIEW_INFOBAR_LABEL,
UTF8ToWide(name_));
}
SkBitmap* ThemePreviewInfobarDelegate::GetIcon() const {
// TODO(aa): Reply with the theme's icon, but this requires reading it
// asynchronously from disk.
return NULL;
}
int ThemePreviewInfobarDelegate::GetButtons() const {
return BUTTON_OK | BUTTON_CANCEL;
}
std::wstring ThemePreviewInfobarDelegate::GetButtonLabel(
ConfirmInfoBarDelegate::InfoBarButton button) const {
switch (button) {
case BUTTON_OK:
return l10n_util::GetString(IDS_THEME_PREVIEW_INFOBAR_OK_BUTTON);
case BUTTON_CANCEL:
return l10n_util::GetString(IDS_THEME_PREVIEW_INFOBAR_CANCEL_BUTTON);
default:
NOTREACHED();
return L"";
}
}
bool ThemePreviewInfobarDelegate::Accept() {
selection_made_ = true;
return true;
}
bool ThemePreviewInfobarDelegate::Cancel() {
selection_made_ = true;
// Blech, this is a total hack.
//
// a) We should be uninstalling via ExtensionsService, not
// Profile::ClearTheme().
// b) We should be able to view the theme without installing it. This would
// help in edge cases like the user closing the window or tab before making
// a decision.
profile_->ClearTheme();
return true;
}
<|endoftext|> |
<commit_before>/***************************************************************************
[email protected] - last modified on //2019
//
//Lauches SigmaStar analysis with rsn mini package
//Allows basic configuration of pile-up check and event cuts
//
****************************************************************************/
AliRsnMiniAnalysisTask * AddTaskSigPM
(
TString outNameSuffix = "SigPM", //suffix for output container
Bool_t isMC = kFALSE, //MC flag
AliPIDResponse::EBeamType collSys = AliPIDResponse::kPBPB, //=0, kPPB=1, kPBPB=2 outNameSuffix
UInt_t triggerMask = AliVEvent::kCentral, //trigger selection
Bool_t enaMultSel = kTRUE, //enable multiplicity axis
Float_t nsigma = 3.0, //PID cut
Float_t masslow = 1.2, //inv mass range lower boundary
Float_t massup = 3.2, //inv mass range upper boundary
Int_t nbins = 2000, //inv mass: N bins
Bool_t enableMonitor = kTRUE, //enable single track QA
Float_t pi_Ls_PIDCut=4., //nsigma V0 daughters
Float_t LsDCA = 0.3, //V0 vtx to PV
Float_t LsCosPoinAn = 0.98, // cos of Pointing Angle
Float_t LsDaughDCA=0.8, // dca V0 daughters
Float_t massTol = 0.006, // mass tolerance 6 MeV
Float_t massTolVeto = 0.0043, // mass tol veto
Bool_t Switch = kFALSE, // switch
Float_t pLife = 25, // life
Float_t v0rapidity= 0.5, // V0 rapidity
Float_t radiuslow=5., // radius low
Bool_t doCustomDCAcuts=kTRUE, //custom dca cuts for V0 daughters
Double_t dcaProton=0.1, // proton dca
Double_t dcaPion=0.1, //pion dca
Double_t minAsym = 0.3, //pair lower abs(asym)
Double_t maxAsym=0.95) //pair maximum abs(asym)
{
//-------------------------------------------
// event cuts
//-------------------------------------------
/*Trigger selection
Std minimum bias trigger AliVEvent::kMB, corresponding to (V0A | V0C | SPD) to be used with
- pp 7 TeV (2010 data)
- PbPb 2.76 TeV (2010 data and 2011 data)
- pp 2.76 TeV (2011 data)
Centrality triggers AliVEvent::kCentral, AliVEvent::kSemicentral to be used with
- PbPb 2.76 TeV (2011 data)
Std minimum bias trigger AliVEvent::kINT7, corrsesponding to (V0A & V0C) to be used with
- pA 5.02 TeV (2013 data)
- pp 13 TeV (2015 data)
*/
Double_t vtxZcut = 10.0; //cm, default cut on vtx z
Bool_t rejectPileUp = kTRUE; //rejects pileup from SPD
Bool_t useMVPileUpSelection = kFALSE; //alternative pile-up rejection, default is SPD
Int_t MinPlpContribSPD = 5; //default value if used
Int_t MinPlpContribMV = 5; //default value if used
// // Bool_t selectDPMJETevtNSDpA = kFALSE; //cut to select true NSD events in DPMJET
//-------------------------------------------
//pair rapidity cut
//-------------------------------------------
Double_t minYlab = -0.5;
Double_t maxYlab = 0.5;
// if (pairCutSetID==pairYCutSet::kCentralTight) { //|y_cm|<0.3
// minYlab = -0.3; maxYlab = 0.3;
// }
// if (pairCutSetID==pairYCutSet::kpADefault) { //-0.5<y_cm<0.0
// minYlab = -0.465; maxYlab = 0.035;
// }
// if (pairCutSetID==pairYCutSet::kpACentral) { //|y_cm|<0.3
// minYlab = -0.765; maxYlab = -0.165;
// }
//-------------------------------------------
//mixing settings
//-------------------------------------------
Int_t nmix = 10;
Float_t maxDiffVzMix = 1.0;
Float_t maxDiffMultMix = 5.0;
//
// -- INITIALIZATION ----------------------------------------------------------------------------
//
// retrieve analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskSigPM", "No analysis manager to connect to.");
return NULL;
}
// create the task and configure
TString taskName = Form("RsnTaskSigPM");
AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);
//trigger
if (!isMC) task->UseESDTriggerMask(triggerMask); //ESD
if(isMC) task->UseESDTriggerMask(AliVEvent::kAnyINT);
// task->SelectCollisionCandidates(triggerMask); //AOD
//-----------------------------------------------------------------------------------------------
// -- MULTIPLICITY/CENTRALITY -------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
if (collSys==AliPIDResponse::kPP) task->UseMultiplicity("AliMultSelection_V0M");
if (collSys==AliPIDResponse::kPPB) task->UseCentrality("AliMultSelection_V0A");
if (collSys==AliPIDResponse::kPBPB) task->UseMultiplicity("AliMultSelection_V0M"); //task->UseCentrality("AliMultSelection_V0M");
//-----------------------------------------------------------------------------------------------
// -- EVENT MIXING CONFIG -----------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
task->UseContinuousMix();
task->SetNMix(nmix);
task->SetMaxDiffVz(maxDiffVzMix);
task->SetMaxDiffMult(maxDiffMultMix);
::Info("AddTaskSstar", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f", nmix, maxDiffVzMix, maxDiffMultMix));
//-----------------------------------------------------------------------------------------------
// -- EVENT SELECTION ---------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
AliRsnEventCuts * rsnEventCuts = new AliRsnEventCuts("rsnEventCuts");
rsnEventCuts->ForceSetupPbPb2018();
rsnEventCuts->SetUseMultSelectionEvtSel();
eventCuts->AddCut(rsnEventCuts);
eventCuts->SetCutScheme(Form("%s", rsnEventCuts->GetName()));
task->SetEventCuts(eventCuts);
//connect task
mgr->AddTask(task);
//-----------------------------------------------------------------------------------------------
// -- EVENT SELECTION MONITOR -------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//vertex position monitoring
Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
outVtx->AddAxis(vtxID, 500, -50.0, 50.0);
//multiplicity or centrality monitoring -- if enabled
if (enaMultSel){
//multiplicity or centrality with forward estimator from AliMulSelectionTask
Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
//reference multiplicity (default with global tracks with good quality, if not available uses tracklets)
Int_t multRefID = task->CreateValue(AliRsnMiniValue::kRefMult, kFALSE);
AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
outMult->AddAxis(multID, 100, 0.0, 100.0);
AliRsnMiniOutput *outRefMult = task->CreateOutput("eventRefMult", "HIST", "EVENT");
outRefMult->AddAxis(multRefID, 400, 0.0, 400.0);
TH2F* hvz = new TH2F("hVzVsCent",Form("Vertex position vs centrality"), 101, 0., 101., 500, -50.0, 50.0);
if (collSys==AliPIDResponse::kPPB)
hvz->GetXaxis()->SetTitle("V0A");
else
hvz->GetXaxis()->SetTitle("V0M");
hvz->GetYaxis()->SetTitle("z_{vtx} (cm)");
task->SetEventQAHist("vz", hvz);
TH2F* hRefMultiVsCent = new TH2F("hRefMultiVsCent",Form("Reference multiplicity vs centrality"), 101, 0., 101., 400, 0., 400.);
if (collSys==AliPIDResponse::kPPB)
hRefMultiVsCent->GetXaxis()->SetTitle("V0A");
else
hRefMultiVsCent->GetXaxis()->SetTitle("V0M");
hRefMultiVsCent->GetYaxis()->SetTitle("GLOBAL");
task->SetEventQAHist("refmulti",hRefMultiVsCent);
TH2F* hMultiVsCent = new TH2F("hMultiVsCent",Form("Multiplicity vs centrality"), 101, 0., 101., 400, 0., 400.);
if (collSys==AliPIDResponse::kPPB)
hMultiVsCent->GetXaxis()->SetTitle("V0A");
else
hMultiVsCent->GetXaxis()->SetTitle("V0M");
hMultiVsCent->GetYaxis()->SetTitle("QUALITY");
task->SetEventQAHist("multicent",hMultiVsCent);
}
//-----------------------------------------------------------------------------------------------
// -- PAIR CUTS (common to all resonances) ------------------------------------------------------
//-----------------------------------------------------------------------------------------------
AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
cutY->SetRangeD(minYlab, maxYlab);
AliRsnCutMiniPair *cutAsym = new AliRsnCutMiniPair("cutAsymmetry", AliRsnCutMiniPair::kAsymRange);
cutAsym->SetRangeD(minAsym, maxAsym);
//AliRsnCutMiniPair* cutV0=new AliRsnCutMiniPair("cutV0", AliRsnCutMiniPair::kContainsV0Daughter);
AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
cutsPair->AddCut(cutY);
cutsPair->AddCut(cutAsym);
cutsPair->SetCutScheme(Form("%s & %s ",cutY->GetName(), cutAsym->GetName()));
AliRsnCutSet *cutsPairY = new AliRsnCutSet("pairCutsY", AliRsnTarget::kMother);
cutsPairY->AddCut(cutY);
cutsPairY->SetCutScheme(cutY->GetName());
//-----------------------------------------------------------------------------------------------
// -- CONFIG ANALYSIS --------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigSigPM.C");
// gROOT->LoadMacro("ConfigSigPM.C");
if (!ConfigSigPM(task, isMC, collSys, cutsPair, cutsPairY, enaMultSel, masslow, massup, nbins, nsigma,
enableMonitor, pi_Ls_PIDCut, LsDCA, LsCosPoinAn, LsDaughDCA, massTol, massTolVeto, Switch, pLife, v0rapidity, radiuslow, doCustomDCAcuts, dcaProton, dcaPion))
return 0x0;
//-----------------------------------------------------------------------------------------------
// -- CONTAINERS --------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
TString outputFileName = AliAnalysisManager::GetCommonFileName();
Printf("AddTaskSstar - Set OutputFileName : \n %s\n", outputFileName.Data() );
AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, output);
return task;
}
<commit_msg>small change in the cuts affecting the triggers<commit_after>/***************************************************************************
[email protected] - last modified on //2019
//
//Lauches SigmaStar analysis with rsn mini package
//Allows basic configuration of pile-up check and event cuts
//
****************************************************************************/
AliRsnMiniAnalysisTask * AddTaskSigPM
(
TString outNameSuffix = "SigPM", //suffix for output container
Bool_t isMC = kFALSE, //MC flag
AliPIDResponse::EBeamType collSys = AliPIDResponse::kPBPB, //=0, kPPB=1, kPBPB=2 outNameSuffix
Int_t triggerMask = 0, //trigger selection
Bool_t enaMultSel = kTRUE, //enable multiplicity axis
Float_t nsigma = 3.0, //PID cut
Float_t masslow = 1.2, //inv mass range lower boundary
Float_t massup = 3.2, //inv mass range upper boundary
Int_t nbins = 2000, //inv mass: N bins
Bool_t enableMonitor = kTRUE, //enable single track QA
Float_t pi_Ls_PIDCut=4., //nsigma V0 daughters
Float_t LsDCA = 0.3, //V0 vtx to PV
Float_t LsCosPoinAn = 0.98, // cos of Pointing Angle
Float_t LsDaughDCA=0.8, // dca V0 daughters
Float_t massTol = 0.006, // mass tolerance 6 MeV
Float_t massTolVeto = 0.0043, // mass tol veto
Bool_t Switch = kFALSE, // switch
Float_t pLife = 25, // life
Float_t v0rapidity= 0.5, // V0 rapidity
Float_t radiuslow=5., // radius low
Bool_t doCustomDCAcuts=kTRUE, //custom dca cuts for V0 daughters
Double_t dcaProton=0.1, // proton dca
Double_t dcaPion=0.1, //pion dca
Double_t minAsym = 0.3, //pair lower abs(asym)
Double_t maxAsym=0.95) //pair maximum abs(asym)
{
//-------------------------------------------
// event cuts
//-------------------------------------------
Double_t vtxZcut = 10.0; //cm, default cut on vtx z
Bool_t rejectPileUp = kTRUE; //rejects pileup from SPD
Bool_t useMVPileUpSelection = kFALSE; //alternative pile-up rejection, default is SPD
Int_t MinPlpContribSPD = 5; //default value if used
Int_t MinPlpContribMV = 5; //default value if used
//-------------------------------------------
//pair rapidity cut
//-------------------------------------------
Double_t minYlab = -0.5;
Double_t maxYlab = 0.5;
//-------------------------------------------
//mixing settings
//-------------------------------------------
Int_t nmix = 10;
Float_t maxDiffVzMix = 1.0;
Float_t maxDiffMultMix = 5.0;
//
// -- INITIALIZATION ----------------------------------------------------------------------------
//
// retrieve analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskSigPM", "No analysis manager to connect to.");
return NULL;
}
// create the task and configure
TString taskName = Form("RsnTaskSigPM");
AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);
//-----------------------------------------------------------------------------------------------
// -- MULTIPLICITY/CENTRALITY -------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
if (collSys==AliPIDResponse::kPP) task->UseMultiplicity("AliMultSelection_V0M");
if (collSys==AliPIDResponse::kPPB) task->UseCentrality("AliMultSelection_V0A");
if (collSys==AliPIDResponse::kPBPB) task->UseMultiplicity("AliMultSelection_V0M"); //task->UseCentrality("AliMultSelection_V0M");
//trigger
if (!isMC) {
if (triggerMask==0) task->UseESDTriggerMask(AliVEvent::kCentral); //ESD
if (triggerMask==1) task->UseESDTriggerMask(AliVEvent::kSemiCentral);
if (triggerMask==3) task->UseESDTriggerMask(AliVEvent::kINT7);
if (triggerMask==4) task->UseESDTriggerMask(AliVEvent::kSemiCentral|AliVEvent::kCentral|AliVEvent::kINT7);
}
if(isMC) task->UseESDTriggerMask(AliVEvent::kAnyINT);
// task->SelectCollisionCandidates(triggerMask); //AOD
//-----------------------------------------------------------------------------------------------
// -- EVENT MIXING CONFIG -----------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
task->UseContinuousMix();
task->SetNMix(nmix);
task->SetMaxDiffVz(maxDiffVzMix);
task->SetMaxDiffMult(maxDiffMultMix);
::Info("AddTaskSstar", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f", nmix, maxDiffVzMix, maxDiffMultMix));
//-----------------------------------------------------------------------------------------------
// -- EVENT SELECTION ---------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
AliRsnEventCuts * rsnEventCuts = new AliRsnEventCuts("rsnEventCuts");
rsnEventCuts->ForceSetupPbPb2018();
// rsnEventCuts->SetUseMultSelectionEvtSel();
AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
eventCuts->AddCut(rsnEventCuts);
eventCuts->SetCutScheme(Form("%s", rsnEventCuts->GetName()));
task->SetEventCuts(eventCuts);
//connect task
mgr->AddTask(task);
//-----------------------------------------------------------------------------------------------
// -- EVENT SELECTION MONITOR -------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//vertex position monitoring
Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
outVtx->AddAxis(vtxID, 500, -50.0, 50.0);
//multiplicity or centrality monitoring -- if enabled
if (enaMultSel){
//multiplicity or centrality with forward estimator from AliMulSelectionTask
Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
//reference multiplicity (default with global tracks with good quality, if not available uses tracklets)
Int_t multRefID = task->CreateValue(AliRsnMiniValue::kRefMult, kFALSE);
AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
outMult->AddAxis(multID, 100, 0.0, 100.0);
AliRsnMiniOutput *outRefMult = task->CreateOutput("eventRefMult", "HIST", "EVENT");
outRefMult->AddAxis(multRefID, 400, 0.0, 400.0);
TH2F* hvz = new TH2F("hVzVsCent",Form("Vertex position vs centrality"), 101, 0., 101., 500, -50.0, 50.0);
if (collSys==AliPIDResponse::kPPB)
hvz->GetXaxis()->SetTitle("V0A");
else
hvz->GetXaxis()->SetTitle("V0M");
hvz->GetYaxis()->SetTitle("z_{vtx} (cm)");
task->SetEventQAHist("vz", hvz);
TH2F* hRefMultiVsCent = new TH2F("hRefMultiVsCent",Form("Reference multiplicity vs centrality"), 101, 0., 101., 400, 0., 400.);
if (collSys==AliPIDResponse::kPPB)
hRefMultiVsCent->GetXaxis()->SetTitle("V0A");
else
hRefMultiVsCent->GetXaxis()->SetTitle("V0M");
hRefMultiVsCent->GetYaxis()->SetTitle("GLOBAL");
task->SetEventQAHist("refmulti",hRefMultiVsCent);
TH2F* hMultiVsCent = new TH2F("hMultiVsCent",Form("Multiplicity vs centrality"), 101, 0., 101., 400, 0., 400.);
if (collSys==AliPIDResponse::kPPB)
hMultiVsCent->GetXaxis()->SetTitle("V0A");
else
hMultiVsCent->GetXaxis()->SetTitle("V0M");
hMultiVsCent->GetYaxis()->SetTitle("QUALITY");
task->SetEventQAHist("multicent",hMultiVsCent);
}
//-----------------------------------------------------------------------------------------------
// -- PAIR CUTS (common to all resonances) ------------------------------------------------------
//-----------------------------------------------------------------------------------------------
AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
cutY->SetRangeD(minYlab, maxYlab);
AliRsnCutMiniPair *cutAsym = new AliRsnCutMiniPair("cutAsymmetry", AliRsnCutMiniPair::kAsymRange);
cutAsym->SetRangeD(minAsym, maxAsym);
//AliRsnCutMiniPair* cutV0=new AliRsnCutMiniPair("cutV0", AliRsnCutMiniPair::kContainsV0Daughter);
AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
cutsPair->AddCut(cutY);
cutsPair->AddCut(cutAsym);
cutsPair->SetCutScheme(Form("%s & %s ",cutY->GetName(), cutAsym->GetName()));
AliRsnCutSet *cutsPairY = new AliRsnCutSet("pairCutsY", AliRsnTarget::kMother);
cutsPairY->AddCut(cutY);
cutsPairY->SetCutScheme(cutY->GetName());
//-----------------------------------------------------------------------------------------------
// -- CONFIG ANALYSIS --------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigSigPM.C");
// gROOT->LoadMacro("ConfigSigPM.C");
if (!ConfigSigPM(task, isMC, collSys, cutsPair, cutsPairY, enaMultSel, masslow, massup, nbins, nsigma,
enableMonitor, pi_Ls_PIDCut, LsDCA, LsCosPoinAn, LsDaughDCA, massTol, massTolVeto, Switch, pLife, v0rapidity, radiuslow, doCustomDCAcuts, dcaProton, dcaPion))
return 0x0;
//-----------------------------------------------------------------------------------------------
// -- CONTAINERS --------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
TString outputFileName = AliAnalysisManager::GetCommonFileName();
Printf("AddTaskSstar - Set OutputFileName : \n %s\n", outputFileName.Data() );
AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, output);
return task;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/standard_layout.h"
#include "views/view.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"
#if defined(OS_WIN)
#include "app/win_util.h"
#endif
class Profile;
namespace {
const int kRightColumnWidth = 270;
const int kIconSize = 85;
// Implements the extension installation prompt for Windows.
class InstallDialogContent : public views::View, public views::DialogDelegate {
public:
InstallDialogContent(ExtensionInstallUI::Delegate* delegate,
Extension* extension, SkBitmap* icon, const std::wstring& warning_text,
bool is_uninstall)
: delegate_(delegate), icon_(NULL), is_uninstall_(is_uninstall) {
// Scale down to 85x85, but allow smaller icons (don't scale up).
gfx::Size size(icon->width(), icon->height());
if (size.width() > kIconSize || size.height() > kIconSize)
size = gfx::Size(kIconSize, kIconSize);
icon_ = new views::ImageView();
icon_->SetImageSize(size);
icon_->SetImage(*icon);
AddChildView(icon_);
heading_ = new views::Label(
l10n_util::GetStringF(is_uninstall ?
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING :
IDS_EXTENSION_INSTALL_PROMPT_HEADING,
UTF8ToWide(extension->name())));
heading_->SetFont(heading_->GetFont().DeriveFont(1, gfx::Font::BOLD));
heading_->SetMultiLine(true);
heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(heading_);
warning_ = new views::Label(warning_text);
warning_->SetMultiLine(true);
warning_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(warning_);
}
private:
// DialogDelegate
virtual std::wstring GetDialogButtonLabel(
MessageBoxFlags::DialogButton button) const {
switch (button) {
case MessageBoxFlags::DIALOGBUTTON_OK:
if (is_uninstall_)
return l10n_util::GetString(IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON);
else
return l10n_util::GetString(IDS_EXTENSION_PROMPT_INSTALL_BUTTON);
case MessageBoxFlags::DIALOGBUTTON_CANCEL:
return l10n_util::GetString(IDS_EXTENSION_PROMPT_CANCEL_BUTTON);
default:
NOTREACHED();
return L"";
}
}
virtual int GetDefaultDialogButton() const {
return MessageBoxFlags::DIALOGBUTTON_CANCEL;
}
virtual bool Accept() {
delegate_->InstallUIProceed();
return true;
}
virtual bool Cancel() {
delegate_->InstallUIAbort();
return true;
}
// WindowDelegate
virtual bool IsModal() const { return true; }
virtual std::wstring GetWindowTitle() const {
if (is_uninstall_)
return l10n_util::GetString(IDS_EXTENSION_UNINSTALL_PROMPT_TITLE);
else
return l10n_util::GetString(IDS_EXTENSION_INSTALL_PROMPT_TITLE);
}
virtual views::View* GetContentsView() { return this; }
// View
virtual gfx::Size GetPreferredSize() {
int width = kRightColumnWidth + kPanelHorizMargin + kPanelHorizMargin;
width += kIconSize;
width += kPanelHorizMargin;
int height = kPanelVertMargin * 2;
height += heading_->GetHeightForWidth(kRightColumnWidth);
height += kPanelVertMargin;
height += warning_->GetHeightForWidth(kRightColumnWidth);
height += kPanelVertMargin;
return gfx::Size(width, std::max(height, kIconSize + kPanelVertMargin * 2));
}
virtual void Layout() {
int x = kPanelHorizMargin;
int y = kPanelVertMargin;
icon_->SetBounds(x, y, kIconSize, kIconSize);
x += kIconSize;
x += kPanelHorizMargin;
heading_->SizeToFit(kRightColumnWidth);
heading_->SetX(x);
heading_->SetY(y);
y += heading_->height();
y += kPanelVertMargin;
warning_->SizeToFit(kRightColumnWidth);
warning_->SetX(x);
warning_->SetY(y);
y += warning_->height();
y += kPanelVertMargin;
}
ExtensionInstallUI::Delegate* delegate_;
views::ImageView* icon_;
views::Label* heading_;
views::Label* warning_;
bool is_uninstall_;
DISALLOW_COPY_AND_ASSIGN(InstallDialogContent);
};
} // namespace
// static
void ExtensionInstallUI::ShowExtensionInstallUIPromptImpl(
Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,
const string16& warning_text, bool is_uninstall) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
if (!browser) {
delegate->InstallUIProceed();
return;
}
BrowserWindow* window = browser->window();
if (!window) {
delegate->InstallUIAbort();
return;
}
views::Window::CreateChromeWindow(window->GetNativeHandle(), gfx::Rect(),
new InstallDialogContent(delegate, extension, icon,
UTF16ToWideHack(warning_text),
is_uninstall))->Show();
}
<commit_msg>Fix a case where we could theoretically install an extension without prompt.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/standard_layout.h"
#include "views/view.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"
#if defined(OS_WIN)
#include "app/win_util.h"
#endif
class Profile;
namespace {
const int kRightColumnWidth = 270;
const int kIconSize = 85;
// Implements the extension installation prompt for Windows.
class InstallDialogContent : public views::View, public views::DialogDelegate {
public:
InstallDialogContent(ExtensionInstallUI::Delegate* delegate,
Extension* extension, SkBitmap* icon, const std::wstring& warning_text,
bool is_uninstall)
: delegate_(delegate), icon_(NULL), is_uninstall_(is_uninstall) {
// Scale down to 85x85, but allow smaller icons (don't scale up).
gfx::Size size(icon->width(), icon->height());
if (size.width() > kIconSize || size.height() > kIconSize)
size = gfx::Size(kIconSize, kIconSize);
icon_ = new views::ImageView();
icon_->SetImageSize(size);
icon_->SetImage(*icon);
AddChildView(icon_);
heading_ = new views::Label(
l10n_util::GetStringF(is_uninstall ?
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING :
IDS_EXTENSION_INSTALL_PROMPT_HEADING,
UTF8ToWide(extension->name())));
heading_->SetFont(heading_->GetFont().DeriveFont(1, gfx::Font::BOLD));
heading_->SetMultiLine(true);
heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(heading_);
warning_ = new views::Label(warning_text);
warning_->SetMultiLine(true);
warning_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(warning_);
}
private:
// DialogDelegate
virtual std::wstring GetDialogButtonLabel(
MessageBoxFlags::DialogButton button) const {
switch (button) {
case MessageBoxFlags::DIALOGBUTTON_OK:
if (is_uninstall_)
return l10n_util::GetString(IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON);
else
return l10n_util::GetString(IDS_EXTENSION_PROMPT_INSTALL_BUTTON);
case MessageBoxFlags::DIALOGBUTTON_CANCEL:
return l10n_util::GetString(IDS_EXTENSION_PROMPT_CANCEL_BUTTON);
default:
NOTREACHED();
return L"";
}
}
virtual int GetDefaultDialogButton() const {
return MessageBoxFlags::DIALOGBUTTON_CANCEL;
}
virtual bool Accept() {
delegate_->InstallUIProceed();
return true;
}
virtual bool Cancel() {
delegate_->InstallUIAbort();
return true;
}
// WindowDelegate
virtual bool IsModal() const { return true; }
virtual std::wstring GetWindowTitle() const {
if (is_uninstall_)
return l10n_util::GetString(IDS_EXTENSION_UNINSTALL_PROMPT_TITLE);
else
return l10n_util::GetString(IDS_EXTENSION_INSTALL_PROMPT_TITLE);
}
virtual views::View* GetContentsView() { return this; }
// View
virtual gfx::Size GetPreferredSize() {
int width = kRightColumnWidth + kPanelHorizMargin + kPanelHorizMargin;
width += kIconSize;
width += kPanelHorizMargin;
int height = kPanelVertMargin * 2;
height += heading_->GetHeightForWidth(kRightColumnWidth);
height += kPanelVertMargin;
height += warning_->GetHeightForWidth(kRightColumnWidth);
height += kPanelVertMargin;
return gfx::Size(width, std::max(height, kIconSize + kPanelVertMargin * 2));
}
virtual void Layout() {
int x = kPanelHorizMargin;
int y = kPanelVertMargin;
icon_->SetBounds(x, y, kIconSize, kIconSize);
x += kIconSize;
x += kPanelHorizMargin;
heading_->SizeToFit(kRightColumnWidth);
heading_->SetX(x);
heading_->SetY(y);
y += heading_->height();
y += kPanelVertMargin;
warning_->SizeToFit(kRightColumnWidth);
warning_->SetX(x);
warning_->SetY(y);
y += warning_->height();
y += kPanelVertMargin;
}
ExtensionInstallUI::Delegate* delegate_;
views::ImageView* icon_;
views::Label* heading_;
views::Label* warning_;
bool is_uninstall_;
DISALLOW_COPY_AND_ASSIGN(InstallDialogContent);
};
} // namespace
// static
void ExtensionInstallUI::ShowExtensionInstallUIPromptImpl(
Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,
const string16& warning_text, bool is_uninstall) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
if (!browser) {
delegate->InstallUIAbort();
return;
}
BrowserWindow* window = browser->window();
if (!window) {
delegate->InstallUIAbort();
return;
}
views::Window::CreateChromeWindow(window->GetNativeHandle(), gfx::Rect(),
new InstallDialogContent(delegate, extension, icon,
UTF16ToWideHack(warning_text),
is_uninstall))->Show();
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.