text
stringlengths 54
60.6k
|
---|
<commit_before>#include "codecvt/codecvt"
#include <cstring>
#include "cppunit-header.h"
#include "multistring.h"
// utility wrapper to adapt locale facets for use outside of locale framework
template<class Facet>
class deletable_facet : public Facet
{
public:
template<class ...Args>
deletable_facet(Args&& ...args) : Facet(std::forward<Args>(args)...) {}
~deletable_facet() {}
};
// Primary declaration
template <typename CVT>
class Test_codecvt_base : public CppUnit::TestFixture
{
public:
typedef CVT cvt_t;
typedef typename CVT::intern_type char_type;
CPPUNIT_TEST_SUITE(Test_codecvt_base);
CPPUNIT_TEST(construction);
CPPUNIT_TEST(encoding);
CPPUNIT_TEST(always_noconv);
CPPUNIT_TEST(max_length);
CPPUNIT_TEST_SUITE_END();
public:
virtual ~Test_codecvt_base()
{ }
virtual void construction()
{
deletable_facet<cvt_t> cvt;
deletable_facet<cvt_t> cvt2(1);
deletable_facet<cvt_t> cvt3(2);
printf("-------> Max encodable = %d\n", get_max_encodable());
static_assert(std::is_same<char, typename cvt_t::extern_type>::value,
"codecvt<> extern_type is invalid");
CPPUNIT_ASSERT(cvt.encoding() == 0);
}
virtual void encoding()
{
deletable_facet<cvt_t> cvt;
CPPUNIT_ASSERT(cvt.encoding() == 0);
}
virtual void always_noconv()
{
deletable_facet<cvt_t> cvt;
CPPUNIT_ASSERT(cvt.always_noconv() == false);
}
char32_t get_max_encodable() { return 0xefffffff; }
virtual void max_length()
{
deletable_facet<cvt_t> cvt;
if (std::is_same<char16_t, char_type>::value)
CPPUNIT_ASSERT(cvt.max_length() <= 4);
else if (std::is_same<char32_t, char_type>::value)
CPPUNIT_ASSERT(cvt.max_length() <= 6);
}
};
template<>
char32_t
Test_codecvt_base<std::codecvt<char16_t, char, std::mbstate_t>>
::get_max_encodable()
{
return 0x10ffff;
}
typedef Test_codecvt_base<std::codecvt<char16_t, char, std::mbstate_t>> c16;
typedef Test_codecvt_base<std::codecvt<char32_t, char, std::mbstate_t>> c32;
typedef Test_codecvt_base<std::codecvt_utf8<char16_t>> c_utf8_16;
typedef Test_codecvt_base<std::codecvt_utf8<char32_t>> c_utf8_32;
typedef Test_codecvt_base<std::codecvt_utf16<char16_t>> c_utf16_16;
typedef Test_codecvt_base<std::codecvt_utf16<char32_t>> c_utf16_32;
typedef Test_codecvt_base<std::codecvt_utf8_utf16<char16_t>> c_utf8_utf16_16;
typedef Test_codecvt_base<std::codecvt_utf8_utf16<char32_t>> c_utf8_utf16_32;
CPPUNIT_TEST_SUITE_REGISTRATION(c16);
CPPUNIT_TEST_SUITE_REGISTRATION(c32);
CPPUNIT_TEST_SUITE_REGISTRATION(c_utf8_16);
CPPUNIT_TEST_SUITE_REGISTRATION(c_utf8_32);
CPPUNIT_TEST_SUITE_REGISTRATION(c_utf16_16);
CPPUNIT_TEST_SUITE_REGISTRATION(c_utf16_32);
CPPUNIT_TEST_SUITE_REGISTRATION(c_utf8_utf16_16);
CPPUNIT_TEST_SUITE_REGISTRATION(c_utf8_utf16_32);
<commit_msg>Working on getting stuff in here<commit_after>#include "codecvt/codecvt"
#include <cstring>
#include "cppunit-header.h"
#include "multistring.h"
// utility wrapper to adapt locale facets for use outside of locale framework
template<class Facet>
class deletable_facet : public Facet
{
public:
template<class ...Args>
deletable_facet(Args&& ...args) : Facet(std::forward<Args>(args)...) {}
~deletable_facet() {}
};
template <typename T>
struct cvt_max_encodable { static const unsigned long value = 0x7ffffffful; };
template <>
struct cvt_max_encodable<std::codecvt<char16_t, char, std::mbstate_t>>
{ static const unsigned long value = utf16_conversion::max_encodable_value(); };
template <typename C,
unsigned long N,
std::codecvt_mode M,
template <class, unsigned long, std::codecvt_mode> class CVT>
struct cvt_max_encodable<CVT<C, N, M>> {
static const unsigned long value = N;
};
// Primary declaration
template <typename CVT>
class Test_codecvt_base : public CppUnit::TestFixture
{
public:
typedef CVT cvt_t;
typedef typename CVT::intern_type char_type;
CPPUNIT_TEST_SUITE(Test_codecvt_base);
CPPUNIT_TEST(construction);
CPPUNIT_TEST(encoding);
CPPUNIT_TEST(always_noconv);
CPPUNIT_TEST(max_length);
CPPUNIT_TEST_SUITE_END();
public:
virtual ~Test_codecvt_base()
{ }
virtual void construction()
{
deletable_facet<cvt_t> cvt;
deletable_facet<cvt_t> cvt2(1);
deletable_facet<cvt_t> cvt3(2);
printf("-------> Max encodable = %d\n", get_max_encodable());
static_assert(std::is_same<char, typename cvt_t::extern_type>::value,
"codecvt<> extern_type is invalid");
CPPUNIT_ASSERT(cvt.encoding() == 0);
}
virtual void encoding()
{
deletable_facet<cvt_t> cvt;
CPPUNIT_ASSERT(cvt.encoding() == 0);
}
virtual void always_noconv()
{
deletable_facet<cvt_t> cvt;
CPPUNIT_ASSERT(cvt.always_noconv() == false);
}
virtual void max_length()
{
deletable_facet<cvt_t> cvt;
if (std::is_same<char16_t, char_type>::value)
CPPUNIT_ASSERT(cvt.max_length() <= 4);
else if (std::is_same<char32_t, char_type>::value)
CPPUNIT_ASSERT(cvt.max_length() <= 6);
}
protected:
char32_t get_max_encodable() { return 0xefffffff; }
};
typedef Test_codecvt_base<std::codecvt<char16_t, char, std::mbstate_t>> c16;
typedef Test_codecvt_base<std::codecvt<char32_t, char, std::mbstate_t>> c32;
typedef Test_codecvt_base<std::codecvt_utf8<char16_t>> c_utf8_16;
typedef Test_codecvt_base<std::codecvt_utf8<char32_t>> c_utf8_32;
typedef Test_codecvt_base<std::codecvt_utf16<char16_t>> c_utf16_16;
typedef Test_codecvt_base<std::codecvt_utf16<char32_t>> c_utf16_32;
typedef Test_codecvt_base<std::codecvt_utf8_utf16<char16_t>> c_utf8_utf16_16;
typedef Test_codecvt_base<std::codecvt_utf8_utf16<char32_t>> c_utf8_utf16_32;
CPPUNIT_TEST_SUITE_REGISTRATION(c16);
CPPUNIT_TEST_SUITE_REGISTRATION(c32);
CPPUNIT_TEST_SUITE_REGISTRATION(c_utf8_16);
CPPUNIT_TEST_SUITE_REGISTRATION(c_utf8_32);
CPPUNIT_TEST_SUITE_REGISTRATION(c_utf16_16);
CPPUNIT_TEST_SUITE_REGISTRATION(c_utf16_32);
CPPUNIT_TEST_SUITE_REGISTRATION(c_utf8_utf16_16);
CPPUNIT_TEST_SUITE_REGISTRATION(c_utf8_utf16_32);
<|endoftext|> |
<commit_before>/* rapt - RichieSam's Adventures in Path Tracing
*
* rapt is the legal property of Adrian Astley
* Copyright Adrian Astley 2015
*/
#include "basic_path_tracer/basic_path_tracer.h"
#include "graphics/d3d_util.h"
#include "graphics/d3d_texture2d.h"
#include "graphics/cuda_texture2d.h"
#include "scene/scene_objects.h"
#include <cuda_runtime.h>
namespace BasicPathTracer {
BasicPathTracer::BasicPathTracer(HINSTANCE hinstance)
: Engine::RAPTEngine(hinstance),
m_backbufferRTV(nullptr),
m_hostCamera(-DirectX::XM_PI, DirectX::XM_PIDIV2, 30.0f),
m_mouseLastPos_X(0),
m_mouseLastPos_Y(0),
m_cameraMoved(true),
m_frameNumber(0u) {
}
bool BasicPathTracer::Initialize(LPCTSTR mainWndCaption, uint32 screenWidth, uint32 screenHeight, bool fullscreen) {
// Initialize the Engine
if (!Engine::RAPTEngine::Initialize(mainWndCaption, screenWidth, screenHeight, fullscreen)) {
return false;
}
// We have to use a RGBA format since CUDA-DirectX interop doesn't support R32G32B32_FLOAT
m_hdrTextureD3D = new Graphics::D3DTexture2D(m_device, screenWidth, screenHeight, DXGI_FORMAT_R32G32B32A32_FLOAT, D3D11_BIND_SHADER_RESOURCE, 1);
m_hdrTextureCuda = new Graphics::CudaTexture2D(screenWidth, screenHeight, 4 /* RGBA */ * sizeof(float));
m_hdrTextureCuda->RegisterResource(m_hdrTextureD3D->GetTexture(), cudaGraphicsRegisterFlagsNone);
m_hdrTextureCuda->MemSet(0);
Graphics::LoadVertexShader(L"fullscreen_triangle_vs.cso", m_device, &m_fullscreenTriangleVS);
Graphics::LoadPixelShader(L"copy_cuda_output_to_backbuffer_ps.cso", m_device, &m_copyCudaOutputToBackbufferPS);
// Create the constant buffer for the pixel shader
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
bufferDesc.ByteWidth = static_cast<uint>(Graphics::CBSize(sizeof(float)));
m_device->CreateBuffer(&bufferDesc, nullptr, &m_copyCudaOutputPSConstantBuffer);
// Bind the shaders and SRV to the pipeline
// We never bind anything else, so we can just do it once during initialization
m_immediateContext->VSSetShader(m_fullscreenTriangleVS, nullptr, 0u);
m_immediateContext->PSSetShader(m_copyCudaOutputToBackbufferPS, nullptr, 0u);
ID3D11ShaderResourceView *hdrSRV = m_hdrTextureD3D->GetShaderResource();
m_immediateContext->PSSetShaderResources(0, 1, &hdrSRV);
m_immediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// Create the scene
// TODO: Use a scene description file rather than hard code the scene
// (Can probably steal the format used by The Halfling Engine)
Scene::Sphere spheres[9];
spheres[0] = {make_float3(0.0f, 0.0f, 0.0f), 4.0f};
spheres[1] = {make_float3(-6.0f, -6.0f, -6.0f), 4.0f};
spheres[2] = {make_float3(-6.0f, -6.0f, 6.0f), 4.0f};
spheres[3] = {make_float3(-6.0f, 6.0f, -6.0f), 4.0f};
spheres[4] = {make_float3(-6.0f, 6.0f, 6.0f), 4.0f};
spheres[5] = {make_float3(6.0f, -6.0f, -6.0f), 4.0f};
spheres[6] = {make_float3(6.0f, -6.0f, 6.0f), 4.0f};
spheres[7] = {make_float3(6.0f, 6.0f, -6.0f), 4.0f};
spheres[8] = {make_float3(6.0f, 6.0f, 6.0f), 4.0f};
CE(cudaMalloc(&d_spheres, 9 * sizeof(Scene::Sphere)));
CE(cudaMemcpy(d_spheres, &spheres, 9 * sizeof(Scene::Sphere), cudaMemcpyHostToDevice));
m_numSpheres = 9;
CE(cudaMalloc(&d_deviceCamera, sizeof(DeviceCamera)));
return true;
}
void BasicPathTracer::Shutdown() {
// Release in the opposite order we initialized in
Engine::RAPTEngine::Shutdown();
}
void BasicPathTracer::OnResize() {
if (!m_d3dInitialized) {
return;
}
// Update the camera projection
m_hostCamera.SetProjection(DirectX::XM_PIDIV2, (float)m_clientWidth / m_clientHeight);
// Release the old views and the old depth/stencil buffer.
ReleaseCOM(m_backbufferRTV);
// Resize the swap chain
HR(m_swapChain->ResizeBuffers(2, m_clientWidth, m_clientHeight, DXGI_FORMAT_R8G8B8A8_UNORM, 0));
// Recreate the render target view.
ID3D11Texture2D *backBuffer;
HR(m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void **>(&backBuffer)));
HR(m_device->CreateRenderTargetView(backBuffer, 0, &m_backbufferRTV));
ReleaseCOM(backBuffer);
// Set the backbuffer as the rendertarget
m_immediateContext->OMSetRenderTargets(1u, &m_backbufferRTV, nullptr);
// Set the viewport transform.
m_screenViewport.TopLeftX = 0;
m_screenViewport.TopLeftY = 0;
m_screenViewport.Width = static_cast<float>(m_clientWidth);
m_screenViewport.Height = static_cast<float>(m_clientHeight);
m_screenViewport.MinDepth = 0.0f;
m_screenViewport.MaxDepth = 1.0f;
m_immediateContext->RSSetViewports(1, &m_screenViewport);
}
void BasicPathTracer::MouseDown(WPARAM buttonState, int x, int y) {
m_mouseLastPos_X = x;
m_mouseLastPos_Y = y;
SetCapture(m_hwnd);
}
void BasicPathTracer::MouseUp(WPARAM buttonState, int x, int y) {
ReleaseCapture();
}
void BasicPathTracer::MouseMove(WPARAM buttonState, int x, int y) {
if ((buttonState & MK_LBUTTON) != 0) {
if (GetKeyState(VK_MENU) & 0x8000) {
// Calculate the new phi and theta based on mouse position relative to where the user clicked
float dPhi = ((float)(m_mouseLastPos_Y - y) / 300);
float dTheta = ((float)(m_mouseLastPos_X - x) / 300);
m_hostCamera.Rotate(-dTheta, dPhi);
}
} else if ((buttonState & MK_MBUTTON) != 0) {
if (GetKeyState(VK_MENU) & 0x8000) {
float dx = ((float)(m_mouseLastPos_X - x));
float dy = ((float)(m_mouseLastPos_Y - y));
m_hostCamera.Pan(dx * 0.1f, -dy * 0.1f);
}
}
m_mouseLastPos_X = x;
m_mouseLastPos_Y = y;
ResetAccumulationBuffer();
m_cameraMoved = true;
}
void BasicPathTracer::MouseWheel(int zDelta) {
m_hostCamera.Zoom((float)zDelta * 0.01f);
ResetAccumulationBuffer();
m_cameraMoved = true;
}
void BasicPathTracer::ResetAccumulationBuffer() {
m_hdrTextureCuda->MemSet(0);
m_frameNumber = 0u;
}
} // End of namespace BasicPathTracer
<commit_msg>BASIC_PATH_TRACER: Fix memory leaks<commit_after>/* rapt - RichieSam's Adventures in Path Tracing
*
* rapt is the legal property of Adrian Astley
* Copyright Adrian Astley 2015
*/
#include "basic_path_tracer/basic_path_tracer.h"
#include "graphics/d3d_util.h"
#include "graphics/d3d_texture2d.h"
#include "graphics/cuda_texture2d.h"
#include "scene/scene_objects.h"
#include <cuda_runtime.h>
namespace BasicPathTracer {
BasicPathTracer::BasicPathTracer(HINSTANCE hinstance)
: Engine::RAPTEngine(hinstance),
m_backbufferRTV(nullptr),
m_hostCamera(-DirectX::XM_PI, DirectX::XM_PIDIV2, 30.0f),
m_mouseLastPos_X(0),
m_mouseLastPos_Y(0),
m_cameraMoved(true),
m_frameNumber(0u) {
}
bool BasicPathTracer::Initialize(LPCTSTR mainWndCaption, uint32 screenWidth, uint32 screenHeight, bool fullscreen) {
// Initialize the Engine
if (!Engine::RAPTEngine::Initialize(mainWndCaption, screenWidth, screenHeight, fullscreen)) {
return false;
}
// We have to use a RGBA format since CUDA-DirectX interop doesn't support R32G32B32_FLOAT
m_hdrTextureD3D = new Graphics::D3DTexture2D(m_device, screenWidth, screenHeight, DXGI_FORMAT_R32G32B32A32_FLOAT, D3D11_BIND_SHADER_RESOURCE, 1);
m_hdrTextureCuda = new Graphics::CudaTexture2D(screenWidth, screenHeight, 4 /* RGBA */ * sizeof(float));
m_hdrTextureCuda->RegisterResource(m_hdrTextureD3D->GetTexture(), cudaGraphicsRegisterFlagsNone);
m_hdrTextureCuda->MemSet(0);
Graphics::LoadVertexShader(L"fullscreen_triangle_vs.cso", m_device, &m_fullscreenTriangleVS);
Graphics::LoadPixelShader(L"copy_cuda_output_to_backbuffer_ps.cso", m_device, &m_copyCudaOutputToBackbufferPS);
// Create the constant buffer for the pixel shader
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
bufferDesc.ByteWidth = static_cast<uint>(Graphics::CBSize(sizeof(float)));
m_device->CreateBuffer(&bufferDesc, nullptr, &m_copyCudaOutputPSConstantBuffer);
// Bind the shaders and SRV to the pipeline
// We never bind anything else, so we can just do it once during initialization
m_immediateContext->VSSetShader(m_fullscreenTriangleVS, nullptr, 0u);
m_immediateContext->PSSetShader(m_copyCudaOutputToBackbufferPS, nullptr, 0u);
ID3D11ShaderResourceView *hdrSRV = m_hdrTextureD3D->GetShaderResource();
m_immediateContext->PSSetShaderResources(0, 1, &hdrSRV);
m_immediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// Create the scene
// TODO: Use a scene description file rather than hard code the scene
// (Can probably steal the format used by The Halfling Engine)
Scene::Sphere spheres[9];
spheres[0] = {make_float3(0.0f, 0.0f, 0.0f), 4.0f};
spheres[1] = {make_float3(-6.0f, -6.0f, -6.0f), 4.0f};
spheres[2] = {make_float3(-6.0f, -6.0f, 6.0f), 4.0f};
spheres[3] = {make_float3(-6.0f, 6.0f, -6.0f), 4.0f};
spheres[4] = {make_float3(-6.0f, 6.0f, 6.0f), 4.0f};
spheres[5] = {make_float3(6.0f, -6.0f, -6.0f), 4.0f};
spheres[6] = {make_float3(6.0f, -6.0f, 6.0f), 4.0f};
spheres[7] = {make_float3(6.0f, 6.0f, -6.0f), 4.0f};
spheres[8] = {make_float3(6.0f, 6.0f, 6.0f), 4.0f};
CE(cudaMalloc(&d_spheres, 9 * sizeof(Scene::Sphere)));
CE(cudaMemcpy(d_spheres, &spheres, 9 * sizeof(Scene::Sphere), cudaMemcpyHostToDevice));
m_numSpheres = 9;
CE(cudaMalloc(&d_deviceCamera, sizeof(DeviceCamera)));
return true;
}
void BasicPathTracer::Shutdown() {
// Release in the opposite order we initialized in
cudaFree(d_deviceCamera);
cudaFree(d_spheres);
ReleaseCOM(m_copyCudaOutputPSConstantBuffer);
ReleaseCOM(m_copyCudaOutputToBackbufferPS);
ReleaseCOM(m_fullscreenTriangleVS);
delete m_hdrTextureCuda;
delete m_hdrTextureD3D;
Engine::RAPTEngine::Shutdown();
}
void BasicPathTracer::OnResize() {
if (!m_d3dInitialized) {
return;
}
// Update the camera projection
m_hostCamera.SetProjection(DirectX::XM_PIDIV2, (float)m_clientWidth / m_clientHeight);
// Release the old views and the old depth/stencil buffer.
ReleaseCOM(m_backbufferRTV);
// Resize the swap chain
HR(m_swapChain->ResizeBuffers(2, m_clientWidth, m_clientHeight, DXGI_FORMAT_R8G8B8A8_UNORM, 0));
// Recreate the render target view.
ID3D11Texture2D *backBuffer;
HR(m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void **>(&backBuffer)));
HR(m_device->CreateRenderTargetView(backBuffer, 0, &m_backbufferRTV));
ReleaseCOM(backBuffer);
// Set the backbuffer as the rendertarget
m_immediateContext->OMSetRenderTargets(1u, &m_backbufferRTV, nullptr);
// Set the viewport transform.
m_screenViewport.TopLeftX = 0;
m_screenViewport.TopLeftY = 0;
m_screenViewport.Width = static_cast<float>(m_clientWidth);
m_screenViewport.Height = static_cast<float>(m_clientHeight);
m_screenViewport.MinDepth = 0.0f;
m_screenViewport.MaxDepth = 1.0f;
m_immediateContext->RSSetViewports(1, &m_screenViewport);
}
void BasicPathTracer::MouseDown(WPARAM buttonState, int x, int y) {
m_mouseLastPos_X = x;
m_mouseLastPos_Y = y;
SetCapture(m_hwnd);
}
void BasicPathTracer::MouseUp(WPARAM buttonState, int x, int y) {
ReleaseCapture();
}
void BasicPathTracer::MouseMove(WPARAM buttonState, int x, int y) {
if ((buttonState & MK_LBUTTON) != 0) {
if (GetKeyState(VK_MENU) & 0x8000) {
// Calculate the new phi and theta based on mouse position relative to where the user clicked
float dPhi = ((float)(m_mouseLastPos_Y - y) / 300);
float dTheta = ((float)(m_mouseLastPos_X - x) / 300);
m_hostCamera.Rotate(-dTheta, dPhi);
}
} else if ((buttonState & MK_MBUTTON) != 0) {
if (GetKeyState(VK_MENU) & 0x8000) {
float dx = ((float)(m_mouseLastPos_X - x));
float dy = ((float)(m_mouseLastPos_Y - y));
m_hostCamera.Pan(dx * 0.1f, -dy * 0.1f);
}
}
m_mouseLastPos_X = x;
m_mouseLastPos_Y = y;
ResetAccumulationBuffer();
m_cameraMoved = true;
}
void BasicPathTracer::MouseWheel(int zDelta) {
m_hostCamera.Zoom((float)zDelta * 0.01f);
ResetAccumulationBuffer();
m_cameraMoved = true;
}
void BasicPathTracer::ResetAccumulationBuffer() {
m_hdrTextureCuda->MemSet(0);
m_frameNumber = 0u;
}
} // End of namespace BasicPathTracer
<|endoftext|> |
<commit_before>#include <boost/python.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/shared_ptr.hpp>
using namespace boost::interprocess;
using namespace boost::python;
void register_shared_memory_object() {
typedef shared_memory_object T;
class_<T, boost::shared_ptr<T>, boost::noncopyable> c("shared_memory_object", init<>());
c.def(
init<create_only_t, const char *, mode_t, optional<const permissions&>>(
args("tag", "name", "mode", "permissions")
)
);
c.def(
init<open_or_create_t, const char *, mode_t, optional<const permissions&>>(
args("tag", "name", "mode", "permissions")
)
);
c.def(
init<open_only_t, const char *, mode_t>(
args("tag", "name", "mode")
)
);
c.def("remove", &T::remove);
c.staticmethod("remove");
//TODO: finish "shared_memory_object"
}
<commit_msg>removed useless file<commit_after><|endoftext|> |
<commit_before>#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/FieldIndexer.h>
#include <ir/index_manager/index/TermReader.h>
#include <ir/index_manager/index/TermPositions.h>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
using namespace std;
namespace bfs = boost::filesystem;
NS_IZENELIB_IR_BEGIN
namespace indexmanager
{
FieldIndexer::FieldIndexer(const char* field, MemCache* pCache, Indexer* pIndexer)
:field_(field),pMemCache_(pCache),pIndexer_(pIndexer),vocFilePointer_(0),alloc_(0),sorter_(0),termCount_(0)
{
skipInterval_ = pIndexer_->getSkipInterval();
maxSkipLevel_ = pIndexer_->getMaxSkipLevel();
if (! pIndexer_->isRealTime())
{
std::string sorterName = field_+".tmp";
bfs::path path(bfs::path(pIndexer->pConfigurationManager_->indexStrategy_.indexLocation_) /bfs::path(sorterName));
sorterFullPath_= path.string();
sorter_=new izenelib::am::IzeneSort<uint32_t, uint8_t, true>(sorterFullPath_.c_str(), 100000000);
}
else
alloc_ = new boost::scoped_alloc(recycle_);
}
FieldIndexer::~FieldIndexer()
{
/*
InMemoryPostingMap::iterator iter = postingMap_.begin()
for(; iter !=postingMap_.end(); ++iter)
{
delete iter->second;
}
*/
if (alloc_) delete alloc_;
pMemCache_ = NULL;
if (sorter_) delete sorter_;
}
void convert(char* data, uint32_t termId, uint32_t docId, uint32_t offset)
{
char* pData = data;
memcpy(pData, &(termId), sizeof(termId));
pData += sizeof(termId);
memcpy(pData, &(docId), sizeof(docId));
pData += sizeof(docId);
memcpy(pData, &(offset), sizeof(offset));
pData += sizeof(offset);
}
void FieldIndexer::addField(docid_t docid, boost::shared_ptr<LAInput> laInput)
{
if (pIndexer_->isRealTime())
{
InMemoryPosting* curPosting;
for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter)
{
InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->termId_);
if (postingIter == postingMap_.end())
{
//curPosting = new InMemoryPosting(pMemCache_, skipInterval_, maxSkipLevel_);
curPosting = BOOST_NEW(*alloc_, InMemoryPosting)(pMemCache_, skipInterval_, maxSkipLevel_);
postingMap_[iter->termId_] = curPosting;
}
else
curPosting = postingIter->second;
curPosting->add(docid, iter->offset_);
}
}
else
{
if (!sorter_)
sorter_=new izenelib::am::IzeneSort<uint32_t, uint8_t, true>(sorterFullPath_.c_str(), 100000000);
char data[12];
for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter)
{
convert(data,iter->termId_,docid,iter->offset_);
sorter_->add_data(12, data);
}
}
}
void FieldIndexer::addField(docid_t docid, boost::shared_ptr<ForwardIndex> forwardindex)
{
InMemoryPosting* curPosting;
for (ForwardIndex::iterator iter = forwardindex->begin(); iter != forwardindex->end(); ++iter)
{
InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->first);
if (postingIter == postingMap_.end())
{
curPosting = BOOST_NEW(*alloc_, InMemoryPosting)(pMemCache_, skipInterval_, maxSkipLevel_);
postingMap_[iter->first] = curPosting;
}
else
curPosting = postingIter->second;
ForwardIndexOffset::iterator endit = iter->second->end();
for (ForwardIndexOffset::iterator it = iter->second->begin(); it != endit; ++it)
curPosting->add(docid, *it);
}
}
void FieldIndexer::reset()
{
InMemoryPosting* pPosting;
for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter)
{
pPosting = iter->second;
if (!pPosting->hasNoChunk())
{
pPosting->reset(); ///clear posting data
}
}
postingMap_.clear();
termCount_ = 0;
}
void writeTermInfo(IndexOutput* pVocWriter, termid_t tid, const TermInfo& termInfo)
{
pVocWriter->writeInt(tid); ///write term id
pVocWriter->writeInt(termInfo.docFreq_); ///write df
pVocWriter->writeInt(termInfo.ctf_); ///write ctf
pVocWriter->writeInt(termInfo.lastDocID_); ///write last doc id
pVocWriter->writeInt(termInfo.skipLevel_); ///write skip level
pVocWriter->writeLong(termInfo.skipPointer_); ///write skip list offset offset
pVocWriter->writeLong(termInfo.docPointer_); ///write document posting offset
pVocWriter->writeInt(termInfo.docPostingLen_); ///write document posting length (without skiplist)
pVocWriter->writeLong(termInfo.positionPointer_); ///write position posting offset
pVocWriter->writeInt(termInfo.positionPostingLen_);///write position posting length
}
fileoffset_t FieldIndexer::write(OutputDescriptor* pWriterDesc)
{
vocFilePointer_ = pWriterDesc->getVocOutput()->getFilePointer();
IndexOutput* pVocWriter = pWriterDesc->getVocOutput();
termid_t tid;
InMemoryPosting* pPosting;
fileoffset_t vocOffset = pVocWriter->getFilePointer();
TermInfo termInfo;
if (pIndexer_->isRealTime())
{
izenelib::util::ScopedWriteLock<izenelib::util::ReadWriteLock> lock(rwLock_);
for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter)
{
pPosting = iter->second;
pPosting->setDirty(true);
if (!pPosting->hasNoChunk())
{
tid = iter->first;
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter,tid,termInfo);
pPosting->reset(); ///clear posting data
termInfo.reset();
termCount_++;
}
//delete pPosting;
//pPosting = NULL;
}
postingMap_.clear();
delete alloc_;
alloc_ = new boost::scoped_alloc(recycle_);
}
else
{
sorter_->sort();
FILE* f = fopen(sorterFullPath_.c_str(),"r");
fseek(f, 0, SEEK_SET);
uint64_t count;
fread(&count, sizeof(uint64_t), 1, f);
pPosting = new InMemoryPosting(pMemCache_, skipInterval_, maxSkipLevel_);
termid_t lastTerm = BAD_DOCID;
try
{
for (uint64_t i = 0; i < count; ++i)
{
uint8_t len;
fread(&len, sizeof(uint8_t), 1, f);
uint32_t docId,offset;
fread(&tid, sizeof(uint32_t), 1, f);
fread(&docId, sizeof(uint32_t), 1, f);
fread(&offset, sizeof(uint32_t), 1, f);
if(tid != lastTerm && lastTerm != BAD_DOCID)
{
if (!pPosting->hasNoChunk())
{
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter, lastTerm, termInfo);
pPosting->reset(); ///clear posting data
pMemCache_->flushMem();
termInfo.reset();
termCount_++;
}
}
pPosting->add(docId, offset);
lastTerm = tid;
}
}catch(std::exception& e)
{
cout<<e.what()<<endl;
}
if (!pPosting->hasNoChunk())
{
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter, lastTerm, termInfo);
pPosting->reset(); ///clear posting data
pMemCache_->flushMem();
termInfo.reset();
termCount_++;
}
fclose(f);
sorter_->clear_files();
delete sorter_;
sorter_ = NULL;
delete pPosting;
}
fileoffset_t vocDescOffset = pVocWriter->getFilePointer();
int64_t vocLength = vocDescOffset - vocOffset;
///begin write vocabulary descriptor
pVocWriter->writeLong(vocLength); ///<VocLength(Int64)>
pVocWriter->writeLong(termCount_); ///<TermCount(Int64)>
///end write vocabulary descriptor
return vocDescOffset;
}
TermReader* FieldIndexer::termReader()
{
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(rwLock_);
return new InMemoryTermReader(getField(),this);
}
}
NS_IZENELIB_IR_END
<commit_msg>make memory buffer size for izenesoft to be aligned with record length<commit_after>#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/FieldIndexer.h>
#include <ir/index_manager/index/TermReader.h>
#include <ir/index_manager/index/TermPositions.h>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
using namespace std;
namespace bfs = boost::filesystem;
NS_IZENELIB_IR_BEGIN
namespace indexmanager
{
FieldIndexer::FieldIndexer(const char* field, MemCache* pCache, Indexer* pIndexer)
:field_(field),pMemCache_(pCache),pIndexer_(pIndexer),vocFilePointer_(0),alloc_(0),sorter_(0),termCount_(0)
{
skipInterval_ = pIndexer_->getSkipInterval();
maxSkipLevel_ = pIndexer_->getMaxSkipLevel();
if (! pIndexer_->isRealTime())
{
std::string sorterName = field_+".tmp";
bfs::path path(bfs::path(pIndexer->pConfigurationManager_->indexStrategy_.indexLocation_) /bfs::path(sorterName));
sorterFullPath_= path.string();
sorter_=new izenelib::am::IzeneSort<uint32_t, uint8_t, true>(sorterFullPath_.c_str(), 120000000);
}
else
alloc_ = new boost::scoped_alloc(recycle_);
}
FieldIndexer::~FieldIndexer()
{
/*
InMemoryPostingMap::iterator iter = postingMap_.begin()
for(; iter !=postingMap_.end(); ++iter)
{
delete iter->second;
}
*/
if (alloc_) delete alloc_;
pMemCache_ = NULL;
if (sorter_) delete sorter_;
}
void convert(char* data, uint32_t termId, uint32_t docId, uint32_t offset)
{
char* pData = data;
memcpy(pData, &(termId), sizeof(termId));
pData += sizeof(termId);
memcpy(pData, &(docId), sizeof(docId));
pData += sizeof(docId);
memcpy(pData, &(offset), sizeof(offset));
pData += sizeof(offset);
}
void FieldIndexer::addField(docid_t docid, boost::shared_ptr<LAInput> laInput)
{
if (pIndexer_->isRealTime())
{
InMemoryPosting* curPosting;
for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter)
{
InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->termId_);
if (postingIter == postingMap_.end())
{
//curPosting = new InMemoryPosting(pMemCache_, skipInterval_, maxSkipLevel_);
curPosting = BOOST_NEW(*alloc_, InMemoryPosting)(pMemCache_, skipInterval_, maxSkipLevel_);
postingMap_[iter->termId_] = curPosting;
}
else
curPosting = postingIter->second;
curPosting->add(docid, iter->offset_);
}
}
else
{
if (!sorter_)
sorter_=new izenelib::am::IzeneSort<uint32_t, uint8_t, true>(sorterFullPath_.c_str(), 120000000);
char data[12];
for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter)
{
convert(data,iter->termId_,docid,iter->offset_);
sorter_->add_data(12, data);
}
}
}
void FieldIndexer::addField(docid_t docid, boost::shared_ptr<ForwardIndex> forwardindex)
{
InMemoryPosting* curPosting;
for (ForwardIndex::iterator iter = forwardindex->begin(); iter != forwardindex->end(); ++iter)
{
InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->first);
if (postingIter == postingMap_.end())
{
curPosting = BOOST_NEW(*alloc_, InMemoryPosting)(pMemCache_, skipInterval_, maxSkipLevel_);
postingMap_[iter->first] = curPosting;
}
else
curPosting = postingIter->second;
ForwardIndexOffset::iterator endit = iter->second->end();
for (ForwardIndexOffset::iterator it = iter->second->begin(); it != endit; ++it)
curPosting->add(docid, *it);
}
}
void FieldIndexer::reset()
{
InMemoryPosting* pPosting;
for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter)
{
pPosting = iter->second;
if (!pPosting->hasNoChunk())
{
pPosting->reset(); ///clear posting data
}
}
postingMap_.clear();
termCount_ = 0;
}
void writeTermInfo(IndexOutput* pVocWriter, termid_t tid, const TermInfo& termInfo)
{
pVocWriter->writeInt(tid); ///write term id
pVocWriter->writeInt(termInfo.docFreq_); ///write df
pVocWriter->writeInt(termInfo.ctf_); ///write ctf
pVocWriter->writeInt(termInfo.lastDocID_); ///write last doc id
pVocWriter->writeInt(termInfo.skipLevel_); ///write skip level
pVocWriter->writeLong(termInfo.skipPointer_); ///write skip list offset offset
pVocWriter->writeLong(termInfo.docPointer_); ///write document posting offset
pVocWriter->writeInt(termInfo.docPostingLen_); ///write document posting length (without skiplist)
pVocWriter->writeLong(termInfo.positionPointer_); ///write position posting offset
pVocWriter->writeInt(termInfo.positionPostingLen_);///write position posting length
}
fileoffset_t FieldIndexer::write(OutputDescriptor* pWriterDesc)
{
vocFilePointer_ = pWriterDesc->getVocOutput()->getFilePointer();
IndexOutput* pVocWriter = pWriterDesc->getVocOutput();
termid_t tid;
InMemoryPosting* pPosting;
fileoffset_t vocOffset = pVocWriter->getFilePointer();
TermInfo termInfo;
if (pIndexer_->isRealTime())
{
izenelib::util::ScopedWriteLock<izenelib::util::ReadWriteLock> lock(rwLock_);
for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter)
{
pPosting = iter->second;
pPosting->setDirty(true);
if (!pPosting->hasNoChunk())
{
tid = iter->first;
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter,tid,termInfo);
pPosting->reset(); ///clear posting data
termInfo.reset();
termCount_++;
}
//delete pPosting;
//pPosting = NULL;
}
postingMap_.clear();
delete alloc_;
alloc_ = new boost::scoped_alloc(recycle_);
}
else
{
sorter_->sort();
FILE* f = fopen(sorterFullPath_.c_str(),"r");
fseek(f, 0, SEEK_SET);
uint64_t count;
fread(&count, sizeof(uint64_t), 1, f);
pPosting = new InMemoryPosting(pMemCache_, skipInterval_, maxSkipLevel_);
termid_t lastTerm = BAD_DOCID;
try
{
for (uint64_t i = 0; i < count; ++i)
{
uint8_t len;
fread(&len, sizeof(uint8_t), 1, f);
uint32_t docId,offset;
fread(&tid, sizeof(uint32_t), 1, f);
fread(&docId, sizeof(uint32_t), 1, f);
fread(&offset, sizeof(uint32_t), 1, f);
if(tid != lastTerm && lastTerm != BAD_DOCID)
{
if (!pPosting->hasNoChunk())
{
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter, lastTerm, termInfo);
pPosting->reset(); ///clear posting data
pMemCache_->flushMem();
termInfo.reset();
termCount_++;
}
}
pPosting->add(docId, offset);
lastTerm = tid;
}
}catch(std::exception& e)
{
cout<<e.what()<<endl;
}
if (!pPosting->hasNoChunk())
{
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter, lastTerm, termInfo);
pPosting->reset(); ///clear posting data
pMemCache_->flushMem();
termInfo.reset();
termCount_++;
}
fclose(f);
sorter_->clear_files();
delete sorter_;
sorter_ = NULL;
delete pPosting;
}
fileoffset_t vocDescOffset = pVocWriter->getFilePointer();
int64_t vocLength = vocDescOffset - vocOffset;
///begin write vocabulary descriptor
pVocWriter->writeLong(vocLength); ///<VocLength(Int64)>
pVocWriter->writeLong(termCount_); ///<TermCount(Int64)>
///end write vocabulary descriptor
return vocDescOffset;
}
TermReader* FieldIndexer::termReader()
{
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(rwLock_);
return new InMemoryTermReader(getField(),this);
}
}
NS_IZENELIB_IR_END
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "format.hpp"
namespace
{
struct ButFormat: public testing::Test
{ };
TEST_F(ButFormat, SampleStrings)
{
{
constexpr auto fmt = BUT_FORMAT("");
EXPECT_EQ( 0u, fmt.expectedArguments() );
EXPECT_EQ( "", fmt.format() );
}
{
constexpr auto fmt = BUT_FORMAT("some test data");
EXPECT_EQ( 0u, fmt.expectedArguments() );
EXPECT_EQ( "some test data", fmt.format() );
}
}
TEST_F(ButFormat, OneArgument)
{
constexpr auto fmt = BUT_FORMAT("try $1 out");
EXPECT_EQ( 1u, fmt.expectedArguments() );
EXPECT_EQ( "try it out", fmt.format("it") );
}
TEST_F(ButFormat, MultipleArguments)
{
constexpr auto fmt = BUT_FORMAT("$2 $1");
EXPECT_EQ( 2u, fmt.expectedArguments() );
EXPECT_EQ( "bar foo", fmt.format("foo", "bar") );
EXPECT_EQ( "answer 42", fmt.format(42, "answer") );
}
/*
TEST_F(ButFormat, RepeatedArguments)
{
constexpr auto fmt = BUT_FORMAT("$1 $2 $1");
EXPECT_EQ( 2u, fmt.expectedArguments() );
EXPECT_EQ( "1 2 1", fmt.format(1,2) );
}
*/
/*
TEST_F(ButFormat, MultipleArgumentsMultipleStyles)
{
{
constexpr auto fmt = BUT_FORMAT("${1} $1");
EXPECT_EQ( 2u, fmt.expectedArguments() );
EXPECT_EQ( "x x", fmt.format("x") );
}
{
constexpr auto fmt = BUT_FORMAT("${V1}=${T1}");
EXPECT_EQ( 2u, fmt.expectedArguments() );
EXPECT_EQ( "int=42", fmt.format(42) );
}
{
constexpr auto fmt = BUT_FORMAT("${1#info} ${V1#text} ${T1#foo}");
EXPECT_EQ( 3u, fmt.expectedArguments() );
EXPECT_EQ( "x x std::string", fmt.format("x") );
}
}
*/
TEST_F(ButFormat, DenseFormats)
{
{
constexpr auto fmt = BUT_FORMAT("$$$1");
EXPECT_EQ( 1u, fmt.expectedArguments() );
EXPECT_EQ( "$kszy", fmt.format("kszy") );
}
{
constexpr auto fmt = BUT_FORMAT("$$x");
EXPECT_EQ( 0u, fmt.expectedArguments() );
EXPECT_EQ( "$x", fmt.format() );
}
}
}
<commit_msg>fixed tests - indexes shall be 0-based, not 1-based<commit_after>#include "gtest/gtest.h"
#include "format.hpp"
namespace
{
struct ButFormat: public testing::Test
{ };
TEST_F(ButFormat, SampleStrings)
{
{
constexpr auto fmt = BUT_FORMAT("");
EXPECT_EQ( 0u, fmt.expectedArguments() );
EXPECT_EQ( "", fmt.format() );
}
{
constexpr auto fmt = BUT_FORMAT("some test data");
EXPECT_EQ( 0u, fmt.expectedArguments() );
EXPECT_EQ( "some test data", fmt.format() );
}
}
TEST_F(ButFormat, OneArgument)
{
constexpr auto fmt = BUT_FORMAT("try $0 out");
EXPECT_EQ( 1u, fmt.expectedArguments() );
EXPECT_EQ( "try it out", fmt.format("it") );
}
TEST_F(ButFormat, MultipleArguments)
{
constexpr auto fmt = BUT_FORMAT("$1 $0");
EXPECT_EQ( 2u, fmt.expectedArguments() );
EXPECT_EQ( "bar foo", fmt.format("foo", "bar") );
EXPECT_EQ( "answer 42", fmt.format(42, "answer") );
}
/*
TEST_F(ButFormat, RepeatedArguments)
{
constexpr auto fmt = BUT_FORMAT("$0 $1 $0");
EXPECT_EQ( 2u, fmt.expectedArguments() );
EXPECT_EQ( "1 2 1", fmt.format(1,2) );
}
*/
/*
TEST_F(ButFormat, MultipleArgumentsMultipleStyles)
{
{
constexpr auto fmt = BUT_FORMAT("${0} $0");
EXPECT_EQ( 2u, fmt.expectedArguments() );
EXPECT_EQ( "x x", fmt.format("x") );
}
{
constexpr auto fmt = BUT_FORMAT("${V0}=${T0}");
EXPECT_EQ( 2u, fmt.expectedArguments() );
EXPECT_EQ( "int=42", fmt.format(42) );
}
{
constexpr auto fmt = BUT_FORMAT("${0#info} ${V0#text} ${T0#foo}");
EXPECT_EQ( 3u, fmt.expectedArguments() );
EXPECT_EQ( "x x std::string", fmt.format("x") );
}
}
*/
TEST_F(ButFormat, DenseFormats)
{
{
constexpr auto fmt = BUT_FORMAT("$$$0");
EXPECT_EQ( 1u, fmt.expectedArguments() );
EXPECT_EQ( "$kszy", fmt.format("kszy") );
}
{
constexpr auto fmt = BUT_FORMAT("$$x");
EXPECT_EQ( 0u, fmt.expectedArguments() );
EXPECT_EQ( "$x", fmt.format() );
}
}
}
<|endoftext|> |
<commit_before>//
// main.cpp
// Playground
//
// Created by Fu Lam Diep on 12.03.16.
// Copyright © 2016 Fu Lam Diep. All rights reserved.
//
#include <iostream>
#include <vector>
#include <glm/glm.hpp>
#include <ChaosCore/core.cpp>
#include "attrib.hpp"
#include "geom.hpp"
using namespace glm;
using namespace chaos;
int main(int argc, const char * argv[])
{
// tgeom<float> a = tgeom<float>();
// a.addValue(vec3());
// a.addValue(vec3(-1.0, -1.0, 2.0));
// info("%i", a.count());
return 0;
}
<commit_msg>[Update] Testing new stuff<commit_after>//
// main.cpp
// Playground
//
// Created by Fu Lam Diep on 12.03.16.
// Copyright © 2016 Fu Lam Diep. All rights reserved.
//
#include <iostream>
#include <vector>
#include <glm/glm.hpp>
#include <ChaosCore/core.cpp>
#include "attrib.hpp"
#include "geom.hpp"
template<typename T>
struct a
{
public:
virtual void getValue () const = 0;
virtual void count () const = 0;
};
template<typename T>
struct b : public virtual a<T>
{
public:
virtual void getValue () const {};
};
template<typename T>
struct c : public virtual a<T>
{
public:
virtual void count () const {}
};
template<typename T>
struct d : public virtual b<T>, public virtual c<T>
{
public:
};
int main(int argc, const char * argv[])
{
d<float> C = d<float>();
C.getValue();
// chaosgl::geom a = chaosgl::geom();
//// a.addValue(glm::vec3());
//// a.addValue(glm::vec3(-1.0, -1.0, 2.0));
// chaos::info("%i", a.count());
return 0;
}
<|endoftext|> |
<commit_before>#include "vast/event.h"
#include "vast/actor/source/test.h"
#include "vast/concept/parseable/core.h"
#include "vast/concept/parseable/numeric/real.h"
#include "vast/concept/parseable/string/char_class.h"
#include "vast/concept/parseable/vast/detail/to_schema.h"
#include "vast/util/assert.h"
#include "vast/util/meta.h"
#include "vast/util/hash/murmur.h"
namespace vast {
namespace source {
namespace {
result<distribution> make_distribution(type const& t) {
auto a = t.find_attribute(type::attribute::default_);
if (!a)
return {};
static auto num = parsers::real_opt_dot;
static auto param_parser = +parsers::alpha >> '(' >> num >> ',' >> num >> ')';
std::string name;
double p0, p1;
auto tie = std::tie(name, p0, p1);
if (!param_parser(a->value, tie))
return error{"invalid distribution specification"};
if (name == "uniform") {
if (is<type::integer>(t))
return {std::uniform_int_distribution<integer>{static_cast<integer>(p0),
static_cast<integer>(p1)}};
else if (is<type::boolean>(t) || is<type::count>(t) || is<type::string>(t))
return {std::uniform_int_distribution<count>{static_cast<count>(p0),
static_cast<count>(p1)}};
else
return {std::uniform_real_distribution<long double>{p0, p1}};
}
if (name == "normal")
return {std::normal_distribution<long double>{p0, p1}};
if (name == "pareto")
return {util::pareto_distribution<long double>{p0, p1}};
return error{"unknown distribution: ", name};
}
struct blueprint_factory {
blueprint_factory(test_state::blueprint& bp) : blueprint_{bp} {
}
template <typename T>
trial<void> operator()(T const& t) {
auto dist = make_distribution(t);
if (dist) {
blueprint_.data.push_back(type{t}.make());
blueprint_.dists.push_back(std::move(*dist));
return nothing;
}
if (dist.empty()) {
blueprint_.data.push_back(nil);
return nothing;
}
return dist.error();
}
trial<void> operator()(type::record const& r) {
for (auto& f : r.fields()) {
auto okay = visit(*this, f.type);
if (!okay)
return okay;
}
return nothing;
}
test_state::blueprint& blueprint_;
};
template <typename RNG>
struct sampler {
sampler(RNG& gen) : gen_{gen} {
}
template <typename D>
long double operator()(D& dist) {
return static_cast<long double>(dist(gen_));
}
RNG& gen_;
};
// Randomizes data according to a list of distributions and a source of
// randomness.
template <typename RNG>
struct randomizer {
randomizer(std::vector<distribution>& dists, RNG& gen)
: dists_{dists}, gen_{gen} {
}
template <typename T>
auto operator()(T&)
-> util::disable_if_t<
std::is_same<T, integer>::value
|| std::is_same<T, count>::value
|| std::is_same<T, real>::value
|| std::is_same<T, time::point>::value
|| std::is_same<T, time::duration>::value
> {
// For types we don't know how to randomize, we just crank the wheel.
sample();
}
void operator()(none) {
// Do nothing.
}
void operator()(boolean& b) {
lcg gen{static_cast<lcg::result_type>(sample())};
std::uniform_int_distribution<count> unif{0, 1};
b = unif(gen);
}
template <typename T>
auto operator()(T& x)
-> std::enable_if_t<
std::is_same<T, integer>::value
|| std::is_same<T, count>::value
|| std::is_same<T, real>::value
> {
x = static_cast<T>(sample());
}
template <typename T>
auto operator()(T& x)
-> std::enable_if_t<
std::is_same<T, time::point>::value
|| std::is_same<T, time::duration>::value
> {
x += time::fractional(sample());
}
void operator()(std::string& str) {
lcg gen{static_cast<lcg::result_type>(sample())};
std::uniform_int_distribution<size_t> unif_size{0, 256};
std::uniform_int_distribution<char> unif_char{32, 126}; // Printable ASCII
str.resize(unif_size(gen));
for (auto& c : str)
c = unif_char(gen);
}
void operator()(address& addr) {
// We hash the generated sample into a 128-bit digest to spread out the
// bits over the entire domain of an IPv6 address.
auto x = sample();
uint32_t bytes[4];
util::detail::murmur3<128>(&x, sizeof(x), 0, bytes);
// P[ip == v6] = 0.5
std::uniform_int_distribution<uint8_t> unif{0, 1};
auto version = unif(gen_) ? address::ipv4 : address::ipv6;
addr = {bytes, version, address::network};
}
void operator()(subnet& sn) {
address addr;
(*this)(addr);
std::uniform_int_distribution<uint8_t> unif{0, 128};
sn = {std::move(addr), unif(gen_)};
}
void operator()(port& p) {
using port_type = std::underlying_type_t<port::port_type>;
std::uniform_int_distribution<port_type> unif{0, 3};
p.number(static_cast<port::number_type>(sample()));
p.type(static_cast<port::port_type>(unif(gen_)));
}
void operator()(record& r) {
for (auto& d : r)
visit(*this, d);
}
auto sample() {
return visit(sampler<RNG>{gen_}, dists_[i++]);
}
std::vector<distribution>& dists_;
size_t i = 0;
RNG& gen_;
};
} // namespace <anonymous>
test_state::test_state(local_actor* self)
: base_state{self, "test-source"},
generator_{std::random_device{}()} {
VAST_ASSERT(num_events_ > 0);
static auto builtin_schema = R"schema(
type test = record
{
b: bool &default="uniform(0,1)",
i: int &default="uniform(-42000,1337)",
c: count &default="pareto(0,1)",
r: real &default="normal(0,1)",
s: string &default="uniform(0,100)",
t: time &default="uniform(0,10)",
d: duration &default="uniform(100,200)",
a: addr &default="uniform(0,2000000)",
s: subnet &default="uniform(1000,2000)",
p: port &default="uniform(1,65384)"
}
)schema";
auto t = detail::to_schema(builtin_schema);
VAST_ASSERT(t);
schema(*t);
}
schema test_state::schema() {
return schema_;
}
void test_state::schema(vast::schema const& sch) {
VAST_ASSERT(!sch.empty());
schema_ = sch;
next_ = schema_.begin();
for (auto& t : schema_) {
blueprint bp;
auto attempt = visit(blueprint_factory{bp}, t);
if (!attempt) {
VAST_ERROR(this, "failed to generate blueprint:", attempt.error());
self->quit(exit::error);
return;
}
if (auto r = get<type::record>(t)) {
auto u = bp.data.unflatten(*r);
if (!u) {
VAST_ERROR(this, "failed to unflatten record:", u.error());
self->quit(exit::error);
return;
}
bp.data = std::move(*u);
}
VAST_ASSERT(!bp.data.empty());
blueprints_[t] = std::move(bp);
}
}
result<event> test_state::extract() {
VAST_ASSERT(next_ != schema_.end());
// Generate random data.
auto& bp = blueprints_[*next_];
randomizer<std::mt19937_64>{bp.dists, generator_}(bp.data);
auto d = is<type::record>(*next_) ? data{bp.data} : bp.data[0];
// Fill a new event.
event e{{std::move(d), *next_}};
e.timestamp(time::now());
e.id(id_++);
// Advance to next type in schema.
if (++next_ == schema_.end())
next_ = schema_.begin();
VAST_ASSERT(num_events_ > 0);
if (--num_events_ == 0)
done_ = true;
return std::move(e);
}
behavior test(stateful_actor<test_state>* self, event_id id, uint64_t events) {
self->state.id_ = id;
self->state.num_events_ = events;
return base(self);
}
} // namespace source
} // namespace vast
<commit_msg>Move assertion to correct location<commit_after>#include "vast/event.h"
#include "vast/actor/source/test.h"
#include "vast/concept/parseable/core.h"
#include "vast/concept/parseable/numeric/real.h"
#include "vast/concept/parseable/string/char_class.h"
#include "vast/concept/parseable/vast/detail/to_schema.h"
#include "vast/util/assert.h"
#include "vast/util/meta.h"
#include "vast/util/hash/murmur.h"
namespace vast {
namespace source {
namespace {
result<distribution> make_distribution(type const& t) {
auto a = t.find_attribute(type::attribute::default_);
if (!a)
return {};
static auto num = parsers::real_opt_dot;
static auto param_parser = +parsers::alpha >> '(' >> num >> ',' >> num >> ')';
std::string name;
double p0, p1;
auto tie = std::tie(name, p0, p1);
if (!param_parser(a->value, tie))
return error{"invalid distribution specification"};
if (name == "uniform") {
if (is<type::integer>(t))
return {std::uniform_int_distribution<integer>{static_cast<integer>(p0),
static_cast<integer>(p1)}};
else if (is<type::boolean>(t) || is<type::count>(t) || is<type::string>(t))
return {std::uniform_int_distribution<count>{static_cast<count>(p0),
static_cast<count>(p1)}};
else
return {std::uniform_real_distribution<long double>{p0, p1}};
}
if (name == "normal")
return {std::normal_distribution<long double>{p0, p1}};
if (name == "pareto")
return {util::pareto_distribution<long double>{p0, p1}};
return error{"unknown distribution: ", name};
}
struct blueprint_factory {
blueprint_factory(test_state::blueprint& bp) : blueprint_{bp} {
}
template <typename T>
trial<void> operator()(T const& t) {
auto dist = make_distribution(t);
if (dist) {
blueprint_.data.push_back(type{t}.make());
blueprint_.dists.push_back(std::move(*dist));
return nothing;
}
if (dist.empty()) {
blueprint_.data.push_back(nil);
return nothing;
}
return dist.error();
}
trial<void> operator()(type::record const& r) {
for (auto& f : r.fields()) {
auto okay = visit(*this, f.type);
if (!okay)
return okay;
}
return nothing;
}
test_state::blueprint& blueprint_;
};
template <typename RNG>
struct sampler {
sampler(RNG& gen) : gen_{gen} {
}
template <typename D>
long double operator()(D& dist) {
return static_cast<long double>(dist(gen_));
}
RNG& gen_;
};
// Randomizes data according to a list of distributions and a source of
// randomness.
template <typename RNG>
struct randomizer {
randomizer(std::vector<distribution>& dists, RNG& gen)
: dists_{dists}, gen_{gen} {
}
template <typename T>
auto operator()(T&)
-> util::disable_if_t<
std::is_same<T, integer>::value
|| std::is_same<T, count>::value
|| std::is_same<T, real>::value
|| std::is_same<T, time::point>::value
|| std::is_same<T, time::duration>::value
> {
// For types we don't know how to randomize, we just crank the wheel.
sample();
}
void operator()(none) {
// Do nothing.
}
void operator()(boolean& b) {
lcg gen{static_cast<lcg::result_type>(sample())};
std::uniform_int_distribution<count> unif{0, 1};
b = unif(gen);
}
template <typename T>
auto operator()(T& x)
-> std::enable_if_t<
std::is_same<T, integer>::value
|| std::is_same<T, count>::value
|| std::is_same<T, real>::value
> {
x = static_cast<T>(sample());
}
template <typename T>
auto operator()(T& x)
-> std::enable_if_t<
std::is_same<T, time::point>::value
|| std::is_same<T, time::duration>::value
> {
x += time::fractional(sample());
}
void operator()(std::string& str) {
lcg gen{static_cast<lcg::result_type>(sample())};
std::uniform_int_distribution<size_t> unif_size{0, 256};
std::uniform_int_distribution<char> unif_char{32, 126}; // Printable ASCII
str.resize(unif_size(gen));
for (auto& c : str)
c = unif_char(gen);
}
void operator()(address& addr) {
// We hash the generated sample into a 128-bit digest to spread out the
// bits over the entire domain of an IPv6 address.
auto x = sample();
uint32_t bytes[4];
util::detail::murmur3<128>(&x, sizeof(x), 0, bytes);
// P[ip == v6] = 0.5
std::uniform_int_distribution<uint8_t> unif{0, 1};
auto version = unif(gen_) ? address::ipv4 : address::ipv6;
addr = {bytes, version, address::network};
}
void operator()(subnet& sn) {
address addr;
(*this)(addr);
std::uniform_int_distribution<uint8_t> unif{0, 128};
sn = {std::move(addr), unif(gen_)};
}
void operator()(port& p) {
using port_type = std::underlying_type_t<port::port_type>;
std::uniform_int_distribution<port_type> unif{0, 3};
p.number(static_cast<port::number_type>(sample()));
p.type(static_cast<port::port_type>(unif(gen_)));
}
void operator()(record& r) {
for (auto& d : r)
visit(*this, d);
}
auto sample() {
return visit(sampler<RNG>{gen_}, dists_[i++]);
}
std::vector<distribution>& dists_;
size_t i = 0;
RNG& gen_;
};
} // namespace <anonymous>
test_state::test_state(local_actor* self)
: base_state{self, "test-source"},
generator_{std::random_device{}()} {
static auto builtin_schema = R"schema(
type test = record
{
b: bool &default="uniform(0,1)",
i: int &default="uniform(-42000,1337)",
c: count &default="pareto(0,1)",
r: real &default="normal(0,1)",
s: string &default="uniform(0,100)",
t: time &default="uniform(0,10)",
d: duration &default="uniform(100,200)",
a: addr &default="uniform(0,2000000)",
s: subnet &default="uniform(1000,2000)",
p: port &default="uniform(1,65384)"
}
)schema";
auto t = detail::to_schema(builtin_schema);
VAST_ASSERT(t);
schema(*t);
}
schema test_state::schema() {
return schema_;
}
void test_state::schema(vast::schema const& sch) {
VAST_ASSERT(!sch.empty());
schema_ = sch;
next_ = schema_.begin();
for (auto& t : schema_) {
blueprint bp;
auto attempt = visit(blueprint_factory{bp}, t);
if (!attempt) {
VAST_ERROR(this, "failed to generate blueprint:", attempt.error());
self->quit(exit::error);
return;
}
if (auto r = get<type::record>(t)) {
auto u = bp.data.unflatten(*r);
if (!u) {
VAST_ERROR(this, "failed to unflatten record:", u.error());
self->quit(exit::error);
return;
}
bp.data = std::move(*u);
}
VAST_ASSERT(!bp.data.empty());
blueprints_[t] = std::move(bp);
}
}
result<event> test_state::extract() {
VAST_ASSERT(next_ != schema_.end());
// Generate random data.
auto& bp = blueprints_[*next_];
randomizer<std::mt19937_64>{bp.dists, generator_}(bp.data);
auto d = is<type::record>(*next_) ? data{bp.data} : bp.data[0];
// Fill a new event.
event e{{std::move(d), *next_}};
e.timestamp(time::now());
e.id(id_++);
// Advance to next type in schema.
if (++next_ == schema_.end())
next_ = schema_.begin();
VAST_ASSERT(num_events_ > 0);
if (--num_events_ == 0)
done_ = true;
return std::move(e);
}
behavior test(stateful_actor<test_state>* self, event_id id, uint64_t events) {
VAST_ASSERT(events > 0);
self->state.id_ = id;
self->state.num_events_ = events;
return base(self);
}
} // namespace source
} // namespace vast
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "ParseNode.hpp"
#include "Context.hpp"
#include "StringPool.hpp"
#include "AssemblyFileWriter.hpp"
using std::list;
using std::vector;
using namespace eddic;
ParseNode::~ParseNode() {
for (NodeIterator it = childs.begin(); it != childs.end(); ++it) {
delete *it;
}
for (TrashIterator it = trash.begin(); it != trash.end(); ++it) {
delete *it;
}
}
void ParseNode::write(AssemblyFileWriter& writer) {
NodeIterator it = childs.begin();
NodeIterator end = childs.end();
for ( ; it != end; ++it) {
(*it)->write(writer);
}
}
void ParseNode::checkVariables() {
NodeIterator it = childs.begin();
NodeIterator end = childs.end();
for ( ; it != end; ++it) {
(*it)->checkVariables();
}
}
void ParseNode::checkStrings(StringPool& pool) {
NodeIterator it = childs.begin();
NodeIterator end = childs.end();
for ( ; it != end; ++it) {
(*it)->checkStrings(pool);
}
}
void ParseNode::optimize() {
NodeIterator it = childs.begin();
NodeIterator end = childs.end();
for ( ; it != end; ++it) {
(*it)->optimize();
}
}
void ParseNode::addLast(ParseNode* node) {
childs.push_back(node);
node->parent = this;
}
void ParseNode::addFirst(ParseNode* node) {
childs.push_front(node);
node->parent = this;
}
void ParseNode::replace(ParseNode* old, ParseNode* node) {
list<ParseNode*>::iterator it = childs.begin();
NodeIterator end = childs.end();
trash.push_back(old);
old->parent = NULL;
node->parent = this;
for ( ; it != end; ++it) {
if (*it == old) {
*it = node;
return;
}
}
}
void ParseNode::remove(ParseNode* node) {
childs.remove(node);
trash.push_back(node);
node->parent = NULL;
}
NodeIterator ParseNode::begin() {
return childs.begin();
}
NodeIterator ParseNode::end() {
return childs.end();
}
<commit_msg>Refactorings<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "ParseNode.hpp"
#include "Context.hpp"
#include "StringPool.hpp"
#include "AssemblyFileWriter.hpp"
using std::list;
using std::vector;
using namespace eddic;
ParseNode::~ParseNode() {
for (NodeIterator it = begin(); it != end(); ++it) {
delete *it;
}
for (TrashIterator it = trash.begin(); it != trash.end(); ++it) {
delete *it;
}
}
void ParseNode::write(AssemblyFileWriter& writer) {
for (NodeIterator it = begin(); it != end(); ++it) {
(*it)->write(writer);
}
}
void ParseNode::checkVariables() {
for (NodeIterator it = begin(); it != end(); ++it) {
(*it)->checkVariables();
}
}
void ParseNode::checkStrings(StringPool& pool) {
for (NodeIterator it = begin(); it != end(); ++it) {
(*it)->checkStrings(pool);
}
}
void ParseNode::optimize() {
for (NodeIterator it = begin(); it != end(); ++it) {
(*it)->optimize();
}
}
void ParseNode::addLast(ParseNode* node) {
childs.push_back(node);
node->parent = this;
}
void ParseNode::addFirst(ParseNode* node) {
childs.push_front(node);
node->parent = this;
}
void ParseNode::replace(ParseNode* old, ParseNode* node) {
list<ParseNode*>::iterator it = childs.begin();
trash.push_back(old);
old->parent = NULL;
node->parent = this;
for ( ; it != end(); ++it) {
if (*it == old) {
*it = node;
return;
}
}
}
void ParseNode::remove(ParseNode* node) {
childs.remove(node);
trash.push_back(node);
node->parent = NULL;
}
NodeIterator ParseNode::begin() {
return childs.begin();
}
NodeIterator ParseNode::end() {
return childs.end();
}
<|endoftext|> |
<commit_before>// Copyright (C) 2012 Rhys Ulerich
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "ar.hpp"
#include <algorithm>
#include <cstdlib>
#include <iterator>
#include <limits>
#include <list>
#include <vector>
#include <octave/oct.h>
#include <octave/oct-map.h>
#include <octave/ov-struct.h>
#include <octave/Cell.h>
/** @file
* A GNU Octave function finding correlation matrices from arsel(...) output.
*/
// Compile-time defaults in the code also appearing in the help message
#define DEFAULT_ABSRHO true
#define STRINGIFY(x) STRINGIFY_HELPER(x)
#define STRINGIFY_HELPER(x) #x
DEFUN_DLD(
arcov, args, nargout,
"\tC = arcov (arsel1, arsel2, absrho)\n"
"\tC = arcov (arsel1, absrho)\n"
"\tFind a correlation matrix for signal collections processed by arsel.\n"
"\t\n"
"\tUse raw samples and information computed by arsel(...) along with\n"
"\tar::decorrelation_time to build an effective covariance matrix for\n"
"\ttwo vectors of signals. Input arsel1 should have been produced\n"
"\tby 'arsel1 = arsel(d1, ...)' and similarly for input arsel2.\n"
"\tThe signal sources d1 and d2 must have had the same dimensions.\n"
"\tA structure is returned which each field contains a matrix indexed by\n"
"\tthe corresponding row in d1 and d2 or a single, globally descriptive\n"
"\tscalar.\n"
"\t\n"
"\tThe number of samples in d1 and d2 (i.e. the number of rows) is\n"
"\treturned in field 'N'. Given the observed autocorrelation structure,\n"
"\ta decorrelation time 'T0' is computed by ar::decorrelation_time\n"
"\tand used to estimate the effective signal covariance 'eff_cov'.\n"
"\tThe number of effectively independent samples is returned in 'eff_N'.\n"
"\tThe absolute value of the autocorrelation function will be used in\n"
"\tcomputing the decorrelation times whenever absrho is true.\n"
"\t\n"
"\tWhen only d1 and arsel1 are provided, the autocovarance is found.\n"
"\tWhen omitted, absrho defaults to " STRINGIFY(DEFAULT_ABSRHO) ".\n"
)
{
// Process incoming positional arguments
bool argsok = false;
bool absrho = DEFAULT_ABSRHO;
Octave_map arsel1, arsel2;
switch (args.length())
{
case 3: absrho = args(2).bool_value();
arsel2 = args(1).map_value();
arsel1 = args(0).map_value();
argsok = !error_state;
break;
case 2: if (!args(1).is_bool_scalar()) // Disambiguate cases
{
arsel2 = args(1).map_value();
}
else
{
absrho = args(1).bool_value();
arsel2 = args(0).map_value();
}
arsel1 = args(0).map_value();
argsok = !error_state;
break;
case 1: arsel2 = args(0).map_value();
arsel1 = args(0).map_value();
argsok = !error_state;
break;
default: argsok = !error_state;
}
if (!argsok)
{
error("Invalid call to arcov. Correct usage is: ");
print_usage();
return octave_value();
}
// Unpack required fields from arsel1 into typesafe instances
const Cell AR1 = arsel1.contents("AR" )(0).cell_value();
const Matrix d1 = arsel1.contents("data" )(0).matrix_value();
const Cell autocor1 = arsel1.contents("autocor")(0).cell_value();
const ColumnVector gain1 = arsel1.contents("gain" )(0).column_vector_value();
const bool submean1 = arsel1.contents("submean")(0).bool_value();
// Unpack required fields from arsel1 into typesafe instances
const Cell AR2 = arsel2.contents("AR" )(0).cell_value();
const Matrix d2 = arsel2.contents("data" )(0).matrix_value();
const Cell autocor2 = arsel2.contents("autocor")(0).cell_value();
const ColumnVector gain2 = arsel2.contents("gain" )(0).column_vector_value();
const bool submean2 = arsel2.contents("submean")(0).bool_value();
// Check that the unpack logic worked as expected
if (error_state)
{
error("arcov: arsel1 or arsel2 lacked fields provided by arsel(...)");
return octave_value();
}
// Ensure data sets d1 and d2 are conformant
if (!(d1.dims() == d2.dims()))
{
error("arcov: arsel1.data and arsel2.data must have same dimensions");
return octave_value();
}
const octave_idx_type M = d1.rows(); // Number of signals
const octave_idx_type N = d1.cols(); // Samples per signal
// Prepare storage to be returned to the caller
Matrix _T0 (dim_vector(M, M));
Matrix _eff_N (dim_vector(M, M));
Matrix _eff_cov(dim_vector(M, M));
// Compute upper triangular portion of _T0, _eff_N, and _eff_cov
// and store the result into both the upper and lower triangular storage
for (octave_idx_type j = 0; j < M; ++j)
{
// Prepare iterators into the raw data for signal d1(j)
ar::strided_adaptor<const double*> s1_begin(d1.data() + j + 0*M, M);
ar::strided_adaptor<const double*> s1_end (d1.data() + j + N*M, M);
// Prepare an iterator over the autocorrelation function for d1(j)
const RowVector AR1j = AR1(j).row_vector_value();
ar::predictor<double> p1 = ar::autocorrelation(
AR1j.fortran_vec() + 1, AR1j.fortran_vec() + AR1j.length(),
gain1(j), autocor1(j).row_vector_value().fortran_vec());
for (octave_idx_type i = j; i < M; ++i)
{
// Prepare an iterator over the autocorrelation function for d2(i)
const RowVector AR2i = AR2 (i).row_vector_value();
ar::predictor<double> p2 = ar::autocorrelation(
AR2i.fortran_vec() + 1, AR2i.fortran_vec() + AR2i.length(),
gain2(i), autocor2(i).row_vector_value().fortran_vec());
// Compute the decorrelation time of d1(j) against d2(i)
const double T0 = ar::decorrelation_time(N, p1, p2, absrho);
// Compute the effective covariance given the decorrelation time
ar::strided_adaptor<const double*> s2_begin(d2.data() + i + 0*M, M);
double mu1, mu2, ncovar;
welford_ncovariance(s1_begin, s1_end, s2_begin, mu1, mu2, ncovar);
if (!submean1 && !submean2) ncovar += N*mu1*mu2;
const double eff_cov = ncovar / (N - T0);
// Save the findings into the (symmetric) result storage
_T0 (i, j) = _T0 (j, i) = T0;
_eff_N (i, j) = _eff_N (j, i) = N / T0;
_eff_cov(i, j) = _eff_cov(j, i) = eff_cov;
// Permit user to interrupt the computations at this time
OCTAVE_QUIT;
}
}
// Provide no results whenever an error was detected
if (error_state)
{
warning("arcov: error detected; no results returned");
return octave_value_list();
}
// Build map containing return fields
Octave_map retval;
retval.assign("absrho", octave_value(absrho));
retval.assign("eff_cov", _eff_cov);
retval.assign("eff_N", _eff_N);
retval.assign("T0", _T0);
return octave_value_list(retval);
}
<commit_msg>Update help message formatting<commit_after>// Copyright (C) 2012 Rhys Ulerich
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "ar.hpp"
#include <algorithm>
#include <cstdlib>
#include <iterator>
#include <limits>
#include <list>
#include <vector>
#include <octave/oct.h>
#include <octave/oct-map.h>
#include <octave/ov-struct.h>
#include <octave/Cell.h>
/** @file
* A GNU Octave function finding correlation matrices from arsel(...) output.
*/
// Compile-time defaults in the code also appearing in the help message
#define DEFAULT_ABSRHO true
#define STRINGIFY(x) STRINGIFY_HELPER(x)
#define STRINGIFY_HELPER(x) #x
DEFUN_DLD(arcov, args, nargout,
" C = arcov (arsel1, arsel2, absrho)\n"
" C = arcov (arsel1, absrho)\n"
" Find a correlation matrix for signal collections processed by arsel.\n"
"\n"
" Use raw samples and information computed by arsel(...) along with\n"
" ar::decorrelation_time to build an effective covariance matrix for two\n"
" vectors of signals. Input arsel1 should have been produced by 'arsel1\n"
" = arsel(d1, ...)' and similarly for input arsel2. The signal sources\n"
" d1 and d2 must have had the same dimensions. A structure is returned\n"
" which each field contains a matrix indexed by the corresponding row\n"
" in d1 and d2 or a single, globally descriptive scalar.\n"
"\n"
" The number of samples in d1 and d2 (i.e. the number of rows) is\n"
" returned in field 'N'. Given the observed autocorrelation structure,\n"
" a decorrelation time 'T0' is computed by ar::decorrelation_time and used\n"
" to estimate the effective signal covariance 'eff_cov'. The number of\n"
" effectively independent samples is returned in 'eff_N'. The absolute\n"
" value of the autocorrelation function will be used in computing the\n"
" decorrelation times whenever absrho is true.\n"
"\n"
" When only d1 and arsel1 are provided, the autocovarance is found.\n"
" When omitted, absrho defaults to " STRINGIFY(DEFAULT_ABSRHO) ".\n"
)
{
// Process incoming positional arguments
bool argsok = false;
bool absrho = DEFAULT_ABSRHO;
Octave_map arsel1, arsel2;
switch (args.length())
{
case 3: absrho = args(2).bool_value();
arsel2 = args(1).map_value();
arsel1 = args(0).map_value();
argsok = !error_state;
break;
case 2: if (!args(1).is_bool_scalar()) // Disambiguate cases
{
arsel2 = args(1).map_value();
}
else
{
absrho = args(1).bool_value();
arsel2 = args(0).map_value();
}
arsel1 = args(0).map_value();
argsok = !error_state;
break;
case 1: arsel2 = args(0).map_value();
arsel1 = args(0).map_value();
argsok = !error_state;
break;
default: argsok = !error_state;
}
if (!argsok)
{
error("Invalid call to arcov. Correct usage is: ");
print_usage();
return octave_value();
}
// Unpack required fields from arsel1 into typesafe instances
const Cell AR1 = arsel1.contents("AR" )(0).cell_value();
const Matrix d1 = arsel1.contents("data" )(0).matrix_value();
const Cell autocor1 = arsel1.contents("autocor")(0).cell_value();
const ColumnVector gain1 = arsel1.contents("gain" )(0).column_vector_value();
const bool submean1 = arsel1.contents("submean")(0).bool_value();
// Unpack required fields from arsel1 into typesafe instances
const Cell AR2 = arsel2.contents("AR" )(0).cell_value();
const Matrix d2 = arsel2.contents("data" )(0).matrix_value();
const Cell autocor2 = arsel2.contents("autocor")(0).cell_value();
const ColumnVector gain2 = arsel2.contents("gain" )(0).column_vector_value();
const bool submean2 = arsel2.contents("submean")(0).bool_value();
// Check that the unpack logic worked as expected
if (error_state)
{
error("arcov: arsel1 or arsel2 lacked fields provided by arsel(...)");
return octave_value();
}
// Ensure data sets d1 and d2 are conformant
if (!(d1.dims() == d2.dims()))
{
error("arcov: arsel1.data and arsel2.data must have same dimensions");
return octave_value();
}
const octave_idx_type M = d1.rows(); // Number of signals
const octave_idx_type N = d1.cols(); // Samples per signal
// Prepare storage to be returned to the caller
Matrix _T0 (dim_vector(M, M));
Matrix _eff_N (dim_vector(M, M));
Matrix _eff_cov(dim_vector(M, M));
// Compute upper triangular portion of _T0, _eff_N, and _eff_cov
// and store the result into both the upper and lower triangular storage
for (octave_idx_type j = 0; j < M; ++j)
{
// Prepare iterators into the raw data for signal d1(j)
ar::strided_adaptor<const double*> s1_begin(d1.data() + j + 0*M, M);
ar::strided_adaptor<const double*> s1_end (d1.data() + j + N*M, M);
// Prepare an iterator over the autocorrelation function for d1(j)
const RowVector AR1j = AR1(j).row_vector_value();
ar::predictor<double> p1 = ar::autocorrelation(
AR1j.fortran_vec() + 1, AR1j.fortran_vec() + AR1j.length(),
gain1(j), autocor1(j).row_vector_value().fortran_vec());
for (octave_idx_type i = j; i < M; ++i)
{
// Prepare an iterator over the autocorrelation function for d2(i)
const RowVector AR2i = AR2 (i).row_vector_value();
ar::predictor<double> p2 = ar::autocorrelation(
AR2i.fortran_vec() + 1, AR2i.fortran_vec() + AR2i.length(),
gain2(i), autocor2(i).row_vector_value().fortran_vec());
// Compute the decorrelation time of d1(j) against d2(i)
const double T0 = ar::decorrelation_time(N, p1, p2, absrho);
// Compute the effective covariance given the decorrelation time
ar::strided_adaptor<const double*> s2_begin(d2.data() + i + 0*M, M);
double mu1, mu2, ncovar;
welford_ncovariance(s1_begin, s1_end, s2_begin, mu1, mu2, ncovar);
if (!submean1 && !submean2) ncovar += N*mu1*mu2;
const double eff_cov = ncovar / (N - T0);
// Save the findings into the (symmetric) result storage
_T0 (i, j) = _T0 (j, i) = T0;
_eff_N (i, j) = _eff_N (j, i) = N / T0;
_eff_cov(i, j) = _eff_cov(j, i) = eff_cov;
// Permit user to interrupt the computations at this time
OCTAVE_QUIT;
}
}
// Provide no results whenever an error was detected
if (error_state)
{
warning("arcov: error detected; no results returned");
return octave_value_list();
}
// Build map containing return fields
Octave_map retval;
retval.assign("absrho", octave_value(absrho));
retval.assign("eff_cov", _eff_cov);
retval.assign("eff_N", _eff_N);
retval.assign("T0", _T0);
return octave_value_list(retval);
}
<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2013
\file goto_line_dialog.cpp
\author ([email protected])
\date 04.01.2013
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "app/rdo_studio_mfc/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "app/rdo_studio_mfc/src/dialog/goto_line_dialog.h"
// --------------------------------------------------------------------------------
GoToLineDialog::GoToLineDialog(PTR(QWidget) pParent, int _line, int lineCount)
: QDialog(pParent),
m_line(_line)
{
setupUi(this);
layout()->setSizeConstraint(QLayout::SetFixedSize);
label->setText(label->text() + " (1 - " + QString::number(lineCount) + ")");
lineEdit->setValidator(new QIntValidator(this));
connect(buttonOk, SIGNAL(clicked()), this, SLOT(okButtonClicked()));
connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
}
void GoToLineDialog::okButtonClicked()
{
m_line = lineEdit->text().toInt();
done(Accepted);
}
int GoToLineDialog::getLine() const
{
return m_line;
}<commit_msg> - теперь в поле отображается текущий номер строки<commit_after>/*!
\copyright (c) RDO-Team, 2013
\file goto_line_dialog.cpp
\author ([email protected])
\date 04.01.2013
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "app/rdo_studio_mfc/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "app/rdo_studio_mfc/src/dialog/goto_line_dialog.h"
// --------------------------------------------------------------------------------
GoToLineDialog::GoToLineDialog(PTR(QWidget) pParent, int _line, int lineCount)
: QDialog(pParent),
m_line(_line)
{
setupUi(this);
layout()->setSizeConstraint(QLayout::SetFixedSize);
label->setText(label->text() + " (1 - " + QString::number(lineCount) + ")");
lineEdit->setValidator(new QIntValidator(this));
lineEdit->setText(QString::number(m_line));
connect(buttonOk, SIGNAL(clicked()), this, SLOT(okButtonClicked()));
connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
}
void GoToLineDialog::okButtonClicked()
{
m_line = lineEdit->text().toInt();
done(Accepted);
}
int GoToLineDialog::getLine() const
{
return m_line;
}<|endoftext|> |
<commit_before>/*
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
extern "C" {
#include "libjsonnet.h"
}
#define JSONNET_VERSION "v0.6.0-beta"
struct ImportCallbackContext {
JsonnetVm *vm;
std::vector<std::string> *jpaths;
};
enum ImportStatus {
IMPORT_STATUS_OK,
IMPORT_STATUS_FILE_NOT_FOUND,
IMPORT_STATUS_IO_ERROR
};
static enum ImportStatus try_path(const std::string &dir, const std::string &rel,
std::string &content)
{
std::string abs_path;
// It is possible that rel is actually absolute.
if (rel.length() > 0 && rel[0] == '/') {
abs_path = rel;
} else {
abs_path = dir + rel;
}
std::ifstream f;
f.open(abs_path.c_str());
if (!f.good()) return IMPORT_STATUS_FILE_NOT_FOUND;
content.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
if (!f.good()) return IMPORT_STATUS_IO_ERROR;
return IMPORT_STATUS_OK;
}
static char *import_callback (void *ctx_, const char *dir, const char *file, int *success)
{
const auto &ctx = *static_cast<ImportCallbackContext*>(ctx_);
std::string input;
ImportStatus status = try_path(dir, file, input);
std::vector<std::string> jpaths(*ctx.jpaths);
// If not found, try library search path.
while (status == IMPORT_STATUS_FILE_NOT_FOUND) {
if (jpaths.size() == 0) {
*success = 0;
const char *err = "No match locally or in the Jsonnet library path.";
char *r = jsonnet_realloc(ctx.vm, nullptr, std::strlen(err) + 1);
std::strcpy(r, err);
return r;
}
status = try_path(jpaths.back(), file, input);
jpaths.pop_back();
}
if (status == IMPORT_STATUS_IO_ERROR) {
*success = 0;
const char *err = std::strerror(errno);
char *r = jsonnet_realloc(ctx.vm, nullptr, std::strlen(err) + 1);
std::strcpy(r, err);
return r;
} else {
assert(status == IMPORT_STATUS_OK);
*success = 1;
char *r = jsonnet_realloc(ctx.vm, nullptr, input.length() + 1);
std::strcpy(r, input.c_str());
return r;
}
}
std::string next_arg(unsigned &i, const std::vector<std::string> &args)
{
i++;
if (i >= args.size()) {
std::cerr << "Expected another commandline argument." << std::endl;
exit(EXIT_FAILURE);
}
return args[i];
}
/** Collect commandline args into a vector of strings, and expand -foo to -f -o -o. */
std::vector<std::string> simplify_args(int argc, const char **argv)
{
std::vector<std::string> r;
for (int i=1 ; i<argc ; ++i) {
std::string arg = argv[i];
if (arg == "--") {
// Add this arg and all remaining ones without simplification.
r.push_back(arg);
while ((++i) < argc)
r.push_back(argv[i]);
break;
}
// Check if it is of the form -abc and convert to -a -b -c
if (arg.length() > 2 && arg[0] == '-' && arg[1] != '-') {
for (unsigned j=1 ; j<arg.length() ; ++j) {
r.push_back("-" + arg.substr(j,1));
}
} else {
r.push_back(arg);
}
}
return r;
}
void version(std::ostream &o)
{
o << "Jsonnet commandline interpreter " << JSONNET_VERSION << std::endl;
}
void usage(std::ostream &o)
{
version(o);
o << "Usage:\n";
o << "jsonnet {<option>} [<filename>]\n";
o << "where <filename> defaults to - (stdin)\n";
o << "and <option> can be:\n";
o << " -h / --help This message\n";
o << " -e / --exec Treat filename as code (requires explicit filename)\n";
o << " -J / --jpath <dir> Specify an additional library search dir\n";
o << " -V / --var <var>=<val> Specify an 'external' var to the given value\n";
o << " -E / --env <var> Bring in an environment var as an 'external' var\n";
o << " -m / --multi Write multiple files, list files on stdout\n";
o << " -S / --string Expect a string, manifest as plain text\n";
o << " -s / --max-stack <n> Number of allowed stack frames\n";
o << " -t / --max-trace <n> Max length of stack trace before cropping\n";
o << " --gc-min-objects <n> Do not run garbage collector until this many\n";
o << " --gc-growth-trigger <n> Run garbage collector after this amount of object growth\n";
o << " --debug-ast Unparse the parsed AST without executing it\n\n";
o << " --version Print version\n";
o << "Multichar options are expanded e.g. -abc becomes -a -b -c.\n";
o << "The -- option suppresses option processing for subsequent arguments.\n";
o << "Note that since jsonnet programs can begin with -, it is advised to\n";
o << "use -- with -e if the program is unknown, e.g. jsonnet -e -- \"$CODE\".";
o << std::endl;
}
long strtol_check(const std::string &str)
{
const char *arg = str.c_str();
char *ep;
long r = std::strtol(arg, &ep, 10);
if (*ep != '\0' || *arg == '\0') {
std::cerr << "ERROR: Invalid integer \"" << arg << "\"\n" << std::endl;
usage(std::cerr);
exit(EXIT_FAILURE);
}
return r;
}
int main(int argc, const char **argv)
{
std::vector<std::string> jpaths;
jpaths.emplace_back("/usr/share/" JSONNET_VERSION "/");
jpaths.emplace_back("/usr/local/share/" JSONNET_VERSION "/");
JsonnetVm *vm = jsonnet_make();
std::string filename = "-";
bool filename_is_code = false;
bool multi = false;
auto args = simplify_args(argc, argv);
std::vector<std::string> remaining_args;
for (unsigned i=0 ; i<args.size() ; ++i) {
const std::string &arg = args[i];
if (arg == "-h" || arg == "--help") {
usage(std::cout);
return EXIT_SUCCESS;
} else if (arg == "-v" || arg == "--version") {
version(std::cout);
return EXIT_SUCCESS;
} else if (arg == "-s" || arg == "--max-stack") {
long l = strtol_check(next_arg(i, args));
if (l < 1) {
std::cerr << "ERROR: Invalid --max-stack value: " << l << "\n" << std::endl;
usage(std::cerr);
return EXIT_FAILURE;
}
jsonnet_max_stack(vm, l);
} else if (arg == "-J" || arg == "--jpath") {
std::string dir = next_arg(i, args);
if (dir.length() == 0) {
std::cerr << "ERROR: -J argument was empty string" << std::endl;
return EXIT_FAILURE;
}
if (dir[dir.length() - 1] != '/')
dir += '/';
jpaths.push_back(dir);
} else if (arg == "-E" || arg == "--env") {
const std::string var = next_arg(i, args);
const char *val = ::getenv(var.c_str());
if (val == nullptr) {
std::cerr << "ERROR: Environment variable " << var
<< " was undefined." << std::endl;
return EXIT_FAILURE;
}
jsonnet_ext_var(vm, var.c_str(), val);
} else if (arg == "-V" || arg == "--var") {
const std::string var_val = next_arg(i, args);
size_t eq_pos = var_val.find_first_of('=', 0);
if (eq_pos == std::string::npos) {
std::cerr << "ERROR: argument not in form <var>=<val> \""
<< var_val << "\"." << std::endl;
return EXIT_FAILURE;
}
const std::string var = var_val.substr(0, eq_pos);
const std::string val = var_val.substr(eq_pos + 1, std::string::npos);
jsonnet_ext_var(vm, var.c_str(), val.c_str());
} else if (arg == "--gc-min-objects") {
long l = strtol_check(next_arg(i, args));
if (l < 0) {
std::cerr << "ERROR: Invalid --gc-min-objects value: " << l << std::endl;
usage(std::cerr);
return EXIT_FAILURE;
}
jsonnet_gc_min_objects(vm, l);
} else if (arg == "-t" || arg == "--max-trace") {
long l = strtol_check(next_arg(i, args));
if (l < 0) {
std::cerr << "ERROR: Invalid --max-trace value: " << l << std::endl;
usage(std::cerr);
return EXIT_FAILURE;
}
jsonnet_max_trace(vm, l);
} else if (arg == "--gc-growth-trigger") {
const char *arg = next_arg(i,args).c_str();
char *ep;
double v = std::strtod(arg, &ep);
if (*ep != '\0' || *arg == '\0') {
std::cerr << "ERROR: Invalid number \"" << arg << "\"" << std::endl;
usage(std::cerr);
return EXIT_FAILURE;
}
if (v < 0) {
std::cerr << "ERROR: Invalid --gc-growth-trigger \"" << arg << "\"\n" << std::endl;
usage(std::cerr);
return EXIT_FAILURE;
}
jsonnet_gc_growth_trigger(vm, v);
} else if (arg == "-e" || arg == "--exec") {
filename_is_code = true;
} else if (arg == "-m" || arg == "--multi") {
multi = true;
} else if (arg == "-S" || arg == "--string") {
jsonnet_string_output(vm, 1);
} else if (arg == "--debug-ast") {
jsonnet_debug_ast(vm, true);
} else if (arg == "--") {
// All subsequent args are not options.
while ((++i) < args.size())
remaining_args.push_back(args[i]);
break;
} else {
remaining_args.push_back(args[i]);
}
}
if (remaining_args.size() > 0)
filename = remaining_args[0];
if (remaining_args.size() > 1) {
std::cerr << "ERROR: Filename already specified as \"" << filename << "\"\n"
<< std::endl;
usage(std::cerr);
return EXIT_FAILURE;
}
if (filename_is_code && remaining_args.size() == 0) {
std::cerr << "ERROR: Must give filename when using -e, --exec\n" << std::endl;
usage(std::cerr);
return EXIT_FAILURE;
}
std::string input;
if (filename_is_code) {
input = filename;
filename = "<cmdline>";
} else {
if (filename == "-") {
filename = "<stdin>";
input.assign(std::istreambuf_iterator<char>(std::cin),
std::istreambuf_iterator<char>());
} else {
std::ifstream f;
f.open(filename.c_str());
if (!f.good()) {
std::string msg = "Opening input file: " + filename;
perror(msg.c_str());
return EXIT_FAILURE;
}
input.assign(std::istreambuf_iterator<char>(f),
std::istreambuf_iterator<char>());
if (!f.good()) {
std::string msg = "Reading input file: " + filename;
perror(msg.c_str());
return EXIT_FAILURE;
}
}
}
ImportCallbackContext import_callback_ctx { vm, &jpaths };
jsonnet_import_callback(vm, import_callback, &import_callback_ctx);
int error;
char *output;
if (multi) {
output = jsonnet_evaluate_snippet_multi(vm, filename.c_str(), input.c_str(), &error);
} else {
output = jsonnet_evaluate_snippet(vm, filename.c_str(), input.c_str(), &error);
}
if (error) {
std::cerr << output;
std::cerr.flush();
jsonnet_realloc(vm, output, 0);
jsonnet_destroy(vm);
return EXIT_FAILURE;
}
if (multi) {
std::map<std::string, std::string> r;
for (const char *c=output ; *c!='\0' ; ) {
const char *filename = c;
const char *c2 = c;
while (*c2 != '\0') ++c2;
++c2;
const char *json = c2;
while (*c2 != '\0') ++c2;
++c2;
c = c2;
r[filename] = json;
}
jsonnet_realloc(vm, output, 0);
for (const auto &pair : r) {
const std::string &new_content = pair.second;
const std::string &filename = pair.first;
std::cout << filename << std::endl;
{
std::ifstream exists(filename.c_str());
if (exists.good()) {
std::string existing_content;
existing_content.assign(std::istreambuf_iterator<char>(exists),
std::istreambuf_iterator<char>());
if (existing_content == new_content) {
// Do not bump the timestamp on the file if its content is the same.
// This may trigger other tools (e.g. make) to do unnecessary work.
continue;
}
}
}
std::ofstream f;
f.open(filename.c_str());
if (!f.good()) {
std::string msg = "Opening output file: " + filename;
perror(msg.c_str());
jsonnet_destroy(vm);
return EXIT_FAILURE;
}
f << new_content;
f.close();
if (!f.good()) {
std::string msg = "Writing to output file: " + filename;
perror(msg.c_str());
jsonnet_destroy(vm);
return EXIT_FAILURE;
}
}
std::cout.flush();
} else {
std::cout << output;
std::cout.flush();
jsonnet_realloc(vm, output, 0);
}
jsonnet_destroy(vm);
return EXIT_SUCCESS;
}
<commit_msg>Filename no-longer defaults to -<commit_after>/*
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
extern "C" {
#include "libjsonnet.h"
}
#define JSONNET_VERSION "v0.6.0-beta"
struct ImportCallbackContext {
JsonnetVm *vm;
std::vector<std::string> *jpaths;
};
enum ImportStatus {
IMPORT_STATUS_OK,
IMPORT_STATUS_FILE_NOT_FOUND,
IMPORT_STATUS_IO_ERROR
};
static enum ImportStatus try_path(const std::string &dir, const std::string &rel,
std::string &content)
{
std::string abs_path;
// It is possible that rel is actually absolute.
if (rel.length() > 0 && rel[0] == '/') {
abs_path = rel;
} else {
abs_path = dir + rel;
}
std::ifstream f;
f.open(abs_path.c_str());
if (!f.good()) return IMPORT_STATUS_FILE_NOT_FOUND;
content.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
if (!f.good()) return IMPORT_STATUS_IO_ERROR;
return IMPORT_STATUS_OK;
}
static char *import_callback (void *ctx_, const char *dir, const char *file, int *success)
{
const auto &ctx = *static_cast<ImportCallbackContext*>(ctx_);
std::string input;
ImportStatus status = try_path(dir, file, input);
std::vector<std::string> jpaths(*ctx.jpaths);
// If not found, try library search path.
while (status == IMPORT_STATUS_FILE_NOT_FOUND) {
if (jpaths.size() == 0) {
*success = 0;
const char *err = "No match locally or in the Jsonnet library path.";
char *r = jsonnet_realloc(ctx.vm, nullptr, std::strlen(err) + 1);
std::strcpy(r, err);
return r;
}
status = try_path(jpaths.back(), file, input);
jpaths.pop_back();
}
if (status == IMPORT_STATUS_IO_ERROR) {
*success = 0;
const char *err = std::strerror(errno);
char *r = jsonnet_realloc(ctx.vm, nullptr, std::strlen(err) + 1);
std::strcpy(r, err);
return r;
} else {
assert(status == IMPORT_STATUS_OK);
*success = 1;
char *r = jsonnet_realloc(ctx.vm, nullptr, input.length() + 1);
std::strcpy(r, input.c_str());
return r;
}
}
std::string next_arg(unsigned &i, const std::vector<std::string> &args)
{
i++;
if (i >= args.size()) {
std::cerr << "Expected another commandline argument." << std::endl;
exit(EXIT_FAILURE);
}
return args[i];
}
/** Collect commandline args into a vector of strings, and expand -foo to -f -o -o. */
std::vector<std::string> simplify_args(int argc, const char **argv)
{
std::vector<std::string> r;
for (int i=1 ; i<argc ; ++i) {
std::string arg = argv[i];
if (arg == "--") {
// Add this arg and all remaining ones without simplification.
r.push_back(arg);
while ((++i) < argc)
r.push_back(argv[i]);
break;
}
// Check if it is of the form -abc and convert to -a -b -c
if (arg.length() > 2 && arg[0] == '-' && arg[1] != '-') {
for (unsigned j=1 ; j<arg.length() ; ++j) {
r.push_back("-" + arg.substr(j,1));
}
} else {
r.push_back(arg);
}
}
return r;
}
void version(std::ostream &o)
{
o << "Jsonnet commandline interpreter " << JSONNET_VERSION << std::endl;
}
void usage(std::ostream &o)
{
version(o);
o << "Usage:\n";
o << "jsonnet {<option>} <filename>\n";
o << "where <filename> can be - (stdin)\n";
o << "and <option> can be:\n";
o << " -h / --help This message\n";
o << " -e / --exec Treat filename as code\n";
o << " -J / --jpath <dir> Specify an additional library search dir\n";
o << " -V / --var <var>=<val> Specify an 'external' var to the given value\n";
o << " -E / --env <var> Bring in an environment var as an 'external' var\n";
o << " -m / --multi Write multiple files, list files on stdout\n";
o << " -S / --string Expect a string, manifest as plain text\n";
o << " -s / --max-stack <n> Number of allowed stack frames\n";
o << " -t / --max-trace <n> Max length of stack trace before cropping\n";
o << " --gc-min-objects <n> Do not run garbage collector until this many\n";
o << " --gc-growth-trigger <n> Run garbage collector after this amount of object growth\n";
o << " --debug-ast Unparse the parsed AST without executing it\n\n";
o << " --version Print version\n";
o << "Multichar options are expanded e.g. -abc becomes -a -b -c.\n";
o << "The -- option suppresses option processing for subsequent arguments.\n";
o << "Note that since jsonnet programs can begin with -, it is advised to\n";
o << "use -- with -e if the program is unknown, e.g. jsonnet -e -- \"$CODE\".";
o << std::endl;
}
long strtol_check(const std::string &str)
{
const char *arg = str.c_str();
char *ep;
long r = std::strtol(arg, &ep, 10);
if (*ep != '\0' || *arg == '\0') {
std::cerr << "ERROR: Invalid integer \"" << arg << "\"\n" << std::endl;
usage(std::cerr);
exit(EXIT_FAILURE);
}
return r;
}
int main(int argc, const char **argv)
{
std::vector<std::string> jpaths;
jpaths.emplace_back("/usr/share/" JSONNET_VERSION "/");
jpaths.emplace_back("/usr/local/share/" JSONNET_VERSION "/");
JsonnetVm *vm = jsonnet_make();
bool filename_is_code = false;
bool multi = false;
auto args = simplify_args(argc, argv);
std::vector<std::string> remaining_args;
for (unsigned i=0 ; i<args.size() ; ++i) {
const std::string &arg = args[i];
if (arg == "-h" || arg == "--help") {
usage(std::cout);
return EXIT_SUCCESS;
} else if (arg == "-v" || arg == "--version") {
version(std::cout);
return EXIT_SUCCESS;
} else if (arg == "-s" || arg == "--max-stack") {
long l = strtol_check(next_arg(i, args));
if (l < 1) {
std::cerr << "ERROR: Invalid --max-stack value: " << l << "\n" << std::endl;
usage(std::cerr);
return EXIT_FAILURE;
}
jsonnet_max_stack(vm, l);
} else if (arg == "-J" || arg == "--jpath") {
std::string dir = next_arg(i, args);
if (dir.length() == 0) {
std::cerr << "ERROR: -J argument was empty string" << std::endl;
return EXIT_FAILURE;
}
if (dir[dir.length() - 1] != '/')
dir += '/';
jpaths.push_back(dir);
} else if (arg == "-E" || arg == "--env") {
const std::string var = next_arg(i, args);
const char *val = ::getenv(var.c_str());
if (val == nullptr) {
std::cerr << "ERROR: Environment variable " << var
<< " was undefined." << std::endl;
return EXIT_FAILURE;
}
jsonnet_ext_var(vm, var.c_str(), val);
} else if (arg == "-V" || arg == "--var") {
const std::string var_val = next_arg(i, args);
size_t eq_pos = var_val.find_first_of('=', 0);
if (eq_pos == std::string::npos) {
std::cerr << "ERROR: argument not in form <var>=<val> \""
<< var_val << "\"." << std::endl;
return EXIT_FAILURE;
}
const std::string var = var_val.substr(0, eq_pos);
const std::string val = var_val.substr(eq_pos + 1, std::string::npos);
jsonnet_ext_var(vm, var.c_str(), val.c_str());
} else if (arg == "--gc-min-objects") {
long l = strtol_check(next_arg(i, args));
if (l < 0) {
std::cerr << "ERROR: Invalid --gc-min-objects value: " << l << std::endl;
usage(std::cerr);
return EXIT_FAILURE;
}
jsonnet_gc_min_objects(vm, l);
} else if (arg == "-t" || arg == "--max-trace") {
long l = strtol_check(next_arg(i, args));
if (l < 0) {
std::cerr << "ERROR: Invalid --max-trace value: " << l << std::endl;
usage(std::cerr);
return EXIT_FAILURE;
}
jsonnet_max_trace(vm, l);
} else if (arg == "--gc-growth-trigger") {
const char *arg = next_arg(i,args).c_str();
char *ep;
double v = std::strtod(arg, &ep);
if (*ep != '\0' || *arg == '\0') {
std::cerr << "ERROR: Invalid number \"" << arg << "\"" << std::endl;
usage(std::cerr);
return EXIT_FAILURE;
}
if (v < 0) {
std::cerr << "ERROR: Invalid --gc-growth-trigger \"" << arg << "\"\n" << std::endl;
usage(std::cerr);
return EXIT_FAILURE;
}
jsonnet_gc_growth_trigger(vm, v);
} else if (arg == "-e" || arg == "--exec") {
filename_is_code = true;
} else if (arg == "-m" || arg == "--multi") {
multi = true;
} else if (arg == "-S" || arg == "--string") {
jsonnet_string_output(vm, 1);
} else if (arg == "--debug-ast") {
jsonnet_debug_ast(vm, true);
} else if (arg == "--") {
// All subsequent args are not options.
while ((++i) < args.size())
remaining_args.push_back(args[i]);
break;
} else {
remaining_args.push_back(args[i]);
}
}
const char *want = filename_is_code ? "code" : "filename";
if (remaining_args.size() == 0) {
std::cerr << "ERROR: Must give " << want << "\n" << std::endl;
usage(std::cerr);
return EXIT_FAILURE;
}
std::string filename = remaining_args[0];
if (remaining_args.size() > 1) {
std::cerr << "ERROR: Already specified " << want << " as \"" << filename << "\"\n"
<< std::endl;
usage(std::cerr);
return EXIT_FAILURE;
}
std::string input;
if (filename_is_code) {
input = filename;
filename = "<cmdline>";
} else {
if (filename == "-") {
filename = "<stdin>";
input.assign(std::istreambuf_iterator<char>(std::cin),
std::istreambuf_iterator<char>());
} else {
std::ifstream f;
f.open(filename.c_str());
if (!f.good()) {
std::string msg = "Opening input file: " + filename;
perror(msg.c_str());
return EXIT_FAILURE;
}
input.assign(std::istreambuf_iterator<char>(f),
std::istreambuf_iterator<char>());
if (!f.good()) {
std::string msg = "Reading input file: " + filename;
perror(msg.c_str());
return EXIT_FAILURE;
}
}
}
ImportCallbackContext import_callback_ctx { vm, &jpaths };
jsonnet_import_callback(vm, import_callback, &import_callback_ctx);
int error;
char *output;
if (multi) {
output = jsonnet_evaluate_snippet_multi(vm, filename.c_str(), input.c_str(), &error);
} else {
output = jsonnet_evaluate_snippet(vm, filename.c_str(), input.c_str(), &error);
}
if (error) {
std::cerr << output;
std::cerr.flush();
jsonnet_realloc(vm, output, 0);
jsonnet_destroy(vm);
return EXIT_FAILURE;
}
if (multi) {
std::map<std::string, std::string> r;
for (const char *c=output ; *c!='\0' ; ) {
const char *filename = c;
const char *c2 = c;
while (*c2 != '\0') ++c2;
++c2;
const char *json = c2;
while (*c2 != '\0') ++c2;
++c2;
c = c2;
r[filename] = json;
}
jsonnet_realloc(vm, output, 0);
for (const auto &pair : r) {
const std::string &new_content = pair.second;
const std::string &filename = pair.first;
std::cout << filename << std::endl;
{
std::ifstream exists(filename.c_str());
if (exists.good()) {
std::string existing_content;
existing_content.assign(std::istreambuf_iterator<char>(exists),
std::istreambuf_iterator<char>());
if (existing_content == new_content) {
// Do not bump the timestamp on the file if its content is the same.
// This may trigger other tools (e.g. make) to do unnecessary work.
continue;
}
}
}
std::ofstream f;
f.open(filename.c_str());
if (!f.good()) {
std::string msg = "Opening output file: " + filename;
perror(msg.c_str());
jsonnet_destroy(vm);
return EXIT_FAILURE;
}
f << new_content;
f.close();
if (!f.good()) {
std::string msg = "Writing to output file: " + filename;
perror(msg.c_str());
jsonnet_destroy(vm);
return EXIT_FAILURE;
}
}
std::cout.flush();
} else {
std::cout << output;
std::cout.flush();
jsonnet_realloc(vm, output, 0);
}
jsonnet_destroy(vm);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "GolfBall.hpp"
#include "../Resources.hpp"
#include "Default3D.vert.hpp"
#include "Default3D.geom.hpp"
#include "Default3D.frag.hpp"
#include "glm/gtc/constants.hpp"
#include "../Util/Log.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
GolfBall::GolfBall(BallType ballType, TerrainObject* terrain) : ModelObject(modelGeometry = Resources().CreateOBJModel("Resources/Models/GolfBall/GolfBall.obj"),
"Resources/Models/GolfBall/Diffuse.png",
"Resources/Models/GolfBall/Normal.png",
"Resources/Models/GolfBall/Specular.png") {
active = false;
restitution = ballType == TWOPIECE ? 0.78f : 0.68f;
this->terrain = terrain;
groundLevel = this->terrain->Position().y;
origin = glm::vec3(1.f, 0.f, 1.f);
/// @todo Mass based on explosive material.
mass = 0.0459f;
this->ballType = ballType;
sphere.position = Position();
SetRadius(0.0214f);
}
GolfBall::~GolfBall() {
Resources().FreeOBJModel(modelGeometry);
}
void GolfBall::Reset(){
active = false;
velocity = glm::vec3(0.f, 0.f, 0.f);
angularVelocity = glm::vec3(0.f, 0.f, 0.f);
SetPosition(origin);
sphere.position = Position();
orientation = glm::quat();
}
void GolfBall::Update(double time, const glm::vec3& wind, std::vector<PlayerObject>& players) {
if (active) {
Move(static_cast<float>(time)* velocity);
sphere.position = Position();
if (glm::length(angularVelocity) > 0.0001f) {
glm::quat deltaQuat = glm::angleAxis(static_cast<float>(time)* glm::length(angularVelocity), glm::normalize(angularVelocity));
orientation = deltaQuat * orientation;
}
glm::vec3 dragForce, magnusForce = glm::vec3(0.f, 0.f, 0.f);
// Check for collision
groundLevel = terrain->GetY(Position().x, Position().z);
if (glm::length(velocity) > 0.0001f && (sphere.position.y - sphere.radius) < groundLevel){
float vCritical = 0.3f;
float e = 0.55f;
float muSliding = 0.51f;
float muRolling = 0.096f;
SetPosition(Position().x, groundLevel + sphere.radius, Position().z);
sphere.position = Position();
//glm::vec3 eRoh = glm::normalize(glm::vec3(0.f, 1.f, 0.f));
glm::vec3 eRoh = terrain->GetNormal(Position().x, Position().z);
Log() << eRoh << "\n";
glm::vec3 tangentialVelocity = velocity - glm::dot(velocity, eRoh) * eRoh;
glm::vec3 eFriction = glm::vec3(0.f, 0.f, 0.f);
if (glm::length(glm::cross(eRoh, angularVelocity) + tangentialVelocity) > 0.0001f){
eFriction = glm::normalize(sphere.radius * glm::cross(eRoh, angularVelocity) + tangentialVelocity);
}
float vRoh = glm::dot(velocity, eRoh);
float deltaU = -(e + 1.f) * vRoh;
glm::vec3 angularDirection = glm::cross(eRoh, glm::normalize(tangentialVelocity));
float w = glm::dot(angularVelocity, angularDirection);
if (fabs(vRoh) < vCritical && glm::length(tangentialVelocity) > 0.0001f) {
if (w * sphere.radius + 0.0001f < glm::length(tangentialVelocity)) {
// Sliding.
velocity = tangentialVelocity - static_cast<float>(time)* (eFriction * muSliding * 9.82f*eRoh.y);
angularVelocity += (5.f / 2.f) * (muSliding * 9.82f / sphere.radius * static_cast<float>(time)) * angularDirection;
}
else {
// Rolling.
velocity = tangentialVelocity - static_cast<float>(time)* (glm::normalize(tangentialVelocity) * muRolling * 9.82f*eRoh.y);
float tangentialVelocityAfter = glm::length(velocity - glm::dot(velocity, eRoh) * eRoh);
angularVelocity = (glm::length(tangentialVelocityAfter) / sphere.radius) * angularDirection;
// Stopped.
if (glm::length(velocity) < 0.005f) {
velocity = glm::vec3(0.f, 0.f, 0.f);
angularVelocity = glm::vec3(0.f, 0.f, 0.f);
}
}
} else {
float deltaTime = pow(mass * mass / (fabs(vRoh) * sphere.radius), 0.2f) * 0.00251744f;
float velocityRoh = glm::dot(velocity, eRoh);
float velocityNormal = glm::dot(velocity, eFriction);
float uRoh = -e*velocityRoh;
float deltauRoh = uRoh - (velocityRoh);
float deltaUn = muSliding*deltauRoh;
float rollUn = (5.f / 7.f)*velocityNormal;
float slideUn = velocityNormal - deltaUn;
if (velocityNormal > rollUn){
velocity = uRoh*eRoh + rollUn*eFriction;
angularVelocity += muRolling * (deltaU + 9.82f*eRoh.y * deltaTime) / sphere.radius * glm::cross(eRoh, eFriction);
} else {
velocity = uRoh*eRoh + slideUn*eFriction;
angularVelocity += muSliding * (deltaU + 9.82f *eRoh.y* deltaTime) / sphere.radius * glm::cross(eRoh, eFriction);
}
}
} else {
// Calculate magnus force.
float v = glm::length(velocity);
float u = glm::length(velocity - wind);
float w = glm::length(angularVelocity);
glm::vec3 eU = (velocity - wind) / u;
magnusForce = glm::vec3(0.f, 0.f, 0.f);
if (u > 0.f && v > 0.f && w > 0.f) {
float Cm = (sqrt(1.f + 0.31f * (w / v)) - 1.f) / 20.f;
float Fm = 0.5f * Cm * 1.23f * area * u * u;
magnusForce = Fm * glm::cross(eU, glm::normalize(angularVelocity));
}
// Calculate drag force.
float cD;
if (ballType == TWOPIECE)
cD = v < 65.f ? -0.0051f * v + 0.53f : 0.21f;
else
cD = v < 60.f ? -0.0084f * v + 0.73f : 0.22f;
dragForce = glm::vec3(0.f, 0.f, 0.f);
if (u > 0.f)
dragForce = -0.5f * 1.23f * area * cD * u * u * eU;
}
// Calculate gravitational force.
glm::vec3 gravitationForce = glm::vec3(0.f, mass * -9.82f, 0.f);
// Get acceleration from total force.
glm::vec3 acceleration = (dragForce + magnusForce + gravitationForce) / mass;
velocity += acceleration * static_cast<float>(time);
}
}
void GolfBall::Render(Camera* camera, const glm::vec2& screenSize, const glm::vec4& clippingPlane) const{
ModelObject::Render(camera, screenSize, clippingPlane);
}
void GolfBall::Explode(std::vector<PlayerObject>& players, int playerIndex){
//@TODO: Set mass equivalent depending on material used.
float equivalenceFactor = 1.0f;
float massEquivalent = mass*equivalenceFactor;
for (auto &player : players){
glm::vec3 distanceV = (Position() - player.Position());
float distance = glm::length(distanceV);
//pow(meq, 1.f/3.f) => cube root of meq
float z = distance / (pow(massEquivalent, 1.f / 3.f));
float alpha = 1 + pow((z / 4.5f), 2.f);
float beta = 1 + pow((z / 0.048f), 2.f);
float gamma = 1 + pow((z / 1.35f), 2.f);
float delta = 1 + pow((z / 0.32f), 2.f);
float Pf = 8.08f*pow(10.f, 7.f)*alpha;
Pf = Pf / sqrt(beta*gamma*delta);
player.TakeDamage(Pf);
}
origin = players[playerIndex].Position();
Reset();
}
void GolfBall::Strike(ClubType club, const glm::vec3& clubVelocity) {
active = true;
// Club velocity in strike plane.
float v = glm::length(clubVelocity);
if (v > 0.f)
{
float sinLoft = sin(club.loft);
float cosLoft = cos(club.loft);
// Ball velocity.
float massCoefficient = club.mass / (club.mass + mass);
float Up = (1.f + restitution) * massCoefficient * v * cosLoft;
float Un = (2.f / 7.f) * massCoefficient * v * sinLoft;
// Go back from strike plane to 3D.
glm::vec3 forward = clubVelocity / v;
glm::vec3 up = glm::cross(forward, glm::cross(glm::vec3(0.f, 1.f, 0.f), forward));
glm::vec3 ep = glm::normalize(cosLoft * forward + sinLoft * up);
glm::vec3 en = glm::normalize(sinLoft * forward - cosLoft * up);
// Total velocity.
velocity = Up * ep + Un * en;
angularVelocity = -Un / sphere.radius * glm::cross(ep, en);
} else {
velocity = glm::vec3(0.f, 0.f, 0.f);
angularVelocity = glm::vec3(0.f, 0.f, 0.f);
}
}
void GolfBall::SetRadius(float radius) {
sphere.radius = radius;
SetScale(glm::vec3(radius, radius, radius));
area = glm::pi<float>() * radius * radius;
}
glm::mat4 GolfBall::Orientation() const {
return glm::toMat4(orientation);
}
<commit_msg>Stuff<commit_after>#include "GolfBall.hpp"
#include "../Resources.hpp"
#include "Default3D.vert.hpp"
#include "Default3D.geom.hpp"
#include "Default3D.frag.hpp"
#include "glm/gtc/constants.hpp"
#include "../Util/Log.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
GolfBall::GolfBall(BallType ballType, TerrainObject* terrain) : ModelObject(modelGeometry = Resources().CreateOBJModel("Resources/Models/GolfBall/GolfBall.obj"),
"Resources/Models/GolfBall/Diffuse.png",
"Resources/Models/GolfBall/Normal.png",
"Resources/Models/GolfBall/Specular.png") {
active = false;
restitution = ballType == TWOPIECE ? 0.78f : 0.68f;
this->terrain = terrain;
groundLevel = this->terrain->Position().y;
origin = glm::vec3(1.f, 0.f, 1.f);
/// @todo Mass based on explosive material.
mass = 0.0459f;
this->ballType = ballType;
sphere.position = Position();
SetRadius(0.0214f);
}
GolfBall::~GolfBall() {
Resources().FreeOBJModel(modelGeometry);
}
void GolfBall::Reset(){
active = false;
velocity = glm::vec3(0.f, 0.f, 0.f);
angularVelocity = glm::vec3(0.f, 0.f, 0.f);
SetPosition(origin);
sphere.position = Position();
orientation = glm::quat();
}
void GolfBall::Update(double time, const glm::vec3& wind, std::vector<PlayerObject>& players) {
if (active) {
Move(static_cast<float>(time)* velocity);
sphere.position = Position();
if (glm::length(angularVelocity) > 0.0001f) {
glm::quat deltaQuat = glm::angleAxis(static_cast<float>(time)* glm::length(angularVelocity), glm::normalize(angularVelocity));
orientation = deltaQuat * orientation;
}
glm::vec3 dragForce, magnusForce = glm::vec3(0.f, 0.f, 0.f);
// Check for collision
groundLevel = terrain->GetY(Position().x, Position().z);
if (glm::length(velocity) > 0.0001f && (sphere.position.y - sphere.radius) < groundLevel){
float vCritical = 0.3f;
float e = 0.35f;
float muSliding = 0.51f;
float muRolling = 0.096f;
SetPosition(Position().x, groundLevel + sphere.radius, Position().z);
sphere.position = Position();
//glm::vec3 eRoh = glm::normalize(glm::vec3(0.f, 1.f, 0.f));
glm::vec3 eRoh = terrain->GetNormal(Position().x, Position().z);
Log() << eRoh << "\n";
glm::vec3 tangentialVelocity = velocity - glm::dot(velocity, eRoh) * eRoh;
glm::vec3 eFriction = glm::vec3(0.f, 0.f, 0.f);
if (glm::length(glm::cross(eRoh, angularVelocity) + tangentialVelocity) > 0.0001f){
eFriction = glm::normalize(sphere.radius * glm::cross(eRoh, angularVelocity) + tangentialVelocity);
}
float vRoh = glm::dot(velocity, eRoh);
float deltaU = -(e + 1.f) * vRoh;
glm::vec3 angularDirection = glm::cross(eRoh, glm::normalize(tangentialVelocity));
float w = glm::dot(angularVelocity, angularDirection);
if (fabs(vRoh) < vCritical && glm::length(tangentialVelocity) > 0.0001f) {
if (w * sphere.radius + 0.0001f < glm::length(tangentialVelocity)) {
// Sliding.
velocity = tangentialVelocity - static_cast<float>(time)* (eFriction * muSliding * 9.82f*eRoh.y);
angularVelocity += (5.f / 2.f) * (muSliding * 9.82f / sphere.radius * static_cast<float>(time)) * angularDirection;
} else {
// Rolling.
velocity = tangentialVelocity - static_cast<float>(time)* (glm::normalize(tangentialVelocity) * muRolling * 9.82f*eRoh.y);
float tangentialVelocityAfter = glm::length(velocity - glm::dot(velocity, eRoh) * eRoh);
angularVelocity = (glm::length(tangentialVelocityAfter) / sphere.radius) * angularDirection;
// Stopped.
if (glm::length(velocity) < 0.005f) {
velocity = glm::vec3(0.f, 0.f, 0.f);
angularVelocity = glm::vec3(0.f, 0.f, 0.f);
}
}
} else {
float deltaTime = pow(mass * mass / (fabs(vRoh) * sphere.radius), 0.2f) * 0.00251744f;
float velocityRoh = glm::dot(velocity, eRoh);
float velocityNormal = glm::dot(velocity, eFriction);
float uRoh = -e*velocityRoh;
float deltauRoh = uRoh - (velocityRoh);
float deltaUn = muSliding*deltauRoh;
float rollUn = (5.f / 7.f)*velocityNormal;
float slideUn = velocityNormal - deltaUn;
if (velocityNormal > rollUn){
velocity = uRoh*eRoh + rollUn*eFriction;
angularVelocity += muRolling * (deltaU + 9.82f*eRoh.y * deltaTime) / sphere.radius * glm::cross(eRoh, eFriction);
} else {
velocity = uRoh*eRoh + slideUn*eFriction;
angularVelocity += muSliding * (deltaU + 9.82f *eRoh.y* deltaTime) / sphere.radius * glm::cross(eRoh, eFriction);
}
}
} else {
// Calculate magnus force.
float v = glm::length(velocity);
float u = glm::length(velocity - wind);
float w = glm::length(angularVelocity);
glm::vec3 eU = (velocity - wind) / u;
magnusForce = glm::vec3(0.f, 0.f, 0.f);
if (u > 0.f && v > 0.f && w > 0.f) {
float Cm = (sqrt(1.f + 0.31f * (w / v)) - 1.f) / 20.f;
float Fm = 0.5f * Cm * 1.23f * area * u * u;
magnusForce = Fm * glm::cross(eU, glm::normalize(angularVelocity));
}
// Calculate drag force.
float cD;
if (ballType == TWOPIECE)
cD = v < 65.f ? -0.0051f * v + 0.53f : 0.21f;
else
cD = v < 60.f ? -0.0084f * v + 0.73f : 0.22f;
dragForce = glm::vec3(0.f, 0.f, 0.f);
if (u > 0.f)
dragForce = -0.5f * 1.23f * area * cD * u * u * eU;
}
// Calculate gravitational force.
glm::vec3 gravitationForce = glm::vec3(0.f, mass * -9.82f, 0.f);
// Get acceleration from total force.
glm::vec3 acceleration = (dragForce + magnusForce + gravitationForce) / mass;
velocity += acceleration * static_cast<float>(time);
}
}
void GolfBall::Render(Camera* camera, const glm::vec2& screenSize, const glm::vec4& clippingPlane) const{
ModelObject::Render(camera, screenSize, clippingPlane);
}
void GolfBall::Explode(std::vector<PlayerObject>& players, int playerIndex){
//@TODO: Set mass equivalent depending on material used.
float equivalenceFactor = 1.0f;
float massEquivalent = mass*equivalenceFactor;
for (auto &player : players){
glm::vec3 distanceV = (Position() - player.Position());
float distance = glm::length(distanceV);
//pow(meq, 1.f/3.f) => cube root of meq
float z = distance / (pow(massEquivalent, 1.f / 3.f));
float alpha = 1 + pow((z / 4.5f), 2.f);
float beta = 1 + pow((z / 0.048f), 2.f);
float gamma = 1 + pow((z / 1.35f), 2.f);
float delta = 1 + pow((z / 0.32f), 2.f);
float Pf = 8.08f*pow(10.f, 7.f)*alpha;
Pf = Pf / sqrt(beta*gamma*delta);
player.TakeDamage(Pf);
}
origin = players[playerIndex].Position();
Reset();
}
void GolfBall::Strike(ClubType club, const glm::vec3& clubVelocity) {
active = true;
// Club velocity in strike plane.
float v = glm::length(clubVelocity);
if (v > 0.f)
{
float sinLoft = sin(club.loft);
float cosLoft = cos(club.loft);
// Ball velocity.
float massCoefficient = club.mass / (club.mass + mass);
float Up = (1.f + restitution) * massCoefficient * v * cosLoft;
float Un = (2.f / 7.f) * massCoefficient * v * sinLoft;
// Go back from strike plane to 3D.
glm::vec3 forward = clubVelocity / v;
glm::vec3 up = glm::cross(forward, glm::cross(glm::vec3(0.f, 1.f, 0.f), forward));
glm::vec3 ep = glm::normalize(cosLoft * forward + sinLoft * up);
glm::vec3 en = glm::normalize(sinLoft * forward - cosLoft * up);
// Total velocity.
velocity = Up * ep + Un * en;
angularVelocity = -Un / sphere.radius * glm::cross(ep, en);
} else {
velocity = glm::vec3(0.f, 0.f, 0.f);
angularVelocity = glm::vec3(0.f, 0.f, 0.f);
}
}
void GolfBall::SetRadius(float radius) {
sphere.radius = radius;
SetScale(glm::vec3(radius, radius, radius));
area = glm::pi<float>() * radius * radius;
}
glm::mat4 GolfBall::Orientation() const {
return glm::toMat4(orientation);
}
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mmessageboxview.h"
#include "mmessageboxview_p.h"
#include "mmessagebox.h"
#include "mlabel.h"
#include <QGraphicsLinearLayout>
MMessageBoxViewPrivate::MMessageBoxViewPrivate()
{
}
MMessageBoxViewPrivate::~MMessageBoxViewPrivate()
{
}
MMessageBoxView::MMessageBoxView(MMessageBox *controller) :
MDialogView(*new MMessageBoxViewPrivate, controller)
{
Q_D(MMessageBoxView);
d->label = new MLabel;
d->label->setAlignment(Qt::AlignCenter);
contentsLayout()->insertItem(0, d->label);
}
MMessageBoxView::~MMessageBoxView()
{
}
void MMessageBoxView::updateData(const QList<const char *>& modifications)
{
MDialogView::updateData(modifications);
Q_D(MMessageBoxView);
const char *member;
foreach(member, modifications) {
if (member == MMessageBoxModel::Text) {
d->label->setText(model()->text());
}
}
updateGeometry();
}
void MMessageBoxView::setupModel()
{
MDialogView::setupModel();
Q_D(MMessageBoxView);
//update text
d->label->setText(model()->text());
updateGeometry();
}
M_REGISTER_VIEW_NEW(MMessageBoxView, MMessageBox)
<commit_msg>Changes: MMessageBox size changed when 3 buttons are added<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mmessageboxview.h"
#include "mmessageboxview_p.h"
#include "mmessagebox.h"
#include "mlabel.h"
#include <QGraphicsLinearLayout>
MMessageBoxViewPrivate::MMessageBoxViewPrivate()
{
}
MMessageBoxViewPrivate::~MMessageBoxViewPrivate()
{
}
MMessageBoxView::MMessageBoxView(MMessageBox *controller) :
MDialogView(*new MMessageBoxViewPrivate, controller)
{
Q_D(MMessageBoxView);
d->label = new MLabel;
d->label->setAlignment(Qt::AlignCenter);
contentsLayout()->insertItem(0, d->label);
}
MMessageBoxView::~MMessageBoxView()
{
}
void MMessageBoxView::updateData(const QList<const char *>& modifications)
{
MDialogView::updateData(modifications);
Q_D(MMessageBoxView);
const char *member;
foreach(member, modifications) {
if (member == MMessageBoxModel::Text) {
d->label->setText(model()->text());
}
}
if(model()->buttons().count() >= 3)
d->dialogBox->setPreferredWidth(style()->maximumSize().width());
else
d->dialogBox->setPreferredWidth(style()->dialogPreferredSize().width());
updateGeometry();
}
void MMessageBoxView::setupModel()
{
MDialogView::setupModel();
Q_D(MMessageBoxView);
//update text
d->label->setText(model()->text());
if(model()->buttons().count() >= 3)
d->dialogBox->setPreferredWidth(style()->maximumSize().width());
else
d->dialogBox->setPreferredWidth(style()->dialogPreferredSize().width());
updateGeometry();
}
M_REGISTER_VIEW_NEW(MMessageBoxView, MMessageBox)
<|endoftext|> |
<commit_before>#include "ShAlgebra.hpp"
#include <map>
#include "ShCtrlGraph.hpp"
#include "ShDebug.hpp"
#include "ShError.hpp"
#include "ShOptimizer.hpp"
#include "ShEnvironment.hpp"
namespace {
using namespace SH;
typedef std::map<ShCtrlGraphNodePtr, ShCtrlGraphNodePtr> CtrlGraphCopyMap;
struct CtrlGraphCopier {
CtrlGraphCopier(CtrlGraphCopyMap& copyMap)
: copyMap(copyMap)
{
}
void operator()(ShCtrlGraphNodePtr node) {
if (!node) return;
ShCtrlGraphNodePtr newNode = new ShCtrlGraphNode(*node);
copyMap[node] = newNode;
}
CtrlGraphCopyMap& copyMap;
};
void copyCtrlGraph(ShCtrlGraphNodePtr head, ShCtrlGraphNodePtr tail,
ShCtrlGraphNodePtr& newHead, ShCtrlGraphNodePtr& newTail)
{
CtrlGraphCopyMap copyMap;
copyMap[0] = 0;
CtrlGraphCopier copier(copyMap);
head->dfs(copier);
for (CtrlGraphCopyMap::iterator I = copyMap.begin(); I != copyMap.end(); ++I) {
ShCtrlGraphNodePtr node = I->first;
if (!node) continue;
for (std::vector<ShCtrlGraphBranch>::iterator J = node->successors.begin(); J != node->successors.end(); ++J) {
J->node = copyMap[J->node];
}
node->follower = copyMap[node->follower];
}
newHead = copyMap[head];
newTail = copyMap[tail];
}
typedef std::map<ShVariableNodePtr, ShVariableNodePtr> VarMap;
struct VariableReplacer {
VariableReplacer(VarMap& v)
: varMap(v)
{
}
void operator()(ShCtrlGraphNodePtr node)
{
if (!node) return;
ShBasicBlockPtr block = node->block;
if (!block) return;
for (ShBasicBlock::ShStmtList::iterator I = block->begin(); I != block->end(); ++I) {
repVar(I->dest);
for (int i = 0; i < 3; i++) {
repVar(I->src[i]);
}
}
}
void repVar(ShVariable& var)
{
VarMap::iterator I = varMap.find(var.node());
if (I == varMap.end()) return;
SH_DEBUG_PRINT("Replacing " << var.node()->name() << " with " << I->second->name());
var.node() = I->second;
}
VarMap& varMap;
};
}
namespace SH {
ShProgram connect(const ShProgram& a, const ShProgram& b)
{
if (a->outputs.size() != b->inputs.size()) {
ShError( ShAlgebraException( "Cannot connect programs. Number of inputs does not match number of outputs" ) );
}
int rkind;
if (a->kind() < 0) {
rkind = b->kind(); // A doesn't have a target. Use b's.
} else {
if (b->kind() < 0) {
rkind = a->kind(); // A has a target, b doesn't
} else {
rkind = -1; // Connecting different targets.
}
}
ShProgram program = new ShProgramNode(rkind);
ShCtrlGraphNodePtr heada, taila, headb, tailb;
copyCtrlGraph(a->ctrlGraph->entry(), a->ctrlGraph->exit(), heada, taila);
copyCtrlGraph(b->ctrlGraph->entry(), b->ctrlGraph->exit(), headb, tailb);
taila->append(headb);
program->ctrlGraph = new ShCtrlGraph(heada, tailb);
for (ShProgramNode::VarList::const_iterator I = a->inputs.begin(); I != a->inputs.end(); ++I) {
program->inputs.push_back(*I);
}
for (ShProgramNode::VarList::const_iterator I = b->outputs.begin(); I != b->outputs.end(); ++I) {
program->outputs.push_back(*I);
}
VarMap varMap;
SH_DEBUG_PRINT("Smashing variables together");
ShEnvironment::shader = program;
ShEnvironment::insideShader = true;
ShProgramNode::VarList::const_iterator I, J;
for (I = a->outputs.begin(), J = b->inputs.begin(); I != a->outputs.end(); ++I, ++J) {
SH_DEBUG_PRINT("Smashing a variable..");
if( (*I)->size() == (*J)->size() ) {
ShError( ShAlgebraException( "Cannot smash variables " + (*I)->name() +
" and " + (*J)->name() + " with different sizes." ) );
}
ShVariableNodePtr n = new ShVariableNode(SH_VAR_TEMP, (*I)->size());
varMap[*I] = n;
varMap[*J] = n;
}
ShEnvironment::shader = 0;
ShEnvironment::insideShader = false;
VariableReplacer replacer(varMap);
program->ctrlGraph->dfs(replacer);
ShOptimizer optimizer(program->ctrlGraph);
optimizer.optimize(ShEnvironment::optimizationLevel);
program->collectVariables();
return program;
}
ShProgram combine(const ShProgram& a, const ShProgram& b)
{
int rkind;
if (a->kind() < 0) {
rkind = b->kind(); // A doesn't have a target. Use b's.
} else {
if (b->kind() < 0) {
rkind = a->kind(); // A has a target, b doesn't
} else {
rkind = -1; // Connecting different targets.
}
}
ShProgram program = new ShProgramNode(rkind);
ShCtrlGraphNodePtr heada, taila, headb, tailb;
copyCtrlGraph(a->ctrlGraph->entry(), a->ctrlGraph->exit(), heada, taila);
copyCtrlGraph(b->ctrlGraph->entry(), b->ctrlGraph->exit(), headb, tailb);
taila->append(headb);
program->ctrlGraph = new ShCtrlGraph(heada, tailb);
for (ShProgramNode::VarList::const_iterator I = a->inputs.begin(); I != a->inputs.end(); ++I) {
program->inputs.push_back(*I);
}
for (ShProgramNode::VarList::const_iterator I = a->outputs.begin(); I != a->outputs.end(); ++I) {
program->outputs.push_back(*I);
}
for (ShProgramNode::VarList::const_iterator I = b->inputs.begin(); I != b->inputs.end(); ++I) {
program->inputs.push_back(*I);
}
for (ShProgramNode::VarList::const_iterator I = b->outputs.begin(); I != b->outputs.end(); ++I) {
program->outputs.push_back(*I);
}
ShOptimizer optimizer(program->ctrlGraph);
optimizer.optimize(ShEnvironment::optimizationLevel);
program->collectVariables();
return program;
}
ShProgram operator<<(const ShProgram& a, const ShProgram& b)
{
return connect(a, b);
}
ShProgram operator+(const ShProgram& a, const ShProgram& b)
{
return combine(a, b);
}
}
<commit_msg>small fix because I can't tell the difference between != and ==<commit_after>#include "ShAlgebra.hpp"
#include <map>
#include "ShCtrlGraph.hpp"
#include "ShDebug.hpp"
#include "ShError.hpp"
#include "ShOptimizer.hpp"
#include "ShEnvironment.hpp"
namespace {
using namespace SH;
typedef std::map<ShCtrlGraphNodePtr, ShCtrlGraphNodePtr> CtrlGraphCopyMap;
struct CtrlGraphCopier {
CtrlGraphCopier(CtrlGraphCopyMap& copyMap)
: copyMap(copyMap)
{
}
void operator()(ShCtrlGraphNodePtr node) {
if (!node) return;
ShCtrlGraphNodePtr newNode = new ShCtrlGraphNode(*node);
copyMap[node] = newNode;
}
CtrlGraphCopyMap& copyMap;
};
void copyCtrlGraph(ShCtrlGraphNodePtr head, ShCtrlGraphNodePtr tail,
ShCtrlGraphNodePtr& newHead, ShCtrlGraphNodePtr& newTail)
{
CtrlGraphCopyMap copyMap;
copyMap[0] = 0;
CtrlGraphCopier copier(copyMap);
head->dfs(copier);
for (CtrlGraphCopyMap::iterator I = copyMap.begin(); I != copyMap.end(); ++I) {
ShCtrlGraphNodePtr node = I->first;
if (!node) continue;
for (std::vector<ShCtrlGraphBranch>::iterator J = node->successors.begin(); J != node->successors.end(); ++J) {
J->node = copyMap[J->node];
}
node->follower = copyMap[node->follower];
}
newHead = copyMap[head];
newTail = copyMap[tail];
}
typedef std::map<ShVariableNodePtr, ShVariableNodePtr> VarMap;
struct VariableReplacer {
VariableReplacer(VarMap& v)
: varMap(v)
{
}
void operator()(ShCtrlGraphNodePtr node)
{
if (!node) return;
ShBasicBlockPtr block = node->block;
if (!block) return;
for (ShBasicBlock::ShStmtList::iterator I = block->begin(); I != block->end(); ++I) {
repVar(I->dest);
for (int i = 0; i < 3; i++) {
if( !I->src[i].null() ) repVar(I->src[i]);
}
}
}
void repVar(ShVariable& var)
{
VarMap::iterator I = varMap.find(var.node());
if (I == varMap.end()) return;
SH_DEBUG_PRINT("Replacing " << var.node()->name() << " with " << I->second->name());
var.node() = I->second;
}
VarMap& varMap;
};
}
namespace SH {
ShProgram connect(const ShProgram& a, const ShProgram& b)
{
if (a->outputs.size() != b->inputs.size()) {
ShError( ShAlgebraException( "Cannot connect programs. Number of inputs does not match number of outputs" ) );
}
int rkind;
if (a->kind() < 0) {
rkind = b->kind(); // A doesn't have a target. Use b's.
} else {
if (b->kind() < 0) {
rkind = a->kind(); // A has a target, b doesn't
} else {
rkind = -1; // Connecting different targets.
}
}
ShProgram program = new ShProgramNode(rkind);
ShCtrlGraphNodePtr heada, taila, headb, tailb;
copyCtrlGraph(a->ctrlGraph->entry(), a->ctrlGraph->exit(), heada, taila);
copyCtrlGraph(b->ctrlGraph->entry(), b->ctrlGraph->exit(), headb, tailb);
taila->append(headb);
program->ctrlGraph = new ShCtrlGraph(heada, tailb);
for (ShProgramNode::VarList::const_iterator I = a->inputs.begin(); I != a->inputs.end(); ++I) {
program->inputs.push_back(*I);
}
for (ShProgramNode::VarList::const_iterator I = b->outputs.begin(); I != b->outputs.end(); ++I) {
program->outputs.push_back(*I);
}
VarMap varMap;
SH_DEBUG_PRINT("Smashing variables together");
ShEnvironment::shader = program;
ShEnvironment::insideShader = true;
ShProgramNode::VarList::const_iterator I, J;
for (I = a->outputs.begin(), J = b->inputs.begin(); I != a->outputs.end(); ++I, ++J) {
SH_DEBUG_PRINT("Smashing a variable..");
if( (*I)->size() != (*J)->size() ) {
ShError( ShAlgebraException( "Cannot smash variables " + (*I)->name() +
" and " + (*J)->name() + " with different sizes." ) );
}
ShVariableNodePtr n = new ShVariableNode(SH_VAR_TEMP, (*I)->size());
varMap[*I] = n;
varMap[*J] = n;
}
ShEnvironment::shader = 0;
ShEnvironment::insideShader = false;
VariableReplacer replacer(varMap);
program->ctrlGraph->dfs(replacer);
ShOptimizer optimizer(program->ctrlGraph);
optimizer.optimize(ShEnvironment::optimizationLevel);
program->collectVariables();
return program;
}
ShProgram combine(const ShProgram& a, const ShProgram& b)
{
int rkind;
if (a->kind() < 0) {
rkind = b->kind(); // A doesn't have a target. Use b's.
} else {
if (b->kind() < 0) {
rkind = a->kind(); // A has a target, b doesn't
} else {
rkind = -1; // Connecting different targets.
}
}
ShProgram program = new ShProgramNode(rkind);
ShCtrlGraphNodePtr heada, taila, headb, tailb;
copyCtrlGraph(a->ctrlGraph->entry(), a->ctrlGraph->exit(), heada, taila);
copyCtrlGraph(b->ctrlGraph->entry(), b->ctrlGraph->exit(), headb, tailb);
taila->append(headb);
program->ctrlGraph = new ShCtrlGraph(heada, tailb);
for (ShProgramNode::VarList::const_iterator I = a->inputs.begin(); I != a->inputs.end(); ++I) {
program->inputs.push_back(*I);
}
for (ShProgramNode::VarList::const_iterator I = a->outputs.begin(); I != a->outputs.end(); ++I) {
program->outputs.push_back(*I);
}
for (ShProgramNode::VarList::const_iterator I = b->inputs.begin(); I != b->inputs.end(); ++I) {
program->inputs.push_back(*I);
}
for (ShProgramNode::VarList::const_iterator I = b->outputs.begin(); I != b->outputs.end(); ++I) {
program->outputs.push_back(*I);
}
ShOptimizer optimizer(program->ctrlGraph);
optimizer.optimize(ShEnvironment::optimizationLevel);
program->collectVariables();
return program;
}
ShProgram operator<<(const ShProgram& a, const ShProgram& b)
{
return connect(a, b);
}
ShProgram operator+(const ShProgram& a, const ShProgram& b)
{
return combine(a, b);
}
}
<|endoftext|> |
<commit_before>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include "SkirtBrim.h"
#include "support.h"
namespace cura
{
void SkirtBrim::getFirstLayerOutline(SliceDataStorage& storage, const unsigned int primary_line_count, const int primary_extruder_skirt_brim_line_width, const bool is_skirt, const bool outside_only, Polygons& first_layer_outline)
{
bool external_only = is_skirt; // whether to include holes or not
const int layer_nr = 0;
if (is_skirt)
{
const bool include_helper_parts = true;
first_layer_outline = storage.getLayerOutlines(layer_nr, include_helper_parts, external_only);
first_layer_outline = first_layer_outline.approxConvexHull();
}
else
{ // add brim underneath support by removing support where there's brim around the model
const bool include_helper_parts = false; // include manually below
first_layer_outline = storage.getLayerOutlines(layer_nr, include_helper_parts, external_only);
first_layer_outline.add(storage.primeTower.ground_poly); // don't remove parts of the prime tower, but make a brim for it
if (outside_only)
{
first_layer_outline = first_layer_outline.removeEmptyHoles();
}
if (storage.support.generated && primary_line_count > 0)
{ // remove model-brim from support
const Polygons& model_brim_covered_area = first_layer_outline.offset(primary_extruder_skirt_brim_line_width * (primary_line_count + primary_line_count % 2)); // always leave a gap of an even number of brim lines, so that it fits if it's generating brim from both sides
SupportLayer& support_layer = storage.support.supportLayers[0];
support_layer.supportAreas = support_layer.supportAreas.difference(model_brim_covered_area);
first_layer_outline.add(support_layer.supportAreas);
first_layer_outline.add(support_layer.skin);
}
}
}
int SkirtBrim::generatePrimarySkirtBrimLines(SliceDataStorage& storage, int start_distance, unsigned int primary_line_count, const int primary_extruder_skirt_brim_line_width, const int64_t primary_extruder_minimal_length, const Polygons& first_layer_outline, Polygons& skirt_brim_primary_extruder)
{
int offset_distance = start_distance - primary_extruder_skirt_brim_line_width / 2;
for (unsigned int skirt_brim_number = 0; skirt_brim_number < primary_line_count; skirt_brim_number++)
{
offset_distance += primary_extruder_skirt_brim_line_width;
Polygons outer_skirt_brim_line = first_layer_outline.offset(offset_distance, ClipperLib::jtRound);
//Remove small inner skirt and brim holes. Holes have a negative area, remove anything smaller then 100x extrusion "area"
for (unsigned int n = 0; n < outer_skirt_brim_line.size(); n++)
{
double area = outer_skirt_brim_line[n].area();
if (area < 0 && area > -primary_extruder_skirt_brim_line_width * primary_extruder_skirt_brim_line_width * 100)
{
outer_skirt_brim_line.remove(n--);
}
}
skirt_brim_primary_extruder.add(outer_skirt_brim_line);
int length = skirt_brim_primary_extruder.polygonLength();
if (skirt_brim_number + 1 >= primary_line_count && length > 0 && length < primary_extruder_minimal_length) //Make brim or skirt have more lines when total length is too small.
{
primary_line_count++;
}
}
return offset_distance;
}
void SkirtBrim::generate(SliceDataStorage& storage, int start_distance, unsigned int primary_line_count, bool outside_only)
{
bool is_skirt = start_distance > 0;
const int adhesion_extruder_nr = storage.getSettingAsIndex("adhesion_extruder_nr");
const ExtruderTrain* adhesion_extruder = storage.meshgroup->getExtruderTrain(adhesion_extruder_nr);
const int primary_extruder_skirt_brim_line_width = adhesion_extruder->getSettingInMicrons("skirt_brim_line_width");
const int64_t primary_extruder_minimal_length = adhesion_extruder->getSettingInMicrons("skirt_brim_minimal_length");
Polygons& skirt_brim_primary_extruder = storage.skirt_brim[adhesion_extruder_nr];
Polygons first_layer_outline;
getFirstLayerOutline(storage, primary_line_count, primary_extruder_skirt_brim_line_width, is_skirt, outside_only, first_layer_outline);
bool has_ooze_shield = storage.oozeShield.size() > 0 && storage.oozeShield[0].size() > 0 ;
bool has_draft_shield = storage.draft_protection_shield.size() > 0;
int offset_distance = generatePrimarySkirtBrimLines(storage, start_distance, primary_line_count, primary_extruder_skirt_brim_line_width, primary_extruder_minimal_length, first_layer_outline, skirt_brim_primary_extruder);
// generate brim for ooze shield and draft shield
if (!is_skirt && (has_ooze_shield || has_draft_shield))
{
// generate areas where to make extra brim for the shields
const int64_t primary_skirt_brim_width = (primary_line_count + primary_line_count % 2) * primary_extruder_skirt_brim_line_width; // always use an even number, because we will fil the area from both sides
Polygons shield_brim;
if (has_ooze_shield)
{
shield_brim = storage.oozeShield[0].difference(storage.oozeShield[0].offset(-primary_skirt_brim_width));
}
if (has_draft_shield)
{
shield_brim = shield_brim.unionPolygons(storage.draft_protection_shield.difference(storage.draft_protection_shield.offset(-primary_skirt_brim_width)));
}
const Polygons outer_primary_brim = first_layer_outline.offset(offset_distance, ClipperLib::jtRound);
shield_brim = shield_brim.difference(outer_primary_brim);
// generate brim within shield_brim
while (shield_brim.size() > 0)
{
shield_brim = shield_brim.offset(-primary_extruder_skirt_brim_line_width);
skirt_brim_primary_extruder.add(shield_brim);
}
// update parameters to generate secondary skirt around
first_layer_outline = storage.draft_protection_shield;
if (has_ooze_shield)
{
first_layer_outline = first_layer_outline.unionPolygons(storage.oozeShield[0]);
}
offset_distance = 0;
}
{ // process other extruders' brim/skirt (as one brim line around the old brim)
int last_width = primary_extruder_skirt_brim_line_width;
for (int extruder = 0; extruder < storage.meshgroup->getExtruderCount(); extruder++)
{
if (extruder == adhesion_extruder_nr || !storage.meshgroup->getExtruderTrain(extruder)->getIsUsed())
{
continue;
}
const ExtruderTrain* train = storage.meshgroup->getExtruderTrain(extruder);
const int width = train->getSettingInMicrons("skirt_brim_line_width");
const int64_t minimal_length = train->getSettingInMicrons("skirt_brim_minimal_length");
offset_distance += last_width / 2 + width/2;
last_width = width;
while (storage.skirt_brim[extruder].polygonLength() < minimal_length)
{
storage.skirt_brim[extruder].add(first_layer_outline.offset(offset_distance, ClipperLib::jtRound));
offset_distance += width;
}
}
}
}
}//namespace cura
<commit_msg>fix: shield-brim got odd number of brim lines, causing gaps (CURA-1062)<commit_after>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include "SkirtBrim.h"
#include "support.h"
namespace cura
{
void SkirtBrim::getFirstLayerOutline(SliceDataStorage& storage, const unsigned int primary_line_count, const int primary_extruder_skirt_brim_line_width, const bool is_skirt, const bool outside_only, Polygons& first_layer_outline)
{
bool external_only = is_skirt; // whether to include holes or not
const int layer_nr = 0;
if (is_skirt)
{
const bool include_helper_parts = true;
first_layer_outline = storage.getLayerOutlines(layer_nr, include_helper_parts, external_only);
first_layer_outline = first_layer_outline.approxConvexHull();
}
else
{ // add brim underneath support by removing support where there's brim around the model
const bool include_helper_parts = false; // include manually below
first_layer_outline = storage.getLayerOutlines(layer_nr, include_helper_parts, external_only);
first_layer_outline.add(storage.primeTower.ground_poly); // don't remove parts of the prime tower, but make a brim for it
if (outside_only)
{
first_layer_outline = first_layer_outline.removeEmptyHoles();
}
if (storage.support.generated && primary_line_count > 0)
{ // remove model-brim from support
const Polygons& model_brim_covered_area = first_layer_outline.offset(primary_extruder_skirt_brim_line_width * (primary_line_count + primary_line_count % 2)); // always leave a gap of an even number of brim lines, so that it fits if it's generating brim from both sides
SupportLayer& support_layer = storage.support.supportLayers[0];
support_layer.supportAreas = support_layer.supportAreas.difference(model_brim_covered_area);
first_layer_outline.add(support_layer.supportAreas);
first_layer_outline.add(support_layer.skin);
}
}
}
int SkirtBrim::generatePrimarySkirtBrimLines(SliceDataStorage& storage, int start_distance, unsigned int primary_line_count, const int primary_extruder_skirt_brim_line_width, const int64_t primary_extruder_minimal_length, const Polygons& first_layer_outline, Polygons& skirt_brim_primary_extruder)
{
int offset_distance = start_distance - primary_extruder_skirt_brim_line_width / 2;
for (unsigned int skirt_brim_number = 0; skirt_brim_number < primary_line_count; skirt_brim_number++)
{
offset_distance += primary_extruder_skirt_brim_line_width;
Polygons outer_skirt_brim_line = first_layer_outline.offset(offset_distance, ClipperLib::jtRound);
//Remove small inner skirt and brim holes. Holes have a negative area, remove anything smaller then 100x extrusion "area"
for (unsigned int n = 0; n < outer_skirt_brim_line.size(); n++)
{
double area = outer_skirt_brim_line[n].area();
if (area < 0 && area > -primary_extruder_skirt_brim_line_width * primary_extruder_skirt_brim_line_width * 100)
{
outer_skirt_brim_line.remove(n--);
}
}
skirt_brim_primary_extruder.add(outer_skirt_brim_line);
int length = skirt_brim_primary_extruder.polygonLength();
if (skirt_brim_number + 1 >= primary_line_count && length > 0 && length < primary_extruder_minimal_length) //Make brim or skirt have more lines when total length is too small.
{
primary_line_count++;
}
}
return offset_distance;
}
void SkirtBrim::generate(SliceDataStorage& storage, int start_distance, unsigned int primary_line_count, bool outside_only)
{
bool is_skirt = start_distance > 0;
const int adhesion_extruder_nr = storage.getSettingAsIndex("adhesion_extruder_nr");
const ExtruderTrain* adhesion_extruder = storage.meshgroup->getExtruderTrain(adhesion_extruder_nr);
const int primary_extruder_skirt_brim_line_width = adhesion_extruder->getSettingInMicrons("skirt_brim_line_width");
const int64_t primary_extruder_minimal_length = adhesion_extruder->getSettingInMicrons("skirt_brim_minimal_length");
Polygons& skirt_brim_primary_extruder = storage.skirt_brim[adhesion_extruder_nr];
Polygons first_layer_outline;
getFirstLayerOutline(storage, primary_line_count, primary_extruder_skirt_brim_line_width, is_skirt, outside_only, first_layer_outline);
bool has_ooze_shield = storage.oozeShield.size() > 0 && storage.oozeShield[0].size() > 0 ;
bool has_draft_shield = storage.draft_protection_shield.size() > 0;
int offset_distance = generatePrimarySkirtBrimLines(storage, start_distance, primary_line_count, primary_extruder_skirt_brim_line_width, primary_extruder_minimal_length, first_layer_outline, skirt_brim_primary_extruder);
// generate brim for ooze shield and draft shield
if (!is_skirt && (has_ooze_shield || has_draft_shield))
{
// generate areas where to make extra brim for the shields
const int64_t primary_skirt_brim_width = (primary_line_count + primary_line_count % 2) * primary_extruder_skirt_brim_line_width; // always use an even number, because we will fil the area from both sides
Polygons shield_brim;
if (has_ooze_shield)
{
shield_brim = storage.oozeShield[0].difference(storage.oozeShield[0].offset(-primary_skirt_brim_width - primary_extruder_skirt_brim_line_width));
}
if (has_draft_shield)
{
shield_brim = shield_brim.unionPolygons(storage.draft_protection_shield.difference(storage.draft_protection_shield.offset(-primary_skirt_brim_width - primary_extruder_skirt_brim_line_width)));
}
const Polygons outer_primary_brim = first_layer_outline.offset(offset_distance, ClipperLib::jtRound);
shield_brim = shield_brim.difference(outer_primary_brim);
// generate brim within shield_brim
while (shield_brim.size() > 0)
{
shield_brim = shield_brim.offset(-primary_extruder_skirt_brim_line_width);
skirt_brim_primary_extruder.add(shield_brim);
}
// update parameters to generate secondary skirt around
first_layer_outline = storage.draft_protection_shield;
if (has_ooze_shield)
{
first_layer_outline = first_layer_outline.unionPolygons(storage.oozeShield[0]);
}
offset_distance = 0;
}
{ // process other extruders' brim/skirt (as one brim line around the old brim)
int last_width = primary_extruder_skirt_brim_line_width;
for (int extruder = 0; extruder < storage.meshgroup->getExtruderCount(); extruder++)
{
if (extruder == adhesion_extruder_nr || !storage.meshgroup->getExtruderTrain(extruder)->getIsUsed())
{
continue;
}
const ExtruderTrain* train = storage.meshgroup->getExtruderTrain(extruder);
const int width = train->getSettingInMicrons("skirt_brim_line_width");
const int64_t minimal_length = train->getSettingInMicrons("skirt_brim_minimal_length");
offset_distance += last_width / 2 + width/2;
last_width = width;
while (storage.skirt_brim[extruder].polygonLength() < minimal_length)
{
storage.skirt_brim[extruder].add(first_layer_outline.offset(offset_distance, ClipperLib::jtRound));
offset_distance += width;
}
}
}
}
}//namespace cura
<|endoftext|> |
<commit_before>/* Copyright (c) 2009-2011 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <getopt.h>
#include <gtest/gtest.h>
#include "Common.h"
#include "Tub.h"
namespace {
/**
* Replaces gtest's PrettyUnitTestResultPrinter with something less verbose.
* This forwards callbacks to the default printer if and when they might be
* interesting.
*/
class QuietUnitTestResultPrinter : public testing::TestEventListener {
public:
/**
* Constructor.
* \param prettyPrinter
* gtest's default unit test result printer. This object takes
* ownership of prettyPrinter and will delete it later.
*/
explicit QuietUnitTestResultPrinter(TestEventListener* prettyPrinter)
: prettyPrinter(prettyPrinter)
, currentTestCase(NULL)
, currentTestInfo(NULL)
{}
void OnTestProgramStart(const testing::UnitTest& unit_test) {
prettyPrinter->OnTestProgramStart(unit_test);
}
void OnTestIterationStart(const testing::UnitTest& unit_test,
int iteration) {
prettyPrinter->OnTestIterationStart(unit_test, iteration);
}
void OnEnvironmentsSetUpStart(const testing::UnitTest& unit_test) {}
void OnEnvironmentsSetUpEnd(const testing::UnitTest& unit_test) {}
void OnTestCaseStart(const testing::TestCase& test_case) {
currentTestCase = &test_case;
}
void OnTestStart(const testing::TestInfo& test_info) {
currentTestInfo = &test_info;
}
void OnTestPartResult(const testing::TestPartResult& test_part_result) {
if (test_part_result.type() != testing::TestPartResult::kSuccess) {
if (currentTestCase != NULL) {
prettyPrinter->OnTestCaseStart(*currentTestCase);
currentTestCase = NULL;
}
if (currentTestInfo != NULL) {
prettyPrinter->OnTestStart(*currentTestInfo);
currentTestInfo = NULL;
}
prettyPrinter->OnTestPartResult(test_part_result);
}
}
void OnTestEnd(const testing::TestInfo& test_info) {
currentTestInfo = NULL;
}
void OnTestCaseEnd(const testing::TestCase& test_case) {
currentTestCase = NULL;
}
void OnEnvironmentsTearDownStart(const testing::UnitTest& unit_test) {}
void OnEnvironmentsTearDownEnd(const testing::UnitTest& unit_test) {}
void OnTestIterationEnd(const testing::UnitTest& unit_test,
int iteration) {
prettyPrinter->OnTestIterationEnd(unit_test, iteration);
}
void OnTestProgramEnd(const testing::UnitTest& unit_test) {
prettyPrinter->OnTestProgramEnd(unit_test);
}
private:
/// gtest's default unit test result printer.
std::unique_ptr<TestEventListener> prettyPrinter;
/// The currently running TestCase that hasn't been printed, or NULL.
const testing::TestCase* currentTestCase;
/// The currently running TestInfo that hasn't been printed, or NULL.
const testing::TestInfo* currentTestInfo;
DISALLOW_COPY_AND_ASSIGN(QuietUnitTestResultPrinter);
};
bool progress = false;
void __attribute__ ((noreturn))
usage(char *arg0)
{
printf("Usage: %s "
"[-p]\n"
"\t-p\t--progress\tShow test progress.\n",
arg0);
exit(EXIT_FAILURE);
}
void
cmdline(int argc, char *argv[])
{
struct option long_options[] = {
{"progress", no_argument, NULL, 'p'},
{0, 0, 0, 0},
};
int c;
int i = 0;
while ((c = getopt_long(argc, argv, ":p",
long_options, &i)) >= 0)
{
switch (c) {
case 'p':
progress = true;
break;
default:
usage(argv[0]);
}
}
}
} // anonymous namespace
int
main(int argc, char *argv[])
{
int googleArgc = 0;
char* googleArgv[] = {NULL};
::testing::InitGoogleTest(&googleArgc, googleArgv);
cmdline(argc, argv);
auto unitTest = ::testing::UnitTest::GetInstance();
auto& listeners = unitTest->listeners();
// set up the environment for unit tests
struct GTestSetupListener : public ::testing::EmptyTestEventListener {
GTestSetupListener()
: testContext()
, scopedContext() {}
// this fires before each test fixture's constructor
void OnTestStart(const ::testing::TestInfo& testInfo) {
testContext.construct(false);
scopedContext.construct(*testContext);
testContext->logger->setLogLevels(RAMCloud::WARNING);
}
// this fires after each test fixture's destructor
void OnTestEnd(const ::testing::TestInfo& testInfo) {
scopedContext.destroy();
testContext.destroy();
}
RAMCloud::Tub<RAMCloud::Context> testContext;
RAMCloud::Tub<RAMCloud::Context::Guard> scopedContext;
};
listeners.Append(new GTestSetupListener());
if (!progress) {
// replace default output printer with quiet one
auto defaultPrinter = listeners.Release(
listeners.default_result_printer());
listeners.Append(new QuietUnitTestResultPrinter(defaultPrinter));
}
return RUN_ALL_TESTS();
}
<commit_msg>Change TestRunner.cc from getopt to boost::program_options<commit_after>/* Copyright (c) 2009-2011 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <gtest/gtest.h>
#include <boost/program_options.hpp>
#include "Common.h"
#include "Tub.h"
namespace {
/**
* Replaces gtest's PrettyUnitTestResultPrinter with something less verbose.
* This forwards callbacks to the default printer if and when they might be
* interesting.
*/
class QuietUnitTestResultPrinter : public testing::TestEventListener {
public:
/**
* Constructor.
* \param prettyPrinter
* gtest's default unit test result printer. This object takes
* ownership of prettyPrinter and will delete it later.
*/
explicit QuietUnitTestResultPrinter(TestEventListener* prettyPrinter)
: prettyPrinter(prettyPrinter)
, currentTestCase(NULL)
, currentTestInfo(NULL)
{}
void OnTestProgramStart(const testing::UnitTest& unit_test) {
prettyPrinter->OnTestProgramStart(unit_test);
}
void OnTestIterationStart(const testing::UnitTest& unit_test,
int iteration) {
prettyPrinter->OnTestIterationStart(unit_test, iteration);
}
void OnEnvironmentsSetUpStart(const testing::UnitTest& unit_test) {}
void OnEnvironmentsSetUpEnd(const testing::UnitTest& unit_test) {}
void OnTestCaseStart(const testing::TestCase& test_case) {
currentTestCase = &test_case;
}
void OnTestStart(const testing::TestInfo& test_info) {
currentTestInfo = &test_info;
}
void OnTestPartResult(const testing::TestPartResult& test_part_result) {
if (test_part_result.type() != testing::TestPartResult::kSuccess) {
if (currentTestCase != NULL) {
prettyPrinter->OnTestCaseStart(*currentTestCase);
currentTestCase = NULL;
}
if (currentTestInfo != NULL) {
prettyPrinter->OnTestStart(*currentTestInfo);
currentTestInfo = NULL;
}
prettyPrinter->OnTestPartResult(test_part_result);
}
}
void OnTestEnd(const testing::TestInfo& test_info) {
currentTestInfo = NULL;
}
void OnTestCaseEnd(const testing::TestCase& test_case) {
currentTestCase = NULL;
}
void OnEnvironmentsTearDownStart(const testing::UnitTest& unit_test) {}
void OnEnvironmentsTearDownEnd(const testing::UnitTest& unit_test) {}
void OnTestIterationEnd(const testing::UnitTest& unit_test,
int iteration) {
prettyPrinter->OnTestIterationEnd(unit_test, iteration);
}
void OnTestProgramEnd(const testing::UnitTest& unit_test) {
prettyPrinter->OnTestProgramEnd(unit_test);
}
private:
/// gtest's default unit test result printer.
std::unique_ptr<TestEventListener> prettyPrinter;
/// The currently running TestCase that hasn't been printed, or NULL.
const testing::TestCase* currentTestCase;
/// The currently running TestInfo that hasn't been printed, or NULL.
const testing::TestInfo* currentTestInfo;
DISALLOW_COPY_AND_ASSIGN(QuietUnitTestResultPrinter);
};
bool progress = false;
} // anonymous namespace
int
main(int argc, char *argv[])
{
namespace po = boost::program_options;
po::options_description configOptions("TestRunner");
configOptions.add_options()
("help,h", "Produce help message")
("verbose,v",
po::value<bool>(&progress)->
default_value(false),
"Show test progress");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, configOptions), vm);
po::notify(vm);
if (vm.count("help")) {
std::cerr << configOptions << std::endl;
exit(1);
}
int googleArgc = 0;
char* googleArgv[] = {NULL};
::testing::InitGoogleTest(&googleArgc, googleArgv);
auto unitTest = ::testing::UnitTest::GetInstance();
auto& listeners = unitTest->listeners();
// set up the environment for unit tests
struct GTestSetupListener : public ::testing::EmptyTestEventListener {
GTestSetupListener()
: testContext()
, scopedContext() {}
// this fires before each test fixture's constructor
void OnTestStart(const ::testing::TestInfo& testInfo) {
testContext.construct(false);
scopedContext.construct(*testContext);
testContext->logger->setLogLevels(RAMCloud::WARNING);
}
// this fires after each test fixture's destructor
void OnTestEnd(const ::testing::TestInfo& testInfo) {
scopedContext.destroy();
testContext.destroy();
}
RAMCloud::Tub<RAMCloud::Context> testContext;
RAMCloud::Tub<RAMCloud::Context::Guard> scopedContext;
};
listeners.Append(new GTestSetupListener());
if (!progress) {
// replace default output printer with quiet one
auto defaultPrinter = listeners.Release(
listeners.default_result_printer());
listeners.Append(new QuietUnitTestResultPrinter(defaultPrinter));
}
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>#ifndef SROOK_INCLUDE_VARIADIC_PLAYER_HPP
#define SROOK_INCLUDE_VARIADIC_PLAYER_HPP
#include<srook/mpl/variadic_tmp_player.hpp>
namespace srook{
namespace mpl{
inline namespace v1{
// Tag to ***er.
// These tags have feautures that changing the mode(Single/All).
namespace variadic_tag{
struct Single{};
struct All{};
}
// Eraser
template<class,class,class...>
struct Eraser;
template<class Mode,class T,class Head,class... Tail>
struct Eraser<Mode,T,Head,Tail...>{
using type=Concat_t<Head,typename Eraser<Mode,T,Tail...>::type>;
};
template<class T,class... Tail>
struct Eraser<variadic_tag::Single,T,T,Tail...>{
using type=pack<Tail...>;
};
template<class T,class... Tail>
struct Eraser<variadic_tag::All,T,T,Tail...>{
using type=typename Eraser<variadic_tag::All,Tail...>::type;
};
template<class Mode,class Tail>
struct Eraser<Mode,Tail>{
using type=pack<>;
};
template<class Mode,class T,class Head,class... Tail>
struct Eraser<Mode,T,pack<Head,Tail...>>:Eraser<Mode,T,Head,Tail...>{};
template<class Mode,class T,class... Pack>
using Eraser_t=typename Eraser<Mode,T,Pack...>::type;
// Replacer
template<class,class,class,class... Pack>
struct Replacer;
template<class Mode,class T,class R,class Head,class... Pack>
struct Replacer<Mode,T,R,Head,Pack...>{
using type=Concat_t<Head,typename Replacer<Mode,T,R,Pack...>::type>;
};
template<class T,class R,class... Pack>
struct Replacer<variadic_tag::Single,T,R,T,Pack...>{
using type=pack<R,Pack...>;
};
template<class T,class R,class... Pack>
struct Replacer<variadic_tag::All,T,R,T,Pack...>{
using type=Concat_t<R,typename Replacer<variadic_tag::All,T,R,Pack...>::type>;
};
template<class Mode,class T,class R>
struct Replacer<Mode,T,R>{
using type=pack<>;
};
template<class Mode,class T,class R,class Head,class... Pack>
struct Replacer<Mode,T,R,pack<Head,Pack...>>:Replacer<Mode,T,R,Head,Pack...>{};
template<class Mode,class T,class R,class... Pack>
using Replacer_t=typename Replacer<Mode,T,R,Pack...>::type;
} // namespace v1
} // namespace mpl
} // namespace srook
#endif
<commit_msg>add generator<commit_after>#ifndef SROOK_INCLUDE_VARIADIC_PLAYER_HPP
#define SROOK_INCLUDE_VARIADIC_PLAYER_HPP
#include<srook/mpl/variadic_tmp_player.hpp>
namespace srook{
namespace mpl{
inline namespace v1{
// Tag to ***er.
// These tags have feautures that changing the mode(Single/All).
namespace variadic_tag{
struct Single{};
struct All{};
}
// Eraser
template<class,class,class...>
struct Eraser;
template<class Mode,class T,class Head,class... Tail>
struct Eraser<Mode,T,Head,Tail...>{
using type=Concat_t<Head,typename Eraser<Mode,T,Tail...>::type>;
};
template<class T,class... Tail>
struct Eraser<variadic_tag::Single,T,T,Tail...>{
using type=pack<Tail...>;
};
template<class T,class... Tail>
struct Eraser<variadic_tag::All,T,T,Tail...>{
using type=typename Eraser<variadic_tag::All,Tail...>::type;
};
template<class Mode,class Tail>
struct Eraser<Mode,Tail>{
using type=pack<>;
};
template<class Mode,class T,class Head,class... Tail>
struct Eraser<Mode,T,pack<Head,Tail...>>:Eraser<Mode,T,Head,Tail...>{};
template<class Mode,class T,class... Pack>
using Eraser_t=typename Eraser<Mode,T,Pack...>::type;
// Replacer
template<class,class,class,class... Pack>
struct Replacer;
template<class Mode,class T,class R,class Head,class... Pack>
struct Replacer<Mode,T,R,Head,Pack...>{
using type=Concat_t<Head,typename Replacer<Mode,T,R,Pack...>::type>;
};
template<class T,class R,class... Pack>
struct Replacer<variadic_tag::Single,T,R,T,Pack...>{
using type=pack<R,Pack...>;
};
template<class T,class R,class... Pack>
struct Replacer<variadic_tag::All,T,R,T,Pack...>{
using type=Concat_t<R,typename Replacer<variadic_tag::All,T,R,Pack...>::type>;
};
template<class Mode,class T,class R>
struct Replacer<Mode,T,R>{
using type=pack<>;
};
template<class Mode,class T,class R,class Head,class... Pack>
struct Replacer<Mode,T,R,pack<Head,Pack...>>:Replacer<Mode,T,R,Head,Pack...>{};
template<class Mode,class T,class R,class... Pack>
using Replacer_t=typename Replacer<Mode,T,R,Pack...>::type;
// make pack: automatic pack generater
template<class T,std::size_t size>
struct make_pack_impl{
using type=Concat_t<T,typename make_pack_impl<T,size-1>::type>;
};
template<class T>
struct make_pack_impl<T,0>{
using type=pack<>;
};
template<class T,std::size_t size>
using make_pack=typename make_pack_impl<T,size>::type;
// pack setting
template<class T,std::size_t s>
struct pack_setting{
static constexpr std::size_t size=s;
using type=T;
};
// make some pack: automatic multiple types pack generater
template<class... PackSetting>
struct make_someting_pack_impl{
private:
using inner_type=make_pack<typename First_t<PackSetting...>::type,First_t<PackSetting...>::size>;
public:
using type=Concat_t<inner_type,typename make_someting_pack_impl<PopFront_t<PackSetting...>>::type>;
};
template<>
struct make_someting_pack_impl<pack<>>{
using type=pack<>;
};
template<class... PackSetting>
using make_some_pack=typename make_someting_pack_impl<PackSetting...>::type;
} // namespace v1
} // namespace mpl
} // namespace srook
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017 alexi [email protected]
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <thread>
#include <stdlib.h>
#include "simple_protocol.hpp"
#include "server.hpp"
void usage(const std::string &usg)
{
errno = EINVAL;
perror("Error");
std::cout << "Usage: \n" << usg << std::endl;
exit (errno);
}
int main(int ac, char* av[]) {
std::string usg = std::string(av[0]) + " <port>";
if (ac != 2) {
usage(usg);
}
int port = atoi(av[1]);
std::unique_ptr<Server> connection(new Server(port));
std::unique_ptr<IProtocol> srv_proto(new SimpleProtocol());
connection->setProtocol(std::move(srv_proto));
connection->run();
std::cout << "The end!" << std::endl;
return 0;
}
<commit_msg>minor fix`<commit_after>/*
* Copyright (c) 2017 alexi [email protected]
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <thread>
#include <stdlib.h>
#include "simple_protocol.hpp"
#include "server.hpp"
void usage(const std::string &usg)
{
errno = EINVAL;
perror("Error");
std::cout << "Usage: \n" << usg << std::endl;
exit (errno);
}
int main(int ac, char* av[]) {
std::string usg = std::string(av[0]) + " <port>";
if (ac != 2) {
usage(usg);
}
int port = atoi(av[1]);
std::unique_ptr<Server> connection(new Server(port));
std::unique_ptr<IProtocol> srv_proto(new SimpleProtocol());
connection->setProtocol(std::move(srv_proto));
connection->run();
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "server.h"
Server::Server(unsigned short port) {
// logging settings
bottleserve.set_access_channels(websocketpp::log::alevel::all);
bottleserve.clear_access_channels(websocketpp::log::alevel::frame_payload);
bottleserve.init_asio();
bottleserve.set_message_handler([this] (websocketpp::connection_hdl hdl, message_ptr msg) {
bottleserve.send(hdl, msg->get_payload(), msg->get_opcode());
std::cout << msg->get_raw_payload() << std::endl;
});
bottleserve.listen(port);
}
void Server::run() {
bottleserve.start_accept();
bottleserve.run();
}
<commit_msg>Add a simple login feature<commit_after>#include <iostream>
#include <sstream>
#include "server.h"
using namespace std;
/*
* Splits a string based on a delimiter character
*
* Won't split into more than 'max' strings. Returns the number of strings that were added
*/
template<typename Iter>
size_t split(const string& str, char val, size_t max, Iter out) {
stringstream ss(str);
string s;
size_t len = 0;
// I love the "goes to" operator (-->)
while( max --> 0 ) {
if(!getline(ss, s, max ? val : '\0')) {
return len;
}
len++;
*out++ = s;
}
return len;
}
bool valid_user(const string& user, const string& pass) {
// TODO: Actually check the username and password here
return user == "anon" || (user == "corny" && pass == "1234");
}
Server::Server(unsigned short port) {
// logging settings
bottleserve.set_access_channels(websocketpp::log::alevel::all);
bottleserve.clear_access_channels(websocketpp::log::alevel::frame_payload);
bottleserve.init_asio();
bottleserve.set_message_handler([this] (websocketpp::connection_hdl hdl, message_ptr msg) {
using namespace websocketpp;
if(msg->get_opcode() != frame::opcode::text) {
bottleserve.close(hdl, close::status::unsupported_data, "Only text data allowed");
return;
}
const auto & line = msg->get_payload();
array<string,3> login;
if(login.size() != split(line, ' ', login.size(), login.begin())
|| login[0] != "login"
|| !valid_user(login[1], login[2])) {
bottleserve.close(hdl, close::status::unsupported_data, "Invalid login");
return;
}
// TODO: Create a connection
bottleserve.send(hdl, msg->get_payload(), msg->get_opcode());
cout << msg->get_opcode() << endl;
cout << msg->get_raw_payload() << endl;
});
bottleserve.listen(port);
}
void Server::run() {
bottleserve.start_accept();
bottleserve.run();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Cloudius Systems
*/
#include "apps/httpd/request_parser.hh"
#include "core/reactor.hh"
#include "core/sstring.hh"
#include "core/app-template.hh"
#include "core/circular_buffer.hh"
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <queue>
#include <bitset>
#include <limits>
#include <cctype>
class http_server {
std::vector<server_socket> _listeners;
public:
void listen(ipv4_addr addr) {
listen_options lo;
lo.reuse_address = true;
_listeners.push_back(engine.listen(make_ipv4_address(addr), lo));
do_accepts(_listeners.size() - 1);
}
void do_accepts(int which) {
_listeners[which].accept().then([this, which] (connected_socket fd, socket_address addr) mutable {
(new connection(*this, std::move(fd), addr))->read().rescue([this] (auto get_ex) {
try {
get_ex();
} catch (std::exception& ex) {
std::cout << "request error " << ex.what() << "\n";
}
});
do_accepts(which);
}).rescue([] (auto get_ex) {
try {
get_ex();
} catch (std::exception& ex) {
std::cout << "accept failed: " << ex.what() << "\n";
}
});
}
class connection {
connected_socket _fd;
input_stream<char> _read_buf;
output_stream<char> _write_buf;
bool _eof = false;
static constexpr size_t limit = 4096;
using tmp_buf = temporary_buffer<char>;
using request = http_request;
struct response {
sstring _response_line;
sstring _body;
std::unordered_map<sstring, sstring> _headers;
};
http_request_parser _parser;
std::unique_ptr<request> _req;
std::unique_ptr<response> _resp;
std::queue<std::unique_ptr<response>,
circular_buffer<std::unique_ptr<response>>> _pending_responses;
public:
connection(http_server& server, connected_socket&& fd, socket_address addr)
: _fd(std::move(fd)), _read_buf(_fd.input())
, _write_buf(_fd.output()) {}
future<> read() {
_parser.init();
return _read_buf.consume(_parser).then([this] {
if (_parser.eof()) {
maybe_done();
return make_ready_future<>();
}
_req = _parser.get_parsed_request();
generate_response(std::move(_req));
read().rescue([this] (auto get_ex) mutable {
try {
get_ex();
} catch (std::exception& ex) {
std::cout << "read failed with " << ex.what() << "\n";
this->maybe_done();
}
});
return make_ready_future<>();
});
}
void respond(std::unique_ptr<response> resp) {
if (!_resp) {
_resp = std::move(resp);
start_response();
} else {
_pending_responses.push(std::move(resp));
}
}
void start_response() {
_resp->_headers["Content-Length"] = to_sstring(_resp->_body.size());
_write_buf.write(_resp->_response_line.begin(), _resp->_response_line.size()).then(
[this] {
return write_response_headers(_resp->_headers.begin());
}).then([this] {
return _write_buf.write("\r\n", 2);
}).then([this] {
return write_body();
}).then([this] {
return _write_buf.flush();
}).then([this] {
_resp.reset();
if (!_pending_responses.empty()) {
_resp = std::move(_pending_responses.front());
_pending_responses.pop();
start_response();
} else {
maybe_done();
}
});
}
future<> write_response_headers(std::unordered_map<sstring, sstring>::iterator hi) {
if (hi == _resp->_headers.end()) {
return make_ready_future<>();
}
return _write_buf.write(hi->first.begin(), hi->first.size()).then(
[this] {
return _write_buf.write(": ", 2);
}).then([hi, this] {
return _write_buf.write(hi->second.begin(), hi->second.size());
}).then([this] {
return _write_buf.write("\r\n", 2);
}).then([hi, this] () mutable {
return write_response_headers(++hi);
});
}
void generate_response(std::unique_ptr<request> req) {
auto resp = std::make_unique<response>();
bool conn_keep_alive = false;
bool conn_close = false;
auto it = req->_headers.find("Connection");
if (it != req->_headers.end()) {
if (it->second == "Keep-Alive") {
conn_keep_alive = true;
} else if (it->second == "Close") {
conn_close = true;
}
}
bool should_close;
// TODO: Handle HTTP/2.0 when it releases
if (req->_version == "1.0") {
resp->_response_line = "HTTP/1.0 200 OK\r\n";
if (conn_keep_alive) {
resp->_headers["Connection"] = "Keep-Alive";
}
should_close = !conn_keep_alive;
} else if (req->_version == "1.1") {
resp->_response_line = "HTTP/1.1 200 OK\r\n";
should_close = conn_close;
} else {
// HTTP/0.9 goes here
resp->_response_line = "HTTP/1.0 200 OK\r\n";
should_close = true;
}
resp->_headers["Content-Type"] = "text/html";
resp->_body = "<html><head><title>this is the future</title></head><body><p>Future!!</p></body></html>";
respond(std::move(resp));
if (should_close) {
_write_buf.close();
}
}
future<> write_body() {
return _write_buf.write(_resp->_body.begin(), _resp->_body.size());
}
void maybe_done() {
if ((_eof || _read_buf.eof()) && !_req && !_resp && _pending_responses.empty()) {
delete this;
}
}
};
};
int main(int ac, char** av) {
app_template app;
app.add_options()
("port", bpo::value<uint16_t>()->default_value(10000), "HTTP Server port") ;
return app.run(ac, av, [&] {
auto&& config = app.configuration();
uint16_t port = config["port"].as<uint16_t>();
std::cout << "Seastar HTTP server listening on port " << port << " ...\n";
for(unsigned c = 0; c < smp::count; c++) {
smp::submit_to(c, [port] () mutable {static thread_local http_server server; server.listen({port});});
}
});
}
<commit_msg>http: convert to use distributed<> infrastructure<commit_after>/*
* Copyright 2014 Cloudius Systems
*/
#include "apps/httpd/request_parser.hh"
#include "core/reactor.hh"
#include "core/sstring.hh"
#include "core/app-template.hh"
#include "core/circular_buffer.hh"
#include "core/smp.hh"
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <queue>
#include <bitset>
#include <limits>
#include <cctype>
class http_server {
std::vector<server_socket> _listeners;
public:
future<> listen(ipv4_addr addr) {
listen_options lo;
lo.reuse_address = true;
_listeners.push_back(engine.listen(make_ipv4_address(addr), lo));
do_accepts(_listeners.size() - 1);
return make_ready_future<>();
}
void do_accepts(int which) {
_listeners[which].accept().then([this, which] (connected_socket fd, socket_address addr) mutable {
(new connection(*this, std::move(fd), addr))->read().rescue([this] (auto get_ex) {
try {
get_ex();
} catch (std::exception& ex) {
std::cout << "request error " << ex.what() << "\n";
}
});
do_accepts(which);
}).rescue([] (auto get_ex) {
try {
get_ex();
} catch (std::exception& ex) {
std::cout << "accept failed: " << ex.what() << "\n";
}
});
}
class connection {
connected_socket _fd;
input_stream<char> _read_buf;
output_stream<char> _write_buf;
bool _eof = false;
static constexpr size_t limit = 4096;
using tmp_buf = temporary_buffer<char>;
using request = http_request;
struct response {
sstring _response_line;
sstring _body;
std::unordered_map<sstring, sstring> _headers;
};
http_request_parser _parser;
std::unique_ptr<request> _req;
std::unique_ptr<response> _resp;
std::queue<std::unique_ptr<response>,
circular_buffer<std::unique_ptr<response>>> _pending_responses;
public:
connection(http_server& server, connected_socket&& fd, socket_address addr)
: _fd(std::move(fd)), _read_buf(_fd.input())
, _write_buf(_fd.output()) {}
future<> read() {
_parser.init();
return _read_buf.consume(_parser).then([this] {
if (_parser.eof()) {
maybe_done();
return make_ready_future<>();
}
_req = _parser.get_parsed_request();
generate_response(std::move(_req));
read().rescue([this] (auto get_ex) mutable {
try {
get_ex();
} catch (std::exception& ex) {
std::cout << "read failed with " << ex.what() << "\n";
this->maybe_done();
}
});
return make_ready_future<>();
});
}
void respond(std::unique_ptr<response> resp) {
if (!_resp) {
_resp = std::move(resp);
start_response();
} else {
_pending_responses.push(std::move(resp));
}
}
void start_response() {
_resp->_headers["Content-Length"] = to_sstring(_resp->_body.size());
_write_buf.write(_resp->_response_line.begin(), _resp->_response_line.size()).then(
[this] {
return write_response_headers(_resp->_headers.begin());
}).then([this] {
return _write_buf.write("\r\n", 2);
}).then([this] {
return write_body();
}).then([this] {
return _write_buf.flush();
}).then([this] {
_resp.reset();
if (!_pending_responses.empty()) {
_resp = std::move(_pending_responses.front());
_pending_responses.pop();
start_response();
} else {
maybe_done();
}
});
}
future<> write_response_headers(std::unordered_map<sstring, sstring>::iterator hi) {
if (hi == _resp->_headers.end()) {
return make_ready_future<>();
}
return _write_buf.write(hi->first.begin(), hi->first.size()).then(
[this] {
return _write_buf.write(": ", 2);
}).then([hi, this] {
return _write_buf.write(hi->second.begin(), hi->second.size());
}).then([this] {
return _write_buf.write("\r\n", 2);
}).then([hi, this] () mutable {
return write_response_headers(++hi);
});
}
void generate_response(std::unique_ptr<request> req) {
auto resp = std::make_unique<response>();
bool conn_keep_alive = false;
bool conn_close = false;
auto it = req->_headers.find("Connection");
if (it != req->_headers.end()) {
if (it->second == "Keep-Alive") {
conn_keep_alive = true;
} else if (it->second == "Close") {
conn_close = true;
}
}
bool should_close;
// TODO: Handle HTTP/2.0 when it releases
if (req->_version == "1.0") {
resp->_response_line = "HTTP/1.0 200 OK\r\n";
if (conn_keep_alive) {
resp->_headers["Connection"] = "Keep-Alive";
}
should_close = !conn_keep_alive;
} else if (req->_version == "1.1") {
resp->_response_line = "HTTP/1.1 200 OK\r\n";
should_close = conn_close;
} else {
// HTTP/0.9 goes here
resp->_response_line = "HTTP/1.0 200 OK\r\n";
should_close = true;
}
resp->_headers["Content-Type"] = "text/html";
resp->_body = "<html><head><title>this is the future</title></head><body><p>Future!!</p></body></html>";
respond(std::move(resp));
if (should_close) {
_write_buf.close();
}
}
future<> write_body() {
return _write_buf.write(_resp->_body.begin(), _resp->_body.size());
}
void maybe_done() {
if ((_eof || _read_buf.eof()) && !_req && !_resp && _pending_responses.empty()) {
delete this;
}
}
};
};
int main(int ac, char** av) {
app_template app;
app.add_options()
("port", bpo::value<uint16_t>()->default_value(10000), "HTTP Server port") ;
return app.run(ac, av, [&] {
auto&& config = app.configuration();
uint16_t port = config["port"].as<uint16_t>();
auto server = new distributed<http_server>;
server->start().then([server = std::move(server), port] () mutable {
server->invoke_on_all(&http_server::listen, ipv4_addr{port});
}).then([port] {
std::cout << "Seastar HTTP server listening on port " << port << " ...\n";
});
});
}
<|endoftext|> |
<commit_before>#include <vector>
#include <cmath>
#include <set>
#include <cassert>
#include "../include/graph.h"
#include "../include/tournament.h"
#include "../include/exceptions.h"
typedef std::shared_ptr<Tournament> tournament_ptr;
bool check_if_fixable(TournamentGraph& graph, std::set<int>& nodes, int winner)
{
int wins = 0;
for(auto node: nodes)
{
if(node != winner && graph.wins(winner, node))
wins++;
}
if (wins < log2(nodes.size()))
return false;
else
{
for (auto node1: nodes)
{
if(node1 == winner)
continue;
wins = 0;
for (auto node2: nodes)
{
if(node1 == node2)
continue;
if(graph.wins(node1, node2))
wins++;
else
break;
}
if(wins == nodes.size() - 1)
return false;
}
return true;
}
}
bool check_if_case_A(TournamentGraph& graph, std::set<int>& nodes, int winner)
{
int wins = 0;
int max_wins_from_losses = 0;
int wins_from_losses;
for(auto node1: nodes)
{
if(node1 != winner && graph.wins(winner, node1))
wins++;
else
{
wins_from_losses = 0;
for (auto node2: nodes)
{
if(node1 == node2)
break;
if(graph.wins(node1,node2))
wins_from_losses++;
}
if(wins_from_losses > max_wins_from_losses)
{
max_wins_from_losses = wins_from_losses;
}
}
}
return wins > max_wins_from_losses;
}
tournament_ptr fix_tournament_A(TournamentGraph& graph,
std::set<int>& nodes, int winner)
{
std::set<tournament_ptr> won_tournaments, lost_tournaments;
for(auto node: nodes)
{
if(winner == node)
continue;
if(graph.wins(winner, node))
won_tournaments.insert(
tournament_ptr(new Tournament(&graph, node)));
else
lost_tournaments.insert(
tournament_ptr(new Tournament(&graph, node)));
}
std::set<tournament_ptr> new_won_tournaments;
std::set<tournament_ptr> won_copy(won_tournaments);
std::set<tournament_ptr> lost_copy(lost_tournaments);
for(auto lose: lost_copy)
{
for(auto win: won_copy)
{
if(won_tournaments.count(win) && graph.wins(win->get_winner(),
lose->get_winner()))
{
won_tournaments.erase(win);
lost_tournaments.erase(lose);
new_won_tournaments.insert(tournament_ptr(
new Tournament(*win, *lose)));
break;
}
}
}
assert(lost_tournaments.size() == 0);
while(won_tournaments.size() > 1)
{
for (auto i = won_tournaments.begin(); i!=won_tournaments.end(); ++i)
{
auto compatitor1 = *i;
if (++i==won_tournaments.end())
{
new_won_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, Tournament(&graph, winner))));
break;
}
auto compatitor2 = *i;
new_won_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, *compatitor2)));
}
won_tournaments = new_won_tournaments;
new_won_tournaments.clear();
}
return *won_tournaments.begin();
}
bool check_if_case_B(TournamentGraph& graph, std::set<int>& nodes, int winner)
{
int wins = 0;
for(auto node: nodes)
{
if(node != winner && graph.wins(winner, node))
wins++;
}
return wins >= nodes.size() / 2;
}
tournament_ptr fix_tournament_B(TournamentGraph &graph,
std::set<int>& nodes, int winner)
{
std::set<tournament_ptr> won_tournaments, lost_tournaments;
std::set<tournament_ptr> new_won_tournaments, new_lost_tournaments;
for (auto node: nodes)
{
if(winner == node)
continue;
if(graph.wins(winner, node))
won_tournaments.insert(
tournament_ptr(new Tournament(&graph, node)));
else
lost_tournaments.insert(
tournament_ptr(new Tournament(&graph, node)));
}
while(lost_tournaments.size() > 0)
{
std::set<tournament_ptr> won_copy(won_tournaments);
std::set<tournament_ptr> lost_copy(lost_tournaments);
for(auto lose: lost_copy)
{
for(auto win: won_copy)
{
if(won_tournaments.count(win) && graph.wins(win->get_winner(),
lose->get_winner()))
{
won_tournaments.erase(win);
lost_tournaments.erase(lose);
new_won_tournaments.insert(tournament_ptr(
new Tournament(*win, *lose)));
break;
}
}
}
for (auto i=lost_tournaments.begin(); i!=lost_tournaments.end(); ++i)
{
auto compatitor1 = *i;
if (++i==lost_tournaments.end())
{
auto won_example = *won_tournaments.begin();
won_tournaments.erase(won_example);
new_lost_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, *won_example)));
break;
}
auto compatitor2 = *i;
new_lost_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, *compatitor2)));
}
for (auto i=won_tournaments.begin(); i!=won_tournaments.end(); ++i)
{
auto compatitor1 = *i;
if (++i==won_tournaments.end())
{
new_won_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, Tournament(&graph, winner))));
break;
}
auto compatitor2 = *i;
new_won_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, *compatitor2)));
}
won_tournaments = new_won_tournaments;
new_won_tournaments.clear();
lost_tournaments = new_lost_tournaments;
new_lost_tournaments.clear();
}
while(won_tournaments.size() > 1)
{
for (auto i = won_tournaments.begin(); i!=won_tournaments.end(); ++i)
{
auto compatitor1 = *i;
++i;
auto compatitor2 = *i;
new_won_tournaments.insert(
std::shared_ptr<Tournament>(
new Tournament(*compatitor1, *compatitor2)));
}
won_tournaments = new_won_tournaments;
new_won_tournaments.clear();
}
return *won_tournaments.begin();
}
bool check_if_case_C(TournamentGraph& graph, std::set<int>& nodes, int winner)
{
std::set<int> won_with, lost_with;
int log2n = std::log2(nodes.size());
for (auto node: nodes)
{
if(node == winner)
continue;
if(graph.wins(winner, node))
won_with.insert(node);
else
lost_with.insert(node);
}
if (won_with.size() < log2n)
return false;
for (auto lose: lost_with)
{
int lose_lost_with_won_count = 0;
for (auto win: won_with)
{
if(graph.wins(win, lose))
lose_lost_with_won_count++;
}
if(lose_lost_with_won_count < log2n)
return false;
}
return true;
}
tournament_ptr fix_tournament_C(TournamentGraph& graph,
std::set<int>& nodes, int winner)
{
std::set<tournament_ptr> won_tournaments, lost_tournaments;
std::set<tournament_ptr> new_won_tournaments, new_lost_tournaments;
tournament_ptr winner_tournament(new Tournament(&graph, winner));
for (auto node: nodes)
{
if(winner == node)
continue;
if(graph.wins(winner, node))
won_tournaments.insert(
tournament_ptr(new Tournament(&graph, node)));
else
lost_tournaments.insert(
tournament_ptr(new Tournament(&graph, node)));
}
while(won_tournaments.size() > 0 || lost_tournaments.size() > 0)
{
auto first_won = *won_tournaments.begin();
won_tournaments.erase(first_won);
winner_tournament = tournament_ptr(
new Tournament(*winner_tournament, *first_won));
std::set<tournament_ptr> won_copy(won_tournaments);
std::set<tournament_ptr> lost_copy(lost_tournaments);
for(auto lose: lost_copy)
{
for(auto win: won_copy)
{
if(won_tournaments.count(win) && graph.wins(win->get_winner(),
lose->get_winner()))
{
won_tournaments.erase(win);
lost_tournaments.erase(lose);
new_won_tournaments.insert(tournament_ptr(
new Tournament(*win, *lose)));
break;
}
}
}
for (auto i=lost_tournaments.begin(); i!=lost_tournaments.end(); ++i)
{
auto compatitor1 = *i;
if (++i==lost_tournaments.end())
{
auto won_example = *won_tournaments.begin();
won_tournaments.erase(won_example);
new_lost_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, *won_example)));
break;
}
auto compatitor2 = *i;
new_lost_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, *compatitor2)));
}
for (auto i=won_tournaments.begin(); i!=won_tournaments.end(); ++i)
{
auto compatitor1 = *i;
if (++i==won_tournaments.end())
{
new_won_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, Tournament(&graph, winner))));
break;
}
auto compatitor2 = *i;
new_won_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, *compatitor2)));
}
won_tournaments = new_won_tournaments;
new_won_tournaments.clear();
lost_tournaments = new_lost_tournaments;
new_lost_tournaments.clear();
}
return winner_tournament;
}
tournament_ptr _fix_tournament(TournamentGraph& graph,
std::set<int>& nodes, int winner)
{
if(check_if_fixable(graph, nodes, winner))
{
if (check_if_case_A(graph, nodes, winner))
return fix_tournament_A(graph, nodes, winner);
else if (check_if_case_B(graph, nodes, winner))
return fix_tournament_B(graph, nodes, winner);
else if (check_if_case_C(graph, nodes, winner))
return fix_tournament_C(graph, nodes, winner);
else
{
printf("Worst Case");
}
}
else
{
throw TournamentUnfixableError();
}
}
void fix_tournament(TournamentGraph& graph, int winner)
{
std::set<int> nodes;
for (int i=0; i<graph.get_size(); ++i)
nodes.insert(i);
tournament_ptr tournament = _fix_tournament(graph, nodes, winner);
}<commit_msg>Fix tournament case A fixing.<commit_after>#include <vector>
#include <cmath>
#include <set>
#include <cassert>
#include "../include/graph.h"
#include "../include/tournament.h"
#include "../include/exceptions.h"
typedef std::shared_ptr<Tournament> tournament_ptr;
bool check_if_fixable(TournamentGraph& graph, std::set<int>& nodes, int winner)
{
int wins = 0;
for(auto node: nodes)
{
if(node != winner && graph.wins(winner, node))
wins++;
}
if (wins < log2(nodes.size()))
return false;
else
{
for (auto node1: nodes)
{
if(node1 == winner)
continue;
wins = 0;
for (auto node2: nodes)
{
if(node1 == node2)
continue;
if(graph.wins(node1, node2))
wins++;
else
break;
}
if(wins == nodes.size() - 1)
return false;
}
return true;
}
}
bool check_if_case_A(TournamentGraph& graph, std::set<int>& nodes, int winner)
{
int wins = 0;
int max_wins_from_losses = 0;
int wins_from_losses;
for(auto node1: nodes)
{
if(node1 == winner)
continue;
if(graph.wins(winner, node1))
wins++;
else
{
wins_from_losses = 0;
for (auto node2: nodes)
{
if(node1 == node2)
continue;
if(graph.wins(node1, node2))
wins_from_losses++;
}
if(wins_from_losses > max_wins_from_losses)
{
max_wins_from_losses = wins_from_losses;
}
}
}
return wins > max_wins_from_losses;
}
tournament_ptr fix_tournament_A(TournamentGraph& graph,
std::set<int>& nodes, int winner)
{
std::set<tournament_ptr> won_tournaments, lost_tournaments;
for(auto node: nodes)
{
if(winner == node)
continue;
if(graph.wins(winner, node))
won_tournaments.insert(
tournament_ptr(new Tournament(&graph, node)));
else
lost_tournaments.insert(
tournament_ptr(new Tournament(&graph, node)));
}
std::set<tournament_ptr> new_won_tournaments;
std::set<tournament_ptr> won_copy(won_tournaments);
std::set<tournament_ptr> lost_copy(lost_tournaments);
for(auto lose: lost_copy)
{
for(auto win: won_copy)
{
if(won_tournaments.count(win) && graph.wins(win->get_winner(),
lose->get_winner()))
{
won_tournaments.erase(win);
lost_tournaments.erase(lose);
new_won_tournaments.insert(tournament_ptr(
new Tournament(*win, *lose)));
break;
}
}
}
assert(lost_tournaments.size() == 0);
do
{
for (auto i = won_tournaments.begin(); i!=won_tournaments.end(); ++i)
{
auto compatitor1 = *i;
if (++i==won_tournaments.end())
{
new_won_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, Tournament(&graph, winner))));
break;
}
auto compatitor2 = *i;
new_won_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, *compatitor2)));
}
won_tournaments = new_won_tournaments;
new_won_tournaments.clear();
}
while (won_tournaments.size() > 1);
return *won_tournaments.begin();
}
bool check_if_case_B(TournamentGraph& graph, std::set<int>& nodes, int winner)
{
int wins = 0;
for(auto node: nodes)
{
if(node != winner && graph.wins(winner, node))
wins++;
}
return wins >= nodes.size() / 2;
}
tournament_ptr fix_tournament_B(TournamentGraph &graph,
std::set<int>& nodes, int winner)
{
std::set<tournament_ptr> won_tournaments, lost_tournaments;
std::set<tournament_ptr> new_won_tournaments, new_lost_tournaments;
for (auto node: nodes)
{
if(winner == node)
continue;
if(graph.wins(winner, node))
won_tournaments.insert(
tournament_ptr(new Tournament(&graph, node)));
else
lost_tournaments.insert(
tournament_ptr(new Tournament(&graph, node)));
}
while(lost_tournaments.size() > 0)
{
std::set<tournament_ptr> won_copy(won_tournaments);
std::set<tournament_ptr> lost_copy(lost_tournaments);
for(auto lose: lost_copy)
{
for(auto win: won_copy)
{
if(won_tournaments.count(win) && graph.wins(win->get_winner(),
lose->get_winner()))
{
won_tournaments.erase(win);
lost_tournaments.erase(lose);
new_won_tournaments.insert(tournament_ptr(
new Tournament(*win, *lose)));
break;
}
}
}
for (auto i=lost_tournaments.begin(); i!=lost_tournaments.end(); ++i)
{
auto compatitor1 = *i;
if (++i==lost_tournaments.end())
{
auto won_example = *won_tournaments.begin();
won_tournaments.erase(won_example);
new_lost_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, *won_example)));
break;
}
auto compatitor2 = *i;
new_lost_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, *compatitor2)));
}
for (auto i=won_tournaments.begin(); i!=won_tournaments.end(); ++i)
{
auto compatitor1 = *i;
if (++i==won_tournaments.end())
{
new_won_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, Tournament(&graph, winner))));
break;
}
auto compatitor2 = *i;
new_won_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, *compatitor2)));
}
won_tournaments = new_won_tournaments;
new_won_tournaments.clear();
lost_tournaments = new_lost_tournaments;
new_lost_tournaments.clear();
}
while(won_tournaments.size() > 1)
{
for (auto i = won_tournaments.begin(); i!=won_tournaments.end(); ++i)
{
auto compatitor1 = *i;
++i;
auto compatitor2 = *i;
new_won_tournaments.insert(
std::shared_ptr<Tournament>(
new Tournament(*compatitor1, *compatitor2)));
}
won_tournaments = new_won_tournaments;
new_won_tournaments.clear();
}
return *won_tournaments.begin();
}
bool check_if_case_C(TournamentGraph& graph, std::set<int>& nodes, int winner)
{
std::set<int> won_with, lost_with;
int log2n = std::log2(nodes.size());
for (auto node: nodes)
{
if(node == winner)
continue;
if(graph.wins(winner, node))
won_with.insert(node);
else
lost_with.insert(node);
}
if (won_with.size() < log2n)
return false;
for (auto lose: lost_with)
{
int lose_lost_with_won_count = 0;
for (auto win: won_with)
{
if(graph.wins(win, lose))
lose_lost_with_won_count++;
}
if(lose_lost_with_won_count < log2n)
return false;
}
return true;
}
tournament_ptr fix_tournament_C(TournamentGraph& graph,
std::set<int>& nodes, int winner)
{
std::set<tournament_ptr> won_tournaments, lost_tournaments;
std::set<tournament_ptr> new_won_tournaments, new_lost_tournaments;
tournament_ptr winner_tournament(new Tournament(&graph, winner));
for (auto node: nodes)
{
if(winner == node)
continue;
if(graph.wins(winner, node))
won_tournaments.insert(
tournament_ptr(new Tournament(&graph, node)));
else
lost_tournaments.insert(
tournament_ptr(new Tournament(&graph, node)));
}
while(won_tournaments.size() > 0 || lost_tournaments.size() > 0)
{
auto first_won = *won_tournaments.begin();
won_tournaments.erase(first_won);
winner_tournament = tournament_ptr(
new Tournament(*winner_tournament, *first_won));
std::set<tournament_ptr> won_copy(won_tournaments);
std::set<tournament_ptr> lost_copy(lost_tournaments);
for(auto lose: lost_copy)
{
for(auto win: won_copy)
{
if(won_tournaments.count(win) && graph.wins(win->get_winner(),
lose->get_winner()))
{
won_tournaments.erase(win);
lost_tournaments.erase(lose);
new_won_tournaments.insert(tournament_ptr(
new Tournament(*win, *lose)));
break;
}
}
}
for (auto i=lost_tournaments.begin(); i!=lost_tournaments.end(); ++i)
{
auto compatitor1 = *i;
if (++i==lost_tournaments.end())
{
auto won_example = *won_tournaments.begin();
won_tournaments.erase(won_example);
new_lost_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, *won_example)));
break;
}
auto compatitor2 = *i;
new_lost_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, *compatitor2)));
}
for (auto i=won_tournaments.begin(); i!=won_tournaments.end(); ++i)
{
auto compatitor1 = *i;
if (++i==won_tournaments.end())
{
new_won_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, Tournament(&graph, winner))));
break;
}
auto compatitor2 = *i;
new_won_tournaments.insert(tournament_ptr(
new Tournament(*compatitor1, *compatitor2)));
}
won_tournaments = new_won_tournaments;
new_won_tournaments.clear();
lost_tournaments = new_lost_tournaments;
new_lost_tournaments.clear();
}
return winner_tournament;
}
tournament_ptr _fix_tournament(TournamentGraph& graph,
std::set<int>& nodes, int winner)
{
if(check_if_fixable(graph, nodes, winner))
{
if (check_if_case_A(graph, nodes, winner))
return fix_tournament_A(graph, nodes, winner);
else if (check_if_case_B(graph, nodes, winner))
return fix_tournament_B(graph, nodes, winner);
else if (check_if_case_C(graph, nodes, winner))
return fix_tournament_C(graph, nodes, winner);
else
{
printf("Worst Case");
}
}
else
{
throw TournamentUnfixableError();
}
}
void fix_tournament(TournamentGraph& graph, int winner)
{
std::set<int> nodes;
for (int i=0; i<graph.get_size(); ++i)
nodes.insert(i);
tournament_ptr tournament = _fix_tournament(graph, nodes, winner);
}<|endoftext|> |
<commit_before>/*
Copyright (c) 2009-2012, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/allocator.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"
#if defined TORRENT_BEOS
#include <kernel/OS.h>
#include <stdlib.h> // malloc/free
#elif !defined TORRENT_WINDOWS
#include <stdlib.h> // valloc/free
#include <unistd.h> // _SC_PAGESIZE
#endif
#if TORRENT_USE_MEMALIGN || TORRENT_USE_POSIX_MEMALIGN || defined TORRENT_WINDOWS
#include <malloc.h> // memalign and _aligned_malloc
#include <stdlib.h> // _aligned_malloc on mingw
#endif
#ifdef TORRENT_WINDOWS
// windows.h must be included after stdlib.h under mingw
#include <windows.h>
#endif
#ifdef TORRENT_MINGW
#define _aligned_malloc __mingw_aligned_malloc
#define _aligned_free __mingw_aligned_free
#endif
#ifdef TORRENT_DEBUG_BUFFERS
#ifndef TORRENT_WINDOWS
#include <sys/mman.h>
#endif
#include "libtorrent/size_type.hpp"
struct alloc_header
{
libtorrent::size_type size;
int magic;
char stack[3072];
};
#endif
#if defined TORRENT_DEBUG_BUFFERS && (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050))
void print_backtrace(char* out, int len, int max_depth = 0);
#endif
namespace libtorrent
{
int page_size()
{
static int s = 0;
if (s != 0) return s;
#ifdef TORRENT_WINDOWS
SYSTEM_INFO si;
GetSystemInfo(&si);
s = si.dwPageSize;
#elif defined TORRENT_BEOS
s = B_PAGE_SIZE;
#else
s = sysconf(_SC_PAGESIZE);
#endif
// assume the page size is 4 kiB if we
// fail to query it
if (s <= 0) s = 4096;
return s;
}
char* page_aligned_allocator::malloc(size_type bytes)
{
TORRENT_ASSERT(bytes >= page_size());
#ifdef TORRENT_DEBUG_BUFFERS
int page = page_size();
int num_pages = (bytes + (page-1)) / page + 2;
char* ret = (char*)valloc(num_pages * page);
// make the two surrounding pages non-readable and -writable
alloc_header* h = (alloc_header*)ret;
h->size = bytes;
h->magic = 0x1337;
#if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)
print_backtrace(h->stack, sizeof(h->stack));
#endif
#ifdef TORRENT_WINDOWS
#define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK)
#define PROT_READ PAGE_READONLY
#endif
mprotect(ret, page, PROT_READ);
mprotect(ret + (num_pages-1) * page, page, PROT_READ);
#ifdef TORRENT_WINDOWS
#undef mprotect
#undef PROT_READ
#endif
// fprintf(stderr, "malloc: %p head: %p tail: %p size: %d\n", ret + page, ret, ret + page + bytes, int(bytes));
return ret + page;
#endif
#if TORRENT_USE_POSIX_MEMALIGN
void* ret;
if (posix_memalign(&ret, page_size(), bytes) != 0) ret = 0;
return (char*)ret;
#elif TORRENT_USE_MEMALIGN
return (char*)memalign(page_size(), bytes);
#elif defined TORRENT_WINDOWS
return (char*)_aligned_malloc(bytes, page_size());
#elif defined TORRENT_BEOS
void* ret = 0;
area_id id = create_area("", &ret, B_ANY_ADDRESS
, (bytes + page_size() - 1) & (page_size()-1), B_NO_LOCK, B_READ_AREA | B_WRITE_AREA);
if (id < B_OK) return 0;
return (char*)ret;
#else
return (char*)valloc(bytes);
#endif
}
void page_aligned_allocator::free(char* const block)
{
#ifdef TORRENT_DEBUG_BUFFERS
#ifdef TORRENT_WINDOWS
#define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK)
#define PROT_READ PAGE_READONLY
#define PROT_WRITE PAGE_READWRITE
#endif
int page = page_size();
// make the two surrounding pages non-readable and -writable
mprotect(block - page, page, PROT_READ | PROT_WRITE);
alloc_header* h = (alloc_header*)(block - page);
int num_pages = (h->size + (page-1)) / page + 2;
TORRENT_ASSERT(h->magic == 0x1337);
mprotect(block + (num_pages-2) * page, page, PROT_READ | PROT_WRITE);
// fprintf(stderr, "free: %p head: %p tail: %p size: %d\n", block, block - page, block + h->size, int(h->size));
h->magic = 0;
#ifdef TORRENT_WINDOWS
#undef mprotect
#undef PROT_READ
#undef PROT_WRITE
#endif
#if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)
print_backtrace(h->stack, sizeof(h->stack));
#endif
::free(block - page);
return;
#endif
#ifdef TORRENT_WINDOWS
_aligned_free(block);
#elif defined TORRENT_BEOS
area_id id = area_for(block);
if (id < B_OK) return;
delete_area(id);
#else
::free(block);
#endif
}
}
<commit_msg>comments<commit_after>/*
Copyright (c) 2009-2012, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/allocator.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"
#if defined TORRENT_BEOS
#include <kernel/OS.h>
#include <stdlib.h> // malloc/free
#elif !defined TORRENT_WINDOWS
#include <stdlib.h> // valloc/free
#include <unistd.h> // _SC_PAGESIZE
#endif
#if TORRENT_USE_MEMALIGN || TORRENT_USE_POSIX_MEMALIGN || defined TORRENT_WINDOWS
#include <malloc.h> // memalign and _aligned_malloc
#include <stdlib.h> // _aligned_malloc on mingw
#endif
#ifdef TORRENT_WINDOWS
// windows.h must be included after stdlib.h under mingw
#include <windows.h>
#endif
#ifdef TORRENT_MINGW
#define _aligned_malloc __mingw_aligned_malloc
#define _aligned_free __mingw_aligned_free
#endif
#ifdef TORRENT_DEBUG_BUFFERS
#ifndef TORRENT_WINDOWS
#include <sys/mman.h>
#endif
#include "libtorrent/size_type.hpp"
struct alloc_header
{
libtorrent::size_type size;
int magic;
char stack[3072];
};
#endif
#if defined TORRENT_DEBUG_BUFFERS && (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050))
void print_backtrace(char* out, int len, int max_depth = 0);
#endif
namespace libtorrent
{
int page_size()
{
static int s = 0;
if (s != 0) return s;
#ifdef TORRENT_WINDOWS
SYSTEM_INFO si;
GetSystemInfo(&si);
s = si.dwPageSize;
#elif defined TORRENT_BEOS
s = B_PAGE_SIZE;
#else
s = sysconf(_SC_PAGESIZE);
#endif
// assume the page size is 4 kiB if we
// fail to query it
if (s <= 0) s = 4096;
return s;
}
char* page_aligned_allocator::malloc(size_type bytes)
{
TORRENT_ASSERT(bytes >= page_size());
#ifdef TORRENT_DEBUG_BUFFERS
int page = page_size();
int num_pages = (bytes + (page-1)) / page + 2;
char* ret = (char*)valloc(num_pages * page);
// make the two surrounding pages non-readable and -writable
alloc_header* h = (alloc_header*)ret;
h->size = bytes;
h->magic = 0x1337;
#if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)
print_backtrace(h->stack, sizeof(h->stack));
#endif
#ifdef TORRENT_WINDOWS
#define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK)
#define PROT_READ PAGE_READONLY
#endif
mprotect(ret, page, PROT_READ);
mprotect(ret + (num_pages-1) * page, page, PROT_READ);
#ifdef TORRENT_WINDOWS
#undef mprotect
#undef PROT_READ
#endif
// fprintf(stderr, "malloc: %p head: %p tail: %p size: %d\n", ret + page, ret, ret + page + bytes, int(bytes));
return ret + page;
#endif
#if TORRENT_USE_POSIX_MEMALIGN
void* ret;
if (posix_memalign(&ret, page_size(), bytes) != 0) ret = 0;
return (char*)ret;
#elif TORRENT_USE_MEMALIGN
return (char*)memalign(page_size(), bytes);
#elif defined TORRENT_WINDOWS
return (char*)_aligned_malloc(bytes, page_size());
#elif defined TORRENT_BEOS
void* ret = 0;
area_id id = create_area("", &ret, B_ANY_ADDRESS
, (bytes + page_size() - 1) & (page_size()-1), B_NO_LOCK, B_READ_AREA | B_WRITE_AREA);
if (id < B_OK) return 0;
return (char*)ret;
#else
return (char*)valloc(bytes);
#endif
}
void page_aligned_allocator::free(char* const block)
{
#ifdef TORRENT_DEBUG_BUFFERS
#ifdef TORRENT_WINDOWS
#define mprotect(buf, size, prot) VirtualProtect(buf, size, prot, NULK)
#define PROT_READ PAGE_READONLY
#define PROT_WRITE PAGE_READWRITE
#endif
int page = page_size();
// make the two surrounding pages non-readable and -writable
mprotect(block - page, page, PROT_READ | PROT_WRITE);
alloc_header* h = (alloc_header*)(block - page);
int num_pages = (h->size + (page-1)) / page + 2;
TORRENT_ASSERT(h->magic == 0x1337);
mprotect(block + (num_pages-2) * page, page, PROT_READ | PROT_WRITE);
// fprintf(stderr, "free: %p head: %p tail: %p size: %d\n", block, block - page, block + h->size, int(h->size));
h->magic = 0;
#ifdef TORRENT_WINDOWS
#undef mprotect
#undef PROT_READ
#undef PROT_WRITE
#endif
#if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)
print_backtrace(h->stack, sizeof(h->stack));
#endif
::free(block - page);
return;
#endif // TORRENT_DEBUG_BUFFERS
#ifdef TORRENT_WINDOWS
_aligned_free(block);
#elif defined TORRENT_BEOS
area_id id = area_for(block);
if (id < B_OK) return;
delete_area(id);
#else
::free(block);
#endif // TORRENT_WINDOWS
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016 Bluespec, Inc. All Rights Reserved.
// This is a boilerplate 'main' to drive a Bluesim executable without
// using the BlueTcl top-level that bsc normally generates.
// Example:
// Suppose your top-level BSV file is Foo.bsv, with top-level module mkFoo
// Compile and link the top-level BSV as usual, e.g.,:
// bsc -sim -u Foo.bsv
// bsc -sim -e mkFoo
// This will produce the usual Bluetcl-based executable (a.out and a.out.so)
// but it will also produce:
// mkFoo.{h,cxx,o}
// model_mkFoo.{h,cxx,o}
// (and of course similar files for any other imported BSV modules)
// Then, compile and link this file with those .o's, like this Makefile target
//
// CXXFAMILY=g++4 // for 32-bit platforms
// CXXFAMILY=g++4_64 // for 64-bit platforms
//
// $(EXE): model_$(TOPMOD).o $(TOPMOD).o
// c++ -O3 \
// -DNEW_MODEL_MKFOO=new_MODEL_$(TOPMOD) \ // new_MODEL_mkFoo
// -DMODEL_MKFOO_H=\"model_$(TOPMOD).h\" \ // "model_mkFoo.h"
// bluesim_main.cxx \ // This file
// -o $@ \ // Your final executable
// -I. \ // bsc-generated .h files, project .h files
// -I$(BLUESPECDIR)/Bluesim \ // Dir for Bluespec release .h files
// -L$(BLUESPECDIR)/Bluesim/$(CXXFAMILY) \ // Dir Bluespec release libs
// $^ \ // all your .o's
// -lbskernel -lbsprim -lpthread // libs
#ifndef MODEL_MKFOO_H
#error MODEL_MKFOO_H not defined
#endif
#ifndef NEW_MODEL_MKFOO
#error NEW_MODEL_MKFOO not defined
#endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include "bluesim_kernel_api.h"
// #include "model_mkFoo.h"
#include MODEL_MKFOO_H
// ================================================================
// Process command line args
static char default_vcd_filename [] = "dump.vcd";
static char *vcd_filename = NULL; // Valid if not NULL
static tUInt64 count = 0; // Valid if positive
static
void process_command_line_args (int argc, char *argv [])
{
// Check for -h (help)
for (int j = 0; j < argc; j++) {
if (strcmp (argv [j], "-h") == 0) {
fprintf (stderr, "Usage: %s [opts]\n", argv [0]);
fprintf (stderr, "Options:\n");
fprintf (stderr, " -h = print help and exit\n");
fprintf (stderr, " -m <N> = execute for N cycles\n");
fprintf (stderr, " -V [<file>] = dump waveforms to VCD file (default: dump.vcd)\n");
fprintf (stderr, "\n");
fprintf (stderr, "Examples:\n");
fprintf (stderr, " %s\n", argv [0]);
fprintf (stderr, " %s -m 3000\n", argv [0]);
fprintf (stderr, " %s -V sim.vcd\n", argv [0]);
exit (1);
}
}
// Check for -V or -V vcd_filename in command-line args
for (int j = 0; j < argc; j++) {
if (strcmp (argv [j], "-V") == 0) {
if (j == (argc - 1))
vcd_filename = & (default_vcd_filename [0]);
else if (argv [j+1][0] != '-')
vcd_filename = argv [j+1];
break;
}
}
// Check for -m <N> flag (execute for N cycles)
long int n = -1;
for (int j = 0; j < argc; j++) {
if (strcmp (argv [j], "-m") == 0) {
if (j == (argc - 1)) {
fprintf (stderr, "Command-line error: -m flag must be followed by a positive integer\n");
exit (1);
}
errno = 0;
n = strtol (argv [j+1], NULL, 0);
if ((errno != 0) || (n < 1)) {
fprintf (stderr, "Command-line error: -m flag must be followed by a positive integer\n");
exit (1);
}
count = n;
break;
}
}
}
// ================================================================
int main (int argc, char *argv[])
{
process_command_line_args (argc, argv);
// tModel model = new_MODEL_mkFoo();
tModel model = NEW_MODEL_MKFOO ();
tSimStateHdl sim = bk_init (model, true, false);
if (vcd_filename != NULL) {
tStatus status = bk_set_VCD_file (sim, vcd_filename);
if (status == BK_ERROR) {
fprintf (stderr, "Error: Could not open file for VCD output: %s\n", vcd_filename);
exit (1);
}
tBool b = bk_enable_VCD_dumping (sim);
if (b == 0) {
fprintf (stderr, "Error: Could not enable VCD dumping in file: %s\n", vcd_filename);
exit (1);
}
fprintf (stdout, "Enabled VCD dumping to file %s\n", vcd_filename);
}
if (count > 0) {
tClock clk = 0;
tEdgeDirection dir = POSEDGE;
bk_quit_after_edge (sim, clk, dir, count);
fprintf (stdout, "Will stop after %0lld clocks\n", count);
}
bk_advance (sim, false);
bk_shutdown (sim);
if (count > 0) {
fprintf (stdout, "Stopped after %0lld clocks\n", count);
}
}
<commit_msg>top module is always mkXsimTop<commit_after>// Copyright (c) 2016 Bluespec, Inc. All Rights Reserved.
// This is a boilerplate 'main' to drive a Bluesim executable without
// using the BlueTcl top-level that bsc normally generates.
// Example:
// Suppose your top-level BSV file is Foo.bsv, with top-level module mkFoo
// Compile and link the top-level BSV as usual, e.g.,:
// bsc -sim -u Foo.bsv
// bsc -sim -e mkFoo
// This will produce the usual Bluetcl-based executable (a.out and a.out.so)
// but it will also produce:
// mkFoo.{h,cxx,o}
// model_mkFoo.{h,cxx,o}
// (and of course similar files for any other imported BSV modules)
// Then, compile and link this file with those .o's, like this Makefile target
//
// CXXFAMILY=g++4 // for 32-bit platforms
// CXXFAMILY=g++4_64 // for 64-bit platforms
//
// $(EXE): model_$(TOPMOD).o $(TOPMOD).o
// c++ -O3 \
// bluesim_main.cxx \ // This file
// -o $@ \ // Your final executable
// -I. \ // bsc-generated .h files, project .h files
// -I$(BLUESPECDIR)/Bluesim \ // Dir for Bluespec release .h files
// -L$(BLUESPECDIR)/Bluesim/$(CXXFAMILY) \ // Dir Bluespec release libs
// $^ \ // all your .o's
// -lbskernel -lbsprim -lpthread // libs
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include "bluesim_kernel_api.h"
// #include MODEL_MKFOO_H
#include "model_mkXsimTop.h"
// ================================================================
// Process command line args
static char default_vcd_filename [] = "dump.vcd";
static char *vcd_filename = NULL; // Valid if not NULL
static tUInt64 count = 0; // Valid if positive
static
void process_command_line_args (int argc, char *argv [])
{
// Check for -h (help)
for (int j = 0; j < argc; j++) {
if (strcmp (argv [j], "-h") == 0) {
fprintf (stderr, "Usage: %s [opts]\n", argv [0]);
fprintf (stderr, "Options:\n");
fprintf (stderr, " -h = print help and exit\n");
fprintf (stderr, " -m <N> = execute for N cycles\n");
fprintf (stderr, " -V [<file>] = dump waveforms to VCD file (default: dump.vcd)\n");
fprintf (stderr, "\n");
fprintf (stderr, "Examples:\n");
fprintf (stderr, " %s\n", argv [0]);
fprintf (stderr, " %s -m 3000\n", argv [0]);
fprintf (stderr, " %s -V sim.vcd\n", argv [0]);
exit (1);
}
}
// Check for -V or -V vcd_filename in command-line args
for (int j = 0; j < argc; j++) {
if (strcmp (argv [j], "-V") == 0) {
if (j == (argc - 1))
vcd_filename = & (default_vcd_filename [0]);
else if (argv [j+1][0] != '-')
vcd_filename = argv [j+1];
break;
}
}
// Check for -m <N> flag (execute for N cycles)
long int n = -1;
for (int j = 0; j < argc; j++) {
if (strcmp (argv [j], "-m") == 0) {
if (j == (argc - 1)) {
fprintf (stderr, "Command-line error: -m flag must be followed by a positive integer\n");
exit (1);
}
errno = 0;
n = strtol (argv [j+1], NULL, 0);
if ((errno != 0) || (n < 1)) {
fprintf (stderr, "Command-line error: -m flag must be followed by a positive integer\n");
exit (1);
}
count = n;
break;
}
}
}
// ================================================================
int main (int argc, char *argv[])
{
process_command_line_args (argc, argv);
// tModel model = NEW_MODEL_MKFOO ();
tModel model = new_MODEL_mkXsimTop();
tSimStateHdl sim = bk_init (model, true, false);
if (vcd_filename != NULL) {
tStatus status = bk_set_VCD_file (sim, vcd_filename);
if (status == BK_ERROR) {
fprintf (stderr, "Error: Could not open file for VCD output: %s\n", vcd_filename);
exit (1);
}
tBool b = bk_enable_VCD_dumping (sim);
if (b == 0) {
fprintf (stderr, "Error: Could not enable VCD dumping in file: %s\n", vcd_filename);
exit (1);
}
fprintf (stdout, "Enabled VCD dumping to file %s\n", vcd_filename);
}
if (count > 0) {
tClock clk = 0;
tEdgeDirection dir = POSEDGE;
bk_quit_after_edge (sim, clk, dir, count);
fprintf (stdout, "Will stop after %0lld clocks\n", count);
}
bk_advance (sim, false);
bk_shutdown (sim);
if (count > 0) {
fprintf (stdout, "Stopped after %0lld clocks\n", count);
}
}
<|endoftext|> |
<commit_before>/** \brief Updates Zeder w/ the last N issues of harvested articles for each journal.
* \author Dr. Johannes Ruscheinski ([email protected])
*
* \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <ctime>
#include <cstdlib>
#include "DbConnection.h"
#include "DbResultSet.h"
#include "DbRow.h"
#include "EmailSender.h"
#include "FileUtil.h"
#include "IniFile.h"
#include "SqlUtil.h"
#include "UBTools.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname
<< " [--min-log-level=log_level] sender_email_address notification_email_address\n";
std::exit(EXIT_FAILURE);
}
const std::string TIMESTAMP_FILENAME("zeder_updater.timestamp");
// Returns the contents of the timestamp file or 0 if the file does not exist
time_t ReadTimeStamp() {
const std::string TIMESTAMP_PATH(UBTools::TUELIB_PATH + TIMESTAMP_FILENAME);
if (FileUtil::Exists(TIMESTAMP_PATH)) {
time_t timestamp;
const auto timestamp_file(FileUtil::OpenInputFileOrDie(TIMESTAMP_PATH));
if (timestamp_file->read(reinterpret_cast<void *>(×tamp), sizeof timestamp) != sizeof timestamp)
LOG_ERROR("failed to read " + std::to_string(sizeof timestamp) + " bytes from \"" + TIMESTAMP_PATH + "\"!");
return timestamp;
} else
return 0;
}
void WriteTimeStamp(const time_t timestamp) {
const std::string TIMESTAMP_PATH(UBTools::TUELIB_PATH + TIMESTAMP_FILENAME);
const auto timestamp_file(FileUtil::OpenOutputFileOrDie(TIMESTAMP_PATH));
if (timestamp_file->write(reinterpret_cast<const void *>(×tamp), sizeof timestamp) != sizeof timestamp)
LOG_ERROR("failed to write " + std::to_string(sizeof timestamp) + " bytes to \"" + TIMESTAMP_PATH + "\"!");
}
void GetJournalInfo(DbConnection * const db_connection, const std::string &zeder_id,
std::string * const superior_control_number, std::string * const superior_title)
{
db_connection->queryOrDie("SELECT control_number,title FROM superior_info WHERE zeder_id="
+ db_connection->escapeAndQuoteString(zeder_id));
DbResultSet result_set(db_connection->getLastResultSet());
if (result_set.empty())
LOG_ERROR("empty results set in table \"superior_info\" for Zeder ID \"" + zeder_id + "\"!");
const DbRow row(result_set.getNextRow());
*superior_control_number = row["control_number"];
*superior_title = row["title"];
}
bool ProcessJournal(DbConnection * const db_connection, const time_t old_timestamp, const std::string &zeder_id,
const std::string &zeder_url_prefix, const unsigned max_issue_count, std::string * const report)
{
std::string superior_control_number, superior_title;
GetJournalInfo(db_connection, zeder_id, &superior_control_number, &superior_title);
db_connection->queryOrDie("SELECT volume,issue,pages,created_at FROM marc_records WHERE zeder_id="
+ db_connection->escapeAndQuoteString(zeder_id) + " ORDER BY created_at DESC LIMIT "
+ std::to_string(max_issue_count));
bool found_at_least_one_new_issue;
DbResultSet result_set(db_connection->getLastResultSet());
while (const DbRow row = result_set.getNextRow()) {
const time_t created_at(SqlUtil::DatetimeToTimeT(row["created_at"]));
std::string status;
if (created_at > old_timestamp) {
found_at_least_one_new_issue = true;
status = "neu";
} else
status = "unverändert";
*report += zeder_url_prefix + zeder_id + "," + superior_title + "," + row["volume"] + ";" + row["issue"] + ";" + row["pages"] + ","
+ status + "\n";
}
return found_at_least_one_new_issue;
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 4)
Usage();
const std::string sender_email_address(argv[2]), notification_email_address(argv[3]);
IniFile ini_file;
const unsigned max_issue_count(ini_file.getUnsigned("", "max_issue_count"));
const std::string zeder_url_prefix(ini_file.getString("", "zeder_url_prefix"));
const time_t old_timestamp(ReadTimeStamp());
DbConnection db_connection;
db_connection.queryOrDie("SELECT DISTINCT marc_records.zeder_id,superior_info.title FROM marc_records LEFT JOIN superior_info ON marc_records.zeder_id=superior_info.zeder_id");
DbResultSet result_set(db_connection.getLastResultSet());
unsigned journal_count(0), updated_journal_count(0);
std::string report;
while (const DbRow row = result_set.getNextRow()) {
if (ProcessJournal(&db_connection, old_timestamp, row["zeder_id"], zeder_url_prefix, max_issue_count, &report))
++updated_journal_count;
++journal_count;
}
WriteTimeStamp(::time(nullptr));
EmailSender::SendEmail(sender_email_address, notification_email_address, "Zeder Updater", report);
LOG_INFO("Found " + std::to_string(updated_journal_count) + " out of " + std::to_string(journal_count) + " journals wuth new entries.");
return EXIT_SUCCESS;
}
<commit_msg>Simplified SQL processing.<commit_after>/** \brief Updates Zeder w/ the last N issues of harvested articles for each journal.
* \author Dr. Johannes Ruscheinski ([email protected])
*
* \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <ctime>
#include <cstdlib>
#include "DbConnection.h"
#include "DbResultSet.h"
#include "DbRow.h"
#include "EmailSender.h"
#include "FileUtil.h"
#include "IniFile.h"
#include "SqlUtil.h"
#include "UBTools.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname
<< " [--min-log-level=log_level] sender_email_address notification_email_address\n";
std::exit(EXIT_FAILURE);
}
const std::string TIMESTAMP_FILENAME("zeder_updater.timestamp");
// Returns the contents of the timestamp file or 0 if the file does not exist
time_t ReadTimeStamp() {
const std::string TIMESTAMP_PATH(UBTools::TUELIB_PATH + TIMESTAMP_FILENAME);
if (FileUtil::Exists(TIMESTAMP_PATH)) {
time_t timestamp;
const auto timestamp_file(FileUtil::OpenInputFileOrDie(TIMESTAMP_PATH));
if (timestamp_file->read(reinterpret_cast<void *>(×tamp), sizeof timestamp) != sizeof timestamp)
LOG_ERROR("failed to read " + std::to_string(sizeof timestamp) + " bytes from \"" + TIMESTAMP_PATH + "\"!");
return timestamp;
} else
return 0;
}
void WriteTimeStamp(const time_t timestamp) {
const std::string TIMESTAMP_PATH(UBTools::TUELIB_PATH + TIMESTAMP_FILENAME);
const auto timestamp_file(FileUtil::OpenOutputFileOrDie(TIMESTAMP_PATH));
if (timestamp_file->write(reinterpret_cast<const void *>(×tamp), sizeof timestamp) != sizeof timestamp)
LOG_ERROR("failed to write " + std::to_string(sizeof timestamp) + " bytes to \"" + TIMESTAMP_PATH + "\"!");
}
bool ProcessJournal(DbConnection * const db_connection, const time_t old_timestamp, const std::string &zeder_id,
const std::string &superior_title, const std::string &zeder_url_prefix, const unsigned max_issue_count,
std::string * const report)
{
db_connection->queryOrDie("SELECT volume,issue,pages,created_at FROM marc_records WHERE zeder_id="
+ db_connection->escapeAndQuoteString(zeder_id) + " ORDER BY created_at DESC LIMIT "
+ std::to_string(max_issue_count));
bool found_at_least_one_new_issue;
DbResultSet result_set(db_connection->getLastResultSet());
while (const DbRow row = result_set.getNextRow()) {
const time_t created_at(SqlUtil::DatetimeToTimeT(row["created_at"]));
std::string status;
if (created_at > old_timestamp) {
found_at_least_one_new_issue = true;
status = "neu";
} else
status = "unverändert";
*report += zeder_url_prefix + zeder_id + "," + superior_title + "," + row["volume"] + ";" + row["issue"] + ";" + row["pages"] + ","
+ status + "\n";
}
return found_at_least_one_new_issue;
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 4)
Usage();
const std::string sender_email_address(argv[2]), notification_email_address(argv[3]);
IniFile ini_file;
const unsigned max_issue_count(ini_file.getUnsigned("", "max_issue_count"));
const std::string zeder_url_prefix(ini_file.getString("", "zeder_url_prefix"));
const time_t old_timestamp(ReadTimeStamp());
DbConnection db_connection;
db_connection.queryOrDie("SELECT DISTINCT marc_records.zeder_id,superior_info.title FROM marc_records LEFT JOIN superior_info ON marc_records.zeder_id=superior_info.zeder_id");
DbResultSet result_set(db_connection.getLastResultSet());
unsigned journal_count(0), updated_journal_count(0);
std::string report;
while (const DbRow row = result_set.getNextRow()) {
if (ProcessJournal(&db_connection, old_timestamp, row["zeder_id"], row["title"], zeder_url_prefix, max_issue_count, &report))
++updated_journal_count;
++journal_count;
}
WriteTimeStamp(::time(nullptr));
EmailSender::SendEmail(sender_email_address, notification_email_address, "Zeder Updater", report);
LOG_INFO("Found " + std::to_string(updated_journal_count) + " out of " + std::to_string(journal_count) + " journals wuth new entries.");
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#pragma once
#include <algorithm>
#include <numeric>
#include "maths/random.hpp"
class DSU {
public:
DSU() : DSU(0) {}
DSU(const size_t vertices_count) : parent_(vertices_count), sets_count_(vertices_count) {
srand(static_cast<uint32_t>(Random::get_rand_seed()));
std::iota(parent_.begin(), parent_.end(), 0);
}
void init(const size_t vertices_count) {
srand(static_cast<uint32_t>(Random::get_rand_seed()));
parent_.resize(vertices_count);
std::iota(parent_.begin(), parent_.end(), 0);
sets_count_ = vertices_count;
}
size_t find_set(const size_t vertex) {
if (vertex != parent_[vertex]) {
parent_[vertex] = find_set(parent_[vertex]);
}
return parent_[vertex];
}
bool unite(const size_t a, const size_t b) {
size_t x = find_set(a);
size_t y = find_set(b);
if (x == y) {
return false;
}
if ((rand() & 1) != 0) {
std::swap(x, y);
}
parent_[x] = y;
--sets_count_;
return true;
}
void finalize() {
for (auto& it : parent_) {
it = find_set(it);
}
}
size_t size() const {
return parent_.size();
}
size_t sets_count() const {
return sets_count_;
}
const std::vector<size_t>& data() const {
return parent_;
}
private:
std::vector<size_t> parent_;
size_t sets_count_;
};<commit_msg>Refactored dsu.hpp.<commit_after>#pragma once
#include <algorithm>
#include <numeric>
#include "maths/random.hpp"
class DSU {
public:
using size_type = std::size_t;
DSU() : DSU(0) {}
explicit DSU(const size_type vertices_count) {
init(vertices_count);
}
void init(const size_type vertices_count) {
parent_.resize(vertices_count);
std::iota(parent_.begin(), parent_.end(), 0);
sets_count_ = vertices_count;
}
size_type find_set(const size_type vertex) {
if (vertex != parent_[vertex]) {
parent_[vertex] = find_set(parent_[vertex]);
}
return parent_[vertex];
}
bool unite(const size_type a, const size_type b) {
size_type x = find_set(a);
size_type y = find_set(b);
if (x == y) {
return false;
}
if (Random::get(2) == 0) {
std::swap(x, y);
}
parent_[x] = y;
--sets_count_;
return true;
}
void finalize() {
for (auto& it : parent_) {
it = find_set(it);
}
}
size_type size() const {
return parent_.size();
}
size_type sets_count() const {
return sets_count_;
}
const std::vector<size_type>& data() const {
return parent_;
}
private:
std::vector<size_type> parent_;
size_type sets_count_;
};<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include "base/timer.h"
class Timer::TimerTask : public Task {
public:
TimerTask(TimerPtr timer, boost::system::error_code ec)
: Task(timer->task_id_, timer->task_instance_), timer_(timer), ec_(ec) {
}
virtual ~TimerTask() {
}
// Invokes user callback.
// Timer could have been cancelled or delete when task was enqueued
virtual bool Run() {
// cancelled task .. ignore
if (task_cancelled()) {
// Cancelled timer's task releases the ownership of the timer
timer_ = NULL;
return true;
}
{
tbb::mutex::scoped_lock lock(timer_->mutex_);
// Handle timer Cancelled when it was enqueued to TBB
// Removes Task reference
if (timer_->state_ == Timer::Cancelled) {
return true;
}
// Conditions to invoke user callback met. Fire it
timer_->SetState(Timer::Fired);
}
bool restart = false;
// TODO: Is this error needed by user?
if (ec_ && !timer_->error_handler_.empty()) {
timer_->error_handler_(timer_->name_,
std::string(ec_.category().name()),
ec_.message());
} else {
restart = timer_->handler_();
}
OnTaskCancel();
if (restart) {
timer_->Start(timer_->time_, timer_->handler_,
timer_->error_handler_);
}
return true;
}
// Task Cancelled/Destroyed when it was Fired.
void OnTaskCancel() {
if (!timer_) {
return;
}
tbb::mutex::scoped_lock lock(timer_->mutex_);
if (timer_->timer_task_ != this) {
assert(!timer_->timer_task_);
}
timer_->timer_task_ = NULL;
timer_->SetState(Timer::Init);
}
private:
TimerPtr timer_;
boost::system::error_code ec_;
DISALLOW_COPY_AND_ASSIGN(TimerTask);
};
Timer::Timer(boost::asio::io_service &service, const std::string &name,
int task_id, int task_instance)
: boost::asio::monotonic_deadline_timer(service), name_(name), handler_(NULL),
error_handler_(NULL), state_(Init), timer_task_(NULL), time_(0),
task_id_(task_id), task_instance_(task_instance), seq_no_(0) {
refcount_ = 0;
}
Timer::~Timer() {
assert(state_ != Running && state_ != Fired);
}
//
// Start a timer
//
// If the timer is already running, return silently
//
bool Timer::Start(int time, Handler handler, ErrorHandler error_handler) {
tbb::mutex::scoped_lock lock(mutex_);
if (time < 0) {
return true;
}
if (state_ == Running || state_ == Fired) {
return true;
}
// Restart the timer
handler_ = handler;
seq_no_++;
error_handler_ = error_handler;
boost::system::error_code ec;
expires_from_now(boost::posix_time::milliseconds(time), ec);
if (ec) {
return false;
}
SetState(Running);
async_wait(boost::bind(Timer::StartTimerTask, this, TimerPtr(this), time,
seq_no_, boost::asio::placeholders::error));
return true;
}
// Cancel a running timer
bool Timer::Cancel() {
tbb::mutex::scoped_lock lock(mutex_);
// A fired timer cannot be cancelled
if (state_ == Fired) {
return false;
}
// Cancel Task. If Task cancel succeeds, there will be no callback.
// Reset TaskRef if call succeeds.
if (timer_task_) {
TaskScheduler::CancelReturnCode rc =
TaskScheduler::GetInstance()->Cancel(timer_task_);
assert(rc != TaskScheduler::FAILED);
timer_task_ = NULL;
}
SetState(Cancelled);
return true;
}
// ASIO callback on timer expiry. Start a task to serve the timer
void Timer::StartTimerTask(boost::asio::monotonic_deadline_timer* t, TimerPtr timer,
int time, uint32_t seq_no,
const boost::system::error_code &ec) {
tbb::mutex::scoped_lock lock(timer->mutex_);
if (timer->state_ == Cancelled) {
return;
}
// If timer was cancelled, no callback is invoked
if (ec && ec.value() == boost::asio::error::operation_aborted) {
return;
}
// Timer could have fired for previous run. Validate the seq_no_
if (timer->seq_no_ != seq_no) {
return;
}
// Start a task and add Task reference.
assert(timer->timer_task_ == NULL);
timer->timer_task_ = new TimerTask(timer, ec);
timer->time_ = time;
TaskScheduler::GetInstance()->Enqueue(timer->timer_task_);
}
//
// TimerManager class routines
//
TimerManager::TimerSet TimerManager::timer_ref_;
tbb::mutex TimerManager::mutex_;
Timer *TimerManager::CreateTimer(
boost::asio::io_service &service, const std::string &name,
int task_id, int task_instance) {
Timer *timer = new Timer(service, name, task_id, task_instance);
AddTimer(timer);
return timer;
}
void TimerManager::AddTimer(Timer *timer) {
tbb::mutex::scoped_lock lock(mutex_);
timer_ref_.insert(TimerPtr(timer));
return;
}
//
// Delete a timer object from the data base, by removing the intrusive
// reference. If any other objects has a reference to this timer such as
// boost::asio, the timer object deletion is automatically deferred
//
bool TimerManager::DeleteTimer(Timer *timer) {
if (!timer || timer->fired()) return false;
timer->Cancel();
tbb::mutex::scoped_lock lock(mutex_);
timer_ref_.erase(TimerPtr(timer));
return true;
}
<commit_msg>move the task_cancelled() check under mutex. Also remove the redundant check<commit_after>/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include "base/timer.h"
class Timer::TimerTask : public Task {
public:
TimerTask(TimerPtr timer, boost::system::error_code ec)
: Task(timer->task_id_, timer->task_instance_), timer_(timer), ec_(ec) {
}
virtual ~TimerTask() {
}
// Invokes user callback.
// Timer could have been cancelled or delete when task was enqueued
virtual bool Run() {
{
tbb::mutex::scoped_lock lock(timer_->mutex_);
// cancelled task .. ignore
if (task_cancelled()) {
// Cancelled timer's task releases the ownership of the timer
timer_ = NULL;
return true;
}
// Conditions to invoke user callback met. Fire it
timer_->SetState(Timer::Fired);
}
bool restart = false;
// TODO: Is this error needed by user?
if (ec_ && !timer_->error_handler_.empty()) {
timer_->error_handler_(timer_->name_,
std::string(ec_.category().name()),
ec_.message());
} else {
restart = timer_->handler_();
}
OnTaskCancel();
if (restart) {
timer_->Start(timer_->time_, timer_->handler_,
timer_->error_handler_);
}
return true;
}
// Task Cancelled/Destroyed when it was Fired.
void OnTaskCancel() {
if (!timer_) {
return;
}
tbb::mutex::scoped_lock lock(timer_->mutex_);
if (timer_->timer_task_ != this) {
assert(!timer_->timer_task_);
}
timer_->timer_task_ = NULL;
timer_->SetState(Timer::Init);
}
private:
TimerPtr timer_;
boost::system::error_code ec_;
DISALLOW_COPY_AND_ASSIGN(TimerTask);
};
Timer::Timer(boost::asio::io_service &service, const std::string &name,
int task_id, int task_instance)
: boost::asio::monotonic_deadline_timer(service), name_(name), handler_(NULL),
error_handler_(NULL), state_(Init), timer_task_(NULL), time_(0),
task_id_(task_id), task_instance_(task_instance), seq_no_(0) {
refcount_ = 0;
}
Timer::~Timer() {
assert(state_ != Running && state_ != Fired);
}
//
// Start a timer
//
// If the timer is already running, return silently
//
bool Timer::Start(int time, Handler handler, ErrorHandler error_handler) {
tbb::mutex::scoped_lock lock(mutex_);
if (time < 0) {
return true;
}
if (state_ == Running || state_ == Fired) {
return true;
}
// Restart the timer
handler_ = handler;
seq_no_++;
error_handler_ = error_handler;
boost::system::error_code ec;
expires_from_now(boost::posix_time::milliseconds(time), ec);
if (ec) {
return false;
}
SetState(Running);
async_wait(boost::bind(Timer::StartTimerTask, this, TimerPtr(this), time,
seq_no_, boost::asio::placeholders::error));
return true;
}
// Cancel a running timer
bool Timer::Cancel() {
tbb::mutex::scoped_lock lock(mutex_);
// A fired timer cannot be cancelled
if (state_ == Fired) {
return false;
}
// Cancel Task. If Task cancel succeeds, there will be no callback.
// Reset TaskRef if call succeeds.
if (timer_task_) {
TaskScheduler::CancelReturnCode rc =
TaskScheduler::GetInstance()->Cancel(timer_task_);
assert(rc != TaskScheduler::FAILED);
timer_task_ = NULL;
}
SetState(Cancelled);
return true;
}
// ASIO callback on timer expiry. Start a task to serve the timer
void Timer::StartTimerTask(boost::asio::monotonic_deadline_timer* t, TimerPtr timer,
int time, uint32_t seq_no,
const boost::system::error_code &ec) {
tbb::mutex::scoped_lock lock(timer->mutex_);
if (timer->state_ == Cancelled) {
return;
}
// If timer was cancelled, no callback is invoked
if (ec && ec.value() == boost::asio::error::operation_aborted) {
return;
}
// Timer could have fired for previous run. Validate the seq_no_
if (timer->seq_no_ != seq_no) {
return;
}
// Start a task and add Task reference.
assert(timer->timer_task_ == NULL);
timer->timer_task_ = new TimerTask(timer, ec);
timer->time_ = time;
TaskScheduler::GetInstance()->Enqueue(timer->timer_task_);
}
//
// TimerManager class routines
//
TimerManager::TimerSet TimerManager::timer_ref_;
tbb::mutex TimerManager::mutex_;
Timer *TimerManager::CreateTimer(
boost::asio::io_service &service, const std::string &name,
int task_id, int task_instance) {
Timer *timer = new Timer(service, name, task_id, task_instance);
AddTimer(timer);
return timer;
}
void TimerManager::AddTimer(Timer *timer) {
tbb::mutex::scoped_lock lock(mutex_);
timer_ref_.insert(TimerPtr(timer));
return;
}
//
// Delete a timer object from the data base, by removing the intrusive
// reference. If any other objects has a reference to this timer such as
// boost::asio, the timer object deletion is automatically deferred
//
bool TimerManager::DeleteTimer(Timer *timer) {
if (!timer || timer->fired()) return false;
timer->Cancel();
tbb::mutex::scoped_lock lock(mutex_);
timer_ref_.erase(TimerPtr(timer));
return true;
}
<|endoftext|> |
<commit_before>#pragma once
#include <cstdint> // uint8_t
#include <functional> // hash
#include <iosfwd>
#include <limits> // numeric_limits
#include <type_traits> // is_nothrow_constructible
#include <utility> // forward
#include "sdd/mem/variant_impl.hh"
#include "sdd/util/hash.hh"
#include "sdd/util/packed.hh"
#include "sdd/util/typelist.hh"
namespace sdd { namespace mem {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Helper struct to determine the type to be constructed in place.
template <typename T>
struct construct {};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief A type-safe discriminated union.
/// @tparam Types The list of possible types.
///
/// This type is meant to be stored in a unique_table, wrapped in a ref_counted.
/// Once constructed, it can never be assigned an other data.
/// It is at the heart of the library: sdd::SDD and sdd::homomorphism definitions rely on it.
template <typename... Types>
struct LIBSDD_ATTRIBUTE_PACKED variant
{
// Can't copy a variant.
const variant& operator=(const variant&) = delete;
variant(const variant&) = delete;
// Can't move a variant.
variant& operator=(variant&&) = delete;
variant(variant&&) = delete;
static_assert( sizeof...(Types) >= 1
, "A variant should contain at least one type.");
static_assert( sizeof...(Types) <= std::numeric_limits<uint8_t>::max()
, "A variant can't hold more than UCHAR_MAX types.");
/// @brief Index of the held type in the list of all possible types.
const uint8_t index;
/// @brief A type large enough to contain all variant's types, with the correct alignement.
using storage_type = typename union_storage<0, Types...>::type;
/// @brief Memory storage suitable for all Types.
const storage_type storage;
/// @brief In place construction of an held type.
///
/// Unlike boost::variant, we don't need the never empty guaranty, so we don't need to check
/// if held types can throw exceptions upon construction.
template <typename T, typename... Args>
variant(construct<T>, Args&&... args)
noexcept(std::is_nothrow_constructible<T, Args...>::value)
: index(util::index_of<T, Types...>::value)
, storage()
{
new (const_cast<storage_type*>(&storage)) T{std::forward<Args>(args)...};
}
/// @brief Destructor.
~variant()
{
apply_visitor(dtor_visitor(), *this);
}
friend
std::ostream&
operator<<(std::ostream& os, const variant& v)
{
return apply_visitor([&](const auto& x) -> std::ostream& {return os << x;}, v);
}
friend
bool
operator==(const variant& lhs, const variant& rhs)
noexcept
{
return lhs.index == rhs.index and apply_binary_visitor(eq_visitor(), lhs, rhs);
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @related variant
template <typename T, typename... Types>
inline
auto
is(const variant<Types...>& v)
noexcept
{
return v.index == util::index_of<typename std::decay<T>::type, Types...>::value;
}
/// @internal
/// @related variant
template <typename T, typename VariantProxy>
inline
auto
is(const VariantProxy& v)
noexcept
{
return is<T>(*v);
}
/// @internal
/// @related variant
template <typename T, typename... Types>
inline
const T&
variant_cast(const variant<Types...>& v)
noexcept
{
assert(is<T>(v));
return *reinterpret_cast<const T*>(&v.storage);
}
/*------------------------------------------------------------------------------------------------*/
} // namespace mem
/*------------------------------------------------------------------------------------------------*/
/// @brief
/// @related mem::variant
template <typename Visitor, typename X, typename... Args>
inline
auto
visit(Visitor&& v, const X& x, Args&&... args)
-> decltype(apply_visitor(std::forward<Visitor>(v), *x, std::forward<Args>(args)...))
{
return apply_visitor(std::forward<Visitor>(v), *x, std::forward<Args>(args)...);
}
/*------------------------------------------------------------------------------------------------*/
/// @brief
/// @related mem::variant
template <typename Visitor, typename X, typename Y, typename... Args>
inline
auto
binary_visit(Visitor&& v, const X& x, const Y& y, Args&&... args)
-> decltype(apply_binary_visitor(std::forward<Visitor>(v), *x, *y, std::forward<Args>(args)...))
{
return apply_binary_visitor(std::forward<Visitor>(v), *x, *y, std::forward<Args>(args)...);
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::mem::variant
template <typename... Types>
struct hash<sdd::mem::variant<Types...>>
{
std::size_t
operator()(const sdd::mem::variant<Types...>& x)
const
{
using namespace sdd::hash;
return seed(apply_visitor(sdd::mem::hash_visitor{}, x)) (val(x.index));
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
<commit_msg>Useless auto specification<commit_after>#pragma once
#include <cstdint> // uint8_t
#include <functional> // hash
#include <iosfwd>
#include <limits> // numeric_limits
#include <type_traits> // is_nothrow_constructible
#include <utility> // forward
#include "sdd/mem/variant_impl.hh"
#include "sdd/util/hash.hh"
#include "sdd/util/packed.hh"
#include "sdd/util/typelist.hh"
namespace sdd { namespace mem {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Helper struct to determine the type to be constructed in place.
template <typename T>
struct construct {};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief A type-safe discriminated union.
/// @tparam Types The list of possible types.
///
/// This type is meant to be stored in a unique_table, wrapped in a ref_counted.
/// Once constructed, it can never be assigned an other data.
/// It is at the heart of the library: sdd::SDD and sdd::homomorphism definitions rely on it.
template <typename... Types>
struct LIBSDD_ATTRIBUTE_PACKED variant
{
// Can't copy a variant.
const variant& operator=(const variant&) = delete;
variant(const variant&) = delete;
// Can't move a variant.
variant& operator=(variant&&) = delete;
variant(variant&&) = delete;
static_assert( sizeof...(Types) >= 1
, "A variant should contain at least one type.");
static_assert( sizeof...(Types) <= std::numeric_limits<uint8_t>::max()
, "A variant can't hold more than UCHAR_MAX types.");
/// @brief Index of the held type in the list of all possible types.
const uint8_t index;
/// @brief A type large enough to contain all variant's types, with the correct alignement.
using storage_type = typename union_storage<0, Types...>::type;
/// @brief Memory storage suitable for all Types.
const storage_type storage;
/// @brief In place construction of an held type.
///
/// Unlike boost::variant, we don't need the never empty guaranty, so we don't need to check
/// if held types can throw exceptions upon construction.
template <typename T, typename... Args>
variant(construct<T>, Args&&... args)
noexcept(std::is_nothrow_constructible<T, Args...>::value)
: index(util::index_of<T, Types...>::value)
, storage()
{
new (const_cast<storage_type*>(&storage)) T{std::forward<Args>(args)...};
}
/// @brief Destructor.
~variant()
{
apply_visitor(dtor_visitor(), *this);
}
friend
std::ostream&
operator<<(std::ostream& os, const variant& v)
{
return apply_visitor([&](const auto& x) -> std::ostream& {return os << x;}, v);
}
friend
bool
operator==(const variant& lhs, const variant& rhs)
noexcept
{
return lhs.index == rhs.index and apply_binary_visitor(eq_visitor(), lhs, rhs);
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @related variant
template <typename T, typename... Types>
inline
bool
is(const variant<Types...>& v)
noexcept
{
return v.index == util::index_of<typename std::decay<T>::type, Types...>::value;
}
/// @internal
/// @related variant
template <typename T, typename VariantProxy>
inline
bool
is(const VariantProxy& v)
noexcept
{
return is<T>(*v);
}
/// @internal
/// @related variant
template <typename T, typename... Types>
inline
const T&
variant_cast(const variant<Types...>& v)
noexcept
{
assert(is<T>(v));
return *reinterpret_cast<const T*>(&v.storage);
}
/*------------------------------------------------------------------------------------------------*/
} // namespace mem
/*------------------------------------------------------------------------------------------------*/
/// @brief
/// @related mem::variant
template <typename Visitor, typename X, typename... Args>
inline
auto
visit(Visitor&& v, const X& x, Args&&... args)
-> decltype(apply_visitor(std::forward<Visitor>(v), *x, std::forward<Args>(args)...))
{
return apply_visitor(std::forward<Visitor>(v), *x, std::forward<Args>(args)...);
}
/*------------------------------------------------------------------------------------------------*/
/// @brief
/// @related mem::variant
template <typename Visitor, typename X, typename Y, typename... Args>
inline
auto
binary_visit(Visitor&& v, const X& x, const Y& y, Args&&... args)
-> decltype(apply_binary_visitor(std::forward<Visitor>(v), *x, *y, std::forward<Args>(args)...))
{
return apply_binary_visitor(std::forward<Visitor>(v), *x, *y, std::forward<Args>(args)...);
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::mem::variant
template <typename... Types>
struct hash<sdd::mem::variant<Types...>>
{
std::size_t
operator()(const sdd::mem::variant<Types...>& x)
const
{
using namespace sdd::hash;
return seed(apply_visitor(sdd::mem::hash_visitor{}, x)) (val(x.index));
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
<|endoftext|> |
<commit_before>#ifndef _SDD_MEM_VARIANT_HH_
#define _SDD_MEM_VARIANT_HH_
#ifndef LIBSDD_VARIANT_SIZE
#define LIBSDD_VARIANT_SIZE 16
#endif
#include <climits> // USHRT_MAX
#include <cstdint> // uint8_t
#include <functional> // hash
#include <iosfwd>
#include <type_traits> // is_nothrow_constructible
#include <utility> // forward
#include "sdd/mem/variant_impl.hh"
#include "sdd/util/hash.hh"
#include "sdd/util/packed.hh"
#include "sdd/util/typelist.hh"
#include "sdd/util/print_sizes_fwd.hh"
namespace sdd { namespace mem {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @page Variant
///
/// The sdd::mem::variant class is at the heart of the library. Indeed, sdd::SDD and
/// sdd::homomorphism definitions rely on it.
///
/// Its purpose is to emulate a union, but with much more possibilities. It's completely inspired
/// from boost::variant.
/// http://www.boost.org/doc/libs/release/doc/html/variant.html
///
/// The visit mechanism uses 'computed goto', a GCC extension, also supported by clang.
/// Note that a 'switch' statement will also do the job.
/// http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Labels-as-Values.html
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Helper struct to determine the type to be constructed in place.
template <typename T>
struct construct {};
/*------------------------------------------------------------------------------------------------*/
// Forward declaration for destructor.
template <typename Visitor, typename Variant, typename... Args>
typename Visitor::result_type
apply_visitor(const Visitor&, const Variant&, Args&&...);
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief A union-like structure.
/// @tparam Types The list of possible types.
///
/// This type is meant to be stored in a unique_table, wrapped in a ref_counted.
/// Once constructed, it can never be assigned an other data.
template <typename... Types>
class LIBSDD_ATTRIBUTE_PACKED variant
{
// Can't copy a variant.
const variant& operator=(const variant&) = delete;
variant(const variant&) = delete;
// Can't move a variant.
variant& operator=(variant&&) = delete;
variant(variant&&) = delete;
private:
template <typename C>
friend void util::print_sizes(std::ostream&);
static_assert( sizeof...(Types) >= 1
, "A variant should contain at least one type.");
static_assert( sizeof...(Types) <= UCHAR_MAX
, "A variant can't hold more than UCHAR_MAX types.");
static_assert( sizeof...(Types) <= LIBSDD_VARIANT_SIZE
, "LIBSDD_VARIANT_SIZE is too small for the required number of types.");
/// @brief Index of the held type in the list of all possible types.
const uint8_t index_;
/// @brief A type large enough to contain all variant's types, with the correct alignement.
typedef typename union_storage<0, Types...>::type storage_type;
/// @brief Memory storage suitable for all Types.
const storage_type storage_;
public:
/// @brief In place construction of an held type.
///
/// Unlike boost::variant, we don't need the never empty guaranty, so we don't need to check
/// if held types can throw exceptions upon construction.
template <typename T, typename... Args>
variant(construct<T>, Args&&... args)
noexcept(std::is_nothrow_constructible<T, Args...>::value)
: index_(util::index_of<const T, const Types...>::value)
, storage_()
{
new (const_cast<storage_type*>(&storage_)) T(std::forward<Args>(args)...);
}
/// @brief Destructor.
~variant()
{
apply_visitor(dtor_visitor(), *this);
}
/// @brief Get as type T.
///
/// No verifications are done.
template <typename T>
const T&
get()
const noexcept
{
return *reinterpret_cast<const T*>(&storage_);
}
/// @brief Return the position of the currently held type in the list of all possible types.
uint8_t
index()
const noexcept
{
return index_;
}
/// @brief Return the raw storage.
const storage_type&
storage()
const noexcept
{
return storage_;
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @related variant
template < typename Visitor
, typename... Types, template <typename...> class Variant
, typename... Args>
inline
typename Visitor::result_type
apply_visitor(const Visitor& v, const Variant<Types...>& x, Args&&... args)
{
return dispatch( v
, x.storage(), util::typelist<Types...>(), x.index()
, std::forward<Args>(args)...);
}
/// @internal
/// @related variant
template < typename Visitor
, typename... Types1, template <typename...> class Variant1
, typename... Types2, template <typename...> class Variant2
, typename... Args>
inline
typename Visitor::result_type
apply_binary_visitor( const Visitor& v
, const Variant1<Types1...>& x, const Variant2<Types2...>& y
, Args&&... args)
{
return binary_dispatch( v
, x.storage(), util::typelist<Types1...>(), x.index()
, y.storage(), util::typelist<Types2...>(), y.index()
, std::forward<Args>(args)...);
}
/// @internal
/// @related variant
template <typename... Types>
inline
bool
operator==(const variant<Types...>& lhs, const variant<Types...>& rhs)
noexcept
{
return lhs.index() == rhs.index() and apply_binary_visitor(eq_visitor(), lhs, rhs);
}
/// @internal
/// @related variant
template <typename T, typename... Types>
inline
const T&
variant_cast(const variant<Types...>& v)
noexcept
{
return v.template get<T>();
}
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @related variant
template <typename... Types>
std::ostream&
operator<<(std::ostream& os, const variant<Types...>& v)
{
return apply_visitor(ostream_visitor(os), v);
}
/*------------------------------------------------------------------------------------------------*/
}} // namespace sdd::mem
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::mem::variant
template <typename... Types>
struct hash<const sdd::mem::variant<Types...>>
{
std::size_t
operator()(const sdd::mem::variant<Types...>& x)
const noexcept
{
std::size_t seed = sdd::mem::apply_visitor(sdd::mem::hash_visitor(), x);
sdd::util::hash_combine(seed, x.index());
return seed;
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_INTERNAL_MEM_VARIANT_HH_
<commit_msg>Reduce the variant's size.<commit_after>#ifndef _SDD_MEM_VARIANT_HH_
#define _SDD_MEM_VARIANT_HH_
#ifndef LIBSDD_VARIANT_SIZE
#define LIBSDD_VARIANT_SIZE 12
#endif
#include <climits> // USHRT_MAX
#include <cstdint> // uint8_t
#include <functional> // hash
#include <iosfwd>
#include <type_traits> // is_nothrow_constructible
#include <utility> // forward
#include "sdd/mem/variant_impl.hh"
#include "sdd/util/hash.hh"
#include "sdd/util/packed.hh"
#include "sdd/util/typelist.hh"
#include "sdd/util/print_sizes_fwd.hh"
namespace sdd { namespace mem {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @page Variant
///
/// The sdd::mem::variant class is at the heart of the library. Indeed, sdd::SDD and
/// sdd::homomorphism definitions rely on it.
///
/// Its purpose is to emulate a union, but with much more possibilities. It's completely inspired
/// from boost::variant.
/// http://www.boost.org/doc/libs/release/doc/html/variant.html
///
/// The visit mechanism uses 'computed goto', a GCC extension, also supported by clang.
/// Note that a 'switch' statement will also do the job.
/// http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Labels-as-Values.html
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Helper struct to determine the type to be constructed in place.
template <typename T>
struct construct {};
/*------------------------------------------------------------------------------------------------*/
// Forward declaration for destructor.
template <typename Visitor, typename Variant, typename... Args>
typename Visitor::result_type
apply_visitor(const Visitor&, const Variant&, Args&&...);
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief A union-like structure.
/// @tparam Types The list of possible types.
///
/// This type is meant to be stored in a unique_table, wrapped in a ref_counted.
/// Once constructed, it can never be assigned an other data.
template <typename... Types>
class LIBSDD_ATTRIBUTE_PACKED variant
{
// Can't copy a variant.
const variant& operator=(const variant&) = delete;
variant(const variant&) = delete;
// Can't move a variant.
variant& operator=(variant&&) = delete;
variant(variant&&) = delete;
private:
template <typename C>
friend void util::print_sizes(std::ostream&);
static_assert( sizeof...(Types) >= 1
, "A variant should contain at least one type.");
static_assert( sizeof...(Types) <= UCHAR_MAX
, "A variant can't hold more than UCHAR_MAX types.");
static_assert( sizeof...(Types) <= LIBSDD_VARIANT_SIZE
, "LIBSDD_VARIANT_SIZE is too small for the required number of types.");
/// @brief Index of the held type in the list of all possible types.
const uint8_t index_;
/// @brief A type large enough to contain all variant's types, with the correct alignement.
typedef typename union_storage<0, Types...>::type storage_type;
/// @brief Memory storage suitable for all Types.
const storage_type storage_;
public:
/// @brief In place construction of an held type.
///
/// Unlike boost::variant, we don't need the never empty guaranty, so we don't need to check
/// if held types can throw exceptions upon construction.
template <typename T, typename... Args>
variant(construct<T>, Args&&... args)
noexcept(std::is_nothrow_constructible<T, Args...>::value)
: index_(util::index_of<const T, const Types...>::value)
, storage_()
{
new (const_cast<storage_type*>(&storage_)) T(std::forward<Args>(args)...);
}
/// @brief Destructor.
~variant()
{
apply_visitor(dtor_visitor(), *this);
}
/// @brief Get as type T.
///
/// No verifications are done.
template <typename T>
const T&
get()
const noexcept
{
return *reinterpret_cast<const T*>(&storage_);
}
/// @brief Return the position of the currently held type in the list of all possible types.
uint8_t
index()
const noexcept
{
return index_;
}
/// @brief Return the raw storage.
const storage_type&
storage()
const noexcept
{
return storage_;
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @related variant
template < typename Visitor
, typename... Types, template <typename...> class Variant
, typename... Args>
inline
typename Visitor::result_type
apply_visitor(const Visitor& v, const Variant<Types...>& x, Args&&... args)
{
return dispatch( v
, x.storage(), util::typelist<Types...>(), x.index()
, std::forward<Args>(args)...);
}
/// @internal
/// @related variant
template < typename Visitor
, typename... Types1, template <typename...> class Variant1
, typename... Types2, template <typename...> class Variant2
, typename... Args>
inline
typename Visitor::result_type
apply_binary_visitor( const Visitor& v
, const Variant1<Types1...>& x, const Variant2<Types2...>& y
, Args&&... args)
{
return binary_dispatch( v
, x.storage(), util::typelist<Types1...>(), x.index()
, y.storage(), util::typelist<Types2...>(), y.index()
, std::forward<Args>(args)...);
}
/// @internal
/// @related variant
template <typename... Types>
inline
bool
operator==(const variant<Types...>& lhs, const variant<Types...>& rhs)
noexcept
{
return lhs.index() == rhs.index() and apply_binary_visitor(eq_visitor(), lhs, rhs);
}
/// @internal
/// @related variant
template <typename T, typename... Types>
inline
const T&
variant_cast(const variant<Types...>& v)
noexcept
{
return v.template get<T>();
}
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @related variant
template <typename... Types>
std::ostream&
operator<<(std::ostream& os, const variant<Types...>& v)
{
return apply_visitor(ostream_visitor(os), v);
}
/*------------------------------------------------------------------------------------------------*/
}} // namespace sdd::mem
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::mem::variant
template <typename... Types>
struct hash<const sdd::mem::variant<Types...>>
{
std::size_t
operator()(const sdd::mem::variant<Types...>& x)
const noexcept
{
std::size_t seed = sdd::mem::apply_visitor(sdd::mem::hash_visitor(), x);
sdd::util::hash_combine(seed, x.index());
return seed;
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_INTERNAL_MEM_VARIANT_HH_
<|endoftext|> |
<commit_before>/**
* blufs - a c++ luafilesystem library
* --------------------------------------------------------
* Copyright 2013-2015 Dmitry Ledentsov
* [MIT License](http://opensource.org/licenses/MIT)
*
*/
#include "blufs_lib.h"
#include <boost/filesystem.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/shared_ptr.hpp>
#include <lua.hpp>
#include <luabind/luabind.hpp>
#include <luabind/tag_function.hpp>
#include <luabind/operator.hpp>
#include <luabind/copy_policy.hpp>
#include <luabind/iterator_policy.hpp>
#include <boost/container/vector.hpp>
#include <string>
#include <stdexcept>
#include <iostream>
namespace blufs = boost::filesystem;
std::ostream& operator<<(std::ostream& s, blufs::path const& p) {
return s << p;
}
blufs::path const& itself(blufs::path const& self) { return self; }
blufs::path absolute_d(blufs::path const& self) { return blufs::absolute(self); }
blufs::path canonical_d(blufs::path const& self) { return blufs::canonical(self); }
void current_path_s(std::string const& p) { blufs::current_path(p); }
bool create_directories_s(std::string const& p) { return blufs::create_directories(p); }
bool create_directory_s(std::string const& p) { return blufs::create_directory(p); }
void copy_s(std::string const& from,std::string const& to) { blufs::copy(from,to); }
void copy_directory_s(std::string const& from,std::string const& to) { blufs::copy_directory(from,to); }
void copy_file_s(std::string const& from,std::string const& to) { blufs::copy_file(from,to); }
void copy_symlink_s(std::string const& from,std::string const& to) { blufs::copy_symlink(from,to); }
void register_blufs (lua_State* L) {
using namespace luabind;
using namespace blufs;
open(L);
module(L, "blufs")
[
class_<path, boost::shared_ptr<path>>("path")
.def(constructor<std::string const&>())
.def(constructor<>())
.def(constructor<path const&>())
.def(tostring(self))
//.def(const_self + path())
.def(const_self / path())
//.def(const_self + std::string())
.def(const_self / std::string())
.def(const_self == std::string())
.property("generic_string", (std::string(path::*)()const) &path::generic_string)
.property("root_path", &path::root_path)
.property("root_name", &path::root_name)
.property("root_directory", &path::root_directory)
.property("relative_path", &path::relative_path)
.property("parent_path", &path::parent_path)
.property("filename", &path::filename)
.property("stem", &path::stem)
.property("extension", &path::extension)
.property("empty", &path::empty)
.property("exists", (bool(*)(path const&))exists)
.property("absolute",absolute_d)
.property("canonical", canonical_d)
.def("parts", itself, copy(result) + return_stl_iterator)
.def("absolute_to", (path(*)(path const&, path const&))absolute)
.def("canonical_to", (path(*)(path const&, path const&))canonical)
.def("clear", &path::clear)
.def("make_preferred", &path::make_preferred)
.def("remove_filename", &path::remove_filename)
.def("replace_extension", &path::replace_extension)
.def("compare", (int(path::*)(std::string const&)const) &path::compare)
.def("compare", (int(path::*)(path const&)const) &path::compare)
.enum_("file_type")
[
value("status_error", blufs::status_error),
value("file_not_found", blufs::file_not_found),
value("regular_file", blufs::regular_file),
value("directory_file", blufs::directory_file),
value("symlink_file", blufs::symlink_file),
value("block_file", blufs::block_file),
value("character_file", blufs::character_file),
value("fifo_file", blufs::fifo_file),
value("socket_file", blufs::socket_file),
value("type_unknown", blufs::type_unknown)
]
.enum_("perms")
[
value("no_perms", blufs::no_perms),
value("owner_read", blufs::owner_read),
value("owner_write", blufs::owner_write),
value("owner_exe", blufs::owner_exe),
value("owner_all", blufs::owner_all),
value("group_read", blufs::group_read),
value("group_write", blufs::group_write),
value("group_exe", blufs::group_exe),
value("group_all", blufs::group_all),
value("others_read", blufs::others_read),
value("others_write", blufs::others_write),
value("others_exe", blufs::others_exe),
value("others_all", blufs::others_all),
value("all_all", blufs::all_all),
value("set_uid_on_exe", blufs::set_uid_on_exe),
value("set_gid_on_exe", blufs::set_gid_on_exe),
value("sticky_bit", blufs::sticky_bit),
value("perms_mask", blufs::perms_mask),
value("perms_not_known", blufs::perms_not_known),
value("add_perms", blufs::add_perms),
value("remove_perms", blufs::remove_perms),
value("symlink_perms", blufs::symlink_perms)
]
,
class_<blufs::space_info>("space_info")
.def_readwrite("capacity", &blufs::space_info::capacity)
.def_readwrite("free", &blufs::space_info::free)
.def_readwrite("available", &blufs::space_info::available)
,
class_<blufs::copy_option>("copy_option")
.enum_("values")
[
value("none", static_cast<int>(blufs::copy_option::none)),
value("fail_if_exists", static_cast<int>(blufs::copy_option::fail_if_exists)),
value("overwrite_if_exists", static_cast<int>(blufs::copy_option::overwrite_if_exists))
]
,
class_<blufs::symlink_option>("symlink_option")
.enum_("values")
[
value("none", static_cast<int>(blufs::symlink_option::none)),
value("no_recurse", static_cast<int>(blufs::symlink_option::no_recurse)),
value("recurse", static_cast<int>(blufs::symlink_option::recurse))
]
,
def("current_path", (blufs::path(*)()) blufs::current_path),
def("current_path", (void(*)(blufs::path const&)) blufs::current_path),
def("current_path", current_path_s ),
def("create_directories", (bool(*)(blufs::path const&)) blufs::create_directories),
def("create_directories", create_directories_s),
def("create_directory", (bool(*)(blufs::path const&)) blufs::create_directory),
def("create_directory", create_directory_s),
def("copy", (void(*)(blufs::path const&,blufs::path const&)) blufs::copy),
def("copy", copy_s),
def("copy_directory", (void(*)(blufs::path const&,blufs::path const&)) blufs::copy_directory),
def("copy_directory", copy_directory_s),
def("copy_file", (void(*)(blufs::path const&,blufs::path const&)) blufs::copy_file),
def("copy_file", copy_file_s),
def("copy_symlink", (void(*)(blufs::path const&,blufs::path const&)) blufs::copy_symlink),
def("copy_symlink", copy_symlink_s)
];
}
<commit_msg>further queries<commit_after>/**
* blufs - a c++ luafilesystem library
* --------------------------------------------------------
* Copyright 2013-2015 Dmitry Ledentsov
* [MIT License](http://opensource.org/licenses/MIT)
*
*/
#include "blufs_lib.h"
#include <boost/filesystem.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/shared_ptr.hpp>
#include <lua.hpp>
#include <luabind/luabind.hpp>
#include <luabind/tag_function.hpp>
#include <luabind/operator.hpp>
#include <luabind/copy_policy.hpp>
#include <luabind/iterator_policy.hpp>
#include <boost/container/vector.hpp>
#include <string>
#include <stdexcept>
#include <iostream>
namespace blufs = boost::filesystem;
std::ostream& operator<<(std::ostream& s, blufs::path const& p) {
return s << p;
}
blufs::path const& itself(blufs::path const& self) { return self; }
blufs::path absolute_d(blufs::path const& self) { return blufs::absolute(self); }
blufs::path canonical_d(blufs::path const& self) { return blufs::canonical(self); }
void current_path_s(std::string const& p) { blufs::current_path(p); }
bool create_directories_s(std::string const& p) { return blufs::create_directories(p); }
bool create_directory_s(std::string const& p) { return blufs::create_directory(p); }
void create_directory_symlink_s(std::string const& from,std::string const& to) { return blufs::create_directory_symlink(from,to); }
void create_hard_link_s(std::string const& from,std::string const& to) { return blufs::create_hard_link(from,to); }
void create_symlink_s(std::string const& from,std::string const& to) { return blufs::create_symlink(from,to); }
void copy_s(std::string const& from,std::string const& to) { blufs::copy(from,to); }
void copy_directory_s(std::string const& from,std::string const& to) { blufs::copy_directory(from,to); }
void copy_file_s(std::string const& from,std::string const& to) { blufs::copy_file(from,to); }
void copy_symlink_s(std::string const& from,std::string const& to) { blufs::copy_symlink(from,to); }
bool equivalent_s(std::string const& from,std::string const& to) { return blufs::equivalent(from,to); }
uintmax_t file_size_s(std::string const& p) { return blufs::file_size(p); }
bool is_directory_s(std::string const& p) { return blufs::is_directory(p); }
bool is_empty_s(std::string const& p) { return blufs::is_empty(p); }
bool is_regular_file_s(std::string const& p) { return blufs::is_regular_file(p); }
bool is_other_s(std::string const& p) { return blufs::is_other(p); }
void register_blufs (lua_State* L) {
using namespace luabind;
using namespace blufs;
open(L);
module(L, "blufs")
[
class_<path, boost::shared_ptr<path>>("path")
.def(constructor<std::string const&>())
.def(constructor<>())
.def(constructor<path const&>())
.def(tostring(self))
//.def(const_self + path())
.def(const_self / path())
//.def(const_self + std::string())
.def(const_self / std::string())
.def(const_self == std::string())
.property("generic_string", (std::string(path::*)()const) &path::generic_string)
.property("root_path", &path::root_path)
.property("root_name", &path::root_name)
.property("root_directory", &path::root_directory)
.property("relative_path", &path::relative_path)
.property("parent_path", &path::parent_path)
.property("filename", &path::filename)
.property("stem", &path::stem)
.property("extension", &path::extension)
.property("empty", &path::empty)
.property("exists", (bool(*)(path const&))exists)
.property("absolute",absolute_d)
.property("canonical", canonical_d)
.def("parts", itself, copy(result) + return_stl_iterator)
.def("absolute_to", (path(*)(path const&, path const&))absolute)
.def("canonical_to", (path(*)(path const&, path const&))canonical)
.def("clear", &path::clear)
.def("make_preferred", &path::make_preferred)
.def("remove_filename", &path::remove_filename)
.def("replace_extension", &path::replace_extension)
.def("compare", (int(path::*)(std::string const&)const) &path::compare)
.def("compare", (int(path::*)(path const&)const) &path::compare)
.enum_("file_type")
[
value("status_error", blufs::status_error),
value("file_not_found", blufs::file_not_found),
value("regular_file", blufs::regular_file),
value("directory_file", blufs::directory_file),
value("symlink_file", blufs::symlink_file),
value("block_file", blufs::block_file),
value("character_file", blufs::character_file),
value("fifo_file", blufs::fifo_file),
value("socket_file", blufs::socket_file),
value("type_unknown", blufs::type_unknown)
]
.enum_("perms")
[
value("no_perms", blufs::no_perms),
value("owner_read", blufs::owner_read),
value("owner_write", blufs::owner_write),
value("owner_exe", blufs::owner_exe),
value("owner_all", blufs::owner_all),
value("group_read", blufs::group_read),
value("group_write", blufs::group_write),
value("group_exe", blufs::group_exe),
value("group_all", blufs::group_all),
value("others_read", blufs::others_read),
value("others_write", blufs::others_write),
value("others_exe", blufs::others_exe),
value("others_all", blufs::others_all),
value("all_all", blufs::all_all),
value("set_uid_on_exe", blufs::set_uid_on_exe),
value("set_gid_on_exe", blufs::set_gid_on_exe),
value("sticky_bit", blufs::sticky_bit),
value("perms_mask", blufs::perms_mask),
value("perms_not_known", blufs::perms_not_known),
value("add_perms", blufs::add_perms),
value("remove_perms", blufs::remove_perms),
value("symlink_perms", blufs::symlink_perms)
]
,
class_<blufs::space_info>("space_info")
.def_readwrite("capacity", &blufs::space_info::capacity)
.def_readwrite("free", &blufs::space_info::free)
.def_readwrite("available", &blufs::space_info::available)
,
class_<blufs::copy_option>("copy_option")
.enum_("values")
[
value("none", static_cast<int>(blufs::copy_option::none)),
value("fail_if_exists", static_cast<int>(blufs::copy_option::fail_if_exists)),
value("overwrite_if_exists", static_cast<int>(blufs::copy_option::overwrite_if_exists))
]
,
class_<blufs::symlink_option>("symlink_option")
.enum_("values")
[
value("none", static_cast<int>(blufs::symlink_option::none)),
value("no_recurse", static_cast<int>(blufs::symlink_option::no_recurse)),
value("recurse", static_cast<int>(blufs::symlink_option::recurse))
]
,
def("current_path", (blufs::path(*)()) blufs::current_path),
def("current_path", (void(*)(blufs::path const&)) blufs::current_path),
def("current_path", current_path_s ),
def("create_directories", (bool(*)(blufs::path const&)) blufs::create_directories),
def("create_directories", create_directories_s),
def("create_directory", (bool(*)(blufs::path const&)) blufs::create_directory),
def("create_directory", create_directory_s),
def("create_directory_symlink", (void(*)(blufs::path const&,blufs::path const&)) blufs::create_directory_symlink),
def("create_directory_symlink", create_directory_symlink_s),
def("create_hard_link", (void(*)(blufs::path const&,blufs::path const&)) blufs::create_hard_link),
def("create_hard_link", create_hard_link_s),
def("create_symlink", (void(*)(blufs::path const&,blufs::path const&)) blufs::create_symlink),
def("create_symlink", create_symlink_s),
def("copy", (void(*)(blufs::path const&,blufs::path const&)) blufs::copy),
def("copy", copy_s),
def("copy_directory", (void(*)(blufs::path const&,blufs::path const&)) blufs::copy_directory),
def("copy_directory", copy_directory_s),
def("copy_file", (void(*)(blufs::path const&,blufs::path const&)) blufs::copy_file),
def("copy_file", copy_file_s),
def("copy_symlink", (void(*)(blufs::path const&,blufs::path const&)) blufs::copy_symlink),
def("copy_symlink", copy_symlink_s),
def("equivalent", (bool(*)(blufs::path const&,blufs::path const&)) blufs::equivalent),
def("equivalent", equivalent_s),
def("file_size", (uintmax_t(*)(blufs::path const&)) blufs::file_size),
def("file_size", file_size_s),
def("initial_path", (blufs::path(*)()) blufs::initial_path),
def("is_directory", (bool(*)(blufs::path const&)) blufs::is_directory),
def("is_directory", is_directory_s),
def("is_empty", (bool(*)(blufs::path const&)) blufs::is_empty),
def("is_empty", is_empty_s),
def("is_regular_file", (bool(*)(blufs::path const&)) blufs::is_regular_file),
def("is_regular_file", is_regular_file_s),
def("is_other", (bool(*)(blufs::path const&)) blufs::is_other),
def("is_other", is_other_s)
//next last_write_time
];
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2019 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "errdoc.hxx"
#include "Request.hxx"
#include "Instance.hxx"
#include "http_server/Request.hxx"
#include "http/Headers.hxx"
#include "HttpResponseHandler.hxx"
#include "translation/Service.hxx"
#include "translation/Handler.hxx"
#include "ResourceLoader.hxx"
#include "istream/istream.hxx"
#include "istream/UnusedHoldPtr.hxx"
#include "pool/pool.hxx"
#include "io/Logger.hxx"
struct ErrorResponseLoader final : HttpResponseHandler, Cancellable {
CancellablePointer cancel_ptr;
Request &request;
http_status_t status;
HttpHeaders headers;
UnusedHoldIstreamPtr body;
TranslateRequest translate_request;
ErrorResponseLoader(Request &_request, http_status_t _status,
HttpHeaders &&_headers, UnusedIstreamPtr _body)
:request(_request), status(_status),
headers(std::move(_headers)),
body(_request.pool, std::move(_body)) {}
void Destroy() {
this->~ErrorResponseLoader();
}
/* virtual methods from class Cancellable */
void Cancel() noexcept override;
/* virtual methods from class HttpResponseHandler */
void OnHttpResponse(http_status_t status, StringMap &&headers,
UnusedIstreamPtr body) noexcept override;
void OnHttpError(std::exception_ptr ep) noexcept override;
};
static void
errdoc_resubmit(ErrorResponseLoader &er)
{
er.request.DispatchResponse(er.status, std::move(er.headers),
std::move(er.body));
}
/*
* HTTP response handler
*
*/
void
ErrorResponseLoader::OnHttpResponse(http_status_t _status, StringMap &&_headers,
UnusedIstreamPtr _body) noexcept
{
if (http_status_is_success(_status)) {
/* close the original (error) response body */
body.Clear();
request.InvokeResponse(status, std::move(_headers), std::move(_body));
} else {
/* close the original (error) response body */
_body.Clear();
errdoc_resubmit(*this);
}
Destroy();
}
void
ErrorResponseLoader::OnHttpError(std::exception_ptr ep) noexcept
{
LogConcat(2, request.request.uri, "error on error document: ", ep);
errdoc_resubmit(*this);
Destroy();
}
/*
* translate handler
*
*/
static void
errdoc_translate_response(TranslateResponse &response, void *ctx)
{
auto &er = *(ErrorResponseLoader *)ctx;
if ((response.status == (http_status_t)0 ||
http_status_is_success(response.status)) &&
response.address.IsDefined()) {
auto &request = er.request;
request.instance.cached_resource_loader
->SendRequest(request.pool, 0, nullptr, nullptr,
HTTP_METHOD_GET,
response.address, HTTP_STATUS_OK,
StringMap(request.pool), nullptr, nullptr,
er, request.cancel_ptr);
} else {
errdoc_resubmit(er);
er.Destroy();
}
}
static void
errdoc_translate_error(std::exception_ptr ep, void *ctx)
{
auto &er = *(ErrorResponseLoader *)ctx;
LogConcat(2, er.request.request.uri,
"error document translation error: ", ep);
errdoc_resubmit(er);
er.Destroy();
}
static constexpr TranslateHandler errdoc_translate_handler = {
.response = errdoc_translate_response,
.error = errdoc_translate_error,
};
static void
fill_translate_request(TranslateRequest *t,
const TranslateRequest *src,
ConstBuffer<void> error_document,
http_status_t status)
{
*t = *src;
t->error_document = error_document;
t->error_document_status = status;
}
/*
* async operation
*
*/
void
ErrorResponseLoader::Cancel() noexcept
{
body.Clear();
CancellablePointer c(std::move(cancel_ptr));
Destroy();
c.Cancel();
}
/*
* constructor
*
*/
void
errdoc_dispatch_response(Request &request2, http_status_t status,
ConstBuffer<void> error_document,
HttpHeaders &&headers, UnusedIstreamPtr body)
{
assert(!error_document.IsNull());
auto &instance = request2.instance;
assert(instance.translation_service != nullptr);
auto *er = NewFromPool<ErrorResponseLoader>(request2.pool, request2,
status, std::move(headers),
std::move(body));
request2.cancel_ptr = *er;
fill_translate_request(&er->translate_request,
&request2.translate.request,
error_document, status);
instance.translation_service->SendRequest(request2.pool,
er->translate_request,
errdoc_translate_handler, er,
er->cancel_ptr);
}
<commit_msg>bp/errdoc: remove redundant body.Clear() call<commit_after>/*
* Copyright 2007-2019 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "errdoc.hxx"
#include "Request.hxx"
#include "Instance.hxx"
#include "http_server/Request.hxx"
#include "http/Headers.hxx"
#include "HttpResponseHandler.hxx"
#include "translation/Service.hxx"
#include "translation/Handler.hxx"
#include "ResourceLoader.hxx"
#include "istream/istream.hxx"
#include "istream/UnusedHoldPtr.hxx"
#include "pool/pool.hxx"
#include "io/Logger.hxx"
struct ErrorResponseLoader final : HttpResponseHandler, Cancellable {
CancellablePointer cancel_ptr;
Request &request;
http_status_t status;
HttpHeaders headers;
UnusedHoldIstreamPtr body;
TranslateRequest translate_request;
ErrorResponseLoader(Request &_request, http_status_t _status,
HttpHeaders &&_headers, UnusedIstreamPtr _body)
:request(_request), status(_status),
headers(std::move(_headers)),
body(_request.pool, std::move(_body)) {}
void Destroy() {
this->~ErrorResponseLoader();
}
/* virtual methods from class Cancellable */
void Cancel() noexcept override;
/* virtual methods from class HttpResponseHandler */
void OnHttpResponse(http_status_t status, StringMap &&headers,
UnusedIstreamPtr body) noexcept override;
void OnHttpError(std::exception_ptr ep) noexcept override;
};
static void
errdoc_resubmit(ErrorResponseLoader &er)
{
er.request.DispatchResponse(er.status, std::move(er.headers),
std::move(er.body));
}
/*
* HTTP response handler
*
*/
void
ErrorResponseLoader::OnHttpResponse(http_status_t _status, StringMap &&_headers,
UnusedIstreamPtr _body) noexcept
{
if (http_status_is_success(_status)) {
/* close the original (error) response body */
body.Clear();
request.InvokeResponse(status, std::move(_headers), std::move(_body));
} else {
/* close the original (error) response body */
_body.Clear();
errdoc_resubmit(*this);
}
Destroy();
}
void
ErrorResponseLoader::OnHttpError(std::exception_ptr ep) noexcept
{
LogConcat(2, request.request.uri, "error on error document: ", ep);
errdoc_resubmit(*this);
Destroy();
}
/*
* translate handler
*
*/
static void
errdoc_translate_response(TranslateResponse &response, void *ctx)
{
auto &er = *(ErrorResponseLoader *)ctx;
if ((response.status == (http_status_t)0 ||
http_status_is_success(response.status)) &&
response.address.IsDefined()) {
auto &request = er.request;
request.instance.cached_resource_loader
->SendRequest(request.pool, 0, nullptr, nullptr,
HTTP_METHOD_GET,
response.address, HTTP_STATUS_OK,
StringMap(request.pool), nullptr, nullptr,
er, request.cancel_ptr);
} else {
errdoc_resubmit(er);
er.Destroy();
}
}
static void
errdoc_translate_error(std::exception_ptr ep, void *ctx)
{
auto &er = *(ErrorResponseLoader *)ctx;
LogConcat(2, er.request.request.uri,
"error document translation error: ", ep);
errdoc_resubmit(er);
er.Destroy();
}
static constexpr TranslateHandler errdoc_translate_handler = {
.response = errdoc_translate_response,
.error = errdoc_translate_error,
};
static void
fill_translate_request(TranslateRequest *t,
const TranslateRequest *src,
ConstBuffer<void> error_document,
http_status_t status)
{
*t = *src;
t->error_document = error_document;
t->error_document_status = status;
}
/*
* async operation
*
*/
void
ErrorResponseLoader::Cancel() noexcept
{
CancellablePointer c(std::move(cancel_ptr));
Destroy();
c.Cancel();
}
/*
* constructor
*
*/
void
errdoc_dispatch_response(Request &request2, http_status_t status,
ConstBuffer<void> error_document,
HttpHeaders &&headers, UnusedIstreamPtr body)
{
assert(!error_document.IsNull());
auto &instance = request2.instance;
assert(instance.translation_service != nullptr);
auto *er = NewFromPool<ErrorResponseLoader>(request2.pool, request2,
status, std::move(headers),
std::move(body));
request2.cancel_ptr = *er;
fill_translate_request(&er->translate_request,
&request2.translate.request,
error_document, status);
instance.translation_service->SendRequest(request2.pool,
er->translate_request,
errdoc_translate_handler, er,
er->cancel_ptr);
}
<|endoftext|> |
<commit_before>#include "btree/rget.hpp"
#include "errors.hpp"
#include <boost/bind.hpp>
#include <boost/make_shared.hpp>
#include "btree/btree_data_provider.hpp"
#include "btree/iteration.hpp"
#include "containers/iterators.hpp"
#include "arch/coroutines.hpp"
/*
* Possible rget designs:
* 1. Depth-first search through the B-tree, then iterating through leaves (and maintaining a stack
* with some data to be able to backtrack).
* 2. Breadth-first search, by maintaining a queue of blocks and releasing the lock on the block
* when we extracted the IDs of its children.
* 3. Hybrid of 1 and 2: maintain a deque and use it as a queue, like in 2, thus releasing the locks
* for the top of the B-tree quickly, however when the deque reaches some size, start using it as
* a stack in depth-first search (but not quite in a usual way; see the note below).
*
* Problems of 1: we have to lock the whole path from the root down to the current node, which works
* fine with small rgets (when max_results is low), but causes unnecessary amounts of locking (and
* probably copy-on-writes, once we implement them).
*
* Problem of 2: while it doesn't hold unnecessary locks to the top (close to root) levels of the
* B-tree, it may try to lock too much at once if the rget query effectively spans too many blocks
* (e.g. when we try to rget the whole database).
*
* Hybrid approach seems to be the best choice here, because we hold the locks as low (far from the
* root) in the tree as possible, while minimizing their number by doing a depth-first search from
* some level.
*
* Note (on hybrid implementation):
* If the deque approach is used, it is important to note that all the nodes in the current level
* are in a reversed order when we decide to switch to popping from the stack:
*
* P Lets assume that we have node P in our deque, P is locked: [P]
* / \ We remove P from the deque, lock its children, and push them back to the deque: [A, B]
* A B Now we can release the P lock.
* /|\ /.\ Next, we remove A, lock its children, and push them back to the deque: [B, c, d, e]
* c d e ..... We release the A lock.
* ..... ......
* At this point we decide that we need to do a depth-first search (to limit the number
* of locked nodes), and start to use deque as a stack. However since we want
* an inorder traversal, not the reversed inorder, we can't pop from the end of
* the deque, we need to pop node 'c' instead of 'e', then (once we're done
* with its depth-first search) do 'd', and then do 'e'.
*
* There are several possible approaches, one of them is putting markers in the deque in
* between the nodes of different B-tree levels, another (probably a better one) is maintaining a
* deque of deques, where the inner deques contain the nodes from the current B-tree level.
*
*
* Currently the DFS design is implemented, since it's the simplest solution, also it is a good
* fit for small rgets (the most popular use-case).
*
*
* Most of the implementation now resides in btree/iteration.{hpp,cc}.
* Actual merging of the slice iterators is done in server/key_value_store.cc.
*/
bool is_not_expired(key_value_pair_t& pair) {
const btree_value_t *value = reinterpret_cast<const btree_value_t *>(pair.value.get());
return !value->expired();
}
key_with_data_provider_t pair_to_key_with_data_provider(boost::shared_ptr<transaction_t>& txn, key_value_pair_t& pair) {
on_thread_t(txn->home_thread());
boost::shared_ptr<data_provider_t> data_provider(value_data_provider_t::create(reinterpret_cast<btree_value_t *>(pair.value.get()), txn.get()));
return key_with_data_provider_t(pair.key, reinterpret_cast<btree_value_t *>(pair.value.get())->mcflags(), data_provider);
}
rget_result_t btree_rget_slice(btree_slice_t *slice, rget_bound_mode_t left_mode, const store_key_t &left_key, rget_bound_mode_t right_mode, const store_key_t &right_key, order_token_t token) {
slice->pre_begin_transaction_sink_.check_out(token);
order_token_t begin_transaction_token = slice->pre_begin_transaction_read_mode_source_.check_in(token.tag() + "+begin_transaction_token").with_read_mode();
boost::shared_ptr<transaction_t> transaction = boost::shared_ptr<transaction_t>(new transaction_t(slice->cache(), rwi_read));
transaction->set_token(slice->post_begin_transaction_checkpoint_.check_through(token).with_read_mode());
boost::shared_ptr<value_sizer_t> sizer = boost::make_shared<memcached_value_sizer_t>(transaction->get_cache()->get_block_size());
transaction->snapshot();
return boost::shared_ptr<one_way_iterator_t<key_with_data_provider_t> >(
new transform_iterator_t<key_value_pair_t, key_with_data_provider_t>(
boost::bind(pair_to_key_with_data_provider, transaction, _1),
new filter_iterator_t<key_value_pair_t>(
is_not_expired,
new slice_keys_iterator_t(sizer, transaction, slice, left_mode, left_key, right_mode, right_key))));
}
<commit_msg>Fixed on_thread_t error with rget.<commit_after>#include "btree/rget.hpp"
#include "errors.hpp"
#include <boost/bind.hpp>
#include <boost/make_shared.hpp>
#include "btree/btree_data_provider.hpp"
#include "btree/iteration.hpp"
#include "containers/iterators.hpp"
#include "arch/coroutines.hpp"
/*
* Possible rget designs:
* 1. Depth-first search through the B-tree, then iterating through leaves (and maintaining a stack
* with some data to be able to backtrack).
* 2. Breadth-first search, by maintaining a queue of blocks and releasing the lock on the block
* when we extracted the IDs of its children.
* 3. Hybrid of 1 and 2: maintain a deque and use it as a queue, like in 2, thus releasing the locks
* for the top of the B-tree quickly, however when the deque reaches some size, start using it as
* a stack in depth-first search (but not quite in a usual way; see the note below).
*
* Problems of 1: we have to lock the whole path from the root down to the current node, which works
* fine with small rgets (when max_results is low), but causes unnecessary amounts of locking (and
* probably copy-on-writes, once we implement them).
*
* Problem of 2: while it doesn't hold unnecessary locks to the top (close to root) levels of the
* B-tree, it may try to lock too much at once if the rget query effectively spans too many blocks
* (e.g. when we try to rget the whole database).
*
* Hybrid approach seems to be the best choice here, because we hold the locks as low (far from the
* root) in the tree as possible, while minimizing their number by doing a depth-first search from
* some level.
*
* Note (on hybrid implementation):
* If the deque approach is used, it is important to note that all the nodes in the current level
* are in a reversed order when we decide to switch to popping from the stack:
*
* P Lets assume that we have node P in our deque, P is locked: [P]
* / \ We remove P from the deque, lock its children, and push them back to the deque: [A, B]
* A B Now we can release the P lock.
* /|\ /.\ Next, we remove A, lock its children, and push them back to the deque: [B, c, d, e]
* c d e ..... We release the A lock.
* ..... ......
* At this point we decide that we need to do a depth-first search (to limit the number
* of locked nodes), and start to use deque as a stack. However since we want
* an inorder traversal, not the reversed inorder, we can't pop from the end of
* the deque, we need to pop node 'c' instead of 'e', then (once we're done
* with its depth-first search) do 'd', and then do 'e'.
*
* There are several possible approaches, one of them is putting markers in the deque in
* between the nodes of different B-tree levels, another (probably a better one) is maintaining a
* deque of deques, where the inner deques contain the nodes from the current B-tree level.
*
*
* Currently the DFS design is implemented, since it's the simplest solution, also it is a good
* fit for small rgets (the most popular use-case).
*
*
* Most of the implementation now resides in btree/iteration.{hpp,cc}.
* Actual merging of the slice iterators is done in server/key_value_store.cc.
*/
bool is_not_expired(key_value_pair_t& pair) {
const btree_value_t *value = reinterpret_cast<const btree_value_t *>(pair.value.get());
return !value->expired();
}
key_with_data_provider_t pair_to_key_with_data_provider(boost::shared_ptr<transaction_t>& txn, key_value_pair_t& pair) {
on_thread_t th(txn->home_thread());
boost::shared_ptr<data_provider_t> data_provider(value_data_provider_t::create(reinterpret_cast<btree_value_t *>(pair.value.get()), txn.get()));
return key_with_data_provider_t(pair.key, reinterpret_cast<btree_value_t *>(pair.value.get())->mcflags(), data_provider);
}
rget_result_t btree_rget_slice(btree_slice_t *slice, rget_bound_mode_t left_mode, const store_key_t &left_key, rget_bound_mode_t right_mode, const store_key_t &right_key, order_token_t token) {
slice->pre_begin_transaction_sink_.check_out(token);
order_token_t begin_transaction_token = slice->pre_begin_transaction_read_mode_source_.check_in(token.tag() + "+begin_transaction_token").with_read_mode();
boost::shared_ptr<transaction_t> transaction = boost::shared_ptr<transaction_t>(new transaction_t(slice->cache(), rwi_read));
transaction->set_token(slice->post_begin_transaction_checkpoint_.check_through(token).with_read_mode());
boost::shared_ptr<value_sizer_t> sizer = boost::make_shared<memcached_value_sizer_t>(transaction->get_cache()->get_block_size());
transaction->snapshot();
return boost::shared_ptr<one_way_iterator_t<key_with_data_provider_t> >(
new transform_iterator_t<key_value_pair_t, key_with_data_provider_t>(
boost::bind(pair_to_key_with_data_provider, transaction, _1),
new filter_iterator_t<key_value_pair_t>(
is_not_expired,
new slice_keys_iterator_t(sizer, transaction, slice, left_mode, left_key, right_mode, right_key))));
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/optional.hpp>
#include "cccallcc.hpp"
int f(cont<int> k) {
k(1);
return 0;
}
boost::optional< cont<int> > global_k;
int g(cont<int> k) {
global_k = k;
return 0;
}
int main() {
std::cout << "f => " << call_cc<int>(f) << std::endl;
std::cout << "g => " << call_cc<int>(g) << std::endl;
if (global_k)
(*global_k)(1);
}
<commit_msg>change simple.cpp output<commit_after>#include <iostream>
#include <boost/optional.hpp>
#include "cccallcc.hpp"
int f(cont<int> k) {
std::cout << "f called" << std::endl;
k(1);
return 0;
}
boost::optional< cont<int> > global_k;
int g(cont<int> k) {
std::cout << "g called" << std::endl;
global_k = k;
return 0;
}
int main() {
std::cout << "f returns " << call_cc<int>(f) << std::endl;
std::cout << "g returns " << call_cc<int>(g) << std::endl;
if (global_k)
(*global_k)(1);
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
*******************************************************************************/
//==============================================================================
// Single cell view simulation worker
//==============================================================================
#include "cellmlfileruntime.h"
#include "cliutils.h"
#include "coredaesolver.h"
#include "corenlasolver.h"
#include "coreodesolver.h"
#include "singlecellviewsimulation.h"
#include "singlecellviewsimulationworker.h"
//==============================================================================
#include <QElapsedTimer>
#include <QMutex>
#include <QThread>
//==============================================================================
namespace OpenCOR {
namespace SingleCellView {
//==============================================================================
SingleCellViewSimulationWorker::SingleCellViewSimulationWorker(const SolverInterfaces &pSolverInterfaces,
CellMLSupport::CellmlFileRuntime *pRuntime,
SingleCellViewSimulation *pSimulation,
SingleCellViewSimulationWorker **pSelf) :
mSolverInterfaces(pSolverInterfaces),
mRuntime(pRuntime),
mSimulation(pSimulation),
mCurrentPoint(0.0),
mProgress(0.0),
mPaused(false),
mStopped(false),
mReset(false),
mError(false),
mSelf(pSelf)
{
// Create our thread
mThread = new QThread();
// Move ourselves to our thread
moveToThread(mThread);
// Create a few connections
connect(mThread, SIGNAL(started()),
this, SLOT(started()));
connect(this, SIGNAL(finished(const int &)),
mThread, SLOT(quit()));
connect(mThread, SIGNAL(finished()),
mThread, SLOT(deleteLater()));
connect(mThread, SIGNAL(finished()),
this, SLOT(deleteLater()));
}
//==============================================================================
bool SingleCellViewSimulationWorker::isRunning() const
{
// Return whether our thread is running
return mThread?
mThread->isRunning() && !mPaused:
false;
}
//==============================================================================
bool SingleCellViewSimulationWorker::isPaused() const
{
// Return whether our thread is paused
return mThread?
mThread->isRunning() && mPaused:
false;
}
//==============================================================================
double SingleCellViewSimulationWorker::currentPoint() const
{
// Return our progress
return mThread?
mThread->isRunning()?mCurrentPoint:mSimulation->data()->startingPoint():
mSimulation->data()->startingPoint();
}
//==============================================================================
double SingleCellViewSimulationWorker::progress() const
{
// Return our progress
return mThread?
mThread->isRunning()?mProgress:0.0:
0.0;
}
//==============================================================================
bool SingleCellViewSimulationWorker::run()
{
// Start our thread
if (mThread) {
mThread->start();
return true;
} else {
return false;
}
}
//==============================================================================
void SingleCellViewSimulationWorker::started()
{
// Let people know that we are running
emit running(false);
// Reset our progress
mProgress = 0.0;
// Set up our ODE/DAE solver
CoreSolver::CoreVoiSolver *voiSolver = 0;
CoreSolver::CoreOdeSolver *odeSolver = 0;
CoreSolver::CoreDaeSolver *daeSolver = 0;
if (mRuntime->needOdeSolver()) {
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare(mSimulation->data()->odeSolverName())) {
// The requested ODE solver was found, so retrieve an instance
// of it
voiSolver = odeSolver = static_cast<CoreSolver::CoreOdeSolver *>(solverInterface->instance());
break;
}
} else {
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare("IDA")) {
// The requested DAE solver was found, so retrieve an instance
// of it
voiSolver = daeSolver = static_cast<CoreSolver::CoreDaeSolver *>(solverInterface->instance());
break;
}
}
// Make sure that we have found our ODE/DAE solver
// Note #1: this should never happen, but we never know, so...
// Note #2: see the end of this method about we do before returning...
if (!voiSolver) {
if (mRuntime->needOdeSolver())
emitError(tr("the ODE solver could not be found"));
else
emitError(tr("the DAE solver could not be found"));
*mSelf = 0;
emit finished(-1);
return;
}
// Set up our NLA solver, if needed
CoreSolver::CoreNlaSolver *nlaSolver = 0;
if (mRuntime->needNlaSolver()) {
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare(mSimulation->data()->nlaSolverName())) {
// The requested NLA solver was found, so retrieve an instance
// of it
nlaSolver = static_cast<CoreSolver::CoreNlaSolver *>(solverInterface->instance());
// Keep track of our NLA solver, so that doNonLinearSolve() can
// work as expected
CoreSolver::setNlaSolver(mRuntime->address(), nlaSolver);
break;
}
// Make sure that we have found our NLA solver
// Note #1: this should never happen, but we never know, so...
// Note #2: see the end of this method about we do before returning...
if (!nlaSolver) {
emitError(tr("the NLA solver could not be found"));
delete voiSolver;
*mSelf = 0;
emit finished(-1);
return;
}
}
// Keep track of any error that might be reported by any of our solvers
mStopped = false;
mError = false;
if (odeSolver)
connect(odeSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
else
connect(daeSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
if (nlaSolver)
connect(nlaSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
// Retrieve our simulation properties
double startingPoint = mSimulation->data()->startingPoint();
double endingPoint = mSimulation->data()->endingPoint();
double pointInterval = mSimulation->data()->pointInterval();
bool increasingPoints = endingPoint > startingPoint;
const double oneOverPointsRange = 1.0/(endingPoint-startingPoint);
int pointCounter = 0;
mCurrentPoint = startingPoint;
// Initialise our ODE/DAE solver
if (odeSolver) {
odeSolver->setProperties(mSimulation->data()->odeSolverProperties());
odeSolver->initialize(mCurrentPoint,
mRuntime->statesCount(),
mSimulation->data()->constants(),
mSimulation->data()->rates(),
mSimulation->data()->states(),
mSimulation->data()->algebraic(),
mRuntime->computeOdeRates());
} else {
daeSolver->setProperties(mSimulation->data()->daeSolverProperties());
daeSolver->initialize(mCurrentPoint, endingPoint,
mRuntime->statesCount(),
mRuntime->condVarCount(),
mSimulation->data()->constants(),
mSimulation->data()->rates(),
mSimulation->data()->states(),
mSimulation->data()->algebraic(),
mSimulation->data()->condVar(),
mRuntime->computeDaeEssentialVariables(),
mRuntime->computeDaeResiduals(),
mRuntime->computeDaeRootInformation(),
mRuntime->computeDaeStateInformation());
}
// Initialise our NLA solver
if (nlaSolver)
nlaSolver->setProperties(mSimulation->data()->nlaSolverProperties());
// Now, we are ready to compute our model, but only if no error has occurred
// so far
int elapsedTime;
if (!mError) {
// Start our timer
QElapsedTimer timer;
elapsedTime = 0;
timer.start();
// Add our first point after making sure that all the variables have
// been computed
mSimulation->data()->recomputeVariables(mCurrentPoint);
mSimulation->results()->addPoint(mCurrentPoint);
// Our main work loop
// Note: for performance reasons, it is essential that the following
// loop doesn't emit any signal, be it directly or indirectly,
// unless it is to let people know that we are pausing or running.
// Indeed, the signal/slot mechanism adds a certain level of
// overhead and, here, we want things to be as fast as possible,
// so...
QMutex pausedMutex;
while ((mCurrentPoint != endingPoint) && !mStopped) {
// Determine our next point and compute our model up to it
++pointCounter;
voiSolver->solve(mCurrentPoint,
increasingPoints?
qMin(endingPoint, startingPoint+pointCounter*pointInterval):
qMax(endingPoint, startingPoint+pointCounter*pointInterval));
// Make sure that no error occurred
if (mError)
break;
// Update our progress
mProgress = (mCurrentPoint-startingPoint)*oneOverPointsRange;
// Add our new point after making sure that all the variables have
// been computed
mSimulation->data()->recomputeVariables(mCurrentPoint);
mSimulation->results()->addPoint(mCurrentPoint);
// Delay things a bit, if (really) needed
if (mSimulation->delay() && !mStopped)
Core::doNothing(100*mSimulation->delay());
// Pause ourselves, if (really) needed
if (mPaused && !mStopped) {
// We should be paused, so stop our timer
elapsedTime += timer.elapsed();
// Let people know that we are paused
emit paused();
// Actually pause ourselves
pausedMutex.lock();
mPausedCondition.wait(&pausedMutex);
pausedMutex.unlock();
// We are not paused anymore
mPaused = false;
// Let people know that we are running again
emit running(true);
// Restart our timer
timer.restart();
}
// Reinitialise our solver, if (really) needed
if (mReset && !mStopped) {
if (odeSolver)
odeSolver->initialize(mCurrentPoint,
mRuntime->statesCount(),
mSimulation->data()->constants(),
mSimulation->data()->rates(),
mSimulation->data()->states(),
mSimulation->data()->algebraic(),
mRuntime->computeOdeRates());
else
daeSolver->initialize(mCurrentPoint, endingPoint,
mRuntime->statesCount(),
mRuntime->condVarCount(),
mSimulation->data()->constants(),
mSimulation->data()->rates(),
mSimulation->data()->states(),
mSimulation->data()->algebraic(),
mSimulation->data()->condVar(),
mRuntime->computeDaeEssentialVariables(),
mRuntime->computeDaeResiduals(),
mRuntime->computeDaeRootInformation(),
mRuntime->computeDaeStateInformation());
mReset = false;
}
}
// Retrieve the total elapsed time, should no error have occurred
if (mError)
// An error occurred, so...
elapsedTime = -1;
// Note: we use -1 as a way to indicate that something went wrong...
else
elapsedTime += timer.elapsed();
} else {
// An error occurred, so...
elapsedTime = -1;
// Note: we use -1 as a way to indicate that something went wrong...
}
// Delete our solver(s)
delete voiSolver;
if (nlaSolver) {
delete nlaSolver;
CoreSolver::unsetNlaSolver(mRuntime->address());
}
// Reset our simulation owner's knowledge of us
// Note: if we were to do it the Qt way, our simulation owner would have a
// slot for our finished() signal, but we want it to know as quickly
// as possible that we are done, so...
*mSelf = 0;
// Let people know that we are done and give them the elapsed time
emit finished(elapsedTime);
}
//==============================================================================
bool SingleCellViewSimulationWorker::pause()
{
// Pause ourselves, but only if we are currently running
if (isRunning()) {
// Ask ourselves to pause
mPaused = true;
return true;
} else {
return false;
}
}
//==============================================================================
bool SingleCellViewSimulationWorker::resume()
{
// Resume ourselves, but only if are currently paused
if (isPaused()) {
// Ask ourselves to resume
mPausedCondition.wakeOne();
return true;
} else {
return false;
}
}
//==============================================================================
bool SingleCellViewSimulationWorker::stop()
{
// Check that we are either running or paused
if (isRunning() || isPaused()) {
// Ask ourselves to stop
mStopped = true;
// Resume ourselves, if needed
if (isPaused())
mPausedCondition.wakeOne();
// Ask our thread to quit and wait for it to do so
mThread->quit();
mThread->wait();
mThread = 0;
// Note: this is in case we want, for example, to retrieve our
// progress...
return true;
} else {
return false;
}
}
//==============================================================================
bool SingleCellViewSimulationWorker::reset()
{
// Check that we are either running or paused
if (isRunning() || isPaused()) {
// Ask ourselves to reinitialise our solver
mReset = true;
return true;
} else {
return false;
}
}
//==============================================================================
void SingleCellViewSimulationWorker::emitError(const QString &pMessage)
{
// A solver error occurred, so keep track of it and let people know about it
mError = true;
emit error(pMessage);
}
//==============================================================================
} // namespace SingleCellView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up [ci skip].<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
*******************************************************************************/
//==============================================================================
// Single cell view simulation worker
//==============================================================================
#include "cellmlfileruntime.h"
#include "cliutils.h"
#include "coredaesolver.h"
#include "corenlasolver.h"
#include "coreodesolver.h"
#include "singlecellviewsimulation.h"
#include "singlecellviewsimulationworker.h"
//==============================================================================
#include <QElapsedTimer>
#include <QMutex>
#include <QThread>
//==============================================================================
namespace OpenCOR {
namespace SingleCellView {
//==============================================================================
SingleCellViewSimulationWorker::SingleCellViewSimulationWorker(const SolverInterfaces &pSolverInterfaces,
CellMLSupport::CellmlFileRuntime *pRuntime,
SingleCellViewSimulation *pSimulation,
SingleCellViewSimulationWorker **pSelf) :
mSolverInterfaces(pSolverInterfaces),
mRuntime(pRuntime),
mSimulation(pSimulation),
mCurrentPoint(0.0),
mProgress(0.0),
mPaused(false),
mStopped(false),
mReset(false),
mError(false),
mSelf(pSelf)
{
// Create our thread
mThread = new QThread();
// Move ourselves to our thread
moveToThread(mThread);
// Create a few connections
connect(mThread, SIGNAL(started()),
this, SLOT(started()));
connect(this, SIGNAL(finished(const int &)),
mThread, SLOT(quit()));
connect(mThread, SIGNAL(finished()),
mThread, SLOT(deleteLater()));
connect(mThread, SIGNAL(finished()),
this, SLOT(deleteLater()));
}
//==============================================================================
bool SingleCellViewSimulationWorker::isRunning() const
{
// Return whether our thread is running
return mThread?
mThread->isRunning() && !mPaused:
false;
}
//==============================================================================
bool SingleCellViewSimulationWorker::isPaused() const
{
// Return whether our thread is paused
return mThread?
mThread->isRunning() && mPaused:
false;
}
//==============================================================================
double SingleCellViewSimulationWorker::currentPoint() const
{
// Return our progress
return mThread?
mThread->isRunning()?mCurrentPoint:mSimulation->data()->startingPoint():
mSimulation->data()->startingPoint();
}
//==============================================================================
double SingleCellViewSimulationWorker::progress() const
{
// Return our progress
return mThread?
mThread->isRunning()?mProgress:0.0:
0.0;
}
//==============================================================================
bool SingleCellViewSimulationWorker::run()
{
// Start our thread
if (mThread) {
mThread->start();
return true;
} else {
return false;
}
}
//==============================================================================
void SingleCellViewSimulationWorker::started()
{
// Let people know that we are running
emit running(false);
// Reset our progress
mProgress = 0.0;
// Set up our ODE/DAE solver
CoreSolver::CoreVoiSolver *voiSolver = 0;
CoreSolver::CoreOdeSolver *odeSolver = 0;
CoreSolver::CoreDaeSolver *daeSolver = 0;
if (mRuntime->needOdeSolver()) {
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare(mSimulation->data()->odeSolverName())) {
// The requested ODE solver was found, so retrieve an instance
// of it
voiSolver = odeSolver = static_cast<CoreSolver::CoreOdeSolver *>(solverInterface->instance());
break;
}
} else {
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare("IDA")) {
// The requested DAE solver was found, so retrieve an instance
// of it
voiSolver = daeSolver = static_cast<CoreSolver::CoreDaeSolver *>(solverInterface->instance());
break;
}
}
// Make sure that we have found our ODE/DAE solver
// Note #1: this should never happen, but we never know, so...
// Note #2: see the end of this method about we do before returning...
if (!voiSolver) {
if (mRuntime->needOdeSolver())
emitError(tr("the ODE solver could not be found"));
else
emitError(tr("the DAE solver could not be found"));
*mSelf = 0;
emit finished(-1);
return;
}
// Set up our NLA solver, if needed
CoreSolver::CoreNlaSolver *nlaSolver = 0;
if (mRuntime->needNlaSolver()) {
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare(mSimulation->data()->nlaSolverName())) {
// The requested NLA solver was found, so retrieve an instance
// of it
nlaSolver = static_cast<CoreSolver::CoreNlaSolver *>(solverInterface->instance());
// Keep track of our NLA solver, so that doNonLinearSolve() can
// work as expected
CoreSolver::setNlaSolver(mRuntime->address(), nlaSolver);
break;
}
// Make sure that we have found our NLA solver
// Note #1: this should never happen, but we never know, so...
// Note #2: see the end of this method about we do before returning...
if (!nlaSolver) {
emitError(tr("the NLA solver could not be found"));
delete voiSolver;
*mSelf = 0;
emit finished(-1);
return;
}
}
// Keep track of any error that might be reported by any of our solvers
mStopped = false;
mError = false;
if (odeSolver)
connect(odeSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
else
connect(daeSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
if (nlaSolver)
connect(nlaSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
// Retrieve our simulation properties
double startingPoint = mSimulation->data()->startingPoint();
double endingPoint = mSimulation->data()->endingPoint();
double pointInterval = mSimulation->data()->pointInterval();
bool increasingPoints = endingPoint > startingPoint;
const double oneOverPointsRange = 1.0/(endingPoint-startingPoint);
int pointCounter = 0;
mCurrentPoint = startingPoint;
// Initialise our ODE/DAE solver
if (odeSolver) {
odeSolver->setProperties(mSimulation->data()->odeSolverProperties());
odeSolver->initialize(mCurrentPoint,
mRuntime->statesCount(),
mSimulation->data()->constants(),
mSimulation->data()->rates(),
mSimulation->data()->states(),
mSimulation->data()->algebraic(),
mRuntime->computeOdeRates());
} else {
daeSolver->setProperties(mSimulation->data()->daeSolverProperties());
daeSolver->initialize(mCurrentPoint, endingPoint,
mRuntime->statesCount(),
mRuntime->condVarCount(),
mSimulation->data()->constants(),
mSimulation->data()->rates(),
mSimulation->data()->states(),
mSimulation->data()->algebraic(),
mSimulation->data()->condVar(),
mRuntime->computeDaeEssentialVariables(),
mRuntime->computeDaeResiduals(),
mRuntime->computeDaeRootInformation(),
mRuntime->computeDaeStateInformation());
}
// Initialise our NLA solver
if (nlaSolver)
nlaSolver->setProperties(mSimulation->data()->nlaSolverProperties());
// Now, we are ready to compute our model, but only if no error has occurred
// so far
int elapsedTime;
if (!mError) {
// Start our timer
QElapsedTimer timer;
elapsedTime = 0;
timer.start();
// Add our first point after making sure that all the variables have
// been computed
mSimulation->data()->recomputeVariables(mCurrentPoint);
mSimulation->results()->addPoint(mCurrentPoint);
// Our main work loop
// Note: for performance reasons, it is essential that the following
// loop doesn't emit any signal, be it directly or indirectly,
// unless it is to let people know that we are pausing or running.
// Indeed, the signal/slot mechanism adds a certain level of
// overhead and, here, we want things to be as fast as possible,
// so...
QMutex pausedMutex;
while ((mCurrentPoint != endingPoint) && !mStopped) {
// Determine our next point and compute our model up to it
++pointCounter;
voiSolver->solve(mCurrentPoint,
increasingPoints?
qMin(endingPoint, startingPoint+pointCounter*pointInterval):
qMax(endingPoint, startingPoint+pointCounter*pointInterval));
// Make sure that no error occurred
if (mError)
break;
// Update our progress
mProgress = (mCurrentPoint-startingPoint)*oneOverPointsRange;
// Add our new point after making sure that all the variables have
// been computed
mSimulation->data()->recomputeVariables(mCurrentPoint);
mSimulation->results()->addPoint(mCurrentPoint);
// Delay things a bit, if (really) needed
if (mSimulation->delay() && !mStopped)
Core::doNothing(100*mSimulation->delay());
// Pause ourselves, if (really) needed
if (mPaused && !mStopped) {
// We should be paused, so stop our timer
elapsedTime += timer.elapsed();
// Let people know that we are paused
emit paused();
// Actually pause ourselves
pausedMutex.lock();
mPausedCondition.wait(&pausedMutex);
pausedMutex.unlock();
// We are not paused anymore
mPaused = false;
// Let people know that we are running again
emit running(true);
// Restart our timer
timer.restart();
}
// Reinitialise our solver, if (really) needed
if (mReset && !mStopped) {
if (odeSolver)
odeSolver->initialize(mCurrentPoint,
mRuntime->statesCount(),
mSimulation->data()->constants(),
mSimulation->data()->rates(),
mSimulation->data()->states(),
mSimulation->data()->algebraic(),
mRuntime->computeOdeRates());
else
daeSolver->initialize(mCurrentPoint, endingPoint,
mRuntime->statesCount(),
mRuntime->condVarCount(),
mSimulation->data()->constants(),
mSimulation->data()->rates(),
mSimulation->data()->states(),
mSimulation->data()->algebraic(),
mSimulation->data()->condVar(),
mRuntime->computeDaeEssentialVariables(),
mRuntime->computeDaeResiduals(),
mRuntime->computeDaeRootInformation(),
mRuntime->computeDaeStateInformation());
mReset = false;
}
}
// Retrieve the total elapsed time, should no error have occurred
if (mError)
// An error occurred, so...
elapsedTime = -1;
// Note: we use -1 as a way to indicate that something went wrong...
else
elapsedTime += timer.elapsed();
} else {
// An error occurred, so...
elapsedTime = -1;
// Note: we use -1 as a way to indicate that something went wrong...
}
// Delete our solver(s)
delete voiSolver;
if (nlaSolver) {
delete nlaSolver;
CoreSolver::unsetNlaSolver(mRuntime->address());
}
// Reset our simulation owner's knowledge of us
// Note: if we were to do it the Qt way, our simulation owner would have a
// slot for our finished() signal, but we want it to know as quickly
// as possible that we are done, so...
*mSelf = 0;
// Let people know that we are done and give them the elapsed time
emit finished(elapsedTime);
}
//==============================================================================
bool SingleCellViewSimulationWorker::pause()
{
// Pause ourselves, but only if we are currently running
if (isRunning()) {
// Ask ourselves to pause
mPaused = true;
return true;
} else {
return false;
}
}
//==============================================================================
bool SingleCellViewSimulationWorker::resume()
{
// Resume ourselves, but only if are currently paused
if (isPaused()) {
// Ask ourselves to resume
mPausedCondition.wakeOne();
return true;
} else {
return false;
}
}
//==============================================================================
bool SingleCellViewSimulationWorker::stop()
{
// Check that we are either running or paused
if (isRunning() || isPaused()) {
// Ask our thread to stop
mStopped = true;
// Resume our thread, if needed
if (isPaused())
mPausedCondition.wakeOne();
// Ask our thread to quit and wait for it to do so
mThread->quit();
mThread->wait();
mThread = 0;
// Note: this is in case we want, for example, to retrieve our
// progress...
return true;
} else {
return false;
}
}
//==============================================================================
bool SingleCellViewSimulationWorker::reset()
{
// Check that we are either running or paused
if (isRunning() || isPaused()) {
// Ask ourselves to reinitialise our solver
mReset = true;
return true;
} else {
return false;
}
}
//==============================================================================
void SingleCellViewSimulationWorker::emitError(const QString &pMessage)
{
// A solver error occurred, so keep track of it and let people know about it
mError = true;
emit error(pMessage);
}
//==============================================================================
} // namespace SingleCellView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) Ian Rees ([email protected]) 2015 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#include <Base/Exception.h>
#include "Enumeration.h"
#include <cassert>
using namespace App;
Enumeration::Enumeration()
: _EnumArray(NULL), _ownEnumArray(false), _index(0), _maxVal(-1)
{
}
Enumeration::Enumeration(const Enumeration &other)
{
if (other._ownEnumArray) {
setEnums(other.getEnumVector());
} else {
_EnumArray = other._EnumArray;
}
_ownEnumArray = other._ownEnumArray;
_index = other._index;
_maxVal = other._maxVal;
}
Enumeration::Enumeration(const char *valStr)
: _ownEnumArray(true), _index(0), _maxVal(0)
{
_EnumArray = new const char*[2];
#if defined (_MSC_VER)
_EnumArray[0] = _strdup(valStr);
#else
_EnumArray[0] = strdup(valStr);
#endif
_EnumArray[1] = NULL;
}
Enumeration::Enumeration(const char **list, const char *valStr)
: _EnumArray(list), _ownEnumArray(false)
{
findMaxVal();
setValue(valStr);
}
Enumeration::~Enumeration()
{
if (_ownEnumArray) {
if (_EnumArray != NULL) {
tearDown();
}
}
}
void Enumeration::tearDown(void)
{
// Ugly...
char **plEnums = (char **)_EnumArray;
// Delete C Strings first
while (*(plEnums++) != NULL) {
free(*plEnums);
}
delete [] _EnumArray;
_EnumArray = NULL;
_ownEnumArray = false;
_maxVal = -1;
}
void Enumeration::setEnums(const char **plEnums)
{
std::string oldValue;
bool preserve = (isValid() && plEnums != NULL);
if (preserve) {
oldValue = getCStr();
}
// set _ownEnumArray
if (isValid() && _ownEnumArray) {
tearDown();
}
// set...
_EnumArray = plEnums;
// set _maxVal
findMaxVal();
// set _index
_index = 0;
if (preserve) {
setValue(oldValue);
}
}
void Enumeration::setEnums(const std::vector<std::string> &values)
{
std::string oldValue;
bool preserve = isValid();
if (preserve) {
oldValue = getCStr();
}
if (isValid() && _ownEnumArray) {
tearDown();
}
_EnumArray = new const char*[values.size() + 1];
int i = 0;
for (std::vector<std::string>::const_iterator it = values.begin(); it != values.end(); ++it) {
#if defined (_MSC_VER)
_EnumArray[i++] = _strdup(it->c_str());
#else
_EnumArray[i++] = strdup(it->c_str());
#endif
}
_EnumArray[i] = 0; // null termination
// Other state variables
_maxVal = values.size() - 1;
_ownEnumArray = true;
_index = 0;
if (preserve) {
setValue(oldValue);
}
}
void Enumeration::setValue(const char *value)
{
// using string methods without set, use setEnums(const char** plEnums) first!
assert(_EnumArray);
if (!_EnumArray) {
_index = 0;
return;
}
unsigned int i = 0;
const char **plEnums = _EnumArray;
// search for the right entry
while (1) {
// end of list? set zero
if (*plEnums == NULL) {
_index = 0;
break;
}
if (strcmp(*plEnums, value) == 0) {
_index = i;
break;
}
++plEnums;
++i;
}
}
void Enumeration::setValue(long value, bool checkRange)
{
if (value >= 0 && value <= _maxVal) {
_index = value;
} else {
if (checkRange) {
throw Base::ValueError("Out of range");
} else {
_index = value;
}
}
}
bool Enumeration::isValue(const char *value) const
{
// using string methods without set, use setEnums(const char** plEnums) first!
assert(_EnumArray);
int i = getInt();
if (i == -1) {
return false;
} else {
return strcmp(_EnumArray[i], value) == 0;
}
}
bool Enumeration::contains(const char *value) const
{
// using string methods without set, use setEnums(const char** plEnums) first!
assert(_EnumArray);
if (!isValid()) {
return false;
}
const char **plEnums = _EnumArray;
// search for the right entry
while (1) {
// end of list?
if (*plEnums == NULL)
return false;
if (strcmp(*plEnums, value) == 0)
return true;
++plEnums;
}
}
const char * Enumeration::getCStr(void) const
{
// using string methods without set, use setEnums(const char** plEnums) first!
assert(_EnumArray);
if (!isValid() || _index < 0 || _index > _maxVal) {
return NULL;
}
return _EnumArray[_index];
}
int Enumeration::getInt(void) const
{
if (!isValid() || _index < 0 || _index > _maxVal) {
return -1;
}
return _index;
}
std::vector<std::string> Enumeration::getEnumVector(void) const
{
// using string methods without set, use setEnums(const char** plEnums) first!
assert(_EnumArray);
std::vector<std::string> result;
const char **plEnums = _EnumArray;
// end of list?
while (*plEnums != NULL) {
result.push_back(*plEnums);
++plEnums;
}
return result;
}
const char ** Enumeration::getEnums(void) const
{
return _EnumArray;
}
bool Enumeration::isValid(void) const
{
return (_EnumArray != NULL && _index >= 0 && _index <= _maxVal);
}
Enumeration & Enumeration::operator=(const Enumeration &other)
{
if (other._ownEnumArray) {
setEnums(other.getEnumVector());
} else {
_EnumArray = other._EnumArray;
}
_ownEnumArray = other._ownEnumArray;
_index = other._index;
_maxVal = other._maxVal;
return *this;
}
bool Enumeration::operator==(const Enumeration &other) const
{
if (getCStr() == NULL || other.getCStr() == NULL) {
return false;
}
return (strcmp(getCStr(), other.getCStr()) == 0);
}
bool Enumeration::operator==(const char *other) const
{
if (getCStr() == NULL) {
return false;
}
return (strcmp(getCStr(), other) == 0);
}
void Enumeration::findMaxVal(void)
{
if (_EnumArray == NULL) {
_maxVal = -1;
return;
}
const char **plEnums = _EnumArray;
long i = 0;
while (*(plEnums++) != NULL) {
++i;
// very unlikely to have enums with more then 5000 entries!
assert(i < 5000);
}
_maxVal = i;
}
<commit_msg>+ fix gcc build failure<commit_after>/***************************************************************************
* Copyright (c) Ian Rees ([email protected]) 2015 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <cassert>
# include <cstring>
# include <cstdlib>
#endif
#include <Base/Exception.h>
#include "Enumeration.h"
using namespace App;
Enumeration::Enumeration()
: _EnumArray(NULL), _ownEnumArray(false), _index(0), _maxVal(-1)
{
}
Enumeration::Enumeration(const Enumeration &other)
{
if (other._ownEnumArray) {
setEnums(other.getEnumVector());
} else {
_EnumArray = other._EnumArray;
}
_ownEnumArray = other._ownEnumArray;
_index = other._index;
_maxVal = other._maxVal;
}
Enumeration::Enumeration(const char *valStr)
: _ownEnumArray(true), _index(0), _maxVal(0)
{
_EnumArray = new const char*[2];
#if defined (_MSC_VER)
_EnumArray[0] = _strdup(valStr);
#else
_EnumArray[0] = strdup(valStr);
#endif
_EnumArray[1] = NULL;
}
Enumeration::Enumeration(const char **list, const char *valStr)
: _EnumArray(list), _ownEnumArray(false)
{
findMaxVal();
setValue(valStr);
}
Enumeration::~Enumeration()
{
if (_ownEnumArray) {
if (_EnumArray != NULL) {
tearDown();
}
}
}
void Enumeration::tearDown(void)
{
// Ugly...
char **plEnums = (char **)_EnumArray;
// Delete C Strings first
while (*(plEnums++) != NULL) {
free(*plEnums);
}
delete [] _EnumArray;
_EnumArray = NULL;
_ownEnumArray = false;
_maxVal = -1;
}
void Enumeration::setEnums(const char **plEnums)
{
std::string oldValue;
bool preserve = (isValid() && plEnums != NULL);
if (preserve) {
oldValue = getCStr();
}
// set _ownEnumArray
if (isValid() && _ownEnumArray) {
tearDown();
}
// set...
_EnumArray = plEnums;
// set _maxVal
findMaxVal();
// set _index
_index = 0;
if (preserve) {
setValue(oldValue);
}
}
void Enumeration::setEnums(const std::vector<std::string> &values)
{
std::string oldValue;
bool preserve = isValid();
if (preserve) {
oldValue = getCStr();
}
if (isValid() && _ownEnumArray) {
tearDown();
}
_EnumArray = new const char*[values.size() + 1];
int i = 0;
for (std::vector<std::string>::const_iterator it = values.begin(); it != values.end(); ++it) {
#if defined (_MSC_VER)
_EnumArray[i++] = _strdup(it->c_str());
#else
_EnumArray[i++] = strdup(it->c_str());
#endif
}
_EnumArray[i] = 0; // null termination
// Other state variables
_maxVal = values.size() - 1;
_ownEnumArray = true;
_index = 0;
if (preserve) {
setValue(oldValue);
}
}
void Enumeration::setValue(const char *value)
{
// using string methods without set, use setEnums(const char** plEnums) first!
assert(_EnumArray);
if (!_EnumArray) {
_index = 0;
return;
}
unsigned int i = 0;
const char **plEnums = _EnumArray;
// search for the right entry
while (1) {
// end of list? set zero
if (*plEnums == NULL) {
_index = 0;
break;
}
if (strcmp(*plEnums, value) == 0) {
_index = i;
break;
}
++plEnums;
++i;
}
}
void Enumeration::setValue(long value, bool checkRange)
{
if (value >= 0 && value <= _maxVal) {
_index = value;
} else {
if (checkRange) {
throw Base::ValueError("Out of range");
} else {
_index = value;
}
}
}
bool Enumeration::isValue(const char *value) const
{
// using string methods without set, use setEnums(const char** plEnums) first!
assert(_EnumArray);
int i = getInt();
if (i == -1) {
return false;
} else {
return strcmp(_EnumArray[i], value) == 0;
}
}
bool Enumeration::contains(const char *value) const
{
// using string methods without set, use setEnums(const char** plEnums) first!
assert(_EnumArray);
if (!isValid()) {
return false;
}
const char **plEnums = _EnumArray;
// search for the right entry
while (1) {
// end of list?
if (*plEnums == NULL)
return false;
if (strcmp(*plEnums, value) == 0)
return true;
++plEnums;
}
}
const char * Enumeration::getCStr(void) const
{
// using string methods without set, use setEnums(const char** plEnums) first!
assert(_EnumArray);
if (!isValid() || _index < 0 || _index > _maxVal) {
return NULL;
}
return _EnumArray[_index];
}
int Enumeration::getInt(void) const
{
if (!isValid() || _index < 0 || _index > _maxVal) {
return -1;
}
return _index;
}
std::vector<std::string> Enumeration::getEnumVector(void) const
{
// using string methods without set, use setEnums(const char** plEnums) first!
assert(_EnumArray);
std::vector<std::string> result;
const char **plEnums = _EnumArray;
// end of list?
while (*plEnums != NULL) {
result.push_back(*plEnums);
++plEnums;
}
return result;
}
const char ** Enumeration::getEnums(void) const
{
return _EnumArray;
}
bool Enumeration::isValid(void) const
{
return (_EnumArray != NULL && _index >= 0 && _index <= _maxVal);
}
Enumeration & Enumeration::operator=(const Enumeration &other)
{
if (other._ownEnumArray) {
setEnums(other.getEnumVector());
} else {
_EnumArray = other._EnumArray;
}
_ownEnumArray = other._ownEnumArray;
_index = other._index;
_maxVal = other._maxVal;
return *this;
}
bool Enumeration::operator==(const Enumeration &other) const
{
if (getCStr() == NULL || other.getCStr() == NULL) {
return false;
}
return (strcmp(getCStr(), other.getCStr()) == 0);
}
bool Enumeration::operator==(const char *other) const
{
if (getCStr() == NULL) {
return false;
}
return (strcmp(getCStr(), other) == 0);
}
void Enumeration::findMaxVal(void)
{
if (_EnumArray == NULL) {
_maxVal = -1;
return;
}
const char **plEnums = _EnumArray;
long i = 0;
while (*(plEnums++) != NULL) {
++i;
// very unlikely to have enums with more then 5000 entries!
assert(i < 5000);
}
_maxVal = i;
}
<|endoftext|> |
<commit_before>/************************************************************************************\
This source file is part of the APRIL Utility library *
For latest info, see http://libapril.sourceforge.net/ *
**************************************************************************************
Copyright (c) 2010 Kresimir Spes ([email protected]) *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php *
\************************************************************************************/
#include "StaticMesh.h"
#include <iostream>
namespace April
{
StaticMesh::StaticMesh()
{
}
StaticMesh::StaticMesh(chstr meshPath)
{
loadFromFile(meshPath);
convertToVertexArray();
}
StaticMesh::~StaticMesh()
{
}
void StaticMesh::convertToVertexArray()
{
mVertexArray = new April::TexturedVertex[3*mPolygons.size()];
for(int i = 0; i < mPolygons.size(); ++i)
{
mVertexArray[3*i + 0].x = mVertices[mPolygons[i].mVertind[0]].x;
mVertexArray[3*i + 0].y = mVertices[mPolygons[i].mVertind[0]].y;
mVertexArray[3*i + 0].z = mVertices[mPolygons[i].mVertind[0]].z;
mVertexArray[3*i + 0].u = mTextureCoordinates[mPolygons[i].mTexind[0]].x;
mVertexArray[3*i + 0].v = mTextureCoordinates[mPolygons[i].mTexind[0]].y;
mVertexArray[3*i + 1].x = mVertices[mPolygons[i].mVertind[1]].x;
mVertexArray[3*i + 1].y = mVertices[mPolygons[i].mVertind[1]].y;
mVertexArray[3*i + 1].z = mVertices[mPolygons[i].mVertind[1]].z;
mVertexArray[3*i + 1].u = mTextureCoordinates[mPolygons[i].mTexind[1]].x;
mVertexArray[3*i + 1].v = mTextureCoordinates[mPolygons[i].mTexind[1]].y;
mVertexArray[3*i + 2].x = mVertices[mPolygons[i].mVertind[2]].x;
mVertexArray[3*i + 2].y = mVertices[mPolygons[i].mVertind[2]].y;
mVertexArray[3*i + 2].z = mVertices[mPolygons[i].mVertind[2]].z;
mVertexArray[3*i + 2].u = mTextureCoordinates[mPolygons[i].mTexind[2]].x;
mVertexArray[3*i + 2].v = mTextureCoordinates[mPolygons[i].mTexind[2]].y;
}
mNumVertices = 3*mPolygons.size();
}
void StaticMesh::loadFromFile(chstr meshPath)
{
FILE *fp;
char buffer[256];
hstr command;
std::cerr << "[aprilutil] loading mesh '" << meshPath << "'" << std::endl;
fp=fopen(meshPath.c_str(), "r");
if( fp == NULL )
throw file_not_found(meshPath);
while( fscanf(fp, "%s", buffer) > 0 )
{
command = hstr(buffer);
if(command == "v")
{
gtypes::Vector3 vert;
if( fscanf(fp, "%f %f %f", &vert.x, &vert.y, &vert.z) != EOF )
{
mVertices.push_back(vert);
//std::cerr << "Vertice (" << msh->mVertices.size() << ")" << "[" << vert.x << "," << vert.y << "," << vert.z << "]" << std::endl;
}
else throw faulty_obj_file(meshPath);
}
else if(command == "vn")
{
gtypes::Vector3 nor;
if( fscanf(fp, "%f %f %f", &nor.x, &nor.y, &nor.z) != EOF )
{
mNormals.push_back(nor);
//std::cerr << "Normal (" << msh->mNormals.size() << ")" << "[" << nor.x << "," << nor.y << "," << nor.z << "]" << std::endl;
}
else throw faulty_obj_file(meshPath);
}
else if(command == "vt")
{
gtypes::Vector2 uv;
if( fscanf(fp, "%f %f", &uv.x, &uv.y) != EOF )
{
mTextureCoordinates.push_back(uv);
//std::cerr << "TexCoord (" << msh->mTextureCoordinates.size() << ")" << "[" << uv.x << "," << uv.y << "]" << std::endl;
}
else throw faulty_obj_file(meshPath);
}
else if(command == "f")
{
Polygon poly;
char buff1[64];
char buff2[64];
char buff3[64];
hstr first, second, third;
if(fscanf(fp, " %s %s %s", buff1, buff2, buff3) == EOF)
throw faulty_obj_file(meshPath);
first = hstr(buff1);
second = hstr(buff2);
third = hstr(buff3);
if(first.count("/") == 0)
{
poly.mVertind[0] = ((int)first - 1);
poly.mVertind[1] = ((int)second - 1);
poly.mVertind[2] = ((int)third - 1);
}
else if(first.count("//") == 1)
{
hstr tmp1, tmp2;
first.split("//", tmp1, tmp2);
poly.mVertind[0] = ((int)tmp1 - 1);
poly.mNorind[0] = ((int)tmp2 - 1);
second.split("//", tmp1, tmp2);
poly.mVertind[1] = ((int)tmp1 - 1);
poly.mNorind[1] = ((int)tmp2 - 1);
third.split("//", tmp1, tmp2);
poly.mVertind[2] = ((int)tmp1 - 1);
poly.mNorind[2] = ((int)tmp2 - 1);
}
else if(first.count("/") == 2)
{
hstr tmp1,tmp2,tmp3, tmp;
first.split('/', tmp1, tmp);
tmp.split('/', tmp2, tmp3);
//std::cerr << tmp1 << " " << tmp2 << " " << tmp3 << std::endl;
poly.mVertind[0] = ((int)tmp1 - 1);
poly.mTexind[0] = ((int)tmp2 - 1);
poly.mNorind[0] = ((int)tmp3 - 1);
second.split('/', tmp1, tmp);
tmp.split('/', tmp2, tmp3);
//std::cerr << tmp1 << " " << tmp2 << " " << tmp3 << std::endl;
poly.mVertind[1] = ((int)tmp1 - 1);
poly.mTexind[1] = ((int)tmp2 - 1);
poly.mNorind[1] = ((int)tmp3 - 1);
third.split('/', tmp1, tmp);
tmp.split('/', tmp2, tmp3);
//std::cerr << tmp1 << " " << tmp2 << " " << tmp3 << std::endl;
poly.mVertind[2] = ((int)tmp1 - 1);
poly.mTexind[2] = ((int)tmp2 - 1);
poly.mNorind[2] = ((int)tmp3 - 1);
}
mPolygons.push_back(poly);
}
else if(command.starts_with("#"))
{
}
else if(command.starts_with("mtllib"))
{
}
else if(command.starts_with("usemtl"))
{
}
else if(command == "s")
{
}
else if(command == "o")
{
}
else if(command == "g")
{
}
}
}
void StaticMesh::setMeshName(chstr meshName)
{
mMeshName = meshName;
}
void StaticMesh::draw(April::RenderOp renderOp)
{
rendersys->render(renderOp, mVertexArray, mNumVertices);
}
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
_faulty_obj_file::_faulty_obj_file(chstr filename, const char* source_file, int line) :
exception("'" + filename + "' is faulty wavefront file!", source_file, line)
{
}
}
<commit_msg>fixed bug in StaticMesh, crased when loading obj files without texture coords<commit_after>/************************************************************************************\
This source file is part of the APRIL Utility library *
For latest info, see http://libapril.sourceforge.net/ *
**************************************************************************************
Copyright (c) 2010 Kresimir Spes ([email protected]) *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php *
\************************************************************************************/
#include "StaticMesh.h"
#include <iostream>
namespace April
{
StaticMesh::StaticMesh()
{
}
StaticMesh::StaticMesh(chstr meshPath)
{
loadFromFile(meshPath);
convertToVertexArray();
}
StaticMesh::~StaticMesh()
{
}
void StaticMesh::convertToVertexArray()
{
mVertexArray = new April::TexturedVertex[3*mPolygons.size()];
bool tex=mTextureCoordinates.size() > 0;
for(int i = 0; i < mPolygons.size(); ++i)
{
mVertexArray[3*i + 0].x = mVertices[mPolygons[i].mVertind[0]].x;
mVertexArray[3*i + 0].y = mVertices[mPolygons[i].mVertind[0]].y;
mVertexArray[3*i + 0].z = mVertices[mPolygons[i].mVertind[0]].z;
if (tex)
{
mVertexArray[3*i + 0].u = mTextureCoordinates[mPolygons[i].mTexind[0]].x;
mVertexArray[3*i + 0].v = mTextureCoordinates[mPolygons[i].mTexind[0]].y;
}
mVertexArray[3*i + 1].x = mVertices[mPolygons[i].mVertind[1]].x;
mVertexArray[3*i + 1].y = mVertices[mPolygons[i].mVertind[1]].y;
mVertexArray[3*i + 1].z = mVertices[mPolygons[i].mVertind[1]].z;
if (tex)
{
mVertexArray[3*i + 1].u = mTextureCoordinates[mPolygons[i].mTexind[1]].x;
mVertexArray[3*i + 1].v = mTextureCoordinates[mPolygons[i].mTexind[1]].y;
}
mVertexArray[3*i + 2].x = mVertices[mPolygons[i].mVertind[2]].x;
mVertexArray[3*i + 2].y = mVertices[mPolygons[i].mVertind[2]].y;
mVertexArray[3*i + 2].z = mVertices[mPolygons[i].mVertind[2]].z;
if (tex)
{
mVertexArray[3*i + 2].u = mTextureCoordinates[mPolygons[i].mTexind[2]].x;
mVertexArray[3*i + 2].v = mTextureCoordinates[mPolygons[i].mTexind[2]].y;
}
}
mNumVertices = 3*mPolygons.size();
}
void StaticMesh::loadFromFile(chstr meshPath)
{
FILE *fp;
char buffer[256];
hstr command;
std::cerr << "[aprilutil] loading mesh '" << meshPath << "'" << std::endl;
fp=fopen(meshPath.c_str(), "r");
if( fp == NULL )
throw file_not_found(meshPath);
while( fscanf(fp, "%s", buffer) > 0 )
{
command = hstr(buffer);
if(command == "v")
{
gtypes::Vector3 vert;
if( fscanf(fp, "%f %f %f", &vert.x, &vert.y, &vert.z) != EOF )
{
mVertices.push_back(vert);
//std::cerr << "Vertice (" << msh->mVertices.size() << ")" << "[" << vert.x << "," << vert.y << "," << vert.z << "]" << std::endl;
}
else throw faulty_obj_file(meshPath);
}
else if(command == "vn")
{
gtypes::Vector3 nor;
if( fscanf(fp, "%f %f %f", &nor.x, &nor.y, &nor.z) != EOF )
{
mNormals.push_back(nor);
//std::cerr << "Normal (" << msh->mNormals.size() << ")" << "[" << nor.x << "," << nor.y << "," << nor.z << "]" << std::endl;
}
else throw faulty_obj_file(meshPath);
}
else if(command == "vt")
{
gtypes::Vector2 uv;
if( fscanf(fp, "%f %f", &uv.x, &uv.y) != EOF )
{
mTextureCoordinates.push_back(uv);
//std::cerr << "TexCoord (" << msh->mTextureCoordinates.size() << ")" << "[" << uv.x << "," << uv.y << "]" << std::endl;
}
else throw faulty_obj_file(meshPath);
}
else if(command == "f")
{
Polygon poly;
char buff1[64];
char buff2[64];
char buff3[64];
hstr first, second, third;
if(fscanf(fp, " %s %s %s", buff1, buff2, buff3) == EOF)
throw faulty_obj_file(meshPath);
first = hstr(buff1);
second = hstr(buff2);
third = hstr(buff3);
if(first.count("/") == 0)
{
poly.mVertind[0] = ((int)first - 1);
poly.mVertind[1] = ((int)second - 1);
poly.mVertind[2] = ((int)third - 1);
}
else if(first.count("//") == 1)
{
hstr tmp1, tmp2;
first.split("//", tmp1, tmp2);
poly.mVertind[0] = ((int)tmp1 - 1);
poly.mNorind[0] = ((int)tmp2 - 1);
second.split("//", tmp1, tmp2);
poly.mVertind[1] = ((int)tmp1 - 1);
poly.mNorind[1] = ((int)tmp2 - 1);
third.split("//", tmp1, tmp2);
poly.mVertind[2] = ((int)tmp1 - 1);
poly.mNorind[2] = ((int)tmp2 - 1);
}
else if(first.count("/") == 2)
{
hstr tmp1,tmp2,tmp3, tmp;
first.split('/', tmp1, tmp);
tmp.split('/', tmp2, tmp3);
//std::cerr << tmp1 << " " << tmp2 << " " << tmp3 << std::endl;
poly.mVertind[0] = ((int)tmp1 - 1);
poly.mTexind[0] = ((int)tmp2 - 1);
poly.mNorind[0] = ((int)tmp3 - 1);
second.split('/', tmp1, tmp);
tmp.split('/', tmp2, tmp3);
//std::cerr << tmp1 << " " << tmp2 << " " << tmp3 << std::endl;
poly.mVertind[1] = ((int)tmp1 - 1);
poly.mTexind[1] = ((int)tmp2 - 1);
poly.mNorind[1] = ((int)tmp3 - 1);
third.split('/', tmp1, tmp);
tmp.split('/', tmp2, tmp3);
//std::cerr << tmp1 << " " << tmp2 << " " << tmp3 << std::endl;
poly.mVertind[2] = ((int)tmp1 - 1);
poly.mTexind[2] = ((int)tmp2 - 1);
poly.mNorind[2] = ((int)tmp3 - 1);
}
mPolygons.push_back(poly);
}
else if(command.starts_with("#"))
{
}
else if(command.starts_with("mtllib"))
{
}
else if(command.starts_with("usemtl"))
{
}
else if(command == "s")
{
}
else if(command == "o")
{
}
else if(command == "g")
{
}
}
}
void StaticMesh::setMeshName(chstr meshName)
{
mMeshName = meshName;
}
void StaticMesh::draw(April::RenderOp renderOp)
{
rendersys->render(renderOp, mVertexArray, mNumVertices);
}
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
_faulty_obj_file::_faulty_obj_file(chstr filename, const char* source_file, int line) :
exception("'" + filename + "' is faulty wavefront file!", source_file, line)
{
}
}
<|endoftext|> |
<commit_before>// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "riegeli/messages/message_parse.h"
#include <stddef.h>
#include <stdint.h>
#include <limits>
#include <string>
#include "absl/base/attributes.h"
#include "absl/base/optimization.h"
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "google/protobuf/io/coded_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
#include "google/protobuf/message_lite.h"
#include "riegeli/base/base.h"
#include "riegeli/base/chain.h"
#include "riegeli/bytes/chain_reader.h"
#include "riegeli/bytes/cord_reader.h"
#include "riegeli/bytes/limiting_reader.h"
#include "riegeli/bytes/reader.h"
namespace riegeli {
namespace {
ABSL_ATTRIBUTE_COLD
inline absl::Status ParseError(google::protobuf::MessageLite& dest) {
return absl::InvalidArgumentError(
absl::StrCat("Failed to parse message of type ", dest.GetTypeName()));
}
ABSL_ATTRIBUTE_COLD
inline absl::Status ParseError(Reader& src,
google::protobuf::MessageLite& dest) {
return src.AnnotateStatus(ParseError(dest));
}
inline absl::Status CheckInitialized(google::protobuf::MessageLite& dest,
ParseOptions options) {
if (!options.partial() && ABSL_PREDICT_FALSE(!dest.IsInitialized())) {
return absl::InvalidArgumentError(
absl::StrCat("Failed to parse message of type ", dest.GetTypeName(),
" because it is missing required fields: ",
dest.InitializationErrorString()));
}
return absl::OkStatus();
}
inline absl::Status CheckInitialized(Reader& src,
google::protobuf::MessageLite& dest,
ParseOptions options) {
if (!options.partial() && ABSL_PREDICT_FALSE(!dest.IsInitialized())) {
return src.AnnotateStatus(absl::InvalidArgumentError(
absl::StrCat("Failed to parse message of type ", dest.GetTypeName(),
" because it is missing required fields: ",
dest.InitializationErrorString())));
}
return absl::OkStatus();
}
} // namespace
namespace messages_internal {
absl::Status ParseFromReaderImpl(Reader& src,
google::protobuf::MessageLite& dest,
ParseOptions options) {
src.Pull();
if (!options.merge() &&
options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&
src.available() <= kMaxBytesToCopy && src.SupportsSize()) {
const absl::optional<Position> size = src.Size();
if (ABSL_PREDICT_FALSE(size == absl::nullopt)) return src.status();
if (src.limit_pos() == *size) {
// The data are flat. `ParsePartialFromArray()` is faster than
// `ParsePartialFromZeroCopyStream()`.
const bool parse_ok =
ABSL_PREDICT_TRUE(src.available() <=
size_t{std::numeric_limits<int>::max()}) &&
dest.ParsePartialFromArray(src.cursor(),
IntCast<int>(src.available()));
src.move_cursor(src.available());
if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(src, dest);
return CheckInitialized(src, dest, options);
}
}
ReaderInputStream input_stream(&src);
bool parse_ok;
if (options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {
parse_ok =
options.merge()
? dest.MergePartialFromBoundedZeroCopyStream(&input_stream, -1)
: dest.ParsePartialFromZeroCopyStream(&input_stream);
} else {
if (!options.merge()) dest.Clear();
google::protobuf::io::CodedInputStream coded_stream(&input_stream);
coded_stream.SetRecursionLimit(options.recursion_limit());
parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&
coded_stream.ConsumedEntireMessage();
}
if (ABSL_PREDICT_FALSE(!src.ok())) return src.status();
if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(src, dest);
return CheckInitialized(src, dest, options);
}
} // namespace messages_internal
absl::Status ParseFromReaderWithLength(Reader& src, size_t length,
google::protobuf::MessageLite& dest,
ParseOptions options) {
if (!options.merge() &&
options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&
length <= kMaxBytesToCopy) {
src.Pull();
if (src.available() >= length) {
// The data are flat. `ParsePartialFromArray()` is faster than
// `ParsePartialFromZeroCopyStream()`.
const bool parse_ok =
dest.ParsePartialFromArray(src.cursor(), IntCast<int>(length));
src.move_cursor(length);
if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(src, dest);
return CheckInitialized(src, dest, options);
}
}
LimitingReader<> reader(
&src, LimitingReaderBase::Options().set_exact_length(length));
ReaderInputStream input_stream(&reader);
bool parse_ok;
if (options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {
parse_ok =
options.merge()
? dest.MergePartialFromBoundedZeroCopyStream(&input_stream, -1)
: dest.ParsePartialFromZeroCopyStream(&input_stream);
} else {
if (!options.merge()) dest.Clear();
google::protobuf::io::CodedInputStream coded_stream(&input_stream);
coded_stream.SetRecursionLimit(options.recursion_limit());
parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&
coded_stream.ConsumedEntireMessage();
}
if (ABSL_PREDICT_FALSE(!reader.ok())) return reader.status();
if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(reader, dest);
const absl::Status status = CheckInitialized(reader, dest, options);
if (!reader.Close()) {
RIEGELI_ASSERT_UNREACHABLE() << "A LimitingReader with !fail_if_longer() "
"has no reason to fail only in Close(): "
<< reader.status();
}
return status;
}
absl::Status ParseFromString(absl::string_view src,
google::protobuf::MessageLite& dest,
ParseOptions options) {
bool parse_ok;
if (ABSL_PREDICT_FALSE(src.size() >
size_t{std::numeric_limits<int>::max()})) {
parse_ok = false;
} else if (!options.merge() && options.recursion_limit() ==
google::protobuf::io::CodedInputStream::
GetDefaultRecursionLimit()) {
parse_ok = dest.ParsePartialFromArray(src.data(), IntCast<int>(src.size()));
} else {
if (!options.merge()) dest.Clear();
google::protobuf::io::ArrayInputStream input_stream(
src.data(), IntCast<int>(src.size()));
google::protobuf::io::CodedInputStream coded_stream(&input_stream);
coded_stream.SetRecursionLimit(options.recursion_limit());
parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&
coded_stream.ConsumedEntireMessage();
}
if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(dest);
return CheckInitialized(dest, options);
}
absl::Status ParseFromChain(const Chain& src,
google::protobuf::MessageLite& dest,
ParseOptions options) {
if (!options.merge() &&
options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&
src.size() <= kMaxBytesToCopy) {
if (const absl::optional<absl::string_view> flat = src.TryFlat()) {
// The data are flat. `ParsePartialFromArray()` is faster than
// `ParsePartialFromZeroCopyStream()`.
if (ABSL_PREDICT_FALSE(!dest.ParsePartialFromArray(
flat->data(), IntCast<int>(flat->size())))) {
return ParseError(dest);
}
return CheckInitialized(dest, options);
}
}
ChainReader<> reader(&src);
// Do not bother with `reader.ok()` or `reader.Close()`. A `ChainReader` can
// never fail.
ReaderInputStream input_stream(&reader);
bool parse_ok;
if (options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {
parse_ok =
options.merge()
? dest.MergePartialFromBoundedZeroCopyStream(&input_stream, -1)
: dest.ParsePartialFromZeroCopyStream(&input_stream);
} else {
if (!options.merge()) dest.Clear();
google::protobuf::io::CodedInputStream coded_stream(&input_stream);
coded_stream.SetRecursionLimit(options.recursion_limit());
parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&
coded_stream.ConsumedEntireMessage();
}
if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(dest);
return CheckInitialized(dest, options);
}
absl::Status ParseFromCord(const absl::Cord& src,
google::protobuf::MessageLite& dest,
ParseOptions options) {
if (!options.merge() &&
options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&
src.size() <= kMaxBytesToCopy) {
if (const absl::optional<absl::string_view> flat = src.TryFlat()) {
// The data are flat. `ParsePartialFromArray()` is faster than
// `ParsePartialFromZeroCopyStream()`.
if (ABSL_PREDICT_FALSE(!dest.ParsePartialFromArray(
flat->data(), IntCast<int>(flat->size())))) {
return ParseError(dest);
}
return CheckInitialized(dest, options);
}
}
CordReader<> reader(&src);
// Do not bother with `reader.ok()` or `reader.Close()`. A `CordReader` can
// never fail.
ReaderInputStream input_stream(&reader);
bool parse_ok;
if (options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {
parse_ok =
options.merge()
? dest.MergePartialFromBoundedZeroCopyStream(&input_stream, -1)
: dest.ParsePartialFromZeroCopyStream(&input_stream);
} else {
if (!options.merge()) dest.Clear();
google::protobuf::io::CodedInputStream coded_stream(&input_stream);
coded_stream.SetRecursionLimit(options.recursion_limit());
parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&
coded_stream.ConsumedEntireMessage();
}
if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(dest);
return CheckInitialized(dest, options);
}
bool ReaderInputStream::Next(const void** data, int* size) {
if (ABSL_PREDICT_FALSE(src_->pos() >=
Position{std::numeric_limits<int64_t>::max()})) {
return false;
}
const Position max_length =
Position{std::numeric_limits<int64_t>::max()} - src_->pos();
if (ABSL_PREDICT_FALSE(!src_->Pull())) return false;
*data = src_->cursor();
*size = SaturatingIntCast<int>(UnsignedMin(src_->available(), max_length));
src_->move_cursor(IntCast<size_t>(*size));
return true;
}
void ReaderInputStream::BackUp(int length) {
RIEGELI_ASSERT_GE(length, 0)
<< "Failed precondition of ZeroCopyInputStream::BackUp(): "
"negative length";
RIEGELI_ASSERT_LE(IntCast<size_t>(length), src_->start_to_cursor())
<< "Failed precondition of ZeroCopyInputStream::BackUp(): "
"length larger than the amount of buffered data";
src_->set_cursor(src_->cursor() - length);
}
bool ReaderInputStream::Skip(int length) {
RIEGELI_ASSERT_GE(length, 0)
<< "Failed precondition of ZeroCopyInputStream::Skip(): negative length";
const Position max_length =
SaturatingSub(Position{std::numeric_limits<int64_t>::max()}, src_->pos());
const size_t length_to_skip =
UnsignedMin(IntCast<size_t>(length), max_length);
return src_->Skip(length_to_skip) &&
length_to_skip == IntCast<size_t>(length);
}
int64_t ReaderInputStream::ByteCount() const {
return SaturatingIntCast<int64_t>(src_->pos());
}
} // namespace riegeli
<commit_msg>Optimizations and simplifications in proto parsing functions:<commit_after>// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "riegeli/messages/message_parse.h"
#include <stddef.h>
#include <stdint.h>
#include <limits>
#include <string>
#include "absl/base/attributes.h"
#include "absl/base/optimization.h"
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "google/protobuf/io/coded_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
#include "google/protobuf/message_lite.h"
#include "riegeli/base/base.h"
#include "riegeli/base/chain.h"
#include "riegeli/bytes/chain_reader.h"
#include "riegeli/bytes/cord_reader.h"
#include "riegeli/bytes/limiting_reader.h"
#include "riegeli/bytes/reader.h"
namespace riegeli {
namespace {
ABSL_ATTRIBUTE_COLD
inline absl::Status ParseError(google::protobuf::MessageLite& dest) {
return absl::InvalidArgumentError(
absl::StrCat("Failed to parse message of type ", dest.GetTypeName()));
}
ABSL_ATTRIBUTE_COLD
inline absl::Status ParseError(Reader& src,
google::protobuf::MessageLite& dest) {
return src.AnnotateStatus(ParseError(dest));
}
inline absl::Status CheckInitialized(google::protobuf::MessageLite& dest,
ParseOptions options) {
if (!options.partial() && ABSL_PREDICT_FALSE(!dest.IsInitialized())) {
return absl::InvalidArgumentError(
absl::StrCat("Failed to parse message of type ", dest.GetTypeName(),
" because it is missing required fields: ",
dest.InitializationErrorString()));
}
return absl::OkStatus();
}
inline absl::Status CheckInitialized(Reader& src,
google::protobuf::MessageLite& dest,
ParseOptions options) {
if (!options.partial() && ABSL_PREDICT_FALSE(!dest.IsInitialized())) {
return src.AnnotateStatus(absl::InvalidArgumentError(
absl::StrCat("Failed to parse message of type ", dest.GetTypeName(),
" because it is missing required fields: ",
dest.InitializationErrorString())));
}
return absl::OkStatus();
}
} // namespace
namespace messages_internal {
absl::Status ParseFromReaderImpl(Reader& src,
google::protobuf::MessageLite& dest,
ParseOptions options) {
src.Pull();
if (!options.merge() &&
options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&
src.available() <= kMaxBytesToCopy && src.SupportsSize()) {
const absl::optional<Position> size = src.Size();
if (ABSL_PREDICT_FALSE(size == absl::nullopt)) return src.status();
if (src.limit_pos() == *size) {
// The data are flat. `ParsePartialFromArray()` is faster than
// `ParsePartialFromZeroCopyStream()`.
const bool parse_ok =
ABSL_PREDICT_TRUE(src.available() <=
size_t{std::numeric_limits<int>::max()}) &&
dest.ParsePartialFromArray(src.cursor(),
IntCast<int>(src.available()));
src.move_cursor(src.available());
if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(src, dest);
return CheckInitialized(src, dest, options);
}
}
ReaderInputStream input_stream(&src);
if (!options.merge()) dest.Clear();
bool parse_ok;
if (options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {
parse_ok = dest.MergePartialFromBoundedZeroCopyStream(&input_stream, -1);
} else {
google::protobuf::io::CodedInputStream coded_stream(&input_stream);
coded_stream.SetRecursionLimit(options.recursion_limit());
parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&
coded_stream.ConsumedEntireMessage();
}
if (ABSL_PREDICT_FALSE(!src.ok())) return src.status();
if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(src, dest);
return CheckInitialized(src, dest, options);
}
} // namespace messages_internal
absl::Status ParseFromReaderWithLength(Reader& src, size_t length,
google::protobuf::MessageLite& dest,
ParseOptions options) {
if (!options.merge() &&
options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&
length <= kMaxBytesToCopy) {
src.Pull();
if (src.available() >= length) {
// The data are flat. `ParsePartialFromArray()` is faster than
// `ParsePartialFromZeroCopyStream()`.
const bool parse_ok =
dest.ParsePartialFromArray(src.cursor(), IntCast<int>(length));
src.move_cursor(length);
if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(src, dest);
return CheckInitialized(src, dest, options);
}
}
LimitingReader<> reader(
&src, LimitingReaderBase::Options().set_exact_length(length));
ReaderInputStream input_stream(&reader);
if (!options.merge()) dest.Clear();
bool parse_ok;
if (options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {
parse_ok = dest.MergePartialFromBoundedZeroCopyStream(&input_stream, -1);
} else {
google::protobuf::io::CodedInputStream coded_stream(&input_stream);
coded_stream.SetRecursionLimit(options.recursion_limit());
parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&
coded_stream.ConsumedEntireMessage();
}
if (ABSL_PREDICT_FALSE(!reader.ok())) return reader.status();
if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(reader, dest);
const absl::Status status = CheckInitialized(reader, dest, options);
if (!reader.Close()) {
RIEGELI_ASSERT_UNREACHABLE() << "A LimitingReader with !fail_if_longer() "
"has no reason to fail only in Close(): "
<< reader.status();
}
return status;
}
absl::Status ParseFromString(absl::string_view src,
google::protobuf::MessageLite& dest,
ParseOptions options) {
bool parse_ok;
if (ABSL_PREDICT_FALSE(src.size() >
size_t{std::numeric_limits<int>::max()})) {
parse_ok = false;
} else if (!options.merge() && options.recursion_limit() ==
google::protobuf::io::CodedInputStream::
GetDefaultRecursionLimit()) {
parse_ok = dest.ParsePartialFromArray(src.data(), IntCast<int>(src.size()));
} else {
if (!options.merge()) dest.Clear();
google::protobuf::io::ArrayInputStream input_stream(
src.data(), IntCast<int>(src.size()));
if (options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {
parse_ok = dest.MergePartialFromBoundedZeroCopyStream(&input_stream, -1);
} else {
google::protobuf::io::CodedInputStream coded_stream(&input_stream);
coded_stream.SetRecursionLimit(options.recursion_limit());
parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&
coded_stream.ConsumedEntireMessage();
}
}
if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(dest);
return CheckInitialized(dest, options);
}
absl::Status ParseFromChain(const Chain& src,
google::protobuf::MessageLite& dest,
ParseOptions options) {
if (!options.merge() &&
options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&
src.size() <= kMaxBytesToCopy) {
if (const absl::optional<absl::string_view> flat = src.TryFlat()) {
// The data are flat. `ParsePartialFromArray()` is faster than
// `ParsePartialFromZeroCopyStream()`.
if (ABSL_PREDICT_FALSE(!dest.ParsePartialFromArray(
flat->data(), IntCast<int>(flat->size())))) {
return ParseError(dest);
}
return CheckInitialized(dest, options);
}
}
ChainReader<> reader(&src);
// Do not bother with `reader.ok()` or `reader.Close()`. A `ChainReader` can
// never fail.
ReaderInputStream input_stream(&reader);
if (!options.merge()) dest.Clear();
bool parse_ok;
if (options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {
parse_ok = dest.MergePartialFromBoundedZeroCopyStream(&input_stream, -1);
} else {
google::protobuf::io::CodedInputStream coded_stream(&input_stream);
coded_stream.SetRecursionLimit(options.recursion_limit());
parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&
coded_stream.ConsumedEntireMessage();
}
if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(dest);
return CheckInitialized(dest, options);
}
absl::Status ParseFromCord(const absl::Cord& src,
google::protobuf::MessageLite& dest,
ParseOptions options) {
if (!options.merge() &&
options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit() &&
src.size() <= kMaxBytesToCopy) {
if (const absl::optional<absl::string_view> flat = src.TryFlat()) {
// The data are flat. `ParsePartialFromArray()` is faster than
// `ParsePartialFromZeroCopyStream()`.
if (ABSL_PREDICT_FALSE(!dest.ParsePartialFromArray(
flat->data(), IntCast<int>(flat->size())))) {
return ParseError(dest);
}
return CheckInitialized(dest, options);
}
}
CordReader<> reader(&src);
// Do not bother with `reader.ok()` or `reader.Close()`. A `CordReader` can
// never fail.
ReaderInputStream input_stream(&reader);
if (!options.merge()) dest.Clear();
bool parse_ok;
if (options.recursion_limit() ==
google::protobuf::io::CodedInputStream::GetDefaultRecursionLimit()) {
parse_ok = dest.MergePartialFromBoundedZeroCopyStream(&input_stream, -1);
} else {
google::protobuf::io::CodedInputStream coded_stream(&input_stream);
coded_stream.SetRecursionLimit(options.recursion_limit());
parse_ok = dest.MergePartialFromCodedStream(&coded_stream) &&
coded_stream.ConsumedEntireMessage();
}
if (ABSL_PREDICT_FALSE(!parse_ok)) return ParseError(dest);
return CheckInitialized(dest, options);
}
bool ReaderInputStream::Next(const void** data, int* size) {
if (ABSL_PREDICT_FALSE(src_->pos() >=
Position{std::numeric_limits<int64_t>::max()})) {
return false;
}
const Position max_length =
Position{std::numeric_limits<int64_t>::max()} - src_->pos();
if (ABSL_PREDICT_FALSE(!src_->Pull())) return false;
*data = src_->cursor();
*size = SaturatingIntCast<int>(UnsignedMin(src_->available(), max_length));
src_->move_cursor(IntCast<size_t>(*size));
return true;
}
void ReaderInputStream::BackUp(int length) {
RIEGELI_ASSERT_GE(length, 0)
<< "Failed precondition of ZeroCopyInputStream::BackUp(): "
"negative length";
RIEGELI_ASSERT_LE(IntCast<size_t>(length), src_->start_to_cursor())
<< "Failed precondition of ZeroCopyInputStream::BackUp(): "
"length larger than the amount of buffered data";
src_->set_cursor(src_->cursor() - length);
}
bool ReaderInputStream::Skip(int length) {
RIEGELI_ASSERT_GE(length, 0)
<< "Failed precondition of ZeroCopyInputStream::Skip(): negative length";
const Position max_length =
SaturatingSub(Position{std::numeric_limits<int64_t>::max()}, src_->pos());
const size_t length_to_skip =
UnsignedMin(IntCast<size_t>(length), max_length);
return src_->Skip(length_to_skip) &&
length_to_skip == IntCast<size_t>(length);
}
int64_t ReaderInputStream::ByteCount() const {
return SaturatingIntCast<int64_t>(src_->pos());
}
} // namespace riegeli
<|endoftext|> |
<commit_before>#include <stan/services/sample/hmc_nuts_dense_e_adapt.hpp>
#include <stan/io/empty_var_context.hpp>
#include <stan/callbacks/unique_stream_writer.hpp>
#include <test/unit/util.hpp>
#include <src/test/unit/services/util.hpp>
#include <test/test-models/good/optimization/rosenbrock.hpp>
#include <test/unit/services/instrumented_callbacks.hpp>
#include <gtest/gtest.h>
#include <iostream>
auto&& blah = stan::math::init_threadpool_tbb();
static constexpr size_t num_chains = 4;
class ServicesSampleHmcNutsDenseEAdaptParMatch : public testing::Test {
public:
ServicesSampleHmcNutsDenseEAdaptParMatch()
: model(std::make_unique<rosenbrock_model_namespace::rosenbrock_model>(
data_context, 0, &model_log)) {
for (int i = 0; i < num_chains; ++i) {
init.push_back(stan::test::unit::instrumented_writer{});
par_parameters.emplace_back(std::make_unique<std::stringstream>(), "#");
seq_parameters.emplace_back(std::make_unique<std::stringstream>(), "#");
diagnostic.push_back(stan::test::unit::instrumented_writer{});
context.push_back(std::make_shared<stan::io::empty_var_context>());
}
}
stan::io::empty_var_context data_context;
std::stringstream model_log;
stan::test::unit::instrumented_logger logger;
std::vector<stan::test::unit::instrumented_writer> init;
using str_writer = stan::callbacks::unique_stream_writer<std::stringstream>;
std::vector<str_writer> par_parameters;
std::vector<str_writer> seq_parameters;
std::vector<stan::test::unit::instrumented_writer> diagnostic;
std::vector<std::shared_ptr<stan::io::empty_var_context>> context;
std::unique_ptr<rosenbrock_model_namespace::rosenbrock_model> model;
};
/**
* This test checks that running multiple chains in one call
* with the same initial id is the same as running multiple calls
* with incrementing chain ids.
*/
TEST_F(ServicesSampleHmcNutsDenseEAdaptParMatch, single_multi_match) {
constexpr unsigned int random_seed = 0;
constexpr unsigned int chain = 0;
constexpr double init_radius = 0;
constexpr int num_warmup = 200;
constexpr int num_samples = 400;
constexpr int num_thin = 5;
constexpr bool save_warmup = true;
constexpr int refresh = 0;
constexpr double stepsize = 0.1;
constexpr double stepsize_jitter = 0;
constexpr int max_depth = 8;
constexpr double delta = .1;
constexpr double gamma = .1;
constexpr double kappa = .1;
constexpr double t0 = .1;
constexpr unsigned int init_buffer = 50;
constexpr unsigned int term_buffer = 50;
constexpr unsigned int window = 100;
stan::test::unit::instrumented_interrupt interrupt;
EXPECT_EQ(interrupt.call_count(), 0);
int return_code = stan::services::sample::hmc_nuts_dense_e_adapt(
*model, num_chains, context, random_seed, chain, init_radius, num_warmup,
num_samples, num_thin, save_warmup, refresh, stepsize, stepsize_jitter,
max_depth, delta, gamma, kappa, t0, init_buffer, term_buffer, window,
interrupt, logger, init, par_parameters, diagnostic);
EXPECT_EQ(0, return_code);
int num_output_lines = (num_warmup + num_samples) / num_thin;
EXPECT_EQ((num_warmup + num_samples) * num_chains, interrupt.call_count());
for (int i = 0; i < num_chains; ++i) {
stan::test::unit::instrumented_writer seq_init;
stan::test::unit::instrumented_writer seq_diagnostic;
return_code = stan::services::sample::hmc_nuts_dense_e_adapt(
*model, *(context[i]), random_seed, i, init_radius, num_warmup,
num_samples, num_thin, save_warmup, refresh, stepsize, stepsize_jitter,
max_depth, delta, gamma, kappa, t0, init_buffer, term_buffer, window,
interrupt, logger, seq_init, seq_parameters[i], seq_diagnostic);
EXPECT_EQ(0, return_code);
}
std::vector<Eigen::MatrixXd> par_res;
for (int i = 0; i < num_chains; ++i) {
auto par_str = par_parameters[i].get_stream().str();
auto sub_par_str = par_str.substr(par_str.find("Elements") - 1);
std::istringstream sub_par_stream(sub_par_str);
Eigen::MatrixXd par_mat
= stan::test::read_stan_sample_csv(sub_par_stream, 80, 9);
par_res.push_back(par_mat);
}
std::vector<Eigen::MatrixXd> seq_res;
for (int i = 0; i < num_chains; ++i) {
auto seq_str = seq_parameters[i].get_stream().str();
auto sub_seq_str = seq_str.substr(seq_str.find("Elements") - 1);
std::istringstream sub_seq_stream(sub_seq_str);
Eigen::MatrixXd seq_mat
= stan::test::read_stan_sample_csv(sub_seq_stream, 80, 9);
seq_res.push_back(seq_mat);
}
for (int i = 0; i < num_chains; ++i) {
Eigen::MatrixXd diff_res
= (par_res[i].array() - seq_res[i].array()).matrix();
EXPECT_MATRIX_EQ(diff_res, Eigen::MatrixXd::Zero(80, 9));
}
}
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#include <stan/services/sample/hmc_nuts_dense_e_adapt.hpp>
#include <stan/io/empty_var_context.hpp>
#include <stan/callbacks/unique_stream_writer.hpp>
#include <test/unit/util.hpp>
#include <src/test/unit/services/util.hpp>
#include <test/test-models/good/optimization/rosenbrock.hpp>
#include <test/unit/services/instrumented_callbacks.hpp>
#include <gtest/gtest.h>
#include <iostream>
auto&& blah = stan::math::init_threadpool_tbb();
static constexpr size_t num_chains = 4;
class ServicesSampleHmcNutsDenseEAdaptParMatch : public testing::Test {
public:
ServicesSampleHmcNutsDenseEAdaptParMatch()
: model(std::make_unique<rosenbrock_model_namespace::rosenbrock_model>(
data_context, 0, &model_log)) {
for (int i = 0; i < num_chains; ++i) {
init.push_back(stan::test::unit::instrumented_writer{});
par_parameters.emplace_back(std::make_unique<std::stringstream>(), "#");
seq_parameters.emplace_back(std::make_unique<std::stringstream>(), "#");
diagnostic.push_back(stan::test::unit::instrumented_writer{});
context.push_back(std::make_shared<stan::io::empty_var_context>());
}
}
stan::io::empty_var_context data_context;
std::stringstream model_log;
stan::test::unit::instrumented_logger logger;
std::vector<stan::test::unit::instrumented_writer> init;
using str_writer = stan::callbacks::unique_stream_writer<std::stringstream>;
std::vector<str_writer> par_parameters;
std::vector<str_writer> seq_parameters;
std::vector<stan::test::unit::instrumented_writer> diagnostic;
std::vector<std::shared_ptr<stan::io::empty_var_context>> context;
std::unique_ptr<rosenbrock_model_namespace::rosenbrock_model> model;
};
/**
* This test checks that running multiple chains in one call
* with the same initial id is the same as running multiple calls
* with incrementing chain ids.
*/
TEST_F(ServicesSampleHmcNutsDenseEAdaptParMatch, single_multi_match) {
constexpr unsigned int random_seed = 0;
constexpr unsigned int chain = 0;
constexpr double init_radius = 0;
constexpr int num_warmup = 200;
constexpr int num_samples = 400;
constexpr int num_thin = 5;
constexpr bool save_warmup = true;
constexpr int refresh = 0;
constexpr double stepsize = 0.1;
constexpr double stepsize_jitter = 0;
constexpr int max_depth = 8;
constexpr double delta = .1;
constexpr double gamma = .1;
constexpr double kappa = .1;
constexpr double t0 = .1;
constexpr unsigned int init_buffer = 50;
constexpr unsigned int term_buffer = 50;
constexpr unsigned int window = 100;
stan::test::unit::instrumented_interrupt interrupt;
EXPECT_EQ(interrupt.call_count(), 0);
int return_code = stan::services::sample::hmc_nuts_dense_e_adapt(
*model, num_chains, context, random_seed, chain, init_radius, num_warmup,
num_samples, num_thin, save_warmup, refresh, stepsize, stepsize_jitter,
max_depth, delta, gamma, kappa, t0, init_buffer, term_buffer, window,
interrupt, logger, init, par_parameters, diagnostic);
EXPECT_EQ(0, return_code);
int num_output_lines = (num_warmup + num_samples) / num_thin;
EXPECT_EQ((num_warmup + num_samples) * num_chains, interrupt.call_count());
for (int i = 0; i < num_chains; ++i) {
stan::test::unit::instrumented_writer seq_init;
stan::test::unit::instrumented_writer seq_diagnostic;
return_code = stan::services::sample::hmc_nuts_dense_e_adapt(
*model, *(context[i]), random_seed, i, init_radius, num_warmup,
num_samples, num_thin, save_warmup, refresh, stepsize, stepsize_jitter,
max_depth, delta, gamma, kappa, t0, init_buffer, term_buffer, window,
interrupt, logger, seq_init, seq_parameters[i], seq_diagnostic);
EXPECT_EQ(0, return_code);
}
std::vector<Eigen::MatrixXd> par_res;
for (int i = 0; i < num_chains; ++i) {
auto par_str = par_parameters[i].get_stream().str();
auto sub_par_str = par_str.substr(par_str.find("Elements") - 1);
std::istringstream sub_par_stream(sub_par_str);
Eigen::MatrixXd par_mat
= stan::test::read_stan_sample_csv(sub_par_stream, 80, 9);
par_res.push_back(par_mat);
}
std::vector<Eigen::MatrixXd> seq_res;
for (int i = 0; i < num_chains; ++i) {
auto seq_str = seq_parameters[i].get_stream().str();
auto sub_seq_str = seq_str.substr(seq_str.find("Elements") - 1);
std::istringstream sub_seq_stream(sub_seq_str);
Eigen::MatrixXd seq_mat
= stan::test::read_stan_sample_csv(sub_seq_stream, 80, 9);
seq_res.push_back(seq_mat);
}
for (int i = 0; i < num_chains; ++i) {
Eigen::MatrixXd diff_res
= (par_res[i].array() - seq_res[i].array()).matrix();
EXPECT_MATRIX_EQ(diff_res, Eigen::MatrixXd::Zero(80, 9));
}
}
<|endoftext|> |
<commit_before>#pragma warning(push)
#pragma warning(disable:4996)
#pragma warning(disable:4244)
#pragma warning(disable:4291)
#pragma warning(disable:4146)
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/GraphWriter.h"
#pragma warning(pop)
#include <functional>
using namespace std;
using namespace clang;
using namespace clang::tooling;
using namespace llvm;
// ***************************************************************************
// vvZbT̃R[obN
// ***************************************************************************
class cincluder : public PPCallbacks {
private:
Preprocessor &PP;
typedef ::std::hash< ::std::string > hash;
typedef ::std::list< hash::result_type > hash_list;
struct header
{
header() : angled(false) {}
header(const ::std::string& n, bool angled_) : name(n), angled(angled_) {}
::std::string name;
bool angled;
hash_list include;
};
typedef ::std::map< hash::result_type, header > Map;
typedef ::std::map< hash::result_type, hash_list > Depend;
Map m_includes;
Depend m_depends;
hash::result_type m_root;
::std::string m_output;
public:
cincluder(Preprocessor &pp) : PP(pp) {}
cincluder(Preprocessor &pp, const ::std::string& output) : PP(pp), m_output(output) {}
const header& getHeader(hash::result_type h)
{
return m_includes[h];
}
::std::string getFilePath(hash::result_type h)
{
return m_includes[h].name;
}
::std::string getFileName(hash::result_type h)
{
::std::string path = getFilePath(h);
size_t dpos1 = path.rfind('\\');
size_t dpos2 = path.rfind('/');
if( dpos1 == ::std::string::npos ) dpos1 = 0;
if( dpos2 == ::std::string::npos ) dpos2 = 0;
const size_t dpos = (::std::max)(dpos1, dpos2) + 1;
return path.substr( dpos );
}
::std::string getFileName(const header& h)
{
::std::string path = h.name;
size_t dpos1 = path.rfind('\\');
size_t dpos2 = path.rfind('/');
if( dpos1 == ::std::string::npos ) dpos1 = 0;
if( dpos2 == ::std::string::npos ) dpos2 = 0;
const size_t dpos = (::std::max)(dpos1, dpos2) + 1;
return path.substr(dpos);
}
void printRoot(hash::result_type h, int indent, bool expand)
{
if( indent > 2 ) return;
for( int i = 0; i < indent; ++i ) errs() << " ";
if( expand ) errs() << "+ ";
else errs() << " ";
errs() << getFileName(h) << "\n";
if( m_depends.find(h) != m_depends.end() )
{
auto depend = m_depends[h];
if( depend.size() > 1 ) ++indent;
for( auto d : depend )
{
printRoot(d, indent, (depend.size() > 1));
}
}
}
void report()
{
for( auto h : m_depends )
{
if( h.second.size() > 1 )
{
errs() << getFileName(h.first) << " is already include by \n";
for( auto d : h.second )
{
printRoot(d, 1, true);
}
}
}
}
void writeID(raw_ostream& OS, hash::result_type h)
{
OS << "header_";
OS.write_hex(h);
}
void dot()
{
if( m_output.empty() ) return;
std::error_code EC;
llvm::raw_fd_ostream OS(m_output, EC, llvm::sys::fs::F_Text);
if( EC )
{
PP.getDiagnostics().Report(diag::err_fe_error_opening) << m_output
<< EC.message();
return;
}
const char* endl = "\n";
OS << "digraph \"dependencies\" {" << endl;
for( auto inc : m_includes )
{
writeID(OS, inc.first);
OS << " [ shape=\"box\", label=\"";
OS << DOT::EscapeString(getFileName(inc.second));
OS << "\"];" << endl;
}
for( auto h : m_depends )
{
for(auto depend : h.second)
{
writeID(OS, h.first);
OS << " -> ";
writeID(OS, depend);
OS << endl;
}
}
OS << "}" << endl;
}
void EndOfMainFile() override
{
report();
dot();
}
void InclusionDirective(SourceLocation HashLoc,
const Token &IncludeTok,
llvm::StringRef FileName,
bool IsAngled,
CharSourceRange FilenameRange,
const FileEntry *File,
llvm::StringRef SearchPath,
llvm::StringRef RelativePath,
const Module *Imported) override
{
if( File == nullptr ) return;
SourceManager& SM = PP.getSourceManager();
const FileEntry* pFromFile = SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(HashLoc)));
if( pFromFile == nullptr ) return;
const auto h = hash()(File->getName());
const auto p = hash()(pFromFile->getName());
{
if( m_includes.find(h) == m_includes.end() )
{
m_includes.insert(::std::make_pair(h, header(File->getName(), IsAngled)));
}
auto it = m_includes.find(p);
if( it == m_includes.end() )
{
m_root = p;
m_includes.insert(::std::make_pair(p, header(pFromFile->getName(), false)));
}
if( it != m_includes.end() )
{
it->second.include.push_back(h);
}
}
if( !IsAngled )
{
auto it = m_depends.find(h);
if( it != m_depends.end() )
{
it->second.push_back(p);
}
else
{
hash_list a;
a.push_back(p);
m_depends.insert(::std::make_pair(h, a));
}
}
#if 0
errs() << "InclusionDirective : ";
if (File) {
if (IsAngled) errs() << "<" << File->getName() << ">\n";
else errs() << "\"" << File->getName() << "\"\n";
} else {
errs() << "not found file ";
if (IsAngled) errs() << "<" << FileName << ">\n";
else errs() << "\"" << FileName << "\"\n";
}
#endif
}
};
class ExampleASTConsumer : public ASTConsumer {
private:
public:
explicit ExampleASTConsumer(CompilerInstance *CI) {
// vvZbT̃R[obNo^
Preprocessor &PP = CI->getPreprocessor();
PP.addPPCallbacks(llvm::make_unique<cincluder>(PP, "test.dot"));
//AttachDependencyGraphGen(PP, "test.dot", "");
}
};
class ExampleFrontendAction : public SyntaxOnlyAction /*ASTFrontendAction*/ {
public:
virtual std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef file) {
return llvm::make_unique<ExampleASTConsumer>(&CI); // pass CI pointer to ASTConsumer
}
};
namespace
{
static cl::OptionCategory CincluderCategory("cincluder");
static cl::opt<::std::string> DotFile("dot", "output dot file", cl::cat(CincluderCategory));
}
int main(int argc, const char** argv)
{
CommonOptionsParser op(argc, argv, CincluderCategory);
ClangTool Tool(op.getCompilations(), op.getSourcePathList());
return Tool.run(newFrontendActionFactory<ExampleFrontendAction>().get());
}
<commit_msg>use dot option<commit_after>#pragma warning(push)
#pragma warning(disable:4996)
#pragma warning(disable:4244)
#pragma warning(disable:4291)
#pragma warning(disable:4146)
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/GraphWriter.h"
#pragma warning(pop)
#include <functional>
using namespace std;
using namespace clang;
using namespace clang::tooling;
using namespace llvm;
// ***************************************************************************
// vvZbT̃R[obN
// ***************************************************************************
class cincluder : public PPCallbacks {
private:
Preprocessor &PP;
typedef ::std::hash< ::std::string > hash;
typedef ::std::list< hash::result_type > hash_list;
struct header
{
header() : angled(false) {}
header(const ::std::string& n, bool angled_) : name(n), angled(angled_) {}
::std::string name;
bool angled;
hash_list include;
};
typedef ::std::map< hash::result_type, header > Map;
typedef ::std::map< hash::result_type, hash_list > Depend;
Map m_includes;
Depend m_depends;
hash::result_type m_root;
::std::string m_output;
public:
cincluder(Preprocessor &pp) : PP(pp) {}
cincluder(Preprocessor &pp, const ::std::string& output) : PP(pp), m_output(output) {}
const header& getHeader(hash::result_type h)
{
return m_includes[h];
}
::std::string getFilePath(hash::result_type h)
{
return m_includes[h].name;
}
::std::string getFileName(hash::result_type h)
{
::std::string path = getFilePath(h);
size_t dpos1 = path.rfind('\\');
size_t dpos2 = path.rfind('/');
if( dpos1 == ::std::string::npos ) dpos1 = 0;
if( dpos2 == ::std::string::npos ) dpos2 = 0;
const size_t dpos = (::std::max)(dpos1, dpos2) + 1;
return path.substr( dpos );
}
::std::string getFileName(const header& h)
{
::std::string path = h.name;
size_t dpos1 = path.rfind('\\');
size_t dpos2 = path.rfind('/');
if( dpos1 == ::std::string::npos ) dpos1 = 0;
if( dpos2 == ::std::string::npos ) dpos2 = 0;
const size_t dpos = (::std::max)(dpos1, dpos2) + 1;
return path.substr(dpos);
}
void printRoot(hash::result_type h, int indent, bool expand)
{
if( indent > 2 ) return;
for( int i = 0; i < indent; ++i ) errs() << " ";
if( expand ) errs() << "+ ";
else errs() << " ";
errs() << getFileName(h) << "\n";
if( m_depends.find(h) != m_depends.end() )
{
auto depend = m_depends[h];
if( depend.size() > 1 ) ++indent;
for( auto d : depend )
{
printRoot(d, indent, (depend.size() > 1));
}
}
}
void report()
{
for( auto h : m_depends )
{
if( h.second.size() > 1 )
{
errs() << getFileName(h.first) << " is already include by \n";
for( auto d : h.second )
{
printRoot(d, 1, true);
}
}
}
}
void writeID(raw_ostream& OS, hash::result_type h)
{
OS << "header_";
OS.write_hex(h);
}
void dot()
{
if( m_output.empty() ) return;
std::error_code EC;
llvm::raw_fd_ostream OS(m_output, EC, llvm::sys::fs::F_Text);
if( EC )
{
PP.getDiagnostics().Report(diag::err_fe_error_opening) << m_output
<< EC.message();
return;
}
const char* endl = "\n";
OS << "digraph \"dependencies\" {" << endl;
for( auto inc : m_includes )
{
writeID(OS, inc.first);
OS << " [ shape=\"box\", label=\"";
OS << DOT::EscapeString(getFileName(inc.second));
OS << "\"];" << endl;
}
for( auto h : m_depends )
{
for(auto depend : h.second)
{
writeID(OS, h.first);
OS << " -> ";
writeID(OS, depend);
OS << endl;
}
}
OS << "}" << endl;
}
void EndOfMainFile() override
{
report();
dot();
}
void InclusionDirective(SourceLocation HashLoc,
const Token &IncludeTok,
llvm::StringRef FileName,
bool IsAngled,
CharSourceRange FilenameRange,
const FileEntry *File,
llvm::StringRef SearchPath,
llvm::StringRef RelativePath,
const Module *Imported) override
{
if( File == nullptr ) return;
SourceManager& SM = PP.getSourceManager();
const FileEntry* pFromFile = SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(HashLoc)));
if( pFromFile == nullptr ) return;
const auto h = hash()(File->getName());
const auto p = hash()(pFromFile->getName());
{
if( m_includes.find(h) == m_includes.end() )
{
m_includes.insert(::std::make_pair(h, header(File->getName(), IsAngled)));
}
auto it = m_includes.find(p);
if( it == m_includes.end() )
{
m_root = p;
m_includes.insert(::std::make_pair(p, header(pFromFile->getName(), false)));
}
if( it != m_includes.end() )
{
it->second.include.push_back(h);
}
}
if( !IsAngled )
{
auto it = m_depends.find(h);
if( it != m_depends.end() )
{
it->second.push_back(p);
}
else
{
hash_list a;
a.push_back(p);
m_depends.insert(::std::make_pair(h, a));
}
}
#if 0
errs() << "InclusionDirective : ";
if (File) {
if (IsAngled) errs() << "<" << File->getName() << ">\n";
else errs() << "\"" << File->getName() << "\"\n";
} else {
errs() << "not found file ";
if (IsAngled) errs() << "<" << FileName << ">\n";
else errs() << "\"" << FileName << "\"\n";
}
#endif
}
};
namespace
{
static cl::OptionCategory CincluderCategory("cincluder");
static cl::opt<::std::string> DotFile("dot", "output dot file", cl::cat(CincluderCategory));
}
class ExampleASTConsumer : public ASTConsumer {
private:
public:
explicit ExampleASTConsumer(CompilerInstance *CI) {
// vvZbT̃R[obNo^
Preprocessor &PP = CI->getPreprocessor();
PP.addPPCallbacks(llvm::make_unique<cincluder>(PP, DotFile));
//AttachDependencyGraphGen(PP, "test.dot", "");
}
};
class ExampleFrontendAction : public SyntaxOnlyAction /*ASTFrontendAction*/ {
public:
virtual std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef file) {
return llvm::make_unique<ExampleASTConsumer>(&CI); // pass CI pointer to ASTConsumer
}
};
int main(int argc, const char** argv)
{
CommonOptionsParser op(argc, argv, CincluderCategory);
ClangTool Tool(op.getCompilations(), op.getSourcePathList());
return Tool.run(newFrontendActionFactory<ExampleFrontendAction>().get());
}
<|endoftext|> |
<commit_before>#include "MainScreen.hpp"
#include "../Util/WarnGuard.hpp"
WARN_GUARD_ON
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "../Graphics/Scene/SceneLoader.hpp"
WARN_GUARD_OFF
#include "../Util/FileLoad.hpp"
#include "../Graphics/Image/ImageLoader.hpp"
#include "../Graphics/Scene/SceneFactory.hpp"
// BufferType for the files loaded
using BufferType = std::vector<std::uint8_t>;
void MainScreen::onInit(ScreenContext& sc)
{
// Store engine ref
mEngine = sc.GetEngine();
// Store file data cache ref
mFileDataCache = sc.GetFileDataCache();
// Cube rotation state
mRotationData.degreesInc = 0.05f;
mRotationData.rotating = false;
// Camera initial position
mCamera.SetPos(glm::vec3(0, 0, 8));
// Create world objects
SetupWorld();
// Create world lights
SetupLights();
// Cam shouldn't follow character initially
mFollowingCharacter = false;
// Initial choosen moving light
mMovingLightIndex = 0;
// Init character
mCharacter.Init(&mEngine->GetWindow(), mScene.get());
// Pass the current scene to renderer
mEngine->GetRenderer().SetScene(mScene.get());
// Load the skybox
mSkybox = std::make_unique<Skybox>();
ImageLoader imLoader;
mSkybox->Load(
{
{ Cubemap::Target::Right, imLoader.Load(*(*mFileDataCache)["ext/Assets/Textures/Skybox/Bluesky/right.jpg"], "jpg") },
{ Cubemap::Target::Left, imLoader.Load(*(*mFileDataCache)["ext/Assets/Textures/Skybox/Bluesky/left.jpg"], "jpg") },
{ Cubemap::Target::Top, imLoader.Load(*(*mFileDataCache)["ext/Assets/Textures/Skybox/Bluesky/top.jpg"], "jpg") },
{ Cubemap::Target::Bottom, imLoader.Load(*(*mFileDataCache)["ext/Assets/Textures/Skybox/Bluesky/bottom.jpg"],"jpg") },
{ Cubemap::Target::Back, imLoader.Load(*(*mFileDataCache)["ext/Assets/Textures/Skybox/Bluesky/back.jpg"], "jpg") },
{ Cubemap::Target::Front, imLoader.Load(*(*mFileDataCache)["ext/Assets/Textures/Skybox/Bluesky/front.jpg"], "jpg") }
}
);
// Do not show AABBs by default
mShowAABBs = false;
}
void MainScreen::SetupWorld()
{
// Load sample scene file
std::string sceneFile= "ext/Scenes/scene.json";
auto sceneFileData = FileLoad<BufferType>(sceneFile);
if(!sceneFileData)
throw std::runtime_error("Couldn't load file (" + sceneFile+ ")");
SceneLoader sceneLoader;
SceneFile sf = sceneLoader.Load(*sceneFileData);
(void) sf;
SceneFactory factory(
&mEngine->GetTextureStore(),
&mEngine->GetModelStore(),
&mEngine->GetMaterialStore(),
mFileDataCache);
mScene = std::move(factory.CreateFromSceneFile(sf));
// Set positions for cubes
SceneNode* node;
std::vector<glm::vec3> cubePositions = {
glm::vec3( 0.0f, 0.0f, 0.0f),
glm::vec3( 4.0f, 10.0f, -20.0f),
glm::vec3(-3.0f, -4.4f, - 5.0f),
glm::vec3(-7.6f, -4.0f, -14.0f),
glm::vec3( 4.4f, -3.5f, - 4.0f),
glm::vec3(-3.4f, 6.0f, -15.0f),
glm::vec3( 2.6f, -4.0f, -17.0f),
glm::vec3( 4.0f, 3.0f, - 5.0f),
glm::vec3( 3.0f, 0.4f, -12.0f),
glm::vec3(-3.5f, 2.0f, - 3.0f)
};
for(std::size_t i = 0; i < cubePositions.size(); ++i)
{
const auto& pos = cubePositions[i];
const std::string name = "cube" + std::to_string(i);
node = mScene->FindNodeByUuid(name);
mScene->Move(node, pos);
mScene->Scale(node, glm::vec3(2.0f));
mScene->Rotate(node, RotationAxis::X, 20.0f * i);
mScene->Rotate(node, RotationAxis::Y, 7.0f * i);
mScene->Rotate(node, RotationAxis::Z, 10.0f * i);
}
}
void UpdateLight(Renderer& renderer, Scene* const scene, int index, const glm::vec3& move)
{
auto& lights = scene->GetLights();
// Get light
SceneNode* curLight = lights[index];
// Move light in scene
scene->Move(curLight, move);
// Move light in renderer
auto trans = curLight->GetTransformation().GetInterpolated(1.0f);
renderer.GetLights().pointLights[index].position = glm::vec3(trans[3].x, trans[3].y, trans[3].z);
};
void MainScreen::SetupLights()
{
// Setup scene lights
Lights& lights = mEngine->GetRenderer().GetLights();
// Add directional light
DirLight dirLight;
dirLight.direction = glm::vec3(-0.3f, -0.5f, -0.5f);
dirLight.properties.ambient = glm::vec3(0.05f, 0.05f, 0.05f);
dirLight.properties.diffuse = glm::vec3(0.4f, 0.4f, 0.4f);
dirLight.properties.specular = glm::vec3(0.5f, 0.5f, 0.5f);
lights.dirLights.push_back(dirLight);
// Add point lights
for (int i = 0; i < 2; ++i)
{
PointLight pointLight;
pointLight.properties.ambient = glm::vec3(0.2f, 0.2f, 0.2f);
pointLight.properties.diffuse = glm::vec3(0.5f, 0.5f, 0.5f);
pointLight.properties.specular = glm::vec3(1.0f, 1.0f, 1.0f);
pointLight.attProps.constant = 1.0f;
pointLight.attProps.linear = 0.09f;
pointLight.attProps.quadratic = 0.032f;
lights.pointLights.push_back(pointLight);
}
// Update lights once to take their initial position
for (int i = 0; i < 2; i++)
UpdateLight(mEngine->GetRenderer(), mScene.get(), i, glm::vec3(0));
}
std::vector<Camera::MoveDirection> MainScreen::CameraMoveDirections()
{
auto& window = mEngine->GetWindow();
std::vector<Camera::MoveDirection> mds;
if(window.IsKeyPressed(Key::W))
mds.push_back(Camera::MoveDirection::Forward);
if(window.IsKeyPressed(Key::A))
mds.push_back(Camera::MoveDirection::Left);
if(window.IsKeyPressed(Key::S))
mds.push_back(Camera::MoveDirection::BackWard);
if(window.IsKeyPressed(Key::D))
mds.push_back(Camera::MoveDirection::Right);
return mds;
}
std::tuple<float, float> MainScreen::CameraLookOffset()
{
auto& window = mEngine->GetWindow();
std::tuple<double, double> curDiff = window.GetCursorDiff();
return std::make_tuple(
static_cast<float>(std::get<0>(curDiff)),
static_cast<float>(std::get<1>(curDiff))
);
}
void MainScreen::onKey(Key k, KeyAction ka)
{
if(k == Key::B && ka == KeyAction::Release)
mShowAABBs = !mShowAABBs;
if(k == Key::R && ka == KeyAction::Release)
mRotationData.rotating = !mRotationData.rotating;
if(k == Key::F && ka == KeyAction::Release)
mFollowingCharacter = !mFollowingCharacter;
if(k == Key::L && ka == KeyAction::Release)
{
if (mMovingLightIndex == 0)
mMovingLightIndex = 1;
else if (mMovingLightIndex == 1)
mMovingLightIndex = 0;
}
if(k == Key::F2)
mOnNextScreenCb();
}
void MainScreen::onUpdate(float dt)
{
(void) dt;
// Update the core
mEngine->Update(dt);
auto& scene = mScene;
auto& window = mEngine->GetWindow();
auto& renderer = mEngine->GetRenderer();
// Update interpolation variables
for (auto& obj : mScene->GetNodes())
{
Transform& trans = obj.second->GetTransformation();
trans.Update();
AABB& aabb = obj.second->GetAABB();
aabb.Update(trans.GetPosition(), trans.GetScale(), trans.GetRotation());
}
// Update camera euler angles
if (window.MouseGrabEnabled())
mCamera.Look(CameraLookOffset());
if (mFollowingCharacter)
{
// Update character
mCharacter.Update();
// Move Camera following character
auto trans = mCharacter.GetCharacterNode()->GetTransformation().GetInterpolated(1.0f);
mCamera.SetPos(glm::vec3(trans[3].x, trans[3].y + 4, trans[3].z + 4));
}
else
{
// Update camera position
mCamera.Move(CameraMoveDirections());
}
// Update the camera matrix
mCamera.Update();
// Update light position
//auto updLight = std::bind(updateLight, renderer, mScene.get(), std::placeholders::_1);
auto updLight = [this, &renderer, &scene](const glm::vec3& move)
{
UpdateLight(renderer, scene.get(), mMovingLightIndex, move);
};
float increase = 0.7f;
if(window.IsKeyPressed(Key::Kp8))
updLight(glm::vec3(0.0f, increase, 0.0f));
if(window.IsKeyPressed(Key::Kp4))
updLight(glm::vec3(-increase, 0.0f, 0.0f));
if(window.IsKeyPressed(Key::Kp2))
updLight(glm::vec3(0.0f, -increase, 0.0f));
if(window.IsKeyPressed(Key::Kp6))
updLight(glm::vec3(increase, 0.0f, 0.0f));
if(window.IsKeyPressed(Key::Kp5))
updLight(glm::vec3(0.0f, 0.0f, -increase));
if(window.IsKeyPressed(Key::Kp0))
updLight(glm::vec3(0.0f, 0.0f, increase));
// Update cubes' rotations
if (mRotationData.rotating)
{
for(auto& p : scene->GetNodes())
{
if (p.first.substr(0, 4) == "cube")
scene->Rotate(p.first, RotationAxis::Y, mRotationData.degreesInc);
}
}
// Update physics
UpdatePhysics(dt);
}
void MainScreen::UpdatePhysics(float dt)
{
(void) dt;
auto& scene = mScene;
SceneNode* teapot = mScene->FindNodeByUuid("teapot");
for(auto& p : scene->GetNodes())
{
SceneNode* cur = p.second.get();
if(cur->GetUUID() == teapot->GetUUID())
continue;
if(Intersects(teapot->GetAABB(), cur->GetAABB()))
scene->Move(teapot, CalcCollisionResponce(teapot->GetAABB(), cur->GetAABB()));
}
}
void MainScreen::onRender(float interpolation)
{
// Get the view matrix and pass it to the renderer
glm::mat4 view = mCamera.InterpolatedView(interpolation);
// Render
mEngine->GetRenderer().SetView(view);
mEngine->GetRenderer().Render(interpolation);
// Render the AABBs if enabled
if (mShowAABBs)
{
AABBRenderer& aabbRenderer = mEngine->GetAABBRenderer();
aabbRenderer.SetView(view);
aabbRenderer.SetScene(mScene.get());
aabbRenderer.Render(interpolation);
}
// Render the skybox
if (mSkybox)
mSkybox->Render(mEngine->GetRenderer().GetProjection(), view);
// Render sample text
mEngine->GetTextRenderer().RenderText("ScaryBox Studios", 10, 10, glm::vec3(1.0f, 0.5f, 0.3f), "visitor");
}
void MainScreen::onShutdown()
{
}
void MainScreen::SetOnNextScreenCb(OnNextScreenCb cb)
{
mOnNextScreenCb = cb;
}
<commit_msg>MainScreen must not call onNextScreen callback twice<commit_after>#include "MainScreen.hpp"
#include "../Util/WarnGuard.hpp"
WARN_GUARD_ON
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "../Graphics/Scene/SceneLoader.hpp"
WARN_GUARD_OFF
#include "../Util/FileLoad.hpp"
#include "../Graphics/Image/ImageLoader.hpp"
#include "../Graphics/Scene/SceneFactory.hpp"
// BufferType for the files loaded
using BufferType = std::vector<std::uint8_t>;
void MainScreen::onInit(ScreenContext& sc)
{
// Store engine ref
mEngine = sc.GetEngine();
// Store file data cache ref
mFileDataCache = sc.GetFileDataCache();
// Cube rotation state
mRotationData.degreesInc = 0.05f;
mRotationData.rotating = false;
// Camera initial position
mCamera.SetPos(glm::vec3(0, 0, 8));
// Create world objects
SetupWorld();
// Create world lights
SetupLights();
// Cam shouldn't follow character initially
mFollowingCharacter = false;
// Initial choosen moving light
mMovingLightIndex = 0;
// Init character
mCharacter.Init(&mEngine->GetWindow(), mScene.get());
// Pass the current scene to renderer
mEngine->GetRenderer().SetScene(mScene.get());
// Load the skybox
mSkybox = std::make_unique<Skybox>();
ImageLoader imLoader;
mSkybox->Load(
{
{ Cubemap::Target::Right, imLoader.Load(*(*mFileDataCache)["ext/Assets/Textures/Skybox/Bluesky/right.jpg"], "jpg") },
{ Cubemap::Target::Left, imLoader.Load(*(*mFileDataCache)["ext/Assets/Textures/Skybox/Bluesky/left.jpg"], "jpg") },
{ Cubemap::Target::Top, imLoader.Load(*(*mFileDataCache)["ext/Assets/Textures/Skybox/Bluesky/top.jpg"], "jpg") },
{ Cubemap::Target::Bottom, imLoader.Load(*(*mFileDataCache)["ext/Assets/Textures/Skybox/Bluesky/bottom.jpg"],"jpg") },
{ Cubemap::Target::Back, imLoader.Load(*(*mFileDataCache)["ext/Assets/Textures/Skybox/Bluesky/back.jpg"], "jpg") },
{ Cubemap::Target::Front, imLoader.Load(*(*mFileDataCache)["ext/Assets/Textures/Skybox/Bluesky/front.jpg"], "jpg") }
}
);
// Do not show AABBs by default
mShowAABBs = false;
}
void MainScreen::SetupWorld()
{
// Load sample scene file
std::string sceneFile= "ext/Scenes/scene.json";
auto sceneFileData = FileLoad<BufferType>(sceneFile);
if(!sceneFileData)
throw std::runtime_error("Couldn't load file (" + sceneFile+ ")");
SceneLoader sceneLoader;
SceneFile sf = sceneLoader.Load(*sceneFileData);
(void) sf;
SceneFactory factory(
&mEngine->GetTextureStore(),
&mEngine->GetModelStore(),
&mEngine->GetMaterialStore(),
mFileDataCache);
mScene = std::move(factory.CreateFromSceneFile(sf));
// Set positions for cubes
SceneNode* node;
std::vector<glm::vec3> cubePositions = {
glm::vec3( 0.0f, 0.0f, 0.0f),
glm::vec3( 4.0f, 10.0f, -20.0f),
glm::vec3(-3.0f, -4.4f, - 5.0f),
glm::vec3(-7.6f, -4.0f, -14.0f),
glm::vec3( 4.4f, -3.5f, - 4.0f),
glm::vec3(-3.4f, 6.0f, -15.0f),
glm::vec3( 2.6f, -4.0f, -17.0f),
glm::vec3( 4.0f, 3.0f, - 5.0f),
glm::vec3( 3.0f, 0.4f, -12.0f),
glm::vec3(-3.5f, 2.0f, - 3.0f)
};
for(std::size_t i = 0; i < cubePositions.size(); ++i)
{
const auto& pos = cubePositions[i];
const std::string name = "cube" + std::to_string(i);
node = mScene->FindNodeByUuid(name);
mScene->Move(node, pos);
mScene->Scale(node, glm::vec3(2.0f));
mScene->Rotate(node, RotationAxis::X, 20.0f * i);
mScene->Rotate(node, RotationAxis::Y, 7.0f * i);
mScene->Rotate(node, RotationAxis::Z, 10.0f * i);
}
}
void UpdateLight(Renderer& renderer, Scene* const scene, int index, const glm::vec3& move)
{
auto& lights = scene->GetLights();
// Get light
SceneNode* curLight = lights[index];
// Move light in scene
scene->Move(curLight, move);
// Move light in renderer
auto trans = curLight->GetTransformation().GetInterpolated(1.0f);
renderer.GetLights().pointLights[index].position = glm::vec3(trans[3].x, trans[3].y, trans[3].z);
};
void MainScreen::SetupLights()
{
// Setup scene lights
Lights& lights = mEngine->GetRenderer().GetLights();
// Add directional light
DirLight dirLight;
dirLight.direction = glm::vec3(-0.3f, -0.5f, -0.5f);
dirLight.properties.ambient = glm::vec3(0.05f, 0.05f, 0.05f);
dirLight.properties.diffuse = glm::vec3(0.4f, 0.4f, 0.4f);
dirLight.properties.specular = glm::vec3(0.5f, 0.5f, 0.5f);
lights.dirLights.push_back(dirLight);
// Add point lights
for (int i = 0; i < 2; ++i)
{
PointLight pointLight;
pointLight.properties.ambient = glm::vec3(0.2f, 0.2f, 0.2f);
pointLight.properties.diffuse = glm::vec3(0.5f, 0.5f, 0.5f);
pointLight.properties.specular = glm::vec3(1.0f, 1.0f, 1.0f);
pointLight.attProps.constant = 1.0f;
pointLight.attProps.linear = 0.09f;
pointLight.attProps.quadratic = 0.032f;
lights.pointLights.push_back(pointLight);
}
// Update lights once to take their initial position
for (int i = 0; i < 2; i++)
UpdateLight(mEngine->GetRenderer(), mScene.get(), i, glm::vec3(0));
}
std::vector<Camera::MoveDirection> MainScreen::CameraMoveDirections()
{
auto& window = mEngine->GetWindow();
std::vector<Camera::MoveDirection> mds;
if(window.IsKeyPressed(Key::W))
mds.push_back(Camera::MoveDirection::Forward);
if(window.IsKeyPressed(Key::A))
mds.push_back(Camera::MoveDirection::Left);
if(window.IsKeyPressed(Key::S))
mds.push_back(Camera::MoveDirection::BackWard);
if(window.IsKeyPressed(Key::D))
mds.push_back(Camera::MoveDirection::Right);
return mds;
}
std::tuple<float, float> MainScreen::CameraLookOffset()
{
auto& window = mEngine->GetWindow();
std::tuple<double, double> curDiff = window.GetCursorDiff();
return std::make_tuple(
static_cast<float>(std::get<0>(curDiff)),
static_cast<float>(std::get<1>(curDiff))
);
}
void MainScreen::onKey(Key k, KeyAction ka)
{
if(k == Key::B && ka == KeyAction::Release)
mShowAABBs = !mShowAABBs;
if(k == Key::R && ka == KeyAction::Release)
mRotationData.rotating = !mRotationData.rotating;
if(k == Key::F && ka == KeyAction::Release)
mFollowingCharacter = !mFollowingCharacter;
if(k == Key::L && ka == KeyAction::Release)
{
if (mMovingLightIndex == 0)
mMovingLightIndex = 1;
else if (mMovingLightIndex == 1)
mMovingLightIndex = 0;
}
if(k == Key::F2 && ka == KeyAction::Release)
mOnNextScreenCb();
}
void MainScreen::onUpdate(float dt)
{
(void) dt;
// Update the core
mEngine->Update(dt);
auto& scene = mScene;
auto& window = mEngine->GetWindow();
auto& renderer = mEngine->GetRenderer();
// Update interpolation variables
for (auto& obj : mScene->GetNodes())
{
Transform& trans = obj.second->GetTransformation();
trans.Update();
AABB& aabb = obj.second->GetAABB();
aabb.Update(trans.GetPosition(), trans.GetScale(), trans.GetRotation());
}
// Update camera euler angles
if (window.MouseGrabEnabled())
mCamera.Look(CameraLookOffset());
if (mFollowingCharacter)
{
// Update character
mCharacter.Update();
// Move Camera following character
auto trans = mCharacter.GetCharacterNode()->GetTransformation().GetInterpolated(1.0f);
mCamera.SetPos(glm::vec3(trans[3].x, trans[3].y + 4, trans[3].z + 4));
}
else
{
// Update camera position
mCamera.Move(CameraMoveDirections());
}
// Update the camera matrix
mCamera.Update();
// Update light position
//auto updLight = std::bind(updateLight, renderer, mScene.get(), std::placeholders::_1);
auto updLight = [this, &renderer, &scene](const glm::vec3& move)
{
UpdateLight(renderer, scene.get(), mMovingLightIndex, move);
};
float increase = 0.7f;
if(window.IsKeyPressed(Key::Kp8))
updLight(glm::vec3(0.0f, increase, 0.0f));
if(window.IsKeyPressed(Key::Kp4))
updLight(glm::vec3(-increase, 0.0f, 0.0f));
if(window.IsKeyPressed(Key::Kp2))
updLight(glm::vec3(0.0f, -increase, 0.0f));
if(window.IsKeyPressed(Key::Kp6))
updLight(glm::vec3(increase, 0.0f, 0.0f));
if(window.IsKeyPressed(Key::Kp5))
updLight(glm::vec3(0.0f, 0.0f, -increase));
if(window.IsKeyPressed(Key::Kp0))
updLight(glm::vec3(0.0f, 0.0f, increase));
// Update cubes' rotations
if (mRotationData.rotating)
{
for(auto& p : scene->GetNodes())
{
if (p.first.substr(0, 4) == "cube")
scene->Rotate(p.first, RotationAxis::Y, mRotationData.degreesInc);
}
}
// Update physics
UpdatePhysics(dt);
}
void MainScreen::UpdatePhysics(float dt)
{
(void) dt;
auto& scene = mScene;
SceneNode* teapot = mScene->FindNodeByUuid("teapot");
for(auto& p : scene->GetNodes())
{
SceneNode* cur = p.second.get();
if(cur->GetUUID() == teapot->GetUUID())
continue;
if(Intersects(teapot->GetAABB(), cur->GetAABB()))
scene->Move(teapot, CalcCollisionResponce(teapot->GetAABB(), cur->GetAABB()));
}
}
void MainScreen::onRender(float interpolation)
{
// Get the view matrix and pass it to the renderer
glm::mat4 view = mCamera.InterpolatedView(interpolation);
// Render
mEngine->GetRenderer().SetView(view);
mEngine->GetRenderer().Render(interpolation);
// Render the AABBs if enabled
if (mShowAABBs)
{
AABBRenderer& aabbRenderer = mEngine->GetAABBRenderer();
aabbRenderer.SetView(view);
aabbRenderer.SetScene(mScene.get());
aabbRenderer.Render(interpolation);
}
// Render the skybox
if (mSkybox)
mSkybox->Render(mEngine->GetRenderer().GetProjection(), view);
// Render sample text
mEngine->GetTextRenderer().RenderText("ScaryBox Studios", 10, 10, glm::vec3(1.0f, 0.5f, 0.3f), "visitor");
}
void MainScreen::onShutdown()
{
}
void MainScreen::SetOnNextScreenCb(OnNextScreenCb cb)
{
mOnNextScreenCb = cb;
}
<|endoftext|> |
<commit_before>// BESAsciiTransmit.cc
// This file is part of bes, A C++ back-end server implementation framework
// for the OPeNDAP Data Access Protocol.
// Copyright (c) 2004,2005 University Corporation for Atmospheric Research
// Author: Patrick West <[email protected]> and Jose Garcia <[email protected]>
//
// 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// You can contact University Corporation for Atmospheric Research at
// 3080 Center Green Drive, Boulder, CO 80301
// (c) COPYRIGHT University Corporation for Atmospheric Research 2004-2005
// Please read the full copyright statement in the file COPYRIGHT_UCAR.
//
// Authors:
// pwest Patrick West <[email protected]>
// jgarcia Jose Garcia <[email protected]>
#include <memory>
#include <BaseType.h>
#include <Sequence.h>
#include <ConstraintEvaluator.h>
#include <D4Group.h>
#include <DMR.h>
//#include <D4CEDriver.h>
#include <D4ConstraintEvaluator.h>
#include <crc.h>
#include <InternalErr.h>
#include <util.h>
#include <escaping.h>
#include <mime_util.h>
#include <BESDapNames.h>
#include <BESDataNames.h>
#include <BESDapTransmit.h>
#include <BESContainer.h>
#include <BESDataDDSResponse.h>
#include <BESDMRResponse.h>
#include <BESDapResponseBuilder.h>
#include <BESError.h>
#include <BESDapError.h>
#include <BESForbiddenError.h>
#include <BESInternalFatalError.h>
#include <BESDebug.h>
#include "BESAsciiTransmit.h"
#include "get_ascii.h"
#include "get_ascii_dap4.h"
using namespace dap_asciival;
BESAsciiTransmit::BESAsciiTransmit() :
BESBasicTransmitter()
{
add_method(DATA_SERVICE, BESAsciiTransmit::send_basic_ascii);
add_method(DAP4DATA_SERVICE, BESAsciiTransmit::send_dap4_csv);
}
// This version of send_basic_ascii() should work for server functions,
// including ones that are used in combination with a selection expression.
// This functionality has not yet been added to the DAP4 version of the
// method, however.
//
// I have some questions regarding how caching will work in this function.
//
// Since this 'transmitter' pattern is pretty common in our code, I think
// it would be good if BESDapResponseBuilder supported it with a set of
// methods that could be used to implement the logic uniformly.
void BESAsciiTransmit::send_basic_ascii(BESResponseObject *obj, BESDataHandlerInterface &dhi)
{
BESDEBUG("ascii", "BESAsciiTransmit::send_base_ascii; modified" << endl);
BESDataDDSResponse *bdds = dynamic_cast<BESDataDDSResponse *>(obj);
if (!bdds) throw BESInternalFatalError("Expected a BESDataDDSResponse instance", __FILE__, __LINE__);
try { // Expanded try block so DAP all DAP errors are caught. ndp 12/23/2015
DataDDS *dds = bdds->get_dds();
ConstraintEvaluator &ce = bdds->get_ce();
dhi.first_container();
string constraint = www2id(dhi.data[POST_CONSTRAINT], "%", "%20%26");
BESDEBUG("ascii", "parsing constraint: " << constraint << endl);
BESDapResponseBuilder rb;
rb.split_ce(ce, constraint);
// If there are functions, parse them and eval.
// Use that DDS and parse the non-function ce
// Serialize using the second ce and the second dds
if (!rb.get_btp_func_ce().empty()) {
BESDEBUG("ascii", "BESAsciiTransmit::send_base_ascii - Found function(s) in CE: " << rb.get_btp_func_ce() << endl);
// Define a local ce evaluator so that the clause(s) from the function parse
// won't get treated like selection clauses later on when serialize is called
// on the DDS (fdds)
ConstraintEvaluator func_eval;
// FIXME Does caching work outside of the DAP module?
#if 0
if (responseCache()) {
BESDEBUG("ascii", "BESAsciiTransmit::send_base_ascii - Using the cache for the server function CE" << endl);
fdds = rb.responseCache()->cache_dataset(dds, get_btp_func_ce(), this, &func_eval, cache_token);
}
else {
BESDEBUG("ascii", "BESAsciiTransmit::send_base_ascii - Cache not found; (re)calculating" << endl);
func_eval.parse_constraint(get_btp_func_ce(), dds);
fdds = func_eval.eval_function_clauses(dds);
}
#endif
func_eval.parse_constraint(rb.get_btp_func_ce(), *dds);
DataDDS *fdds = func_eval.eval_function_clauses(*dds);
// Server functions might mark variables to use their read()
// methods. Clear that so the CE in d_dap2ce will control what is
// sent. If that is empty (there was only a function call) all
// of the variables in the intermediate DDS (i.e., the function
// result) will be sent.
fdds->mark_all(false);
ce.parse_constraint(rb.get_ce(), *fdds);
fdds->tag_nested_sequences(); // Tag Sequences as Parent or Leaf node.
int response_size_limit = dds->get_response_limit(); // use the original DDS
if (response_size_limit != 0 && fdds->get_request_size(true) > response_size_limit) {
string msg = "The Request for " + long_to_string(fdds->get_request_size(true) / 1024)
+ "KB is too large; requests for this user are limited to "
+ long_to_string(response_size_limit / 1024) + "KB.";
throw Error(msg);
}
// Now we have the correct values in fdds, so set the BESResponseObject so
// that it will reference that. At a minimum, its dtor will free the object.
// So, delete the initial DataDDS*
bdds->set_dds(fdds);
delete dds;
dds = fdds;
// FIXME Caching broken outside of the DAP module?
#if 0
if (!store_dap2_result(data_stream, dds, eval)) {
serialize_dap2_data_dds(data_stream, *fdds, eval, true /* was 'false'. jhrg 3/10/15 */);
}
if (responseCache()) responseCache()->unlock_and_close(cache_token);
#endif
}
else {
BESDEBUG("ascii", "BESAsciiTransmit::send_base_ascii - Simple constraint" << endl);
ce.parse_constraint(rb.get_ce(), *dds); // Throws Error if the ce doesn't parse.
dds->tag_nested_sequences(); // Tag Sequences as Parent or Leaf node.
if (dds->get_response_limit() != 0 && dds->get_request_size(true) > dds->get_response_limit()) {
string msg = "The Request for " + long_to_string(dds->get_request_size(true) / 1024)
+ "KB is too large; requests for this user are limited to "
+ long_to_string(dds->get_response_limit() / 1024) + "KB.";
throw Error(msg);
}
// FIXME Caching...
#if 0
if (!store_dap2_result(data_stream, dds, eval)) {
serialize_dap2_data_dds(data_stream, dds, eval);
}
#endif
}
for (DDS::Vars_iter i = dds->var_begin(); i != dds->var_end(); i++) {
if ((*i)->send_p()) {
BESDEBUG("ascii", "BESAsciiTransmit::send_base_ascii; call to intern_data() for '" << (*i)->name() << "'" << endl);
(*i)->intern_data(ce, *dds);
}
}
// Now that we have constrained the DataDDS and read in the data,
// send it as ascii
DataDDS *ascii_dds = datadds_to_ascii_datadds(dds);
get_data_values_as_ascii(ascii_dds, dhi.get_output_stream());
dhi.get_output_stream() << flush;
delete ascii_dds;
}
catch (Error &e) {
throw BESDapError("Failed to get values as ascii: " + e.get_error_message(), false, e.get_error_code(), __FILE__, __LINE__);
}
catch (BESError &e) {
throw;
}
catch (...) {
throw BESInternalError("Failed to get values as ascii: Unknown exception caught", __FILE__, __LINE__);
}
}
/**
* Transmits DAP4 Data as Comma Separated Values
*/
void BESAsciiTransmit::send_dap4_csv(BESResponseObject *obj, BESDataHandlerInterface &dhi)
{
BESDEBUG("ascii", "BESAsciiTransmit::send_dap4_csv" << endl);
BESDMRResponse *bdmr = dynamic_cast<BESDMRResponse *>(obj);
if (!bdmr) throw BESInternalFatalError("Expected a BESDMRResponse instance.", __FILE__, __LINE__);
DMR *dmr = bdmr->get_dmr();
string dap4Constraint = www2id(dhi.data[DAP4_CONSTRAINT], "%", "%20%26");
string dap4Function = www2id(dhi.data[DAP4_FUNCTION], "%", "%20%26");
// Not sure we need this...
dhi.first_container();
try {
// Handle *functional* constraint expressions specially
// Use the D4FunctionDriver class and evaluate the functions, building
// an new DMR, then evaluate the D4CE in the context of that DMR.
// This might be coded as "if (there's a function) do this else process the CE".
// Or it might be coded as "if (there's a function) build the new DMR, then fall
// through and process the CE but on the new DMR". jhrg 9/3/14
if (!dap4Constraint.empty()) {
D4ConstraintEvaluator d4ce(dmr);
bool parse_ok = d4ce.parse(dap4Constraint);
if (!parse_ok) throw Error(malformed_expr, "Constraint Expression (" + d_dap4ce + ") failed to parse.");
}
else {
dmr->root()->set_send_p(true);
}
print_values_as_ascii(dmr, dhi.get_output_stream());
dhi.get_output_stream() << flush;
}
catch (Error &e) {
throw BESDapError("Failed to return values as ascii: " + e.get_error_message(), false, e.get_error_code(),__FILE__, __LINE__);
}
catch (BESError &e){
throw;
}
catch (...) {
throw BESInternalError("Failed to return values as ascii: Unknown exception caught", __FILE__, __LINE__);
}
BESDEBUG("ascii", "Done BESAsciiTransmit::send_dap4_csv" << endl);
}
<commit_msg>Copy pasta error<commit_after>// BESAsciiTransmit.cc
// This file is part of bes, A C++ back-end server implementation framework
// for the OPeNDAP Data Access Protocol.
// Copyright (c) 2004,2005 University Corporation for Atmospheric Research
// Author: Patrick West <[email protected]> and Jose Garcia <[email protected]>
//
// 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// You can contact University Corporation for Atmospheric Research at
// 3080 Center Green Drive, Boulder, CO 80301
// (c) COPYRIGHT University Corporation for Atmospheric Research 2004-2005
// Please read the full copyright statement in the file COPYRIGHT_UCAR.
//
// Authors:
// pwest Patrick West <[email protected]>
// jgarcia Jose Garcia <[email protected]>
#include <memory>
#include <BaseType.h>
#include <Sequence.h>
#include <ConstraintEvaluator.h>
#include <D4Group.h>
#include <DMR.h>
//#include <D4CEDriver.h>
#include <D4ConstraintEvaluator.h>
#include <crc.h>
#include <InternalErr.h>
#include <util.h>
#include <escaping.h>
#include <mime_util.h>
#include <BESDapNames.h>
#include <BESDataNames.h>
#include <BESDapTransmit.h>
#include <BESContainer.h>
#include <BESDataDDSResponse.h>
#include <BESDMRResponse.h>
#include <BESDapResponseBuilder.h>
#include <BESError.h>
#include <BESDapError.h>
#include <BESForbiddenError.h>
#include <BESInternalFatalError.h>
#include <BESDebug.h>
#include "BESAsciiTransmit.h"
#include "get_ascii.h"
#include "get_ascii_dap4.h"
using namespace dap_asciival;
BESAsciiTransmit::BESAsciiTransmit() :
BESBasicTransmitter()
{
add_method(DATA_SERVICE, BESAsciiTransmit::send_basic_ascii);
add_method(DAP4DATA_SERVICE, BESAsciiTransmit::send_dap4_csv);
}
// This version of send_basic_ascii() should work for server functions,
// including ones that are used in combination with a selection expression.
// This functionality has not yet been added to the DAP4 version of the
// method, however.
//
// I have some questions regarding how caching will work in this function.
//
// Since this 'transmitter' pattern is pretty common in our code, I think
// it would be good if BESDapResponseBuilder supported it with a set of
// methods that could be used to implement the logic uniformly.
void BESAsciiTransmit::send_basic_ascii(BESResponseObject *obj, BESDataHandlerInterface &dhi)
{
BESDEBUG("ascii", "BESAsciiTransmit::send_base_ascii; modified" << endl);
BESDataDDSResponse *bdds = dynamic_cast<BESDataDDSResponse *>(obj);
if (!bdds) throw BESInternalFatalError("Expected a BESDataDDSResponse instance", __FILE__, __LINE__);
try { // Expanded try block so DAP all DAP errors are caught. ndp 12/23/2015
DataDDS *dds = bdds->get_dds();
ConstraintEvaluator &ce = bdds->get_ce();
dhi.first_container();
string constraint = www2id(dhi.data[POST_CONSTRAINT], "%", "%20%26");
BESDEBUG("ascii", "parsing constraint: " << constraint << endl);
BESDapResponseBuilder rb;
rb.split_ce(ce, constraint);
// If there are functions, parse them and eval.
// Use that DDS and parse the non-function ce
// Serialize using the second ce and the second dds
if (!rb.get_btp_func_ce().empty()) {
BESDEBUG("ascii", "BESAsciiTransmit::send_base_ascii - Found function(s) in CE: " << rb.get_btp_func_ce() << endl);
// Define a local ce evaluator so that the clause(s) from the function parse
// won't get treated like selection clauses later on when serialize is called
// on the DDS (fdds)
ConstraintEvaluator func_eval;
// FIXME Does caching work outside of the DAP module?
#if 0
if (responseCache()) {
BESDEBUG("ascii", "BESAsciiTransmit::send_base_ascii - Using the cache for the server function CE" << endl);
fdds = rb.responseCache()->cache_dataset(dds, get_btp_func_ce(), this, &func_eval, cache_token);
}
else {
BESDEBUG("ascii", "BESAsciiTransmit::send_base_ascii - Cache not found; (re)calculating" << endl);
func_eval.parse_constraint(get_btp_func_ce(), dds);
fdds = func_eval.eval_function_clauses(dds);
}
#endif
func_eval.parse_constraint(rb.get_btp_func_ce(), *dds);
DataDDS *fdds = func_eval.eval_function_clauses(*dds);
// Server functions might mark variables to use their read()
// methods. Clear that so the CE in d_dap2ce will control what is
// sent. If that is empty (there was only a function call) all
// of the variables in the intermediate DDS (i.e., the function
// result) will be sent.
fdds->mark_all(false);
ce.parse_constraint(rb.get_ce(), *fdds);
fdds->tag_nested_sequences(); // Tag Sequences as Parent or Leaf node.
int response_size_limit = dds->get_response_limit(); // use the original DDS
if (response_size_limit != 0 && fdds->get_request_size(true) > response_size_limit) {
string msg = "The Request for " + long_to_string(fdds->get_request_size(true) / 1024)
+ "KB is too large; requests for this user are limited to "
+ long_to_string(response_size_limit / 1024) + "KB.";
throw Error(msg);
}
// Now we have the correct values in fdds, so set the BESResponseObject so
// that it will reference that. At a minimum, its dtor will free the object.
// So, delete the initial DataDDS*
bdds->set_dds(fdds);
delete dds;
dds = fdds;
// FIXME Caching broken outside of the DAP module?
#if 0
if (!store_dap2_result(data_stream, dds, eval)) {
serialize_dap2_data_dds(data_stream, *fdds, eval, true /* was 'false'. jhrg 3/10/15 */);
}
if (responseCache()) responseCache()->unlock_and_close(cache_token);
#endif
}
else {
BESDEBUG("ascii", "BESAsciiTransmit::send_base_ascii - Simple constraint" << endl);
ce.parse_constraint(rb.get_ce(), *dds); // Throws Error if the ce doesn't parse.
dds->tag_nested_sequences(); // Tag Sequences as Parent or Leaf node.
if (dds->get_response_limit() != 0 && dds->get_request_size(true) > dds->get_response_limit()) {
string msg = "The Request for " + long_to_string(dds->get_request_size(true) / 1024)
+ "KB is too large; requests for this user are limited to "
+ long_to_string(dds->get_response_limit() / 1024) + "KB.";
throw Error(msg);
}
// FIXME Caching...
#if 0
if (!store_dap2_result(data_stream, dds, eval)) {
serialize_dap2_data_dds(data_stream, dds, eval);
}
#endif
}
for (DDS::Vars_iter i = dds->var_begin(); i != dds->var_end(); i++) {
if ((*i)->send_p()) {
BESDEBUG("ascii", "BESAsciiTransmit::send_base_ascii; call to intern_data() for '" << (*i)->name() << "'" << endl);
(*i)->intern_data(ce, *dds);
}
}
// Now that we have constrained the DataDDS and read in the data,
// send it as ascii
DataDDS *ascii_dds = datadds_to_ascii_datadds(dds);
get_data_values_as_ascii(ascii_dds, dhi.get_output_stream());
dhi.get_output_stream() << flush;
delete ascii_dds;
}
catch (Error &e) {
throw BESDapError("Failed to get values as ascii: " + e.get_error_message(), false, e.get_error_code(), __FILE__, __LINE__);
}
catch (BESError &e) {
throw;
}
catch (...) {
throw BESInternalError("Failed to get values as ascii: Unknown exception caught", __FILE__, __LINE__);
}
}
/**
* Transmits DAP4 Data as Comma Separated Values
*/
void BESAsciiTransmit::send_dap4_csv(BESResponseObject *obj, BESDataHandlerInterface &dhi)
{
BESDEBUG("ascii", "BESAsciiTransmit::send_dap4_csv" << endl);
BESDMRResponse *bdmr = dynamic_cast<BESDMRResponse *>(obj);
if (!bdmr) throw BESInternalFatalError("Expected a BESDMRResponse instance.", __FILE__, __LINE__);
DMR *dmr = bdmr->get_dmr();
string dap4Constraint = www2id(dhi.data[DAP4_CONSTRAINT], "%", "%20%26");
string dap4Function = www2id(dhi.data[DAP4_FUNCTION], "%", "%20%26");
// Not sure we need this...
dhi.first_container();
try {
// Handle *functional* constraint expressions specially
// Use the D4FunctionDriver class and evaluate the functions, building
// an new DMR, then evaluate the D4CE in the context of that DMR.
// This might be coded as "if (there's a function) do this else process the CE".
// Or it might be coded as "if (there's a function) build the new DMR, then fall
// through and process the CE but on the new DMR". jhrg 9/3/14
if (!dap4Constraint.empty()) {
D4ConstraintEvaluator d4ce(dmr);
bool parse_ok = d4ce.parse(dap4Constraint);
if (!parse_ok) throw Error(malformed_expr, "Constraint Expression (" + dap4Constraint + ") failed to parse.");
}
else {
dmr->root()->set_send_p(true);
}
print_values_as_ascii(dmr, dhi.get_output_stream());
dhi.get_output_stream() << flush;
}
catch (Error &e) {
throw BESDapError("Failed to return values as ascii: " + e.get_error_message(), false, e.get_error_code(),__FILE__, __LINE__);
}
catch (BESError &e){
throw;
}
catch (...) {
throw BESInternalError("Failed to return values as ascii: Unknown exception caught", __FILE__, __LINE__);
}
BESDEBUG("ascii", "Done BESAsciiTransmit::send_dap4_csv" << endl);
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cpr/cpr.h>
#include <utils.h>
#include "command.h"
#include "../CommandHandler.h"
#include "../OptionParser.h"
#include "../skills.h"
#define REG 0
#define IRON 1
#define ULT 2
/* full name of the command */
CMDNAME("level");
/* description of the command */
CMDDESCR("look up players' levels");
/* command usage synopsis */
CMDUSAGE("$level [-i|-u] [-n] SKILL RSN");
static const std::string HS_BASE =
"http://services.runescape.com/m=hiscore_oldschool";
static const std::string HS_IRON = "_ironman";
static const std::string HS_ULT = "_ultimate";
static const std::string HS_QUERY = "/index_lite.ws?player=";
static std::string get_hiscores(const std::string &rsn, int8_t id, int8_t type,
std::string &err);
/* level: look up players' levels */
std::string CommandHandler::level(char *out, struct command *c)
{
std::string output = "@" + std::string(c->nick) + ", ";
std::string rsn, err, nick, res, which;
std::vector<std::string> argv;
bool usenick;
int8_t id, type;
char buf[RSN_BUF];
OptionParser op(c->fullCmd, "inu");
int opt;
static struct OptionParser::option long_opts[] = {
{ "help", NO_ARG, 'h' },
{ "ironman", NO_ARG, 'i' },
{ "nick", NO_ARG, 'n' },
{ "ultimate", NO_ARG, 'u' },
{ 0, 0, 0 }
};
usenick = false;
type = REG;
while ((opt = op.getopt_long(long_opts)) != EOF) {
switch (opt) {
case 'h':
return HELPMSG(CMDNAME, CMDUSAGE, CMDDESCR);
case 'i':
type = IRON;
which = "(iron) ";
break;
case 'n':
usenick = true;
break;
case 'u':
type = ULT;
which = "(ult) ";
break;
case '?':
return std::string(op.opterr());
default:
return "";
}
}
if (op.optind() == c->fullCmd.length())
return USAGEMSG(CMDNAME, CMDUSAGE);
utils::split(c->fullCmd.substr(op.optind()), ' ', argv);
if (argv.size() != 2)
return USAGEMSG(CMDNAME, CMDUSAGE);
if (!getrsn(buf, RSN_BUF, c->fullCmd.substr(op.optind()).c_str(),
c->nick, usenick))
return CMDNAME + ": " + std::string(buf);
rsn = std::string(buf);
std::replace(rsn.begin(), rsn.end(), '-', '_');
if ((id = skill_id(argv[0])) == -1)
return c->cmd + ": invalid skill name: " + argv[0];
if ((res = get_hiscores(rsn, id, type, err)).empty())
return c->cmd + ": " + err;
/* skill nickname is displayed to save space */
nick = skill_nick(id);
std::transform(nick.begin(), nick.end(), nick.begin(), toupper);
return "[" + nick + "] " + which + "Name: " + rsn + ", " + res;
}
/* get_hiscores: return hiscore data of player rsn in skill */
static std::string get_hiscores(const std::string &rsn, int8_t id, int8_t type,
std::string &err)
{
cpr::Response resp;
std::vector<std::string> skills;
std::vector<std::string> tokens;
std::string url;
url = HS_BASE;
if (type == IRON)
url += HS_IRON;
else if (type == ULT)
url += HS_ULT;
url += HS_QUERY;
resp = cpr::Get(cpr::Url(url + rsn),
cpr::Header{{ "Connection", "close" }});
if (resp.text.find("404 - Page not found") != std::string::npos) {
err = "player '" + rsn + "' not found on ";
if (type == IRON)
err += "ironman ";
else if (type == ULT)
err += "ultimate ironman ";
err += "hiscores";
return "";
}
utils::split(resp.text, '\n', skills);
utils::split(skills[id], ',', tokens);
return "Level: " + tokens[1] + ", Exp: "
+ utils::formatInteger(tokens[2]) + ", Rank: "
+ utils::formatInteger(tokens[0]);
}
<commit_msg>Update level command<commit_after>#include <algorithm>
#include <cpr/cpr.h>
#include <utils.h>
#include "command.h"
#include "../CommandHandler.h"
#include "../option.h"
#include "../skills.h"
#include "../strfmt.h"
#define REG 0
#define IRON 1
#define ULT 2
/* full name of the command */
_CMDNAME("level");
/* description of the command */
_CMDDESCR("look up players' levels");
/* command usage synopsis */
_CMDUSAGE("$level [-i|-u] [-n] SKILL RSN");
static const char *HS_BASE =
"http://services.runescape.com/m=hiscore_oldschool";
static const char *HS_IRON = "_ironman";
static const char *HS_ULT = "_ultimate";
static const char *HS_QUERY = "/index_lite.ws?player=";
static void get_hiscores(char *out, struct command *c, const char *rsn,
int id, int type);
/* level: look up players' levels */
std::string CommandHandler::level(char *out, struct command *c)
{
int usenick, id, type;
char buf[RSN_BUF];
int opt;
static struct option long_opts[] = {
{ "help", NO_ARG, 'h' },
{ "ironman", NO_ARG, 'i' },
{ "nick", NO_ARG, 'n' },
{ "ultimate", NO_ARG, 'u' },
{ 0, 0, 0 }
};
opt_init();
usenick = 0;
type = REG;
while ((opt = getopt_long(c->argc, c->argv, "inu", long_opts)) != EOF) {
switch (opt) {
case 'h':
_HELPMSG(out, _CMDNAME, _CMDUSAGE, _CMDDESCR);
return "";
case 'i':
type = IRON;
break;
case 'n':
usenick = 1;
break;
case 'u':
type = ULT;
break;
case '?':
_sprintf(out, MAX_MSG, "%s", opterr());
return "";
default:
return "";
}
}
if (optind != c->argc - 2)
_USAGEMSG(out, _CMDNAME, _CMDUSAGE);
else if (!getrsn(buf, RSN_BUF, c->argv[optind + 1], c->nick, usenick))
_sprintf(out, MAX_MSG, "%s: %s", c->argv[0], buf);
else if ((id = skill_id(c->argv[optind])) == -1)
_sprintf(out, MAX_MSG, "%s: invalid skill name: %s",
c->argv[0], c->argv[optind]);
else
get_hiscores(out, c, buf, id, type);
return "";
/* skill nickname is displayed to save space */
/* nick = skill_nick(id); */
/* std::transform(nick.begin(), nick.end(), nick.begin(), toupper); */
/* return "[" + nick + "] " + which + "Name: " + rsn + ", " + res; */
}
/* get_hiscores: return hiscore data of player rsn in skill id */
static void get_hiscores(char *out, struct command *c, const char *rsn,
int id, int type)
{
cpr::Response resp;
char buf[MAX_MSG];
char exp[RSN_BUF];
char rnk[RSN_BUF];
char nick[8];
char *s, *t, *u;
int i;
strcpy(buf, HS_BASE);
if (type == IRON)
strcat(buf, HS_IRON);
else if (type == ULT)
strcat(buf, HS_ULT);
strcat(buf, HS_QUERY);
strcat(buf, rsn);
resp = cpr::Get(cpr::Url(buf), cpr::Header{{ "Connection", "close" }});
strcpy(buf, resp.text.c_str());
if (strstr(buf, "404 - Page not found")) {
_sprintf(out, MAX_MSG, "%s: player '%s' not found on "
"%shiscores", c->argv[0], rsn,
type == REG ? "" : type == IRON ? "ironman "
: "ultimate ironman ");
return;
}
s = buf;
for (i = 0; i < id; ++i)
s = strchr(s, '\n') + 1;
if ((t = strchr(s, '\n')))
*t = '\0';
t = strchr(s, ',');
*t++ = '\0';
u = strchr(t, ',');
*u++ = '\0';
fmtnum(rnk, RSN_BUF, s);
fmtnum(exp, RSN_BUF, u);
_sprintf(nick, 8, "%s", skill_nick(id).c_str());
for (i = 0; nick[i]; ++i)
nick[i] = toupper(nick[i]);
_sprintf(out, MAX_MSG, "[%s]%s Name: %s, Level: %s, Exp: %s, Rank: %s",
nick, type == REG ? "" : type == IRON ? " (iron)"
: " (ult)", rsn, t, exp, rnk);
}
<|endoftext|> |
<commit_before>#include "Jitter.h"
#include <iostream>
#include <set>
#ifdef _DEBUG
//#define DUMP_STATEMENTS
#endif
#ifdef DUMP_STATEMENTS
#include <iostream>
#endif
using namespace Jitter;
void CJitter::AllocateRegisters(BASIC_BLOCK& basicBlock)
{
auto& symbolTable = basicBlock.symbolTable;
std::multimap<unsigned int, STATEMENT> loadStatements;
std::multimap<unsigned int, STATEMENT> spillStatements;
#ifdef DUMP_STATEMENTS
DumpStatementList(basicBlock.statements);
std::cout << std::endl;
#endif
auto allocRanges = ComputeAllocationRanges(basicBlock);
for(const auto& allocRange : allocRanges)
{
SymbolRegAllocInfo symbolRegAllocs;
ComputeLivenessForRange(basicBlock, allocRange, symbolRegAllocs);
MarkAliasedSymbols(basicBlock, allocRange, symbolRegAllocs);
AssociateSymbolsToRegisters(symbolRegAllocs);
//Replace all references to symbols by references to allocated registers
for(const auto& statementInfo : IndexedStatementList(basicBlock.statements))
{
auto& statement(statementInfo.statement);
const auto& statementIdx(statementInfo.index);
if(statementIdx < allocRange.first) continue;
if(statementIdx > allocRange.second) break;
statement.VisitOperands(
[&] (SymbolRefPtr& symbolRef, bool)
{
auto symbol = symbolRef->GetSymbol();
auto symbolRegAllocIterator = symbolRegAllocs.find(symbol);
if(symbolRegAllocIterator != std::end(symbolRegAllocs))
{
const auto& symbolRegAlloc = symbolRegAllocIterator->second;
if(symbolRegAlloc.registerId != -1)
{
symbolRef = MakeSymbolRef(
symbolTable.MakeSymbol(symbolRegAlloc.registerType, symbolRegAlloc.registerId));
}
}
}
);
}
//Prepare load and spills
for(const auto& symbolRegAllocPair : symbolRegAllocs)
{
const auto& symbol = symbolRegAllocPair.first;
const auto& symbolRegAlloc = symbolRegAllocPair.second;
//Check if it's actually allocated
if(symbolRegAlloc.registerId == -1) continue;
//firstUse == -1 means it is written to but never used afterwards in this block
//Do we need to load register at the beginning?
//If symbol is read and we use this symbol before we define it, so we need to load it first
if((symbolRegAlloc.firstUse != -1) && (symbolRegAlloc.firstUse <= symbolRegAlloc.firstDef))
{
STATEMENT statement;
statement.op = OP_MOV;
statement.dst = std::make_shared<CSymbolRef>(
symbolTable.MakeSymbol(symbolRegAlloc.registerType, symbolRegAlloc.registerId));
statement.src1 = std::make_shared<CSymbolRef>(symbol);
loadStatements.insert(std::make_pair(allocRange.first, statement));
}
//If symbol is defined, we need to save it at the end
if(symbolRegAlloc.firstDef != -1)
{
STATEMENT statement;
statement.op = OP_MOV;
statement.dst = std::make_shared<CSymbolRef>(symbol);
statement.src1 = std::make_shared<CSymbolRef>(
symbolTable.MakeSymbol(symbolRegAlloc.registerType, symbolRegAlloc.registerId));
spillStatements.insert(std::make_pair(allocRange.second, statement));
}
}
}
#ifdef DUMP_STATEMENTS
DumpStatementList(basicBlock.statements);
std::cout << std::endl;
#endif
std::map<unsigned int, StatementList::const_iterator> loadPoints;
std::map<unsigned int, StatementList::const_iterator> spillPoints;
//Load
for(const auto& statementInfo : ConstIndexedStatementList(basicBlock.statements))
{
const auto& statementIdx(statementInfo.index);
if(loadStatements.find(statementIdx) != std::end(loadStatements))
{
loadPoints.insert(std::make_pair(statementIdx, statementInfo.iterator));
}
}
//Spill
for(const auto& statementInfo : ConstIndexedStatementList(basicBlock.statements))
{
const auto& statementIdx(statementInfo.index);
if(spillStatements.find(statementIdx) != std::end(spillStatements))
{
const auto& statement = statementInfo.statement;
auto statementIterator = statementInfo.iterator;
if((statement.op != OP_CONDJMP) && (statement.op != OP_JMP) && (statement.op != OP_CALL))
{
statementIterator++;
}
spillPoints.insert(std::make_pair(statementIdx, statementIterator));
}
}
//Loads
for(const auto& loadPoint : loadPoints)
{
unsigned int statementIndex = loadPoint.first;
for(auto statementIterator = loadStatements.lower_bound(statementIndex);
statementIterator != loadStatements.upper_bound(statementIndex);
statementIterator++)
{
const auto& statement(statementIterator->second);
basicBlock.statements.insert(loadPoint.second, statement);
}
}
//Spills
for(const auto& spillPoint : spillPoints)
{
unsigned int statementIndex = spillPoint.first;
for(auto statementIterator = spillStatements.lower_bound(statementIndex);
statementIterator != spillStatements.upper_bound(statementIndex);
statementIterator++)
{
const auto& statement(statementIterator->second);
basicBlock.statements.insert(spillPoint.second, statement);
}
}
#ifdef DUMP_STATEMENTS
DumpStatementList(basicBlock.statements);
std::cout << std::endl;
#endif
}
void CJitter::AssociateSymbolsToRegisters(SymbolRegAllocInfo& symbolRegAllocs) const
{
std::multimap<SYM_TYPE, unsigned int> availableRegisters;
{
unsigned int regCount = m_codeGen->GetAvailableRegisterCount();
for(unsigned int i = 0; i < regCount; i++)
{
availableRegisters.insert(std::make_pair(SYM_REGISTER, i));
}
}
{
unsigned int regCount = m_codeGen->GetAvailableMdRegisterCount();
for(unsigned int i = 0; i < regCount; i++)
{
availableRegisters.insert(std::make_pair(SYM_REGISTER128, i));
}
}
auto isRegisterAllocatable =
[] (SYM_TYPE symbolType)
{
return
(symbolType == SYM_RELATIVE) || (symbolType == SYM_TEMPORARY) ||
(symbolType == SYM_RELATIVE128) || (symbolType == SYM_TEMPORARY128);
};
//Sort symbols by usage count
std::list<SymbolRegAllocInfo::value_type*> sortedSymbols;
for(auto& symbolRegAllocPair : symbolRegAllocs)
{
const auto& symbol(symbolRegAllocPair.first);
const auto& symbolRegAlloc(symbolRegAllocPair.second);
if(!isRegisterAllocatable(symbol->m_type)) continue;
if(symbolRegAlloc.aliased) continue;
sortedSymbols.push_back(&symbolRegAllocPair);
}
sortedSymbols.sort(
[] (SymbolRegAllocInfo::value_type* symbolRegAllocPair1, SymbolRegAllocInfo::value_type* symbolRegAllocPair2)
{
return symbolRegAllocPair1->second.useCount > symbolRegAllocPair2->second.useCount;
}
);
for(auto& symbolRegAllocPair : sortedSymbols)
{
if(availableRegisters.empty()) break;
const auto& symbol = symbolRegAllocPair->first;
auto& symbolRegAlloc = symbolRegAllocPair->second;
//Find suitable register for this symbol
auto registerIterator = std::end(availableRegisters);
auto registerIteratorEnd = std::end(availableRegisters);
if((symbol->m_type == SYM_RELATIVE) || (symbol->m_type == SYM_TEMPORARY))
{
registerIterator = availableRegisters.lower_bound(SYM_REGISTER);
registerIteratorEnd = availableRegisters.upper_bound(SYM_REGISTER);
}
else if((symbol->m_type == SYM_RELATIVE128) || (symbol->m_type == SYM_TEMPORARY128))
{
registerIterator = availableRegisters.lower_bound(SYM_REGISTER128);
registerIteratorEnd = availableRegisters.upper_bound(SYM_REGISTER128);
}
if(registerIterator != registerIteratorEnd)
{
symbolRegAlloc.registerType = registerIterator->first;
symbolRegAlloc.registerId = registerIterator->second;
availableRegisters.erase(registerIterator);
}
}
}
CJitter::AllocationRangeArray CJitter::ComputeAllocationRanges(const BASIC_BLOCK& basicBlock)
{
AllocationRangeArray result;
unsigned int currentStart = 0;
for(const auto& statementInfo : ConstIndexedStatementList(basicBlock.statements))
{
const auto& statement(statementInfo.statement);
const auto& statementIdx(statementInfo.index);
if(statement.op == OP_CALL)
{
//Gotta split here
result.push_back(std::make_pair(currentStart, statementIdx));
currentStart = statementIdx + 1;
}
}
result.push_back(std::make_pair(currentStart, basicBlock.statements.size() - 1));
return result;
}
void CJitter::ComputeLivenessForRange(const BASIC_BLOCK& basicBlock, const AllocationRange& allocRange, SymbolRegAllocInfo& symbolRegAllocs) const
{
auto& symbolTable(basicBlock.symbolTable);
const auto& statements(basicBlock.statements);
for(const auto& statementInfo : ConstIndexedStatementList(basicBlock.statements))
{
const auto& statement(statementInfo.statement);
unsigned int statementIdx(statementInfo.index);
if(statementIdx < allocRange.first) continue;
if(statementIdx > allocRange.second) continue;
statement.VisitDestination(
[&] (const SymbolRefPtr& symbolRef, bool)
{
auto symbol(symbolRef->GetSymbol());
auto& symbolRegAlloc = symbolRegAllocs[symbol];
symbolRegAlloc.useCount++;
if(symbolRegAlloc.firstDef == -1)
{
symbolRegAlloc.firstDef = statementIdx;
}
if((symbolRegAlloc.lastDef == -1) || (statementIdx > symbolRegAlloc.lastDef))
{
symbolRegAlloc.lastDef = statementIdx;
}
}
);
statement.VisitSources(
[&] (const SymbolRefPtr& symbolRef, bool)
{
auto symbol(symbolRef->GetSymbol());
auto& symbolRegAlloc = symbolRegAllocs[symbol];
symbolRegAlloc.useCount++;
if(symbolRegAlloc.firstUse == -1)
{
symbolRegAlloc.firstUse = statementIdx;
}
}
);
//Special case (probably because of badly designed instruction)
if(statement.op == OP_MD_MOV_MASKED)
{
//MD_MOV_MASKED will use the values from dst, so, it's actually
//used before being defined
auto symbol(statement.dst->GetSymbol());
auto& symbolRegAlloc = symbolRegAllocs[symbol];
if(symbolRegAlloc.firstUse == -1)
{
symbolRegAlloc.firstUse = statementIdx;
}
}
}
}
void CJitter::MarkAliasedSymbols(const BASIC_BLOCK& basicBlock, const AllocationRange& allocRange, SymbolRegAllocInfo& symbolRegAllocs) const
{
for(const auto& statementInfo : ConstIndexedStatementList(basicBlock.statements))
{
auto& statement(statementInfo.statement);
const auto& statementIdx(statementInfo.index);
if(statementIdx < allocRange.first) continue;
if(statementIdx > allocRange.second) break;
if(statement.op == OP_PARAM_RET)
{
//This symbol will end up being written to by the callee, thus will be aliased
auto& symbolRegAlloc = symbolRegAllocs[statement.src1->GetSymbol()];
symbolRegAlloc.aliased = true;
}
for(auto& symbolRegAlloc : symbolRegAllocs)
{
if(symbolRegAlloc.second.aliased) continue;
auto testedSymbol = symbolRegAlloc.first;
statement.VisitOperands(
[&](const SymbolRefPtr& symbolRef, bool)
{
auto symbol = symbolRef->GetSymbol();
if(symbol->Equals(testedSymbol.get())) return;
if(symbol->Aliases(testedSymbol.get()))
{
symbolRegAlloc.second.aliased = true;
}
}
);
}
}
}
<commit_msg>Made register allocation more predictable.<commit_after>#include "Jitter.h"
#include <iostream>
#include <set>
#ifdef _DEBUG
//#define DUMP_STATEMENTS
#endif
#ifdef DUMP_STATEMENTS
#include <iostream>
#endif
using namespace Jitter;
void CJitter::AllocateRegisters(BASIC_BLOCK& basicBlock)
{
auto& symbolTable = basicBlock.symbolTable;
std::multimap<unsigned int, STATEMENT> loadStatements;
std::multimap<unsigned int, STATEMENT> spillStatements;
#ifdef DUMP_STATEMENTS
DumpStatementList(basicBlock.statements);
std::cout << std::endl;
#endif
auto allocRanges = ComputeAllocationRanges(basicBlock);
for(const auto& allocRange : allocRanges)
{
SymbolRegAllocInfo symbolRegAllocs;
ComputeLivenessForRange(basicBlock, allocRange, symbolRegAllocs);
MarkAliasedSymbols(basicBlock, allocRange, symbolRegAllocs);
AssociateSymbolsToRegisters(symbolRegAllocs);
//Replace all references to symbols by references to allocated registers
for(const auto& statementInfo : IndexedStatementList(basicBlock.statements))
{
auto& statement(statementInfo.statement);
const auto& statementIdx(statementInfo.index);
if(statementIdx < allocRange.first) continue;
if(statementIdx > allocRange.second) break;
statement.VisitOperands(
[&] (SymbolRefPtr& symbolRef, bool)
{
auto symbol = symbolRef->GetSymbol();
auto symbolRegAllocIterator = symbolRegAllocs.find(symbol);
if(symbolRegAllocIterator != std::end(symbolRegAllocs))
{
const auto& symbolRegAlloc = symbolRegAllocIterator->second;
if(symbolRegAlloc.registerId != -1)
{
symbolRef = MakeSymbolRef(
symbolTable.MakeSymbol(symbolRegAlloc.registerType, symbolRegAlloc.registerId));
}
}
}
);
}
//Prepare load and spills
for(const auto& symbolRegAllocPair : symbolRegAllocs)
{
const auto& symbol = symbolRegAllocPair.first;
const auto& symbolRegAlloc = symbolRegAllocPair.second;
//Check if it's actually allocated
if(symbolRegAlloc.registerId == -1) continue;
//firstUse == -1 means it is written to but never used afterwards in this block
//Do we need to load register at the beginning?
//If symbol is read and we use this symbol before we define it, so we need to load it first
if((symbolRegAlloc.firstUse != -1) && (symbolRegAlloc.firstUse <= symbolRegAlloc.firstDef))
{
STATEMENT statement;
statement.op = OP_MOV;
statement.dst = std::make_shared<CSymbolRef>(
symbolTable.MakeSymbol(symbolRegAlloc.registerType, symbolRegAlloc.registerId));
statement.src1 = std::make_shared<CSymbolRef>(symbol);
loadStatements.insert(std::make_pair(allocRange.first, statement));
}
//If symbol is defined, we need to save it at the end
if(symbolRegAlloc.firstDef != -1)
{
STATEMENT statement;
statement.op = OP_MOV;
statement.dst = std::make_shared<CSymbolRef>(symbol);
statement.src1 = std::make_shared<CSymbolRef>(
symbolTable.MakeSymbol(symbolRegAlloc.registerType, symbolRegAlloc.registerId));
spillStatements.insert(std::make_pair(allocRange.second, statement));
}
}
}
#ifdef DUMP_STATEMENTS
DumpStatementList(basicBlock.statements);
std::cout << std::endl;
#endif
std::map<unsigned int, StatementList::const_iterator> loadPoints;
std::map<unsigned int, StatementList::const_iterator> spillPoints;
//Load
for(const auto& statementInfo : ConstIndexedStatementList(basicBlock.statements))
{
const auto& statementIdx(statementInfo.index);
if(loadStatements.find(statementIdx) != std::end(loadStatements))
{
loadPoints.insert(std::make_pair(statementIdx, statementInfo.iterator));
}
}
//Spill
for(const auto& statementInfo : ConstIndexedStatementList(basicBlock.statements))
{
const auto& statementIdx(statementInfo.index);
if(spillStatements.find(statementIdx) != std::end(spillStatements))
{
const auto& statement = statementInfo.statement;
auto statementIterator = statementInfo.iterator;
if((statement.op != OP_CONDJMP) && (statement.op != OP_JMP) && (statement.op != OP_CALL))
{
statementIterator++;
}
spillPoints.insert(std::make_pair(statementIdx, statementIterator));
}
}
//Loads
for(const auto& loadPoint : loadPoints)
{
unsigned int statementIndex = loadPoint.first;
for(auto statementIterator = loadStatements.lower_bound(statementIndex);
statementIterator != loadStatements.upper_bound(statementIndex);
statementIterator++)
{
const auto& statement(statementIterator->second);
basicBlock.statements.insert(loadPoint.second, statement);
}
}
//Spills
for(const auto& spillPoint : spillPoints)
{
unsigned int statementIndex = spillPoint.first;
for(auto statementIterator = spillStatements.lower_bound(statementIndex);
statementIterator != spillStatements.upper_bound(statementIndex);
statementIterator++)
{
const auto& statement(statementIterator->second);
basicBlock.statements.insert(spillPoint.second, statement);
}
}
#ifdef DUMP_STATEMENTS
DumpStatementList(basicBlock.statements);
std::cout << std::endl;
#endif
}
void CJitter::AssociateSymbolsToRegisters(SymbolRegAllocInfo& symbolRegAllocs) const
{
std::multimap<SYM_TYPE, unsigned int> availableRegisters;
{
unsigned int regCount = m_codeGen->GetAvailableRegisterCount();
for(unsigned int i = 0; i < regCount; i++)
{
availableRegisters.insert(std::make_pair(SYM_REGISTER, i));
}
}
{
unsigned int regCount = m_codeGen->GetAvailableMdRegisterCount();
for(unsigned int i = 0; i < regCount; i++)
{
availableRegisters.insert(std::make_pair(SYM_REGISTER128, i));
}
}
auto isRegisterAllocatable =
[] (SYM_TYPE symbolType)
{
return
(symbolType == SYM_RELATIVE) || (symbolType == SYM_TEMPORARY) ||
(symbolType == SYM_RELATIVE128) || (symbolType == SYM_TEMPORARY128);
};
//Sort symbols by usage count
std::list<SymbolRegAllocInfo::value_type*> sortedSymbols;
for(auto& symbolRegAllocPair : symbolRegAllocs)
{
const auto& symbol(symbolRegAllocPair.first);
const auto& symbolRegAlloc(symbolRegAllocPair.second);
if(!isRegisterAllocatable(symbol->m_type)) continue;
if(symbolRegAlloc.aliased) continue;
sortedSymbols.push_back(&symbolRegAllocPair);
}
sortedSymbols.sort(
[] (SymbolRegAllocInfo::value_type* symbolRegAllocPair1, SymbolRegAllocInfo::value_type* symbolRegAllocPair2)
{
const auto& symbol1(symbolRegAllocPair1->first);
const auto& symbol2(symbolRegAllocPair2->first);
const auto& symbolRegAlloc1(symbolRegAllocPair1->second);
const auto& symbolRegAlloc2(symbolRegAllocPair2->second);
if(symbolRegAlloc1.useCount == symbolRegAlloc2.useCount)
{
if(symbol1->m_type == symbol2->m_type)
{
return symbol1->m_valueLow > symbol2->m_valueLow;
}
else
{
return symbol1->m_type > symbol2->m_type;
}
}
else
{
return symbolRegAlloc1.useCount > symbolRegAlloc2.useCount;
}
}
);
for(auto& symbolRegAllocPair : sortedSymbols)
{
if(availableRegisters.empty()) break;
const auto& symbol = symbolRegAllocPair->first;
auto& symbolRegAlloc = symbolRegAllocPair->second;
//Find suitable register for this symbol
auto registerIterator = std::end(availableRegisters);
auto registerIteratorEnd = std::end(availableRegisters);
if((symbol->m_type == SYM_RELATIVE) || (symbol->m_type == SYM_TEMPORARY))
{
registerIterator = availableRegisters.lower_bound(SYM_REGISTER);
registerIteratorEnd = availableRegisters.upper_bound(SYM_REGISTER);
}
else if((symbol->m_type == SYM_RELATIVE128) || (symbol->m_type == SYM_TEMPORARY128))
{
registerIterator = availableRegisters.lower_bound(SYM_REGISTER128);
registerIteratorEnd = availableRegisters.upper_bound(SYM_REGISTER128);
}
if(registerIterator != registerIteratorEnd)
{
symbolRegAlloc.registerType = registerIterator->first;
symbolRegAlloc.registerId = registerIterator->second;
availableRegisters.erase(registerIterator);
}
}
}
CJitter::AllocationRangeArray CJitter::ComputeAllocationRanges(const BASIC_BLOCK& basicBlock)
{
AllocationRangeArray result;
unsigned int currentStart = 0;
for(const auto& statementInfo : ConstIndexedStatementList(basicBlock.statements))
{
const auto& statement(statementInfo.statement);
const auto& statementIdx(statementInfo.index);
if(statement.op == OP_CALL)
{
//Gotta split here
result.push_back(std::make_pair(currentStart, statementIdx));
currentStart = statementIdx + 1;
}
}
result.push_back(std::make_pair(currentStart, basicBlock.statements.size() - 1));
return result;
}
void CJitter::ComputeLivenessForRange(const BASIC_BLOCK& basicBlock, const AllocationRange& allocRange, SymbolRegAllocInfo& symbolRegAllocs) const
{
auto& symbolTable(basicBlock.symbolTable);
const auto& statements(basicBlock.statements);
for(const auto& statementInfo : ConstIndexedStatementList(basicBlock.statements))
{
const auto& statement(statementInfo.statement);
unsigned int statementIdx(statementInfo.index);
if(statementIdx < allocRange.first) continue;
if(statementIdx > allocRange.second) continue;
statement.VisitDestination(
[&] (const SymbolRefPtr& symbolRef, bool)
{
auto symbol(symbolRef->GetSymbol());
auto& symbolRegAlloc = symbolRegAllocs[symbol];
symbolRegAlloc.useCount++;
if(symbolRegAlloc.firstDef == -1)
{
symbolRegAlloc.firstDef = statementIdx;
}
if((symbolRegAlloc.lastDef == -1) || (statementIdx > symbolRegAlloc.lastDef))
{
symbolRegAlloc.lastDef = statementIdx;
}
}
);
statement.VisitSources(
[&] (const SymbolRefPtr& symbolRef, bool)
{
auto symbol(symbolRef->GetSymbol());
auto& symbolRegAlloc = symbolRegAllocs[symbol];
symbolRegAlloc.useCount++;
if(symbolRegAlloc.firstUse == -1)
{
symbolRegAlloc.firstUse = statementIdx;
}
}
);
//Special case (probably because of badly designed instruction)
if(statement.op == OP_MD_MOV_MASKED)
{
//MD_MOV_MASKED will use the values from dst, so, it's actually
//used before being defined
auto symbol(statement.dst->GetSymbol());
auto& symbolRegAlloc = symbolRegAllocs[symbol];
if(symbolRegAlloc.firstUse == -1)
{
symbolRegAlloc.firstUse = statementIdx;
}
}
}
}
void CJitter::MarkAliasedSymbols(const BASIC_BLOCK& basicBlock, const AllocationRange& allocRange, SymbolRegAllocInfo& symbolRegAllocs) const
{
for(const auto& statementInfo : ConstIndexedStatementList(basicBlock.statements))
{
auto& statement(statementInfo.statement);
const auto& statementIdx(statementInfo.index);
if(statementIdx < allocRange.first) continue;
if(statementIdx > allocRange.second) break;
if(statement.op == OP_PARAM_RET)
{
//This symbol will end up being written to by the callee, thus will be aliased
auto& symbolRegAlloc = symbolRegAllocs[statement.src1->GetSymbol()];
symbolRegAlloc.aliased = true;
}
for(auto& symbolRegAlloc : symbolRegAllocs)
{
if(symbolRegAlloc.second.aliased) continue;
auto testedSymbol = symbolRegAlloc.first;
statement.VisitOperands(
[&](const SymbolRefPtr& symbolRef, bool)
{
auto symbol = symbolRef->GetSymbol();
if(symbol->Equals(testedSymbol.get())) return;
if(symbol->Aliases(testedSymbol.get()))
{
symbolRegAlloc.second.aliased = true;
}
}
);
}
}
}
<|endoftext|> |
<commit_before>/** Copyright (C) 2015 Ultimaker - Released under terms of the AGPLv3 License */
#include "LayerPlanBuffer.h"
#include "gcodeExport.h"
#include "utils/logoutput.h"
#include "FffProcessor.h"
namespace cura {
void LayerPlanBuffer::flush()
{
if (buffer.size() > 0)
{
insertPreheatCommands(); // insert preheat commands of the very last layer
}
while (!buffer.empty())
{
buffer.front().writeGCode(gcode);
if (CommandSocket::isInstantiated())
{
CommandSocket::getInstance()->flushGcode();
}
buffer.pop_front();
}
}
void LayerPlanBuffer::insertPreheatCommand(ExtruderPlan& extruder_plan_before, double time_after_extruder_plan_start, int extruder, double temp)
{
double acc_time = 0.0;
for (unsigned int path_idx = extruder_plan_before.paths.size() - 1; int(path_idx) != -1 ; path_idx--)
{
GCodePath& path = extruder_plan_before.paths[path_idx];
const double time_this_path = path.estimates.getTotalTime();
acc_time += time_this_path;
if (acc_time > time_after_extruder_plan_start)
{
const double time_before_path_end = acc_time - time_after_extruder_plan_start;
bool wait = false;
extruder_plan_before.insertCommand(path_idx, extruder, temp, wait, time_this_path - time_before_path_end);
return;
}
}
bool wait = false;
unsigned int path_idx = 0;
extruder_plan_before.insertCommand(path_idx, extruder, temp, wait); // insert at start of extruder plan if time_after_extruder_plan_start > extruder_plan.time
}
Preheat::WarmUpResult LayerPlanBuffer::timeBeforeExtruderPlanToInsert(std::vector<ExtruderPlan*>& extruder_plans, unsigned int extruder_plan_idx)
{
ExtruderPlan& extruder_plan = *extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
double initial_print_temp = preheat_config.getInitialPrintTemp(extruder);
if (initial_print_temp == 0)
{
initial_print_temp = extruder_plan.printing_temperature;
}
double in_between_time = 0.0;
for (unsigned int extruder_plan_before_idx = extruder_plan_idx - 1; int(extruder_plan_before_idx) >= 0; extruder_plan_before_idx--)
{ // find a previous extruder plan where the same extruder is used to see what time this extruder wasn't used
ExtruderPlan& extruder_plan = *extruder_plans[extruder_plan_before_idx];
if (extruder_plan.extruder == extruder)
{
Preheat::WarmUpResult warm_up = preheat_config.timeBeforeEndToInsertPreheatCommand_coolDownWarmUp(in_between_time, extruder, initial_print_temp);
warm_up.heating_time = std::min(in_between_time, warm_up.heating_time + extra_preheat_time);
return warm_up;
}
in_between_time += extruder_plan.estimates.getTotalTime();
}
// The last extruder plan with the same extruder falls outside of the buffer
// assume the nozzle has cooled down to strandby temperature already.
Preheat::WarmUpResult warm_up;
warm_up.total_time_window = in_between_time;
warm_up.lowest_temperature = preheat_config.getStandbyTemp(extruder);
constexpr bool during_printing = false;
warm_up.heating_time = preheat_config.timeBeforeEndToInsertPreheatCommand_warmUp(warm_up.lowest_temperature, extruder, initial_print_temp, during_printing);
if (warm_up.heating_time > in_between_time)
{
warm_up.heating_time = in_between_time;
warm_up.lowest_temperature = in_between_time / preheat_config.getTimeToHeatup1Degree(extruder);
}
warm_up.heating_time = warm_up.heating_time + extra_preheat_time;
return warm_up;
}
void LayerPlanBuffer::insertPreheatCommand_singleExtrusion(ExtruderPlan& prev_extruder_plan, int extruder, double required_temp)
{
// time_before_extruder_plan_end is halved, so that at the layer change the temperature will be half way betewen the two requested temperatures
double time_before_extruder_plan_end = 0.5 * preheat_config.timeBeforeEndToInsertPreheatCommand_warmUp(prev_extruder_plan.printing_temperature, extruder, required_temp, true);
time_before_extruder_plan_end = std::min(prev_extruder_plan.estimates.getTotalTime(), time_before_extruder_plan_end);
insertPreheatCommand(prev_extruder_plan, time_before_extruder_plan_end, extruder, required_temp);
}
void LayerPlanBuffer::handleStandbyTemp(std::vector<ExtruderPlan*>& extruder_plans, unsigned int extruder_plan_idx, double standby_temp)
{
ExtruderPlan& extruder_plan = *extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
for (unsigned int extruder_plan_before_idx = extruder_plan_idx - 2; int(extruder_plan_before_idx) >= 0; extruder_plan_before_idx--)
{
if (extruder_plans[extruder_plan_before_idx]->extruder == extruder)
{
extruder_plans[extruder_plan_before_idx + 1]->prev_extruder_standby_temp = standby_temp;
return;
}
}
logWarning("Warning: Couldn't find previous extruder plan so as to set the standby temperature. Inserting temp command in earliest available layer.\n");
ExtruderPlan& earliest_extruder_plan = *extruder_plans[0];
constexpr bool wait = false;
earliest_extruder_plan.insertCommand(0, extruder, standby_temp, wait);
}
void LayerPlanBuffer::insertPreheatCommand_multiExtrusion(std::vector<ExtruderPlan*>& extruder_plans, unsigned int extruder_plan_idx)
{
ExtruderPlan& extruder_plan = *extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
double initial_print_temp = preheat_config.getInitialPrintTemp(extruder);
double print_temp = extruder_plan.printing_temperature;
double final_print_temp = preheat_config.getFinalPrintTemp(extruder);
if (initial_print_temp == 0)
{
initial_print_temp = extruder_plan.printing_temperature;
}
Preheat::WarmUpResult heating_time_and_from_temp = timeBeforeExtruderPlanToInsert(extruder_plans, extruder_plan_idx);
if (heating_time_and_from_temp.total_time_window < preheat_config.getMinimalTimeWindow(extruder))
{
handleStandbyTemp(extruder_plans, extruder_plan_idx, initial_print_temp);
return; // don't insert preheat command and just stay on printing temperature
}
else
{
handleStandbyTemp(extruder_plans, extruder_plan_idx, heating_time_and_from_temp.lowest_temperature);
}
double time_before_extruder_plan_to_insert = heating_time_and_from_temp.heating_time;
for (unsigned int extruder_plan_before_idx = extruder_plan_idx - 1; int(extruder_plan_before_idx) >= 0; extruder_plan_before_idx--)
{
ExtruderPlan& extruder_plan_before = *extruder_plans[extruder_plan_before_idx];
assert (extruder_plan_before.extruder != extruder);
double time_here = extruder_plan_before.estimates.getTotalTime();
if (time_here >= time_before_extruder_plan_to_insert)
{
insertPreheatCommand(extruder_plan_before, time_before_extruder_plan_to_insert, extruder, initial_print_temp);
return;
}
time_before_extruder_plan_to_insert -= time_here;
}
// time_before_extruder_plan_to_insert falls before all plans in the buffer
bool wait = false;
unsigned int path_idx = 0;
extruder_plans[0]->insertCommand(path_idx, extruder, initial_print_temp, wait); // insert preheat command at verfy beginning of buffer
}
void LayerPlanBuffer::insertPreheatCommand(std::vector<ExtruderPlan*>& extruder_plans, unsigned int extruder_plan_idx)
{
ExtruderPlan& extruder_plan = *extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
ExtruderPlan* prev_extruder_plan = extruder_plans[extruder_plan_idx - 1];
int prev_extruder = prev_extruder_plan->extruder;
if (prev_extruder != extruder)
{ // set previous extruder to standby temperature
extruder_plan.prev_extruder_standby_temp = preheat_config.getStandbyTemp(prev_extruder);
}
if (prev_extruder == extruder)
{
insertPreheatCommand_singleExtrusion(*prev_extruder_plan, extruder, extruder_plan.printing_temperature);
}
else
{
insertPreheatCommand_multiExtrusion(extruder_plans, extruder_plan_idx);
}
}
void LayerPlanBuffer::insertPreheatCommands()
{
if (buffer.back().extruder_plans.size() == 0 || (buffer.back().extruder_plans.size() == 1 && buffer.back().extruder_plans[0].paths.size() == 0))
{ // disregard empty layer
buffer.pop_back();
return;
}
std::vector<ExtruderPlan*> extruder_plans;
extruder_plans.reserve(buffer.size() * 2);
for (GCodePlanner& layer_plan : buffer)
{
for (ExtruderPlan& extr_plan : layer_plan.extruder_plans)
{
extruder_plans.push_back(&extr_plan);
}
}
// insert commands for all extruder plans on this layer
GCodePlanner& layer_plan = buffer.back();
for (unsigned int extruder_plan_idx = 0; extruder_plan_idx < layer_plan.extruder_plans.size(); extruder_plan_idx++)
{
ExtruderPlan& extruder_plan = layer_plan.extruder_plans[extruder_plan_idx];
double time = extruder_plan.estimates.getTotalUnretractedTime();
if (time <= 0.0
|| extruder_plan.estimates.getMaterial() == 0.0 // extruder plan only consists of moves (when an extruder switch occurs at the beginning of a layer)
)
{
continue;
}
double avg_flow = extruder_plan.estimates.getMaterial() / time; // TODO: subtract retracted travel time
extruder_plan.printing_temperature = preheat_config.getTemp(extruder_plan.extruder, avg_flow, extruder_plan.is_initial_layer);
if (buffer.size() == 1 && extruder_plan_idx == 0)
{ // the very first extruder plan of the current meshgroup
int extruder = extruder_plan.extruder;
for (int extruder_idx = 0; extruder_idx < getSettingAsCount("machine_extruder_count"); extruder_idx++)
{ // set temperature of the first nozzle, turn other nozzles down
if (FffProcessor::getInstance()->getMeshgroupNr() == 0)
{
// override values from GCodeExport::setInitialTemps
// the first used extruder should be set to the required temp in the start gcode
// see FffGcodeWriter::processStartingCode
if (extruder_idx == extruder)
{
gcode.setInitialTemp(extruder_idx, extruder_plan.printing_temperature);
}
else
{
gcode.setInitialTemp(extruder_idx, preheat_config.getStandbyTemp(extruder_idx));
}
}
else
{
if (extruder_idx != extruder)
{ // TODO: do we need to do this?
extruder_plan.prev_extruder_standby_temp = preheat_config.getStandbyTemp(extruder_idx);
}
}
}
continue;
}
unsigned int overall_extruder_plan_idx = extruder_plans.size() - layer_plan.extruder_plans.size() + extruder_plan_idx;
insertPreheatCommand(extruder_plans, overall_extruder_plan_idx);
}
}
} // namespace cura<commit_msg>fix: insert temp commands for preheat and precool (CURA-1932)<commit_after>/** Copyright (C) 2015 Ultimaker - Released under terms of the AGPLv3 License */
#include "LayerPlanBuffer.h"
#include "gcodeExport.h"
#include "utils/logoutput.h"
#include "FffProcessor.h"
namespace cura {
void LayerPlanBuffer::flush()
{
if (buffer.size() > 0)
{
insertPreheatCommands(); // insert preheat commands of the very last layer
}
while (!buffer.empty())
{
buffer.front().writeGCode(gcode);
if (CommandSocket::isInstantiated())
{
CommandSocket::getInstance()->flushGcode();
}
buffer.pop_front();
}
}
void LayerPlanBuffer::insertPreheatCommand(ExtruderPlan& extruder_plan_before, double time_after_extruder_plan_start, int extruder, double temp)
{
double acc_time = 0.0;
for (unsigned int path_idx = extruder_plan_before.paths.size() - 1; int(path_idx) != -1 ; path_idx--)
{
GCodePath& path = extruder_plan_before.paths[path_idx];
const double time_this_path = path.estimates.getTotalTime();
acc_time += time_this_path;
if (acc_time > time_after_extruder_plan_start)
{
const double time_before_path_end = acc_time - time_after_extruder_plan_start;
bool wait = false;
extruder_plan_before.insertCommand(path_idx, extruder, temp, wait, time_this_path - time_before_path_end);
return;
}
}
bool wait = false;
unsigned int path_idx = 0;
extruder_plan_before.insertCommand(path_idx, extruder, temp, wait); // insert at start of extruder plan if time_after_extruder_plan_start > extruder_plan.time
}
Preheat::WarmUpResult LayerPlanBuffer::timeBeforeExtruderPlanToInsert(std::vector<ExtruderPlan*>& extruder_plans, unsigned int extruder_plan_idx)
{
ExtruderPlan& extruder_plan = *extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
double initial_print_temp = preheat_config.getInitialPrintTemp(extruder);
if (initial_print_temp == 0)
{
initial_print_temp = extruder_plan.printing_temperature;
}
double in_between_time = 0.0;
for (unsigned int extruder_plan_before_idx = extruder_plan_idx - 1; int(extruder_plan_before_idx) >= 0; extruder_plan_before_idx--)
{ // find a previous extruder plan where the same extruder is used to see what time this extruder wasn't used
ExtruderPlan& extruder_plan = *extruder_plans[extruder_plan_before_idx];
if (extruder_plan.extruder == extruder)
{
Preheat::WarmUpResult warm_up = preheat_config.timeBeforeEndToInsertPreheatCommand_coolDownWarmUp(in_between_time, extruder, initial_print_temp);
warm_up.heating_time = std::min(in_between_time, warm_up.heating_time + extra_preheat_time);
return warm_up;
}
in_between_time += extruder_plan.estimates.getTotalTime();
}
// The last extruder plan with the same extruder falls outside of the buffer
// assume the nozzle has cooled down to strandby temperature already.
Preheat::WarmUpResult warm_up;
warm_up.total_time_window = in_between_time;
warm_up.lowest_temperature = preheat_config.getStandbyTemp(extruder);
constexpr bool during_printing = false;
warm_up.heating_time = preheat_config.timeBeforeEndToInsertPreheatCommand_warmUp(warm_up.lowest_temperature, extruder, initial_print_temp, during_printing);
if (warm_up.heating_time > in_between_time)
{
warm_up.heating_time = in_between_time;
warm_up.lowest_temperature = in_between_time / preheat_config.getTimeToHeatup1Degree(extruder);
}
warm_up.heating_time = warm_up.heating_time + extra_preheat_time;
return warm_up;
}
void LayerPlanBuffer::insertPreheatCommand_singleExtrusion(ExtruderPlan& prev_extruder_plan, int extruder, double required_temp)
{
// time_before_extruder_plan_end is halved, so that at the layer change the temperature will be half way betewen the two requested temperatures
double time_before_extruder_plan_end = 0.5 * preheat_config.timeBeforeEndToInsertPreheatCommand_warmUp(prev_extruder_plan.printing_temperature, extruder, required_temp, true);
time_before_extruder_plan_end = std::min(prev_extruder_plan.estimates.getTotalTime(), time_before_extruder_plan_end);
insertPreheatCommand(prev_extruder_plan, time_before_extruder_plan_end, extruder, required_temp);
}
void LayerPlanBuffer::handleStandbyTemp(std::vector<ExtruderPlan*>& extruder_plans, unsigned int extruder_plan_idx, double standby_temp)
{
ExtruderPlan& extruder_plan = *extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
for (unsigned int extruder_plan_before_idx = extruder_plan_idx - 2; int(extruder_plan_before_idx) >= 0; extruder_plan_before_idx--)
{
if (extruder_plans[extruder_plan_before_idx]->extruder == extruder)
{
extruder_plans[extruder_plan_before_idx + 1]->prev_extruder_standby_temp = standby_temp;
return;
}
}
logWarning("Warning: Couldn't find previous extruder plan so as to set the standby temperature. Inserting temp command in earliest available layer.\n");
ExtruderPlan& earliest_extruder_plan = *extruder_plans[0];
constexpr bool wait = false;
earliest_extruder_plan.insertCommand(0, extruder, standby_temp, wait);
}
void LayerPlanBuffer::insertPreheatCommand_multiExtrusion(std::vector<ExtruderPlan*>& extruder_plans, unsigned int extruder_plan_idx)
{
ExtruderPlan& extruder_plan = *extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
double initial_print_temp = preheat_config.getInitialPrintTemp(extruder);
double print_temp = extruder_plan.printing_temperature;
double final_print_temp = preheat_config.getFinalPrintTemp(extruder);
if (initial_print_temp == 0)
{
initial_print_temp = extruder_plan.printing_temperature;
}
Preheat::WarmUpResult heating_time_and_from_temp = timeBeforeExtruderPlanToInsert(extruder_plans, extruder_plan_idx);
if (heating_time_and_from_temp.total_time_window < preheat_config.getMinimalTimeWindow(extruder))
{
handleStandbyTemp(extruder_plans, extruder_plan_idx, initial_print_temp);
return; // don't insert preheat command and just stay on printing temperature
}
else
{
handleStandbyTemp(extruder_plans, extruder_plan_idx, heating_time_and_from_temp.lowest_temperature);
}
double heated_pre_travel_time = 0;
if (initial_print_temp != 0)
{ // handle heating from initial_print_temperature to printing_tempreature
unsigned int path_idx;
for (path_idx = 0; path_idx < extruder_plan.paths.size(); path_idx++)
{
GCodePath& path = extruder_plan.paths[path_idx];
heated_pre_travel_time += path.estimates.getTotalTime();
if (!path.isTravelPath())
{
break;
}
}
bool wait = false;
extruder_plan.insertCommand(path_idx, extruder, print_temp, wait);
}
double heated_post_travel_time = 0;
if (final_print_temp != 0)
{ // handle precool from print_temp to final_print_temperature
unsigned int path_idx;
for (path_idx = extruder_plan.paths.size() - 1; int(path_idx) >= 0; path_idx--)
{
GCodePath& path = extruder_plan.paths[path_idx];
if (!path.isTravelPath())
{
break;
}
heated_post_travel_time += path.estimates.getTotalTime();
}
double time_window = extruder_plan.estimates.getTotalTime() - heated_pre_travel_time - heated_post_travel_time;
constexpr bool during_printing = true;
Preheat::CoolDownResult warm_cool_result = preheat_config.timeBeforeEndToInsertPreheatCommand_warmUpCoolDown(time_window, extruder, initial_print_temp, print_temp, final_print_temp, during_printing);
double cool_down_time = warm_cool_result.cooling_time;
double extrusion_time_seen = 0;
for (; int(path_idx) >= 0; path_idx--)
{
GCodePath& path = extruder_plan.paths[path_idx];
extrusion_time_seen += path.estimates.getTotalTime();
if (extrusion_time_seen >= cool_down_time)
{
break;
}
}
bool wait = false;
double time_after_path_start = extrusion_time_seen - cool_down_time;
extruder_plan.insertCommand(path_idx, extruder, final_print_temp, wait, time_after_path_start);
}
// handle preheat command
double time_before_extruder_plan_to_insert = heating_time_and_from_temp.heating_time;
for (unsigned int extruder_plan_before_idx = extruder_plan_idx - 1; int(extruder_plan_before_idx) >= 0; extruder_plan_before_idx--)
{
ExtruderPlan& extruder_plan_before = *extruder_plans[extruder_plan_before_idx];
assert (extruder_plan_before.extruder != extruder);
double time_here = extruder_plan_before.estimates.getTotalTime();
if (time_here >= time_before_extruder_plan_to_insert)
{
insertPreheatCommand(extruder_plan_before, time_before_extruder_plan_to_insert, extruder, initial_print_temp);
return;
}
time_before_extruder_plan_to_insert -= time_here;
}
// time_before_extruder_plan_to_insert falls before all plans in the buffer
bool wait = false;
unsigned int path_idx = 0;
extruder_plans[0]->insertCommand(path_idx, extruder, initial_print_temp, wait); // insert preheat command at verfy beginning of buffer
}
void LayerPlanBuffer::insertPreheatCommand(std::vector<ExtruderPlan*>& extruder_plans, unsigned int extruder_plan_idx)
{
ExtruderPlan& extruder_plan = *extruder_plans[extruder_plan_idx];
int extruder = extruder_plan.extruder;
ExtruderPlan* prev_extruder_plan = extruder_plans[extruder_plan_idx - 1];
int prev_extruder = prev_extruder_plan->extruder;
if (prev_extruder != extruder)
{ // set previous extruder to standby temperature
extruder_plan.prev_extruder_standby_temp = preheat_config.getStandbyTemp(prev_extruder);
}
if (prev_extruder == extruder)
{
insertPreheatCommand_singleExtrusion(*prev_extruder_plan, extruder, extruder_plan.printing_temperature);
}
else
{
insertPreheatCommand_multiExtrusion(extruder_plans, extruder_plan_idx);
}
}
void LayerPlanBuffer::insertPreheatCommands()
{
if (buffer.back().extruder_plans.size() == 0 || (buffer.back().extruder_plans.size() == 1 && buffer.back().extruder_plans[0].paths.size() == 0))
{ // disregard empty layer
buffer.pop_back();
return;
}
std::vector<ExtruderPlan*> extruder_plans;
extruder_plans.reserve(buffer.size() * 2);
for (GCodePlanner& layer_plan : buffer)
{
for (ExtruderPlan& extr_plan : layer_plan.extruder_plans)
{
extruder_plans.push_back(&extr_plan);
}
}
// insert commands for all extruder plans on this layer
GCodePlanner& layer_plan = buffer.back();
for (unsigned int extruder_plan_idx = 0; extruder_plan_idx < layer_plan.extruder_plans.size(); extruder_plan_idx++)
{
ExtruderPlan& extruder_plan = layer_plan.extruder_plans[extruder_plan_idx];
double time = extruder_plan.estimates.getTotalUnretractedTime();
if (time <= 0.0
|| extruder_plan.estimates.getMaterial() == 0.0 // extruder plan only consists of moves (when an extruder switch occurs at the beginning of a layer)
)
{
continue;
}
double avg_flow = extruder_plan.estimates.getMaterial() / time; // TODO: subtract retracted travel time
extruder_plan.printing_temperature = preheat_config.getTemp(extruder_plan.extruder, avg_flow, extruder_plan.is_initial_layer);
if (buffer.size() == 1 && extruder_plan_idx == 0)
{ // the very first extruder plan of the current meshgroup
int extruder = extruder_plan.extruder;
for (int extruder_idx = 0; extruder_idx < getSettingAsCount("machine_extruder_count"); extruder_idx++)
{ // set temperature of the first nozzle, turn other nozzles down
if (FffProcessor::getInstance()->getMeshgroupNr() == 0)
{
// override values from GCodeExport::setInitialTemps
// the first used extruder should be set to the required temp in the start gcode
// see FffGcodeWriter::processStartingCode
if (extruder_idx == extruder)
{
gcode.setInitialTemp(extruder_idx, extruder_plan.printing_temperature);
}
else
{
gcode.setInitialTemp(extruder_idx, preheat_config.getStandbyTemp(extruder_idx));
}
}
else
{
if (extruder_idx != extruder)
{ // TODO: do we need to do this?
extruder_plan.prev_extruder_standby_temp = preheat_config.getStandbyTemp(extruder_idx);
}
}
}
continue;
}
unsigned int overall_extruder_plan_idx = extruder_plans.size() - layer_plan.extruder_plans.size() + extruder_plan_idx;
insertPreheatCommand(extruder_plans, overall_extruder_plan_idx);
}
}
} // namespace cura<|endoftext|> |
<commit_before>#include "../includes/declarations.h"
//Function used to check collision with the balls. Attribute obstacle checks if the ball is the black or red.
bool checkCollision(int xp, int yp)
{
for (int i = 0; i < num_circles; i++)
{
int xc = circles[i].x;
int yc = circles[i].y;
int r = circles[i].r;
if ((xc - xp)*(xc-xp) + (yc - yp)*(yc-yp) <= r*r )
{
if(circles[i].hit==false)
collected--;
circles[i].hit = true;
if(circles[i].obstacle==true)
{
circles[i].hit=false;
resetAll();
return false;
}
if(collected==0)
{
level++;
next_level=true;
}
return true;
}
}
return false;
}
//Function used for level select range checking.
bool inCircle(int xp, int yp, float xc, float yc)
{
double r = 0.083 * WIDTH;
if ((xc - xp)*(xc-xp) + (yc - yp)*(yc-yp) <= r*r )
return true;
return false;
}
<commit_msg>Removes trailing newline, adds little documentation<commit_after>#include "../includes/declarations.h"
//Function used to check collision with the balls. Attribute obstacle checks if the ball is the black or red.
bool checkCollision(int xp, int yp)
{
for (int i = 0; i < num_circles; i++)
{
int xc = circles[i].x;
int yc = circles[i].y;
int r = circles[i].r;
if ((xc - xp)*(xc-xp) + (yc - yp)*(yc-yp) <= r*r )
{
if(circles[i].hit==false)
collected--;
circles[i].hit = true;
if(circles[i].obstacle==true)
{
circles[i].hit=false;
resetAll();
return false;
}
if(collected==0)
{
level++;
next_level=true;
}
return true;
}
}
return false;
}
//Function used for level select range checking.
bool inCircle(int xp, int yp, float xc, float yc)
{
double r = 0.083 * WIDTH;
// Calculating if the line has reached inner point of circle, computing (x1-x2)**2 + (y1-y2)**2 < r**2
if ((xc - xp)*(xc-xp) + (yc - yp)*(yc-yp) <= r*r )
return true;
return false;
}<|endoftext|> |
<commit_before>/*!
* \file File component.cpp
* \brief Implementation of Component class
*
* Here is the implementation of Component's methods
*
* \sa component.hpp
*/
#include <component.hpp>
#include <gameObject.hpp>
/*!
@fn void Component::own(GameObject *go)
@brief Assigns a object as property (like a ownage thing) of a component
@param GameObject *go
@return void
@warning none
*/
void Component::own(GameObject *go) {
entity = go->uid;
}
/*!
@fn bool Component::kills_component(float time)
@brief Sets the death of a component
@param float time
@return boolean value
@warning none
*/
bool Component::kills_component(float time) {
UNUSED(time);
return true;
}
<commit_msg>[ASSERTS] adds assertions at component.cpp<commit_after>/*!
* \file File component.cpp
* \brief Implementation of Component class
*
* Here is the implementation of Component's methods
*
* \sa component.hpp
*/
#include <component.hpp>
#include <gameObject.hpp>
/*!
@fn void Component::own(GameObject *go)
@brief Assigns a object as property (like a ownage thing) of a component
@param GameObject *go
@return void
@warning none
*/
void Component::own(GameObject *go) {
assert(go != NULL);
entity = go->uid;
}
/*!
@fn bool Component::kills_component(float time)
@brief Sets the death of a component
@param float time
@return boolean value
@warning none
*/
bool Component::kills_component(float time) {
UNUSED(time);
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2012 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.
#ifdef HAVE_CONFIG_H
# include <oce-config.h>
#endif
#ifndef WNT
#include <OSD_Process.ixx>
#include <OSD_WhoAmI.hxx>
#include <OSD_Environment.hxx>
const OSD_WhoAmI Iam = OSD_WProcess;
#include <errno.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <stdlib.h>
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#if defined(HAVE_TIME_H)
# include <time.h>
#endif
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#ifdef HAVE_PWD_H
# include <pwd.h> // For command getpwuid
#endif
OSD_Process::OSD_Process(){
}
void OSD_Process::Spawn (const TCollection_AsciiString& cmd,
const Standard_Boolean /*ShowWindow*/)
{
system(cmd.ToCString());
}
void OSD_Process::TerminalType(TCollection_AsciiString& Name){
TCollection_AsciiString which="TERM";
OSD_Environment term (which,"");
term.Value();
which = term.Value();
Name = term.Name();
}
// Get date of system date
Quantity_Date OSD_Process::SystemDate(){
Quantity_Date result;
Standard_Integer month=0,day=0,year=0,hh=0,mn=0,ss=0;
struct tm transfert;
time_t secs;
struct timeval tval;
int status;
status = gettimeofday( &tval, NULL );
if (status == -1) myError.SetValue (errno, Iam, "GetSystem");
else {
secs = tval.tv_sec;
#ifdef HAVE_LOCALTIME_R
localtime_r(&secs, &transfert);
#else
memcpy(&transfert, localtime(&secs), sizeof(struct tm));
#endif
month = transfert.tm_mon + 1; // Add to January (month #1)
day = transfert.tm_mday;
year = transfert.tm_year;
hh = transfert.tm_hour;
mn = transfert.tm_min ;
ss = transfert.tm_sec ;
}
result.SetValues ( month, day, year+1900, hh, mn, ss);
return (result);
}
Standard_Integer OSD_Process::ProcessId(){
return (getpid());
}
Standard_Integer OSD_Process::UserId(){
return (getuid());
}
TCollection_AsciiString OSD_Process::UserName(){
struct passwd *infos;
infos = getpwuid(getuid());
TCollection_AsciiString result=infos->pw_name;
return(result);
}
Standard_Boolean OSD_Process::IsSuperUser (){
if (getuid()) {
return Standard_False;
}
else {
return Standard_True;
}
}
OSD_Path OSD_Process::CurrentDirectory(){
OSD_Path result;
TCollection_AsciiString Name;
char *ret;
#if !defined(MAXPATHLEN) && defined(__GLIBC__)
char *cwd = getcwd(NULL,0);
ret = cwd;
#else
char cwd[MAXPATHLEN+1] ;
ret = getcwd(cwd,MAXPATHLEN+1);
#endif
if (!ret)
myError.SetValue (errno, Iam, "Where");
else {
Name = cwd;
// JPT : August,20 1993. This code has been replaced by #ifdef ... #endif
// position = Name.SearchFromEnd(".");
// if (position != -1){
// Ext = Name;
// Ext.Remove(1,position);
// Name.Remove( position,Ext.Length()+1);
// }
// result.SetValues("","","","","",Name,Ext);
// End
#if defined(vax) || defined(__vms)
Standard_Integer iDisk = Name.Search(":");
if (iDisk){
TCollection_AsciiString Disk;
TCollection_AsciiString Directory;
Disk = Name.SubString(1,iDisk-1);
Directory = Name.SubString(iDisk+1,Name.Length());
result.SetValues("","","",Disk,Directory,"","");
}
#else
Name += TCollection_AsciiString("/");
result = OSD_Path(Name);
// result.SetValues("","","","",Name,"","");
#endif
#if !defined(MAXPATHLEN) && defined(__GLIBC__)
free(cwd);
#endif
}
return (result);
}
void OSD_Process::SetCurrentDirectory(const OSD_Path& where){
TCollection_AsciiString Name;
int status;
where.SystemName(Name);
status = chdir (Name.ToCString());
if (status == -1) myError.SetValue(errno, Iam, "Move to directory");
}
void OSD_Process::Reset(){
myError.Reset();
}
Standard_Boolean OSD_Process::Failed()const{
return( myError.Failed());
}
void OSD_Process::Perror() {
myError.Perror();
}
Standard_Integer OSD_Process::Error()const{
return( myError.Error());
}
#else
//------------------------------------------------------------------------
//------------------- WNT Sources of OSD_Path ---------------------------
//------------------------------------------------------------------------
//it is important to undefine NOUSER and enforce including <windows.h> before
//Standard_Macro.hxx defines it and includes <windows.h> causing compilation errors
#ifdef NOUSER
#undef NOUSER /* we need SW_HIDE from windows.h */
#endif
#include <windows.h>
#ifdef SetCurrentDirectory
# undef SetCurrentDirectory /* undefine SetCurrentDirectory from <winbase.h> to correctly include <OSD_Process.hxx> */
#endif
#include <OSD_Process.hxx>
#include <OSD_Path.hxx>
#include <Quantity_Date.hxx>
#include <OSD_WNT_1.hxx>
#include <lmcons.h> /// pour UNLEN ( see MSDN about GetUserName() )
#if !defined (_MSC_VER) || (_MSC_VER >= 1600)
#include <stdint.h>
#endif
void _osd_wnt_set_error ( OSD_Error&, OSD_WhoAmI, ... );
OSD_Process :: OSD_Process () {
} // end constructor
void OSD_Process :: Spawn ( const TCollection_AsciiString& cmd ,
const Standard_Boolean ShowWindow /* = Standard_True */) {
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory ( &si, sizeof ( STARTUPINFO ) );
si.cb = sizeof ( STARTUPINFO );
//============================================
//---> Added by Stephane Routelous ( [email protected] ) [16.03.01]
//---> Reason : to allow to hide the window
if ( !ShowWindow )
{
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
}
//<--- End Added by Stephane Routelous ( [email protected] ) [16.03.01]
//============================================
if (!CreateProcess (
NULL, (char *)cmd.ToCString (), NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi
)
)
_osd_wnt_set_error ( myError, OSD_WProcess );
else {
CloseHandle ( pi.hThread );
WaitForSingleObject ( pi.hProcess, INFINITE );
CloseHandle ( pi.hProcess );
} // end else
} // end OSD_Process :: Spawn
void OSD_Process :: TerminalType ( TCollection_AsciiString& Name ) {
Name = TEXT( "WIN32 console" );
} // end OSD_Process :: TerminalType
Quantity_Date OSD_Process :: SystemDate () {
Quantity_Date retVal;
SYSTEMTIME st;
GetLocalTime ( &st );
retVal.SetValues (
st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds
);
return retVal;
} // end OSD_Process :: SystemDate
Standard_Integer OSD_Process :: UserId () {
PSID retVal = NULL;
HANDLE hProcessToken = INVALID_HANDLE_VALUE;
PTOKEN_OWNER pTKowner = NULL;
if ( !OpenProcessToken (
GetCurrentProcess (),
TOKEN_QUERY, &hProcessToken
) ||
( pTKowner = ( PTOKEN_OWNER )GetTokenInformationEx (
hProcessToken, TokenOwner
)
) == NULL ||
( retVal = CopySidEx ( pTKowner -> Owner ) ) == NULL
)
_osd_wnt_set_error ( myError, OSD_WProcess );
if ( hProcessToken != INVALID_HANDLE_VALUE ) CloseHandle ( hProcessToken );
if ( pTKowner != NULL ) FreeTokenInformation ( pTKowner );
return ( intptr_t )retVal;
} // end OSD_Process :: UserId
TCollection_AsciiString OSD_Process :: UserName ()
{
Standard_PCharacter pBuff = new char[UNLEN + 1];
DWORD dwSize = UNLEN + 1;
TCollection_AsciiString retVal;
if ( !GetUserName ( pBuff, &dwSize ) )
{
_osd_wnt_set_error ( myError, OSD_WProcess );
}
else
{
TCollection_AsciiString theTmpUserName(pBuff,(int)dwSize -1 );
retVal = theTmpUserName;
}
delete [] pBuff;
return retVal;
} // end OSD_Process :: UserName
Standard_Boolean OSD_Process :: IsSuperUser () {
Standard_Boolean retVal = FALSE;
PSID pSIDadmin;
HANDLE hProcessToken = INVALID_HANDLE_VALUE;
PTOKEN_GROUPS pTKgroups = NULL;
if ( !OpenProcessToken (
GetCurrentProcess (),
TOKEN_QUERY, &hProcessToken
) ||
( pTKgroups = ( PTOKEN_GROUPS )GetTokenInformationEx (
hProcessToken, TokenGroups
)
) == NULL
)
_osd_wnt_set_error ( myError, OSD_WProcess );
else {
pSIDadmin = AdminSid ();
for ( int i = 0; i < ( int )pTKgroups -> GroupCount; ++i )
if ( EqualSid ( pTKgroups -> Groups[ i ].Sid, pSIDadmin ) ) {
retVal = TRUE;
break;
} // end if
} // end else
if ( hProcessToken != INVALID_HANDLE_VALUE ) CloseHandle ( hProcessToken );
if ( pTKgroups != NULL ) FreeTokenInformation ( pTKgroups );
return retVal;
} // end OSD_Process :: IsSuperUser
Standard_Integer OSD_Process :: ProcessId () {
return ( Standard_Integer )GetCurrentProcessId ();
} // end OSD_Process :: ProcessId
OSD_Path OSD_Process :: CurrentDirectory () {
Standard_PCharacter pBuff = NULL;
DWORD dwSize = 0;
OSD_Path retVal;
dwSize = GetCurrentDirectory ( dwSize, pBuff );
pBuff = new Standard_Character[ dwSize ];
if ( ( dwSize = GetCurrentDirectory ( dwSize, pBuff ) ) == NULL )
_osd_wnt_set_error ( myError, OSD_WProcess );
else
retVal = OSD_Path ( pBuff );
delete[] pBuff;
return retVal;
} // end OSD_Process :: CurrentDirectory
void OSD_Process :: SetCurrentDirectory ( const OSD_Path& where ) {
#ifdef UNICODE
# define SetCurrentDirectory SetCurrentDirectoryW
#else
# define SetCurrentDirectory SetCurrentDirectoryA
#endif // UNICODE
TCollection_AsciiString path;
where.SystemName ( path );
if ( !::SetCurrentDirectory ( path.ToCString () ) )
_osd_wnt_set_error ( myError, OSD_WProcess );
} // end OSD_Process :: SetCurrentDirectory
Standard_Boolean OSD_Process :: Failed () const {
return myError.Failed ();
} // end OSD_Process :: Failed
void OSD_Process :: Reset () {
myError.Reset ();
} // end OSD_Process :: Reset
void OSD_Process :: Perror () {
myError.Perror ();
} // end OSD_Process :: Perror
Standard_Integer OSD_Process :: Error () const {
return myError.Error ();
} // end OSD_Process :: Error
#endif
<commit_msg>Capture any system call errors<commit_after>// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2012 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.
#ifdef HAVE_CONFIG_H
# include <oce-config.h>
#endif
#ifndef WNT
#include <OSD_Process.ixx>
#include <OSD_WhoAmI.hxx>
#include <OSD_Environment.hxx>
const OSD_WhoAmI Iam = OSD_WProcess;
#include <errno.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <stdlib.h>
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#if defined(HAVE_TIME_H)
# include <time.h>
#endif
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#ifdef HAVE_PWD_H
# include <pwd.h> // For command getpwuid
#endif
OSD_Process::OSD_Process(){
}
void OSD_Process::Spawn (const TCollection_AsciiString& cmd,
const Standard_Boolean /*ShowWindow*/)
{
if (0 != system(cmd.ToCString()))
myError.SetValue(errno, Iam, "Spawn");
}
void OSD_Process::TerminalType(TCollection_AsciiString& Name){
TCollection_AsciiString which="TERM";
OSD_Environment term (which,"");
term.Value();
which = term.Value();
Name = term.Name();
}
// Get date of system date
Quantity_Date OSD_Process::SystemDate(){
Quantity_Date result;
Standard_Integer month=0,day=0,year=0,hh=0,mn=0,ss=0;
struct tm transfert;
time_t secs;
struct timeval tval;
int status;
status = gettimeofday( &tval, NULL );
if (status == -1) myError.SetValue (errno, Iam, "GetSystem");
else {
secs = tval.tv_sec;
#ifdef HAVE_LOCALTIME_R
localtime_r(&secs, &transfert);
#else
memcpy(&transfert, localtime(&secs), sizeof(struct tm));
#endif
month = transfert.tm_mon + 1; // Add to January (month #1)
day = transfert.tm_mday;
year = transfert.tm_year;
hh = transfert.tm_hour;
mn = transfert.tm_min ;
ss = transfert.tm_sec ;
}
result.SetValues ( month, day, year+1900, hh, mn, ss);
return (result);
}
Standard_Integer OSD_Process::ProcessId(){
return (getpid());
}
Standard_Integer OSD_Process::UserId(){
return (getuid());
}
TCollection_AsciiString OSD_Process::UserName(){
struct passwd *infos;
infos = getpwuid(getuid());
TCollection_AsciiString result=infos->pw_name;
return(result);
}
Standard_Boolean OSD_Process::IsSuperUser (){
if (getuid()) {
return Standard_False;
}
else {
return Standard_True;
}
}
OSD_Path OSD_Process::CurrentDirectory(){
OSD_Path result;
TCollection_AsciiString Name;
char *ret;
#if !defined(MAXPATHLEN) && defined(__GLIBC__)
char *cwd = getcwd(NULL,0);
ret = cwd;
#else
char cwd[MAXPATHLEN+1] ;
ret = getcwd(cwd,MAXPATHLEN+1);
#endif
if (!ret)
myError.SetValue (errno, Iam, "Where");
else {
Name = cwd;
// JPT : August,20 1993. This code has been replaced by #ifdef ... #endif
// position = Name.SearchFromEnd(".");
// if (position != -1){
// Ext = Name;
// Ext.Remove(1,position);
// Name.Remove( position,Ext.Length()+1);
// }
// result.SetValues("","","","","",Name,Ext);
// End
#if defined(vax) || defined(__vms)
Standard_Integer iDisk = Name.Search(":");
if (iDisk){
TCollection_AsciiString Disk;
TCollection_AsciiString Directory;
Disk = Name.SubString(1,iDisk-1);
Directory = Name.SubString(iDisk+1,Name.Length());
result.SetValues("","","",Disk,Directory,"","");
}
#else
Name += TCollection_AsciiString("/");
result = OSD_Path(Name);
// result.SetValues("","","","",Name,"","");
#endif
#if !defined(MAXPATHLEN) && defined(__GLIBC__)
free(cwd);
#endif
}
return (result);
}
void OSD_Process::SetCurrentDirectory(const OSD_Path& where){
TCollection_AsciiString Name;
int status;
where.SystemName(Name);
status = chdir (Name.ToCString());
if (status == -1) myError.SetValue(errno, Iam, "Move to directory");
}
void OSD_Process::Reset(){
myError.Reset();
}
Standard_Boolean OSD_Process::Failed()const{
return( myError.Failed());
}
void OSD_Process::Perror() {
myError.Perror();
}
Standard_Integer OSD_Process::Error()const{
return( myError.Error());
}
#else
//------------------------------------------------------------------------
//------------------- WNT Sources of OSD_Path ---------------------------
//------------------------------------------------------------------------
//it is important to undefine NOUSER and enforce including <windows.h> before
//Standard_Macro.hxx defines it and includes <windows.h> causing compilation errors
#ifdef NOUSER
#undef NOUSER /* we need SW_HIDE from windows.h */
#endif
#include <windows.h>
#ifdef SetCurrentDirectory
# undef SetCurrentDirectory /* undefine SetCurrentDirectory from <winbase.h> to correctly include <OSD_Process.hxx> */
#endif
#include <OSD_Process.hxx>
#include <OSD_Path.hxx>
#include <Quantity_Date.hxx>
#include <OSD_WNT_1.hxx>
#include <lmcons.h> /// pour UNLEN ( see MSDN about GetUserName() )
#if !defined (_MSC_VER) || (_MSC_VER >= 1600)
#include <stdint.h>
#endif
void _osd_wnt_set_error ( OSD_Error&, OSD_WhoAmI, ... );
OSD_Process :: OSD_Process () {
} // end constructor
void OSD_Process :: Spawn ( const TCollection_AsciiString& cmd ,
const Standard_Boolean ShowWindow /* = Standard_True */) {
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory ( &si, sizeof ( STARTUPINFO ) );
si.cb = sizeof ( STARTUPINFO );
//============================================
//---> Added by Stephane Routelous ( [email protected] ) [16.03.01]
//---> Reason : to allow to hide the window
if ( !ShowWindow )
{
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
}
//<--- End Added by Stephane Routelous ( [email protected] ) [16.03.01]
//============================================
if (!CreateProcess (
NULL, (char *)cmd.ToCString (), NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi
)
)
_osd_wnt_set_error ( myError, OSD_WProcess );
else {
CloseHandle ( pi.hThread );
WaitForSingleObject ( pi.hProcess, INFINITE );
CloseHandle ( pi.hProcess );
} // end else
} // end OSD_Process :: Spawn
void OSD_Process :: TerminalType ( TCollection_AsciiString& Name ) {
Name = TEXT( "WIN32 console" );
} // end OSD_Process :: TerminalType
Quantity_Date OSD_Process :: SystemDate () {
Quantity_Date retVal;
SYSTEMTIME st;
GetLocalTime ( &st );
retVal.SetValues (
st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds
);
return retVal;
} // end OSD_Process :: SystemDate
Standard_Integer OSD_Process :: UserId () {
PSID retVal = NULL;
HANDLE hProcessToken = INVALID_HANDLE_VALUE;
PTOKEN_OWNER pTKowner = NULL;
if ( !OpenProcessToken (
GetCurrentProcess (),
TOKEN_QUERY, &hProcessToken
) ||
( pTKowner = ( PTOKEN_OWNER )GetTokenInformationEx (
hProcessToken, TokenOwner
)
) == NULL ||
( retVal = CopySidEx ( pTKowner -> Owner ) ) == NULL
)
_osd_wnt_set_error ( myError, OSD_WProcess );
if ( hProcessToken != INVALID_HANDLE_VALUE ) CloseHandle ( hProcessToken );
if ( pTKowner != NULL ) FreeTokenInformation ( pTKowner );
return ( intptr_t )retVal;
} // end OSD_Process :: UserId
TCollection_AsciiString OSD_Process :: UserName ()
{
Standard_PCharacter pBuff = new char[UNLEN + 1];
DWORD dwSize = UNLEN + 1;
TCollection_AsciiString retVal;
if ( !GetUserName ( pBuff, &dwSize ) )
{
_osd_wnt_set_error ( myError, OSD_WProcess );
}
else
{
TCollection_AsciiString theTmpUserName(pBuff,(int)dwSize -1 );
retVal = theTmpUserName;
}
delete [] pBuff;
return retVal;
} // end OSD_Process :: UserName
Standard_Boolean OSD_Process :: IsSuperUser () {
Standard_Boolean retVal = FALSE;
PSID pSIDadmin;
HANDLE hProcessToken = INVALID_HANDLE_VALUE;
PTOKEN_GROUPS pTKgroups = NULL;
if ( !OpenProcessToken (
GetCurrentProcess (),
TOKEN_QUERY, &hProcessToken
) ||
( pTKgroups = ( PTOKEN_GROUPS )GetTokenInformationEx (
hProcessToken, TokenGroups
)
) == NULL
)
_osd_wnt_set_error ( myError, OSD_WProcess );
else {
pSIDadmin = AdminSid ();
for ( int i = 0; i < ( int )pTKgroups -> GroupCount; ++i )
if ( EqualSid ( pTKgroups -> Groups[ i ].Sid, pSIDadmin ) ) {
retVal = TRUE;
break;
} // end if
} // end else
if ( hProcessToken != INVALID_HANDLE_VALUE ) CloseHandle ( hProcessToken );
if ( pTKgroups != NULL ) FreeTokenInformation ( pTKgroups );
return retVal;
} // end OSD_Process :: IsSuperUser
Standard_Integer OSD_Process :: ProcessId () {
return ( Standard_Integer )GetCurrentProcessId ();
} // end OSD_Process :: ProcessId
OSD_Path OSD_Process :: CurrentDirectory () {
Standard_PCharacter pBuff = NULL;
DWORD dwSize = 0;
OSD_Path retVal;
dwSize = GetCurrentDirectory ( dwSize, pBuff );
pBuff = new Standard_Character[ dwSize ];
if ( ( dwSize = GetCurrentDirectory ( dwSize, pBuff ) ) == NULL )
_osd_wnt_set_error ( myError, OSD_WProcess );
else
retVal = OSD_Path ( pBuff );
delete[] pBuff;
return retVal;
} // end OSD_Process :: CurrentDirectory
void OSD_Process :: SetCurrentDirectory ( const OSD_Path& where ) {
#ifdef UNICODE
# define SetCurrentDirectory SetCurrentDirectoryW
#else
# define SetCurrentDirectory SetCurrentDirectoryA
#endif // UNICODE
TCollection_AsciiString path;
where.SystemName ( path );
if ( !::SetCurrentDirectory ( path.ToCString () ) )
_osd_wnt_set_error ( myError, OSD_WProcess );
} // end OSD_Process :: SetCurrentDirectory
Standard_Boolean OSD_Process :: Failed () const {
return myError.Failed ();
} // end OSD_Process :: Failed
void OSD_Process :: Reset () {
myError.Reset ();
} // end OSD_Process :: Reset
void OSD_Process :: Perror () {
myError.Perror ();
} // end OSD_Process :: Perror
Standard_Integer OSD_Process :: Error () const {
return myError.Error ();
} // end OSD_Process :: Error
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef WNT
#include <OSD_Process.ixx>
#include <OSD_WhoAmI.hxx>
#include <OSD_Environment.hxx>
const OSD_WhoAmI Iam = OSD_WProcess;
#include <errno.h>
#include <stdlib.h>
#include <sys/param.h>
#include <sys/time.h>
#include <pwd.h> // For command getpwuid
#include <unistd.h>
OSD_Process::OSD_Process(){
}
void OSD_Process::Spawn (const TCollection_AsciiString& cmd,
const Standard_Boolean /*ShowWindow*/)
{
if (0 != system(cmd.ToCString()))
myError.SetValue(errno, Iam, "Spawn");
}
void OSD_Process::TerminalType(TCollection_AsciiString& Name){
TCollection_AsciiString which="TERM";
OSD_Environment term (which,"");
term.Value();
which = term.Value();
Name = term.Name();
}
// Get date of system date
Quantity_Date OSD_Process::SystemDate(){
Quantity_Date result;
Standard_Integer month=0,day=0,year=0,hh=0,mn=0,ss=0;
struct tm transfert;
time_t secs;
struct timeval tval;
int status;
status = gettimeofday( &tval, NULL );
if (status == -1) myError.SetValue (errno, Iam, "GetSystem");
else {
secs = tval.tv_sec;
#ifdef HAVE_LOCALTIME_R
localtime_r(&secs, &transfert);
#else
memcpy(&transfert, localtime(&secs), sizeof(struct tm));
#endif
month = transfert.tm_mon + 1; // Add to January (month #1)
day = transfert.tm_mday;
year = transfert.tm_year;
hh = transfert.tm_hour;
mn = transfert.tm_min ;
ss = transfert.tm_sec ;
}
result.SetValues ( month, day, year+1900, hh, mn, ss);
return (result);
}
Standard_Integer OSD_Process::ProcessId(){
return (getpid());
}
Standard_Integer OSD_Process::UserId(){
return (getuid());
}
TCollection_AsciiString OSD_Process::UserName(){
struct passwd *infos;
infos = getpwuid(getuid());
TCollection_AsciiString result=infos->pw_name;
return(result);
}
Standard_Boolean OSD_Process::IsSuperUser (){
if (getuid()) {
return Standard_False;
}
else {
return Standard_True;
}
}
OSD_Path OSD_Process::CurrentDirectory(){
char cwd[MAXPATHLEN+1] ;
OSD_Path result;
TCollection_AsciiString Name;
if (!getcwd(cwd,MAXPATHLEN+1))
myError.SetValue (errno, Iam, "Where");
else {
Name = cwd;
// JPT : August,20 1993. This code has been replaced by #ifdef ... #endif
// position = Name.SearchFromEnd(".");
// if (position != -1){
// Ext = Name;
// Ext.Remove(1,position);
// Name.Remove( position,Ext.Length()+1);
// }
// result.SetValues("","","","","",Name,Ext);
// End
#if defined(vax) || defined(__vms)
Standard_Integer iDisk = Name.Search(":");
if (iDisk){
TCollection_AsciiString Disk;
TCollection_AsciiString Directory;
Disk = Name.SubString(1,iDisk-1);
Directory = Name.SubString(iDisk+1,Name.Length());
result.SetValues("","","",Disk,Directory,"","");
}
#else
Name += TCollection_AsciiString("/");
result = OSD_Path(Name);
// result.SetValues("","","","",Name,"","");
#endif
}
return (result);
}
void OSD_Process::SetCurrentDirectory(const OSD_Path& where){
TCollection_AsciiString Name;
int status;
where.SystemName(Name);
status = chdir (Name.ToCString());
if (status == -1) myError.SetValue(errno, Iam, "Move to directory");
}
void OSD_Process::Reset(){
myError.Reset();
}
Standard_Boolean OSD_Process::Failed()const{
return( myError.Failed());
}
void OSD_Process::Perror() {
myError.Perror();
}
Standard_Integer OSD_Process::Error()const{
return( myError.Error());
}
#else
//------------------------------------------------------------------------
//------------------- WNT Sources of OSD_Path ---------------------------
//------------------------------------------------------------------------
//it is important to undefine NOUSER and enforce including <windows.h> before
//Standard_Macro.hxx defines it and includes <windows.h> causing compilation errors
#ifdef NOUSER
#undef NOUSER /* we need SW_HIDE from windows.h */
#endif
#include <windows.h>
#ifdef SetCurrentDirectory
# undef SetCurrentDirectory /* undefine SetCurrentDirectory from <winbase.h> to correctly include <OSD_Process.hxx> */
#endif
#include <OSD_Process.hxx>
#include <OSD_Path.hxx>
#include <Quantity_Date.hxx>
#include <Standard_PExtCharacter.hxx>
#include <TCollection_ExtendedString.hxx>
#include <OSD_WNT_1.hxx>
#include <LMCONS.H> /// pour UNLEN ( see MSDN about GetUserName() )
#pragma warning( disable : 4700 )
void _osd_wnt_set_error ( OSD_Error&, OSD_WhoAmI, ... );
OSD_Process :: OSD_Process () {
} // end constructor
void OSD_Process :: Spawn ( const TCollection_AsciiString& cmd ,
const Standard_Boolean ShowWindow /* = Standard_True */) {
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory ( &si, sizeof ( STARTUPINFO ) );
si.cb = sizeof ( STARTUPINFO );
//============================================
//---> Added by Stephane Routelous ( [email protected] ) [16.03.01]
//---> Reason : to allow to hide the window
if ( !ShowWindow )
{
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
}
//<--- End Added by Stephane Routelous ( [email protected] ) [16.03.01]
//============================================
if (!CreateProcess (
NULL, (char *)cmd.ToCString (), NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi
)
)
_osd_wnt_set_error ( myError, OSD_WProcess );
else {
CloseHandle ( pi.hThread );
WaitForSingleObject ( pi.hProcess, INFINITE );
CloseHandle ( pi.hProcess );
} // end else
} // end OSD_Process :: Spawn
void OSD_Process :: TerminalType ( TCollection_AsciiString& Name ) {
Name = "WIN32 console";
} // end OSD_Process :: TerminalType
Quantity_Date OSD_Process :: SystemDate () {
Quantity_Date retVal;
SYSTEMTIME st;
GetLocalTime ( &st );
retVal.SetValues (
st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds
);
return retVal;
} // end OSD_Process :: SystemDate
Standard_Integer OSD_Process :: UserId () {
PSID retVal = NULL;
HANDLE hProcessToken = INVALID_HANDLE_VALUE;
PTOKEN_OWNER pTKowner = NULL;
if ( !OpenProcessToken (
GetCurrentProcess (),
TOKEN_QUERY, &hProcessToken
) ||
( pTKowner = ( PTOKEN_OWNER )GetTokenInformationEx (
hProcessToken, TokenOwner
)
) == NULL ||
( retVal = CopySidEx ( pTKowner -> Owner ) ) == NULL
)
_osd_wnt_set_error ( myError, OSD_WProcess );
if ( hProcessToken != INVALID_HANDLE_VALUE ) CloseHandle ( hProcessToken );
if ( pTKowner != NULL ) FreeTokenInformation ( pTKowner );
return ( Standard_Integer )retVal;
} // end OSD_Process :: UserId
TCollection_AsciiString OSD_Process :: UserName ()
{
Standard_PCharacter pBuff = new char[UNLEN + 1];
DWORD dwSize = UNLEN + 1;
TCollection_AsciiString retVal;
if ( !GetUserName ( pBuff, &dwSize ) )
{
_osd_wnt_set_error ( myError, OSD_WProcess );
}
else
{
TCollection_AsciiString theTmpUserName(pBuff,(int)dwSize -1 );
retVal = theTmpUserName;
}
delete [] pBuff;
return retVal;
} // end OSD_Process :: UserName
Standard_Boolean OSD_Process :: IsSuperUser () {
Standard_Boolean retVal = FALSE;
PSID pSIDadmin;
HANDLE hProcessToken = INVALID_HANDLE_VALUE;
PTOKEN_GROUPS pTKgroups = NULL;
if ( !OpenProcessToken (
GetCurrentProcess (),
TOKEN_QUERY, &hProcessToken
) ||
( pTKgroups = ( PTOKEN_GROUPS )GetTokenInformationEx (
hProcessToken, TokenGroups
)
) == NULL
)
_osd_wnt_set_error ( myError, OSD_WProcess );
else {
pSIDadmin = AdminSid ();
for ( int i = 0; i < ( int )pTKgroups -> GroupCount; ++i )
if ( EqualSid ( pTKgroups -> Groups[ i ].Sid, pSIDadmin ) ) {
retVal = TRUE;
break;
} // end if
} // end else
if ( hProcessToken != INVALID_HANDLE_VALUE ) CloseHandle ( hProcessToken );
if ( pTKgroups != NULL ) FreeTokenInformation ( pTKgroups );
return retVal;
} // end OSD_Process :: IsSuperUser
Standard_Integer OSD_Process :: ProcessId () {
return ( Standard_Integer )GetCurrentProcessId ();
} // end OSD_Process :: ProcessId
OSD_Path OSD_Process :: CurrentDirectory () {
OSD_Path anCurrentDirectory;
DWORD dwSize = PATHLEN + 1;
Standard_WideChar* pBuff = new wchar_t[dwSize];
if ( GetCurrentDirectoryW(dwSize, (wchar_t*)pBuff) > 0 )
{
// conversion to UTF-8 is performed inside
TCollection_AsciiString aPath(TCollection_ExtendedString((Standard_ExtString)pBuff));
anCurrentDirectory = OSD_Path ( aPath );
}
else
_osd_wnt_set_error ( myError, OSD_WProcess );
delete[] pBuff;
return anCurrentDirectory;
} // end OSD_Process :: CurrentDirectory
void OSD_Process :: SetCurrentDirectory ( const OSD_Path& where ) {
TCollection_AsciiString path;
where.SystemName ( path );
TCollection_ExtendedString pathW(path);
if ( !::SetCurrentDirectoryW ( (const wchar_t*) pathW.ToExtString () ) )
_osd_wnt_set_error ( myError, OSD_WProcess );
} // end OSD_Process :: SetCurrentDirectory
Standard_Boolean OSD_Process :: Failed () const {
return myError.Failed ();
} // end OSD_Process :: Failed
void OSD_Process :: Reset () {
myError.Reset ();
} // end OSD_Process :: Reset
void OSD_Process :: Perror () {
myError.Perror ();
} // end OSD_Process :: Perror
Standard_Integer OSD_Process :: Error () const {
return myError.Error ();
} // end OSD_Process :: Error
#endif
<commit_msg>Fix OSD_Process::CurrentDirectory() on the Hurd, MAXPATHLEN is not defined<commit_after>// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef WNT
#include <OSD_Process.ixx>
#include <OSD_WhoAmI.hxx>
#include <OSD_Environment.hxx>
const OSD_WhoAmI Iam = OSD_WProcess;
#include <errno.h>
#include <stdlib.h>
#include <sys/param.h>
#include <sys/time.h>
#include <pwd.h> // For command getpwuid
#include <unistd.h>
OSD_Process::OSD_Process(){
}
void OSD_Process::Spawn (const TCollection_AsciiString& cmd,
const Standard_Boolean /*ShowWindow*/)
{
if (0 != system(cmd.ToCString()))
myError.SetValue(errno, Iam, "Spawn");
}
void OSD_Process::TerminalType(TCollection_AsciiString& Name){
TCollection_AsciiString which="TERM";
OSD_Environment term (which,"");
term.Value();
which = term.Value();
Name = term.Name();
}
// Get date of system date
Quantity_Date OSD_Process::SystemDate(){
Quantity_Date result;
Standard_Integer month=0,day=0,year=0,hh=0,mn=0,ss=0;
struct tm transfert;
time_t secs;
struct timeval tval;
int status;
status = gettimeofday( &tval, NULL );
if (status == -1) myError.SetValue (errno, Iam, "GetSystem");
else {
secs = tval.tv_sec;
#ifdef HAVE_LOCALTIME_R
localtime_r(&secs, &transfert);
#else
memcpy(&transfert, localtime(&secs), sizeof(struct tm));
#endif
month = transfert.tm_mon + 1; // Add to January (month #1)
day = transfert.tm_mday;
year = transfert.tm_year;
hh = transfert.tm_hour;
mn = transfert.tm_min ;
ss = transfert.tm_sec ;
}
result.SetValues ( month, day, year+1900, hh, mn, ss);
return (result);
}
Standard_Integer OSD_Process::ProcessId(){
return (getpid());
}
Standard_Integer OSD_Process::UserId(){
return (getuid());
}
TCollection_AsciiString OSD_Process::UserName(){
struct passwd *infos;
infos = getpwuid(getuid());
TCollection_AsciiString result=infos->pw_name;
return(result);
}
Standard_Boolean OSD_Process::IsSuperUser (){
if (getuid()) {
return Standard_False;
}
else {
return Standard_True;
}
}
OSD_Path OSD_Process::CurrentDirectory(){
OSD_Path result;
TCollection_AsciiString Name;
char *ret;
#if !defined(MAXPATHLEN) && defined(__GLIBC__)
char *cwd = getcwd(NULL,0);
ret = cwd;
#else
char cwd[MAXPATHLEN+1] ;
ret = getcwd(cwd,MAXPATHLEN+1);
#endif
if (!ret)
myError.SetValue (errno, Iam, "Where");
else {
Name = cwd;
// JPT : August,20 1993. This code has been replaced by #ifdef ... #endif
// position = Name.SearchFromEnd(".");
// if (position != -1){
// Ext = Name;
// Ext.Remove(1,position);
// Name.Remove( position,Ext.Length()+1);
// }
// result.SetValues("","","","","",Name,Ext);
// End
#if defined(vax) || defined(__vms)
Standard_Integer iDisk = Name.Search(":");
if (iDisk){
TCollection_AsciiString Disk;
TCollection_AsciiString Directory;
Disk = Name.SubString(1,iDisk-1);
Directory = Name.SubString(iDisk+1,Name.Length());
result.SetValues("","","",Disk,Directory,"","");
}
#else
Name += TCollection_AsciiString("/");
result = OSD_Path(Name);
// result.SetValues("","","","",Name,"","");
#endif
#if !defined(MAXPATHLEN) && defined(__GLIBC__)
free(cwd);
#endif
}
return (result);
}
void OSD_Process::SetCurrentDirectory(const OSD_Path& where){
TCollection_AsciiString Name;
int status;
where.SystemName(Name);
status = chdir (Name.ToCString());
if (status == -1) myError.SetValue(errno, Iam, "Move to directory");
}
void OSD_Process::Reset(){
myError.Reset();
}
Standard_Boolean OSD_Process::Failed()const{
return( myError.Failed());
}
void OSD_Process::Perror() {
myError.Perror();
}
Standard_Integer OSD_Process::Error()const{
return( myError.Error());
}
#else
//------------------------------------------------------------------------
//------------------- WNT Sources of OSD_Path ---------------------------
//------------------------------------------------------------------------
//it is important to undefine NOUSER and enforce including <windows.h> before
//Standard_Macro.hxx defines it and includes <windows.h> causing compilation errors
#ifdef NOUSER
#undef NOUSER /* we need SW_HIDE from windows.h */
#endif
#include <windows.h>
#ifdef SetCurrentDirectory
# undef SetCurrentDirectory /* undefine SetCurrentDirectory from <winbase.h> to correctly include <OSD_Process.hxx> */
#endif
#include <OSD_Process.hxx>
#include <OSD_Path.hxx>
#include <Quantity_Date.hxx>
#include <Standard_PExtCharacter.hxx>
#include <TCollection_ExtendedString.hxx>
#include <OSD_WNT_1.hxx>
#include <LMCONS.H> /// pour UNLEN ( see MSDN about GetUserName() )
#pragma warning( disable : 4700 )
void _osd_wnt_set_error ( OSD_Error&, OSD_WhoAmI, ... );
OSD_Process :: OSD_Process () {
} // end constructor
void OSD_Process :: Spawn ( const TCollection_AsciiString& cmd ,
const Standard_Boolean ShowWindow /* = Standard_True */) {
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory ( &si, sizeof ( STARTUPINFO ) );
si.cb = sizeof ( STARTUPINFO );
//============================================
//---> Added by Stephane Routelous ( [email protected] ) [16.03.01]
//---> Reason : to allow to hide the window
if ( !ShowWindow )
{
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
}
//<--- End Added by Stephane Routelous ( [email protected] ) [16.03.01]
//============================================
if (!CreateProcess (
NULL, (char *)cmd.ToCString (), NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi
)
)
_osd_wnt_set_error ( myError, OSD_WProcess );
else {
CloseHandle ( pi.hThread );
WaitForSingleObject ( pi.hProcess, INFINITE );
CloseHandle ( pi.hProcess );
} // end else
} // end OSD_Process :: Spawn
void OSD_Process :: TerminalType ( TCollection_AsciiString& Name ) {
Name = "WIN32 console";
} // end OSD_Process :: TerminalType
Quantity_Date OSD_Process :: SystemDate () {
Quantity_Date retVal;
SYSTEMTIME st;
GetLocalTime ( &st );
retVal.SetValues (
st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds
);
return retVal;
} // end OSD_Process :: SystemDate
Standard_Integer OSD_Process :: UserId () {
PSID retVal = NULL;
HANDLE hProcessToken = INVALID_HANDLE_VALUE;
PTOKEN_OWNER pTKowner = NULL;
if ( !OpenProcessToken (
GetCurrentProcess (),
TOKEN_QUERY, &hProcessToken
) ||
( pTKowner = ( PTOKEN_OWNER )GetTokenInformationEx (
hProcessToken, TokenOwner
)
) == NULL ||
( retVal = CopySidEx ( pTKowner -> Owner ) ) == NULL
)
_osd_wnt_set_error ( myError, OSD_WProcess );
if ( hProcessToken != INVALID_HANDLE_VALUE ) CloseHandle ( hProcessToken );
if ( pTKowner != NULL ) FreeTokenInformation ( pTKowner );
return ( Standard_Integer )retVal;
} // end OSD_Process :: UserId
TCollection_AsciiString OSD_Process :: UserName ()
{
Standard_PCharacter pBuff = new char[UNLEN + 1];
DWORD dwSize = UNLEN + 1;
TCollection_AsciiString retVal;
if ( !GetUserName ( pBuff, &dwSize ) )
{
_osd_wnt_set_error ( myError, OSD_WProcess );
}
else
{
TCollection_AsciiString theTmpUserName(pBuff,(int)dwSize -1 );
retVal = theTmpUserName;
}
delete [] pBuff;
return retVal;
} // end OSD_Process :: UserName
Standard_Boolean OSD_Process :: IsSuperUser () {
Standard_Boolean retVal = FALSE;
PSID pSIDadmin;
HANDLE hProcessToken = INVALID_HANDLE_VALUE;
PTOKEN_GROUPS pTKgroups = NULL;
if ( !OpenProcessToken (
GetCurrentProcess (),
TOKEN_QUERY, &hProcessToken
) ||
( pTKgroups = ( PTOKEN_GROUPS )GetTokenInformationEx (
hProcessToken, TokenGroups
)
) == NULL
)
_osd_wnt_set_error ( myError, OSD_WProcess );
else {
pSIDadmin = AdminSid ();
for ( int i = 0; i < ( int )pTKgroups -> GroupCount; ++i )
if ( EqualSid ( pTKgroups -> Groups[ i ].Sid, pSIDadmin ) ) {
retVal = TRUE;
break;
} // end if
} // end else
if ( hProcessToken != INVALID_HANDLE_VALUE ) CloseHandle ( hProcessToken );
if ( pTKgroups != NULL ) FreeTokenInformation ( pTKgroups );
return retVal;
} // end OSD_Process :: IsSuperUser
Standard_Integer OSD_Process :: ProcessId () {
return ( Standard_Integer )GetCurrentProcessId ();
} // end OSD_Process :: ProcessId
OSD_Path OSD_Process :: CurrentDirectory () {
OSD_Path anCurrentDirectory;
DWORD dwSize = PATHLEN + 1;
Standard_WideChar* pBuff = new wchar_t[dwSize];
if ( GetCurrentDirectoryW(dwSize, (wchar_t*)pBuff) > 0 )
{
// conversion to UTF-8 is performed inside
TCollection_AsciiString aPath(TCollection_ExtendedString((Standard_ExtString)pBuff));
anCurrentDirectory = OSD_Path ( aPath );
}
else
_osd_wnt_set_error ( myError, OSD_WProcess );
delete[] pBuff;
return anCurrentDirectory;
} // end OSD_Process :: CurrentDirectory
void OSD_Process :: SetCurrentDirectory ( const OSD_Path& where ) {
TCollection_AsciiString path;
where.SystemName ( path );
TCollection_ExtendedString pathW(path);
if ( !::SetCurrentDirectoryW ( (const wchar_t*) pathW.ToExtString () ) )
_osd_wnt_set_error ( myError, OSD_WProcess );
} // end OSD_Process :: SetCurrentDirectory
Standard_Boolean OSD_Process :: Failed () const {
return myError.Failed ();
} // end OSD_Process :: Failed
void OSD_Process :: Reset () {
myError.Reset ();
} // end OSD_Process :: Reset
void OSD_Process :: Perror () {
myError.Perror ();
} // end OSD_Process :: Perror
Standard_Integer OSD_Process :: Error () const {
return myError.Error ();
} // end OSD_Process :: Error
#endif
<|endoftext|> |
<commit_before>#include <string>
#include <cstring>
#include <fstream>
#include <vector>
#include "global.h"
#include "RoleFactory.h"
#include "util/EventSender.h"
LogCategory mainlog("main", "Main");
ConfigVariable<std::vector<std::string>> dc_files("general/dc_files", std::vector<std::string>());
int main(int argc, char *argv[])
{
std::string cfg_file;
//TODO: Perhaps verbosity should be specified via command-line switch?
if(argc < 2)
{
cfg_file = "openotpd.yml";
}
else
{
cfg_file = "openotpd.yml";
for(int i = 1; i < argc; i++)
{
if(strcmp(argv[i], "--config") == 0 && i + 1 < argc)
{
cfg_file = argv[++i];
}
else if(strcmp(argv[i], "--log") == 0 && i + 1 < argc)
{
delete g_logger;
g_logger = new Logger(argv[++i]);
}
}
}
mainlog.info() << "Loading configuration file..." << std::endl;
std::ifstream file(cfg_file.c_str());
if(!file.is_open())
{
mainlog.fatal() << "Failed to open configuration file." << std::endl;
return 1;
}
if(!g_config->load(file))
{
mainlog.fatal() << "Could not parse configuration file!" << std::endl;
return 1;
}
file.close();
std::vector<std::string> dc_file_names = dc_files.get_val();
for(auto it = dc_file_names.begin(); it != dc_file_names.end(); ++it)
{
if(!g_dcf->read(*it))
{
mainlog.fatal() << "Could not read DC file " << *it << std::endl;
return 1;
}
}
MessageDirector::singleton.init_network();
g_eventsender.init();
YAML::Node node = g_config->copy_node();
node = node["roles"];
for(auto it = node.begin(); it != node.end(); ++it)
{
RoleFactory::singleton.instantiate_role((*it)["type"].as<std::string>(), *it);
}
try
{
io_service.run();
}
catch(std::exception &e)
{
mainlog.fatal() << "Exception from the network io service: "
<< e.what() << std::endl;
}
//gDCF->read("filename.dc");
// TODO: Load DC, bind/connect MD, and instantiate components.
// TODO: Run libevent main loop.
return 0;
}
<commit_msg>Cleanup: Config is a positional argument, log has the -L shorthand<commit_after>#include <string>
#include <cstring>
#include <fstream>
#include <vector>
#include "global.h"
#include "RoleFactory.h"
#include "util/EventSender.h"
LogCategory mainlog("main", "Main");
ConfigVariable<std::vector<std::string>> dc_files("general/dc_files", std::vector<std::string>());
int main(int argc, char *argv[])
{
std::string cfg_file;
//TODO: Perhaps verbosity should be specified via command-line switch?
if(argc < 2)
{
cfg_file = "openotpd.yml";
}
else
{
cfg_file = "openotpd.yml";
for(int i = 1; i < argc; i++)
{
if((strcmp(argv[i], "--log") == 0 || strcmp(argv[i], "-l") == 0) && i + 1 < argc)
{
delete g_logger;
g_logger = new Logger(argv[++i]);
}
}
if(argv[argc - 1][0] != '-')
{
cfg_file = argv[argc - 1];
}
}
mainlog.info() << "Loading configuration file..." << std::endl;
std::ifstream file(cfg_file.c_str());
if(!file.is_open())
{
mainlog.fatal() << "Failed to open configuration file." << std::endl;
return 1;
}
if(!g_config->load(file))
{
mainlog.fatal() << "Could not parse configuration file!" << std::endl;
return 1;
}
file.close();
std::vector<std::string> dc_file_names = dc_files.get_val();
for(auto it = dc_file_names.begin(); it != dc_file_names.end(); ++it)
{
if(!g_dcf->read(*it))
{
mainlog.fatal() << "Could not read DC file " << *it << std::endl;
return 1;
}
}
MessageDirector::singleton.init_network();
g_eventsender.init();
YAML::Node node = g_config->copy_node();
node = node["roles"];
for(auto it = node.begin(); it != node.end(); ++it)
{
RoleFactory::singleton.instantiate_role((*it)["type"].as<std::string>(), *it);
}
try
{
io_service.run();
}
catch(std::exception &e)
{
mainlog.fatal() << "Exception from the network io service: "
<< e.what() << std::endl;
}
//gDCF->read("filename.dc");
// TODO: Load DC, bind/connect MD, and instantiate components.
// TODO: Run libevent main loop.
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Datto 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 <nanomsg/pair.h>
#include <memory>
#include <util/MessageQueue.h>
#include <iostream>
#include <algorithm>
#include <msgpack.hpp>
#include <thread>
#include <util/logging.h>
#include <giomm/dbusconnection.h>
#include "nanomsg.h"
#include "RDPServerWorker.h"
#include "rdp/RDPListener.h"
#include "common.h"
Glib::ustring RDPServerWorker::introspection_xml =
"<node>"
" <interface name='org.RDPMux.ServerWorker'>"
" <property type='i' name='Port' access='read' />"
" </interface>"
"</node>";
void RDPServerWorker::setDBusConnection(Glib::RefPtr<Gio::DBus::Connection> conn)
{
if (!dbus_conn)
dbus_conn = conn;
}
void RDPServerWorker::run()
{
int to = 1000000;
// create nanomsg socket using the path passed in.
// ACHTUNG: remember that the path _must exist_ on the filesystem, otherwise this silently fails!
// TODO: Make it throw an exception when the file path doesn't exist.
nn::socket *sock = new nn::socket(AF_SP, NN_PAIR);
try {
VLOG(3) << "Socket path is " << this->socket_path.data();
sock->bind(this->socket_path.data());
sock->setsockopt(NN_SOL_SOCKET, NN_RCVTIMEO, &to, sizeof(to));
// chmod socket to 777 // TODO: replace with actual solution
chmod(this->socket_path.data(), S_IRWXU | S_IRWXG | S_IRWXO);
} catch (nn::exception &ex) {
LOG(WARNING) << "Socket binding went wrong: " << ex.what();
return;
}
VLOG(2) << "WORKER " << this << ": Socket bound, hopefully it's listening properly. Address: " << sock;
// TODO: If listener startup fails, ServerWorker won't know about it :(
VLOG(3) << "WORKER " << this << ": Now passing sock to RDP listener and starting listener thread";
std::thread listener_thread([this](nn::socket *socket) {
VLOG(3) << "WORKER " << this << ": Internal socket pointer is " << socket;
RDPListener *listener;
try {
listener = new RDPListener(socket);
} catch (std::runtime_error &e) {
LOG(WARNING) << "WORKER " << this << ": Listener startup failed";
return;
}
l = listener;
listener->RunServer(this->port);
delete l;
}, sock);
listener_thread.detach();
// now that listener is up we can register the object on the bus
const Gio::DBus::InterfaceVTable vtable(sigc::mem_fun(*this, &RDPServerWorker::on_method_call), sigc::mem_fun(*this, &RDPServerWorker::on_property_call));
Glib::ustring worker_dbus_base_name = "/org/RDPMux/ServerWorker/";
// sanitize uuid before creating dbus object
std::string thing = uuid;
thing.erase(std::remove(thing.begin(), thing.end(), '-'), thing.end());
worker_dbus_base_name += thing;
Glib::RefPtr<Gio::DBus::NodeInfo> introspection_data;
try {
introspection_data = Gio::DBus::NodeInfo::create_for_xml(introspection_xml);
} catch (const Glib::Error &ex) {
LOG(WARNING) << "WORKER " << this << ": Unable to create ServerWorker introspection data.";
return;
}
registered_id = dbus_conn->register_object(worker_dbus_base_name,
introspection_data->lookup_interface(), vtable);
MessageQueue qemu_event_queue;
// main QEMU recv loop.
while (true) {
{
// check if we are terminating
Glib::Mutex::Lock lock(mutex);
if (stop) {
delete l;
break;
}
}
// Then we process incoming qemu events and send them to the RDP client
while (!qemu_event_queue.isEmpty()) {
processIncomingMessage(qemu_event_queue.dequeue());
}
// finally, we block waiting on new qemu events to come to us, and put them on the queue when they do.
void *buf = nullptr;
VLOG(3) << "WORKER " << this << ": Blocking on socket receive now";
int nbytes = sock->recv(&buf, NN_MSG, 0); // blocking
VLOG(3) << "WORKER " << this << ": Received event from socket";
if (nbytes > 0) {
QueueItem *item = new QueueItem(buf, nbytes); // QueueItem is responsible for the buf from this point on.
qemu_event_queue.enqueue(item);
}
}
dbus_conn->unregister_object(registered_id);
VLOG(1) << "WORKER " << this << ": Main loop terminated.";
}
void RDPServerWorker::processIncomingMessage(const QueueItem *item)
{
std::vector<uint32_t> rvec;
// deserialize message
msgpack::unpacked msg;
msgpack::unpack(&msg, (char *) item->item, (size_t) item->item_size);
VLOG(3) << "WORKER " << this << ": Unpacked object, now converting it to a vector";
try {
msgpack::object obj = msg.get();
obj.convert(&rvec);
} catch (std::exception& ex) {
LOG(ERROR) << "Msgpack conversion failed: " << ex.what();
LOG(ERROR) << "Offending buffer is " << msg.get();
return;
}
VLOG(2) << "WORKER " << this << ": Incoming vector is: " << rvec;
// now we filter by what type of message it is
if (rvec[0] == DISPLAY_UPDATE) {
VLOG(1) << "WORKER " << this << ": DisplayWorker processing display update event now";
l->processDisplayUpdate(rvec);
} else if (rvec[0] == DISPLAY_SWITCH) {
VLOG(2) << "WORKER " << this << ": DisplayWorker processing display switch event now";
l->processDisplaySwitch(rvec, this->vm_id);
} else if (rvec[0] == SHUTDOWN) {
VLOG(2) << "WORKER " << this << ": Shutdown event received!";
// TODO: process shutdown events
} else {
// what the hell have you sent me
LOG(WARNING) << "Invalid message type sent.";
}
// by deleting the item, we also free the buf
delete item;
}
void RDPServerWorker::on_method_call(const Glib::RefPtr<Gio::DBus::Connection> &,
const Glib::ustring &,
const Glib::ustring &,
const Glib::ustring &,
const Glib::ustring &method_name,
const Glib::VariantContainerBase ¶meters,
const Glib::RefPtr<Gio::DBus::MethodInvocation> &invocation)
{
// no methods for now, but this stub needs to be here
}
void RDPServerWorker::on_property_call(Glib::VariantBase& property,
const Glib::RefPtr<Gio::DBus::Connection>&,
const Glib::ustring&, // sender
const Glib::ustring&, // object path
const Glib::ustring&, // interface_name
const Glib::ustring& property_name)
{
if (property_name == "Port") {
property = Glib::Variant<uint16_t>::create(port);
}
}<commit_msg>Fixed setting permissions on socket<commit_after>/*
* Copyright 2016 Datto 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 <nanomsg/pair.h>
#include <memory>
#include <util/MessageQueue.h>
#include <iostream>
#include <algorithm>
#include <sys/stat.h>
#include <msgpack.hpp>
#include <thread>
#include <util/logging.h>
#include <giomm/dbusconnection.h>
#include "nanomsg.h"
#include "RDPServerWorker.h"
#include "common.h"
Glib::ustring RDPServerWorker::introspection_xml =
"<node>"
" <interface name='org.RDPMux.ServerWorker'>"
" <property type='i' name='Port' access='read' />"
" </interface>"
"</node>";
void RDPServerWorker::setDBusConnection(Glib::RefPtr<Gio::DBus::Connection> conn)
{
if (!dbus_conn)
dbus_conn = conn;
}
void RDPServerWorker::run()
{
int to = 1000000;
nn::socket *sock = new nn::socket(AF_SP, NN_PAIR);
try {
VLOG(3) << "Socket path is " << this->socket_path.data();
sock->bind(this->socket_path.data());
sock->setsockopt(NN_SOL_SOCKET, NN_RCVTIMEO, &to, sizeof(to));
// chmod socket to 777 // TODO: replace with actual solution
auto path = this->socket_path.substr(6, Glib::ustring::npos);
if (chmod(path.data(), S_IRWXU | S_IRWXG | S_IRWXO) < 0) {
LOG(WARNING) << "Setting permissions on the socket failed: " << strerror(errno);
}
} catch (nn::exception &ex) {
LOG(WARNING) << "Socket binding went wrong: " << ex.what();
return;
}
VLOG(2) << "WORKER " << this << ": Socket bound, hopefully it's listening properly. Address: " << sock;
// TODO: If listener startup fails, ServerWorker won't know about it :(
VLOG(3) << "WORKER " << this << ": Now passing sock to RDP listener and starting listener thread";
std::thread listener_thread([this](nn::socket *socket) {
VLOG(3) << "WORKER " << this << ": Internal socket pointer is " << socket;
RDPListener *listener;
try {
listener = new RDPListener(socket);
} catch (std::runtime_error &e) {
LOG(WARNING) << "WORKER " << this << ": Listener startup failed";
return;
}
l = listener;
listener->RunServer(this->port);
delete l;
}, sock);
listener_thread.detach();
// now that listener is up we can register the object on the bus
const Gio::DBus::InterfaceVTable vtable(sigc::mem_fun(*this, &RDPServerWorker::on_method_call), sigc::mem_fun(*this, &RDPServerWorker::on_property_call));
Glib::ustring worker_dbus_base_name = "/org/RDPMux/ServerWorker/";
// sanitize uuid before creating dbus object
std::string thing = uuid;
thing.erase(std::remove(thing.begin(), thing.end(), '-'), thing.end());
worker_dbus_base_name += thing;
Glib::RefPtr<Gio::DBus::NodeInfo> introspection_data;
try {
introspection_data = Gio::DBus::NodeInfo::create_for_xml(introspection_xml);
} catch (const Glib::Error &ex) {
LOG(WARNING) << "WORKER " << this << ": Unable to create ServerWorker introspection data.";
return;
}
registered_id = dbus_conn->register_object(worker_dbus_base_name,
introspection_data->lookup_interface(), vtable);
MessageQueue qemu_event_queue;
// main QEMU recv loop.
while (true) {
{
// check if we are terminating
Glib::Mutex::Lock lock(mutex);
if (stop) {
delete l;
break;
}
}
// Then we process incoming qemu events and send them to the RDP client
while (!qemu_event_queue.isEmpty()) {
processIncomingMessage(qemu_event_queue.dequeue());
}
// finally, we block waiting on new qemu events to come to us, and put them on the queue when they do.
void *buf = nullptr;
VLOG(3) << "WORKER " << this << ": Blocking on socket receive now";
int nbytes = sock->recv(&buf, NN_MSG, 0); // blocking
VLOG(3) << "WORKER " << this << ": Received event from socket";
if (nbytes > 0) {
QueueItem *item = new QueueItem(buf, nbytes); // QueueItem is responsible for the buf from this point on.
qemu_event_queue.enqueue(item);
}
}
dbus_conn->unregister_object(registered_id);
VLOG(1) << "WORKER " << this << ": Main loop terminated.";
}
void RDPServerWorker::processIncomingMessage(const QueueItem *item)
{
std::vector<uint32_t> rvec;
// deserialize message
msgpack::unpacked msg;
msgpack::unpack(&msg, (char *) item->item, (size_t) item->item_size);
VLOG(3) << "WORKER " << this << ": Unpacked object, now converting it to a vector";
try {
msgpack::object obj = msg.get();
obj.convert(&rvec);
} catch (std::exception& ex) {
LOG(ERROR) << "Msgpack conversion failed: " << ex.what();
LOG(ERROR) << "Offending buffer is " << msg.get();
return;
}
VLOG(2) << "WORKER " << this << ": Incoming vector is: " << rvec;
// now we filter by what type of message it is
if (rvec[0] == DISPLAY_UPDATE) {
VLOG(1) << "WORKER " << this << ": DisplayWorker processing display update event now";
l->processDisplayUpdate(rvec);
} else if (rvec[0] == DISPLAY_SWITCH) {
VLOG(2) << "WORKER " << this << ": DisplayWorker processing display switch event now";
l->processDisplaySwitch(rvec, this->vm_id);
} else if (rvec[0] == SHUTDOWN) {
VLOG(2) << "WORKER " << this << ": Shutdown event received!";
// TODO: process shutdown events
} else {
// what the hell have you sent me
LOG(WARNING) << "Invalid message type sent.";
}
// by deleting the item, we also free the buf
delete item;
}
void RDPServerWorker::on_method_call(const Glib::RefPtr<Gio::DBus::Connection> &,
const Glib::ustring &,
const Glib::ustring &,
const Glib::ustring &,
const Glib::ustring &method_name,
const Glib::VariantContainerBase ¶meters,
const Glib::RefPtr<Gio::DBus::MethodInvocation> &invocation)
{
// no methods for now, but this stub needs to be here
}
void RDPServerWorker::on_property_call(Glib::VariantBase& property,
const Glib::RefPtr<Gio::DBus::Connection>&,
const Glib::ustring&, // sender
const Glib::ustring&, // object path
const Glib::ustring&, // interface_name
const Glib::ustring& property_name)
{
if (property_name == "Port") {
property = Glib::Variant<uint16_t>::create(port);
}
}<|endoftext|> |
<commit_before>// RemoveOrAddTool.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "RemoveOrAddTool.h"
#include "../interface/HeeksObj.h"
#include "MarkedList.h"
RemoveOrAddTool::RemoveOrAddTool(HeeksObj *object, HeeksObj *owner, HeeksObj *prev_object) : m_belongs_to_owner(false)
{
m_object = object;
m_owner = owner;
m_prev_object = prev_object;
}
RemoveOrAddTool::~RemoveOrAddTool()
{
if(m_owner == NULL)return;
if(!m_belongs_to_owner)delete m_object;
}
static wxString string_for_GetTitle;
const wxChar* AddObjectTool::GetTitle()
{
string_for_GetTitle.assign(_("Add "));
string_for_GetTitle.append(m_object->GetShortStringOrTypeString());
return string_for_GetTitle.c_str();
}
void RemoveOrAddTool::Add()
{
if (wxGetApp().m_doing_rollback && (m_owner == NULL))
{
m_owner = NULL;
}
if (m_owner == NULL)
{
wxMessageBox(_T("Can't Have NULL owner!"));
return;
}
m_owner->Add(m_object, m_prev_object);
wxGetApp().WasAdded(m_object);
wxGetApp().WasModified(m_owner);
m_belongs_to_owner = true;
}
void RemoveOrAddTool::Remove()
{
while (m_object->Owner())
{
m_owner = m_object->Owner();
m_object->Owner()->Remove(m_object);
wxGetApp().WasRemoved(m_object);
wxGetApp().WasModified(m_owner);
m_object->RemoveOwner(m_object->Owner());
}
m_belongs_to_owner = false;
}
void AddObjectTool::Run()
{
Add();
}
void AddObjectTool::RollBack()
{
Remove();
}
RemoveObjectTool::RemoveObjectTool(HeeksObj *object):RemoveOrAddTool(object, NULL, NULL)
{
if(object)m_owner = object->Owner();
else m_owner = NULL;
}
void RemoveObjectTool::Run()
{
Remove();
}
void RemoveObjectTool::RollBack()
{
Add();
}
ManyRemoveOrAddTool::~ManyRemoveOrAddTool()
{
if(!m_belongs_to_owner){
std::list<HeeksObj*>::iterator It;
for(It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
delete object;
}
}
}
void ManyRemoveOrAddTool::Add()
{
if (m_owner == NULL)
{
wxMessageBox(_T("Can't have NULL owner!"));
return;
}
std::list<HeeksObj*>::iterator It;
for(It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
m_owner->Add(object, NULL);
}
wxGetApp().WereAdded(m_objects);
wxGetApp().WasModified(m_owner);
m_belongs_to_owner = true;
}
void ManyRemoveOrAddTool::Remove()
{
std::list<HeeksObj*>::iterator It;
for(It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
if(m_owner)
m_owner->Remove(object);
wxGetApp().m_marked_list->Remove(object, false);
}
wxGetApp().WereRemoved(m_objects);
wxGetApp().WasModified(m_owner);
for(It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
object->RemoveOwners();
}
m_belongs_to_owner = false;
}
const wxChar* AddObjectsTool::GetTitle()
{
return _("Add Objects");
}
void AddObjectsTool::Run()
{
Add();
}
void AddObjectsTool::RollBack()
{
Remove();
}
const wxChar* RemoveObjectsTool::GetTitle()
{
return _("Remove Objects");
}
void RemoveObjectsTool::Run()
{
Remove();
}
void RemoveObjectsTool::RollBack()
{
Add();
}
void ChangeOwnerTool::Run()
{
// to do
}
void ChangeOwnerTool::RollBack()
{
// to do
}
ManyChangeOwnerTool::ManyChangeOwnerTool(const std::list<HeeksObj*> &list, HeeksObj* new_owner): m_objects(list), m_new_owner(new_owner)
{
for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
m_prev_owners.push_back(object->Owner());
}
}
void ManyChangeOwnerTool::Run()
{
for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
object->Owner()->Remove(object);
wxGetApp().m_marked_list->Remove(object, false);
}
wxGetApp().WereRemoved(m_objects);
wxGetApp().WereModified(m_prev_owners);
for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
m_new_owner->Add(object, NULL);
}
wxGetApp().WereAdded(m_objects);
wxGetApp().WasModified(m_new_owner);
}
void ManyChangeOwnerTool::RollBack()
{
for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
m_new_owner->Remove(object);
wxGetApp().m_marked_list->Remove(object, false);
}
wxGetApp().WereRemoved(m_objects);
wxGetApp().WasModified(m_new_owner);
std::list<HeeksObj*>::iterator PrevIt = m_objects.begin();
for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++, PrevIt++){
HeeksObj* object = *It;
HeeksObj* prev_owner = *PrevIt;
prev_owner->Add(object, NULL);
}
wxGetApp().WereAdded(m_objects);
wxGetApp().WereModified(m_prev_owners);
}
<commit_msg>I fixed a problem < create two points, select them, do "Group", they don't appear in the group in the tree >. This problem appeared after Jon Pry's multiple parents change. This doesn't fix celeron55's < if I copy & paste a group, it will do it, but the result is an empty group and copies of the solids in it >, which I will fix before the end of this day.<commit_after>// RemoveOrAddTool.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "RemoveOrAddTool.h"
#include "../interface/HeeksObj.h"
#include "MarkedList.h"
RemoveOrAddTool::RemoveOrAddTool(HeeksObj *object, HeeksObj *owner, HeeksObj *prev_object) : m_belongs_to_owner(false)
{
m_object = object;
m_owner = owner;
m_prev_object = prev_object;
}
RemoveOrAddTool::~RemoveOrAddTool()
{
if(m_owner == NULL)return;
if(!m_belongs_to_owner)delete m_object;
}
static wxString string_for_GetTitle;
const wxChar* AddObjectTool::GetTitle()
{
string_for_GetTitle.assign(_("Add "));
string_for_GetTitle.append(m_object->GetShortStringOrTypeString());
return string_for_GetTitle.c_str();
}
void RemoveOrAddTool::Add()
{
if (wxGetApp().m_doing_rollback && (m_owner == NULL))
{
m_owner = NULL;
}
if (m_owner == NULL)
{
wxMessageBox(_T("Can't Have NULL owner!"));
return;
}
m_owner->Add(m_object, m_prev_object);
wxGetApp().WasAdded(m_object);
wxGetApp().WasModified(m_owner);
m_belongs_to_owner = true;
}
void RemoveOrAddTool::Remove()
{
while (m_object->Owner())
{
m_owner = m_object->Owner();
m_object->Owner()->Remove(m_object);
wxGetApp().WasRemoved(m_object);
wxGetApp().WasModified(m_owner);
m_object->RemoveOwner(m_object->Owner());
}
m_belongs_to_owner = false;
}
void AddObjectTool::Run()
{
Add();
}
void AddObjectTool::RollBack()
{
Remove();
}
RemoveObjectTool::RemoveObjectTool(HeeksObj *object):RemoveOrAddTool(object, NULL, NULL)
{
if(object)m_owner = object->Owner();
else m_owner = NULL;
}
void RemoveObjectTool::Run()
{
Remove();
}
void RemoveObjectTool::RollBack()
{
Add();
}
ManyRemoveOrAddTool::~ManyRemoveOrAddTool()
{
if(!m_belongs_to_owner){
std::list<HeeksObj*>::iterator It;
for(It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
delete object;
}
}
}
void ManyRemoveOrAddTool::Add()
{
if (m_owner == NULL)
{
wxMessageBox(_T("Can't have NULL owner!"));
return;
}
std::list<HeeksObj*>::iterator It;
for(It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
m_owner->Add(object, NULL);
}
wxGetApp().WereAdded(m_objects);
wxGetApp().WasModified(m_owner);
m_belongs_to_owner = true;
}
void ManyRemoveOrAddTool::Remove()
{
std::list<HeeksObj*>::iterator It;
for(It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
if(m_owner)
m_owner->Remove(object);
wxGetApp().m_marked_list->Remove(object, false);
}
wxGetApp().WereRemoved(m_objects);
wxGetApp().WasModified(m_owner);
for(It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
object->RemoveOwners();
}
m_belongs_to_owner = false;
}
const wxChar* AddObjectsTool::GetTitle()
{
return _("Add Objects");
}
void AddObjectsTool::Run()
{
Add();
}
void AddObjectsTool::RollBack()
{
Remove();
}
const wxChar* RemoveObjectsTool::GetTitle()
{
return _("Remove Objects");
}
void RemoveObjectsTool::Run()
{
Remove();
}
void RemoveObjectsTool::RollBack()
{
Add();
}
void ChangeOwnerTool::Run()
{
// to do
}
void ChangeOwnerTool::RollBack()
{
// to do
}
ManyChangeOwnerTool::ManyChangeOwnerTool(const std::list<HeeksObj*> &list, HeeksObj* new_owner): m_objects(list), m_new_owner(new_owner)
{
for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
m_prev_owners.push_back(object->Owner());
}
}
void ManyChangeOwnerTool::Run()
{
for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
object->Owner()->Remove(object);
wxGetApp().m_marked_list->Remove(object, false);
}
wxGetApp().WereRemoved(m_objects);
wxGetApp().WereModified(m_prev_owners);
for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
object->RemoveOwner(object->Owner());
m_new_owner->Add(object, NULL);
}
wxGetApp().WereAdded(m_objects);
wxGetApp().WasModified(m_new_owner);
}
void ManyChangeOwnerTool::RollBack()
{
for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
HeeksObj* object = *It;
m_new_owner->Remove(object);
wxGetApp().m_marked_list->Remove(object, false);
}
wxGetApp().WereRemoved(m_objects);
wxGetApp().WasModified(m_new_owner);
std::list<HeeksObj*>::iterator PrevIt = m_objects.begin();
for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++, PrevIt++){
HeeksObj* object = *It;
HeeksObj* prev_owner = *PrevIt;
prev_owner->Add(object, NULL);
}
wxGetApp().WereAdded(m_objects);
wxGetApp().WereModified(m_prev_owners);
}
<|endoftext|> |
<commit_before>#include "TextInputWidget.hpp"
#include <iostream>
gsf::TextInputWidget::TextInputWidget(float width, float height, sf::Font &font)
: ChildWidget{ width, height }
//, m_text{ "", font, 12, sf::Color::Black }
, m_text{ nullptr }
, m_cursor{ "|", font, 12 }
, m_scrollable{ nullptr }
, m_isFocused{ false }
, m_cursorPos{ 0 }
, m_lBreaksBefCur{ 0 }
, m_isCursorShown{ true }
, m_blinkFreq{ 0.8f }
, m_lastBlinkTime{ 0.f }
, m_minBreakCharCnt{ 0 }
{
std::unique_ptr<TextWidget> text{
std::make_unique<TextWidget>("", font, 12, sf::Color::Black) };
std::unique_ptr<ScrollableWidget> scrollabe{
std::make_unique<ScrollableWidget>(width, height) };
m_scrollable = scrollabe.get();
m_text = text.get();
scrollabe->setBackgroundColor(sf::Color::Red);
scrollabe->attachChild(std::move(text));
//attachChild(std::move(text));
attachChild(std::move(scrollabe));
m_cursor.setFillColor(sf::Color::Black);
//m_text.setFont(font);
//m_text.setCharacterSize(12);
//m_text.setTextColor(sf::Color::Black);
//m_text.setOrigin(0.f, 0.f);
//m_text.setPosition(0.f, 0.f);
//m_scrollableWidget.attachChild();
}
void gsf::TextInputWidget::setText(const std::string &text)
{
m_text->setText(text);
}
std::string gsf::TextInputWidget::getText() const
{
return m_text->getText().toAnsiString();
}
void gsf::TextInputWidget::setCharacterSize(const unsigned int size)
{
m_text->setCharacterSize(size);
}
unsigned int gsf::TextInputWidget::getCharacterSize() const
{
return m_text->getCharacterSize();
}
void gsf::TextInputWidget::setTextColor(const sf::Color color)
{
m_text->setTextColor(color);
}
sf::Color gsf::TextInputWidget::getTextColor() const
{
return m_text->getTextColor();
}
bool gsf::TextInputWidget::isFocused() const
{
return m_isFocused;
}
void gsf::TextInputWidget::setIsVerticalScrollEnabled(bool isEnabled)
{
m_scrollable->setIsVerticalScrollEnabled(isEnabled);
}
bool gsf::TextInputWidget::isVerticalScrollEnabled() const
{
return m_scrollable->isVerticalScrollEnabled();
}
void gsf::TextInputWidget::setIsHorizontalScrollEnabled(bool isEnabled)
{
m_scrollable->setIsHorizontalScrollEnabled(isEnabled);
}
bool gsf::TextInputWidget::isHorizontalScrollEnabled() const
{
return m_scrollable->isHorizontalScrollEnabled();
}
void gsf::TextInputWidget::drawCurrent(sf::RenderTarget &target,
sf::RenderStates states) const
{
}
void gsf::TextInputWidget::drawCurrentAfterChildren(sf::RenderTarget &target,
sf::RenderStates states) const
{
// Draw cursor after children, so that children are not drawn over cursor
if (m_isCursorShown)
{
target.draw(m_cursor, states);
}
}
void gsf::TextInputWidget::updateCurrent(float dt)
{
// Update cursor stuff
m_lastBlinkTime += dt;
if (m_lastBlinkTime >= m_blinkFreq)
{
m_isCursorShown = !m_isCursorShown;
m_lastBlinkTime = 0.f;
}
//std::wstring text{ m_currentText };
//std::wstring text{ m_shownText };
//m_text->setText(text);
}
bool gsf::TextInputWidget::handleEventCurrent(sf::Event &event)
{
//bool handled{ ChildWidget::handleEvent(event) };/*||
// m_scrollable->handleEventWidget(event) };*/
// Check if actual Widget is focused
if (event.type == sf::Event::MouseButtonPressed)
{
sf::Vector2f mousePos{ (float) event.mouseButton.x,
(float) event.mouseButton.y };
bool isMouseInShownArea{ getShownArea().contains(mousePos) };
bool intersecting{ isIntersecting(mousePos) };
if (isMouseInShownArea && intersecting)
{
m_isFocused = true;
}
else
{
m_isFocused = false;
}
}
if (event.type == sf::Event::KeyPressed && m_isFocused)
{
switch (event.key.code)
{
case sf::Keyboard::Left:
if (m_cursorPos > 0)
{
m_cursorPos--;
}
// when cursor is moved it should be drawn so we reset its status
resetCursorStatus();
adjustShownText();
return true;
case sf::Keyboard::Right:
if (m_cursorPos < m_currentText.length())
{
m_cursorPos++;
}
resetCursorStatus();
adjustShownText();
m_cursor.setPosition
(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));
return true;
default: break;
}
}
// If Widget is focused and Text entered, handle entered text
if (m_isFocused && event.type == sf::Event::TextEntered)
{
// To handle umlauts and other 'exotic' chars we use widestring
// and wide char
//std::wstring actualTxt{ m_text.getString().toWideString() };
wchar_t c{ static_cast<wchar_t>(event.text.unicode) };
std::cout << "Entered: " << c << std::endl;
switch (c)
{
// Backspace
case 8:
if (m_currentText.length() > 0)
{
// Remove chars right of cursor when there are chars
if (m_cursorPos > 0 && m_cursorPos < m_currentText.length())
{
m_currentText.erase(m_cursorPos - 1, 1);
m_cursorPos--;
}
// When cursos is at the end of the text, p
// place cursor behind char which we want to delete,
else if (m_cursorPos == m_currentText.length())
{
// Delete last char
m_currentText.pop_back();
m_cursorPos--;
}
}
break;
// Delete Pressed
case 127:
if (m_currentText.length() > 0 &&
m_cursorPos < m_currentText.length())
{
m_currentText.erase(m_cursorPos, 1);
}
break;
// Enter key
case 13: m_currentText.insert(m_cursorPos, L"\n"); m_cursorPos++; break;
// Add char to text
default: m_currentText.insert(m_cursorPos, std::wstring() + c); m_cursorPos++;
}
resetCursorStatus();
m_shownText = m_currentText;
m_text->setText(m_shownText);
adjustShownText();
m_cursor.setPosition(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));
m_scrollable->recalculateScroll();
m_scrollable->scrollToRight();
m_scrollable->scrollToBottom();
return true;
}
return false;
//return handled;
}
void gsf::TextInputWidget::adjustShownText()
{
/*
if (m_scrollable->isHorizontalScrollEnabled() || m_currentText.size() == 0)
return;
m_lBreaksBefCur = 0;
m_text->setText("");
m_shownText = L"";
// Add min cnt of chars we had in the past for a line break
m_shownText = m_currentText.substr(0, m_minBreakCharCnt);
// Start searching by the min cnt of chars we had in the past
bool done{ false };
unsigned int actualPos = m_minBreakCharCnt;
do
{
m_text->setText(m_shownText);
// Search expotenzial the pos where text dont fits anymore, and then
// search binary in this area
int i{ 1 };
while(m_text->getWidth() < m_scrollable->getWidth())
{
wchar_t c{ m_currentText[actualPos + i - 1] };
m_shownText += c;
}
// The search area is now between i / 2 and i -1
// In this area we now search binary
// Remove chars util the text fits in its parent
while(m_text->getWidth() > m_scrollable->getWidth())
{
m_shownText.pop_back();
actualPos--;
m_text->setText(m_shownText);
// The minimum has changed
m_minBreakCharCnt--;
};
} while (!done);
*/
if (!m_scrollable->isHorizontalScrollEnabled())
{
//std::cout << "POS: (" << m_text->findCharacterPos(1).x << "|"
// << m_text->findCharacterPos(0).y << ")" << std::endl;
m_lBreaksBefCur = 0;
//m_text->setText("");
sf::Text tmpText("", m_text->getFont(), m_text->getCharacterSize());
std::wstring tmpString{ L" " };
std::wstring shownString{ L"" };
//m_shownText = L"";
unsigned int charCntLine{ 0 };
for (unsigned int i{ 0 }; i < m_currentText.size(); i++)
{
wchar_t c{ m_currentText[i] };
tmpString.pop_back();
tmpString += c;
tmpString += L' ';
tmpText.setString(tmpString);
// Text is out of widget so add a line break before the last added char
if (tmpText.findCharacterPos(i + 1).x > m_scrollable->getWidth())
{
if (i < m_cursorPos)
{
// We have to increase the "line breaks befor cursor" counter
// so we add the cursor later on the right position
m_lBreaksBefCur++;
}
shownString += tmpString.substr(i - charCntLine + 1, charCntLine);
shownString += L"\n";
tmpString = L" ";
charCntLine = 1;
//tmpString.insert(tmpString.size() - 2, L"\n");
}
else
{
charCntLine++;
}
}
tmpString.pop_back();
shownString += tmpString;
m_shownText = shownString;
m_text->setText(m_shownText);
}
/*
if (!m_scrollable->isHorizontalScrollEnabled())
{
//std::cout << "POS: (" << m_text->findCharacterPos(1).x << "|"
// << m_text->findCharacterPos(0).y << ")" << std::endl;
m_lBreaksBefCur = 0;
m_text->setText("");
m_shownText = L"";
for (unsigned int i{ 0 }; i != m_currentText.size(); i++)
{
wchar_t c{ m_currentText[i] };
m_shownText += c;
m_text->setText(m_shownText);
// Text is out of widget so add a line break before the last added char
if (m_text->findCharacterPos(i).x > m_scrollable->getWidth())
{
if (i < m_cursorPos)
{
// We have to increase the "line breaks befor cursor" counter
// so we add the cursor later on the right position
m_lBreaksBefCur++;
}
m_shownText.insert(m_shownText.size() - 2, L"\n");
}
}
m_text->setText(m_shownText);
}
*/
}
void gsf::TextInputWidget::resetCursorStatus()
{
m_lastBlinkTime = 0.f;
m_isCursorShown = true;
}
<commit_msg>Make cursor movebale with arrow keys<commit_after>#include "TextInputWidget.hpp"
#include <iostream>
gsf::TextInputWidget::TextInputWidget(float width, float height, sf::Font &font)
: ChildWidget{ width, height }
//, m_text{ "", font, 12, sf::Color::Black }
, m_text{ nullptr }
, m_cursor{ "|", font, 12 }
, m_scrollable{ nullptr }
, m_isFocused{ false }
, m_cursorPos{ 0 }
, m_lBreaksBefCur{ 0 }
, m_isCursorShown{ true }
, m_blinkFreq{ 0.8f }
, m_lastBlinkTime{ 0.f }
, m_minBreakCharCnt{ 0 }
{
std::unique_ptr<TextWidget> text{
std::make_unique<TextWidget>("", font, 12, sf::Color::Black) };
std::unique_ptr<ScrollableWidget> scrollabe{
std::make_unique<ScrollableWidget>(width, height) };
m_scrollable = scrollabe.get();
m_text = text.get();
scrollabe->setBackgroundColor(sf::Color::Red);
scrollabe->attachChild(std::move(text));
//attachChild(std::move(text));
attachChild(std::move(scrollabe));
m_cursor.setFillColor(sf::Color::Black);
//m_text.setFont(font);
//m_text.setCharacterSize(12);
//m_text.setTextColor(sf::Color::Black);
//m_text.setOrigin(0.f, 0.f);
//m_text.setPosition(0.f, 0.f);
//m_scrollableWidget.attachChild();
}
void gsf::TextInputWidget::setText(const std::string &text)
{
m_text->setText(text);
}
std::string gsf::TextInputWidget::getText() const
{
return m_text->getText().toAnsiString();
}
void gsf::TextInputWidget::setCharacterSize(const unsigned int size)
{
m_text->setCharacterSize(size);
}
unsigned int gsf::TextInputWidget::getCharacterSize() const
{
return m_text->getCharacterSize();
}
void gsf::TextInputWidget::setTextColor(const sf::Color color)
{
m_text->setTextColor(color);
}
sf::Color gsf::TextInputWidget::getTextColor() const
{
return m_text->getTextColor();
}
bool gsf::TextInputWidget::isFocused() const
{
return m_isFocused;
}
void gsf::TextInputWidget::setIsVerticalScrollEnabled(bool isEnabled)
{
m_scrollable->setIsVerticalScrollEnabled(isEnabled);
}
bool gsf::TextInputWidget::isVerticalScrollEnabled() const
{
return m_scrollable->isVerticalScrollEnabled();
}
void gsf::TextInputWidget::setIsHorizontalScrollEnabled(bool isEnabled)
{
m_scrollable->setIsHorizontalScrollEnabled(isEnabled);
}
bool gsf::TextInputWidget::isHorizontalScrollEnabled() const
{
return m_scrollable->isHorizontalScrollEnabled();
}
void gsf::TextInputWidget::drawCurrent(sf::RenderTarget &target,
sf::RenderStates states) const
{
}
void gsf::TextInputWidget::drawCurrentAfterChildren(sf::RenderTarget &target,
sf::RenderStates states) const
{
// Draw cursor after children, so that children are not drawn over cursor
if (m_isCursorShown)
{
target.draw(m_cursor, states);
}
}
void gsf::TextInputWidget::updateCurrent(float dt)
{
// Update cursor stuff
m_lastBlinkTime += dt;
if (m_lastBlinkTime >= m_blinkFreq)
{
m_isCursorShown = !m_isCursorShown;
m_lastBlinkTime = 0.f;
}
//std::wstring text{ m_currentText };
//std::wstring text{ m_shownText };
//m_text->setText(text);
}
bool gsf::TextInputWidget::handleEventCurrent(sf::Event &event)
{
//bool handled{ ChildWidget::handleEvent(event) };/*||
// m_scrollable->handleEventWidget(event) };*/
// Check if actual Widget is focused
if (event.type == sf::Event::MouseButtonPressed)
{
sf::Vector2f mousePos{ (float) event.mouseButton.x,
(float) event.mouseButton.y };
bool isMouseInShownArea{ getShownArea().contains(mousePos) };
bool intersecting{ isIntersecting(mousePos) };
if (isMouseInShownArea && intersecting)
{
m_isFocused = true;
}
else
{
m_isFocused = false;
}
}
if (event.type == sf::Event::KeyPressed && m_isFocused)
{
switch (event.key.code)
{
case sf::Keyboard::Left:
if (m_cursorPos > 0)
{
m_cursorPos--;
}
// when cursor is moved it should be drawn so we reset its status
resetCursorStatus();
adjustShownText();
return true;
case sf::Keyboard::Right:
if (m_cursorPos < m_currentText.length())
{
m_cursorPos++;
}
resetCursorStatus();
adjustShownText();
m_cursor.setPosition
(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));
return true;
default: break;
}
}
// If Widget is focused and Text entered, handle entered text
if (m_isFocused && event.type == sf::Event::TextEntered)
{
// To handle umlauts and other 'exotic' chars we use widestring
// and wide char
//std::wstring actualTxt{ m_text.getString().toWideString() };
wchar_t c{ static_cast<wchar_t>(event.text.unicode) };
std::cout << "Entered: " << c << std::endl;
switch (c)
{
// Backspace
case 8:
if (m_currentText.length() > 0)
{
// Remove chars right of cursor when there are chars
if (m_cursorPos > 0 && m_cursorPos < m_currentText.length())
{
m_currentText.erase(m_cursorPos - 1, 1);
m_cursorPos--;
}
// When cursos is at the end of the text, p
// place cursor behind char which we want to delete,
else if (m_cursorPos == m_currentText.length())
{
// Delete last char
m_currentText.pop_back();
m_cursorPos--;
}
}
break;
// Delete Pressed
case 127:
if (m_currentText.length() > 0 &&
m_cursorPos < m_currentText.length())
{
m_currentText.erase(m_cursorPos, 1);
}
break;
// Enter key
case 13: m_currentText.insert(m_cursorPos, L"\n"); m_cursorPos++; break;
// Add char to text
default: m_currentText.insert(m_cursorPos, std::wstring() + c); m_cursorPos++;
}
resetCursorStatus();
m_shownText = m_currentText;
m_text->setText(m_shownText);
adjustShownText();
m_cursor.setPosition(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));
m_scrollable->recalculateScroll();
m_scrollable->scrollToRight();
m_scrollable->scrollToBottom();
return true;
}
return false;
//return handled;
}
void gsf::TextInputWidget::adjustShownText()
{
/*
if (m_scrollable->isHorizontalScrollEnabled() || m_currentText.size() == 0)
return;
m_lBreaksBefCur = 0;
m_text->setText("");
m_shownText = L"";
// Add min cnt of chars we had in the past for a line break
m_shownText = m_currentText.substr(0, m_minBreakCharCnt);
// Start searching by the min cnt of chars we had in the past
bool done{ false };
unsigned int actualPos = m_minBreakCharCnt;
do
{
m_text->setText(m_shownText);
// Search expotenzial the pos where text dont fits anymore, and then
// search binary in this area
int i{ 1 };
while(m_text->getWidth() < m_scrollable->getWidth())
{
wchar_t c{ m_currentText[actualPos + i - 1] };
m_shownText += c;
}
// The search area is now between i / 2 and i -1
// In this area we now search binary
// Remove chars util the text fits in its parent
while(m_text->getWidth() > m_scrollable->getWidth())
{
m_shownText.pop_back();
actualPos--;
m_text->setText(m_shownText);
// The minimum has changed
m_minBreakCharCnt--;
};
} while (!done);
*/
// advance is the with of the glyph
//float advance { m_text->getFont().getGlyph(c, m_text->getCharacterSize(),
// false).advance };
if (!m_scrollable->isHorizontalScrollEnabled())
{
//std::cout << "POS: (" << m_text->findCharacterPos(1).x << "|"
// << m_text->findCharacterPos(0).y << ")" << std::endl;
m_lBreaksBefCur = 0;
//m_text->setText("");
sf::Text tmpText("", m_text->getFont(), m_text->getCharacterSize());
std::wstring tmpString{ L"" };
std::wstring shownString{ L"" };
//m_shownText = L"";
unsigned int charCntLine{ 0 };
for (unsigned int i{ 0 }; i < m_currentText.size(); i++)
{
wchar_t c{ m_currentText[i] };
float advance { m_text->getFont().getGlyph(c, m_text->getCharacterSize(),
false).advance };
std::cout << "Advance: " << advance << std::endl;
tmpString += c;
tmpText.setString(tmpString);
// Text is out of widget so add a line break before the last added char
if (tmpText.findCharacterPos(i + 1).x > m_scrollable->getWidth())
{
if (i < m_cursorPos)
{
// We have to increase the "line breaks befor cursor" counter
// so we add the cursor later on the right position
m_lBreaksBefCur++;
}
shownString += tmpString.substr(i - charCntLine, charCntLine);
shownString += L"\n";
tmpString = L"";
tmpString += c;
charCntLine = 1;
}
else
{
charCntLine++;
}
}
shownString += tmpString;
m_shownText = shownString;
m_text->setText(m_shownText);
}
/*
if (!m_scrollable->isHorizontalScrollEnabled())
{
//std::cout << "POS: (" << m_text->findCharacterPos(1).x << "|"
// << m_text->findCharacterPos(0).y << ")" << std::endl;
m_lBreaksBefCur = 0;
m_text->setText("");
m_shownText = L"";
for (unsigned int i{ 0 }; i != m_currentText.size(); i++)
{
wchar_t c{ m_currentText[i] };
m_shownText += c;
m_text->setText(m_shownText);
// Text is out of widget so add a line break before the last added char
if (m_text->findCharacterPos(i).x > m_scrollable->getWidth())
{
if (i < m_cursorPos)
{
// We have to increase the "line breaks befor cursor" counter
// so we add the cursor later on the right position
m_lBreaksBefCur++;
}
m_shownText.insert(m_shownText.size() - 2, L"\n");
}
}
m_text->setText(m_shownText);
}
*/
}
void gsf::TextInputWidget::resetCursorStatus()
{
m_lastBlinkTime = 0.f;
m_isCursorShown = true;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. Redistributions
* in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution. Neither the name of
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include <cassert>
#include "arch/x86/emulenv.hh"
#include "base/misc.hh"
using namespace X86ISA;
void EmulEnv::doModRM(const ExtMachInst & machInst)
{
assert(machInst.modRM.mod != 3);
//Use the SIB byte for addressing if the modrm byte calls for it.
if (machInst.modRM.rm == 4 && machInst.addrSize != 2) {
scale = 1 << machInst.sib.scale;
index = machInst.sib.index | (machInst.rex.x << 3);
base = machInst.sib.base | (machInst.rex.b << 3);
//In this special case, we don't use a base. The displacement also
//changes, but that's managed by the predecoder.
if (machInst.sib.base == INTREG_RBP && machInst.modRM.mod == 0)
base = NUM_INTREGS;
//In -this- special case, we don't use an index.
if (index == INTREG_RSP)
index = NUM_INTREGS;
} else {
if (machInst.addrSize == 2) {
warn("I'm not really using 16 bit MODRM like I'm supposed to!\n");
} else {
scale = 0;
base = machInst.modRM.rm | (machInst.rex.b << 3);
if (machInst.modRM.mod == 0 && machInst.modRM.rm == 5) {
//Since we need to use a different encoding of this
//instruction anyway, just ignore the base in those cases
base = NUM_INTREGS;
}
}
}
//Figure out what segment to use. This won't be entirely accurate since
//the presence of a displacement is supposed to make the instruction
//default to the data segment.
if ((base != INTREG_RBP && base != INTREG_RSP) ||
0/*Has an immediate offset*/) {
seg = SEGMENT_REG_DS;
//Handle any segment override that might have been in the instruction
int segFromInst = machInst.legacy.seg;
if (segFromInst)
seg = (SegmentRegIndex)(segFromInst - 1);
} else {
seg = SEGMENT_REG_SS;
}
}
void EmulEnv::setSeg(const ExtMachInst & machInst)
{
seg = SEGMENT_REG_DS;
//Handle any segment override that might have been in the instruction
int segFromInst = machInst.legacy.seg;
if (segFromInst)
seg = (SegmentRegIndex)(segFromInst - 1);
}
<commit_msg>X86: Actually handle 16 bit mode modrm.<commit_after>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. Redistributions
* in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution. Neither the name of
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include <cassert>
#include "arch/x86/emulenv.hh"
#include "base/misc.hh"
using namespace X86ISA;
void EmulEnv::doModRM(const ExtMachInst & machInst)
{
assert(machInst.modRM.mod != 3);
//Use the SIB byte for addressing if the modrm byte calls for it.
if (machInst.modRM.rm == 4 && machInst.addrSize != 2) {
scale = 1 << machInst.sib.scale;
index = machInst.sib.index | (machInst.rex.x << 3);
base = machInst.sib.base | (machInst.rex.b << 3);
//In this special case, we don't use a base. The displacement also
//changes, but that's managed by the predecoder.
if (machInst.sib.base == INTREG_RBP && machInst.modRM.mod == 0)
base = NUM_INTREGS;
//In -this- special case, we don't use an index.
if (index == INTREG_RSP)
index = NUM_INTREGS;
} else {
if (machInst.addrSize == 2) {
unsigned rm = machInst.modRM.rm;
if (rm <= 3) {
scale = 1;
if (rm < 2) {
base = INTREG_RBX;
} else {
base = INTREG_RBP;
}
index = (rm % 2) ? INTREG_RDI : INTREG_RSI;
} else {
scale = 0;
switch (rm) {
case 4:
base = INTREG_RSI;
break;
case 5:
base = INTREG_RDI;
break;
case 6:
base = INTREG_RBP;
break;
case 7:
base = INTREG_RBX;
break;
}
}
} else {
scale = 0;
base = machInst.modRM.rm | (machInst.rex.b << 3);
if (machInst.modRM.mod == 0 && machInst.modRM.rm == 5) {
//Since we need to use a different encoding of this
//instruction anyway, just ignore the base in those cases
base = NUM_INTREGS;
}
}
}
//Figure out what segment to use. This won't be entirely accurate since
//the presence of a displacement is supposed to make the instruction
//default to the data segment.
if ((base != INTREG_RBP && base != INTREG_RSP) ||
0/*Has an immediate offset*/) {
seg = SEGMENT_REG_DS;
//Handle any segment override that might have been in the instruction
int segFromInst = machInst.legacy.seg;
if (segFromInst)
seg = (SegmentRegIndex)(segFromInst - 1);
} else {
seg = SEGMENT_REG_SS;
}
}
void EmulEnv::setSeg(const ExtMachInst & machInst)
{
seg = SEGMENT_REG_DS;
//Handle any segment override that might have been in the instruction
int segFromInst = machInst.legacy.seg;
if (segFromInst)
seg = (SegmentRegIndex)(segFromInst - 1);
}
<|endoftext|> |
<commit_before>#pragma once
#include "../base/assert.hpp"
#include "../base/base.hpp"
#include "../std/string.hpp"
#include "../std/sstream.hpp"
#include "../std/utility.hpp"
namespace m2
{
template <int kDepthLevels = 31> class CellId
{
public:
// TODO: Move CellId::DEPTH_LEVELS to private.
static int const DEPTH_LEVELS = kDepthLevels;
static uint32_t const MAX_COORD = 1U << DEPTH_LEVELS;
CellId() : m_Bits(0), m_Level(0)
{
ASSERT(IsValid(), ());
}
explicit CellId(string const & s)
{
*this = FromString(s);
}
static CellId Root()
{
return CellId(0, 0);
}
static CellId FromBitsAndLevel(uint64_t bits, int level)
{
return CellId(bits, level);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Simple getters
int Level() const
{
ASSERT(IsValid(), (m_Bits, m_Level));
return m_Level;
}
CellId Parent() const
{
ASSERT(IsValid(), (m_Bits, m_Level));
ASSERT_GREATER(m_Level, 0, ());
return CellId(m_Bits >> 2, m_Level - 1);
}
CellId AncestorAtLevel(int level) const
{
ASSERT(IsValid(), (m_Bits, m_Level));
ASSERT_GREATER_OR_EQUAL(m_Level, level, ());
return CellId(m_Bits >> ((m_Level - level) << 1), level);
}
CellId Child(int8_t c) const
{
ASSERT(c >= 0 && c < 4, (c, m_Bits, m_Level));
ASSERT(IsValid(), (m_Bits, m_Level));
ASSERT_LESS(m_Level, DEPTH_LEVELS - 1, ());
return CellId((m_Bits << 2) | c, m_Level + 1);
}
char WhichChildOfParent() const
{
ASSERT(IsValid(), (m_Bits, m_Level));
ASSERT_GREATER(m_Level, 0, ());
return m_Bits & 3;
}
uint64_t SubTreeSize(int depth) const
{
ASSERT(IsValid(), (m_Bits, m_Level));
ASSERT(m_Level < depth && depth <= DEPTH_LEVELS, (m_Bits, m_Level, depth));
return TreeSizeForDepth(depth - m_Level);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Operators
bool operator == (CellId const & cellId) const
{
ASSERT(IsValid(), (m_Bits, m_Level));
ASSERT(cellId.IsValid(), (cellId.m_Bits, cellId.m_Level));
return m_Bits == cellId.m_Bits && m_Level == cellId.m_Level;
}
bool operator != (CellId const & cellId) const
{
return !(*this == cellId);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Conversion to/from string
string ToString() const
{
ASSERT(IsValid(), (m_Bits, m_Level));
string result(m_Level, '0');
uint64_t bits = m_Bits;
for (int i = 0; i < m_Level; ++i, bits >>= 2)
result[m_Level - 1 - i] += (bits & 3);
ASSERT_EQUAL(*this, FromString(result), (m_Bits, m_Level, result));
return result;
}
// Is string @s a valid CellId representation?
// Note that empty string is a valid CellId.
static bool IsCellId(string const & s)
{
size_t const length = s.size();
if (length >= DEPTH_LEVELS)
return false;
for (size_t i = 0; i < length; ++i)
{
if (s[i] < '0' || s[i] > '3')
return false;
}
return true;
}
static CellId FromString(string const & s)
{
ASSERT(IsCellId(s), (s));
uint64_t bits = 0;
size_t const level = s.size();
ASSERT_LESS(level, static_cast<size_t>(DEPTH_LEVELS), (s));
for (size_t i = 0; i < level; ++i)
{
ASSERT((s[i] >= '0') && (s[i] <= '3'), (s, i));
bits = (bits << 2) | (s[i] - '0');
}
return CellId(bits, static_cast<int>(level));
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Conversion to/from point
// Cell area width and height.
// Should be 1 for the bottom level cell.
uint32_t Radius() const
{
ASSERT(IsValid(), (m_Bits, m_Level));
return 1 << (DEPTH_LEVELS - 1 - m_Level);
}
pair<uint32_t, uint32_t> XY() const
{
ASSERT(IsValid(), (m_Bits, m_Level));
uint32_t offset = 1 << (DEPTH_LEVELS - 1 - m_Level);
pair<uint32_t, uint32_t> xy(offset, offset);
uint64_t bits = m_Bits;
while (bits > 0)
{
offset <<= 1;
if (bits & 1)
xy.first += offset;
if (bits & 2)
xy.second += offset;
bits >>= 2;
}
ASSERT_EQUAL(*this, FromXY(xy.first, xy.second, m_Level), ());
return xy;
}
static CellId FromXY(uint32_t x, uint32_t y, int level)
{
ASSERT_LESS(level, static_cast<int>(DEPTH_LEVELS), (x, y, level));
// Since MAX_COORD == 1 << DEPTH_LEVELS, if x|y == MAX_COORD, they should be decremented.
if (x >= MAX_COORD)
{
ASSERT_EQUAL(x, static_cast<uint32_t>(MAX_COORD), (x, y, level));
x = MAX_COORD - 1;
}
if (y >= MAX_COORD)
{
ASSERT_EQUAL(y, static_cast<uint32_t>(MAX_COORD), (x, y, level));
y = MAX_COORD - 1;
}
x >>= DEPTH_LEVELS - level;
y >>= DEPTH_LEVELS - level;
// This operation is called "perfect shuffle". Optimized bit trick can be used here.
uint64_t bits = 0;
for (int i = 0; i < level; ++i)
bits |= ((uint64_t((y >> i) & 1) << (2 * i + 1)) | (uint64_t((x >> i) & 1) << (2 * i)));
return CellId(bits, level);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Ordering
struct LessLevelOrder
{
bool operator() (CellId<DEPTH_LEVELS> const & id1, CellId<DEPTH_LEVELS> const & id2) const
{
if (id1.m_Level != id2.m_Level)
return id1.m_Level < id2.m_Level;
if (id1.m_Bits != id2.m_Bits)
return id1.m_Bits < id2.m_Bits;
return false;
}
};
struct LessPreOrder
{
bool operator() (CellId<DEPTH_LEVELS> const & id1, CellId<DEPTH_LEVELS> const & id2) const
{
int64_t const n1 = id1.ToInt64LevelZOrder(DEPTH_LEVELS);
int64_t const n2 = id2.ToInt64LevelZOrder(DEPTH_LEVELS);
ASSERT_EQUAL(n1 < n2, id1.ToString() < id2.ToString(), (id1, id2));
return n1 < n2;
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////
// Numbering
// Default ToInt64().
int64_t ToInt64(int depth) const
{
return ToInt64LevelZOrder(depth);
}
// Default FromInt64().
static CellId FromInt64(int64_t v, int depth)
{
return FromInt64LevelZOrder(v, depth);
}
// Level order, numbering by Z-curve.
int64_t ToInt64LevelZOrder(int depth) const
{
ASSERT(0 < depth && depth <= DEPTH_LEVELS, (m_Bits, m_Level, depth));
ASSERT(IsValid(), (m_Bits, m_Level));
if (m_Level >= depth)
return AncestorAtLevel(depth - 1).ToInt64(depth);
else
{
uint64_t bits = m_Bits, res = 0;
for (int i = 0; i <= m_Level; ++i, bits >>= 2)
res += bits + 1;
bits = m_Bits;
for (int i = m_Level + 1; i < depth; ++i)
{
bits <<= 2;
res += bits;
}
ASSERT_GREATER(res, 0, (m_Bits, m_Level));
ASSERT_LESS_OR_EQUAL(res, TreeSizeForDepth(depth), (m_Bits, m_Level));
return static_cast<int64_t>(res);
}
}
// Level order, numbering by Z-curve.
static CellId FromInt64LevelZOrder(int64_t v, int depth)
{
ASSERT_GREATER(v, 0, ());
ASSERT(0 < depth && depth <= DEPTH_LEVELS, (v, depth));
ASSERT_LESS_OR_EQUAL(v, TreeSizeForDepth(depth), ());
uint64_t bits = 0;
int level = 0;
--v;
while (v > 0)
{
bits <<= 2;
++level;
uint64_t subTreeSize = TreeSizeForDepth(depth - level);
for (--v; v >= subTreeSize; v -= subTreeSize)
++bits;
}
return CellId(bits, level);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
private:
static uint64_t TreeSizeForDepth(int depth)
{
ASSERT(0 < depth && depth <= DEPTH_LEVELS, (depth));
return ((1ULL << 2 * depth) - 1) / 3ULL;
}
CellId(uint64_t bits, int level) : m_Bits(bits), m_Level(level)
{
ASSERT_LESS(level, static_cast<uint32_t>(DEPTH_LEVELS), (bits, level));
ASSERT_LESS(bits, 1ULL << m_Level * 2, (bits, m_Level));
ASSERT(IsValid(), (m_Bits, m_Level));
}
bool IsValid() const
{
if (m_Level < 0 || m_Level >= DEPTH_LEVELS)
return false;
if (m_Bits >= (1ULL << m_Level * 2))
return false;
return true;
}
uint64_t m_Bits;
int m_Level;
};
template <int DEPTH_LEVELS> string DebugPrint(CellId<DEPTH_LEVELS> const & id)
{
ostringstream out;
out << "CellId<" << DEPTH_LEVELS << ">(\"" << id.ToString().c_str() << "\")";
return out.str();
}
}
<commit_msg>Warning fixes<commit_after>#pragma once
#include "../base/assert.hpp"
#include "../base/base.hpp"
#include "../std/string.hpp"
#include "../std/sstream.hpp"
#include "../std/utility.hpp"
namespace m2
{
template <int kDepthLevels = 31> class CellId
{
public:
// TODO: Move CellId::DEPTH_LEVELS to private.
static int const DEPTH_LEVELS = kDepthLevels;
static uint32_t const MAX_COORD = 1U << DEPTH_LEVELS;
CellId() : m_Bits(0), m_Level(0)
{
ASSERT(IsValid(), ());
}
explicit CellId(string const & s)
{
*this = FromString(s);
}
static CellId Root()
{
return CellId(0, 0);
}
static CellId FromBitsAndLevel(uint64_t bits, int level)
{
return CellId(bits, level);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Simple getters
int Level() const
{
ASSERT(IsValid(), (m_Bits, m_Level));
return m_Level;
}
CellId Parent() const
{
ASSERT(IsValid(), (m_Bits, m_Level));
ASSERT_GREATER(m_Level, 0, ());
return CellId(m_Bits >> 2, m_Level - 1);
}
CellId AncestorAtLevel(int level) const
{
ASSERT(IsValid(), (m_Bits, m_Level));
ASSERT_GREATER_OR_EQUAL(m_Level, level, ());
return CellId(m_Bits >> ((m_Level - level) << 1), level);
}
CellId Child(int8_t c) const
{
ASSERT(c >= 0 && c < 4, (c, m_Bits, m_Level));
ASSERT(IsValid(), (m_Bits, m_Level));
ASSERT_LESS(m_Level, DEPTH_LEVELS - 1, ());
return CellId((m_Bits << 2) | c, m_Level + 1);
}
char WhichChildOfParent() const
{
ASSERT(IsValid(), (m_Bits, m_Level));
ASSERT_GREATER(m_Level, 0, ());
return m_Bits & 3;
}
uint64_t SubTreeSize(int depth) const
{
ASSERT(IsValid(), (m_Bits, m_Level));
ASSERT(m_Level < depth && depth <= DEPTH_LEVELS, (m_Bits, m_Level, depth));
return TreeSizeForDepth(depth - m_Level);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Operators
bool operator == (CellId const & cellId) const
{
ASSERT(IsValid(), (m_Bits, m_Level));
ASSERT(cellId.IsValid(), (cellId.m_Bits, cellId.m_Level));
return m_Bits == cellId.m_Bits && m_Level == cellId.m_Level;
}
bool operator != (CellId const & cellId) const
{
return !(*this == cellId);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Conversion to/from string
string ToString() const
{
ASSERT(IsValid(), (m_Bits, m_Level));
string result(m_Level, '0');
uint64_t bits = m_Bits;
for (int i = 0; i < m_Level; ++i, bits >>= 2)
result[m_Level - 1 - i] += (bits & 3);
ASSERT_EQUAL(*this, FromString(result), (m_Bits, m_Level, result));
return result;
}
// Is string @s a valid CellId representation?
// Note that empty string is a valid CellId.
static bool IsCellId(string const & s)
{
size_t const length = s.size();
if (length >= DEPTH_LEVELS)
return false;
for (size_t i = 0; i < length; ++i)
{
if (s[i] < '0' || s[i] > '3')
return false;
}
return true;
}
static CellId FromString(string const & s)
{
ASSERT(IsCellId(s), (s));
uint64_t bits = 0;
size_t const level = s.size();
ASSERT_LESS(level, static_cast<size_t>(DEPTH_LEVELS), (s));
for (size_t i = 0; i < level; ++i)
{
ASSERT((s[i] >= '0') && (s[i] <= '3'), (s, i));
bits = (bits << 2) | static_cast<uint64_t>(s[i] - '0');
}
return CellId(bits, static_cast<int>(level));
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Conversion to/from point
// Cell area width and height.
// Should be 1 for the bottom level cell.
uint32_t Radius() const
{
ASSERT(IsValid(), (m_Bits, m_Level));
return 1 << (DEPTH_LEVELS - 1 - m_Level);
}
pair<uint32_t, uint32_t> XY() const
{
ASSERT(IsValid(), (m_Bits, m_Level));
uint32_t offset = 1 << (DEPTH_LEVELS - 1 - m_Level);
pair<uint32_t, uint32_t> xy(offset, offset);
uint64_t bits = m_Bits;
while (bits > 0)
{
offset <<= 1;
if (bits & 1)
xy.first += offset;
if (bits & 2)
xy.second += offset;
bits >>= 2;
}
ASSERT_EQUAL(*this, FromXY(xy.first, xy.second, m_Level), ());
return xy;
}
static CellId FromXY(uint32_t x, uint32_t y, int level)
{
ASSERT_LESS(level, static_cast<int>(DEPTH_LEVELS), (x, y, level));
// Since MAX_COORD == 1 << DEPTH_LEVELS, if x|y == MAX_COORD, they should be decremented.
if (x >= MAX_COORD)
{
ASSERT_EQUAL(x, static_cast<uint32_t>(MAX_COORD), (x, y, level));
x = MAX_COORD - 1;
}
if (y >= MAX_COORD)
{
ASSERT_EQUAL(y, static_cast<uint32_t>(MAX_COORD), (x, y, level));
y = MAX_COORD - 1;
}
x >>= DEPTH_LEVELS - level;
y >>= DEPTH_LEVELS - level;
// This operation is called "perfect shuffle". Optimized bit trick can be used here.
uint64_t bits = 0;
for (int i = 0; i < level; ++i)
bits |= ((uint64_t((y >> i) & 1) << (2 * i + 1)) | (uint64_t((x >> i) & 1) << (2 * i)));
return CellId(bits, level);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Ordering
struct LessLevelOrder
{
bool operator() (CellId<DEPTH_LEVELS> const & id1, CellId<DEPTH_LEVELS> const & id2) const
{
if (id1.m_Level != id2.m_Level)
return id1.m_Level < id2.m_Level;
if (id1.m_Bits != id2.m_Bits)
return id1.m_Bits < id2.m_Bits;
return false;
}
};
struct LessPreOrder
{
bool operator() (CellId<DEPTH_LEVELS> const & id1, CellId<DEPTH_LEVELS> const & id2) const
{
int64_t const n1 = id1.ToInt64LevelZOrder(DEPTH_LEVELS);
int64_t const n2 = id2.ToInt64LevelZOrder(DEPTH_LEVELS);
ASSERT_EQUAL(n1 < n2, id1.ToString() < id2.ToString(), (id1, id2));
return n1 < n2;
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////
// Numbering
// Default ToInt64().
int64_t ToInt64(int depth) const
{
return ToInt64LevelZOrder(depth);
}
// Default FromInt64().
static CellId FromInt64(int64_t v, int depth)
{
return FromInt64LevelZOrder(v, depth);
}
// Level order, numbering by Z-curve.
int64_t ToInt64LevelZOrder(int depth) const
{
ASSERT(0 < depth && depth <= DEPTH_LEVELS, (m_Bits, m_Level, depth));
ASSERT(IsValid(), (m_Bits, m_Level));
if (m_Level >= depth)
return AncestorAtLevel(depth - 1).ToInt64(depth);
else
{
uint64_t bits = m_Bits, res = 0;
for (int i = 0; i <= m_Level; ++i, bits >>= 2)
res += bits + 1;
bits = m_Bits;
for (int i = m_Level + 1; i < depth; ++i)
{
bits <<= 2;
res += bits;
}
ASSERT_GREATER(res, 0, (m_Bits, m_Level));
ASSERT_LESS_OR_EQUAL(res, TreeSizeForDepth(depth), (m_Bits, m_Level));
return static_cast<int64_t>(res);
}
}
// Level order, numbering by Z-curve.
static CellId FromInt64LevelZOrder(int64_t v, int depth)
{
ASSERT_GREATER(v, 0, ());
ASSERT(0 < depth && depth <= DEPTH_LEVELS, (v, depth));
ASSERT_LESS_OR_EQUAL(v, TreeSizeForDepth(depth), ());
uint64_t bits = 0;
int level = 0;
--v;
while (v > 0)
{
bits <<= 2;
++level;
uint64_t subTreeSize = TreeSizeForDepth(depth - level);
for (--v; v >= subTreeSize; v -= subTreeSize)
++bits;
}
return CellId(bits, level);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
private:
static uint64_t TreeSizeForDepth(int depth)
{
ASSERT(0 < depth && depth <= DEPTH_LEVELS, (depth));
return ((1ULL << 2 * depth) - 1) / 3ULL;
}
CellId(uint64_t bits, int level) : m_Bits(bits), m_Level(level)
{
ASSERT_LESS(level, static_cast<uint32_t>(DEPTH_LEVELS), (bits, level));
ASSERT_LESS(bits, 1ULL << m_Level * 2, (bits, m_Level));
ASSERT(IsValid(), (m_Bits, m_Level));
}
bool IsValid() const
{
if (m_Level < 0 || m_Level >= DEPTH_LEVELS)
return false;
if (m_Bits >= (1ULL << m_Level * 2))
return false;
return true;
}
uint64_t m_Bits;
int m_Level;
};
template <int DEPTH_LEVELS> string DebugPrint(CellId<DEPTH_LEVELS> const & id)
{
ostringstream out;
out << "CellId<" << DEPTH_LEVELS << ">(\"" << id.ToString().c_str() << "\")";
return out.str();
}
}
<|endoftext|> |
<commit_before>/* Gobby - GTK-based collaborative text editor
* Copyright (C) 2008-2014 Armin Burgmeier <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "commands/auth-commands.hpp"
#include "util/i18n.hpp"
#include <libinfinity/common/inf-xmpp-connection.h>
#include <libinfinity/common/inf-error.h>
#include <gtkmm/stock.h>
namespace
{
void show_error(const GError* error,
Gobby::StatusBar& statusbar,
InfXmlConnection* connection)
{
gchar* remote;
g_object_get(connection,
"remote-hostname", &remote,
NULL);
Glib::ustring short_message(Glib::ustring::compose(
"Authentication failed for \"%1\"", remote));
g_free(remote);
if(error->domain ==
inf_authentication_detail_error_quark())
{
statusbar.add_error_message(
short_message,
inf_authentication_detail_strerror(
InfAuthenticationDetailError(
error->code)));
}
else
{
statusbar.add_error_message(
short_message,
error->message);
}
}
}
Gobby::AuthCommands::AuthCommands(Gtk::Window& parent,
Browser& browser,
StatusBar& statusbar,
ConnectionManager& connection_manager,
const Preferences& preferences):
m_parent(parent),
m_browser(browser),
m_connection_manager(connection_manager),
m_statusbar(statusbar),
m_preferences(preferences)
{
GError* error = NULL;
m_sasl_context = inf_sasl_context_new(&error);
if(!m_sasl_context)
{
std::string error_message =
std::string("SASL initialization error: ") +
error->message;
g_error_free(error);
throw std::runtime_error(error_message);
}
inf_sasl_context_set_callback(
m_sasl_context, &AuthCommands::sasl_callback_static, this);
// Set SASL context for new connections:
m_connection_manager.set_sasl_context(m_sasl_context,
"ANONYMOUS PLAIN");
g_signal_connect(
G_OBJECT(m_browser.get_store()),
"set-browser",
G_CALLBACK(&AuthCommands::set_browser_callback_static),
this);
}
Gobby::AuthCommands::~AuthCommands()
{
m_connection_manager.set_sasl_context(NULL, NULL);
inf_sasl_context_unref(m_sasl_context);
for(RetryMap::iterator iter = m_retries.begin();
iter != m_retries.end(); ++iter)
{
g_signal_handler_disconnect(iter->first, iter->second.handle);
}
}
void Gobby::AuthCommands::set_sasl_error(InfXmppConnection* connection,
const gchar* message)
{
GError* error = g_error_new_literal(
inf_authentication_detail_error_quark(),
INF_AUTHENTICATION_DETAIL_ERROR_AUTHENTICATION_FAILED,
message
);
inf_xmpp_connection_set_sasl_error(connection, error);
g_error_free(error);
}
void Gobby::AuthCommands::sasl_callback(InfSaslContextSession* session,
InfXmppConnection* xmpp,
Gsasl_property prop)
{
const Glib::ustring username = m_preferences.user.name;
const std::string correct_password = m_preferences.user.password;
const char* password;
switch(prop)
{
case GSASL_ANONYMOUS_TOKEN:
inf_sasl_context_session_set_property(
session, GSASL_ANONYMOUS_TOKEN, username.c_str());
inf_sasl_context_session_continue(session, GSASL_OK);
break;
case GSASL_AUTHID:
inf_sasl_context_session_set_property(
session, GSASL_AUTHID, username.c_str());
inf_sasl_context_session_continue(session, GSASL_OK);
break;
case GSASL_PASSWORD:
{
RetryMap::iterator i = m_retries.find(xmpp);
if(i == m_retries.end())
i = insert_retry_info(xmpp);
RetryInfo& info(i->second);
if(!info.last_password.empty())
{
inf_sasl_context_session_set_property(
session, GSASL_PASSWORD,
info.last_password.c_str());
inf_sasl_context_session_continue(session,
GSASL_OK);
}
else
{
// Query user for password
g_assert(info.password_dialog == NULL);
gchar* remote_id;
g_object_get(G_OBJECT(xmpp),
"remote-hostname", &remote_id,
NULL);
Glib::ustring remote_id_(remote_id);
g_free(remote_id);
info.password_dialog = new PasswordDialog(
m_parent, remote_id_, info.retries);
info.password_dialog->add_button(
Gtk::Stock::CANCEL,
Gtk::RESPONSE_CANCEL);
info.password_dialog->add_button(
Gtk::Stock::OK,
Gtk::RESPONSE_ACCEPT);
Gtk::Dialog& dialog = *info.password_dialog;
dialog.signal_response().connect(sigc::bind(
sigc::mem_fun(
*this,
&AuthCommands::on_response),
session, xmpp));
info.password_dialog->present();
}
}
break;
case GSASL_VALIDATE_ANONYMOUS:
if(m_preferences.user.require_password)
{
inf_sasl_context_session_continue(
session,
GSASL_AUTHENTICATION_ERROR
);
set_sasl_error(xmpp, _("Password required"));
}
else
{
inf_sasl_context_session_continue(session, GSASL_OK);
}
break;
case GSASL_VALIDATE_SIMPLE:
password = inf_sasl_context_session_get_property(
session, GSASL_PASSWORD);
if(strcmp(password, correct_password.c_str()) != 0)
{
inf_sasl_context_session_continue(
session,
GSASL_AUTHENTICATION_ERROR
);
set_sasl_error(xmpp, _("Incorrect password"));
}
else
{
inf_sasl_context_session_continue(session, GSASL_OK);
}
break;
default:
inf_sasl_context_session_continue(session, GSASL_NO_CALLBACK);
break;
}
}
void Gobby::AuthCommands::on_response(int response_id,
InfSaslContextSession* session,
InfXmppConnection* xmpp)
{
RetryMap::iterator i = m_retries.find(xmpp);
g_assert(i != m_retries.end());
RetryInfo& info(i->second);
if(response_id == Gtk::RESPONSE_ACCEPT)
info.last_password = info.password_dialog->get_password();
else
info.last_password = "";
delete info.password_dialog;
info.password_dialog = NULL;
++info.retries;
if(info.last_password.empty())
{
inf_sasl_context_session_continue(session, GSASL_NO_PASSWORD);
}
else
{
inf_sasl_context_session_set_property(
session, GSASL_PASSWORD, info.last_password.c_str());
inf_sasl_context_session_continue(session, GSASL_OK);
}
}
void Gobby::AuthCommands::set_browser_callback(InfBrowser* old_browser,
InfBrowser* new_browser)
{
// TODO: Disconnect from the signal on destruction?
if(new_browser != NULL && INFC_IS_BROWSER(new_browser))
{
g_signal_connect(
G_OBJECT(new_browser),
"error",
G_CALLBACK(browser_error_callback_static),
this);
}
}
void Gobby::AuthCommands::browser_error_callback(InfcBrowser* browser,
GError* error)
{
// The Browser already displays errors inline, but we want
// auth-related error messages to show up in the status bar.
InfXmlConnection* connection = infc_browser_get_connection(browser);
g_assert(INF_IS_XMPP_CONNECTION(connection));
InfXmppConnection* xmpp = INF_XMPP_CONNECTION(connection);
RetryMap::iterator iter = m_retries.find(xmpp);
if(iter == m_retries.end())
iter = insert_retry_info(xmpp);
Glib::ustring& last_password(iter->second.last_password);
Glib::ustring old_password;
old_password.swap(last_password);
if(error->domain ==
g_quark_from_static_string("INF_XMPP_CONNECTION_AUTH_ERROR"))
{
// Authentication failed for some reason, maybe because the
// server aborted authentication. If we were querying a
// password then close the dialog now.
delete iter->second.password_dialog;
iter->second.password_dialog = NULL;
const GError* sasl_error =
inf_xmpp_connection_get_sasl_error(xmpp);
if(sasl_error != NULL &&
sasl_error->domain ==
inf_authentication_detail_error_quark())
{
handle_error_detail(xmpp, sasl_error,
old_password,
last_password);
}
else if(sasl_error != NULL)
{
show_error(sasl_error, m_statusbar, connection);
}
else
{
show_error(error, m_statusbar, connection);
}
}
else if(error->domain == inf_gsasl_error_quark())
{
show_error(error, m_statusbar, connection);
}
}
void Gobby::AuthCommands::handle_error_detail(InfXmppConnection* xmpp,
const GError* detail_error,
Glib::ustring& old_password,
Glib::ustring& last_password)
{
GError* error = NULL;
switch(detail_error->code)
{
case INF_AUTHENTICATION_DETAIL_ERROR_AUTHENTICATION_FAILED:
inf_xmpp_connection_retry_sasl_authentication(xmpp, &error);
break;
case INF_AUTHENTICATION_DETAIL_ERROR_TRY_AGAIN:
old_password.swap(last_password);
inf_xmpp_connection_retry_sasl_authentication(xmpp, &error);
break;
default:
show_error(detail_error, m_statusbar,
INF_XML_CONNECTION(xmpp));
break;
}
if(error)
{
show_error(error, m_statusbar,
INF_XML_CONNECTION(xmpp));
g_error_free(error);
}
}
Gobby::AuthCommands::RetryMap::iterator
Gobby::AuthCommands::insert_retry_info(InfXmppConnection* xmpp)
{
RetryMap::iterator iter = m_retries.insert(
std::make_pair(xmpp,
RetryInfo())).first;
iter->second.retries = 0;
iter->second.handle = g_signal_connect(
G_OBJECT(xmpp),
"notify::status",
G_CALLBACK(on_notify_status_static),
this);
iter->second.password_dialog = NULL;
return iter;
}
void Gobby::AuthCommands::on_notify_status(InfXmppConnection* connection)
{
InfXmlConnectionStatus status;
g_object_get(G_OBJECT(connection), "status", &status, NULL);
if(status != INF_XML_CONNECTION_OPENING)
{
RetryMap::iterator iter = m_retries.find(connection);
g_signal_handler_disconnect(connection, iter->second.handle);
delete iter->second.password_dialog;
m_retries.erase(iter);
}
}
<commit_msg>Adapt to modified libinfinity API<commit_after>/* Gobby - GTK-based collaborative text editor
* Copyright (C) 2008-2014 Armin Burgmeier <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "commands/auth-commands.hpp"
#include "util/i18n.hpp"
#include <libinfinity/common/inf-xmpp-connection.h>
#include <libinfinity/common/inf-error.h>
#include <gtkmm/stock.h>
namespace
{
void show_error(const GError* error,
Gobby::StatusBar& statusbar,
InfXmlConnection* connection)
{
gchar* remote;
g_object_get(connection,
"remote-hostname", &remote,
NULL);
Glib::ustring short_message(Glib::ustring::compose(
"Authentication failed for \"%1\"", remote));
g_free(remote);
if(error->domain ==
inf_authentication_detail_error_quark())
{
statusbar.add_error_message(
short_message,
inf_authentication_detail_strerror(
InfAuthenticationDetailError(
error->code)));
}
else
{
statusbar.add_error_message(
short_message,
error->message);
}
}
}
Gobby::AuthCommands::AuthCommands(Gtk::Window& parent,
Browser& browser,
StatusBar& statusbar,
ConnectionManager& connection_manager,
const Preferences& preferences):
m_parent(parent),
m_browser(browser),
m_connection_manager(connection_manager),
m_statusbar(statusbar),
m_preferences(preferences)
{
GError* error = NULL;
m_sasl_context = inf_sasl_context_new(&error);
if(!m_sasl_context)
{
std::string error_message =
std::string("SASL initialization error: ") +
error->message;
g_error_free(error);
throw std::runtime_error(error_message);
}
inf_sasl_context_set_callback(
m_sasl_context, &AuthCommands::sasl_callback_static,
this, NULL);
// Set SASL context for new connections:
m_connection_manager.set_sasl_context(m_sasl_context,
"ANONYMOUS PLAIN");
g_signal_connect(
G_OBJECT(m_browser.get_store()),
"set-browser",
G_CALLBACK(&AuthCommands::set_browser_callback_static),
this);
}
Gobby::AuthCommands::~AuthCommands()
{
m_connection_manager.set_sasl_context(NULL, NULL);
inf_sasl_context_unref(m_sasl_context);
for(RetryMap::iterator iter = m_retries.begin();
iter != m_retries.end(); ++iter)
{
g_signal_handler_disconnect(iter->first, iter->second.handle);
}
}
void Gobby::AuthCommands::set_sasl_error(InfXmppConnection* connection,
const gchar* message)
{
GError* error = g_error_new_literal(
inf_authentication_detail_error_quark(),
INF_AUTHENTICATION_DETAIL_ERROR_AUTHENTICATION_FAILED,
message
);
inf_xmpp_connection_set_sasl_error(connection, error);
g_error_free(error);
}
void Gobby::AuthCommands::sasl_callback(InfSaslContextSession* session,
InfXmppConnection* xmpp,
Gsasl_property prop)
{
const Glib::ustring username = m_preferences.user.name;
const std::string correct_password = m_preferences.user.password;
const char* password;
switch(prop)
{
case GSASL_ANONYMOUS_TOKEN:
inf_sasl_context_session_set_property(
session, GSASL_ANONYMOUS_TOKEN, username.c_str());
inf_sasl_context_session_continue(session, GSASL_OK);
break;
case GSASL_AUTHID:
inf_sasl_context_session_set_property(
session, GSASL_AUTHID, username.c_str());
inf_sasl_context_session_continue(session, GSASL_OK);
break;
case GSASL_PASSWORD:
{
RetryMap::iterator i = m_retries.find(xmpp);
if(i == m_retries.end())
i = insert_retry_info(xmpp);
RetryInfo& info(i->second);
if(!info.last_password.empty())
{
inf_sasl_context_session_set_property(
session, GSASL_PASSWORD,
info.last_password.c_str());
inf_sasl_context_session_continue(session,
GSASL_OK);
}
else
{
// Query user for password
g_assert(info.password_dialog == NULL);
gchar* remote_id;
g_object_get(G_OBJECT(xmpp),
"remote-hostname", &remote_id,
NULL);
Glib::ustring remote_id_(remote_id);
g_free(remote_id);
info.password_dialog = new PasswordDialog(
m_parent, remote_id_, info.retries);
info.password_dialog->add_button(
Gtk::Stock::CANCEL,
Gtk::RESPONSE_CANCEL);
info.password_dialog->add_button(
Gtk::Stock::OK,
Gtk::RESPONSE_ACCEPT);
Gtk::Dialog& dialog = *info.password_dialog;
dialog.signal_response().connect(sigc::bind(
sigc::mem_fun(
*this,
&AuthCommands::on_response),
session, xmpp));
info.password_dialog->present();
}
}
break;
case GSASL_VALIDATE_ANONYMOUS:
if(m_preferences.user.require_password)
{
inf_sasl_context_session_continue(
session,
GSASL_AUTHENTICATION_ERROR
);
set_sasl_error(xmpp, _("Password required"));
}
else
{
inf_sasl_context_session_continue(session, GSASL_OK);
}
break;
case GSASL_VALIDATE_SIMPLE:
password = inf_sasl_context_session_get_property(
session, GSASL_PASSWORD);
if(strcmp(password, correct_password.c_str()) != 0)
{
inf_sasl_context_session_continue(
session,
GSASL_AUTHENTICATION_ERROR
);
set_sasl_error(xmpp, _("Incorrect password"));
}
else
{
inf_sasl_context_session_continue(session, GSASL_OK);
}
break;
default:
inf_sasl_context_session_continue(session, GSASL_NO_CALLBACK);
break;
}
}
void Gobby::AuthCommands::on_response(int response_id,
InfSaslContextSession* session,
InfXmppConnection* xmpp)
{
RetryMap::iterator i = m_retries.find(xmpp);
g_assert(i != m_retries.end());
RetryInfo& info(i->second);
if(response_id == Gtk::RESPONSE_ACCEPT)
info.last_password = info.password_dialog->get_password();
else
info.last_password = "";
delete info.password_dialog;
info.password_dialog = NULL;
++info.retries;
if(info.last_password.empty())
{
inf_sasl_context_session_continue(session, GSASL_NO_PASSWORD);
}
else
{
inf_sasl_context_session_set_property(
session, GSASL_PASSWORD, info.last_password.c_str());
inf_sasl_context_session_continue(session, GSASL_OK);
}
}
void Gobby::AuthCommands::set_browser_callback(InfBrowser* old_browser,
InfBrowser* new_browser)
{
// TODO: Disconnect from the signal on destruction?
if(new_browser != NULL && INFC_IS_BROWSER(new_browser))
{
g_signal_connect(
G_OBJECT(new_browser),
"error",
G_CALLBACK(browser_error_callback_static),
this);
}
}
void Gobby::AuthCommands::browser_error_callback(InfcBrowser* browser,
GError* error)
{
// The Browser already displays errors inline, but we want
// auth-related error messages to show up in the status bar.
InfXmlConnection* connection = infc_browser_get_connection(browser);
g_assert(INF_IS_XMPP_CONNECTION(connection));
InfXmppConnection* xmpp = INF_XMPP_CONNECTION(connection);
RetryMap::iterator iter = m_retries.find(xmpp);
if(iter == m_retries.end())
iter = insert_retry_info(xmpp);
Glib::ustring& last_password(iter->second.last_password);
Glib::ustring old_password;
old_password.swap(last_password);
if(error->domain ==
g_quark_from_static_string("INF_XMPP_CONNECTION_AUTH_ERROR"))
{
// Authentication failed for some reason, maybe because the
// server aborted authentication. If we were querying a
// password then close the dialog now.
delete iter->second.password_dialog;
iter->second.password_dialog = NULL;
const GError* sasl_error =
inf_xmpp_connection_get_sasl_error(xmpp);
if(sasl_error != NULL &&
sasl_error->domain ==
inf_authentication_detail_error_quark())
{
handle_error_detail(xmpp, sasl_error,
old_password,
last_password);
}
else if(sasl_error != NULL)
{
show_error(sasl_error, m_statusbar, connection);
}
else
{
show_error(error, m_statusbar, connection);
}
}
else if(error->domain == inf_gsasl_error_quark())
{
show_error(error, m_statusbar, connection);
}
}
void Gobby::AuthCommands::handle_error_detail(InfXmppConnection* xmpp,
const GError* detail_error,
Glib::ustring& old_password,
Glib::ustring& last_password)
{
GError* error = NULL;
switch(detail_error->code)
{
case INF_AUTHENTICATION_DETAIL_ERROR_AUTHENTICATION_FAILED:
inf_xmpp_connection_retry_sasl_authentication(xmpp, &error);
break;
case INF_AUTHENTICATION_DETAIL_ERROR_TRY_AGAIN:
old_password.swap(last_password);
inf_xmpp_connection_retry_sasl_authentication(xmpp, &error);
break;
default:
show_error(detail_error, m_statusbar,
INF_XML_CONNECTION(xmpp));
break;
}
if(error)
{
show_error(error, m_statusbar,
INF_XML_CONNECTION(xmpp));
g_error_free(error);
}
}
Gobby::AuthCommands::RetryMap::iterator
Gobby::AuthCommands::insert_retry_info(InfXmppConnection* xmpp)
{
RetryMap::iterator iter = m_retries.insert(
std::make_pair(xmpp,
RetryInfo())).first;
iter->second.retries = 0;
iter->second.handle = g_signal_connect(
G_OBJECT(xmpp),
"notify::status",
G_CALLBACK(on_notify_status_static),
this);
iter->second.password_dialog = NULL;
return iter;
}
void Gobby::AuthCommands::on_notify_status(InfXmppConnection* connection)
{
InfXmlConnectionStatus status;
g_object_get(G_OBJECT(connection), "status", &status, NULL);
if(status != INF_XML_CONNECTION_OPENING)
{
RetryMap::iterator iter = m_retries.find(connection);
g_signal_handler_disconnect(connection, iter->second.handle);
delete iter->second.password_dialog;
m_retries.erase(iter);
}
}
<|endoftext|> |
<commit_before><commit_msg>7766bc08-2d53-11e5-baeb-247703a38240<commit_after><|endoftext|> |
<commit_before>#include "Halide.h"
using namespace Halide;
using namespace Halide::ConciseCasts;
int main(int argc, char **argv) {
Target target = get_target_from_environment();
std::cout << "Target: " << target.to_string() << "\n";
// We take two 8 bit matrices as input.
Var x("x"), y("y");
ImageParam A(UInt(8), 2);
ImageParam B(UInt(8), 2);
// Align the extent of the K dimension to the product of our split
// factors.
const int k_split_factor = 32;
Expr k_extent = A.dim(0).extent();
k_extent = (k_extent/(k_split_factor*4))*(k_split_factor*4);
A.dim(0).set_extent(k_extent);
B.dim(1).set_extent(k_extent);
// We split directly in the algorithm by a factor of 4, so we can
// generate vrmpy instructions on Hexagon.
RDom rk(0, k_extent/4, "k");
// Define the reordering of B as a separate stage so we can lift
// the interleaving required by vrmpy out of the inner loop.
Func B_swizzled("B_swizzled");
Var k("k");
B_swizzled(x, y, k) = B(x, 4*y + k);
Func AB("AB");
AB(x, y) = u32(0);
AB(x, y) +=
u32(u16(A(4*rk + 0, y))*u16(B_swizzled(x, rk, 0))) +
u32(u16(A(4*rk + 1, y))*u16(B_swizzled(x, rk, 1))) +
u32(u16(A(4*rk + 2, y))*u16(B_swizzled(x, rk, 2))) +
u32(u16(A(4*rk + 3, y))*u16(B_swizzled(x, rk, 3)));
Func output = AB.in();
// Schedule.
int vector_size_u8 = target.natural_vector_size<uint8_t>();
bool use_hexagon = false;
if (target.has_feature(Target::HVX_64)) {
vector_size_u8 = 64;
use_hexagon = true;
} else if (target.has_feature(Target::HVX_128)) {
vector_size_u8 = 128;
use_hexagon = true;
}
int vector_size_u32 = vector_size_u8 / 4;
if (use_hexagon) {
RVar rki, rko, rkoo, rkoi;
Var xo("xo"), yo("yo");
output
.compute_root()
.hexagon()
.tile(x, y, xo, yo, x, y, vector_size_u8, 4, TailStrategy::RoundUp)
.reorder(x, y, yo, xo)
.vectorize(x)
.unroll(y)
.parallel(xo);
AB.compute_at(output, yo)
.vectorize(x)
.unroll(y);
AB.update(0)
// Split k so we can read a cache line of A at a time.
.split(rk, rko, rki, k_split_factor)
.reorder(x, y, rki, rko)
.vectorize(x)
.unroll(y)
.unroll(rki, 4);
Var kx("kx");
B_swizzled.compute_at(output, xo)
.reorder_storage(k, x, y)
.fuse(k, x, kx)
.vectorize(kx, vector_size_u8*4, TailStrategy::RoundUp);
} else {
Var xi("xi"), xii("xii"), yi("yi"), yii("yii");
RVar rki("rki");
// This schedule taken from test/performance/matrix_multiplication.cpp
constexpr int kBlockSize = 32;
const int kBlockSizeXi = 8;
output
.compute_root()
.tile(x, y, x, y, xi, yi, vector_size_u8, 4, TailStrategy::RoundUp)
.reorder(xi, yi, x, y)
.vectorize(xi)
.unroll(yi)
.parallel(y);
AB.compute_root()
.vectorize(x, vector_size_u32);
AB.update(0)
.split(x, x, xi, kBlockSize, TailStrategy::GuardWithIf)
.split(xi, xi, xii, kBlockSizeXi, TailStrategy::GuardWithIf)
.split(y, y, yi, kBlockSize, TailStrategy::GuardWithIf)
.split(yi, yi, yii, 4, TailStrategy::GuardWithIf)
.split(rk, rk, rki, kBlockSize, TailStrategy::GuardWithIf)
.reorder(xii, yii, xi, rki, yi, rk, x, y)
.parallel(y)
.vectorize(xii)
.unroll(xi)
.unroll(yii);
}
// Require scanlines of the input and output to be aligned, and
// tell Halide about our dimension convention.
for (auto i : {(OutputImageParam)A, (OutputImageParam)B, output.output_buffer()}) {
int align = vector_size_u8/i.type().bytes();
i.dim(0)
.set_bounds(0, (i.dim(0).extent()/align)*align);
i.dim(1)
.set_bounds(0, (i.dim(1).extent()/align)*align)
.set_stride((i.dim(1).stride()/align)*align);
}
std::stringstream hdr;
hdr << argv[2] << ".h";
output.compile_to_header(hdr.str(), {A, B}, argv[2], target);
std::stringstream obj;
obj << argv[1] << ".o";
output.compile_to_object(obj.str(), {A, B}, argv[2], target);
return 0;
}
<commit_msg>More straightforward schedule for swizzling.<commit_after>#include "Halide.h"
using namespace Halide;
using namespace Halide::ConciseCasts;
int main(int argc, char **argv) {
Target target = get_target_from_environment();
std::cout << "Target: " << target.to_string() << "\n";
// We take two 8 bit matrices as input.
Var x("x"), y("y");
ImageParam A(UInt(8), 2);
ImageParam B(UInt(8), 2);
// Align the extent of the K dimension to the product of our split
// factors.
const int k_split_factor = 32;
Expr k_extent = A.dim(0).extent();
k_extent = (k_extent/(k_split_factor*4))*(k_split_factor*4);
A.dim(0).set_extent(k_extent);
B.dim(1).set_extent(k_extent);
// We split directly in the algorithm by a factor of 4, so we can
// generate vrmpy instructions on Hexagon.
RDom rk(0, k_extent/4, "k");
// Define the reordering of B as a separate stage so we can lift
// the interleaving required by vrmpy out of the inner loop.
Func B_swizzled("B_swizzled");
Var k("k");
B_swizzled(x, y, k) = B(x, 4*y + k);
Func AB("AB");
AB(x, y) = u32(0);
AB(x, y) +=
u32(u16(A(4*rk + 0, y))*u16(B_swizzled(x, rk, 0))) +
u32(u16(A(4*rk + 1, y))*u16(B_swizzled(x, rk, 1))) +
u32(u16(A(4*rk + 2, y))*u16(B_swizzled(x, rk, 2))) +
u32(u16(A(4*rk + 3, y))*u16(B_swizzled(x, rk, 3)));
Func output = AB.in();
// Schedule.
int vector_size_u8 = target.natural_vector_size<uint8_t>();
bool use_hexagon = false;
if (target.has_feature(Target::HVX_64)) {
vector_size_u8 = 64;
use_hexagon = true;
} else if (target.has_feature(Target::HVX_128)) {
vector_size_u8 = 128;
use_hexagon = true;
}
int vector_size_u32 = vector_size_u8 / 4;
if (use_hexagon) {
RVar rki, rko, rkoo, rkoi;
Var xo("xo"), yo("yo");
output
.compute_root()
.hexagon()
.tile(x, y, xo, yo, x, y, vector_size_u8, 4, TailStrategy::RoundUp)
.reorder(x, y, yo, xo)
.vectorize(x)
.unroll(y)
.parallel(xo);
AB.compute_at(output, yo)
.vectorize(x)
.unroll(y);
AB.update(0)
// Split k so we can read a cache line of A at a time.
.split(rk, rko, rki, k_split_factor)
.reorder(x, y, rki, rko)
.vectorize(x)
.unroll(y)
.unroll(rki, 4);
Var kx("kx");
B_swizzled.compute_at(output, xo)
.reorder_storage(k, x, y)
.reorder(k, x, y)
.vectorize(x, vector_size_u8, TailStrategy::RoundUp)
.unroll(k);
} else {
Var xi("xi"), xii("xii"), yi("yi"), yii("yii");
RVar rki("rki");
// This schedule taken from test/performance/matrix_multiplication.cpp
constexpr int kBlockSize = 32;
const int kBlockSizeXi = 8;
output
.compute_root()
.tile(x, y, x, y, xi, yi, vector_size_u8, 4, TailStrategy::RoundUp)
.reorder(xi, yi, x, y)
.vectorize(xi)
.unroll(yi)
.parallel(y);
AB.compute_root()
.vectorize(x, vector_size_u32);
AB.update(0)
.split(x, x, xi, kBlockSize, TailStrategy::GuardWithIf)
.split(xi, xi, xii, kBlockSizeXi, TailStrategy::GuardWithIf)
.split(y, y, yi, kBlockSize, TailStrategy::GuardWithIf)
.split(yi, yi, yii, 4, TailStrategy::GuardWithIf)
.split(rk, rk, rki, kBlockSize, TailStrategy::GuardWithIf)
.reorder(xii, yii, xi, rki, yi, rk, x, y)
.parallel(y)
.vectorize(xii)
.unroll(xi)
.unroll(yii);
}
// Require scanlines of the input and output to be aligned, and
// tell Halide about our dimension convention.
for (auto i : {(OutputImageParam)A, (OutputImageParam)B, output.output_buffer()}) {
int align = vector_size_u8/i.type().bytes();
i.dim(0)
.set_bounds(0, (i.dim(0).extent()/align)*align);
i.dim(1)
.set_bounds(0, (i.dim(1).extent()/align)*align)
.set_stride((i.dim(1).stride()/align)*align);
}
std::stringstream hdr;
hdr << argv[2] << ".h";
output.compile_to_header(hdr.str(), {A, B}, argv[2], target);
std::stringstream obj;
obj << argv[1] << ".o";
output.compile_to_object(obj.str(), {A, B}, argv[2], target);
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>4aefa8ae-2e1d-11e5-affc-60f81dce716c<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 arduino-menusystem
* Licensed under the MIT license (see LICENSE)
*/
#include "MenuSystem.h"
// *********************************************************
// MenuComponent
// *********************************************************
MenuComponent::MenuComponent(const char* name)
: _name(name)
{
}
const char* MenuComponent::get_name() const
{
return _name;
}
void MenuComponent::set_name(const char* name)
{
_name = name;
}
// *********************************************************
// Menu
// *********************************************************
Menu(const char* name, void (*callback)(Menu*) = NULL)
: MenuComponent(name),
_disp_callback(callback),
_p_sel_menu_component(NULL),
_menu_components(NULL),
_p_parent(NULL),
_num_menu_components(0),
_cur_menu_component_num(0),
_prev_menu_component_num(0)
{
}
boolean Menu::display()
{
if (_disp_callback) {
(*_disp_callback)(this);
return true;
}
return false;
}
void set_display_callback(void (*callback)(Menu*))
{
_disp_callback = callback;
}
boolean Menu::next(boolean loop)
{
_prev_menu_component_num; = _cur_menu_component_num;
if (_cur_menu_component_num != _num_menu_components - 1)
{
_cur_menu_component_num++;
_p_sel_menu_component = _menu_components[_cur_menu_component_num];
return true;
} else if (loop) {
_cur_menu_component_num = 0;
_p_sel_menu_component = _menu_components[_cur_menu_component_num];
return true;
}
return false;
}
boolean Menu::prev(boolean loop)
{
_prev_menu_component_num; = _cur_menu_component_num;
if (_cur_menu_component_num != 0)
{
cur_menu_component_num--;
_p_sel_menu_component = _menu_components[_cur_menu_component_num];
return true;
} else if (loop)
{
_cur_menu_component_num = _num_menu_components - 1;
_p_sel_menu_component = _menu_components[_cur_menu_component_num];
return true;
}
return false;
}
MenuComponent* Menu::activate()
{
MenuComponent* pComponent = _menu_components[_cur_menu_component_num];
if (pComponent == NULL)
return NULL;
return pComponent->select();
}
MenuComponent* Menu::select()
{
return this;
}
void Menu::reset()
{
for (int i = 0; i < _num_menu_components; ++i)
_menu_components[i]->reset();
_prev_menu_component_num; = 0;
_cur_menu_component_num = 0;
_p_sel_menu_component = _menu_components[0];
}
void Menu::add_item(MenuItem* pItem, void (*on_select)(MenuItem*))
{
// Resize menu component list, keeping existing items.
// If it fails, there the item is not added and the function returns.
_menu_components = (MenuComponent**) realloc(_menu_components,
(_num_menu_components + 1)
* sizeof(MenuComponent*));
if (_menu_components == NULL)
return;
_menu_components[_num_menu_components] = pItem;
pItem->set_select_function(on_select);
if (_num_menu_components == 0)
_p_sel_menu_component = pItem;
_num_menu_components++;
}
Menu const* Menu::get_parent() const
{
return _p_parent;
}
void Menu::set_parent(Menu* pParent)
{
_p_parent = pParent;
}
Menu const* Menu::add_menu(Menu* pMenu)
{
// Resize menu component list, keeping existing items.
// If it fails, there the item is not added and the function returns.
_menu_components = (MenuComponent**) realloc(_menu_components,
(_num_menu_components + 1)
* sizeof(MenuComponent*));
if (_menu_components == NULL)
return NULL;
pMenu->set_parent(this);
_menu_components[_num_menu_components] = pMenu;
if (_num_menu_components == 0)
_p_sel_menu_component = pMenu;
_num_menu_components++;
return pMenu;
}
MenuComponent const* Menu::get_menu_component(byte index) const
{
return _menu_components[index];
}
MenuComponent const* Menu::get_selected() const
{
return _p_sel_menu_component;
}
byte Menu::get_num_menu_components() const
{
return _num_menu_components;
}
byte Menu::get_cur_menu_component_num() const
{
return _cur_menu_component_num;
}
byte Menu::get_prev_menu_component_num() const
{
return _prev_menu_component_num;
}
// *********************************************************
// MenuItem
// *********************************************************
MenuItem::MenuItem(const char* name)
: MenuComponent(name),
_on_select(0)
{
}
void MenuItem::set_select_function(void (*on_select)(MenuItem*))
{
_on_select = on_select;
}
MenuComponent* MenuItem::select()
{
if (_on_select != NULL)
_on_select(this);
return 0;
}
void MenuItem::reset()
{
// Do nothing.
}
// *********************************************************
// MenuSystem
// *********************************************************
MenuSystem::MenuSystem()
: _p_root_menu(NULL),
_p_curr_menu(NULL)
{
}
boolean MenuSystem::next(boolean loop)
{
return _p_curr_menu->next(loop);
}
boolean MenuSystem::prev(boolean loop)
{
return _p_curr_menu->prev(loop);
}
void MenuSystem::reset()
{
_p_curr_menu = _p_root_menu;
_p_root_menu->reset();
}
void MenuSystem::select(bool reset)
{
MenuComponent* pComponent = _p_curr_menu->activate();
if (pComponent != NULL)
_p_curr_menu = (Menu*) pComponent;
else
if (reset) this->reset();
}
boolean MenuSystem::back()
{
if (_p_curr_menu != _p_root_menu)
{
_p_curr_menu = const_cast<Menu*>(_p_curr_menu->get_parent());
return true;
}
// We are already in the root menu
return false;
}
void MenuSystem::set_root_menu(Menu* p_root_menu)
{
_p_root_menu = p_root_menu;
_p_curr_menu = p_root_menu;
}
Menu const* MenuSystem::get_current_menu() const
{
return _p_curr_menu;
}
boolean MenuSystem::display()
{
if (_p_curr_menu != NULL) return _p_curr_menu->display();
return false;
}
<commit_msg>Fixed typos, code compiles<commit_after>/*
* Copyright (c) 2015 arduino-menusystem
* Licensed under the MIT license (see LICENSE)
*/
#include "MenuSystem.h"
// *********************************************************
// MenuComponent
// *********************************************************
MenuComponent::MenuComponent(const char* name)
: _name(name)
{
}
const char* MenuComponent::get_name() const
{
return _name;
}
void MenuComponent::set_name(const char* name)
{
_name = name;
}
// *********************************************************
// Menu
// *********************************************************
Menu::Menu(const char* name, void (*callback)(Menu*))
: MenuComponent(name),
_disp_callback(callback),
_p_sel_menu_component(NULL),
_menu_components(NULL),
_p_parent(NULL),
_num_menu_components(0),
_cur_menu_component_num(0),
_prev_menu_component_num(0)
{
}
boolean Menu::display()
{
if (_disp_callback) {
(*_disp_callback)(this);
return true;
}
return false;
}
void Menu::set_display_callback(void (*callback)(Menu*))
{
_disp_callback = callback;
}
boolean Menu::next(boolean loop)
{
_prev_menu_component_num = _cur_menu_component_num;
if (_cur_menu_component_num != _num_menu_components - 1)
{
_cur_menu_component_num++;
_p_sel_menu_component = _menu_components[_cur_menu_component_num];
return true;
} else if (loop) {
_cur_menu_component_num = 0;
_p_sel_menu_component = _menu_components[_cur_menu_component_num];
return true;
}
return false;
}
boolean Menu::prev(boolean loop)
{
_prev_menu_component_num = _cur_menu_component_num;
if (_cur_menu_component_num != 0)
{
_cur_menu_component_num--;
_p_sel_menu_component = _menu_components[_cur_menu_component_num];
return true;
} else if (loop)
{
_cur_menu_component_num = _num_menu_components - 1;
_p_sel_menu_component = _menu_components[_cur_menu_component_num];
return true;
}
return false;
}
MenuComponent* Menu::activate()
{
MenuComponent* pComponent = _menu_components[_cur_menu_component_num];
if (pComponent == NULL)
return NULL;
return pComponent->select();
}
MenuComponent* Menu::select()
{
return this;
}
void Menu::reset()
{
for (int i = 0; i < _num_menu_components; ++i)
_menu_components[i]->reset();
_prev_menu_component_num = 0;
_cur_menu_component_num = 0;
_p_sel_menu_component = _menu_components[0];
}
void Menu::add_item(MenuItem* pItem, void (*on_select)(MenuItem*))
{
// Resize menu component list, keeping existing items.
// If it fails, there the item is not added and the function returns.
_menu_components = (MenuComponent**) realloc(_menu_components,
(_num_menu_components + 1)
* sizeof(MenuComponent*));
if (_menu_components == NULL)
return;
_menu_components[_num_menu_components] = pItem;
pItem->set_select_function(on_select);
if (_num_menu_components == 0)
_p_sel_menu_component = pItem;
_num_menu_components++;
}
Menu const* Menu::get_parent() const
{
return _p_parent;
}
void Menu::set_parent(Menu* pParent)
{
_p_parent = pParent;
}
Menu const* Menu::add_menu(Menu* pMenu)
{
// Resize menu component list, keeping existing items.
// If it fails, there the item is not added and the function returns.
_menu_components = (MenuComponent**) realloc(_menu_components,
(_num_menu_components + 1)
* sizeof(MenuComponent*));
if (_menu_components == NULL)
return NULL;
pMenu->set_parent(this);
_menu_components[_num_menu_components] = pMenu;
if (_num_menu_components == 0)
_p_sel_menu_component = pMenu;
_num_menu_components++;
return pMenu;
}
MenuComponent const* Menu::get_menu_component(byte index) const
{
return _menu_components[index];
}
MenuComponent const* Menu::get_selected() const
{
return _p_sel_menu_component;
}
byte Menu::get_num_menu_components() const
{
return _num_menu_components;
}
byte Menu::get_cur_menu_component_num() const
{
return _cur_menu_component_num;
}
byte Menu::get_prev_menu_component_num() const
{
return _prev_menu_component_num;
}
// *********************************************************
// MenuItem
// *********************************************************
MenuItem::MenuItem(const char* name)
: MenuComponent(name),
_on_select(0)
{
}
void MenuItem::set_select_function(void (*on_select)(MenuItem*))
{
_on_select = on_select;
}
MenuComponent* MenuItem::select()
{
if (_on_select != NULL)
_on_select(this);
return 0;
}
void MenuItem::reset()
{
// Do nothing.
}
// *********************************************************
// MenuSystem
// *********************************************************
MenuSystem::MenuSystem()
: _p_root_menu(NULL),
_p_curr_menu(NULL)
{
}
boolean MenuSystem::next(boolean loop)
{
return _p_curr_menu->next(loop);
}
boolean MenuSystem::prev(boolean loop)
{
return _p_curr_menu->prev(loop);
}
void MenuSystem::reset()
{
_p_curr_menu = _p_root_menu;
_p_root_menu->reset();
}
void MenuSystem::select(bool reset)
{
MenuComponent* pComponent = _p_curr_menu->activate();
if (pComponent != NULL)
_p_curr_menu = (Menu*) pComponent;
else
if (reset) this->reset();
}
boolean MenuSystem::back()
{
if (_p_curr_menu != _p_root_menu)
{
_p_curr_menu = const_cast<Menu*>(_p_curr_menu->get_parent());
return true;
}
// We are already in the root menu
return false;
}
void MenuSystem::set_root_menu(Menu* p_root_menu)
{
_p_root_menu = p_root_menu;
_p_curr_menu = p_root_menu;
}
Menu const* MenuSystem::get_current_menu() const
{
return _p_curr_menu;
}
boolean MenuSystem::display()
{
if (_p_curr_menu != NULL) return _p_curr_menu->display();
return false;
}
<|endoftext|> |
<commit_before><commit_msg>506ca440-5216-11e5-a7b4-6c40088e03e4<commit_after><|endoftext|> |
<commit_before>/*
* RBGolfPin.cpp
* golf
*
* Created by Robert Rose on 4/17/09.
* Copyright 2009 __MyCompanyName__. All rights reserved.
*
*/
#include "RBGolfPin.h"
#include "RudeGL.h"
const float kGolfPinHeight = 10.0f;
const float kGolfPinFlagHeight = 2.0f;
const unsigned int kGolfPinFlagColor = 0xFF0000FF;
const unsigned int kGolfPinColor = 0xFFFFFFFF;
RBGolfPin::RBGolfPin()
{
}
RBGolfPin::~RBGolfPin()
{
}
void RBGolfPin::Render()
{
RGL.Enable(kBackfaceCull, true);
RGL.Enable(kDepthTest, true);
RudeObject::Render();
RGL.LoadIdentity();
RGL.Enable(kDepthTest, false);
glDisable(GL_TEXTURE_2D);
RGL.EnableClient(kVertexArray, true);
RGL.EnableClient(kColorArray, true);
RGL.EnableClient(kTextureCoordArray, false);
GLfloat point[] = {
m_position.x(), m_position.y() + kGolfPinHeight, m_position.z(),
m_position.x(), m_position.y() + kGolfPinHeight - kGolfPinFlagHeight, m_position.z(),
m_position.x(), m_position.y() + kGolfPinHeight - kGolfPinFlagHeight, m_position.z(),
m_position.x(), m_position.y(), m_position.z(),
};
unsigned int colors[] = {
kGolfPinFlagColor,
kGolfPinFlagColor,
kGolfPinColor,
kGolfPinColor
};
glVertexPointer(3, GL_FLOAT, 0, point);
glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors);
glDrawArrays(GL_LINES, 0, 4);
}
<commit_msg>pin render updates<commit_after>/*
* RBGolfPin.cpp
* golf
*
* Created by Robert Rose on 4/17/09.
* Copyright 2009 __MyCompanyName__. All rights reserved.
*
*/
#include "RBGolfPin.h"
#include "RudeGL.h"
const float kGolfPinHeight = 10.0f;
const float kGolfPinFlagHeight = 2.0f;
const unsigned int kGolfPinFlagColor = 0xFF0000FF;
const unsigned int kGolfPinColor = 0xFFFFFFFF;
RBGolfPin::RBGolfPin()
{
}
RBGolfPin::~RBGolfPin()
{
}
void RBGolfPin::Render()
{
RGL.Enable(kBackfaceCull, true);
RGL.Enable(kDepthTest, true);
RudeObject::Render();
RGL.LoadIdentity();
RGL.Enable(kDepthTest, false);
glDisable(GL_TEXTURE_2D);
RGL.EnableClient(kVertexArray, true);
RGL.EnableClient(kColorArray, true);
RGL.EnableClient(kTextureCoordArray, false);
GLfloat point[] = {
m_position.x(), m_position.y() + kGolfPinHeight - kGolfPinFlagHeight, m_position.z(),
m_position.x(), m_position.y(), m_position.z(),
};
unsigned int colors[] = {
kGolfPinColor,
kGolfPinColor
};
glVertexPointer(3, GL_FLOAT, 0, point);
glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors);
glDrawArrays(GL_LINES, 0, 2);
}
<|endoftext|> |
<commit_before><commit_msg>We apologise for the previous fix. Those responsible have been sacked<commit_after><|endoftext|> |
<commit_before><commit_msg>Add a "library" root tag to the xml file<commit_after><|endoftext|> |
<commit_before><commit_msg>d2a6044f-352a-11e5-ae8c-34363b65e550<commit_after><|endoftext|> |
<commit_before><commit_msg>a12be9a6-2d3e-11e5-8885-c82a142b6f9b<commit_after><|endoftext|> |
<commit_before><commit_msg>ecbc2fb3-2e4e-11e5-a4cf-28cfe91dbc4b<commit_after><|endoftext|> |
<commit_before><commit_msg>I finished programming, there is nothing left to program<commit_after><|endoftext|> |
<commit_before><commit_msg>Don't kick users for setting nicks<commit_after><|endoftext|> |
<commit_before><commit_msg>9363bf06-2d14-11e5-af21-0401358ea401<commit_after><|endoftext|> |
<commit_before><commit_msg>code and doc reorgs for clarity<commit_after><|endoftext|> |
<commit_before><commit_msg>5ae7ec4a-2d16-11e5-af21-0401358ea401<commit_after><|endoftext|> |
<commit_before><commit_msg>having coffee<commit_after><|endoftext|> |
<commit_before><commit_msg>eaf0e252-585a-11e5-a98d-6c40088e03e4<commit_after><|endoftext|> |
<commit_before><commit_msg>Backup, rebase this later<commit_after><|endoftext|> |
<commit_before><commit_msg>f4f35ad2-585a-11e5-90eb-6c40088e03e4<commit_after><|endoftext|> |
<commit_before><commit_msg>481661f8-5216-11e5-a118-6c40088e03e4<commit_after><|endoftext|> |
<commit_before><commit_msg>gsghfklghjsad<commit_after><|endoftext|> |
<commit_before><commit_msg>swapVariantの安定性向上<commit_after><|endoftext|> |
<commit_before>#include <zorba/zorba.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <sstream>
// tests are allowed to use internals
#include "api/unmarshaller.h"
#include "store/api/item.h"
#include "zorbatypes/xqpstring.h"
#include "util/properties.h"
using namespace zorba;
using namespace std;
void set_var (string name, string val, DynamicContext_t dctx)
{
if (name [name.size () - 1] == ':')
{
Item lItem = Zorba::getInstance()->getItemFactory()->createString(val);
if(name != ".") {
dctx->setVariable(name.substr (0, name.size () - 1), lItem);
} else
dctx->setContextItem(lItem);
}
else if (name[name.size () - 1] != ':')
{
ifstream is (val.c_str ());
assert (is);
if(name != ".")
dctx->setVariableAsDocument(name, val.c_str(), is);
else
dctx->setContextItemAsDocument(val.c_str(), is);
}
}
// TODO: for now apitest users expect 0 even for error results; this should change
#ifndef _WIN32_WCE
int main(int argc, char* argv[])
#else
int _tmain(int argc, _TCHAR* argv[])
#endif
{
// read the command file properties
if (! Properties::load(argc,argv))
return 4;
Properties* lProp = Properties::instance();
zorba::XQuery::CompilerHints chints;
chints.opt_level = lProp->useOptimizer () ? XQuery::CompilerHints::O1 : XQuery::CompilerHints::O0;
// output file (either a file or the standard out if no file is specified)
auto_ptr<ostream> outputFile (lProp->useResultFile() ?
new ofstream (lProp->getResultFile().c_str()) :
NULL);
ostream *resultFile = outputFile.get ();
if (resultFile == NULL)
resultFile = &cout;
// input file (either from a file or given as parameter)
const char* fname = lProp->getQuery().c_str();
auto_ptr<istream> qfile(!lProp->inlineQuery()&&*fname!='\0' ?
(istream*) new ifstream(fname) :
(istream*) new istringstream(fname));
if (!qfile->good() || qfile->eof()) {
cerr << "no query given or not readable " << fname << endl;
return 3;
}
// print the query if requested
if (lProp->printQuery()) {
cout << "Query text:\n";
copy (istreambuf_iterator<char> (*qfile), istreambuf_iterator<char> (), ostreambuf_iterator<char> (cout));
cout << "\n" << endl;
qfile->seekg(0); // go back to the beginning
}
// start processing
Zorba* zengine = Zorba::getInstance();
// start parsing the query
XQuery_t query;
try {
query = zengine->compileQuery(*qfile, chints);
} catch (ZorbaException &e) {
cerr << "Compilation error: " << e << endl;
return 1;
}
// set external variables
vector<pair <string, string> > ext_vars = lProp->getExternalVars ();
DynamicContext_t dctx = query->getDynamicContext ();
for (vector<pair <string, string> >::const_iterator iter = ext_vars.begin ();
iter != ext_vars.end (); iter++) {
set_var (iter->first, iter->second, dctx);
}
// output the result (either using xml serialization or using show)
cout << "Running query and printing result..." << endl;
if (lProp->useSerializer())
{
try
{
*resultFile << query;
}
catch (ZorbaException &e)
{
zengine->shutdown();
cerr << "Execution error: " << e << endl;
return 2;
}
}
else
{
ResultIterator_t result = query->iterator();
try
{
result->open();
Item lItem;
while (result->next(lItem)) {
// unmarshall the store item from the api item
store::Item_t lStoreItem = Unmarshaller::getInternalItem(lItem);
*resultFile << lStoreItem->show() << endl;
}
result->close();
}
catch (ZorbaException &e)
{
result->close();
zengine->shutdown();
cerr << "Execution error: " << e << endl;
return 2;
}
}
query.reset();
zengine->shutdown();
return 0;
}
<commit_msg>close query in case of errors<commit_after>#include <zorba/zorba.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <sstream>
// tests are allowed to use internals
#include "api/unmarshaller.h"
#include "store/api/item.h"
#include "zorbatypes/xqpstring.h"
#include "util/properties.h"
using namespace zorba;
using namespace std;
void set_var (string name, string val, DynamicContext_t dctx)
{
if (name [name.size () - 1] == ':')
{
Item lItem = Zorba::getInstance()->getItemFactory()->createString(val);
if(name != ".") {
dctx->setVariable(name.substr (0, name.size () - 1), lItem);
} else
dctx->setContextItem(lItem);
}
else if (name[name.size () - 1] != ':')
{
ifstream is (val.c_str ());
assert (is);
if(name != ".")
dctx->setVariableAsDocument(name, val.c_str(), is);
else
dctx->setContextItemAsDocument(val.c_str(), is);
}
}
// TODO: for now apitest users expect 0 even for error results; this should change
#ifndef _WIN32_WCE
int main(int argc, char* argv[])
#else
int _tmain(int argc, _TCHAR* argv[])
#endif
{
// read the command file properties
if (! Properties::load(argc,argv))
return 4;
Properties* lProp = Properties::instance();
zorba::XQuery::CompilerHints chints;
chints.opt_level = lProp->useOptimizer () ? XQuery::CompilerHints::O1 : XQuery::CompilerHints::O0;
// output file (either a file or the standard out if no file is specified)
auto_ptr<ostream> outputFile (lProp->useResultFile() ?
new ofstream (lProp->getResultFile().c_str()) :
NULL);
ostream *resultFile = outputFile.get ();
if (resultFile == NULL)
resultFile = &cout;
// input file (either from a file or given as parameter)
const char* fname = lProp->getQuery().c_str();
auto_ptr<istream> qfile(!lProp->inlineQuery()&&*fname!='\0' ?
(istream*) new ifstream(fname) :
(istream*) new istringstream(fname));
if (!qfile->good() || qfile->eof()) {
cerr << "no query given or not readable " << fname << endl;
return 3;
}
// print the query if requested
if (lProp->printQuery()) {
cout << "Query text:\n";
copy (istreambuf_iterator<char> (*qfile), istreambuf_iterator<char> (), ostreambuf_iterator<char> (cout));
cout << "\n" << endl;
qfile->seekg(0); // go back to the beginning
}
// start processing
Zorba* zengine = Zorba::getInstance();
// start parsing the query
XQuery_t query;
try {
query = zengine->compileQuery(*qfile, chints);
} catch (ZorbaException &e) {
cerr << "Compilation error: " << e << endl;
return 1;
}
// set external variables
vector<pair <string, string> > ext_vars = lProp->getExternalVars ();
DynamicContext_t dctx = query->getDynamicContext ();
for (vector<pair <string, string> >::const_iterator iter = ext_vars.begin ();
iter != ext_vars.end (); iter++) {
set_var (iter->first, iter->second, dctx);
}
// output the result (either using xml serialization or using show)
cout << "Running query and printing result..." << endl;
if (lProp->useSerializer())
{
try
{
*resultFile << query;
}
catch (ZorbaException &e)
{
query.reset();
zengine->shutdown();
cerr << "Execution error: " << e << endl;
return 2;
}
}
else
{
ResultIterator_t result = query->iterator();
try
{
result->open();
Item lItem;
while (result->next(lItem)) {
// unmarshall the store item from the api item
store::Item_t lStoreItem = Unmarshaller::getInternalItem(lItem);
*resultFile << lStoreItem->show() << endl;
}
result->close();
}
catch (ZorbaException &e)
{
result->close();
zengine->shutdown();
cerr << "Execution error: " << e << endl;
return 2;
}
}
query.reset();
zengine->shutdown();
return 0;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS 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 Kaveh Vahedipour
////////////////////////////////////////////////////////////////////////////////
#include "AgencyFeature.h"
#include "Agency/Agent.h"
#include "Logger/Logger.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
#include "RestServer/EndpointFeature.h"
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
using namespace arangodb::rest;
AgencyFeature::AgencyFeature(application_features::ApplicationServer* server)
: ApplicationFeature(server, "Agency"),
_size(1),
_agentId(0),
_minElectionTimeout(1.0),
_maxElectionTimeout(5.0),
_notify(false),
_supervision(false),
_waitForSync(true),
_supervisionFrequency(5.0),
_compactionStepSize(1000) {
setOptional(true);
requiresElevatedPrivileges(false);
startsAfter("Database");
startsAfter("Dispatcher");
startsAfter("Endpoint");
startsAfter("QueryRegistry");
startsAfter("Random");
startsAfter("Recovery");
startsAfter("Scheduler");
startsAfter("Server");
}
AgencyFeature::~AgencyFeature() {}
void AgencyFeature::collectOptions(std::shared_ptr<ProgramOptions> options) {
options->addSection("agency", "Configure the agency");
options->addOption("--agency.size", "number of agents",
new UInt64Parameter(&_size));
options->addOption("--agency.id", "this agent's id",
new UInt32Parameter(&_agentId));
options->addOption(
"--agency.election-timeout-min",
"minimum timeout before an agent calls for new election [s]",
new DoubleParameter(&_minElectionTimeout));
options->addOption(
"--agency.election-timeout-max",
"maximum timeout before an agent calls for new election [s]",
new DoubleParameter(&_maxElectionTimeout));
options->addOption("--agency.endpoint", "agency endpoints",
new VectorParameter<StringParameter>(&_agencyEndpoints));
options->addOption("--agency.notify", "notify others",
new BooleanParameter(&_notify));
options->addOption("--agency.supervision",
"perform arangodb cluster supervision",
new BooleanParameter(&_supervision));
options->addOption("--agency.supervision-frequency",
"arangodb cluster supervision frequency [s]",
new DoubleParameter(&_supervisionFrequency));
options->addOption("--agency.compaction-step-size",
"step size between state machine compactions",
new UInt64Parameter(&_compactionStepSize));
options->addHiddenOption("--agency.wait-for-sync",
"wait for hard disk syncs on every persistence call "
"(required in production)",
new BooleanParameter(&_waitForSync));
}
void AgencyFeature::validateOptions(std::shared_ptr<ProgramOptions> options) {
ProgramOptions::ProcessingResult const& result = options->processingResult();
if (!result.touched("agency.id")) {
disable();
return;
}
// Agency size
if (_size < 1) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "AGENCY: agency must have size greater 0";
FATAL_ERROR_EXIT();
}
// Size needs to be odd
if (_size % 2 == 0) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "AGENCY: agency must have odd number of members";
FATAL_ERROR_EXIT();
}
// Id out of range
if (_agentId >= _size) {
LOG_TOPIC(FATAL, Logger::AGENCY) << "agency.id must not be larger than or "
<< "equal to agency.size";
FATAL_ERROR_EXIT();
}
// Timeouts sanity
if (_minElectionTimeout <= 0.) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "agency.election-timeout-min must not be negative!";
FATAL_ERROR_EXIT();
} else if (_minElectionTimeout < 0.15) {
LOG_TOPIC(WARN, Logger::AGENCY)
<< "very short agency.election-timeout-min!";
}
if (_maxElectionTimeout <= _minElectionTimeout) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "agency.election-timeout-max must not be shorter than or"
<< "equal to agency.election-timeout-min.";
FATAL_ERROR_EXIT();
}
if (_maxElectionTimeout <= 2 * _minElectionTimeout) {
LOG_TOPIC(WARN, Logger::AGENCY)
<< "agency.election-timeout-max should probably be chosen longer!"
<< " " << __FILE__ << __LINE__;
}
}
void AgencyFeature::prepare() {
_agencyEndpoints.resize(static_cast<size_t>(_size));
}
void AgencyFeature::start() {
if (!isEnabled()) {
return;
}
// TODO: Port this to new options handling
std::string endpoint;
std::string port = "8529";
EndpointFeature* endpointFeature =
ApplicationServer::getFeature<EndpointFeature>("Endpoint");
auto endpoints = endpointFeature->httpEndpoints();
if (!endpoints.empty()) {
std::string const& tmp = endpoints.front();
size_t pos = tmp.find(':',10);
if (pos != std::string::npos) {
port = tmp.substr(pos + 1, tmp.size() - pos);
}
}
endpoint = std::string("tcp://localhost:" + port);
_agent.reset(new consensus::Agent(consensus::config_t(
_agentId, _minElectionTimeout, _maxElectionTimeout, endpoint,
_agencyEndpoints, _notify, _supervision, _waitForSync,
_supervisionFrequency, _compactionStepSize)));
_agent->start();
_agent->load();
}
void AgencyFeature::unprepare() {
if (!isEnabled()) {
return;
}
_agent->beginShutdown();
if (_agent != nullptr) {
int counter = 0;
while (_agent->isRunning()) {
usleep(100000);
// emit warning after 5 seconds
if (++counter == 10 * 5) {
LOG_TOPIC(WARN, Logger::AGENCY) << "waiting for agent thread to finish";
}
}
}
}
<commit_msg>some additional checking of vector bounds and assertions<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS 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 Kaveh Vahedipour
////////////////////////////////////////////////////////////////////////////////
#include "AgencyFeature.h"
#include "Agency/Agent.h"
#include "Logger/Logger.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
#include "RestServer/EndpointFeature.h"
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
using namespace arangodb::rest;
AgencyFeature::AgencyFeature(application_features::ApplicationServer* server)
: ApplicationFeature(server, "Agency"),
_size(1),
_agentId(0),
_minElectionTimeout(0.5),
_maxElectionTimeout(2.5),
_notify(false),
_supervision(false),
_waitForSync(true),
_supervisionFrequency(5.0),
_compactionStepSize(1000) {
setOptional(true);
requiresElevatedPrivileges(false);
startsAfter("Database");
startsAfter("Dispatcher");
startsAfter("Endpoint");
startsAfter("QueryRegistry");
startsAfter("Random");
startsAfter("Recovery");
startsAfter("Scheduler");
startsAfter("Server");
}
AgencyFeature::~AgencyFeature() {}
void AgencyFeature::collectOptions(std::shared_ptr<ProgramOptions> options) {
options->addSection("agency", "Configure the agency");
options->addOption("--agency.size", "number of agents",
new UInt64Parameter(&_size));
options->addOption("--agency.id", "this agent's id",
new UInt32Parameter(&_agentId));
options->addOption(
"--agency.election-timeout-min",
"minimum timeout before an agent calls for new election [s]",
new DoubleParameter(&_minElectionTimeout));
options->addOption(
"--agency.election-timeout-max",
"maximum timeout before an agent calls for new election [s]",
new DoubleParameter(&_maxElectionTimeout));
options->addOption("--agency.endpoint", "agency endpoints",
new VectorParameter<StringParameter>(&_agencyEndpoints));
options->addOption("--agency.notify", "notify others",
new BooleanParameter(&_notify));
options->addOption("--agency.supervision",
"perform arangodb cluster supervision",
new BooleanParameter(&_supervision));
options->addOption("--agency.supervision-frequency",
"arangodb cluster supervision frequency [s]",
new DoubleParameter(&_supervisionFrequency));
options->addOption("--agency.compaction-step-size",
"step size between state machine compactions",
new UInt64Parameter(&_compactionStepSize));
options->addHiddenOption("--agency.wait-for-sync",
"wait for hard disk syncs on every persistence call "
"(required in production)",
new BooleanParameter(&_waitForSync));
}
void AgencyFeature::validateOptions(std::shared_ptr<ProgramOptions> options) {
ProgramOptions::ProcessingResult const& result = options->processingResult();
if (!result.touched("agency.id")) {
disable();
return;
}
// Agency size
if (_size < 1) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "AGENCY: agency must have size greater 0";
FATAL_ERROR_EXIT();
}
// Size needs to be odd
if (_size % 2 == 0) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "AGENCY: agency must have odd number of members";
FATAL_ERROR_EXIT();
}
// Id out of range
if (_agentId >= _size) {
LOG_TOPIC(FATAL, Logger::AGENCY) << "agency.id must not be larger than or "
<< "equal to agency.size";
FATAL_ERROR_EXIT();
}
// Timeouts sanity
if (_minElectionTimeout <= 0.) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "agency.election-timeout-min must not be negative!";
FATAL_ERROR_EXIT();
} else if (_minElectionTimeout < 0.15) {
LOG_TOPIC(WARN, Logger::AGENCY)
<< "very short agency.election-timeout-min!";
}
if (_maxElectionTimeout <= _minElectionTimeout) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "agency.election-timeout-max must not be shorter than or"
<< "equal to agency.election-timeout-min.";
FATAL_ERROR_EXIT();
}
if (_maxElectionTimeout <= 2 * _minElectionTimeout) {
LOG_TOPIC(WARN, Logger::AGENCY)
<< "agency.election-timeout-max should probably be chosen longer!"
<< " " << __FILE__ << __LINE__;
}
}
void AgencyFeature::prepare() {
_agencyEndpoints.resize(static_cast<size_t>(_size));
}
void AgencyFeature::start() {
if (!isEnabled()) {
return;
}
// TODO: Port this to new options handling
std::string endpoint;
std::string port = "8529";
EndpointFeature* endpointFeature =
ApplicationServer::getFeature<EndpointFeature>("Endpoint");
auto endpoints = endpointFeature->httpEndpoints();
if (!endpoints.empty()) {
std::string const& tmp = endpoints.front();
size_t pos = tmp.find(':',10);
if (pos != std::string::npos) {
port = tmp.substr(pos + 1, tmp.size() - pos);
}
}
endpoint = std::string("tcp://localhost:" + port);
_agent.reset(new consensus::Agent(consensus::config_t(
_agentId, _minElectionTimeout, _maxElectionTimeout, endpoint,
_agencyEndpoints, _notify, _supervision, _waitForSync,
_supervisionFrequency, _compactionStepSize)));
_agent->start();
_agent->load();
}
void AgencyFeature::unprepare() {
if (!isEnabled()) {
return;
}
_agent->beginShutdown();
if (_agent != nullptr) {
int counter = 0;
while (_agent->isRunning()) {
usleep(100000);
// emit warning after 5 seconds
if (++counter == 10 * 5) {
LOG_TOPIC(WARN, Logger::AGENCY) << "waiting for agent thread to finish";
}
}
}
}
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief SCI (UART) サンプル @n
RX64M, RX71M: @n
12MHz のベースクロックを使用する @n
P07 ピンにLEDを接続する @n
SCI1 を使用する @n
RX65N (Renesas Envision kit RX65N): @n
12MHz のベースクロックを使用する @n
P70 に接続された LED を利用する @n
SCI9 を使用する @n
RX24T: @n
10MHz のベースクロックを使用する @n
P00 ピンにLEDを接続する @n
SCI1 を使用する @n
RX66T: @n
10MHz のベースクロックを使用する @n
P00 ピンにLEDを接続する @n
SCI1 を使用する @n
RX72N: (Renesas Envision kit RX72N) @n
16MHz のベースクロックを使用する @n
P40 ピンにLEDを接続する @n
SCI2 を使用する @n
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2018, 2020 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/cmt_io.hpp"
#include "common/command.hpp"
#include "common/format.hpp"
#include "common/input.hpp"
namespace {
#if defined(SIG_RX71M)
typedef device::system_io<12'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
typedef device::SCI1 SCI_CH;
static const char* system_str_ = { "RX71M" };
#elif defined(SIG_RX64M)
typedef device::system_io<12'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
typedef device::SCI1 SCI_CH;
static const char* system_str_ = { "RX64M" };
#elif defined(SIG_RX65N)
typedef device::system_io<12'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
typedef device::SCI9 SCI_CH;
static const char* system_str_ = { "RX65N" };
#elif defined(SIG_RX24T)
typedef device::system_io<10'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
typedef device::SCI1 SCI_CH;
static const char* system_str_ = { "RX24T" };
#elif defined(SIG_RX66T)
typedef device::system_io<10'000'000, 160'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
typedef device::SCI1 SCI_CH;
static const char* system_str_ = { "RX66T" };
#elif defined(SIG_RX72N)
typedef device::system_io<16'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT4, device::bitpos::B0> LED;
typedef device::SCI2 SCI_CH;
static const char* system_str_ = { "RX72N" };
#endif
typedef utils::fixed_fifo<char, 512> RXB; // RX (RECV) バッファの定義
typedef utils::fixed_fifo<char, 256> TXB; // TX (SEND) バッファの定義
typedef device::sci_io<SCI_CH, RXB, TXB> SCI;
// SCI ポートの第二候補を選択する場合
// typedef device::sci_io<SCI_CH, RXB, TXB, device::port_map::option::SECOND> SCI;
SCI sci_;
typedef device::cmt_io<device::CMT0> CMT;
CMT cmt_;
typedef utils::command<256> CMD;
CMD cmd_;
}
extern "C" {
// syscalls.c から呼ばれる、標準出力(stdout, stderr)
void sci_putch(char ch)
{
sci_.putch(ch);
}
void sci_puts(const char* str)
{
sci_.puts(str);
}
// syscalls.c から呼ばれる、標準入力(stdin)
char sci_getch(void)
{
return sci_.getch();
}
uint16_t sci_length()
{
return sci_.recv_length();
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
SYSTEM_IO::setup_system_clock();
{ // タイマー設定(100Hz)
uint8_t intr = 4;
cmt_.start(100, intr);
}
{ // SCI の開始
uint8_t intr = 2; // 割り込みレベル
uint32_t baud = 115200; // ボーレート
sci_.start(baud, intr);
}
auto clk = F_ICLK / 1000000;
utils::format("Start SCI (UART) sample for '%s' %d[MHz]\n") % system_str_ % clk;
LED::DIR = 1;
LED::P = 0;
{
utils::format("SCI Baud rate (set): %d\n") % sci_.get_baud_rate();
float rate = 1.0f - static_cast<float>(sci_.get_baud_rate()) / sci_.get_baud_rate(true);
rate *= 100.0f;
utils::format("SCI Baud rate (real): %d (%3.2f [%%])\n") % sci_.get_baud_rate(true) % rate;
utils::format("CMT rate: %d [Hz]\n") % cmt_.get_rate();
}
cmd_.set_prompt("# ");
uint8_t cnt = 0;
while(1) {
cmt_.sync();
if(cmd_.service()) {
uint32_t cmdn = cmd_.get_words();
uint32_t n = 0;
while(n < cmdn) {
char tmp[256];
if(cmd_.get_word(n, tmp, sizeof(tmp))) {
utils::format("Param%d: '%s'\n") % n % tmp;
}
++n;
}
}
++cnt;
if(cnt >= 50) {
cnt = 0;
}
if(cnt < 25) {
LED::P = 0;
} else {
LED::P = 1;
}
}
}
<commit_msg>Update: cleanup<commit_after>//=====================================================================//
/*! @file
@brief SCI (UART) サンプル @n
RX64M, RX71M: @n
12MHz のベースクロックを使用する @n
P07 ピンにLEDを接続する @n
SCI1 を使用する @n
RX65N (Renesas Envision kit RX65N): @n
12MHz のベースクロックを使用する @n
P70 に接続された LED を利用する @n
SCI9 を使用する @n
RX24T: @n
10MHz のベースクロックを使用する @n
P00 ピンにLEDを接続する @n
SCI1 を使用する @n
RX66T: @n
10MHz のベースクロックを使用する @n
P00 ピンにLEDを接続する @n
SCI1 を使用する @n
RX72N: (Renesas Envision kit RX72N) @n
16MHz のベースクロックを使用する @n
P40 ピンにLEDを接続する @n
SCI2 を使用する @n
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2018, 2020 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/cmt_io.hpp"
#include "common/command.hpp"
#include "common/format.hpp"
#include "common/input.hpp"
namespace {
#if defined(SIG_RX71M)
typedef device::system_io<12'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
typedef device::SCI1 SCI_CH;
static const char* system_str_ = { "RX71M" };
#elif defined(SIG_RX64M)
typedef device::system_io<12'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
typedef device::SCI1 SCI_CH;
static const char* system_str_ = { "RX64M" };
#elif defined(SIG_RX65N)
typedef device::system_io<12'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
typedef device::SCI9 SCI_CH;
static const char* system_str_ = { "RX65N" };
#elif defined(SIG_RX24T)
typedef device::system_io<10'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
typedef device::SCI1 SCI_CH;
static const char* system_str_ = { "RX24T" };
#elif defined(SIG_RX66T)
typedef device::system_io<10'000'000, 160'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
typedef device::SCI1 SCI_CH;
static const char* system_str_ = { "RX66T" };
#elif defined(SIG_RX72N)
typedef device::system_io<16'000'000> SYSTEM_IO;
typedef device::PORT<device::PORT4, device::bitpos::B0> LED;
typedef device::SCI2 SCI_CH;
static const char* system_str_ = { "RX72N" };
#endif
typedef utils::fixed_fifo<char, 512> RXB; // RX (RECV) バッファの定義
typedef utils::fixed_fifo<char, 256> TXB; // TX (SEND) バッファの定義
typedef device::sci_io<SCI_CH, RXB, TXB> SCI;
// SCI ポートの第二候補を選択する場合
// typedef device::sci_io<SCI_CH, RXB, TXB, device::port_map::option::SECOND> SCI;
SCI sci_;
typedef device::cmt_io<device::CMT0> CMT;
CMT cmt_;
typedef utils::command<256> CMD;
CMD cmd_;
}
extern "C" {
// syscalls.c から呼ばれる、標準出力(stdout, stderr)
void sci_putch(char ch)
{
sci_.putch(ch);
}
void sci_puts(const char* str)
{
sci_.puts(str);
}
// syscalls.c から呼ばれる、標準入力(stdin)
char sci_getch(void)
{
return sci_.getch();
}
uint16_t sci_length()
{
return sci_.recv_length();
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
SYSTEM_IO::setup_system_clock();
{ // タイマー設定(100Hz)
uint8_t intr = 4;
cmt_.start(100, intr);
}
{ // SCI の開始
uint8_t intr = 2; // 割り込みレベル
uint32_t baud = 115200; // ボーレート
sci_.start(baud, intr);
}
auto clk = F_ICLK / 1000000;
utils::format("Start SCI (UART) sample for '%s' %d[MHz]\n") % system_str_ % clk;
LED::DIR = 1;
LED::P = 0;
{
utils::format("SCI Baud rate (set): %d\n") % sci_.get_baud_rate();
float rate = 1.0f - static_cast<float>(sci_.get_baud_rate()) / sci_.get_baud_rate(true);
rate *= 100.0f;
utils::format("SCI Baud rate (real): %d (%3.2f [%%])\n") % sci_.get_baud_rate(true) % rate;
utils::format("CMT rate (set): %d [Hz]\n") % cmt_.get_rate();
rate = 1.0f - static_cast<float>(cmt_.get_rate()) / cmt_.get_rate(true);
rate *= 100.0f;
utils::format("CMT rate (real): %d [Hz] (%3.2f [%%])\n") % cmt_.get_rate(true) % rate;
}
cmd_.set_prompt("# ");
uint8_t cnt = 0;
while(1) {
cmt_.sync();
if(cmd_.service()) {
uint32_t cmdn = cmd_.get_words();
uint32_t n = 0;
while(n < cmdn) {
char tmp[256];
if(cmd_.get_word(n, tmp, sizeof(tmp))) {
utils::format("Param%d: '%s'\n") % n % tmp;
}
++n;
}
}
++cnt;
if(cnt >= 50) {
cnt = 0;
}
if(cnt < 25) {
LED::P = 0;
} else {
LED::P = 1;
}
}
}
<|endoftext|> |
<commit_before><commit_msg>Maintain center of rotation for compound objects.<commit_after><|endoftext|> |
<commit_before>#include <stdio.h>
#include <cmath>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <assert.h>
#include "common/util.h"
#include "common/swaglog.h"
#include "common/visionimg.h"
#include "ui.hpp"
#include "paint.hpp"
int write_param_float(float param, const char* param_name, bool persistent_param) {
char s[16];
int size = snprintf(s, sizeof(s), "%f", param);
return Params(persistent_param).write_db_value(param_name, s, size < sizeof(s) ? size : sizeof(s));
}
static void ui_init_vision(UIState *s) {
// Invisible until we receive a calibration message.
s->scene.world_objects_visible = false;
for (int i = 0; i < s->vipc_client->num_buffers; i++) {
s->texture[i].reset(new EGLImageTexture(&s->vipc_client->buffers[i]));
glBindTexture(GL_TEXTURE_2D, s->texture[i]->frame_tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// BGR
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
}
assert(glGetError() == GL_NO_ERROR);
}
void ui_init(UIState *s) {
s->sm = new SubMaster({"modelV2", "controlsState", "uiLayoutState", "liveCalibration", "radarState", "thermal", "frame",
"health", "carParams", "driverState", "dMonitoringState", "sensorEvents"});
s->started = false;
s->status = STATUS_OFFROAD;
s->fb = std::make_unique<FrameBuffer>("ui", 0, true, &s->fb_w, &s->fb_h);
ui_nvg_init(s);
s->last_frame = nullptr;
s->vipc_client_rear = new VisionIpcClient("camerad", VISION_STREAM_RGB_BACK, true);
s->vipc_client_front = new VisionIpcClient("camerad", VISION_STREAM_RGB_FRONT, true);
s->vipc_client = s->vipc_client_rear;
}
static int get_path_length_idx(const cereal::ModelDataV2::XYZTData::Reader &line, const float path_height) {
const auto line_x = line.getX();
int max_idx = 0;
for (int i = 0; i < TRAJECTORY_SIZE && line_x[i] < path_height; ++i) {
max_idx = i;
}
return max_idx;
}
static void update_lead(UIState *s, const cereal::RadarState::Reader &radar_state,
const cereal::ModelDataV2::XYZTData::Reader &line, int idx) {
auto &lead_data = s->scene.lead_data[idx];
lead_data = (idx == 0) ? radar_state.getLeadOne() : radar_state.getLeadTwo();
if (lead_data.getStatus()) {
const int path_idx = get_path_length_idx(line, lead_data.getDRel());
car_space_to_full_frame(s, lead_data.getDRel(), lead_data.getYRel(), -line.getZ()[path_idx], &s->scene.lead_vertices[idx]);
}
}
template <class T>
static void update_line_data(const UIState *s, const cereal::ModelDataV2::XYZTData::Reader &line,
float y_off, float z_off, T *pvd, float max_distance) {
const auto line_x = line.getX(), line_y = line.getY(), line_z = line.getZ();
int max_idx = -1;
vertex_data *v = &pvd->v[0];
const float margin = 500.0f;
for (int i = 0; ((i < TRAJECTORY_SIZE) and (line_x[i] < fmax(MIN_DRAW_DISTANCE, max_distance))); i++) {
v += car_space_to_full_frame(s, line_x[i], -line_y[i] - y_off, -line_z[i] + z_off, v, margin);
max_idx = i;
}
for (int i = max_idx; i >= 0; i--) {
v += car_space_to_full_frame(s, line_x[i], -line_y[i] + y_off, -line_z[i] + z_off, v, margin);
}
pvd->cnt = v - pvd->v;
assert(pvd->cnt < std::size(pvd->v));
}
static void update_model(UIState *s, const cereal::ModelDataV2::Reader &model) {
UIScene &scene = s->scene;
const float max_distance = fmin(model.getPosition().getX()[TRAJECTORY_SIZE - 1], MAX_DRAW_DISTANCE);
// update lane lines
const auto lane_lines = model.getLaneLines();
const auto lane_line_probs = model.getLaneLineProbs();
for (int i = 0; i < std::size(scene.lane_line_vertices); i++) {
scene.lane_line_probs[i] = lane_line_probs[i];
update_line_data(s, lane_lines[i], 0.025 * scene.lane_line_probs[i], 1.22, &scene.lane_line_vertices[i], max_distance);
}
// update road edges
const auto road_edges = model.getRoadEdges();
const auto road_edge_stds = model.getRoadEdgeStds();
for (int i = 0; i < std::size(scene.road_edge_vertices); i++) {
scene.road_edge_stds[i] = road_edge_stds[i];
update_line_data(s, road_edges[i], 0.025, 1.22, &scene.road_edge_vertices[i], max_distance);
}
// update path
const float lead_d = scene.lead_data[0].getStatus() ? scene.lead_data[0].getDRel() * 2. : MAX_DRAW_DISTANCE;
float path_length = (lead_d > 0.) ? lead_d - fmin(lead_d * 0.35, 10.) : MAX_DRAW_DISTANCE;
path_length = fmin(path_length, max_distance);
update_line_data(s, model.getPosition(), 0.5, 0, &scene.track_vertices, path_length);
}
static void update_sockets(UIState *s) {
UIScene &scene = s->scene;
SubMaster &sm = *(s->sm);
if (sm.update(0) == 0){
return;
}
if (s->started && sm.updated("controlsState")) {
scene.controls_state = sm["controlsState"].getControlsState();
}
if (sm.updated("radarState")) {
auto radar_state = sm["radarState"].getRadarState();
const auto line = sm["modelV2"].getModelV2().getPosition();
update_lead(s, radar_state, line, 0);
update_lead(s, radar_state, line, 1);
}
if (sm.updated("liveCalibration")) {
scene.world_objects_visible = true;
auto extrinsicl = sm["liveCalibration"].getLiveCalibration().getExtrinsicMatrix();
for (int i = 0; i < 3 * 4; i++) {
scene.extrinsic_matrix.v[i] = extrinsicl[i];
}
}
if (sm.updated("modelV2")) {
update_model(s, sm["modelV2"].getModelV2());
}
if (sm.updated("uiLayoutState")) {
auto data = sm["uiLayoutState"].getUiLayoutState();
s->active_app = data.getActiveApp();
scene.sidebar_collapsed = data.getSidebarCollapsed();
}
if (sm.updated("thermal")) {
scene.thermal = sm["thermal"].getThermal();
}
if (sm.updated("health")) {
auto health = sm["health"].getHealth();
scene.hwType = health.getHwType();
s->ignition = health.getIgnitionLine() || health.getIgnitionCan();
} else if ((s->sm->frame - s->sm->rcv_frame("health")) > 5*UI_FREQ) {
scene.hwType = cereal::HealthData::HwType::UNKNOWN;
}
if (sm.updated("carParams")) {
s->longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl();
}
if (sm.updated("driverState")) {
scene.driver_state = sm["driverState"].getDriverState();
}
if (sm.updated("dMonitoringState")) {
scene.dmonitoring_state = sm["dMonitoringState"].getDMonitoringState();
scene.is_rhd = scene.dmonitoring_state.getIsRHD();
scene.frontview = scene.dmonitoring_state.getIsPreview();
} else if (scene.frontview && (sm.frame - sm.rcv_frame("dMonitoringState")) > UI_FREQ/2) {
scene.frontview = false;
}
if (sm.updated("sensorEvents")) {
for (auto sensor : sm["sensorEvents"].getSensorEvents()) {
if (sensor.which() == cereal::SensorEventData::LIGHT) {
s->light_sensor = sensor.getLight();
} else if (!s->started && sensor.which() == cereal::SensorEventData::ACCELERATION) {
s->accel_sensor = sensor.getAcceleration().getV()[2];
} else if (!s->started && sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) {
s->gyro_sensor = sensor.getGyroUncalibrated().getV()[1];
}
}
}
}
static void update_alert(UIState *s) {
if (!s->started || s->scene.frontview) return;
UIScene &scene = s->scene;
if (s->sm->updated("controlsState")) {
auto alert_sound = scene.controls_state.getAlertSound();
if (scene.alert_type.compare(scene.controls_state.getAlertType()) != 0) {
if (alert_sound == AudibleAlert::NONE) {
s->sound->stop();
} else {
s->sound->play(alert_sound);
}
}
scene.alert_text1 = scene.controls_state.getAlertText1();
scene.alert_text2 = scene.controls_state.getAlertText2();
scene.alert_size = scene.controls_state.getAlertSize();
scene.alert_type = scene.controls_state.getAlertType();
scene.alert_blinking_rate = scene.controls_state.getAlertBlinkingRate();
auto alert_status = scene.controls_state.getAlertStatus();
if (alert_status == cereal::ControlsState::AlertStatus::USER_PROMPT) {
s->status = STATUS_WARNING;
} else if (alert_status == cereal::ControlsState::AlertStatus::CRITICAL) {
s->status = STATUS_ALERT;
} else {
s->status = scene.controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED;
}
}
// Handle controls timeout
if ((s->sm->frame - s->started_frame) > 10 * UI_FREQ) {
const uint64_t cs_frame = s->sm->rcv_frame("controlsState");
if (cs_frame < s->started_frame) {
// car is started, but controlsState hasn't been seen at all
s->scene.alert_text1 = "openpilot Unavailable";
s->scene.alert_text2 = "Waiting for controls to start";
s->scene.alert_size = cereal::ControlsState::AlertSize::MID;
} else if ((s->sm->frame - cs_frame) > 5 * UI_FREQ) {
// car is started, but controls is lagging or died
if (s->scene.alert_text2 != "Controls Unresponsive") {
s->sound->play(AudibleAlert::CHIME_WARNING_REPEAT);
LOGE("Controls unresponsive");
}
s->scene.alert_text1 = "TAKE CONTROL IMMEDIATELY";
s->scene.alert_text2 = "Controls Unresponsive";
s->scene.alert_size = cereal::ControlsState::AlertSize::FULL;
s->status = STATUS_ALERT;
}
}
}
static void update_params(UIState *s) {
const uint64_t frame = s->sm->frame;
if (frame % (5*UI_FREQ) == 0) {
read_param(&s->is_metric, "IsMetric");
} else if (frame % (6*UI_FREQ) == 0) {
s->scene.athenaStatus = NET_DISCONNECTED;
uint64_t last_ping = 0;
if (read_param(&last_ping, "LastAthenaPingTime") == 0) {
s->scene.athenaStatus = nanos_since_boot() - last_ping < 70e9 ? NET_CONNECTED : NET_ERROR;
}
}
}
static void update_vision(UIState *s) {
if (!s->vipc_client->connected && s->started) {
s->vipc_client = s->scene.frontview ? s->vipc_client_front : s->vipc_client_rear;
if (s->vipc_client->connect(false)){
ui_init_vision(s);
}
}
if (s->vipc_client->connected){
VisionBuf * buf = s->vipc_client->recv();
if (buf != nullptr){
s->last_frame = buf;
}
}
}
void ui_update(UIState *s) {
update_params(s);
update_sockets(s);
update_alert(s);
s->started = s->scene.thermal.getStarted() || s->scene.frontview;
update_vision(s);
// Handle onroad/offroad transition
if (!s->started && s->status != STATUS_OFFROAD) {
s->status = STATUS_OFFROAD;
s->active_app = cereal::UiLayoutState::App::HOME;
s->scene.sidebar_collapsed = false;
s->sound->stop();
s->vipc_client->connected = false;
} else if (s->started && s->status == STATUS_OFFROAD) {
s->status = STATUS_DISENGAGED;
s->started_frame = s->sm->frame;
s->active_app = cereal::UiLayoutState::App::NONE;
s->scene.sidebar_collapsed = true;
s->scene.alert_size = cereal::ControlsState::AlertSize::NONE;
}
}
<commit_msg>UI: function update_status (#19679)<commit_after>#include <stdio.h>
#include <cmath>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <assert.h>
#include "common/util.h"
#include "common/swaglog.h"
#include "common/visionimg.h"
#include "ui.hpp"
#include "paint.hpp"
int write_param_float(float param, const char* param_name, bool persistent_param) {
char s[16];
int size = snprintf(s, sizeof(s), "%f", param);
return Params(persistent_param).write_db_value(param_name, s, size < sizeof(s) ? size : sizeof(s));
}
static void ui_init_vision(UIState *s) {
// Invisible until we receive a calibration message.
s->scene.world_objects_visible = false;
for (int i = 0; i < s->vipc_client->num_buffers; i++) {
s->texture[i].reset(new EGLImageTexture(&s->vipc_client->buffers[i]));
glBindTexture(GL_TEXTURE_2D, s->texture[i]->frame_tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// BGR
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
}
assert(glGetError() == GL_NO_ERROR);
}
void ui_init(UIState *s) {
s->sm = new SubMaster({"modelV2", "controlsState", "uiLayoutState", "liveCalibration", "radarState", "thermal", "frame",
"health", "carParams", "driverState", "dMonitoringState", "sensorEvents"});
s->started = false;
s->status = STATUS_OFFROAD;
s->fb = std::make_unique<FrameBuffer>("ui", 0, true, &s->fb_w, &s->fb_h);
ui_nvg_init(s);
s->last_frame = nullptr;
s->vipc_client_rear = new VisionIpcClient("camerad", VISION_STREAM_RGB_BACK, true);
s->vipc_client_front = new VisionIpcClient("camerad", VISION_STREAM_RGB_FRONT, true);
s->vipc_client = s->vipc_client_rear;
}
static int get_path_length_idx(const cereal::ModelDataV2::XYZTData::Reader &line, const float path_height) {
const auto line_x = line.getX();
int max_idx = 0;
for (int i = 0; i < TRAJECTORY_SIZE && line_x[i] < path_height; ++i) {
max_idx = i;
}
return max_idx;
}
static void update_lead(UIState *s, const cereal::RadarState::Reader &radar_state,
const cereal::ModelDataV2::XYZTData::Reader &line, int idx) {
auto &lead_data = s->scene.lead_data[idx];
lead_data = (idx == 0) ? radar_state.getLeadOne() : radar_state.getLeadTwo();
if (lead_data.getStatus()) {
const int path_idx = get_path_length_idx(line, lead_data.getDRel());
car_space_to_full_frame(s, lead_data.getDRel(), lead_data.getYRel(), -line.getZ()[path_idx], &s->scene.lead_vertices[idx]);
}
}
template <class T>
static void update_line_data(const UIState *s, const cereal::ModelDataV2::XYZTData::Reader &line,
float y_off, float z_off, T *pvd, float max_distance) {
const auto line_x = line.getX(), line_y = line.getY(), line_z = line.getZ();
int max_idx = -1;
vertex_data *v = &pvd->v[0];
const float margin = 500.0f;
for (int i = 0; ((i < TRAJECTORY_SIZE) and (line_x[i] < fmax(MIN_DRAW_DISTANCE, max_distance))); i++) {
v += car_space_to_full_frame(s, line_x[i], -line_y[i] - y_off, -line_z[i] + z_off, v, margin);
max_idx = i;
}
for (int i = max_idx; i >= 0; i--) {
v += car_space_to_full_frame(s, line_x[i], -line_y[i] + y_off, -line_z[i] + z_off, v, margin);
}
pvd->cnt = v - pvd->v;
assert(pvd->cnt < std::size(pvd->v));
}
static void update_model(UIState *s, const cereal::ModelDataV2::Reader &model) {
UIScene &scene = s->scene;
const float max_distance = fmin(model.getPosition().getX()[TRAJECTORY_SIZE - 1], MAX_DRAW_DISTANCE);
// update lane lines
const auto lane_lines = model.getLaneLines();
const auto lane_line_probs = model.getLaneLineProbs();
for (int i = 0; i < std::size(scene.lane_line_vertices); i++) {
scene.lane_line_probs[i] = lane_line_probs[i];
update_line_data(s, lane_lines[i], 0.025 * scene.lane_line_probs[i], 1.22, &scene.lane_line_vertices[i], max_distance);
}
// update road edges
const auto road_edges = model.getRoadEdges();
const auto road_edge_stds = model.getRoadEdgeStds();
for (int i = 0; i < std::size(scene.road_edge_vertices); i++) {
scene.road_edge_stds[i] = road_edge_stds[i];
update_line_data(s, road_edges[i], 0.025, 1.22, &scene.road_edge_vertices[i], max_distance);
}
// update path
const float lead_d = scene.lead_data[0].getStatus() ? scene.lead_data[0].getDRel() * 2. : MAX_DRAW_DISTANCE;
float path_length = (lead_d > 0.) ? lead_d - fmin(lead_d * 0.35, 10.) : MAX_DRAW_DISTANCE;
path_length = fmin(path_length, max_distance);
update_line_data(s, model.getPosition(), 0.5, 0, &scene.track_vertices, path_length);
}
static void update_sockets(UIState *s) {
SubMaster &sm = *(s->sm);
if (sm.update(0) == 0) return;
UIScene &scene = s->scene;
if (s->started && sm.updated("controlsState")) {
scene.controls_state = sm["controlsState"].getControlsState();
}
if (sm.updated("radarState")) {
auto radar_state = sm["radarState"].getRadarState();
const auto line = sm["modelV2"].getModelV2().getPosition();
update_lead(s, radar_state, line, 0);
update_lead(s, radar_state, line, 1);
}
if (sm.updated("liveCalibration")) {
scene.world_objects_visible = true;
auto extrinsicl = sm["liveCalibration"].getLiveCalibration().getExtrinsicMatrix();
for (int i = 0; i < 3 * 4; i++) {
scene.extrinsic_matrix.v[i] = extrinsicl[i];
}
}
if (sm.updated("modelV2")) {
update_model(s, sm["modelV2"].getModelV2());
}
if (sm.updated("uiLayoutState")) {
auto data = sm["uiLayoutState"].getUiLayoutState();
s->active_app = data.getActiveApp();
scene.sidebar_collapsed = data.getSidebarCollapsed();
}
if (sm.updated("thermal")) {
scene.thermal = sm["thermal"].getThermal();
}
if (sm.updated("health")) {
auto health = sm["health"].getHealth();
scene.hwType = health.getHwType();
s->ignition = health.getIgnitionLine() || health.getIgnitionCan();
} else if ((s->sm->frame - s->sm->rcv_frame("health")) > 5*UI_FREQ) {
scene.hwType = cereal::HealthData::HwType::UNKNOWN;
}
if (sm.updated("carParams")) {
s->longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl();
}
if (sm.updated("driverState")) {
scene.driver_state = sm["driverState"].getDriverState();
}
if (sm.updated("dMonitoringState")) {
scene.dmonitoring_state = sm["dMonitoringState"].getDMonitoringState();
scene.is_rhd = scene.dmonitoring_state.getIsRHD();
scene.frontview = scene.dmonitoring_state.getIsPreview();
} else if (scene.frontview && (sm.frame - sm.rcv_frame("dMonitoringState")) > UI_FREQ/2) {
scene.frontview = false;
}
if (sm.updated("sensorEvents")) {
for (auto sensor : sm["sensorEvents"].getSensorEvents()) {
if (sensor.which() == cereal::SensorEventData::LIGHT) {
s->light_sensor = sensor.getLight();
} else if (!s->started && sensor.which() == cereal::SensorEventData::ACCELERATION) {
s->accel_sensor = sensor.getAcceleration().getV()[2];
} else if (!s->started && sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) {
s->gyro_sensor = sensor.getGyroUncalibrated().getV()[1];
}
}
}
}
static void update_alert(UIState *s) {
if (!s->started || s->scene.frontview) return;
UIScene &scene = s->scene;
if (s->sm->updated("controlsState")) {
auto alert_sound = scene.controls_state.getAlertSound();
if (scene.alert_type.compare(scene.controls_state.getAlertType()) != 0) {
if (alert_sound == AudibleAlert::NONE) {
s->sound->stop();
} else {
s->sound->play(alert_sound);
}
}
scene.alert_text1 = scene.controls_state.getAlertText1();
scene.alert_text2 = scene.controls_state.getAlertText2();
scene.alert_size = scene.controls_state.getAlertSize();
scene.alert_type = scene.controls_state.getAlertType();
scene.alert_blinking_rate = scene.controls_state.getAlertBlinkingRate();
}
// Handle controls timeout
if ((s->sm->frame - s->started_frame) > 10 * UI_FREQ) {
const uint64_t cs_frame = s->sm->rcv_frame("controlsState");
if (cs_frame < s->started_frame) {
// car is started, but controlsState hasn't been seen at all
s->scene.alert_text1 = "openpilot Unavailable";
s->scene.alert_text2 = "Waiting for controls to start";
s->scene.alert_size = cereal::ControlsState::AlertSize::MID;
} else if ((s->sm->frame - cs_frame) > 5 * UI_FREQ) {
// car is started, but controls is lagging or died
if (s->scene.alert_text2 != "Controls Unresponsive") {
s->sound->play(AudibleAlert::CHIME_WARNING_REPEAT);
LOGE("Controls unresponsive");
}
s->scene.alert_text1 = "TAKE CONTROL IMMEDIATELY";
s->scene.alert_text2 = "Controls Unresponsive";
s->scene.alert_size = cereal::ControlsState::AlertSize::FULL;
s->status = STATUS_ALERT;
}
}
}
static void update_params(UIState *s) {
const uint64_t frame = s->sm->frame;
if (frame % (5*UI_FREQ) == 0) {
read_param(&s->is_metric, "IsMetric");
} else if (frame % (6*UI_FREQ) == 0) {
s->scene.athenaStatus = NET_DISCONNECTED;
uint64_t last_ping = 0;
if (read_param(&last_ping, "LastAthenaPingTime") == 0) {
s->scene.athenaStatus = nanos_since_boot() - last_ping < 70e9 ? NET_CONNECTED : NET_ERROR;
}
}
}
static void update_vision(UIState *s) {
if (!s->vipc_client->connected && s->started) {
s->vipc_client = s->scene.frontview ? s->vipc_client_front : s->vipc_client_rear;
if (s->vipc_client->connect(false)){
ui_init_vision(s);
}
}
if (s->vipc_client->connected){
VisionBuf * buf = s->vipc_client->recv();
if (buf != nullptr){
s->last_frame = buf;
}
}
}
static void update_status(UIState *s) {
s->started = s->scene.thermal.getStarted() || s->scene.frontview;
if (s->started && s->sm->updated("controlsState")) {
auto alert_status = s->scene.controls_state.getAlertStatus();
if (alert_status == cereal::ControlsState::AlertStatus::USER_PROMPT) {
s->status = STATUS_WARNING;
} else if (alert_status == cereal::ControlsState::AlertStatus::CRITICAL) {
s->status = STATUS_ALERT;
} else {
s->status = s->scene.controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED;
}
}
// Handle onroad/offroad transition
if (!s->started && s->status != STATUS_OFFROAD) {
s->status = STATUS_OFFROAD;
s->active_app = cereal::UiLayoutState::App::HOME;
s->scene.sidebar_collapsed = false;
s->sound->stop();
s->vipc_client->connected = false;
} else if (s->started && s->status == STATUS_OFFROAD) {
s->status = STATUS_DISENGAGED;
s->started_frame = s->sm->frame;
s->active_app = cereal::UiLayoutState::App::NONE;
s->scene.sidebar_collapsed = true;
s->scene.alert_size = cereal::ControlsState::AlertSize::NONE;
}
}
void ui_update(UIState *s) {
update_params(s);
update_sockets(s);
update_alert(s);
update_status(s);
update_vision(s);
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2013 - 2015, Göteborg Bit Factory.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <test.h>
#include <Dates.h>
#include <Context.h>
Context context;
////////////////////////////////////////////////////////////////////////////////
void testInit (UnitTest& t, const std::string& value, Variant& var)
{
try
{
namedDates (value, var);
t.pass (value + " --> valid");
}
catch (const std::string& e)
{
t.fail (value + " --> valid");
t.diag (e);
}
catch (...)
{
t.fail (value + " --> valid");
}
}
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char** argv)
{
UnitTest t (91);
Variant sunday; testInit (t, "sunday", sunday);
Variant monday; testInit (t, "monday", monday);
Variant tuesday; testInit (t, "tuesday", tuesday);
Variant wednesday; testInit (t, "wednesday", wednesday);
Variant thursday; testInit (t, "thursday", thursday);
Variant friday; testInit (t, "friday", friday);
Variant saturday; testInit (t, "saturday", saturday);
Variant sun; testInit (t, "sun", sun);
Variant mon; testInit (t, "mon", mon);
Variant tue; testInit (t, "tue", tue);
Variant wed; testInit (t, "wed", wed);
Variant thu; testInit (t, "thu", thu);
Variant fri; testInit (t, "fri", fri);
Variant sat; testInit (t, "sat", sat);
t.ok (sunday == sun, "sunday == sun");
t.ok (monday == mon, "monday == mon");
t.ok (tuesday == tue, "tuesday == tue");
t.ok (wednesday == wed, "wednesday == wed");
t.ok (thursday == thu, "thursday == thu");
t.ok (friday == fri, "friday == fri");
t.ok (saturday == sat, "saturday == sat");
Variant january; testInit (t, "january", january);
Variant february; testInit (t, "february", february);
Variant march; testInit (t, "march", march);
Variant april; testInit (t, "april", april);
Variant may; testInit (t, "may", may);
Variant june; testInit (t, "june", june);
Variant july; testInit (t, "july", july);
Variant august; testInit (t, "august", august);
Variant september; testInit (t, "september", september);
Variant october; testInit (t, "october", october);
Variant november; testInit (t, "november", november);
Variant december; testInit (t, "december", december);
Variant jan; testInit (t, "jan", jan);
Variant feb; testInit (t, "feb", feb);
Variant mar; testInit (t, "mar", mar);
Variant apr; testInit (t, "apr", apr);
Variant jun; testInit (t, "jun", jun);
Variant jul; testInit (t, "jul", jul);
Variant aug; testInit (t, "aug", aug);
Variant sep; testInit (t, "sep", sep);
Variant oct; testInit (t, "oct", oct);
Variant nov; testInit (t, "nov", nov);
Variant dec; testInit (t, "dec", dec);
t.ok (january == jan, "january == jan");
t.ok (february == feb, "february == feb");
t.ok (march == mar, "march == mar");
t.ok (april == apr, "april == apr");
// May has only three letters.
t.ok (june == jun, "june == jun");
t.ok (july == jul, "july == jul");
t.ok (august == aug, "august == aug");
t.ok (september == sep, "september == sep");
t.ok (october == oct, "october == oct");
t.ok (november == nov, "november == nov");
t.ok (december == dec, "december == dec");
// Simply instantiate these for now. Test later.
Variant now; testInit (t, "now", now);
Variant today; testInit (t, "today", today);
Variant sod; testInit (t, "sod", sod);
Variant yesterday; testInit (t, "yesterday", yesterday);
Variant tomorrow; testInit (t, "tomorrow", tomorrow);
Variant eod; testInit (t, "eod", eod);
Variant soy; testInit (t, "soy", soy);
Variant eoy; testInit (t, "eoy", eoy);
Variant socm; testInit (t, "socm", socm);
Variant eocm; testInit (t, "eocm", eocm);
Variant som; testInit (t, "som", som);
Variant eom; testInit (t, "eom", eom);
Variant later; testInit (t, "later", later);
Variant someday; testInit (t, "someday", someday);
Variant easter; testInit (t, "easter", easter);
Variant eastermonday; testInit (t, "eastermonday", eastermonday);
Variant ascension; testInit (t, "ascension", ascension);
Variant pentecost; testInit (t, "pentecost", pentecost);
Variant goodfriday; testInit (t, "goodfriday", goodfriday);
Variant pi; testInit (t, "pi", pi);
Variant var_true; testInit (t, "true", var_true);
Variant var_false; testInit (t, "false", var_false);
Variant midsommar; testInit (t, "midsommar", midsommar);
Variant midsommarafton; testInit (t, "midsommarafton", midsommarafton);
t.ok (now >= today, "now >= today");
t.ok (sod == tomorrow, "sod == tomorrow");
t.ok (sod > eod, "sod > eod");
t.ok (yesterday < today, "yesterday < today");
t.ok (today < tomorrow, "today < tomorrow");
t.ok (socm < eocm, "socm < eocm");
t.ok (now < later, "now < later");
t.ok (now < someday, "now < someday");
t.ok (goodfriday < easter, "goodfriday < easter");
t.ok (easter < eastermonday, "easter < eastermonday");
t.ok (easter < midsommarafton, "easter < midsommarafton");
t.ok (midsommarafton < midsommar, "midsommarafton < midsommar");
return 0;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Test: Added abbreviated date tests<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2013 - 2015, Göteborg Bit Factory.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <test.h>
#include <Dates.h>
#include <Context.h>
Context context;
////////////////////////////////////////////////////////////////////////////////
void testInit (UnitTest& t, const std::string& value, Variant& var)
{
try
{
namedDates (value, var);
t.pass (value + " --> valid");
}
catch (const std::string& e)
{
t.fail (value + " --> valid");
t.diag (e);
}
catch (...)
{
t.fail (value + " --> valid");
}
}
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char** argv)
{
UnitTest t (98);
Variant sunday; testInit (t, "sunday", sunday);
Variant monday; testInit (t, "monday", monday);
Variant tuesday; testInit (t, "tuesday", tuesday);
Variant wednesday; testInit (t, "wednesday", wednesday);
Variant thursday; testInit (t, "thursday", thursday);
Variant friday; testInit (t, "friday", friday);
Variant saturday; testInit (t, "saturday", saturday);
Variant sun; testInit (t, "sun", sun);
Variant mon; testInit (t, "mon", mon);
Variant tue; testInit (t, "tue", tue);
Variant wed; testInit (t, "wed", wed);
Variant thu; testInit (t, "thu", thu);
Variant fri; testInit (t, "fri", fri);
Variant sat; testInit (t, "sat", sat);
t.ok (sunday == sun, "sunday == sun");
t.ok (monday == mon, "monday == mon");
t.ok (tuesday == tue, "tuesday == tue");
t.ok (wednesday == wed, "wednesday == wed");
t.ok (thursday == thu, "thursday == thu");
t.ok (friday == fri, "friday == fri");
t.ok (saturday == sat, "saturday == sat");
Variant january; testInit (t, "january", january);
Variant february; testInit (t, "february", february);
Variant march; testInit (t, "march", march);
Variant april; testInit (t, "april", april);
Variant may; testInit (t, "may", may);
Variant june; testInit (t, "june", june);
Variant july; testInit (t, "july", july);
Variant august; testInit (t, "august", august);
Variant september; testInit (t, "september", september);
Variant october; testInit (t, "october", october);
Variant november; testInit (t, "november", november);
Variant december; testInit (t, "december", december);
Variant jan; testInit (t, "jan", jan);
Variant feb; testInit (t, "feb", feb);
Variant mar; testInit (t, "mar", mar);
Variant apr; testInit (t, "apr", apr);
Variant jun; testInit (t, "jun", jun);
Variant jul; testInit (t, "jul", jul);
Variant aug; testInit (t, "aug", aug);
Variant sep; testInit (t, "sep", sep);
Variant oct; testInit (t, "oct", oct);
Variant nov; testInit (t, "nov", nov);
Variant dec; testInit (t, "dec", dec);
t.ok (january == jan, "january == jan");
t.ok (february == feb, "february == feb");
t.ok (march == mar, "march == mar");
t.ok (april == apr, "april == apr");
// May has only three letters.
t.ok (june == jun, "june == jun");
t.ok (july == jul, "july == jul");
t.ok (august == aug, "august == aug");
t.ok (september == sep, "september == sep");
t.ok (october == oct, "october == oct");
t.ok (november == nov, "november == nov");
t.ok (december == dec, "december == dec");
// Simply instantiate these for now. Test later.
Variant now; testInit (t, "now", now);
Variant today; testInit (t, "today", today);
Variant sod; testInit (t, "sod", sod);
Variant yesterday; testInit (t, "yesterday", yesterday);
Variant tomorrow; testInit (t, "tomorrow", tomorrow);
Variant eod; testInit (t, "eod", eod);
Variant soy; testInit (t, "soy", soy);
Variant eoy; testInit (t, "eoy", eoy);
Variant socm; testInit (t, "socm", socm);
Variant eocm; testInit (t, "eocm", eocm);
Variant som; testInit (t, "som", som);
Variant eom; testInit (t, "eom", eom);
Variant later; testInit (t, "later", later);
Variant someday; testInit (t, "someday", someday);
Variant easter; testInit (t, "easter", easter);
Variant eastermonday; testInit (t, "eastermonday", eastermonday);
Variant ascension; testInit (t, "ascension", ascension);
Variant pentecost; testInit (t, "pentecost", pentecost);
Variant goodfriday; testInit (t, "goodfriday", goodfriday);
Variant pi; testInit (t, "pi", pi);
Variant var_true; testInit (t, "true", var_true);
Variant var_false; testInit (t, "false", var_false);
Variant midsommar; testInit (t, "midsommar", midsommar);
Variant midsommarafton; testInit (t, "midsommarafton", midsommarafton);
// Check abbreviations.
// TW-1515: abbreviation.minimum does not apply to date recognition
Variant yesterday2; testInit (t, "yesterday", yesterday2);
Variant yesterday3; testInit (t, "yesterda", yesterday3);
Variant yesterday4; testInit (t, "yesterd", yesterday4);
Variant yesterday5; testInit (t, "yester", yesterday5);
Variant yesterday6; testInit (t, "yeste", yesterday6);
Variant yesterday7; testInit (t, "yest", yesterday7);
Variant yesterday8; testInit (t, "yes", yesterday8);
t.ok (now >= today, "now >= today");
t.ok (sod == tomorrow, "sod == tomorrow");
t.ok (sod > eod, "sod > eod");
t.ok (yesterday < today, "yesterday < today");
t.ok (today < tomorrow, "today < tomorrow");
t.ok (socm < eocm, "socm < eocm");
t.ok (now < later, "now < later");
t.ok (now < someday, "now < someday");
t.ok (goodfriday < easter, "goodfriday < easter");
t.ok (easter < eastermonday, "easter < eastermonday");
t.ok (easter < midsommarafton, "easter < midsommarafton");
t.ok (midsommarafton < midsommar, "midsommarafton < midsommar");
return 0;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>/*
File: LibSVL.cpp
Purpose: Compiles all code necessary for SVL.h.
Author: Andrew Willmott
*/
#define __SVL__
#ifdef VL_DEBUG
#define VL_CHECKING
#endif
#define LIBPIXEL__MATH__COMPILEGUARD
using namespace std;
#include "basics.h"
#include "constants.h"
#include "utils.h"
#include "vec4.cpp"
#include "vec.cpp"
#include "mat2.cpp"
#include "mat3.cpp"
#include "mat4.cpp"
#include "mat.cpp"
#undef LIBPIXEL__MATH__COMPILEGUARD<commit_msg>Remove unused 'using namespace'<commit_after>/*
File: LibSVL.cpp
Purpose: Compiles all code necessary for SVL.h.
Author: Andrew Willmott
*/
#define __SVL__
#ifdef VL_DEBUG
#define VL_CHECKING
#endif
#define LIBPIXEL__MATH__COMPILEGUARD
#include "basics.h"
#include "constants.h"
#include "utils.h"
#include "vec4.cpp"
#include "vec.cpp"
#include "mat2.cpp"
#include "mat3.cpp"
#include "mat4.cpp"
#include "mat.cpp"
#undef LIBPIXEL__MATH__COMPILEGUARD<|endoftext|> |
<commit_before>#include "AConfig.h"
#if(HAS_STD_2X1_THRUSTERS)
#include "Device.h"
#include "Pin.h"
#include "Thrusters2X1.h"
#include "Settings.h"
#include "Motors.h"
#include "Timer.h"
//Motors motors(9, 10, 11);
//Motors motors(6, 7, 8);
Motors motors(PORT_PIN,VERTICLE_PIN,STARBORD_PIN);
int new_p = MIDPOINT;
int new_s = MIDPOINT;
int new_v = MIDPOINT;
int p = MIDPOINT;
int v = MIDPOINT;
int s = MIDPOINT;
float trg_throttle,trg_yaw,trg_lift;
int trg_motor_power;
Timer controltime;
Timer thrusterOutput;
boolean bypasssmoothing;
#ifdef ESCPOWER_PIN
bool canPowerESCs = true;
Pin escpower("escpower", ESCPOWER_PIN, escpower.digital, escpower.out);
#else
boolean canPowerESCs = false;
#endif
int smoothAdjustedServoPosition(int target, int current){
// if the MIDPOINT is betwen the change requested in velocity we want to go to MIDPOINT first, and right away.
if (((current < MIDPOINT) && (MIDPOINT < target)) || ((target < MIDPOINT) && (MIDPOINT < current))){
return MIDPOINT;
}
// if the change is moving us closer to MIDPOINT it is a reduction of power and we can move all the way to the target
// in one command
if (abs(MIDPOINT-target) < abs(MIDPOINT-current)){
return target;
}
// else, we need to smooth out amp spikes by making a series of incrimental changes in the motors, so only move part of
// the way to the target this time.
double x = target - current;
int sign = (x>0) - (x<0);
int adjustedVal = current + sign * (min(abs(target - current), Settings::smoothingIncriment));
// skip the deadzone
if (sign<0) {
return (min(adjustedVal,Settings::deadZone_min));
} else if(sign>0){
return (max(adjustedVal,Settings::deadZone_max));
} else
return (adjustedVal);
}
void Thrusters::device_setup(){
motors.reset();
thrusterOutput.reset();
controltime.reset();
bypasssmoothing = false;
#ifdef ESCPOWER_PIN
escpower.reset();
escpower.write(1); //Turn on the ESCs
#endif
}
void Thrusters::device_loop(Command command){
if (command.cmp("mtrmod")) {
Motors::motor_positive_modifer[0] = command.args[1]/100;
Motors::motor_positive_modifer[1] = command.args[2]/100;
Motors::motor_positive_modifer[2] = command.args[3]/100;
Motors::motor_negative_modifer[0] = command.args[4]/100;
Motors::motor_negative_modifer[1] = command.args[5]/100;
Motors::motor_negative_modifer[2] = command.args[6]/100;
}
if (command.cmp("rmtrmod")) {
Serial.print(F("mtrmod:"));
Serial.print(Motors::motor_positive_modifer[0]);
Serial.print (",");
Serial.print(Motors::motor_positive_modifer[1]);
Serial.print (",");
Serial.print(Motors::motor_positive_modifer[2]);
Serial.print (",");
Serial.print(Motors::motor_negative_modifer[0]);
Serial.print (",");
Serial.print(Motors::motor_negative_modifer[1]);
Serial.print (",");
Serial.print(Motors::motor_negative_modifer[2]);
Serial.println (";");
}
if (command.cmp("go")) {
//ignore corrupt data
if (command.args[1]>999 && command.args[2] >999 && command.args[3] > 999 && command.args[1]<2001 && command.args[2]<2001 && command.args[3] < 2001) {
p = command.args[1];
v = command.args[2];
s = command.args[3];
if (command.args[4] == 1) bypasssmoothing=true;
}
}
if (command.cmp("port")) {
//ignore corrupt data
if (command.args[1]>999 && command.args[1]<2001) {
p = command.args[1];
if (command.args[2] == 1) bypasssmoothing=true;
}
}
if (command.cmp("vertical")) {
//ignore corrupt data
if (command.args[1]>999 && command.args[1]<2001) {
v = command.args[1];
if (command.args[2] == 1) bypasssmoothing=true;
}
}
if (command.cmp("starbord")) {
//ignore corrupt data
if (command.args[1]>999 && command.args[1]<2001) {
s = command.args[1];
if (command.args[2] == 1) bypasssmoothing=true;
}
}
if (command.cmp("thro") || command.cmp("yaw")){
if (command.cmp("thro")){
if (command.args[1]>=-100 && command.args[1]<=100) {
trg_throttle = command.args[1]/100.0;
}
}
if (trg_throttle>=0){
p = 1500 + 500*trg_throttle;
s = p;
} else {
p = 1500 + 250*trg_throttle;
s = p;
}
trg_motor_power = s;
if (command.cmp("yaw")) {
//ignore corrupt data
if (command.args[1]>=-100 && command.args[1]<=100) { //percent of max turn
trg_yaw = command.args[1]/100.0;
int turn = trg_yaw*250; //max range due to reverse range
int sign=0;
sign = (turn>0) - (turn<0);
if (trg_throttle >=0){
int offset = (abs(turn)+trg_motor_power)-2000;
if (offset < 0) offset = 0;
p = trg_motor_power+turn-offset;
s = trg_motor_power-turn-offset;
} else {
int offset = 1000-(trg_motor_power-abs(turn));
if (offset < 0) offset = 0;
p = trg_motor_power+turn+offset;
s = trg_motor_power-turn+offset;
}
}
}
}
if (command.cmp("lift")){
if (command.args[1]>=-100 && command.args[1]<=100) {
trg_lift = command.args[1]/100.0;
if (trg_lift>=0){
v = 1500 + 500*trg_lift;
} else {
v = 1500 + 250*trg_lift;
}
}
}
#ifdef ESCPOWER_PIN
else if (command.cmp("escp")) {
escpower.write(command.args[1]); //Turn on the ESCs
Serial.print(F("log:escpower="));
Serial.print(command.args[1]);
Serial.println(';');
}
#endif
else if (command.cmp("start")) {
motors.reset();
}
else if (command.cmp("stop")) {
motors.stop();
}
#ifdef ESCPOWER_PIN
else if ((command.cmp("mcal")) && (canPowerESCs)){
Serial.println(F("log:Motor Callibration Staring;"));
//Experimental. Add calibration code here
Serial.println(F("log:Motor Callibration Complete;"));
}
#endif
//to reduce AMP spikes, smooth large power adjustments out. This incirmentally adjusts the motors and servo
//to their new positions in increments. The incriment should eventually be adjustable from the cockpit so that
//the pilot could have more aggressive response profiles for the ROV.
if (controltime.elapsed (50)) {
if (p!=new_p || v!=new_v || s!=new_s) {
new_p = smoothAdjustedServoPosition(p,new_p);
new_v = smoothAdjustedServoPosition(v,new_v);
new_s = smoothAdjustedServoPosition(s,new_s);
if (bypasssmoothing)
{
new_p=p;
new_v=v;
new_s=s;
bypasssmoothing = false;
}
motors.go(new_p, new_v, new_s);
}
}
navdata::FTHR = map((new_p + new_s) / 2, 1000,2000,-100,100);
//The output from the motors is unique to the thruster configuration
if (thrusterOutput.elapsed(1000)){
Serial.print(F("motors:"));
Serial.print(new_p);
Serial.print(',');
Serial.print(new_v);
Serial.print(',');
Serial.print(new_s);
Serial.println(';');
Serial.print(F("mtarg:"));
Serial.print(p);
Serial.print(',');
Serial.print(v);
Serial.print(',');
Serial.print(s);
Serial.println(';');
}
}
#endif
<commit_msg>Changed list api behavior to allow full speed.<commit_after>#include "AConfig.h"
#if(HAS_STD_2X1_THRUSTERS)
#include "Device.h"
#include "Pin.h"
#include "Thrusters2X1.h"
#include "Settings.h"
#include "Motors.h"
#include "Timer.h"
//Motors motors(9, 10, 11);
//Motors motors(6, 7, 8);
Motors motors(PORT_PIN,VERTICLE_PIN,STARBORD_PIN);
int new_p = MIDPOINT;
int new_s = MIDPOINT;
int new_v = MIDPOINT;
int p = MIDPOINT;
int v = MIDPOINT;
int s = MIDPOINT;
float trg_throttle,trg_yaw,trg_lift;
int trg_motor_power;
Timer controltime;
Timer thrusterOutput;
boolean bypasssmoothing;
#ifdef ESCPOWER_PIN
bool canPowerESCs = true;
Pin escpower("escpower", ESCPOWER_PIN, escpower.digital, escpower.out);
#else
boolean canPowerESCs = false;
#endif
int smoothAdjustedServoPosition(int target, int current){
// if the MIDPOINT is betwen the change requested in velocity we want to go to MIDPOINT first, and right away.
if (((current < MIDPOINT) && (MIDPOINT < target)) || ((target < MIDPOINT) && (MIDPOINT < current))){
return MIDPOINT;
}
// if the change is moving us closer to MIDPOINT it is a reduction of power and we can move all the way to the target
// in one command
if (abs(MIDPOINT-target) < abs(MIDPOINT-current)){
return target;
}
// else, we need to smooth out amp spikes by making a series of incrimental changes in the motors, so only move part of
// the way to the target this time.
double x = target - current;
int sign = (x>0) - (x<0);
int adjustedVal = current + sign * (min(abs(target - current), Settings::smoothingIncriment));
// skip the deadzone
if (sign<0) {
return (min(adjustedVal,Settings::deadZone_min));
} else if(sign>0){
return (max(adjustedVal,Settings::deadZone_max));
} else
return (adjustedVal);
}
void Thrusters::device_setup(){
motors.reset();
thrusterOutput.reset();
controltime.reset();
bypasssmoothing = false;
#ifdef ESCPOWER_PIN
escpower.reset();
escpower.write(1); //Turn on the ESCs
#endif
}
void Thrusters::device_loop(Command command){
if (command.cmp("mtrmod")) {
Motors::motor_positive_modifer[0] = command.args[1]/100;
Motors::motor_positive_modifer[1] = command.args[2]/100;
Motors::motor_positive_modifer[2] = command.args[3]/100;
Motors::motor_negative_modifer[0] = command.args[4]/100;
Motors::motor_negative_modifer[1] = command.args[5]/100;
Motors::motor_negative_modifer[2] = command.args[6]/100;
}
if (command.cmp("rmtrmod")) {
Serial.print(F("mtrmod:"));
Serial.print(Motors::motor_positive_modifer[0]);
Serial.print (",");
Serial.print(Motors::motor_positive_modifer[1]);
Serial.print (",");
Serial.print(Motors::motor_positive_modifer[2]);
Serial.print (",");
Serial.print(Motors::motor_negative_modifer[0]);
Serial.print (",");
Serial.print(Motors::motor_negative_modifer[1]);
Serial.print (",");
Serial.print(Motors::motor_negative_modifer[2]);
Serial.println (";");
}
if (command.cmp("go")) {
//ignore corrupt data
if (command.args[1]>999 && command.args[2] >999 && command.args[3] > 999 && command.args[1]<2001 && command.args[2]<2001 && command.args[3] < 2001) {
p = command.args[1];
v = command.args[2];
s = command.args[3];
if (command.args[4] == 1) bypasssmoothing=true;
}
}
if (command.cmp("port")) {
//ignore corrupt data
if (command.args[1]>999 && command.args[1]<2001) {
p = command.args[1];
if (command.args[2] == 1) bypasssmoothing=true;
}
}
if (command.cmp("vertical")) {
//ignore corrupt data
if (command.args[1]>999 && command.args[1]<2001) {
v = command.args[1];
if (command.args[2] == 1) bypasssmoothing=true;
}
}
if (command.cmp("starbord")) {
//ignore corrupt data
if (command.args[1]>999 && command.args[1]<2001) {
s = command.args[1];
if (command.args[2] == 1) bypasssmoothing=true;
}
}
if (command.cmp("thro") || command.cmp("yaw")){
if (command.cmp("thro")){
if (command.args[1]>=-100 && command.args[1]<=100) {
trg_throttle = command.args[1]/100.0;
}
}
if (trg_throttle>=0){
p = 1500 + 500*trg_throttle;
s = p;
} else {
p = 1500 + 250*trg_throttle;
s = p;
}
trg_motor_power = s;
if (command.cmp("yaw")) {
//ignore corrupt data
if (command.args[1]>=-100 && command.args[1]<=100) { //percent of max turn
trg_yaw = command.args[1]/100.0;
int turn = trg_yaw*250; //max range due to reverse range
int sign=0;
sign = (turn>0) - (turn<0);
if (trg_throttle >=0){
int offset = (abs(turn)+trg_motor_power)-2000;
if (offset < 0) offset = 0;
p = trg_motor_power+turn-offset;
s = trg_motor_power-turn-offset;
} else {
int offset = 1000-(trg_motor_power-abs(turn));
if (offset < 0) offset = 0;
p = trg_motor_power+turn+offset;
s = trg_motor_power-turn+offset;
}
}
}
}
if (command.cmp("lift")){
if (command.args[1]>=-100 && command.args[1]<=100) {
trg_lift = command.args[1]/100.0;
v = 1500 + 500*trg_lift;
}
}
#ifdef ESCPOWER_PIN
else if (command.cmp("escp")) {
escpower.write(command.args[1]); //Turn on the ESCs
Serial.print(F("log:escpower="));
Serial.print(command.args[1]);
Serial.println(';');
}
#endif
else if (command.cmp("start")) {
motors.reset();
}
else if (command.cmp("stop")) {
motors.stop();
}
#ifdef ESCPOWER_PIN
else if ((command.cmp("mcal")) && (canPowerESCs)){
Serial.println(F("log:Motor Callibration Staring;"));
//Experimental. Add calibration code here
Serial.println(F("log:Motor Callibration Complete;"));
}
#endif
//to reduce AMP spikes, smooth large power adjustments out. This incirmentally adjusts the motors and servo
//to their new positions in increments. The incriment should eventually be adjustable from the cockpit so that
//the pilot could have more aggressive response profiles for the ROV.
if (controltime.elapsed (50)) {
if (p!=new_p || v!=new_v || s!=new_s) {
new_p = smoothAdjustedServoPosition(p,new_p);
new_v = smoothAdjustedServoPosition(v,new_v);
new_s = smoothAdjustedServoPosition(s,new_s);
if (bypasssmoothing)
{
new_p=p;
new_v=v;
new_s=s;
bypasssmoothing = false;
}
motors.go(new_p, new_v, new_s);
}
}
navdata::FTHR = map((new_p + new_s) / 2, 1000,2000,-100,100);
//The output from the motors is unique to the thruster configuration
if (thrusterOutput.elapsed(1000)){
Serial.print(F("motors:"));
Serial.print(new_p);
Serial.print(',');
Serial.print(new_v);
Serial.print(',');
Serial.print(new_s);
Serial.println(';');
Serial.print(F("mtarg:"));
Serial.print(p);
Serial.print(',');
Serial.print(v);
Serial.print(',');
Serial.print(s);
Serial.println(';');
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef FILES_HPP
#define FILES_HPP
#define NUMBER_OF_FILES 12
const char* src_file_names[NUMBER_OF_FILES] = {"../../../../images/binary/avatar.bmp",
"../../../../images/binary/cameleon.bmp",
"../../../../images/binary/frozen.bmp",
"../../../../images/binary/giraffe.bmp",
"../../../../images/binary/snow_leopard.bmp",
"../../../../images/binary/tmnt_1.bmp",
"../../../../images/binary/tmnt_2.bmp",
"../../../../images/binary/transformers.bmp",
"../../../../images/binary/tree_1.bmp",
"../../../../images/binary/tree_2.bmp",
"../../../../images/binary/tree_3.bmp",
"../../../../images/binary/zebra.bmp"};
const char* dst_file_names[NUMBER_OF_FILES] = {"../../../../images/skeletonized/avatar.bmp",
"../../../../images/skeletonized/cameleon.bmp",
"../../../../images/skeletonized/frozen.bmp",
"../../../../images/skeletonized/giraffe.bmp",
"../../../../images/skeletonized/snow_leopard.bmp",
"../../../../images/skeletonized/tmnt_1.bmp",
"../../../../images/skeletonized/tmnt_2.bmp",
"../../../../images/skeletonized/transformers.bmp",
"../../../../images/skeletonized/tree_1.bmp",
"../../../../images/skeletonized/tree_2.bmp",
"../../../../images/skeletonized/tree_3.bmp",
"../../../../images/skeletonized/zebra.bmp"};
#endif
<commit_msg>delete files.hpp. No longer needed<commit_after><|endoftext|> |
<commit_before>#include <NfcAdapter.h>
NfcAdapter::NfcAdapter(PN532Interface &interface)
{
shield = new PN532(interface);
}
NfcAdapter::~NfcAdapter(void)
{
delete shield;
}
void NfcAdapter::begin()
{
shield->begin();
uint32_t versiondata = shield->getFirmwareVersion();
if (! versiondata) {
Serial.print(F("Didn't find PN53x board"));
while (1); // halt
}
Serial.print(F("Found chip PN5")); Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print(F("Firmware ver. ")); Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
// configure board to read RFID tags
shield->SAMConfig();
}
boolean NfcAdapter::tagPresent()
{
uint8_t success;
uidLength = 0;
// TODO is cast of uidLength OK?
success = shield->readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, (uint8_t*)&uidLength);
// if (success)
// {
// Serial.println("Found an ISO14443A card");
// Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
// Serial.print(" UID Value: ");
// shield->PrintHex(uid, uidLength);
// Serial.println("");
// }
return success;
}
NfcTag NfcAdapter::read()
{
uint8_t type = guessTagType();
// TODO need an abstraction of Driver
if (type == TAG_TYPE_MIFARE_CLASSIC)
{
#ifdef NDEF_DEBUG
Serial.println(F("Reading Mifare Classic"));
#endif
MifareClassic mifareClassic = MifareClassic(*shield);
return mifareClassic.read(uid, uidLength);
}
else if (type == TAG_TYPE_2)
{
#ifdef NDEF_DEBUG
Serial.println(F("Reading Mifare Ultralight"));
#endif
MifareUltralight ultralight = MifareUltralight(*shield);
return ultralight.read(uid, uidLength);
}
else if (type = TAG_TYPE_UNKNOWN)
{
Serial.print(F("Can not determine tag type"));
//Serial.print(F("Can not determine tag type for ATQA 0x"));
//Serial.print(atqa, HEX);Serial.print(" SAK 0x");Serial.println(sak, HEX);
return NfcTag(uid, uidLength);
}
else
{
Serial.print(F("No driver for card type "));Serial.println(type);
// TODO should set type here
return NfcTag(uid, uidLength);
}
}
boolean NfcAdapter::write(NdefMessage& ndefMessage)
{
boolean success;
if (uidLength == 4)
{
MifareClassic mifareClassic = MifareClassic(*shield);
success = mifareClassic.write(ndefMessage, uid, uidLength);
}
else
{
Serial.println(F("Unsupported Tag"));
success = false;
}
return success;
}
// TODO this should return a Driver MifareClassic, MifareUltralight, Type 4, Unknown
// Guess Tag Type by looking at the ATQA and SAK values
// Need to follow spec for Card Identification. Maybe AN1303, AN1305 and ???
unsigned int NfcAdapter::guessTagType()
{
// 4 byte id - Mifare Classic
// - ATQA 0x4 && SAK 0x8
// 7 byte id
// - ATQA 0x44 && SAK 0x8 - Mifare Classic
// - ATQA 0x44 && SAK 0x0 - Mifare Ultralight NFC Forum Type 2
// - ATQA 0x344 && SAK 0x20 - NFC Forum Type 4
if (uidLength == 4)
{
return TAG_TYPE_MIFARE_CLASSIC;
}
else
{
return TAG_TYPE_2;
}
}
<commit_msg>guess tag type for write<commit_after>#include <NfcAdapter.h>
NfcAdapter::NfcAdapter(PN532Interface &interface)
{
shield = new PN532(interface);
}
NfcAdapter::~NfcAdapter(void)
{
delete shield;
}
void NfcAdapter::begin()
{
shield->begin();
uint32_t versiondata = shield->getFirmwareVersion();
if (! versiondata) {
Serial.print(F("Didn't find PN53x board"));
while (1); // halt
}
Serial.print(F("Found chip PN5")); Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print(F("Firmware ver. ")); Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
// configure board to read RFID tags
shield->SAMConfig();
}
boolean NfcAdapter::tagPresent()
{
uint8_t success;
uidLength = 0;
// TODO is cast of uidLength OK?
success = shield->readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, (uint8_t*)&uidLength);
// if (success)
// {
// Serial.println("Found an ISO14443A card");
// Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
// Serial.print(" UID Value: ");
// shield->PrintHex(uid, uidLength);
// Serial.println("");
// }
return success;
}
NfcTag NfcAdapter::read()
{
uint8_t type = guessTagType();
// TODO need an abstraction of Driver
if (type == TAG_TYPE_MIFARE_CLASSIC)
{
#ifdef NDEF_DEBUG
Serial.println(F("Reading Mifare Classic"));
#endif
MifareClassic mifareClassic = MifareClassic(*shield);
return mifareClassic.read(uid, uidLength);
}
else if (type == TAG_TYPE_2)
{
#ifdef NDEF_DEBUG
Serial.println(F("Reading Mifare Ultralight"));
#endif
MifareUltralight ultralight = MifareUltralight(*shield);
return ultralight.read(uid, uidLength);
}
else if (type = TAG_TYPE_UNKNOWN)
{
Serial.print(F("Can not determine tag type"));
//Serial.print(F("Can not determine tag type for ATQA 0x"));
//Serial.print(atqa, HEX);Serial.print(" SAK 0x");Serial.println(sak, HEX);
return NfcTag(uid, uidLength);
}
else
{
Serial.print(F("No driver for card type "));Serial.println(type);
// TODO should set type here
return NfcTag(uid, uidLength);
}
}
boolean NfcAdapter::write(NdefMessage& ndefMessage)
{
boolean success;
uint8_t type = guessTagType();
if (type == TAG_TYPE_MIFARE_CLASSIC)
{
MifareClassic mifareClassic = MifareClassic(*shield);
success = mifareClassic.write(ndefMessage, uid, uidLength);
}
else if (type == TAG_TYPE_2)
{
MifareUltralight mifareUltralight = MifareUltralight(*shield);
success = mifareUltralight.write(ndefMessage, uid, uidLength);
}
else
{
Serial.println(F("Unsupported Tag"));
success = false;
}
return success;
}
// TODO this should return a Driver MifareClassic, MifareUltralight, Type 4, Unknown
// Guess Tag Type by looking at the ATQA and SAK values
// Need to follow spec for Card Identification. Maybe AN1303, AN1305 and ???
unsigned int NfcAdapter::guessTagType()
{
// 4 byte id - Mifare Classic
// - ATQA 0x4 && SAK 0x8
// 7 byte id
// - ATQA 0x44 && SAK 0x8 - Mifare Classic
// - ATQA 0x44 && SAK 0x0 - Mifare Ultralight NFC Forum Type 2
// - ATQA 0x344 && SAK 0x20 - NFC Forum Type 4
if (uidLength == 4)
{
return TAG_TYPE_MIFARE_CLASSIC;
}
else
{
return TAG_TYPE_2;
}
}
<|endoftext|> |
<commit_before>#include "cnn/training.h"
namespace cnn {
using namespace std;
Trainer::~Trainer() {}
float Trainer::clip_gradients() {
float gscale = 1;
if (clipping_enabled) {
double gg = 0;
for (auto p : model->all_parameters_list())
gg+=p->g_squared_l2norm();
gg = sqrt(gg);
if (gg > clip_threshold) {
++clips;
gscale = clip_threshold / gg;
}
}
return gscale;
}
void SimpleSGDTrainer::update(real scale) {
const float gscale = clip_gradients();
for (auto p : model->parameters_list()) {
#if HAVE_CUDA
cerr << "implement update\n"; abort();
#else
auto reg = (*p->values) * lambda;
*p->values -= ((eta * scale * gscale) * *p->g + reg);
#endif
p->clear();
}
for (auto p : model->lookup_parameters_list()) {
for (auto i : p->non_zero_grads) {
#if HAVE_CUDA
cerr << "implement lookup update\n"; abort();
#else
auto reg = (*p->values[i]) * lambda;
*p->values[i] -= (*p->grads[i] * (eta * scale) + reg);
#endif
}
p->clear();
}
++updates;
}
#if 0
static inline Tensor& get_or_init(Tensor& x, const Tensor& t) {
#if WITH_THPP_BACKEND
if (x.ndims() == 0) {
x = Tensor(t.sizes());
x.zero();
}
return x;
#endif
#ifdef WITH_EIGEN_BACKEND
if (x.rows() == 0) {
x = t;
x.setZero();
}
return x;
#endif
#if WITH_MINERVA_BACKEND
#endif
}
void MomentumSGDTrainer::update(real scale) {
clip_gradients();
for (auto p : model->parameters_list()) {
Tensor& v = get_or_init(vp[p], p->values);
const Tensor reg = p->values * lambda;
v = momentum * v - (eta * scale) * p->g;
p->values += v;
p->values -= reg;
p->clear();
}
for (auto p : model->lookup_parameters_list()) {
unordered_map<unsigned, Tensor>& vx = vl[p];
for (auto& it : p->g) {
Tensor& v = get_or_init(vx[it.first], it.second);
const Tensor reg = p->values[it.first] * lambda;
v = momentum * v - (eta * scale) * it.second;
p->values[it.first] += v;
p->values[it.first] -= reg;
}
p->clear();
}
++updates;
}
#endif
#if 0
void RMSPropTrainer::update(real scale) {
for (auto p : params) {
Tensor& x = p->values;
Tensor& g = p->g;
Tensor& v = vp[p];
v *= decay;
v += g.cwiseProduct(g) * (1.0 - decay);
const Tensor reg = x * lambda;
x -= eta * g.cwiseQuotient((v + Tensor::Constant(v.rows(),v.cols(),eps)).cwiseSqrt());
x -= reg;
p->clear();
}
for (auto p : lookup_params) {
unordered_map<unsigned, Tensor>& vt = vl[p];
for (auto it : p->g) {
Tensor& x = p->values[it.first];
Tensor& g = it.second;
Tensor& v = vt[it.first];
if (v.rows() == 0) v = g * 0;
v *= decay;
v += g.cwiseProduct(g) * (1.0 - decay);
const Tensor reg = x * lambda;
x -= eta * g.cwiseQuotient((v + Tensor::Constant(v.rows(),v.cols(),eps)).cwiseSqrt());
x -= reg;
}
p->clear();
}
}
#endif
} // namespace cnn
<commit_msg>scale properly<commit_after>#include "cnn/training.h"
namespace cnn {
using namespace std;
Trainer::~Trainer() {}
float Trainer::clip_gradients() {
float gscale = 1;
if (clipping_enabled) {
double gg = 0;
for (auto p : model->all_parameters_list())
gg+=p->g_squared_l2norm();
gg = sqrt(gg);
if (gg > clip_threshold) {
++clips;
gscale = clip_threshold / gg;
}
}
return gscale;
}
void SimpleSGDTrainer::update(real scale) {
const float gscale = clip_gradients();
for (auto p : model->parameters_list()) {
#if HAVE_CUDA
cerr << "implement update\n"; abort();
#else
auto reg = (*p->values) * lambda;
*p->values -= ((eta * scale * gscale) * *p->g + reg);
#endif
p->clear();
}
for (auto p : model->lookup_parameters_list()) {
for (auto i : p->non_zero_grads) {
#if HAVE_CUDA
cerr << "implement lookup update\n"; abort();
#else
auto reg = (*p->values[i]) * lambda;
*p->values[i] -= (*p->grads[i] * (eta * scale * gscale) + reg);
#endif
}
p->clear();
}
++updates;
}
#if 0
static inline Tensor& get_or_init(Tensor& x, const Tensor& t) {
#if WITH_THPP_BACKEND
if (x.ndims() == 0) {
x = Tensor(t.sizes());
x.zero();
}
return x;
#endif
#ifdef WITH_EIGEN_BACKEND
if (x.rows() == 0) {
x = t;
x.setZero();
}
return x;
#endif
#if WITH_MINERVA_BACKEND
#endif
}
void MomentumSGDTrainer::update(real scale) {
clip_gradients();
for (auto p : model->parameters_list()) {
Tensor& v = get_or_init(vp[p], p->values);
const Tensor reg = p->values * lambda;
v = momentum * v - (eta * scale) * p->g;
p->values += v;
p->values -= reg;
p->clear();
}
for (auto p : model->lookup_parameters_list()) {
unordered_map<unsigned, Tensor>& vx = vl[p];
for (auto& it : p->g) {
Tensor& v = get_or_init(vx[it.first], it.second);
const Tensor reg = p->values[it.first] * lambda;
v = momentum * v - (eta * scale) * it.second;
p->values[it.first] += v;
p->values[it.first] -= reg;
}
p->clear();
}
++updates;
}
#endif
#if 0
void RMSPropTrainer::update(real scale) {
for (auto p : params) {
Tensor& x = p->values;
Tensor& g = p->g;
Tensor& v = vp[p];
v *= decay;
v += g.cwiseProduct(g) * (1.0 - decay);
const Tensor reg = x * lambda;
x -= eta * g.cwiseQuotient((v + Tensor::Constant(v.rows(),v.cols(),eps)).cwiseSqrt());
x -= reg;
p->clear();
}
for (auto p : lookup_params) {
unordered_map<unsigned, Tensor>& vt = vl[p];
for (auto it : p->g) {
Tensor& x = p->values[it.first];
Tensor& g = it.second;
Tensor& v = vt[it.first];
if (v.rows() == 0) v = g * 0;
v *= decay;
v += g.cwiseProduct(g) * (1.0 - decay);
const Tensor reg = x * lambda;
x -= eta * g.cwiseQuotient((v + Tensor::Constant(v.rows(),v.cols(),eps)).cwiseSqrt());
x -= reg;
}
p->clear();
}
}
#endif
} // namespace cnn
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2014 Ruben Nijveld, Aaron van Geffen
* See LICENSE for license.
*/
#include "../config.h"
#include "sqlite.h"
#include <sqlite3.h>
#include <stdio.h>
#include <iostream>
namespace dazeus {
namespace db {
/**
* Cleanup all prepared queries and close the connection.
*/
SQLiteDatabase::~SQLiteDatabase()
{
if (conn_) {
sqlite3_finalize(find_property);
sqlite3_finalize(remove_property);
sqlite3_finalize(update_property);
sqlite3_finalize(properties);
sqlite3_finalize(add_permission);
sqlite3_finalize(remove_permission);
sqlite3_finalize(has_permission);
int res = sqlite3_close(conn_);
assert(res == SQLITE_OK);
}
}
void SQLiteDatabase::open()
{
// Connect the lot!
int fail = sqlite3_open_v2(dbc_.filename.c_str(), &conn_,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
NULL);
if (fail) {
auto error = "Can't open database (code " + std::to_string(fail) + "): " +
sqlite3_errmsg(conn_);
throw exception(error);
}
upgradeDB();
bootstrapDB();
}
/**
* @brief Try to create a prepared statement on the SQLite3 connection.
*/
void SQLiteDatabase::tryPrepare(const std::string &stmt,
sqlite3_stmt **target) const
{
int result = sqlite3_prepare_v2(conn_, stmt.c_str(), stmt.length(), target,
NULL);
if (result != SQLITE_OK) {
throw exception(
std::string("Failed to prepare SQL statement, got an error: ") +
sqlite3_errmsg(conn_));
}
}
/**
* @brief Try to bind a parameter to a prepared statement.
*/
void SQLiteDatabase::tryBind(sqlite3_stmt *target, int param,
const std::string &value) const
{
int result = sqlite3_bind_text(target, param, value.c_str(), value.length(),
SQLITE_TRANSIENT);
if (result != SQLITE_OK) {
throw exception("Failed to bind parameter " + std::to_string(param) +
" to query with error: " + sqlite3_errmsg(conn_) +
" (errorcode " + std::to_string(result) + ")");
}
}
/**
* @brief Prepare all SQL statements used by the database layer
*/
void SQLiteDatabase::bootstrapDB()
{
tryPrepare(
"SELECT value FROM dazeus_properties "
"WHERE key = ?1 "
" AND (network = ?2 OR network = '') "
" AND (receiver = ?3 OR receiver = '') "
" AND (sender = ?4 OR sender = '') "
"ORDER BY network DESC, receiver DESC, sender DESC "
"LIMIT 1",
&find_property);
tryPrepare(
"DELETE FROM dazeus_properties "
"WHERE key = ?1 "
" AND network = ?3 AND receiver = ?4 AND sender = ?5",
&remove_property);
tryPrepare(
"INSERT OR REPLACE INTO dazeus_properties "
"(key, value, network, receiver, sender) "
"VALUES (?1, ?2, ?3, ?4, ?5) ",
&update_property);
tryPrepare(
"SELECT key FROM dazeus_properties "
"WHERE key LIKE ?1 || '%' "
" AND network = ?2 AND receiver = ?3 AND sender = ?4",
&properties);
tryPrepare(
"INSERT OR REPLACE INTO dazeus_permissions "
"(permission, network, receiver, sender) "
"VALUES (?1, ?2, ?3, ?4) ",
&add_permission);
tryPrepare(
"DELETE FROM dazeus_permissions "
"WHERE permission = ?1 "
" AND network = ?2 AND receiver = ?3 AND sender = ?4",
&remove_permission);
tryPrepare(
"SELECT * FROM dazeus_permissions "
"WHERE permission = ?1 "
" AND network = ?2 AND receiver = ?3 AND sender = ?4",
&has_permission);
}
/**
* @brief Upgrade the database to the latest version.
*/
void SQLiteDatabase::upgradeDB()
{
bool found = false;
int errc = sqlite3_exec(conn_,
"SELECT name FROM sqlite_master WHERE type = 'table' "
"AND name = 'dazeus_properties'",
[](void* found, int, char**, char**)
{
*(static_cast<bool*>(found)) = true;
return 0;
}, static_cast<void*>(&found), NULL);
if (errc != SQLITE_OK) {
throw exception(std::string("Failed to retrieve database version: ") +
sqlite3_errmsg(conn_));
}
int db_version = 0;
if (errc == SQLITE_OK) {
if (found) {
// table exists, query for latest version
errc = sqlite3_exec(conn_,
"SELECT value FROM dazeus_properties "
"WHERE key = 'dazeus_version' LIMIT 1",
[](void* dbver, int columns, char** values, char**)
{
if (columns > 0) {
*(static_cast<int*>(dbver)) = std::stoi(values[0]);
}
return 0;
}, static_cast<void*>(&db_version), NULL);
}
}
const char *upgrades[] = {
"CREATE TABLE dazeus_properties( "
"key VARCHAR(255) NOT NULL, "
"value TEXT NOT NULL, "
"network VARCHAR(255) NOT NULL, "
"receiver VARCHAR(255) NOT NULL, "
"sender VARCHAR(255) NOT NULL, "
"created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"PRIMARY KEY(key, network, receiver, sender) "
")"
,
"CREATE TABLE dazeus_permissions( "
"permission VARCHAR(255) NOT NULL, "
"network VARCHAR(255) NOT NULL, "
"receiver VARCHAR(255) NOT NULL, "
"sender VARCHAR(255) NOT NULL, "
"created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"PRIMARY KEY(permission, network, receiver, sender) "
")"
};
// run any outstanding updates
static int target_version = std::end(upgrades) - std::begin(upgrades);
if (db_version < target_version) {
std::cout << "Will now upgrade database from version " << db_version
<< " to version " << target_version << "." << std::endl;
for (int i = db_version; i < target_version; ++i) {
int result = sqlite3_exec(conn_, upgrades[i], NULL, NULL, NULL);
if (result != SQLITE_OK) {
throw exception("Could not run upgrade " + std::to_string(i) +
", got error: " + sqlite3_errmsg(conn_));
}
}
std::cout << "Upgrade completed. Will now update dazeus_version to "
<< target_version << std::endl;
errc = sqlite3_exec(conn_,
("INSERT OR REPLACE INTO dazeus_properties "
"(key, value, network, receiver, sender) "
"VALUES ('dazeus_version', '" + std::to_string(target_version) + "', "
" '', '', '') ").c_str(),
NULL, NULL, NULL);
if (errc != SQLITE_OK) {
throw exception(
"Could not set dazeus_version to latest version, got error: " +
std::string(sqlite3_errmsg(conn_)));
}
}
}
std::string SQLiteDatabase::property(const std::string &variable,
const std::string &networkScope,
const std::string &receiverScope,
const std::string &senderScope)
{
tryBind(find_property, 1, variable);
tryBind(find_property, 2, networkScope);
tryBind(find_property, 3, receiverScope);
tryBind(find_property, 4, senderScope);
int errc = sqlite3_step(find_property);
if (errc == SQLITE_ROW) {
std::string value = reinterpret_cast<const char *>(sqlite3_column_text(find_property, 0));
sqlite3_reset(find_property);
return value;
} else if (errc == SQLITE_DONE) {
// TODO: define behavior when no result is found
sqlite3_reset(find_property);
return "";
} else {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(find_property);
throw exception(msg);
}
}
void SQLiteDatabase::setProperty(const std::string &variable,
const std::string &value, const std::string &networkScope,
const std::string &receiverScope,
const std::string &senderScope)
{
sqlite3_stmt *stmt = value == "" ? remove_property : update_property;
tryBind(stmt, 1, variable);
tryBind(stmt, 2, value);
tryBind(stmt, 3, networkScope);
tryBind(stmt, 4, receiverScope);
tryBind(stmt, 5, senderScope);
int errc = sqlite3_step(stmt);
if (errc != SQLITE_OK && errc != SQLITE_DONE) {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(stmt);
throw exception(msg);
}
sqlite3_reset(stmt);
}
std::vector<std::string> SQLiteDatabase::propertyKeys(const std::string &prefix,
const std::string &networkScope,
const std::string &receiverScope,
const std::string &senderScope)
{
// Return a vector of all the property keys matching the criteria.
std::vector<std::string> keys = std::vector<std::string>();
tryBind(properties, 1, prefix);
tryBind(properties, 2, networkScope);
tryBind(properties, 3, receiverScope);
tryBind(properties, 4, senderScope);
while (true) {
int errc = sqlite3_step(properties);
if (errc == SQLITE_ROW) {
std::string value = reinterpret_cast<const char *>(sqlite3_column_text(properties, 0));
keys.push_back(value);
} else if (errc == SQLITE_DONE) {
sqlite3_reset(properties);
break;
} else {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(properties);
throw exception(msg);
}
}
return keys;
}
bool SQLiteDatabase::hasPermission(const std::string &perm_name,
const std::string &network, const std::string &channel,
const std::string &sender, bool defaultPermission) const
{
tryBind(has_permission, 1, perm_name);
tryBind(has_permission, 2, network);
tryBind(has_permission, 3, channel);
tryBind(has_permission, 4, sender);
int errc = sqlite3_step(has_permission);
if (errc == SQLITE_ROW) {
sqlite3_reset(has_permission);
return true;
} else if (errc == SQLITE_DONE) {
sqlite3_reset(has_permission);
return defaultPermission;
} else {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(has_permission);
throw exception(msg);
}
}
void SQLiteDatabase::unsetPermission(const std::string &perm_name,
const std::string &network, const std::string &receiver,
const std::string &sender)
{
tryBind(remove_permission, 1, perm_name);
tryBind(remove_permission, 2, network);
tryBind(remove_permission, 3, receiver);
tryBind(remove_permission, 4, sender);
int errc = sqlite3_step(remove_permission);
if (errc != SQLITE_OK && errc != SQLITE_DONE) {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(remove_permission);
throw exception(msg);
}
sqlite3_reset(remove_permission);
}
void SQLiteDatabase::setPermission(bool permission, const std::string &perm_name,
const std::string &network, const std::string &receiver,
const std::string &sender)
{
tryBind(add_permission, 1, perm_name);
tryBind(add_permission, 2, network);
tryBind(add_permission, 3, receiver);
tryBind(add_permission, 4, sender);
int errc = sqlite3_step(add_permission);
if (errc != SQLITE_OK && errc != SQLITE_DONE) {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(add_permission);
throw exception(msg);
}
sqlite3_reset(add_permission);
}
} // namespace db
} // namespace dazeus
<commit_msg>Substring matching for sqlite<commit_after>/**
* Copyright (c) 2014 Ruben Nijveld, Aaron van Geffen
* See LICENSE for license.
*/
#include "../config.h"
#include "sqlite.h"
#include <sqlite3.h>
#include <stdio.h>
#include <iostream>
namespace dazeus {
namespace db {
/**
* Cleanup all prepared queries and close the connection.
*/
SQLiteDatabase::~SQLiteDatabase()
{
if (conn_) {
sqlite3_finalize(find_property);
sqlite3_finalize(remove_property);
sqlite3_finalize(update_property);
sqlite3_finalize(properties);
sqlite3_finalize(add_permission);
sqlite3_finalize(remove_permission);
sqlite3_finalize(has_permission);
int res = sqlite3_close(conn_);
assert(res == SQLITE_OK);
}
}
void SQLiteDatabase::open()
{
// Connect the lot!
int fail = sqlite3_open_v2(dbc_.filename.c_str(), &conn_,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
NULL);
if (fail) {
auto error = "Can't open database (code " + std::to_string(fail) + "): " +
sqlite3_errmsg(conn_);
throw exception(error);
}
upgradeDB();
bootstrapDB();
}
/**
* @brief Try to create a prepared statement on the SQLite3 connection.
*/
void SQLiteDatabase::tryPrepare(const std::string &stmt,
sqlite3_stmt **target) const
{
int result = sqlite3_prepare_v2(conn_, stmt.c_str(), stmt.length(), target,
NULL);
if (result != SQLITE_OK) {
throw exception(
std::string("Failed to prepare SQL statement, got an error: ") +
sqlite3_errmsg(conn_));
}
}
/**
* @brief Try to bind a parameter to a prepared statement.
*/
void SQLiteDatabase::tryBind(sqlite3_stmt *target, int param,
const std::string &value) const
{
int result = sqlite3_bind_text(target, param, value.c_str(), value.length(),
SQLITE_TRANSIENT);
if (result != SQLITE_OK) {
throw exception("Failed to bind parameter " + std::to_string(param) +
" to query with error: " + sqlite3_errmsg(conn_) +
" (errorcode " + std::to_string(result) + ")");
}
}
/**
* @brief Prepare all SQL statements used by the database layer
*/
void SQLiteDatabase::bootstrapDB()
{
tryPrepare(
"SELECT value FROM dazeus_properties "
"WHERE key = ?1 "
" AND (network = ?2 OR network = '') "
" AND (receiver = ?3 OR receiver = '') "
" AND (sender = ?4 OR sender = '') "
"ORDER BY network DESC, receiver DESC, sender DESC "
"LIMIT 1",
&find_property);
tryPrepare(
"DELETE FROM dazeus_properties "
"WHERE key = ?1 "
" AND network = ?3 AND receiver = ?4 AND sender = ?5",
&remove_property);
tryPrepare(
"INSERT OR REPLACE INTO dazeus_properties "
"(key, value, network, receiver, sender) "
"VALUES (?1, ?2, ?3, ?4, ?5) ",
&update_property);
tryPrepare(
"SELECT key FROM dazeus_properties "
"WHERE SUBSTR(key, 0, LENGTH(?1)) = ?1 "
" AND network = ?2 AND receiver = ?3 AND sender = ?4",
&properties);
tryPrepare(
"INSERT OR REPLACE INTO dazeus_permissions "
"(permission, network, receiver, sender) "
"VALUES (?1, ?2, ?3, ?4) ",
&add_permission);
tryPrepare(
"DELETE FROM dazeus_permissions "
"WHERE permission = ?1 "
" AND network = ?2 AND receiver = ?3 AND sender = ?4",
&remove_permission);
tryPrepare(
"SELECT * FROM dazeus_permissions "
"WHERE permission = ?1 "
" AND network = ?2 AND receiver = ?3 AND sender = ?4",
&has_permission);
}
/**
* @brief Upgrade the database to the latest version.
*/
void SQLiteDatabase::upgradeDB()
{
bool found = false;
int errc = sqlite3_exec(conn_,
"SELECT name FROM sqlite_master WHERE type = 'table' "
"AND name = 'dazeus_properties'",
[](void* found, int, char**, char**)
{
*(static_cast<bool*>(found)) = true;
return 0;
}, static_cast<void*>(&found), NULL);
if (errc != SQLITE_OK) {
throw exception(std::string("Failed to retrieve database version: ") +
sqlite3_errmsg(conn_));
}
int db_version = 0;
if (errc == SQLITE_OK) {
if (found) {
// table exists, query for latest version
errc = sqlite3_exec(conn_,
"SELECT value FROM dazeus_properties "
"WHERE key = 'dazeus_version' LIMIT 1",
[](void* dbver, int columns, char** values, char**)
{
if (columns > 0) {
*(static_cast<int*>(dbver)) = std::stoi(values[0]);
}
return 0;
}, static_cast<void*>(&db_version), NULL);
}
}
const char *upgrades[] = {
"CREATE TABLE dazeus_properties( "
"key VARCHAR(255) NOT NULL, "
"value TEXT NOT NULL, "
"network VARCHAR(255) NOT NULL, "
"receiver VARCHAR(255) NOT NULL, "
"sender VARCHAR(255) NOT NULL, "
"created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"PRIMARY KEY(key, network, receiver, sender) "
")"
,
"CREATE TABLE dazeus_permissions( "
"permission VARCHAR(255) NOT NULL, "
"network VARCHAR(255) NOT NULL, "
"receiver VARCHAR(255) NOT NULL, "
"sender VARCHAR(255) NOT NULL, "
"created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"PRIMARY KEY(permission, network, receiver, sender) "
")"
};
// run any outstanding updates
static int target_version = std::end(upgrades) - std::begin(upgrades);
if (db_version < target_version) {
std::cout << "Will now upgrade database from version " << db_version
<< " to version " << target_version << "." << std::endl;
for (int i = db_version; i < target_version; ++i) {
int result = sqlite3_exec(conn_, upgrades[i], NULL, NULL, NULL);
if (result != SQLITE_OK) {
throw exception("Could not run upgrade " + std::to_string(i) +
", got error: " + sqlite3_errmsg(conn_));
}
}
std::cout << "Upgrade completed. Will now update dazeus_version to "
<< target_version << std::endl;
errc = sqlite3_exec(conn_,
("INSERT OR REPLACE INTO dazeus_properties "
"(key, value, network, receiver, sender) "
"VALUES ('dazeus_version', '" + std::to_string(target_version) + "', "
" '', '', '') ").c_str(),
NULL, NULL, NULL);
if (errc != SQLITE_OK) {
throw exception(
"Could not set dazeus_version to latest version, got error: " +
std::string(sqlite3_errmsg(conn_)));
}
}
}
std::string SQLiteDatabase::property(const std::string &variable,
const std::string &networkScope,
const std::string &receiverScope,
const std::string &senderScope)
{
tryBind(find_property, 1, variable);
tryBind(find_property, 2, networkScope);
tryBind(find_property, 3, receiverScope);
tryBind(find_property, 4, senderScope);
int errc = sqlite3_step(find_property);
if (errc == SQLITE_ROW) {
std::string value = reinterpret_cast<const char *>(sqlite3_column_text(find_property, 0));
sqlite3_reset(find_property);
return value;
} else if (errc == SQLITE_DONE) {
// TODO: define behavior when no result is found
sqlite3_reset(find_property);
return "";
} else {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(find_property);
throw exception(msg);
}
}
void SQLiteDatabase::setProperty(const std::string &variable,
const std::string &value, const std::string &networkScope,
const std::string &receiverScope,
const std::string &senderScope)
{
sqlite3_stmt *stmt = value == "" ? remove_property : update_property;
tryBind(stmt, 1, variable);
tryBind(stmt, 2, value);
tryBind(stmt, 3, networkScope);
tryBind(stmt, 4, receiverScope);
tryBind(stmt, 5, senderScope);
int errc = sqlite3_step(stmt);
if (errc != SQLITE_OK && errc != SQLITE_DONE) {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(stmt);
throw exception(msg);
}
sqlite3_reset(stmt);
}
std::vector<std::string> SQLiteDatabase::propertyKeys(const std::string &prefix,
const std::string &networkScope,
const std::string &receiverScope,
const std::string &senderScope)
{
// Return a vector of all the property keys matching the criteria.
std::vector<std::string> keys = std::vector<std::string>();
tryBind(properties, 1, prefix);
tryBind(properties, 2, networkScope);
tryBind(properties, 3, receiverScope);
tryBind(properties, 4, senderScope);
while (true) {
int errc = sqlite3_step(properties);
if (errc == SQLITE_ROW) {
std::string value = reinterpret_cast<const char *>(sqlite3_column_text(properties, 0));
keys.push_back(value);
} else if (errc == SQLITE_DONE) {
sqlite3_reset(properties);
break;
} else {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(properties);
throw exception(msg);
}
}
return keys;
}
bool SQLiteDatabase::hasPermission(const std::string &perm_name,
const std::string &network, const std::string &channel,
const std::string &sender, bool defaultPermission) const
{
tryBind(has_permission, 1, perm_name);
tryBind(has_permission, 2, network);
tryBind(has_permission, 3, channel);
tryBind(has_permission, 4, sender);
int errc = sqlite3_step(has_permission);
if (errc == SQLITE_ROW) {
sqlite3_reset(has_permission);
return true;
} else if (errc == SQLITE_DONE) {
sqlite3_reset(has_permission);
return defaultPermission;
} else {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(has_permission);
throw exception(msg);
}
}
void SQLiteDatabase::unsetPermission(const std::string &perm_name,
const std::string &network, const std::string &receiver,
const std::string &sender)
{
tryBind(remove_permission, 1, perm_name);
tryBind(remove_permission, 2, network);
tryBind(remove_permission, 3, receiver);
tryBind(remove_permission, 4, sender);
int errc = sqlite3_step(remove_permission);
if (errc != SQLITE_OK && errc != SQLITE_DONE) {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(remove_permission);
throw exception(msg);
}
sqlite3_reset(remove_permission);
}
void SQLiteDatabase::setPermission(bool permission, const std::string &perm_name,
const std::string &network, const std::string &receiver,
const std::string &sender)
{
tryBind(add_permission, 1, perm_name);
tryBind(add_permission, 2, network);
tryBind(add_permission, 3, receiver);
tryBind(add_permission, 4, sender);
int errc = sqlite3_step(add_permission);
if (errc != SQLITE_OK && errc != SQLITE_DONE) {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(add_permission);
throw exception(msg);
}
sqlite3_reset(add_permission);
}
} // namespace db
} // namespace dazeus
<|endoftext|> |
<commit_before>#include "dbmanager.h"
bool DBManager::openDB()
{
db = QSqlDatabase::addDatabase("QSQLITE");
QFileInfo fileInfo("vertsys.db");
db.setDatabaseName(fileInfo.absoluteFilePath());
bool status;
if (!fileInfo.exists())
{
status = db.open();
QSqlQuery query(db);
qDebug() << "Creating tables" << endl;
query.exec("CREATE TABLE climber (name VARCHAR(32), phone VARCHAR(16), address VARCHAR(40),\
email VARCHAR(50), expirationDate DATE, startDate DATE, status CHAR(1), PRIMARY KEY (email))");
query.exec("CREATE TABLE payment (id INTEGER PRIMARY KEY, email TEXT, paymentDate DATE, expirationDate DATE, value NUMERIC, FOREIGN KEY(email) REFERENCES climber(email))");
}
else
status = db.open();
return status;
}
QSqlError DBManager::lastError()
{
return db.lastError();
}
DBManager::~DBManager()
{
db.close();
}
<commit_msg>update db, insert table payment<commit_after>/* CHANGES IN DB
* enriquefynn: First model -v0
* thadeuk: Added payment table -v1
*/
#include <QStringList>
#include "dbmanager.h"
bool DBManager::openDB()
{
db = QSqlDatabase::addDatabase("QSQLITE");
QFileInfo fileInfo("vertsys.db");
db.setDatabaseName(fileInfo.absoluteFilePath());
bool status = db.open();
QSqlQuery query(db);
if (!fileInfo.exists())
{
qDebug() << "Creating tables" << endl;
query.exec("CREATE TABLE climber (name VARCHAR(32), phone VARCHAR(16), address VARCHAR(40),\
email VARCHAR(50), expirationDate DATE, startDate DATE, status CHAR(1), PRIMARY KEY (email))");
query.exec("CREATE TABLE payment (id INTEGER PRIMARY KEY, email TEXT, paymentDate DATE, expirationDate DATE, value NUMERIC, FOREIGN KEY(email) REFERENCES climber(email))");
}
else
{
//Check if db is not v1
if (!db.tables().contains("payment"))
{
qDebug() << "Updating to DB v1" << endl;
query.exec("CREATE TABLE payment (id INTEGER PRIMARY KEY, email TEXT, paymentDate DATE, expirationDate DATE, value NUMERIC, FOREIGN KEY(email) REFERENCES climber(email))");
}
}
return status;
}
QSqlError DBManager::lastError()
{
return db.lastError();
}
DBManager::~DBManager()
{
db.close();
}
<|endoftext|> |
<commit_before><commit_msg>fixed a simple compilation problem of fft unit test in windows ticket #79<commit_after><|endoftext|> |
<commit_before>/*
* PolarPulse.cpp
*
* Created on: 15.05.2016
* Author: niklausd
*/
#include <Timer.h>
#include <Arduino.h>
#include "PolarPulse.h"
const bool PolarPulse::IS_POS_LOGIC = false;
const bool PolarPulse::IS_NEG_LOGIC = true;
const int PolarPulse::PLS_NC = -1;
const int PolarPulse::IND_NC = -1;
const unsigned int PolarPulse::s_defaultPulsePollTimeMillis = 5;
const unsigned int PolarPulse::s_defaultReportIntervalMillis = 15000;
//-----------------------------------------------------------------------------
class PollingTimerAdapter : public TimerAdapter
{
private:
PolarPulse* m_pulseSesor;
bool m_lastWasPulseActive;
public:
PollingTimerAdapter(PolarPulse* pulseSesor)
: m_pulseSesor(pulseSesor)
, m_lastWasPulseActive(false)
{ }
void timeExpired()
{
if (0 != m_pulseSesor)
{
bool currentIsPulseActive = m_pulseSesor->isPulseActive();
if (m_lastWasPulseActive != currentIsPulseActive)
{
m_lastWasPulseActive = currentIsPulseActive;
m_pulseSesor->setIndicator(currentIsPulseActive);
if (currentIsPulseActive)
{
m_pulseSesor->countPulse();
}
}
}
}
};
//-----------------------------------------------------------------------------
class ReportTimerAdapter : public TimerAdapter
{
private:
PolarPulse* m_pulseSesor;
public:
ReportTimerAdapter(PolarPulse* pulseSesor)
: m_pulseSesor(pulseSesor)
{ }
void timeExpired()
{
if (0 != m_pulseSesor)
{
m_pulseSesor->reportInterval();
}
}
};
//-----------------------------------------------------------------------------
PolarPulse::PolarPulse(int pulsePin, int indicatorPin, bool isPulsePinNegativeLogic, PolarPulseAdapter* adapter)
: m_pollingTimer(new Timer(new PollingTimerAdapter(this), Timer::IS_RECURRING, s_defaultPulsePollTimeMillis))
, m_reportTimer(new Timer(new ReportTimerAdapter(this), Timer::IS_RECURRING, s_defaultReportIntervalMillis))
, m_adapter(adapter)
, m_isPulsePinNegativeLogic(isPulsePinNegativeLogic)
, m_count(false)
, m_heartBeatRate(0)
, m_pulsePin(pulsePin)
, m_indicatorPin(indicatorPin)
{
if (0 <= m_pulsePin)
{
pinMode(m_pulsePin, INPUT);
digitalWrite(m_pulsePin, m_isPulsePinNegativeLogic ? HIGH : LOW); // pull
}
if (0 <= m_indicatorPin)
{
pinMode(m_indicatorPin, OUTPUT);
digitalWrite(m_indicatorPin, m_count);
}
}
PolarPulse::~PolarPulse()
{
delete m_pollingTimer->adapter();
m_pollingTimer->attachAdapter(0);
delete m_pollingTimer;
m_pollingTimer = 0;
delete m_reportTimer->adapter();
m_reportTimer->attachAdapter(0);
delete m_reportTimer;
m_reportTimer = 0;
}
PolarPulseAdapter* PolarPulse::adapter()
{
return m_adapter;
}
void PolarPulse::attachAdapter(PolarPulseAdapter* adapter)
{
m_adapter = adapter;
}
bool PolarPulse::isPulseActive()
{
bool active = false;
if (0 <= m_pulsePin)
{
active = digitalRead(m_pulsePin);
active = (m_isPulsePinNegativeLogic ? !active : active);
}
return active;
}
void PolarPulse::countPulse()
{
m_count++;
}
void PolarPulse::reportInterval()
{
const unsigned int c_extrapolationFactor = 60000 / s_defaultReportIntervalMillis;
m_heartBeatRate = m_count * c_extrapolationFactor;
m_count = 0;
if (0 != m_adapter)
{
m_adapter->notifyHeartBeatRate(m_heartBeatRate);
}
}
void PolarPulse::setIndicator(bool isActive)
{
if (0 <= m_indicatorPin)
{
digitalWrite(m_indicatorPin, !isActive);
}
}
<commit_msg>change s_defaultReportIntervalMillis down to 5 seconds<commit_after>/*
* PolarPulse.cpp
*
* Created on: 15.05.2016
* Author: niklausd
*/
#include <Timer.h>
#include <Arduino.h>
#include "PolarPulse.h"
const bool PolarPulse::IS_POS_LOGIC = false;
const bool PolarPulse::IS_NEG_LOGIC = true;
const int PolarPulse::PLS_NC = -1;
const int PolarPulse::IND_NC = -1;
const unsigned int PolarPulse::s_defaultPulsePollTimeMillis = 5;
const unsigned int PolarPulse::s_defaultReportIntervalMillis = 5000;
//-----------------------------------------------------------------------------
class PollingTimerAdapter : public TimerAdapter
{
private:
PolarPulse* m_pulseSesor;
bool m_lastWasPulseActive;
public:
PollingTimerAdapter(PolarPulse* pulseSesor)
: m_pulseSesor(pulseSesor)
, m_lastWasPulseActive(false)
{ }
void timeExpired()
{
if (0 != m_pulseSesor)
{
bool currentIsPulseActive = m_pulseSesor->isPulseActive();
if (m_lastWasPulseActive != currentIsPulseActive)
{
m_lastWasPulseActive = currentIsPulseActive;
m_pulseSesor->setIndicator(currentIsPulseActive);
if (currentIsPulseActive)
{
m_pulseSesor->countPulse();
}
}
}
}
};
//-----------------------------------------------------------------------------
class ReportTimerAdapter : public TimerAdapter
{
private:
PolarPulse* m_pulseSesor;
public:
ReportTimerAdapter(PolarPulse* pulseSesor)
: m_pulseSesor(pulseSesor)
{ }
void timeExpired()
{
if (0 != m_pulseSesor)
{
m_pulseSesor->reportInterval();
}
}
};
//-----------------------------------------------------------------------------
PolarPulse::PolarPulse(int pulsePin, int indicatorPin, bool isPulsePinNegativeLogic, PolarPulseAdapter* adapter)
: m_pollingTimer(new Timer(new PollingTimerAdapter(this), Timer::IS_RECURRING, s_defaultPulsePollTimeMillis))
, m_reportTimer(new Timer(new ReportTimerAdapter(this), Timer::IS_RECURRING, s_defaultReportIntervalMillis))
, m_adapter(adapter)
, m_isPulsePinNegativeLogic(isPulsePinNegativeLogic)
, m_count(false)
, m_heartBeatRate(0)
, m_pulsePin(pulsePin)
, m_indicatorPin(indicatorPin)
{
if (0 <= m_pulsePin)
{
pinMode(m_pulsePin, INPUT);
digitalWrite(m_pulsePin, m_isPulsePinNegativeLogic ? HIGH : LOW); // pull
}
if (0 <= m_indicatorPin)
{
pinMode(m_indicatorPin, OUTPUT);
digitalWrite(m_indicatorPin, m_count);
}
}
PolarPulse::~PolarPulse()
{
delete m_pollingTimer->adapter();
m_pollingTimer->attachAdapter(0);
delete m_pollingTimer;
m_pollingTimer = 0;
delete m_reportTimer->adapter();
m_reportTimer->attachAdapter(0);
delete m_reportTimer;
m_reportTimer = 0;
}
PolarPulseAdapter* PolarPulse::adapter()
{
return m_adapter;
}
void PolarPulse::attachAdapter(PolarPulseAdapter* adapter)
{
m_adapter = adapter;
}
bool PolarPulse::isPulseActive()
{
bool active = false;
if (0 <= m_pulsePin)
{
active = digitalRead(m_pulsePin);
active = (m_isPulsePinNegativeLogic ? !active : active);
}
return active;
}
void PolarPulse::countPulse()
{
m_count++;
}
void PolarPulse::reportInterval()
{
const unsigned int c_extrapolationFactor = 60000 / s_defaultReportIntervalMillis;
m_heartBeatRate = m_count * c_extrapolationFactor;
m_count = 0;
if (0 != m_adapter)
{
m_adapter->notifyHeartBeatRate(m_heartBeatRate);
}
}
void PolarPulse::setIndicator(bool isActive)
{
if (0 <= m_indicatorPin)
{
digitalWrite(m_indicatorPin, !isActive);
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <influxdb_raw_db_utf8.h>
#include <influxdb_simple_api.h>
#include <influxdb_line.h>
using namespace influxdb::api;
int main(int argc, char* argv[])
{
try
{
const char* url = "http://localhost:8086";
influxdb::raw::db_utf8 db(url);
influxdb::api::simple_db api(url, "demo");
api.drop();
api.create();
// {"results":[{"series":[{"columns":["name"],"name":"databases","values":[["_internal"],["mydb"]]}]}]}
std::cout << db.get("show databases") << std::endl;
api.insert(line("test", key_value_pairs(), key_value_pairs("value", 42)));
// {"results":[{"series":[{"columns":["time","value"],"name":"test","values":[["2016-10-28T22:11:22.8110348Z",42]]}]}]}
std::cout << db.get("select * from demo..test") << std::endl;
api.drop();
}
catch (std::exception const& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
<commit_msg>demo with the async api<commit_after>#include <influxdb_raw_db_utf8.h>
#include <influxdb_simple_api.h>
#include <influxdb_line.h>
#include <influxdb_simple_async_api.h>
#include <iostream>
#include <thread>
#include <chrono>
using namespace influxdb::api;
int main(int argc, char* argv[])
{
try
{
const char* url = "http://localhost:8086";
influxdb::raw::db_utf8 db(url);
influxdb::api::simple_db api(url, "demo");
influxdb::async_api::simple_db async_api(url, "demo");
api.drop();
api.create();
// {"results":[{"series":[{"columns":["name"],"name":"databases","values":[["_internal"],["mydb"]]}]}]}
std::cout << db.get("show databases") << std::endl;
async_api.insert(line("test", key_value_pairs(), key_value_pairs("value", 41)));
api.insert(line("test", key_value_pairs(), key_value_pairs("value", 42)));
std::this_thread::sleep_for(std::chrono::milliseconds(101));
// {"results":[{"series":[{"columns":["time","value"],"name":"test","values":[["2016-10-28T22:11:22.8110348Z",42]]}]}]}
std::cout << db.get("select * from demo..test") << std::endl;
// or if the async call passes through:
// {"results":[{"series":[{"name":"test","columns":["time","value"],
// "values":[["2016-12-09T20:24:18.8239801Z",42],["2016-12-09T20:24:18.9026688Z",41]]}]}]}
api.drop();
}
catch (std::exception const& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "dialogarp.h"
#include "ui_dialogarp.h"
Dialogarp::Dialogarp(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialogarp)
{
ui->setupUi(this);
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(StartArp()));
ui->lv_client->setModel(new QStringListModel());
#ifdef _WIN32
system("arp -a > arp_dump");
#elif __linux__
system("arp -an > arp_dump");
#endif
std::ifstream file("arp_dump");
if (!file.is_open())
return ;
std::string line;
char ip[100];
char mac[100];
while (std::getline(file, line, '\n'))
{
#ifdef __linux__
if (!std::sscanf(line.c_str(), "%*s %s at %s %*s", ip, mac))
continue;
#elif _WIN32
if (line.find("dynamic") == std::string::npos)
continue;
if (!std::sscanf(line.c_str(), "%s\t%s\tdynamic", ip, mac))
continue;
#endif
client_t *client = new client_t;
client->ip = ip;
client->ip.erase(std::remove(client->ip.begin(), client->ip.end(), '('));
client->ip.erase(std::remove(client->ip.begin(), client->ip.end(), ')'));
clients.push_back(client);
char smac[6];
sscanf(mac, "%x:%x:%x:%x:%x:%x", (unsigned int *) &smac[0], (unsigned int *) &smac[1], (unsigned int *) &smac[2], (unsigned int *) &smac[3], (unsigned int *) &smac[4], (unsigned int *) &smac[5]);
memcpy(client->mac, smac, 6);
}
QStringList list;
list = ((QStringListModel *) ui->lv_client->model())->stringList();
for (std::vector<client_t *>::iterator it = clients.begin(); it != clients.end(); it++)
list.append((*it)->ip.c_str());
((QStringListModel *) ui->lv_client->model())->setStringList(list);
}
Dialogarp::~Dialogarp()
{
delete ui;
}
void Dialogarp::StartArp()
{
if (ui->lv_client->selectionModel()->selectedRows().count() < 2)
return ;
int index1 = ui->lv_client->selectionModel()->selectedRows().at(0).row();
int index2 = ui->lv_client->selectionModel()->selectedRows().at(1).row();
((MainWindow *) this->parentWidget())->StartArp(clients[index1]->ip, clients[index1]->mac, clients[index2]->ip, clients[index2]->mac);
}
<commit_msg>Fix model/list qlistview<commit_after>#include "dialogarp.h"
#include "ui_dialogarp.h"
Dialogarp::Dialogarp(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialogarp)
{
ui->setupUi(this);
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(StartArp()));
#ifdef _WIN32
system("arp -a > arp_dump");
#elif __linux__
system("arp -an > arp_dump");
#endif
std::ifstream file("arp_dump");
if (!file.is_open())
return ;
std::string line;
char ip[100];
char mac[100];
while (std::getline(file, line, '\n'))
{
#ifdef __linux__
if (!std::sscanf(line.c_str(), "%*s %s at %s %*s", ip, mac))
continue;
#elif _WIN32
if (line.find("dynamic") == std::string::npos)
continue;
if (!std::sscanf(line.c_str(), "%s\t%s\tdynamic", ip, mac))
continue;
#endif
client_t *client = new client_t;
client->ip = ip;
client->ip.erase(std::remove(client->ip.begin(), client->ip.end(), '('));
client->ip.erase(std::remove(client->ip.begin(), client->ip.end(), ')'));
clients.push_back(client);
char smac[6];
sscanf(mac, "%x:%x:%x:%x:%x:%x", (unsigned int *) &smac[0], (unsigned int *) &smac[1], (unsigned int *) &smac[2], (unsigned int *) &smac[3], (unsigned int *) &smac[4], (unsigned int *) &smac[5]);
memcpy(client->mac, smac, 6);
}
QStringListModel *model = new QStringListModel();
QStringList list;
for (std::vector<client_t *>::iterator it = clients.begin(); it != clients.end(); it++)
list << ((*it)->ip.c_str());
model->setStringList(list);
ui->lv_client->setModel(model);
}
Dialogarp::~Dialogarp()
{
delete ui;
}
void Dialogarp::StartArp()
{
if (ui->lv_client->selectionModel()->selectedRows().count() < 2)
return ;
int index1 = ui->lv_client->selectionModel()->selectedRows().at(0).row();
int index2 = ui->lv_client->selectionModel()->selectedRows().at(1).row();
((MainWindow *) this->parentWidget())->StartArp(clients[index1]->ip, clients[index1]->mac, clients[index2]->ip, clients[index2]->mac);
}
<|endoftext|> |
<commit_before>#define SOL_CHECK_ARGUMENTS
#include <sol.hpp>
#include <iostream>
int main() {
std::cout << "=== protected_functions example ===" << std::endl;
sol::state lua;
// A complicated function which can error out
// We define both in terms of Lua code
lua.script(R"(
function handler (message)
return "Handled this message: " .. message
end
function f (a)
if a < 0 then
error("negative number detected")
end
return a + 5
end
)");
// Get a protected function out of Lua
sol::protected_function f = lua["f"];
// Set a non-default error handler
f.error_handler = lua["handler"];
sol::protected_function_result result = f(-500);
if (result.valid()) {
// Call succeeded
int x = result;
std::cout << "call succeeded, result is " << x << std::endl;
}
else {
// Call failed
sol::error err = result;
std::string what = err.what();
std::cout << "call failed, sol::error::what() is " << what << std::endl;
// 'what' Should read
// "Handled this message: negative number detected"
}
std::cout << std::endl;
}
<commit_msg>made "error" accessible in the Lua state<commit_after>#define SOL_CHECK_ARGUMENTS
#include <sol.hpp>
#include <iostream>
int main() {
std::cout << "=== protected_functions example ===" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
// A complicated function which can error out
// We define both in terms of Lua code
lua.script(R"(
function handler (message)
return "Handled this message: " .. message
end
function f (a)
if a < 0 then
error("negative number detected")
end
return a + 5
end
)");
// Get a protected function out of Lua
sol::protected_function f = lua["f"];
// Set a non-default error handler
f.error_handler = lua["handler"];
sol::protected_function_result result = f(-500);
if (result.valid()) {
// Call succeeded
int x = result;
std::cout << "call succeeded, result is " << x << std::endl;
}
else {
// Call failed
sol::error err = result;
std::string what = err.what();
std::cout << "call failed, sol::error::what() is " << what << std::endl;
// 'what' Should read
// "Handled this message: negative number detected"
}
std::cout << std::endl;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "obj_general_weapon.h"
#include "obj_base_weapon.h"
#include "obj_gun.h"
#include "range.h"
#include "obj_arrow.h"
#include "obj_handgonne.h"
#include "obj_tool.h"
const char *getAmmoKeyword(int ammo){
if(ammo < AMMO_NONE ||
ammo >= AMMO_MAX){
return shellkeyword[0];
}
return shellkeyword[ammo];
}
const char *getAmmoDescr(int ammo){
if(ammo < AMMO_NONE ||
ammo >= AMMO_MAX){
return shelldesc[0];
}
return shelldesc[ammo];
}
void TGun::dropSpentCasing(TRoom *roomp){
TObj *obj;
char buf[256];
int ammo=getAmmoType();
int robj = real_object(13874);
if (robj < 0 || robj >= (signed int) obj_index.size()) {
vlogf(LOG_BUG, fmt("dropSpentCasing(): No object (%d) in database!") % 13874);
return;
}
obj = read_object(robj, REAL);
obj->swapToStrung();
sprintf(buf, "casing spent %s", getAmmoDescr(ammo));
delete [] obj->name;
obj->name = mud_str_dup(buf);
sprintf(buf, "<o>a spent %s casing<1>", getAmmoDescr(ammo));
delete [] obj->shortDescr;
obj->shortDescr = mud_str_dup(buf);
sprintf(buf, "A spent <o>%s casing<1> lies here.", getAmmoDescr(ammo));
delete [] obj->descr;
obj->setDescr(mud_str_dup(buf));
*roomp += *obj;
return;
}
void gload_usage(TBeing *tb){
tb->sendTo("Syntax : (loading) gload <gun> <ammo>\n\r");
tb->sendTo("Syntax : (unloading) gload unload <gun>\n\r");
return;
}
void TGun::loadMe(TBeing *ch, TAmmo *ammo)
{
--(*ammo);
setAmmo(ammo);
act("You load $p into $N.", TRUE, ch, ammo, this, TO_CHAR);
act("$n loads $p into $N.", TRUE, ch, ammo, this, TO_ROOM);
ch->addToWait(combatRound(1));
}
void TGun::unloadMe(TBeing *ch, TAmmo *ammo)
{
TThing *arrow=dynamic_cast<TThing *>(ammo);
if(ammo->getRounds() == 0){
--(*ammo);
*roomp += *ammo;
act("You unload $N and drop $p.", TRUE, ch, ammo, this, TO_CHAR);
act("$n unloads $N and drops $p.", TRUE, ch, ammo, this, TO_ROOM);
} else {
--(*arrow);
*this += *arrow;
act("You unload $N.", TRUE, ch, ammo, this, TO_CHAR);
act("$n unloads $N.", TRUE, ch, ammo, this, TO_ROOM);
}
ch->addToWait(combatRound(1));
}
void TBeing::doGload(sstring arg)
{
sstring arg1, arg2;
sstring buf;
TObj *bow;
TThing *arrow;
TGun *gun;
TAmmo *ammo=NULL;
TBeing *tb;
arg1=arg.word(0);
arg2=arg.word(1);
if(arg1.empty()){
gload_usage(this);
return;
}
if(arg1 != "unload"){
generic_find(arg1.c_str(), FIND_OBJ_INV | FIND_OBJ_EQUIP | FIND_OBJ_ROOM, this, &tb, &bow);
if(!bow || !(gun=dynamic_cast<TGun *>(bow))){
gload_usage(this);
return;
}
if(arg2.empty()){
arg2=getAmmoKeyword(gun->getAmmoType());
}
if(!(arrow = searchLinkedListVis(this, arg2, getStuff())) ||
!(ammo=dynamic_cast<TAmmo *>(arrow))){
gload_usage(this);
return;
}
if(gun->getAmmo()){
buf = fmt("unload %s") % arg1;
doGload(buf);
if(gun->getAmmo()){
sendTo("That gun is already loaded!\n\r");
return;
}
}
if(ammo->getAmmoType() != gun->getAmmoType()){
sendTo("That isn't the right kind of ammunition.\n\r");
return;
}
gun->loadMe(this, ammo);
} else {
generic_find(arg2.c_str(), FIND_OBJ_INV | FIND_OBJ_EQUIP | FIND_OBJ_ROOM, this, &tb, &bow);
if (!bow || !(gun=dynamic_cast<TGun *>(bow))){
gload_usage(this);
return;
}
if(!(ammo=gun->getAmmo())){
sendTo("That gun isn't loaded!\n\r");
return;
}
gun->unloadMe(this, ammo);
}
}
int TGun::suggestedPrice() const
{
int pricetmp=TBaseWeapon::suggestedPrice();
pricetmp *= getROF();
pricetmp /= 10;
return pricetmp;
}
sstring TGun::statObjInfo() const
{
sstring buf, sbuf;
TGenWeapon::statObjInfo();
TAmmo *ammo=getAmmo();
buf = fmt("Rate of Fire: %i, Ammo Type: %s, Ammo: %i, Ammo Loaded: %s") %
getROF() % getAmmoDescr(getAmmoType()) % (ammo?ammo->getRounds():0) %
(ammo?ammo->getName():"None");
sbuf += buf;
buf = fmt("\n\rSilenced: %s Caseless: %s Clipless: %s Fouled: %s") %
(isSilenced()?"yes":"no") % (isCaseless()?"yes":"no") %
(isClipless()?"yes":"no") % (isFouled()?"yes":"no");
sbuf += buf;
return sbuf;
}
void TGun::describeObjectSpecifics(const TBeing *ch) const
{
if(getAmmo()){
ch->sendTo(fmt("It has %i rounds of %s ammunition left.\n\r") %
getAmmo()->getRounds() % getAmmoDescr(getAmmoType()));
} else {
// yeah yeah bad grammar, may as well be consistant though
ch->sendTo(fmt("It has 0 rounds of %s ammunition left.\n\r") %
getAmmoDescr(getAmmoType()));
}
}
void TAmmo::describeObjectSpecifics(const TBeing *ch) const
{
ch->sendTo(fmt("It has %i rounds of %s ammunition left.\n\r") %
getRounds() % getAmmoDescr(getAmmoType()));
}
void TGun::assignFourValues(int x1, int x2, int x3, int x4)
{
setROF(x1);
setWeapDamLvl(GET_BITS(x2, 7, 8));
setWeapDamDev(GET_BITS(x2, 15, 8));
setFlags(x3);
setAmmoType(x4);
}
void TGun::getFourValues(int *x1, int *x2, int *x3, int *x4) const {
int x = 0;
*x1=getROF();
SET_BITS(x, 7, 8, getWeapDamLvl());
SET_BITS(x, 15, 8, getWeapDamDev());
*x2 = x;
*x3=getFlags();
*x4=getAmmoType();
}
TGun::TGun() :
TGenWeapon(),
rof(1),
ammotype(1)
{
setMaxSharp(100);
setCurSharp(100);
}
TGun::TGun(const TGun &a) :
TGenWeapon(a),
rof(a.rof),
ammotype(a.ammotype)
{
}
TGun & TGun::operator=(const TGun &a)
{
if (this == &a) return *this;
TGenWeapon::operator=(a);
return *this;
}
TGun::~TGun()
{
}
sstring TAmmo::statObjInfo() const
{
sstring buf, sbuf;
buf = fmt("Ammo Type: %s, Rounds Remaining: %i") %
getAmmoDescr(getAmmoType()) % getRounds();
sbuf += buf;
return sbuf;
}
TAmmo::TAmmo() :
TObj()
{
}
TAmmo::TAmmo(const TAmmo &a) :
TObj(a),
ammotype(a.ammotype),
rounds(a.rounds)
{
}
TAmmo & TAmmo::operator=(const TAmmo &a)
{
if (this == &a) return *this;
TObj::operator=(a);
ammotype=a.ammotype;
rounds=a.rounds;
return *this;
}
TAmmo::~TAmmo()
{
}
void TAmmo::assignFourValues(int x1, int x2, int x3, int x4){
setAmmoType(x1);
setRounds(x2);
}
void TAmmo::getFourValues(int *x1, int *x2, int *x3, int *x4) const
{
*x1 = getAmmoType();
*x2 = getRounds();
*x3 = 0;
*x4 = 0;
}
void TAmmo::setRounds(int r) {
if(r<=0){
char buf[256];
sprintf(buf, "%s empty", name);
if(isObjStat(ITEM_STRUNG)){
delete [] name;
} else {
swapToStrung();
}
name=mud_str_dup(buf);
}
rounds=r;
}
sstring TAmmo::showModifier(showModeT tMode, const TBeing *tBeing) const
{
// recurse if necessary
sstring tString = TObj::showModifier(tMode, tBeing);
if (getRounds()<=0) {
tString += " (empty)";
}
return tString;
}
sstring TGun::showModifier(showModeT tMode, const TBeing *tBeing) const
{
// recurse if necessary
sstring tString = TObj::showModifier(tMode, tBeing);
if (!getAmmo() || getAmmo()->getRounds()<=0) {
tString += " (empty)";
}
return tString;
}
int TGun::shootMeBow(TBeing *ch, TBeing *targ, unsigned int count, dirTypeT dir, int shoot_dist)
{
TAmmo *ammo;
TObj *bullet;
char buf[256];
if (targ &&
ch->checkPeacefulVictim("They are in a peaceful room. You can't seem to fire the gun.\n\r", targ))
return FALSE;
if (targ && ch->noHarmCheck(targ))
return FALSE;
sstring capbuf, capbuf2;
ch->addToWait(combatRound(2));
int rof=getROF();
while(rof--){
if(!(ammo=dynamic_cast<TAmmo *>(getAmmo())) || ammo->getRounds()<=0){
act("Click. $N is out of ammunition.", TRUE, ch, NULL, this, TO_CHAR);
// keep looping to simulate trigger pulls - looks cooler
continue;
}
// grab a bullet object and adjust for damage
bullet=read_object(31864, VIRTUAL);
TArrow *tmp=dynamic_cast<TArrow *>(bullet);
if(tmp){
tmp->setWeapDamLvl(getWeapDamLvl());
tmp->setWeapDamDev(getWeapDamDev());
}
// decrement ammo and drop a casing
if(!isCaseless())
dropSpentCasing(ch->roomp);
setRounds(getRounds()-1);
// send messages
capbuf = colorString(ch, ch->desc, bullet->getName(), NULL, COLOR_OBJECTS, TRUE);
capbuf2 = colorString(ch, ch->desc, getName(), NULL, COLOR_OBJECTS, TRUE);
if (targ)
ch->sendTo(COLOR_MOBS, fmt("You shoot %s out of %s at %s.\n\r") %
capbuf.uncap() % capbuf2.uncap() %
targ->getName());
else
ch->sendTo(fmt("You shoot %s out of %s.\n\r") %
capbuf.uncap() %
capbuf2.uncap());
sprintf(buf, "$n points $p %swards, and shoots $N out of it.",
dirs[dir]);
act(buf, FALSE, ch, this, bullet, TO_ROOM);
// put the bullet in the room and then "throw" it
*ch->roomp += *bullet;
int rc = throwThing(bullet, dir, ch->in_room, &targ, shoot_dist, 10, ch);
if(!isSilenced())
ch->roomp->getZone()->sendTo("A gunshot echoes in the distance.\n\r",
ch->in_room);
// delete the bullet afterwards, arbitrary decision
// since they are arrow type and you usually don't find spent lead anyway
delete bullet;
bullet = NULL;
if (IS_SET_DELETE(rc, DELETE_VICT)) {
delete targ;
targ = NULL;
return FALSE;
}
}
return FALSE;
}
void TGun::setRounds(int r){
if(getAmmo()){
if(r<=0 && isClipless()){
TAmmo *ammo=getAmmo();
delete ammo;
} else
getAmmo()->setRounds(r);
}
}
int TGun::getRounds() const {
if(getAmmo())
return getAmmo()->getRounds();
else
return 0;
}
void TGun::describeContains(const TBeing *ch) const
{
// just to avoid the "something in it" message
}
TThing *findFlint(TThing *stuff){
TThing *tt;
TTool *flint;
TThing *ret;
if(!stuff)
return NULL;
for(tt=stuff;tt;tt=tt->nextThing){
if(tt && (flint=dynamic_cast<TTool *>(tt)) &&
(flint->getToolType() == TOOL_FLINTSTEEL))
return tt;
if(tt && tt->getStuff() && (ret=findFlint(tt->getStuff())))
return ret;
}
return NULL;
}
TThing *findPowder(TThing *stuff, int uses){
TThing *tt;
TTool *powder;
TThing *ret;
if(!stuff)
return NULL;
for(tt=stuff;tt;tt=tt->nextThing){
if(tt && (powder=dynamic_cast<TTool *>(tt)) &&
(powder->getToolType() == TOOL_BLACK_POWDER) &&
powder->getToolUses() >= uses)
return tt;
if(tt && tt->getStuff() && (ret=findPowder(tt->getStuff(), uses)))
return ret;
}
return NULL;
}
TThing *findShot(TThing *stuff, ammoTypeT ammotype){
TThing *tt;
TAmmo *Shot;
TThing *ret;
if(!stuff)
return NULL;
for(tt=stuff;tt;tt=tt->nextThing){
if(tt && (Shot=dynamic_cast<TAmmo *>(tt)) &&
Shot->getAmmoType()==ammotype)
return tt;
if(tt && tt->getStuff() && (ret=findShot(tt->getStuff(), ammotype)))
return ret;
}
return NULL;
}
<commit_msg>fixed a few bugs with unload<commit_after>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "obj_general_weapon.h"
#include "obj_base_weapon.h"
#include "obj_gun.h"
#include "range.h"
#include "obj_arrow.h"
#include "obj_handgonne.h"
#include "obj_tool.h"
const char *getAmmoKeyword(int ammo){
if(ammo < AMMO_NONE ||
ammo >= AMMO_MAX){
return shellkeyword[0];
}
return shellkeyword[ammo];
}
const char *getAmmoDescr(int ammo){
if(ammo < AMMO_NONE ||
ammo >= AMMO_MAX){
return shelldesc[0];
}
return shelldesc[ammo];
}
void TGun::dropSpentCasing(TRoom *roomp){
TObj *obj;
char buf[256];
int ammo=getAmmoType();
int robj = real_object(13874);
if (robj < 0 || robj >= (signed int) obj_index.size()) {
vlogf(LOG_BUG, fmt("dropSpentCasing(): No object (%d) in database!") % 13874);
return;
}
obj = read_object(robj, REAL);
obj->swapToStrung();
sprintf(buf, "casing spent %s", getAmmoDescr(ammo));
delete [] obj->name;
obj->name = mud_str_dup(buf);
sprintf(buf, "<o>a spent %s casing<1>", getAmmoDescr(ammo));
delete [] obj->shortDescr;
obj->shortDescr = mud_str_dup(buf);
sprintf(buf, "A spent <o>%s casing<1> lies here.", getAmmoDescr(ammo));
delete [] obj->descr;
obj->setDescr(mud_str_dup(buf));
*roomp += *obj;
return;
}
void gload_usage(TBeing *tb){
tb->sendTo("Syntax : (loading) gload <gun> <ammo>\n\r");
tb->sendTo("Syntax : (unloading) gload unload <gun>\n\r");
return;
}
void TGun::loadMe(TBeing *ch, TAmmo *ammo)
{
--(*ammo);
setAmmo(ammo);
act("You load $p into $N.", TRUE, ch, ammo, this, TO_CHAR);
act("$n loads $p into $N.", TRUE, ch, ammo, this, TO_ROOM);
ch->addToWait(combatRound(1));
}
void TGun::unloadMe(TBeing *ch, TAmmo *ammo)
{
if(ammo->getRounds() == 0){
--(*ammo);
*ch->roomp += *ammo;
act("You unload $N and drop $p.", TRUE, ch, ammo, this, TO_CHAR);
act("$n unloads $N and drops $p.", TRUE, ch, ammo, this, TO_ROOM);
} else {
--(*ammo);
*ch += *ammo;
act("You unload $N.", TRUE, ch, ammo, this, TO_CHAR);
act("$n unloads $N.", TRUE, ch, ammo, this, TO_ROOM);
}
ch->addToWait(combatRound(1));
}
void TBeing::doGload(sstring arg)
{
sstring arg1, arg2;
sstring buf;
TObj *bow;
TThing *arrow;
TGun *gun;
TAmmo *ammo=NULL;
TBeing *tb;
arg1=arg.word(0);
arg2=arg.word(1);
if(arg1.empty()){
gload_usage(this);
return;
}
if(arg1 != "unload"){
generic_find(arg1.c_str(), FIND_OBJ_INV | FIND_OBJ_EQUIP | FIND_OBJ_ROOM, this, &tb, &bow);
if(!bow || !(gun=dynamic_cast<TGun *>(bow))){
gload_usage(this);
return;
}
if(arg2.empty()){
arg2=getAmmoKeyword(gun->getAmmoType());
}
if(!(arrow = searchLinkedListVis(this, arg2, getStuff())) ||
!(ammo=dynamic_cast<TAmmo *>(arrow))){
gload_usage(this);
return;
}
if(gun->getAmmo()){
buf = fmt("unload %s") % arg1;
doGload(buf);
if(gun->getAmmo()){
sendTo("That gun is already loaded!\n\r");
return;
}
}
if(ammo->getAmmoType() != gun->getAmmoType()){
sendTo("That isn't the right kind of ammunition.\n\r");
return;
}
gun->loadMe(this, ammo);
} else {
generic_find(arg2.c_str(), FIND_OBJ_INV | FIND_OBJ_EQUIP | FIND_OBJ_ROOM, this, &tb, &bow);
if (!bow || !(gun=dynamic_cast<TGun *>(bow))){
gload_usage(this);
return;
}
if(!(ammo=gun->getAmmo())){
sendTo("That gun isn't loaded!\n\r");
return;
}
gun->unloadMe(this, ammo);
}
}
int TGun::suggestedPrice() const
{
int pricetmp=TBaseWeapon::suggestedPrice();
pricetmp *= getROF();
pricetmp /= 10;
return pricetmp;
}
sstring TGun::statObjInfo() const
{
sstring buf, sbuf;
TGenWeapon::statObjInfo();
TAmmo *ammo=getAmmo();
buf = fmt("Rate of Fire: %i, Ammo Type: %s, Ammo: %i, Ammo Loaded: %s") %
getROF() % getAmmoDescr(getAmmoType()) % (ammo?ammo->getRounds():0) %
(ammo?ammo->getName():"None");
sbuf += buf;
buf = fmt("\n\rSilenced: %s Caseless: %s Clipless: %s Fouled: %s") %
(isSilenced()?"yes":"no") % (isCaseless()?"yes":"no") %
(isClipless()?"yes":"no") % (isFouled()?"yes":"no");
sbuf += buf;
return sbuf;
}
void TGun::describeObjectSpecifics(const TBeing *ch) const
{
if(getAmmo()){
ch->sendTo(fmt("It has %i rounds of %s ammunition left.\n\r") %
getAmmo()->getRounds() % getAmmoDescr(getAmmoType()));
} else {
// yeah yeah bad grammar, may as well be consistant though
ch->sendTo(fmt("It has 0 rounds of %s ammunition left.\n\r") %
getAmmoDescr(getAmmoType()));
}
}
void TAmmo::describeObjectSpecifics(const TBeing *ch) const
{
ch->sendTo(fmt("It has %i rounds of %s ammunition left.\n\r") %
getRounds() % getAmmoDescr(getAmmoType()));
}
void TGun::assignFourValues(int x1, int x2, int x3, int x4)
{
setROF(x1);
setWeapDamLvl(GET_BITS(x2, 7, 8));
setWeapDamDev(GET_BITS(x2, 15, 8));
setFlags(x3);
setAmmoType(x4);
}
void TGun::getFourValues(int *x1, int *x2, int *x3, int *x4) const {
int x = 0;
*x1=getROF();
SET_BITS(x, 7, 8, getWeapDamLvl());
SET_BITS(x, 15, 8, getWeapDamDev());
*x2 = x;
*x3=getFlags();
*x4=getAmmoType();
}
TGun::TGun() :
TGenWeapon(),
rof(1),
ammotype(1)
{
setMaxSharp(100);
setCurSharp(100);
}
TGun::TGun(const TGun &a) :
TGenWeapon(a),
rof(a.rof),
ammotype(a.ammotype)
{
}
TGun & TGun::operator=(const TGun &a)
{
if (this == &a) return *this;
TGenWeapon::operator=(a);
return *this;
}
TGun::~TGun()
{
}
sstring TAmmo::statObjInfo() const
{
sstring buf, sbuf;
buf = fmt("Ammo Type: %s, Rounds Remaining: %i") %
getAmmoDescr(getAmmoType()) % getRounds();
sbuf += buf;
return sbuf;
}
TAmmo::TAmmo() :
TObj()
{
}
TAmmo::TAmmo(const TAmmo &a) :
TObj(a),
ammotype(a.ammotype),
rounds(a.rounds)
{
}
TAmmo & TAmmo::operator=(const TAmmo &a)
{
if (this == &a) return *this;
TObj::operator=(a);
ammotype=a.ammotype;
rounds=a.rounds;
return *this;
}
TAmmo::~TAmmo()
{
}
void TAmmo::assignFourValues(int x1, int x2, int x3, int x4){
setAmmoType(x1);
setRounds(x2);
}
void TAmmo::getFourValues(int *x1, int *x2, int *x3, int *x4) const
{
*x1 = getAmmoType();
*x2 = getRounds();
*x3 = 0;
*x4 = 0;
}
void TAmmo::setRounds(int r) {
if(r<=0){
char buf[256];
sprintf(buf, "%s empty", name);
if(isObjStat(ITEM_STRUNG)){
delete [] name;
} else {
swapToStrung();
}
name=mud_str_dup(buf);
}
rounds=r;
}
sstring TAmmo::showModifier(showModeT tMode, const TBeing *tBeing) const
{
// recurse if necessary
sstring tString = TObj::showModifier(tMode, tBeing);
if (getRounds()<=0) {
tString += " (empty)";
}
return tString;
}
sstring TGun::showModifier(showModeT tMode, const TBeing *tBeing) const
{
// recurse if necessary
sstring tString = TObj::showModifier(tMode, tBeing);
if (!getAmmo() || getAmmo()->getRounds()<=0) {
tString += " (empty)";
}
return tString;
}
int TGun::shootMeBow(TBeing *ch, TBeing *targ, unsigned int count, dirTypeT dir, int shoot_dist)
{
TAmmo *ammo;
TObj *bullet;
char buf[256];
if (targ &&
ch->checkPeacefulVictim("They are in a peaceful room. You can't seem to fire the gun.\n\r", targ))
return FALSE;
if (targ && ch->noHarmCheck(targ))
return FALSE;
sstring capbuf, capbuf2;
ch->addToWait(combatRound(2));
int rof=getROF();
while(rof--){
if(!(ammo=dynamic_cast<TAmmo *>(getAmmo())) || ammo->getRounds()<=0){
act("Click. $N is out of ammunition.", TRUE, ch, NULL, this, TO_CHAR);
// keep looping to simulate trigger pulls - looks cooler
continue;
}
// grab a bullet object and adjust for damage
bullet=read_object(31864, VIRTUAL);
TArrow *tmp=dynamic_cast<TArrow *>(bullet);
if(tmp){
tmp->setWeapDamLvl(getWeapDamLvl());
tmp->setWeapDamDev(getWeapDamDev());
}
// decrement ammo and drop a casing
if(!isCaseless())
dropSpentCasing(ch->roomp);
setRounds(getRounds()-1);
// send messages
capbuf = colorString(ch, ch->desc, bullet->getName(), NULL, COLOR_OBJECTS, TRUE);
capbuf2 = colorString(ch, ch->desc, getName(), NULL, COLOR_OBJECTS, TRUE);
if (targ)
ch->sendTo(COLOR_MOBS, fmt("You shoot %s out of %s at %s.\n\r") %
capbuf.uncap() % capbuf2.uncap() %
targ->getName());
else
ch->sendTo(fmt("You shoot %s out of %s.\n\r") %
capbuf.uncap() %
capbuf2.uncap());
sprintf(buf, "$n points $p %swards, and shoots $N out of it.",
dirs[dir]);
act(buf, FALSE, ch, this, bullet, TO_ROOM);
// put the bullet in the room and then "throw" it
*ch->roomp += *bullet;
int rc = throwThing(bullet, dir, ch->in_room, &targ, shoot_dist, 10, ch);
if(!isSilenced())
ch->roomp->getZone()->sendTo("A gunshot echoes in the distance.\n\r",
ch->in_room);
// delete the bullet afterwards, arbitrary decision
// since they are arrow type and you usually don't find spent lead anyway
delete bullet;
bullet = NULL;
if (IS_SET_DELETE(rc, DELETE_VICT)) {
delete targ;
targ = NULL;
return FALSE;
}
}
return FALSE;
}
void TGun::setRounds(int r){
if(getAmmo()){
if(r<=0 && isClipless()){
TAmmo *ammo=getAmmo();
delete ammo;
} else
getAmmo()->setRounds(r);
}
}
int TGun::getRounds() const {
if(getAmmo())
return getAmmo()->getRounds();
else
return 0;
}
void TGun::describeContains(const TBeing *ch) const
{
// just to avoid the "something in it" message
}
TThing *findFlint(TThing *stuff){
TThing *tt;
TTool *flint;
TThing *ret;
if(!stuff)
return NULL;
for(tt=stuff;tt;tt=tt->nextThing){
if(tt && (flint=dynamic_cast<TTool *>(tt)) &&
(flint->getToolType() == TOOL_FLINTSTEEL))
return tt;
if(tt && tt->getStuff() && (ret=findFlint(tt->getStuff())))
return ret;
}
return NULL;
}
TThing *findPowder(TThing *stuff, int uses){
TThing *tt;
TTool *powder;
TThing *ret;
if(!stuff)
return NULL;
for(tt=stuff;tt;tt=tt->nextThing){
if(tt && (powder=dynamic_cast<TTool *>(tt)) &&
(powder->getToolType() == TOOL_BLACK_POWDER) &&
powder->getToolUses() >= uses)
return tt;
if(tt && tt->getStuff() && (ret=findPowder(tt->getStuff(), uses)))
return ret;
}
return NULL;
}
TThing *findShot(TThing *stuff, ammoTypeT ammotype){
TThing *tt;
TAmmo *Shot;
TThing *ret;
if(!stuff)
return NULL;
for(tt=stuff;tt;tt=tt->nextThing){
if(tt && (Shot=dynamic_cast<TAmmo *>(tt)) &&
Shot->getAmmoType()==ammotype)
return tt;
if(tt && tt->getStuff() && (ret=findShot(tt->getStuff(), ammotype)))
return ret;
}
return NULL;
}
<|endoftext|> |
<commit_before>// This file is part of the dune-grid-multiscale project:
// http://users.dune-project.org/projects/dune-grid-multiscale
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#include <dune/stuff/test/main.hh> // <- has to come first
#include <dune/stuff/common/disable_warnings.hh>
# include <dune/grid/sgrid.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/stuff/common/string.hh>
#include <dune/grid/multiscale/provider/cube.hh>
using namespace Dune;
typedef SGrid< 2, 2 > GridType;
template< class GridPartType >
void measureTiming(const GridPartType& gridPart, Dune::Stuff::Common::LogStream& out, const std::string name = "")
{
out << " walking " << name << " grid part... " << std::flush;
Dune::Timer timer;
unsigned int elements = 0;
for (typename GridPartType::template Codim< 0 >::IteratorType it = gridPart.template begin< 0 >();
it != gridPart.template end< 0 >();
++it)
++elements;
out << " done (has " << elements << " elements, took " << timer.elapsed() << " sek)" << std::endl;
} // void measureTiming()
template< class GlobalGridPartType, class LocalGridPartType, class OutStreamType >
struct Inspect
{
template< int dim, int codim >
struct Codim
{
static void entities(const GlobalGridPartType& globalGridPart, const LocalGridPartType& localGridPart, const std::string prefix, OutStreamType& out)
{
// walk all codim entitites
for (auto entityIt = localGridPart.template begin< codim >(); entityIt != localGridPart.template end< codim >(); ++entityIt) {
const auto& entity = *entityIt;
const auto& geometryType = entity.type();
const auto globalIndex = globalGridPart.indexSet().index(entity);
const auto localIndex = localGridPart.indexSet().index(entity);
out << prefix << geometryType << ", global index " << globalIndex << ", local index " << localIndex << std::endl;
out << prefix << " corners: ";
auto geometry = entity.geometry();
for (int i = 0; i < (geometry.corners() - 1); ++i)
out << "(" << geometry.corner(i) << "), ";
out << "(" << geometry.corner(geometry.corners() - 1) << ")" << std::endl;
} // walk all codim entitites
// increase Codim
Inspect< GlobalGridPartType, LocalGridPartType, OutStreamType >::Codim< dim, codim + 1 >::entities(globalGridPart, localGridPart, prefix, out);
}
}; // struct Codim
}; // struct Inspect
template< class GlobalGridPartType, class LocalGridPartType, class OutStreamType >
template< int codim >
struct Inspect< GlobalGridPartType, LocalGridPartType, OutStreamType >::Codim< codim, codim >
{
static void entities(const GlobalGridPartType& globalGridPart, const LocalGridPartType& localGridPart, const std::string prefix, OutStreamType& out)
{
// walk all codim entitites
for (auto entityIt = localGridPart.template begin< codim >(); entityIt != localGridPart.template end< codim >(); ++entityIt) {
const auto& entity = *entityIt;
const auto& geometryType = entity.type();
const auto globalIndex = globalGridPart.indexSet().index(entity);
const auto localIndex = localGridPart.indexSet().index(entity);
out << prefix << geometryType << ", global index " << globalIndex << ", local index " << localIndex << std::endl;
out << prefix << " corners: (" << entity.geometry().center() << ")" << std::endl;
} // walk all codim entitites
}
};
class CubeProvider
: public ::testing::Test
{
protected:
typedef grid::Multiscale::Providers::Cube< GridType > ProviderType;
typedef typename ProviderType::MsGridType MsGridType;
CubeProvider()
: ms_grid_(ProviderType::create()->ms_grid())
{}
std::shared_ptr< const MsGridType > ms_grid_;
}; // class CubeProvider
TEST_F(CubeProvider, global_gridpart)
{
const auto& globalGridPart = *(ms_grid_->globalGridPart());
Inspect< MsGridType::GlobalGridPartType, MsGridType::GlobalGridPartType, Dune::Stuff::Common::LogStream >
::Codim< GridType::dimension, 0 >
::entities(globalGridPart, globalGridPart, " ", DSC_LOG_INFO);
}
TEST_F(CubeProvider, local_grid_parts)
{
const auto& globalGridPart = *(ms_grid_->globalGridPart());
for (unsigned int subdomain = 0; subdomain < ms_grid_->size(); ++subdomain) {
DSC_LOG_INFO << "subdomain " << subdomain << std::endl;
const auto& localGridPart = *(ms_grid_->localGridPart(subdomain));
Inspect< MsGridType::GlobalGridPartType, MsGridType::LocalGridPartType, Dune::Stuff::Common::LogStream >
::Codim< GridType::dimension, 0 >
::entities(globalGridPart, localGridPart, " ", DSC_LOG_INFO);
}
}
TEST_F(CubeProvider, boundary_grid_parts)
{
const auto& globalGridPart = *(ms_grid_->globalGridPart());
for (unsigned int subdomain = 0; subdomain < ms_grid_->size(); ++subdomain) {
if (ms_grid_->boundary(subdomain)) {
DSC_LOG_INFO << "subdomain " << subdomain << std::endl;
const auto& boundaryGridPart = *(ms_grid_->boundaryGridPart(subdomain));
Inspect< MsGridType::GlobalGridPartType, MsGridType::BoundaryGridPartType, Dune::Stuff::Common::LogStream >
::Codim< GridType::dimension, 0 >
::entities(globalGridPart, boundaryGridPart, " ", DSC_LOG_INFO);
}
}
}
TEST_F(CubeProvider, coupling_grid_parts)
{
const auto& globalGridPart = *(ms_grid_->globalGridPart());
for (size_t ss = 0; ss < ms_grid_->size(); ++ss) {
for (auto nn : ms_grid_->neighborsOf(ss)) {
const auto& coupling_grid_part = *(ms_grid_->couplingGridPart(ss, nn));
DSC_LOG_INFO << "testing coupling grid part: " << ss << ", " << nn << std::endl;
// walk the grid part
for (auto entityIterator = coupling_grid_part.begin< 0 >();
entityIterator != coupling_grid_part.end< 0 >();
++entityIterator) {
const auto& entity = *entityIterator;
const unsigned int entityIndex = coupling_grid_part.indexSet().index(entity);
DSC_LOG_INFO << "entity " << entityIndex << ", neighbors " << std::flush;
// walk the intersections
for (auto intersectionIterator = coupling_grid_part.ibegin(entity);
intersectionIterator != coupling_grid_part.iend(entity);
++intersectionIterator) {
const auto& intersection = *intersectionIterator;
const auto neighborPtr = intersection.outside();
const auto& neighbor = *neighborPtr;
const unsigned int neighborIndex = globalGridPart.indexSet().index(neighbor);
DSC_LOG_INFO << neighborIndex << " ";
} // walk the intersections
DSC_LOG_INFO << std::endl;
} // walk the grid part
}
}
}
TEST_F(CubeProvider, timings)
{
// time grid parts
DSC_LOG_INFO << "timing grid parts:" << std::endl;
const auto globalGridPart = ms_grid_->globalGridPart();
measureTiming(*globalGridPart, DSC_LOG_INFO, "global");
const auto neighbor = *(ms_grid_->neighborsOf(0).begin());
const auto couplingGridPart = ms_grid_->couplingGridPart(0, neighbor);
measureTiming(*couplingGridPart, DSC_LOG_INFO, "coupling (subdomain 0 with " + DSC::toString(neighbor) + ")");
const auto firstLocalGridPart = ms_grid_->localGridPart(0);
measureTiming(*firstLocalGridPart, DSC_LOG_INFO, "local (subdomain 0)");
for (unsigned int subdomain = 1; subdomain < ms_grid_->size(); ++subdomain) {
const auto localGridPart = ms_grid_->localGridPart(subdomain);
measureTiming(*localGridPart, DSC_LOG_DEBUG, "local (subdomain " + DSC::toString(subdomain) + ")");
}
}
<commit_msg>[test.provider] make it compile again<commit_after>// This file is part of the dune-grid-multiscale project:
// http://users.dune-project.org/projects/dune-grid-multiscale
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#include <dune/stuff/test/main.hxx> // <- has to come first
#include <dune/stuff/common/disable_warnings.hh>
# include <dune/grid/sgrid.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/stuff/common/string.hh>
#include <dune/grid/multiscale/provider/cube.hh>
using namespace Dune;
typedef SGrid< 2, 2 > GridType;
template< class GridPartType >
void measureTiming(const GridPartType& gridPart, Dune::Stuff::Common::LogStream& out, const std::string name = "")
{
out << " walking " << name << " grid part... " << std::flush;
Dune::Timer timer;
unsigned int elements = 0;
for (typename GridPartType::template Codim< 0 >::IteratorType it = gridPart.template begin< 0 >();
it != gridPart.template end< 0 >();
++it)
++elements;
out << " done (has " << elements << " elements, took " << timer.elapsed() << " sek)" << std::endl;
} // void measureTiming()
template< class GlobalGridPartType, class LocalGridPartType, class OutStreamType >
struct Inspect
{
template< int dim, int codim >
struct Codim
{
static void entities(const GlobalGridPartType& globalGridPart, const LocalGridPartType& localGridPart, const std::string prefix, OutStreamType& out)
{
// walk all codim entitites
for (auto entityIt = localGridPart.template begin< codim >(); entityIt != localGridPart.template end< codim >(); ++entityIt) {
const auto& entity = *entityIt;
const auto& geometryType = entity.type();
const auto globalIndex = globalGridPart.indexSet().index(entity);
const auto localIndex = localGridPart.indexSet().index(entity);
out << prefix << geometryType << ", global index " << globalIndex << ", local index " << localIndex << std::endl;
out << prefix << " corners: ";
auto geometry = entity.geometry();
for (int i = 0; i < (geometry.corners() - 1); ++i)
out << "(" << geometry.corner(i) << "), ";
out << "(" << geometry.corner(geometry.corners() - 1) << ")" << std::endl;
} // walk all codim entitites
// increase Codim
Inspect< GlobalGridPartType, LocalGridPartType, OutStreamType >::Codim< dim, codim + 1 >::entities(globalGridPart, localGridPart, prefix, out);
}
}; // struct Codim
}; // struct Inspect
template< class GlobalGridPartType, class LocalGridPartType, class OutStreamType >
template< int codim >
struct Inspect< GlobalGridPartType, LocalGridPartType, OutStreamType >::Codim< codim, codim >
{
static void entities(const GlobalGridPartType& globalGridPart, const LocalGridPartType& localGridPart, const std::string prefix, OutStreamType& out)
{
// walk all codim entitites
for (auto entityIt = localGridPart.template begin< codim >(); entityIt != localGridPart.template end< codim >(); ++entityIt) {
const auto& entity = *entityIt;
const auto& geometryType = entity.type();
const auto globalIndex = globalGridPart.indexSet().index(entity);
const auto localIndex = localGridPart.indexSet().index(entity);
out << prefix << geometryType << ", global index " << globalIndex << ", local index " << localIndex << std::endl;
out << prefix << " corners: (" << entity.geometry().center() << ")" << std::endl;
} // walk all codim entitites
}
};
class CubeProvider
: public ::testing::Test
{
protected:
typedef grid::Multiscale::Providers::Cube< GridType > ProviderType;
typedef typename ProviderType::MsGridType MsGridType;
CubeProvider()
: ms_grid_(ProviderType::create()->ms_grid())
{}
std::shared_ptr< const MsGridType > ms_grid_;
}; // class CubeProvider
TEST_F(CubeProvider, global_gridpart)
{
const auto& globalGridPart = ms_grid_->globalGridPart();
Inspect< MsGridType::GlobalGridPartType, MsGridType::GlobalGridPartType, Dune::Stuff::Common::LogStream >
::Codim< GridType::dimension, 0 >
::entities(globalGridPart, globalGridPart, " ", DSC_LOG_INFO);
}
TEST_F(CubeProvider, local_grid_parts)
{
const auto& globalGridPart = ms_grid_->globalGridPart();
for (unsigned int subdomain = 0; subdomain < ms_grid_->size(); ++subdomain) {
DSC_LOG_INFO << "subdomain " << subdomain << std::endl;
const auto& localGridPart = ms_grid_->localGridPart(subdomain);
Inspect< MsGridType::GlobalGridPartType, MsGridType::LocalGridPartType, Dune::Stuff::Common::LogStream >
::Codim< GridType::dimension, 0 >
::entities(globalGridPart, localGridPart, " ", DSC_LOG_INFO);
}
}
TEST_F(CubeProvider, boundary_grid_parts)
{
const auto& globalGridPart = ms_grid_->globalGridPart();
for (unsigned int subdomain = 0; subdomain < ms_grid_->size(); ++subdomain) {
if (ms_grid_->boundary(subdomain)) {
DSC_LOG_INFO << "subdomain " << subdomain << std::endl;
const auto& boundaryGridPart = ms_grid_->boundaryGridPart(subdomain);
Inspect< MsGridType::GlobalGridPartType, MsGridType::BoundaryGridPartType, Dune::Stuff::Common::LogStream >
::Codim< GridType::dimension, 0 >
::entities(globalGridPart, boundaryGridPart, " ", DSC_LOG_INFO);
}
}
}
TEST_F(CubeProvider, coupling_grid_parts)
{
const auto& globalGridPart = ms_grid_->globalGridPart();
for (size_t ss = 0; ss < ms_grid_->size(); ++ss) {
for (auto nn : ms_grid_->neighborsOf(ss)) {
const auto& coupling_grid_part = ms_grid_->couplingGridPart(ss, nn);
DSC_LOG_INFO << "testing coupling grid part: " << ss << ", " << nn << std::endl;
// walk the grid part
for (auto entityIterator = coupling_grid_part.begin< 0 >();
entityIterator != coupling_grid_part.end< 0 >();
++entityIterator) {
const auto& entity = *entityIterator;
const unsigned int entityIndex = coupling_grid_part.indexSet().index(entity);
DSC_LOG_INFO << "entity " << entityIndex << ", neighbors " << std::flush;
// walk the intersections
for (auto intersectionIterator = coupling_grid_part.ibegin(entity);
intersectionIterator != coupling_grid_part.iend(entity);
++intersectionIterator) {
const auto& intersection = *intersectionIterator;
const auto neighborPtr = intersection.outside();
const auto& neighbor = *neighborPtr;
const unsigned int neighborIndex = globalGridPart.indexSet().index(neighbor);
DSC_LOG_INFO << neighborIndex << " ";
} // walk the intersections
DSC_LOG_INFO << std::endl;
} // walk the grid part
}
}
}
TEST_F(CubeProvider, timings)
{
// time grid parts
DSC_LOG_INFO << "timing grid parts:" << std::endl;
const auto globalGridPart = ms_grid_->globalGridPart();
measureTiming(globalGridPart, DSC_LOG_INFO, "global");
const auto neighbor = *(ms_grid_->neighborsOf(0).begin());
const auto couplingGridPart = ms_grid_->couplingGridPart(0, neighbor);
measureTiming(couplingGridPart, DSC_LOG_INFO, "coupling (subdomain 0 with " + DSC::toString(neighbor) + ")");
const auto firstLocalGridPart = ms_grid_->localGridPart(0);
measureTiming(firstLocalGridPart, DSC_LOG_INFO, "local (subdomain 0)");
for (unsigned int subdomain = 1; subdomain < ms_grid_->size(); ++subdomain) {
const auto localGridPart = ms_grid_->localGridPart(subdomain);
measureTiming(localGridPart, DSC_LOG_DEBUG, "local (subdomain " + DSC::toString(subdomain) + ")");
}
}
<|endoftext|> |
<commit_before>#include <criterion/criterion.h>
#include <criterion/redirect.h>
#include <iostream>
#include <string>
// set a timeout for I/O tests
TestSuite(redirect, .timeout = 0.1);
#if __GNUC__ >= 5
Test(redirect, mock) {
auto fmock = criterion::mock_file();
fmock << "Hello" << std::flush;
fmock.seekg(0);
std::string contents;
fmock >> contents;
cr_assert_eq(contents, "Hello");
}
#endif
Test(redirect, mock_c) {
std::FILE* fmock = cr_mock_file_size(4096);
std::fprintf(fmock, "Hello");
std::fflush(fmock);
std::rewind(fmock);
char contents[sizeof ("Hello")] = {0};
fgets(contents, sizeof (contents), fmock);
cr_assert_str_eq(contents, "Hello");
}
Test(redirect, assertions) {
std::FILE* f1 = cr_mock_file_size(4096);
std::FILE* f2 = cr_mock_file_size(4096);
std::FILE* f3 = cr_mock_file_size(4096);
fprintf(f1, "Foo");
fprintf(f2, "Foo");
fprintf(f3, "Bar");
fflush(f1);
fflush(f2);
fflush(f3);
cr_expect_file_contents_eq(f1, f1);
rewind(f1);
cr_expect_file_contents_eq(f1, f2);
rewind(f1);
cr_expect_file_contents_neq(f1, f3);
fclose(f1);
fclose(f2);
fclose(f3);
}
Test(redirect, stdout_) {
cr_redirect_stdout();
std::cout << "Foo" << std::flush;
cr_expect_stdout_eq_str("Foo");
cr_expect_stdout_neq_str("Bar");
}
Test(redirect, stderr_) {
cr_redirect_stderr();
std::cerr << "Foo" << std::flush;
cr_expect_stderr_eq_str("Foo");
cr_expect_stderr_neq_str("Bar");
}
Test(redirect, stdin_) {
auto& f_cin = criterion::get_redirected_cin();
f_cin << "Foo";
f_cin.close();
std::string read;
std::cin >> read;
cr_expect_eq(read, "Foo");
cr_expect_neq(read, "Bar");
}
<commit_msg>Relaxed io tests timeout to 1 second<commit_after>#include <criterion/criterion.h>
#include <criterion/redirect.h>
#include <iostream>
#include <string>
// set a timeout for I/O tests
TestSuite(redirect, .timeout = 1);
#if __GNUC__ >= 5
Test(redirect, mock) {
auto fmock = criterion::mock_file();
fmock << "Hello" << std::flush;
fmock.seekg(0);
std::string contents;
fmock >> contents;
cr_assert_eq(contents, "Hello");
}
#endif
Test(redirect, mock_c) {
std::FILE* fmock = cr_mock_file_size(4096);
std::fprintf(fmock, "Hello");
std::fflush(fmock);
std::rewind(fmock);
char contents[sizeof ("Hello")] = {0};
fgets(contents, sizeof (contents), fmock);
cr_assert_str_eq(contents, "Hello");
}
Test(redirect, assertions) {
std::FILE* f1 = cr_mock_file_size(4096);
std::FILE* f2 = cr_mock_file_size(4096);
std::FILE* f3 = cr_mock_file_size(4096);
fprintf(f1, "Foo");
fprintf(f2, "Foo");
fprintf(f3, "Bar");
fflush(f1);
fflush(f2);
fflush(f3);
cr_expect_file_contents_eq(f1, f1);
rewind(f1);
cr_expect_file_contents_eq(f1, f2);
rewind(f1);
cr_expect_file_contents_neq(f1, f3);
fclose(f1);
fclose(f2);
fclose(f3);
}
Test(redirect, stdout_) {
cr_redirect_stdout();
std::cout << "Foo" << std::flush;
cr_expect_stdout_eq_str("Foo");
cr_expect_stdout_neq_str("Bar");
}
Test(redirect, stderr_) {
cr_redirect_stderr();
std::cerr << "Foo" << std::flush;
cr_expect_stderr_eq_str("Foo");
cr_expect_stderr_neq_str("Bar");
}
Test(redirect, stdin_) {
auto& f_cin = criterion::get_redirected_cin();
f_cin << "Foo";
f_cin.close();
std::string read;
std::cin >> read;
cr_expect_eq(read, "Foo");
cr_expect_neq(read, "Bar");
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "JoinMenu.h"
/* system headers */
#include <string>
#include <vector>
/* common implementation headers */
#include "FontManager.h"
/* local implementation headers */
#include "StartupInfo.h"
#include "MainMenu.h"
#include "HUDDialogStack.h"
#include "MenuDefaultKey.h"
#include "ServerStartMenu.h"
#include "ServerMenu.h"
#include "Protocol.h"
#include "HUDuiControl.h"
#include "HUDuiLabel.h"
#include "HUDuiTypeIn.h"
#include "HUDuiList.h"
#include "TimeKeeper.h"
/* from playing.h */
StartupInfo* getStartupInfo();
typedef void (*JoinGameCallback)(bool success, void* data);
void joinGame(JoinGameCallback, void* userData);
typedef void (*ConnectStatusCallback)(std::string& str);
void setConnectStatusCB(ConnectStatusCallback);
void drawFrame(const float dt);
JoinMenu* JoinMenu::activeMenu = NULL;
JoinMenu::JoinMenu() : oldErrorCallback(NULL),
serverStartMenu(NULL), serverMenu(NULL)
{
// cache font face ID
int fontFace = MainMenu::getFontFace();
// add controls
std::vector<HUDuiControl*>& list = getControls();
StartupInfo* info = getStartupInfo();
HUDuiLabel* label = new HUDuiLabel;
label->setFontFace(fontFace);
label->setString("Join Game");
list.push_back(label);
findServer = new HUDuiLabel;
findServer->setFontFace(fontFace);
findServer->setString("Find Server");
list.push_back(findServer);
connectLabel = new HUDuiLabel;
connectLabel->setFontFace(fontFace);
connectLabel->setString("Connect");
list.push_back(connectLabel);
callsign = new HUDuiTypeIn;
callsign->setFontFace(fontFace);
callsign->setLabel("Callsign:");
callsign->setMaxLength(CallSignLen - 1);
callsign->setString(info->callsign);
list.push_back(callsign);
team = new HUDuiList;
team->setFontFace(fontFace);
team->setLabel("Team:");
team->setCallback(teamCallback, NULL);
std::vector<std::string>& teams = team->getList();
// these do not need to be in enum order, but must match getTeam() & setTeam()
teams.push_back(std::string(Team::getName(AutomaticTeam)));
teams.push_back(std::string(Team::getName(RogueTeam)));
teams.push_back(std::string(Team::getName(RedTeam)));
teams.push_back(std::string(Team::getName(GreenTeam)));
teams.push_back(std::string(Team::getName(BlueTeam)));
teams.push_back(std::string(Team::getName(PurpleTeam)));
teams.push_back(std::string(Team::getName(ObserverTeam)));
team->update();
setTeam(info->team);
list.push_back(team);
server = new HUDuiTypeIn;
server->setFontFace(fontFace);
server->setLabel("Server:");
server->setMaxLength(64);
server->setString(info->serverName);
list.push_back(server);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port = new HUDuiTypeIn;
port->setFontFace(fontFace);
port->setLabel("Port:");
port->setMaxLength(5);
port->setString(buffer);
list.push_back(port);
email = new HUDuiTypeIn;
email->setFontFace(fontFace);
email->setLabel("Email:");
email->setMaxLength(EmailLen - 1);
email->setString(info->email);
list.push_back(email);
startServer = new HUDuiLabel;
startServer->setFontFace(fontFace);
startServer->setString("Start Server");
list.push_back(startServer);
status = new HUDuiLabel;
status->setFontFace(fontFace);
status->setString("");
list.push_back(status);
failedMessage = new HUDuiLabel;
failedMessage->setFontFace(fontFace);
failedMessage->setString("");
list.push_back(failedMessage);
initNavigation(list, 1, list.size() - 3);
}
JoinMenu::~JoinMenu()
{
delete serverStartMenu;
delete serverMenu;
}
HUDuiDefaultKey* JoinMenu::getDefaultKey()
{
return MenuDefaultKey::getInstance();
}
void JoinMenu::show()
{
activeMenu = this;
StartupInfo* info = getStartupInfo();
// set fields
callsign->setString(info->callsign);
setTeam(info->team);
server->setString(info->serverName);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port->setString(buffer);
// clear status
oldErrorCallback = NULL;
setStatus("");
}
void JoinMenu::dismiss()
{
loadInfo();
setConnectStatusCB(NULL);
activeMenu = NULL;
}
void JoinMenu::loadInfo()
{
// load startup info with current settings
StartupInfo* info = getStartupInfo();
strcpy(info->callsign, callsign->getString().c_str());
info->team = getTeam();
strcpy(info->serverName, server->getString().c_str());
info->serverPort = atoi(port->getString().c_str());
strcpy(info->email, email->getString().c_str());
}
void JoinMenu::execute()
{
HUDuiControl* focus = HUDui::getFocus();
if (focus == startServer) {
if (!serverStartMenu) serverStartMenu = new ServerStartMenu;
HUDDialogStack::get()->push(serverStartMenu);
} else if (focus == findServer) {
if (!serverMenu) serverMenu = new ServerMenu;
HUDDialogStack::get()->push(serverMenu);
} else if (focus == connectLabel) {
// load startup info
loadInfo();
// make sure we've got what we need
StartupInfo* info = getStartupInfo();
if (info->callsign[0] == '\0') {
setStatus("You must enter a callsign.");
return;
}
if (info->serverName[0] == '\0') {
setStatus("You must enter a server.");
return;
}
if (info->serverPort <= 0 || info->serverPort > 65535) {
char buffer[60];
sprintf(buffer, "Port is invalid. Try %d.", ServerPort);
setStatus(buffer);
return;
}
// let user know we're trying
setStatus("Trying...");
// schedule attempt to join game
oldErrorCallback = setErrorCallback(joinErrorCallback);
setConnectStatusCB(&connectStatusCallback);
joinGame(&joinGameCallback, this);
}
}
void JoinMenu::joinGameCallback(bool okay, void* _self)
{
JoinMenu* self = (JoinMenu*)_self;
if (okay) {
// it worked! pop all the menus.
HUDDialogStack* stack = HUDDialogStack::get();
while (stack->isActive()) stack->pop();
} else {
// failed. let user know.
self->setStatus("Connection failed.");
}
setErrorCallback(self->oldErrorCallback);
self->oldErrorCallback = NULL;
}
void JoinMenu::connectStatusCallback(std::string& str)
{
static TimeKeeper prev = TimeKeeper::getNullTime();
JoinMenu* self = activeMenu;
self->setFailedMessage(str.c_str());
// limit framerate to 2 fps - if you can't draw 2 fps you're screwed anyhow
// if we draw too many fps then people with fast connections and slow computers
// will have a problem on their hands, since we aren't multithreading
const float dt = TimeKeeper::getCurrent() - prev;
if (dt >= 0.5f) {
// render that puppy
drawFrame(dt);
prev = TimeKeeper::getCurrent();
}
}
void JoinMenu::joinErrorCallback(const char* msg)
{
JoinMenu* self = activeMenu;
self->setFailedMessage(msg);
// also forward to old callback
if (self->oldErrorCallback) (*self->oldErrorCallback)(msg);
}
void JoinMenu::setFailedMessage(const char* msg)
{
failedMessage->setString(msg);
FontManager &fm = FontManager::instance();
const float width = fm.getStrLength(MainMenu::getFontFace(),
failedMessage->getFontSize(), failedMessage->getString());
failedMessage->setPosition(center - 0.5f * width, failedMessage->getY());
}
TeamColor JoinMenu::getTeam() const
{
return team->getIndex() == 0 ? AutomaticTeam : TeamColor(team->getIndex() - 1);
}
void JoinMenu::setTeam(TeamColor teamcol)
{
team->setIndex(teamcol == AutomaticTeam ? 0 : int(teamcol) + 1);
}
void JoinMenu::setStatus(const char* msg, const std::vector<std::string> *)
{
status->setString(msg);
FontManager &fm = FontManager::instance();
const float width = fm.getStrLength(status->getFontFace(),
status->getFontSize(), status->getString());
status->setPosition(center - 0.5f * width, status->getY());
if (!oldErrorCallback) joinErrorCallback("");
}
void JoinMenu::teamCallback(HUDuiControl*, void*)
{
// do nothing (for now)
}
void JoinMenu::resize(int width, int height)
{
HUDDialog::resize(width, height);
// use a big font for title, smaller font for the rest
const float titleFontSize = (float)height / 15.0f;
const float fontSize = (float)height / 36.0f;
center = 0.5f * (float)width;
FontManager &fm = FontManager::instance();
// reposition title
std::vector<HUDuiControl*>& list = getControls();
HUDuiLabel* title = (HUDuiLabel*)list[0];
title->setFontSize(titleFontSize);
const float titleWidth = fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString());
const float titleHeight = fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, "");
float x = 0.5f * ((float)width - titleWidth);
float y = (float)height - titleHeight;
title->setPosition(x, y);
// reposition options
x = 0.5f * ((float)width - 0.5f * titleWidth);
y -= 0.6f * titleHeight;
list[1]->setFontSize(fontSize);
const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, "");
const int count = list.size();
for (int i = 1; i < count; i++) {
list[i]->setFontSize(fontSize);
list[i]->setPosition(x, y);
y -= 1.0f * h;
if (i <= 2 || i == 7) y -= 0.5f * h;
}
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>prevent an infinite loop (that happened on a frequent reconnect) on the callback<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "JoinMenu.h"
/* system headers */
#include <string>
#include <vector>
/* common implementation headers */
#include "FontManager.h"
/* local implementation headers */
#include "StartupInfo.h"
#include "MainMenu.h"
#include "HUDDialogStack.h"
#include "MenuDefaultKey.h"
#include "ServerStartMenu.h"
#include "ServerMenu.h"
#include "Protocol.h"
#include "HUDuiControl.h"
#include "HUDuiLabel.h"
#include "HUDuiTypeIn.h"
#include "HUDuiList.h"
#include "TimeKeeper.h"
/* from playing.h */
StartupInfo* getStartupInfo();
typedef void (*JoinGameCallback)(bool success, void* data);
void joinGame(JoinGameCallback, void* userData);
typedef void (*ConnectStatusCallback)(std::string& str);
void setConnectStatusCB(ConnectStatusCallback);
void drawFrame(const float dt);
JoinMenu* JoinMenu::activeMenu = NULL;
JoinMenu::JoinMenu() : oldErrorCallback(NULL),
serverStartMenu(NULL), serverMenu(NULL)
{
// cache font face ID
int fontFace = MainMenu::getFontFace();
// add controls
std::vector<HUDuiControl*>& list = getControls();
StartupInfo* info = getStartupInfo();
HUDuiLabel* label = new HUDuiLabel;
label->setFontFace(fontFace);
label->setString("Join Game");
list.push_back(label);
findServer = new HUDuiLabel;
findServer->setFontFace(fontFace);
findServer->setString("Find Server");
list.push_back(findServer);
connectLabel = new HUDuiLabel;
connectLabel->setFontFace(fontFace);
connectLabel->setString("Connect");
list.push_back(connectLabel);
callsign = new HUDuiTypeIn;
callsign->setFontFace(fontFace);
callsign->setLabel("Callsign:");
callsign->setMaxLength(CallSignLen - 1);
callsign->setString(info->callsign);
list.push_back(callsign);
team = new HUDuiList;
team->setFontFace(fontFace);
team->setLabel("Team:");
team->setCallback(teamCallback, NULL);
std::vector<std::string>& teams = team->getList();
// these do not need to be in enum order, but must match getTeam() & setTeam()
teams.push_back(std::string(Team::getName(AutomaticTeam)));
teams.push_back(std::string(Team::getName(RogueTeam)));
teams.push_back(std::string(Team::getName(RedTeam)));
teams.push_back(std::string(Team::getName(GreenTeam)));
teams.push_back(std::string(Team::getName(BlueTeam)));
teams.push_back(std::string(Team::getName(PurpleTeam)));
teams.push_back(std::string(Team::getName(ObserverTeam)));
team->update();
setTeam(info->team);
list.push_back(team);
server = new HUDuiTypeIn;
server->setFontFace(fontFace);
server->setLabel("Server:");
server->setMaxLength(64);
server->setString(info->serverName);
list.push_back(server);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port = new HUDuiTypeIn;
port->setFontFace(fontFace);
port->setLabel("Port:");
port->setMaxLength(5);
port->setString(buffer);
list.push_back(port);
email = new HUDuiTypeIn;
email->setFontFace(fontFace);
email->setLabel("Email:");
email->setMaxLength(EmailLen - 1);
email->setString(info->email);
list.push_back(email);
startServer = new HUDuiLabel;
startServer->setFontFace(fontFace);
startServer->setString("Start Server");
list.push_back(startServer);
status = new HUDuiLabel;
status->setFontFace(fontFace);
status->setString("");
list.push_back(status);
failedMessage = new HUDuiLabel;
failedMessage->setFontFace(fontFace);
failedMessage->setString("");
list.push_back(failedMessage);
initNavigation(list, 1, list.size() - 3);
}
JoinMenu::~JoinMenu()
{
delete serverStartMenu;
delete serverMenu;
}
HUDuiDefaultKey* JoinMenu::getDefaultKey()
{
return MenuDefaultKey::getInstance();
}
void JoinMenu::show()
{
activeMenu = this;
StartupInfo* info = getStartupInfo();
// set fields
callsign->setString(info->callsign);
setTeam(info->team);
server->setString(info->serverName);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port->setString(buffer);
// clear status
oldErrorCallback = NULL;
setStatus("");
}
void JoinMenu::dismiss()
{
loadInfo();
setConnectStatusCB(NULL);
activeMenu = NULL;
}
void JoinMenu::loadInfo()
{
// load startup info with current settings
StartupInfo* info = getStartupInfo();
strcpy(info->callsign, callsign->getString().c_str());
info->team = getTeam();
strcpy(info->serverName, server->getString().c_str());
info->serverPort = atoi(port->getString().c_str());
strcpy(info->email, email->getString().c_str());
}
void JoinMenu::execute()
{
HUDuiControl* focus = HUDui::getFocus();
if (focus == startServer) {
if (!serverStartMenu) serverStartMenu = new ServerStartMenu;
HUDDialogStack::get()->push(serverStartMenu);
} else if (focus == findServer) {
if (!serverMenu) serverMenu = new ServerMenu;
HUDDialogStack::get()->push(serverMenu);
} else if (focus == connectLabel) {
// load startup info
loadInfo();
// make sure we've got what we need
StartupInfo* info = getStartupInfo();
if (info->callsign[0] == '\0') {
setStatus("You must enter a callsign.");
return;
}
if (info->serverName[0] == '\0') {
setStatus("You must enter a server.");
return;
}
if (info->serverPort <= 0 || info->serverPort > 65535) {
char buffer[60];
sprintf(buffer, "Port is invalid. Try %d.", ServerPort);
setStatus(buffer);
return;
}
// let user know we're trying
setStatus("Trying...");
// schedule attempt to join game
oldErrorCallback = setErrorCallback(joinErrorCallback);
setConnectStatusCB(&connectStatusCallback);
joinGame(&joinGameCallback, this);
}
}
void JoinMenu::joinGameCallback(bool okay, void* _self)
{
JoinMenu* self = (JoinMenu*)_self;
if (okay) {
// it worked! pop all the menus.
HUDDialogStack* stack = HUDDialogStack::get();
while (stack->isActive()) stack->pop();
} else {
// failed. let user know.
self->setStatus("Connection failed.");
}
setErrorCallback(self->oldErrorCallback);
self->oldErrorCallback = NULL;
}
void JoinMenu::connectStatusCallback(std::string& str)
{
static TimeKeeper prev = TimeKeeper::getNullTime();
JoinMenu* self = activeMenu;
self->setFailedMessage(str.c_str());
// limit framerate to 2 fps - if you can't draw 2 fps you're screwed anyhow
// if we draw too many fps then people with fast connections and slow computers
// will have a problem on their hands, since we aren't multithreading
const float dt = TimeKeeper::getCurrent() - prev;
if (dt >= 0.5f) {
// render that puppy
drawFrame(dt);
prev = TimeKeeper::getCurrent();
}
}
void JoinMenu::joinErrorCallback(const char* msg)
{
JoinMenu* self = activeMenu;
self->setFailedMessage(msg);
// also forward to old callback if it's not this callback
if (self->oldErrorCallback && self->oldErrorCallback != self->joinErrorCallback) {
(*self->oldErrorCallback)(msg);
}
}
void JoinMenu::setFailedMessage(const char* msg)
{
failedMessage->setString(msg);
FontManager &fm = FontManager::instance();
const float width = fm.getStrLength(MainMenu::getFontFace(),
failedMessage->getFontSize(), failedMessage->getString());
failedMessage->setPosition(center - 0.5f * width, failedMessage->getY());
}
TeamColor JoinMenu::getTeam() const
{
return team->getIndex() == 0 ? AutomaticTeam : TeamColor(team->getIndex() - 1);
}
void JoinMenu::setTeam(TeamColor teamcol)
{
team->setIndex(teamcol == AutomaticTeam ? 0 : int(teamcol) + 1);
}
void JoinMenu::setStatus(const char* msg, const std::vector<std::string> *)
{
status->setString(msg);
FontManager &fm = FontManager::instance();
const float width = fm.getStrLength(status->getFontFace(),
status->getFontSize(), status->getString());
status->setPosition(center - 0.5f * width, status->getY());
if (!oldErrorCallback) joinErrorCallback("");
}
void JoinMenu::teamCallback(HUDuiControl*, void*)
{
// do nothing (for now)
}
void JoinMenu::resize(int width, int height)
{
HUDDialog::resize(width, height);
// use a big font for title, smaller font for the rest
const float titleFontSize = (float)height / 15.0f;
const float fontSize = (float)height / 36.0f;
center = 0.5f * (float)width;
FontManager &fm = FontManager::instance();
// reposition title
std::vector<HUDuiControl*>& list = getControls();
HUDuiLabel* title = (HUDuiLabel*)list[0];
title->setFontSize(titleFontSize);
const float titleWidth = fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString());
const float titleHeight = fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, "");
float x = 0.5f * ((float)width - titleWidth);
float y = (float)height - titleHeight;
title->setPosition(x, y);
// reposition options
x = 0.5f * ((float)width - 0.5f * titleWidth);
y -= 0.6f * titleHeight;
list[1]->setFontSize(fontSize);
const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, "");
const int count = list.size();
for (int i = 1; i < count; i++) {
list[i]->setFontSize(fontSize);
list[i]->setPosition(x, y);
y -= 1.0f * h;
if (i <= 2 || i == 7) y -= 0.5f * h;
}
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
/* class interface header */
#include "bzfs.h"
#include "bzfsEvents.h"
#include "GameKeeper.h"
extern void sendMessage(int playerIndex, PlayerId dstPlayer, const char *message);
// ----------------- SpreeTracker-----------------
/*typedef struct
{
int playerID;
std::string callsign;
double startTime;
double lastUpdateTime;
int spreeTotal;
}trPlayerHistoryRecord;
std::map<int, trPlayerHistoryRecord > playerList; */
PlayHistoryTracker::PlayHistoryTracker()
{
}
PlayHistoryTracker::~PlayHistoryTracker()
{
}
void PlayHistoryTracker::process ( BaseEventData *eventData )
{
switch (eventData->eventType)
{
case eNullEvent:
case eZoneEntryEvent:
case eCaptureEvent:
case eZoneExitEvent:
// really WTF!!!!
break;
case ePlayerDieEvent:
{
PlayerDieEventData *deathRecord = (PlayerDieEventData*)eventData;
GameKeeper::Player *killerData = GameKeeper::Player::getPlayerByIndex(deathRecord->killerID);
//GameKeeper::Player *victimData = GameKeeper::Player::getPlayerByIndex(deathRecord->playerID);
// clear out the dude who got shot, since he won't be having any SPREEs
if (playerList.find(deathRecord->playerID) != playerList.end())
{
trPlayerHistoryRecord &record = playerList.find(deathRecord->playerID)->second;
std::string message;
if ( record.spreeTotal >= 5 && record.spreeTotal < 10 )
message = record.callsign + std::string("'s rampage was stoped by ") + std::string(killerData->player.getCallSign());
if ( record.spreeTotal >= 10 && record.spreeTotal < 20 )
message = record.callsign + std::string("'s killing spree was halted by ") + std::string(killerData->player.getCallSign());
if ( record.spreeTotal >= 20 )
message = std::string("The unstopable reign of ") + record.callsign + std::string(" was ended by ") + std::string(killerData->player.getCallSign());
if (message.size())
sendMessage(ServerPlayer, AllPlayers, message.c_str());
record.spreeTotal = 0;
record.startTime = deathRecord->time;
record.lastUpdateTime = deathRecord->time;
}
// chock up another win for our killer
// if they weren't the same as the killer ( suicide ).
if ( (deathRecord->playerID != deathRecord->killerID) && playerList.find(deathRecord->killerID) != playerList.end())
{
trPlayerHistoryRecord &record = playerList.find(deathRecord->killerID)->second;
record.spreeTotal++;
record.lastUpdateTime = deathRecord->time;
std::string message;
if ( record.spreeTotal > 5 )
message = record.callsign + std::string(" is on a Rampage!");
if ( record.spreeTotal > 10 )
message = record.callsign + std::string(" is on a Killing Spree!");
if ( record.spreeTotal > 20 )
message = record.callsign + std::string(" is Unstoppable!!");
if (message.size())
sendMessage(ServerPlayer, AllPlayers, message.c_str());
}
}
break;
case ePlayerSpawnEvent:
// really WTF!!!!
break;
case ePlayerJoinEvent:
{
trPlayerHistoryRecord playerRecord;
playerRecord.playerID = ((PlayerJoinPartEventData*)eventData)->playerID;
playerRecord.callsign = ((PlayerJoinPartEventData*)eventData)->callsign;
playerRecord.spreeTotal = 0;
playerRecord.lastUpdateTime = ((PlayerJoinPartEventData*)eventData)->time;
playerRecord.startTime = playerRecord.lastUpdateTime;
playerList[((PlayerJoinPartEventData*)eventData)->playerID] = playerRecord;
}
break;
case ePlayerPartEvent:
{
std::map<int, trPlayerHistoryRecord >::iterator itr = playerList.find( ((PlayerJoinPartEventData*)eventData)->playerID );
if (itr != playerList.end())
playerList.erase(itr);
}
break;
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>make the play history messages come out on the right kill numbers.<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
/* class interface header */
#include "bzfs.h"
#include "bzfsEvents.h"
#include "GameKeeper.h"
extern void sendMessage(int playerIndex, PlayerId dstPlayer, const char *message);
// ----------------- SpreeTracker-----------------
/*typedef struct
{
int playerID;
std::string callsign;
double startTime;
double lastUpdateTime;
int spreeTotal;
}trPlayerHistoryRecord;
std::map<int, trPlayerHistoryRecord > playerList; */
PlayHistoryTracker::PlayHistoryTracker()
{
}
PlayHistoryTracker::~PlayHistoryTracker()
{
}
void PlayHistoryTracker::process ( BaseEventData *eventData )
{
switch (eventData->eventType)
{
case eNullEvent:
case eZoneEntryEvent:
case eCaptureEvent:
case eZoneExitEvent:
// really WTF!!!!
break;
case ePlayerDieEvent:
{
PlayerDieEventData *deathRecord = (PlayerDieEventData*)eventData;
GameKeeper::Player *killerData = GameKeeper::Player::getPlayerByIndex(deathRecord->killerID);
//GameKeeper::Player *victimData = GameKeeper::Player::getPlayerByIndex(deathRecord->playerID);
// clear out the dude who got shot, since he won't be having any SPREEs
if (playerList.find(deathRecord->playerID) != playerList.end())
{
trPlayerHistoryRecord &record = playerList.find(deathRecord->playerID)->second;
std::string message;
if ( record.spreeTotal >= 5 && record.spreeTotal < 10 )
message = record.callsign + std::string("'s rampage was stoped by ") + std::string(killerData->player.getCallSign());
if ( record.spreeTotal >= 10 && record.spreeTotal < 20 )
message = record.callsign + std::string("'s killing spree was halted by ") + std::string(killerData->player.getCallSign());
if ( record.spreeTotal >= 20 )
message = std::string("The unstopable reign of ") + record.callsign + std::string(" was ended by ") + std::string(killerData->player.getCallSign());
if (message.size())
sendMessage(ServerPlayer, AllPlayers, message.c_str());
record.spreeTotal = 0;
record.startTime = deathRecord->time;
record.lastUpdateTime = deathRecord->time;
}
// chock up another win for our killer
// if they weren't the same as the killer ( suicide ).
if ( (deathRecord->playerID != deathRecord->killerID) && playerList.find(deathRecord->killerID) != playerList.end())
{
trPlayerHistoryRecord &record = playerList.find(deathRecord->killerID)->second;
record.spreeTotal++;
record.lastUpdateTime = deathRecord->time;
std::string message;
if ( record.spreeTotal == 5 )
message = record.callsign + std::string(" is on a Rampage!");
if ( record.spreeTotal == 10 )
message = record.callsign + std::string(" is on a Killing Spree!");
if ( record.spreeTotal == 20 )
message = record.callsign + std::string(" is Unstoppable!!");
if ( record.spreeTotal > 20 && record.spreeTotal%5 == 0 )
message = record.callsign + std::string("'s continues rage");
if (message.size())
sendMessage(ServerPlayer, AllPlayers, message.c_str());
}
}
break;
case ePlayerSpawnEvent:
// really WTF!!!!
break;
case ePlayerJoinEvent:
{
trPlayerHistoryRecord playerRecord;
playerRecord.playerID = ((PlayerJoinPartEventData*)eventData)->playerID;
playerRecord.callsign = ((PlayerJoinPartEventData*)eventData)->callsign;
playerRecord.spreeTotal = 0;
playerRecord.lastUpdateTime = ((PlayerJoinPartEventData*)eventData)->time;
playerRecord.startTime = playerRecord.lastUpdateTime;
playerList[((PlayerJoinPartEventData*)eventData)->playerID] = playerRecord;
}
break;
case ePlayerPartEvent:
{
std::map<int, trPlayerHistoryRecord >::iterator itr = playerList.find( ((PlayerJoinPartEventData*)eventData)->playerID );
if (itr != playerList.end())
playerList.erase(itr);
}
break;
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.